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 |
|---|---|---|---|---|---|---|---|---|---|---|
2bbe6c91c53b871e6c2aad0b3c26508db3a0cf3f | Gruntfile.js | Gruntfile.js | module.exports = function(grunt) {
'use strict';
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
// Task configuration.
aws: grunt.file.readJSON('.aws-deploy.json'),
s3: {
options: {
accessKeyId: '<%= aws.accessKeyId %>',
secretAccessKey: '<%= aws.secretAccessKey %>',
bucket: 'gamekeller',
region: 'eu-central-1',
gzip: false,
overwrite: false
},
assets: {
cwd: 'public/',
src: ['assets/**', '!assets/manifest.json']
}
}
})
// Load local grunt tasks.
grunt.loadTasks('grunt')
// Load necessary plugins.
grunt.loadNpmTasks('grunt-aws')
// Production simulating task.
grunt.registerTask('prod', ['revupdate', 'precompile'])
// Database operation tasks.
grunt.registerTask('db', ['dropDB', 'seedDB'])
grunt.registerTask('db.drop', ['dropDB'])
grunt.registerTask('db.seed', ['seedDB'])
// Deploy task.
grunt.registerTask('deploy', ['bower', 'precompile', 's3', 'revupdate'])
} | module.exports = function(grunt) {
'use strict';
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
// Task configuration.
aws: grunt.file.readJSON('.aws-deploy.json'),
s3: {
options: {
accessKeyId: '<%= aws.accessKeyId %>',
secretAccessKey: '<%= aws.secretAccessKey %>',
bucket: 'gamekeller',
region: 'eu-central-1',
gzip: false,
overwrite: false,
access: 'private'
},
assets: {
cwd: 'public/',
src: ['assets/**', '!assets/manifest.json']
}
}
})
// Load local grunt tasks.
grunt.loadTasks('grunt')
// Load necessary plugins.
grunt.loadNpmTasks('grunt-aws')
// Production simulating task.
grunt.registerTask('prod', ['revupdate', 'precompile'])
// Database operation tasks.
grunt.registerTask('db', ['dropDB', 'seedDB'])
grunt.registerTask('db.drop', ['dropDB'])
grunt.registerTask('db.seed', ['seedDB'])
// Deploy task.
grunt.registerTask('deploy', ['bower', 'precompile', 's3', 'revupdate'])
} | Use private ACL for S3 | Grunt/deploy: Use private ACL for S3
| JavaScript | mit | gamekeller/next,gamekeller/next | ---
+++
@@ -15,7 +15,8 @@
bucket: 'gamekeller',
region: 'eu-central-1',
gzip: false,
- overwrite: false
+ overwrite: false,
+ access: 'private'
},
assets: {
cwd: 'public/', |
56abe6dc632ece6f1cb2518f654c6da499798a28 | Gruntfile.js | Gruntfile.js | /**
* Copyright (c) Ajay Sreedhar. All rights reserved.
*
* Licensed under the MIT License.
* Please see LICENSE file located in the project root for more information.
*/
'use strict';
const loadTasks = require('load-grunt-tasks');
const {copyConfig, babelConfig} = require('./build/grunt-config');
const {cleanBuild, startRenderer, makeRelease} = require('./build/grunt-task');
module.exports = function (grunt) {
loadTasks(grunt, {pattern: ['grunt-contrib-copy', 'grunt-babel']});
grunt.initConfig({
copy: copyConfig,
babel: babelConfig
});
grunt.registerTask('clean', 'Cleans up the output files.', cleanBuild);
grunt.registerTask('render', 'Starts the electron renderer.', startRenderer);
grunt.registerTask('release', 'Makes an app release.', makeRelease);
grunt.registerTask('dist', ['clean', 'babel', 'copy']);
grunt.registerTask('start', ['dist', 'render']);
};
| /**
* Copyright (c) Ajay Sreedhar. All rights reserved.
*
* Licensed under the MIT License.
* Please see LICENSE file located in the project root for more information.
*/
'use strict';
const loadTasks = require('load-grunt-tasks');
const {copyConfig, babelConfig} = require('./build/grunt-config');
const {cleanBuild, startRenderer, makeRelease} = require('./build/grunt-task');
module.exports = function (grunt) {
loadTasks(grunt, {pattern: ['grunt-contrib-copy', 'grunt-babel']});
grunt.initConfig({
copy: copyConfig,
babel: babelConfig
});
grunt.registerTask('clean', 'Cleans up the output files.', cleanBuild);
grunt.registerTask('render', 'Starts the electron renderer.', startRenderer);
grunt.registerTask('dist', 'Makes a distributable release.', makeRelease);
grunt.registerTask('compile', ['clean', 'babel', 'copy']);
grunt.registerTask('start', ['compile', 'render']);
};
| Rename dist script as compile | change: Rename dist script as compile
| JavaScript | mit | ajaysreedhar/kongdash,ajaysreedhar/kongdash,ajaysreedhar/kongdash | ---
+++
@@ -22,8 +22,8 @@
grunt.registerTask('clean', 'Cleans up the output files.', cleanBuild);
grunt.registerTask('render', 'Starts the electron renderer.', startRenderer);
- grunt.registerTask('release', 'Makes an app release.', makeRelease);
+ grunt.registerTask('dist', 'Makes a distributable release.', makeRelease);
- grunt.registerTask('dist', ['clean', 'babel', 'copy']);
- grunt.registerTask('start', ['dist', 'render']);
+ grunt.registerTask('compile', ['clean', 'babel', 'copy']);
+ grunt.registerTask('start', ['compile', 'render']);
}; |
3ab63bdd39ba71a9ad8a7cd0dbb768dc26daec64 | Gruntfile.js | Gruntfile.js | module.exports = function (grunt) {
require('load-grunt-tasks')(grunt);
grunt.initConfig({
handlebars: {
compile: {
options: {
amd: ['handlebars', 'handlebars.helpers'],
namespace: 'templates',
partialRegex: /.*/,
partialsPathRegex: /\/partials\//,
processName: function (path) {
return path.match(/([\w]+)\.hbs/)[1];
}
},
files: {
'static/templates/compiled.js': ['src/views/**/*.hbs']
}
}
},
jshint: {
server: {
options: {
jshintrc: true
},
src: ['src/**/*.js']
},
client: {
options: {
jshintrc: true
},
src: ['static/js/**/*.js']
},
tests: {
options: {
jshintrc: true
},
src: ['test/**/*.js']
}
},
sass: {
dist: {
files: {
'static/css/styles.css': 'static/css/styles.scss'
}
}
},
watch: {
handlebars: {
files: ['src/views/**/*.hbs'],
tasks: ['handlebars']
},
jshint: {
files: ['src/**/*.js', 'static/js/**/*.js', 'test/**/*.js'],
tasks: ['jshint']
},
sass: {
files: ['static/css/**/*.scss'],
tasks: ['sass']
}
}
});
grunt.registerTask('default', ['handlebars', 'jshint', 'sass']);
};
| module.exports = function (grunt) {
require('load-grunt-tasks')(grunt);
grunt.initConfig({
handlebars: {
compile: {
options: {
amd: ['handlebars', 'handlebars.helpers'],
namespace: 'templates',
partialRegex: /.*/,
partialsPathRegex: /\/partials\//,
processName: function (path) {
return path.match(/([\w]+)\.hbs/)[1];
}
},
files: {
'static/templates/compiled.js': ['src/views/**/*.hbs']
}
}
},
jshint: {
server: {
options: {
jshintrc: true
},
src: ['src/**/*.js']
},
client: {
options: {
jshintrc: true,
ignores: ['static/js/**/*.min.js']
},
src: ['static/js/**/*.js']
},
tests: {
options: {
jshintrc: true
},
src: ['test/**/*.js']
}
},
sass: {
dist: {
files: {
'static/css/styles.css': 'static/css/styles.scss'
}
}
},
watch: {
handlebars: {
files: ['src/views/**/*.hbs'],
tasks: ['handlebars']
},
jshint: {
files: ['src/**/*.js', 'static/js/**/*.js', 'test/**/*.js'],
tasks: ['jshint']
},
sass: {
files: ['static/css/**/*.scss'],
tasks: ['sass']
}
}
});
grunt.registerTask('default', ['handlebars', 'jshint', 'sass']);
};
| Set jshint to ignore minified files. | Set jshint to ignore minified files.
| JavaScript | mit | neogeek/nodejs-starter-kit | ---
+++
@@ -37,7 +37,8 @@
client: {
options: {
- jshintrc: true
+ jshintrc: true,
+ ignores: ['static/js/**/*.min.js']
},
src: ['static/js/**/*.js']
}, |
0cfe946a2394d1f3def3c55763b856c15ab29892 | Gruntfile.js | Gruntfile.js | const zipFileName = 'extension.zip';
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
webstoreUpload: {
accounts: {
default: {
cli_auth: true, // eslint-disable-line
publish: true,
client_id: process.env.CLIENT_ID, // eslint-disable-line
client_secret: process.env.CLIENT_SECRET, // eslint-disable-line
refresh_token: process.env.REFRESH_TOKEN // eslint-disable-line
}
},
extensions: {
refinedGitHub: {
appID: 'hlepfoohegkhhmjieoechaddaejaokhf', // App ID from chrome webstore
publish: true,
zip: zipFileName
}
}
}
});
grunt.loadNpmTasks('grunt-webstore-upload');
grunt.registerTask('default', ['webstoreUpload']);
};
| const zipFileName = 'extension.zip';
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
webstore_upload: { // eslint-disable-line
accounts: {
default: {
cli_auth: true, // eslint-disable-line
publish: true,
client_id: process.env.CLIENT_ID, // eslint-disable-line
client_secret: process.env.CLIENT_SECRET, // eslint-disable-line
refresh_token: process.env.REFRESH_TOKEN // eslint-disable-line
}
},
extensions: {
refinedGitHub: {
appID: 'hlepfoohegkhhmjieoechaddaejaokhf', // App ID from chrome webstore
publish: true,
zip: zipFileName
}
}
}
});
grunt.loadNpmTasks('grunt-webstore-upload');
grunt.registerTask('default', ['webstore_upload']);
};
| Change deploy Grunt taskname to snake case | Change deploy Grunt taskname to snake case
| JavaScript | mit | sindresorhus/refined-github,busches/refined-github,jgierer12/refined-github,busches/refined-github,sindresorhus/refined-github,jgierer12/refined-github | ---
+++
@@ -2,7 +2,7 @@
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
- webstoreUpload: {
+ webstore_upload: { // eslint-disable-line
accounts: {
default: {
cli_auth: true, // eslint-disable-line
@@ -23,5 +23,5 @@
});
grunt.loadNpmTasks('grunt-webstore-upload');
- grunt.registerTask('default', ['webstoreUpload']);
+ grunt.registerTask('default', ['webstore_upload']);
}; |
1d7088cfae8aa64ff834e1d20911df15af06f745 | Gruntfile.js | Gruntfile.js | module.exports = function(grunt) {
// load grunt tasks from package.json
require('load-grunt-tasks')(grunt);
// Project configuration.
grunt.initConfig({
clean: {
dist: [
'dist',
'robert/**/*.pyc',
]
},
compass: {
dist: {
options: {
sassDir: 'robert/static/sass/',
cssDir: 'robert/static/css/',
outputStyle: 'compressed',
}
}
},
concurrent: {
server: {
options: {
logConcurrentOutput: true,
},
tasks: ['watch', 'shell:devserver']
}
},
shell: {
options: {
stdout: true,
stderr: true,
},
devserver: {
command: 'python run_devserver.py',
},
freeze: {
command: 'python freeze.py',
}
},
watch: {
options: {
livereload: true,
},
python: {
files: ['robert/**/*.py'],
tasks: []
},
sass: {
files: ['robert/static/sass/*.scss'],
tasks: ['compass'],
},
templates: {
files: ['robert/templates/*.html'],
tasks: [],
},
articles: {
files: ['articles/*.md'],
tasks: [],
},
},
});
grunt.registerTask('default', [
'build',
'concurrent:server',
]);
grunt.registerTask('build', [
'clean',
'compass',
'shell:freeze',
]);
};
| module.exports = function(grunt) {
// load grunt tasks from package.json
require('load-grunt-tasks')(grunt);
// Project configuration.
grunt.initConfig({
clean: {
dist: [
'dist',
'robert/**/*.pyc',
],
postbuild: [
'dist/static/sass',
],
},
compass: {
dist: {
options: {
sassDir: 'robert/static/sass/',
cssDir: 'robert/static/css/',
outputStyle: 'compressed',
}
}
},
concurrent: {
server: {
options: {
logConcurrentOutput: true,
},
tasks: ['watch', 'shell:devserver']
}
},
shell: {
options: {
stdout: true,
stderr: true,
},
devserver: {
command: 'python run_devserver.py',
},
freeze: {
command: 'python freeze.py',
}
},
watch: {
options: {
livereload: true,
},
python: {
files: ['robert/**/*.py'],
tasks: []
},
sass: {
files: ['robert/static/sass/*.scss'],
tasks: ['compass'],
},
templates: {
files: ['robert/templates/*.html'],
tasks: [],
},
articles: {
files: ['articles/*.md'],
tasks: [],
},
},
});
grunt.registerTask('default', [
'build',
'concurrent:server',
]);
grunt.registerTask('build', [
'clean:dist',
'compass',
'shell:freeze',
'clean:postbuild',
]);
};
| Add a postbuild task to grunt to remove unnecessary build artifacts | Add a postbuild task to grunt to remove unnecessary build artifacts
| JavaScript | mit | thusoy/robertblag,thusoy/robertblag,thusoy/robertblag | ---
+++
@@ -10,7 +10,10 @@
dist: [
'dist',
'robert/**/*.pyc',
- ]
+ ],
+ postbuild: [
+ 'dist/static/sass',
+ ],
},
compass: {
@@ -74,8 +77,9 @@
]);
grunt.registerTask('build', [
- 'clean',
+ 'clean:dist',
'compass',
'shell:freeze',
+ 'clean:postbuild',
]);
}; |
1e421c03fce6c4b1e167c232838b3273249f0fc9 | api/models/rat.js | api/models/rat.js | var mongoose, RatSchema, Schema;
mongoose = require( 'mongoose' );
Schema = mongoose.Schema;
RatSchema = new Schema({
'archive': {
default: false,
type: Boolean
},
'CMDRname': {
type: String
},
'createdAt': {
type: Date
},
'drilled': {
default: false,
type: Boolean
},
'gamertag': {
type: String
},
'lastModified': {
type: Date
},
'joined': {
default: Date.now(),
type: Date
},
'netlog': {
type: {
'commanderId': {
type: String
},
'data': {
type: Schema.Types.Mixed
},
'userId': {
type: String
}
}
},
'nickname': {
type: String
}
});
RatSchema.index({
'CMDRname': 'text',
'gamertag': 'text',
'nickname': 'text'
});
RatSchema.pre( 'save', function ( next ) {
var timestamp;
timestamp = Date.now();
this.createdAt = this.createdAt || timestamp;
this.lastModified = timestamp;
next();
});
RatSchema.set( 'toJSON', {
virtuals: true,
transform: function ( document, ret, options ) {
ret.id = ret._id;
delete ret._id;
}
});
module.exports = mongoose.model( 'Rat', RatSchema );
| var mongoose, RatSchema, Schema;
mongoose = require( 'mongoose' );
Schema = mongoose.Schema;
RatSchema = new Schema({
'archive': {
default: false,
type: Boolean
},
'CMDRname': {
type: String
},
'createdAt': {
type: Date
},
'drilled': {
default: false,
type: Boolean
},
'gamertag': {
type: String
},
'lastModified': {
type: Date
},
'joined': {
default: Date.now(),
type: Date
},
'netlog': {
type: {
'commanderId': {
type: String
},
'data': {
type: Schema.Types.Mixed
},
'userId': {
type: String
}
}
},
'nickname': {
type: [String]
}
});
RatSchema.index({
'CMDRname': 'text',
'gamertag': 'text',
'nickname': 'text'
});
RatSchema.pre( 'save', function ( next ) {
var timestamp;
timestamp = Date.now();
this.createdAt = this.createdAt || timestamp;
this.lastModified = timestamp;
next();
});
RatSchema.set( 'toJSON', {
virtuals: true,
transform: function ( document, ret, options ) {
ret.id = ret._id;
delete ret._id;
}
});
module.exports = mongoose.model( 'Rat', RatSchema );
| Add rescue field to store client's messages | Add rescue field to store client's messages
| JavaScript | bsd-3-clause | FuelRats/api.fuelrats.com,FuelRats/api.fuelrats.com,FuelRats/api.fuelrats.com | ---
+++
@@ -42,7 +42,7 @@
}
},
'nickname': {
- type: String
+ type: [String]
}
});
|
0e854b660501e3bcdf01071392b9ab0ec8b9a5f0 | src/components/Iframe/index.js | src/components/Iframe/index.js | import React, {PropTypes} from 'react'
import injectSheet from '../../utils/jss'
function Iframe({src, sheet: {classes}}) {
return <iframe src={src} className={classes.iframe} />
}
Iframe.propTypes = {
src: PropTypes.string.isRequired,
sheet: PropTypes.object.isRequired
}
const styles = {
iframe: {
width: '100%',
height: '100%',
border: 0
}
}
export default injectSheet(styles)(Iframe)
| import React, {PropTypes} from 'react'
import injectSheet from '../../utils/jss'
function Iframe({src, sheet: {classes}}) {
return <iframe src={src} className={classes.iframe} />
}
Iframe.propTypes = {
src: PropTypes.string.isRequired,
sheet: PropTypes.object.isRequired
}
const styles = {
iframe: {
width: '100%',
height: '100vh',
minHeight: 50,
border: 0,
display: 'block'
}
}
export default injectSheet(styles)(Iframe)
| Fix iframe height after migration to vh | Fix iframe height after migration to vh
| JavaScript | mit | cssinjs/cssinjs | ---
+++
@@ -13,8 +13,10 @@
const styles = {
iframe: {
width: '100%',
- height: '100%',
- border: 0
+ height: '100vh',
+ minHeight: 50,
+ border: 0,
+ display: 'block'
}
}
|
b0fc06384fcddaf293c5c9f66b4a49b8f2f7c56b | app/index.js | app/index.js | import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import Routes from './routes'
import Store from './store'
ReactDOM.render(
<Provider store={Store}>
<Routes />
</Provider>,
document.getElementById('root')
)
| import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import Routes from './routes'
import Store from './store'
ReactDOM.render(
<Provider store={Store}>
<Routes />
</Provider>,
document.getElementById('application')
)
| Fix the root component id. | Fix the root component id.
| JavaScript | mit | rhberro/the-react-client,rhberro/the-react-client | ---
+++
@@ -9,5 +9,5 @@
<Provider store={Store}>
<Routes />
</Provider>,
- document.getElementById('root')
+ document.getElementById('application')
) |
ccc12a7dae4b01674f9bc76efaefef5f901852e2 | src/components/preview/Code.js | src/components/preview/Code.js | // @flow
import { PureComponent } from 'react'
import Lowlight from 'react-lowlight'
import js from 'highlight.js/lib/languages/javascript'
import type { Children } from 'react'
type Props = {
className:string,
children: Children,
}
Lowlight.registerLanguage('js', js)
export default class Code extends PureComponent<void, Props, void> {
static languageClassNamePattern = /\s*language-([\w-]+)\s*/
// for lint
props: Props
get language (): string {
const match = (this.props.className || '').match(Code.languageClassNamePattern)
const lang = (match && match[1]) || ''
return Lowlight.hasLanguage(lang) ? lang : ''
}
get value (): string {
return this.props.children[0]
}
render () {
return (
<Lowlight
language={this.language}
value={this.value}
inline
/>
)
}
}
| // @flow
import { PureComponent } from 'react'
import Lowlight from 'react-lowlight'
import type { Children } from 'react'
import langMap from 'settings/languageNameMap'
type Props = {
className:string,
children: Children,
}
type State = {
language: string,
}
export default class Code extends PureComponent<void, Props, State> {
static languageClassNamePattern = /\s*language-([\w-]+)\s*/
constructor (props: Props) {
super(props)
this.state = {
language: '',
}
}
state: State
componentWillMount () {
this.registerLanguage(this.props.className)
}
componentWillReceiveProps ({ className }: Props) {
this.registerLanguage(className)
}
async registerLanguage (className: string) {
const match = (className || '').match(Code.languageClassNamePattern)
const langName = (match && match[1]) || ''
const lang = langMap[langName]
if (lang == null) {
this.setState({ language: '' })
} else if (Lowlight.hasLanguage(langName)) {
this.setState({ language: langName })
} else {
Lowlight.registerLanguage(langName, await lang.load())
this.setState({ language: langName })
}
}
get value (): string {
return this.props.children[0]
}
render () {
return (
<Lowlight
language={this.state.language}
value={this.value}
inline
/>
)
}
}
| Load language config for highlight.js dynamically | Load language config for highlight.js dynamically
| JavaScript | mit | izumin5210/OHP,izumin5210/OHP | ---
+++
@@ -1,27 +1,51 @@
// @flow
import { PureComponent } from 'react'
import Lowlight from 'react-lowlight'
-import js from 'highlight.js/lib/languages/javascript'
import type { Children } from 'react'
+import langMap from 'settings/languageNameMap'
type Props = {
className:string,
children: Children,
}
-Lowlight.registerLanguage('js', js)
+type State = {
+ language: string,
+}
-export default class Code extends PureComponent<void, Props, void> {
+export default class Code extends PureComponent<void, Props, State> {
static languageClassNamePattern = /\s*language-([\w-]+)\s*/
- // for lint
- props: Props
+ constructor (props: Props) {
+ super(props)
+ this.state = {
+ language: '',
+ }
+ }
- get language (): string {
- const match = (this.props.className || '').match(Code.languageClassNamePattern)
- const lang = (match && match[1]) || ''
- return Lowlight.hasLanguage(lang) ? lang : ''
+ state: State
+
+ componentWillMount () {
+ this.registerLanguage(this.props.className)
+ }
+
+ componentWillReceiveProps ({ className }: Props) {
+ this.registerLanguage(className)
+ }
+
+ async registerLanguage (className: string) {
+ const match = (className || '').match(Code.languageClassNamePattern)
+ const langName = (match && match[1]) || ''
+ const lang = langMap[langName]
+ if (lang == null) {
+ this.setState({ language: '' })
+ } else if (Lowlight.hasLanguage(langName)) {
+ this.setState({ language: langName })
+ } else {
+ Lowlight.registerLanguage(langName, await lang.load())
+ this.setState({ language: langName })
+ }
}
get value (): string {
@@ -31,7 +55,7 @@
render () {
return (
<Lowlight
- language={this.language}
+ language={this.state.language}
value={this.value}
inline
/> |
1433d3379014c115636cf0d472fb085c5397b4a7 | test/mocha/github-2xx-76.js | test/mocha/github-2xx-76.js | "use strict";
var Promise = require("../../js/debug/bluebird.js");
Promise.longStackTraces();
var assert = require("assert");
describe("github276 - stack trace cleaner", function(){
specify("message with newline and a$_b should not be removed", function(done){
Promise.resolve(1).then(function() {
throw new Error("Blah\n a$_b");
}).catch(function(e) {
var msg = e.stack.split('\n')[1]
assert(msg.indexOf('a$_b') >= 0, 'message should contain a$_b');
}).done(done, done);
});
});
| "use strict";
var Promise = require("../../js/debug/bluebird.js");
Promise.longStackTraces();
var assert = require("assert");
var isNodeJS = typeof process !== "undefined" &&
typeof process.execPath === "string";
if (isNodeJS) {
describe("github276 - stack trace cleaner", function(){
specify("message with newline and a$_b should not be removed", function(done){
Promise.resolve(1).then(function() {
throw new Error("Blah\n a$_b");
}).caught(function(e) {
var msg = e.stack.split('\n')[1]
assert(msg.indexOf('a$_b') >= 0, 'message should contain a$_b');
}).done(done, done);
});
});
}
| Add nodejs guard for nodejs test | Add nodejs guard for nodejs test
| JavaScript | mit | tpphu/bluebird,joemcelroy/bluebird,lindenle/bluebird,BigDSK/bluebird,cwhatley/bluebird,avinoamr/bluebird,Wanderfalke/bluebird,tesfaldet/bluebird,paulcbetts/bluebird,timnew/bluebird,techniq/bluebird,robertn702/bluebird,atom-morgan/bluebird,Scientifik/bluebird,perfecting/bluebird,javraindawn/bluebird,RobinQu/bluebird,vladikoff/bluebird,StefanoDeVuono/bluebird,matklad/bluebird,perfecting/bluebird,alubbe/bluebird,impy88/bluebird,ryanwholey/bluebird,rrpod/bluebird,ziad-saab/bluebird,n1kolas/bluebird,ajitsy/bluebird,alubbe/bluebird,a25patel/bluebird,tpphu/bluebird,lo1tuma/bluebird,starkwang/bluebird,kidaa/bluebird,impy88/bluebird,codevlabs/bluebird,henryqdineen/bluebird,tesfaldet/bluebird,kidaa/bluebird,HBOCodeLabs/bluebird,petkaantonov/bluebird,linalu1/bluebird,ryanwholey/bluebird,ankushg/bluebird,avinoamr/bluebird,peterKaleta/bluebird,codevlabs/bluebird,reggi/bluebird,code-monkeys/bluebird,arenaonline/bluebird,code-monkeys/bluebird,janzal/bluebird,wainage/bluebird,cgvarela/bluebird,kjvalencik/bluebird,akinsella/bluebird,BridgeAR/bluebird,naoufal/bluebird,garysye/bluebird,davyengone/bluebird,rrpod/bluebird,ryanwholey/bluebird,esco/bluebird,janmeier/bluebird,mdarveau/bluebird,briandela/bluebird,gillesdemey/bluebird,TechnicalPursuit/bluebird,javraindawn/bluebird,Scientifik/bluebird,whatupdave/bluebird,abhishekgahlot/bluebird,justsml/bluebird,a25patel/bluebird,djchie/bluebird,tesfaldet/bluebird,bjonica/bluebird,DeX3/bluebird,moretti/bluebird,matklad/bluebird,BridgeAR/bluebird,yonjah/bluebird,abhishekgahlot/bluebird,DrewVartanian/bluebird,naoufal/bluebird,angelxmoreno/bluebird,jozanza/bluebird,cwhatley/bluebird,migclark/bluebird,fmoliveira/bluebird,moretti/bluebird,code-monkeys/bluebird,akinsella/bluebird,lo1tuma/bluebird,jozanza/bluebird,soyuka/bluebird,perfecting/bluebird,goopscoop/bluebird,a25patel/bluebird,StefanoDeVuono/bluebird,bjonica/bluebird,spion/bluebird,briandela/bluebird,ricardo-hdz/bluebird,peterKaleta/bluebird,javraindawn/bluebird,haohui/bluebird,DrewVartanian/bluebird,amelon/bluebird,Zeratul5/bluebird,fadzlan/bluebird,gillesdemey/bluebird,STRML/bluebird,ydaniv/bluebird,gillesdemey/bluebird,DrewVartanian/bluebird,xbenjii/bluebird,tpphu/bluebird,janzal/bluebird,fadzlan/bluebird,justsml/bluebird,P-Seebauer/bluebird,sandrinodimattia/bluebird,janmeier/bluebird,goofiw/bluebird,satyadeepk/bluebird,Scientifik/bluebird,TechnicalPursuit/bluebird,petkaantonov/bluebird,alubbe/bluebird,goofiw/bluebird,goopscoop/bluebird,matklad/bluebird,starkwang/bluebird,xdevelsistemas/bluebird,techniq/bluebird,timnew/bluebird,ydaniv/bluebird,cgvarela/bluebird,HBOCodeLabs/bluebird,bsiddiqui/bluebird,developmentstudio/bluebird,atom-morgan/bluebird,impy88/bluebird,lindenle/bluebird,paulcbetts/bluebird,illahi0/bluebird,goopscoop/bluebird,whatupdave/bluebird,briandela/bluebird,fadzlan/bluebird,cusspvz/bluebird,ydaniv/bluebird,haohui/bluebird,garysye/bluebird,yonjah/bluebird,ricardo-hdz/bluebird,djchie/bluebird,xbenjii/bluebird,amelon/bluebird,ScheerMT/bluebird,reggi/bluebird,johnculviner/bluebird,rrpod/bluebird,henryqdineen/bluebird,wainage/bluebird,ronaldbaltus/bluebird,Zeratul5/bluebird,dantheuber/bluebird,kidaa/bluebird,robertn702/bluebird,xdevelsistemas/bluebird,mcanthony/bluebird,mcanthony/bluebird,spion/bluebird,bjonica/bluebird,lo1tuma/bluebird,ronaldbaltus/bluebird,RobinQu/bluebird,BigDSK/bluebird,joemcelroy/bluebird,JaKXz/bluebird,henryqdineen/bluebird,esco/bluebird,RobinQu/bluebird,developmentstudio/bluebird,cgvarela/bluebird,davyengone/bluebird,dantheuber/bluebird,peterKaleta/bluebird,JaKXz/bluebird,migclark/bluebird,jozanza/bluebird,kjvalencik/bluebird,JaKXz/bluebird,illahi0/bluebird,mdarveau/bluebird,ajitsy/bluebird,bsiddiqui/bluebird,migclark/bluebird,atom-morgan/bluebird,BridgeAR/bluebird,codevlabs/bluebird,justsml/bluebird,amelon/bluebird,developmentstudio/bluebird,HBOCodeLabs/bluebird,enicolasWebs/bluebird,bsiddiqui/bluebird,linalu1/bluebird,linalu1/bluebird,STRML/bluebird,robertn702/bluebird,ajitsy/bluebird,soyuka/bluebird,cusspvz/bluebird,haohui/bluebird,STRML/bluebird,Wanderfalke/bluebird,cusspvz/bluebird,DeX3/bluebird,StefanoDeVuono/bluebird,avinoamr/bluebird,angelxmoreno/bluebird,esco/bluebird,joemcelroy/bluebird,timnew/bluebird,n1kolas/bluebird,ziad-saab/bluebird,arenaonline/bluebird,illahi0/bluebird,yonjah/bluebird,TechnicalPursuit/bluebird,P-Seebauer/bluebird,Zeratul5/bluebird,P-Seebauer/bluebird,enicolasWebs/bluebird,whatupdave/bluebird,ScheerMT/bluebird,ankushg/bluebird,fmoliveira/bluebird,kjvalencik/bluebird,ScheerMT/bluebird,dantheuber/bluebird,moretti/bluebird,vladikoff/bluebird,sandrinodimattia/bluebird,soyuka/bluebird,DeX3/bluebird,lindenle/bluebird,abhishekgahlot/bluebird,djchie/bluebird,vladikoff/bluebird,reggi/bluebird,cwhatley/bluebird,naoufal/bluebird,goofiw/bluebird,angelxmoreno/bluebird,garysye/bluebird,johnculviner/bluebird,satyadeepk/bluebird,mdarveau/bluebird,petkaantonov/bluebird,wainage/bluebird,sandrinodimattia/bluebird,mcanthony/bluebird,davyengone/bluebird,johnculviner/bluebird,xbenjii/bluebird,paulcbetts/bluebird,janzal/bluebird,ricardo-hdz/bluebird,fmoliveira/bluebird,satyadeepk/bluebird,n1kolas/bluebird,Wanderfalke/bluebird,xdevelsistemas/bluebird,techniq/bluebird,ronaldbaltus/bluebird,arenaonline/bluebird,ankushg/bluebird,ziad-saab/bluebird,enicolasWebs/bluebird,janmeier/bluebird,starkwang/bluebird,BigDSK/bluebird,akinsella/bluebird | ---
+++
@@ -4,15 +4,18 @@
var Promise = require("../../js/debug/bluebird.js");
Promise.longStackTraces();
var assert = require("assert");
+var isNodeJS = typeof process !== "undefined" &&
+ typeof process.execPath === "string";
-describe("github276 - stack trace cleaner", function(){
- specify("message with newline and a$_b should not be removed", function(done){
- Promise.resolve(1).then(function() {
- throw new Error("Blah\n a$_b");
- }).catch(function(e) {
- var msg = e.stack.split('\n')[1]
- assert(msg.indexOf('a$_b') >= 0, 'message should contain a$_b');
- }).done(done, done);
+if (isNodeJS) {
+ describe("github276 - stack trace cleaner", function(){
+ specify("message with newline and a$_b should not be removed", function(done){
+ Promise.resolve(1).then(function() {
+ throw new Error("Blah\n a$_b");
+ }).caught(function(e) {
+ var msg = e.stack.split('\n')[1]
+ assert(msg.indexOf('a$_b') >= 0, 'message should contain a$_b');
+ }).done(done, done);
+ });
});
-});
-
+} |
92334651e178d2760434e8e1923ba691c69f448c | src/events/mouse-dispatcher.js | src/events/mouse-dispatcher.js | var slice = [].slice
exports = function mouseDispatcher(name, fn) {
return function(x, y) {
var target = document.elementFromPoint(x, y) || document
var event = new MouseEvent(name, {
bubbles: true,
clientX: x,
clientY: y
})
fn.apply(event, slice.call(arguments, 2))
target.dispatchEvent(event)
}
}
| var slice = [].slice
exports = function mouseDispatcher(name, fn) {
return function(clientX, clientY, shiftKey, ctrlKey, altKey, metaKey) {
var target = document.elementFromPoint(clientX, clientY) || document
var event = new MouseEvent(name, {
bubbles: true,
clientX: clientX,
clientY: clientY,
shiftKey: shiftKey,
ctrlKey: ctrlKey,
altKey: altKey,
metaKey: metaKey
})
fn.apply(event, slice.call(arguments, 6))
target.dispatchEvent(event)
}
}
| Handle modifier keys in mouse dispatcher | Handle modifier keys in mouse dispatcher
| JavaScript | unlicense | freedraw/core,freedraw/core | ---
+++
@@ -1,14 +1,18 @@
var slice = [].slice
exports = function mouseDispatcher(name, fn) {
- return function(x, y) {
- var target = document.elementFromPoint(x, y) || document
+ return function(clientX, clientY, shiftKey, ctrlKey, altKey, metaKey) {
+ var target = document.elementFromPoint(clientX, clientY) || document
var event = new MouseEvent(name, {
bubbles: true,
- clientX: x,
- clientY: y
+ clientX: clientX,
+ clientY: clientY,
+ shiftKey: shiftKey,
+ ctrlKey: ctrlKey,
+ altKey: altKey,
+ metaKey: metaKey
})
- fn.apply(event, slice.call(arguments, 2))
+ fn.apply(event, slice.call(arguments, 6))
target.dispatchEvent(event)
}
} |
112f786717f405f0b2b708fe67d4b6df780386ea | models/Author.js | models/Author.js | var keystone = require('keystone');
var Types = keystone.Field.Types;
/**
* Author Model
* ==========
*/
var Author = new keystone.List('Author');
Author.add({
firstName: { type: Types.Text, initial: true, required: true, index: true },
lastName: { type: Types.Text, initial: true, required: true, index: true },
email: { type: Types.Email },
affiliations: { type: Types.Relationship, ref: 'Organization', many: true },
});
/**
* Registration
*/
Author.defaultColumns = 'firstName, lastName';
Author.register();
| var keystone = require('keystone');
var Types = keystone.Field.Types;
/**
* Author Model
* ==========
*/
var Author = new keystone.List('Author');
Author.add({
name: { type: Types.Name, initial: true, required: true, index: true },
email: { type: Types.Email },
affiliations: { type: Types.Relationship, ref: 'Organization', many: true },
});
/**
* Registration
*/
Author.defaultColumns = 'name, affiliations';
Author.register();
| Use single name field for authors | Use single name field for authors
| JavaScript | mit | zharley/papers,zharley/papers | ---
+++
@@ -8,8 +8,7 @@
var Author = new keystone.List('Author');
Author.add({
- firstName: { type: Types.Text, initial: true, required: true, index: true },
- lastName: { type: Types.Text, initial: true, required: true, index: true },
+ name: { type: Types.Name, initial: true, required: true, index: true },
email: { type: Types.Email },
affiliations: { type: Types.Relationship, ref: 'Organization', many: true },
});
@@ -17,5 +16,5 @@
/**
* Registration
*/
-Author.defaultColumns = 'firstName, lastName';
+Author.defaultColumns = 'name, affiliations';
Author.register(); |
f768f26e0b1da687a04da7256047d12d34b11f1c | examples/example2.js | examples/example2.js | var ping = require("../index");
var hosts = ['192.168.1.1', 'google.com', 'yahoo.com'];
hosts.forEach(function (host) {
ping.promise.probe(host)
.then(function (res) {
console.log(res);
})
.done();
});
hosts.forEach(function (host) {
ping.promise.probe(host, {
timeout: 10,
extra: ["-i 2"]
})
.then(function (res) {
console.log(res);
})
.done();
});
| var ping = require("../index");
var hosts = ['192.168.1.1', 'google.com', 'yahoo.com'];
hosts.forEach(function (host) {
ping.promise.probe(host)
.then(function (res) {
console.log(res);
})
.done();
});
hosts.forEach(function (host) {
ping.promise.probe(host, {
timeout: 10,
extra: ["-i", "2"]
})
.then(function (res) {
console.log(res);
})
.done();
});
| Fix bug on window platform | Fix bug on window platform
--Overview
1. Window's ping command treat '-i 2' as an invalid option. Therefore,
we must split them up. IE using ['-i', '2'] instead of ['-i 2']
| JavaScript | mit | alexgervais/node-ping,danielzzz/node-ping | ---
+++
@@ -13,7 +13,7 @@
hosts.forEach(function (host) {
ping.promise.probe(host, {
timeout: 10,
- extra: ["-i 2"]
+ extra: ["-i", "2"]
})
.then(function (res) {
console.log(res); |
2ba85374c28132da84e6f7679bb1bb4f487db14d | webpack.config.js | webpack.config.js | var path = require('path');
var webpack = require('webpack');
var Clean = require('clean-webpack-plugin');
var webpackConfig = require("./webpack-base-config");
webpackConfig.entry = path.resolve(__dirname, 'src/main.js');
if (process.env.npm_lifecycle_event === 'release') {
webpackConfig.plugins.push(new webpack.optimize.UglifyJsPlugin({
compress: {warnings: false},
output: {comments: false}
}));
} else {
webpackConfig.plugins.push(new Clean(['dist']));
}
webpackConfig.output = {
path: path.resolve(__dirname, 'dist'),
publicPath: '<%=baseUrl%>/',
filename: 'clappr.js',
library: 'Clappr',
libraryTarget: 'umd',
};
module.exports = webpackConfig;
| var path = require('path');
var webpack = require('webpack');
var Clean = require('clean-webpack-plugin');
var webpackConfig = require("./webpack-base-config");
webpackConfig.entry = path.resolve(__dirname, 'src/main.js');
if (process.env.npm_lifecycle_event === 'release') {
webpackConfig.plugins.push(new webpack.optimize.UglifyJsPlugin({
compress: {warnings: false},
output: {comments: false}
}));
} else {
webpackConfig.plugins.push(new Clean(['dist'], {verbose: false}));
}
webpackConfig.output = {
path: path.resolve(__dirname, 'dist'),
publicPath: '<%=baseUrl%>/',
filename: 'clappr.js',
library: 'Clappr',
libraryTarget: 'umd',
};
module.exports = webpackConfig;
| Set verbose to false in webpack clean plugin | Set verbose to false in webpack clean plugin | JavaScript | bsd-3-clause | flavioribeiro/clappr,clappr/clappr,flavioribeiro/clappr,clappr/clappr,clappr/clappr,flavioribeiro/clappr | ---
+++
@@ -11,7 +11,7 @@
output: {comments: false}
}));
} else {
- webpackConfig.plugins.push(new Clean(['dist']));
+ webpackConfig.plugins.push(new Clean(['dist'], {verbose: false}));
}
webpackConfig.output = { |
d341843ff99eeb5b3371e8e13420363366f2d8bf | js/components/games/DeployButton.react.js | js/components/games/DeployButton.react.js | "use strict";
var _ = require('mori');
var Router = require('react-router');
var React = require('react');
var mori = require("mori");
var UnitCell = require('../board/UnitCell.react.js');
var GameStore = require('../../stores/GameStore.js');
var ProfileLink = require('../common/ProfileLink.react.js');
var GameActions = require('../../actions/GameActions.js');
module.exports = React.createClass({
render: function () {
var game = this.props.game;
var state = _.getIn(game, ["board", "state"]);
var stash = _.getIn(game, ["board", "stash", this.props.playerCode]);
var originalStash = _.getIn(this.props.originalGame, ["board", "stash", this.props.playerCode]);
var css = "btn btn-info";
if("deploy" === state) {
if(_.isEmpty(originalStash)) {
css = "hide";
} else if(!_.isEmpty(stash)) {
css = "btn btn-default disabled";
}
} else {
css = "hide";
}
return (
<a onClick={this.click} className={css}>Deploy</a>
);
},
click: function click(ev) {
GameActions.deployGame(this.props.game);
}
});
| "use strict";
var _ = require('mori');
var Router = require('react-router');
var React = require('react');
var mori = require("mori");
var UnitCell = require('../board/UnitCell.react.js');
var GameStore = require('../../stores/GameStore.js');
var ProfileLink = require('../common/ProfileLink.react.js');
var GameActions = require('../../actions/GameActions.js');
module.exports = React.createClass({
render: function () {
var game = this.props.game;
var stash = _.getIn(game, ["board", "stash", this.props.playerCode]);
var originalGame = this.props.originalGame;
var state = _.getIn(originalGame, ["board", "state"]);
var originalStash = _.getIn(originalGame, ["board", "stash", this.props.playerCode]);
console.log(state)
var css = "btn btn-info";
if("deploy" === state) {
if(_.isEmpty(originalStash)) {
css = "hide";
} else if(!_.isEmpty(stash)) {
css = "btn btn-default disabled";
}
} else {
css = "hide";
}
return (
<a onClick={this.click} className={css}>Deploy</a>
);
},
click: function click(ev) {
GameActions.deployGame(this.props.game);
}
});
| Fix deploy button for second player | Fix deploy button for second player
| JavaScript | mit | orionsbelt-battlegrounds/frontend,orionsbelt-battlegrounds/frontend,orionsbelt-battlegrounds/frontend | ---
+++
@@ -13,10 +13,13 @@
render: function () {
var game = this.props.game;
- var state = _.getIn(game, ["board", "state"]);
var stash = _.getIn(game, ["board", "stash", this.props.playerCode]);
- var originalStash = _.getIn(this.props.originalGame, ["board", "stash", this.props.playerCode]);
+ var originalGame = this.props.originalGame;
+ var state = _.getIn(originalGame, ["board", "state"]);
+ var originalStash = _.getIn(originalGame, ["board", "stash", this.props.playerCode]);
+
+ console.log(state)
var css = "btn btn-info";
if("deploy" === state) {
if(_.isEmpty(originalStash)) { |
4012357932dc0d9acb17076cd321affa6d94cb81 | src/ggrc/assets/javascripts/components/assessment/info-pane/info-pane.js | src/ggrc/assets/javascripts/components/assessment/info-pane/info-pane.js | /*!
Copyright (C) 2017 Google Inc., authors, and contributors
Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
*/
(function (can, GGRC) {
'use strict';
var tpl = can.view(GGRC.mustache_path +
'/components/assessment/info-pane/info-pane.mustache');
/**
* Assessment Specific Info Pane View Component
*/
GGRC.Components('assessmentInfoPane', {
tag: 'assessment-info-pane',
template: tpl,
viewModel: {
define: {
isLocked: {
type: 'htmlbool',
value: false
}
},
instance: {}
}
});
})(window.can, window.GGRC);
| /*!
Copyright (C) 2017 Google Inc., authors, and contributors
Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
*/
(function (can, GGRC) {
'use strict';
var tpl = can.view(GGRC.mustache_path +
'/components/assessment/info-pane/info-pane.mustache');
/**
* Assessment Specific Info Pane View Component
*/
GGRC.Components('assessmentInfoPane', {
tag: 'assessment-info-pane',
template: tpl,
viewModel: {
define: {
mappedSnapshots: {
value: function () {
return [];
}
},
controls: {
get: function () {
return this.attr('mappedSnapshots')
.filter(function (item) {
return item.child_type === 'Control';
});
}
},
relatedInformation: {
get: function () {
return this.attr('mappedSnapshots')
.filter(function (item) {
return item.child_type !== 'Control';
});
}
}
},
instance: null,
getSnapshotQuery: function () {
var relevantFilters = [{
type: this.attr('instance.type'),
id: this.attr('instance.id'),
operation: 'relevant'
}];
return GGRC.Utils.QueryAPI
.buildParam('Snapshot', {}, relevantFilters, [], []);
},
requestQuery: function (query) {
var dfd = can.Deferred();
this.attr('isLoading', true);
GGRC.Utils.QueryAPI
.batchRequests(query)
.done(function (response) {
var type = Object.keys(response)[0];
var values = response[type].values;
dfd.resolve(values);
})
.fail(function () {
dfd.resolve([]);
})
.always(function () {
this.attr('isLoading', false);
}.bind(this));
return dfd;
},
loadSnapshots: function () {
var query = this.getSnapshotQuery();
return this.requestQuery(query);
}
},
init: function () {
this.viewModel.attr('mappedSnapshots')
.replace(this.viewModel.loadSnapshots());
},
events: {
'{viewModel.instance} related_destinations': function () {
console.info('Was related_destinations called!!!!', arguments);
}
}
});
})(window.can, window.GGRC);
| Add Extra Loading Logic to Assessment Info Pane Component | Add Extra Loading Logic to Assessment Info Pane Component
| JavaScript | apache-2.0 | AleksNeStu/ggrc-core,AleksNeStu/ggrc-core,AleksNeStu/ggrc-core,AleksNeStu/ggrc-core | ---
+++
@@ -16,12 +16,69 @@
template: tpl,
viewModel: {
define: {
- isLocked: {
- type: 'htmlbool',
- value: false
+ mappedSnapshots: {
+ value: function () {
+ return [];
+ }
+ },
+ controls: {
+ get: function () {
+ return this.attr('mappedSnapshots')
+ .filter(function (item) {
+ return item.child_type === 'Control';
+ });
+ }
+ },
+ relatedInformation: {
+ get: function () {
+ return this.attr('mappedSnapshots')
+ .filter(function (item) {
+ return item.child_type !== 'Control';
+ });
+ }
}
},
- instance: {}
+ instance: null,
+ getSnapshotQuery: function () {
+ var relevantFilters = [{
+ type: this.attr('instance.type'),
+ id: this.attr('instance.id'),
+ operation: 'relevant'
+ }];
+ return GGRC.Utils.QueryAPI
+ .buildParam('Snapshot', {}, relevantFilters, [], []);
+ },
+ requestQuery: function (query) {
+ var dfd = can.Deferred();
+ this.attr('isLoading', true);
+ GGRC.Utils.QueryAPI
+ .batchRequests(query)
+ .done(function (response) {
+ var type = Object.keys(response)[0];
+ var values = response[type].values;
+ dfd.resolve(values);
+ })
+ .fail(function () {
+ dfd.resolve([]);
+ })
+ .always(function () {
+ this.attr('isLoading', false);
+ }.bind(this));
+ return dfd;
+ },
+ loadSnapshots: function () {
+ var query = this.getSnapshotQuery();
+ return this.requestQuery(query);
+ }
+ },
+ init: function () {
+ this.viewModel.attr('mappedSnapshots')
+ .replace(this.viewModel.loadSnapshots());
+ },
+ events: {
+ '{viewModel.instance} related_destinations': function () {
+ console.info('Was related_destinations called!!!!', arguments);
+ }
}
});
})(window.can, window.GGRC); |
e2fb55b5ff165df0f58e4cdeffeb1c34f49fe382 | angular-toggle-switch.js | angular-toggle-switch.js | angular.module('toggle-switch', ['ng']).directive('toggleSwitch', function() {
return {
restrict: 'EA',
replace: true,
scope: {
model: '='
},
template: '<div class="switch" ng-click="toggle()"><div class="switch-animate switch-off" ng-class="{\'switch-off\': !model, \'switch-on\': model}"><span class="switch-left">On</span><span class="knob"> </span><span class="switch-right">Off</span></div></div>',
link: function($scope, element, attrs) {
if ($scope.model == null) {
$scope.model = false;
}
return $scope.toggle = function() {
return $scope.model = !$scope.model;
};
}
};
});
| angular.module('toggle-switch', ['ng']).directive('toggleSwitch', function() {
return {
restrict: 'EA',
replace: true,
scope: {
model: '='
},
template: '<div class="switch" ng-click="toggle()"><div class="switch-animate" ng-class="{\'switch-off\': !model, \'switch-on\': model}"><span class="switch-left">On</span><span class="knob"> </span><span class="switch-right">Off</span></div></div>',
link: function($scope, element, attrs) {
if ($scope.model == null) {
$scope.model = false;
}
return $scope.toggle = function() {
return $scope.model = !$scope.model;
};
}
};
});
| Remove default class switch-off (fix css bug when a switcher is set to true by default) | Remove default class switch-off (fix css bug when a switcher is set to true by default)
| JavaScript | mit | JeromeSadou/angular-toggle-switch,cgarvis/angular-toggle-switch,JumpLink/angular-toggle-switch,nilpath/angular-toggle-switch,razvanz/angular-toggle-switch,zachlysobey/angular-toggle-switch,ProtonMail/angular-toggle-switch,nilpath/angular-toggle-switch,JeromeSadou/angular-toggle-switch,chris110408/angular-toggle-switch,JumpLink/angular-toggle-switch | ---
+++
@@ -5,7 +5,7 @@
scope: {
model: '='
},
- template: '<div class="switch" ng-click="toggle()"><div class="switch-animate switch-off" ng-class="{\'switch-off\': !model, \'switch-on\': model}"><span class="switch-left">On</span><span class="knob"> </span><span class="switch-right">Off</span></div></div>',
+ template: '<div class="switch" ng-click="toggle()"><div class="switch-animate" ng-class="{\'switch-off\': !model, \'switch-on\': model}"><span class="switch-left">On</span><span class="knob"> </span><span class="switch-right">Off</span></div></div>',
link: function($scope, element, attrs) {
if ($scope.model == null) {
$scope.model = false; |
56733b29e6b79dd0b7b00f7a9fe778b209ceaa73 | backend/server/apikey.js | backend/server/apikey.js | // apikey module validates the apikey argument used in the call. It
// caches the list of users to make lookups faster.
module.exports = function(users) {
'use strict';
let apikeyCache = require('./apikey-cache')(users);
let httpStatus = require('http-status');
// whiteList contains paths that don't require
// a valid apikey.
let whiteList = {
"/login": true,
"/socket.io/socket.io.js": true,
"/socket.io/": true
};
// validateAPIKey Looks up the apikey. If none is specified, or a
// bad key is passed then abort the calls and send back an 401.
return function *validateAPIKey(next) {
if (!(this.path in whiteList)) {
let UNAUTHORIZED = httpStatus.UNAUTHORIZED;
let apikey = this.query.apikey || this.throw(UNAUTHORIZED, 'Not authorized');
let user = yield apikeyCache.find(apikey);
if (! user) {
this.throw(UNAUTHORIZED, 'Not authorized');
}
this.reqctx = {
user: user
};
}
yield next;
};
};
| // apikey module validates the apikey argument used in the call. It
// caches the list of users to make lookups faster.
module.exports = function(users) {
'use strict';
let apikeyCache = require('./apikey-cache')(users);
let httpStatus = require('http-status');
// whiteList contains paths that don't require
// a valid apikey.
let whiteList = {
"/login": true
};
// validateAPIKey Looks up the apikey. If none is specified, or a
// bad key is passed then abort the calls and send back an 401.
return function *validateAPIKey(next) {
if (!(this.path in whiteList)) {
let UNAUTHORIZED = httpStatus.UNAUTHORIZED;
let apikey = this.query.apikey || this.throw(UNAUTHORIZED, 'Not authorized');
let user = yield apikeyCache.find(apikey);
if (! user) {
this.throw(UNAUTHORIZED, 'Not authorized');
}
this.reqctx = {
user: user
};
}
yield next;
};
};
| Remove console statement. Cleanup whitelist since socket.io paths will never been seen in route mount point. | Remove console statement. Cleanup whitelist since socket.io paths will never been seen in route mount point.
| JavaScript | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org | ---
+++
@@ -8,9 +8,7 @@
// whiteList contains paths that don't require
// a valid apikey.
let whiteList = {
- "/login": true,
- "/socket.io/socket.io.js": true,
- "/socket.io/": true
+ "/login": true
};
// validateAPIKey Looks up the apikey. If none is specified, or a
// bad key is passed then abort the calls and send back an 401. |
0222a20e870c475b0d3c979ad3d09d0c0ea69706 | lib/assets/javascripts/dashboard/data/authenticated-user-model.js | lib/assets/javascripts/dashboard/data/authenticated-user-model.js | var Backbone = require('backbone');
module.exports = Backbone.Model.extend({
defaults: {
username: '',
avatar_url: ''
},
url: function () {
return '//' + this.getHost() + '/api/v3/me';
},
getHost: function () {
var currentHost = window.location.host;
return this.get('host') ? this.get('host') : currentHost;
}
});
| var Backbone = require('backbone');
module.exports = Backbone.Model.extend({
defaults: {
username: '',
avatar_url: ''
},
url: function () {
return `//${this.getHost()}/api/v1/get_authenticated_users`;
},
getHost: function () {
var currentHost = window.location.host;
return this.get('host') ? this.get('host') : currentHost;
}
});
| Change AuthenticatedUser URL to query /v1/get_authenticated_users instead of /v3/me | Change AuthenticatedUser URL to query /v1/get_authenticated_users instead of /v3/me
| JavaScript | bsd-3-clause | CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb | ---
+++
@@ -7,7 +7,7 @@
},
url: function () {
- return '//' + this.getHost() + '/api/v3/me';
+ return `//${this.getHost()}/api/v1/get_authenticated_users`;
},
getHost: function () { |
a939f2794cac08ee94baf53c3fe5587b3f122725 | rollup.config.js | rollup.config.js | /**
* NOTE: This file must only use node v0.12 features + ES modules.
*/
import babel from 'rollup-plugin-babel';
import json from 'rollup-plugin-json';
import babelrc from 'babelrc-rollup';
const pkg = require('./package.json');
const external = Object.keys(pkg.dependencies).concat(['path', 'fs']);
export default {
entry: 'src/index.js',
plugins: [
json(),
babel(babelrc())
],
external: external,
targets: [
{
format: 'cjs',
dest: pkg['main']
},
{
format: 'es6',
dest: pkg['jsnext:main']
}
]
};
| /**
* NOTE: This file must only use node v0.12 features + ES modules.
*/
import babel from 'rollup-plugin-babel';
import json from 'rollup-plugin-json';
import babelrc from 'babelrc-rollup';
var pkg = require('./package.json');
var external = Object.keys(pkg.dependencies).concat(['path', 'fs']);
export default {
entry: 'src/index.js',
plugins: [
json(),
babel(babelrc())
],
external: external,
targets: [
{
format: 'cjs',
dest: pkg['main']
},
{
format: 'es6',
dest: pkg['jsnext:main']
}
]
};
| Use `var` instead of `const` for node 0.12 support. | Use `var` instead of `const` for node 0.12 support.
| JavaScript | mit | alangpierce/decaffeinate,decaffeinate/decaffeinate,alangpierce/decaffeinate,eventualbuddha/decaffeinate,decaffeinate/decaffeinate,alangpierce/decaffeinate,eventualbuddha/decaffeinate | ---
+++
@@ -6,8 +6,8 @@
import json from 'rollup-plugin-json';
import babelrc from 'babelrc-rollup';
-const pkg = require('./package.json');
-const external = Object.keys(pkg.dependencies).concat(['path', 'fs']);
+var pkg = require('./package.json');
+var external = Object.keys(pkg.dependencies).concat(['path', 'fs']);
export default {
entry: 'src/index.js', |
df4079541ec0ca698bbabedf176b164f25833551 | rollup.config.js | rollup.config.js | import commonjs from 'rollup-plugin-commonjs';
import babel from 'rollup-plugin-babel';
import uglify from 'rollup-plugin-uglify';
import replace from 'rollup-plugin-replace';
import resolve from 'rollup-plugin-node-resolve';
const env = process.env.NODE_ENV;
const config = {
output: {
name: 'react-uncontrolled-form',
format: 'umd',
globals: {react: 'React'}
},
external: ['react'],
plugins: [
resolve({jsnext: true}),
commonjs({include: 'node_modules/**'}),
babel({exclude: 'node_modules/**'}),
replace({'process.env.NODE_ENV': JSON.stringify(env)})
]
};
if (env === 'production') {
config.plugins.push(
uglify({
compress: {
pure_getters: true,
unsafe: true,
unsafe_proto: true,
passes: 2,
}
})
);
}
export default config;
| import commonjs from 'rollup-plugin-commonjs';
import babel from 'rollup-plugin-babel';
import uglify from 'rollup-plugin-uglify';
import replace from 'rollup-plugin-replace';
import resolve from 'rollup-plugin-node-resolve';
const env = process.env.NODE_ENV;
const config = {
output: {
name: 'react-uncontrolled-form',
format: 'umd',
globals: {react: 'React'}
},
external: ['react'],
plugins: [
resolve({jsnext: true}),
commonjs({include: 'node_modules/**'}),
babel({exclude: 'node_modules/**'}),
replace({'process.env.NODE_ENV': JSON.stringify(env)})
]
};
if (env === 'production') {
config.plugins.push(
uglify({
compress: {
pure_getters: true,
unsafe: true,
unsafe_proto: true
}
})
);
}
export default config;
| Remove unnecessary uglify `passes` property | Remove unnecessary uglify `passes` property | JavaScript | mit | ericvaladas/formwood | ---
+++
@@ -26,8 +26,7 @@
compress: {
pure_getters: true,
unsafe: true,
- unsafe_proto: true,
- passes: 2,
+ unsafe_proto: true
}
})
); |
cc6731b13b26a56aa705a8835605009f3e11f36c | routes/signup.js | routes/signup.js | var bcrypt = require('bcrypt');
var crypto = require('crypto');
var passport = require('passport');
var request = require('request');
var SALT = process.env.SALT;
var SIGNUP_URL = process.env.LANDLINE_API + '/teams';
module.exports = function(router) {
router.get('/signup', function(req, res) {
res.render('signup', { title: 'Landline | Signup' });
});
router.post('/signup', function(req, res) {
if (!req.body.email || !req.body.password || !req.body.name || !req.body.url) {
return res.render('signup', {
title: 'Landline | Signup',
error: 'All fields are required'
});
}
var password = req.body.password;
req.body.name = req.body.name.toLowerCase();
req.body.password = bcrypt.hashSync(password, SALT);
req.body.secret = crypto.randomBytes(48).toString('hex');
request.post({
url: SIGNUP_URL,
json: true,
body: req.body
}, function(err, response) {
if (err) {
return res.render('signup', {
title: 'Landline | Signup',
error: err.message
});
}
req.session.teamName = req.body.name;
req.session.jwt = response.body.token;
passport.authenticate('local')(req, res, function () {
res.redirect('/settings');
});
});
});
};
| var bcrypt = require('bcrypt');
var crypto = require('crypto');
var passport = require('passport');
var request = require('request');
var SALT = process.env.SALT;
var SIGNUP_URL = process.env.LANDLINE_API + '/teams';
module.exports = function(router) {
router.get('/signup', function(req, res) {
res.render('signup', { title: 'Landline | Signup' });
});
router.post('/signup', function(req, res) {
if (!req.body.email || !req.body.password || !req.body.name || !req.body.url) {
return res.render('signup', {
title: 'Landline | Signup',
error: 'All fields are required'
});
}
var password = req.body.password;
req.body.name = req.body.name.toLowerCase();
req.body.password = bcrypt.hashSync(password, SALT);
req.body.secret = crypto.randomBytes(24).toString('hex');
request.post({
url: SIGNUP_URL,
json: true,
body: req.body
}, function(err, response) {
if (err) {
return res.render('signup', {
title: 'Landline | Signup',
error: err.message
});
}
req.session.teamName = req.body.name;
req.session.jwt = response.body.token;
passport.authenticate('local')(req, res, function () {
res.redirect('/settings');
});
});
});
};
| Make the initial shared secret less obnoxiously long | Make the initial shared secret less obnoxiously long
| JavaScript | agpl-3.0 | asm-products/landline.io,asm-products/landline.io | ---
+++
@@ -23,7 +23,7 @@
req.body.name = req.body.name.toLowerCase();
req.body.password = bcrypt.hashSync(password, SALT);
- req.body.secret = crypto.randomBytes(48).toString('hex');
+ req.body.secret = crypto.randomBytes(24).toString('hex');
request.post({
url: SIGNUP_URL, |
80e664a171286279828e2bb62781a8d5b3c8e881 | server/config.js | server/config.js | /* eslint-disable no-process-env */
export const NODE_ENV = process.env.NODE_ENV || 'development';
export const isDevelopment = () => NODE_ENV === 'development';
export const isProduction = () => NODE_ENV === 'production';
export const PORT = process.env.PORT || 3000;
| /* eslint-disable no-process-env */
export const NODE_ENV = process.env.NODE_ENV || 'development';
export const isDevelopment = () => NODE_ENV === 'development';
export const isProduction = () => NODE_ENV === 'production';
export const PORT = process.env.PORT || 3010;
| Update server to be from port 3010 | Update server to be from port 3010
| JavaScript | mit | golmansax/my-site-in-express,golmansax/my-site-in-express | ---
+++
@@ -4,4 +4,4 @@
export const isDevelopment = () => NODE_ENV === 'development';
export const isProduction = () => NODE_ENV === 'production';
-export const PORT = process.env.PORT || 3000;
+export const PORT = process.env.PORT || 3010; |
3b07035c1790c787899044c44c89b84e048deadd | server/server.js | server/server.js | var assert = require('assert');
var config = require('config');
var express = require('express');
var mongoose = require('mongoose');
var db = mongoose.connection;
var locationSchema = new mongoose.Schema({
'category': String,
'location': {
'latitude': Number,
'longitude': Number
}
});
var Location = mongoose.model('Location', locationSchema);
mongoose.connect(config.get('mongo').url);
var app = express();
// For debugging in development
app.set('json spaces', 2);
app.get('/', function(req, res) {
res.json({});
});
app.get('/locations', function(req, res) {
Location.find(function(_err, locations) {
return res.json(locations);
});
});
var server = app.listen(8080, function() {
console.log('Server up');
});
| var assert = require('assert');
var config = require('config');
var express = require('express');
var mongoose = require('mongoose');
var db = mongoose.connection;
var locationSchema = new mongoose.Schema({
'category': String,
'location': {
'latitude': Number,
'longitude': Number
}
});
var Location = mongoose.model('Location', locationSchema);
mongoose.connect(config.get('mongo').url);
var app = express();
// For debugging in development
app.set('json spaces', 2);
app.get('/', function(req, res) {
res.json({});
});
app.get('/locations', function(req, res) {
Location.find({'category': req.query.category}, function(_err, locations) {
return res.json(locations);
});
});
var server = app.listen(8080, function() {
console.log('Server up');
});
| Add filtering /locations by category | Add filtering /locations by category
| JavaScript | mit | volontario/volontario-server | ---
+++
@@ -27,7 +27,7 @@
});
app.get('/locations', function(req, res) {
- Location.find(function(_err, locations) {
+ Location.find({'category': req.query.category}, function(_err, locations) {
return res.json(locations);
});
}); |
124e478cf6849a523910e2bd58d98b8d645bcd43 | src/index.js | src/index.js | #!/usr/bin/env node --harmony
var inquirer = require("inquirer");
var makeLicense = require("./make-license.js")
console.log("make-license");
var questions = [
{
type: "list",
name: "license",
message: "Choose a License",
choices: [ "MIT", "ISC", "BSD 3", "UNLICENSE", "NO LICENSE" ]
}
];
inquirer.prompt(questions, function( answers ) {
makeLicense(answers);
});
| #!/usr/bin/env node --harmony
var inquirer = require("inquirer");
var makeLicense = require("./make-license.js")
console.log("make-license");
var questions = [
{
type: "list",
name: "license",
message: "Choose a License",
choices: [ "MIT", "ISC", "BSD 2", "BSD 3", "UNLICENSE", "NO LICENSE" ]
}
];
inquirer.prompt(questions, function( answers ) {
makeLicense(answers);
});
| Add bsd 2 to menu | Add bsd 2 to menu | JavaScript | mit | accraze/make-license,accraze/make-license | ---
+++
@@ -11,7 +11,7 @@
type: "list",
name: "license",
message: "Choose a License",
- choices: [ "MIT", "ISC", "BSD 3", "UNLICENSE", "NO LICENSE" ]
+ choices: [ "MIT", "ISC", "BSD 2", "BSD 3", "UNLICENSE", "NO LICENSE" ]
}
];
|
e2ce6b77eabc0cfabe06e443298734e8629ad8c2 | src/index.js | src/index.js | define([
"text!src/welcome.md"
], function(welcomeMessage) {
var commands = codebox.require("core/commands");
var dialogs = codebox.require("utils/dialogs");
var File = codebox.require("models/file");
// About dialog
commands.register({
id: "about.show",
title: "Application: About",
shortcuts: [
"mod+shift+a"
],
run: function() {
return dialogs.alert("About Codebox");
}
});
// Welcome message
commands.register({
id: "about.welcome",
title: "Application: Welcome",
run: function() {
return commands.run("file.open", {
file: File.buffer("welcome.md", welcomeMessage)
})
}
});
});a | define([
"text!src/welcome.md"
], function(welcomeMessage) {
var commands = codebox.require("core/commands");
var dialogs = codebox.require("utils/dialogs");
var File = codebox.require("models/file");
// About dialog
commands.register({
id: "about.show",
title: "Application: About",
run: function() {
return dialogs.alert("About Codebox");
}
});
// Welcome message
commands.register({
id: "about.welcome",
title: "Application: Welcome",
run: function() {
return commands.run("file.open", {
file: File.buffer("welcome.md", welcomeMessage)
})
}
});
});a | Remove shortcut for about dialog | Remove shortcut for about dialog
| JavaScript | apache-2.0 | etopian/codebox-package-about,etopian/codebox-package-about,CodeboxIDE/package-about,CodeboxIDE/package-about | ---
+++
@@ -9,9 +9,6 @@
commands.register({
id: "about.show",
title: "Application: About",
- shortcuts: [
- "mod+shift+a"
- ],
run: function() {
return dialogs.alert("About Codebox");
} |
22bab20dd6ef60c7a372257c41d8a026c73b477a | src/index.js | src/index.js | /* @flow */
import './vendor';
import ReactDOM from 'react-dom';
import routes from './routes';
setTimeout(() => {
ReactDOM.render(routes, document.querySelector('#webedit'));
}, 500);
| /* @flow */
import './vendor';
import ReactDOM from 'react-dom';
import routes from './routes';
document.addEventListener('DOMContentLoaded', () => {
ReactDOM.render(routes, document.querySelector('#webedit'));
});
| Use a dom ready event instead of timeout speculations | Use a dom ready event instead of timeout speculations
| JavaScript | mit | blinkenrocket/webedit-react,blinkenrocket/webedit-react | ---
+++
@@ -3,6 +3,6 @@
import ReactDOM from 'react-dom';
import routes from './routes';
-setTimeout(() => {
- ReactDOM.render(routes, document.querySelector('#webedit'));
-}, 500);
+document.addEventListener('DOMContentLoaded', () => {
+ ReactDOM.render(routes, document.querySelector('#webedit'));
+}); |
f3f41884b55ed4b039f30b1604c6d69be2f6c739 | src/index.js | src/index.js | import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import YTSearch from 'youtube-api-search';
import SearchBar from './components/SearchBar';
import VideoList from './components/VideoList';
const YT_API = 'AIzaSyDqL_re6cE8YhtNr_O7GvX1SX3aQo1clyg';
class App extends Component {
constructor(props) {
super(props);
this.state = { videos: [] };
YTSearch({ key: YT_API, term: 'coc'}, (videos) => {
this.setState({ videos });
});
}
render() {
return (
<div>
<SearchBar />
<VideoList videos={this.state.videos} />
</div>
);
}
}
ReactDOM.render(<App />, document.querySelector('.container'));
| import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import YTSearch from 'youtube-api-search';
import SearchBar from './components/SearchBar';
import VideoList from './components/VideoList';
const YT_API = 'AIzaSyDqL_re6cE8YhtNr_O7GvX1SX3aQo1clyg';
class App extends Component {
constructor(props) {
super(props);
this.state = { videos: undefined };
YTSearch({ key: YT_API, term: 'coc'}, (videos) => {
this.setState({ videos });
});
}
render() {
return (
<div>
<SearchBar />
<VideoList videos={this.state.videos} />
</div>
);
}
}
ReactDOM.render(<App />, document.querySelector('.container'));
| Set state.video value to undefined | Set state.video value to undefined
| JavaScript | mit | mimukit/react-youtube-app,mimukit/react-youtube-app | ---
+++
@@ -13,7 +13,7 @@
constructor(props) {
super(props);
- this.state = { videos: [] };
+ this.state = { videos: undefined };
YTSearch({ key: YT_API, term: 'coc'}, (videos) => {
this.setState({ videos }); |
aabdea65e3187b6b267896464b86333dcc3233d5 | src/index.js | src/index.js | import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Route } from 'react-router-dom';
import './styles/index.css';
import Background from './components/Background';
import Footer from './components/Footer';
import Header from './components/Header';
import ScrollToTop from './components/ScrollToTop';
import Home from './scenes/Home';
import Store from './scenes/Store';
import registerServiceWorker from './registerServiceWorker';
import './i18n';
if (process.env.NODE_ENV === 'production') {
window.Raven
.config('https://0ddfcefcf922465488c2dde443f9c9d5@sentry.io/230876')
.install();
}
ReactDOM.render(
<BrowserRouter>
<ScrollToTop>
<Background />
<Header />
<Route exact path="/" component={Home} />
<Route path="/store" component={Store} />
<Footer />
</ScrollToTop>
</BrowserRouter>,
document.getElementById('root'),
);
registerServiceWorker();
| import React from 'react';
import ReactDOM from 'react-dom';
import {
BrowserRouter as Router,
Redirect,
Route,
Switch,
} from 'react-router-dom';
import './styles/index.css';
import Background from './components/Background';
import Footer from './components/Footer';
import Header from './components/Header';
import ScrollToTop from './components/ScrollToTop';
import Home from './scenes/Home';
import Store from './scenes/Store';
import registerServiceWorker from './registerServiceWorker';
import './i18n';
if (process.env.NODE_ENV === 'production') {
window.Raven
.config('https://0ddfcefcf922465488c2dde443f9c9d5@sentry.io/230876')
.install();
}
ReactDOM.render(
<Router>
<ScrollToTop>
<Background />
<Header />
<Switch>
<Route exact path="/" component={Home} />
<Route path="/store" component={Store} />
<Redirect from="*" to="/" />
</Switch>
<Footer />
</ScrollToTop>
</Router>,
document.getElementById('root'),
);
registerServiceWorker();
| Add Switch and Redirect for Router | Add Switch and Redirect for Router
| JavaScript | mit | ELTCOIN/website | ---
+++
@@ -1,6 +1,11 @@
import React from 'react';
import ReactDOM from 'react-dom';
-import { BrowserRouter, Route } from 'react-router-dom';
+import {
+ BrowserRouter as Router,
+ Redirect,
+ Route,
+ Switch,
+} from 'react-router-dom';
import './styles/index.css';
import Background from './components/Background';
import Footer from './components/Footer';
@@ -19,15 +24,18 @@
}
ReactDOM.render(
- <BrowserRouter>
+ <Router>
<ScrollToTop>
<Background />
<Header />
- <Route exact path="/" component={Home} />
- <Route path="/store" component={Store} />
+ <Switch>
+ <Route exact path="/" component={Home} />
+ <Route path="/store" component={Store} />
+ <Redirect from="*" to="/" />
+ </Switch>
<Footer />
</ScrollToTop>
- </BrowserRouter>,
+ </Router>,
document.getElementById('root'),
);
|
ee50f51a89fc140102d3b6d576762d453443299e | src/index.js | src/index.js | // Return Promise
const imageMerge = (sources = []) => new Promise(resolve => {
// Load sources
const images = sources.map(source => new Promise(resolve => {
const img = new Image();
img.onload = () => resolve(Object.assign({}, source, {img}));
img.src = source.src;
}));
// Create canvas
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// When sources have loaded
Promise.all(images)
.then(images => {
// Set canvas dimensions
canvas.width = Math.max(...images.map(image => image.img.width));
canvas.height = Math.max(...images.map(image => image.img.height));
// Draw images to canvas
images.forEach(image => ctx.drawImage(image.img, image.x || 0, image.y || 0));
// Resolve data uri
resolve(canvas.toDataURL());
});
});
module.exports = imageMerge;
| // Return Promise
const imageMerge = (sources = []) => new Promise(resolve => {
// Load sources
const images = sources.map(source => new Promise(resolve => {
// Convert strings to objects
if (typeof source === 'string') {
source = {src: source};
}
// Resolve source and img when loaded
const img = new Image();
img.onload = () => resolve(Object.assign({}, source, {img}));
img.src = source.src;
}));
// Create canvas
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// When sources have loaded
Promise.all(images)
.then(images => {
// Set canvas dimensions
canvas.width = Math.max(...images.map(image => image.img.width));
canvas.height = Math.max(...images.map(image => image.img.height));
// Draw images to canvas
images.forEach(image => ctx.drawImage(image.img, image.x || 0, image.y || 0));
// Resolve data uri
resolve(canvas.toDataURL());
});
});
module.exports = imageMerge;
| Allow array of src strings to be passed in | Allow array of src strings to be passed in
| JavaScript | mit | lukechilds/merge-images | ---
+++
@@ -2,6 +2,12 @@
const imageMerge = (sources = []) => new Promise(resolve => {
// Load sources
const images = sources.map(source => new Promise(resolve => {
+ // Convert strings to objects
+ if (typeof source === 'string') {
+ source = {src: source};
+ }
+
+ // Resolve source and img when loaded
const img = new Image();
img.onload = () => resolve(Object.assign({}, source, {img}));
img.src = source.src; |
5e86a4ba2ebe27b0971d8cb1b569c27dbe3fba37 | src/index.js | src/index.js | import { certificates, certificatesAsync } from './certificates';
import { sign, signAsync } from './sign';
import {
paramsForDetachedSignature,
paramsForDetachedSignatureAsync,
} from './params_for_detached_signature';
import { digestValue, digestValueAsync } from './digest_value';
import { cadesplugin } from './constants';
console.log('----', cadesplugin);
/**
* @class
* @name CryptoProProvider
* @description Module provide methods for signing requests with Crypto Pro
* @author Vitaly Mashanov <vvmashanov@yandex.ru>
*/
/**
* @function
* @name isAsync
* @description Checking, which method used by browser (Async or NPAPI)
* @return {boolean}
*/
const isAsync = () => (cadesplugin.CreateObjectAsync || false);
export default {
certificates: isAsync() ? certificatesAsync : certificates,
sign: isAsync() ? signAsync : sign,
paramsForDetachedSignature: isAsync() ? paramsForDetachedSignatureAsync : paramsForDetachedSignature,
digestValue: isAsync() ? digestValueAsync : digestValue,
};
| import { certificates, certificatesAsync } from './certificates';
import { sign, signAsync } from './sign';
import {
paramsForDetachedSignature,
paramsForDetachedSignatureAsync,
} from './params_for_detached_signature';
import { digestValue, digestValueAsync } from './digest_value';
import { cadesplugin } from './constants';
/**
* @class
* @name CryptoProProvider
* @description Module provide methods for signing requests with Crypto Pro
* @author Vitaly Mashanov <vvmashanov@yandex.ru>
*/
/**
* @function
* @name isAsync
* @description Checking, which method used by browser (Async or NPAPI)
* @return {boolean}
*/
const isAsync = () => (cadesplugin.CreateObjectAsync || false);
export default {
certificates: isAsync() ? certificatesAsync : certificates,
sign: isAsync() ? signAsync : sign,
paramsForDetachedSignature: isAsync() ? paramsForDetachedSignatureAsync : paramsForDetachedSignature,
digestValue: isAsync() ? digestValueAsync : digestValue,
};
| Call of console was deleted | Call of console was deleted
| JavaScript | mit | VMashanov/crypto-pro-provider,VMashanov/crypto-pro-provider | ---
+++
@@ -6,8 +6,6 @@
} from './params_for_detached_signature';
import { digestValue, digestValueAsync } from './digest_value';
import { cadesplugin } from './constants';
-
-console.log('----', cadesplugin);
/**
* @class |
7d299640acbdb594561f493bd78868a5281e7e4d | app/angular/services/friend_service.js | app/angular/services/friend_service.js | 'use strict';
module.exports = function(app) {
app.service('FriendService', ['$rootScope', '$http', function($rs, $http) {
let allFriends = {};
let getAllFriends = function(emailOrUsername) {
return new Promise((resolve, reject) => {
let userData = {
emailOrUsername: emailOrUsername,
};
$http.post(`${$rs.baseUrl}/friends/all`, userData)
.then((friends) => {
allFriends.friends = friends.data;
resolve();
})
.catch((err) => {
console.log('error getting all friends');
});
});
}
let addFriend = function(friendId) {
let friendData = {
_id: friendId,
};
$http.post(`${$rs.baseUrl}/friends/add`, friendData)
.then((res) => {
console.log(res.data);
})
.catch((err) => {
console.log(err.data);
});
};
return {
getAllFriends: getAllFriends,
addFriend: addFriend,
data: {
allFriends: allFriends,
},
}
}]);
}
| 'use strict';
module.exports = function(app) {
app.service('FriendService', ['$rootScope', '$http', function($rs, $http) {
let data = {
allFriends: {},
};
let getAllFriends = function(emailOrUsername) {
let userData = {
emailOrUsername: emailOrUsername,
};
return $http.post(`${$rs.baseUrl}/friends/all`, userData)
.then((friends) => {
data.allFriends.friends = friends.data;
})
.catch((err) => {
console.log('error getting all friends');
});
}
let addFriend = function(friendId) {
let friendData = {
_id: friendId,
};
return $http.post(`${$rs.baseUrl}/friends/add`, friendData)
.then((res) => {
console.log(res.data);
})
.catch((err) => {
console.log(err.data);
});
};
return {
getAllFriends: getAllFriends,
addFriend: addFriend,
data: data,
}
}]);
}
| Remove promises returning data from Friend Service. Unused. | Remove promises returning data from Friend Service. Unused.
| JavaScript | mit | sendjmoon/GolfFourFriends,sendjmoon/GolfFourFriends | ---
+++
@@ -2,29 +2,29 @@
module.exports = function(app) {
app.service('FriendService', ['$rootScope', '$http', function($rs, $http) {
- let allFriends = {};
+
+ let data = {
+ allFriends: {},
+ };
let getAllFriends = function(emailOrUsername) {
- return new Promise((resolve, reject) => {
- let userData = {
- emailOrUsername: emailOrUsername,
- };
- $http.post(`${$rs.baseUrl}/friends/all`, userData)
- .then((friends) => {
- allFriends.friends = friends.data;
- resolve();
- })
- .catch((err) => {
- console.log('error getting all friends');
- });
- });
+ let userData = {
+ emailOrUsername: emailOrUsername,
+ };
+ return $http.post(`${$rs.baseUrl}/friends/all`, userData)
+ .then((friends) => {
+ data.allFriends.friends = friends.data;
+ })
+ .catch((err) => {
+ console.log('error getting all friends');
+ });
}
let addFriend = function(friendId) {
let friendData = {
_id: friendId,
};
- $http.post(`${$rs.baseUrl}/friends/add`, friendData)
+ return $http.post(`${$rs.baseUrl}/friends/add`, friendData)
.then((res) => {
console.log(res.data);
})
@@ -36,9 +36,7 @@
return {
getAllFriends: getAllFriends,
addFriend: addFriend,
- data: {
- allFriends: allFriends,
- },
+ data: data,
}
}]);
} |
7059a9d40f27b2ff3bd1acb0d9b3a7a0e72bdd8a | examples/main-page/main.js | examples/main-page/main.js | window.onload = function() {
d3.json("../examples/data/gitstats.json", function(data) {
data.forEach(function(d) {
d.date = new Date(d.date);
d.name = d.name === "ashwinraman9" ? "aramaswamy" : d.name;
});
var dataset = {data: data, metadata: {}};
var commitSVG = d3.select("#intro-chart");
sizeSVG(commitSVG);
commitChart(commitSVG, dataset);
var scatterFullSVG = d3.select("#scatter-full");
sizeSVG(scatterFullSVG);
scatterFull(scatterFullSVG, dataset);
var lineSVG = d3.select("#line-chart");
sizeSVG(lineSVG);
lineChart(lineSVG, dataset);
});
}
function sizeSVG(svg) {
var width = svg.node().clientWidth;
var height = Math.min(width*.75, 600);
svg.attr("height", height);
}
| window.onload = function() {
d3.json("examples/data/gitstats.json", function(data) {
data.forEach(function(d) {
d.date = new Date(d.date);
d.name = d.name === "ashwinraman9" ? "aramaswamy" : d.name;
});
var dataset = {data: data, metadata: {}};
var commitSVG = d3.select("#intro-chart");
sizeSVG(commitSVG);
commitChart(commitSVG, dataset);
var scatterFullSVG = d3.select("#scatter-full");
sizeSVG(scatterFullSVG);
scatterFull(scatterFullSVG, dataset);
var lineSVG = d3.select("#line-chart");
sizeSVG(lineSVG);
lineChart(lineSVG, dataset);
});
}
function sizeSVG(svg) {
var width = svg.node().clientWidth;
var height = Math.min(width*.75, 600);
svg.attr("height", height);
}
| Fix it gau! oh godgp | Fix it gau! oh godgp
| JavaScript | mit | gdseller/plottable,alyssaq/plottable,jacqt/plottable,softwords/plottable,palantir/plottable,iobeam/plottable,palantir/plottable,NextTuesday/plottable,palantir/plottable,gdseller/plottable,iobeam/plottable,danmane/plottable,softwords/plottable,jacqt/plottable,jacqt/plottable,danmane/plottable,onaio/plottable,palantir/plottable,onaio/plottable,RobertoMalatesta/plottable,onaio/plottable,RobertoMalatesta/plottable,NextTuesday/plottable,NextTuesday/plottable,gdseller/plottable,softwords/plottable,danmane/plottable,alyssaq/plottable,RobertoMalatesta/plottable,alyssaq/plottable,iobeam/plottable | ---
+++
@@ -1,5 +1,5 @@
window.onload = function() {
- d3.json("../examples/data/gitstats.json", function(data) {
+ d3.json("examples/data/gitstats.json", function(data) {
data.forEach(function(d) {
d.date = new Date(d.date);
d.name = d.name === "ashwinraman9" ? "aramaswamy" : d.name; |
6e712d8ded370fea4b7f1a8df6d896a3ae4472c4 | src/authentication/sessions.js | src/authentication/sessions.js | 'use strict';
export default {
setup,
};
/**
* Module dependencies.
*/
import SequelizeStore from 'koa-generic-session-sequelize';
// import convert from 'koa-convert';
import session from 'koa-generic-session';
/**
* Prepares session middleware and methods without attaching to the stack
*
* @param {Object} settings
* @param {Object} database
* @param {Object} [store] Store for `koa-generic-sessions`. Uses the database if a store is not provided
* @return {Object}
*/
function setup(settings, database, store) {
return {
// session middleware
session: session({
key: 'identityDesk.sid',
store: store || new SequelizeStore(database),
}),
sessionMethods: function(ctx, next) {
// set the secret keys for Keygrip
ctx.app.keys = settings.session.keys;
// attach session methods
ctx.identityDesk = {
get(key) {
if (ctx.session && ctx.session.identityDesk && ctx.session.identityDesk[key] !== undefined) {
return ctx.session.identityDesk[key];
} else {
return undefined;
}
},
set(values) {
ctx.session = ctx.session || { identityDesk: { values } };
ctx.session.identityDesk = ctx.session.identityDesk || { values };
Object.assign(ctx.session.identityDesk, values);
},
};
return next();
},
};
} | 'use strict';
export default {
setup,
};
/**
* Module dependencies.
*/
import SequelizeStore from 'koa-generic-session-sequelize';
// import convert from 'koa-convert';
import session from 'koa-generic-session';
/**
* Prepares session middleware and methods without attaching to the stack
*
* @param {Object} settings
* @param {Object} database
* @param {Object} [store] Store for `koa-generic-sessions`. Uses the database if a store is not provided
* @return {Object}
*/
function setup(settings, database, store) {
return {
// session middleware
session: session({
key: 'identityDesk.sid',
store: store || new SequelizeStore(database),
}),
sessionMethods: function(ctx, next) {
// set the secret keys for Keygrip
ctx.app.keys = settings.session.keys;
// attach session methods
ctx.identityDesk = {
get(key) {
if (ctx.session && ctx.session.identityDesk && ctx.session.identityDesk[key] !== undefined) {
return ctx.session.identityDesk[key];
} else {
return undefined;
}
},
set(values) {
ctx.session = ctx.session || { identityDesk: values };
ctx.session.identityDesk = ctx.session.identityDesk || values;
Object.assign(ctx.session.identityDesk, values);
},
};
return next();
},
};
} | Fix bug of session data being stored with an extra `values` key | Fix bug of session data being stored with an extra `values` key
| JavaScript | mit | HiFaraz/identity-desk | ---
+++
@@ -41,8 +41,8 @@
}
},
set(values) {
- ctx.session = ctx.session || { identityDesk: { values } };
- ctx.session.identityDesk = ctx.session.identityDesk || { values };
+ ctx.session = ctx.session || { identityDesk: values };
+ ctx.session.identityDesk = ctx.session.identityDesk || values;
Object.assign(ctx.session.identityDesk, values);
},
}; |
db8294dc10fb9240bacbdc65e724d884d81b74c7 | src/components/GlobalSearch.js | src/components/GlobalSearch.js | import React, { Component, findDOMNode } from 'react';
import styles from './GlobalSearch.scss';
export default class GlobalSearch extends Component {
render () {
return (
<input
ref='searchBox'
placeholder={this.props.placeholder}
className={styles['gs-input']}
onChange={this.props.onChange}
onKeyUp={this.props.onKeyUp}
onFocus={this.props.onFocus}
onClick={() => {
findDOMNode(this).select();
}}
/>
);
};
};
GlobalSearch.propTypes = {
placeholder: React.PropTypes.string,
onFocus: React.PropTypes.func.isRequired,
onChange: React.PropTypes.func.isRequired,
onKeyUp: React.PropTypes.func.isRequired,
styles: React.PropTypes.object
};
| import React, { Component } from 'react';
import { findDOMNode } from 'react-dom';
import styles from './GlobalSearch.scss';
export default class GlobalSearch extends Component {
render () {
return (
<input
ref='searchBox'
placeholder={this.props.placeholder}
className={styles['gs-input']}
onChange={this.props.onChange}
onKeyUp={this.props.onKeyUp}
onFocus={this.props.onFocus}
onClick={() => {
findDOMNode(this).select();
}}
/>
);
};
};
GlobalSearch.propTypes = {
placeholder: React.PropTypes.string,
onFocus: React.PropTypes.func.isRequired,
onChange: React.PropTypes.func.isRequired,
onKeyUp: React.PropTypes.func.isRequired,
styles: React.PropTypes.object
};
| Swap deprecated findDOMNode to the version from the react-dom module. | Swap deprecated findDOMNode to the version from the react-dom module.
| JavaScript | bsd-3-clause | FiviumAustralia/RNSH-Pilot,FiviumAustralia/RNSH-Pilot,FiviumAustralia/RNSH-Pilot | ---
+++
@@ -1,4 +1,5 @@
-import React, { Component, findDOMNode } from 'react';
+import React, { Component } from 'react';
+import { findDOMNode } from 'react-dom';
import styles from './GlobalSearch.scss';
export default class GlobalSearch extends Component { |
13351bc9c4dc36a27251ed9147ab35b7c771fce5 | packages/shared/lib/keys/keyImport.js | packages/shared/lib/keys/keyImport.js | import { getKeys } from 'pmcrypto';
import { readFileAsString } from '../helpers/file';
const PRIVATE_KEY_EXPR = /-----BEGIN PGP PRIVATE KEY BLOCK-----(?:(?!-----)[\s\S])*-----END PGP PRIVATE KEY BLOCK-----/g;
export const parseArmoredKeys = (fileString) => {
return fileString.match(PRIVATE_KEY_EXPR) || [];
};
export const parseKeys = (filesAsStrings = []) => {
const armoredKeys = parseArmoredKeys(filesAsStrings.join('\n'));
if (!armoredKeys.length) {
return [];
}
return Promise.all(armoredKeys.map(async (armoredPrivateKey) => {
try {
const [key] = await getKeys(armoredPrivateKey);
return key;
} catch (e) {
// ignore errors
}
})).then((result) => result.filter(Boolean));
};
export const parseKeyFiles = async (files = []) => {
const filesAsStrings = await Promise.all(files.map(readFileAsString)).catch(() => []);
return parseKeys(filesAsStrings);
};
| import { getKeys } from 'pmcrypto';
import { readFileAsString } from '../helpers/file';
const PRIVATE_KEY_EXPR = /-----BEGIN PGP (PRIVATE|PUBLIC) KEY BLOCK-----(?:(?!-----)[\s\S])*-----END PGP (PRIVATE|PUBLIC) KEY BLOCK-----/g;
export const parseArmoredKeys = (fileString) => {
return fileString.match(PRIVATE_KEY_EXPR) || [];
};
export const parseKeys = (filesAsStrings = []) => {
const armoredKeys = parseArmoredKeys(filesAsStrings.join('\n'));
if (!armoredKeys.length) {
return [];
}
return Promise.all(
armoredKeys.map(async (armoredPrivateKey) => {
try {
const [key] = await getKeys(armoredPrivateKey);
return key;
} catch (e) {
// ignore errors
}
})
).then((result) => result.filter(Boolean));
};
export const parseKeyFiles = async (files = []) => {
const filesAsStrings = await Promise.all(files.map(readFileAsString)).catch(() => []);
return parseKeys(filesAsStrings);
};
| Update REGEX to accept also public keys | Update REGEX to accept also public keys
| JavaScript | mit | ProtonMail/WebClient,ProtonMail/WebClient,ProtonMail/WebClient | ---
+++
@@ -2,7 +2,7 @@
import { readFileAsString } from '../helpers/file';
-const PRIVATE_KEY_EXPR = /-----BEGIN PGP PRIVATE KEY BLOCK-----(?:(?!-----)[\s\S])*-----END PGP PRIVATE KEY BLOCK-----/g;
+const PRIVATE_KEY_EXPR = /-----BEGIN PGP (PRIVATE|PUBLIC) KEY BLOCK-----(?:(?!-----)[\s\S])*-----END PGP (PRIVATE|PUBLIC) KEY BLOCK-----/g;
export const parseArmoredKeys = (fileString) => {
return fileString.match(PRIVATE_KEY_EXPR) || [];
@@ -14,14 +14,16 @@
return [];
}
- return Promise.all(armoredKeys.map(async (armoredPrivateKey) => {
- try {
- const [key] = await getKeys(armoredPrivateKey);
- return key;
- } catch (e) {
- // ignore errors
- }
- })).then((result) => result.filter(Boolean));
+ return Promise.all(
+ armoredKeys.map(async (armoredPrivateKey) => {
+ try {
+ const [key] = await getKeys(armoredPrivateKey);
+ return key;
+ } catch (e) {
+ // ignore errors
+ }
+ })
+ ).then((result) => result.filter(Boolean));
};
export const parseKeyFiles = async (files = []) => { |
31488615c3bd0a3b9ae1399c479dee95d503273e | client/app/validators/messages.js | client/app/validators/messages.js | import Messages from 'ember-cp-validations/validators/messages';
export default Messages.extend({
blank: 'Поле не может быть пустым',
email: 'Значение должно быть адресом электронной почты',
emailNotFound: 'Адрес не найден',
notANumber: 'Значение должно быть числом',
notAnInteger: 'Значение должно быть целым числом',
positive: 'Значение должно быть положительным числом',
invalid: 'Поле заполнено неверно'
});
| import Messages from 'ember-cp-validations/validators/messages';
export default Messages.extend({
blank: 'Поле не может быть пустым',
email: 'Значение должно быть адресом электронной почты',
emailNotFound: 'Адрес не найден',
notANumber: 'Значение должно быть числом',
notAnInteger: 'Значение должно быть целым числом',
positive: 'Значение должно быть положительным числом',
invalid: 'Поле заполнено неверно',
url: 'Значение не является ссылкой'
});
| Add custom message for invalid url | Add custom message for invalid url
| JavaScript | mit | yandex-shri-minsk-2016/yummy-time,yandex-shri-minsk-2016/yummy-time,yandex-shri-minsk-2016/yummy-time | ---
+++
@@ -7,5 +7,6 @@
notANumber: 'Значение должно быть числом',
notAnInteger: 'Значение должно быть целым числом',
positive: 'Значение должно быть положительным числом',
- invalid: 'Поле заполнено неверно'
+ invalid: 'Поле заполнено неверно',
+ url: 'Значение не является ссылкой'
}); |
fa117ab8cfa2a82fd20ee9312a8719d604dc010b | test/util/string.js | test/util/string.js | var assert = require('chai').assert;
var string = require('../../util/string');
describe('util/string', function () {
describe('#isEmpty', function () {
it('should return true', function () {
assert(true, string.isEmpty());
assert(true, string.isEmpty(''));
assert(true, string.isEmpty(' '));
});
it('should return false', function () {
assert.isFalse(string.isEmpty('myString'));
});
});
}); | var assert = require('chai').assert;
var string = require('../../util/string');
describe('util/string', function () {
describe('#isEmpty', function () {
it('should return true', function () {
assert.isTrue(string.isEmpty());
assert.isTrue(string.isEmpty(''));
assert.isTrue(string.isEmpty(' '));
});
it('should return false', function () {
assert.isFalse(string.isEmpty('myString'));
});
});
}); | Change assert style: use method isTrue | Change assert style: use method isTrue
| JavaScript | mit | pmu-tech/grunt-erb | ---
+++
@@ -4,9 +4,9 @@
describe('util/string', function () {
describe('#isEmpty', function () {
it('should return true', function () {
- assert(true, string.isEmpty());
- assert(true, string.isEmpty(''));
- assert(true, string.isEmpty(' '));
+ assert.isTrue(string.isEmpty());
+ assert.isTrue(string.isEmpty(''));
+ assert.isTrue(string.isEmpty(' '));
});
it('should return false', function () {
assert.isFalse(string.isEmpty('myString')); |
69d8e29ba6c802699c38bec0c9ec65ccdbfa0d95 | src/client/StatusBar.js | src/client/StatusBar.js | import React, {Component} from 'react';
import Mousetrap from 'mousetrap';
class StatusBar extends Component {
componentDidMount() {
Mousetrap.bind(['alt+a'], this.toggleSearchAllWindows);
}
render() {
return (
/* jshint ignore:start */
<label className='status'>
<input type='checkbox' checked={this.props.searchAllWindows}
onChange={this.onChange} />
<span>Show tabs from <u>a</u>ll windows</span>
</label>
/* jshint ignore:end */
);
}
toggleSearchAllWindows() {
this.props.changeSearchAllWindows(!this.props.searchAllWindows);
}
onChange(evt) {
this.props.changeSearchAllWindows(evt.target.checked);
}
}
export default StatusBar; | import React, {Component} from 'react';
import Mousetrap from 'mousetrap';
class StatusBar extends Component {
constructor(props) {
super(props);
this.toggleSearchAllWindows = this.toggleSearchAllWindows.bind(this);
this.onChange = this.onChange.bind(this);
}
componentDidMount() {
Mousetrap.bind(['alt+a'], this.toggleSearchAllWindows);
}
render() {
return (
/* jshint ignore:start */
<label className='status'>
<input type='checkbox' checked={this.props.searchAllWindows}
onChange={this.onChange} />
<span>Show tabs from <u>a</u>ll windows</span>
</label>
/* jshint ignore:end */
);
}
toggleSearchAllWindows() {
this.props.changeSearchAllWindows(!this.props.searchAllWindows);
}
onChange(evt) {
this.props.changeSearchAllWindows(evt.target.checked);
}
}
export default StatusBar; | Fix for toggle all windows | Fix for toggle all windows
| JavaScript | mit | fewhnhouse/chrome-tab-switcher | ---
+++
@@ -3,6 +3,11 @@
class StatusBar extends Component {
+ constructor(props) {
+ super(props);
+ this.toggleSearchAllWindows = this.toggleSearchAllWindows.bind(this);
+ this.onChange = this.onChange.bind(this);
+ }
componentDidMount() {
Mousetrap.bind(['alt+a'], this.toggleSearchAllWindows);
} |
b791de38894ffa04c66a8c8c7164da1bb3cb4dc6 | src/main/resources/static/js/autocomplete-lecturer-for-subject.js | src/main/resources/static/js/autocomplete-lecturer-for-subject.js | export default class AutoCompleteSubjects {
constructor(wrapper) {
this.wrapper = wrapper;
}
initialize(selector) {
const $input = this.wrapper.find('input[type=text]');
const $realInput = this.wrapper.find('input[type=hidden]');
const jsonUrl = this.wrapper.data("url");
$input.materialize_autocomplete({
multiple: {
enable: false
},
dropdown: {
el: '.dropdown-content',
itemTemplate: '<li class="ac-item" data-id="<%= item.id %>" data-text=\'<%= item.name %>\'><a href="javascript:void(0)"><%= item.name %></a></li>',
},
getData: function (value, callback) {
const url = jsonUrl + `?filter=${value}`;
$.ajax({
url: url,
})
.then(data => {
callback(value, data);
});
},
onSelect: function (item) {
$realInput.val(item.id);
},
});
}
} | export default class AutoCompleteSubjects {
constructor(wrapper) {
this.wrapper = wrapper;
}
initialize(selector) {
const $input = this.wrapper.find('input[type=text]');
const $realInput = this.wrapper.find('input[type=hidden]');
const jsonUrl = this.wrapper.data("url");
$input.materialize_autocomplete({
multiple: {
enable: false
},
dropdown: {
el: '.dropdown-content',
itemTemplate: '<li class="ac-item" data-id="<%= item.id %>" data-text=\'<%= item.name %>\'><a href="javascript:void(0)"><%= item.name %></a></li>',
},
getData: function (value, callback) {
const url = jsonUrl + `?search=${value}`;
$.ajax({
url: url,
})
.then(data => {
callback(value, data);
});
},
onSelect: function (item) {
$realInput.val(item.id);
},
});
}
} | Rename GET parameter from ?filter to ?search | Rename GET parameter from ?filter to ?search
| JavaScript | mit | university-information-system/uis,university-information-system/uis,university-information-system/uis,university-information-system/uis | ---
+++
@@ -18,7 +18,7 @@
itemTemplate: '<li class="ac-item" data-id="<%= item.id %>" data-text=\'<%= item.name %>\'><a href="javascript:void(0)"><%= item.name %></a></li>',
},
getData: function (value, callback) {
- const url = jsonUrl + `?filter=${value}`;
+ const url = jsonUrl + `?search=${value}`;
$.ajax({
url: url, |
878b9eeb01b579bf30ab30d5d8f1e76f34aa4aee | gruntfile.js | gruntfile.js | "use strict";
/*jshint node: true*/
/*eslint-env node*/
module.exports = function (grunt) {
require("time-grunt")(grunt);
// Since the tasks are split using load-grunt-config, a global object contains the configuration
/*global configFile, configuration*/
var ConfigFile = require("./make/configFile.js");
global.configFile = new ConfigFile();
global.configuration = configFile.content;
if (configFile.isNew()) {
grunt.registerTask("default", function () {
var done = this.async(); //eslint-disable-line no-invalid-this
grunt.util.spawn({
cmd: "node",
args: ["make/config"],
opts: {
stdio: "inherit"
}
}, function (error) {
if (error) {
done();
return;
}
grunt.util.spawn({
grunt: true,
args: ["check", "jsdoc", "default"],
opts: {
stdio: "inherit"
}
}, done);
});
});
return;
}
configFile.readSourceFiles();
// Amend the configuration with internal settings
configuration.pkg = grunt.file.readJSON("./package.json");
require("load-grunt-config")(grunt);
grunt.task.loadTasks("grunt/tasks");
};
| "use strict";
/*jshint node: true*/
/*eslint-env node*/
module.exports = function (grunt) {
require("time-grunt")(grunt);
// Since the tasks are split using load-grunt-config, a global object contains the configuration
/*global configFile, configuration*/
var ConfigFile = require("./make/configFile.js");
global.configFile = new ConfigFile();
global.configuration = Object.create(configFile.content);
if (configFile.isNew()) {
grunt.registerTask("default", function () {
var done = this.async(); //eslint-disable-line no-invalid-this
grunt.util.spawn({
cmd: "node",
args: ["make/config"],
opts: {
stdio: "inherit"
}
}, function (error) {
if (error) {
done();
return;
}
grunt.util.spawn({
grunt: true,
args: ["check", "jsdoc", "default"],
opts: {
stdio: "inherit"
}
}, done);
});
});
return;
}
configFile.readSourceFiles();
// Amend the configuration with internal settings
configuration.pkg = grunt.file.readJSON("./package.json");
require("load-grunt-config")(grunt);
grunt.task.loadTasks("grunt/tasks");
};
| Secure content that must not be altered by grunt | Secure content that must not be altered by grunt
| JavaScript | mit | ArnaudBuchholz/gpf-js,ArnaudBuchholz/gpf-js | ---
+++
@@ -10,7 +10,7 @@
/*global configFile, configuration*/
var ConfigFile = require("./make/configFile.js");
global.configFile = new ConfigFile();
- global.configuration = configFile.content;
+ global.configuration = Object.create(configFile.content);
if (configFile.isNew()) {
grunt.registerTask("default", function () {
var done = this.async(); //eslint-disable-line no-invalid-this |
5d973ab69edbf2618020bab1b764838f4d17ef47 | src/plugins/configure/index.js | src/plugins/configure/index.js | const { next, hookStart, hookEnd } = require('hooter/effects')
const assignDefaults = require('./assignDefaults')
const validateConfig = require('./validateConfig')
const EVENTS_WITH_CONFIG = ['start', 'execute', 'process', 'handle', 'error']
module.exports = function* configurePlugin() {
let schema, config
function* provideConfig(...args) {
let event = this.type
if (!config && event !== 'error') {
throw new Error(
`The config must already be defined at the beginning of "${event}"`
)
}
return yield next(config, ...args)
}
yield hookEnd('schema', function* (_schema) {
schema = yield next(_schema).or(_schema)
return schema
})
yield hookStart('configure', function* (_config) {
return yield next(schema, _config)
})
yield hookStart('configure', function* (_schema, _config) {
_config = assignDefaults(_schema, _config)
return yield next(_schema, _config)
})
yield hookEnd('configure', function* (_schema, _config) {
validateConfig(_schema, _config)
config = yield next(_schema, _config).or(_config)
return config
})
for (let event of EVENTS_WITH_CONFIG) {
yield hookStart(event, provideConfig)
}
}
| const { next, hookStart, hookEnd } = require('hooter/effects')
const assignDefaults = require('./assignDefaults')
const validateConfig = require('./validateConfig')
const EVENTS_WITH_CONFIG = ['start', 'execute', 'process', 'handle', 'error']
module.exports = function* configurePlugin() {
let schema, config
function* provideConfig(...args) {
let event = this.name
if (!config && event !== 'error') {
throw new Error(
`The config must already be defined at the beginning of "${event}"`
)
}
return yield next(config, ...args)
}
yield hookEnd('schema', function* (_schema) {
schema = yield next(_schema).or(_schema)
return schema
})
yield hookStart('configure', function* (_config) {
return yield next(schema, _config)
})
yield hookStart('configure', function* (_schema, _config) {
_config = assignDefaults(_schema, _config)
return yield next(_schema, _config)
})
yield hookEnd('configure', function* (_schema, _config) {
validateConfig(_schema, _config)
config = yield next(_schema, _config).or(_config)
return config
})
for (let event of EVENTS_WITH_CONFIG) {
yield hookStart(event, provideConfig)
}
}
| Fix provideConfig() in configure using event.type instead of event.name | Fix provideConfig() in configure using event.type instead of event.name
| JavaScript | isc | alex-shnayder/comanche | ---
+++
@@ -10,7 +10,7 @@
let schema, config
function* provideConfig(...args) {
- let event = this.type
+ let event = this.name
if (!config && event !== 'error') {
throw new Error( |
59bdb85cdaa72829024108e3fc1fb71777e389f6 | persistance.js | persistance.js | const models = require('./models')
const Course = models.Course
const path = require('path')
const url = require('url')
const uri = url.format({
pathname: path.join(__dirname, 'data.db'),
protocol: 'nedb:',
slashes: true
})
const init = function(cb){
models.init(uri, function(err){
if(err){
console.log("Models initialization failed")
cb(err)
}else{
console.log("Models initialized..")
cb()
}
})
}
const saveCourse = function(course, cb){
let c = Course.create(course)
c.save().then(function(doc){
cb(null, doc._id)
}, function(err){
cb(err)
})
}
const getCourse = function(course, cb){
Course.findOne(course).then(function(doc){
cb(null, doc)
}, function(err){
cb(err)
})
}
const getCourses = function(course, cb){
Course.find(course).then(function(docs){
cb(null, docs)
}, function(err){
cb(err)
})
}
module.exports = {
init,
saveCourse,
getCourse,
getCourses
}
| const models = require('./models')
const Course = models.Course
const path = require('path')
const url = require('url')
const uri = url.format({
pathname: path.join(__dirname, 'data.db'),
protocol: 'nedb:',
slashes: true
})
const init = function(cb){
models.init(uri, function(err){
if(err){
console.log("Models initialization failed")
cb(err)
}else{
console.log("Models initialized..")
cb()
}
})
}
const saveCourse = function(course, cb){
let c = Course.create(course)
c.save().then(function(doc){
cb(null, doc._id)
}, function(err){
cb(err)
})
}
const getCourse = function(course, cb){
Course.findOne(course).then(function(doc){
cb(null, doc)
}, function(err){
cb(err)
})
}
const getCourses = function(course, cb){
Course.find(course, {sort: '-startDate'}).then(function(docs){
cb(null, docs)
}, function(err){
cb(err)
})
}
module.exports = {
init,
saveCourse,
getCourse,
getCourses
}
| Sort courses based on startDate | Sort courses based on startDate
| JavaScript | mit | nilenso/dhobi-seva-electron,nilenso/dhobi-seva-electron | ---
+++
@@ -39,7 +39,7 @@
}
const getCourses = function(course, cb){
- Course.find(course).then(function(docs){
+ Course.find(course, {sort: '-startDate'}).then(function(docs){
cb(null, docs)
}, function(err){
cb(err) |
445300182d2217a85dbb16ca2cee9522ce2c43a0 | templates/react-class/index.js | templates/react-class/index.js | import React, { Component } from 'react'
class {{file}} extends Component {
render () {
return (
<div className="{{file}}">
</div>
)
}
}
export default {{file}}
| import React, { Component } from 'react'
import './{{file}}.css'
class {{file}} extends Component {
render () {
return (
<div className="{{file}}">
</div>
)
}
}
export default {{file}}
| Add CSS import to react-class template | Add CSS import to react-class template
| JavaScript | isc | tu4mo/teg | ---
+++
@@ -1,4 +1,6 @@
import React, { Component } from 'react'
+
+import './{{file}}.css'
class {{file}} extends Component {
render () { |
8b153821c3a8348a4a54442af453fd61b6e3d51f | app/assets/javascripts/ruby_prof_rails/home.js | app/assets/javascripts/ruby_prof_rails/home.js | $(function() {
$('form').preventDoubleSubmission();
$('form').on('submit', function(e){
$(this).find('button').text('Processing...')
});
select_profiles_tab_from_url_hash();
disable_modal_links();
});
function disable_modal_links(){
if( !bootstrap_enabled() ){
$("a[data-toggle='modal'").hide();
}
}
function bootstrap_enabled(){
return (typeof $().modal == 'function');
}
function select_profiles_tab_from_url_hash(){
if( window.location.hash == '#profiles' ){
$('#profiles-tab a').tab('show');
}
}
// jQuery plugin to prevent double submission of forms
jQuery.fn.preventDoubleSubmission = function() {
$(this).on('submit',function(e){
var $form = $(this);
if ($form.data('submitted') === true) {
// Previously submitted - don't submit again
e.preventDefault();
} else {
// Mark it so that the next submit can be ignored
$form.data('submitted', true);
}
});
// Keep chainability
return this;
};
| $(function() {
$('form').preventDoubleSubmission();
$('form').on('submit', function(e){
$(this).find('button').text('Processing...')
});
select_profiles_tab_from_url_hash();
disable_modal_links();
});
function disable_modal_links(){
if( !bootstrap_enabled() ){
$("a[data-toggle='modal'").hide();
}
}
function bootstrap_enabled(){
return (typeof $().modal == 'function');
}
function select_profiles_tab_from_url_hash(){
if( window.location.hash == '#profiles' ){
$('#my-profiles-tab a').tab('show');
}
}
// jQuery plugin to prevent double submission of forms
jQuery.fn.preventDoubleSubmission = function() {
$(this).on('submit',function(e){
var $form = $(this);
if ($form.data('submitted') === true) {
// Previously submitted - don't submit again
e.preventDefault();
} else {
// Mark it so that the next submit can be ignored
$form.data('submitted', true);
}
});
// Keep chainability
return this;
};
| Add Exclude Formats to skip | Add Exclude Formats to skip
| JavaScript | mit | tleish/ruby-prof-rails,tleish/ruby-prof-rails,tleish/ruby-prof-rails | ---
+++
@@ -22,7 +22,7 @@
function select_profiles_tab_from_url_hash(){
if( window.location.hash == '#profiles' ){
- $('#profiles-tab a').tab('show');
+ $('#my-profiles-tab a').tab('show');
}
}
|
5a0f409a488a4a5d3fed358fda6f71cd7dc66676 | rollup.config.js | rollup.config.js | import resolve from 'rollup-plugin-node-resolve'
import minify from 'rollup-plugin-minify-es'
import license from 'rollup-plugin-license'
export default {
input: 'src/micro-panel-all.js',
output: [
{
format: 'iife',
name: 'codeflask_element',
file: 'dist/micro-panel-all.bundle.min.js',
sourcemap: true,
}
],
plugins: [
resolve(),
minify(),
license({
banner: `@license
micro-panel is public domain or available under the Unlicense.
lit-element/lit-html/etc. (c) The Polymer Authors under BSD 3-Clause.`
}),
],
}
| import resolve from 'rollup-plugin-node-resolve'
import minify from 'rollup-plugin-minify-es'
import license from 'rollup-plugin-license'
export default {
input: 'src/micro-panel-all.js',
output: [
{
format: 'iife',
name: 'codeflask_element',
file: 'dist/micro-panel-all.bundle.min.js',
sourcemap: true,
}
],
plugins: [
resolve(),
minify(),
license({
banner: `@license
micro-panel | Unlicense.
lit-element/lit-html (c) The Polymer Authors | BSD 3-Clause.
CodeFlask (c) Claudio Holanda | MIT.
Prism (c) Lea Verou | MIT.`
}),
],
}
| Add codeflask/prism to license banner | Add codeflask/prism to license banner
| JavaScript | unlicense | myfreeweb/micro-panel,myfreeweb/micro-panel | ---
+++
@@ -17,8 +17,10 @@
minify(),
license({
banner: `@license
-micro-panel is public domain or available under the Unlicense.
-lit-element/lit-html/etc. (c) The Polymer Authors under BSD 3-Clause.`
+micro-panel | Unlicense.
+lit-element/lit-html (c) The Polymer Authors | BSD 3-Clause.
+CodeFlask (c) Claudio Holanda | MIT.
+Prism (c) Lea Verou | MIT.`
}),
],
} |
c3ebe5ba281de674c18c47130df3aabfac1cd0c8 | lib/index.js | lib/index.js | var native = require('../build/Release/dhcurve'),
common = require('./common.js'),
Promise = require('es6-promises'),
_ = require('goal');
function generateKeyPair() {
}
module.exports = _.mixin({
generateKeyPair: generateKeyPair
}, common);
| var global = function() {
return this;
}();
var native = require('../build/Release/dhcurve'),
common = require('./common.js'),
Promise = global.Promise || require('es6-promises'),
_ = require('goal');
function generateKeyPair() {
}
module.exports = _.mixin({
generateKeyPair: generateKeyPair
}, common);
| Use Promises in node.js if found. | Use Promises in node.js if found.
| JavaScript | mit | mbullington/dhcurve | ---
+++
@@ -1,6 +1,10 @@
+var global = function() {
+ return this;
+}();
+
var native = require('../build/Release/dhcurve'),
common = require('./common.js'),
- Promise = require('es6-promises'),
+ Promise = global.Promise || require('es6-promises'),
_ = require('goal');
function generateKeyPair() { |
6e69926de990faac1132b2f434c493750766b101 | src/grid-interaction.js | src/grid-interaction.js | import gtr from './global-translation.js'
import GraphicsHandler from './graphics-handler.js'
import MouseHandler from './mouse-handler.js'
import {getIsometricCoordinate} from './isometric-math.js'
const CONTAINER = document.querySelector('.graphics-wrapper')
export default class GridInteraction {
constructor () {
this.gh = new GraphicsHandler(CONTAINER)
}
clear () {
this.gh.clearCanvas()
}
render () {
const x = MouseHandler.position().x
const y = MouseHandler.position().y
if (x !== this.oldX && y !== this.oldY) {
this.oldX = x
this.oldY = y
const gPos = gtr.toGlobal(x, y)
const isoCoord = getIsometricCoordinate(gPos.x, gPos.y)
this.gh.clearCanvas()
this.gh.fillStyle = 'rgba(0, 0, 0, 0.2)'
this.gh.drawTriangle(isoCoord.a1, isoCoord.a2, isoCoord.right)
}
}
}
| import gtr from './global-translation.js'
import GraphicsHandler from './graphics-handler.js'
import MouseHandler from './mouse-handler.js'
import {getIsometricCoordinate} from './isometric-math.js'
const CONTAINER = document.querySelector('.graphics-wrapper')
export default class GridInteraction {
constructor () {
this.gh = new GraphicsHandler(CONTAINER)
this.isTouchDevice = 'ontouchstart' in window || navigator.maxTouchPoints
};
}
clear () {
this.gh.clearCanvas()
}
render () {
const x = MouseHandler.position().x
const y = MouseHandler.position().y
if (!isTouchDevice && x !== this.oldX && y !== this.oldY) {
this.oldX = x
this.oldY = y
const gPos = gtr.toGlobal(x, y)
const isoCoord = getIsometricCoordinate(gPos.x, gPos.y)
this.gh.clearCanvas()
this.gh.fillStyle = 'rgba(0, 0, 0, 0.2)'
this.gh.drawTriangle(isoCoord.a1, isoCoord.a2, isoCoord.right)
}
}
}
| Fix that removes hover effect on touch devices | Fix that removes hover effect on touch devices
| JavaScript | apache-2.0 | drpentagon/isometric-paint,drpentagon/isometric-paint | ---
+++
@@ -8,6 +8,8 @@
export default class GridInteraction {
constructor () {
this.gh = new GraphicsHandler(CONTAINER)
+ this.isTouchDevice = 'ontouchstart' in window || navigator.maxTouchPoints
+};
}
clear () {
@@ -17,7 +19,7 @@
render () {
const x = MouseHandler.position().x
const y = MouseHandler.position().y
- if (x !== this.oldX && y !== this.oldY) {
+ if (!isTouchDevice && x !== this.oldX && y !== this.oldY) {
this.oldX = x
this.oldY = y
const gPos = gtr.toGlobal(x, y) |
ac64d509ed40712a7c10c265b642560c0a8a0b6e | scripts/chris.js | scripts/chris.js | var audio = document.getElementById("chris");
function pauseChris() {
if (audio.currentTime >= 331000) {
audio.pause();
alert(interval);
}
}
function playChris() {
audio.currentTime = 952;
audio.play();
var interval = setInterval(pauseChris, 1000);
}
function addChrisButton() {
var div = document.getElementById("audioContainer");
var button = document.createElement("BUTTON");
button.setAttribute("type", "button");
button.addEventListener("click", playChris);
button.innerText = "Escuchar a Chris";
div.insertBefore(button, audio);
}
addChrisButton();
| var audio = document.getElementById("chris");
function pauseChris() {
if (audio.currentTime >= 331000) {
audio.pause();
alert(audio.currentTime);
}
}
function playChris() {
audio.currentTime = 952;
audio.play();
var interval = setInterval(pauseChris, 1000);
}
function addChrisButton() {
var div = document.getElementById("audioContainer");
var button = document.createElement("BUTTON");
button.setAttribute("type", "button");
button.addEventListener("click", playChris);
button.innerText = "Escuchar a Chris";
div.insertBefore(button, audio);
}
addChrisButton();
| Check current time after pause | Check current time after pause
| JavaScript | mit | nvdaes/nvdaes.github.io,nvdaes/nvdaes.github.io | ---
+++
@@ -3,7 +3,7 @@
function pauseChris() {
if (audio.currentTime >= 331000) {
audio.pause();
- alert(interval);
+ alert(audio.currentTime);
}
}
|
9adb52b6fd343ca01b4d706a0b87be7fe09b3e7b | src/content_scripts/pivotal_tracker/view/toggle_feature_notifier.js | src/content_scripts/pivotal_tracker/view/toggle_feature_notifier.js | import $ from 'jquery';
export default class ToggleFeatureNotifier {
constructor({chromeWrapper}) {
this._chromeWrapper = chromeWrapper;
this.notify = this.notify.bind(this);
}
notify() {
const optionsUrl = this._chromeWrapper.getURL('src/options/index.html');
prependElementAsChildOf('#tracker', `
<div class="ui message">
<i class="close icon"></i>
<div class="header">
WWLTW Extension Update
</div>
<p>You can enable and disable the WWLTW chrome extension for individual backlogs from
the <a href="${optionsUrl}" target="_blank">bottom of the options page.</a></p>
</div>
`);
$('.message .close').on('click', function () {
$(this)
.closest('.message')
.transition('fade')
;
});
}
}
const prependElementAsChildOf = function (parent, html) {
let elementContainer = document.createElement('div');
elementContainer.innerHTML = html;
$(parent).prepend(elementContainer);
}; | import $ from 'jquery';
export default class ToggleFeatureNotifier {
constructor({chromeWrapper}) {
this._chromeWrapper = chromeWrapper;
this.notify = this.notify.bind(this);
}
notify() {
const optionsUrl = this._chromeWrapper.getURL('src/options/index.html');
prependElementAsChildOf('#tracker', `
<div class="ui message">
<i class="close icon"></i>
<div class="header">
WWLTW Extension Update
</div>
<p>The WWLTW chrome extension is now disabled by default for all backlogs. You can enable it for any of your backlogs from
the <a href="${optionsUrl}" target="_blank">bottom of the options page.</a></p>
</div>
`);
$('.message .close').on('click', function () {
$(this)
.closest('.message')
.transition('fade')
;
});
}
}
const prependElementAsChildOf = function (parent, html) {
let elementContainer = document.createElement('div');
elementContainer.innerHTML = html;
$(parent).prepend(elementContainer);
}; | Update copy for toggle feature notification | Update copy for toggle feature notification
| JavaScript | isc | oliverswitzer/wwltw-for-pivotal-tracker,oliverswitzer/wwltw-for-pivotal-tracker | ---
+++
@@ -15,7 +15,7 @@
<div class="header">
WWLTW Extension Update
</div>
- <p>You can enable and disable the WWLTW chrome extension for individual backlogs from
+ <p>The WWLTW chrome extension is now disabled by default for all backlogs. You can enable it for any of your backlogs from
the <a href="${optionsUrl}" target="_blank">bottom of the options page.</a></p>
</div>
`); |
931fa47355cb7f5d5bce4d77affb7313211ac043 | base.js | base.js | var util = require('util');
module.exports = function (name, defaultMessage, status) {
util.inherits(Constructor, Error);
return Constructor;
function Constructor (message, code) {
Error.call(this);
Error.captureStackTrace(this, arguments.callee);
this.name = name;
this.message = message || defaultMessage;
this.status = status;
this.expose = true;
if (code !== undefined) this.code = code;
}
}; | var util = require('util');
module.exports = function (name, defaultMessage, status) {
util.inherits(Constructor, Error);
return Constructor;
function Constructor (message, code) {
Error.call(this, message || defaultMessage);
Error.captureStackTrace(this, arguments.callee);
this.name = name;
this.status = status;
this.expose = true;
if (code !== undefined) this.code = code;
}
};
| Set error message using constructor | Set error message using constructor
| JavaScript | mit | aantthony/errors | ---
+++
@@ -7,10 +7,9 @@
return Constructor;
function Constructor (message, code) {
- Error.call(this);
+ Error.call(this, message || defaultMessage);
Error.captureStackTrace(this, arguments.callee);
this.name = name;
- this.message = message || defaultMessage;
this.status = status;
this.expose = true;
if (code !== undefined) this.code = code; |
8436bfbd641fd92d85116a4f6683d18fc23282a7 | app/common/resourceCache/reducer.js | app/common/resourceCache/reducer.js | import {
SET_RESOURCE,
MARK_DASHBOARD_DIRTY,
RESET_RESOURCE_CACHE
} from './actions';
const markAllDirty = (keys, state) => {
const dirty = {};
keys.forEach((key) => {
dirty[key] = { ...state[key], dirty: true };
});
return dirty;
};
const resourceReducer = (state = {}, action) => {
switch (action.type) {
case MARK_DASHBOARD_DIRTY:
return {
...state,
...markAllDirty(action.payload, state),
};
case SET_RESOURCE:
return {
...state,
[action.payload.key]: action.payload.resource,
};
case RESET_RESOURCE_CACHE:
return {};
default:
return state;
}
};
export default resourceReducer;
| import {
SET_RESOURCE,
MARK_DASHBOARD_DIRTY,
RESET_RESOURCE_CACHE
} from './actions';
const markAllDirty = (keys, state) => {
const dirty = {};
keys.forEach((key) => {
if (state[key]) {
dirty[key] = { ...state[key], dirty: true };
}
});
return dirty;
};
const resourceReducer = (state = {}, action) => {
switch (action.type) {
case MARK_DASHBOARD_DIRTY:
return {
...state,
...markAllDirty(action.payload, state),
};
case SET_RESOURCE:
return {
...state,
[action.payload.key]: action.payload.resource,
};
case RESET_RESOURCE_CACHE:
return {};
default:
return state;
}
};
export default resourceReducer;
| Check for the existence of the resource cache key before attempting to make dirty | Check for the existence of the resource cache key before attempting to make dirty
| JavaScript | mit | nathanhood/mmdb,nathanhood/mmdb | ---
+++
@@ -8,7 +8,9 @@
const dirty = {};
keys.forEach((key) => {
- dirty[key] = { ...state[key], dirty: true };
+ if (state[key]) {
+ dirty[key] = { ...state[key], dirty: true };
+ }
});
return dirty; |
aea4582982e586365f788ed0d886262da7ab325f | server/controllers/students.js | server/controllers/students.js | //var Teachers = require('../models/teachers');
//var TeacherClasses = require('../models/Teacher_classes');
//var Classes = require('../models/classes');
//var ClassLessons = require('../models/class_lessons');
// var Lessons = require('../models/lessons');
//var RequestedResponses = require('../models/requested_responses');
module.exports = {
readyStage : function(io, req, res, next) {
// io.on('connection', function(client){
// console.log('Hey, server! A student is ready to learn!');
// client.emit('greeting', 'Hello, student!');
// client.on('responseRecorded', function(data){
// io.sockets.emit('responseRecordedFromStudent', data);
// });
// });
res.status(200).send('Hello from the other side');
}
}; | //var Teachers = require('../models/teachers');
//var TeacherClasses = require('../models/Teacher_classes');
//var Classes = require('../models/classes');
//var ClassLessons = require('../models/class_lessons');
// var Lessons = require('../models/lessons');
//var RequestedResponses = require('../models/requested_responses');
module.exports = {
readyStage : function(io, req, res, next) {
//var studentInformation = req.body.studentData
var pollResponse = {
responseId: 1,
type: 'thumbs',
datetime: new Date(),
lessonId: 13,
};
io.on('connection', function(student){
student.emit('studentStandby', studentInformation);
student.on('teacherConnect', function() {
student.emit('teacherConnect');
});
student.on('newPoll', function(data) {
student.emit(data);
});
setTimeout(function(){
io.sockets.emit('responseFromStudent', pollResponse);
}, 5000);
});
res.status(200).send('Hello from the other side');
}
}; | Add student information to connection socket event | Add student information to connection socket event
| JavaScript | mit | Jakeyrob/thumbroll,shanemcgraw/thumbroll,Jakeyrob/thumbroll,absurdSquid/thumbroll,shanemcgraw/thumbroll,shanemcgraw/thumbroll,absurdSquid/thumbroll,Jakeyrob/thumbroll | ---
+++
@@ -9,17 +9,31 @@
readyStage : function(io, req, res, next) {
- // io.on('connection', function(client){
- // console.log('Hey, server! A student is ready to learn!');
+ //var studentInformation = req.body.studentData
+ var pollResponse = {
+ responseId: 1,
+ type: 'thumbs',
+ datetime: new Date(),
+ lessonId: 13,
+ };
+
+ io.on('connection', function(student){
- // client.emit('greeting', 'Hello, student!');
+ student.emit('studentStandby', studentInformation);
- // client.on('responseRecorded', function(data){
- // io.sockets.emit('responseRecordedFromStudent', data);
- // });
+ student.on('teacherConnect', function() {
+ student.emit('teacherConnect');
+ });
- // });
+ student.on('newPoll', function(data) {
+ student.emit(data);
+ });
+ setTimeout(function(){
+ io.sockets.emit('responseFromStudent', pollResponse);
+ }, 5000);
+
+ });
res.status(200).send('Hello from the other side');
}
}; |
c2c520b16f46f94d9b82251b344f0ef7de158903 | app/assets/javascripts/sprangular.js | app/assets/javascripts/sprangular.js | //
// General
//
//= require underscore
//= require underscore.string
//= require jquery
//= require angular
//= require angularytics
//= require bootstrap-sass-official
//= require validity
//
// Angular specific
//
//= require angular-translate
//= require angular-strap/angular-strap.js
//= require angular-strap/angular-strap.tpl.js
//= require angular-route
//= require angular-sanitize
//= require angular-animate
//= require sprangular/app
| //
// General
//
//= require underscore
//= require underscore.string
//= require angular
//= require angularytics
//= require bootstrap-sass-official
//= require validity
//
// Angular specific
//
//= require angular-translate
//= require angular-strap/angular-strap.js
//= require angular-strap/angular-strap.tpl.js
//= require angular-route
//= require angular-sanitize
//= require angular-animate
//= require sprangular/app
| Remove include of jquery, it should be included by host app | Remove include of jquery, it should be included by host app
| JavaScript | mit | sprangular/sprangular,sprangular/sprangular,sprangular/sprangular | ---
+++
@@ -4,7 +4,6 @@
//= require underscore
//= require underscore.string
-//= require jquery
//= require angular
//= require angularytics
//= require bootstrap-sass-official |
bee4589cdd421a33aad2d5f25fbd97f777bf2e58 | app/assets/javascripts/application.js | app/assets/javascripts/application.js | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require tinymce-jquery
//= require_tree .
//= require_tree ../../../vendor/assets/javascripts/.
| // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require tinymce-jquery
//= require_tree ../../../vendor/assets/javascripts/.
//= require_tree .
| Move vender js files in manifest so the tree can access them | Move vender js files in manifest so the tree can access them
| JavaScript | mit | timmykat/openeffects.org,timmykat/openeffects.org,timmykat/openeffects.org,ofxa/openeffects.org,timmykat/openeffects.org,ofxa/openeffects.org,ofxa/openeffects.org,ofxa/openeffects.org | ---
+++
@@ -13,5 +13,5 @@
//= require jquery
//= require jquery_ujs
//= require tinymce-jquery
+//= require_tree ../../../vendor/assets/javascripts/.
//= require_tree .
-//= require_tree ../../../vendor/assets/javascripts/. |
cbeaf1c062caa2262ab7dc0553069f8708a0d472 | app/assets/javascripts/application.js | app/assets/javascripts/application.js | // This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
//= require jquery
//= require jquery_ujs
//= require jquery.cookie
//= require jquery.tools.min
//= require knockout
//= require superbly-tagfield.min
//= require maps
//= require map_display
//= require map_edit
//= require map_popup
//= require map_style
//= require openlayers_pz
//= require ui
//= require tags
//= require supercool
//= require library_message
| // This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
//= require jquery
//= require jquery_ujs
//= require jquery.cookie
//= require jquery.tools.min
//= require knockout
//= require superbly-tagfield.min
//= require maps
//= require map_display
//= require map_edit
//= require map_popup
//= require map_style
//= require openlayers_pz
//= require ui
//= require tags
//= require library_message
| Remove supercool.js from manifest as tag plugin causes errors in IE8. | Remove supercool.js from manifest as tag plugin causes errors in IE8.
Looks like the plugin does not support empty jQuery sets for when the
field isn't present.
| JavaScript | mit | cyclestreets/cyclescape,auto-mat/toolkit,cyclestreets/cyclescape,auto-mat/toolkit,cyclestreets/cyclescape | ---
+++
@@ -18,5 +18,4 @@
//= require openlayers_pz
//= require ui
//= require tags
-//= require supercool
//= require library_message |
7db436acaad26f648be77abea89f726e2677434f | app/assets/javascripts/application.js | app/assets/javascripts/application.js | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require_tree .
| // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require namespace
//= require_tree .
| Load namespace javascript file before all others | Load namespace javascript file before all others
| JavaScript | mit | joshmcarthur/inquest,joshmcarthur/inquest | ---
+++
@@ -13,4 +13,5 @@
//= require jquery
//= require jquery_ujs
//= require bootstrap
+//= require namespace
//= require_tree . |
ae50e4f695c7f68ce839332cc548696d1692e5c0 | app/assets/javascripts/districts/controllers/district_modal_controller.js | app/assets/javascripts/districts/controllers/district_modal_controller.js | VtTracker.DistrictModalController = Ember.ObjectController.extend({
needs: ['index'],
modalTitle: function() {
if (this.get('isNew')) {
return 'New District';
} else {
return 'Edit District';
}
}.property('isNew'),
actions: {
save: function() {
var _self = this;
var isNew = _self.get('model.isNew');
_self.get('model').save().then(function() {
if (isNew) {
_self.set('controllers.index.newDistrict', _self.store.createRecord('district'));
}
});
}
}
});
| VtTracker.DistrictModalController = Ember.ObjectController.extend({
needs: ['index'],
modalTitle: function() {
if (this.get('isNew')) {
return 'New District';
} else {
return 'Edit District';
}
}.property('isNew'),
actions: {
removeModal: function() {
this.get('model').rollback();
return true;
},
save: function() {
var _self = this;
var isNew = _self.get('model.isNew');
_self.get('model').save().then(function() {
if (isNew) {
_self.set('controllers.index.newDistrict', _self.store.createRecord('district'));
}
});
}
}
});
| Rollback district edit model when modal is closed | Rollback district edit model when modal is closed | JavaScript | mit | bfcoder/vt-ht-tracker,bfcoder/vt-ht-tracker,bfcoder/vt-ht-tracker | ---
+++
@@ -10,6 +10,11 @@
}.property('isNew'),
actions: {
+ removeModal: function() {
+ this.get('model').rollback();
+ return true;
+ },
+
save: function() {
var _self = this;
var isNew = _self.get('model.isNew'); |
b28a11df9533f9fa91945264bb34e51ea977c417 | javascripts/extension.js | javascripts/extension.js | $("div.entry").live('click', function( e ) {
var item = $(e.target).closest('.entry');
if (!item.find('.entry-actions span.google-plus').length) {
item.find(".entry-actions span.tag").after($('<span class="link google-plus">Share to Google+</span>'));
}
});
$(".entry-actions span.google-plus").live('click', function( e ) {
var entry = $(e.target).closest('.entry');
var link = entry.find('a.entry-original').attr('href');
$("#gbg3").trigger('click');
}); | $("div.entry").live('click', function( e ) {
var link, href, item = $(e.target).closest('.entry');
if (!item.find('.entry-actions span.google-plus').length) {
href = 'https://plus.google.com/?status=' + item.find('a.entry-title-link').attr('href');
link = $('<a target="_blank">Share to Google+</a>').attr('href', href);
item.find(".entry-actions span.tag").after($('<span class="link google-plus"></span>').html(link));
}
});
| Create a share link with ?status | Create a share link with ?status
| JavaScript | mit | felipeelias/reader_to_plus | ---
+++
@@ -1,14 +1,9 @@
$("div.entry").live('click', function( e ) {
- var item = $(e.target).closest('.entry');
+ var link, href, item = $(e.target).closest('.entry');
if (!item.find('.entry-actions span.google-plus').length) {
- item.find(".entry-actions span.tag").after($('<span class="link google-plus">Share to Google+</span>'));
+ href = 'https://plus.google.com/?status=' + item.find('a.entry-title-link').attr('href');
+ link = $('<a target="_blank">Share to Google+</a>').attr('href', href);
+ item.find(".entry-actions span.tag").after($('<span class="link google-plus"></span>').html(link));
}
});
-
-$(".entry-actions span.google-plus").live('click', function( e ) {
- var entry = $(e.target).closest('.entry');
- var link = entry.find('a.entry-original').attr('href');
-
- $("#gbg3").trigger('click');
-}); |
3af0ea079e7710f16599de9565c9c9f07f666d4c | lib/ui/views/targetSelector.js | lib/ui/views/targetSelector.js | /*
* Copyright 2014 BlackBerry Ltd.
*
* 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 TargetSelectorView,
targetSelectorTemplate;
TargetSelectorView = Backbone.View.extend({
initialize: function () {
// Find the template and save it
$.get("pages/targetSelector.html", function (data) {
targetSelectorTemplate = data;
});
},
render: function () {
// Use the template to create the html to display
var view = this,
showDevices = view.model.get("buildSettings").device,
template;
if (typeof showDevices === "undefined") {
showDevices = true;
}
this.model.targetFilter(showDevices, function (filteredTargets) {
template = _.template(targetSelectorTemplate, {
targetNameList: Object.keys(filteredTargets)
});
// Put the new html inside of the assigned element
view.$el.html(template);
});
},
events: {
},
display: function (model) {
this.model = model;
this.render();
}
});
module.exports = TargetSelectorView;
| /*
* Copyright 2014 BlackBerry Ltd.
*
* 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 TargetSelectorView,
targetSelectorTemplate;
TargetSelectorView = Backbone.View.extend({
initialize: function () {
// Find the template and save it
$.get("pages/targetSelector.html", function (data) {
targetSelectorTemplate = data;
});
},
render: function () {
// Use the template to create the html to display
var view = this,
buildSettings = view.model.get("buildSettings"),
showDevices = !buildSettings || typeof buildSettings.device === "undefined" || buildSettings.device,
template;
this.model.targetFilter(showDevices, function (filteredTargets) {
template = _.template(targetSelectorTemplate, {
targetNameList: Object.keys(filteredTargets)
});
// Put the new html inside of the assigned element
view.$el.html(template);
});
},
events: {
},
display: function (model) {
this.model = model;
this.render();
}
});
module.exports = TargetSelectorView;
| Fix target selector for imported projects | Fix target selector for imported projects
| JavaScript | apache-2.0 | blackberry/webworks-gui,blackberry-webworks/webworks-gui,blackberry/webworks-gui,blackberry-webworks/webworks-gui | ---
+++
@@ -26,12 +26,9 @@
render: function () {
// Use the template to create the html to display
var view = this,
- showDevices = view.model.get("buildSettings").device,
+ buildSettings = view.model.get("buildSettings"),
+ showDevices = !buildSettings || typeof buildSettings.device === "undefined" || buildSettings.device,
template;
-
- if (typeof showDevices === "undefined") {
- showDevices = true;
- }
this.model.targetFilter(showDevices, function (filteredTargets) {
template = _.template(targetSelectorTemplate, { |
994654819859ddb726b92d0f4d571bb75bbcbe91 | test/support/logger-factory.js | test/support/logger-factory.js | var _ = require('lodash')
var assert = require('assert')
module.exports = function () {
var log = []
return {
write: function () {
log.push(_(arguments).toArray().join(' '))
},
read: function () { return log },
toString: function () { return log.join('\n') },
assert: function () {
var lines = _.toArray(arguments)
_.each(lines, function (line, i) {
if (line instanceof RegExp) {
assert(line.test(log[i]), line.toString() + ' did not match: "' + log[i] + '"')
} else {
assert.equal(log[i], line)
}
})
}
}
}
| var _ = require('lodash')
var assert = require('assert')
module.exports = function () {
var log = []
return {
write: function () {
log.push(_(arguments).toArray().join(' '))
},
read: function () { return log },
toString: function () { return log.join('\n') },
assert: function () {
var lines = _.toArray(arguments)
try {
_.each(lines, function (line, i) {
if (line instanceof RegExp) {
assert(line.test(log[i]), line.toString() + ' did not match: "' + log[i] + '"')
} else {
assert.equal(log[i], line)
}
})
} catch (e) {
console.error('Error asserting the log. Full log follows:')
console.log(log)
throw e
}
}
}
}
| Make debugging easier by always printing the log | Make debugging easier by always printing the log | JavaScript | mit | testdouble/teenytest,testdouble/teenytest | ---
+++
@@ -13,13 +13,19 @@
assert: function () {
var lines = _.toArray(arguments)
- _.each(lines, function (line, i) {
- if (line instanceof RegExp) {
- assert(line.test(log[i]), line.toString() + ' did not match: "' + log[i] + '"')
- } else {
- assert.equal(log[i], line)
- }
- })
+ try {
+ _.each(lines, function (line, i) {
+ if (line instanceof RegExp) {
+ assert(line.test(log[i]), line.toString() + ' did not match: "' + log[i] + '"')
+ } else {
+ assert.equal(log[i], line)
+ }
+ })
+ } catch (e) {
+ console.error('Error asserting the log. Full log follows:')
+ console.log(log)
+ throw e
+ }
}
}
} |
ed2c390f30ceeb1f5e0ff5618006fb9f1bc778ef | app/users/edit/responsibilities/controller.js | app/users/edit/responsibilities/controller.js | import Controller from '@ember/controller'
import { task } from 'ember-concurrency'
import QueryParams from 'ember-parachute'
import moment from 'moment'
const UsersEditResponsibilitiesQueryParams = new QueryParams({})
export default Controller.extend(UsersEditResponsibilitiesQueryParams.Mixin, {
setup() {
this.get('projects').perform()
this.get('supervisees').perform()
},
projects: task(function*() {
return yield this.store.query('project', {
reviewer: this.get('model.id'),
include: 'customer',
ordering: 'customer__name,name'
})
}),
supervisees: task(function*() {
let supervisor = this.get('model.id')
yield this.store.query('worktime-balance', {
supervisor,
date: moment().format('YYYY-MM-DD')
})
return yield this.store.query('user', { supervisor, ordering: 'username' })
})
})
| import Controller from '@ember/controller'
import { task } from 'ember-concurrency'
import QueryParams from 'ember-parachute'
import moment from 'moment'
const UsersEditResponsibilitiesQueryParams = new QueryParams({})
export default Controller.extend(UsersEditResponsibilitiesQueryParams.Mixin, {
setup() {
this.get('projects').perform()
this.get('supervisees').perform()
},
projects: task(function*() {
return yield this.store.query('project', {
reviewer: this.get('model.id'),
include: 'customer',
ordering: 'customer__name,name'
})
}),
supervisees: task(function*() {
let supervisor = this.get('model.id')
let balances = yield this.store.query('worktime-balance', {
supervisor,
date: moment().format('YYYY-MM-DD'),
include: 'user'
})
return balances.mapBy('user')
})
})
| Use included to fetch supervisees | Use included to fetch supervisees
| JavaScript | agpl-3.0 | anehx/timed-frontend,adfinis-sygroup/timed-frontend,adfinis-sygroup/timed-frontend,anehx/timed-frontend,adfinis-sygroup/timed-frontend | ---
+++
@@ -22,11 +22,12 @@
supervisees: task(function*() {
let supervisor = this.get('model.id')
- yield this.store.query('worktime-balance', {
+ let balances = yield this.store.query('worktime-balance', {
supervisor,
- date: moment().format('YYYY-MM-DD')
+ date: moment().format('YYYY-MM-DD'),
+ include: 'user'
})
- return yield this.store.query('user', { supervisor, ordering: 'username' })
+ return balances.mapBy('user')
})
}) |
faa007e535289ee435df9ec4a92f3b229bbd9227 | app_server/app/controllers/AdminController.js | app_server/app/controllers/AdminController.js | /**
* Admin Controller
* @module AdminController
*/
var rfr = require('rfr');
var Joi = require('joi');
var Boom = require('boom');
var Utility = rfr('app/util/Utility');
var Service = rfr('app/services/Service');
var logger = Utility.createLogger(__filename);
function AdminController(server, options) {
this.server = server;
this.options = options;
}
var Class = AdminController.prototype;
Class.registerRoutes = function () {
this.server.route({
method: 'POST', path: '/',
config: {
auth: false
},
handler: this.createAdmin
});
};
/* Routes handlers */
Class.createAdmin = function (request, reply) {
};
exports.register = function (server, options, next) {
var adminController = new AdminController(server, options);
server.bind(adminController);
adminController.registerRoutes();
next();
};
exports.register.attributes = {
name: 'AdminController'
};
| /**
* Admin Controller
* @module AdminController
*/
var rfr = require('rfr');
var Joi = require('joi');
var Boom = require('boom');
var bcrypt = require('bcryptjs');
var Utility = rfr('app/util/Utility');
var Authenticator = rfr('app/policies/Authenticator');
var Service = rfr('app/services/Service');
var logger = Utility.createLogger(__filename);
function AdminController(server, options) {
this.server = server;
this.options = options;
}
var Class = AdminController.prototype;
Class.registerRoutes = function () {
this.server.route({
method: 'POST', path: '/',
config: {
auth: {scope: Authenticator.SCOPE.ADMIN}
},
handler: this.createAdmin
});
};
/* Routes handlers */
Class.createAdmin = function (request, reply) {
var credentials = {
username: request.payload.username,
password: encrypt(request.payload.password)
};
Service.createNewAdmin(credentials)
.then(function (admin) {
if (!admin || admin instanceof Error) {
return reply(Boom.badRequest('Unable to create admin ' + credentials));
}
// overwrite with unencrypted password
admin.password = request.payload.password;
reply(admin).created();
});
};
/* Helpers for everything above */
var encrypt = function (password) {
var salt = bcrypt.genSaltSync(10);
return bcrypt.hashSync(password, salt);
};
exports.register = function (server, options, next) {
var adminController = new AdminController(server, options);
server.bind(adminController);
adminController.registerRoutes();
next();
};
exports.register.attributes = {
name: 'AdminController'
};
| Implement basic create admin with username / password only | Implement basic create admin with username / password only
| JavaScript | mit | nus-mtp/worldscope,nus-mtp/worldscope,nus-mtp/worldscope,nus-mtp/worldscope | ---
+++
@@ -5,8 +5,10 @@
var rfr = require('rfr');
var Joi = require('joi');
var Boom = require('boom');
+var bcrypt = require('bcryptjs');
var Utility = rfr('app/util/Utility');
+var Authenticator = rfr('app/policies/Authenticator');
var Service = rfr('app/services/Service');
var logger = Utility.createLogger(__filename);
@@ -21,7 +23,7 @@
this.server.route({
method: 'POST', path: '/',
config: {
- auth: false
+ auth: {scope: Authenticator.SCOPE.ADMIN}
},
handler: this.createAdmin
});
@@ -29,6 +31,27 @@
/* Routes handlers */
Class.createAdmin = function (request, reply) {
+ var credentials = {
+ username: request.payload.username,
+ password: encrypt(request.payload.password)
+ };
+
+ Service.createNewAdmin(credentials)
+ .then(function (admin) {
+ if (!admin || admin instanceof Error) {
+ return reply(Boom.badRequest('Unable to create admin ' + credentials));
+ }
+
+ // overwrite with unencrypted password
+ admin.password = request.payload.password;
+ reply(admin).created();
+ });
+};
+
+/* Helpers for everything above */
+var encrypt = function (password) {
+ var salt = bcrypt.genSaltSync(10);
+ return bcrypt.hashSync(password, salt);
};
exports.register = function (server, options, next) { |
d01f5941fa4a017d3b4434ba2a4f58b98364ba43 | lib/node/nodes/source.js | lib/node/nodes/source.js | 'use strict';
var Node = require('../node');
var TYPE = 'source';
var PARAMS = {
query: Node.PARAM.STRING()
};
var Source = Node.create(TYPE, PARAMS);
module.exports = Source;
module.exports.TYPE = TYPE;
module.exports.PARAMS = PARAMS;
Source.prototype.sql = function() {
return this.query;
};
Source.prototype.setColumnsNames = function(columns) {
this.columns = columns;
// Makes columns affecting Node.id().
// When a `select * from table` might end in a different set of columns
// we want to have a different node.
this.setAttributeToModifyId('columns');
};
/**
* Source nodes are ready by definition
*
* @returns {Node.STATUS}
*/
Source.prototype.getStatus = function() {
return Node.STATUS.READY;
};
Source.prototype.getAndSetUpdatedAt = function(databaseService, callback) {
if (this.updatedAt !== null) {
return callback(null, this.updatedAt);
}
databaseService.getLastUpdatedTimeFromAffectedTables(this.sql(), function(err, lastUpdatedAt) {
if (err) {
return callback(err);
}
this.updatedAt = lastUpdatedAt;
return callback(null, this.updatedAt);
}.bind(this));
};
| 'use strict';
var Node = require('../node');
var TYPE = 'source';
var PARAMS = {
query: Node.PARAM.STRING()
};
var Source = Node.create(TYPE, PARAMS, {
beforeCreate: function(node) {
// Last updated time in source node means data changed so it has to modify node.id
node.setAttributeToModifyId('updatedAt');
}
});
module.exports = Source;
module.exports.TYPE = TYPE;
module.exports.PARAMS = PARAMS;
Source.prototype.sql = function() {
return this.query;
};
Source.prototype.setColumnsNames = function(columns) {
this.columns = columns;
// Makes columns affecting Node.id().
// When a `select * from table` might end in a different set of columns
// we want to have a different node.
this.setAttributeToModifyId('columns');
};
/**
* Source nodes are ready by definition
*
* @returns {Node.STATUS}
*/
Source.prototype.getStatus = function() {
return Node.STATUS.READY;
};
Source.prototype.getAndSetUpdatedAt = function(databaseService, callback) {
if (this.updatedAt !== null) {
return callback(null, this.updatedAt);
}
databaseService.getLastUpdatedTimeFromAffectedTables(this.sql(), function(err, lastUpdatedAt) {
if (err) {
return callback(err);
}
this.updatedAt = lastUpdatedAt;
return callback(null, this.updatedAt);
}.bind(this));
};
| Make updatedAt modifying node.id in Source nodes | Make updatedAt modifying node.id in Source nodes
| JavaScript | bsd-3-clause | CartoDB/camshaft | ---
+++
@@ -7,7 +7,12 @@
query: Node.PARAM.STRING()
};
-var Source = Node.create(TYPE, PARAMS);
+var Source = Node.create(TYPE, PARAMS, {
+ beforeCreate: function(node) {
+ // Last updated time in source node means data changed so it has to modify node.id
+ node.setAttributeToModifyId('updatedAt');
+ }
+});
module.exports = Source;
module.exports.TYPE = TYPE; |
21cd7291094b7b03a5571287bf3673db3b13006e | lib/panes/output-area.js | lib/panes/output-area.js | /* @flow */
import { CompositeDisposable } from "atom";
import ResizeObserver from "resize-observer-polyfill";
import React from "react";
import { reactFactory, OUTPUT_AREA_URI } from "./../utils";
import typeof store from "../store";
import OutputArea from "./../components/output-area";
export default class OutputPane {
element = document.createElement("div");
disposer = new CompositeDisposable();
constructor(store: store) {
this.element.classList.add("hydrogen", "watch-sidebar");
// HACK: Dispatch a window resize Event for the slider history to recompute
// We should use native ResizeObserver once Atom ships with a newer version of Electron
// Or fork react-rangeslider to fix https://github.com/whoisandie/react-rangeslider/issues/62
const resizeObserver = new ResizeObserver(this.resize);
resizeObserver.observe(this.element);
reactFactory(
<OutputArea store={store} />,
this.element,
null,
this.disposer
);
}
resize = () => {
window.dispatchEvent(new Event("resize"));
};
getTitle = () => "Hydrogen Output Area";
getURI = () => OUTPUT_AREA_URI;
getDefaultLocation = () => "right";
getAllowedLocations = () => ["left", "right", "bottom"];
destroy() {
this.disposer.dispose();
this.element.remove();
}
}
| /* @flow */
import { CompositeDisposable, Disposable } from "atom";
import ResizeObserver from "resize-observer-polyfill";
import React from "react";
import { reactFactory, OUTPUT_AREA_URI } from "./../utils";
import typeof store from "../store";
import OutputArea from "./../components/output-area";
export default class OutputPane {
element = document.createElement("div");
disposer = new CompositeDisposable();
constructor(store: store) {
this.element.classList.add("hydrogen", "watch-sidebar");
// HACK: Dispatch a window resize Event for the slider history to recompute
// We should use native ResizeObserver once Atom ships with a newer version of Electron
// Or fork react-rangeslider to fix https://github.com/whoisandie/react-rangeslider/issues/62
const resizeObserver = new ResizeObserver(this.resize);
resizeObserver.observe(this.element);
this.disposer.add(
new Disposable(() => {
if (store.kernel) store.kernel.outputStore.clear();
})
);
reactFactory(
<OutputArea store={store} />,
this.element,
null,
this.disposer
);
}
resize = () => {
window.dispatchEvent(new Event("resize"));
};
getTitle = () => "Hydrogen Output Area";
getURI = () => OUTPUT_AREA_URI;
getDefaultLocation = () => "right";
getAllowedLocations = () => ["left", "right", "bottom"];
destroy() {
this.disposer.dispose();
this.element.remove();
}
}
| Reset output store if pane is closed | Reset output store if pane is closed
| JavaScript | mit | nteract/hydrogen,nteract/hydrogen,xanecs/hydrogen,rgbkrk/hydrogen | ---
+++
@@ -1,6 +1,6 @@
/* @flow */
-import { CompositeDisposable } from "atom";
+import { CompositeDisposable, Disposable } from "atom";
import ResizeObserver from "resize-observer-polyfill";
import React from "react";
@@ -21,6 +21,12 @@
// Or fork react-rangeslider to fix https://github.com/whoisandie/react-rangeslider/issues/62
const resizeObserver = new ResizeObserver(this.resize);
resizeObserver.observe(this.element);
+
+ this.disposer.add(
+ new Disposable(() => {
+ if (store.kernel) store.kernel.outputStore.clear();
+ })
+ );
reactFactory(
<OutputArea store={store} />, |
616729f152d9f513bf02ad3b0f41a21fbc89761a | lib/instagram.js | lib/instagram.js | var config = {
clientId: '',
clientSecret: '',
hashTag: 'ruisrock2014'
}
var getIg = function(){
var ig = require('instagram-node').instagram();
ig.use({ client_id: config.clientId,
client_secret: config.clientSecret});
return ig;
}
var parseIgMediaObject = function(media){
return {
link: media.link,
title: (media.caption==null)?"":media.caption.text,
thumbnail: media.images.thumbnail.url,
small_image: media.images.low_resolution.url,
image: media.images.standard_resolution.url,
likes: media.likes.count,
tags: media.tags
}
}
var parseIgMedia = function(medias){
var data = [];
medias.forEach(function(media){
data.push(parseIgMediaObject(media));
});
return data;
}
module.exports = {
tagMedia: function(req, res) {
try{
getIg().tag_media_recent(config.hashTag, function(err, medias, pagination, limit) {
if(err) throw new Error("Virhe");
res.send(JSON.stringify({status: 200, media: parseIgMedia(medias)}));
});
}catch(err){
res.send(500, JSON.stringify({status: 500, error: err.message}));
}
}
} | var config = {
clientId: '',
clientSecret: '',
hashTag: 'ruisrock2014'
}
var getIg = function(){
var ig = require('instagram-node').instagram();
ig.use({ client_id: config.clientId,
client_secret: config.clientSecret});
return ig;
}
var parseIgMediaObject = function(media){
return {
link: media.link,
title: (media.caption==null)?"":media.caption.text,
thumbnail: media.images.thumbnail.url,
small_image: media.images.low_resolution.url,
image: media.images.standard_resolution.url,
likes: media.likes.count,
tags: media.tags
}
}
var parseIgMedia = function(medias){
var data = [];
medias.forEach(function(media){
data.push(parseIgMediaObject(media));
});
return data;
}
module.exports = {
tagMedia: function(req, res) {
try{
getIg().tag_media_recent(config.hashTag, function(err, medias, pagination, limit) {
if(err)res.send(500);
else res.send(JSON.stringify({media: parseIgMedia(medias)}));
});
}catch(err){
res.send(500);
}
}
}
| Send 500 every now and then | Send 500 every now and then
| JavaScript | mit | futurice/festapp-server,futurice/sec-conference-server,0is1/festapp-server,futurice/sec-conference-server | ---
+++
@@ -35,11 +35,11 @@
tagMedia: function(req, res) {
try{
getIg().tag_media_recent(config.hashTag, function(err, medias, pagination, limit) {
- if(err) throw new Error("Virhe");
- res.send(JSON.stringify({status: 200, media: parseIgMedia(medias)}));
+ if(err)res.send(500);
+ else res.send(JSON.stringify({media: parseIgMedia(medias)}));
});
}catch(err){
- res.send(500, JSON.stringify({status: 500, error: err.message}));
+ res.send(500);
}
} |
a5f3d39929b4886ae28711d607c05275bfab74ca | dev/_/components/js/comparisonSetCollection.js | dev/_/components/js/comparisonSetCollection.js | AV.ComparisonSetCollection = Backbone.Collection.extend({
url: AV.URL('set.json'),
updateURL: function() {
this.url = AV.URL('set.json');
}
});
| AV.ComparisonSetCollection = Backbone.Collection.extend({
url: AV.URL('set'),//'.json'),
updateURL: function() {
this.url = AV.URL('set');//'.json');
}
});
| Remove .json from the set url | Remove .json from the set url
| JavaScript | bsd-3-clause | Swarthmore/juxtaphor,Swarthmore/juxtaphor | ---
+++
@@ -1,6 +1,6 @@
AV.ComparisonSetCollection = Backbone.Collection.extend({
- url: AV.URL('set.json'),
+ url: AV.URL('set'),//'.json'),
updateURL: function() {
- this.url = AV.URL('set.json');
+ this.url = AV.URL('set');//'.json');
}
}); |
98148ba689955cd9f07a55e6360207f613ceb6aa | gest.js | gest.js | #! /usr/bin/env node
const args = require('./args') // TODO
const path = require('path')
const { graphql: config } = require(path.join(process.cwd(), 'package.json'))
const { sendQuery, readFile, checkPath, REPL } = require('./src/api')
const { pullHeaders, colorResponse } = require('./src/util')
args
.option('header', 'HTTP request header')
.option('baseUrl', 'Base URL for sending HTTP requests')
const flags = args.parse(process.argv)
if (!flags.help && !flags.version) {
let schema
try {
schema = require(path.join(process.cwd(), (config && config.schema) || 'schema.js'))
} catch (e) {
console.log('\nSchema not found. Trying running `gest` with your `schema.js` in the current working directory.\n')
process.exit()
}
const options = Object.assign({}, config, pullHeaders(flags), { baseURL: flags.baseUrl })
if (args.sub && args.sub.length) {
checkPath(path.join(__dirname, args.sub[0]))
.then(readFile)
.catch(() => args.sub[0])
.then(sendQuery(schema, options))
.then(colorResponse)
.then(console.log)
.catch(console.log)
.then(() => process.exit())
} else {
// REPL
REPL(schema, options)
}
}
| #! /usr/bin/env node
const args = require('./args') // TODO
const path = require('path')
const { sendQuery, readFile, checkPath, REPL } = require('./src/api')
const { pullHeaders, colorResponse } = require('./src/util')
args
.option('header', 'HTTP request header')
.option('baseUrl', 'Base URL for sending HTTP requests')
const flags = args.parse(process.argv)
if (!flags.help && !flags.version) {
let config
let schema
try {
config = require(path.join(process.cwd(), 'package.json'))
} catch (e) {}
try {
schema = require(path.join(process.cwd(), (config && config.schema) || 'schema'))
} catch (e) {
switch (e.code) {
case 'MODULE_NOT_FOUND':
console.log('\nSchema not found. Trying running `gest` with your `schema.js` in the current working directory.\n')
break
default: console.log(e)
}
process.exit()
}
const options = Object.assign({}, config, pullHeaders(flags), { baseURL: flags.baseUrl })
if (args.sub && args.sub.length) {
checkPath(path.join(__dirname, args.sub[0]))
.then(readFile)
.catch(() => args.sub[0])
.then(sendQuery(schema, options))
.then(colorResponse)
.then(console.log)
.catch(console.log)
.then(() => process.exit())
} else {
// REPL
REPL(schema, options)
}
}
| Add error handling to chekcing package.json | Add error handling to chekcing package.json
| JavaScript | mit | mfix22/graphicli | ---
+++
@@ -1,7 +1,6 @@
#! /usr/bin/env node
const args = require('./args') // TODO
const path = require('path')
-const { graphql: config } = require(path.join(process.cwd(), 'package.json'))
const { sendQuery, readFile, checkPath, REPL } = require('./src/api')
const { pullHeaders, colorResponse } = require('./src/util')
@@ -12,11 +11,20 @@
const flags = args.parse(process.argv)
if (!flags.help && !flags.version) {
+ let config
let schema
try {
- schema = require(path.join(process.cwd(), (config && config.schema) || 'schema.js'))
+ config = require(path.join(process.cwd(), 'package.json'))
+ } catch (e) {}
+ try {
+ schema = require(path.join(process.cwd(), (config && config.schema) || 'schema'))
} catch (e) {
- console.log('\nSchema not found. Trying running `gest` with your `schema.js` in the current working directory.\n')
+ switch (e.code) {
+ case 'MODULE_NOT_FOUND':
+ console.log('\nSchema not found. Trying running `gest` with your `schema.js` in the current working directory.\n')
+ break
+ default: console.log(e)
+ }
process.exit()
}
|
c488bae8b97a3a9207d1aa0bbea424c92d493df0 | lib/handlers/providers/index.js | lib/handlers/providers/index.js | "use strict";
var Anyfetch = require('anyfetch');
module.exports.get = function get(req, res, next) {
var anyfetchClient = new Anyfetch(req.accessToken.token);
anyfetchClient.getDocuments({
fields: 'facets.providers'
}, function updated(err, anyfetchRes) {
if(!err) {
var providers = anyfetchRes.body.facets.providers;
res.send({
'count': providers.length
});
}
next(err);
});
};
| "use strict";
var Anyfetch = require('anyfetch');
module.exports.get = function get(req, res, next) {
var anyfetchClient = new Anyfetch(req.accessToken.token);
anyfetchClient.getDocuments({
fields: 'facets.providers'
}, function updated(err, anyfetchRes) {
if(!err) {
var providers = anyfetchRes.body.facets.providers;
res.send({
'count': providers ? providers.length || 0
});
}
next(err);
});
};
| Fix for missing providers length | Fix for missing providers length
| JavaScript | mit | AnyFetch/companion-server | ---
+++
@@ -9,7 +9,7 @@
if(!err) {
var providers = anyfetchRes.body.facets.providers;
res.send({
- 'count': providers.length
+ 'count': providers ? providers.length || 0
});
}
next(err); |
521c7e73b09e71d34d8966f35952cb26ce010bd0 | src/nih_wayfinding/app/scripts/views/routing/directions/row-detail-directive.js | src/nih_wayfinding/app/scripts/views/routing/directions/row-detail-directive.js | (function () {
'use strict';
/* ngInject */
function RowDetail($compile) {
// TODO: Animate the row appearing
var template = [
'<tr ng-show="visible"><td colspan="2">',
'<ul class="list-unstyled">',
'<li ng-repeat="feature in item.directions.features">',
'<img width="20px" height="20px" ng-src="{{ ::feature.img }}" />{{ ::feature.note }}',
'</li>',
'<li ng-repeat="warning in item.directions.warnings">',
'<img width="20px" height="20px" ng-src="{{ ::warning.img }}" />{{ ::warning.note }}',
'</li>',
'</ul>',
'</td></tr>'
].join('');
var module = {
restrict: 'A',
scope: false,
link: link,
};
return module;
function link(scope, element) {
if (!hasDetails(scope.item)) {
return;
}
scope.visible = false;
var row = $compile(template)(scope);
element.after(row);
element.click(function () {
scope.visible = !scope.visible;
scope.$apply();
});
function hasDetails(item) {
var directions = item.directions;
return directions && (directions.features.length || directions.warnings.length);
}
}
}
angular.module('nih.views.routing')
.directive('rowDetail', RowDetail);
})();
| (function () {
'use strict';
/* ngInject */
function RowDetail($compile) {
// TODO: Animate the row appearing
var template = [
'<div class="block" ng-show="visible">',
'<ul class="list-unstyled">',
'<li ng-repeat="feature in item.directions.features">',
'<img width="20px" height="20px" ng-src="{{ ::feature.img }}" /> {{ ::feature.note }}',
'</li>',
'<li ng-repeat="warning in item.directions.warnings">',
'<img width="20px" height="20px" ng-src="{{ ::warning.img }}" /> {{ ::warning.note }}',
'</li>',
'</ul>',
'</div>'
].join('');
var module = {
restrict: 'A',
scope: false,
link: link,
};
return module;
function link(scope, element) {
if (!hasDetails(scope.item)) {
return;
}
scope.visible = false;
var row = $compile(template)(scope);
element.find('td:last-child').append(row);
element.click(function () {
scope.visible = !scope.visible;
scope.$apply();
});
function hasDetails(item) {
var directions = item.directions;
return directions && (directions.features.length || directions.warnings.length);
}
}
}
angular.module('nih.views.routing')
.directive('rowDetail', RowDetail);
})();
| Move step-by-step direction details into element | Move step-by-step direction details into element
| JavaScript | apache-2.0 | azavea/nih-wayfinding,azavea/nih-wayfinding | ---
+++
@@ -5,16 +5,16 @@
function RowDetail($compile) {
// TODO: Animate the row appearing
var template = [
- '<tr ng-show="visible"><td colspan="2">',
+ '<div class="block" ng-show="visible">',
'<ul class="list-unstyled">',
'<li ng-repeat="feature in item.directions.features">',
- '<img width="20px" height="20px" ng-src="{{ ::feature.img }}" />{{ ::feature.note }}',
+ '<img width="20px" height="20px" ng-src="{{ ::feature.img }}" /> {{ ::feature.note }}',
'</li>',
'<li ng-repeat="warning in item.directions.warnings">',
- '<img width="20px" height="20px" ng-src="{{ ::warning.img }}" />{{ ::warning.note }}',
+ '<img width="20px" height="20px" ng-src="{{ ::warning.img }}" /> {{ ::warning.note }}',
'</li>',
'</ul>',
- '</td></tr>'
+ '</div>'
].join('');
var module = {
@@ -34,7 +34,7 @@
scope.visible = false;
var row = $compile(template)(scope);
- element.after(row);
+ element.find('td:last-child').append(row);
element.click(function () {
scope.visible = !scope.visible; |
fea9882a1d77bae8f5710c79af3cd17677e97345 | client/js/helpers/rosetexloader.js | client/js/helpers/rosetexloader.js | 'use strict';
/**
* @note Returns texture immediately, but doesn't load till later.
*/
var ROSETexLoader = {};
ROSETexLoader.load = function(path, callback) {
var tex = DDS.load(path, function() {
if (callback) {
callback();
}
});
tex.minFilter = tex.magFilter = THREE.LinearFilter;
return tex;
};
| 'use strict';
/**
* @note Returns texture immediately, but doesn't load till later.
*/
var ROSETexLoader = {};
ROSETexLoader.load = function(path, callback) {
var tex = DDS.load(path, function() {
if (callback) {
callback();
}
});
tex.minFilter = tex.magFilter = THREE.LinearFilter;
tex.path = path;
return tex;
};
| Set .path in dds textures for debugging. | Set .path in dds textures for debugging.
| JavaScript | agpl-3.0 | brett19/rosebrowser,Jiwan/rosebrowser,exjam/rosebrowser,exjam/rosebrowser,Jiwan/rosebrowser,brett19/rosebrowser | ---
+++
@@ -11,5 +11,6 @@
}
});
tex.minFilter = tex.magFilter = THREE.LinearFilter;
+ tex.path = path;
return tex;
}; |
4505a470372a5d4df66d6945039000a3da9f0358 | 006.js | 006.js | var _ = require('lazy.js');
var square = function square (n) {
return Math.pow(n, 2);
};
var sum = function sum (n, m) {
return n + m;
};
var sumOfSquares = function sumOfSquares (range) {
return range.map(square).reduce(sum);
};
var squareOfSum = function squareOfSum (range) {
return square(range.reduce(sum), 2);
};
var difference = function difference (range) {
return squareOfSum(range) - sumOfSquares(range);
};
console.log(difference(_.range(1,11)));
console.log(difference(_.range(1,101)));
| Add initial global JS solution for problem 6 | Add initial global JS solution for problem 6
| JavaScript | mit | jrhorn424/euler,jrhorn424/euler | ---
+++
@@ -0,0 +1,24 @@
+var _ = require('lazy.js');
+
+var square = function square (n) {
+ return Math.pow(n, 2);
+};
+
+var sum = function sum (n, m) {
+ return n + m;
+};
+
+var sumOfSquares = function sumOfSquares (range) {
+ return range.map(square).reduce(sum);
+};
+
+var squareOfSum = function squareOfSum (range) {
+ return square(range.reduce(sum), 2);
+};
+
+var difference = function difference (range) {
+ return squareOfSum(range) - sumOfSquares(range);
+};
+
+console.log(difference(_.range(1,11)));
+console.log(difference(_.range(1,101))); | |
659234ef7c0c6efd14be14997ddd7d2e97a3d385 | closure/goog/disposable/idisposable.js | closure/goog/disposable/idisposable.js | // Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// 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.
/**
* @fileoverview Definition of the disposable interface. A disposable object
* has a dispose method to to clean up references and resources.
* @author nnaze@google.com (Nathan Naze)
*/
goog.provide('goog.disposable.IDisposable');
/**
* Interface for a disposable object. If a instance requires cleanup
* (references COM objects, DOM notes, or other disposable objects), it should
* implement this interface (it may subclass goog.Disposable).
* @interface
*/
goog.disposable.IDisposable = function() {};
/**
* Disposes of the object and its resources.
* @return {void} Nothing.
*/
goog.disposable.IDisposable.prototype.dispose = goog.abstractMethod;
/**
* @return {boolean} Whether the object has been disposed of.
*/
goog.disposable.IDisposable.prototype.isDisposed = goog.abstractMethod;
| // Copyright 2011 The Closure Library Authors. All Rights Reserved.
//
// 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.
/**
* @fileoverview Definition of the disposable interface. A disposable object
* has a dispose method to to clean up references and resources.
* @author nnaze@google.com (Nathan Naze)
*/
goog.provide('goog.disposable.IDisposable');
/**
* Interface for a disposable object. If a instance requires cleanup
* (references COM objects, DOM nodes, or other disposable objects), it should
* implement this interface (it may subclass goog.Disposable).
* @record
*/
goog.disposable.IDisposable = function() {};
/**
* Disposes of the object and its resources.
* @return {void} Nothing.
*/
goog.disposable.IDisposable.prototype.dispose = goog.abstractMethod;
/**
* @return {boolean} Whether the object has been disposed of.
*/
goog.disposable.IDisposable.prototype.isDisposed = goog.abstractMethod;
| Allow object literals to be IDisposable | Allow object literals to be IDisposable
RELNOTES[INC]: goog.disposable.IDisposable is now @record
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=129902477
| JavaScript | apache-2.0 | redforks/closure-library,redforks/closure-library,redforks/closure-library,redforks/closure-library | ---
+++
@@ -25,9 +25,9 @@
/**
* Interface for a disposable object. If a instance requires cleanup
- * (references COM objects, DOM notes, or other disposable objects), it should
+ * (references COM objects, DOM nodes, or other disposable objects), it should
* implement this interface (it may subclass goog.Disposable).
- * @interface
+ * @record
*/
goog.disposable.IDisposable = function() {};
|
bb6c53c86c6f9aabf70fd3cd70a885f2083ed790 | app.js | app.js | 'use strict';
/**
* Imports.
*/
const express = require('express');
/**
* Initialize Express.
*/
const app = express();
// Setup locals variable in config/index.js.
app.locals = require('./config');
// Configure express app based on local configuration.
app.set('env', app.locals.express.env);
/**
* Routing.
*/
// Root:
app.get('/', (req, res) => {
res.send('Hi, I\'m Blink!');
});
// Api root:
app.use('/api', require('./api'));
// API Version 1
app.use('/api/v1', require('./api/v1'));
/**
* Listen.
*/
app.listen(app.locals.express.port, () => {
app.locals.logger.info(`Blink is listening on port:${app.locals.express.port} env:${app.get('env')}`);
});
module.exports = app;
| 'use strict';
/**
* Imports.
*/
const express = require('express');
const http = require('http');
/**
* Initialize Express.
*/
const app = express();
// Setup locals variable in config/index.js.
app.locals = require('./config');
// Configure express app based on local configuration.
app.set('env', app.locals.express.env);
/**
* Routing.
*/
// Root:
app.get('/', (req, res) => {
res.send('Hi, I\'m Blink!');
});
// Api root:
app.use('/api', require('./api'));
// API Version 1
app.use('/api/v1', require('./api/v1'));
/**
* Create server.
*/
const server = http.createServer(app);
server.listen(app.locals.express.port, () => {
const address = server.address();
app.locals.logger.info(`Blink is listening on port:${address.port} env:${app.locals.express.env}`);
});
module.exports = app;
| Print actual port number in server init log | Print actual port number in server init log
| JavaScript | mit | DoSomething/blink,DoSomething/blink | ---
+++
@@ -4,6 +4,7 @@
* Imports.
*/
const express = require('express');
+const http = require('http');
/**
* Initialize Express.
@@ -31,10 +32,12 @@
app.use('/api/v1', require('./api/v1'));
/**
- * Listen.
+ * Create server.
*/
-app.listen(app.locals.express.port, () => {
- app.locals.logger.info(`Blink is listening on port:${app.locals.express.port} env:${app.get('env')}`);
+const server = http.createServer(app);
+server.listen(app.locals.express.port, () => {
+ const address = server.address();
+ app.locals.logger.info(`Blink is listening on port:${address.port} env:${app.locals.express.env}`);
});
module.exports = app; |
650756852a9ff4011afe2e662495066fdce079e8 | app.js | app.js | #!/usr/bin/env node
/*
* SQL API loader
* ===============
*
* node app [environment]
*
* environments: [development, test, production]
*
*/
var _ = require('underscore');
// sanity check arguments
var ENV = process.argv[2];
if (ENV != 'development' && ENV != 'production' && ENV != 'test') {
console.error("\n./app [environment]");
console.error("environments: [development, test, production]");
process.exit(1);
}
// set Node.js app settings and boot
global.settings = require(__dirname + '/config/settings');
var env = require(__dirname + '/config/environments/' + ENV);
_.extend(global.settings, env);
// kick off controller
var app = require(global.settings.app_root + '/app/controllers/app');
app.listen(global.settings.node_port, global.settings.node_host, function() {
console.log("CartoDB SQL API listening on " + global.settings.node_host + ":" + global.settings.node_port);
});
| #!/usr/bin/env node
/*
* SQL API loader
* ===============
*
* node app [environment]
*
* environments: [development, test, production]
*
*/
var _ = require('underscore');
// sanity check arguments
var ENV = process.argv[2];
if (ENV != 'development' && ENV != 'production' && ENV != 'test') {
console.error("\n./app [environment]");
console.error("environments: [development, test, production]");
process.exit(1);
}
// set Node.js app settings and boot
global.settings = require(__dirname + '/config/settings');
var env = require(__dirname + '/config/environments/' + ENV);
_.extend(global.settings, env);
// kick off controller
if ( ! global.settings.base_url ) global.settings.base_url = '/api/*';
var app = require(global.settings.app_root + '/app/controllers/app');
app.listen(global.settings.node_port, global.settings.node_host, function() {
console.log("CartoDB SQL API listening on " +
global.settings.node_host + ":" + global.settings.node_port +
" with base_url " + global.settings.base_url);
});
| Use a default base_url when not specified in config file | Use a default base_url when not specified in config file
Also report the base_url at startup
| JavaScript | bsd-3-clause | calvinmetcalf/CartoDB-SQL-API,dbirchak/CartoDB-SQL-API,calvinmetcalf/CartoDB-SQL-API,calvinmetcalf/CartoDB-SQL-API,CartoDB/CartoDB-SQL-API,dbirchak/CartoDB-SQL-API,dbirchak/CartoDB-SQL-API,CartoDB/CartoDB-SQL-API,calvinmetcalf/CartoDB-SQL-API,dbirchak/CartoDB-SQL-API | ---
+++
@@ -25,7 +25,10 @@
_.extend(global.settings, env);
// kick off controller
+if ( ! global.settings.base_url ) global.settings.base_url = '/api/*';
var app = require(global.settings.app_root + '/app/controllers/app');
app.listen(global.settings.node_port, global.settings.node_host, function() {
- console.log("CartoDB SQL API listening on " + global.settings.node_host + ":" + global.settings.node_port);
+ console.log("CartoDB SQL API listening on " +
+ global.settings.node_host + ":" + global.settings.node_port +
+ " with base_url " + global.settings.base_url);
}); |
61eb38969435727ff074b1a95253b577c88c4dfb | common/endpoints/endpoints.service.js | common/endpoints/endpoints.service.js | export default [
'config',
'hs.common.laymanService',
function (config, laymanService) {
const me = this;
function getItemsPerPageConfig(ds) {
return angular.isDefined(ds.paging) &&
angular.isDefined(ds.paging.itemsPerPage)
? ds.paging.itemsPerPage
: config.dsPaging || 20;
}
angular.extend(me, {
endpoints: [
...(config.status_manager_url
? {
type: 'statusmanager',
title: 'Status manager',
url: config.status_manager_url,
}
: []),
...(config.datasources || []).map((ds) => {
return {
url: ds.url,
type: ds.type,
title: ds.title,
datasourcePaging: {
start: 0,
limit: getItemsPerPageConfig(ds),
loaded: false,
},
compositionsPaging: {
start: 0,
limit: getItemsPerPageConfig(ds),
},
paging: {
itemsPerPage: getItemsPerPageConfig(ds),
},
user: ds.user,
liferayProtocol: ds.liferayProtocol,
originalConfiguredUser: ds.user,
getCurrentUserIfNeeded: laymanService.getCurrentUserIfNeeded,
};
}),
],
});
return me;
},
];
| export default [
'config',
'hs.common.laymanService',
function (config, laymanService) {
const me = this;
function getItemsPerPageConfig(ds) {
return angular.isDefined(ds.paging) &&
angular.isDefined(ds.paging.itemsPerPage)
? ds.paging.itemsPerPage
: config.dsPaging || 20;
}
angular.extend(me, {
endpoints: [
...(config.status_manager_url
? [
{
type: 'statusmanager',
title: 'Status manager',
url: config.status_manager_url,
},
]
: []),
...(config.datasources || []).map((ds) => {
return {
url: ds.url,
type: ds.type,
title: ds.title,
datasourcePaging: {
start: 0,
limit: getItemsPerPageConfig(ds),
loaded: false,
},
compositionsPaging: {
start: 0,
limit: getItemsPerPageConfig(ds),
},
paging: {
itemsPerPage: getItemsPerPageConfig(ds),
},
user: ds.user,
liferayProtocol: ds.liferayProtocol,
originalConfiguredUser: ds.user,
getCurrentUserIfNeeded: laymanService.getCurrentUserIfNeeded,
};
}),
],
});
return me;
},
];
| Correct adding of statusmanager to endpoints | Correct adding of statusmanager to endpoints
| JavaScript | mit | hslayers/hslayers-ng,hslayers/hslayers-ng,hslayers/hslayers-ng,hslayers/hslayers-ng | ---
+++
@@ -14,11 +14,13 @@
angular.extend(me, {
endpoints: [
...(config.status_manager_url
- ? {
- type: 'statusmanager',
- title: 'Status manager',
- url: config.status_manager_url,
- }
+ ? [
+ {
+ type: 'statusmanager',
+ title: 'Status manager',
+ url: config.status_manager_url,
+ },
+ ]
: []),
...(config.datasources || []).map((ds) => {
return { |
c320a3d7430bf3242bd9147ba7c6e95b09c45e52 | src/constants.js | src/constants.js | 'use strict';
const isClipMediaRef = {
$not: {
startTime: 0,
endTime: null
}
}
const isClipMediaRefWithTitle = {
$not: {
startTime: 0,
endTime: null
},
$not: {
title: null
},
$not: {
title: ''
}
}
module.exports = {
isClipMediaRef: isClipMediaRef,
isClipMediaRefWithTitle: isClipMediaRefWithTitle
}
| 'use strict';
const isClipMediaRef = {
$not: {
startTime: 0,
endTime: null
}
}
const isClipMediaRefWithTitle = {
$not: {
startTime: 0,
endTime: null
},
$and: {
$not: {
title: null
}
},
$and: {
$not: {
title: ''
}
}
}
module.exports = {
isClipMediaRef: isClipMediaRef,
isClipMediaRefWithTitle: isClipMediaRefWithTitle
}
| Fix broken isClipMediaRefWithTitle for real this time (I think) | Fix broken isClipMediaRefWithTitle for real this time (I think)
| JavaScript | agpl-3.0 | podverse/podverse-web,podverse/podverse-web,podverse/podverse-web,podverse/podverse-web | ---
+++
@@ -12,11 +12,15 @@
startTime: 0,
endTime: null
},
- $not: {
- title: null
+ $and: {
+ $not: {
+ title: null
+ }
},
- $not: {
- title: ''
+ $and: {
+ $not: {
+ title: ''
+ }
}
}
|
c3352aa312e75183b629c3fb7b5948ccf4c2d080 | spec/javascripts/reports/components/modal_open_name_spec.js | spec/javascripts/reports/components/modal_open_name_spec.js | import Vue from 'vue';
import Vuex from 'vuex';
import component from '~/reports/components/modal_open_name.vue';
import { mountComponentWithStore } from 'spec/helpers/vue_mount_component_helper';
describe('Modal open name', () => {
const Component = Vue.extend(component);
let vm;
const store = new Vuex.Store({
actions: {
openModal: () => {},
},
state: {},
mutations: {},
});
beforeEach(() => {
vm = mountComponentWithStore(Component, {
store,
props: {
issue: {
title: 'Issue',
},
status: 'failed',
},
});
});
afterEach(() => {
vm.$destroy();
});
it('renders the issue name', () => {
expect(vm.$el.textContent.trim()).toEqual('Issue');
});
it('calls openModal actions when button is clicked', () => {
spyOn(vm, 'openModal');
vm.$el.click();
expect(vm.openModal).toHaveBeenCalled();
});
});
| import Vue from 'vue';
import Vuex from 'vuex';
import component from '~/reports/components/modal_open_name.vue';
import { mountComponentWithStore } from 'spec/helpers/vue_mount_component_helper';
Vue.use(Vuex);
describe('Modal open name', () => {
const Component = Vue.extend(component);
let vm;
const store = new Vuex.Store({
actions: {
openModal: () => {},
},
state: {},
mutations: {},
});
beforeEach(() => {
vm = mountComponentWithStore(Component, {
store,
props: {
issue: {
title: 'Issue',
},
status: 'failed',
},
});
});
afterEach(() => {
vm.$destroy();
});
it('renders the issue name', () => {
expect(vm.$el.textContent.trim()).toEqual('Issue');
});
it('calls openModal actions when button is clicked', () => {
spyOn(vm, 'openModal');
vm.$el.click();
expect(vm.openModal).toHaveBeenCalled();
});
});
| Add missing Vue.use in test | Add missing Vue.use in test
| JavaScript | mit | stoplightio/gitlabhq,stoplightio/gitlabhq,mmkassem/gitlabhq,stoplightio/gitlabhq,mmkassem/gitlabhq,mmkassem/gitlabhq,stoplightio/gitlabhq,mmkassem/gitlabhq | ---
+++
@@ -2,6 +2,8 @@
import Vuex from 'vuex';
import component from '~/reports/components/modal_open_name.vue';
import { mountComponentWithStore } from 'spec/helpers/vue_mount_component_helper';
+
+Vue.use(Vuex);
describe('Modal open name', () => {
const Component = Vue.extend(component); |
0aeefb8fb3b8e58f7312323aab397f622b251013 | tests/local_protractor.conf.js | tests/local_protractor.conf.js | exports.config = {
// Locally, we should just use the default standalone Selenium server
// In Travis, we set up the Selenium serving via Sauce Labs
// Tests to run
specs: [
'./protractor/**/*.spec.js'
],
// Capabilities to be passed to the webdriver instance
// For a full list of available capabilities, see https://code.google.com/p/selenium/wiki/DesiredCapabilities
capabilities: {
'browserName': 'firefox',
},
// Calls to protractor.get() with relative paths will be prepended with the baseUrl
baseUrl: 'http://localhost:3030/tests/protractor/',
// Selector for the element housing the angular app
rootElement: 'body',
// Options to be passed to minijasminenode
jasmineNodeOpts: {
// onComplete will be called just before the driver quits.
onComplete: null,
// If true, display spec names.
isVerbose: true,
// If true, print colors to the terminal.
showColors: true,
// If true, include stack traces in failures.
includeStackTrace: true,
// Default time to wait in ms before a test fails.
defaultTimeoutInterval: 20000
}
};
| exports.config = {
// Locally, we should just use the default standalone Selenium server
// In Travis, we set up the Selenium serving via Sauce Labs
// Tests to run
specs: [
'./protractor/**/*.spec.js'
],
// Capabilities to be passed to the webdriver instance
// For a full list of available capabilities, see https://code.google.com/p/selenium/wiki/DesiredCapabilities
capabilities: {
'browserName': 'chrome',
},
// Calls to protractor.get() with relative paths will be prepended with the baseUrl
baseUrl: 'http://localhost:3030/tests/protractor/',
// Selector for the element housing the angular app
rootElement: 'body',
// Options to be passed to minijasminenode
jasmineNodeOpts: {
// onComplete will be called just before the driver quits.
onComplete: null,
// If true, display spec names.
isVerbose: true,
// If true, print colors to the terminal.
showColors: true,
// If true, include stack traces in failures.
includeStackTrace: true,
// Default time to wait in ms before a test fails.
defaultTimeoutInterval: 20000
}
};
| Change e2e tests back to running on Chrome | Change e2e tests back to running on Chrome
| JavaScript | mit | denisKaranja/angularfire,douglascorrea/angularfire,jamestalmage/angularfire,fbentz/angularfire,fbentz/angularfire,FirebaseExtended/angularfire,FirebaseExtended/angularfire,nbr1ninrsan2/angularfire,bpietravalle/angularfire,FirebaseExtended/angularfire,yoda-yoda/angularfire,cesarmarinhorj/angularfire,bpietravalle/angularfire,yoda-yoda/angularfire,itxd/angularfire,cesarmarinhorj/angularfire,yoda-yoda/angularfire,cesarmarinhorj/angularfire,fbentz/angularfire,nbr1ninrsan2/angularfire,nbr1ninrsan2/angularfire,bpietravalle/angularfire,denisKaranja/angularfire,itxd/angularfire,douglascorrea/angularfire,jamestalmage/angularfire,douglascorrea/angularfire,itxd/angularfire,denisKaranja/angularfire,jamestalmage/angularfire | ---
+++
@@ -10,7 +10,7 @@
// Capabilities to be passed to the webdriver instance
// For a full list of available capabilities, see https://code.google.com/p/selenium/wiki/DesiredCapabilities
capabilities: {
- 'browserName': 'firefox',
+ 'browserName': 'chrome',
},
// Calls to protractor.get() with relative paths will be prepended with the baseUrl |
06cea187980cd50fd4699e689b4191ffb2a4d9fc | src/modules/__specs__/AppView.spec.js | src/modules/__specs__/AppView.spec.js | /*eslint-disable max-nested-callbacks*/
import React from 'react';
import {shallow} from 'enzyme';
import {describe, it} from 'mocha';
import {expect} from 'chai';
import Spinner from 'react-native-gifted-spinner';
import AppView from '../AppView';
describe('<AppView />', () => {
describe('isReady', () => {
it('should render a <Spinner /> if not ready', () => {
const fn = () => {};
const wrapper = shallow(
<AppView
isReady={false}
isLoggedIn={false}
dispatch={fn}
/>
);
expect(wrapper.find(Spinner)).to.have.lengthOf(1);
});
it('should not render a <Spinner /> if ready', () => {
const fn = () => {};
const wrapper = shallow(
<AppView
isReady={true}
isLoggedIn={false}
dispatch={fn}
/>
);
expect(wrapper.find(Spinner)).to.have.lengthOf(0);
});
});
});
| /*eslint-disable max-nested-callbacks*/
import React from 'react';
import {shallow} from 'enzyme';
import {describe, it} from 'mocha';
import {expect} from 'chai';
import {ActivityIndicator} from 'react-native';
import AppView from '../AppView';
describe('<AppView />', () => {
describe('isReady', () => {
it('should render a <ActivityIndicator /> if not ready', () => {
const fn = () => {};
const wrapper = shallow(
<AppView
isReady={false}
isLoggedIn={false}
dispatch={fn}
/>
);
expect(wrapper.find(ActivityIndicator)).to.have.lengthOf(1);
});
it('should not render a <ActivityIndicator /> if ready', () => {
const fn = () => {};
const wrapper = shallow(
<AppView
isReady={true}
isLoggedIn={false}
dispatch={fn}
/>
);
expect(wrapper.find(ActivityIndicator)).to.have.lengthOf(0);
});
});
});
| Fix AppView test to render activity indicator | Fix AppView test to render activity indicator
| JavaScript | mit | WWCJSBoulder/DWClient,justinhaaheim/empower-app,BrianJVarley/simple-offset-pro,salokas/barcodebar,ming-cho/react-native-demo,AcademyPgh/Y1S2-ReplayFX-Schedule,keyifadami/CrewCrossCheck,mandlamag/ESXApp,ming-cho/react-native-demo,yogakurniawan/phoney-mobile,mandlamag/ESXApp,apoi/kahvi,WWCJSBoulder/DWClient,chriswohlfarth/mojifi-app,justinhaaheim/empower-app,chriswohlfarth/mojifi-app,mandlamag/ESXApp,keyifadami/CrewCrossCheck,ericmasiello/TrailReporter,justinhaaheim/empower-app,dominictracey/hangboard,3vangelos/reshout,3vangelos/reshout,AcademyPgh/Y1S2-ReplayFX-Schedule,justinhaaheim/empower-app,dominictracey/hangboard,3vangelos/reshout,fabriziomoscon/pepperoni-app-kit,yogakurniawan/phoney-mobile,keyifadami/CrewCrossCheck,salokas/barcodebar,3vangelos/reshout,AcademyPgh/Y1S2-ReplayFX-Schedule,salokas/barcodebar,keyifadami/CrewCrossCheck,apoi/kahvi,BrianJVarley/simple-offset-pro,keyifadami/CrewCrossCheck,Florenz23/sangoo_04,BrianJVarley/simple-offset-pro,fabriziomoscon/pepperoni-app-kit,Florenz23/sangoo_04,mandlamag/ESXApp,ericmasiello/TrailReporter,ming-cho/react-native-demo,Florenz23/sangoo_04,chriswohlfarth/mojifi-app,yogakurniawan/phoney-mobile,mandlamag/ESXApp,fabriziomoscon/pepperoni-app-kit,apoi/kahvi,fabriziomoscon/pepperoni-app-kit,apoi/kahvi,dominictracey/hangboard,ericmasiello/TrailReporter,chriswohlfarth/mojifi-app,BrianJVarley/simple-offset-pro,ming-cho/react-native-demo,dominictracey/hangboard,Florenz23/sangoo_04,yogakurniawan/phoney-mobile,ericmasiello/TrailReporter,AcademyPgh/Y1S2-ReplayFX-Schedule,3vangelos/reshout,chriswohlfarth/mojifi-app,ming-cho/react-native-demo,WWCJSBoulder/DWClient,justinhaaheim/empower-app,apoi/kahvi,salokas/barcodebar,dominictracey/hangboard,ericmasiello/TrailReporter,fabriziomoscon/pepperoni-app-kit,AcademyPgh/Y1S2-ReplayFX-Schedule,WWCJSBoulder/DWClient | ---
+++
@@ -4,13 +4,12 @@
import {shallow} from 'enzyme';
import {describe, it} from 'mocha';
import {expect} from 'chai';
-import Spinner from 'react-native-gifted-spinner';
-
+import {ActivityIndicator} from 'react-native';
import AppView from '../AppView';
describe('<AppView />', () => {
describe('isReady', () => {
- it('should render a <Spinner /> if not ready', () => {
+ it('should render a <ActivityIndicator /> if not ready', () => {
const fn = () => {};
const wrapper = shallow(
<AppView
@@ -20,10 +19,10 @@
/>
);
- expect(wrapper.find(Spinner)).to.have.lengthOf(1);
+ expect(wrapper.find(ActivityIndicator)).to.have.lengthOf(1);
});
- it('should not render a <Spinner /> if ready', () => {
+ it('should not render a <ActivityIndicator /> if ready', () => {
const fn = () => {};
const wrapper = shallow(
<AppView
@@ -33,7 +32,7 @@
/>
);
- expect(wrapper.find(Spinner)).to.have.lengthOf(0);
+ expect(wrapper.find(ActivityIndicator)).to.have.lengthOf(0);
});
});
}); |
e986ee873dd62c0c333aa7530a1753cef09af39f | chartflo/templates/dashboards/app.js | chartflo/templates/dashboards/app.js | function loadDashboard(page, dashboard) {
var url = "/dashboards/page/"+dashboard+"/"+page+"/";
console.log("Getting", url);
var spinner = '<div class="text-center" style="width:100%;margin-top:5em;opacity:0.6">';
spinner = spinner + '<i class="fa fa-spinner fa-spin fa-5x fa-fw"></i>\n</div>';
$("#content").html(spinner);
axios.get(url).then(function (response) {
$('#content').html(response.data);
}).catch(function (error) {
console.log(error);
});
$(".sparkline-embeded").each(function () {
var $this = $(this);
$this.sparkline('html', $this.data());
});
}
$(document).ready(function () {
loadDashboard("index", "{{ dashboard }}");
$(".sparkline").each(function () {
var $this = $(this);
$this.sparkline('html', $this.data());
});
}); | function loadDashboard(page, dashboard, destination) {
var url = "/dashboards/page/"+dashboard+"/"+page+"/";
console.log("Getting", url);
var spinner = '<div class="text-center" style="width:100%;margin-top:5em;opacity:0.6">';
spinner = spinner + '<i class="fa fa-spinner fa-spin fa-5x fa-fw"></i>\n</div>';
if ( destination === undefined) {
destination = "#content"
}
$(destination).html(spinner);
axios.get(url).then(function (response) {
$(destination).html(response.data);
}).catch(function (error) {
console.log(error);
});
$(".sparkline-embeded").each(function () {
//console.log("LOAD");
var $this = $(this);
$this.sparkline('html', $this.data());
console.log($this.data())
});
}
$(document).ready(function () {
loadDashboard("index", "{{ dashboard }}");
$(".sparkline").each(function () {
//console.log("INIT");
var $this = $(this);
$this.sparkline('html', $this.data());
console.log($this.data())
});
}); | Improve the js pages loading function | Improve the js pages loading function
| JavaScript | mit | synw/django-chartflo,synw/django-chartflo,synw/django-chartflo | ---
+++
@@ -1,24 +1,31 @@
-function loadDashboard(page, dashboard) {
+function loadDashboard(page, dashboard, destination) {
var url = "/dashboards/page/"+dashboard+"/"+page+"/";
console.log("Getting", url);
var spinner = '<div class="text-center" style="width:100%;margin-top:5em;opacity:0.6">';
spinner = spinner + '<i class="fa fa-spinner fa-spin fa-5x fa-fw"></i>\n</div>';
- $("#content").html(spinner);
+ if ( destination === undefined) {
+ destination = "#content"
+ }
+ $(destination).html(spinner);
axios.get(url).then(function (response) {
- $('#content').html(response.data);
+ $(destination).html(response.data);
}).catch(function (error) {
console.log(error);
});
$(".sparkline-embeded").each(function () {
- var $this = $(this);
- $this.sparkline('html', $this.data());
+ //console.log("LOAD");
+ var $this = $(this);
+ $this.sparkline('html', $this.data());
+ console.log($this.data())
});
}
$(document).ready(function () {
loadDashboard("index", "{{ dashboard }}");
$(".sparkline").each(function () {
- var $this = $(this);
- $this.sparkline('html', $this.data());
+ //console.log("INIT");
+ var $this = $(this);
+ $this.sparkline('html', $this.data());
+ console.log($this.data())
});
}); |
5deb018244d0a06f6d3feccb21b1c0e26864321d | app/controllers/application.js | app/controllers/application.js | import Em from 'ember';
import { task, timeout } from 'ember-concurrency';
const { computed } = Em;
var applicationController = Em.Controller.extend({
activeNote: null,
hideSidePanel: false,
init: function() {
Em.run.scheduleOnce('afterRender', () => {
$('body div').first().addClass('app-container');
});
},
// data
sortedNotes: computed('model.[]', 'model.@each.updatedAt', function() {
return this.get('model').sortBy('updatedAt', 'createdAt').reverseObjects();
}),
deleteNoteTask: task(function *(note) {
yield timeout(150);
this.get('model').removeObject(note);
if (Em.isEmpty(this.get('model'))) {
this.send('createNote');
} else {
this.send('showNote', this.get('sortedNotes.firstObject'));
}
yield note.destroyRecord();
}).drop(),
actions: {
createNote: function() {
this.transitionToRoute('new');
},
deleteNote: function(note) {
this.get('deleteNoteTask').perform(note);
// this.get('model').removeObject(note);
// if (Em.isEmpty(this.get('model'))) {
// this.send('createNote');
// } else {
// this.send('showNote', this.get('model.lastObject'));
// }
// note.destroyRecord();
},
// deleteAll: function() {
// this.get('notes').forEach(function(note) {
// note.destroyRecord();
// });
// },
toggleSidePanelHidden: function() {
this.toggleProperty('hideSidePanel');
}
}
});
export default applicationController;
| import Em from 'ember';
import { task, timeout } from 'ember-concurrency';
const { computed } = Em;
var applicationController = Em.Controller.extend({
activeNote: null,
hideSidePanel: false,
init: function() {
Em.run.scheduleOnce('afterRender', () => {
$('body div').first().addClass('app-container');
});
},
// data
sortedNotes: computed('model.[]', 'model.@each.updatedAt', function() {
return this.get('model').sortBy('updatedAt', 'createdAt').reverseObjects();
}),
deleteNote: task(function *(note) {
yield timeout(150);
this.get('model').removeObject(note);
if (Em.isEmpty(this.get('model'))) {
this.send('createNote');
} else {
this.send('showNote', this.get('sortedNotes.firstObject'));
}
yield note.destroyRecord();
}).drop(),
actions: {
createNote() {
this.transitionToRoute('new');
},
deleteNote(note) {
this.get('deleteNote').perform(note);
},
signOut() {
this.get('session').close().then(()=> {
this.transitionToRoute('signin');
});
},
toggleSidePanelHidden() {
this.toggleProperty('hideSidePanel');
}
}
});
export default applicationController;
| Include a `signOut` action. Make `deleteNote` an e-c task. ES6-ify some function syntax. | Include a `signOut` action. Make `deleteNote` an e-c task. ES6-ify some function syntax.
| JavaScript | mit | ddoria921/Notes,ddoria921/Notes | ---
+++
@@ -19,7 +19,7 @@
return this.get('model').sortBy('updatedAt', 'createdAt').reverseObjects();
}),
- deleteNoteTask: task(function *(note) {
+ deleteNote: task(function *(note) {
yield timeout(150);
this.get('model').removeObject(note);
if (Em.isEmpty(this.get('model'))) {
@@ -31,28 +31,21 @@
}).drop(),
actions: {
- createNote: function() {
+ createNote() {
this.transitionToRoute('new');
},
- deleteNote: function(note) {
- this.get('deleteNoteTask').perform(note);
- // this.get('model').removeObject(note);
- // if (Em.isEmpty(this.get('model'))) {
- // this.send('createNote');
- // } else {
- // this.send('showNote', this.get('model.lastObject'));
- // }
- // note.destroyRecord();
+ deleteNote(note) {
+ this.get('deleteNote').perform(note);
},
- // deleteAll: function() {
- // this.get('notes').forEach(function(note) {
- // note.destroyRecord();
- // });
- // },
+ signOut() {
+ this.get('session').close().then(()=> {
+ this.transitionToRoute('signin');
+ });
+ },
- toggleSidePanelHidden: function() {
+ toggleSidePanelHidden() {
this.toggleProperty('hideSidePanel');
}
} |
82544193853cd0988ee2536d134d1fa451d8fbb4 | day3/solution.js | day3/solution.js | let input = require("fs").readFileSync("./data").toString();
let santaPosition = [0, 0];
let roboSantaPosition = [0, 0];
let uniqueSantaPositions = [];
function updateUniquePositions() {
if (uniqueSantaPositions.indexOf(santaPosition.toString()) === -1) {
uniqueSantaPositions.push(santaPosition.toString());
}
if (uniqueSantaPositions.indexOf(roboSantaPosition.toString()) === -1) {
uniqueSantaPositions.push(roboSantaPosition.toString());
}
}
updateUniquePositions();
input.split("").forEach((char, index) => {
let currentSantaPos = index % 2 === 0 ? santaPosition : roboSantaPosition; // Part 2
if (char === "^") {
currentSantaPos[1]++;
} else if (char === "v") {
currentSantaPos[1]--;
} else if (char === ">") {
currentSantaPos[0]++;
} else if (char === "<") {
currentSantaPos[0]--;
}
updateUniquePositions();
});
console.log("Houses with at least one present:", uniqueSantaPositions.length);
| let input = require("fs").readFileSync("./data").toString();
let santaPosition = [0, 0];
let roboSantaPosition = [0, 0];
let uniqueSantaPositions = [];
function updateUniquePositions() {
let santaPositionStr = santaPosition.toString();
let roboSantaPositionStr = roboSantaPosition.toString();
if (uniqueSantaPositions.indexOf(santaPositionStr) === -1) {
uniqueSantaPositions.push(santaPositionStr);
}
if (uniqueSantaPositions.indexOf(roboSantaPositionStr) === -1) {
uniqueSantaPositions.push(roboSantaPositionStr);
}
}
updateUniquePositions();
input.split("").forEach((char, index) => {
let currentSantaPos = index % 2 === 0 ? santaPosition : roboSantaPosition; // Part 2
if (char === "^") {
currentSantaPos[1]++;
} else if (char === "v") {
currentSantaPos[1]--;
} else if (char === ">") {
currentSantaPos[0]++;
} else if (char === "<") {
currentSantaPos[0]--;
}
updateUniquePositions();
});
console.log("Houses with at least one present:", uniqueSantaPositions.length);
| Move toString conversions to only happen once. | Move toString conversions to only happen once.
| JavaScript | mit | Mark-Simulacrum/advent-of-code-2015,Mark-Simulacrum/advent-of-code-2015,Mark-Simulacrum/advent-of-code-2015,Mark-Simulacrum/advent-of-code-2015 | ---
+++
@@ -6,12 +6,15 @@
let uniqueSantaPositions = [];
function updateUniquePositions() {
- if (uniqueSantaPositions.indexOf(santaPosition.toString()) === -1) {
- uniqueSantaPositions.push(santaPosition.toString());
+ let santaPositionStr = santaPosition.toString();
+ let roboSantaPositionStr = roboSantaPosition.toString();
+
+ if (uniqueSantaPositions.indexOf(santaPositionStr) === -1) {
+ uniqueSantaPositions.push(santaPositionStr);
}
- if (uniqueSantaPositions.indexOf(roboSantaPosition.toString()) === -1) {
- uniqueSantaPositions.push(roboSantaPosition.toString());
+ if (uniqueSantaPositions.indexOf(roboSantaPositionStr) === -1) {
+ uniqueSantaPositions.push(roboSantaPositionStr);
}
}
|
1856ce1b2b89d3d708f38e7bde323446864646c9 | js/game.js | js/game.js | class Dice extends React.Component {
constructor() {
super();
this.state = {
value: '',
words: this.parseInput(decodeURIComponent(location.search.substring(5))),
div: document.createElement("div")
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
parseInput(input) {
return input.split('\n\r').map(x => x.split('\n').filter(Boolean));
}
handleChange(event) {
this.setState({value: event.target.value});
}
createChild(text) {
var p = document.createElement("p");
p.appendChild(document.createTextNode(text));
return p;
}
handleSubmit() {
var div = this.state.div;
while (div.hasChildNodes()) {
div.removeChild(div.lastChild);
}
var words = this.state.words;
for(var i = 0; i < words.length; i++) {
var random = words[i][Math.floor(Math.random()*(words.length-1))];
div.appendChild(this.createChild(random));
}
document.body.appendChild(div);
}
render() {
return (
<div>
<input type="button" value="Throw dice" onClick={this.handleSubmit}/>
</div>
);
}
}
ReactDOM.render(
<Dice />,
document.getElementById('root')
); | class Dice extends React.Component {
constructor() {
super();
this.state = {
words: this.parseInput(decodeURIComponent(location.search.substring(5))),
div: document.createElement("div")
};
this.handleSubmit = this.handleSubmit.bind(this);
}
parseInput(input) {
return input.split('\n\r').map(x => x.split('\n').filter(Boolean));
}
image(word) {
}
appendWord(text) {
var p = document.createElement("p");
p.appendChild(document.createTextNode(text));
return p;
}
appendImg(src) {
var img = document.createElement("img");
img.className = 'img';
img.src = random;
}
handleSubmit() {
var div = this.state.div;
while (div.hasChildNodes()) {
div.removeChild(div.lastChild);
}
var words = this.state.words;
for(var i = 0; i < words.length; i++) {
var random = words[i][Math.floor(Math.random()*(words.length-1))];
if (this.image(random)) {
div.appendChild(this.appendImg(random));
}
else {
div.appendChild(this.appendWord(random));
}
}
document.body.appendChild(div);
}
render() {
return (
<div>
<input type="button" value="Throw dice" onClick={this.handleSubmit}/>
</div>
);
}
}
ReactDOM.render(
<Dice />,
document.getElementById('root')
); | Add function to append img on the page | Add function to append img on the page
| JavaScript | mit | testlnord/wurfelspiel,testlnord/wurfelspiel,testlnord/wurfelspiel | ---
+++
@@ -2,12 +2,10 @@
constructor() {
super();
this.state = {
- value: '',
words: this.parseInput(decodeURIComponent(location.search.substring(5))),
div: document.createElement("div")
};
- this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
@@ -15,14 +13,20 @@
return input.split('\n\r').map(x => x.split('\n').filter(Boolean));
}
- handleChange(event) {
- this.setState({value: event.target.value});
+ image(word) {
+
}
- createChild(text) {
+ appendWord(text) {
var p = document.createElement("p");
p.appendChild(document.createTextNode(text));
- return p;
+ return p;
+ }
+
+ appendImg(src) {
+ var img = document.createElement("img");
+ img.className = 'img';
+ img.src = random;
}
handleSubmit() {
@@ -33,7 +37,12 @@
var words = this.state.words;
for(var i = 0; i < words.length; i++) {
var random = words[i][Math.floor(Math.random()*(words.length-1))];
- div.appendChild(this.createChild(random));
+ if (this.image(random)) {
+ div.appendChild(this.appendImg(random));
+ }
+ else {
+ div.appendChild(this.appendWord(random));
+ }
}
document.body.appendChild(div);
} |
dbe567f5ce926657ecca94b48ab32666777ecffd | app/js/app.js | app/js/app.js | var app = angular.module('plugD', [
'angularUtils.directives.dirPagination'
]);
app.controller("PluginController",function(){
});
app.directive("pluginList", ['$http',function($http){
return {
restrict:"E",
templateUrl:"partials/plugin-list.html",
controller: function($http){
var self = this;
self.filter = {gmod:"", term:"", perPage:5};
self.sortKey = "name";
self.order ='+';
$http.get('api/plugins.json')
.then(function(data){
self.plugins = data;
}, function(data){
// todo: error
});
},
controllerAs:"plug"
}
}]);
| var app = angular.module('plugD', [
'angularUtils.directives.dirPagination'
]);
app.controller("PluginController",function(){
});
app.directive("pluginList", ['$http',function($http){
return {
restrict:"E",
templateUrl:"partials/plugin-list.html",
controller: function($http){
var self = this;
self.filter = {gmod:"", term:"", perPage:5};
self.sortKey = "name";
self.order ='+';
$http.get('api/plugins.json')
.then(function(data){
self.plugins = data:data;
}, function(data){
// todo: error
});
},
controllerAs:"plug"
}
}]);
| Use inner data array of response | Use inner data array of response
| JavaScript | bsd-2-clause | vivekkrish/jbrowse-registry,GMOD/jbrowse-registry,vivekkrish/jbrowse-registry,vivekkrish/jbrowse-registry,GMOD/jbrowse-registry,GMOD/jbrowse-registry,GMOD/jbrowse-registry | ---
+++
@@ -17,7 +17,7 @@
$http.get('api/plugins.json')
.then(function(data){
- self.plugins = data;
+ self.plugins = data:data;
}, function(data){
// todo: error
}); |
212033e54f0d4729b0ade59aaaad19074b388cc0 | server/main.js | server/main.js | import { Meteor } from 'meteor/meteor';
import { handleMigration } from './migrations';
Meteor.startup(() => {
handleMigration();
}); | import { Meteor } from 'meteor/meteor';
import { handleMigration } from './migrations';
import '/imports/minutes';
import '/imports/meetingseries';
Meteor.startup(() => {
handleMigration();
}); | Fix meteor method not found error by initializing meteor methods on the server | Fix meteor method not found error by initializing meteor methods on the server
| JavaScript | mit | RobNeXX/4minitz,Huggle77/4minitz,RobNeXX/4minitz,RobNeXX/4minitz,4minitz/4minitz,Huggle77/4minitz,4minitz/4minitz,Huggle77/4minitz,4minitz/4minitz | ---
+++
@@ -1,5 +1,8 @@
import { Meteor } from 'meteor/meteor';
import { handleMigration } from './migrations';
+
+import '/imports/minutes';
+import '/imports/meetingseries';
Meteor.startup(() => {
handleMigration(); |
08517b8cc97af75922ad40704fc333bdd0cba5fa | test/src/main.js | test/src/main.js | requirejs.config({
baseUrl: 'test',
paths: {
pvcf: '../../lib/pvcf',
when: '../test/vendor/when/when',
node: '../test/vendor/when/node',
callbacks: '../test/vendor/when/callbacks'
}
});
requirejs(['pvcf'], function run(pvcf) {
var definitions = pvcf.definitions;
var ViewDefinition = definitions.ViewDefinition;
var TabManager = pvcf.TabManager;
// ### View list. ###
// # Events #
var addEvent = new ViewDefinition('test/templates/addEvent.html', ['test/modules/addEvent.js'], true);
// # Tab manager #
var tabManager = new TabManager();
var startTab = tabManager.openTab();
startTab.openView(addEvent).done(function () {
tabManager.closeTab(startTab);
});
tabManager.getContainerElement().appendChild(startTab.getContainerElement());
document.body.appendChild(tabManager.getContainerElement());
}); | requirejs.config({
baseUrl: 'test',
paths: {
pvcf: '../../lib/pvcf',
when: '../test/vendor/when/when',
node: '../test/vendor/when/node',
callbacks: '../test/vendor/when/callbacks'
}
});
requirejs(['pvcf'], function run(pvcf) {
var definitions = pvcf.definitions;
var ViewDefinition = definitions.ViewDefinition;
var PatternDefinition = definitions.PatternDefinition;
var PatternManager = pvcf.PatternManager;
var TabManager = pvcf.TabManager;
// ### View list ###
// # Events #
var addEvent = new ViewDefinition('test/templates/addEvent.html', ['test/modules/addEvent.js'], true);
var showEvent = new ViewDefinition('test/templates/showEvent.html', ['test/modules/showEvent.js'], true);
// # Pattern manager #
var patternManager = new PatternManager();
// ### Pattern list ###
patternManager.addPattern(new PatternDefinition('event/add', addEvent));
patternManager.addPattern(new PatternDefinition('event/show/:id', showEvent));
// # Tab manager #
var tabManager = new TabManager();
document.body.appendChild(tabManager.getContainerElement());
function main() {
console.log('Appliaction started!');
}
// window.onload actions:
var startTab = tabManager.openTab();
startTab.openView(addEvent).done(function () {
tabManager.closeTab(startTab);
});
tabManager.getContainerElement().appendChild(startTab.getContainerElement());
main();
// window.hashchange actions:
window.addEventListener('hashchange', main);
}); | Extend initialize layer by pattern manager. | Extend initialize layer by pattern manager.
| JavaScript | mit | rootsher/pvcf,rootsher/pvcf,rootsher/pvcf | ---
+++
@@ -10,19 +10,43 @@
requirejs(['pvcf'], function run(pvcf) {
var definitions = pvcf.definitions;
+
var ViewDefinition = definitions.ViewDefinition;
+ var PatternDefinition = definitions.PatternDefinition;
+
+ var PatternManager = pvcf.PatternManager;
var TabManager = pvcf.TabManager;
- // ### View list. ###
+ // ### View list ###
// # Events #
var addEvent = new ViewDefinition('test/templates/addEvent.html', ['test/modules/addEvent.js'], true);
+ var showEvent = new ViewDefinition('test/templates/showEvent.html', ['test/modules/showEvent.js'], true);
+
+
+ // # Pattern manager #
+
+ var patternManager = new PatternManager();
+
+ // ### Pattern list ###
+
+ patternManager.addPattern(new PatternDefinition('event/add', addEvent));
+ patternManager.addPattern(new PatternDefinition('event/show/:id', showEvent));
// # Tab manager #
var tabManager = new TabManager();
+ document.body.appendChild(tabManager.getContainerElement());
+
+
+ function main() {
+ console.log('Appliaction started!');
+ }
+
+
+ // window.onload actions:
var startTab = tabManager.openTab();
startTab.openView(addEvent).done(function () {
@@ -31,5 +55,9 @@
tabManager.getContainerElement().appendChild(startTab.getContainerElement());
- document.body.appendChild(tabManager.getContainerElement());
+ main();
+
+
+ // window.hashchange actions:
+ window.addEventListener('hashchange', main);
}); |
3f90b18a50479eff488ee86fa64a2cc0412716b9 | http/code.js | http/code.js | var runScraper = function() {
$(this).attr('disabled', true)
$(this).addClass('loading').html('Scraping…')
var stocks = $('#stocks_input').val()
var escaped_stocks = scraperwiki.shellEscape(stocks)
scraperwiki.exec('python tool/pandas_finance.py ' + escaped_stocks, getStocksSuccess)
}
var getStocksSuccess = function(data) {
$('#submitBtn').attr('disabled', false)
if (data.indexOf('File "tool/pandas_finance.py"') != -1) {
scraperwiki.alert('Error in pandas_finance.py', data, true)
$('#submitBtn').removeClass('loading').html('<i class="icon-remove"></i> Error')
$('#submitBtn').removeClass('btn-primary').addClass('btn-danger')
setTimeout(function() {
$('#submitBtn').html('Get Stocks')
$('#submitBtn').removeClass('btn-danger').addClass('btn-primary')
}, 4000)
} else {
$('#submitBtn').removeClass('loading').html('<i class="icon-ok"></i> Done')
scraperwiki.tool.redirect("/dataset/" + scraperwiki.box)
}
}
$(function() {
$('#submitBtn').on('click', runScraper)
})
| var param_from_input = function(css) {
return scraperwiki.shellEscape($(css).val())
}
var runScraper = function() {
$(this).attr('disabled', true)
$(this).addClass('loading').html('Scraping…')
var stocks = param_from_input('#stocks_input')
var start_date = param_from_input('#start-date')
var end_date = param_from_input('#end-date')
var command = ['python tool/pandas_finance.py', stocks, start_date, end_date].join(' ')
scraperwiki.exec(command, getStocksSuccess)
}
var getStocksSuccess = function(data) {
$('#submitBtn').attr('disabled', false)
if (data.indexOf('File "tool/pandas_finance.py"') != -1) {
scraperwiki.alert('Error in pandas_finance.py', data, true)
$('#submitBtn').removeClass('loading').html('<i class="icon-remove"></i> Error')
$('#submitBtn').removeClass('btn-primary').addClass('btn-danger')
setTimeout(function() {
$('#submitBtn').html('Get Stocks')
$('#submitBtn').removeClass('btn-danger').addClass('btn-primary')
}, 4000)
} else {
$('#submitBtn').removeClass('loading').html('<i class="icon-ok"></i> Done')
scraperwiki.tool.redirect("/dataset/" + scraperwiki.box)
}
}
$(function() {
$('#submitBtn').on('click', runScraper)
})
| Send command with date range from web UI. | Send command with date range from web UI.
| JavaScript | agpl-3.0 | scraperwiki/stock-tool,scraperwiki/stock-tool | ---
+++
@@ -1,9 +1,16 @@
+var param_from_input = function(css) {
+ return scraperwiki.shellEscape($(css).val())
+}
+
var runScraper = function() {
$(this).attr('disabled', true)
$(this).addClass('loading').html('Scraping…')
- var stocks = $('#stocks_input').val()
- var escaped_stocks = scraperwiki.shellEscape(stocks)
- scraperwiki.exec('python tool/pandas_finance.py ' + escaped_stocks, getStocksSuccess)
+ var stocks = param_from_input('#stocks_input')
+ var start_date = param_from_input('#start-date')
+ var end_date = param_from_input('#end-date')
+
+ var command = ['python tool/pandas_finance.py', stocks, start_date, end_date].join(' ')
+ scraperwiki.exec(command, getStocksSuccess)
}
var getStocksSuccess = function(data) { |
a8cb21f70f884c5b854b54f1de85d993ef687aaf | index.ios.js | index.ios.js | let React = require('react-native');
let {
AppRegistry,
StyleSheet,
Text,
View,
StatusBarIOS
} = React;
class Meowth extends React.Component {
componentWillMount() {
StatusBarIOS.setStyle('light-content');
}
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to Meowth
</Text>
<Text style={styles.instructions}>
Subtitle
</Text>
</View>
);
}
}
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#084265',
},
welcome: {
color: '#F5FCFF',
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#CCCCCC',
marginBottom: 5,
},
});
AppRegistry.registerComponent('meowth', () => Meowth);
| let React = require('react-native');
let FreshSetup = require('./src/FreshSetup');
let {
AppRegistry,
NavigatorIOS,
StatusBarIOS,
StyleSheet,
} = React;
class Meowth extends React.Component {
componentWillMount() {
StatusBarIOS.setStyle('light-content');
}
render() {
return (
<NavigatorIOS
style={styles.container}
initialRoute={{
component: FreshSetup,
title: 'Welcome',
backButtonTitle: 'Back',
passProps: {
pageId: 'welcome',
}
}}
barTintColor="#084265"
tintColor="#ffffff"
titleTextColor="#ffffff"
/>
);
}
}
var styles = StyleSheet.create({
container: {
flex: 1,
},
});
AppRegistry.registerComponent('meowth', () => Meowth);
| Add router navigation Externalise main component to a separate file | Add router navigation
Externalise main component to a separate file
| JavaScript | apache-2.0 | yrezgui/meowth-ios | ---
+++
@@ -1,10 +1,10 @@
let React = require('react-native');
+let FreshSetup = require('./src/FreshSetup');
let {
AppRegistry,
+ NavigatorIOS,
+ StatusBarIOS,
StyleSheet,
- Text,
- View,
- StatusBarIOS
} = React;
class Meowth extends React.Component {
@@ -14,35 +14,27 @@
render() {
return (
- <View style={styles.container}>
- <Text style={styles.welcome}>
- Welcome to Meowth
- </Text>
- <Text style={styles.instructions}>
- Subtitle
- </Text>
- </View>
+ <NavigatorIOS
+ style={styles.container}
+ initialRoute={{
+ component: FreshSetup,
+ title: 'Welcome',
+ backButtonTitle: 'Back',
+ passProps: {
+ pageId: 'welcome',
+ }
+ }}
+ barTintColor="#084265"
+ tintColor="#ffffff"
+ titleTextColor="#ffffff"
+ />
);
}
}
-
+
var styles = StyleSheet.create({
container: {
flex: 1,
- justifyContent: 'center',
- alignItems: 'center',
- backgroundColor: '#084265',
- },
- welcome: {
- color: '#F5FCFF',
- fontSize: 20,
- textAlign: 'center',
- margin: 10,
- },
- instructions: {
- textAlign: 'center',
- color: '#CCCCCC',
- marginBottom: 5,
},
});
|
8f17182642f52022ed2664f7232dac5218302e02 | gateways/paypal_express/script.js | gateways/paypal_express/script.js | (function() {
/***********************************************************/
/* Handle Proceed to Payment
/***********************************************************/
jQuery(function() {
jQuery(document).on('proceedToPayment', function(event, ShoppingCart) {
if (ShoppingCart.gateway != 'paypal_express') {
return;
}
var order = {
products: storejs.get('grav-shoppingcart-basket-data'),
data: storejs.get('grav-shoppingcart-checkout-form-data'),
shipping: storejs.get('grav-shoppingcart-shipping-method'),
payment: 'paypal',
token: storejs.get('grav-shoppingcart-order-token').token,
amount: ShoppingCart.totalOrderPrice.toString(),
gateway: ShoppingCart.gateway
};
jQuery.ajax({
url: ShoppingCart.settings.baseURL + ShoppingCart.settings.urls.save_order_url + '?task=preparePayment',
data: order,
type: 'POST'
})
.success(function(redirectUrl) {
ShoppingCart.clearCart();
window.location = redirectUrl;
})
.error(function() {
alert('Payment not successful. Please contact us.');
});
});
});
})();
| (function() {
/***********************************************************/
/* Handle Proceed to Payment
/***********************************************************/
jQuery(function() {
jQuery(document).on('proceedToPayment', function(event, ShoppingCart) {
if (ShoppingCart.gateway != 'paypal_express') {
return;
}
var order = {
products: storejs.get('grav-shoppingcart-basket-data'),
data: storejs.get('grav-shoppingcart-checkout-form-data'),
shipping: storejs.get('grav-shoppingcart-shipping-method'),
payment: 'paypal',
token: storejs.get('grav-shoppingcart-order-token').token,
amount: ShoppingCart.totalOrderPrice.toString(),
gateway: ShoppingCart.gateway
};
jQuery.ajax({
url: ShoppingCart.settings.baseURL + ShoppingCart.settings.urls.save_order_url + '/task:preparePayment',
data: order,
type: 'POST'
})
.success(function(redirectUrl) {
ShoppingCart.clearCart();
window.location = redirectUrl;
})
.error(function() {
alert('Payment not successful. Please contact us.');
});
});
});
})();
| Use new structure for 2.0 | Use new structure for 2.0
| JavaScript | mit | flaviocopes/grav-plugin-shoppingcart-paypal,flaviocopes/grav-plugin-shoppingcart-paypal | ---
+++
@@ -20,7 +20,7 @@
};
jQuery.ajax({
- url: ShoppingCart.settings.baseURL + ShoppingCart.settings.urls.save_order_url + '?task=preparePayment',
+ url: ShoppingCart.settings.baseURL + ShoppingCart.settings.urls.save_order_url + '/task:preparePayment',
data: order,
type: 'POST'
}) |
495d7a008b1621531cdf39f2d74ac22aee42deac | both/routes/authenticated.js | both/routes/authenticated.js | const authenticatedRoutes = FlowRouter.group({
name: 'authenticated'
});
authenticatedRoutes.route( '/', {
name: 'index',
action() {
BlazeLayout.render( 'default', { yield: 'index' } );
}
});
authenticatedRoutes.route( '/dashboard', {
name: 'dashboard',
action() {
BlazeLayout.render( 'default', { yield: 'dashboard' } );
}
});
authenticatedRoutes.route('/wish-detail/:_id', {
name: 'wishDetail',
action() {
BlazeLayout.render( 'default', { yield: 'wishDetail' } );
}
});
| const authenticatedRoutes = FlowRouter.group({
name: 'authenticated'
});
authenticatedRoutes.route( '/', {
name: 'index',
action() {
BlazeLayout.render( 'default', { yield: 'index' } );
}
});
authenticatedRoutes.route( '/dashboard', {
name: 'dashboard',
action() {
BlazeLayout.render( 'default', { yield: 'dashboard' } );
}
});
authenticatedRoutes.route('/wish/:_id', {
name: 'wishDetail',
action() {
BlazeLayout.render( 'default', { yield: 'wishDetail' } );
}
});
authenticatedRoutes.route('/wish/new', {
name: 'wishNew',
action() {
BlazeLayout.render( 'default', { yield: 'wishNew' } );
}
});
| Refactor wish-detail -> wish, added new route: wishNew. | Refactor wish-detail -> wish, added new route: wishNew.
| JavaScript | mit | lnwKodeDotCom/WeWish,lnwKodeDotCom/WeWish | ---
+++
@@ -16,9 +16,16 @@
}
});
-authenticatedRoutes.route('/wish-detail/:_id', {
+authenticatedRoutes.route('/wish/:_id', {
name: 'wishDetail',
action() {
BlazeLayout.render( 'default', { yield: 'wishDetail' } );
}
});
+
+authenticatedRoutes.route('/wish/new', {
+ name: 'wishNew',
+ action() {
+ BlazeLayout.render( 'default', { yield: 'wishNew' } );
+ }
+}); |
d0c02bdfc462c2f8bc748e44ce3f5d4552fc58db | background.js | background.js | chrome.webRequest.onBeforeRequest.addListener(
(details) => {
chrome.tabs.sendMessage(details.tabId, { content: "message" }, () => {});
const startTime = new Date().getTime();
let randNumber;
while ((new Date().getTime() - startTime) < 5000) {
/* prevent errors on empty fn in loop */
randNumber = Math.random();
}
return { cancel: (randNumber + 1) > 0 };
},
{
urls: [
"*://*.piguiqproxy.com/*",
"*://*.amgload.net/*",
"*://*.dsn-fishki.ru/*",
"*://*.rcdn.pro/*",
"*://*.smcheck.org/*",
]
},
["blocking"]
); | chrome.webRequest.onBeforeRequest.addListener(
(details) => {
chrome.tabs.sendMessage(details.tabId, { content: "message" }, () => {});
const startTime = new Date().getTime();
let randNumber;
while ((new Date().getTime() - startTime) < 5000) {
/* prevent errors on empty fn in loop */
randNumber = Math.random();
}
return { cancel: (randNumber + 1) > 0 };
},
{
urls: [
"*://*.piguiqproxy.com/*",
"*://*.amgload.net/*",
"*://*.dsn-fishki.ru/*",
"*://*.rcdn.pro/*",
"*://*.smcheck.org/*",
"*://*.zmctrack.net/*",
]
},
["blocking"]
); | Add new one site to filter | Add new one site to filter
| JavaScript | mit | VladReshet/no-ads-forever | ---
+++
@@ -19,6 +19,7 @@
"*://*.dsn-fishki.ru/*",
"*://*.rcdn.pro/*",
"*://*.smcheck.org/*",
+ "*://*.zmctrack.net/*",
]
},
["blocking"] |
ff72938231c463ff7d6ac0eb0b38c229f06e6246 | components/Cards/PlaceListingCard/PlaceListingCard.js | components/Cards/PlaceListingCard/PlaceListingCard.js | import React, { PropTypes } from 'react';
import DestinationListingCard from '../DestinationListingCard/DestinationListingCard';
import Badge from '../../Badge/Badge';
import css from './PlaceListingCard.css';
const PlaceListingCard = (props) => {
const {
name,
location,
spaceDetail,
...rest,
} = props;
return (
<DestinationListingCard
name={
<span>
<Badge className={ css.badge } context="primary" hollow>Place</Badge>
{ name }
</span>
}
information={ [location, spaceDetail] }
{ ...rest }
/>
);
};
PlaceListingCard.propTypes = {
name: PropTypes.node,
location: PropTypes.node,
spaceDetail: PropTypes.node,
price: PropTypes.node,
priceUnit: PropTypes.node,
priceFromLabel: PropTypes.node,
};
export default PlaceListingCard; | import React, { PropTypes } from 'react';
import DestinationListingCard from '../DestinationListingCard/DestinationListingCard';
import Badge from '../../Badge/Badge';
import css from './PlaceListingCard.css';
const PlaceListingCard = (props) => {
const {
name,
location,
spaceDetail,
placeBadgeText,
...rest,
} = props;
return (
<DestinationListingCard
name={
<span>
<Badge className={ css.badge } context="primary" hollow>{ placeBadgeText }</Badge>
{ name }
</span>
}
information={ [location, spaceDetail] }
{ ...rest }
/>
);
};
PlaceListingCard.propTypes = {
name: PropTypes.node,
location: PropTypes.node,
spaceDetail: PropTypes.node,
placeBadgeText: PropTypes.string,
price: PropTypes.node,
priceUnit: PropTypes.node,
priceFromLabel: PropTypes.node,
};
PlaceListingCard.defaultProps = {
placeBadgeText: 'Place',
};
export default PlaceListingCard; | Allow place badge text to be localised | Allow place badge text to be localised
| JavaScript | mit | NGMarmaduke/bloom,appearhere/bloom,NGMarmaduke/bloom,rdjpalmer/bloom,appearhere/bloom,rdjpalmer/bloom,appearhere/bloom,rdjpalmer/bloom,NGMarmaduke/bloom | ---
+++
@@ -10,6 +10,7 @@
name,
location,
spaceDetail,
+ placeBadgeText,
...rest,
} = props;
@@ -17,7 +18,7 @@
<DestinationListingCard
name={
<span>
- <Badge className={ css.badge } context="primary" hollow>Place</Badge>
+ <Badge className={ css.badge } context="primary" hollow>{ placeBadgeText }</Badge>
{ name }
</span>
}
@@ -31,9 +32,14 @@
name: PropTypes.node,
location: PropTypes.node,
spaceDetail: PropTypes.node,
+ placeBadgeText: PropTypes.string,
price: PropTypes.node,
priceUnit: PropTypes.node,
priceFromLabel: PropTypes.node,
};
+PlaceListingCard.defaultProps = {
+ placeBadgeText: 'Place',
+};
+
export default PlaceListingCard; |
2eacea5fc28a1edb0cc18319a32267cd6841aa7e | src/handler.js | src/handler.js | 'use strict';
const dirs = {
M1A: 'M1 → Kabaty',
M1B: 'M1 → Młociny',
M2A: 'M2 → Dworzec Wileński',
M2B: 'M2 → Rondo Daszyńskiego',
};
export default {
onGetSchedules: function(res) {
print(
res.schedule.reduce(
getDirections, dirs));
},
};
function print(dirs) {
console.log(
'dirs = ' + JSON.stringify(dirs, null, 2));
}
function getDirections(seq, cur) {
return Object.assign(
seq, ...cur.routes.map(
route => getDirectionsForLine(cur.id, route)));
}
function getDirectionsForLine(id, route) {
return {
[id + route.dir]: id + ' → ' + route.end.name,
};
}
| 'use strict';
const dirs = {
M1A: 'M1 → Kabaty',
M1B: 'M1 → Młociny',
M2A: 'M2 → Dworzec Wileński',
M2B: 'M2 → Rondo Daszyńskiego',
};
export default {
onGetSchedules: function(res) {
print(
res.schedule.reduce(
getDirections, dirs));
},
};
function print(dirs) {
console.log(
'dirs = ' + JSON.stringify(dirs, null, 2) + ';');
}
function getDirections(seq, cur) {
return Object.assign(
seq, ...cur.routes.map(
route => getDirectionsForLine(cur.id, route)));
}
function getDirectionsForLine(id, route) {
return {
[id + route.dir]: id + ' → ' + route.end.name,
};
}
| Add a trailing semicolon to the output | Add a trailing semicolon to the output
| JavaScript | isc | stasm/get-ztm-dirs | ---
+++
@@ -18,7 +18,7 @@
function print(dirs) {
console.log(
- 'dirs = ' + JSON.stringify(dirs, null, 2));
+ 'dirs = ' + JSON.stringify(dirs, null, 2) + ';');
}
function getDirections(seq, cur) { |
b33be185ba08eef310536b73278aec60a1a3c3db | test/mock-xhr.js | test/mock-xhr.js | function MockXHR() {
this.method = null
this.url = null
this.data = null
this.headers = {}
this.readyState = 0
this.status = 0
this.responseText = null
}
MockXHR.responses = {}
MockXHR.prototype.open = function(method, url) {
this.method = method
this.url = url
}
MockXHR.prototype.setRequestHeader = function (name, value) {
this.headers[name] = value
}
var origin = (function() {
var link = document.createElement('a')
link.href = '/'
return link.href
})()
MockXHR.prototype.send = function(data) {
this.data = data
var xhr = this
setTimeout(function() {
var path = xhr.url.replace(origin, '/')
var handle = MockXHR.responses[path]
if (handle) {
handle(xhr)
} else {
console.warn('missing mocked response', path)
}
}, 100);
}
MockXHR.prototype.respond = function(status, body) {
this.readyState = 4
this.status = status
this.responseText = body
var event = {}
this.onload(event)
}
MockXHR.prototype.abort = function() {
// Do nothing.
}
MockXHR.prototype.slow = function() {
var event = {}
this.ontimeout(event)
}
MockXHR.prototype.error = function() {
var event = {}
this.onerror(event)
}
| function MockXHR() {
this.method = null
this.url = null
this.data = null
this.headers = {}
this.readyState = 0
this.status = 0
this.responseText = null
}
MockXHR.responses = {}
MockXHR.prototype.open = function(method, url) {
this.method = method
this.url = url
}
MockXHR.prototype.setRequestHeader = function (name, value) {
this.headers[name] = value
}
var origin = (function() {
var link = document.createElement('a')
link.href = '/'
return link.href
})()
MockXHR.prototype.send = function(data) {
this.data = data
var xhr = this
setTimeout(function() {
var path = xhr.url.replace(origin, '/')
var handle = MockXHR.responses[path]
if (handle) {
handle(xhr)
} else {
throw 'missing mocked response: ' + path
}
}, 100);
}
MockXHR.prototype.respond = function(status, body) {
this.readyState = 4
this.status = status
this.responseText = body
var event = {}
this.onload(event)
}
MockXHR.prototype.abort = function() {
// Do nothing.
}
MockXHR.prototype.slow = function() {
var event = {}
this.ontimeout(event)
}
MockXHR.prototype.error = function() {
var event = {}
this.onerror(event)
}
| Throw instead of console for linter | Throw instead of console for linter
| JavaScript | mit | github/include-fragment-element,github/include-fragment-element | ---
+++
@@ -35,7 +35,7 @@
if (handle) {
handle(xhr)
} else {
- console.warn('missing mocked response', path)
+ throw 'missing mocked response: ' + path
}
}, 100);
} |
dccdf983e68961fd3cd6d87bd207dc7deb02086b | app/assets/javascripts/tinymce/plugins/uploadimage/plugin.js | app/assets/javascripts/tinymce/plugins/uploadimage/plugin.js | (function() {
tinymce.PluginManager.requireLangPack('uploadimage');
tinymce.create('tinymce.plugins.UploadImage', {
UploadImage: function(ed, url) {
var form, iframe, win, editor = ed;
function showDialog() {
this.win = editor.windowManager.open({
width: 350 + parseInt(editor.getLang('uploadimage.delta_width', 0), 10),
height: 180 + parseInt(editor.getLang('uploadimage.delta_height', 0), 10),
url: url + '/dialog.html',
}, {
plugin_url: url
});
}
ed.addButton('uploadimage', {
title: ed.translate('Insert an image from your computer'),
onclick: showDialog,
image: url + '/img/uploadimage.png',
stateSelector: 'img[data-mce-uploadimage]'
});
}
});
tinymce.PluginManager.add('uploadimage', tinymce.plugins.UploadImage);
})();
| (function() {
tinymce.PluginManager.requireLangPack('uploadimage');
tinymce.create('tinymce.plugins.UploadImage', {
UploadImage: function(ed, url) {
var form, iframe, win, editor = ed;
function showDialog() {
this.win = editor.windowManager.open({
width: 350 + parseInt(editor.getLang('uploadimage.delta_width', 0), 10),
height: 180 + parseInt(editor.getLang('uploadimage.delta_height', 0), 10),
url: url + '/dialog.html',
}, {
plugin_url: url
});
}
// Add a button that opens a window
editor.addButton('uploadimage', {
tooltip: ed.translate('Insert an image from your computer'),
icon : 'image',
onclick: showDialog
});
// Adds a menu item to the tools menu
editor.addMenuItem('uploadimage', {
text: ed.translate('Insert an image from your computer'),
icon : 'image',
context: 'insert',
onclick: showDialog
});
}
});
tinymce.PluginManager.add('uploadimage', tinymce.plugins.UploadImage);
})();
| Use the default TinyMCE4 image icon | Use the default TinyMCE4 image icon
| JavaScript | mit | dancingbytes/tinymce-rails-imageupload,CraigJZ/tinymce-rails-imageupload-1,dancingbytes/tinymce-rails-imageupload,PerfectlyNormal/tinymce-rails-imageupload,PerfectlyNormal/tinymce-rails-imageupload,PerfectlyNormal/tinymce-rails-imageupload,ekubal/tinymce-rails-imageupload,ekubal/tinymce-rails-imageupload,ekubal/tinymce-rails-imageupload,CraigJZ/tinymce-rails-imageupload-1,dancingbytes/tinymce-rails-imageupload,CraigJZ/tinymce-rails-imageupload-1 | ---
+++
@@ -13,11 +13,19 @@
plugin_url: url
});
}
- ed.addButton('uploadimage', {
- title: ed.translate('Insert an image from your computer'),
- onclick: showDialog,
- image: url + '/img/uploadimage.png',
- stateSelector: 'img[data-mce-uploadimage]'
+ // Add a button that opens a window
+ editor.addButton('uploadimage', {
+ tooltip: ed.translate('Insert an image from your computer'),
+ icon : 'image',
+ onclick: showDialog
+ });
+
+ // Adds a menu item to the tools menu
+ editor.addMenuItem('uploadimage', {
+ text: ed.translate('Insert an image from your computer'),
+ icon : 'image',
+ context: 'insert',
+ onclick: showDialog
});
}
}); |
1ff8ffaf7cc89670e9aa35745f52a605157bc934 | build/webpack.config.js | build/webpack.config.js | /**
* ownCloud - Music app
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Pauli Järvinen <pauli.jarvinen@gmail.com>
* @copyright 2020 Pauli Järvinen
*
*/
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const ESLintPlugin = require('eslint-webpack-plugin');
module.exports = {
mode: 'production',
entry: {
app: '../js/config/index.js',
files_music_player: '../js/embedded/index.js'
},
output: {
filename: 'webpack.[name].js',
path: path.resolve(__dirname, '../js/public'),
},
resolve: {
alias: {
'angular': path.resolve(__dirname, '../js/vendor/angular'),
'lodash': path.resolve(__dirname, '../js/vendor/lodash'),
}
},
plugins: [
new MiniCssExtractPlugin({filename: 'webpack.app.css'}),
new ESLintPlugin({
files: '../js'
})
],
module: {
rules: [
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
],
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
outputPath: 'img/'
}
}
],
}
],
},
}; | /**
* ownCloud - Music app
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Pauli Järvinen <pauli.jarvinen@gmail.com>
* @copyright 2020 Pauli Järvinen
*
*/
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const ESLintPlugin = require('eslint-webpack-plugin');
module.exports = {
mode: 'production',
devtool: 'source-map',
entry: {
app: '../js/config/index.js',
files_music_player: '../js/embedded/index.js'
},
output: {
filename: 'webpack.[name].js',
path: path.resolve(__dirname, '../js/public'),
},
resolve: {
alias: {
'angular': path.resolve(__dirname, '../js/vendor/angular'),
'lodash': path.resolve(__dirname, '../js/vendor/lodash'),
}
},
plugins: [
new MiniCssExtractPlugin({filename: 'webpack.app.css'}),
new ESLintPlugin({
files: '../js'
})
],
module: {
rules: [
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
],
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
outputPath: 'img/'
}
}
],
}
],
},
}; | Configure webpack so that `eval` is not used in the development mode | Configure webpack so that `eval` is not used in the development mode
Using eval is not allowed by the CSP of newer Nextcloud versions.
| JavaScript | agpl-3.0 | paulijar/music,owncloud/music,owncloud/music,paulijar/music,paulijar/music,owncloud/music,paulijar/music,owncloud/music,owncloud/music,paulijar/music | ---
+++
@@ -15,6 +15,7 @@
module.exports = {
mode: 'production',
+ devtool: 'source-map',
entry: {
app: '../js/config/index.js',
files_music_player: '../js/embedded/index.js' |
d6ed0c7bc74b83ea46887c1afa1da3fd0f7f2481 | client/packages/core-app-worona/src/app/settings-app-extension-worona/selectorCreators/index.js | client/packages/core-app-worona/src/app/settings-app-extension-worona/selectorCreators/index.js | import { find } from 'lodash';
export const getSettings = namespace => state => state.settings.collection[namespace];
export const getSetting = (namespace, setting) => state =>
state.settings.collection[namespace][setting];
export const getSettingById = _id => state => find(state.settings.collection, it => it._id === _id);
| import { find } from 'lodash';
export const getSettings = namespace => state => state.settings.collection[namespace];
export const getSetting = (namespace, setting) => state =>
state.settings.collection[namespace][setting];
export const getSettingsById = _id => state =>
find(state.settings.collection, item => item._id === _id);
export const getSettingById = (_id, setting) => state =>
find(state.settings.collection, item => item._id === _id)[setting];
| Add getSettingById and fix getSettingsById. | Add getSettingById and fix getSettingsById.
| JavaScript | mit | worona/worona-app,worona/worona-app | ---
+++
@@ -1,8 +1,10 @@
import { find } from 'lodash';
export const getSettings = namespace => state => state.settings.collection[namespace];
+export const getSetting = (namespace, setting) => state =>
+ state.settings.collection[namespace][setting];
-export const getSetting = (namespace, setting) => state =>
-state.settings.collection[namespace][setting];
-
-export const getSettingById = _id => state => find(state.settings.collection, it => it._id === _id);
+export const getSettingsById = _id => state =>
+ find(state.settings.collection, item => item._id === _id);
+export const getSettingById = (_id, setting) => state =>
+ find(state.settings.collection, item => item._id === _id)[setting]; |
e3fde9655ce25219938afcb8d6aa056adbf1c545 | src/components/QuestionForm.js | src/components/QuestionForm.js | import React, {Component} from 'react'
import Field from './Field.js'
import Select from './Select.js'
import Input from './Input.js'
import Label from './Label.js'
export default class QuestionForm extends Component {
handleChange = e => {
const {name, value} = e.target
this.props.onChange({
[name]: value
})
}
render() {
const { id, number } = this.props.question
return (
<form onChange={this.handleChange}>
<Field>
<Label htmlFor="type">Question Type</Label>
<Select id="type" name="type" options={['Text', 'Numeric', 'Multiple - Radio', 'Multiple - Checkbox']} />
</Field>
<Field>
<Label htmlFor="id">Question ID</Label>
<Input value={id} id="id" name="id" />
</Field>
<Field>
<Label htmlFor="number">Question Number</Label>
<Input value={number} id="number" name="number" />
</Field>
</form>
)
}
}
| import React, {Component} from 'react'
import Field from './Field.js'
import Select from './Select.js'
import Input from './Input.js'
import Label from './Label.js'
export default class QuestionForm extends Component {
handleChange = e => {
const {name, value} = e.target
this.props.onChange({
[name]: value
})
}
render() {
const { id, number, title } = this.props.question
return (
<form onChange={this.handleChange}>
<Field>
<Label htmlFor="type">Question Type</Label>
<Select id="type" name="type" options={['Text', 'Numeric', 'Multiple - Radio', 'Multiple - Checkbox']} />
</Field>
<Field>
<Label htmlFor="id">Question ID</Label>
<Input value={id} id="id" name="id" />
</Field>
<Field>
<Label htmlFor="number">Question Number</Label>
<Input value={number} id="number" name="number" />
</Field>
<Field>
<Label htmlFor="title">Question Title</Label>
<Input value={title} id="question-title" name="title" />
</Field>
<Field>
<Label htmlFor="guidance-title">Question Guidance Title</Label>
<Input value="" id="question-guidance-title" name="guidance-title" />
</Field>
</form>
)
}
}
| Add question title and guidance title fields. | Add question title and guidance title fields.
| JavaScript | mit | ONSdigital/eq-author,ONSdigital/eq-author,ONSdigital/eq-author | ---
+++
@@ -14,7 +14,7 @@
}
render() {
- const { id, number } = this.props.question
+ const { id, number, title } = this.props.question
return (
<form onChange={this.handleChange}>
<Field>
@@ -29,6 +29,14 @@
<Label htmlFor="number">Question Number</Label>
<Input value={number} id="number" name="number" />
</Field>
+ <Field>
+ <Label htmlFor="title">Question Title</Label>
+ <Input value={title} id="question-title" name="title" />
+ </Field>
+ <Field>
+ <Label htmlFor="guidance-title">Question Guidance Title</Label>
+ <Input value="" id="question-guidance-title" name="guidance-title" />
+ </Field>
</form>
)
} |
b0b117554055bb0452c02955965627b00841ca94 | packages/strapi-plugin-content-type-builder/admin/src/containers/FormModal/utils/reservedNames.js | packages/strapi-plugin-content-type-builder/admin/src/containers/FormModal/utils/reservedNames.js | const JS_BUILT_IN_OBJECTS = [
'object',
'function',
'boolean',
'symbol',
'error',
'infinity',
'number',
'math',
'date',
];
const RESERVED_NAMES = ['admin', 'series', 'file', ...JS_BUILT_IN_OBJECTS];
export default RESERVED_NAMES;
| const JS_BUILT_IN_OBJECTS = [
'boolean',
'date',
'error',
'function',
'infinity',
'map',
'math',
'number',
'object',
'symbol',
];
const RESERVED_NAMES = [
'admin',
'series',
'file',
'news',
...JS_BUILT_IN_OBJECTS,
];
export default RESERVED_NAMES;
| Add map and series to RESERVED_NAMES | Add map and series to RESERVED_NAMES
| JavaScript | mit | wistityhq/strapi,wistityhq/strapi | ---
+++
@@ -1,14 +1,21 @@
const JS_BUILT_IN_OBJECTS = [
+ 'boolean',
+ 'date',
+ 'error',
+ 'function',
+ 'infinity',
+ 'map',
+ 'math',
+ 'number',
'object',
- 'function',
- 'boolean',
'symbol',
- 'error',
- 'infinity',
- 'number',
- 'math',
- 'date',
];
-const RESERVED_NAMES = ['admin', 'series', 'file', ...JS_BUILT_IN_OBJECTS];
+const RESERVED_NAMES = [
+ 'admin',
+ 'series',
+ 'file',
+ 'news',
+ ...JS_BUILT_IN_OBJECTS,
+];
export default RESERVED_NAMES; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.