commit
stringlengths
40
40
old_file
stringlengths
4
264
new_file
stringlengths
4
264
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
624
message
stringlengths
15
4.7k
lang
stringclasses
3 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
55b2c19f6abe49e242a87853250d7da3dec26762
route-urls.js
route-urls.js
var m = angular.module("routeUrls", []); m.factory("urls", function($route) { var pathsByName = {}; angular.forEach($route.routes, function (route, path) { if (route.name) { pathsByName[route.name] = path; } }); var regexs = {}; var path = function (name, params) { var url = pathsByName[name] || "/"; angular.forEach(params || {}, function (value, key) { var regex = regexs[key]; if (regex === undefined) { regex = regexs[key] = new RegExp(":" + key + "(/|$)"); } url = url.replace(regex, value); }); return url; }; return { path: path, href: function (name, params) { return "#" + path(name, params); } }; });
var m = angular.module("routeUrls", []); m.factory("urls", function($route) { var pathsByName = {}; angular.forEach($route.routes, function (route, path) { if (route.name) { pathsByName[route.name] = path; } }); var regexs = {}; var path = function (name, params) { var url = pathsByName[name] || "/"; angular.forEach(params || {}, function (value, key) { var regex = regexs[key]; if (regex === undefined) { regex = regexs[key] = new RegExp(":" + key + "(?=/|$)"); } url = url.replace(regex, value); }); return url; }; return { path: path, href: function (name, params) { return "#" + path(name, params); } }; });
Resolve regex forward lookahead issue
Resolve regex forward lookahead issue
JavaScript
mit
emgee/angular-route-urls,emgee/angular-route-urls
44200ed7deeb5ef12932b2f82f791643e16939a7
match-highlighter.js
match-highlighter.js
function MatchHighlighter() { 'use strict'; const mergeRanges = function(indexes) { return indexes.reduce(function(obj, index, pos) { const prevIndex = indexes[pos - 1] || 0; const currentIndex = indexes[pos]; const nextIndex = indexes[pos + 1] || 0; if (currentIndex === nextIndex - 1 || currentIndex === prevIndex + 1 || indexes.length === 1) { obj.ranges[obj.rangeIndex].push(currentIndex); } else if (currentIndex > 0 && indexes.length > 1) { obj.rangeIndex = obj.ranges.push([currentIndex]); } return obj; }, { ranges:[[]], rangeIndex: 0 }).ranges; }; const wrapHighlight = function(letter) { return '<b>' + letter + '</b>'; }; this.highlight = function(input, result) { const matched = FuzzaldrinPlus.match(result, input); const substrings = mergeRanges(matched).map(function(range) { return range.map(function(index) { return result.charAt(index); }).join(''); }); return substrings.reduce(function(res, substring) { return res.replace(substring, wrapHighlight(substring)); }, result); }; return this; }
function MatchHighlighter() { 'use strict'; const mergeRanges = function(indexes) { return indexes.reduce(function(obj, index, pos) { const prevIndex = indexes[pos - 1] || 0; const currentIndex = indexes[pos]; const nextIndex = indexes[pos + 1] || 0; if (currentIndex === nextIndex - 1 || currentIndex === prevIndex + 1 || indexes.length === 1) { obj.ranges[obj.rangeIndex].push(currentIndex); } else if (currentIndex > 0 && indexes.length > 1) { obj.rangeIndex = obj.ranges.push([currentIndex]) - 1; } return obj; }, { ranges:[[]], rangeIndex: 0 }).ranges; }; const wrapHighlight = function(letter) { return '<b>' + letter + '</b>'; }; this.highlight = function(input, result) { const matched = FuzzaldrinPlus.match(result, input); const substrings = mergeRanges(matched).map(function(range) { return range.map(function(index) { return result.charAt(index); }).join(''); }); return substrings.reduce(function(res, substring) { return res.replace(substring, wrapHighlight(substring)); }, result); }; return this; }
Fix off-by-one error in match highlighter
Fix off-by-one error in match highlighter
JavaScript
mit
YurySolovyov/fuzzymark,YurySolovyov/fuzzymark,YuriSolovyov/fuzzymark,YuriSolovyov/fuzzymark
d213fa0c22440904b526a1793464dc3e5d69b980
src/components/video_list.js
src/components/video_list.js
import React from 'react'; import VideoListItem from './video_list_item'; const VideoList = (props) => { const videoItems = props.videos.map((video) => { return <VideoListItem video = {video} /> }); return ( <ul className="col-md-4 list-group"> {videoItems} </ul> ); } export default VideoList;
Add functionality to VideoList component
Add functionality to VideoList component
JavaScript
mit
izabelka/redux-simple-starter,izabelka/redux-simple-starter
28948b82be7d6da510d0afce5aa8d839df0ab1b0
test/main_spec.js
test/main_spec.js
let chai = require('chai') let chaiHttp = require('chai-http') let server = require('../src/main.js') import {expect} from 'chai' chai.use(chaiHttp) describe('server', () => { before( () => { server.listen(); }) after( () => { server.close(); }) describe('/', () => { it('should return 200', (done) => { chai.request(server) .get('/') .end((err, res) => { console.log(res); expect(res.status).to.equal(200); expect(res.text).to.equal('Node.js Server is running'); server.close(); done(); }) }) }) })
let chai = require('chai') let chaiHttp = require('chai-http') let server = require('../src/main.js') import {expect} from 'chai' chai.use(chaiHttp) describe('server', () => { before( () => { server.listen(); }) after( () => { server.close(); }) describe('/', () => { it('should return 200', (done) => { chai.request(server) .get('/') .end((err, res) => { expect(res.status).to.equal(200); expect(res.text).to.equal('Node.js Server is running'); server.close(); done(); }) }) }) })
Remove logging from server test
Remove logging from server test
JavaScript
mit
GLNRO/react-redux-threejs,GLNRO/react-redux-threejs
68eceecffb4ea457fe92d623f5722fd25c09e718
src/js/routers/app-router.js
src/js/routers/app-router.js
import * as Backbone from 'backbone'; import Items from '../collections/items'; import SearchBoxView from '../views/searchBox-view'; import SearchResultsView from '../views/searchResults-view'; import AppView from '../views/app-view'; import DocumentSet from '../helpers/search'; import dispatcher from '../helpers/dispatcher'; class AppRouter extends Backbone.Router { get routes() { return { '': 'loadDefault', 'search/(?*queryString)': 'showSearchResults' }; } initialize() { this.listenTo(dispatcher, 'router:go', this.go); } go(route) { this.navigate(route, {trigger: true}); } loadDefault() { new AppView(); } showSearchResults(queryString) { let q = queryString.substring(2); DocumentSet.search(q).then(function(result) { let currentDocuments = new DocumentSet(result).documents; let docCollection = new Items(currentDocuments); new SearchResultsView({collection: docCollection}).render(); }); } } export default AppRouter;
import * as Backbone from 'backbone'; import Items from '../collections/items'; import SearchBoxView from '../views/searchBox-view'; import SearchResultsView from '../views/searchResults-view'; import AppView from '../views/app-view'; import Events from '../helpers/backbone-events'; import DocumentSet from '../helpers/search'; class AppRouter extends Backbone.Router { get routes() { return { '': 'loadDefault', 'search/(?*queryString)': 'showSearchResults' }; } initialize() { this.listenTo(Events, 'router:go', this.go); } go(route) { this.navigate(route, {trigger: true}); } loadDefault() { new AppView(); } showSearchResults(queryString) { let q = queryString.substring(2); DocumentSet.search(q).then(function(result) { let currentDocuments = new DocumentSet(result).documents; let docCollection = new Items(currentDocuments); new SearchResultsView({collection: docCollection}).render(); }); } } export default AppRouter;
Use Events instead of custom dispatcher (more)
Use Events instead of custom dispatcher (more)
JavaScript
mit
trevormunoz/katherine-anne,trevormunoz/katherine-anne,trevormunoz/katherine-anne
b4b22938c6feba84188859e522f1b44c274243db
src/modules/workshop/workshop.routes.js
src/modules/workshop/workshop.routes.js
// Imports import UserRoles from '../../core/auth/constants/userRoles'; import WorkshopController from './workshop.controller'; import WorkshopHeaderController from './workshop-header.controller'; import { workshop } from './workshop.resolve'; import { carBrands } from '../home/home.resolve'; /** * @ngInject * @param RouterHelper */ export default function routing(RouterHelper) { const states = [{ state: 'modules.workshop', config: { url: '/korjaamot/:id', title: 'Korjaamo', params: { id: null, selected: null, }, data: { access: UserRoles.ROLE_ANON, }, views: { 'content@': { template: require('./partials/workshop.html'), controller: WorkshopController, controllerAs: 'vm', resolve: { _workshop: workshop, _carBrands: carBrands, }, }, 'header@': { template: require('./partials/header.html'), controller: WorkshopHeaderController, controllerAs: 'vm', resolve: { _workshop: workshop, }, }, }, }, }]; RouterHelper.configureStates(states); }
// Imports import UserRoles from '../../core/auth/constants/userRoles'; import WorkshopController from './workshop.controller'; import WorkshopHeaderController from './workshop-header.controller'; import { workshop } from './workshop.resolve'; import { carBrands } from '../home/home.resolve'; /** * @ngInject * @param RouterHelper * @param WorkshopSharedDataService */ export default function routing(RouterHelper, WorkshopSharedDataService) { const states = [{ state: 'modules.workshop', config: { url: '/korjaamot/:id', title: 'Korjaamo', params: { id: null, selected: null, }, data: { access: UserRoles.ROLE_ANON, }, views: { 'content@': { template: require('./partials/workshop.html'), controller: WorkshopController, controllerAs: 'vm', resolve: { _workshop: workshop, _carBrands: carBrands, _sharedData() { // Set action to information when routing to workshop details WorkshopSharedDataService.action = 'information'; }, }, }, 'header@': { template: require('./partials/header.html'), controller: WorkshopHeaderController, controllerAs: 'vm', resolve: { _workshop: workshop, }, }, }, }, }]; RouterHelper.configureStates(states); }
Set action to information when routing to workshop details
Set action to information when routing to workshop details
JavaScript
mit
ProtaconSolutions/Poc24h-January2017-FrontEnd,ProtaconSolutions/Poc24h-January2017-FrontEnd
f7dfb99616f47561d83f9609c8a32fd6275a053c
src/components/CategoryBody.js
src/components/CategoryBody.js
/** * Created by farid on 8/16/2017. */ import React, {Component} from "react"; import Post from "./Post"; import PropTypes from 'prop-types'; class CategoryBody extends Component { render() { return ( <div className="card-body"> <div className="row"> { this.props.posts.map((post, index) => ( <div className="col-md-4" key={index}> <Post post={post}/> <br/> </div> )) } </div> </div> ) } } CategoryBody.propTypes = { posts: PropTypes.array.isRequired }; export default CategoryBody;
/** * Created by farid on 8/16/2017. */ import React, {Component} from "react"; import Post from "./Post"; import PropTypes from 'prop-types'; class CategoryBody extends Component { render() { return ( <div className="card-body"> <div className="row"> { this.props.posts.map((post, index) => ( <div className="col-md-6" key={index} > <Post post={post} isEditEnabled={true} isDeleteEnabled={true}/> <br/> </div> )) } </div> </div> ) } } CategoryBody.propTypes = { posts: PropTypes.array.isRequired }; export default CategoryBody;
Enable delete and update post on home page
feat: Enable delete and update post on home page
JavaScript
mit
faridsaud/udacity-readable-project,faridsaud/udacity-readable-project
f49ab42589462d519c4304f9c3014a8d5f04e1b3
native/components/safe-area-view.react.js
native/components/safe-area-view.react.js
// @flow import * as React from 'react'; import { SafeAreaView } from 'react-navigation'; const forceInset = { top: 'always', bottom: 'never' }; type Props = {| style?: $PropertyType<React.ElementConfig<typeof SafeAreaView>, 'style'>, children?: React.Node, |}; function InsetSafeAreaView(props: Props) { const { style, children } = props; return ( <SafeAreaView forceInset={forceInset} style={style}> {children} </SafeAreaView> ); } export default InsetSafeAreaView;
// @flow import type { ViewStyle } from '../types/styles'; import * as React from 'react'; import { View } from 'react-native'; import { useSafeArea } from 'react-native-safe-area-context'; type Props = {| style?: ViewStyle, children?: React.Node, |}; function InsetSafeAreaView(props: Props) { const insets = useSafeArea(); const style = [ { paddingTop: insets.top }, props.style, ]; return ( <View style={style}> {props.children} </View> ); } export default InsetSafeAreaView;
Update SafeAreaView for React Nav 5
[native] Update SafeAreaView for React Nav 5 Can't import directly from React Nav anymore, using `react-native-safe-area-context` now
JavaScript
bsd-3-clause
Ashoat/squadcal,Ashoat/squadcal,Ashoat/squadcal,Ashoat/squadcal,Ashoat/squadcal,Ashoat/squadcal,Ashoat/squadcal
7afb5342fb92ed902b962a3324f731833a1cdb00
client/userlist.js
client/userlist.js
var UserList = React.createClass({ componentDidMount: function() { socket.on('join', this._join); socket.on('part', this._part); }, render: function() { return ( <ul id='online-list'></ul> ); }, _join: function(username) { if (username != myUsername) { addOnlineUserToList(username); } }, _part: function(username) { $('#online-list li span').filter(function() { return $(this).text() == username; }).parent().remove(); } }); React.render(<UserList />, document.getElementsByClassName('nicklist')[0]);
var UserList = React.createClass({ componentDidMount: function() { socket.on('join', this._join); socket.on('part', this._part); }, render: function() { return ( <ul id='online-list'></ul> ); }, _join: function(username) { if (username != myUsername) { addOnlineUserToList(username); } }, _part: function(username) { $('#online-list li span').filter(function() { return $(this).text() == username; }).parent().remove(); } }); var User = React.createClass({ render: function() { return ( <li> </li> ) } }); React.render(<UserList />, document.getElementsByClassName('nicklist')[0]);
Create prototype react component for user in list
Create prototype react component for user in list
JavaScript
mit
mbalamat/ting,odyvarv/ting-1,gtklocker/ting,gtklocker/ting,mbalamat/ting,sirodoht/ting,dionyziz/ting,VitSalis/ting,gtklocker/ting,gtklocker/ting,odyvarv/ting-1,sirodoht/ting,sirodoht/ting,dionyziz/ting,dionyziz/ting,odyvarv/ting-1,mbalamat/ting,mbalamat/ting,dionyziz/ting,odyvarv/ting-1,VitSalis/ting,VitSalis/ting,VitSalis/ting,sirodoht/ting
f26e7eb203948d7fff0d0c44a34a675d0631adcf
trace/snippets.js
trace/snippets.js
/** * Copyright 2017, Google, Inc. * 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. */ 'use strict'; // [START trace_setup_explicit] require('@google-cloud/trace-agent').start({ projectId: 'your-project-id', keyFilename: '/path/to/key.json' }); // [END trace_setup_explicity]
/** * Copyright 2017, Google, Inc. * 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. */ 'use strict'; // [START trace_setup_explicit] require('@google-cloud/trace-agent').start({ projectId: 'your-project-id', keyFilename: '/path/to/key.json' }); // [END trace_setup_explicit]
Fix type on region tag
Fix type on region tag
JavaScript
apache-2.0
JustinBeckwith/nodejs-docs-samples,thesandlord/nodejs-docs-samples,thesandlord/nodejs-docs-samples,JustinBeckwith/nodejs-docs-samples,GoogleCloudPlatform/nodejs-docs-samples,GoogleCloudPlatform/nodejs-docs-samples,GoogleCloudPlatform/nodejs-docs-samples,JustinBeckwith/nodejs-docs-samples,GoogleCloudPlatform/nodejs-docs-samples
0c2e8d75c01e8032adcde653a458528db0683c44
karma.conf.js
karma.conf.js
module.exports = function(config){ config.set({ basePath : './', files : [ 'app/bower_components/angular/angular.js', 'app/bower_components/angular-route/angular-route.js', 'app/bower_components/angular-mocks/angular-mocks.js', 'app/components/**/*.js', 'app/view*/**/*.js' ], autoWatch : true, frameworks: ['jasmine'], browsers : ['Chrome'], plugins : [ 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-jasmine', 'karma-junit-reporter' ], junitReporter : { outputFile: 'test_out/unit.xml', suite: 'unit' } }); };
module.exports = function(config){ config.set({ basePath : './', files : [ 'app/bower_components/angular/angular.js', 'app/bower_components/angular-route/angular-route.js', 'app/bower_components/angular-mocks/angular-mocks.js', 'app/components/**/*.js', 'app/view*/**/*.js' ], autoWatch : true, frameworks: ['jasmine'], browsers : ['Chrome', 'Firefox'], plugins : [ 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-jasmine', 'karma-junit-reporter' ], junitReporter : { outputFile: 'test_out/unit.xml', suite: 'unit' } }); };
Change karma to run both Firefox and Chrome.
Change karma to run both Firefox and Chrome. I have both, I care about both, so run both!
JavaScript
agpl-3.0
CCJ16/registration,CCJ16/registration,CCJ16/registration
a783fbcd8bcff07672e64ada1f75c7290c9a765a
src/chrome/index.js
src/chrome/index.js
/* eslint-disable no-console */ import { CONFIG } from '../constants'; import { Socket } from 'phoenix'; import { startPlugin } from '..'; import listenAuth from './listenAuth'; import handleNotifications from './handleNotifications'; import handleWork from './handleWork'; import renderIcon from './renderIcon'; export const startChromePlugin = (auth, chrome, enhancer, socketConstructor = Socket) => { const reloader = () => window.location.reload(true); const plugin = startPlugin({ auth, enhancer, reloader, socketConstructor }); const store = plugin.getStore(); const getStore = () => store; listenAuth(store, chrome); handleNotifications(store, chrome); renderIcon(store, chrome); handleWork(store, chrome); if (CONFIG.env === 'dev') { // redux dev tools don't work with the plugin, so we have a dumb // replacement. store.subscribe(() => { const { worker, socket } = store.getState(); console.log('Worker:', worker.toJS(), 'Socket:', socket.toJS()); }); } return { getStore }; };
/* eslint-disable no-console */ import { CONFIG } from '../constants'; import { Socket } from 'phoenix'; import { startPlugin } from '..'; import listenAuth from './listenAuth'; import handleNotifications from './handleNotifications'; import handleWork from './handleWork'; import renderIcon from './renderIcon'; export const startChromePlugin = (auth, chrome, enhancer, socketConstructor = Socket) => { const reloader = () => window.location.reload(true); const plugin = startPlugin({ auth, enhancer, reloader, socketConstructor }); const store = plugin.getStore(); const getStore = () => store; listenAuth(store, chrome); handleNotifications(store, chrome); renderIcon(store, chrome); handleWork(store, chrome); if (CONFIG.env === 'dev') { // redux dev tools don't work with the plugin, so we have a dumb // replacement. store.subscribe(() => { const { worker, socket, plugin: pluginState } = store.getState(); console.log('Worker:', worker.toJS(), 'Socket:', socket.toJS(), 'Plugin:', pluginState.toJS()); }); } return { getStore }; };
Add plugin state to logging
Add plugin state to logging
JavaScript
mit
rainforestapp/tester-chrome-extension,rainforestapp/tester-chrome-extension,rainforestapp/tester-chrome-extension
51cebb77df8d4eec12da134b765d5fe046eefeda
karma.conf.js
karma.conf.js
var istanbul = require('browserify-istanbul'); var isparta = require('isparta'); module.exports = function (config) { 'use strict'; config.set({ browsers: [ 'Chrome', 'Firefox', 'Safari', 'Opera' ], reporters: ['progress', 'notify', 'coverage'], frameworks: ['browserify', 'mocha', 'chai-sinon', 'sinon'], // list of files / patterns to load in the browser files: ['./tests/spec/**/*.js'], preprocessors: { './tests/spec/**/*.js': ['browserify'] }, client: { mocha: {reporter: 'html'} // change Karma's debug.html to the mocha web reporter }, browserify: { debug: true, transform: [ //'babelify', istanbul({ instrumenter: isparta, ignore: ['**/node_modules/**', '**/test/**'], }) ], configure: function (bundle) { bundle.on('bundled', function (error) { if (error != null) console.error(error.message); }); } }, notifyReporter: { reportEachFailure: true, reportSuccess: true } }); };
var istanbul = require('browserify-istanbul'); var isparta = require('isparta'); module.exports = function (config) { 'use strict'; config.set({ browsers: [ //'PhantomJS', 'Chrome', 'Firefox', 'Safari', 'Opera' ], reporters: ['progress', 'notify', 'coverage'], frameworks: ['browserify', 'mocha', 'chai-sinon', 'sinon'], // list of files / patterns to load in the browser files: ['./tests/spec/**/*.js'], preprocessors: { './tests/spec/**/*.js': ['browserify'] }, client: { mocha: {reporter: 'html'} // change Karma's debug.html to the mocha web reporter }, browserify: { debug: true, transform: [ //'babelify', istanbul({ instrumenter: isparta, ignore: ['**/node_modules/**', '**/test/**'], }) ], configure: function (bundle) { bundle.on('bundled', function (error) { if (error != null) console.error(error.message); }); } }, notifyReporter: { reportEachFailure: true, reportSuccess: true }, logLevel: 'LOG_INFO', }); };
Set log level. PhantomJS off.
Set log level. PhantomJS off.
JavaScript
mit
ekazakov/dumpjs
b4cd7c829a7d17888902f5468d4ea0a0f1084c42
src/common/Popup.js
src/common/Popup.js
/* @flow */ import React, { PureComponent } from 'react'; import type { ChildrenArray } from 'react'; import { View, Dimensions, StyleSheet } from 'react-native'; const styles = StyleSheet.create({ popup: { marginRight: 20, marginLeft: 20, marginBottom: 2, bottom: 0, borderRadius: 5, shadowOpacity: 0.25, elevation: 3, }, }); type Props = { children: ChildrenArray<*>, }; export default class Popup extends PureComponent<Props> { props: Props; static contextTypes = { styles: () => null, }; render() { const { height } = Dimensions.get('window'); return ( <View style={[this.context.styles.backgroundColor, styles.popup]} maxHeight={height / 4}> {this.props.children} </View> ); } }
/* @flow */ import React, { PureComponent } from 'react'; import type { ChildrenArray } from 'react'; import { View, StyleSheet } from 'react-native'; const styles = StyleSheet.create({ popup: { marginRight: 20, marginLeft: 20, marginBottom: 2, bottom: 0, borderRadius: 5, shadowOpacity: 0.25, elevation: 3, }, }); type Props = { children: ChildrenArray<*>, }; export default class Popup extends PureComponent<Props> { props: Props; static contextTypes = { styles: () => null, }; render() { return ( <View style={[this.context.styles.backgroundColor, styles.popup]}>{this.props.children}</View> ); } }
Remove extraneous `maxHeight` prop on a `View`.
popup: Remove extraneous `maxHeight` prop on a `View`. This is not a prop that the `View` component supports. It has never had any effect, and the Flow 0.75 we'll pull in with RN 0.56 will register it as an error. This prop was added in commit ce0395cff when changing the component used here to a `ScrollView`, and 62ddf77a7 left it around when changing back to a `View`.
JavaScript
apache-2.0
vishwesh3/zulip-mobile,vishwesh3/zulip-mobile,vishwesh3/zulip-mobile,vishwesh3/zulip-mobile
c6d77a8570bbd3592acc1430672e57219f418072
Libraries/Utilities/PerformanceLoggerContext.js
Libraries/Utilities/PerformanceLoggerContext.js
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow strict-local * @format */ import * as React from 'react'; import {useContext} from 'react'; import GlobalPerformanceLogger from './GlobalPerformanceLogger'; import type {IPerformanceLogger} from './createPerformanceLogger'; /** * This is a React Context that provides a scoped instance of IPerformanceLogger. * We wrap every <AppContainer /> with a Provider for this context so the logger * should be available in every component. * See React docs about using Context: https://reactjs.org/docs/context.html */ const PerformanceLoggerContext: React.Context<IPerformanceLogger> = React.createContext( GlobalPerformanceLogger, ); if (__DEV__) { PerformanceLoggerContext.displayName = 'PerformanceLoggerContext'; } export function usePerformanceLogger(): IPerformanceLogger { return useContext(PerformanceLoggerContext); } export default PerformanceLoggerContext;
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow strict * @format */ import * as React from 'react'; import {useContext} from 'react'; import GlobalPerformanceLogger from './GlobalPerformanceLogger'; import type {IPerformanceLogger} from './createPerformanceLogger'; /** * This is a React Context that provides a scoped instance of IPerformanceLogger. * We wrap every <AppContainer /> with a Provider for this context so the logger * should be available in every component. * See React docs about using Context: https://reactjs.org/docs/context.html */ const PerformanceLoggerContext: React.Context<IPerformanceLogger> = React.createContext( GlobalPerformanceLogger, ); if (__DEV__) { PerformanceLoggerContext.displayName = 'PerformanceLoggerContext'; } export function usePerformanceLogger(): IPerformanceLogger { return useContext(PerformanceLoggerContext); } export default PerformanceLoggerContext;
Make some modules flow strict
Make some modules flow strict Summary: TSIA Changelog: [Internal] Reviewed By: mdvacca Differential Revision: D28412774 fbshipit-source-id: 899a78e573bb49633690275052d5e7cb069327fb
JavaScript
mit
facebook/react-native,myntra/react-native,facebook/react-native,pandiaraj44/react-native,myntra/react-native,janicduplessis/react-native,javache/react-native,myntra/react-native,javache/react-native,pandiaraj44/react-native,javache/react-native,javache/react-native,janicduplessis/react-native,janicduplessis/react-native,myntra/react-native,janicduplessis/react-native,pandiaraj44/react-native,janicduplessis/react-native,javache/react-native,facebook/react-native,javache/react-native,facebook/react-native,pandiaraj44/react-native,pandiaraj44/react-native,javache/react-native,facebook/react-native,janicduplessis/react-native,pandiaraj44/react-native,javache/react-native,facebook/react-native,facebook/react-native,facebook/react-native,myntra/react-native,myntra/react-native,janicduplessis/react-native,myntra/react-native,myntra/react-native,pandiaraj44/react-native,janicduplessis/react-native,myntra/react-native,facebook/react-native,pandiaraj44/react-native,javache/react-native
752c2c39790cf1ffb1e97850991d2f13c25f92b8
src/config/babel.js
src/config/babel.js
// External const mem = require('mem'); // Ours const { merge } = require('../utils/structures'); const { getProjectConfig } = require('./project'); const PROJECT_TYPES_CONFIG = { preact: { plugins: [ [ require.resolve('@babel/plugin-transform-react-jsx'), { pragma: 'h' } ] ] }, react: { presets: [require.resolve('@babel/preset-react')] } }; module.exports.getBabelConfig = mem(({ isModernJS } = {}) => { const { babel: projectBabelConfig, pkg, type } = getProjectConfig(); return merge( { presets: [ [ require.resolve('@babel/preset-env'), { targets: { browsers: isModernJS ? ['Chrome >= 76', 'Safari >= 12.1', 'iOS >= 12.3', 'Firefox >= 69', 'Edge >= 18'] : pkg.browserslist || ['> 1% in au', '> 5%', 'Firefox ESR'] }, useBuiltIns: 'entry', corejs: 3, modules: process.env.NODE_ENV === 'test' ? 'commonjs' : false } ] ], plugins: [ require.resolve('@babel/plugin-proposal-object-rest-spread'), require.resolve('@babel/plugin-syntax-dynamic-import'), require.resolve('@babel/plugin-proposal-class-properties') ] }, PROJECT_TYPES_CONFIG[type], projectBabelConfig ); });
// External const mem = require('mem'); // Ours const { merge } = require('../utils/structures'); const { getProjectConfig } = require('./project'); const PROJECT_TYPES_CONFIG = { preact: { plugins: [ [ require.resolve('@babel/plugin-transform-react-jsx'), { pragma: 'h' } ] ] }, react: { presets: [require.resolve('@babel/preset-react')] } }; module.exports.getBabelConfig = mem(({ isModernJS } = {}) => { const { babel: projectBabelConfig, pkg, type } = getProjectConfig(); return merge( { presets: [ [ require.resolve('@babel/preset-env'), { targets: { browsers: isModernJS ? ['Chrome >= 80', 'Safari >= 12.1', 'iOS >= 12.3', 'Firefox >= 72', 'Edge >= 18'] : pkg.browserslist || ['> 1% in AU', 'Firefox ESR', 'IE 11'] }, useBuiltIns: 'entry', corejs: 3, modules: process.env.NODE_ENV === 'test' ? 'commonjs' : false } ] ], plugins: [ require.resolve('@babel/plugin-proposal-object-rest-spread'), require.resolve('@babel/plugin-syntax-dynamic-import'), require.resolve('@babel/plugin-proposal-class-properties') ] }, PROJECT_TYPES_CONFIG[type], projectBabelConfig ); });
Update target browsers. IE 11 needs to be manually specified now becuase it's dropped below 1% in Australia, but is still supported by ABC.
Update target browsers. IE 11 needs to be manually specified now becuase it's dropped below 1% in Australia, but is still supported by ABC.
JavaScript
mit
abcnews/aunty,abcnews/aunty,abcnews/aunty
2525fe4097ff124239ed56956209d4d0ffefac27
test/unit/util/walk-tree.js
test/unit/util/walk-tree.js
import walkTree from '../../../src/util/walk-tree'; describe('utils/walk-tree', function () { it('should walk parents before walking descendants', function () { var order = []; var one = document.createElement('one'); one.innerHTML = '<two><three></three></two>'; walkTree(one, function (elem) { order.push(elem.tagName); }); expect(order[0]).to.equal('ONE'); expect(order[1]).to.equal('TWO'); expect(order[2]).to.equal('THREE'); }); });
import walkTree from '../../../src/util/walk-tree'; describe('utils/walk-tree', function () { var one, order; beforeEach(function () { order = []; one = document.createElement('one'); one.innerHTML = '<two><three></three></two>'; }); it('should walk parents before walking descendants', function () { walkTree(one, function (elem) { order.push(elem.tagName); }); expect(order.length).to.equal(3); expect(order[0]).to.equal('ONE'); expect(order[1]).to.equal('TWO'); expect(order[2]).to.equal('THREE'); }); it('should accept a filter that filters out a node removing it and its descendants', function () { walkTree(one, function (elem) { order.push(elem.tagName); }, function (elem) { return elem.tagName !== 'TWO'; }); expect(order.length).to.equal(1); expect(order[0]).to.equal('ONE'); }); });
Write test for walkTre() filter.
Write test for walkTre() filter.
JavaScript
mit
skatejs/skatejs,antitoxic/skatejs,chrisdarroch/skatejs,skatejs/skatejs,skatejs/skatejs,chrisdarroch/skatejs
1a07a7c7900cc14582fdaf41a96933d221a439e0
tests/client/unit/s.Spec.js
tests/client/unit/s.Spec.js
describe('Satellite game', function () { beforeEach(function () { }); it('should exists', function () { expect(s).to.be.an('object'); expect(s).to.have.property('config'); expect(s).to.have.property('init'); }); it('should contains ship properties', function () { expect(s).to.have.deep.property('config.ship.hull'); expect(s).to.have.deep.property('config.ship.shields'); expect(s).to.have.deep.property('config.ship.maxSpeed'); }); it('should init the game', function () { var spy = sinon.spy(); s.init('init', spy); spy.called.should.equal.true; expect(s).to.have.property('projector').and.to.be.an('object'); expect(s).to.have.property('loader').and.to.be.an('object'); expect(s).to.have.property('game').and.to.be.an('object'); }); });
describe('Satellite game', function () { it('should exists', function () { expect(s).to.be.an('object'); expect(s).to.have.property('config'); expect(s).to.have.property('init'); }); it('should contains ship properties', function () { expect(s).to.have.deep.property('config.ship.hull'); expect(s).to.have.deep.property('config.ship.shields'); expect(s).to.have.deep.property('config.ship.maxSpeed'); }); it('should init the game', function () { var spy = sinon.spy(); s.init('init', spy); spy.called.should.equal.true; expect(s).to.have.property('projector').and.to.be.an('object'); expect(s).to.have.property('loader').and.to.be.an('object'); expect(s).to.have.property('game').and.to.be.an('object'); }); });
Remove unused before each call
Remove unused before each call
JavaScript
bsd-2-clause
satellite-game/Satellite,satellite-game/Satellite,satellite-game/Satellite
3f934607b9404a5edca6b6a7f68c934d90c899ce
static/js/featured-projects.js
static/js/featured-projects.js
$('.project-toggle-featured').on('click', function() { const projectId = $(this).data("project-id"), featured = $(this).data("featured") === "True"; method = featured ? "DELETE" : "POST"; $.ajax({ type: method, url: `/admin/featured/${projectId}`, dataType: 'json' }).done(() => { const newStatus = featured ? "False" : "True"; $(this).data('featured', newStatus); $(this).html(newStatus); }); })
$('.project-toggle-featured').on('click', function() { const projectId = $(this).data("project-id"), featured = $(this).val() === "Remove"; method = featured ? "DELETE" : "POST"; $.ajax({ type: method, url: `/admin/featured/${projectId}`, dataType: 'json' }).done(() => { const newStatus = featured ? "Add" : "Remove"; $(this).html(newStatus); }); })
Update featured projects button text
Update featured projects button text
JavaScript
bsd-3-clause
LibCrowds/libcrowds-bs4-pybossa-theme,LibCrowds/libcrowds-bs4-pybossa-theme
06e880b204d4b19edb42116d7a7fad85e8889de9
webpack.common.js
webpack.common.js
var webpack = require('webpack'), path = require('path'), CleanWebpackPlugin = require('clean-webpack-plugin'); var libraryName = 'webstompobs', dist = '/dist'; module.exports = { entry: __dirname + '/src/index.ts', context: path.resolve("./src"), output: { path: path.join(__dirname, dist), filename: libraryName + '.bundle.js', library: libraryName, libraryTarget: 'umd', umdNamedDefine: true }, resolve: { extensions: ['.js', '.ts', '.jsx', '.tsx' ] }, plugins: [ new CleanWebpackPlugin(['dist']) ], module: { rules: [ { test: /\.tsx?$/, loader: "awesome-typescript-loader" }, { enforce: "pre", test: /\.js$/, loader: "source-map-loader" } ] } };
var webpack = require('webpack'), path = require('path'), CleanWebpackPlugin = require('clean-webpack-plugin'); var libraryName = 'webstompobs', dist = '/dist'; module.exports = { target: 'node', entry: __dirname + '/src/index.ts', context: path.resolve("./src"), output: { path: path.join(__dirname, dist), filename: libraryName + '.bundle.js', library: libraryName, libraryTarget: 'umd', umdNamedDefine: true }, resolve: { extensions: ['.js', '.ts', '.jsx', '.tsx' ] }, plugins: [ new CleanWebpackPlugin(['dist']) ], module: { rules: [ { test: /\.tsx?$/, loader: "awesome-typescript-loader" }, { enforce: "pre", test: /\.js$/, loader: "source-map-loader" } ] } };
FIX : Version was not compatible with node
FIX : Version was not compatible with node Reason : webpack was using window
JavaScript
apache-2.0
fpozzobon/webstomp-obs,fpozzobon/webstomp-obs,fpozzobon/webstomp-obs
f75613d01d047cfbc5b8cc89154ad6eee64d6155
lib/Filter.js
lib/Filter.js
import React, { Component, PropTypes } from 'react'; import FormControl from 'react-bootstrap/lib/FormControl'; class Filter extends Component { constructor(props){ super(props); this.state = {filterValue : this.props.query}; this.inputChanged = this.inputChanged.bind(this); } componentWillUnmount(){ if(this.timeout){ window.clearTimeout(this.timeout); this.timeout = null; } } inputChanged(event){ this.setState({filterValue: event.target.value}); if (this.timeout){ window.clearTimeout(this.timeout); this.timeout = null; } this.timeout = window.setTimeout(()=>{ this.props.config.eventHandler( { type:'filter-change', id: this.props.config.id, column: this.props.column, query: this.state.filterValue } ); }, 300); } render(){ return( <FormControl id={'filter_for_'+this.props.column} type='search' key={this.props.column} value={this.state.filterValue} onChange={this.inputChanged} placeholder={"Filter..."} /> ); } } Filter.propTypes = { query: PropTypes.string, config: PropTypes.object, column: PropTypes.string.isRequired }; export default Filter;
import React, { Component, PropTypes } from 'react'; import FormControl from 'react-bootstrap/lib/FormControl'; class Filter extends Component { constructor(props){ super(props); this.state = {filterValue : this.props.query}; this.inputChanged = this.inputChanged.bind(this); } componentWillUnmount(){ if(this.timeout){ window.clearTimeout(this.timeout); this.timeout = null; } } inputChanged(event){ this.setState({filterValue: event.target.value}); if (this.timeout){ window.clearTimeout(this.timeout); this.timeout = null; } this.timeout = window.setTimeout(()=>{ this.props.config.eventHandler( { type:'filter-change', id: this.props.config.id, column: this.props.column, query: this.state.filterValue } ); }, 300); } render(){ return( <FormControl id={'filter_for_'+this.props.column} type='search' key={this.props.column} value={this.state.filterValue} onChange={this.inputChanged} placeholder={'Filter...'} /> ); } } Filter.propTypes = { query: PropTypes.string, config: PropTypes.object, column: PropTypes.string.isRequired }; export default Filter;
Use single quotes for strings
Use single quotes for strings
JavaScript
mit
eddyson-de/react-grid,eddyson-de/react-grid
4c141ac898f6a7bad42db55445bb5fecf99639bd
src/user/user-interceptor.js
src/user/user-interceptor.js
export default function userInterceptor($localStorage){ function request(config){ if(config.headers.Authorization){ return config; } if($localStorage.token){ config.headers.Authorization = 'bearer ' + $localStorage.token; } return config; } return {request}; } userInterceptor.$inject = ['$localStorage'];
export default function userInterceptor(user){ function request(config){ if(config.headers.Authorization){ return config; } if(user.token){ config.headers.Authorization = 'bearer ' + user.token; } return config; } return {request}; } userInterceptor.$inject = ['$localStorage'];
Use user service in interceptor
Use user service in interceptor
JavaScript
mit
tamaracha/wbt-framework,tamaracha/wbt-framework,tamaracha/wbt-framework
5841cf3eb49b17d5c851d8e7e2f6b4573b8fe620
src/components/nlp/template.js
src/components/nlp/template.js
/** * Created by Tomasz Gabrysiak @ Infermedica on 08/02/2017. */ import html from '../../templates/helpers'; const template = (context) => { return new Promise((resolve) => { resolve(html` <h5 class="card-title">Tell us how you feel.</h5> <div class="card-text"> <form> <div class="form-group"> <label for="input-feel">We will try to recognize your symptoms using Natural Language Processing algorithms.</label> <textarea placeholder="e.g. I got headache" class="form-control" id="input-feel" rows="4"></textarea> </div> </form> <p>Identified observations:</p> <ul class="list-unstyled" id="observations"> </ul> <p class="text-muted small"><i class="fa fa-info-circle"></i> This screen uses our NLP engine to find symptoms in a written text. Evidences found in text will be marked as initial which is important to our engine. Please read more about initial evidences <a target="_blank">here</a>. All of the identified symptoms will be added to your interview after clicking <span class="badge badge-primary">Next</span>.</p> </div> `); }); }; export default template;
/** * Created by Tomasz Gabrysiak @ Infermedica on 08/02/2017. */ import html from '../../templates/helpers'; const template = (context) => { return new Promise((resolve) => { resolve(html` <h5 class="card-title">Tell us how you feel.</h5> <div class="card-text"> <form> <div class="form-group"> <label for="input-feel">We will try to recognize your symptoms using Natural Language Processing algorithms.</label> <textarea placeholder="e.g. I got headache" class="form-control" id="input-feel" rows="4"></textarea> </div> </form> <p>Identified observations:</p> <ul class="list-unstyled" id="observations"> </ul> <p class="text-muted small"><i class="fa fa-info-circle"></i> This screen uses our NLP engine to find symptoms in a written text. Evidence found in text will be marked as initial which is important to our engine. Please read more about initial evidence <a target="_blank" href="https://developer.infermedica.com/docs/diagnosis#gathering-initial-evidence">here</a>. All of the identified symptoms will be added to your interview after clicking <span class="badge badge-primary">Next</span>.</p> </div> `); }); }; export default template;
Fix typos in text about NLP
Fix typos in text about NLP
JavaScript
mit
infermedica/js-symptom-checker-example,infermedica/js-symptom-checker-example
434fcc48ae69280d9295327ec6592c462ba55ab3
webpack.config.js
webpack.config.js
// Used to run webpack dev server to test the demo in local const webpack = require('webpack'); const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = (env, options) => ({ mode: options.mode, devtool: 'source-map', entry: path.resolve(__dirname, 'demo/js/demo.js'), output: { path: path.resolve(__dirname, 'pages'), filename: '[name][chunkhash].js', }, module: { rules: [ { test: /\.js$/, exclude: [/node_modules/], use: [ { loader: 'babel-loader', }, ], }, { test: /\.css$/, loaders: ['style-loader', 'css-loader'], }, ], }, plugins: [ options.mode === 'development' ? new webpack.HotModuleReplacementPlugin() : () => {}, new HtmlWebpackPlugin({ template: path.resolve(__dirname, 'demo/index.html'), }), ], devServer: { contentBase: './demo', }, });
// Used to run webpack dev server to test the demo in local const webpack = require('webpack'); const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = (env, options) => ({ mode: options.mode, devtool: 'source-map', entry: path.resolve(__dirname, 'demo/js/demo.js'), output: { path: path.resolve(__dirname, 'pages'), filename: options.mode === 'production' ? '[name][chunkhash].js' : '[name].js', }, module: { rules: [ { test: /\.js$/, exclude: [/node_modules/], use: [ { loader: 'babel-loader', }, ], }, { test: /\.css$/, loaders: ['style-loader', 'css-loader'], }, ], }, plugins: [ options.mode === 'development' ? new webpack.HotModuleReplacementPlugin() : () => {}, new HtmlWebpackPlugin({ template: path.resolve(__dirname, 'demo/index.html'), }), ], devServer: { contentBase: './demo', }, });
Fix chunkhash not allowed in development
Fix chunkhash not allowed in development
JavaScript
mit
springload/react-accessible-accordion,springload/react-accessible-accordion,springload/react-accessible-accordion
458790663023230f78c75753bb2619bd437c1117
webpack.config.js
webpack.config.js
const path = require('path'); module.exports = { entry: { 'acrolinx-sidebar-integration': './src/acrolinx-sidebar-integration.ts', 'tests': './test/index.ts' }, module: { rules: [ { test: /\.tsx?$/, use: 'ts-loader', exclude: /node_modules/ } ] }, resolve: { extensions: ['.tsx', '.ts', '.js'] }, output: { filename: '[name].js', publicPath: "/distrib/", path: path.resolve(__dirname, 'distrib') } };
const path = require('path'); module.exports = { entry: { 'acrolinx-sidebar-integration': './src/acrolinx-sidebar-integration.ts', 'tests': './test/index.ts' }, module: { rules: [ { test: /\.tsx?$/, loader: 'ts-loader', exclude: /node_modules/, options: { transpileOnly: true } } ] }, resolve: { extensions: ['.tsx', '.ts', '.js'] }, output: { filename: '[name].js', publicPath: "/distrib/", path: path.resolve(__dirname, 'distrib') } };
Use webpack just for transpileOnly of ts to js.
Use webpack just for transpileOnly of ts to js. Type checking is done by IDE, npm run tscWatch or build anyway.
JavaScript
apache-2.0
acrolinx/acrolinx-sidebar-demo
3f2d406174bdeec38478bf1cb342266a0c1c6554
webpack.config.js
webpack.config.js
var webpack = require('webpack') module.exports = { entry: { ui: './lib/ui/main.js', vendor: ['react', 'debug'] }, output: { path: 'dist', filename: '[name].js' }, module: { loaders: [ {test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel'}, {test: /\.json$/, loader: 'json'} ] }, resolve: { alias: { bacon: "baconjs" } }, plugins: [ new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.js'), new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/) ] }
var webpack = require('webpack') module.exports = { entry: { ui: './lib/ui/main.js', vendor: ['react', 'debug', 'd3', 'react-bootstrap'] }, output: { path: 'dist', filename: '[name].js' }, module: { loaders: [ {test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel'}, {test: /\.json$/, loader: 'json'} ] }, resolve: { alias: { bacon: "baconjs" } }, plugins: [ new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.js'), new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/) ] }
Move stuff to vendor bundle
Move stuff to vendor bundle
JavaScript
apache-2.0
SignalK/instrumentpanel,SignalK/instrumentpanel
a6854e7f88a94b09a0f15400463af8693249de09
lib/config.js
lib/config.js
'use strict' const path = require('path') const nconf = require('nconf') const defaults = { port: 5000, mongo: { url: 'mongodb://localhost/link-analyzer', }, redis: { host: 'localhost', port: 6379, }, kue: { prefix: 'q', }, } nconf .file({ file: path.join(__dirname, '..', 'config.json') }) .env({ separator: '_', lowerCase: true }) .defaults({ store: defaults }) module.exports = nconf
'use strict' const path = require('path') const nconf = require('nconf') const defaults = { port: 6000, mongo: { url: 'mongodb://localhost/link-analyzer', }, redis: { host: 'localhost', port: 6379, }, kue: { prefix: 'q', }, } nconf .file({ file: path.join(__dirname, '..', 'config.json') }) .env({ separator: '_', lowerCase: true }) .defaults({ store: defaults }) module.exports = nconf
Change default port to 6000 as specified in geogw
Change default port to 6000 as specified in geogw
JavaScript
mit
inspireteam/link-analyzer
a752e6c1c2eadfaf2a278c7d5ee7f0494b8ed163
lib/batch/translator.js
lib/batch/translator.js
function Translator(domain) { this.domain = domain; this.init(); } Translator.prototype = { TYPE_ADD: 'add', MAPPED_FIELDS: { 'id': '_key' }, init: function() { this.table = this.getTableName(this.domain); }, getTableName: function(domain) { return domain; }, translate: function(batch) { }, translateOne: function(batch) { switch (batch.type) { case this.TYPE_ADD: return this.addToLoad(batch); default: throw new Error('batch type "' + batch.type + '" is not acceptable'); } }, addToLoad: function(batch) { var line = { _key: batch.id }; for (var field in batch.fields) { if (!batch.fields.hasOwnProperty(field)) continue; line[field] = batch.fields[field]; } var command = 'load --table ' + this.table + JSON.stringify([line]); return command; } }; exports.Translator = Translator;
function Translator(domain) { this.domain = domain; this.init(); } Translator.prototype = { TYPE_ADD: 'add', MAPPED_FIELDS: { 'id': '_key' }, init: function() { this.table = this.getTableName(this.domain); }, getTableName: function(domain) { return domain; }, translate: function(batch) { }, translateOne: function(batch) { switch (batch.type) { case this.TYPE_ADD: return this.addToLoad(batch); default: throw new Error('batch type "' + batch.type + '" is not acceptable'); } }, addToLoad: function(batch) { var line = { _key: batch.id }; for (var field in batch.fields) { if (!batch.fields.hasOwnProperty(field)) continue; line[field] = batch.fields[field]; } var command = 'load --table ' + this.table + ' ' + JSON.stringify([line]); return command; } }; exports.Translator = Translator;
Add padding space between table name and loaded data
Add padding space between table name and loaded data
JavaScript
mit
groonga/gcs,groonga/gcs
ed45aff0857eeac70aef4d339f6f97c805cadc82
src/model/settings.js
src/model/settings.js
import {Events} from 'tabris'; import {mixin} from './helpers'; const store = {}; class Settings { get serverUrl() { return store.serverUrl; } set serverUrl(url) { store.serverUrl = url; localStorage.setItem('serverUrl', url); this.trigger('change:serverUrl'); } load() { store.serverUrl = localStorage.getItem('serverUrl') || 'http://192.168.1.'; } } mixin(Settings, Events); export default new Settings();
import {Events} from 'tabris'; import {mixin} from './helpers'; const store = {}; class Settings { get serverUrl() { return store.serverUrl; } set serverUrl(url) { store.serverUrl = url; localStorage.setItem('serverUrl', url); this.trigger('change:serverUrl'); } load() { store.serverUrl = localStorage.getItem('serverUrl') || 'http://192.168.1.1'; } } mixin(Settings, Events); export default new Settings();
Use complete IP address as default
Use complete IP address as default Work around crash due to tabris-js issue 956
JavaScript
mit
ralfstx/kitchen-radio-app
68b7afc956bf0dc2802f266183abb08e9930b3e9
lib/errors.js
lib/errors.js
var inherits = require('inherits'); var self = module.exports = { FieldValidationError: FieldValidationError, ModelValidationError: ModelValidationError, messages: { "en-us": { "generic": "Failed to validate field", "required": "The field is required", "wrong_type": "Field value is not of type {type}" } }, getMessage: function(type, params, lang) { lang = lang || "en-us"; return self.messages[lang][type].replace(/\${([\w:]+)}/g, function(match, varname) { return params[varname]; }); } }; function FieldValidationError(type, params) { this.type = type || 'generic'; this.params = params; this.message = self.getMessage(type, params); this.stack = new Error(this.message).stack; } inherits(FieldValidationError, Error); function ModelValidationError(errors) { this.errors = errors; this.message = "Error validating the model \n"+JSON.stringify(errors); this.stack = new Error(this.message).stack; } inherits(ModelValidationError, Error);
var inherits = require('inherits'); var self = module.exports = { FieldValidationError: FieldValidationError, ModelValidationError: ModelValidationError, messages: { "en-us": { "generic": "Failed to validate field", "required": "The field is required", "wrong_type": "Field value is not of type {type}" } }, getMessage: function(type, params, lang) { lang = lang || "en-us"; return self.messages[lang][type].replace(/\${([\w:]+)}/g, function(match, varname) { return params[varname]; }); } }; function FieldValidationError(type, params) { this.type = type || 'generic'; this.params = params; this.message = self.getMessage(type, params); this.stack = new Error(this.message).stack; } inherits(FieldValidationError, Error); function ModelValidationError(errors) { this.errors = errors; var message = "Error validating the model \n"; Object.keys(errors).forEach(function(field) { message += field + ": " + errors[field].message + "\n"; }); this.message = message; this.stack = new Error(this.message).stack; } inherits(ModelValidationError, Error);
Improve formatting of ModelValidationError toString()
Improve formatting of ModelValidationError toString()
JavaScript
mit
mariocasciaro/minimodel,D4H/minimodel
b9129f100079a6bf96d086b95c8f65fa8f82d8d4
lib/memdash/server/public/charts.js
lib/memdash/server/public/charts.js
$(document).ready(function(){ $.jqplot('gets-sets', [$("#gets-sets").data("gets"), $("#gets-sets").data("sets")], { title: 'Gets & Sets', grid: { drawBorder: false, shadow: false, background: '#fefefe' }, axesDefaults: { labelRenderer: $.jqplot.CanvasAxisLabelRenderer }, seriesDefaults: { rendererOptions: { smooth: true } } }); $.jqplot('hits-misses', [$("#hits-misses").data("hits"), $("#hits-misses").data("misses")], { title: 'Hits & Misses', grid: { drawBorder: false, shadow: false, background: '#fefefe' }, axesDefaults: { labelRenderer: $.jqplot.CanvasAxisLabelRenderer }, seriesDefaults: { rendererOptions: { smooth: true } } }); });
$(document).ready(function(){ $.jqplot('gets-sets', [$("#gets-sets").data("gets"), $("#gets-sets").data("sets")], { title: 'Gets & Sets', grid: { drawBorder: false, shadow: false, background: '#fefefe' }, axesDefaults: { labelRenderer: $.jqplot.CanvasAxisLabelRenderer }, seriesDefaults: { rendererOptions: { smooth: true } }, series: [ {label: 'Gets'}, {label: 'Sets'} ], legend: { show: true }, seriesColors: ["rgb(36, 173, 227)", "rgb(227, 36, 132)"] }); $.jqplot('hits-misses', [$("#hits-misses").data("hits"), $("#hits-misses").data("misses")], { title: 'Hits & Misses', grid: { drawBorder: false, shadow: false, background: '#fefefe' }, axesDefaults: { labelRenderer: $.jqplot.CanvasAxisLabelRenderer }, seriesDefaults: { rendererOptions: { smooth: true } }, series: [ {label: 'Hits'}, {label: 'Misses'} ], legend: { show: true }, seriesColors: ["rgb(227, 36, 132)", "rgb(227, 193, 36)"] }); });
Set legends and colors of series
Set legends and colors of series
JavaScript
mit
bryckbost/memdash,bryckbost/memdash
bf2db67a14522f853bd0e898286947fdb0ed626b
src/js/constants.js
src/js/constants.js
/* eslint-disable max-len */ import dayjs from "dayjs"; export const GDQ_API_ENDPOINT = "https://api.gdqstat.us"; export const OFFLINE_MODE = true; const LIVE_STORAGE_ENDPOINT = "https://storage.api.gdqstat.us"; // Note: Keep this up-to-date with the most recent event export const EVENT_YEAR = 2019; export const EVENT_SHORT_NAME = "agdq"; export const EVENT_START_DATE = dayjs("01-05-20"); const OFFLINE_STORAGE_ENDPOINT = `/data/${EVENT_YEAR}/${EVENT_SHORT_NAME}_final`; export const GDQ_STORAGE_ENDPOINT = OFFLINE_MODE ? OFFLINE_STORAGE_ENDPOINT : LIVE_STORAGE_ENDPOINT; export const DONATION_TRACKER_URL = `https://gamesdonequick.com/tracker/index/${EVENT_SHORT_NAME}${EVENT_YEAR}`; export const SECONDARY_COLOR = "#F21847"; export const PRIMARY_COLOR = "#00AEEF"; export const PANEL_BACKGROUND_COLOR = "#EEEEEE"; export const LIGHT_FILL_COLOR = "#DDDDDD"; export const DARK_FILL_COLOR = "#333333";
/* eslint-disable max-len */ import dayjs from "dayjs"; export const GDQ_API_ENDPOINT = "https://api.gdqstat.us"; export const OFFLINE_MODE = true; const LIVE_STORAGE_ENDPOINT = "https://storage.api.gdqstat.us"; // Note: Keep this up-to-date with the most recent event export const EVENT_YEAR = 2020; export const EVENT_SHORT_NAME = "agdq"; export const EVENT_START_DATE = dayjs("01-05-20"); const OFFLINE_STORAGE_ENDPOINT = `/data/${EVENT_YEAR}/${EVENT_SHORT_NAME}_final`; export const GDQ_STORAGE_ENDPOINT = OFFLINE_MODE ? OFFLINE_STORAGE_ENDPOINT : LIVE_STORAGE_ENDPOINT; export const DONATION_TRACKER_URL = `https://gamesdonequick.com/tracker/index/${EVENT_SHORT_NAME}${EVENT_YEAR}`; export const SECONDARY_COLOR = "#F21847"; export const PRIMARY_COLOR = "#00AEEF"; export const PANEL_BACKGROUND_COLOR = "#EEEEEE"; export const LIGHT_FILL_COLOR = "#DDDDDD"; export const DARK_FILL_COLOR = "#333333";
Fix offline endpoint to point to 2020 instead of 2019
Fix offline endpoint to point to 2020 instead of 2019
JavaScript
mit
bcongdon/sgdq-stats,bcongdon/gdq-stats,bcongdon/sgdq-stats,bcongdon/gdq-stats,bcongdon/sgdq-stats
24c1af11a108aa8be55337f057b453cb1052cab6
test/components/Button_test.js
test/components/Button_test.js
// import { test, getRenderedComponent } from '../spec_helper' // import { default as subject } from '../../src/components/buttons/Button' // test('#render', (assert) => { // const button = getRenderedComponent(subject, {className: 'MyButton'}, 'Yo') // assert.equal(button.type, 'button') // assert.equal(button.props.className, 'MyButton Button') // assert.equal(button.props.classListName, 'Button') // assert.equal(button.props.children, 'Yo') // assert.end() // })
import { expect, getRenderedComponent } from '../spec_helper' import { default as subject } from '../../src/components/buttons/Button' describe('Button#render', () => { it('renders correctly', () => { const button = getRenderedComponent(subject, {className: 'MyButton'}, 'Yo') expect(button.type).to.equal('button') expect(button.props.className).to.equal('MyButton Button') expect(button.props.classListName).to.equal('Button') expect(button.props.children).to.equal('Yo') }) })
Add back in the button tests
Add back in the button tests
JavaScript
mit
ello/webapp,ello/webapp,ello/webapp
0178ee1c94589270d78af013cf7ad493de04b637
src/reducers/index.js
src/reducers/index.js
import { combineReducers } from 'redux' import { RECEIVE_STOP_DATA } from '../actions' const cardsReducer = () => { return {cards: [{name: 'Fruängen', stopId: '9260', updating: false, error: false},{name: 'Slussen', stopId: '9192', updating: false, error: false}]} } const stopsReducer = (state, action) => { switch (action.type) { case RECEIVE_STOP_DATA: var s = Object.assign({}, state) s.stops[action.stop] = action.data.departures return s default: return state == undefined ? {stops: {}} : state } } const departuresApp = combineReducers({ cardsReducer, stopsReducer }) export default departuresApp
import { combineReducers } from 'redux' import { RECEIVE_STOP_DATA } from '../actions' const cardsReducer = () => { return {cards: [ { name: 'Fruängen', stopId: '9260', updating: false, error: false, lines: [{ line: '14', direction: 1 }] }, { name: 'Slussen', stopId: '9192', updating: false, error: false, lines: [{ line: '14', direction: 2 }] }]} } /* * Filter new stop information and add them to the new state */ const stopsReducer = (state, action) => { switch (action.type) { case RECEIVE_STOP_DATA: var newState = Object.assign({}, state) newState.stops[action.stop] = action.data.departures return newState default: return state == undefined ? {stops: {}} : state } } const departuresApp = combineReducers({ cardsReducer, stopsReducer }) export default departuresApp
Add direction information to cards
Add direction information to cards
JavaScript
apache-2.0
Ozzee/sl-departures,Ozzee/sl-departures
6648b1b1027a7fcc099f88339b312c7a03de1cd8
src/server/loggers.js
src/server/loggers.js
'use strict'; var winston = require('winston'); var expressWinston = require('express-winston'); var requestLogger = expressWinston.logger({ transports: [ new winston.transports.Console({ json: true, colorize: true }) ], meta: true, msg: 'HTTP {{req.method}} {{req.url}}', expressFormat: true, colorStatus: true }); var errorLogger = expressWinston.errorLogger({ transports: [ new winston.transports.Console({ json: true, colorize: true }) ] }); var logger = new (winston.Logger)({ transports: [ new (winston.transports.Console)({ timestamp: function() { return Date.now(); }, formatter: function(options) { // Return string will be passed to logger. return options.timestamp() +' '+ options.level.toUpperCase() +' '+ (undefined !== options.message ? options.message : '') + (options.meta && Object.keys(options.meta).length ? '\n\t'+ JSON.stringify(options.meta) : '' ); } }) ] }); module.exports = { request: requestLogger, error: errorLogger, logger: logger };
'use strict'; var winston = require('winston'); var expressWinston = require('express-winston'); var requestLogger = expressWinston.logger({ transports: [ new winston.transports.Console({ json: true, colorize: true }) ], meta: true, msg: 'HTTP {{req.method}} {{req.url}}', expressFormat: true, colorStatus: true }); var errorLogger = expressWinston.errorLogger({ transports: [ new winston.transports.Console({ json: true, colorize: true }) ] }); var logger = new (winston.Logger)({ transports: [ new (winston.transports.Console)({ timestamp: function() { return Date.now(); }, formatter: function(options) { // Return string will be passed to logger. return options.timestamp() +' '+ options.level.toLowerCase() + ': '+ (undefined !== options.message ? options.message : '') + (options.meta && Object.keys(options.meta).length ? '\n\t'+ JSON.stringify(options.meta) : '' ); } }) ] }); module.exports = { request: requestLogger, error: errorLogger, logger: logger };
Change log level to lowercase
Change log level to lowercase
JavaScript
mit
rangle/the-clusternator,rafkhan/the-clusternator,bennett000/the-clusternator,alanthai/the-clusternator,rangle/the-clusternator,bennett000/the-clusternator,bennett000/the-clusternator,rangle/the-clusternator,rafkhan/the-clusternator,alanthai/the-clusternator
7b6ba59b367e90de2137c5300b264578d67e85e1
src/sprites/Turret.js
src/sprites/Turret.js
import Obstacle from './Obstacle' export default class extends Obstacle { constructor (game, player, x, y, frame, bulletFrame) { super(game, player, x, y, frame) this.weapon = this.game.plugins.add(Phaser.Weapon) this.weapon.trackSprite(this) this.weapon.createBullets(50, 'chars_small', bulletFrame) this.weapon.bulletSpeed = 600 this.weapon.fireRate = 200 this.target = null } update () { super.update() this.game.physics.arcade.overlap(this.player, this.weapon.bullets, this.onCollision, null, this) if (!this.inCamera) { return } if (this.target != null) { this.weapon.fireAtSprite(this.target) } else if (this.weapon.fire()) { this.weapon.fireAngle += 30 } } onCollision () { super.onCollision() const saved = this.target this.target = null setTimeout(() => this.target = saved, 1000) } }
import Obstacle from './Obstacle' export default class extends Obstacle { constructor (game, player, x, y, frame, bulletFrame) { super(game, player, x, y, frame) this.weapon = this.game.plugins.add(Phaser.Weapon) this.weapon.trackSprite(this) this.weapon.createBullets(50, 'chars_small', bulletFrame) this.weapon.bulletSpeed = 600 this.weapon.fireRate = 200 this.target = null } update () { super.update() this.game.physics.arcade.overlap(this.player, this.weapon.bullets, this.onCollision, null, this) if (!this.inCamera) { return } if (this.target != null) { this.weapon.fireAtSprite(this.target) } else if (this.weapon.fire()) { this.weapon.fireAngle += 30 } } onCollision () { super.onCollision() if (this.target != null) { const saved = this.target this.target = null setTimeout(() => this.target = saved, 1000) } } }
Fix reaggroing when player gets hit while deaggrod.
Fix reaggroing when player gets hit while deaggrod.
JavaScript
mit
mikkpr/LD38,mikkpr/LD38
ae1be9535929473c219b16e7710d6b2fb969859d
lib/npmrel.js
lib/npmrel.js
var fs = require('fs'); var path = require('path'); var exec = require('child_process').exec; var semver = require('semver'); var sh = require('execSync'); var packageJSONPath = path.join(process.cwd(), 'package.json'); var packageJSON = require(packageJSONPath); module.exports = function(newVersion, commitMessage){ var newSemver = packageJSON.version = getNewSemver(newVersion); fs.writeFileSync(packageJSONPath, JSON.stringify(packageJSON, null, 2)); commitMessage = (commitMessage || 'Release v%s').replace(/%s/g, newSemver); runCommand('git commit -am "' + commitMessage + '"'); runCommand('git tag v' + newSemver); runCommand('git push origin --all'); runCommand('git push origin --tags'); if (!packageJSON.private) runCommand('npm publish'); }; function getNewSemver(newVersion) { var newSemver = semver.valid(newVersion); if (!newSemver) newSemver = semver.inc(packageJSON.version, newVersion); if (!newSemver) throw new Error('Invalid new version'); return newSemver; } function getCommitMessage(commitMessage, newSemver) { commitMessage = commitMessage || 'Release v%s'; return commitMessage.replace(/%s/g, newSemver); } function runCommand(cmd) { if (!sh.run(cmd)) throw new Error('[' + command + '] failed'); }
var fs = require('fs'); var path = require('path'); var exec = require('child_process').exec; var semver = require('semver'); var sh = require('execSync'); var packageJSONPath = path.join(process.cwd(), 'package.json'); var packageJSON = require(packageJSONPath); module.exports = function(newVersion, commitMessage){ var newSemver = packageJSON.version = getNewSemver(newVersion); fs.writeFileSync(packageJSONPath, JSON.stringify(packageJSON, null, 2)); commitMessage = (commitMessage || 'Release v%s').replace(/%s/g, newSemver); runCommand('git commit -am "' + commitMessage + '"'); runCommand('git tag v' + newSemver); runCommand('git push origin --all'); runCommand('git push origin --tags'); if (!packageJSON.private) runCommand('npm publish'); }; function getNewSemver(newVersion) { var newSemver = semver.valid(newVersion); if (!newSemver) newSemver = semver.inc(packageJSON.version, newVersion); if (!newSemver) throw new Error('Invalid new version'); return newSemver; } function getCommitMessage(commitMessage, newSemver) { commitMessage = commitMessage || 'Release v%s'; return commitMessage.replace(/%s/g, newSemver); } function runCommand(cmd) { if (sh.run(cmd)) throw new Error('[' + command + '] failed'); }
Throw errors on non-zero cmd exit codes
Throw errors on non-zero cmd exit codes
JavaScript
mit
tanem/npmrel
c08b8593ffbd3762083af29ea452a09ba5180832
.storybook/webpack.config.js
.storybook/webpack.config.js
const genDefaultConfig = require('@storybook/vue/dist/server/config/defaults/webpack.config.js') const merge = require('webpack-merge') module.exports = (baseConfig, env) => { const storybookConfig = genDefaultConfig(baseConfig, env) const quasarConfig = require('../build/webpack.dev.conf.js') /* when building with storybook we do not want to extract css as we normally do in production */ process.env.DISABLE_EXTRACT_CSS = true const quasarBasePlugins = require('../build/webpack.base.conf.js').plugins // use Quasar config as default let mergedConfig = merge(quasarConfig, storybookConfig) // set Storybook entrypoint mergedConfig.entry = storybookConfig.entry // allow relative module resolution as used in Storybook mergedConfig.resolve.modules = storybookConfig.resolve.modules // only use Quasars loaders mergedConfig.module.rules = quasarConfig.module.rules // enable Storybook http server mergedConfig.plugins = storybookConfig.plugins // get Quasar's DefinePlugin and PostCSS settings mergedConfig.plugins.unshift(quasarBasePlugins[0], quasarBasePlugins[1]) return mergedConfig }
const genDefaultConfig = require('@storybook/vue/dist/server/config/defaults/webpack.config.js') const merge = require('webpack-merge') module.exports = (baseConfig, env) => { /* when building with storybook we do not want to extract css as we normally do in production */ process.env.DISABLE_EXTRACT_CSS = true const storybookConfig = genDefaultConfig(baseConfig, env) const quasarConfig = require('../build/webpack.dev.conf.js') const quasarBasePlugins = require('../build/webpack.base.conf.js').plugins // use Quasar config as default let mergedConfig = merge(quasarConfig, storybookConfig) // set Storybook entrypoint mergedConfig.entry = storybookConfig.entry // allow relative module resolution as used in Storybook mergedConfig.resolve.modules = storybookConfig.resolve.modules // only use Quasars loaders mergedConfig.module.rules = quasarConfig.module.rules // enable Storybook http server mergedConfig.plugins = storybookConfig.plugins // get Quasar's DefinePlugin and PostCSS settings mergedConfig.plugins.unshift(quasarBasePlugins[0], quasarBasePlugins[1]) return mergedConfig }
Set DISABLE_EXTRACT_CSS in correct place
Set DISABLE_EXTRACT_CSS in correct place
JavaScript
mit
yunity/foodsaving-frontend,yunity/karrot-frontend,yunity/foodsaving-frontend,yunity/karrot-frontend,yunity/foodsaving-frontend,yunity/foodsaving-frontend,yunity/karrot-frontend,yunity/karrot-frontend
e30668139c173653ff962d393311f36cb64ab08f
test/components/Post.spec.js
test/components/Post.spec.js
import { expect } from 'chai'; import { mount } from 'enzyme'; import React from 'react'; import Post from '../../src/js/components/Post'; describe('<Post/>', () => { const post = { id: 0, title: 'Test Post', content: 'empty', description: 'empty', author: 'bot', slug: 'test-post', tags: ['test', 'react'], }; it('renders post title', () => { const result = mount(<Post post={post} />); expect(result.find('.post__title').text()).to.eq('Test Post'); }); it('renders post metadata', () => { const result = mount(<Post post={post} />); expect(result.find('.post__meta').text()).to.eq(' a few seconds ago'); }); it('renders post image', () => { const postWithImage = { ...post, img: 'image.png' }; const result = mount(<Post post={postWithImage} />); expect(result.find('.post__image').length).to.eq(1); }); it('renders no image if missing', () => { const result = mount(<Post post={post} />); expect(result.find('.post__image').length).to.eq(0); }); });
import { expect } from 'chai'; import { mount, shallow } from 'enzyme'; import React from 'react'; import Post from '../../src/js/components/Post'; describe('<Post/>', () => { const post = { id: 0, title: 'Test Post', content: 'empty', description: 'empty', author: 'bot', slug: 'test-post', tags: ['test', 'react'], }; it('renders post title', () => { const result = shallow(<Post post={post} />); expect(result.find('.post__title').text()).to.eq('Test Post'); }); it('renders post metadata', () => { const result = mount(<Post post={post} />); expect(result.find('.post__meta').text()).to.eq(' a few seconds ago'); }); it('renders post image', () => { const postWithImage = { ...post, img: 'image.png' }; const result = shallow(<Post post={postWithImage} />); expect(result.find('.post__image').length).to.eq(1); }); it('renders no image if missing', () => { const result = mount(<Post post={post} />); expect(result.find('.post__image').length).to.eq(0); }); });
Replace `mount` calls with `shallow` in <Post> tests
Replace `mount` calls with `shallow` in <Post> tests
JavaScript
mit
slavapavlutin/pavlutin-node,slavapavlutin/pavlutin-node
4f1c3887f77927ac93daa825357b4bf94914d9f1
test/remove.js
test/remove.js
#!/usr/bin/env node 'use strict'; /** Load modules. */ var fs = require('fs'), path = require('path'); /** Resolve program params. */ var args = process.argv.slice(process.argv[0] === process.execPath ? 2 : 0), filePath = path.resolve(args[1]); var pattern = (function() { var result = args[0], delimiter = result.charAt(0), lastIndex = result.lastIndexOf(delimiter); return RegExp(result.slice(1, lastIndex), result.slice(lastIndex + 1)); }()); /** Used to match lines of code. */ var reLine = /.*/gm; /*----------------------------------------------------------------------------*/ fs.writeFileSync(filePath, fs.readFileSync(filePath, 'utf-8').replace(pattern, function(match) { return match.replace(reLine, ''); }), 'utf-8');
#!/usr/bin/env node 'use strict'; /** Load modules. */ var fs = require('fs'), path = require('path'); /** Resolve program params. */ var args = process.argv.slice(process.argv[0] === process.execPath ? 2 : 0), filePath = path.resolve(args[1]); var pattern = (function() { var result = args[0], delimiter = result.charAt(0), lastIndex = result.lastIndexOf(delimiter); return RegExp(result.slice(1, lastIndex), result.slice(lastIndex + 1)); }()); /** Used to match lines of code. */ var reLine = /.*/gm; /*----------------------------------------------------------------------------*/ fs.writeFileSync(filePath, fs.readFileSync(filePath, 'utf-8').replace(pattern, function(match) { return match.replace(reLine, ''); }));
Remove 'utf-8' option because it's the default.
Remove 'utf-8' option because it's the default.
JavaScript
mit
steelsojka/lodash,msmorgan/lodash,steelsojka/lodash,beaugunderson/lodash,boneskull/lodash,msmorgan/lodash,boneskull/lodash,rlugojr/lodash,beaugunderson/lodash,rlugojr/lodash
2b0dd27492594ee525eab38f6f4428d596d31207
tests/tests.js
tests/tests.js
QUnit.test( "hello test", function( assert ) { assert.ok( 1 == "1", "Passed!" ); });
QUnit.test( "getOptions default", function( assert ) { var options = $.fn.inputFileText.getOptions(); assert.equal(options.text, 'Choose File', 'Should return default text option when no text option is provided.'); assert.equal(options.remove, false, 'Should return default remove option when no text option is provided.'); });
Test that getOptions returns default options when none are provided
Test that getOptions returns default options when none are provided
JavaScript
mit
datchung/jquery.inputFileText,datchung/jquery.inputFileText
05f554d4bdd9f5e5af4959e97c29d6566f8824e0
app/scripts/directives/clojurepipeline.js
app/scripts/directives/clojurepipeline.js
'use strict'; /** * @ngdoc directive * @name grafterizerApp.directive:clojurePipeline * @description * # clojurePipeline */ angular.module('grafterizerApp') .directive('clojurePipeline', function (generateClojure) { return { template: '<div ui-codemirror="editorOptions" ng-model="clojure"></div>', restrict: 'E', scope: { transformation: '=', }, link: { pre: function(scope) { scope.editorOptions = { lineWrapping : true, // lineNumbers: true, mode: 'clojure', readOnly: true }; }, post: function(scope, element, attrs) { scope.$watch('transformation', function(){ if (!scope.transformation) { return; } // console.log(scope.transformation) scope.clojure = generateClojure.fromTransformation(scope.transformation); }, true); } } }; });
'use strict'; /** * @ngdoc directive * @name grafterizerApp.directive:clojurePipeline * @description * # clojurePipeline */ angular.module('grafterizerApp') .directive('clojurePipeline', function (generateClojure) { return { template: '<div ui-codemirror="editorOptions" ng-model="clojure"></div>', restrict: 'E', scope: { transformation: '=', }, link: { pre: function(scope) { scope.editorOptions = { lineWrapping : true, // lineNumbers: true, mode: 'clojure', readOnly: true }; }, post: function(scope, element, attrs) { scope.$watch('transformation', function(){ if (!scope.transformation) { return; } // console.log(scope.transformation) scope.clojure = generateClojure.fromTransformation(scope.transformation); }, true); // TODO workaround random bug scope.$watch("$parent.selectedTabIndex", function(){ if (scope['$parent'].selectedTabIndex) { window.setTimeout(function(){ try { element.children().children()[0].CodeMirror.refresh(); }catch(e){} }, 1); } }); } } }; });
Refresh the CodeMirror view if it's inside a md-tabs
Refresh the CodeMirror view if it's inside a md-tabs Featuring a setTimeout
JavaScript
epl-1.0
datagraft/grafterizer,dapaas/grafterizer,dapaas/grafterizer,datagraft/grafterizer
a8b64f852c6e223b21a4052fa9af885e79f6692e
app/server/shared/api-server/api-error.js
app/server/shared/api-server/api-error.js
/** * Copyright © 2017 Highpine. All rights reserved. * * @author Max Gopey <gopeyx@gmail.com> * @copyright 2017 Highpine * @license https://opensource.org/licenses/MIT MIT License */ class ApiError { constructor(message) { this.message = message; this.stack = Error().stack; } static withStatusCode (statusCode, message) { let apiError = new ApiError(message); apiError.status = statusCode; return apiError; }; } module.exports = ApiError;
/** * Copyright © 2017 Highpine. All rights reserved. * * @author Max Gopey <gopeyx@gmail.com> * @copyright 2017 Highpine * @license https://opensource.org/licenses/MIT MIT License */ class ApiError extends Error { constructor(message, id) { super(message, id); this.message = message; this.stack = Error().stack; } static withStatusCode (statusCode, message) { let apiError = new ApiError(message); apiError.status = statusCode; return apiError; }; } module.exports = ApiError;
Add inheritance from Error for ApiError
Add inheritance from Error for ApiError
JavaScript
mit
highpine/highpine,highpine/highpine,highpine/highpine
fbb7654967bb83d7c941e9eef6a87162fbff676b
src/actions/index.js
src/actions/index.js
// import axios from 'axios'; export const FETCH_SEARCH_RESULTS = 'fetch_search_results'; // const ROOT_URL = 'http://herokuapp.com/'; export function fetchSearchResults(term, location) { // const request = axios.get(`${ROOT_URL}/${term}/${location}`); const testJSON = { data: [ { name: 'Michael Mina', url: 'yelp.com/michaelminna' }, { name: 'Sushi', url: 'yelp.com/sushi' }, { name: 'Thai', url: 'yelp.com/thai' }, { name: 'Chinese', url: 'yelp.com/chinese' } ] }; return { type: FETCH_SEARCH_RESULTS, payload: testJSON } }
import axios from 'axios'; export const FETCH_SEARCH_RESULTS = 'fetch_search_results'; const ROOT_URL = 'https://earlybirdsearch.herokuapp.com/?'; export function fetchSearchResults(term, location) { const request = axios.get(`${ROOT_URL}business=${term}&location=${location}`); console.log(request); // const testJSON = { // data: [ // { name: 'Michael Mina', url: 'yelp.com/michaelminna' }, // { name: 'Sushi', url: 'yelp.com/sushi' }, // { name: 'Thai', url: 'yelp.com/thai' }, // { name: 'Chinese', url: 'yelp.com/chinese' } // ] // }; return { type: FETCH_SEARCH_RESULTS, payload: request } }
Add heroku url to axios request
Add heroku url to axios request
JavaScript
mit
EarlyRavens/ReactJSFrontEnd,EarlyRavens/ReactJSFrontEnd
c6dc037de56ebc5b1beb853cc89478c1228f95b9
lib/repositories/poets_repository.js
lib/repositories/poets_repository.js
var _ = require('underscore'); module.exports = function(dbConfig) { var db = require('./poemlab_database')(dbConfig); return { create: function(user_data, callback) { var params = _.values(_.pick(user_data, ["name", "email", "password"])); db.query("insert into poets (name, email, password) values ($1, $2, $3) returning id", params, function(err, result) { if (err) { return callback(err); } var user = { id: result.rows[0].id }; callback(null, user); } ); }, read: function(user_id, callback) { db.query("select * from poets where id = $1", [user_id], function(err, result) { if (err) { return callback(err); } callback(null, result.rows[0]); }); }, destroy: function(user_id, callback) { db.query("delete from poets where id = $1", [user_id], function(err, result) { callback(err); }); }, all: function(callback) { db.query("select * from poets", [], function(err, result) { if (err) { return callback(err); } callback(null, result.rows); }); } }; };
var _ = require('underscore'); module.exports = function(dbConfig) { var db = require('./poemlab_database')(dbConfig); return { create: function(user_data, callback) { var params = _.values(_.pick(user_data, ["name", "email", "password"])); db.query("insert into poets (name, email, password) values ($1, $2, $3) " + "returning id, name, email", params, function(err, result) { if (err) { return callback(err); } callback(null, result.rows[0]); } ); }, read: function(user_id, callback) { db.query("select * from poets where id = $1", [user_id], function(err, result) { if (err) { return callback(err); } callback(null, result.rows[0]); }); }, destroy: function(user_id, callback) { db.query("delete from poets where id = $1", [user_id], function(err, result) { callback(err); }); }, all: function(callback) { db.query("select * from poets", [], function(err, result) { if (err) { return callback(err); } callback(null, result.rows); }); } }; };
Return all poet attributes except password from create method
Return all poet attributes except password from create method
JavaScript
mit
jimguys/poemlab,jimguys/poemlab
f620f2919897b40b9f960a3e147c54be0d0d6549
src/cssrelpreload.js
src/cssrelpreload.js
/*! CSS rel=preload polyfill. Depends on loadCSS function. [c]2016 @scottjehl, Filament Group, Inc. Licensed MIT */ (function( w ){ // rel=preload support test if( !w.loadCSS ){ return; } var rp = loadCSS.relpreload = {}; rp.support = function(){ try { return w.document.createElement( "link" ).relList.supports( "preload" ); } catch (e) { return false; } }; // loop preload links and fetch using loadCSS rp.poly = function(){ var links = w.document.getElementsByTagName( "link" ); for( var i = 0; i < links.length; i++ ){ var link = links[ i ]; if( link.rel === "preload" && link.getAttribute( "as" ) === "style" ){ w.loadCSS( link.href, link ); link.rel = null; } } }; // if link[rel=preload] is not supported, we must fetch the CSS manually using loadCSS if( !rp.support() ){ rp.poly(); var run = w.setInterval( rp.poly, 300 ); if( w.addEventListener ){ w.addEventListener( "load", function(){ w.clearInterval( run ); } ); } if( w.attachEvent ){ w.attachEvent( "onload", function(){ w.clearInterval( run ); } ) } } }( this ));
/*! CSS rel=preload polyfill. Depends on loadCSS function. [c]2016 @scottjehl, Filament Group, Inc. Licensed MIT */ (function( w ){ // rel=preload support test if( !w.loadCSS ){ return; } var rp = loadCSS.relpreload = {}; rp.support = function(){ try { return w.document.createElement( "link" ).relList.supports( "preload" ); } catch (e) { return false; } }; // loop preload links and fetch using loadCSS rp.poly = function(){ var links = w.document.getElementsByTagName( "link" ); for( var i = 0; i < links.length; i++ ){ var link = links[ i ]; if( link.rel === "preload" && link.getAttribute( "as" ) === "style" ){ w.loadCSS( link.href, link ); link.rel = null; } } }; // if link[rel=preload] is not supported, we must fetch the CSS manually using loadCSS if( !rp.support() ){ rp.poly(); var run = w.setInterval( rp.poly, 300 ); if( w.addEventListener ){ w.addEventListener( "load", function(){ rp.poly(); w.clearInterval( run ); } ); } if( w.attachEvent ){ w.attachEvent( "onload", function(){ w.clearInterval( run ); } ) } } }( this ));
Fix for bug where script might not be called
Fix for bug where script might not be called Firefox and IE/Edge won't load links that appear after the polyfill. What I think has been happening is the w.load event fires and clears the "run" interval before it has a chance to load styles that occur in between the last interval. This addition calls the rp.poly function one last time to make sure it catches any that occur within that interval gap. Original demo with link after polyfill (non-working in Firefox, IE, Edge): http://s.codepen.io/fatjester/debug/gMMrxv Modified version with link after polyfill (is working in Firefox, IE, Edge): http://s.codepen.io/fatjester/debug/gMMrxv #180
JavaScript
mit
filamentgroup/loadCSS,filamentgroup/loadCSS
dc706a5bc91d647fade86d3f9d948a95e447be35
javascript/signup.js
javascript/signup.js
function submitEmail() { var button = document.getElementById('submit'); button.onclick = function() { var parent = document.getElementById('parent').value; var phone = document.getElementById('phone-number').value; var student = document.getElementById('student').value; var age = document.getElementById('age').value; var allergies = document.getElementById('allergies').value; var comments = document.getElementById('comments').value; var mailto = 'mailto:gpizarro@javaman.net'; var subject = '&subject=I%20Would%20Like%20To%20Sign%20My%20Child%20Up'; var body = '&body='; body += 'I would like to sign ' + student + ' up for Code Reboot 2017.'; body += ' ' + student + ' is ' + age + ' years old.'; if(allergies != '') { body += '%0A %0AAllergies: %0A' + allergies; } if(comments != '') { body += '%0A %0AMy Comments: %0A' + comments; } body += '%0A %0AThank you, %0A' + parent + ' %0A' + phone; console.log(mailto + subject + body); window.location.replace(mailto + subject + body); } }
function submitEmail() { var button = document.getElementById('submit'); button.onclick = function() { var parent = document.getElementById('parent').value; var phone = document.getElementById('phone-number').value; var student = document.getElementById('student').value; var age = document.getElementById('age').value; var allergies = document.getElementById('allergies').value; var comments = document.getElementById('comments').value; var mailto = 'mailto:gpizarro@javaman.net'; var subject = '?subject=I%20Would%20Like%20To%20Sign%20My%20Child%20Up'; var body = '&body='; body += 'I would like to sign ' + student + ' up for Code Reboot 2017.'; body += ' ' + student + ' is ' + age + ' years old.'; if(allergies != '') { body += '%0A %0AAllergies: %0A' + allergies; } if(comments != '') { body += '%0A %0AMy Comments: %0A' + comments; } body += '%0A %0AThank you, %0A' + parent + ' %0A' + phone; console.log(mailto + subject + body); window.location.replace(mailto + subject + body); } }
Change & to ? | FIXED
Change & to ? | FIXED
JavaScript
apache-2.0
Coding-Camp-2017/website,Coding-Camp-2017/website
c3609cbe9d33222f2bd5c466b874f4943094143f
src/middleware/authenticate.js
src/middleware/authenticate.js
export default (config) => { if ( ! config.enabled) return (req, res, next) => { next() } var header = (config.header || 'Authorization').toLowerCase() var tokenLength = 32 var tokenRegExp = new RegExp(`^Token ([a-zA-Z0-9]{${tokenLength}})$`) return (req, res, next) => { var value = req.headers[header] var err req.auth = { header: value } if ( ! req.auth.header) { err = new Error(`Missing ${config.header} header.`) err.statusCode = 401 return next(err) } if (config.byToken) { var token = value.replace(tokenRegExp, '$1') if (token.length !== tokenLength) { err = new Error('Invalid token.') err.statusCode = 401 return next(err) } req.auth.token = token } if ( ! config.method) return next() config.method(req, config, req.data, (err, user) => { if (err) { err = new Error(err) err.statusCode = 401 return next(err) } req.user = user next() }) } }
export default (config) => { if ( ! config.enabled) return (req, res, next) => { next() } var verifyHeader = ( !! config.header) var header = (config.header || '').toLowerCase() var tokenLength = 32 var tokenRegExp = new RegExp(`^Token ([a-zA-Z0-9]{${tokenLength}})$`) return (req, res, next) => { var err req.auth = {} if (verifyHeader) { var value = req.auth.header = req.headers[header] if ( ! value) { err = new Error(`Missing ${config.header} header.`) err.statusCode = 401 return next(err) } if (config.byToken) { var token = value.replace(tokenRegExp, '$1') if (token.length !== tokenLength) { err = new Error('Invalid token.') err.statusCode = 401 return next(err) } req.auth.token = token } } if ( ! config.method) return next() config.method(req, config, req.data, (err, user) => { if (err) { err = new Error(err) err.statusCode = 401 return next(err) } req.user = user next() }) } }
Make request header optional in authentication middleware.
Make request header optional in authentication middleware.
JavaScript
mit
kukua/concava
983c7b9e42902589a4d893b8d327a49650a761c9
src/fuzzy-wrapper.js
src/fuzzy-wrapper.js
import React from 'react'; import PropTypes from "prop-types"; export default class FuzzyWrapper extends React.Component { constructor(props) { super(); this.state = { isOpen: false, }; // create a bound function to invoke when keys are pressed on the body. this.keyEvent = (function(event) { if (this.props.isKeyPressed(event)) { event.preventDefault(); this.setState({isOpen: !this.state.isOpen}); } }).bind(this); } componentDidMount() { document.body.addEventListener('keydown', this.keyEvent); } componentWillUnmount() { document.body.removeEventListener('keydown', this.keyEvent); } // Called by the containing fuzzysearcher to close itself. onClose() { this.setState({isOpen: false}); } render() { return this.props.popup( this.state.isOpen, this.onClose.bind(this), ); } } FuzzyWrapper.PropTypes = { isKeyPressed: PropTypes.func.isRequired, popup: PropTypes.func.isRequired, }; FuzzyWrapper.defaultProps = { isKeyPressed: () => false, popup: () => null, };
import React from 'react'; import PropTypes from "prop-types"; export default class FuzzyWrapper extends React.Component { constructor(props) { super(); this.state = { isOpen: false, }; // create a bound function to invoke when keys are pressed on the body. this.keyEvent = (function(event) { if (this.props.isKeyPressed(event)) { event.preventDefault(); this.setState({isOpen: !this.state.isOpen}); } }).bind(this); } componentDidMount() { document.body.addEventListener('keydown', this.keyEvent); } componentWillUnmount() { document.body.removeEventListener('keydown', this.keyEvent); } // Called by the containing fuzzysearcher to close itself. onClose() { this.setState({isOpen: false}); } render() { return this.props.popup( this.state.isOpen, this.onClose.bind(this), ); } } FuzzyWrapper.propTypes = { isKeyPressed: PropTypes.func.isRequired, popup: PropTypes.func.isRequired, }; FuzzyWrapper.defaultProps = { isKeyPressed: () => false, popup: () => null, };
Fix propTypes warning in FuzzyWrapper
Fix propTypes warning in FuzzyWrapper
JavaScript
mit
1egoman/fuzzy-picker
365e1016f05fab1b739b318d5bfacaa926bc8f96
src/lib/getIssues.js
src/lib/getIssues.js
const Request = require('request'); module.exports = (user, cb) => { Request.get({ url: `https://api.github.com/users/${user}/repos`, headers: { 'User-Agent': 'GitPom' } }, cb); };
const Request = require('request'); module.exports = (options, cb) => { Request.get({ url: `https://api.github.com/repos/${options.repoOwner}/${options.repoName}/issues`, headers: { 'User-Agent': 'GitPom', Accept: `application/vnd.github.v3+json`, Authorization: `token ${options.access_token}` } }, cb); };
Build module to fetch issues for a selected repo
Build module to fetch issues for a selected repo
JavaScript
mit
The-Authenticators/gitpom,The-Authenticators/gitpom
07b845fc27fdd3ef75f517e6554a1fef762233b7
client/js/helpers/rosetexmanager.js
client/js/helpers/rosetexmanager.js
'use strict'; function _RoseTextureManager() { this.textures = {}; } _RoseTextureManager.prototype.normalizePath = function(path) { return path; }; _RoseTextureManager.prototype._load = function(path, callback) { var tex = DDS.load(path, function() { if (callback) { callback(); } }); tex.minFilter = tex.magFilter = THREE.LinearFilter; return tex; }; _RoseTextureManager.prototype.load = function(path, callback) { var normPath = this.normalizePath(path); var foundTex = this.textures[normPath]; if (foundTex) { if (callback) { callback(); } return foundTex; } var newTex = this._load(path, callback); this.textures[normPath] = newTex; return newTex; }; var RoseTextureManager = new _RoseTextureManager();
'use strict'; function _RoseTextureManager() { this.textures = {}; } _RoseTextureManager.prototype._load = function(path, callback) { var tex = DDS.load(path, function() { if (callback) { callback(); } }); tex.minFilter = tex.magFilter = THREE.LinearFilter; return tex; }; _RoseTextureManager.prototype.load = function(path, callback) { var normPath = normalizePath(path); var foundTex = this.textures[normPath]; if (foundTex) { if (callback) { callback(); } return foundTex; } var newTex = this._load(path, callback); this.textures[normPath] = newTex; return newTex; }; var RoseTextureManager = new _RoseTextureManager();
Make RoseTexManager use global normalizePath.
Make RoseTexManager use global normalizePath.
JavaScript
agpl-3.0
brett19/rosebrowser,brett19/rosebrowser,Jiwan/rosebrowser,exjam/rosebrowser,Jiwan/rosebrowser,exjam/rosebrowser
fa40d7c3a2bdb01a72855103fa72095667fddb71
js/application.js
js/application.js
// View $(document).ready(function() { console.log("Ready!"); // initialize the game and create a board var game = new Game(); PopulateBoard(game.flattenBoard()); //Handles clicks on the checkers board $(".board").on("click", function(e){ e.preventDefault(); game.test(game); }) // .board on click, a funciton }) // end (document).ready var PopulateBoard = function(board){ board.forEach(function(value, index){ if (value == "green"){ console.log("GREEN"); console.log(index); $(".board").append($.parseHTML('<a href="'+(index+1)+'" id="square'+(index+1)+'" class="green"></a>')); } else if (value == "blue"){ console.log("blue"); // $(".board").append($.parseHTML('<a href="'+(index+1)+'" id="square'+(index+1)+'" class="blue"></a>')); } else if (value == "empty"){ console.log("Empty"); } }) }
// View $(document).ready(function() { console.log("Ready!"); // initialize the game and create a board var game = new Game(); PopulateBoard(game.flattenBoard()); //Handles clicks on the checkers board $(".board").on("click", function(e){ e.preventDefault(); game.test(game); }) // .board on click, a funciton }) // end (document).ready var PopulateBoard = function(board){ board.forEach(function(value, index){ if (value == "green"){ console.log("GREEN"); console.log(index); $(".board").append($.parseHTML('<a href="'+(index+1)+'" id="square'+(index+1)+'" class="green"></a>')); } else if (value == "blue"){ console.log("blue"); // $(".board").append($.parseHTML('<a href="'+(index+1)+'" id="square'+(index+1)+'" class="blue"></a>')); } else if (value == "empty"){ console.log("Empty"); } else { $(".board").append($.parseHTML('<div class="null"></div>')); } }) }
Add else to into populate board to create a div elemento for the not used squares
Add else to into populate board to create a div elemento for the not used squares
JavaScript
mit
RenanBa/checkers-v1,RenanBa/checkers-v1
87cf25bf581b4c96562f884d4b9c329c3c36a469
lib/config.js
lib/config.js
'use strict'; var _ = require('lodash') , defaultConf, developmentConf, env, extraConf, productionConf, testConf; env = process.env.NODE_ENV || 'development'; defaultConf = { logger: 'dev', port: process.env.PORT || 3000, mongoUri: 'mongodb://localhost/SecureChat' }; developmentConf = {}; productionConf = { mongoUri: process.env.MONGOLAB_URI }; testConf = { mongoUri: 'mongodb://localhost/SecureChatTest' }; extraConf = { development: developmentConf, production: productionConf, test: testConf }[env]; module.exports = _.merge(defaultConf, extraConf);
'use strict'; var _ = require('lodash') , defaultConf, developmentConf, env, extraConf, productionConf, testConf; env = process.env.NODE_ENV || 'development'; defaultConf = { port: process.env.PORT || 3000, }; developmentConf = { logger: 'dev', mongoUri: 'mongodb://localhost/SecureChat' }; productionConf = { logger: 'default', mongoUri: process.env.MONGOLAB_URI }; testConf = { logger: function () {}, mongoUri: 'mongodb://localhost/SecureChatTest' }; extraConf = { development: developmentConf, production: productionConf, test: testConf }[env]; module.exports = _.merge(defaultConf, extraConf);
Change loggers and move some options
Change loggers and move some options
JavaScript
mit
Hilzu/SecureChat
028b0c515a4d5e0bf26ca76cb101272b49f25219
client/index.js
client/index.js
// client start file const Display = require('./interface.js'); const network = require('./network.js'); let dis = new Display(); // TODO: placeholder nick let nick = "Kneelawk"; // TODO: placeholder server let server = "http://localhost:8080"; let session; network.login(server, nick).on('login', (body) => { session = body; }).on('error', (error) => { // TODO: error handling }); let lastTime = 0; let updateLoopId = setInterval(() => { network.update(server, lastTime).on('response', (messages) => { if (messages && messages.length > 0) { messages.sort((a, b) => { if (a.timestamp > b.timestamp) return 1; else if (a.timestamp < b.timestamp) return -1; else return 0; }); messages.forEach((element) => { dis.recieve(element.timestamp, element.nick, element.body); }); lastTime = messages[messages.length - 1].timestamp; } }).on('error', (error) => { // TODO: error handling }); }, 1000); // checking every second should be good enough // TODO: get input from user // TODO: stopping the client and disconnecting
// client start file const Display = require('./interface.js'); const network = require('./network.js'); let dis = new Display(); // TODO: placeholder nick let nick = "Kneelawk"; // TODO: placeholder server let server = "http://localhost:8080"; let session; network.login(server, nick).on('login', (body) => { if (!body) { // TODO: more error handling } session = body; }).on('error', (error) => { // TODO: error handling }); let lastTime = 0; let updateLoopId = setInterval(() => { network.update(server, lastTime).on('response', (messages) => { if (messages && messages.length > 0) { messages.sort((a, b) => { if (a.timestamp > b.timestamp) return 1; else if (a.timestamp < b.timestamp) return -1; else return 0; }); messages.forEach((element) => { dis.recieve(element.timestamp, element.nick, element.body); }); lastTime = messages[messages.length - 1].timestamp; } }).on('error', (error) => { // TODO: error handling }); }, 1000); // checking every second should be good enough // TODO: get input from user // TODO: stopping the client and disconnecting
Add check for invalid connection
Add check for invalid connection
JavaScript
mit
PokerDaddy/scaling-potato,PokerDaddy/scaling-potato
beb7349f523e7087979260698c9e799684ecc531
scripts/components/button-group.js
scripts/components/button-group.js
'use strict'; var VNode = require('virtual-dom').VNode; var VText = require('virtual-dom').VText; /** * Button. * * @param {object} props * @param {string} props.text * @param {function} [props.onClick] * @param {string} [props.style=primary] * @param {string} [props.type=button] * @returns {VNode} */ function button(props) { var className = 'coins-logon-widget-button'; var onClick = props.onClick; var style = props.style || 'primary'; var text = props.text; var type = props.type || 'button'; className += ' coins-logon-widget-button-' + style; var properties = { className: className, type: type, }; if (onClick) { properties.onclick = onClick; } return new VNode('button', properties, [new VText(text)]); } /** * Button group. * * @see button * * @{param} {...object} props Properties passed to `button` * @returns {VNode} */ function buttonGroup(props) { var children = arguments.length > 1 ? [].slice.call(arguments).map(button) : [button(props)]; var className = 'coins-logon-widget-button-group'; return new VNode('div', { className: className }, children); } module.exports = buttonGroup;
'use strict'; var VNode = require('virtual-dom').VNode; var VText = require('virtual-dom').VText; /** * Button. * @private * * @param {object} props * @param {string} props.text * @param {function} [props.onClick] * @param {string} [props.style=primary] * @param {string} [props.type=button] * @returns {VNode} */ function _button(props) { var className = 'coins-logon-widget-button'; var onClick = props.onClick; var style = props.style || 'primary'; var text = props.text; var type = props.type || 'button'; className += ' coins-logon-widget-button-' + style; var properties = { className: className, type: type, }; if (onClick) { properties.onclick = onClick; } return new VNode('button', properties, [new VText(text)]); } /** * Button group. * * @see button * * @{param} {...object} props Properties passed to `button` * @returns {VNode} */ function buttonGroup(props) { var children = arguments.length > 1 ? [].slice.call(arguments).map(_button) : [_button(props)]; var className = 'coins-logon-widget-button-group'; return new VNode('div', { className: className }, children); } module.exports = buttonGroup;
Make 'button' component more obviously private.
Make 'button' component more obviously private.
JavaScript
mit
MRN-Code/coins-logon-widget,MRN-Code/coins-logon-widget
b8864dc79530a57b5974bed932adb0e4c6ccf73c
server/api/nodes/nodeController.js
server/api/nodes/nodeController.js
var Node = require('./nodeModel.js'), handleError = require('../../util.js').handleError, handleQuery = require('../queryHandler.js'); module.exports = { createNode : function (req, res, next) { var newNode = req.body; // Support /nodes and /roadmaps/roadmapID/nodes newNode.parentRoadmap = newNode.parentRoadmap || req.params.roadmapID; Node(newNode).save() .then(function(dbResults){ res.status(201).json(dbResults); }) .catch(handleError(next)); }, getNodeByID : function (req, res, next) { var _id = req.params.nodeID; Node.findById(_id) .then(function(dbResults){ res.json(dbResults); }) .catch(handleError(next)); }, updateNode : function (req, res, next) { var _id = req.params.nodeID; var updateCommand = req.body; Node.findByIdAndUpdate(_id, updateCommand) .then(function(dbResults){ res.json(dbResults); }) .catch(handleError(next)); }, deleteNode : function (req, res, next) { } };
var Node = require('./nodeModel.js'), handleError = require('../../util.js').handleError, handleQuery = require('../queryHandler.js'); module.exports = { createNode : function (req, res, next) { var newNode = req.body; // Support /nodes and /roadmaps/roadmapID/nodes newNode.parentRoadmap = newNode.parentRoadmap || req.params.roadmapID; Node(newNode).save() .then(function(dbResults){ res.status(201).json(dbResults); }) .catch(handleError(next)); }, getNodeByID : function (req, res, next) { var _id = req.params.nodeID; Node.findById(_id) .then(function(dbResults){ res.json(dbResults); }) .catch(handleError(next)); }, updateNode : function (req, res, next) { var _id = req.params.nodeID; var updateCommand = req.body; Node.findByIdAndUpdate(_id, updateCommand) .then(function(dbResults){ res.json(dbResults); }) .catch(handleError(next)); }, deleteNode : function (req, res, next) { var _id = req.params.nodeID; Node.findByIdAndRemove(_id) .then(function(dbResults){ res.json(dbResults); }) .catch(handleError(next)); } };
Add route handler for DELETE /api/nodes/:nodeID
Add route handler for DELETE /api/nodes/:nodeID
JavaScript
mit
sreimer15/RoadMapToAnything,GMeyr/RoadMapToAnything,delventhalz/RoadMapToAnything,cyhtan/RoadMapToAnything,sreimer15/RoadMapToAnything,cyhtan/RoadMapToAnything,RoadMapToAnything/RoadMapToAnything,GMeyr/RoadMapToAnything,RoadMapToAnything/RoadMapToAnything,delventhalz/RoadMapToAnything
2cbe06fdf4fa59605cb41a5f6bfb9940530989b5
src/schemas/index.js
src/schemas/index.js
import {header} from './header'; import {mime} from './mime'; import {security} from './security'; import {tags} from './tags'; import {paths} from './paths'; import {types} from './types'; export const fieldsToShow = { 'header': [ 'info', 'contact', 'license', 'host', 'basePath' ], 'types': ['definitions'], 'mime': ['consumes', 'produces'] }; export const schema = { 'type': 'object', 'children': { header, mime, security, tags, paths, types, 'definitions': { 'type': 'link', 'target': '/types' }, 'info': { 'type': 'link', 'target': '/header/info' }, 'contact': { 'type': 'link', 'target': '/header/contact' }, 'license': { 'type': 'link', 'target': '/header/license' }, 'host': { 'type': 'link', 'target': '/header/host/host' }, 'basePath': { 'type': 'link', 'target': '/header/host/basePath' }, 'schemes': { 'type': 'link', 'target': '/header/host/schemes' }, 'consumes': { 'type': 'link', 'target': '/mime/consumes' }, 'produces': { 'type': 'link', 'target': '/mime/produces' } } };
import {header} from './header'; import {mime} from './mime'; import {security} from './security'; import {tags} from './tags'; import {paths} from './paths'; import {types} from './types'; export const fieldsToShow = { 'header': [ 'info', 'contact', 'license', 'host', 'basePath', 'schemes' ], 'types': ['definitions'], 'mime': ['consumes', 'produces'] }; export const schema = { 'type': 'object', 'children': { header, mime, security, tags, paths, types, 'definitions': { 'type': 'link', 'target': '/types' }, 'info': { 'type': 'link', 'target': '/header/info' }, 'contact': { 'type': 'link', 'target': '/header/contact' }, 'license': { 'type': 'link', 'target': '/header/license' }, 'host': { 'type': 'link', 'target': '/header/host/host' }, 'basePath': { 'type': 'link', 'target': '/header/host/basePath' }, 'schemes': { 'type': 'link', 'target': '/header/host/schemes' }, 'consumes': { 'type': 'link', 'target': '/mime/consumes' }, 'produces': { 'type': 'link', 'target': '/mime/produces' } } };
Add Schemes to JSON preview
Add Schemes to JSON preview
JavaScript
mit
apinf/open-api-designer,apinf/openapi-designer,apinf/openapi-designer,apinf/open-api-designer
2f63b0d6c9f16e4820d969532e8f9ae00ab66bdd
eslint-rules/no-primitive-constructors.js
eslint-rules/no-primitive-constructors.js
/** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @emails react-core */ 'use strict'; module.exports = function(context) { function report(node, name, msg) { context.report(node, `Do not use the ${name} constructor. ${msg}`); } function check(node) { const name = node.callee.name; switch (name) { case 'Boolean': report( node, name, 'To cast a value to a boolean, use double negation: !!value' ); break; case 'String': report( node, name, 'To cast a value to a string, concat it with the empty string ' + '(unless it\'s a symbol, which have different semantics): ' + '\'\' + value' ); break; } } return { CallExpression: check, NewExpression: check, }; };
/** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @emails react-core */ 'use strict'; module.exports = function(context) { function report(node, name, msg) { context.report(node, `Do not use the ${name} constructor. ${msg}`); } function check(node) { const name = node.callee.name; switch (name) { case 'Boolean': report( node, name, 'To cast a value to a boolean, use double negation: !!value' ); break; case 'String': report( node, name, 'To cast a value to a string, concat it with the empty string ' + '(unless it\'s a symbol, which have different semantics): ' + '\'\' + value' ); break; case 'Number': report( node, name, 'To cast a value to a number, use the plus operator: +value' ); break; } } return { CallExpression: check, NewExpression: check, }; };
Add error for number constructor, too
Add error for number constructor, too
JavaScript
mit
aickin/react,jquense/react,billfeller/react,mhhegazy/react,nhunzaker/react,silvestrijonathan/react,brigand/react,trueadm/react,kaushik94/react,prometheansacrifice/react,cpojer/react,mosoft521/react,joecritch/react,yungsters/react,glenjamin/react,jdlehman/react,facebook/react,roth1002/react,edvinerikson/react,TheBlasfem/react,mjackson/react,edvinerikson/react,jdlehman/react,kaushik94/react,roth1002/react,camsong/react,syranide/react,silvestrijonathan/react,jorrit/react,yiminghe/react,mhhegazy/react,anushreesubramani/react,trueadm/react,jordanpapaleo/react,maxschmeling/react,ericyang321/react,pyitphyoaung/react,glenjamin/react,camsong/react,silvestrijonathan/react,apaatsio/react,yungsters/react,tomocchino/react,pyitphyoaung/react,camsong/react,yungsters/react,wmydz1/react,jameszhan/react,maxschmeling/react,nhunzaker/react,aickin/react,Simek/react,apaatsio/react,jameszhan/react,pyitphyoaung/react,roth1002/react,terminatorheart/react,facebook/react,nhunzaker/react,jzmq/react,anushreesubramani/react,acdlite/react,edvinerikson/react,wmydz1/react,yangshun/react,shergin/react,apaatsio/react,jdlehman/react,roth1002/react,ArunTesco/react,mjackson/react,joecritch/react,camsong/react,kaushik94/react,yangshun/react,prometheansacrifice/react,VioletLife/react,empyrical/react,cpojer/react,trueadm/react,rricard/react,rricard/react,VioletLife/react,mhhegazy/react,VioletLife/react,rickbeerendonk/react,jorrit/react,mjackson/react,aickin/react,jorrit/react,jameszhan/react,mjackson/react,flarnie/react,sekiyaeiji/react,STRML/react,jordanpapaleo/react,mosoft521/react,yungsters/react,ericyang321/react,yiminghe/react,jordanpapaleo/react,empyrical/react,dilidili/react,rricard/react,krasimir/react,chenglou/react,edvinerikson/react,billfeller/react,mhhegazy/react,leexiaosi/react,jzmq/react,Simek/react,quip/react,terminatorheart/react,Simek/react,acdlite/react,anushreesubramani/react,jquense/react,silvestrijonathan/react,joecritch/react,ericyang321/react,trueadm/react,STRML/react,jdlehman/react,jameszhan/react,brigand/react,chicoxyzzy/react,cpojer/react,empyrical/react,yangshun/react,cpojer/react,tomocchino/react,leexiaosi/react,mhhegazy/react,flarnie/react,jordanpapaleo/react,camsong/react,rickbeerendonk/react,STRML/react,TheBlasfem/react,TheBlasfem/react,mhhegazy/react,jdlehman/react,mjackson/react,chicoxyzzy/react,trueadm/react,shergin/react,acdlite/react,AlmeroSteyn/react,AlmeroSteyn/react,quip/react,empyrical/react,yangshun/react,ericyang321/react,kaushik94/react,rickbeerendonk/react,quip/react,billfeller/react,aickin/react,syranide/react,rickbeerendonk/react,wmydz1/react,apaatsio/react,jdlehman/react,tomocchino/react,ericyang321/react,nhunzaker/react,AlmeroSteyn/react,STRML/react,jameszhan/react,maxschmeling/react,krasimir/react,edvinerikson/react,jquense/react,AlmeroSteyn/react,flarnie/react,tomocchino/react,quip/react,jquense/react,shergin/react,leexiaosi/react,billfeller/react,sekiyaeiji/react,syranide/react,yangshun/react,VioletLife/react,krasimir/react,tomocchino/react,dilidili/react,VioletLife/react,dilidili/react,silvestrijonathan/react,prometheansacrifice/react,brigand/react,aickin/react,jdlehman/react,sekiyaeiji/react,jzmq/react,glenjamin/react,camsong/react,dilidili/react,silvestrijonathan/react,VioletLife/react,pyitphyoaung/react,anushreesubramani/react,anushreesubramani/react,rricard/react,facebook/react,glenjamin/react,chicoxyzzy/react,flipactual/react,prometheansacrifice/react,STRML/react,jquense/react,maxschmeling/react,billfeller/react,acdlite/react,krasimir/react,apaatsio/react,dilidili/react,ArunTesco/react,nhunzaker/react,empyrical/react,jameszhan/react,mosoft521/react,mjackson/react,flarnie/react,dilidili/react,ArunTesco/react,shergin/react,TheBlasfem/react,jordanpapaleo/react,quip/react,terminatorheart/react,mosoft521/react,ericyang321/react,yungsters/react,brigand/react,AlmeroSteyn/react,empyrical/react,joecritch/react,mjackson/react,Simek/react,kaushik94/react,wmydz1/react,Simek/react,flarnie/react,aickin/react,yungsters/react,silvestrijonathan/react,flarnie/react,chenglou/react,glenjamin/react,terminatorheart/react,syranide/react,tomocchino/react,chicoxyzzy/react,quip/react,yangshun/react,maxschmeling/react,STRML/react,ericyang321/react,chicoxyzzy/react,chenglou/react,pyitphyoaung/react,pyitphyoaung/react,AlmeroSteyn/react,shergin/react,roth1002/react,dilidili/react,facebook/react,shergin/react,jorrit/react,glenjamin/react,jzmq/react,yungsters/react,nhunzaker/react,VioletLife/react,chenglou/react,tomocchino/react,flipactual/react,anushreesubramani/react,terminatorheart/react,camsong/react,rickbeerendonk/react,wmydz1/react,maxschmeling/react,wmydz1/react,facebook/react,nhunzaker/react,brigand/react,yiminghe/react,chicoxyzzy/react,jorrit/react,jquense/react,edvinerikson/react,TheBlasfem/react,jquense/react,mhhegazy/react,krasimir/react,kaushik94/react,acdlite/react,brigand/react,rickbeerendonk/react,prometheansacrifice/react,jorrit/react,terminatorheart/react,TheBlasfem/react,jorrit/react,AlmeroSteyn/react,acdlite/react,krasimir/react,facebook/react,krasimir/react,joecritch/react,chenglou/react,joecritch/react,cpojer/react,jzmq/react,yiminghe/react,acdlite/react,flipactual/react,STRML/react,edvinerikson/react,trueadm/react,facebook/react,chenglou/react,wmydz1/react,billfeller/react,apaatsio/react,roth1002/react,shergin/react,prometheansacrifice/react,billfeller/react,prometheansacrifice/react,rricard/react,mosoft521/react,mosoft521/react,roth1002/react,empyrical/react,jordanpapaleo/react,quip/react,pyitphyoaung/react,flarnie/react,yangshun/react,kaushik94/react,brigand/react,rickbeerendonk/react,rricard/react,chicoxyzzy/react,yiminghe/react,Simek/react,jordanpapaleo/react,apaatsio/react,maxschmeling/react,mosoft521/react,jzmq/react,aickin/react,trueadm/react,anushreesubramani/react,yiminghe/react,jameszhan/react,joecritch/react,yiminghe/react,chenglou/react,jzmq/react,glenjamin/react,cpojer/react,cpojer/react,Simek/react
d40bead054b0883ff59ae6ddd311bf93c5da6de3
public/js/scripts.js
public/js/scripts.js
$(document).ready(function(){ $('.datepicker').pickadate({ onSet: function (ele) { if(ele.select){ this.close(); } } }); $('.timepicker').pickatime({ min: [7,30], max: [19,0], interval: 15, onSet: function (ele) { if(ele.select){ this.close(); } } }); $('select').material_select(); });
$(document).ready(function(){ $('.datepicker').pickadate({ onSet: function (ele) { if(ele.select){ this.close(); } }, min: true }); $('.timepicker').pickatime({ min: [7,30], max: [19,0], interval: 15, onSet: function (ele) { if(ele.select){ this.close(); } } }); $('select').material_select(); });
Disable the selection of past dates
Disable the selection of past dates
JavaScript
mit
warrenca/silid,warrenca/silid,warrenca/silid,warrenca/silid
fe14355e054947a6ef00b27884d6c3efc8a3fb62
server.js
server.js
var express = require('express'); var _ = require('lodash'); var app = express(); app.use(express.favicon('public/img/favicon.ico')); app.use(express.static('public')); app.use(express.logger('dev')); app.use(express.bodyParser()); app.set('view engine', 'jade'); app.set('views', __dirname + '/views'); var Situation = require('./lib/situation'); app.post('/process', function(req, res) { var situ = new Situation(req.body.situation); var resp = situ.get('simulation'); res.send({ params: req.body.situation, situation: _.extend({}, situ.computedValues, situ.userValues), response: resp, claimedValues: situ.claimedValues }); }); app.get('/', function(req, res){ res.render('index'); }); app.listen(process.env.PORT || 5000);
var express = require('express'); var _ = require('lodash'); var app = express(); app.use(express.favicon('public/img/favicon.ico')); app.use(express.static('public')); app.use(express.logger('dev')); app.use(express.json()); app.set('view engine', 'jade'); app.set('views', __dirname + '/views'); var Situation = require('./lib/situation'); app.post('/process', function(req, res) { var situ = new Situation(req.body.situation); var resp = situ.get('simulation'); res.send({ params: req.body.situation, situation: _.extend({}, situ.computedValues, situ.userValues), response: resp, claimedValues: situ.claimedValues }); }); app.get('/', function(req, res){ res.render('index'); }); app.listen(process.env.PORT || 5000);
Replace bodyParser by json middleware
Replace bodyParser by json middleware
JavaScript
agpl-3.0
sgmap/mes-aides-ui,sgmap/mes-aides-ui,sgmap/mes-aides-ui,sgmap/mes-aides-ui
55ac0e6be4b8a286c095a1a009777e336bc315cf
node_scripts/run_server.js
node_scripts/run_server.js
require('../lib/fin/lib/js.io/packages/jsio') jsio.addPath('./lib/fin/js', 'shared') jsio.addPath('./lib/fin/js', 'server') jsio.addPath('.', 'fan') jsio('import fan.Server') jsio('import fan.Connection') var redisEngine = require('../lib/fin/engines/redis') var fanServer = new fan.Server(fan.Connection, redisEngine) fanServer.listen('csp', { port: 5555 }) // for browser clients fanServer.listen('tcp', { port: 5556, timeout: 0 }) // for robots
require('../lib/fin/lib/js.io/packages/jsio') jsio.addPath('./lib/fin/js', 'shared') jsio.addPath('./lib/fin/js', 'server') jsio.addPath('.', 'fan') jsio('import fan.Server') jsio('import fan.Connection') var redisEngine = require('../lib/fin/engines/node') var fanServer = new fan.Server(fan.Connection, redisEngine) fanServer.listen('csp', { port: 5555 }) // for browser clients fanServer.listen('tcp', { port: 5556, timeout: 0 }) // for robots
Use the node engine by default
Use the node engine by default
JavaScript
mit
marcuswestin/Focus
6754468b9a1821993d5980c39e09f6eb772ecd41
examples/analyzer-inline.spec.js
examples/analyzer-inline.spec.js
'use strict'; var codeCopter = require('../'); /** * A pretty harsh analyzer that passes NO files for the reason that "it sucks" starting on line 1. * * @returns {Object} An object consistent with a code-copter Analysis object bearing the inevitable message that the code in the analyzed file sucks. */ function itSucks () { return { errors: [{ line: 1, message: 'It sucks. Starting here.' }], pass: false }; } codeCopter.configure({ analyzers: { itSucks: itSucks } }); describe('Inline Analyzer Example', codeCopter);
'use strict'; var codeCopter = require('../'); /** * A pretty harsh analyzer that passes NO files for the reason that "it sucks" starting on line 1. * * @param {FileSourceData} fileSourceData - The file source data to analyze. * @returns {Object} An object consistent with a code-copter Analysis object bearing the inevitable message that the code in the analyzed file sucks. */ function itSucks (fileSourceData) { // OPTIMIZATION: Skip analysis loop and just tell them their code sucks. // //for (let sample of fileSourceData) { // // TODO: Test sample.text to see if it sucks, add error message for sample.line //} return { errors: [{ line: 1, message: 'It sucks. Starting here.' }], pass: false }; } codeCopter.configure({ analyzers: { itSucks: itSucks } }); describe('Inline Analyzer Example', codeCopter);
Include reference to parameter received by analyzers
Include reference to parameter received by analyzers
JavaScript
isc
jtheriault/code-copter,jtheriault/code-copter
e5b67dcf51ee97b6890b06a5d17b890bbf616081
bin/index.js
bin/index.js
#!/usr/bin/env node const fs = require('fs') const path = require('path') const concise = require('../src/index') const command = { name: process.argv[2], input: process.argv[3], output: process.argv[4] } const build = (input, output) => { concise.process(fs.readFileSync(input, 'utf8'), { from: input }).then(css => { // Create all the parent directories if required fs.mkdirSync(path.dirname(output), { recursive: true }) // Write the CSS fs.writeFile(output, css, err => { if (err) throw err console.log(`File written: ${output}\nFrom: ${input}`); }) }); }; const watch = path => { console.log(`Currently watching for changes in: ${path}`); fs.watch(path, {recursive: true}, (eventType, filename) => { console.log(`${eventType.charAt(0).toUpperCase() + eventType.slice(1)} in: ${filename}`); build(); }); }; switch (command.name) { case 'compile': build(command.input, command.output); break case 'watch': build(command.input, command.output); watch(path.dirname(command.input)); break default: console.log('Unknown command') break }
#!/usr/bin/env node const fs = require('fs') const path = require('path') const concise = require('../src/index') const command = { name: process.argv[2], input: process.argv[3], output: process.argv[4] } const build = (input, output) => { concise.process(fs.readFileSync(input, 'utf8'), { from: input }).then(result => { // Create all the parent directories if required fs.mkdirSync(path.dirname(output), { recursive: true }) // Write the CSS fs.writeFile(output, result.css, err => { if (err) throw err console.log(`File written: ${output}\nFrom: ${input}`); }) }); }; const watch = path => { console.log(`Currently watching for changes in: ${path}`); fs.watch(path, {recursive: true}, (eventType, filename) => { console.log(`${eventType.charAt(0).toUpperCase() + eventType.slice(1)} in: ${filename}`); build(); }); }; switch (command.name) { case 'compile': build(command.input, command.output); break case 'watch': build(command.input, command.output); watch(path.dirname(command.input)); break default: console.log('Unknown command') break }
Use the `css` property of `Result`
Use the `css` property of `Result`
JavaScript
mit
ConciseCSS/concise.css
c0747bbf0ba35c22f393d347a1b87729659031a3
src/routes/index.js
src/routes/index.js
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import $ from 'jQuery'; import CoreLayout from 'layouts/CoreLayout'; import HomeView from 'views/HomeView'; import ResumeView from 'views/ResumeView'; import UserFormView from 'views/UserFormView'; import AboutView from 'views/AboutView'; import SecretView from 'views/SecretView'; function requireAuth(nextState, replaceState) { // NOTE: will change url address when deployed $.ajax({ url: 'http://localhost:3000/authentication', async: false, type: 'POST', contentType: 'application/json', success: (data) => { if (data.Auth === false) { replaceState({ nextPathname: nextState.location.pathname }, '/'); } }, error: (xhr, status, err) => console.error(err) }); } export default ( <Route path='/' component={CoreLayout}> <IndexRoute component={ResumeView} /> <Route path='/userform' component={UserFormView} /> <Route path='/resume' component={ResumeView} /> <Route path='/about' component={AboutView} /> <Route path='/secretpage' component={SecretView} onEnter={requireAuth} /> </Route> );
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import $ from 'jQuery'; import CoreLayout from 'layouts/CoreLayout'; import HomeView from 'views/HomeView'; import ResumeView from 'views/ResumeView'; import UserFormView from 'views/UserFormView'; import AboutView from 'views/AboutView'; import SecretView from 'views/SecretView'; function requireAuth(nextState, replaceState) { // NOTE: will change url address when deployed $.ajax({ url: 'http://localhost:3000/authentication', async: false, type: 'POST', contentType: 'application/json', success: (data) => { if (data.Auth === false) { replaceState({ nextPathname: nextState.location.pathname }, '/'); } }, error: (xhr, status, err) => console.error(err) }); } export default ( <Route path='/' component={CoreLayout}> <IndexRoute component={HomeView} /> <Route path='/userform' component={UserFormView} /> <Route path='/resume' component={ResumeView} /> <Route path='/about' component={AboutView} /> <Route path='/secretpage' component={SecretView} onEnter={requireAuth} /> </Route> );
Update default view user renders due to Melody
[chore]: Update default view user renders due to Melody
JavaScript
mit
dont-fear-the-repo/fear-the-repo,sujaypatel16/fear-the-repo,AndrewTHuang/fear-the-repo,ericsonmichaelj/fear-the-repo,AndrewTHuang/fear-the-repo,ericsonmichaelj/fear-the-repo,sujaypatel16/fear-the-repo,dont-fear-the-repo/fear-the-repo
a00a62f147489141cfb7d3fb2d10e08e8f161e01
demo/js/components/workbench-new.js
demo/js/components/workbench-new.js
angular.module('yds').directive('ydsWorkbenchNew', ['$ocLazyLoad', '$timeout', '$window', 'Data', 'Basket', 'Workbench', function ($ocLazyLoad, $timeout, $window, Data, Basket, Workbench) { return { restrict: 'E', scope: { lang: '@', userId: '@' }, templateUrl: ((typeof Drupal != 'undefined') ? Drupal.settings.basePath + Drupal.settings.yds_project.modulePath + '/' : '') + 'templates/workbench-new.html', link: function (scope, element) { scope.ydsAlert = ""; var editorContainer = angular.element(element[0].querySelector('.highcharts-editor-container')); //if userId is undefined or empty, stop the execution of the directive if (_.isUndefined(scope.userId) || scope.userId.trim().length == 0) { scope.ydsAlert = "The YDS component is not properly configured." + "Please check the corresponding documentation section"; return false; } //check if the language attr is defined, else assign default value if (_.isUndefined(scope.lang) || scope.lang.trim() == "") scope.lang = "en"; // Load the required CSS & JS files for the Editor $ocLazyLoad.load([ "css/highcharts-editor.min.css", "lib/highcharts-editor.js" ]).then(function () { // Start the Highcharts Editor highed.ready(function () { highed.Editor(editorContainer[0]); }); }); } } } ]);
angular.module('yds').directive('ydsWorkbenchNew', ['$ocLazyLoad', '$timeout', '$window', 'Data', 'Basket', 'Workbench', function ($ocLazyLoad, $timeout, $window, Data, Basket, Workbench) { return { restrict: 'E', scope: { lang: '@', userId: '@' }, templateUrl: ((typeof Drupal != 'undefined') ? Drupal.settings.basePath + Drupal.settings.yds_project.modulePath + '/' : '') + 'templates/workbench-new.html', link: function (scope, element) { scope.ydsAlert = ""; var editorContainer = angular.element(element[0].querySelector('.highcharts-editor-container')); //if userId is undefined or empty, stop the execution of the directive if (_.isUndefined(scope.userId) || scope.userId.trim().length == 0) { scope.ydsAlert = "The YDS component is not properly configured." + "Please check the corresponding documentation section"; return false; } //check if the language attr is defined, else assign default value if (_.isUndefined(scope.lang) || scope.lang.trim() == "") scope.lang = "en"; var editorOptions = { features: "import templates customize export" }; // Load the required CSS & JS files for the Editor $ocLazyLoad.load([ "css/highcharts-editor.min.css", "lib/highcharts-editor.js" ]).then(function () { // Start the Highcharts Editor highed.ready(function () { highed.Editor(editorContainer[0], editorOptions); }); }); } } } ]);
Disable steps that are not needed in Highcharts Editor
Disable steps that are not needed in Highcharts Editor
JavaScript
apache-2.0
YourDataStories/components-visualisation,YourDataStories/components-visualisation,YourDataStories/components-visualisation
7b1ee57b1fc73b6bf75818561a2f5bba39b50344
src/scripts/main.js
src/scripts/main.js
console.log('main.js'); // Load Css async w LoadCSS & +1 polyfill / https://www.npmjs.com/package/fg-loadcss?notice=MIvGLZ2qXNAEF8AM1kvyFWL8p-1MwaU7UpJd8jcG var stylesheet = loadCSS( "styles/main.css" ); onloadCSS( stylesheet, function() { console.log( "LoadCSS > Stylesheet has loaded. Yay !" ); $('.no-fouc').fadeIn(); // Jquery animation }); // Load Hyphenopoly plugins, manage font césure & text FOUC // Need to be loaded beofre HyphenopolyLoader, cf. gulpfile paths.scripts.src var Hyphenopoly = { require: { "en-us": "hyphenation" }, paths: { patterndir: 'assets/hyphenopoly/patterns/', maindir: 'assets/hyphenopoly/' }, setup: { classnames: { "hyphenate": {} } } };
console.log('main.js'); // Load Css async w LoadCSS & +1 polyfill / https://www.npmjs.com/package/fg-loadcss?notice=MIvGLZ2qXNAEF8AM1kvyFWL8p-1MwaU7UpJd8jcG var stylesheet = loadCSS( "styles/main.css" ); onloadCSS( stylesheet, function() { console.log( "LoadCSS > Stylesheet has loaded. Yay !" ); // + No Fouc management $('.no-fouc').fadeIn(); // Lovely Jquery animation on load // Fouc out management $('a').click(function(e) { e.preventDefault(); newLocation = this.href; $('body').fadeOut(200, function() { window.location = newLocation; }); }); }); // Load Hyphenopoly plugins, manage font césure & text FOUC // Need to be loaded beofre HyphenopolyLoader, cf. gulpfile paths.scripts.src var Hyphenopoly = { require: { "en-us": "hyphenation" }, paths: { patterndir: 'assets/hyphenopoly/patterns/', maindir: 'assets/hyphenopoly/' }, setup: { classnames: { "hyphenate": {} } } };
Add / Fouc out (on link clic)
Add / Fouc out (on link clic)
JavaScript
mit
youpiwaza/chaos-boilerplate,youpiwaza/chaos-boilerplate
3908db4cabd5193aa3798a48277369b86b786f73
tests/nock.js
tests/nock.js
/** * Copyright (c) 2015 IBM Cloudant, Inc. 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. */ function noop() { return this; } function nock_noop() { // Return a completely inert nock-compatible object. return {head:noop, get:noop, post:noop, put:noop, 'delete':noop, reply:noop, filteringPath:noop, done:noop}; } if (process.env.NOCK_OFF) { var nock = nock_noop; } else { var nock = require('nock'); } module.exports = nock;
/** * Copyright (c) 2015 IBM Cloudant, Inc. 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. */ function noop() { return this; } function nock_noop() { // Return a completely inert nock-compatible object. return {head:noop, get:noop, post:noop, put:noop, 'delete':noop, reply:noop, filteringPath:noop, done:noop, query:noop}; } if (process.env.NOCK_OFF) { var nock = nock_noop; } else { var nock = require('nock'); } module.exports = nock;
Add the .query() method to the Nock noop
Add the .query() method to the Nock noop
JavaScript
apache-2.0
KimStebel/nodejs-cloudant,cloudant/nodejs-cloudant,cloudant/nodejs-cloudant
ae166fa6cd8ef9c8a73ff1b9e7a1e64503e6061e
src/js/portfolio.js
src/js/portfolio.js
var observer = lozad(".lazy", { rootMargin: "25%", threshold: 0 }); observer.observe();
import IntersectionObserver from 'intersection-observer'; import Lozad from 'lozad'; let observer = Lozad('.lazy', { rootMargin: '25%', threshold: 0 }); observer.observe();
Use ES6 import for Portfolio JS dependencies
Use ES6 import for Portfolio JS dependencies
JavaScript
mit
stevecochrane/stevecochrane.com,stevecochrane/stevecochrane.com
a7a88cac0976c49e05fa9ea278320749f6ef1ba0
rollup.config-dev.js
rollup.config-dev.js
"use strict"; const baseConfig = require("./rollup.config"); const plugin = require("./plugin"); const path = require("path"); module.exports = baseConfig.map((config, index) => { config.plugins.push(plugin({ open: true, filename: `stats.${index}.html`, template: getTemplateType(config) })); return config; }); function getTemplateType({ input }) { const filename = path.basename(input, path.extname(input)); const [, templateType] = filename.split("-"); return templateType; }
"use strict"; const baseConfig = require("./rollup.config"); const plugin = require("./plugin"); const path = require("path"); module.exports = baseConfig.map(config => { const templateType = getTemplateType(config); config.plugins.push( plugin({ open: true, filename: `stats.${templateType}.html`, template: templateType }) ); return config; }); function getTemplateType({ input }) { const filename = path.basename(input, path.extname(input)); const [, templateType] = filename.split("-"); return templateType; }
Use template name for statts file name
Use template name for statts file name
JavaScript
mit
btd/rollup-plugin-visualizer,btd/rollup-plugin-visualizer
0d58435c37ad66fa5bea391672cb490c13e455f7
website/mcapp.projects/src/app/models/project.model.js
website/mcapp.projects/src/app/models/project.model.js
/*@ngInject*/ function ProjectModelService(projectsAPI) { class Project { constructor(id, name, owner) { this.id = id; this.name = name; this.owner = owner; this.samples_count = 0; this.processes_count = 0; this.experiments_count = 0; this.files_count = 0; this.description = ""; this.birthtime = 0; this.mtime = 0; } static fromJSON(data) { let p = new Project(data.id, data.name, data.owner); p.samples_count = data.samples; p.processes_count = data.processes; p.experiments_count = data.experiments; p.files_counts = data.files; p.description = data.description; p.birthtime = new Date(data.birthtime * 1000); p.mtime = new Date(data.mtime * 1000); p.users = data.users; p.owner_details = data.owner_details; return p; } static get(id) { } static getProjectsForCurrentUser() { return projectsAPI.getAllProjects().then( (projects) => projects.map(p => Project.fromJSON(p)) ); } save() { } update() { } } return Project; } angular.module('materialscommons').factory('ProjectModel', ProjectModelService);
/*@ngInject*/ function ProjectModelService(projectsAPI) { class Project { constructor(id, name, owner) { this.id = id; this.name = name; this.owner = owner; this.samples_count = 0; this.processes_count = 0; this.experiments_count = 0; this.files_count = 0; this.description = ""; this.birthtime = 0; this.owner_details = {}; this.mtime = 0; } static fromJSON(data) { let p = new Project(data.id, data.name, data.owner); p.samples_count = data.samples; p.processes_count = data.processes; p.experiments_count = data.experiments; p.files_counts = data.files; p.description = data.description; p.birthtime = new Date(data.birthtime * 1000); p.mtime = new Date(data.mtime * 1000); p.users = data.users; p.owner_details = data.owner_details; return p; } static get(id) { } static getProjectsForCurrentUser() { return projectsAPI.getAllProjects().then( (projects) => projects.map(p => Project.fromJSON(p)) ); } save() { } update() { } } return Project; } angular.module('materialscommons').factory('ProjectModel', ProjectModelService);
Add default value for owner_details.
Add default value for owner_details.
JavaScript
mit
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
7de0b3e5e86bcd995e30f6aa953e86c7730ffa28
transform-response-to-objects.js
transform-response-to-objects.js
module.exports = ResponseToObjects; var Transform = require('readable-stream/transform'); var inherits = require('inherits'); var isArray = require('is-array'); /** * Parse written Livefyre API Responses (strings or objects) into a * readable stream of objects from response.data * If data is an array, each item of the array will be emitted separately * If an error response is written in, emit an error event */ function ResponseToObjects(opts) { opts = opts || {}; opts.objectMode = true; return Transform.call(this, opts); } inherits(ResponseToObjects, Transform); /** * Required by stream/transform */ ResponseToObjects.prototype._transform = function (response, encoding, done) { var err; if (typeof response === 'string') { response = JSON.parse(response); } if (response.status === 'error') { err = new Error('ResponseToObjects transform had an error response written in'); err.response = response; this.emit('error', err); return; } var data = response.data; if ( ! data) { err = new Error('Response has no data'); err.response = response; this.emit('error', err); return; } if ( ! isArray(data)) { data = [data]; } data.forEach(this.push.bind(this)); done(); };
module.exports = ResponseToObjects; var Transform = require('readable-stream/transform'); var inherits = require('inherits'); var isArray = require('is-array'); /** * Parse written Livefyre API Responses (strings or objects) into a * readable stream of objects from response.data * If data is an array, each item of the array will be emitted separately * If an error response is written in, emit an error event */ function ResponseToObjects(opts) { opts = opts || {}; opts.objectMode = true; Transform.call(this, opts); } inherits(ResponseToObjects, Transform); /** * Required by stream/transform */ ResponseToObjects.prototype._transform = function (response, encoding, done) { var err; if (typeof response === 'string') { response = JSON.parse(response); } if (response.status === 'error') { err = new Error('ResponseToObjects transform had an error response written in'); err.response = response; this.emit('error', err); return; } var data = response.data; if ( ! data) { err = new Error('Response has no data'); err.response = response; this.emit('error', err); return; } if ( ! isArray(data)) { data = [data]; } data.forEach(this.push.bind(this)); done(); };
Remove unnecessary return in ResponseToObjects
Remove unnecessary return in ResponseToObjects
JavaScript
mit
gobengo/chronos-stream
0f9b5317e5a9ce68372d62c814dfbd260b748169
JavaScriptUI-DOM-TeamWork-Kinetic/Scripts/GameEngine.js
JavaScriptUI-DOM-TeamWork-Kinetic/Scripts/GameEngine.js
 var GameEngine = ( function () { function start(){ var x, y, color, i, j, lengthBoard, lengthField; var players = []; players.push( Object.create( GameObjects.Player ).init( 'First', 'white' ) ); players.push( Object.create( GameObjects.Player ).init( 'Second', 'black' ) ); var board = GameObjects.Board.init( players ); GameDraw.background(); lengthBoard = board.length; for ( i = 0; i < lengthBoard; i += 1 ) { lengthField = board[i].length; for ( j = 0; j < lengthField; j += 1 ) { x = i; y = j; color = board[i][j].color; GameDraw.createCircle( x, y, color ); } } GameDraw.playGround(); } return{ start: start, } }() )
var GameEngine = ( function () { function start() { var x, y, color, i, j, lengthBoard, lengthField; var players = []; players.push(Object.create(GameObjects.Player).init('First', 'white')); players.push(Object.create(GameObjects.Player).init('Second', 'black')); var board = GameObjects.Board.init(players); GameDraw.background(); lengthBoard = board.length; for (i = 0; i < lengthBoard; i += 1) { lengthField = board[i].length; for (j = 0; j < lengthField; j += 1) { x = i; y = j; color = board[i][j].color; GameDraw.createCircle(x, y, color); } } GameDraw.playGround(); } function update(){ // currentPlayer = GetCurrentPlayer - depending on player.isOnTurn or isFirstPlayerOnTurn // flag hasThrownDice -> if not - throw dice(allowedMoves = diceResult, currentPlayerMoves = 0); else - continue // if (currentPlayer.hasHitPiece) -> Call function(s) to deal with this situation. // if can't put piece -> playerMoves = allowedMoves // if ((currentPlayerMoves < allowedMoves) && hasMovedPiece (sets to true when called from onDrag event on piece) // Subcases: move from position to position/ collect piece // Call function(s) to deal with this situation. -> hasMovedPiece = false, currentPlayerMoves++; // Missed logic? // if current player has no pieces on the board -> He wins. // if (playerMoves === allowedMoves) -> change player, hasThrownDice = false } return { start: start, update: update }; }()); // All events will call GameEngine.Update() and GameDraw.Update().
Add pseudo code for game update according to game state.
Add pseudo code for game update according to game state.
JavaScript
mit
Vesper-Team/JavaScriptUI-DOM-TeamWork,Vesper-Team/JavaScriptUI-DOM-TeamWork
5390da989457ecff7dbfa94637c042e2d63f2841
examples/Node.js/exportTadpoles.js
examples/Node.js/exportTadpoles.js
require('../../index.js'); var scope = require('./Tadpoles'); scope.view.exportFrames({ amount: 200, directory: __dirname, onComplete: function() { console.log('Done exporting.'); }, onProgress: function(event) { console.log(event.percentage + '% complete, frame took: ' + event.delta); } });
require('../../node.js/'); var paper = require('./Tadpoles'); paper.view.exportFrames({ amount: 400, directory: __dirname, onComplete: function() { console.log('Done exporting.'); }, onProgress: function(event) { console.log(event.percentage + '% complete, frame took: ' + event.delta); } });
Clean up Node.js tadpoles example.
Clean up Node.js tadpoles example.
JavaScript
mit
0/paper.js,0/paper.js
8c1899b772a1083ce739e237990652b73b41a48d
src/apps/investment-projects/constants.js
src/apps/investment-projects/constants.js
const { concat } = require('lodash') const currentYear = (new Date()).getFullYear() const GLOBAL_NAV_ITEM = { path: '/investment-projects', label: 'Investment projects', permissions: [ 'investment.read_associated_investmentproject', 'investment.read_all_investmentproject', ], order: 5, } const LOCAL_NAV = [ { path: 'details', label: 'Project details', }, { path: 'team', label: 'Project team', }, { path: 'interactions', label: 'Interactions', permissions: [ 'interaction.read_associated_investmentproject_interaction', 'interaction.read_all_interaction', ], }, { path: 'evaluation', label: 'Evaluations', }, { path: 'audit', label: 'Audit history', }, { path: 'documents', label: 'Documents', permissions: [ 'investment.read_investmentproject_document', ], }, ] const DEFAULT_COLLECTION_QUERY = { estimated_land_date_after: `${currentYear}-04-05`, estimated_land_date_before: `${currentYear + 1}-04-06`, sortby: 'estimated_land_date:asc', } const APP_PERMISSIONS = concat(LOCAL_NAV, GLOBAL_NAV_ITEM) module.exports = { GLOBAL_NAV_ITEM, LOCAL_NAV, DEFAULT_COLLECTION_QUERY, APP_PERMISSIONS, }
const { concat } = require('lodash') const GLOBAL_NAV_ITEM = { path: '/investment-projects', label: 'Investment projects', permissions: [ 'investment.read_associated_investmentproject', 'investment.read_all_investmentproject', ], order: 5, } const LOCAL_NAV = [ { path: 'details', label: 'Project details', }, { path: 'team', label: 'Project team', }, { path: 'interactions', label: 'Interactions', permissions: [ 'interaction.read_associated_investmentproject_interaction', 'interaction.read_all_interaction', ], }, { path: 'evaluation', label: 'Evaluations', }, { path: 'audit', label: 'Audit history', }, { path: 'documents', label: 'Documents', permissions: [ 'investment.read_investmentproject_document', ], }, ] const DEFAULT_COLLECTION_QUERY = { sortby: 'estimated_land_date:asc', } const APP_PERMISSIONS = concat(LOCAL_NAV, GLOBAL_NAV_ITEM) module.exports = { GLOBAL_NAV_ITEM, LOCAL_NAV, DEFAULT_COLLECTION_QUERY, APP_PERMISSIONS, }
Remove preset date filters in investment collection
Remove preset date filters in investment collection
JavaScript
mit
uktrade/data-hub-frontend,uktrade/data-hub-frontend,uktrade/data-hub-fe-beta2,uktrade/data-hub-fe-beta2,uktrade/data-hub-frontend
ec0c70f94319a898453252d4c4a7d8020e40081b
take_screenshots.js
take_screenshots.js
var target = UIATarget.localTarget(); function captureLocalizedScreenshot(name) { var target = UIATarget.localTarget(); var model = target.model(); var rect = target.rect(); if (model.match(/iPhone/)) { if (rect.size.height > 480) model = "iphone5"; else model = "iphone"; } else { model = "ipad"; } var orientation = "portrait"; if (rect.size.height < rect.size.width) orientation = "landscape"; var language = target.frontMostApp(). preferencesValueForKey("AppleLanguages")[0]; var parts = [model, orientation, language, name]; target.captureScreenWithName(parts.join("-")); } var window = target.frontMostApp().mainWindow(); captureLocalizedScreenshot("screen1"); window.buttons()[0].tap(); target.delay(0.5); captureLocalizedScreenshot("screen2");
var target = UIATarget.localTarget(); function captureLocalizedScreenshot(name) { var target = UIATarget.localTarget(); var model = target.model(); var rect = target.rect(); if (model.match(/iPhone/)) { if (rect.size.height > 480) model = "iphone5"; else model = "iphone"; } else { model = "ipad"; } var orientation = "portrait"; if (rect.size.height < rect.size.width) orientation = "landscape"; var language = target.frontMostApp(). preferencesValueForKey("AppleLanguages")[0]; var parts = [language, model, orientation, name]; target.captureScreenWithName(parts.join("-")); } var window = target.frontMostApp().mainWindow(); captureLocalizedScreenshot("screen1"); window.buttons()[0].tap(); target.delay(0.5); captureLocalizedScreenshot("screen2");
Put the language first in the screen shot generation
Put the language first in the screen shot generation
JavaScript
mit
wordpress-mobile/ui-screen-shooter,myhanhtran1999/UIScreenShot,jonathanpenn/ui-screen-shooter,duk42111/ui-screen-shooter,myhanhtran1999/UIScreenShot,wordpress-mobile/ui-screen-shooter,jonathanpenn/ui-screen-shooter,duk42111/ui-screen-shooter,myhanhtran1999/UIScreenShot
e771602c05add371bdb1d8d7082f87ae02715cae
app/commands.js
app/commands.js
var _ = require('underscore'); var util = require('util'); exports.setup = function() { global.commands = {}; }; exports.handle = function(evt, msg) { if(msg.slice(0, 1) != "!") return; var m = msg.match(/^!([A-Za-z0-9]+)(?: (.+))?$/); if(!m) return; if(global.commands[m[1].lower()]) global.commands[m[1].lower()](evt, m[2]); else console.log("[commands.js] unknown command: '!%s'", m[1]); };
var _ = require('underscore'); var util = require('util'); exports.setup = function() { global.commands = {}; }; exports.handle = function(evt, msg) { if(msg.slice(0, 1) != "!") return; var m = msg.match(/^!([A-Za-z0-9]+)(?: (.+))?$/); if(!m) return; if(global.commands[m[1].toLowerCase()]) global.commands[m[1].toLowerCase()](evt, m[2]); else console.log("[commands.js] unknown command: '!%s'", m[1]); };
Fix error. Thought this was Python for a second xD
Fix error. Thought this was Python for a second xD
JavaScript
mit
ircah/cah-js,ircah/cah-js
ce4db4da61560acb8536332b4092dcbf0ae1b9a8
test/case5/case5.js
test/case5/case5.js
;((rc) => { 'use strict'; var tagContent = 'router2-content'; var tagView = 'router2-view'; var div = document.createElement('div'); div.innerHTML = ` <${tagContent} id="case5-1" hash="case5-1"> Case 5-1 <div> <div> <div> <${tagContent} id="case5-11" hash="case5-11"> Case 5-11 </${tagContent}> </div> </div> </div> </${tagContent}> `; var async1 = async_test('Case 5: hash changed to content[hash="case5-1/case5-11"]'); async1.next = async1.step_func(_ => { var check_hash = async1.step_func((e) => { window.removeEventListener('hashchange', check_hash); var content1 = document.querySelector('#case5-1'); var content2 = document.querySelector('#case5-11'); //assert_false(content1.hidden); //assert_false(content2.hidden); //document.body.removeChild(div); async1.done(); rc.next(); }); window.addEventListener('hashchange', check_hash); window.location.hash = "case5-1/case5-11"; }); rc.push(_ => { async1.step(_ => { document.body.appendChild(div); async1.next(); }); }) })(window.routeCases);
;((rc) => { 'use strict'; var tagContent = 'router2-content'; var tagView = 'router2-view'; var div = document.createElement('div'); div.innerHTML = ` <${tagContent} id="case5-1" hash="case5-1"> Case 5-1 <div> <div> <div> <${tagContent} id="case5-11" hash="case5-11"> Case 5-11 </${tagContent}> </div> </div> </div> </${tagContent}> `; var async1 = async_test('Case 5: hash changed to content[hash="case5-1/case5-11"]'); async1.next = async1.step_func(_ => { var check_hash = async1.step_func((e) => { window.removeEventListener('hashchange', check_hash); var content1 = document.querySelector('#case5-1'); var content2 = document.querySelector('#case5-11'); assert_false(content1.hidden); assert_false(content2.hidden); document.body.removeChild(div); async1.done(); rc.next(); }); window.addEventListener('hashchange', check_hash); window.location.hash = "case5-1/case5-11"; }); rc.push(_ => { async1.step(_ => { document.body.appendChild(div); async1.next(); }); }) })(window.routeCases);
Fix the test 1 at case 5
Fix the test 1 at case 5
JavaScript
isc
m3co/router3,m3co/router3
e50a7eec7a8d1cb130da08cdae8c022b82af0e35
app/controllers/sessionobjective.js
app/controllers/sessionobjective.js
import Ember from 'ember'; export default Ember.ObjectController.extend(Ember.I18n.TranslateableProperties, { proxiedObjectives: [], session: null, course: null, actions: { addParent: function(parentProxy){ var newParent = parentProxy.get('content'); var self = this; var sessionObjective = this.get('model'); sessionObjective.get('parents').then(function(ourParents){ newParent.get('children').then(function(newParentChildren){ newParentChildren.addObject(sessionObjective); newParent.save().then(function(newParent){ ourParents.addObject(newParent); sessionObjective.save().then(function(sessionObjective){ self.set('model', sessionObjective); }); }); }); }); }, removeParent: function(parentProxy){ var self = this; var removingParent = parentProxy.get('content'); var sessionObjective = this.get('model'); sessionObjective.get('parents').then(function(ourParents){ ourParents.removeObject(removingParent); removingParent.get('children').then(function(children){ children.addObject(sessionObjective); sessionObjective.save().then(function(sessionObjective){ self.set('model', sessionObjective); removingParent.save(); }); }); }); } } });
import Ember from 'ember'; export default Ember.ObjectController.extend(Ember.I18n.TranslateableProperties, { proxiedObjectives: [], session: null, course: null, actions: { addParent: function(parentProxy){ var newParent = parentProxy.get('content'); var sessionObjective = this.get('model'); sessionObjective.get('parents').then(function(ourParents){ ourParents.addObject(newParent); newParent.get('children').then(function(newParentChildren){ newParentChildren.addObject(sessionObjective); newParent.save(); sessionObjective.save(); }); }); }, removeParent: function(parentProxy){ var removingParent = parentProxy.get('content'); var sessionObjective = this.get('model'); sessionObjective.get('parents').then(function(ourParents){ ourParents.removeObject(removingParent); removingParent.get('children').then(function(children){ children.removeObject(sessionObjective); removingParent.save(); sessionObjective.save(); }); }); } } });
Fix issue with removing parent and speed up the process
Fix issue with removing parent and speed up the process
JavaScript
mit
stopfstedt/frontend,stopfstedt/frontend,jrjohnson/frontend,thecoolestguy/frontend,gabycampagna/frontend,thecoolestguy/frontend,jrjohnson/frontend,ilios/frontend,djvoa12/frontend,gboushey/frontend,djvoa12/frontend,gboushey/frontend,ilios/frontend,dartajax/frontend,dartajax/frontend,gabycampagna/frontend
6be5d442638239436104e48cd8977a7742c86c38
bin/repl.js
bin/repl.js
#!/usr/bin/env node var repl = require('repl'); var Chrome = require('../'); Chrome(function (chrome) { var chromeRepl = repl.start({ 'prompt': 'chrome> ' }); chromeRepl.on('exit', function () { chrome.close(); }); for (var domain in chrome) { chromeRepl.context[domain] = chrome[domain]; } });
#!/usr/bin/env node var repl = require('repl'); var protocol = require('../lib/Inspector.json'); var Chrome = require('../'); Chrome(function (chrome) { var chromeRepl = repl.start({ 'prompt': 'chrome> ' }); chromeRepl.on('exit', function () { chrome.close(); }); for (var domainIdx in protocol.domains) { var domainName = protocol.domains[domainIdx].domain; chromeRepl.context[domainName] = chrome[domainName]; } });
Add protocol API only to the REPL context
Add protocol API only to the REPL context
JavaScript
mit
valaxy/chrome-remote-interface,cyrus-and/chrome-remote-interface,washtubs/chrome-remote-interface,cyrus-and/chrome-remote-interface
c4d7ea7e74d0f81b6b38a6623e47ccfee3a0fab1
src/locale/index.js
src/locale/index.js
import React from 'react' import * as ReactIntl from 'react-intl' import languageResolver from './languageResolver' import messagesFetcher from './messagesFetcher' function wrappedReactIntlProvider(language, localizedMessages) { return function SanityIntlProvider(props) { return <ReactIntl.IntlProvider locale={language} messages={localizedMessages} {...props} /> } } const SanityIntlProviderPromise = languageResolver.then(language => { return messagesFetcher.fetchLocalizedMessages(language).then(localizedMessages => { // TODO: ReactIntl.addLocaleData() return { ReactIntl, SanityIntlProvider: wrappedReactIntlProvider(language, localizedMessages) } }) }) module.exports = SanityIntlProviderPromise
import React from 'react' import * as ReactIntl from 'react-intl' import languageResolver from './languageResolver' import messagesFetcher from './messagesFetcher' function wrappedReactIntlProvider(language, localizedMessages) { return function SanityIntlProvider(props) { return <ReactIntl.IntlProvider locale={language} messages={localizedMessages} {...props} /> } } const SanityIntlPromise = languageResolver.then(language => { return messagesFetcher.fetchLocalizedMessages(language).then(localizedMessages => { const languagePrexif = language.split('-')[0] const localeData = require(`react-intl/locale-data/${languagePrexif}`) ReactIntl.addLocaleData(localeData) return { ReactIntl, SanityIntlProvider: wrappedReactIntlProvider(language, localizedMessages) } }) }) module.exports = SanityIntlPromise
Add localeData for requested lanuage
Add localeData for requested lanuage
JavaScript
mit
sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity
38bc4c6908ef3bd56b4c9d724b218313cb3400a5
webpack.config.production.js
webpack.config.production.js
import webpack from 'webpack'; import ExtractTextPlugin from 'extract-text-webpack-plugin'; import baseConfig from './webpack.config.base'; const config = { ...baseConfig, devtool: 'source-map', entry: './app/index', output: { ...baseConfig.output, publicPath: '../dist/' }, module: { ...baseConfig.module, loaders: [ ...baseConfig.module.loaders, { test: /\.global\.css$/, loader: ExtractTextPlugin.extract( 'style-loader', 'css-loader' ) }, { test: /^((?!\.global).)*\.css$/, loader: ExtractTextPlugin.extract( 'style-loader', 'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]' ) } ] }, plugins: [ ...baseConfig.plugins, new webpack.optimize.OccurenceOrderPlugin(), new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('production') }), new webpack.optimize.UglifyJsPlugin({ compressor: { screw_ie8: true, warnings: false } }), new ExtractTextPlugin('style.css', { allChunks: true }) ], target: 'electron-renderer' }; export default config;
import webpack from 'webpack'; import ExtractTextPlugin from 'extract-text-webpack-plugin'; import baseConfig from './webpack.config.base'; const config = { ...baseConfig, devtool: 'source-map', entry: './app/index', output: { ...baseConfig.output, publicPath: '../dist/' }, module: { ...baseConfig.module, loaders: [ ...baseConfig.module.loaders, { test: /\.global\.css$/, loader: ExtractTextPlugin.extract( 'style-loader', 'css-loader' ) }, { test: /^((?!\.global).)*\.css$/, loader: ExtractTextPlugin.extract( 'style-loader', 'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]' ) } ] }, plugins: [ ...baseConfig.plugins, new webpack.optimize.OccurrenceOrderPlugin(), new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('production') }), new webpack.optimize.UglifyJsPlugin({ compressor: { screw_ie8: true, warnings: false } }), new ExtractTextPlugin('style.css', { allChunks: true }) ], target: 'electron-renderer' }; export default config;
Fix typo: `OccurenceOrderPlugin` to `OccurrenceOrderPlugin`
Fix typo: `OccurenceOrderPlugin` to `OccurrenceOrderPlugin`
JavaScript
mit
stefanKuijers/aw-fullstack-app,waha3/Electron-NeteaseCloudMusic,treyhuffine/tuchbase,foysalit/wallly-electron,joshuef/peruse,jenyckee/electron-virtual-midi,pahund/scenescreen,dfucci/Borrowr,mitchconquer/electron_cards,xiplias/github-browser,cosio55/app-informacion-bitso,Byte-Code/lm-digital-store-private-test,joshuef/peruse,kaunio/gloso,opensprints/opensprints-electron,kimurakenshi/caravanas,barbalex/kapla3,Andrew-Hird/bFM-desktop,irwinb/table-viewer,waha3/Electron-NeteaseCloudMusic,anthonyraymond/joal-desktop,pahund/scenescreen,kme211/srt-maker,treyhuffine/tuchbase,Byte-Code/lm-digitalstore,ACalix/sprinthub,thirdicrypto/darkwallet-electron-ui,carly-lee/electron-sleep-timer,barbalex/kapla3,eranimo/explorer,anthonyraymond/joal-desktop,chentsulin/electron-react-boilerplate,linuxing3/electron-react,eranimo/explorer,Byte-Code/lm-digital-store-private-test,UniSiegenCSCW/remotino,sdlfj/eq-roll-tracker,riccardopiola/LeagueFlash,swiecki/strigine,espenbjorkeng/Rabagast,gidich/votrient-kiosk,Andrew-Hird/bFM-desktop,sdlfj/eq-roll-tracker,kivo360/ECC-GUI,nantaphop/redd,dfucci/Borrowr,nefa/eletrcon-react-redux,kme211/srt-maker,Sebkasanzew/Electroweb,kimurakenshi/caravanas,mitchconquer/electron_cards,ThomasBaldry/mould-maker-desktop,Byte-Code/lm-digitalstore,foysalit/wallly-electron,JoaoCnh/picto-pc,anthonyraymond/joal-desktop,runandrew/memoriae,lhache/katalogz,swiecki/strigine,thirdicrypto/darkwallet-electron-ui,ACalix/sprinthub,knpwrs/electron-react-boilerplate,linuxing3/electron-react,carly-lee/electron-sleep-timer,TheCbac/MICA-Desktop,irwinb/table-viewer,baublet/lagniappe,nefa/eletrcon-react-redux,knpwrs/electron-react-boilerplate,alecholmez/crew-electron,UniSiegenCSCW/remotino,xuandeng/base_app,ycai2/visual-git-stats,nantaphop/redd,lhache/katalogz,riccardopiola/LeagueFlash,surrealroad/electron-react-boilerplate,ycai2/visual-git-stats,jaytrepka/kryci-jmena,TheCbac/MICA-Desktop,jhen0409/electron-react-boilerplate,xiplias/github-browser,xuandeng/base_app,gidich/votrient-kiosk,alecholmez/crew-electron,jenyckee/electron-virtual-midi,tw00089923/kcr_bom,Sebkasanzew/Electroweb,surrealroad/electron-react-boilerplate,UniSiegenCSCW/remotino,jhen0409/electron-react-boilerplate,eranimo/explorer,JoaoCnh/picto-pc,tw00089923/kcr_bom,espenbjorkeng/Rabagast,kivo360/ECC-GUI,bird-system/bs-label-convertor,ThomasBaldry/mould-maker-desktop,cosio55/app-informacion-bitso,zackhall/ack-chat,runandrew/memoriae,ivtpz/brancher,kaunio/gloso,stefanKuijers/aw-fullstack-app,opensprints/opensprints-electron,chentsulin/electron-react-boilerplate,jaytrepka/kryci-jmena,bird-system/bs-label-convertor,baublet/lagniappe,surrealroad/electron-react-boilerplate,zackhall/ack-chat,ivtpz/brancher
fd5937050f8f97301d909beadfa3e87ef9f4aa13
src/components/forms/LinksControl.js
src/components/forms/LinksControl.js
import React, { Component, PropTypes } from 'react' import FormControl from './FormControl' /* eslint-disable react/prefer-stateless-function */ class LinksControl extends Component { static propTypes = { text: PropTypes.oneOfType([ PropTypes.string, PropTypes.array, ]), } static defaultProps = { className: 'LinksControl', id: 'external_links', label: 'Links', name: 'user[links]', placeholder: 'Links (optional)', } getLinks() { const { text } = this.props const links = text || '' if (typeof links === 'string') { return links } return links.map((link) => link.text).join(', ') } render() { return ( <FormControl { ...this.props } autoCapitalize="off" autoCorrect="off" maxLength="50" text={ this.getLinks() } type="text" /> ) } } export default LinksControl
import React, { Component, PropTypes } from 'react' import FormControl from './FormControl' /* eslint-disable react/prefer-stateless-function */ class LinksControl extends Component { static propTypes = { text: PropTypes.oneOfType([ PropTypes.string, PropTypes.array, ]), } static defaultProps = { className: 'LinksControl', id: 'external_links', label: 'Links', name: 'user[links]', placeholder: 'Links (optional)', } getLinks() { const { text } = this.props const links = text || '' if (typeof links === 'string') { return links } return links.map((link) => link.text).join(', ') } render() { return ( <FormControl { ...this.props } autoCapitalize="off" autoCorrect="off" text={ this.getLinks() } type="text" /> ) } } export default LinksControl
Remove max-length on links control
Remove max-length on links control The `max-length` attribute was inadvertently added. [Finishes: #119027729](https://www.pivotaltracker.com/story/show/119027729) [#119014219](https://www.pivotaltracker.com/story/show/119014219)
JavaScript
mit
ello/webapp,ello/webapp,ello/webapp
17bcd21bf30b3baabbacb1e45b59c7103b3cdbd3
webpack/webpack.common.config.js
webpack/webpack.common.config.js
// Common webpack configuration used by webpack.hot.config and webpack.rails.config. var path = require("path"); module.exports = { context: __dirname, // the project dir entry: [ "./assets/javascripts/example" ], // In case you wanted to load jQuery from the CDN, this is how you would do it: // externals: { // jquery: "var jQuery" // }, resolve: { root: [path.join(__dirname, "scripts"), path.join(__dirname, "assets/javascripts"), path.join(__dirname, "assets/stylesheets")], extensions: ["", ".webpack.js", ".web.js", ".js", ".jsx", ".scss", ".css", "config.js"] }, module: { loaders: [ { test: require.resolve("react"), loader: "expose?React" } ] } };
// Common webpack configuration used by webpack.hot.config and webpack.rails.config. var path = require("path"); module.exports = { context: __dirname, // the project dir entry: [ "./assets/javascripts/example" ], // In case you wanted to load jQuery from the CDN, this is how you would do it: // externals: { // jquery: "var jQuery" // }, resolve: { root: [path.join(__dirname, "scripts"), path.join(__dirname, "assets/javascripts"), path.join(__dirname, "assets/stylesheets")], extensions: ["", ".webpack.js", ".web.js", ".js", ".jsx", ".scss", ".css", "config.js"] }, module: { loaders: [] } };
Remove exposing React as that was fixed in the React update
Remove exposing React as that was fixed in the React update
JavaScript
mit
mscienski/stpauls,szyablitsky/react-webpack-rails-tutorial,RomanovRoman/react-webpack-rails-tutorial,crmaxx/react-webpack-rails-tutorial,roxolan/react-webpack-rails-tutorial,Rvor/react-webpack-rails-tutorial,phosphene/react-on-rails-cherrypick,jeffthemaximum/Teachers-Dont-Pay-Jeff,shakacode/react-webpack-rails-tutorial,skv-headless/react-webpack-rails-tutorial,skv-headless/react-webpack-rails-tutorial,michaelgruber/react-webpack-rails-tutorial,janklimo/react-webpack-rails-tutorial,stevecj/term_palette_maker,shakacode/react-webpack-rails-tutorial,BadAllOff/react-webpack-rails-tutorial,RomanovRoman/react-webpack-rails-tutorial,jeffthemaximum/jeffline,michaelgruber/react-webpack-rails-tutorial,CerebralStorm/workout_logger,hoffmanc/react-webpack-rails-tutorial,justin808/react-webpack-rails-tutorial,BadAllOff/react-webpack-rails-tutorial,phosphene/react-on-rails-cherrypick,csmalin/react-webpack-rails-tutorial,skv-headless/react-webpack-rails-tutorial,shilu89757/react-webpack-rails-tutorial,bronson/react-webpack-rails-tutorial,shakacode/react-webpack-rails-tutorial,jeffthemaximum/jeffline,janklimo/react-webpack-rails-tutorial,cacheflow/react-webpack-rails-tutorial,cacheflow/react-webpack-rails-tutorial,michaelgruber/react-webpack-rails-tutorial,csterritt/react-webpack-rails-tutorial,janklimo/react-webpack-rails-tutorial,szyablitsky/react-webpack-rails-tutorial,Johnnycus/react-webpack-rails-tutorial,justin808/react-webpack-rails-tutorial,BadAllOff/react-webpack-rails-tutorial,StanBoyet/react-webpack-rails-tutorial,jeffthemaximum/Teachers-Dont-Pay-Jeff,jeffthemaximum/Teachers-Dont-Pay-Jeff,thiagoc7/react-webpack-rails-tutorial,yakovenkodenis/react-webpack-rails-tutorial,CerebralStorm/workout_logger,roxolan/react-webpack-rails-tutorial,thiagoc7/react-webpack-rails-tutorial,crmaxx/react-webpack-rails-tutorial,StanBoyet/react-webpack-rails-tutorial,CerebralStorm/workout_logger,kentwilliam/react-webpack-rails-tutorial,phosphene/react-on-rails-cherrypick,csterritt/react-webpack-rails-tutorial,crmaxx/react-webpack-rails-tutorial,kentwilliam/react-webpack-rails-tutorial,shilu89757/react-webpack-rails-tutorial,roxolan/react-webpack-rails-tutorial,bsy/react-webpack-rails-tutorial,BadAllOff/react-webpack-rails-tutorial,Rvor/react-webpack-rails-tutorial,bsy/react-webpack-rails-tutorial,suzukaze/react-webpack-rails-tutorial,hoffmanc/react-webpack-rails-tutorial,Johnnycus/react-webpack-rails-tutorial,shilu89757/react-webpack-rails-tutorial,kentwilliam/react-webpack-rails-tutorial,bronson/react-webpack-rails-tutorial,stevecj/term_palette_maker,StanBoyet/react-webpack-rails-tutorial,bsy/react-webpack-rails-tutorial,shunwen/react-webpack-rails-tutorial,phosphene/react-on-rails-cherrypick,bsy/react-webpack-rails-tutorial,jeffthemaximum/jeffline,stevecj/term_palette_maker,RomanovRoman/react-webpack-rails-tutorial,StanBoyet/react-webpack-rails-tutorial,shunwen/react-webpack-rails-tutorial,csterritt/react-webpack-rails-tutorial,CerebralStorm/workout_logger,bronson/react-webpack-rails-tutorial,cacheflow/react-webpack-rails-tutorial,jeffthemaximum/Teachers-Dont-Pay-Jeff,csmalin/react-webpack-rails-tutorial,szyablitsky/react-webpack-rails-tutorial,jeffthemaximum/jeffline,suzukaze/react-webpack-rails-tutorial,thiagoc7/react-webpack-rails-tutorial,shunwen/react-webpack-rails-tutorial,Rvor/react-webpack-rails-tutorial,cacheflow/react-webpack-rails-tutorial,crmaxx/react-webpack-rails-tutorial,suzukaze/react-webpack-rails-tutorial,janklimo/react-webpack-rails-tutorial,Johnnycus/react-webpack-rails-tutorial,michaelgruber/react-webpack-rails-tutorial,yakovenkodenis/react-webpack-rails-tutorial,RomanovRoman/react-webpack-rails-tutorial,justin808/react-webpack-rails-tutorial,hoffmanc/react-webpack-rails-tutorial,shilu89757/react-webpack-rails-tutorial,yakovenkodenis/react-webpack-rails-tutorial,yakovenkodenis/react-webpack-rails-tutorial,shunwen/react-webpack-rails-tutorial,szyablitsky/react-webpack-rails-tutorial,suzukaze/react-webpack-rails-tutorial,jeffthemaximum/Teachers-Dont-Pay-Jeff,stevecj/term_palette_maker,csmalin/react-webpack-rails-tutorial,justin808/react-webpack-rails-tutorial,shakacode/react-webpack-rails-tutorial,bronson/react-webpack-rails-tutorial,hoffmanc/react-webpack-rails-tutorial,jeffthemaximum/jeffline,skv-headless/react-webpack-rails-tutorial,thiagoc7/react-webpack-rails-tutorial,Johnnycus/react-webpack-rails-tutorial,csmalin/react-webpack-rails-tutorial,roxolan/react-webpack-rails-tutorial,csterritt/react-webpack-rails-tutorial,Rvor/react-webpack-rails-tutorial,kentwilliam/react-webpack-rails-tutorial,mscienski/stpauls
255c7b47e7686650f5712fb2632d3b4c0e863d64
src/lib/substituteVariantsAtRules.js
src/lib/substituteVariantsAtRules.js
import _ from 'lodash' import postcss from 'postcss' const variantGenerators = { hover: (container, config) => { const cloned = container.clone() cloned.walkRules(rule => { rule.selector = `.hover${config.options.separator}${rule.selector.slice(1)}:hover` }) return cloned.nodes }, focus: (container, config) => { const cloned = container.clone() cloned.walkRules(rule => { rule.selector = `.focus${config.options.separator}${rule.selector.slice(1)}:focus` }) return cloned.nodes }, } export default function(config) { return function(css) { const unwrappedConfig = config() css.walkAtRules('variants', atRule => { const variants = postcss.list.comma(atRule.params) if (variants.includes('responsive')) { const responsiveParent = postcss.atRule({ name: 'responsive' }) atRule.before(responsiveParent) responsiveParent.append(atRule) } atRule.before(atRule.clone().nodes) _.forEach(['focus', 'hover'], variant => { if (variants.includes(variant)) { atRule.before(variantGenerators[variant](atRule, unwrappedConfig)) } }) atRule.remove() }) } }
import _ from 'lodash' import postcss from 'postcss' const variantGenerators = { hover: (container, config) => { const cloned = container.clone() cloned.walkRules(rule => { rule.selector = `.hover${config.options.separator}${rule.selector.slice(1)}:hover` }) container.before(cloned.nodes) }, focus: (container, config) => { const cloned = container.clone() cloned.walkRules(rule => { rule.selector = `.focus${config.options.separator}${rule.selector.slice(1)}:focus` }) container.before(cloned.nodes) }, } export default function(config) { return function(css) { const unwrappedConfig = config() css.walkAtRules('variants', atRule => { const variants = postcss.list.comma(atRule.params) if (variants.includes('responsive')) { const responsiveParent = postcss.atRule({ name: 'responsive' }) atRule.before(responsiveParent) responsiveParent.append(atRule) } atRule.before(atRule.clone().nodes) _.forEach(['focus', 'hover'], variant => { if (variants.includes(variant)) { variantGenerators[variant](atRule, unwrappedConfig) } }) atRule.remove() }) } }
Move responsibility for appending nodes into variant generators themselves
Move responsibility for appending nodes into variant generators themselves
JavaScript
mit
tailwindlabs/tailwindcss,tailwindlabs/tailwindcss,tailwindlabs/tailwindcss,tailwindcss/tailwindcss
fcb2a9ecda9fe5dfb9484531ab697ef4c26ae608
test/create-test.js
test/create-test.js
var tape = require("tape"), jsdom = require("jsdom"), d3 = Object.assign(require("../"), require("d3-selection")); /************************************* ************ Components ************* *************************************/ // Leveraging create hook with selection as first argument. var checkboxHTML = ` <label class="form-check-label"> <input type="checkbox" class="form-check-input"> <span class="checkbox-label-span"></span> </label> `, checkbox = d3.component("div", "form-check") .create(function (selection){ selection.html(checkboxHTML); }) .render(function (selection, props){ if(props && props.label){ selection.select(".checkbox-label-span") .text(props.label); } }); /************************************* ************** Tests **************** *************************************/ tape("Create hook should pass selection on enter.", function(test) { var div = d3.select(jsdom.jsdom().body).append("div"); div.call(checkbox); test.equal(div.html(), `<div class="form-check">${checkboxHTML}</div>`); test.end(); }); tape("Render should have access to selection content from create hook.", function(test) { var div = d3.select(jsdom.jsdom().body).append("div"); div.call(checkbox, { label: "My Checkbox"}); test.equal(div.select(".checkbox-label-span").text(), "My Checkbox"); test.end(); });
var tape = require("tape"), jsdom = require("jsdom"), d3 = Object.assign(require("../"), require("d3-selection")); /************************************* ************ Components ************* *************************************/ // Leveraging create hook with selection as first argument. var card = d3.component("div", "card") .create(function (selection){ selection .append("div").attr("class", "card-block") .append("div").attr("class", "card-text"); }) .render(function (selection, props){ selection .select(".card-text") .text(props.text); }); /************************************* ************** Tests **************** *************************************/ tape("Create hook should pass selection on enter.", function(test) { var div = d3.select(jsdom.jsdom().body).append("div"); div.call(card, { text: "I'm in a card." }); test.equal(div.html(), [ '<div class="card">', '<div class="card-block">', '<div class="card-text">', "I\'m in a card.", "</div>", "</div>", "</div>" ].join("")); test.end(); });
Change test to use card concept
Change test to use card concept
JavaScript
bsd-3-clause
curran/d3-component
3500fe09fd8aba9d9d789f1308d57955aaeacd5d
public/javascripts/page.js
public/javascripts/page.js
$(function() { var socket = new WebSocket("ws://" + window.location.host + "/"); socket.onmessage = function(message){ console.log('got a message: ') console.log(message) } });
$(function() { var socket = new WebSocket("ws://" + window.location.host + "/"); socket.addEventListener('message', function(message){ console.log('got a message: ') console.log(message) }); });
Use addEventListener rather than onmessage
Use addEventListener rather than onmessage
JavaScript
mit
portlandcodeschool-jsi/barebones-chat,portlandcodeschool-jsi/barebones-chat
1a8ad6d06e5b465ee331cbc5c4957862edf31950
test/fixtures/output_server.js
test/fixtures/output_server.js
/* * grunt-external-daemon * https://github.com/jlindsey/grunt-external-daemon * * Copyright (c) 2013 Joshua Lindsey * Licensed under the MIT license. */ 'use strict'; process.stdout.write("STDOUT Message"); process.stderr.write("STDERR Message");
/* * grunt-external-daemon * https://github.com/jlindsey/grunt-external-daemon * * Copyright (c) 2013 Joshua Lindsey * Licensed under the MIT license. */ 'use strict'; process.stdout.setEncoding('utf-8'); process.stderr.setEncoding('utf-8'); process.stdout.write("STDOUT Message"); process.stderr.write("STDERR Message");
Add encoding to output server streams
Add encoding to output server streams
JavaScript
mit
jlindsey/grunt-external-daemon
ea850baf397ae98a78222691e1f38571d66d029c
db/config.js
db/config.js
//For Heroku Deployment var URI = require('urijs'); var config = URI.parse(process.env.DATABASE_URL); config['ssl'] = true; module.exports = config; // module.exports = { // database: 'sonder', // user: 'postgres', // //password: 'postgres', // port: 32769, // host: '192.168.99.100' // };
//For Heroku Deployment var URI = require('urijs'); // var config = URI.parse(process.env.DATABASE_URL); // config['ssl'] = true; var config = process.env.DATABASE_URL; module.exports = config; // module.exports = { // database: 'sonder', // user: 'postgres', // //password: 'postgres', // port: 32769, // host: '192.168.99.100' // };
Connect to PG via ENV string
Connect to PG via ENV string
JavaScript
mit
aarontrank/SonderServer,MapReactor/SonderServer,MapReactor/SonderServer,aarontrank/SonderServer
7470675462f60a8260ca6f9d8e890f297046bee5
src/frontend/components/UserApp.js
src/frontend/components/UserApp.js
import React from "react"; import RightColumn from "./RightColumn"; const UserApp = ({ children }) => ( <div className="main-container"> <section className="who-are-we"> <h1>GBG tech</h1> </section> <section className="row center-container"> <section className="content"> {children} </section> <RightColumn/> </section> </div> ); export default UserApp;
import React from "react"; import RightColumn from "./RightColumn"; const UserApp = ({ children }) => ( <div className="main-container"> <section className="who-are-we"> <h1>#gbgtech</h1> </section> <section className="row center-container"> <section className="content"> {children} </section> <RightColumn/> </section> </div> ); export default UserApp;
Use lowercase name of gbgtech
Use lowercase name of gbgtech
JavaScript
mit
gbgtech/gbgtechWeb,gbgtech/gbgtechWeb
588a552ce9750a70f0c80ed574c139f563d5ffcc
optimize/index.js
optimize/index.js
var eng = require('./node/engine'); var index = module.exports = { localMinimize: function(func, options, callback) { eng.runPython('local', func, options, callback); }, globalMinimize: function(func, options, callback) { eng.runPython('global', func, options, callback); }, nonNegLeastSquares: function(A, b, callback) { eng.runPython('nnls', A, b, callback); }, fitCurve: function(func, xData, yData, options, callback) { eng.runPython('fit', func, options, callback, xData, yData); }, findRoot: function(func, lower, upper, options, callback) { eng.runPython('root', func, options, callback, lower, upper); } }; index.fitCurve.linear = function(xData, yData, callback) { eng.runPython('fit', 'a * x + b', { variables: ['x', 'a', 'b'] }, callback, xData, yData); }; index.fitCurve.quadratic = function(xData, yData, callback) { eng.runPython('fit', 'a * (x**2) + b * x + c', { variables: ['x', 'a', 'b', 'c'] }, callback, xData, yData); };
var eng = require('./node/engine'); var index = module.exports = { localMinimize: function(func, options, callback) { eng.runPython('local', func, options, callback); }, globalMinimize: function(func, options, callback) { eng.runPython('global', func, options, callback); }, minimizeEuclideanNorm: function(A, b, callback) { eng.runPython('nnls', A, b, callback); }, fitCurve: function(func, xData, yData, options, callback) { eng.runPython('fit', func, options, callback, xData, yData); }, findRoot: function(func, lower, upper, options, callback) { eng.runPython('root', func, options, callback, lower, upper); }, findVectorRoot: function(func, guess, options, callback) { eng.runPython('vectorRoot', func, options, callback, guess); }, calcDerivatives: function(func, point, options, callback) { eng.runPython('derivative', func, options, callback, point); } }; index.fitCurve.linear = function(xData, yData, callback) { eng.runPython('fit', 'a * x + b', { variables: ['x', 'a', 'b'] }, callback, xData, yData); }; index.fitCurve.quadratic = function(xData, yData, callback) { eng.runPython('fit', 'a * (x**2) + b * x + c', { variables: ['x', 'a', 'b', 'c'] }, callback, xData, yData); };
Add API for derivative, vector root
Add API for derivative, vector root
JavaScript
mit
acjones617/scipy-node,acjones617/scipy-node
cda7032237124def696840041c872e5fc9427ad4
delighted.js
delighted.js
var Delighted = require('./lib/delighted'); module.exports = function(key) { return new Delighted(key); };
var Delighted = require('./lib/Delighted'); module.exports = function(key) { return new Delighted(key); };
Change case for required Delighted in lib
Change case for required Delighted in lib Linux is case sensitive and fails to load the required file.
JavaScript
mit
delighted/delighted-node
94396993d1a0552559cb5b822f797adee09ea2b1
test/com/spinal/ioc/plugins/theme-test.js
test/com/spinal/ioc/plugins/theme-test.js
/** * com.spinal.ioc.plugins.ThemePlugin Class Tests * @author Patricio Ferreira <3dimentionar@gmail.com> **/ define(['ioc/plugins/theme'], function(ThemePlugin) { describe('com.spinal.ioc.plugins.ThemePlugin', function() { before(function() { }); after(function() { }); describe('#new()', function() { }); }); });
/** * com.spinal.ioc.plugins.ThemePlugin Class Tests * @author Patricio Ferreira <3dimentionar@gmail.com> **/ define(['ioc/plugins/theme'], function(ThemePlugin) { describe('com.spinal.ioc.plugins.ThemePlugin', function() { before(function() { this.plugin = null; }); after(function() { delete this.plugin; }); describe('#new()', function() { it('Should return an instance of ThemePlugin'); }); describe('#parse()', function() { it('Should parse themes from specified on a given spec'); }); describe('#currentTheme()', function() { it('Should return the current theme'); }); describe('#useBootstrap()', function() { it('Should inject bootstrap-core and bootstrap-theme'); it('Should inject only bootstrap-core'); it('Should inject only bootstrap-theme'); }); describe('#useDefault()', function() { it('Should inject theme flagged as default'); }); describe('#validate()', function() { it('Should return false: theme name is not a String'); it('Should return false: theme is not registered'); it('Should return false: current theme is the same as the one being validated'); }); describe('#applyTheme()', function() { it('Should inject a given theme'); }); describe('#removeTheme()', function() { it('Should remove all themes except for bootstrap core and theme'); }); describe('#resolveURI()', function() { it('Should resolve theme URI for a given theme path'); }); describe('#getTheme()', function() { it('Should retrieve a theme object registered given a theme name'); it('Should NOT retrieve a theme object registered given a theme name'); }); describe('#changeTheme()', function() { it('Should change the current theme with another one given a theme name'); }); describe('#run()', function() { it('Should executes plugin logic'); }); }); });
Test cases for ThemePlugin Class added to the unit test file.
Test cases for ThemePlugin Class added to the unit test file.
JavaScript
mit
nahuelio/boneyard,3dimention/spinal,3dimention/boneyard
53b76340aa614a01a206a728f14406aa1cdef1c9
test/e2e/page/create/create_result_box.js
test/e2e/page/create/create_result_box.js
'use strict'; (function (module, undefined) { function CreateResultBox(elem) { // TODO: add property 'list' and 'details' for each UI state. this.elem = elem; this.list = new TimetableList(elem); } Object.defineProperties(CreateResultBox.prototype, { 'showingList': { value: true }, 'showingDetails': { value: false } }); CreateResultBox.prototype.clickGenerateButton = function () { return this.elem.$('.btn-generate').click(); }; module.exports = CreateResultBox; function TimetableList(box) { this.ttElems = box.$$('.item-timetable'); } Object.defineProperties(TimetableList.prototype, { 'nTimetables': { get: function () { return this.ttElems.count(); } } }); TimetableList.prototype.getItemAt = function (index) { return new TimetableListItem(this.ttElems.get(index)); }; function TimetableListItem(elem) { this.elem = elem; } Object.defineProperties(TimetableListItem.prototype, { 'credits': { get: function () { return this.elem.$('.credits').getText(); } }, 'nClassDays': { get: function () { return this.elem.$('.n-class-days').getText(); } }, 'nFreeHours': { get: function () { return this.elem.$('.n-free-hours').getText(); } } }); })(module);
'use strict'; (function (module, undefined) { function CreateResultBox(elem) { // TODO: add property 'list' and 'details' for each UI state. this.elem = elem; this.list = new TimetableList(elem); } Object.defineProperties(CreateResultBox.prototype, { 'showingList': { value: true }, 'showingDetails': { value: false } }); module.exports = CreateResultBox; function TimetableList(box) { this.ttElems = box.$$('.item-timetable'); } Object.defineProperties(TimetableList.prototype, { 'nTimetables': { get: function () { return this.ttElems.count(); } } }); TimetableList.prototype.getItemAt = function (index) { return new TimetableListItem(this.ttElems.get(index)); }; function TimetableListItem(elem) { this.elem = elem; } Object.defineProperties(TimetableListItem.prototype, { 'credits': { get: function () { return this.elem.$('.credits').getText(); } }, 'nClassDays': { get: function () { return this.elem.$('.n-class-days').getText(); } }, 'nFreeHours': { get: function () { return this.elem.$('.n-free-hours').getText(); } } }); })(module);
Remove useless & wrong code for CreateResultBox
Remove useless & wrong code for CreateResultBox * Copy & paste sucks.
JavaScript
mit
kyukyukyu/dash-web,kyukyukyu/dash-web
27b391f8bdf57b9c3215ef99a29351ba55db65f5
public/main.js
public/main.js
$(function() { var formatted_string = 'hoge'; // $('#text_output').text(formatted_string); $('#text_input').bind('keyup', function(e) { var text = $('#text_input').val(); console.log(text); $.ajax({ url: 'http://localhost:9292/parse/', method: 'POST', crossDomain: true, data: {'text': text} }).error(function() { console.log('Error'); }).done(function(text) { console.log(text); update(text); }); }); }); function update(formatted_string) { $('#text_output').html(formatted_string); }
$(function() { var formatted_string = 'hoge'; // $('#text_output').text(formatted_string); $('#text_input').bind('keyup', function(e) { var text = $('#text_input').val(); console.log(text); parse(text); }); }); function update(formatted_string) { $('#text_output').html(formatted_string); } function parse(text) { $.ajax({ url: 'http://localhost:9292/parse/', method: 'POST', crossDomain: true, data: {'text': text} }).error(function() { console.log('Error'); }).done(function(text) { console.log(text); update(text); }); }
Split out to parse function
Split out to parse function
JavaScript
mit
gouf/test_sinatra_markdown_preview,gouf/test_sinatra_markdown_preview
512ebaf12ea76d3613c2742d4ea5b61a257e5e04
test/templateLayout.wefTest.js
test/templateLayout.wefTest.js
/*! * templateLayout tests * Copyright (c) 2011 Pablo Escalada * MIT Licensed */ TestCase("templateLayout", { "test templateLayout registration":function () { assertNotUndefined(wef.plugins.registered.templateLayout); assertEquals("templateLayout", wef.plugins.registered["templateLayout"].name); }, "test templateLayout namespace":function () { assertNotUndefined(wef.plugins.templateLayout); assertEquals("templateLayout", wef.plugins.templateLayout.name); } }); AsyncTestCase("templateLayoutAsync", { "test templateLayout listen cssParser events":function (queue) { //requires cssParser var text = "body {display-model: \"a (intrinsic), b (intrinsic)\";} div#uno {situated: a; display-model: \"123 (intrinsic)\";}"; queue.call(function (callbacks) { var myCallback = callbacks.add(function () { wef.plugins.registered.templateLayout.templateLayout(); wef.plugins.registered.cssParser.cssParser().parse(text); }); window.setTimeout(myCallback, 5000); }); queue.call(function () { var result = wef.plugins.registered.templateLayout.getLastEvent().property; //console.log(result); assertEquals("display-model", result); }) } })
/*! * templateLayout tests * Copyright (c) 2011 Pablo Escalada * MIT Licensed */ TestCase("templateLayout", { "test templateLayout registration":function () { assertNotUndefined(wef.plugins.registered.templateLayout); assertEquals("templateLayout", wef.plugins.registered.templateLayout.name); }, "test templateLayout namespace":function () { assertNotUndefined(wef.fn.templateLayout); assertEquals("templateLayout", wef.fn.templateLayout.name); } }); AsyncTestCase("templateLayoutAsync", { "test templateLayout listen cssParser events":function (queue) { //requires cssParser var text = "body {display-model: \"a (intrinsic), b (intrinsic)\";} div#uno {situated: a; display-model: \"123 (intrinsic)\";}"; queue.call(function (callbacks) { var myCallback = callbacks.add(function () { wef.fn.templateLayout.init(); wef.fn.cssParser.init().parse(text); }); window.setTimeout(myCallback, 5000); }); queue.call(function () { var result = wef.fn.templateLayout.getLastEvent().property; //console.log(result); assertEquals("display-model", result); }) } })
Update code to pass tests
Update code to pass tests
JavaScript
mit
diesire/cssTemplateLayout,diesire/cssTemplateLayout,diesire/cssTemplateLayout
302c3434a44b3e51d84b70e801a72e9119f106f4
src/scripts/main.js
src/scripts/main.js
// ES2015 polyfill import 'babel-polyfill'; // Modernizr import './modernizr'; // Components import './components/example';
// Polyfills // Only use the polyfills you need e.g // import 'core-js/object'; // import 'js-polyfills/html'; // Modernizr import './modernizr'; // Components import './components/example';
Use core-js and js-polyfills instead of babel-polyfill
Use core-js and js-polyfills instead of babel-polyfill
JavaScript
mit
strt/strt-boilerplate,strt/strt-boilerplate
940f4f4da198335f51c2f8e76fc1c0caffb7736c
__tests__/index.js
__tests__/index.js
import config from "../" import postcss from "postcss" import stylelint from "stylelint" import test from "tape" test("basic properties of config", t => { t.ok(isObject(config.rules), "rules is object") t.end() }) function isObject(obj) { return typeof obj === "object" && obj !== null } const css = ( `a { \ttop: .2em; } `) postcss() .use(stylelint(config)) .process(css) .then(checkResult) .catch(e => console.log(e.stack)) function checkResult(result) { const { messages } = result test("expected warnings", t => { t.equal(messages.length, 1, "flags one warning") t.ok(messages.every(m => m.type === "warning"), "message of type warning") t.ok(messages.every(m => m.plugin === "stylelint"), "message of plugin stylelint") t.equal(messages[0].text, "Expected a leading zero (number-leading-zero)", "correct warning text") t.end() }) }
import config from "../" import stylelint from "stylelint" import test from "tape" test("basic properties of config", t => { t.ok(isObject(config.rules), "rules is object") t.end() }) function isObject(obj) { return typeof obj === "object" && obj !== null } const css = ( `a { \ttop: .2em; } `) stylelint.lint({ code: css, config: config, }) .then(checkResult) .catch(function (err) { console.error(err.stack) }) function checkResult(data) { const { errored, results } = data const { warnings } = results[0] test("expected warnings", t => { t.ok(errored, "errored") t.equal(warnings.length, 1, "flags one warning") t.equal(warnings[0].text, "Expected a leading zero (number-leading-zero)", "correct warning text") t.end() }) }
Use stylelint standalone API in test
Use stylelint standalone API in test
JavaScript
mit
ntwb/stylelint-config-wordpress,WordPress-Coding-Standards/stylelint-config-wordpress,GaryJones/stylelint-config-wordpress,stylelint/stylelint-config-wordpress
fd7dda54d0586906ccd07726352ba8566176ef71
app/scripts/app.js
app/scripts/app.js
(function () { 'use strict'; /** * ngInject */ function StateConfig($urlRouterProvider) { $urlRouterProvider.otherwise('/'); } // color ramp for sectors var sectorColors = { 'School (K-12)': '#A6CEE3', 'Office': '#1F78B4', 'Warehouse': '#B2DF8A', 'College/ University': '#33A02C', 'Other': '#FB9A99', 'Retail': '#E31A1C', 'Municipal': '#FDBF6F', 'Multifamily': '#FF7F00', 'Hotel': '#CAB2D6', 'Industrial': '#6A3D9A', 'Unknown': '#DDDDDD' }; /** * @ngdoc overview * @name mos * @description * # mos * * Main module of the application. */ angular .module('mos', [ 'mos.views.charts', 'mos.views.map', 'mos.views.info', 'mos.views.detail', 'mos.views.compare', 'headroom' ]).config(StateConfig); angular.module('mos').constant('MOSColors', sectorColors); })();
(function () { 'use strict'; /** * ngInject */ function StateConfig($urlRouterProvider) { $urlRouterProvider.otherwise('/'); } // color ramp for sectors var sectorColors = { 'School (K-12)': '#A6CEE3', 'Office': '#1F78B4', 'Medical Office': '#52A634', 'Warehouse': '#B2DF8A', 'College/ University': '#33A02C', 'Other': '#FB9A99', 'Retail': '#E31A1C', 'Municipal': '#FDBF6F', 'Multifamily': '#FF7F00', 'Hotel': '#CAB2D6', 'Industrial': '#6A3D9A', 'Worship': '#9C90C4', 'Supermarket': '#E8AE6C', 'Parking': '#C9DBE6', 'Laboratory': '#3AA3FF', 'Hospital': '#C6B4FF', 'Data Center': '#B8FFA8', 'Unknown': '#DDDDDD' }; /** * @ngdoc overview * @name mos * @description * # mos * * Main module of the application. */ angular .module('mos', [ 'mos.views.charts', 'mos.views.map', 'mos.views.info', 'mos.views.detail', 'mos.views.compare', 'headroom' ]).config(StateConfig); angular.module('mos').constant('MOSColors', sectorColors); })();
Add remaining building types to MOSColors
Add remaining building types to MOSColors
JavaScript
mit
azavea/mos-energy-benchmark,azavea/mos-energy-benchmark,azavea/mos-energy-benchmark
dfcde972cde79fd3f354366ac3d9f3bc136a5981
app/server/grid.js
app/server/grid.js
import _ from 'underscore'; class Grid { // The state of a particular game grid constructor({ columnCount = 7, rowCount = 6, columns = _.times(columnCount, () => []), lastPlacedChip = null }) { this.columnCount = columnCount; this.rowCount = rowCount; this.columns = columns; this.lastPlacedChip = lastPlacedChip; } // Reset the grid by removing all placed chips resetGrid() { this.columns.forEach((column) => { column.length = 0; }); this.lastPlacedChip = null; } // Place the given chip into the column defined on it placeChip(chip) { if (chip.column >= 0 && chip.column < this.columnCount && (this.columns[chip.column].length + 1) < this.rowCount) { this.columns[chip.column].push(chip); this.lastPlacedChip = chip; chip.row = this.columns[chip.column].length - 1; } } toJSON() { return { columnCount: this.columnCount, rowCount: this.rowCount, columns: this.columns, lastPlacedChip: this.lastPlacedChip }; } } export default Grid;
import _ from 'underscore'; class Grid { // The state of a particular game grid constructor({ columnCount = 7, rowCount = 6, columns = _.times(columnCount, () => []), lastPlacedChip = null }) { this.columnCount = columnCount; this.rowCount = rowCount; this.columns = columns; this.lastPlacedChip = lastPlacedChip; } // Reset the grid by removing all placed chips resetGrid() { this.columns.forEach((column) => { column.length = 0; }); this.lastPlacedChip = null; } // Place the given chip into the column defined on it placeChip(chip) { if (chip.column >= 0 && chip.column < this.columnCount && this.columns[chip.column].length < this.rowCount) { this.columns[chip.column].push(chip); this.lastPlacedChip = chip; chip.row = this.columns[chip.column].length - 1; } } toJSON() { return { columnCount: this.columnCount, rowCount: this.rowCount, columns: this.columns, lastPlacedChip: this.lastPlacedChip }; } } export default Grid;
Fix bug where chip cannot be placed in last row
Fix bug where chip cannot be placed in last row
JavaScript
mit
caleb531/connect-four
202941769bd594e31719303882df16ee6ece95c9
react/index.js
react/index.js
var deps = [ '/stdlib/tag.js', '/stdlib/observable.js' ]; function increment(x) { return String(parseInt(x, 10) + 1); } function onReady(tag, observable) { var value = observable.observe("0"); function onChange(evt) { value.set(evt.target.value); } var input = tag.tag({ name: 'input', attributes: {type: 'number', value: value}, handlers: {keyup: onChange, change: onChange} }); var inc = observable.lift(increment); var output = tag.tag({ name: 'input', attributes: {type: 'number', value: inc(value), readOnly: true} }); var div = tag.tag({name: 'div', contents: [input, output]}); yoink.define(div); } yoink.require(deps, onReady);
var deps = [ '/stdlib/tag.js', '/stdlib/observable.js' ]; function increment(x) { return String(parseInt(x, 10) + 1); } function onReady(tag, observable) { var value = observable.observe("0"); var input = tag.tag({ name: 'input', attributes: {type: 'number', value: value}, }); var inc = observable.lift(increment); var output = tag.tag({ name: 'input', attributes: {type: 'number', value: inc(value), readOnly: true} }); var div = tag.tag({name: 'div', contents: [input, output]}); yoink.define(div); } yoink.require(deps, onReady);
Add 'change' event handler if tag attribute is an observable.
Add 'change' event handler if tag attribute is an observable.
JavaScript
bsd-3-clause
garious/poochie-examples,garious/yoink-examples,garious/poochie-examples,garious/yoink-examples