commit
stringlengths
40
40
subject
stringlengths
1
3.25k
old_file
stringlengths
4
311
new_file
stringlengths
4
311
old_contents
stringlengths
0
26.3k
lang
stringclasses
3 values
proba
float64
0
1
diff
stringlengths
0
7.82k
31f8f1f1b0e0db9e90f13c472df94ca188725ee3
Add mfRange in preferences
defaultOptions/mass.js
defaultOptions/mass.js
define(function () { return { "options": { "minimalHeight": 0, "widthTop": 0.1, "widthBottom": 0.2, "zone": { "low": -0.5, "high": 4.5 }, "mfRange":"C0-30 H0-60 N0-5 O0-10 F0-3 Cl0-3", "maxResults": 200, "bestOf": 0, "minSimilarity": 50, "minUnsaturation":-5, "maxUnsaturation": 50, "useUnsaturation": false, "integerUnsaturation": false, "massRange": 0.1, "decimalsPPM":4, "decimalsMass": 4, "addExperimentalExtract":true } } });
JavaScript
0
@@ -265,38 +265,52 @@ %22C0- -3 +10 0 H0- -6 +20 0 N0- -5 +10 O0-10 +S0-5 F0- -3 +5 Cl0- -3 +5 Br0-5 %22,%0A
52b0c509ccd701ba8758c310d4979b5eb20fb7b9
add debug logging (DEBUG=refocus:pubsub:elapsed) (#1144)
realtime/pubSubStats.js
realtime/pubSubStats.js
/** * Copyright (c) 2019, salesforce.com, inc. * All rights reserved. * Licensed under the BSD 3-Clause license. * For full license text, see LICENSE.txt file in the repo root or * https://opensource.org/licenses/BSD-3-Clause */ /** * /realtime/pubSubStats.js */ const activityLogType = 'pubsub'; const globalKey = require('./constants').pubSubStatsAggregator; const activityLog = require('../utils/activityLog'); const logLinePrototype = require('../config/activityLog')[activityLogType]; const errorMessage = { src: 'pubSubStats.track error: src must be "pub" or "sub"', evt: 'pubSubStats.track error: evt must be non-empty string', obj: 'pubSubStats.track error: obj must be a non-array object', }; /** * Used by publishers and subscribers to track the pubsub stats by event type * and process. These stats are stored and updated in memory in a global * variable by each publisher (i.e. every node process running on each web dyno * and every worker dyno) and by each subscriber (i.e. every node process * running on each web dyno). * * Note: we tried storing in redis first, rather than a global variable within * the node process, but that redis instance became a bottleneck which caused * performance issues so here we are using "global". * * @param {String} src - "pub" or "sub" * @param {String} evt - the real-time event type * @param {Object} obj - the event payload * @throws {Error} if invalid args */ function track(src, evt, obj) { const now = Date.now(); // Validate args if (!['pub', 'sub'].includes(src)) { throw new Error(errorMessage.src); } if (!evt || typeof evt !== 'string' || evt.length === 0) { throw new Error(errorMessage.evt); } if (!obj || typeof obj !== 'object' || Array.isArray(obj)) { throw new Error(errorMessage.obj); } /* * Calculate the elapsed time. If we can't find an "updatedAt" attribute, * treat the elapsed time as 0 but console.trace the object. */ let elapsed = 0; if (obj.hasOwnProperty('updatedAt')) { elapsed = now - new Date(obj.updatedAt); } else if (obj.hasOwnProperty('new') && obj.new.hasOwnProperty('updatedAt')) { elapsed = now - new Date(obj.new.updatedAt); } else { console.trace('Where is updatedAt? ' + JSON.stringify(obj)); } // Initialize the global variable if necessary if (!global.hasOwnProperty(globalKey)) { global[globalKey] = {}; } /* * Initialize a new attribute in the global variable for this event type, if * necessary. */ if (!global[globalKey].hasOwnProperty(evt)) { global[globalKey][evt] = { pubCount: 0, pubTime: 0, subCount: 0, subTime: 0, }; } // Increment the count and elapsed time for this event. if (src === 'pub') { global[globalKey][evt].pubCount++; global[globalKey][evt].pubTime += elapsed; } else if (src === 'sub') { global[globalKey][evt].subCount++; global[globalKey][evt].subTime += elapsed; } } // track /** * Returns an array of pubsub stats objects to get logged and resets the global * pubSubStatsAggregator. * * @param {String} processName - the process name, e.g. web.1:3, worker.2, ... * @returns {Array<Object>} objects to get logged */ function prepareLogLines(processName) { // Short-circuit return empty array if there is nothing to log if (!global.hasOwnProperty(globalKey) || Object.keys(global[globalKey]).length === 0) { return []; } // Copy and reset the tracked stats const eventStats = JSON.parse(JSON.stringify(global[globalKey])); delete global[globalKey]; // Prepare and return a log line for each event type return Object.keys(eventStats).map((evt) => { const l = JSON.parse(JSON.stringify(logLinePrototype)); l.process = processName; l.key = evt; return Object.assign(l, eventStats[evt]); }); } // prepareLogLines /** * Writes out the pub-sub statistics for each event type and reset the global * pubSubStatsAggregator. * * @param {String} processName - the process name, e.g. web.1:3, worker.2, ... */ function log(processName) { prepareLogLines(processName).forEach((obj) => { activityLog.printActivityLogString(obj, activityLogType); }); } // log module.exports = { log, prepareLogLines, // export for testing only track, };
JavaScript
0
@@ -265,16 +265,74 @@ .js%0A */%0A +const debug = require('debug')('refocus:pubsub:elapsed');%0A const ac @@ -2045,46 +2045,155 @@ ;%0A -if (obj.hasOwnProperty('updatedAt')) %7B +let updatedAtFromObj;%0A let nameFromObj;%0A if (obj.hasOwnProperty('updatedAt')) %7B%0A updatedAtFromObj = obj.updatedAt;%0A nameFromObj = obj.name; %0A @@ -2311,24 +2311,98 @@ atedAt')) %7B%0A + updatedAtFromObj = obj.new.updatedAt;%0A nameFromObj = obj.new.name;%0A elapsed @@ -2515,24 +2515,269 @@ obj));%0A %7D%0A%0A + if (elapsed %3E 1000) %7B%0A debug(%60/realtime/pubSubStats.js%7Ctrack%7Csrc=$%7Bsrc%7D%7Cevt=$%7Bevt%7D%7C%60 +%0A %60now=$%7Bnow%7D%7Cname=$%7BnameFromObj%7D%7CupdatedAt=$%7BupdatedAtFromObj%7D%7C%60 +%0A %60updatedAtAsDate=$%7Bnew Date(updatedAtFromObj)%7D%7Celapsed=$%7Belapsed%7D%7C%60);%0A %7D%0A%0A // Initial
18b705e3d0be7a01410b72f2f9468288069ec13f
Add numbers (favorites, likes, comments) to posts on MyPostsToolPage
src/pages/tools/my-posts-tool.js
src/pages/tools/my-posts-tool.js
/* This file is a part of libertysoil.org website Copyright (C) 2016 Loki Education (Social Enterprise) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import React, { PropTypes } from 'react'; import { connect } from 'react-redux'; import Helmet from 'react-helmet'; import { Link } from 'react-router'; import { truncate } from 'grapheme-utils'; import { uuid4, Immutable as ImmutablePropType } from '../../prop-types/common'; import { MapOfPosts } from '../../prop-types/posts'; import { MapOfUsers } from '../../prop-types/users'; import createSelector from '../../selectors/createSelector'; import currentUserSelector from '../../selectors/currentUser'; import { ActionsTrigger } from '../../triggers'; import ApiClient from '../../api/client'; import { API_HOST } from '../../config'; import Button from '../../components/button'; import VisibilitySensor from '../../components/visibility-sensor'; const LIMIT = 25; class MyPostsToolPage extends React.Component { static displayName = 'SchoolsToolPage'; static propTypes = { current_user: ImmutablePropType(PropTypes.shape({ id: uuid4 })), dispatch: PropTypes.func.isRequired, posts: ImmutablePropType(MapOfPosts).isRequired, ui: ImmutablePropType(PropTypes.shape({ progress: ImmutablePropType(PropTypes.shape({ loadingUserPostsRiver: PropTypes.bool })).isRequired })), user_posts_river: ImmutablePropType(PropTypes.arrayOf(uuid4)).isRequired, users: ImmutablePropType(MapOfUsers) }; static async fetchData(router, store, client) { const userId = store.getState().getIn(['current_user', 'id']); const userName = store.getState().getIn(['users', userId, 'username']); const trigger = new ActionsTrigger(client, store.dispatch); await trigger.toolsLoadUserPostsRiver(userName, { limit: LIMIT, sort: '-created_at' }); } state = { displayLoadMore: true }; handleLoadPosts = async () => { const userId = this.props.current_user.get('id'); const userName = this.props.users.getIn([userId, 'username']); const client = new ApiClient(API_HOST); const trigger = new ActionsTrigger(client, this.props.dispatch); const result = await trigger.toolsLoadUserPostsRiver(userName, { limit: LIMIT, offset: this.props.user_posts_river.size, sort: '-created_at' }); if (Array.isArray(result) && result.length === 0) { this.setState({ displayLoadMore: false }); } }; handleLoadOnSensor = async (isVisible) => { if (isVisible && !this.props.ui.getIn(['progress', 'loadingUserPostsRiver'])) { this.handleLoadPosts(); } }; render() { const { posts, ui, user_posts_river } = this.props; const postsToDisplay = user_posts_river.map(postId => posts.get(postId)); return ( <div> <Helmet title="My posts tool on " /> {postsToDisplay.map((post, index) => <div className="tools_item tools_item-clickable" key={index}> <Link to={`/post/${post.get('id')}`}>{truncate(post.get('text'), { length: 70 })}</Link> </div> )} <div className="layout layout-align_center layout__space layout__space-double"> {this.state.displayLoadMore && user_posts_river.size >= LIMIT && <VisibilitySensor onChange={this.handleLoadOnSensor}> <Button title="Load more..." waiting={ui.getIn(['progress', 'loadingUserPostsRiver'])} onClick={this.handleLoadPosts} /> </VisibilitySensor> } </div> </div> ); } } const selector = createSelector( state => state.get('ui'), state => state.get('posts'), state => state.getIn(['tools', 'user_posts_river']), state => state.get('users'), currentUserSelector, (ui, posts, user_posts_river, users, current_user) => ({ ui, posts, user_posts_river, users, ...current_user }) ); export default connect(selector)(MyPostsToolPage);
JavaScript
0
@@ -1500,16 +1500,58 @@ ensor';%0A +import Icon from '../../components/icon';%0A %0A%0Aconst @@ -3621,23 +3621,71 @@ able -%22 key=%7Bindex%7D%3E%0A + layout layout-align_justify%22 key=%7Bindex%7D%3E%0A %3Cdiv%3E%0A @@ -3781,16 +3781,799 @@ %3C/Link%3E%0A + %3C/div%3E%0A %3Cdiv className=%22layout%22%3E%0A %3Cspan className=%22card__toolbar_item%22%3E%0A %3CIcon icon=%22favorite_border%22 outline size=%22small%22 /%3E%0A %3Cspan className=%22card__toolbar_item_value%22%3E%7Bpost.get('likers').size%7D%3C/span%3E%0A %3C/span%3E%0A%0A %3Cspan className=%22card__toolbar_item%22%3E%0A %3CIcon icon=%22star_border%22 outline size=%22small%22 /%3E%0A %3Cspan className=%22card__toolbar_item_value%22%3E%7Bpost.get('favourers').size%7D%3C/span%3E%0A %3C/span%3E%0A%0A %3Cspan className=%22card__toolbar_item%22 %3E%0A %3CIcon icon=%22chat_bubble_outline%22 outline size=%22small%22 /%3E%0A %3Cspan className=%22card__toolbar_item_value%22%3E%7Bpost.get('comments')%7D%3C/span%3E%0A %3C/span%3E%0A %3C/div%3E%0A
add2bb15aa38db9d538e68a6f74ffa7a0a2b7f12
Update videos.js
demo/demoApp/videos.js
demo/demoApp/videos.js
(function () { "use strict"; window.App.videos = [ { title: 'Teenage Mutant Ninja Turtles', url: 'http://fs.to/get/dl/6jw62sx93srfw13ejj1l2j2c6.0.521872670.0.1414844737/Teenage+Mutant+Ninja+Turtles+%282014%29+1080p.x264+AC3.mkv', type: 'vod' }, { title: '2Elephants Dream', url: 'https://archive.org/download/ElephantsDream/ed_1024_512kb.mp4', type: 'vod' }, { title: '3Europa plus', url: 'http://europaplus.cdnvideo.ru/europaplus-live/eptv_main.sdp/playlist.m3u8', type: 'hls' }, { title: '4PIK TV', url: 'http://phone.pik-tv.com/live/mp4:piktv3pik3tv/playlist.m3u8', type: 'hls' }, { title: '5Redbull', url: 'http://live.iphone.redbull.de.edgesuite.net/webtvHD.m3u8', type: 'hls' } ]; })();
JavaScript
0
@@ -958,8 +958,9 @@ %5D;%0A%7D)(); +%0A
abe9482a3e33c4114fad2233e53200e578e69bb6
Fix error handling
deploy/deploy-utils.js
deploy/deploy-utils.js
const path = require("path"); const homedir = require("os").homedir(); const fs = require("fs"); const spawn = require("child_process").spawn; const execFile = require("child_process").execFile; const { Subject, of, bindCallback, throwError } = require("rxjs"); const { map, mergeMap } = require("rxjs/operators"); exports.getConfigPath = function() { return path.join(homedir, ".chipster", "deploy-scripts.json"); }; exports.getConfig = function() { let confPath = this.getConfigPath(); let subject = new Subject(); fs.readFile(confPath, "utf8", (err, data) => { if (err) { if (err.code == "ENOENT") { subject.throwError( new Error("configuration file not found: " + confPath) ); } else { subject.throwError(err); } } else { try { let parsed = JSON.parse(data); subject.next(parsed); subject.complete(); } catch (err) { console.log("conf parse error", err); throwError( new Error("configuration file parsing failed", confPath, "\n", err) ); } } }); return subject; }; /** * Run a process * * Inherit stdin, stdout and stderr from the parent process. * Throw an error if the process exit code is not zero. * * @param {string} cmd * @param {string[]} args * @param {string} cwd working directory path or null to inherit */ exports.run = function(cmd, args, cwd) { return of(null).pipe( mergeMap(() => { // how would we convert this to an observable with bindCallback, when we are // are interested only about the "close" event? let subject = new Subject(); const child = spawn(cmd, args, { cwd: cwd, stdio: "inherit" }); child.on("close", code => { if (code != 0) { subject.error( new Error( cmd + " " + args.join(" ") + " exited with exit code " + code ) ); } subject.next(); subject.complete(); }); return subject; }) ); }; exports.runAndGetOutput = function(cmd, args) { // use regular bindCallback (instead of bindNodeCallback) to access stdout // and stderr also when there is an error return bindCallback(execFile)(cmd, args).pipe( map(res => { let err = res[0]; let stdout = res[1]; let stderr = res[2]; if (err) { console.log(stdout); console.log(stderr); throw err; } return stdout; }) ); };
JavaScript
0.000007
@@ -633,38 +633,22 @@ subject. -throwError(%0A +error( new Erro @@ -693,25 +693,16 @@ onfPath) -%0A );%0A @@ -727,22 +727,17 @@ subject. -throwE +e rror(err @@ -945,22 +945,25 @@ -throwE +subject.e rror(%0A
91808d5900804bf3d3bd8b8104c117f9f3dd17e6
check if auth is null
desktop-site/client.js
desktop-site/client.js
import 'babel-core/polyfill'; import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { Router, browserHistory } from 'react-router'; import useScroll from 'scroll-behavior/lib/useStandardScroll'; import configureStore from 'commons/redux/store'; import configureRoutes from 'routes'; import reducer from 'redux/reducers'; const store = configureStore(reducer, window.__INITIAL_STATE__); // const history = useScroll(() => browserHistory)(); const history = browserHistory; if (module.hot) { // Enable Webpack hot module replacement for reducers module.hot.accept('./redux/reducers', () => { const nextRootReducer = require('./redux/reducers'); store.replaceReducer(nextRootReducer); }); } require('../commons/utils/i18n').init(store); const routes = configureRoutes({ getAuth() { return store.getState().auth; }, }); if (window.gaid) { const ga = require('react-ga'); const options = { debug: false }; ga.initialize(window.gaid, options); history.listen((location) => { const auth = store.getState().auth; // 2016. 04. 19. [heekyu] TODO remove common logic for (var i = 0; i < (auth.roles || []).length; i++) { // eslint-disable-line const role = auth.roles[i]; if (role.type === 'admin') { return; } } ga.pageview(location.pathname); }); } render( <Provider store={store}> <Router history={history}> {routes} </Router> </Provider>, document.getElementById('root') );
JavaScript
0.00032
@@ -1094,16 +1094,34 @@ ).auth;%0A + if (auth) %7B%0A // 2 @@ -1171,16 +1171,18 @@ gic%0A + for (var @@ -1252,24 +1252,26 @@ -line%0A + const role = @@ -1288,24 +1288,26 @@ s%5Bi%5D;%0A + + if (role.typ @@ -1335,16 +1335,18 @@ + return;%0A @@ -1341,16 +1341,26 @@ return;%0A + %7D%0A %7D%0A
c8033ca959df0cc0b3702c3974cc5763b2fe93fe
fix CWD determination
devserver/devserver.js
devserver/devserver.js
/** * Custom development server with hot reload functionality using Babel * * @package: KPC client * @author: pospi <sam@everledger.io> * @since: 2016-09-08 * @flow */ const path = require('path'); const webpack = require('webpack'); const express = require('express'); const serveStatic = require('serve-static'); const devMiddleware = require('webpack-dev-middleware'); const hotMiddleware = require('webpack-hot-middleware'); const historyApiFallback = require("connect-history-api-fallback"); const topPath = path.join(__dirname, '../'); const staticPath = path.join(__dirname, './build/'); // read config const { EXTERNAL_PORT, WEBPACK_CONFIG_FILE, } = process.env; const webpackConfig = require(path.resolve(process.cwd, WEBPACK_CONFIG_FILE)); // init server (use express since the webpack middleware works on that) const app = express(); const compiler = webpack(webpackConfig); // route anything webpack or static dir doesn't handle via index file app.use(historyApiFallback(null)); app.use(function(req, res, next) { if (!req.url.match(/^\/(__webpack_hmr|res\/|.*?\.(js|json|css|jpg|gif|png)$)/)) { req.url = '/'; } next(); }); // webpack bindings const pn = 'verbose'; // none, errors-only, minimal, normal, verbose app.use(devMiddleware(compiler, { publicPath: webpackConfig.output.publicPath, contentBase: webpackConfig.devServer.contentBase, historyApiFallback: webpackConfig.devServer.historyApiFallback, stats: { // @see https://github.com/webpack/docs/wiki/node.js-api#stats context: topPath, hash: false, version: false, timings: true, assets: true, entrypoints: pn === "verbose", chunks: true, chunkModules: true, modules: true, cached: false, children: true, warnings: true, errorDetails: true, reasons: true, usedExports: true, providedExports: true, colors: true, }, })); app.use(hotMiddleware(compiler)); // pass through anything from the bundle dir directly app.use(serveStatic(staticPath, { 'index': false, })); // start! app.listen(EXTERNAL_PORT, function(err) { if (err) { return console.error(err); } console.log(`Listening at http://localhost:${EXTERNAL_PORT}/`); });
JavaScript
0.000001
@@ -737,16 +737,18 @@ cess.cwd +() , WEBPAC
c344d60d5f8412fffb912588f7e3dcf19d5b8f26
use computed prop (which uses caching) instead of calling the fn directly
src/shared/getComponentOption.js
src/shared/getComponentOption.js
import { isFunction, isObject } from '../utils/is-type' import { defaultInfo } from './constants' import { merge } from './merge' import { inMetaInfoBranch } from './meta-helpers' export function getComponentMetaInfo (options = {}, component) { return getComponentOption(options, component, defaultInfo) } /** * Returns the `opts.option` $option value of the given `opts.component`. * If methods are encountered, they will be bound to the component context. * If `opts.deep` is true, will recursively merge all child component * `opts.option` $option values into the returned result. * * @param {Object} opts - options * @param {Object} opts.component - Vue component to fetch option data from * @param {Boolean} opts.deep - look for data in child components as well? * @param {Function} opts.arrayMerge - how should arrays be merged? * @param {String} opts.keyName - the name of the option to look for * @param {Object} [result={}] - result so far * @return {Object} result - final aggregated result */ export function getComponentOption (options = {}, component, result = {}) { const { keyName } = options const { $options, $children } = component if (component._inactive) { return result } // only collect option data if it exists if ($options[keyName]) { let data = $options[keyName] // if option is a function, replace it with it's result if (isFunction(data)) { data = data.call(component) } // ignore data if its not an object, then we keep our previous result if (!isObject(data)) { return result } // merge with existing options result = merge(result, data, options) } // collect & aggregate child options if deep = true if ($children.length) { $children.forEach((childComponent) => { // check if the childComponent is in a branch // return otherwise so we dont walk all component branches unnecessarily if (!inMetaInfoBranch(childComponent)) { return } result = getComponentOption(options, childComponent, result) }) } return result }
JavaScript
0
@@ -1135,16 +1135,27 @@ const %7B + $metaInfo, $option @@ -1181,16 +1181,16 @@ mponent%0A - %0A if (c @@ -1312,165 +1312,291 @@ -let data = $options%5BkeyName%5D%0A%0A // if option is a function, replace it with it's result%0A if (isFunction(data)) %7B%0A data = data.call(component)%0A %7D +// if $metaInfo exists then %5BkeyName%5D was defined as a function%0A // and set to the computed prop $metaInfo in the mixin%0A // using the computed prop should be a small performance increase%0A // because Vue caches those internally%0A const data = $metaInfo %7C%7C $options%5BkeyName%5D %0A%0A
6465808cdac6ea592bcbba2b7816309b6d277c01
Insert role wildcard into beginning of role list
role_manager.js
role_manager.js
/** Role Manager Middleware @description Provides middleware that can be inserted into a router that serves as an access level gateway for deciding if a user can retrieve the given content. Must be run *after* the Verify Authtoken middleware so that the current user's role is set properly. @author tylerFowler **/ 'use strict'; const _ = require('underscore'); const AuthGWError = require('errors'); // character that represents 'All' roles const RoleWildcard = '*'; module.exports = exports = RoleManager; function RoleManager(roles) { this.roles = roles; } /** @name RoleManager#restrictTo @desc Middleware that restricts access to a route to the given role list Note that this must be run *after* the verify token middleware or any middleware that sets the 'userRole' key on the request object @param { String[]|String } allowedRoles @returns 401 Unauthorized if the user role key is not present @returns 403 Forbidden if the request's role isn't in the allowd roles list **/ RoleManager.prototype.restrictTo = function restrictTo(allowedRoles) { restrictToExpress.call(this, allowedRoles); }; let restrictToExpress = function restrictTo(allowedRoles) { return (req, res, next) => { if (!Array.isArray(allowedRoles)) allowedRoles = [allowedRoles]; if (_.contains(allowedRoles, RoleWildcard)) return next(); if (!req.userRole) return res.sendStatus(401); if (_.contains(allowedRoles, req.userRole)) return next(); res.sendStatus(403); }; }; /** RoleManager#getRolesFromMinimum @desc Gets the list of every role above & including the given min role Note that this assumes that the list of roles is lowest to highest priority @param { String } minRole => a value in the role list, case insensitive @returns { String[] } @throws InvalidRoleError if minRole is not a value in roles **/ RoleManager.prototype.getRolesFromMinimum = function getRolesFromMinimum(minRole) { if (!_.contains(this.roles, minRole)) throw new AuthGWError.InvalidRoleError(minRole); return _.chain(this.roles) .map(r => r.toLowerCase()) .last(roles.length - this.roles.findIndex(r => r === minRole.toLowerCase())) .value(); };
JavaScript
0.000001
@@ -571,26 +571,117 @@ %7B%0A -this.roles = +// be sure to add the wildcard to the beginning of the roles list%0A this.roles = _.union(RoleWildcard, roles +) ;%0A%7D%0A
b16c9776d4401d0a218a05a1f7ea281f7fadb711
Update typewriter.min.js
dist/typewriter.min.js
dist/typewriter.min.js
const TYPEWRITER_MODE_DEFAULT=0,TYPEWRITER_MODE_CORRECTION=1,TYPEWRITER_MODE_ARRAY=2;!function(){var t=function(o,s){function i(){h.cursor.classList.contains(h.options.cursor.no_blink_class)||h.cursor.classList.add(h.options.cursor.no_blink_class)}function e(){h.cursor.classList.contains(h.options.cursor.no_blink_class)&&h.cursor.classList.remove(h.options.cursor.no_blink_class)}function n(t,o){"number"==typeof t&&(o=t,t=void 0);var s=void 0!==t&&"function"==typeof t?t:u,i=void 0!==o&&"number"==typeof o?o:h.options.callback_delay;window.setTimeout(function(){void 0!==s&&"function"==typeof s&&(s(h),s==u&&(u=void 0))},1e3*i)}function r(t,o){if(t=void 0===t||"string"!=typeof t?"Invalid String":t,t.length>0){i();var s=document.createElement(h.options.letters.tag);s.classList.add(h.options.letters["class"]),s.innerHTML=" "==t[0]?"&nbsp;":t[0],s.addEventListener("animationend",function(){r(t.slice(1,t.length),o),this.removeEventListener("animationend",arguments.callee)}),h.parent.insertBefore(s,h.cursor)}else e(),n(o)}function c(){d instanceof Array&&(h.options.mode==TYPEWRITER_MODE_ARRAY||h.options.mode==TYPEWRITER_MODE_CORRECTION)&&(d.length>0?d[0]instanceof Array?a(d[0],function(){d=d.slice(1,d.length),d.length>=1?h.erase(function(){c()}):n()}):r(d[0],function(){d=d.slice(1,d.length),d.length>=1?h.erase(function(){c()}):n()}):n())}function a(t,o){void 0===t&&(t=d),t instanceof Array&&h.options.mode!=TYPEWRITER_MODE_DEFAULT&&(2!=t.length?r(void 0===t[0]?"I don't know what to type":t[0]):r(t[0],function(){for(var s=t[0].length<=t[1].length?t[0].length:t[1].length,i=s,e=0;s>e;e++)t[0][e]!=t[1][e]&&(i=e,e=s);l(i,function(){r(t[1].replace(t[0].slice(0,i),""),function(){n(o)})})}))}function l(t,o){h.parent.childNodes.length-1>t?h.backspace(function(){l(t,o)}):void 0!==o&&n(o)}function p(){switch(h.options.mode){case TYPEWRITER_MODE_DEFAULT:r(d);break;case TYPEWRITER_MODE_CORRECTION:a();break;case TYPEWRITER_MODE_ARRAY:c()}}if(this===HTMLElement)return new t(o,s);var h=this.parent=this;this.cursor=void 0,this.options=void 0;var d=void 0===o?"I have no clue what to type":o;"object"!=typeof o||o instanceof Array||void 0!==s||(s=o);var u=void 0;return this.setOptions=function(t){return this.options=void 0===t||"object"!=typeof t?{}:t,(void 0===this.options.mode||"number"!=typeof this.options.mode||this.options.mode>2||this.options.mode<0)&&(this.options.mode=TYPEWRITER_MODE_DEFAULT),this.options.mode!=TYPEWRITER_MODE_ARRAY&&this.options.mode!=TYPEWRITER_MODE_CORRECTION||d instanceof Array||(this.options.mode=TYPEWRITER_MODE_DEFAULT),this.options.mode==TYPEWRITER_MODE_DEFAULT&&d instanceof Array&&(0==d.length&&(d[0]="I have no clue what to type"),d=d[0]),void 0!==this.options.start_delay&&"number"==typeof this.options.start_delay||(this.options.start_delay=2),void 0!==this.options.callback_delay&&"number"==typeof this.options.callback_delay||(this.options.callback_delay=1),void 0!==this.options.letters&&"object"==typeof this.options.letters||(this.options.letters={}),void 0!==this.options.letters.tag&&"string"==typeof this.options.letters.tag||(this.options.letters.tag="span"),void 0!==this.options.letters["class"]&&"string"==typeof this.options.letters["class"]||(this.options.letters["class"]="typewriter-letter"),void 0!==this.options.letters.remove_class&&"string"==typeof this.options.letters.remove_class||(this.options.letters.remove_class="typewriter-letter-remove"),void 0!==this.options.cursor&&"object"==typeof this.options.cursor||(this.options.cursor={}),void 0!==this.options.cursor.tag&&"string"==typeof this.options.cursor.tag||(this.options.cursor.tag="span"),void 0!==this.options.cursor["class"]&&"string"==typeof this.options.cursor["class"]||(this.options.cursor["class"]="typewriter-cursor"),void 0!==this.options.cursor.no_blink_class&&"string"==typeof this.options.cursor.no_blink_class||(this.options.cursor.no_blink_class="typewriter-cursor-noblink"),void 0===this.cursor&&(this.cursor=document.createElement(this.options.cursor.tag),this.cursor.classList.add(this.options.cursor["class"]),this.parent.appendChild(this.cursor)),this},this.setContent=function(t){return d=void 0===t?d:t,d instanceof Array&&this.options.mode!=TYPEWRITER_MODE_ARRAY&&this.options.mode!=TYPEWRITER_MODE_CORRECTION&&(d=void 0==d[0]?"I have no clue what to type":d[0]),this},this.setCallback=function(t){return u=void 0===t||"function"!=typeof t?u:t,this},this.erase=function(t){this.parent.childNodes.length>1?(i(),this.backspace(function(){h.erase(t)})):(e(),void 0!==t&&"function"==typeof t&&n(t))},this.backspace=function(t){if(this.parent.childNodes.length>1){var o=this.parent.childNodes.length-2;this.parent.childNodes[o].classList.add(this.options.letters.remove_class),this.parent.childNodes[o].addEventListener("animationend",function(){h.parent.removeChild(h.parent.childNodes[o]),this.removeEventListener("animationend",arguments.callee),void 0!==t&&"function"==typeof t&&n(t,0)})}},this.start=function(t){void 0!==t&&this.setCallback(t),window.setTimeout(function(){p()},1e3*this.options.start_delay)},this.startNoDelay=function(t){void 0!==t&&this.setCallback(t),p()},this.setOptions(s),this};HTMLElement.prototype.typewriter||(HTMLElement.prototype.typewriter=t)}();
JavaScript
0.000001
@@ -78,16 +78,17 @@ ARRAY=2; + !functio @@ -5223,8 +5223,9 @@ r=t)%7D(); +%0A
0edc4b4706f71d43273812a1ed36f2f9b81958cf
update index.js
routes/index.js
routes/index.js
var os = require("os"); var npm = require("../npm"); var express = require("express"); var passport = require("passport"); var router = express.Router(); var config = require(hb.config); router.get("/", function (req, res, next) { if (req.user) { next(); } else { req.session.referer = "/"; res.redirect("/login"); } }, function (req, res, next) { npm.package("homebridge", function (err, server) { res.render("index", { controller: "index", title: "Status", user: req.user, server: server }); }); }); router.get("/status", function (req, res, next) { var mem = { total: parseFloat(((os.totalmem() / 1024) / 1024) / 1024).toFixed(2), used: parseFloat((((os.totalmem() - os.freemem()) / 1024) / 1024) / 1024).toFixed(2), free: parseFloat(((os.freemem() / 1024) / 1024) / 1024).toFixed(2) } var load = parseFloat((parseFloat(os.loadavg()) * 100) / os.cpus().length).toFixed(2); var uptime = { delta: Math.floor(os.uptime()) }; uptime.days = Math.floor(uptime.delta / 86400); uptime.delta -= uptime.days * 86400; uptime.hours = Math.floor(uptime.delta / 3600) % 24; uptime.delta -= uptime.hours * 3600; uptime.minutes = Math.floor(uptime.delta / 60) % 60; res.render("status", { layout: false, port: config.bridge.port, console_port: app.get("port"), uptime: uptime, cpu: load, mem: mem }); }); router.get("/pin", function (req, res, next) { if (req.user) { next(); } else { req.session.referer = "/"; res.redirect("/login"); } }, function (req, res, next) { res.setHeader("Content-type", "image/svg+xml"); res.render("pin", { layout: false, pin: config.bridge.pin }); }); router.get("/restart", function (req, res, next) { if (req.user) { next(); } else { req.session.referer = "/"; res.redirect("/login"); } }, function (req, res, next) { res.render("progress", { layout: false, message: "Restarting Server", redirect: "/" }); require("child_process").exec(hb.restart); }); router.get("/upgrade", function (req, res, next) { if (req.user) { next(); } else { req.session.referer = "/"; res.redirect("/login"); } }, function (req, res, next) { app.get("log")("Homebridge server upgraded."); res.render("progress", { layout: false, message: "Upgrading Server", redirect: "/" }); npm.update("homebridge", function (err, stdout, stderr) { require("child_process").exec(hb.restart); }); }); router.get("/logout", function (req, res, next) { if (req.user) { next(); } else { req.session.referer = "/"; res.redirect("/login"); } }, function (req, res) { app.get("log")(req.user.name + " logged out."); req.logout(); res.redirect("/"); }); router.get("/login", function (req, res) { res.render("login", { layout: false, controller: "login" }); }); router.post("/login", function (req, res) { passport.authenticate("local", function (err, user, info) { if (err) { return next(err); } if (!user) { app.get("log")("Failed login attempt."); return res.redirect("/login"); } req.logIn(user, function (err) { if (err) { return next(err); } var referer = req.session.referer ? req.session.referer : "/"; delete req.session.referer; app.get("log")(user.name + " successfully logged in."); return res.redirect(referer); }); })(req, res); }); module.exports = router;
JavaScript
0
@@ -1,12 +1,36 @@ +var fs = require(%22fs%22);%0A var os = req @@ -1108,16 +1108,149 @@ %7D;%0A%0A + var temp = fs.readFileSync(%22/sys/class/thermal/thermal_zone0/temp%22);%0A var cputemp = ((temp/1000).toPrecision(3)) + %22%C2%B0C%22;%0A %0A upti @@ -1672,16 +1672,42 @@ mem: mem +,%0A cputemp: cputemp %0A %7D);
1842488d16b230efc1a60de20d5bb26692f3b744
Update items.js
routes/items.js
routes/items.js
require('./db'); initDB(); var USE_FASTCACHE = false; var http = require('http'); //Create and populate or delete the database. exports.dbOptions = function(req, res) { var option = req.params.option.toLowerCase(); if(option === 'create'){ cloudant.db.create('items', function(err, body){ if(!err){ populateDB(); res.send({msg:'Successfully created database and populated!'}); } else{ res.send({msg:err}); } }); } else if(option === 'delete'){ cloudant.db.destroy('items',function(err, body){ if(!err){ res.send({msg:'Successfully deleted db items!'}); } else res.send({msg:'Error deleting db items: ' + err}); }); } else res.send({msg: 'your option was not understood. Please use "create" or "delete"'}); } //Create an item to add to the database. exports.create = function(req, res) { db.insert(req.body, function (err, body, headers) { if (!err) { res.send({msg: 'Successfully created item'}); } else { res.send({msg: 'Error on insert, maybe the item already exists: ' + err}); } }); } //find an item by ID. exports.find = function(req, res) { var id = req.params.id; if (USE_FASTCACHE) { var idAsNumber = parseInt(id.substring(id.length - 2), 16); if (!idAsNumber || idAsNumber % 3 === 2) { res.status(500).send({msg: 'server error'}); } else { res.status(200).send({msg: 'all good'}); } return; } db.get(id, { revs_info: false }, function(err, body) { if (!err){ res.send(body); } else{ res.send({msg:'Error: could not find item: ' + id}); } }); } //list all the database contents. exports.list = function(req, res) { db.list({include_docs: true}, function (err, body, headers) { if (!err) { res.send(body); return; } else res.send({msg:'Error listing items: ' + err}); }); } //update an item using an ID. exports.update = function(req, res) { var id = req.params.id; var data = req.body; db.get(id,{revs_info:true}, function (err, body) { if(!err){ data._rev = body._rev; db.insert(data, id, function(err, body, headers){ if(!err){ res.send({msg:'Successfully updated item: ' + JSON.stringify(data)}); } else res.send({msg:'Error inserting for update: ' + err}); }); } else res.send({msg:'Error getting item for update: ' + err}); }); } //remove an item from the database using an ID. exports.remove = function(req, res){ var id = req.params.id; db.get(id, { revs_info: true }, function(err, body) { if (!err){ //console.log('Deleting item: ' + id); db.destroy(id, body._rev, function(err, body){ if(!err){ res.send({msg:'Successfully deleted item'}); } else{ res.send({msg:'Error in delete: ' + err}); } }) } else{ res.send({msg:'Error getting item id: ' + err}); } }); } //calculate the fibonacci of 20. exports.fib = function(req, res) { res.send({msg:'Done with fibonacci of 20: ' + fib(20)}); } var fib = function(n) { if (n < 2) { return 1; } else { return (fib(n - 2) + fib(n - 1)); } } exports.loadTest = function(req, res) { // *************** (1 of 3) comment the next line to get the full loadTest function *********** // res.json({"success": 0, "fail": 0, "time": 0}); /* var testCount = req.query.count; testCount = testCount ? parseInt(testCount) : 100; var successCount = 0, failCount = 0; var startTime = Date.now(); var callback = function(response) { if (response.statusCode === 200) { successCount++; } else { failCount++; } if (successCount + failCount === testCount) { var endTime = Date.now(); res.json({"success": successCount, "fail": failCount, "time": endTime - startTime}); } }; var itemId1 = "1f9e7891bffb03605e3a9b43f996f6ea"; var itemId2 = "9dce21273d13dc1dcb1b47370359e753"; for (var i = 0; i < testCount; i++) { http.get({ host: req.get('host'), path: "/items/" + (i % 2 ? itemId1 : itemId2) }, callback); } // *************** (2 of 3) comment the next line to get the full loadTest function *********** //*/ // *************** (3 of 3) change USE_FASTCACHE up at the top to 'true' to enable enhanced lookup *********** };
JavaScript
0.000001
@@ -41,20 +41,19 @@ CACHE = -fals +tru e;%0A%0Avar
c6a7e41db561490cbb630da0de378515ffdfa57a
Fix login redirect
routes/login.js
routes/login.js
var bcrypt = require('bcrypt'); var LocalStrategy = require('passport-local').Strategy; var passport = require('passport'); var request = require('request'); var LOGIN_URL = process.env.LANDLINE_API + '/teams'; var SALT = process.env.SALT; passport.use(new LocalStrategy({ usernameField: 'name', passwordField: 'password' }, function(name, password, done) { if (!name || !password) { return done(new Error('All fields are required')); } var _password = bcrypt.hashSync(password, SALT); var _body = { name: name, password: _password }; request.post({ url: LOGIN_URL + '/' + name, json: true, body: _body }, function(err, response, body) { if (err) { return done(err); } done(null, response.body); }); } )); passport.serializeUser(function(team, done) { done(null, team); }); passport.deserializeUser(function(team, done) { request.get({ url: LOGIN_URL + '/' + team.name, json: true, auth: { bearer: team.token } }, function(err, response, body) { if (err) { return done(err); } done(null, response.body); }); }); module.exports = function(router) { router.get('/login', function(req, res) { res.render('login', { title: 'Landline | Login' }); }); router.post('/login', passport.authenticate('local', { successRedirect: '/settings', failureRedirect: '/login', failureFlash: true })); };
JavaScript
0.000001
@@ -1397,16 +1397,8 @@ : '/ -settings ',%0A
e337559be3ffda38f22bec6b066dd2a8014d9bd9
Add error handling
routes/media.js
routes/media.js
module.exports = function(router) { 'use strict'; var Media = require('../models/Media'); router.route('/media') // get all the media (accessed at GET http://localhost:port/api/media) .get(function(req, res) { Media.find(function(err, models) { if (err) res.send(err); res.json(models); }); }) // create a media (accessed at POST http://localhost:port/api/media) .post(function(req, res) { // create a new instance of the Media model var model = new Media(); // set the media attributes model.name = req.body.name; model.description = req.body.description; model.active = req.body.active; // save the media and check for errors model.save(function(err) { if (err) { res.send(err); return; } res.json({ message: 'Media created!' }); }); }); router.route('/media/:media_id') // get the media with that id (accessed at GET http://localhost:port/api/media/:media_id) .get(function(req, res) { Media.findById(req.params.media_id, function(err, model) { if (err) { res.send(err); return; } if (!model) { res.sendStatus(404); return; } res.json(model); }); }) // update the media with this id (accessed at PUT http://localhost:port/api/media/:media_id) .put(function(req, res) { // use our media model to find the media we want Media.findById(req.params.media_id, function(err, model) { if (err) { res.send(err); return; } if (!model) { res.sendStatus(404); return; } // update the media info model.name = req.body.name; model.description = req.body.description; model.active = req.body.active; // save the model model.save(function(err) { if (err) { res.send(err); return; } res.json({ message: 'Media updated!' }); }); }); }) // delete the media with this id (accessed at DELETE http://localhost:port/api/media/:media_id) .delete(function(req, res) { Media.remove({ _id: req.params.media_id }, function(err, model) { if (err) { res.send(err); return; } res.json({ message: 'Successfully deleted' }); }); }); };
JavaScript
0.000002
@@ -255,24 +255,25 @@ , models) %7B%0A +%0A if ( @@ -276,16 +276,18 @@ if (err) + %7B %0A @@ -296,32 +296,61 @@ res.send(err);%0A + return;%0A %7D%0A%0A res.json
c4f3f03cc6f50301b3f1f78d73745c6e26a1e90d
Add route for creating piles
routes/piles.js
routes/piles.js
var express = require('express'); var pg = require('pg'); var router = express.Router(); var conString = "postgres://localhost:5432/freestr"; /* GET piles listing. */ router.get('/', function(req, res, next) { var results = []; pg.connect(conString, function(err, client, done) { if (err) { done(); console.log(err); } var query = client.query('SELECT * FROM piles'); query.on('row', function(row) { results.push(row); }); query.on('end', function() { done(); return res.json(results); }); }); }); module.exports = router;
JavaScript
0
@@ -558,16 +558,656 @@ );%0A%7D);%0A%0A +router.post('/', function(req, res, next) %7B%0A var results = %5B%5D;%0A var data = %7Bname: req.body.name, location: req.body.location, items: req.body.number_of_items%7D;%0A%0A pg.connect(conString, function(err, client, done) %7B%0A if (err) %7B%0A done();%0A console.log(err);%0A %7D%0A var query = client.query('INSERT INTO piles (name, location, number_of_items) VALUES ($1, $2, $3)', %5Bdata.name, data.location, data.items%5D);%0A%0A var query = client.query('SELECT * FROM piles');%0A query.on('row', function(row) %7B%0A results.push(row);%0A %7D);%0A query.on('end', function() %7B%0A done();%0A return res.json(results);%0A %7D);%0A %7D);%0A%7D); %0A%0Amodule
ba95af42e7877e1c2bd563b0bed83a07a35ae536
fix stats for references
routes/stats.js
routes/stats.js
var express = require("express"), // bodyParser = require("body-parser"), async = require("async"), error = require("../middlewares/error.js"), Template = require("../models/templates.js"), Reference = require("../models/references"), Verify = require("./verify"), router = express.Router(); router.route("/") .get(Verify.verifyOrdinaryUser, function(req, res, next) { async.parallel({ "tag": function(callback) { Template.aggregate([{ $unwind: "$tags" }, { $group: { _id: "$tags", count: { $sum: 1 } } }], function(err, results) { console.log(results); callback(null, results); }); }, "reference": function(callback) { Template.aggregate([{ $unwind: "$reference" }, { $group: { _id: "$reference", count: { $sum: 1 } } }], function(err, results) { console.log(results); Reference.populate(results, { path: "_id" }, function(err, reference) { console.log(reference); callback(null, reference); }) }); }, "createdBy": function(callback) { Template.aggregate([{ $group: { _id: "$createdBy", count: { $sum: 1 } } }], function(err, results) { console.log(results); callback(null, results); }); } }, function(err, results) { console.log(results); res.json(results); } ); }); module.exports = router;
JavaScript
0
@@ -754,16 +754,17 @@ eference +s %22 %7D, %7B $ @@ -788,16 +788,17 @@ eference +s %22, count @@ -892,173 +892,32 @@ -Reference.populate(results, %7B path: %22_id%22 %7D, function(err, reference) %7B%0A console.log(reference);%0A callback(null, reference);%0A %7D) +callback(null, results); %0A
b425679f4c406b18dd191360e95fafa8d29d2f33
add some comment
routes/token.js
routes/token.js
var express = require('express'); var request = require('request'); var sign=require('../libs/sign');//微信提供的签名方法 var config=require('../libs/config.json');//配置文件 var router = express.Router(); /* 最简单的获取签名信息 */ router.get('/', function(req, res) { request('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='+config.appId+'&secret='+config.appSecret, function (error, response, body) { console.log('根据appId和appSecret获取accessToken ..'); if(error || response.statusCode != 200){ res.send(error); return; } var access_token=JSON.parse(body).access_token; console.log('access_token: '+access_token); request('https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='+access_token+'&type=jsapi', function (error, response, body) { console.log('根据accessToken获取..'); if (error || response.statusCode != 200) { res.send(error); return; } var ticket=JSON.parse(body).ticket; console.log('ticket: '+ticket); var result=sign(ticket,config.url); res.send(result); }); }); }); router.get('/client', function(req, res) { request('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='+config.appId+'&secret='+config.appSecret, function (error, response, body) { console.log('根据appId和appSecret获取accessToken ..'); if(error || response.statusCode != 200){ res.send(error); return; } var access_token=JSON.parse(body).access_token; console.log('access_token: '+access_token); request('https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='+access_token+'&type=jsapi', function (error, response, body) { console.log('根据accessToken获取..'); if (error || response.statusCode != 200) { res.send(error); return; } var ticket=JSON.parse(body).ticket; console.log('ticket: '+ticket); var result=sign(ticket,config.url); //这之前,都和上面的「router.get('/', function(req, res) {..」是一样的。 res.render('client',{config:config, result:result}); }); }); }); module.exports = router;
JavaScript
0
@@ -1057,16 +1057,58 @@ %0A%7D);%0A%0A +/* %E6%AD%A3%E5%BC%8F%E7%9A%84%E6%BC%94%E7%A4%BA%E4%BB%A3%E7%A0%81%EF%BC%8C%E5%8C%85%E6%8B%AC%E6%9C%8D%E5%8A%A1%E5%99%A8%E7%AB%AF%E7%94%9F%E6%88%90%E7%AD%BE%E5%90%8D%EF%BC%8C%E5%AE%A2%E6%88%B7%E7%AB%AF%E9%80%9A%E8%BF%87%E7%AD%BE%E5%90%8D%E4%BD%BF%E7%94%A8%E5%BE%AE%E4%BF%A1API%E6%96%B9%E6%B3%95 */%0A router.g
602dad4711044999a45e53b6b04d2b5e63c872e5
Refactor trace controller
routes/trace.js
routes/trace.js
const express = require('express'); const validator = require('validator'); const HttpStatus = require('http-status-codes'); const router = express.Router(); const Executor = require('../models/executor'); const Ip2Location = require('../models/ip2location'); const Terminator = require('../models/terminator'); router.post('/', (req, res, next) => { console.log(`trace domain name ${req.body.domainName} received`); if (!validator.isFQDN(req.body.domainName) && !validator.isIP(req.body.domainName)) { console.log(`trace not a valid domain name or ip received, returning http ${HttpStatus.BAD_REQUEST}`); res.sendStatus(HttpStatus.BAD_REQUEST); return; } if (req.session.pid !== undefined) { Terminator.terminate(req.session.pid); } let socketNamespace = null; let isSocketConnected = false; const executor = new Executor(new Ip2Location()); executor .on('pid', (pid) => { req.session.pid = pid; if (pid !== undefined) { socketNamespace = req.app.io.of('/' + pid); socketNamespace.on('connection', (socket) => { console.log(`a user from ${socket.conn.remoteAddress} connected`); isSocketConnected = true; socket.on('disconnect', () => { console.log(`a user from ${socket.conn.remoteAddress} disconnected`); Terminator.terminate(pid); }); }); console.log(`trace process with id ${pid} created, returning http ${HttpStatus.OK}`); res.status(HttpStatus.OK).send({ pid: pid }); } else { console.log(`trace process not created, returning http ${HttpStatus.INTERNAL_SERVER_ERROR}`); res.sendStatus(HttpStatus.INTERNAL_SERVER_ERROR); } }) .on('destination', (destination) => { if (!isSocketConnected) { Terminator.terminate(req.session.pid); return; } socketNamespace.emit('destination', destination); }) .on('data', (data) => { socketNamespace.emit('data', data); }) .on('done', (code) => { socketNamespace.emit('done'); }); executor.start(req.body.domainName); }); module.exports = router;
JavaScript
0
@@ -853,16 +853,77 @@ false;%0A + const dataQueue = %5B%5D;%0A let destinationHolder = null;%0A%0A cons @@ -2046,33 +2046,40 @@ -if (!isSocketConnected) %7B +destinationHolder = destination; %0A @@ -2079,32 +2079,35 @@ on;%0A +%7D)%0A Terminator.t @@ -2098,70 +2098,146 @@ -Terminator.terminate(req.session.pid);%0A return; +.on('data', (data) =%3E %7B%0A dataQueue.push(data);%0A%0A if (isSocketConnected) %7B%0A while (dataQueue.length) %7B %0A @@ -2241,23 +2241,16 @@ - %7D%0A%0A @@ -2280,34 +2280,65 @@ t('d -estination', destination); +ata', dataQueue.shift());%0A %7D%0A %7D %0A @@ -2355,35 +2355,35 @@ .on('d -ata +one ', ( -data +code ) =%3E %7B%0A @@ -2416,63 +2416,40 @@ t('d -ata', data);%0A %7D)%0A .on('done', (code) =%3E %7B +estination', destinationHolder); %0A
e27262ea0f97c1858b8bd050869eb904df0fb4c4
remove link
routes/users.js
routes/users.js
var express = require('express'); var router = express.Router(); /* GET users listing. */ router.get('/', function(req, res, next) { res.send('respond with a resource', res.send({a:1, b:2, c:3}), res.send(<A HREF= "index.js"> index </A>); }); module.exports = router;
JavaScript
0.000001
@@ -194,51 +194,8 @@ :3%7D) -, res.send(%3CA HREF= %22index.js%22%3E index %3C/A%3E) ;%0A%7D)
43cb8fcdd7661b34dceef7de360e2d962aedad9b
order trips by start date
routes/users.js
routes/users.js
"use strict"; const express = require('express'); const router = express.Router(); module.exports = (knex) => { router.get("/:user_id", (req, res) => { let u_id = req.params.user_id knex .select("*") .from("users") .where('id', u_id) .then((results) => { res.json(results); }); }); //get all trips from a user router.get("/:user_id/trips", (req, res) => { let u_id = req.params.user_id knex .select("*") .from("trips") .where('user_id', u_id) .then((results) => { res.json(results); }); }); router.get("/:user_id/trips/:trip_id/days", (req, res) => { let u_id = req.params.user_id let t_id = req.params.trip_id knex .select('days.id', 'date', 'day_start_location', 'day_end_location', 'day_img_url') .from('days') .join('trips', 'trips.id', '=', 'days.trip_id') .join('users', 'users.id', '=', 'trips.user_id') .where('user_id', u_id) .andWhere('trip_id', t_id) .then((results) => { res.json(results); }); }); router.get("/:user_id/trips/:trip_id/events", (req, res) => { let u_id = req.params.user_id let t_id = req.params.trip_id let d_id = req.params.day_id knex .select('day_id','events.id','event_type', 'start_time', 'end_time', 'event_description') .from('events') .join('days', 'days.id', '=', 'events.day_id') .join('trips', 'trips.id', '=', 'days.trip_id') .join('users', 'users.id', '=', 'trips.user_id') .where('user_id', u_id) .andWhere('trip_id', t_id) .then((results) => { res.json(results); }); }); router.post("/:user_id/trips/new", (req, res) => { console.log('inserting trip into database: ', req.body) knex('trips') .returning('id') .insert({ user_id: req.params.user_id, trip_start: req.body.trip_start, trip_end: req.body.trip_end, trip_title: req.body.trip_title, trip_start_location: req.body.trip_start_location, trip_destination: req.body.trip_destination }) .then((tripId) => { console.log(tripId) knex('days') .returning('id') .insert({ trip_id: tripId[0], date: '11/01/2016', day_start_location: 'toronto' }) .then(() => { res.json(tripId) }); }); }); router.post("/:user_id/trips/:trip_id/days/new", (req, res) => { knex('days') .insert({ trip_id: req.params.trip_id, date: req.body.date, day_start_location: req.body.day_start_location, day_end_location: req.body.day_end_location, day_img_url: req.body.day_img_url }) .then((results) => { res.json(results) }) }); return router; }
JavaScript
0.000001
@@ -509,32 +509,69 @@ user_id', u_id)%0A + .orderBy('trip_start', 'desc')%0A .then((res
f56d6938219e274d86e826a8852d4d661bf082a9
add new rules
rules/import.js
rules/import.js
'use strict' module.exports = { plugins: [ 'import' ], settings: { 'import/resolver': { node: { extensions: [ '.js', '.json' ], }, }, 'import/extensions': [ '.js', '.json' ], 'import/core-modules': [], 'import/ignore': [ 'node_modules', '\\.(coffee|scss|css|less|hbs|svg|json)$', ], }, rules: { 'import/default': 'off', 'import/export': 'error', 'import/exports-last': 'error', 'import/extensions': 'off', 'import/first': 'off', 'import/group-exports': 'off', 'import/max-dependencies': 'off', 'import/named': 'error', 'import/namespace': [ 'error', { allowComputed: true, } ], 'import/newline-after-import': [ 'error', { count: 1, } ], 'import/no-absolute-path': 'error', 'import/no-amd': 'off', 'import/no-anonymous-default-export': 'error', 'import/no-commonjs': 'off', 'import/no-default-export': 'off', 'import/no-deprecated': 'off', 'import/no-duplicates': 'off', 'import/no-dynamic-require': 'off', 'import/no-extraneous-dependencies': [ 'error', { devDependencies: true, optionalDependencies: true, peerDependencies: false, } ], 'import/no-internal-modules': 'off', 'import/no-mutable-exports': 'error', 'import/no-named-as-default-member': 'off', 'import/no-named-as-default': 'error', 'import/no-named-default': 'error', 'import/no-namespace': 'off', 'import/no-nodejs-modules': 'off', 'import/no-restricted-paths': 'off', 'import/no-self-import': 'error', 'import/no-unassigned-import': 'off', 'import/no-unresolved': [ 'error', { commonjs: true, caseSensitive: true, } ], 'import/no-useless-path-segments': 'error', 'import/no-webpack-loader-syntax': 'off', 'import/order': 'error', 'import/prefer-default-export': 'error', 'import/unambiguous': 'off', }, }
JavaScript
0.000001
@@ -899,32 +899,62 @@ mmonjs': 'off',%0A + 'import/no-cycle': 'off',%0A 'import/no-d
0f6e38848f114ffe85e59a3c472c22c40faadd95
Add example configs for projects with mkdir -p dirs and projects with repo paths
sampleConfig.js
sampleConfig.js
var global = { host: 'http://subdomain.yourdomain.com', port: 8461, secretUrlSuffix: 'putSomeAlphanumericSecretCharsHere' }; var projects = [ { repo: { owner: 'yourbitbucketusername', slug: 'your-bitbucket-private-repo-name', url: 'git@bitbucket.org:yourbitbucketusername/your-bitbucket-private-repo-name.git', privateKey: '/home/youruser/.ssh/id_rsa' }, dest: { host: 'yourstaticwebhost.com', username: 'yourusername', password: 'yourpassword', path: '/home/youruser/html_dest/' } }, { repo: { owner: 'yourbitbucketusername', slug: 'your-bitbucket-public-repo-name', url: 'git@bitbucket.org:yourbitbucketusername/your-bitbucket-public-repo-name.git', }, dest: { host: 'yourstaticwebhost.com', username: 'yourusername', password: 'yourpassword', path: '/home/youruser/html_dest/' } } ]; var winstonOptions = { colorize: true, level: 'info', timestamp: true }; module.exports = { global: global, projects: projects, winstonOptions: winstonOptions };
JavaScript
0
@@ -884,36 +884,491 @@ '/home/youruser/ -html +some_other/directory/that_may/not_exist_yet/'%0A %7D%0A %7D,%0A %7B%0A repo: %7B%0A owner: 'yourbitbucketusername',%0A slug: 'your-bitbucket-repo-with-subdir',%0A url: 'git@bitbucket.org:yourbitbucketusername/your-bitbucket-repo-with-subdir.git',%0A path: '/your-repo-subdir'%0A %7D,%0A dest: %7B%0A host: 'yourstaticwebhost.com',%0A username: 'yourusername',%0A privateKey: '/home/youruser/.ssh/another_id_rsa',%0A path: '/home/youruser/another _dest/'%0A %7D%0A
8359ba4cfe38402999f21770e37045cedd5c5341
Change the background color for incident
packages/frontend/src/routes/Incidents/containers/IncidentsContainer.js
packages/frontend/src/routes/Incidents/containers/IncidentsContainer.js
import React, { PropTypes } from 'react' import ReactDOM from 'react-dom' import { connect } from 'react-redux' import { fetchIncidents, postIncident, updateIncident, deleteIncident } from '../modules/incidents' // import IncidentDialog from 'components/IncidentDialog' import IncidentDialog from 'components/ComponentDialog' import FoolproofDialog from 'components/FoolproofDialog' import Button from 'components/Button' import classnames from 'classnames' import classes from './IncidentsContainer.scss' const dialogType = { none: 0, add: 1, update: 2, delete: 3 } class Incidents extends React.Component { constructor () { super() this.state = { dialogType: dialogType.none, incident: null } this.handleShowDialog = this.handleShowDialog.bind(this) this.handleHideDialog = this.handleHideDialog.bind(this) this.handleAdd = this.handleAdd.bind(this) this.handleUpdate = this.handleUpdate.bind(this) this.handleDelete = this.handleDelete.bind(this) this.renderListItem = this.renderListItem.bind(this) this.renderDialog = this.renderDialog.bind(this) } componentDidMount () { this.props.dispatch(fetchIncidents) } componentDidUpdate () { let dialog = ReactDOM.findDOMNode(this.refs.incidentDialog) || ReactDOM.findDOMNode(this.refs.foolproofDialog) if (dialog) { if (!dialog.showModal) { dialogPolyfill.registerDialog(dialog) } try { dialog.showModal() // workaround https://github.com/GoogleChrome/dialog-polyfill/issues/105 let overlay = document.querySelector('._dialog_overlay') if (overlay) { overlay.style = null } } catch (ex) { console.warn('Failed to show dialog (the dialog may be already shown)') } } } handleShowDialog (type, incident) { this.setState({ incident: incident, dialogType: type }) } handleHideDialog (refs) { let dialog = ReactDOM.findDOMNode(refs) dialog.close() this.setState({ incident: null, dialogType: dialogType.none }) } handleAdd (id, name, message, impact, componentIDs, status) { this.props.dispatch(postIncident(id, name, message, impact, componentIDs, status)) this.handleHideDialog(this.refs.incidentDialog) } handleUpdate (id, name, message, impact, componentIDs, status) { this.props.dispatch(updateIncident(id, name, message, impact, componentIDs, status)) this.handleHideDialog(this.refs.incidentDialog) } handleDelete (id) { this.props.dispatch(deleteIncident(id)) this.handleHideDialog(this.refs.foolproofDialog) } renderListItem (incident) { let statusColor = '#388e3c' return ( <li key={incident.id} className='mdl-list__item mdl-list__item--two-line mdl-shadow--2dp'> <span className='mdl-list__item-primary-content'> <i className={classnames(classes.icon, 'material-icons', 'mdl-list__item-avatar')} style={{color: statusColor}}>check_circle</i> <span>{incident.name}</span> <span className='mdl-list__item-sub-title'>updated at {incident.updated_at}</span> </span> <span className='mdl-list__item-secondary-content'> <div className='mdl-grid'> <div className='mdl-cell mdl-cell--6-col'> <Button plain name='Edit' onClick={() => this.handleShowDialog(dialogType.edit, incident)} /> </div> <div className='mdl-cell mdl-cell--6-col'> <Button plain name='Delete' onClick={() => this.handleShowDialog(dialogType.delete, incident)} /> </div> </div> </span> </li> ) } renderDialog () { let dialog switch (this.state.dialogType) { case dialogType.none: dialog = null break case dialogType.add: let incident = { id: '', name: '', impact: '', updated_at: '' } dialog = <IncidentDialog ref='incidentDialog' onCompleted={this.handleAdd} onCanceled={() => { this.handleHideDialog(this.refs.incidentDialog) }} incident={incident} actionName='Add' /> break case dialogType.update: dialog = <IncidentDialog ref='incidentDialog' onCompleted={this.handleUpdate} onCanceled={() => { this.handleHideDialog(this.refs.incidentDialog) }} incident={this.state.incident} actionName='Update' /> break case dialogType.delete: dialog = <FoolproofDialog ref='foolproofDialog' onCompleted={this.handleDelete} onCanceled={() => { this.handleHideDialog(this.refs.foolproofDialog) }} incident={this.state.incident} /> break default: console.warn('unknown dialog type: ', this.state.dialogType) } return dialog } render () { const { incidents, isFetching } = this.props const incidentItems = incidents.map(this.renderListItem) const dialog = this.renderDialog() const textInButton = (<div> <i className='material-icons'>add</i> Incident </div>) return (<div className={classnames(classes.layout, 'mdl-grid')} style={{ opacity: isFetching ? 0.5 : 1 }}> <div className='mdl-cell mdl-cell--9-col mdl-cell--middle'> <h4>Incidents</h4> </div> <div className={classnames(classes.showDialogButton, 'mdl-cell mdl-cell--3-col mdl-cell--middle')}> <Button onClick={() => this.handleShowDialog(dialogType.add)} name={textInButton} class='mdl-button--accent' /> </div> <ul className='mdl-cell mdl-cell--12-col mdl-list'> {incidentItems} </ul> {dialog} </div>) } } Incidents.propTypes = { incidents: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.string.isRequired, name: PropTypes.string.isRequired, impact: PropTypes.string.isRequired, updated_at: PropTypes.string.isRequired }).isRequired).isRequired, isFetching: PropTypes.bool.isRequired, dispatch: PropTypes.func.isRequired } const mapStateToProps = (state) => { return { isFetching: state.incidents.isFetching, incidents: state.incidents.incidents } } export default connect(mapStateToProps)(Incidents)
JavaScript
0.000011
@@ -2656,16 +2656,44 @@ 388e3c'%0A + let bgColor = '#ffffff'%0A retu @@ -2965,16 +2965,17 @@ style=%7B%7B + color: s @@ -2984,16 +2984,46 @@ tusColor +, 'background-color': bgColor %7D%7D%3Echeck
1a6b43fe45e58b38bc01518541b272df6300dc1a
Add console.log feedback to migration, fix a bug
packages/lesswrong/server/migrations/2019-05-01-migrateSubscriptions.js
packages/lesswrong/server/migrations/2019-05-01-migrateSubscriptions.js
import { newMutation } from 'meteor/vulcan:core'; import { registerMigration } from './migrationUtils'; import { forEachDocumentBatchInCollection } from '../queryUtil'; import Users from 'meteor/vulcan:users'; import { Comments } from '../../lib/collections/comments/collection.js'; import { Posts } from '../../lib/collections/posts/collection.js'; import { Subscriptions } from '../../lib/collections/subscriptions/collection.js'; registerMigration({ name: "migrateSubscriptions", idempotent: true, action: async () => { forEachDocumentBatchInCollection({ collection: Users, batchSize: 1000, callback: async (users) => { for (let user of users) { const oldSubscriptions = user.subscribedItems; const newSubscriptions = []; // Fetch subscribed posts and comments. A user's subscription to // their own post/comment doesn't count and is removed; a subscription // to someone else's post/comment is migrated to the Subscriptions // table. if (oldSubscriptions?.Comments) { const commentIDs = _.map(oldSubscriptions.Comments, s=>s.itemId); const comments = await Comments.find({_id: {$in: commentIDs}}).fetch(); for (let comment of comments) { if (comment.userId !== user._id) { newSubscriptions.push({ userId: user._id, state: "subscribed", documentId: comment._id, collectionName: "Comments", type: "newReplies", }); } } } if (oldSubscriptions?.Posts) { const postIDs = _.map(oldSubscriptions.Posts, s=>s.itemId); const posts = await Posts.find({_id: {$in: postIDs}}).fetch(); for (let post of posts) { if (post.userId !== user._id) { newSubscriptions.push({ userId: user._id, state: "subscribed", documentId: post._id, collectionName: "Posts", type: "newComments", }); } } } // Migrate subscriptions to groups if (oldSubscriptions?.Localgroups) { for (let group of oldSubscriptions.Localgroups) { newSubscriptions.push({ userId: user._id, state: "subscribed", documentId: group._id, collectionName: "Localgroups", type: "newEvents", }); } } // Migrate subscriptions to other users if (oldSubscriptions?.Users) { for (let userSubscribedTo of oldSubscriptions.Users) { newSubscriptions.push({ userId: user._id, state: "subscribed", documentId: userSubscribedTo._id, collectionName: "Users", type: "newPosts", }); } } // Save the resulting subscriptions in the Subscriptions table if (newSubscriptions.length > 0) { Promise.all(_.map(newSubscriptions, async sub => { await newMutation({ collection: Subscriptions, document: sub, context: { currentUser: user }, validate: false }); })); } // Remove subscribedItems from the user if (oldSubscriptions) { await Users.update( { _id: user._id }, { $unset: { subscribedItems: 1 } } ); } } } }); }, });
JavaScript
0
@@ -527,16 +527,202 @@ %3E %7B%0A +let numCommentSubscriptions = 0;%0A let numPostSubscriptions = 0;%0A let numGroupSubscriptions = 0;%0A let numUserSubscriptions = 0;%0A let numTotalSubscriptions = 0;%0A %0A await forEachD @@ -744,24 +744,24 @@ ollection(%7B%0A - collec @@ -1778,32 +1778,75 @@ %7D);%0A + numCommentSubscriptions++;%0A %7D%0A @@ -2392,32 +2392,72 @@ %7D);%0A + numPostSubscriptions++;%0A %7D%0A @@ -2887,32 +2887,71 @@ %7D);%0A + numGroupSubscriptions++;%0A %7D%0A @@ -3373,32 +3373,70 @@ %7D);%0A + numUserSubscriptions++;%0A %7D%0A @@ -3570,24 +3570,86 @@ ngth %3E 0) %7B%0A + numTotalSubscriptions += newSubscriptions.length;%0A @@ -3811,37 +3811,8 @@ ub,%0A - context: %7B%0A @@ -3840,34 +3840,16 @@ er: user -%0A %7D ,%0A @@ -3873,16 +3873,17 @@ e: false +, %0A @@ -4180,32 +4180,32 @@ );%0A %7D%0A - %7D%0A @@ -4194,24 +4194,377 @@ %7D%0A %7D%0A + %0A // eslint-disable-next-line no-console%0A console.log(%60Migrated batch of $%7Busers.length%7D users. Cumulative updates: $%7BnumCommentSubscriptions%7D comment subscriptions, $%7BnumPostSubscriptions%7D post subscriptions, $%7BnumGroupSubscriptions%7D group subscriptions, $%7BnumUserSubscriptions%7D user subscriptions ($%7BnumTotalSubscriptions%7D total)%60);%0A %7D%0A
bd6222916f34f96f16167ecfca900ad50ccf4c14
fix bug in default badge, require type
js/collections/VerifiedMods.js
js/collections/VerifiedMods.js
import _ from 'underscore'; import { Collection } from 'backbone'; import app from '../app'; import Mod from '../models/VerifiedMod'; export default class extends Collection { constructor(...args) { super(...args); this.data = {}; } model(attrs, options) { return new Mod(attrs, options); } modelId(attrs) { return attrs.peerID; } url() { return app.localSettings.get('verifiedModsProvider'); } get data() { return this._data; } set data(data) { this._data = data; } /** * Return a list of verified moderators that match the ids passed in * @param IDs {array} - a list of IDs */ matched(IDs) { return this.filter(mod => IDs.includes(mod.get('peerID'))); } /** * Return a badge to use to represent the verified moderators available on a listing. * @param IDs {array} - a list of IDs */ defaultBadge(IDs) { const modelWithBadge = _.find(this.matched(IDs), mod => mod.get('type').badge); return modelWithBadge.get('type').badge; } parse(response) { this.data = response.data || {}; this.data.url = this.url(); // backup for templates if the link is missing const parsedResponse = response.moderators ? response.moderators : []; /* Embed the type in each moderator so it's easier to use elsewhere. It should look like: peerID: string, type: { name: string, description: string, badge: url string, } */ parsedResponse.forEach((mod) => { mod.type = {}; if (response.types && response.types.length && mod.type) { mod.type = _.findWhere(response.types, { name: mod.type }) || {}; } mod.type.badge = mod.type.badge || '../imgs/verifiedModeratorBadge.png'; }); return parsedResponse; } }
JavaScript
0
@@ -822,16 +822,75 @@ isting.%0A + * If none of the moderators are verified, return false.%0A * @pa @@ -1043,16 +1043,36 @@ return + !!modelWithBadge && modelWi @@ -1119,24 +1119,736 @@ response) %7B%0A + /* The data is expected to be delivered in the following format. There must be at least one%0A type with a badge, or the grey loading badge will be shown instead.%0A %7B%0A data: %7B%0A name: 'name of provider (required)',%0A description: 'description of the provider (optional)',%0A link: 'url to the provider (required)'%0A %7D,%0A types: %5B%0A %7B%0A name: 'standard (required)',%0A description: 'description of this type of moderator (optional)',%0A badge: 'url to the badge image'%0A %7D%0A %5D,%0A moderators: %5B%0A %7B%0A peerID: 'QmVFNEj1rv2d3ZqSwhQZW2KT4zsext4cAMsTZRt5dAQqFJ',%0A type: 'standard'%0A %7D%0A %5D%0A %7D%0A */%0A this.dat @@ -2253,24 +2253,108 @@ %0A %7D%0A + If the type is missing, the grey default badge will be show in the template.%0A */%0A @@ -2391,29 +2391,8 @@ %3E %7B%0A - mod.type = %7B%7D;%0A @@ -2538,87 +2538,8 @@ %7D%0A - mod.type.badge = mod.type.badge %7C%7C '../imgs/verifiedModeratorBadge.png';%0A
9f63c25d545a1448411ee53c67f1fc7f2b9c9bbb
Update single.js test
other/single.js
other/single.js
// this is just for speical testing of single object var jsroot = require("jsroot"); var fs = require("fs"); var filename = "http://jsroot.gsi.de/files/histpainter6.root", itemname = "draw_contlst1"; function MakeTest(file, item, callback) { file.ReadObject(item).then(obj => { jsroot.MakeSVG( { object: obj, width: 1200, height: 800 }, function(svg) { fs.writeFileSync(item + ".svg", svg); console.log('create ' + item + '.svg file size = ' + svg.length); if (callback) callback(); }); }); } jsroot.OpenFile(filename).then(file => { /* MakeTest(file,"draw_hstack", function() { MakeTest(file,"draw_nostackb", function() { MakeTest(file,"draw_hstack", function() { }); }); }); return; */ file.ReadObject(itemname).then(obj => { // var subpad = obj.fPrimitives.arr[2]; // var subpad = obj; jsroot.MakeSVG( { object: obj, width: 1200, height: 800 }, function(svg) { fs.writeFileSync("single.svg", svg); console.log('create single.svg file size', svg.length); }); }); });
JavaScript
0.000001
@@ -45,17 +45,16 @@ e object - %0A%0Avar js @@ -214,64 +214,105 @@ ion -MakeTest(file, item, callback) %7B%0A file.ReadObject(item +TestEve() %7B%0A jsroot.HttpRequest(%22http://jsroot.gsi.de/files/geom/evegeoshape.json.gz%22, %22object%22 ).th @@ -336,33 +336,32 @@ jsroot.MakeSVG( - %7B object: obj, w @@ -381,39 +381,37 @@ eight: 800 %7D -, functio +).the n(svg -) + =%3E %7B%0A @@ -431,16 +431,12 @@ ync( -item + %22 +%22eve .svg @@ -477,20 +477,11 @@ ate -' + item + ' +eve .svg @@ -494,14 +494,10 @@ size - = ' + +', svg @@ -516,57 +516,48 @@ - if (callback) callback( +%7D );%0A - - %7D);%0A - %7D);%0A%7D%0A%0A +%7D%0A%0Afunction TestHist() %7B%0A%0A jsro @@ -597,323 +597,58 @@ %3E %7B%0A -/* MakeTest(file,%22draw_hstack%22, function() %7B%0A MakeTest(file,%22draw_nostackb%22, function() %7B%0A MakeTest(file,%22draw_hstack%22, function() %7B%0A %7D);%0A %7D);%0A %7D);%0A return;%0A*/ %0A %0A file.ReadObject(itemname).then(obj =%3E %7B%0A // var subpad = obj.fPrimitives.arr%5B2%5D;%0A // var subpad = obj;%0A +%0A file.ReadObject(itemname).then(obj =%3E %7B%0A @@ -710,23 +710,21 @@ 00 %7D -, functio +).the n(svg -) + =%3E %7B%0A @@ -723,32 +723,35 @@ g =%3E %7B%0A + + fs.writeFileSync @@ -752,22 +752,20 @@ leSync(%22 -single +hist .svg%22, s @@ -761,32 +761,35 @@ ist.svg%22, svg);%0A + console @@ -801,22 +801,20 @@ 'create -single +hist .svg fil @@ -845,18 +845,25 @@ + %7D);%0A +%0A +%7D); %0A @@ -867,11 +867,34 @@ %7D);%0A%7D +%0A%0A%0ATestEve();%0ATestHist( );%0A
6d24b258e6822a5c6e5fb75b56f14821097bdc44
add extension uninstall redirect script
chrome-specific/background.js
chrome-specific/background.js
/* eslint-disable */ chrome.browserAction.onClicked.addListener(function(tab) { chrome.browserAction.setPopup({ popup: 'popup.html', }); });
JavaScript
0
@@ -134,12 +134,91 @@ ',%0A%09%7D);%0A%7D);%0A +%0Achrome.runtime.setUninstallURL('https://siddharth31.typeform.com/to/Z8AUHk');%0A
c7cbede3650c23f134096e709135fb32c33ee403
Simplify Elements example by using Math.max
example/elements.js
example/elements.js
/* tags: basic, lines <p> This example demonstrates how you can use `elements` to draw lines. </p> */ const regl = require('../regl')() regl.clear({ color: [0, 0, 0, 1], depth: 1 }) var lineWidth = 3 if (lineWidth > regl.limits.lineWidthDims[1]) { lineWidth = regl.limits.lineWidthDims[1] } regl({ frag: ` precision mediump float; uniform vec4 color; void main() { gl_FragColor = color; }`, vert: ` precision mediump float; attribute vec2 position; void main() { gl_Position = vec4(position, 0, 1); }`, attributes: { position: (new Array(5)).fill().map((x, i) => { var theta = 2.0 * Math.PI * i / 5 return [ Math.sin(theta), Math.cos(theta) ] }) }, uniforms: { color: [1, 0, 0, 1] }, elements: [ [0, 1], [0, 2], [0, 3], [0, 4], [1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4] ], lineWidth: lineWidth })()
JavaScript
0
@@ -205,71 +205,19 @@ h = -3%0Aif (lineWidth %3E regl.limits.lineWidthDims%5B1%5D) %7B%0A lineWidth = +Math.max(3, reg @@ -241,18 +241,17 @@ hDims%5B1%5D -%0A%7D +) %0A%0Aregl(%7B
3f8eb60ed52f60441247eea29293c9313ada17c2
Add cvApp module
app/js/app.js
app/js/app.js
app.js
JavaScript
0.000001
@@ -1,6 +1,85 @@ -app.js +'use strict';%0A%0Avar cvApp = angular.module('cvApp', %5B'ngRoute', 'cvAppControllers'%5D);%0A
4ee36f459f55ff2aca7c6942b8498ef852ff3e41
Fix exception caused by incorrect file ordering
renderer/lib/migrations.js
renderer/lib/migrations.js
/* eslint-disable camelcase */ module.exports = { run } var fs = require('fs-extra') var path = require('path') var semver = require('semver') var config = require('../../config') // Change `state.saved` (which will be saved back to config.json on exit) as // needed, for example to deal with config.json format changes across versions function run (state) { // Migration: replace "{ version: 1 }" with app version (semver) if (!semver.valid(state.saved.version)) { state.saved.version = '0.0.0' // Pre-0.7.0 version, so run all migrations } var version = state.saved.version if (semver.lt(version, '0.7.0')) { migrate_0_7_0(state) } // Future migrations... // if (semver.lt(version, '0.8.0')) { // migrate_0_8_0(state) // } // Config is now on the new version state.saved.version = config.APP_VERSION } function migrate_0_7_0 (state) { console.log('migrate to 0.7.0') state.saved.torrents.forEach(function (ts) { var infoHash = ts.infoHash // Migration: replace torrentPath with torrentFileName var src, dst if (ts.torrentPath) { // There are a number of cases to handle here: // * Originally we used absolute paths // * Then, relative paths for the default torrents, eg '../static/sintel.torrent' // * Then, paths computed at runtime for default torrents, eg 'sintel.torrent' // * Finally, now we're getting rid of torrentPath altogether console.log('migration: replacing torrentPath %s', ts.torrentPath) if (path.isAbsolute(ts.torrentPath)) { src = ts.torrentPath } else if (ts.torrentPath.startsWith('..')) { src = ts.torrentPath } else { src = path.join(config.STATIC_PATH, ts.torrentPath) } dst = path.join(config.CONFIG_TORRENT_PATH, infoHash + '.torrent') // Synchronous FS calls aren't ideal, but probably OK in a migration // that only runs once if (src !== dst) fs.copySync(src, dst) delete ts.torrentPath ts.torrentFileName = infoHash + '.torrent' } // Migration: replace posterURL with posterFileName if (ts.posterURL) { console.log('migration: replacing posterURL %s', ts.posterURL) var extension = path.extname(ts.posterURL) src = path.isAbsolute(ts.posterURL) ? ts.posterURL : path.join(config.STATIC_PATH, ts.posterURL) dst = path.join(config.CONFIG_POSTER_PATH, infoHash + extension) // Synchronous FS calls aren't ideal, but probably OK in a migration // that only runs once if (src !== dst) fs.copySync(src, dst) delete ts.posterURL ts.posterFileName = infoHash + extension } // Migration: add per-file selections if (!ts.selections && ts.files) { ts.selections = ts.files.map((x) => true) } }) }
JavaScript
0.000022
@@ -359,36 +359,25 @@ ate) %7B%0A // -Migration: r +R eplace %22%7B ve @@ -981,36 +981,25 @@ ash%0A%0A // -Migration: r +R eplace torre @@ -1423,35 +1423,24 @@ onsole.log(' -migration: replacing to @@ -2026,20 +2026,9 @@ // -Migration: r +R epla @@ -2107,19 +2107,8 @@ og(' -migration: repl @@ -2622,68 +2622,186 @@ // -Migration: add per-file selections%0A if (!ts.selections && +Fix exception caused by incorrect file ordering.%0A // https://github.com/feross/webtorrent-desktop/pull/604#issuecomment-222805214%0A delete ts.defaultPlayFileIndex%0A delete ts. @@ -2805,25 +2805,27 @@ ts.files -) %7B %0A - +delete ts.sele @@ -2834,42 +2834,35 @@ ions - = ts.files.map((x) =%3E true)%0A %7D +%0A delete ts.fileModtimes %0A %7D
4d98e85b8e3387b0c3c38ff1fb33f58d2905c909
update example producer file
example/producer.js
example/producer.js
/** * XadillaX created at 2015-12-19 23:37:40 With ♥ * * Copyright (c) 2015 Souche.com, all rights * reserved. */ "use strict"; var Producer = require("../lib/producer"); var producer = new Producer( "PID", "access_key", "secret_key"); console.log("Connecting to Aliyun ONS..."); producer.start(function() { console.log("Started."); setInterval(function() { for(var i = 0; i < 10; i++) { producer.send("ons_subscriber_test", "tagA", "Hello " + i + "!", function(err, messageId) { console.log(err, messageId); }); /* jshint ignore: line */ } }, 1000); });
JavaScript
0
@@ -494,16 +494,30 @@ i + %22!%22, + 86400 * 1000, functio
cea96bcad0ac73156fc303118cf316470d03cf9c
Update package-test.js
package-test.js
package-test.js
const package = require('./package.json'); const packageJson = require('package-json'); const SAFE_TIME = 1000 * 1 * 60 * 60 * 24 * 7; //7days const EXCEPTIONS = ['canvas', 'ethereum-ens', 'webpack']; const CUSTOM_DIST = { ['babel-core']: 'bridge' }; const ALL_PACKAGES = Object.assign( {}, package.dependencies, package.devDependencies ); const names = Object.keys(ALL_PACKAGES); let updatesFound = false; const looper = () => { if (!names.length) { if (updatesFound) process.exit(1); else process.exit(0); } const _name = names.shift(); if (EXCEPTIONS.includes(_name)) return looper(); if (ALL_PACKAGES[_name].includes('^') || ALL_PACKAGES[_name].includes('~')) { console.error( 'Invalid character ~ or ^ found on package.json version string, only fixed versions are allowed' ); process.exit(1); } packageJson(_name, { fullMetadata: true, allVersions: true }) .then(info => { const latestVersion = info['dist-tags'][CUSTOM_DIST[_name] || 'latest']; const latestVersionTime = info['time'][latestVersion]; if ( ALL_PACKAGES[_name] !== latestVersion && new Date(latestVersionTime).getTime() < new Date().getTime() - SAFE_TIME ) { console.error( 'new update found', _name, ALL_PACKAGES[_name], latestVersion, latestVersionTime ); updatesFound = true; } }) .then(looper); }; looper();
JavaScript
0.000002
@@ -191,16 +191,30 @@ webpack' +, 'babel-jest' %5D;%0Aconst
d526b351a93d6069032daf4a1de1d33ff4c4c1b2
Remove dead code from Record#soundcloud
app/record.js
app/record.js
'use strict'; const Paths = require('./paths'); module.exports = class Record { constructor(id) { this.id = id; } isTrack() { return !['playlist', 'album'].includes(this.kind); } static soundcloud(hash) { var width = hash.kind == 'playlist' ? 't300x300' : 't200x200'; if (hash.tracks_uri) var icon = hash.user.avatar_url.size(width); else if (hash.artwork_url) var icon = hash.artwork_url.size(width); else if (hash.kind != 'playlist') var icon = Paths.default_artwork; var record = new Record(hash.id); record.title = hash.title; record.icon = icon; record.genre = hash.genre; record.url = hash.permalink_url; record.kind = hash.kind; record.tags = hash.tag_list; record.waveform_url = hash.waveform_url; record.human_time = Formatter.time(hash.duration * Math.pow(10, -3)); record.duration = hash.duration * Math.pow(10, -3); record.origin = hash.origin; record.type = hash.type; record.service = 'soundcloud'; if (hash.user) record.artist = hash.user.username; if (hash.uri) record.uri = hash.uri; if (hash.tracks_uri) { record.track_count = hash.track_count; record.tracks_uri = hash.tracks_uri; } if (hash.tracks) { record.items = hash.tracks.map((track, i) => { console.log("whenever you're reached, tell me bra"); return Record.soundcloud(track); }).map(MetaModel.mapRecords); } return record; } static youtube(hash) { if (hash.id && typeof hash.id !== 'string') var id = hash.id.videoId; else var id = hash.id; var record = new Record(id); if (hash.snippet) { record.title = hash.snippet.title; record.artist = hash.snippet.channelTitle; record.icon = hash.snippet.thumbnails.medium.url; record.tags = hash.snippet.tags; } if (hash.contentDetails) { record.human_time = Formatter.time(hash.contentDetails.duration); record.duration = Formatter.duration(record.human_time); if (hash.contentDetails.itemCount) record.items_count = hash.contentDetails.itemCount; } record.page_token = hash.page_token record.service = 'youtube'; if (hash.items) record.items = hash.items.map((record) => { return Record.youtube(record); }).map(MetaModel.mapRecords); return record; } static local(hash) { var record = new Record(hash.id); for (var key in hash) { if (key == 'icon') record[key] = 'file://' + hash[key]; else record[key] = hash[key]; } if (!hash.icon && hash.album == true) record.icon = hash.items.first().icon; else if (!hash.icon) record.icon = Paths.default_artwork; if (record.album == true) record.artist = hash.items.first().artist; record.service = 'local'; record.human_time = Formatter.time(hash.duration); return record; } }
JavaScript
0
@@ -299,89 +299,8 @@ if -(hash.tracks_uri)%0A var icon = hash.user.avatar_url.size(width);%0A else if (has @@ -1142,248 +1142,64 @@ acks -_uri) %7B%0A record.track_count = hash.track_count;%0A record.tracks_uri = hash.tracks_uri;%0A %7D%0A%0A if (hash.tracks) %7B%0A record.items = hash.tracks.map((track, i) =%3E %7B%0A console.log(%22whenever you're reached, tell me bra%22); +) %7B%0A record.items = hash.tracks.map((track, i) =%3E %7B %0A
e00198615bb8f761afa5324753f92135f6bd399f
Revert "Fix for <STRIPE_ACCOUNT>"
example/src/Root.js
example/src/Root.js
import React, { PureComponent } from 'react' import { View, Platform, StyleSheet } from 'react-native' import DrawerLayout from 'react-native-drawer-layout-polyfill' import stripe from 'tipsi-stripe' import Header from './components/Header' import MenuItem from './components/MenuItem' import ApplePayScreen from './scenes/ApplePayScreen' import AndroidPayScreen from './scenes/AndroidPayScreen' import CardFormScreen from './scenes/CardFormScreen' import CustomCardScreen from './scenes/CustomCardScreen' import CustomBankScreen from './scenes/CustomBankScreen' import CardTextFieldScreen from './scenes/CardTextFieldScreen' import SourceScreen from './scenes/SourceScreen' import PaymentIntentScreen from './scenes/PaymentIntentScreen' import SetupIntentScreen from './scenes/SetupIntentScreen' import testID from './utils/testID' stripe.setOptions({ publishableKey: '<PUBLISHABLE_KEY>', merchantId: '<MERCHANT_ID>', androidPayMode: 'test', }) const connectedAccount = '<STRIPE_ACCOUNT>'; if (connectedAccount != '') { stripe.setStripeAccount(connectedAccount) } export default class Root extends PureComponent { state = { index: 0, isDrawerOpen: false, routes: [ Platform.select({ ios: ApplePayScreen, android: AndroidPayScreen, }), CardFormScreen, CustomCardScreen, CustomBankScreen, CardTextFieldScreen, SourceScreen, PaymentIntentScreen, SetupIntentScreen, ].filter((item) => item), } getCurrentScene = () => this.state.routes[this.state.index] handleChangeTab = (index) => { this.drawer.closeDrawer() this.setState({ index }) } handleDrawerRef = (node) => { this.drawer = node } handleMenuPress = () => { if (this.state.isDrawerOpen) { this.drawer.closeDrawer() } else { this.drawer.openDrawer() } } handleDrawerOpen = () => { this.setState({ isDrawerOpen: true }) } handleDrawerClose = () => { this.setState({ isDrawerOpen: false }) } /* eslint-disable react/no-array-index-key */ renderNavigation = () => ( <View style={styles.drawer}> {this.state.routes.map((Scene, index) => ( <MenuItem key={index} title={Scene.title} active={this.state.index === index} onPress={() => this.handleChangeTab(index)} {...testID(Scene.title)} /> ))} </View> ) render() { const Scene = this.getCurrentScene() return ( <View style={styles.container}> <View style={styles.statusbar} /> <Header title={`Example: ${Scene.title}`} onMenuPress={this.handleMenuPress} /> <DrawerLayout drawerWidth={200} drawerPosition={DrawerLayout.positions.Left} renderNavigationView={this.renderNavigation} onDrawerOpen={this.handleDrawerOpen} onDrawerClose={this.handleDrawerClose} ref={this.handleDrawerRef} > <Scene /> </DrawerLayout> </View> ) } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#f5f5f5', }, statusbar: { height: Platform.select({ ios: 20, android: 0 }), }, drawer: { flex: 1, backgroundColor: '#ffffff', }, })
JavaScript
0
@@ -951,33 +951,32 @@ %7D)%0A%0A -const connected +stripe.setStripe Account - = +( '%3CST @@ -993,85 +993,9 @@ NT%3E' -;%0Aif (connectedAccount != '') %7B%0A stripe.setStripeAccount(connectedAccount)%0A%7D +) %0A%0Aex
bfc6f06c3023a7b98198c459d9ea2c9621503d67
Allow http and https links
ipol_demo/clientApp/js/demo.results.js
ipol_demo/clientApp/js/demo.results.js
var clientApp = clientApp || {}; var helpers = clientApp.helpers || {}; var results = clientApp.results || {}; var ddl_results, info; results.draw = function (run_response) { ddl_results = ddl.results; work_url = run_response.work_url; info = run_response.algo_info; $('.results').removeClass('di-none'); $('.results-container').empty(); if (run_response.messages) run_response.messages.sort().forEach(printMessage); for (let i = 0; i < ddl_results.length; i++) { var functionName = $.fn[ddl_results[i].type]; if ($.isFunction(functionName)) printResult(ddl_results[i], i); else console.error(ddl_results[i].type + ' result type is not defined'); } } function printMessage(message, index, messages){ printResult({ 'type': 'message', 'contents': [message] }, 'msg-' + index); } function printResult(result, index) { if (!isVisible(result)) return; $('<div class=result_' + index + ' ></div>').appendTo($('.results-container')); $('.result_' + index)[result.type](result, index); } function getFileURL(file){ if (file.startsWith('http')) return file; if (!getParameterFromURL('archive')) return work_url + file; var images_ddl = $.extend({}, ddl.archive.files, ddl.archive.hidden_files); var images_ddl_keys = Object.keys(images_ddl); for (let i = 0; i < images_ddl_keys.length; i++) for (let j = 0; j < experiment.files.length; j++) if (images_ddl[images_ddl_keys[i]] === experiment.files[j].name && images_ddl_keys[i] === file) return experiment.files[j].url; return null; } function isVisible(result) { return result.visible ? eval(result.visible) : true; } $.fn.file_download = function (result, index) { if (result.repeat) { $(this).append('<div class=file_download_content_' + index + ' ></div>'); for (let idx = 0; idx < eval(result.repeat); idx++) { var file = eval(result.contents); $('.file_download_content_' + index).append('<div class=download_' + index + '_' + idx + ' ></div>'); $('.download_' + index + '_' + idx).addClass('file_download'); $('.download_' + index + '_' + idx).append('<a href=' + getFileURL(file) + ' download><img src=./assets/file.svg class=file-icon >' + eval(result.label) + '</a>') } } else { $(this).append('<h4>' + result.label + '</h4>'); $(this).children().addClass('file_download_title'); $(this).append('<div class=file_download_content_' + index + ' ></div>'); if (typeof result.contents == "string") { $('.file_download_content_' + index).append('<div class=download_' + index + ' ></div>'); $('.download_' + index).addClass('file_download'); $('.download_' + index).append('<a href=' + getFileURL(result.contents) + ' download><img src=./assets/file.svg class=file-icon >' + result.contents + '</a>') } else { var contentKeys = Object.keys(result.contents); for (let i = 0; i < contentKeys.length; i++) { $('.file_download_content_' + index).append('<div class=download_' + index + '_' + i + ' ></div>'); $('.download_' + index + '_' + i).addClass('file_download'); $('.download_' + index + '_' + i).append('<a href=' + getFileURL(result.contents[contentKeys[i]]) + ' download><img src=./assets/file.svg class=file-icon >' + contentKeys[i] + '</a>') } } } } $.fn.text_file = function (result, index) { var request = new XMLHttpRequest(); request.open('GET', getFileURL(result.contents), true); request.responseType = 'blob'; request.onload = function () { var reader = new FileReader(); reader.readAsText(request.response); reader.onload = function (e) { $('.result_' + index).append('<h3>' + result.label + '</h3>'); $('.result_' + index).append('<pre class=text_file_content id=text_file_' + index + ' >' + e.target.result + '</pre>'); if (result.style) $('#text_file_' + index).css(JSON.parse(result.style.replace(/'/g, '"'))); }; }; request.send(); } $.fn.html_text = function (result, index) { var text = ''; var html_text = ''; var content = []; if (!Array.isArray(result.contents)) content.push(result.contents); else content = result.contents; for (let i = 0; i < content.length; i++) text += content[i]; try { html_text = eval(text); } catch (e) { html_text = text; } $(this).append("<div class=html_text_" + index + " ></div>"); $('.html_text_' + index).html(html_text); } $.fn.message = function (result, index) { $(this).append("<div class=message_" + index + " ></div>"); $('.message_' + index).html(eval(result.contents)); $('.message_' + index).addClass('result-msg-box'); if (result.backgroundColor) $('.message_' + index).css({ backgroundColor: result.backgroundColor }); if (result.textColor) $('.message_' + index).css({ color: result.textColor }); }
JavaScript
0
@@ -1084,16 +1084,50 @@ th('http +s://') %7C%7C file.startsWith('http:// ')) retu
77728f7eac4fcb3c832c675e31bcd46f732ee5ba
space out error text
app/routes.js
app/routes.js
"use strict"; // boilerplate includes var config = require("../config/config"), es = require("./boot").es, helpers = require("./helpers"), fs = require("fs"); // Number of reports per request for web page results and RSS results var HTML_SIZE = 10; var XML_SIZE = 50; module.exports = function(app) { // The homepage. A temporary search page. app.get('/', function(req, res) { res.render("index.html", { inspector: null }); }); app.get('/about', function(req, res) { res.redirect(302, 'https://sunlightfoundation.com/blog/2014/11/07/opengov-voices-opening-up-government-reports-through-teamwork-and-open-data/'); }); app.get('/reports', function(req, res) { var query; if (req.query.query) query = req.query.query; else query = "*"; var inspector = req.query.inspector || null; var page = req.query.page || 1; search(query, inspector, page, HTML_SIZE).then(function(results) { res.render("reports.html", { results: results, query: req.query.query, inspector: inspector, page: page, size: HTML_SIZE }); }, function(err) { console.log("Noooo!"); res.status(500); res.render("reports.html", { results: null, query: null, inspector: inspector, page: null }); }); }); app.get('/reports.xml', function(req, res) { var query; if (req.query.query) { query = req.query.query; if (query.charAt(0) != "\"" || query.charAt(query.length-1) != "\"") query = "\"" + query + "\""; } else query = "*"; var inspector = req.query.inspector || null; var page = req.query.page || 1; search(query, inspector, page, XML_SIZE).then(function(results) { res.type("atom"); res.render("reports.xml.ejs", { results: results, query: req.query.query, inspector: inspector, page: page, size: XML_SIZE, self_url: req.url }); }, function(err) { console.log("Noooo!"); res.status(500); res.type("text"); res.send("Server error"); }); }); app.get('/inspectors', function(req, res) { res.render("inspectors.html"); }); app.get('/inspectors/:inspector', function(req, res) { var metadata = helpers.inspector_info(req.params.inspector); if (metadata) { var inspectorReportCount = null; if (helpers.counts.inspectors) inspectorReportCount = helpers.counts.inspectors[req.params.inspector] || 0; search("*", req.params.inspector, 1, HTML_SIZE).then(function(results) { res.render("inspector.html", { inspector: req.params.inspector, metadata: metadata, inspectorReportCount: inspectorReportCount, results: results }); }, function(err) { console.log("Noooo!"); res.render("inspector.html", { inspector: req.params.inspector, metadata: metadata, inspectorReportCount: inspectorReportCount, results: [] }); }); } else { res.status(404); res.render("inspector.html", {metadata: null}); } }); app.get('/reports/:inspector/:report_id', function(req, res) { get(req.params.inspector, req.params.report_id).then(function(result) { res.render("report.html", { report: result._source }); }, function(err) { console.log("Nooooo! " + err); res.status(500); res.render("report.html", {report: null}); }); }); }; function get(inspector, report_id) { return es.get({ index: config.elasticsearch.index_read, type: 'reports', id: inspector + '-' + report_id }); } function search(query, inspector, page, size) { var from = (page - 1) * size; var body = { "from": from, "size": size, "query": { "filtered": { "query": { "query_string": { "query": query, "default_operator": "AND", "use_dis_max": true, "fields": ["text", "title", "summary"] } } } }, "sort": [{ "published_on": "desc" }], "highlight": { "encoder": "html", "pre_tags": ["<b>"], "post_tags": ["</b>"], "fields": { "*": {} }, "order": "score", "fragment_size": 500 }, "_source": ["report_id", "year", "inspector", "agency", "title", "agency_name", "url", "landing_url", "inspector_url", "published_on", "type", "file_type"] }; if (inspector) { body.query.filtered.filter = { "term": { "inspector": inspector } }; } return es.search({ index: config.elasticsearch.index_read, type: 'reports', body: body }); }
JavaScript
0.999856
@@ -1173,36 +1173,47 @@ sole.log(%22Noooo! -%22 +%5Cn%5Cn%22 + err );%0A +%0A res.status @@ -2069,28 +2069,39 @@ .log(%22Noooo! -%22 +%5Cn%5Cn%22 + err );%0A +%0A res.st @@ -2912,17 +2912,27 @@ (%22Noooo! -%22 +%5Cn%5Cn%22 + err );%0A @@ -3505,17 +3505,20 @@ %22Nooooo! - +%5Cn%5Cn %22 + err)
a7bd88a999901c1e58a02a0366966dee7b0594a5
Enable file rename test on Linux
test/events/parent-rename.test.js
test/events/parent-rename.test.js
const fs = require('fs-extra') const {Fixture} = require('../helper') const {EventMatcher} = require('../matcher') // These cases interfere with the caches on MacOS, but other platforms should handle them correctly as well. describe('when a parent directory is renamed', function () { let fixture, matcher let originalParentDir, originalFile let finalParentDir, finalFile beforeEach(async function () { fixture = new Fixture() await fixture.before() await fixture.log() originalParentDir = fixture.watchPath('parent-0') originalFile = fixture.watchPath('parent-0', 'file.txt') finalParentDir = fixture.watchPath('parent-1') finalFile = fixture.watchPath('parent-1', 'file.txt') await fs.mkdir(originalParentDir) await fs.writeFile(originalFile, 'contents\n') matcher = new EventMatcher(fixture) await matcher.watch([], {}) }) afterEach(async function () { await fixture.after(this.currentTest) }) it('tracks the file rename across event batches ^linux', async function () { const changedFile = fixture.watchPath('parent-1', 'file-1.txt') await fs.rename(originalParentDir, finalParentDir) await until('the rename event arrives', matcher.allEvents( {action: 'renamed', kind: 'directory', oldPath: originalParentDir, path: finalParentDir} )) await fs.rename(finalFile, changedFile) await until('the rename event arrives', matcher.allEvents( {action: 'renamed', kind: 'file', oldPath: finalFile, path: changedFile} )) }) it('tracks the file rename within the same event batch ^linux', async function () { const changedFile = fixture.watchPath('parent-1', 'file-1.txt') await fs.rename(originalParentDir, finalParentDir) await fs.rename(finalFile, changedFile) await until('the rename events arrive', matcher.allEvents( {action: 'renamed', kind: 'directory', oldPath: originalParentDir, path: finalParentDir}, {action: 'renamed', kind: 'file', oldPath: finalFile, path: changedFile} )) }) it('tracks the file rename when the directory is renamed first ^linux', async function () { const changedFile = fixture.watchPath('parent-0', 'file-1.txt') await fs.rename(originalFile, changedFile) await fs.rename(originalParentDir, finalParentDir) await until('the rename events arrive', matcher.allEvents( {action: 'renamed', kind: 'file', oldPath: originalFile, path: changedFile}, {action: 'renamed', kind: 'directory', oldPath: originalParentDir, path: finalParentDir} )) }) })
JavaScript
0
@@ -1009,23 +1009,16 @@ batches - %5Elinux ', async
091b146c0b6936f91810ac3f0cb3fa7a356f32fc
Fix type name of initial content element of new sections
entry_types/scrolled/package/src/editor/models/Chapter.js
entry_types/scrolled/package/src/editor/models/Chapter.js
import Backbone from 'backbone'; import { configurationContainer, entryTypeEditorControllerUrls, failureTracking, delayedDestroying, ForeignKeySubsetCollection } from 'pageflow/editor'; export const Chapter = Backbone.Model.extend({ mixins: [ configurationContainer({ autoSave: true, includeAttributesInJSON: ['position'] }), delayedDestroying, entryTypeEditorControllerUrls.forModel({resources: 'chapters'}), failureTracking ], initialize(attributes, options) { this.sections = new ForeignKeySubsetCollection({ parent: options.sections, parentModel: this, foreignKeyAttribute: 'chapterId', parentReferenceAttribute: 'chapter' }); this.entry = options.entry; }, addSection(attributes) { const section = this.sections.create({ position: this.sections.length, chapterId: this.id, ...attributes }, { contentElements: this.entry.contentElements }); section.once('sync', () => { section.contentElements.create({ typeName: 'editableTextBlock', configuration: { } }); }); } });
JavaScript
0.000074
@@ -1062,17 +1062,9 @@ e: ' -editableT +t extB
e8523d878ada4c932689b9de7c87cf9420849d86
Add margins to work with sticky header
client/js/hah-app/feedback.js
client/js/hah-app/feedback.js
import React from 'react' import { ReactTypeformEmbed } from 'react-typeform-embed' import injectSheet from 'react-jss' import LogoAndNavigation from '../mini-app/logo-and-navigation' import Footer from '../mini-app/components/footer' import { Desktop, Phone } from '../components/breakpoints' import Spacer from '../components/spacer' const TITLE_TEXT = "We're listening." const BODY_TEXT_1 = 'We want to hear what you have to say. Our goal is to continually ' + "improve women's access to affordable, reliable, and non-violent healthcare options, " + 'regardless of their situation.' const BODY_TEXT_2 = 'Got something you want to tell us? Run into an issue?' const BODY_TEXT_3 = 'How can we make finding local resources the easiest thing to do?' const Feedback = ({ classes }) => ( <div> <LogoAndNavigation /> <Phone> <div> <Spacer height="36px" /> <div className={classes.titleTextPhone}>{TITLE_TEXT}</div> <Spacer height="28px" /> <div className={classes.gridContainerPhone}> <div className={classes.bodyTextPhone}> {BODY_TEXT_1} <Spacer height="28px" /> {BODY_TEXT_2} <Spacer height="28px" /> <div className={classes.blueText}>{BODY_TEXT_3}</div> </div> </div> </div> </Phone> <Desktop> <div> <Spacer height="60px" /> <div className={classes.titleTextDesktop}>{TITLE_TEXT}</div> <Spacer height="32px" /> <div className={classes.gridContainerDesktop}> <div className={classes.bodyTextDesktop}> {BODY_TEXT_1} <Spacer height="32px" /> {BODY_TEXT_2} <Spacer height="32px" /> <div className={classes.blueText}>{BODY_TEXT_3}</div> </div> </div> </div> </Desktop> <ReactTypeformEmbed url="https://helpassisther.typeform.com/to/pUhArd" style={{ position: 'unset', height: '500px' }} /> <Footer /> </div> ) const styles = { titleTextPhone: { color: '#000000', 'font-family': 'hah-regular', 'font-size': '24px', 'line-height': '28px', 'text-align': 'center', }, titleTextDesktop: { color: '#000000', 'font-family': 'hah-regular', 'font-size': '40px', 'line-height': '48px', 'text-align': 'center', }, gridContainerPhone: { display: 'grid', 'grid-template-columns': '5% 90% 5%', }, gridContainerDesktop: { display: 'grid', 'grid-template-columns': '20% 60% 20%', }, bodyTextPhone: { color: '#000000', 'font-family': 'hah-regular', 'font-size': '14px', 'line-height': '20px', 'text-align': 'center', 'grid-column-start': 2, 'grid-column-end': 3, }, bodyTextDesktop: { color: '#000000', 'font-family': 'hah-regular', 'font-size': '24px', 'line-height': '35px', 'text-align': 'center', 'grid-column-start': 2, 'grid-column-end': 3, }, blueText: { color: '#3D65F9', }, } export default injectSheet(styles)(Feedback)
JavaScript
0
@@ -829,34 +829,81 @@ %09%3CPhone%3E%0A%09%09%09%3Cdiv + className=%7Bclasses.feedbackPageContainerPhone%7D %3E%0A - %09%09%09%09%3CSpacer heig @@ -1323,24 +1323,73 @@ top%3E%0A%09%09%09%3Cdiv + className=%7Bclasses.feedbackPageContainerDesktop%7D %3E%0A%09%09%09%09%3CSpace @@ -1964,16 +1964,16 @@ div%3E%0A)%0A%0A - const st @@ -1981,16 +1981,149 @@ les = %7B%0A +%09feedbackPageContainerPhone: %7B%0A%09%09margin: '55px 0px 0px 0px',%0A%09%7D,%0A%09feedbackPageContainerDesktop: %7B%0A%09%09margin: '100px 0px 0px 0px',%0A%09%7D,%0A %09titleTe
46a8e9a2845111d57cf2d94c2c37f800e280bd14
Fix search bar search
client/src/components/Page.js
client/src/components/Page.js
import PropTypes from 'prop-types' import React, {Component} from 'react' import _get from 'lodash/get' import autobind from 'autobind-decorator' import NotFound from 'components/NotFound' import {setMessages} from 'components/Messages' import API from 'api' import NProgress from 'nprogress' import 'nprogress/nprogress.css' import _isEqual from 'lodash/isEqual' import { DEFAULT_PAGE_PROPS } from 'actions' const NPROGRESS_CONTAINER = '.header' if (process.env.NODE_ENV !== 'test') { NProgress.configure({ parent: NPROGRESS_CONTAINER }) } export default class Page extends Component { static propTypes = { setPageProps: PropTypes.func.isRequired, } constructor(props, pageProps) { super(props) if (typeof props.setPageProps === 'function') { props.setPageProps(pageProps || DEFAULT_PAGE_PROPS) } this.state = { notFound: false, invalidRequest: false, } this.renderPage = this.render this.render = Page.prototype.render } componentWillMount() { window.scrollTo(0,0) if (document.querySelector(NPROGRESS_CONTAINER)) { NProgress.start() } } loadData(props, context) { this.setState({notFound: false, invalidRequest: false}) if (this.fetchData) { document.body.classList.add('loading') this.fetchData(props || this.props, context || this.context) let promise = API.inProgress if (promise && promise.then instanceof Function) { NProgress.set(0.5) promise.then(this.doneLoading, this.doneLoading) } else { this.doneLoading() } return promise } else { this.doneLoading() } } @autobind doneLoading(response) { NProgress.done() document.body.classList.remove('loading') if (response) { if (response.status === 404 || (response.status === 500 && _get(response, ['errors', 0]) === 'Invalid Syntax')) { this.setState({notFound: true}) } else if (response.status === 500) { this.setState({invalidRequest: true}) } } return response } render() { if (this.state.notFound) { let modelName = this.constructor.modelName let text = modelName ? `${modelName} #${this.props.match.params.id}` : `Page` return <NotFound text={`${text} not found.`} /> } else if (this.state.invalidRequest) { return <NotFound text="There was an error processing this request. Please contact an administrator." /> } return this.renderPage() } componentWillReceiveProps(nextProps, nextContext) { // Filter out React Router props before comparing; for the property names, // see https://github.com/ReactTraining/react-router/issues/4424#issuecomment-285809552 const routerProps = ['match', 'location', 'history'] const filteredNextProps = Object.without(nextProps, ...routerProps) const filteredProps = Object.without(this.props, ...routerProps) if (!_isEqual(filteredProps, filteredNextProps)) { this.loadData(nextProps, nextContext) } else if (!_isEqual(this.context, nextContext)) { this.loadData(nextProps, nextContext) } } componentDidMount() { setMessages(this.props, this.state) this.loadData(this.props) } }
JavaScript
0.000002
@@ -2417,16 +2417,356 @@ text) %7B%0A +%09%09// Location always has a new key. In order to check whether the location%0A%09%09// really changed filter out the key.%0A%09%09const locationFilterProps = %5B'key'%5D%0A%09%09const nextPropsFilteredLocation = Object.without(nextProps.location, ...locationFilterProps)%0A%09%09const propsFilteredLocation = Object.without(this.props.location, ...locationFilterProps)%0A %09%09// Fil @@ -3210,16 +3210,133 @@ ontext)%0A +%09%09%7D else if (!_isEqual(propsFilteredLocation, nextPropsFilteredLocation)) %7B%0A%09%09%09this.loadData(nextProps, nextContext)%0A %09%09%7D else
51e9495dceda86c95a4d281cfef764dde5530e3c
Use ramda's mergeAll instead of spread syntax
app/server.js
app/server.js
import express from 'express' import path from 'path' import {match} from 'react-router' import compression from 'compression' import appConfig from './config' import crypto from 'crypto' import Promise from 'bluebird' import bodyParser from 'body-parser' import DB from './db' import CourseRoutes from './routes/course' import ApiRoutes from './routes/api' import errorLoggerRoutes from './routes/errorLogger' import {appState} from './store/lukkariStore' import Routes from './pages/routes' import forceSSL from 'express-force-ssl' import {renderFullPage} from './pages/initPage' import Logger from './logger' const fs = Promise.promisifyAll(require('fs')) process.on('unhandledRejection', (reason, p) => { Logger.error('Unhandled Rejection at: Promise', p, 'reason:', reason) }) const server = express() server.use(compression({threshold: 512})) server.use(bodyParser.json()) server.use(bodyParser.urlencoded({extended: true})) server.disable('x-powered-by') server.use('/course', CourseRoutes) server.use('/api', ApiRoutes) server.use('/favicon.png', express.static(`${__dirname}/img/favicon.png`)) server.use('/github.png', express.static(`${__dirname}/img/github.png`)) server.use('/spinner.gif', express.static(`${__dirname}/img/spinner.gif`)) const cssFilePath = path.resolve(`${__dirname}/../.generated/styles.css`) const bundleJsFilePath = path.resolve(`${__dirname}/../.generated/bundle.js`) if (process.env.NODE_ENV !== 'production') { server.use('/test/', express.static(path.resolve(`${__dirname}'/../test`))) server.use('/node_modules/', express.static(path.resolve(`${__dirname}'/../node_modules`))) } else { server.use(forceSSL) server.set('forceSSLOptions', { enable301Redirects: true, trustXFPHeader: true, httpsPort: 443, sslRequiredMessage: 'SSL Required.' }) } const checksumPromise = filePath => fs .readFileAsync(filePath) .then(fileContent => crypto.createHash('md5') .update(fileContent) .digest('hex')) const serveStaticResource = (filePath) => (req, res, next) => checksumPromise(filePath) .then(checksum => { if (req.params.checksum === checksum) { const twoHoursInSeconds = 60 * 60 * 2 res.setHeader('Cache-Control', `public, max-age=${twoHoursInSeconds}`) res.setHeader('ETag', checksum) res.sendFile(filePath) } else { res.status(404).send() } }) .catch(next) server.get('/static/:checksum/styles.css', serveStaticResource(cssFilePath)) server.get('/static/:checksum/bundle.js', serveStaticResource(bundleJsFilePath)) const buildInitialState = (displayName) => { const pageState = () => { switch (displayName) { case 'LukkariPage': return {} case 'CatalogPage': return {} case 'NotFoundPage': return {} default: return null } } return { ...pageState, ...{ selectedCourses: [], searchResults: [], currentDate: new Date(), isModalOpen: false, selectedIndex: -1, waitingAjax: false, departmentCourses: [], department: 'TITE' } } } const getNeedFunctionParams = (displayName, params, queryParams) => { switch (displayName) { case 'LukkariPage': return { courses: queryParams.courses } case 'CatalogPage': return { department: params.department ? params.department.toUpperCase() : 'TITE' } default: return null } } const fetchComponentData = (components, pathParams, queryParams) => { const needs = components.reduce((prev, current) => { return current ? (current.needs || []).concat(prev) : prev }, []) const promises = needs.reduce((prev, currNeed) => { const param = getNeedFunctionParams(components[1].displayName, pathParams, queryParams) if (param) { const action = currNeed(param) appState.dispatch(action) return prev.concat(action.promise) } else { return prev } }, []) return Promise.all(promises) } server.get('/.well-known/acme-challenge/:content', (req, res) => res.send(appConfig.letsEncryptReponse)) server.use('/errors', errorLoggerRoutes) server.get('*', (req, res) => { const urlPath = req.url match({routes: Routes, location: urlPath}, (error, redirectLocation, renderProps) => { if (error) { return res.status(500).send('Server error') } else if (redirectLocation) { return res.redirect(302, redirectLocation.pathname + redirectLocation.search) } else if (renderProps === null) { return res.status(404).send('Not found') } else { return Promise .all([checksumPromise(cssFilePath), checksumPromise(bundleJsFilePath), fetchComponentData(renderProps.components, renderProps.params, renderProps.location.query)]) .then(([cssChecksum, bundleJsChecksum]) => { const initialState = {...(buildInitialState(renderProps.components[1].displayName)), ...(appState.currentState)} return Promise.resolve(renderFullPage( initialState, {cssChecksum, bundleJsChecksum}, renderProps )) .then((page) => res.send(page)) }) .catch((err) => { res.status(500).send('Server error') Logger.error('Server error', err.stack) }) } }) }) export const start = (port) => { const env = process.env.NODE_ENV ? process.env.NODE_ENV : 'development' const reportPages = () => { Logger.info(`Page available at http://localhost:${port} in ${env}`) } return DB.isTableInitialized('course') .then((exists) => exists ? null : DB.initializeDb()) .then(() => new Promise((resolve) => { server.listen(port, resolve) })).then(reportPages) }
JavaScript
0
@@ -47,16 +47,47 @@ 'path'%0A +import %7BmergeAll%7D from 'ramda'%0A import %7B @@ -4902,13 +4902,41 @@ e = -%7B...( +mergeAll(%5BappState.currentState, buil @@ -4991,38 +4991,10 @@ ame) +%5D ) -, ...(appState.currentState)%7D %0A
7c41cf9dc0aaf379afd80cafb03d1cea0aa9737c
update config format
app/server.js
app/server.js
'use strict'; var P = require('bluebird'); var minimist = require('minimist'); var path = require('path'); var fs = require('fs'); var forever = require('forever'); var child_process = require('child_process'); var pomeloLogger = require('pomelo-logger'); var logger = pomeloLogger.getLogger('memdb', __filename); var startShard = function(opts){ var Database = require('./database'); var server = require('socket.io')(); var db = new Database(opts); db.start().then(function(){ logger.warn('server started'); }); server.on('connection', function(socket){ var connId = db.connect(); var remoteAddr = socket.conn.remoteAddress; socket.on('req', function(msg){ logger.info('[%s] %s => %j', connId, remoteAddr, msg); var resp = {seq : msg.seq}; P.try(function(){ if(msg.method === 'info'){ return { connId : connId }; } else{ return db.execute(connId, msg.method, msg.args); } }) .then(function(ret){ resp.err = null; resp.data = ret; }, function(err){ resp.err = err.stack; resp.data = null; }) .then(function(){ socket.emit('resp', resp); var level = resp.err ? 'warn' : 'info'; logger[level]('[%s] %s <= %j', connId, remoteAddr, resp); }) .catch(function(e){ logger.error(e.stack); }); }); socket.on('disconnect', function(){ db.disconnect(connId); logger.info('%s disconnected', remoteAddr); }); logger.info('%s connected', remoteAddr); }); server.listen(opts.port); var _isShutingDown = false; var shutdown = function(){ if(_isShutingDown){ return; } _isShutingDown = true; return P.try(function(){ server.close(); return db.stop(); }) .catch(function(e){ logger.error(e.stack); }) .finally(function(){ logger.warn('server closed'); setTimeout(function(){ process.exit(0); }, 200); }); }; process.on('SIGTERM', shutdown); process.on('SIGINT', shutdown); }; if (require.main === module) { process.on('uncaughtException', function(err) { logger.error('Uncaught exception: %s', err.stack); }); var argv = minimist(process.argv.slice(2)); if(argv.help || argv.h){ var usage = 'Usage: server.js [options]\n\n' + 'Options:\n' + ' -c, --conf path Specify config file path (must with .json extension)\n' + ' -s, --shard shardId Start specific shard\n' + ' -d, --daemon Start as daemon\n' + ' -h, --help Display this help'; console.log(usage); process.exit(0); } var searchPaths = []; var confPath = argv.conf || argv.c || null; if(confPath){ searchPaths.push(confPath); } searchPaths = searchPaths.concat(['./memdb.json', '~/.memdb.json', '/etc/memdb.json']); var conf = null; for(var i=0; i<searchPaths.length; i++){ if(fs.existsSync(searchPaths[i])){ conf = require(path.resolve(searchPaths[i])); break; } } if(!conf){ console.error('Error: config file not found! %j', searchPaths); process.exit(1); } var shardId = argv.s || argv.shard || null; if(conf.promise && conf.promise.longStackTraces){ P.longStackTraces(); } // Configure logger var loggerConf = conf.logger || {}; var base = loggerConf.path || '/var/log/memdb'; pomeloLogger.configure(path.join(__dirname, 'log4js.json'), {shardId : shardId, base : base}); var level = loggerConf.level || 'INFO'; pomeloLogger.setGlobalLogLevel(pomeloLogger.levels[level]); var shards = conf.shards || {}; var isDaemon = argv.d || argv.daemon; if(!shardId){ console.error('Please specify shardId with --shard'); process.exit(1); // Main script, will start all shards via ssh // Object.keys(shards).forEach(function(shardId){ // var host = shards[shardId].host; // console.info('start %s via ssh... (TBD)', shardId); // // TODO: start shard // }); } else{ // Start specific shard var shardConfig = shards[shardId]; if(!shardConfig){ console.error('Shard %s not exist in config', shardId); process.exit(1); } if(isDaemon){ console.warn('Daemon mode is not supported now'); isDaemon = false; } if(isDaemon && !argv.child){ var args = process.argv.slice(2); args.push('--child'); forever.startDaemon(__filename, { max : 1, slient : true, killTree : false, args : args, }); } else{ var opts = { shard : shardId, host : shardConfig.host, port : shardConfig.port, locking : shardConfig.locking, event : shardConfig.event, backend : shardConfig.backend, slave : shardConfig.slave, collections : conf.collections, }; startShard(opts); } } }
JavaScript
0.000001
@@ -4170,45 +4170,8 @@ );%0A%0A - var shards = conf.shards %7C%7C %7B%7D;%0A%0A @@ -4208,16 +4208,16 @@ daemon;%0A + %0A if( @@ -4658,16 +4658,36 @@ onfig = +conf.shards && conf. shards%5Bs @@ -4819,32 +4819,60 @@ it(1);%0A %7D +%0A delete conf.shards; %0A%0A if(isD @@ -5321,206 +5321,102 @@ -var opts = %7B%0A shard : shardId,%0A host : shardConfig.host,%0A port : shardConfig.port,%0A locking : shardConfig.locking,%0A event : +// Override shard specific config%0A conf.shard = shardId;%0A for(var key in sha @@ -5427,15 +5427,10 @@ nfig -.event, +)%7B %0A @@ -5446,129 +5446,37 @@ -backend : shardConfig.backend,%0A slave : shardConfig.slave,%0A collections : conf.collections, +conf%5Bkey%5D = shardConfig%5Bkey%5D; %0A @@ -5477,33 +5477,32 @@ %5D;%0A %7D -; %0A sta @@ -5509,20 +5509,20 @@ rtShard( -opts +conf );%0A
987f24225d8bebb6c2079d0fc202d5331d32d242
add song change
public/javascripts/angularApp.js
public/javascripts/angularApp.js
var app = angular.module('djq', ['ui.router']) app.factory('users', ['$http', function($http) { var o = { users: [] }; o.getAll = function(){ return $http.get('/users').success(function(data) { angular.copy(data, o.users); })}; o.addDj = function(dj){ return $http.post('/users/add', dj).success(function(data){ o.users.push(data); })}; return o; }]) // we might not need this, but are keeping it for now... app.factory('queue', ['$http', function($http) { var o = { queue: [], playing: {} }; o.getAll = function(username){ return $http.get('/users/' + username).success(function(data) { angular.copy(data.queue, o.queue); })}; o.addSong = function(username, song){ return $http.post('/'+username+'/addSong', song).success(function(){ o.getAll(username); })}; o.popSong = function(username){ return $http.post('/'+username+'/popSong').success(function(data){ o.playing = data; o.getAll(username); })}; o.upvoteSong = function(username, song){ return $http.post('/'+username+'/upvoteSong', song).success(function(){ o.getAll(username); })}; o.downvoteSong = function(username, song){ return $http.post('/'+username+'/downvoteSong', song).success(function(){ o.getAll(username); })}; return o; }]) app.config ([ '$stateProvider', '$urlRouterProvider', '$locationProvider', function($stateProvider, $urlRouterProvider, $locationProvider) { $stateProvider .state('home', { url: '/', templateUrl: '/home.html', controller: 'MainCtrl', resolve: { postPromise: ['users', function(users){ return users.getAll(); }] } }) .state('users', { url: '/:username', templateUrl: '/dj.html', controller: 'UsersCtrl', resolve: { postPromise: ['$stateParams', 'queue', function($stateParams, queue) { return queue.getAll($stateParams.username); }] } }); $locationProvider.html5Mode(true); }]); app.controller('MainCtrl', [ '$scope', 'users', function($scope, users) { $scope.users = users.users $scope.addDj = function() { if (!$scope.username || $scope.username === '') { alert("Please enter a username!"); return; } if (!$scope.password || $scope.password === '') { alert("Please enter a password!"); return; } if (!$scope.email || $scope.email === '') { alert("Please enter an email!"); return; } var dj = { username: $scope.username, password: $scope.password, email: $scope.email }; users.addDj(dj); $scope.username = ''; $scope.password = ''; $scope.email = ''; } }] ); app.controller('UsersCtrl', [ '$scope', '$stateParams', 'queue', function($scope, $stateParams, queue) { $scope.username = $stateParams.username; $scope.queue = queue.queue; $scope.playing = queue.playing; $scope.keyPress = function() { console.log($('#searchbar').val()); if ($('#searchbar').val() === '') { $('#results').empty(); } else { search($('#searchbar').val()); } } $scope.addSong = function() { var song = {title: $scope.title, length: $scope.length, url: $scope.url, thumbnail: $scope.thumbnail }; queue.addSong($scope.username, song); $scope.title = ''; $scope.length = ''; $scope.url = ''; $scope.thumbnail = ''; } $scope.upvoteSong = function(song) { queue.upvoteSong($scope.username, song); $scope.songId = ''; } $scope.downvoteSong = function(song) { queue.downvoteSong($scope.username, song); $scope.songId = ''; } $scope.popSong = function() { queue.popSong($scope.username); } $scope.getPlaying = function() { console.log(queue.playing); } } ]);
JavaScript
0.000003
@@ -3060,148 +3060,15 @@ ion( -) %7B%0A%09%09%09var song = %7Btitle: %09%09$scope.title,%0A%09%09%09%09%09 %09length: %09$scope.length,%0A%09%09%09%09%09%09url: %09%09$scope.url,%0A%09%09%09%09%09%09thumbnail: %09$scope.thumbnail%0A%09%09%09%7D;%0A +song) %7B %0A%09%09%09 @@ -3133,32 +3133,8 @@ '';%0A -%09%09%09$scope.length%09%09= '';%0A %09%09%09$
11488df27421a4300d921a6f8a5a3e8f672fb158
Return the rejected Promise (#12)
index.js
index.js
'use strict'; const fs = require('fs'); const pify = require('pify'); const isExe = (mode, gid, uid) => { if (process.platform === 'win32') { return true; } const isGroup = gid ? process.getgid && gid === process.getgid() : true; const isUser = uid ? process.getuid && uid === process.getuid() : true; return Boolean((mode & parseInt('0001', 8)) || ((mode & parseInt('0010', 8)) && isGroup) || ((mode & parseInt('0100', 8)) && isUser)); }; module.exports = name => { if (typeof name !== 'string') { Promise.reject(new TypeError('Expected a string')); } return pify(fs.stat)(name).then(stats => stats && stats.isFile() && isExe(stats.mode, stats.gid, stats.uid)); }; module.exports.sync = name => { if (typeof name !== 'string') { throw new Error('Expected a string'); } const stats = fs.statSync(name); return stats && stats.isFile() && isExe(stats.mode, stats.gid, stats.uid); }; module.exports.checkMode = isExe;
JavaScript
0.999947
@@ -510,16 +510,23 @@ g') %7B%0A%09%09 +return Promise.
d388d1ee4255955b7a26e5465afd5c0e803105fd
Fix googleapis version lookup
provider/googleProvider.js
provider/googleProvider.js
'use strict'; const path = require('path'); const fs = require('fs'); const os = require('os'); const _ = require('lodash'); const google = require('googleapis').google; const packageJson = require('../package.json'); const constants = { providerName: 'google', }; class GoogleProvider { static getProviderName() { return constants.providerName; } constructor(serverless) { this.serverless = serverless; this.provider = this; // only load plugin in a Google service context this.serverless.setProvider(constants.providerName, this); const serverlessVersion = this.serverless.version; const pluginVersion = packageJson.version; const googleApisVersion = packageJson.dependencies.googleapis; google.options({ headers: { 'User-Agent': `Serverless/${serverlessVersion} Serverless-Google-Provider/${pluginVersion} Googleapis/${googleApisVersion}`, }, }); this.sdk = { google, deploymentmanager: google.deploymentmanager('v2'), storage: google.storage('v1'), logging: google.logging('v2'), cloudfunctions: google.cloudfunctions('v1'), }; } request() { // grab necessary stuff from arguments array const lastArg = arguments[Object.keys(arguments).pop()]; //eslint-disable-line const hasParams = (typeof lastArg === 'object'); const filArgs = _.filter(arguments, v => typeof v === 'string'); //eslint-disable-line const params = hasParams ? lastArg : {}; const service = filArgs[0]; const serviceInstance = this.sdk[service]; this.isServiceSupported(service); const authClient = this.getAuthClient(); return authClient.authorize().then(() => { const requestParams = { auth: authClient }; // merge the params from the request call into the base functionParams _.merge(requestParams, params); return filArgs.reduce(((p, c) => p[c]), this.sdk).bind(serviceInstance)(requestParams) .then(result => result.data) .catch((error) => { if (error && error.errors && error.errors[0].message && _.includes(error.errors[0].message, 'project 1043443644444')) { throw new Error("Incorrect configuration. Please change the 'project' key in the 'provider' block in your Serverless config file."); } else if (error) { throw error; } }); }); } getAuthClient() { let credentials = this.serverless.service.provider.credentials || process.env.GOOGLE_APPLICATION_CREDENTIALS; const credParts = credentials.split(path.sep); if (credParts[0] === '~') { credParts[0] = os.homedir(); credentials = credParts.reduce((memo, part) => path.join(memo, part), ''); } const keyFileContent = fs.readFileSync(credentials).toString(); const key = JSON.parse(keyFileContent); return new google.auth .JWT(key.client_email, null, key.private_key, ['https://www.googleapis.com/auth/cloud-platform']); } isServiceSupported(service) { if (!_.includes(Object.keys(this.sdk), service)) { const errorMessage = [ `Unsupported service API "${service}".`, ` Supported service APIs are: ${Object.keys(this.sdk).join(', ')}`, ].join(''); throw new Error(errorMessage); } } } module.exports = GoogleProvider;
JavaScript
0.000001
@@ -173,16 +173,22 @@ %0Aconst p +luginP ackageJs @@ -219,16 +219,199 @@ .json'); + // eslint-disable-line import/newline-after-import%0Aconst googleApisPackageJson = require(require.resolve('googleapis/package.json')); // eslint-disable-line import/no-dynamic-require %0A%0Aconst @@ -820,32 +820,38 @@ luginVersion = p +luginP ackageJson.versi @@ -888,43 +888,37 @@ n = -packageJson.dependencies.googleapis +googleApisPackageJson.version ;%0A%0A
7dc55910c0b6c203fbb03d95bf957dd3d6517d6b
Change variable names from length to offset to be more accurate
lilt.js
lilt.js
/*! * lilt.js v0.1 (https://github.com/jimmylorunning/lilt.js) * Copyright (c) 2015 * Licensed under MIT (https://github.com/jimmylorunning/lilt.js/LICENSE) */ (function( $ ) { $.fn.liltMoveShadow = function(options) { return this.each(function() { console.log('hahaha'); var settings = $.extend({ 'horizontal-length': "-20px", 'blur-radius': "5px", 'spread-radius': "5px", 'shadow-color': "#999999", 'subtleness': "5" }, options, { 'horizontal-length': $(this).data("horizontal-length"), 'blur-radius': $(this).data("blur-radius"), 'spread-radius': $(this).data("spread-radius"), 'shadow-color': $(this).data("shadow-color"), 'subtleness': $(this).data("subtleness") } ); // avoid divide by zero & negative numbers if (settings['subtleness'] < 1) { settings['subtleness'] = 1; } scrollPos = $(window).scrollTop(); boxPos = $(this).offset().top; shadowPos = Math.ceil((boxPos - scrollPos) / settings['subtleness']); shadowStyle = settings['horizontal-length'] + ' ' + shadowPos + "px " + settings['blur-radius'] + ' ' + settings['spread-radius'] + ' ' + settings['shadow-color']; /* probably should test for vendor supported property: */ /* http://www.javascriptkit.com/javatutors/setcss3properties.shtml */ $(this).css('box-shadow', shadowStyle); $(this).css('-moz-box-shadow', shadowStyle); $(this).css('-webkit-box-shadow', shadowStyle); }); // .each } }( jQuery )); (function ( $, window, document, undefined ) { $.fn.lilt = function(options) { $(window).scroll( function() { $(".lilt").liltMoveShadow(options); }); } }(jQuery, window, document)); /* on page load, run lilt: $().lilt(); optional: set default options for your page: $().lilt( {'shadow-color': '#ff0000'} ); override individual tags with data attributes */
JavaScript
0.000001
@@ -259,37 +259,8 @@ %7B%0A%0A - console.log('hahaha');%0A @@ -307,22 +307,22 @@ izontal- -length +offset ': %22-20p @@ -341,33 +341,34 @@ 'blur-radius': %22 -5 +40 px%22,%0A 'sp @@ -382,17 +382,17 @@ dius': %22 -5 +0 px%22,%0A @@ -446,17 +446,17 @@ ness': %22 -5 +7 %22%0A @@ -489,22 +489,22 @@ izontal- -length +offset ': $(thi @@ -523,22 +523,22 @@ izontal- -length +offset %22),%0A @@ -902,16 +902,17 @@ scroll +Y Pos = $( @@ -941,16 +941,17 @@ box +Y Pos = $( @@ -976,25 +976,30 @@ ;%0A -shadowPos +verticalOffset = Math. @@ -1007,16 +1007,17 @@ eil((box +Y Pos - sc @@ -1020,16 +1020,17 @@ - scroll +Y Pos) / s @@ -1098,14 +1098,14 @@ tal- -length +offset '%5D + @@ -1115,17 +1115,22 @@ ' + -shadowPos +verticalOffset + %22 @@ -1636,24 +1636,64 @@ (options) %7B%0A + $(%22.lilt%22).liltMoveShadow(options);%0A $(window
2fbad002e2d9918f9ac4d0c9485c23754c48e68d
Add "bright" ansi escape code variations to deansi.
public/javascripts/lib/deansi.js
public/javascripts/lib/deansi.js
var Deansi = { // http://ascii-table.com/ansi-escape-sequences.php // http://cukes.info/gherkin/api/ruby/latest/Gherkin/Formatter/AnsiEscapes.html styles: { '0': null, '1': 'bold', '4': 'underscore', '30': 'black', '31': 'red', '32': 'green', '33': 'yellow', '34': 'blue', '35': 'magenta', '36': 'cyan', '37': 'white', '90': 'grey', '40': 'bg-black', '41': 'bg-red', '42': 'bg-green', '43': 'bg-yellow', '44': 'bg-blue', '45': 'bg-magenta', '46': 'bg-cyan', '47': 'bg-white', }, parse: function(string) { string = this.replace_escapes(string); string = this.replace_styles(string); string = this.remove_closings(string); string = this.parse_linefeeds(string); return string; }, replace_escapes: function(string) { string = string.replace(new RegExp(String.fromCharCode(27) + "\\(B", 'gm'), '') return string.replace(new RegExp(String.fromCharCode(27), 'gm'), ''); }, replace_styles: function(string) { var pattern = /\[(?:0;)?((?:1|4|30|31|32|33|34|35|36|37|90|40|41|42|43|44|45|46|47|;)+)m(.*?)(?=\[[\d;]*m|$)/gm; return string.replace(pattern, function(match, styles, string) { return '<span class="' + Deansi.to_styles(styles) + '">' + string + '</span>'; }); }, remove_closings: function(string) { return string.replace(/\[0?m/gm, ''); }, parse_linefeeds: function(string) { string = string.replace(/\[K\r/, "\r"); string = string.replace(/^.*\r(?!$)/gm, ''); return string; }, to_styles: function(string) { return _.compact(_.map(string.split(';'), function(number) { return Deansi.styles[number]; })).join(' '); }, };
JavaScript
0
@@ -380,12 +380,201 @@ ': ' -grey +black bright',%0A '31': 'red bright',%0A '32': 'green bright',%0A '33': 'yellow bright',%0A '34': 'blue bright',%0A '35': 'magenta bright',%0A '36': 'cyan bright',%0A '37': 'white bright ',%0A
d1270a98860859771e80d87083c784908a1f1d95
print lat lng
index.js
index.js
var express = require('express'); var bodyParser = require('body-parser') var app = express(); var sqlite3 = require('sqlite3').verbose(); var dbName = './trek.db'; var db = new sqlite3.Database(dbName); var request = require('request'); var googleMapsApi = 'http://maps.googleapis.com/maps/api/geocode/json?address=' app.use(bodyParser.json()); app.get('/', function (req, res) { res.send('Hello World!'); }); //Adds user if user doesn't exist. Updates username if user exists app.put('/user', function(req, res){ console.log(req.body); var stmt = db.prepare("INSERT OR REPLACE INTO users (id,username) VALUES (?, ?)"); stmt.run(req.body.id, req.body.name); stmt.finalize(); console.log("Added User"); db.each("SELECT id, username FROM users", function(err, row) { console.log(row.id + ": " + row.username); }); res.send(req.body); }); //Get a location if it exists. Creates a new one if not app.get('/loc', function(req, res){ console.log(req.body); request(googleMapsApi + req.body.zipcode, function (error, response, body) { if (!error && response.statusCode == 200) { console.log(body) // Show the HTML for the Google homepage. } }) // var stmt = db.prepare("INSERT OR REPLACE INTO locs (id,ta_id) VALUES (?, ?)"); // stmt.run(req.body.id, req.body.name); // stmt.finalize(); // console.log("Added Location"); // db.each("SELECT id, ta_id FROM locs", function(err, row) { // console.log(row.id + ": " + row.ta_id); // }); // res.send(req.body); }); //Returns json of all games in a given zip code app.get('/localGames', function(req, res){ console.log(req.body); var json; var games = []; var i = 0; db.all("SELECT id, end, points FROM games WHERE zipcode = " + req.body.zipcode, function(err, rows) { // rows.forEach(function (row) { // //console.log(row.imageUrl); // games[i] = row.imageUrl; // i++; // //console.log("Url added to array"); // }); json = JSON.stringify(rows); // console.log(games.toString()); console.log(json); res.type('text/plain'); res.send(json); }); }); //Returns a given players cumulative score app.get('/score', function(req, res){ console.log(req.body); var score = 0; var json; db.all("SELECT points FROM games WHERE winnerID = " + req.body.id, function(err, rows) { rows.forEach(function (row) { score += row.points; }); json = JSON.stringify({ value: score}); console.log(json); res.type('text/plain'); res.send(json); }); }); var server = app.listen(80, function () { var host = server.address().address; var port = server.address().port; console.log('Example app listening at http://%s:%s', host, port); });
JavaScript
0.999999
@@ -967,16 +967,51 @@ q.body); +%0A%09var location;%0A%09var lat;%0A%09var lng; %0A%0A%09reque @@ -1135,24 +1135,128 @@ %0A%09%09%09 -console.log(body +location = body.results.geometry.location;%0A%09%09%09lat = location.lat;%0A%09%09%09lng = location.lng;%0A%09%09%09console.log(lat + %22, %22 + lng ) //
3a3f80b405c1b6034a76bc93cf1774e79c35da90
Correct count for test
test/test-refugee-counts-model.js
test/test-refugee-counts-model.js
var assert = require('assert'); var should = require('should'); var fs = require('fs'); var moment = require('moment'); var RefugeeCountsModel = require('../src/js/model/refugee-counts-model.js'); // for some reason the "total values" // http://popstats.unhcr.org/en/asylum_seekers_monthly // displays invalid sums // // also the csv export has some more values than the // web view // lastDayStamp = function(year, month) { return moment([year, month + 1, 1]).subtract(1, 'days').unix(); } describe('RefugeeCountsModel', function() { var stamp = moment([2015, 10, 21]).unix(); var data = JSON.parse(fs.readFileSync('temp/data-assets/asylum.json')); var model = new RefugeeCountsModel(data); describe('asylumData', function() { it('correct total for germany during jan 2015', function() { assert.equal(data .filter(function(item) { return item.ac == "DEU" && item.year==2012 && item.month==1}) .reduce(function(prev, val) { return prev + val.count}, 0), 4667); }); }) describe('pairCountsByDestination', function() { it('correct total for AFG -> DEU @ jan 2015', function() { assert.equal(model.pairCountsByDestination['DEU']['AFG'][3][0].count, 1129); }); }); describe('getTotalDestinationCounts', function() { it('correct total for germany after jan 2015', function() { assert.equal(model.getTotalDestinationCounts( 'DEU', moment([2012, 0, 31]).unix()).asylumApplications, 4667); }); it('correct total for germany at end of 2014', function() { assert.equal(model.getTotalDestinationCounts('DEU', moment([2014, 11, 31]).unix()) .asylumApplications, 346633); }); it('correct total for finland at end of 2014', function() { assert.equal(model.getTotalDestinationCounts('FIN', moment([2014, 11, 31]).unix()) .asylumApplications, 8894); }); }); describe('getOriginCountsByDestinationCountries()', function() { it('correct total for SYR->GER after one months end', function() { assert.equal(model.getOriginCountsByDestinationCountries( 'SYR', lastDayStamp(2012, 0))['DEU'].asylumApplications, 210); }); it('correct total for SYR->GER after two months end', function() { assert.equal(model.getOriginCountsByDestinationCountries( 'SYR', lastDayStamp(2012, 1))['DEU'].asylumApplications, 440); }); }); describe('getDestinationCountsByOriginCountries()', function() { it('correct total for SYR->GER after one months end', function() { assert.equal(model.getDestinationCountsByOriginCountries( 'DEU', lastDayStamp(2012, 0))['SYR'].asylumApplications, 210); }); it('correct total for SYR->GER after two months end', function() { assert.equal(model.getDestinationCountsByOriginCountries( 'DEU', lastDayStamp(2012, 1))['SYR'].asylumApplications, 440); }); }); });
JavaScript
0.000001
@@ -1188,11 +1188,11 @@ t, 1 -129 +248 );%0A%09
a9305037939052f8305248a1f518711d4e81d08e
Update colors-almost-equal threshold
test/unit/ColorConversionTests.js
test/unit/ColorConversionTests.js
const {test, Test} = require('tap'); const {rgbToHsv, hsvToRgb} = require('../../src/util/color-conversions'); Test.prototype.addAssert('colorsAlmostEqual', 2, function (found, wanted, message, extra) { /* eslint-disable no-invalid-this */ message += `: found ${JSON.stringify(Array.from(found))}, wanted ${JSON.stringify(Array.from(wanted))}`; // should always return another assert call, or // this.pass(message) or this.fail(message, extra) if (found.length !== wanted.length) { return this.fail(message, extra); } for (let i = 0; i < found.length; i++) { if (Math.abs(found[i] - wanted[i]) > 1e-3) { return this.fail(message, extra); } } return this.pass(message); /* eslint-enable no-invalid-this */ }); test('RGB to HSV', t => { const dst = [0, 0, 0]; t.colorsAlmostEqual(rgbToHsv([255, 255, 255], dst), [0, 0, 1], 'white'); t.colorsAlmostEqual(rgbToHsv([0, 0, 0], dst), [0, 0, 0], 'black'); t.colorsAlmostEqual(rgbToHsv([127, 127, 127], dst), [0, 0, 0.498], 'grey'); t.colorsAlmostEqual(rgbToHsv([255, 255, 0], dst), [0.167, 1, 1], 'yellow'); t.colorsAlmostEqual(rgbToHsv([1, 0, 0], dst), [0, 1, 0.00392], 'dark red'); t.end(); }); test('HSV to RGB', t => { const dst = new Uint8ClampedArray(3); t.colorsAlmostEqual(hsvToRgb([0, 1, 1], dst), [255, 0, 0], 'red'); t.colorsAlmostEqual(hsvToRgb([1, 1, 1], dst), [255, 0, 0], 'red (hue of 1)'); t.colorsAlmostEqual(hsvToRgb([0.5, 1, 1], dst), [0, 255, 255], 'cyan'); t.colorsAlmostEqual(hsvToRgb([1.5, 1, 1], dst), [0, 255, 255], 'cyan (hue of 1.5)'); t.colorsAlmostEqual(hsvToRgb([0, 0, 0], dst), [0, 0, 0], 'black'); t.colorsAlmostEqual(hsvToRgb([0.5, 1, 0], dst), [0, 0, 0], 'black (with hue and saturation)'); t.colorsAlmostEqual(hsvToRgb([0, 1, 0.00392], dst), [1, 0, 0], 'dark red'); t.end(); });
JavaScript
0.000004
@@ -588,24 +588,111 @@ gth; i++) %7B%0A + // smallest meaningful difference--detects changes in hue value after rounding%0A if ( @@ -727,13 +727,19 @@ %5D) %3E - 1e-3 += 0.5 / 360 ) %7B%0A
d889a1500bdf6824a06c00f9a0304ec201be31d0
Make sure events are working correctly on front page
public/javascripts/views/home.js
public/javascripts/views/home.js
define([ 'zepto', 'Underscore', 'Backbone', 'models/expenses', 'text!../../tpl/home.html' ], function ($, _, Backbone, Expenses, template) { var HomeView = Backbone.View.extend({ events:{ "click #get":"refresh" }, initialize: function(){ this.bind(); this.refresh(); }, render: function () { this.el=_.template(template,{'models':this.model.toJSON()}); this.slot.html(this.el); return this; }, refresh: function(){ this.model.fetch(); }, bind: function(){ this.model.on('reset',this.render,this); this.model.on('add', this.render,this); this.model.on('remove',this.render, this); } }); return new HomeView({model:new Expenses()}); });
JavaScript
0.000001
@@ -264,16 +264,181 @@ refresh%22 +,%0A %22click tr%22: %22navigate_row%22%0A%0A %7D,%0A navigate_row: function (event)%7B%0A $(event.currentTarget).find('a')%5B0%5D.click(); %0A @@ -437,33 +437,32 @@ %0A %7D,%0A -%0A init @@ -617,11 +617,17 @@ his. +$ el -= +.html( _.te @@ -669,24 +669,25 @@ l.toJSON()%7D) +) ;%0A
75d3ba66dbc6d3173fda5d1399f7754b5730c0f0
Update nightwatch.conf.js
nightwatch.conf.js
nightwatch.conf.js
const { SAUCE_USERNAME, SAUCE_ACCESS_KEY, TRAVIS_JOB_NUMBER, TRAVIS_BRANCH, TRAVIS_PULL_REQUEST } = process.env; module.exports = { src_folders: "test/browser", output_folder: "test_report", custom_commands_path: "test/nightwatch_custom", test_workers: { enabled: true, workers: "auto", }, test_settings: { default: { launch_url: "http://localhost", selenium_host: "ondemand.saucelabs.com", selenium_port: 80, webdriver: { username: SAUCE_USERNAME, access_key: SAUCE_ACCESS_KEY, default_path_prefix: "/wd/hub", }, desiredCapabilities: { javascriptEnabled: true, acceptSslCerts: true, "tunnel-identifier": TRAVIS_JOB_NUMBER, ...(TRAVIS_BRANCH === "master" && TRAVIS_PULL_REQUEST === "false" ? { build: `build-${ TRAVIS_JOB_NUMBER }` } : {}) }, }, chrome: { desiredCapabilities: { platform: "Windows 10", browserName: "chrome", version: "latest", }, }, chrome_old: { desiredCapabilities: { platform: "Windows 10", browserName: "chrome", version: "latest-1", }, }, firefox: { desiredCapabilities: { platform: "Windows 10", browserName: "firefox", version: "latest", }, }, firefox_old: { desiredCapabilities: { platform: "Windows 10", browserName: "firefox", version: "latest-1", }, }, firefox_esr: { desiredCapabilities: { platform: "Windows 10", browserName: "firefox", version: "68.0", }, }, edge: { desiredCapabilities: { platform: "Windows 10", browserName: "MicrosoftEdge", version: "latest", }, }, edge_old: { desiredCapabilities: { platform: "Windows 10", browserName: "MicrosoftEdge", version: "latest-1", }, }, safari: { desiredCapabilities: { platform: "macOS 10.14", browserName: "safari", version: "latest", }, }, safari_old: { desiredCapabilities: { platform: "macOS 10.13", browserName: "safari", version: "latest", }, }, }, };
JavaScript
0.000001
@@ -250,84 +250,8 @@ %22,%0A%0A - test_workers: %7B%0A enabled: true,%0A workers: %22auto%22,%0A %7D,%0A%0A @@ -2445,9 +2445,9 @@ 10.1 -4 +5 %22,%0A @@ -2644,9 +2644,9 @@ 10.1 -3 +4 %22,%0A
dbcca58e83bf0c5927b5b4a74c79ad94800c595a
Correct sample encoding
index.js
index.js
var _ = require('lodash-node'), zlib = require('zlib'), spawn = require('child_process').spawn; exports.record = function (options, callback) { var recording = ''; var defaults = { sampleRate: 16000, compress: false }; if (_.isFunction(options)) callback = options; options = _.merge(options, defaults); // capture audio stream var cmd = 'sox'; var cmdArgs = [ '-q', '-b','16', '-d','-t','wav','-', 'rate','16000','channels','1', 'silence','1','0.1',(options.threshold || '0.1')+'%','1','1.0',(options.threshold || '0.1')+'%' ]; console.log('Recording...'); var rec = spawn(cmd, cmdArgs, 'pipe'); // process stdout rec.stdout.setEncoding('binary'); rec.stdout.on('data', function (data) { console.log('Receiving data...'); recording += data; }); // exit recording rec.on('close', function (code) { var buff = new Buffer(recording, 'binary'); callback(null, buff); }); }; exports.compress = function (input, callback) { console.log('Compressing...'); console.time('Compressed'); zlib.gzip(input, function (err, result) { console.timeEnd('Compressed'); console.log('Compressed size:', result.length, 'bytes'); if (err) callback(err); callback(null, result); }); };
JavaScript
0.00001
@@ -384,11 +384,11 @@ = ' -sox +rec ';%0A @@ -417,83 +417,364 @@ -q', + // show no progress %0A '- -b +r ', + '16 -', +000', // sample rate %0A '- -d','-t','wav','- +c', '1', // channels%0A '-e', 'signed-integer ', -%0A - 'rate +// sample encoding%0A '-b ', + '16 -000','channels','1', +', // precision (bits)%0A '-t', 'wav', // audio type%0A '-', // pipe%0A // end on silence %0A @@ -784,16 +784,17 @@ ilence', + '1','0.1 @@ -795,16 +795,17 @@ ','0.1', + (options @@ -828,13 +828,31 @@ .1') -+ + + '%25', +%0A '1', @@ -857,16 +857,17 @@ ','1.0', + (options @@ -886,17 +886,19 @@ %7C '0.1') -+ + + '%25'%0A %5D;
156e28952ded6c3d0a73b1eb0a6cdcfadee07b4c
row.length can be <= limit
index.js
index.js
'use strict'; module.exports = maxLen; function maxLen (string, warningLength, errorLength) { return string.split('\n').map(function (row, index) { var line = index + 1; if (row.length < warningLength) { return false; } if (row.length < errorLength) { return { fatal: false, line: line, message: 'Line ' + line + ' exceeds the recommended line length of ' + warningLength + '.', ruleId: 'max-len', severity: 1 }; } return { fatal: false, line: line, message: 'Line ' + line + ' exceeds the maximum line length of ' + errorLength + '.', ruleId: 'max-len', severity: 2 }; }).filter(Boolean); }
JavaScript
0.999995
@@ -191,16 +191,17 @@ length %3C += warning @@ -256,16 +256,17 @@ length %3C += errorLe
9a2f96c6741bf824220a1d272b39c1b3792f641a
Optimize processing of _is_capacity_full to execute earlier; Write annotations
index.js
index.js
var ___ = '___send-to-shoulder___'; var _ = '_hole_'; var log = 1 ? console.log : function(){} ; var purry = module.exports = function(f){ if (f.length === 0) throw new Error('purry is not compatible with variable-argument functions.') var initial_stock = []; var i = f.length; while(i > 0){ initial_stock.push(_); i--; } return accumulate_arguments(f, f.length, 0, initial_stock, 0, f.length - 1, false); }; // @f –– The wrapped function // @capacity –– The param count of f // @_capacity_used –– The remaining holes of _stock // @_stock –– The plugged holes so far // @_stock_i_min –– The minimum index to start stocking at. function accumulate_arguments(f, capacity, _capacity_used, _stock, _stock_i_min, _stock_i_max, _f_has_holes){ return function(){ var arguments_count = arguments.length; // Bail ASAP if no arguments given if (!arguments_count) { return capacity === _capacity_used ? f.apply(null, _stock) : accumulate_arguments(f, capacity, _capacity_used, _stock, _stock_i_min, _stock_i_max, _f_has_holes) ; } // TODO? Bail ASAP if all arguments given in single shot // if (!_capacity_used && arguments_count === capacity) // index for various loops below var i; // log('\n\nInvoked: capacity %d | instance capacity %d | stock %j | new args %j', capacity, capacity - _capacity_used, _stock, arguments) // Cloning, to avoid clobbering var stock = []; var _stock_count = _stock.length; i = 0; while(i < _stock_count) { stock[i] = _stock[i]; i++; } // Shadowing, to avoid clobbering var capacity_used = _capacity_used; var stock_i_min = _stock_i_min; var stock_i_max = _stock_i_max; var f_has_holes = _f_has_holes; var is_delayed_execution = false; var argument; var stock_i = stock_i_min; var incby = 1; var endloop = arguments_count; var limit = stock_i_max + 1; process_new_arguments: for(i = 0; i !== endloop; i += incby) { // log('\nend condition: %d !== %d | stock_i: %d', i, endloop, stock_i); argument = arguments[i]; if (argument === _) { is_delayed_execution = true; if (i + incby === endloop) break; f_has_holes = true; stock_i += incby // log('Hit Hole _, offset @ %d'); continue; } if (argument === ___) { is_delayed_execution = true; if (i + incby === endloop) break; incby = -1; stock_i = stock_i_max; limit = stock_i_min - 1; // log('Hit shoulder ___ of size (%d)', (arguments_count - (i + 1))); endloop = i; i = arguments_count; continue; } if (f_has_holes) { while (stock[stock_i] !== _) { if (stock_i === limit) break process_new_arguments; stock_i += incby; } } // log('Add argument: %j @ i%d', argument, stock_i); stock[stock_i] = argument; // log('stock: %j', stock); if (stock_i_min === stock_i) stock_i_min++; if (stock_i_max === stock_i) stock_i_max--; capacity_used++; stock_i += incby; } // log('\nProcessing Complete. ') // log('Not applicable, stock: %j', stock); // log('Applicable! %j', stock); return is_delayed_execution || capacity !== capacity_used ? accumulate_arguments(f, capacity, capacity_used, stock, stock_i_min, stock_i_max, f_has_holes) : f.apply(null, stock) ; }; } purry._ = _; purry.___ = ___; purry.install = function(symbol_, symbol___){ purry.installSyntax(symbol_, symbol___); Function.prototype.purry = purry; }; purry.installSyntax = function(symbol_, symbol___){ GLOBAL[symbol_ || '_'] = _; GLOBAL[symbol___ || '___'] = ___; };
JavaScript
0.000001
@@ -754,16 +754,71 @@ holes)%7B%0A + var _is_capacity_full = capacity === _capacity_used;%0A return @@ -830,16 +830,16 @@ tion()%7B%0A - var @@ -955,29 +955,19 @@ return -capacity === +_is _capacit @@ -960,36 +960,36 @@ rn _is_capacity_ -used +full ?%0A f.app @@ -2215,32 +2215,124 @@ ecution = true;%0A + // If _ is last argument it has no affect%0A // other than delaying execution.%0A if (i + @@ -2884,32 +2884,210 @@ ock_i%5D !== _) %7B%0A + // If an argument falls out of bounds, discard it.%0A // Also discard everything after, because all subsequent%0A // arguments will be out of bounds too.%0A if (st @@ -3175,24 +3175,105 @@ %7D%0A %7D%0A%0A + // With an argument and and its resolved index in hand,%0A // stock it!%0A // log @@ -3365,32 +3365,308 @@ // -log('stock: %25j', stock); +Take note of new argument minimum/maximums.%0A // For example if the min is at 0 and we fill 0 we know we can%0A // never fill it again.%0A // These markers allow subsequent invocation to start/stop%0A // stock_i at optimized points meaning a certain amount of%0A // loops are skipped. %0A @@ -3781,24 +3781,24 @@ ity_used++;%0A - stock_ @@ -3805,24 +3805,58 @@ i += incby;%0A + // log('stock: %25j', stock);%0A %7D%0A%0A%0A
77923d1a6037b9812cfb1f13b80f1db246a7a5df
Add URI fragment decoding in order to allow usage of PEM content in there too. (it was originally meant only for hexadecimal content which needs no encoding)
index.js
index.js
/*jshint browser: true, strict: true, globalstrict: true, indent: 4, immed: true, latedef: true, undef: true, regexdash: false */ /*global Hex, Base64, ASN1 */ "use strict"; var maxLength = 10240, reHex = /^\s*(?:[0-9A-Fa-f][0-9A-Fa-f]\s*)+$/, tree = id('tree'), dump = id('dump'), wantHex = id('wantHex'), area = id('area'), file = id('file'), hash = null; function id(elem) { return document.getElementById(elem); } function text(el, string) { if ('textContent' in el) el.textContent = string; else el.innerText = string; } function decode(der) { tree.innerHTML = ''; dump.innerHTML = ''; try { var asn1 = ASN1.decode(der); tree.appendChild(asn1.toDOM()); if (wantHex.checked) dump.appendChild(asn1.toHexDOM()); var hex = (der.length < maxLength) ? asn1.toHexString() : ''; if (area.value === '') area.value = hex; try { window.location.hash = hash = '#' + hex; } catch (e) { // fails with "Access Denied" on IE with URLs longer than ~2048 chars window.location.hash = hash = '#'; } } catch (e) { text(tree, e); } } function decodeArea() { try { var val = area.value, der = reHex.test(val) ? Hex.decode(val) : Base64.unarmor(val); decode(der); } catch (e) { text(tree, e); dump.innerHTML = ''; } } function decodeBinaryString(str) { var der; try { if (reHex.test(str)) der = Hex.decode(str); else if (Base64.re.test(str)) der = Base64.unarmor(str); else der = str; decode(der); } catch (e) { text(tree, 'Cannot decode file.'); dump.innerHTML = ''; } } function clearAll() { area.value = ''; tree.innerHTML = ''; dump.innerHTML = ''; hash = window.location.hash = ''; } // this is only used if window.FileReader function read(f) { area.value = ''; // clear text area, will get hex content var r = new FileReader(); r.onloadend = function () { if (r.error) alert("Your browser couldn't read the specified file (error code " + r.error.code + ")."); else decodeBinaryString(r.result); }; r.readAsBinaryString(f); } function load() { if (file.files.length === 0) alert("Select a file to load first."); else read(file.files[0]); } function loadFromHash() { if (window.location.hash && window.location.hash != hash) { hash = window.location.hash; area.value = hash.substr(1); decodeArea(); } } function stop(e) { e.stopPropagation(); e.preventDefault(); } function dragAccept(e) { stop(e); if (e.dataTransfer.files.length > 0) read(e.dataTransfer.files[0]); } // main if ('onhashchange' in window) window.onhashchange = loadFromHash; loadFromHash(); document.ondragover = stop; document.ondragleave = stop; if ('FileReader' in window) { file.style.display = 'block'; file.onchange = load; document.ondrop = dragAccept; }
JavaScript
0
@@ -2610,29 +2610,264 @@ -area.value = +// Firefox is not consistent with other browsers and return an%0A // already-decoded hash string so we risk double-decoding here,%0A // but since %25 is not allowed in base64 nor hexadecimal, it's ok%0A area.value = decodeURIComponent( hash.sub @@ -2872,16 +2872,17 @@ ubstr(1) +) ;%0A @@ -3372,9 +3372,8 @@ cept;%0A%7D%0A -%0A
624f88f8d82f5a343cc42d85a9d5cf9b5b6d6a11
Update app.js
assets/app.js
assets/app.js
--- --- {% include_relative _js/index.js %}
JavaScript
0.000002
@@ -2,16 +2,21 @@ --%0A---%0A%0A +%3C!-- %7B%25 inclu @@ -42,8 +42,13 @@ ex.js %25%7D + --%3E%0A
11e305447ee9001d130f0876a45019646e661998
fix missing labels property on exported models
index.js
index.js
var conversions = require('./conversions'); var route = require('./route'); var convert = {}; var models = Object.keys(conversions); function wrapRaw(fn) { var wrappedFn = function (args) { if (args === undefined || args === null) { return args; } if (arguments.length > 1) { args = Array.prototype.slice.call(arguments); } return fn(args); }; // preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } function wrapRounded(fn) { var wrappedFn = function (args) { if (args === undefined || args === null) { return args; } if (arguments.length > 1) { args = Array.prototype.slice.call(arguments); } var result = fn(args); // we're assuming the result is an array here. // see notice in conversions.js; don't use box types // in conversion functions. if (typeof result === 'object') { for (var len = result.length, i = 0; i < len; i++) { result[i] = Math.round(result[i]); } } return result; }; // preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } models.forEach(function (fromModel) { convert[fromModel] = {}; Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); var routes = route(fromModel); var routeModels = Object.keys(routes); routeModels.forEach(function (toModel) { var fn = routes[toModel]; convert[fromModel][toModel] = wrapRounded(fn); convert[fromModel][toModel].raw = wrapRaw(fn); }); }); module.exports = convert;
JavaScript
0.000001
@@ -1344,16 +1344,110 @@ nnels%7D); +%0A%09Object.defineProperty(convert%5BfromModel%5D, 'labels', %7Bvalue: conversions%5BfromModel%5D.labels%7D); %0A%0A%09var r
95068fe0ac71efff3243cab33069fd6dc71d7e03
Add printInterpolations and scanList options
index.js
index.js
#! /usr/bin/env node const program = require('commander') const colors = require('colors') const configResolver = require('./src/configResolver') const configWriter = require('./src/configWriter') const interpolationResolver = require('./src/interpolationResolver') const hooks = require('./src/hooks') let configElement = '_default' function handleHook (element, acc) { acc.push(element) return acc } // Set up and parse program arguments. // We only really care about the first positional argument // giving use the correct config to use program .arguments('[configElement]') .action(_configElement => { configElement = _configElement }) .option('-s, --scan', 'Automatically detect interpolatinos from content') .option('-l, --list', 'List available typical recipes recipes') .option('-p, --print', 'Print the config selected config element to stdout') .option( '-h, --hook <input>', 'One or more files with hooks.', handleHook, [] ) .option( '-d, --disable-interpolation', 'Disables all handling of interpolation. ' + 'If -s/--scan is enabled simultaneously, it will be ignored') .parse(process.argv) // Merge regular config file and folder config let config = Object.assign( {}, configResolver.resolve(), configResolver.resolveFolderConfig() ) // We have hooks to initialize if (program.hook) { hooks.initialize(program.hook) } // If list is true, we simply list the available recipes if (program.list) { console.log(colors.green('Available typical recipes:')) Object.keys(config).forEach(element => { console.log(colors.gray(' + ' + element.toString())) }) process.exit(0) } // Does it exist? if (!config[configElement]) { console.error(colors.red('Found no recipe named \'' + configElement + '\' in resolved config')) process.exit(1) } let resolvedElement = config[configElement] if (program.disableInterpolation) { resolvedElement.__disableInterpolations__ = true } // If print is true, we simply print the recipe, and exit if (program.print) { console.log(colors.green('Typical recipe ') + '"' + colors.cyan(configElement) + '"') console.log(colors.gray(JSON.stringify(resolvedElement, null, 2))) process.exit(0) } if (!program.disableInterpolation && program.scan) { interpolationResolver.scan(resolvedElement, (result) => { resolvedElement.__interpolations__ = (resolvedElement.__interpolations__ || []).concat(result) configWriter.write(resolvedElement) }) } else { configWriter.write(resolvedElement) }
JavaScript
0
@@ -722,24 +722,207 @@ m content')%0A + .option('-S, --scan-list', 'Automatically detect interpolatinos from content, and print them to stdout.')%0A .option('-I, --print-interpolations', 'Print interpolations for recipe')%0A .option('- @@ -2247,73 +2247,438 @@ s.gr -een('Typical recipe ') + '%22' + colors.cyan(configElement) + '%22')%0A +ay(JSON.stringify(resolvedElement, null, 2)))%0A process.exit(0)%0A%7D%0A%0A// If printInterpolations is true, we print the interpolations config of the recipe%0Aif (program.printInterpolations) %7B%0A console.log(colors.gray(JSON.stringify(resolvedElement.__interpolations__, null, 2)))%0A process.exit(0)%0A%7D%0A%0A// If we scanList is true, we scan and then print.%0Aif (program.scanList) %7B%0A interpolationResolver.scan(resolvedElement, result =%3E %7B%0A co @@ -2706,32 +2706,40 @@ (JSON.stringify( +%0A ( resolvedElement, @@ -2733,35 +2733,98 @@ olvedElement -, null, 2)) +.__interpolations__ %7C%7C %5B%5D).concat(result),%0A null,%0A 2%0A )))%0A %7D )%0A process.
fdf3e01f9861b32089742676330938bf6bb208ab
use babylon, add `.file` method
index.js
index.js
/*! * babel-extract-comments <https://github.com/jonschlinkert/babel-extract-comments> * * Copyright (c) 2014 Jon Schlinkert, contributors. * Licensed under the MIT license. */ 'use strict'; /** * Extract code comments from the given `string`. * * ```js * var extract = require('babel-extract-comments'); * extract('// this is a code comment'); * ``` * @param {String} `string` String of javascript * @param {Function} `fn` Optional. Function to transform commend objects (AST tokens) * @return {Object} Object of code comments. * @api public */ module.exports = function(str, fn) { var babel = require('babel-core'); var res = babel.transform(str, { ast: true, comments: true, code: false }); var comments = res.ast.comments; var len = comments.length, i = -1; while (++i < len) { var comment = comments[i]; comment.range = [comment.start, comment.end]; if (typeof fn === 'function') { var obj = fn(comment); if (obj) { comment = obj; } } } return comments; };
JavaScript
0.000001
@@ -105,16 +105,22 @@ (c) 2014 +-2018, Jon Sch @@ -130,32 +130,18 @@ kert -, contributors.%0A * Licen +.%0A * Relea sed @@ -154,17 +154,17 @@ the MIT -l +L icense.%0A @@ -183,16 +183,109 @@ rict';%0A%0A +const fs = require('fs');%0Aconst path = require('path');%0Aconst babylon = require('babylon');%0A%0A /**%0A * E @@ -397,16 +397,28 @@ s');%0A * +console.log( extract( @@ -449,181 +449,427 @@ nt') +) ;%0A * -%60%60%60%0A * @param %7BString%7D %60string%60 String of javascript%0A * @param %7BFunction%7D %60fn%60 Optional. Function to transform commend objects (AST tokens)%0A * @return %7BObject%7D Object +// %5B%7B type: 'CommentBlock',%0A * // value: '!%5Cn * babel-extract-comments %3Chttps://github.com/jonschlinkert/babel-extract-comments%3E%5Cn *%5Cn *%0A * // Copyright (c) 2014-2018, Jon Schlinkert.%5Cn * Released under the MIT License.%5Cn ',%0A * // start: 0,%0A * // end: 173,%0A * // loc: SourceLocation %7B start: %5BPosition%5D, end: %5BPosition%5D %7D %7D%5D%0A * %60%60%60%0A * @param %7BString%7D %60string%60 String of javascript%0A * @return %7BArray%7D Array of @@ -880,16 +880,23 @@ comment + object s.%0A * @a @@ -914,491 +914,879 @@ */%0A%0A -module.exports = function(str, fn) %7B%0A var babel = require('babel-core');%0A var res = babel.transform(str, %7B%0A ast: true,%0A comments: true,%0A code: false%0A %7D);%0A%0A var comments = res.ast.comments;%0A var len = comments.length, i = -1;%0A while (++i %3C len) %7B%0A var comment = comments%5Bi%5D;%0A comment.range = %5Bcomment.start, comment.end%5D;%0A if (typeof fn === 'function') %7B%0A var obj = fn(comment);%0A if (obj) %7B%0A comment = obj;%0A %7D%0A %7D%0A %7D%0A return comments;%0A%7D +function extract(str, options) %7B%0A const res = babylon.parse(str, options);%0A return res.comments;%0A%7D%0A%0A/**%0A * Extract code comments from a JavaScript file.%0A *%0A * %60%60%60js%0A * console.log(extract.file('some-file.js'), %7B cwd: 'some/path' %7D);%0A * // %5B %7B type: 'Line',%0A * // value: ' this is a line comment',%0A * // range: %5B 0, 25 %5D,%0A * // loc: %7B start: %7B line: 1, column: 0 %7D, end: %7B line: 1, column: 25 %7D %7D %7D %5D%0A * %60%60%60%0A * @param %7BString%7D %60file%60 Filepath to the file to parse.%0A * @param %7BObject%7D %60options%60 Options to pass to %5Besprima%5D%5B%5D.%0A * @return %7BArray%7D Array of code comment objects.%0A * @api public%0A */%0A%0Aextract.file = function(file, options) %7B%0A const opts = Object.assign(%7B cwd: process.cwd() %7D, options);%0A const str = fs.readFileSync(path.resolve(opts.cwd, file), 'utf8');%0A return extract(str, options);%0A%7D;%0A%0A/**%0A * Expose %60extract%60%0A */%0A%0Amodule.exports = extract ;%0A
1ea3016d933248edec7179645542a458dfec3818
declare strict mode
index.js
index.js
#! /usr/bin/env node const config = require('./config.json'); const dash_button = require('node-dash-button'); // TODO: accept and register an array of button MACs const dash = dash_button(config.button.id); const util = require('util'); const _ = require('lodash'); const when = require('when'); // Twilio Credentials const accountSid = config.twilio.sid; const authToken = config.twilio.token; //require the Twilio module and create a REST client const client = require('twilio')(accountSid, authToken); console.log('twilio client created.'); /*** * * @param to : any number Twilio can deliver to * @param from : A number you bought from Twilio and can use for outbound communication * @param message : text message to send * @returns {*} : a promise which resolves in to single twilio response, an array of twilio responses or a twilio error */ const sendSms = function (to, from, message) { if (_.isArray(to)) { let promiseArray = []; for (let i = 0; i < to.length; i++) { promiseArray.push(sendSms(to[i], from, message)); } return when.settle(promiseArray).then((descriptors) => { let successful = []; for (let i = 0; i < descriptors.length; i++) { if (descriptors[i].state === 'fulfilled') { successful.push(descriptors[i].value); } else { console.log(`twilio API error: ${descriptors[i].reason}`); } } console.log(`Sent ${successful.length} out of ${promiseArray.length} successfully.`); return successful; }).catch((err) => { console.log(`Error with when.settle in sendSms(): ${util.inspect(err, false, null)}`); return new Error(`Error with when.settle in sendSms(): ${util.inspect(err, false, null)}`); }); } else { return new Promise((resolve, reject) => { client.messages.create({ to: to, from: from, body: message }, (err, message) => { if (err) { console.log(`twilio api error: ${util.inspect(err, false, null)}`); reject(err); } else { console.log(`twilio response: ${util.inspect(message, false, null)}`); resolve(message); } }); }); } }; console.log('waiting for dash button to be pressed...'); dash.on('detected', () => { console.log('Dash button detected!'); // for now we can ignore the promise as it handles any logging and we've no need to care about when it resolves or rejects sendSms(config.message.to, config.message.from, config.message.body) .then((response) => { // }) .catch((err) => { // }); });
JavaScript
0.00415
@@ -899,16 +899,32 @@ sage) %7B%0A + %22use strict%22;%0A if (_.
541fd81e2bee72af21c423923c4f304a9db2500a
fix processing of options
index.js
index.js
'use strict'; var Download = require('download'); var RELEASE_BASE_URL = 'http://wordpress.org/wordpress-'; var wp = require('./wp'); function getLatestVersion(requestedVersion, cb) { if (requestedVersion) { process.nextTick(function() { cb(null, requestedVersion); }) } else { wp.getLatestVersion(function(err, latestVersion) { if (err) { return cb(err); } cb(null, latestVersion); }); } } module.exports = function(options, callback) { options = options || {}; if (typeof options === 'string') { options = {version: options}; } getLatestVersion(options.version, function(_, version) { if (!version) { if (callback) { return callback(new Error('No version specified.')); } throw new Error('No version specified.'); } options.version = version; if (!options.format) { options.format = 'zip'; } if (typeof options.extract === 'undefined') { options.extract = true; } if (options.extract) { options.dir = (options.dir || './wordpress-{version}').replace('{version}', options.version); } var archiveUrl = RELEASE_BASE_URL + options.version + '.' + options.format; var download = new Download({extract: !!options.extract, strip: 1 }).get(archiveUrl); if (options.extract || options.dir) { download.dest(options.dir); } download.run(callback); }); };
JavaScript
0.000001
@@ -497,36 +497,8 @@ %7B%0A -options = options %7C%7C %7B%7D;%0A%0A if ( @@ -551,24 +551,142 @@ version: + options%7D;%0A %7D%0A else if (typeof options === 'function') %7B%0A callback = options;%0A options = null;%0A %7D%0A options = options %7D;%0A %7D%0A%0A @@ -677,22 +677,23 @@ options -%7D;%0A %7D + %7C%7C %7B%7D; %0A%0A getL
9f00996ffab1026b46862ad61a772c8c661641fb
Make compatible with hydro 0.6
index.js
index.js
/** * External dependencies. */ var Formatter = require('hydro-formatter'); /** * Dot formatter. * * @constructor */ var Dot = Formatter.extend(); /** * Before all tests. * * @param {Array} tests * @api public */ Dot.prototype.beforeAll = function(tests) { this.println(); this.print(this.padding); }; /** * After each test. * * @param {Object} test * @api public */ Dot.prototype.afterTest = function(test) { var status = test.failed ? 'red' : 'green'; this.print(this.color(status, '.')); }; /** * After all tests. * * @param {Result} test result * @api public */ Dot.prototype.afterAll = function(result) { this.println(); this.displayResult(result); this.displayFailed(result); }; /** * Primary export. */ module.exports = Dot;
JavaScript
0
@@ -182,32 +182,8 @@ %0A *%0A - * @param %7BArray%7D tests%0A * @ @@ -233,21 +233,16 @@ unction( -tests ) %7B%0A th @@ -401,16 +401,44 @@ test) %7B%0A + if (test.skipped) return;%0A var st @@ -549,39 +549,8 @@ %0A *%0A - * @param %7BResult%7D test result%0A * @ @@ -599,22 +599,16 @@ unction( -result ) %7B%0A th @@ -642,22 +642,16 @@ yResult( -result );%0A thi @@ -670,14 +670,8 @@ led( -result );%0A%7D
40992a7f76d1732c0bf67b7ad3f7e579aad385b3
Update node test
node-test/index.js
node-test/index.js
import { createRequire } from 'module'; const require = createRequire(import.meta.url); const xterm = require('xterm-core'); console.log('Creating xterm-core terminal...'); const terminal = new xterm.Terminal(); console.log('Writing `ls` to terminal...') terminal.write('ls', () => { const bufferLine = terminal.buffer.normal.getLine(terminal.buffer.normal.cursorY); const contents = bufferLine.translateToString(); console.log(`Contents of terminal active buffer are: ${contents}`); // ls });
JavaScript
0.000001
@@ -87,21 +87,24 @@ ;%0Aconst -xt +T erm +inal = requi @@ -111,20 +111,43 @@ re(' -xterm-core') +../lib-headless/xterm.js').Terminal ;%0A%0Ac @@ -214,22 +214,16 @@ l = new -xterm. Terminal @@ -285,18 +285,44 @@ .write(' -ls +foo %5Cx1b%5B1;31mbar%5Cx1b%5B0m baz ', () =%3E @@ -457,16 +457,20 @@ oString( +true );%0A con @@ -537,15 +537,24 @@ %7D%60); // -ls +foo bar baz %0A%7D);%0A
1bfd230751f3ba074d8409c2311c87c06724f3e4
Fix incorrect caching headers if gzip is enabled by etag is not
index.js
index.js
'use strict'; var crypto = require('crypto'); var zlib = require('zlib'); var Promise = require('promise'); var ms = require('ms'); var mime = require('mime'); module.exports = prepareResponse; function prepareResponse(body, headers, options) { if (typeof body === 'string') body = new Buffer(body); if (!Buffer.isBuffer(body)) { return Promise.reject(new TypeError('Text must be either a buffer or a string')); } options = options || {}; var result = new Promise(function (resolve, reject) { if (options.gzip === false) return resolve(null); zlib.gzip(body, function (err, res) { if (err) return reject(err); else return resolve(res); }); }).then(function (gzippedBody) { if (typeof options.gzip !== 'boolean' && gzippedBody.length >= body.length) { options.gzip = false; } return new PreparedResponse(body, options.gzip !== false ? gzippedBody : null, headers, options); }); result.send = function (req, res, next) { return result.done(function (response) { response.send(req, res); }, next); }; return result; } function PreparedResponse(body, gzippedBody, headers, options) { this.body = body; this.gzippedBody = gzippedBody; this.etag = md5(body); this.headers = Object.keys(headers || {}).map(function (header) { var value = headers[header]; if (header.toLowerCase() === 'cache-control') { if (typeof value === 'string' && ms(value)) { value = 'public, max-age=' + Math.floor(ms(value) / 1000); } else if (typeof headers.cache === 'number') { value = 'public, max-age=' + Math.floor(value / 1000); } } if (header.toLowerCase() === 'content-type' && value.indexOf('/') === -1) { value = mime.lookup(value); } return new Header(header, value); }); this.options = options || {}; } PreparedResponse.prototype.send = function (req, res) { this.headers.forEach(function (header) { header.set(res); }); if (this.options.etag !== false) { // vary if (!res.getHeader('Vary')) { res.setHeader('Vary', 'Accept-Encoding'); } else if (!~res.getHeader('Vary').indexOf('Accept-Encoding')) { res.setHeader('Vary', res.getHeader('Vary') + ', Accept-Encoding'); } //check old etag if (req.headers['if-none-match'] === this.etag) { res.statusCode = 304; res.end(); return; } //add new etag res.setHeader('ETag', this.etag); } //add gzip if (this.options.gzip !== false && supportsGzip(req)) { res.setHeader('Content-Encoding', 'gzip'); res.setHeader('Content-Length', this.gzippedBody.length); if ('HEAD' === req.method) res.end(); else res.end(this.gzippedBody); } else { res.setHeader('Content-Length', this.body.length); if ('HEAD' === req.method) res.end(); else res.end(this.body); } }; function Header(key, value) { this.key = key; this.value = value; } Header.prototype.set = function (res) { res.setHeader(this.key, this.value); }; function md5(str) { return crypto.createHash('md5').update(str).digest("hex"); } function supportsGzip(req) { return req.headers && req.headers['accept-encoding'] && req.headers['accept-encoding'].indexOf('gzip') !== -1; }
JavaScript
0.000001
@@ -2092,24 +2092,277 @@ == false) %7B%0A + //check old etag%0A if (req.headers%5B'if-none-match'%5D === this.etag) %7B%0A res.statusCode = 304;%0A res.end();%0A return;%0A %7D%0A%0A //add new etag%0A res.setHeader('ETag', this.etag);%0A %7D%0A%0A //add gzip%0A if (this.options.gzip !== false) %7B%0A // vary%0A @@ -2596,224 +2596,11 @@ %7D%0A -%0A //check old etag%0A if (req.headers%5B'if-none-match'%5D === this.etag) %7B%0A res.statusCode = 304;%0A res.end();%0A return;%0A %7D%0A%0A //add new etag%0A res.setHeader('ETag', this.etag);%0A %7D%0A%0A //add gzip + %7D %0A i
a176887c249099d4293df6bfb3508da2e457e324
Add object shorthand rule for properties (#46)
index.js
index.js
'use strict' /* eslint-disable */ module.exports = { "env": { "es6": true, "node": true }, "extends": "eslint:recommended", "parserOptions": { "ecmaVersion": 2018 }, "plugins": [ "dependencies", "implicit-dependencies" ], "rules": { "dependencies/case-sensitive": 2, "dependencies/no-cycles": 2, "dependencies/no-unresolved": 2, "dependencies/require-json-ext": 2, "block-scoped-var": 2, "brace-style": [ 2, "1tbs" ], "camelcase": 2, "comma-dangle": [ 2, "only-multiline" ], "comma-spacing": [ 2, { "before": false, "after": true } ], "comma-style": [ 2, "last" ], "consistent-this": [ 2, "self" ], "curly": [ 2, "all" ], "dot-notation": 2, "eol-last": 2, "eqeqeq": 2, "implicit-arrow-linebreak": [ 2, "beside" ], "implicit-dependencies/no-implicit": [ 2, { "peer": true, "dev": true, "optional": true } ], "indent": [ 2, 4, { "MemberExpression": 0, "SwitchCase": 1 } ], "key-spacing": 2, "keyword-spacing": 2, "linebreak-style": 2, "new-cap": [ 2, { "capIsNewExceptions": [ "Sendgrid", "Bookshelf" ], "newIsCapExceptions": [ "self" ] } ], "no-array-constructor": 2, "no-console": 0, "no-else-return": 2, "no-eq-null": 2, "no-extra-parens": [ 2, "functions" ], "no-implicit-globals": 2, "no-lonely-if": 2, "no-multi-spaces": 2, "no-multiple-empty-lines": [ 2, { "max": 1, "maxEOF": 0, "maxBOF": 0 } ], "no-multi-str": 2, "no-new-object": 2, "no-restricted-syntax": [ 2, { "selector": "CallExpression[callee.name!='parseInt'] > Identifier[name='parseInt']", "message": "Call parseInt directly to guarantee radix param is not incorrectly provided" } ], "no-return-assign": [ 2, "always" ], "no-sequences": 2, "no-shadow-restricted-names": 2, "no-spaced-func": 2, "no-unsafe-negation": 2, "no-unused-vars": [ 2, { "args": "none", "vars": "all" } ], "no-use-before-define": [ 2, "nofunc" ], "no-useless-return": 2, "no-var": 2, "object-curly-spacing": [ 2, "always", { "objectsInObjects": false } ], "one-var": [ 2, "never" ], "padded-blocks": 0, "padding-line-between-statements": [ 2, { "blankLine": "always", "prev": "directive", "next": "*" }, { "blankLine": "any", "prev": "directive", "next": "directive" }, { "blankLine": "always", "prev": "*", "next": "return" } ], "prefer-const": 2, "quotes": [ 2, "single", "avoid-escape" ], "semi": [ 2, "never" ], "semi-spacing": 2, "space-before-blocks": 2, "space-before-function-paren": [ 2, { "anonymous": "never", "named": "never", "asyncArrow": "always" } ], "space-in-parens": [ 2, "never" ], "space-infix-ops": 2, "space-unary-ops": [ 2, { "words": true, "nonwords": false } ], "spaced-comment": 2, "strict": [ 2, "global" ], "valid-typeof": [ 2, { "requireStringLiterals": true } ], "vars-on-top": 2, "wrap-iife": [ 2, "inside" ] } }
JavaScript
0
@@ -3183,32 +3183,85 @@ %22no-var%22: 2,%0A + %22object-shorthand%22: %5B%22error%22, %22properties%22%5D,%0A %22object-
6357a36226c548aba44fb4e4fe7f39e8ba341cef
Update variable handling
index.js
index.js
module.exports = function (inputArray, singleCb, finalCb) { var len = inputArray.length; var lenTarget = 0; for (i = 0; i < len; i++) { (function() { var ii = i; process.nextTick( function(){ singleCb(inputArray[ii]); lenTarget++; if (lenTarget === len) { finalCb(inputArray); } }); })(); } }
JavaScript
0
@@ -53,19 +53,31 @@ alCb) %7B%0A -var +for (let i = 0, len = i @@ -96,13 +96,9 @@ ngth -;%0Avar +, len @@ -112,21 +112,8 @@ = 0; -%0A%0Afor (i = 0; i %3C @@ -146,11 +146,11 @@ %7B%0A%09%09 -var +let ii @@ -309,8 +309,9 @@ )();%0A%7D%0A%7D +%0A
c1e01e4600a1c862054fbb4119101f61c544d3d2
Remove anything inside the parentheses
index.js
index.js
import _ from 'lodash'; import fs from 'fs'; import stream, { Transform } from 'stream'; const streamify = (text) => { let s = new stream.Readable(); s.push(text); s.push(null); return s; }; const stripComments = (s) => { let re1 = /^\s+|\s+$/g; // Strip leading and trailing spaces let re2 = /\s*[#;].*$/g; // Strip everything after # or ; to the end of the line, including preceding spaces return s.replace(re1, '').replace(re2, ''); }; const removeSpaces = (s) => { return s.replace(/\s+/g, ''); }; // http://reprap.org/wiki/G-code#Special_fields // The checksum "cs" for a GCode string "cmd" (including its line number) is computed // by exor-ing the bytes in the string up to and not including the * character. const computeChecksum = (s) => { let cs = 0; s = s || ''; for (let i = 0; i < s.length; ++i) { let c = s[i].charCodeAt(0); cs = cs ^ c; } return cs; }; class GCodeParser extends Transform { constructor(options) { super(_.extend({}, options, { objectMode: true })); this.options = options || {}; } _transform(chunk, encoding, next) { // decode binary chunks as UTF-8 encoding = encoding || 'utf8'; if (Buffer.isBuffer(chunk)) { if (encoding === 'buffer') { encoding = 'utf8'; } chunk = chunk.toString(encoding); } let lines = chunk.split(/\r\n|\r|\n/g); _.each(lines, (line) => { line = _.trim(stripComments(line)); if (line.length === 0) { return; } let n; // Line number let cs; // Checksum let words = []; let list = removeSpaces(line) .match(/([a-zA-Z][0-9\+\-\.]*)|(\*[0-9]+)/igm) || []; _.each(list, (word) => { let letter = word[0].toUpperCase(); let argument = word.substr(1); argument = _.isNaN(parseFloat(argument)) ? argument : Number(argument); // // Special fields // { // N: Line number if (letter === 'N' && _.isUndefined(n)) { // Line (block) number in program n = Number(argument); return; } } { // *: Checksum if (letter === '*' && _.isUndefined(cs)) { cs = Number(argument); return; } } words.push([letter, argument]); }); // Exclude * (Checksum) from the line if (line.lastIndexOf('*') >= 0) { line = line.substr(0, line.lastIndexOf('*')); } let obj = {}; obj.line = line; obj.words = words; (typeof(n) !== 'undefined') && (obj.N = n); // Line number (typeof(cs) !== 'undefined') && (obj.cs = cs); // Checksum if (obj.cs && (computeChecksum(line) !== obj.cs)) { obj.err = true; // checksum failed } this.push(obj); }); next(); } _flush(done) { done(); } } const parseStream = (stream, callback) => { callback = callback || ((err) => {}); try { let results = []; stream.pipe(new GCodeParser()) .on('data', (data) => { results.push(data); }) .on('end', () => { callback(null, results); }) .on('error', callback); } catch(err) { callback(err); return; } return stream; }; const parseFile = (file, callback) => { file = file || ''; let s = fs.createReadStream(file, { encoding: 'utf8' }); s.on('error', callback); return parseStream(s, callback); }; const parseText = (text, callback) => { let s = streamify(text); return parseStream(s, callback); }; export { GCodeParser, parseStream, parseFile, parseText };
JavaScript
0.999999
@@ -241,88 +241,25 @@ -let re1 = /%5E%5Cs+%7C%5Cs+$/g; // Strip leading and trailing spaces%0A le +cons t re -2 +1 = /%5Cs*%5B #;%5D. @@ -258,14 +258,14 @@ %5Cs*%5B +%25 #;%5D.* -$ /g; @@ -293,10 +293,14 @@ fter + %25, # +, or @@ -352,16 +352,88 @@ spaces%0A + const re2 = /%5Cs*%5C(.*%5C)/g; // Remove anything inside the parentheses%0A retu @@ -1427,26 +1427,28 @@ %7D%0A%0A -le +cons t lines = ch @@ -1445,21 +1445,49 @@ lines = -chunk +stripComments(chunk)%0A .split(/ @@ -1497,24 +1497,25 @@ n%7C%5Cr%7C%5Cn/g);%0A +%0A _.ea @@ -1552,43 +1552,110 @@ -line = _.trim(stripComments(line)); +const list = removeSpaces(line)%0A .match(/(%5Ba-zA-Z%5D%5B0-9%5C+%5C-%5C.%5D*)%7C(%5C*%5B0-9%5D+)/igm) %7C%7C %5B%5D;%0A %0A @@ -1669,18 +1669,18 @@ if (li -ne +st .length @@ -1824,120 +1824,8 @@ %5B%5D; -%0A let list = removeSpaces(line)%0A .match(/(%5Ba-zA-Z%5D%5B0-9%5C+%5C-%5C.%5D*)%7C(%5C*%5B0-9%5D+)/igm) %7C%7C %5B%5D; %0A%0A
82b4beae47585f4ba2927609cd76b144e8a0d535
Fix addon page with wrong baseURL
tests/dummy/config/environment.js
tests/dummy/config/environment.js
/* jshint node: true */ module.exports = function (environment) { var ENV = { modulePrefix: "dummy", environment: environment, baseURL: "/", locationType: "auto", EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. "with-controller": true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === "development") { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === "test") { // Testem prefers this... ENV.baseURL = "/"; ENV.locationType = "none"; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = "#ember-testing"; } if (environment === "production") { } return ENV; };
JavaScript
0
@@ -976,16 +976,115 @@ on%22) %7B%0A%0A +%09%09var name = this.project.pkg.name;%0A%09%09ENV.locationType = %22hash%22;%0A%09%09ENV.baseURL = %22/%22 + name + %22/%22;%0A %09%7D%0A%0A%09ret
99e8521dd980f902e187c89c35bfb318463c31fb
Fix function name
index.js
index.js
/** * Created by Durgaprasad Budhwani on 1/2/2016. */ import React, { DeviceEventEmitter } from 'react-native'; import Loading from './loading'; const { StyleSheet, View, Text } = React; const styles = StyleSheet.create({ container: { position: 'absolute', backgroundColor: 'rgba(0,0,0,0.3)', justifyContent: 'center', alignItems: 'center', top: 0, bottom: 0, left: 0, right: 0, flex: 1 }, progressBar: { margin: 10, justifyContent: 'center', alignItems: 'center', padding: 10 } }); const BusyIndicator = React.createClass({ propTypes: { color: React.PropTypes.string, overlayColor: React.PropTypes.string, overlayHeight: React.PropTypes.number, overlayWidth: React.PropTypes.number, text: React.PropTypes.string, textColor: React.PropTypes.string, textFontSize: React.PropTypes.number }, getDefaultProps() { return { isDismissible: false, overlayWidth: 120, overlayHeight: 100, overlayColor: '#333333', color: '#f5f5f5', text: 'Please wait...', textColor: '#f5f5f5', textFontSize: 14 }; }, getInitialState() { return { isVisible: false }; }, componentDidMount () { this.emitter = DeviceEventEmitter.addListener('changeLoadingEffect', this.changeLoadingEffect, null); }, componentDidUnmount() { this.emitter.remove(); }, changeLoadingEffect(state) { this.setState({ isVisible: state.isVisible, text: state.title != null ? state.title : 'Please wait...' }); }, render() { const customStyles = StyleSheet.create({ overlay: { alignItems: 'center', justifyContent: 'center', borderRadius: 10, padding: 10, backgroundColor: this.props.overlayColor, width: this.props.overlayWidth, height: this.props.overlayHeight }, text: { color: this.props.textColor, fontSize: this.props.textFontSize, marginTop: 8 } }); if (!this.state.isVisible) { return (<View />); } else { return ( <View style={[styles.container]}> <View style={customStyles.overlay}> <Loading color={this.props.color} size="small" style={styles.progressBar}/> <Text numberOfLines={1} style={customStyles.text}>{this.state.text}</Text> </View> </View> ); } } }); module.exports = BusyIndicator;
JavaScript
0.999896
@@ -1369,19 +1369,20 @@ omponent -Did +Will Unmount(
c848cdb32bfdbd1730e2b78baa5316992cd64c0d
Fix refresh 404 with hash URL
tests/dummy/config/environment.js
tests/dummy/config/environment.js
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'dummy', environment: environment, baseURL: '/', locationType: 'auto', contentSecurityPolicy: { 'img-src': "'self' data: emberjs.com assets-cdn.github.com", }, EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { ENV.baseURL = '/ember-bulma'; } return ENV; };
JavaScript
0.000001
@@ -1179,16 +1179,47 @@ bulma';%0A + ENV.locationType = 'hash';%0A %7D%0A%0A r
ff3cc9c5425ead8dc3780ca0699c11e0a9be4c31
Fix bugs
index.js
index.js
(function(global, factory) { if (typeof define === 'function' && define.amd) { define([], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(); // CommonJS } else { global.mova = factory(); // Globals } }(this, function() { 'use strict'; var languages = {}; var language; function argsToArray(args) { return Array.prototype.slice.call(args, 0); } function preparePath(parts) { parts = parts || []; var path = []; for (var i = 0; i < parts.length; i++) { path = path.concat(parts[i].split('.')); } return path; } function pathToString(path) { return path.join('.'); } function resolvePath(tree, path, originalPath) { originalPath = originalPath || path; var node = tree[path[0]]; switch (typeof node) { case 'string': return node; case 'object': var nextPath = path.slice(1); if (!nextPath.length) { return pathToString(originalPath); } return resolvePath(node, nextPath, originalPath); default: return pathToString(originalPath); } } function mova() { return resolvePath(language, preparePath(argsToArray(arguments))); } mova.addLanguages = function(newLanguages) { for (var key in Object.keys(newLanguages)) { languages[key] = newLanguages[key]; } if (!language) { mova.setLanguage(Object.keys(languages)[0]); } }; mova.setLanguage = function(key) { language = languages[key] || language; }; mova.nameSpace = function() { var outerArgs = argsToArray(arguments); return function() { return mova(outerArgs, argsToArray(arguments)); } }; return mova; }));
JavaScript
0.000004
@@ -1291,23 +1291,18 @@ -for ( var key - in +s = Obj @@ -1323,16 +1323,40 @@ nguages) +;%0A for (var i in keys ) %7B%0A @@ -1370,16 +1370,20 @@ ages%5Bkey +s%5Bi%5D %5D = newL @@ -1394,16 +1394,20 @@ ages%5Bkey +s%5Bi%5D %5D;%0A %7D @@ -1695,17 +1695,29 @@ urn mova -( +.apply(null, outerArg @@ -1717,18 +1717,24 @@ uterArgs -, +.concat( argsToAr @@ -1748,16 +1748,17 @@ uments)) +) ;%0A %7D%0A
8593d0f6a3202a569adb5031d3b20cf28e98fcb8
Add support for observing an SNS topic.
index.js
index.js
var Rx = require('rx'), _ = require('lodash'); function receiveMessage(sqs, params, callback) { sqs.receiveMessage(params, function (err, data) { callback(err, data); receiveMessage(sqs, params, callback); }); } exports.observerFromQueue = function (sqs, params) { return Rx.Observer.create(function (messageParams) { sqs.sendMessage(_.defaults(messageParams, params), function (err, data) { }); }); }; exports.observableFromQueue = function (sqs, params) { return Rx.Observable.create(function (observer) { receiveMessage(sqs, params, function (err, data) { if (err) { observer.onError(err); } else if (data && data.Messages) { _.forEach(data.Messages, function (message) { observer.onNext(message); }); } return function () { /* Clean up */ }; }); }); }; exports.subjectFromQueue = function (sqs, sendParams, receiveParams) { return Rx.Subject.create( exports.observerFromQueue(sqs, sendParams), exports.observableFromQueue(sqs, receiveParams) ); };
JavaScript
0
@@ -235,16 +235,229 @@ %7D);%0A%7D%0A%0A +exports.observerFromTopic = function (sns, params) %7B%0A return Rx.Observer.create(function (messageParams) %7B%0A sns.publish(_.defaults(messageParams, params), function (err, data) %7B%0A%0A %7D);%0A %7D);%0A%7D;%0A%0A exports.
8b2bca56475112250b61d68b0ce4c40e378e9a03
Use new fn style, add name
index.js
index.js
import lingalaData from './lingala-english_data.js'; /** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { StyleSheet, Text, TouchableOpacity, ListView, View } from 'react-native'; import Dimensions from 'Dimensions' const chooseRandomFour = function(lingalaData) { var results = {testSubject: {}, randomFour: []}; var keys = Object.keys(lingalaData); for(i = 0; i < 4; i++) { var key = keys[Math.floor((Math.random() * keys.length) + 1) - 1]; var result = {index: i, lingala: key, english: lingalaData[key]}; results['randomFour'].push(result); } results['testSubject'] = results.randomFour[Math.floor((Math.random() * 4) + 1) - 1]; return results; } class lingala extends Component { constructor(props, context) { super(props, context); this.state = { correctNumber: 0, incorrectNumber: 0, currentTest: chooseRandomFour(lingalaData) } } next() { this.setState({ currentTest: chooseRandomFour(lingalaData), correct: undefined, correctIndex: undefined }); } choose(index) { var correct; var correctNumber = this.state.correctNumber; var incorrectNumber = this.state.incorrectNumber; if(index === this.state.currentTest.testSubject.index) { correctNumber++; correct = true; } else { incorrectNumber++; correct = false; } this.setState({ correct: correct, correctNumber: correctNumber, incorrectNumber: incorrectNumber, correctIndex: this.state.currentTest.testSubject.index }); } componentWillMount() { this.state.currentTest = chooseRandomFour(lingalaData); } getStyle(index) { if(this.state.correct !== undefined) { if(index === this.state.correctIndex) { return styles.correctResponse; } else { return styles.incorrectResponse; } } else { return styles.normalPossibleResponse; } } getOptionsList(options) { var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); var dataSource = ds.cloneWithRows(options) return ( <View style={styles.quarter}> <ListView styles={styles.quarter} horizontal={true} dataSource={dataSource} renderRow={(rowData) => { if(this.state.correct === undefined) { return (<View style={this.getStyle(rowData.index)}> <TouchableOpacity style={styles.touch} onPress={() => {this.choose(rowData.index)}}> <View> <Text> {rowData['lingala']} </Text> </View> </TouchableOpacity> </View>) } else { return (<View style={this.getStyle(rowData.index)}> <View> <Text> {rowData['lingala']} </Text> </View> </View>) } }} /> </View> ) } render() { return ( <View style={styles.container}> <View style={styles.topBar}> <View style={styles.quarterWidth}> <Text style={styles.topText}> {"Correct: " + this.state.correctNumber} </Text> </View> <View style={styles.quarterWidth}> <Text style={styles.topText}> {"Incorrect: " + this.state.incorrectNumber} </Text> </View> <View style={styles.quarterWidth}></View> <View style={styles.quarterWidth}> <TouchableOpacity onPress={this.next.bind(this)}> <Text style={styles.topText}> Next </Text> </TouchableOpacity> </View> </View> <View style={styles.topHalf}> <Text> {this.state.currentTest.testSubject['english']} </Text> </View> <View style={styles.bottomHalf}> {this.getOptionsList(this.state.currentTest.randomFour.slice(0, 2))} {this.getOptionsList(this.state.currentTest.randomFour.slice(2, 4))} </View> </View> ); } } var { width, height } = Dimensions.get('window'); const styles = StyleSheet.create({ container: { backgroundColor: '#F5FCFF', }, topHalf: { height: (height / 2) - 50, flex: 1, justifyContent: 'center', alignItems: 'center', flexDirection: 'column', backgroundColor: '#F5FCFF', }, bottomHalf: { height: (height / 2), flex: 1, justifyContent: 'center', alignItems: 'center', flexDirection: 'column', backgroundColor: '#F5FCFF', }, quarter: { height: height / 4, flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', flexDirection: 'row' }, normalPossibleResponse: { height: height / 4, width: width / 2, flex: 1, justifyContent: 'center', alignItems: 'center', alignSelf: 'stretch', backgroundColor: 'blue' }, correctResponse: { height: height / 4, width: width / 2, flex: 1, justifyContent: 'center', alignItems: 'center', alignSelf: 'stretch', backgroundColor: 'green' }, incorrectResponse: { height: height / 4, width: width / 2, flex: 1, justifyContent: 'center', alignItems: 'center', alignSelf: 'stretch', backgroundColor: 'red' }, topBar: { height: 50, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', backgroundColor: 'black' }, threeQuartersWidth: { width: (width / 4) * 3 }, quarterWidth: { paddingLeft: 15, width: width / 4 }, topText: { color: 'white' }, touch: { justifyContent: 'center', alignItems: 'center', alignSelf: 'stretch', flex: 1 } }); export default lingala
JavaScript
0
@@ -58,84 +58,31 @@ %0A * -Sample React Native App%0A * https://github.com/facebook/react-native%0A * @flow +lingala flashcards app %0A */ @@ -284,16 +284,8 @@ r = -function (lin @@ -293,16 +293,19 @@ alaData) + =%3E %7B%0A var
4edcb908f1f2835a8ab206c4b47adfef7a72f38b
Update default port
index.js
index.js
'use strict'; let cors = require('cors'); let express = require('express'); let helmet = require('helmet'); let mongoose = require('mongoose'); let router = express.Router(); let session = require('express-session'); let app = module.exports = express(); // App setup app.set('port', (process.env.PORT || 3000)); app.use(cors()); // Security app.set('trust proxy', 1) // trust first proxy app.use(helmet()); app.disable('x-powered-by'); app.use(session({ secret: 's3Cur3', name: 'sessionId', }) ); // Routes setup app.use('/v1', router) app.set('port', (process.env.PORT || 5000)); // Database setup mongoose.connect('mongodb://127.0.0.1:27017/nobreaks') require('./lib/character/index')(router); require('./lib/guild/index')(router); app.listen(app.get('port'), () => { console.log('No Breaks API is running on port', app.get('port')); });
JavaScript
0.000001
@@ -260,24 +260,41 @@ / App setup%0A +app.use(cors());%0A app.set('por @@ -322,29 +322,12 @@ %7C%7C -3000));%0Aapp.use(cors( +5001 ));%0A @@ -547,53 +547,8 @@ ter) -%0Aapp.set('port', (process.env.PORT %7C%7C 5000)); %0A%0A//
b24d7eeacd007c7ba12f97c4b50b27edd904204e
use path.resolve to get verdaccio bin path
index.js
index.js
'use strict' const path = require('path') const childProcess = require('child_process') module.exports = () => { const configPath = path.join(__dirname, 'registry/config.yaml') const verdaccioBin = 'node_modules/verdaccio/bin/verdaccio' return childProcess.spawnSync('node', [verdaccioBin, '-c', configPath], {stdio: 'inherit'}) }
JavaScript
0.000001
@@ -200,22 +200,25 @@ n = -'node_modules/ +require.resolve(' verd @@ -237,16 +237,17 @@ rdaccio' +) %0A retur
8002965ab70fd53f7d7a9284354e6afc948d3de5
Fix misnamed parameter
components/RaffleContainer.js
components/RaffleContainer.js
import React, { Component } from 'react'; import { Formik } from 'formik'; import { Loading, RaffleForm, Results } from '.'; export class RaffleContainer extends Component { // eslint-disable-next-line react/sort-comp initialState = { error: '', winners: [], }; state = this.initialState; render() { return ( <section className="ph3 pv3 pv4-ns mw6-m mw7-l center-ns"> <Formik initialValues={{ meetup: 'frontend-devs', count: 2, specificEventId: '', meetupApiKey: '', }} onSubmit={async ( { meetup, count, event, meetupApiKey }, { setSubmitting }, ) => { setSubmitting(true); // lib is coming from UMD in /static until StdLib's lib-js is on NPM try { const results = await global.window.lib.wKovacs64[ 'meetup-raffle' ]({ meetup, count, event, meetupApiKey, }); if (results.winners) { this.setState({ winners: results.winners }); } else { throw new Error('Malformed results received.'); } } catch (err) { this.setState({ error: err.message }); } setSubmitting(false); }} render={({ handleSubmit, isSubmitting }) => { if (isSubmitting) { return ( <div className="tc"> <Loading className="h5 w5" /> </div> ); } if (this.state.error || this.state.winners.length) { return ( <Results onReset={() => { this.setState(this.initialState); }} onSubmit={handleSubmit} {...this.state} /> ); } return <RaffleForm />; }} /> </section> ); } } export default RaffleContainer;
JavaScript
0.000002
@@ -627,21 +627,31 @@ count, -e +specificE vent +Id , meetup @@ -1022,13 +1022,23 @@ -e +specificE vent +Id ,%0A
a749d2d60a156f84ee44528767212335abeb02f1
remove unused import
index.js
index.js
'use strict'; var fs = require('fs'); var path = require('path'); var gutil = require('gulp-util'); var through = require('through2'); var vulcanize = require('vulcanize'); module.exports = function (options) { options = options || {}; if (!options.dest) { throw new gutil.PluginError('gulp-vulcanize', '`dest` required'); } return through.obj(function (file, enc, cb) { if (file.isNull()) { cb(null, file); return; } if (file.isStream()) { cb(new gutil.PluginError('gulp-vulcanize', 'Streaming not supported')); return; } options.input = file.path; options.inputSrc = file.contents; options.output = path.join(options.dest, file.path.replace(file.base, '')); options.outputHandler = function(filename, data, finished) { this.push(new gutil.File({ cwd: file.cwd, base: path.dirname(filename), path: filename, contents: new Buffer(data) })); if (finished) { cb(); } }.bind(this); vulcanize.setOptions(options, function () {}); try { vulcanize.processDocument(); } catch (err) { this.emit('error', new gutil.PluginError('gulp-vulcanize', err, {fileName: file.path})); } }); };
JavaScript
0.000001
@@ -11,32 +11,8 @@ t';%0A -var fs = require('fs');%0A var
d858bbf331dc0db60cad340ef7b8f3e9be49c4d5
patch tweaks
index.js
index.js
/*! * is-generator-function-name <https://github.com/tunnckoCore/is-generator-function-name> * * Copyright (c) 2015 Charlike Mike Reagent, contributors. * Released under the MIT license. */ 'use strict' module.exports = function isGeneratorFunctionName (co) { if (!co || !co.constructor) { return false } return co.constructor.name === 'GeneratorFunction' || co.constructor.displayName === 'GeneratorFunction' }
JavaScript
0.000001
@@ -313,24 +313,31 @@ lse%0A %7D%0A +%0A -return +var constr = co.cons @@ -347,17 +347,21 @@ ctor -. +%0A var name = -== 'Ge @@ -380,63 +380,69 @@ ion' - %7C%7C%0A co.constructor.displayName === 'GeneratorFunction' +%0A%0A return constr.name === name %7C%7C constr.displayName === name %0A%7D%0A
946b9bd52706d057dcb621259d3fbebfa7f85015
Update animalListScene.js
components/animalListScene.js
components/animalListScene.js
import React from 'react'; import { View, Text, TouchableHighlight, TextInput, StyleSheet, Alert } from 'react-native'; import * as scenes from '../scenes'; import AlphabetListView from 'react-native-alphabetlistview'; import animalDb from '../animals'; var navigator; var bg; class Cell extends React.Component { constructor(props) { super(props); } render() { return ( <TouchableHighlight onPress={() => scenes.navigatePush(navigator, scenes.ANIMAL_DETAIL, {animal: this.props.item.animal})} underlayColor='#bbbbbb' > <View style={{height:30, paddingLeft: 5}}> <Text style={{color: 'white'}}>{this.props.item.name}</Text> </View> </TouchableHighlight> ); } } class SectionItem extends React.Component { constructor(props) { super(props); } render() { return ( <View style={{ backgroundColor: this.props.bgColor, width: 30, height: 30, borderLeftWidth: 1, borderColor: 'white', justifyContent: 'center', }}> <Text style={{color: 'white', textAlign: 'center', fontWeight: '700'}}>{this.props.title}</Text> </View> ); } } class SectionHeader extends React.Component { constructor(props) { super(props); } render() { // inline styles used for brevity, use a stylesheet when possible var textStyle = { textAlign:'center', color:'#fff', fontWeight:'700', fontSize:24 }; var viewStyle = { backgroundColor: '#104f1f' }; return ( <View style={viewStyle}> <Text style={textStyle}>{this.props.title}</Text> </View> ); } } export default class AnimalListScene extends React.Component { constructor(props) { super(props); navigator = this.props.navigator; bg = this.props.bg; this.state = this.prepareSortedStructure(animalDb); } componentWillMount() { bg(); } prepareSortedStructure(animals) { let state = { fullData: {} }; const removeAccents = { 'Č' : 'C', 'Š' : 'S', 'Ú' : 'U', 'Ž' : 'Z', }; for (let animalID in animals) { let animal = animals[animalID]; let firstLetter = animal.name.charAt(0).toUpperCase(); if ((firstLetter === 'C') && (animal.name.charAt(1) === 'h')) { firstLetter = 'Ch'; } if (firstLetter in removeAccents) { firstLetter = removeAccents[firstLetter]; } if (!(firstLetter in state.fullData)) { state.fullData[firstLetter] = []; } state.fullData[firstLetter].push(animal); }; for (let letter in state.fullData) { state.fullData[letter].sort(function(a, b) { return a.name.localeCompare(b.name); }) }; state['data'] = state.fullData; return state; } setFilter(text) { this.setState({ text: text.text, data: this.filter(text.text.toUpperCase()), }) } filter(text) { let data = {}; for (let letter in this.state.fullData) { for (let idx in this.state.fullData[letter]) { if (this.state.fullData[letter][idx].name.toUpperCase().includes(text)) { if (!(letter in data)) { data[letter] = []; } data[letter].push(this.state.fullData[letter][idx]); } } } if (Object.keys(data).length === 0) { data['*'] = [{name: 'Zvíře s požadovaným jménem v aplikaci zatím chybí'}]; } return data; } render() { return ( <View style={{flex: 1}}> <TextInput style={{height: 40, textAlign: 'center', borderColor: 'gray', borderWidth: 1, backgroundColor: 'white'}} onChangeText={(text) => this.setFilter({text})} value={this.state.text} placeholder='Hledat' autoCorrect={false} /> <AlphabetListView data={this.state.data} cell={Cell} cellHeight={30} sectionListItem={SectionItem} sectionHeader={SectionHeader} sectionHeaderHeight={22.5} compareFunction={(a,b) => {return a.localeCompare(b); }} style={{ backgroundColor: '#104f1f', }} /> </View> ); } } AnimalListScene.propTypes = { bg: React.PropTypes.func.isRequired, navigator: React.PropTypes.object.isRequired, };
JavaScript
0
@@ -2145,16 +2145,33 @@ : 'Z',%0A + '%C4%9A' : 'E',%0A %7D;%0A%0A
d2ef7e30b2b84586cffbd6f275fbc838861564c8
build orm from resources instead of schemas
index.js
index.js
var _ = require('lodash'); var Waterline = require('waterline'); function createModel (schema, name, doc, connection) { return schema.type === 'object' && { dynamicFinders: false, associationFinders: false, identity: name.toLowerCase(), globalId: name, connection: connection, attributes: createAttributes(schema, doc) }; } function createAttributes (schema, doc) { return _.mapValues(schema.properties, function (property, name) { var ref = property.$ref || (property.items && property.items.$ref) || ''; return _.compact({ type: getType(property), notNull: !!property.required, model: property.$ref, collection: property.items ? property.items.$ref : undefined, via: ref.split('/')[1] || undefined }); }); } function getType (property) { if (_.contains([ 'object', 'array' ], (property.type || '').toLowerCase())) { return undefined; } else { return property.type; } } /** * Return a list of Waterline collection objects that can be passed into * waterline.loadCollections * * @param doc - a google discovery doc (restDescription) */ exports.createCollections = function (doc, connection) { return _.compact( _.map(doc.schemas, function (schema, name) { var model = createModel(schema, name, doc, connection || 'sailsDiscovery'); if (_.isObject(model)) { return Waterline.Collection.extend(model); } else { console.log('adsdadsadasdsadas'); return; } }) ); };
JavaScript
0
@@ -1170,24 +1170,25 @@ ction (doc, +_ connection) @@ -1181,32 +1181,85 @@ _connection) %7B%0A + var connection = _connection %7C%7C 'sailsDiscovery';%0A%0A return _.compa @@ -1276,22 +1276,24 @@ map(doc. -schema +resource s, funct @@ -1297,22 +1297,24 @@ nction ( -schema +resource , name) @@ -1311,24 +1311,61 @@ ce, name) %7B%0A + var schema = doc.shemas%5Bname%5D;%0A var mo @@ -1415,199 +1415,59 @@ tion - %7C%7C 'sailsDiscovery');%0A if (_.isObject(model)) %7B%0A return Waterline.Collection.extend(model);%0A %7D%0A else %7B%0A console.log('adsdadsadasdsadas');%0A return;%0A %7D +);%0A return Waterline.Collection.extend(model); %0A
4428d344f1522c51fdc39aa8476eec20ec3a342b
Generate an id for each search result
utils/generate_index.js
utils/generate_index.js
const fs = require('fs'); const path = require('path'); const lunr = require('lunr'); const removeMarkdown = require('remove-markdown'); const readmePath = path.resolve(__dirname, '..', 'README.md'); main(); function main() { console.log(JSON.stringify(generateIndex([ fs.readFileSync(readmePath, { encoding: 'utf-8' }) ]).toJSON())); } function generateIndex(files) { const index = lunr(function() { this.field('title', { boost: 10 // Match title results before the rest }); this.field('body'); this.ref('id'); }); files.forEach(function(file) { const lines = file.split('\n'); index.add({ title: removeMarkdown(lines[0]), body: removeMarkdown(lines.slice(1).join('\n')) }); }); return index; }
JavaScript
0.999967
@@ -415,24 +415,44 @@ unction() %7B%0A + this.ref('id');%0A this.fie @@ -552,36 +552,16 @@ body');%0A - this.ref('id');%0A %7D);%0A%0A @@ -588,16 +588,19 @@ ion(file +, i ) %7B%0A @@ -648,16 +648,87 @@ x.add(%7B%0A + id: i, // This should be something unique. Url slug for example.%0A ti
7d8f86cbf85ebd2179195ff6a2a7a1c5dcb9da58
Add tests for removing a selection when disabled
tests/selection/multiple-tests.js
tests/selection/multiple-tests.js
module('Selection containers - Multiple'); var MultipleSelection = require('select2/selection/multiple'); var $ = require('jquery'); var Options = require('select2/options'); var Utils = require('select2/utils'); var options = new Options({}); test('display uses templateSelection', function (assert) { var called = false; var templateOptions = new Options({ templateSelection: function (data) { called = true; return data.text; } }); var selection = new MultipleSelection( $('#qunit-fixture .multiple'), templateOptions ); var out = selection.display({ text: 'test' }); assert.ok(called); assert.equal(out, 'test'); }); test('templateSelection can addClass', function (assert) { var called = false; var templateOptions = new Options({ templateSelection: function (data, container) { called = true; container.addClass('testclass'); return data.text; } }); var selection = new MultipleSelection( $('#qunit-fixture .multiple'), templateOptions ); var $container = selection.selectionContainer(); var out = selection.display({ text: 'test' }, $container); assert.ok(called); assert.equal(out, 'test'); assert.ok($container.hasClass('testclass')); }); test('empty update clears the selection', function (assert) { var selection = new MultipleSelection( $('#qunit-fixture .multiple'), options ); var $selection = selection.render(); var $rendered = $selection.find('.select2-selection__rendered'); $rendered.text('testing'); selection.update([]); assert.equal($rendered.text(), ''); }); test('escapeMarkup is being used', function (assert) { var selection = new MultipleSelection( $('#qunit-fixture .multiple'), options ); var $selection = selection.render(); var $rendered = $selection.find('.select2-selection__rendered'); var unescapedText = '<script>bad("stuff");</script>'; selection.update([{ text: unescapedText }]); assert.equal( $rendered.text().substr(1), unescapedText, 'The text should be escaped by default to prevent injection' ); });
JavaScript
0.000001
@@ -1097,19 +1097,17 @@ iner();%0A - %0A + var ou @@ -1221,11 +1221,9 @@ ');%0A - %0A + as @@ -2130,16 +2130,16 @@ ection'%0A - );%0A%7D); @@ -2135,12 +2135,1123 @@ n'%0A );%0A%7D);%0A +%0Atest('clear button respects the disabled state', function (assert) %7B%0A var options = new Options(%7B%0A disabled: true%0A %7D);%0A%0A var $select = $('#qunit-fixture .multiple');%0A%0A var container = new MockContainer();%0A var $container = $('%3Cdiv%3E%3C/div%3E');%0A%0A var selection = new MultipleSelection(%0A $select,%0A options%0A );%0A%0A var $selection = selection.render();%0A $container.append($selection);%0A%0A selection.bind(container, $container);%0A%0A // Select an option%0A selection.update(%5B%7B%0A text: 'Test'%0A %7D%5D);%0A%0A var $rendered = $selection.find('.select2-selection__rendered');%0A%0A var $pill = $rendered.find('.select2-selection__choice');%0A%0A assert.equal($pill.length, 1, 'There should only be one selection');%0A%0A var $remove = $pill.find('.select2-selection__choice__remove');%0A%0A assert.equal(%0A $remove.length,%0A 1,%0A 'The remove icon is displayed for the selection'%0A );%0A%0A // Set up the unselect handler%0A selection.on('unselect', function (params) %7B%0A assert.ok(false, 'The unselect handler should not be triggered');%0A %7D);%0A%0A // Trigger the handler for the remove icon%0A $remove.trigger('click');%0A%7D);%0A
9a4c96a2fdc4c12efddaa2889eb2488fe6777a6d
Update video.js
SRC/JS/video.js
SRC/JS/video.js
JavaScript
0.000001
@@ -1 +1,1051 @@ +var video = %7B%0A //%E4%B8%BB%E8%AE%BA%E5%9D%9B%0A %22zhu%22 : %5B%0A %7B%0A %22title%22 : %22%E7%99%BE%E5%BA%A6%E4%B8%96%E7%95%8C2015%E4%B8%BB%E8%AE%BA%E5%9D%9B%E5%85%A8%E7%A8%8B%E5%9B%9E%E9%A1%BE%22,%0A %22embed%22 : '%3Cembed src=%22http://player.video.qiyi.com/f5bc8cc248d6629914b5f3082bb21442/0/0/v_19rrodwrx0.swf-albumId=395916600-tvId=395916600-isPurchase=0-cnId=30%22 allowFullScreen=%22true%22 quality=%22high%22 width=%22581%22 height=%22345%22 align=%22middle%22 allowScriptAccess=%22always%22 type=%22application/x-shockwave-flash%22%3E%3C/embed%3E',%0A %22src%22 : %22http://baiduworld.baidu.com/2015/images2015/sp_img01.png%22%0A %7D,%0A %7B%0A %22title%22 : %22%E7%99%BE%E5%BA%A6%E4%B8%96%E7%95%8C2015%E6%9D%8E%E5%BD%A6%E5%AE%8F%E6%BC%94%E8%AE%B2%EF%BC%9A%E7%B4%A2%E5%BC%95%E7%9C%9F%E5%AE%9E%E4%B8%96%E7%95%8C%22,%0A %22embed%22 : '%3Cembed src=%22http://player.video.qiyi.com/07179f044066e8e3341967de14e4a800/0/0/v_19rrodyoy4.swf-albumId=395888800-tvId=395888800-isPurchase=0-cnId=30%22 allowFullScreen=%22true%22 quality=%22high%22 width=%22581%22 height=%22345%22 align=%22middle%22 allowScriptAccess=%22always%22 type=%22application/x-shockwave-flash%22%3E%3C/embed%3E',%0A %22src%22 : %22http://baiduworld.baidu.com/2015/images2015/sp_img02.png%22%0A %7D%0A %5D,%0A //%E5%9C%B0%E5%9B%BE%E8%AE%BA%E5%9D%9B%0A %22map%22 : %5B%0A %5D,%0A //%E4%BA%BA%E5%92%8C%E6%9C%8D%E5%8A%A1%E8%AE%BA%E5%9D%9B%0A %22ren%22 : %5B%0A%0A %5D, %0A
0486d6a2a9cd52949e4c422e2260b4b0ff8283f9
I changed the event names so they are less goofy
Stack.js
Stack.js
var events = require('events') util = require('util') function QuickConnectStack(id, funcs, data, qc, cb, testing) { events.EventEmitter.call(this) var ValCFs, DCFs, VCFs, self = this, state = { going: false, cfIndex: -1, waitingCallback: null } this.id = id cb?this.on('ended', cb):'' function go() { if (state.going) { throw new Error("Stack is already started") } // console.log('go!') state.going = true self.emit('started', data) dispatch() } this.go = go ValCFs = funcs.validationMapConsumables[id].slice() DCFs = funcs.dataMapConsumables[id].slice() VCFs = funcs.viewMapConsumables[id].slice() function dispatch() { var callback = testing?testingCallback:defaultCallback if (ValCFs.length > 0) { if (ValCFs.length == 1){ callback = testing?ValCFsDoneTestingCallback:ValCFsDoneCallback } dispatchToValCF(callback) } else if (DCFs.length > 0) { if (DCFs.length == 1){ callback = testing?ValCFsDoneTestingCallback:DCFsDoneCallback } dispatchToDCF(callback) } else if (VCFs.length > 0) { if (VCFs.length == 1){ callback = testing?VCFsDoneTestingCallback:VCFsDoneCallback } dispatchToVCF(callback) } else { selfDestruct() } } function dispatchToValCF(callback) { var func = ValCFs.shift() dispatchToCF("ValCF", func, callback) } function dispatchToDCF(callback) { var func = DCFs.shift() dispatchToCF("DCF", func, callback) } function dispatchToVCF(callback) { var func = VCFs.shift() dispatchToCF("VCF", func, callback) } function newStackObject() { return { "asyncStackContinue":asyncStackContinue, "asyncStackExit":asyncStackExit, "asyncStackError":asyncStackError, "WAIT_FOR_DATA":qc.WAIT_FOR_DATA, "STACK_CONTINUE":qc.STACK_CONTINUE, "STACK_EXIT":qc.STACK_EXIT, "handleRequest":qc.handleRequest } } function dispatchToCF(type, func, callback) { var result, err, obj // console.log('dispatch to cf') state.cfIndex ++ try { obj = newStackObject() result = func.call(obj, data, obj) } catch (error) { self.emit('errored', error, data, state.cfIndex) selfDestruct(true) return } if (result === qc.STACK_CONTINUE) { callback() } else if (result === qc.STACK_EXIT) { selfDestruct() } else if (type == "DCF",result === qc.WAIT_FOR_DATA) { state.waitingCallback = callback self.emit('waiting', data, state.cfIndex) } else { err = new Error("Improper CF return value: " + util.inspect(result)) self.emit('errored', err, data, state.cfIndex) } } function defaultCallback() { qc.nextTick(dispatch) } function testingCallback() { self.emit('CFComplete', data, state.cfIndex) defaultCallback() } function ValCFsDoneCallback() { self.emit('validated', data, state.cfIndex) qc.nextTick(dispatch) } function ValCFsDoneTestingCallback() { self.emit('CFComplete', data, state.cfIndex) ValCFsDoneCallback() } function DCFsDoneCallback() { self.emit('datad', data, state.cfIndex) qc.nextTick(dispatch) } function DCFsDoneTestingCallback() { self.emit('CFComplete', data, state.cfIndex) DCFsDoneCallback() } function VCFsDoneCallback() { self.emit('viewed', data, state.cfIndex) qc.nextTick(selfDestruct) } function VCFsDoneTestingCallback() { self.emit('CFComplete', data, state.cfIndex) VCFsDoneCallback() } function asyncStackContinue(key, results) { data[key] = results qc.nextTick(state.waitingCallback) } function asyncStackExit(key, results) { data[key] = results selfDestruct() } function asyncStackError(error) { self.emit('errored', error, data, state.cfIndex) selfDestruct(true) } function selfDestruct(err) { ValCFs.length = 0//probably don't need these in some cases. oh well. DCFs.length = 0 VCFs.length = 0 if (!err) { self.emit('ended', data, state.cfIndex) } } } util.inherits(QuickConnectStack, events.EventEmitter); /* events emitted by the stack: started ended waiting errored validated datad viewed CFComplete (if testing) */ exports.Stack = QuickConnectStack
JavaScript
0.998081
@@ -278,18 +278,16 @@ .on('end -ed ', cb):' @@ -288,16 +288,16 @@ cb):''%0A + %09%0A%09funct @@ -448,18 +448,16 @@ t('start -ed ', data) @@ -2150,34 +2150,32 @@ self.emit('error -ed ', error, data, @@ -2468,19 +2468,16 @@ it('wait -ing ', data, @@ -2595,26 +2595,24 @@ .emit('error -ed ', err, data @@ -2620,32 +2620,56 @@ state.cfIndex)%0A +%09 selfDestruct(true)%0A %09 %7D%0A%09%7D%0A%09%0A%09funct @@ -2879,17 +2879,20 @@ validate -d +Done ', data, @@ -3101,17 +3101,20 @@ it('data -d +Done ', data, @@ -3319,18 +3319,20 @@ it('view +Don e -d ', data, @@ -3740,18 +3740,16 @@ t('error -ed ', error @@ -3973,18 +3973,16 @@ mit('end -ed ', data, @@ -4106,36 +4106,29 @@ tart -ed %0A end -ed %0A wait -ing %0A error ed%0A @@ -4123,18 +4123,16 @@ %0A error -ed %0A valid @@ -4138,26 +4138,34 @@ date -d +Done %0A data -d +Done %0A view +Don e -d %0A C
7fca604b486b379888d9cacaef9dc9d48f2a2085
Remove support for ScrollComposite
src/tabris/widgets/ScrollView.js
src/tabris/widgets/ScrollView.js
tabris.registerWidget("_ScrollBar", { _type: "rwt.widgets.ScrollBar", _events: {Selection: true}, _properties: { style: "any" } }); tabris.registerWidget("ScrollView", { _type: "rwt.widgets.ScrolledComposite", _supportsChildren: true, _properties: { direction: { type: ["choice", ["horizontal", "vertical"]], default: "vertical" }, scrollX: { type: "number", access: { set: function(name, value) { if (this.get("direction") === "horizontal") { this._nativeSet("origin", [value, 0]); } }, get: function() { return this.get("direction") === "horizontal" ? this._nativeGet("origin")[0] : 0; } } }, scrollY: { type: "number", access: { set: function(name, value) { if (this.get("direction") === "vertical") { this._nativeSet("origin", [0, value]); } }, get: function() { return this.get("direction") === "vertical" ? this._nativeGet("origin")[1] : 0; } } } }, _events: { scroll: { listen: function(listen) { if (listen) { this._scrollBar.on("Selection", this._scrollBarListener, this); } else { this._scrollBar.off("Selection", this._scrollBarListener, this); } }, trigger: function(position) { this.trigger(this, position, {}); } } }, _create: function(properties) { this._super("_create", arguments); var style = properties.direction === "horizontal" ? ["H_SCROLL"] : ["V_SCROLL"]; this._nativeSet("style", style); this._scrollBar = tabris.create("_ScrollBar", { style: properties.direction === "horizontal" ? ["HORIZONTAL"] : ["VERTICAL"] }); this._scrollBar._nativeSet("parent", this.cid); this._composite = new tabris.Composite(); this._composite._nativeSet("parent", this.cid); this._nativeSet("content", this._composite.cid); return this; }, _scrollBarListener: function() { var origin = this._nativeGet("origin"); this.trigger("scroll", this, {x: origin[0], y: origin[1]}); }, _getContainer: function() { return this._composite; } }); tabris.registerWidget("ScrollComposite", tabris.ScrollView);
JavaScript
0.000001
@@ -2243,66 +2243,4 @@ %7D);%0A -%0Atabris.registerWidget(%22ScrollComposite%22, tabris.ScrollView);%0A
ead727bf13bdea8cb71eb9f4c89328a3fab7f75d
Fix templates and add newlines
src/transforms/cordova-assets.js
src/transforms/cordova-assets.js
export function CORDOVA_ASSET_TEMPLATE(assetType, platform, {src, d, w, h} = {}) { return `<${assetType} src="${src}" platform="${platform}"${d?` density="${d}"`:``}${w?` width="${w}"`:``}${h?` height="${h}`:``}" />`; } export function PGBUILD_ASSET_TEMPLATE(assetType, platform, {src, d, w, h} = {}) { return `<${assetType} src="${src}" gap:platform="${platform}"${d?` gap:qualifier="${d}"`:``}${w?` width="${w}"`:``}${h?` height="${h}`:``}" />`; } /** * Create a list of icons or splash screens * @param assetType {string} icon | splash * @param assetTemplate {function} one of the above templates * @param cordova {*} */ export function transformCordovaAssets(assetType, assetTemplate, {cordova} = {cordova: {platforms: [], assets: {}}} ) { let {platforms} = cordova, assets = cordova[assetType]; if (platforms instanceof Array && assets instanceof Object) { return platforms.map( platform => { let assetList = assets[platform]; if (assetList instanceof Array) { return assetList.map(assetTemplate.bind(undefined, assetType, platform)); } else { return ""; } }).join("\n "); } else { return ""; } }
JavaScript
0
@@ -195,38 +195,38 @@ h?%60 height=%22$%7Bh%7D +%22 %60:%60%60%7D -%22 /%3E%60;%0A%7D%0Aexport f @@ -441,14 +441,14 @@ $%7Bh%7D +%22 %60:%60%60%7D -%22 /%3E%60 @@ -1113,16 +1113,29 @@ atform)) +.join(%22%5Cn %22) ;%0A
97f0a7f0df01b8677456b12f8bb5ffacd2b93315
Add event callback hook function because of timing issue
src/tv-webos/applicationProxy.js
src/tv-webos/applicationProxy.js
'use strict'; module.exports = { exit: function (success, fail, args) { window.close(); }, launchApp: function (success, fail, args) { try { var paramAppId = args[0].appId; var paramData = {}; paramData.data = args[0].data; /*jshint undef: false */ paramData.callerAppId = webOS.fetchAppId(); /*jshint undef: false */ webOS.service.request('luna://com.webos.applicationManager', { method: 'launch', parameters: { 'id': paramAppId, 'params': paramData }, onSuccess: function (data) { success(data); }, onFailure: function (e) { var error = new Error(); error.name = e.name; throw error; } }); } catch (e) { var error = new Error(); error.name = e.name; setTimeout(function() { fail(error); }, 0); } }, getRequestedAppInfo: function (success, fail, args) { try { var receivedData = null; if(receivedData === null) { receivedData = JSON.parse(window.localStorage.getItem('requestedappinfodata')); window.localStorage.setItem('requestedappinfodata', ''); } if(typeof receivedData === 'object' && receivedData.hasOwnProperty('data')) { var passedData = receivedData.data; var callerAppId = receivedData.callerAppId; success({callerAppId: callerAppId, data: passedData}); } else { var error = new Error(); error.message = 'failed to get data'; error.name = 'failed to get data'; throw error; } } catch(e) { setTimeout(function() { fail(e); }, 0); } } }; require('cordova/exec/proxy').add('toast.application', module.exports);
JavaScript
0.000001
@@ -8,16 +8,818 @@ rict';%0A%0A +var hookSuccessCallback = %7B%7D;%0A%0Adocument.addEventListener('webOSLaunch', function(inData) %7B%0A console.log('webOSLaunch');%0A %0A if(typeof hookSuccessCallback === 'function')%7B%0A window.localStorage.setItem('requestedappinfodata', JSON.stringify(inData.detail));%0A hookSuccessCallback(%7BcallerAppId: inData.detail.callerAppId, data: inData.detail.data%7D);%0A %7D%0A%7D, false);%0A%0Adocument.addEventListener('webOSRelaunch', function(inData) %7B%0A /*jshint undef: false */%0A console.log('webOSRelaunch');%0A %0A if(typeof hookSuccessCallback === 'function')%7B%0A window.localStorage.setItem('requestedappinfodata', JSON.stringify(inData.detail));%0A hookSuccessCallback(%7BcallerAppId: inData.detail.callerAppId, data: inData.detail.data%7D);%0A %7D%0A%0A PalmSystem.activate();%0A%7D, false);%0A%0A module.e @@ -2004,32 +2004,33 @@ args) %7B%0A + try %7B%0A @@ -2035,32 +2035,45 @@ -var receivedData = null; + console.log('getRequestedAppInfo');%0A %0A @@ -2081,19 +2081,21 @@ -if( + var received @@ -2104,20 +2104,14 @@ ta = -== null) %7B%0A + %7B%7D;%0A%0A @@ -2123,36 +2123,13 @@ - receivedData = JSON.parse( +if(!! wind @@ -2176,17 +2176,17 @@ odata')) -; +%7B %0A @@ -2186,32 +2186,59 @@ + receivedData = JSON.parse( window.localStor @@ -2233,33 +2233,33 @@ ow.localStorage. -s +g etItem('requeste @@ -2275,15 +2275,13 @@ ata' -, '' +) );%0A + @@ -2299,24 +2299,25 @@ + if(typeof re @@ -2379,17 +2379,16 @@ 'data')) - %7B%0A @@ -2401,64 +2401,18 @@ -var passedData = receivedData.data;%0A var + success(%7B call @@ -2418,18 +2418,17 @@ lerAppId - = +: receive @@ -2448,81 +2448,39 @@ ppId -;%0A success(%7BcallerAppId: callerAppId, data: passedData%7D);%0A +, data: receivedData.data%7D); %0A @@ -2481,32 +2481,33 @@ %0A %7D%0A + else @@ -2529,167 +2529,41 @@ -var error = new Error();%0A error.message = 'failed to get data';%0A error.name = 'failed to get data';%0A throw error;%0A + hookSuccessCallback = success;%0A
4902edcfd29c06b3b8406ae15a8943d54aa13bf6
Fix issue triggering print dialog in production
pages/doc.js
pages/doc.js
import { Component, createRef } from 'react'; import { connect } from 'react-redux'; import { withStyles } from '@material-ui/core/styles'; import SplitPane from 'react-split-pane'; import { fetchDoc, fetchServerDoc } from '../src/actions'; import Document, { Meta } from '../src/components/Document'; import Locations from '../src/components/Locations'; import Finder from '../src/components/Finder'; import SplitPaneLayout from '../src/components/SplitPaneLayout'; import { parseLocation, copyMetadata } from '../src/utils'; import HotKeys from '../src/components/HotKeys'; import Typography from '@material-ui/core/Typography'; const styles = theme => ({ container: theme.mixins.toolbar, finderSplitPane: { position: 'absolute', width: '100%', height: '100%', }, }); class Doc extends Component { state = { finder: false, printMode: false }; keys = [ { name: 'copyMetadata', key: 'c', help: 'Copy MD5 and path to clipboard', handler: (e, showMessage) => { if (this.props.data && this.props.data.content) { showMessage(copyMetadata(this.props.data)); } }, }, ]; root = createRef(); componentDidMount() { const { query, pathname } = parseLocation(); const fetch = () => { if (query.path) { this.props.dispatch( fetchDoc(query.path, { includeParents: this.state.finder, }) ); } else if (this.state.finder) { this.props.dispatch(fetchDoc(pathname, { includeParents: true })); } else { this.props.dispatch(fetchServerDoc()); } }; const newState = {}; if (query.finder && query.finder !== 'false') { newState.finder = true; } if (query.print && query.print !== 'false') { newState.printMode = true; } if (Object.keys(newState).length) { this.setState(newState, fetch); } else { fetch(); } } componentDidUpdate(prevProps, prevState) { if (this.root.current && !this.state.finder) { this.root.current.focus(); } if (this.state.printMode && prevProps.isFetching && !this.props.isFetching) { window.print(); } } render() { const { data, url, collection, isFetching, error, classes } = this.props; const { finder, printMode } = this.state; if (!url) { return null; } if (error) { return ( <Typography style={{ margin: '5rem 2rem' }}> {error.message} </Typography> ); } const doc = <Document fullPage toolbar={!printMode} />; const meta = <Meta doc={data} collection={collection} />; let content = null; if (finder) { content = ( <div className={classes.finderSplitPane}> <div className={classes.container} /> <SplitPane split="horizontal" defaultSize="25%" style={{ position: 'relative' }}> <div> <Finder isFetching={isFetching} data={data} url={url} /> </div> <SplitPaneLayout container={false} left={meta} defaultSizeLeft={'30%'} defaultSizeMiddle={'70%'}> {doc} </SplitPaneLayout> </SplitPane> </div> ); } else if (printMode) { content = ( <div> {meta} {doc} </div> ); } else { // remove this branch when https://github.com/CRJI/EIC/issues/83 is done content = ( <SplitPaneLayout left={data && <Locations data={data} url={url} />} right={doc} defaultSizeLeft={'25%'} defaultSizeMiddle={'70%'}> {meta} </SplitPaneLayout> ); } return ( <HotKeys keys={this.keys} focused> <div ref={this.root} tabIndex="-1"> {content} </div> </HotKeys> ); } } export default connect(({ doc: { isFetching, data, url, collection, error } }) => ({ isFetching, data, url, collection, error, }))(withStyles(styles)(Doc));
JavaScript
0
@@ -2386,54 +2386,42 @@ && -prevProps.isFetching && !this.props.isFetching +this.props.data && !prevProps.data ) %7B%0A
51df7f8618920764a72cbaed0934cfd88655df12
fix popup
saiku-ui/js/saiku/views/LoginForm.js
saiku-ui/js/saiku/views/LoginForm.js
/* * Copyright 2012 OSBI Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * The login prompt on startup */ var LoginForm = Modal.extend({ type: "login", message: _.template("<form id='login_form'>" + "<label for='username' class='i18n'>Username</label>" + "<input type='text' id='username' name='username' value='' />" + "<label for='password' class='i18n'>Password</label>" + "<input type='password' id='password' name='password' value='' />" + "<% if (Settings.EVALUATION_PANEL_LOGIN) { %>" + "<div class='eval-panel'>" + "<a href='#eval_login' class='i18n' id='eval-login'>Evaluation Login</a>" + "<div class='eval-panel-user clearfix' hidden>" + "<ul>" + "<li class='i18n'>Administrator</li>" + "<li class='i18n'>Username: admin</li>" + "<li class='i18n'>Password: admin</li>" + "</ul>" + "</div>" + "</div>" + "<% } %>" + "</form>")(), buttons: [ { text: "Login", method: "login" } ], events: { 'click a': 'call', 'keyup #login_form input': 'check', 'click #eval-login': 'show_panel_user' }, initialize: function(args) { _.extend(this, args); _.bindAll(this, "adjust"); this.options.title = Settings.VERSION; this.bind('open', this.adjust); }, adjust: function() { $(this.el).parent().find('.ui-dialog-titlebar-close').hide(); $(this.el).find("#username").select().focus(); }, check: function(event) { if(event.which === 13) { this.login(); } }, login: function() { var l_username = $(this.el).find("#username").val(); var l_password = $(this.el).find("#password").val(); $(this.el).dialog('close'); this.session.login(l_username, l_password, $(this.el)); return true; }, setMessage: function(message) { this.$el.find('.dialog_body').html(this.message); }, setError: function(message){ $(this.el).find(".dialog_response").html(message); }, show_panel_user: function(event) { event.preventDefault(); var $currentTarget = $(event.currentTarget); $currentTarget.next().slideToggle('fast'); } });
JavaScript
0.000002
@@ -2649,17 +2649,68 @@ ssage);%0A -%09 + $(this.el).find('.clearlink').unbind();%0A %7D,%0A%0A
334c644c502d92abc831a3a3fff82fd79f7b3ae0
Handle empty reputation for unknown sites
ext/web-of-trust.js
ext/web-of-trust.js
'use strict'; const url = require('url'); const requestPromise = require('request-promise'); /** @module webOfTrust */ module.exports = { /** @method getReputation * @description Fetch reputation from Web of Trust api * @param {String} apiKey - Web Of Trust API Key * @param {String} articleUrl - URL of the articleUrl */ getReputation: (apiKey, articleUrl) => { var options = { uri: 'http://api.mywot.com/0.4/public_link_json2', qs: { hosts: url.parse(articleUrl).hostname + '/', key: apiKey }, headers: {'User-Agent': 'Request-Promise'}, json: true }; return requestPromise(options); }, /** @method formatResponse * @description Convert Web of Trust API response to match our specification * @param {Object} wotResponse - Web Of Trust API response object */ formatResponse: wotResponse => { // Pull the reputation information out of the API // https://www.mywot.com/wiki/API#public_link_json2 const domain = Object.keys(wotResponse)[0]; const reputation = wotResponse[domain]['0'][0]; const confidence = wotResponse[domain]['0'][1]; const categories = Object.keys(wotResponse[domain].categories); return { trustworthiness: { reputation: reputation, confidence: confidence, description: getDescription(reputation) }, categories: categories.filter(x => { // Only use categories over 50% confidence return wotResponse[domain].categories[x] >= 50; }).map(getLabel) }; } }; /** @method getDescription * @description Convert reputation value to a description * @param {Number} score - Web Of Trust reputation value */ function getDescription(score) { if (score >= 80) { return 'Excellent'; } else if (score >= 60) { return 'Good'; } else if (score >= 40) { return 'Unsatisfactory'; } else if (score >= 20) { return 'Poor'; } return 'Very Poor'; } /** @method getLabel * @description Convert category ID to descriptive labels * @param {String} categoryId - Web Of Trust category ID */ function getLabel(categoryId) { const label = { 101: 'Malware or viruses', 102: 'Poor customer experience', 103: 'Phishing', 104: 'Scam', 105: 'Potentially illegal', 201: 'Misleading claims or unethical', 202: 'Privacy risks', 203: 'Suspicious', 204: 'Hate, discrimination', 205: 'Spam', 206: 'Potentially unwanted programs', 207: 'Ads / pop-ups', 301: 'Online tracking', 302: 'Alternative or controversial medicine', 303: 'Opinions, religion, politics', 401: 'Adult content', 402: 'Incidental nudity', 403: 'Gruesome or shocking', 404: 'Site for kids', 501: 'Good site' }; return (label[categoryId]) ? label[categoryId] : 'Other'; }
JavaScript
0.000001
@@ -994,24 +994,259 @@ sponse)%5B0%5D;%0A +%0A%09%09if (!wotResponse%5Bdomain%5D%5B'0'%5D) %7B%0A%09%09%09// Bail if the response doesn't contain a reputation%0A%09%09%09return %7B%0A%09%09%09%09trustworthiness: %7B%0A%09%09%09%09%09reputation: null,%0A%09%09%09%09%09confidence: 0,%0A%09%09%09%09%09description: 'Unknown'%0A%09%09%09%09%7D,%0A%09%09%09%09categories: %5B%5D%0A%09%09%09%7D;%0A%09%09%7D%0A%0A %09%09const repu
2a1915d2f346adf56203cc1c66f93a48f1fd6377
Fix isrequired mesage on unnecesary timePicker
frontend/app/js/components/serverboard/board/daterange.js
frontend/app/js/components/serverboard/board/daterange.js
import React from 'react' import Calendar from 'rc-calendar'; import moment from 'moment' import {pretty_ago} from 'app/utils' require("sass/calendar.sass") const DATE_FORMAT="YYYY-MM-DD hh:mm" const TimePicker=React.createClass({ propTypes:{ value: React.PropTypes.object.isRequired }, componentDidMount(){ let self=this $(this.refs.h).dropdown({ onChange: self.handleChangeHour }) $(this.refs.m).dropdown({ onChange: self.handleChangeMinute }) }, handleChangeMinute(v){ let val=this.props.value.minutes(v) this.props.onSelect(val) }, handleChangeHour(v){ let val=this.props.value.hours(v) this.props.onSelect(val) }, range(max){ var hh=[] for (var i=0;i<max;i++){ hh.push( (""+"0"+i).slice(-2) ) } return hh }, render(){ const props=this.props const value=props.value return ( <div className="ui form time"> <select ref="h" className="ui dropdown" defaultValue={value.format("H")}> {this.range(24).map( (h) => <option key={h} value={h}>{h}</option> )} </select> <select ref="m" className="ui dropdown" defaultValue={value.format("m")}> {this.range(60).map( (m) => <option key={m} value={m}>{m}</option> )} </select> </div> ) } }) const DatetimePicker=React.createClass({ propTypes:{ value: React.PropTypes.object.isRequired, onSelect: React.PropTypes.func.isRequired, onClose: React.PropTypes.func.isRequired, }, getInitialState(){ return ({ now: moment(), value: this.props.value }) }, componentDidMount(){ let position=$(this.refs.el).offset() $(this.refs.calendar).css({ top: position.top+5, left: position.left-20 }) }, isDateDisabled(date){ return date.diff(this.state.now) > (24*60*60); }, handleClickBackground(ev){ if (ev.target == this.refs.background) this.props.onClose() }, handleDateSelect(value){ this.setState({value}) }, handleOk(){ this.props.onSelect(this.state.value) this.props.onClose() }, setToday(){ this.props.onSelect(moment()) this.props.onClose() }, timePicker: ( <TimePicker /> ), render(){ const props=this.props return ( <span ref="el"> <div ref="background" className="ui menu full background" onClick={this.handleClickBackground}> <div ref="calendar" className="ui calendar"> <label>Date:</label> <Calendar value={this.state.value} onSelect={this.handleDateSelect} onChange={this.handleDateSelect} disabledDate={this.isDateDisabled} showToday={false} /> <label>Time:</label> <TimePicker value={this.state.value} onSelect={this.handleDateSelect} /> <div className="ui right" style={{marginTop: 10}}> <button className="ui button" onClick={this.setToday} >Set now</button> <button className="ui button yellow" onClick={this.handleOk} >Set selected</button> </div> </div> </div> </span> ) } }) const DatetimeItem=React.createClass({ propTypes:{ value: React.PropTypes.object.isRequired, now: React.PropTypes.object.isRequired, onSelect: React.PropTypes.func.isRequired, }, getInitialState(){ return { open_calendar: false } }, onToggleCalendar(){ this.setState({open_calendar: !this.state.open_calendar}) }, render(){ const props=this.props const pretty=pretty_ago(props.value, props.now, 60 * 1000) return ( <div title={props.value.format("YYYY-MM-DD HH:mm")}> <a className="item" onClick={this.onToggleCalendar}> <label>{props.label}</label> <div className="value"> {pretty}<br/> <span className="meta" style={{color: "#bbb", fontWeight: "normal"}}>at {props.value.format("HH:mm")}</span> </div> </a> {this.state.open_calendar ? ( <DatetimePicker value={props.value} onClose={this.onToggleCalendar} onSelect={(value) => props.onSelect(moment(value))} /> ) : null } </div> ) } }) const DateRange=function(props){ return ( <div className="menu" id="daterange"> <DatetimeItem label="From" value={props.start} onSelect={props.onStartChange} now={props.now} /> <DatetimeItem label="to" value={props.end} onSelect={props.onEndChange} now={props.now} /> </div> ) } export default DateRange
JavaScript
0
@@ -2224,48 +2224,8 @@ %7D,%0A - timePicker: (%0A %3CTimePicker /%3E%0A ),%0A re
9330df3e0dd5a8d465000e0504bb8887ef29eab4
Disable E2E tests
protractor.conf.js
protractor.conf.js
exports.config = { baseUrl: 'http://localhost:8000/', framework: 'jasmine', specs: 'e2e/**/*.test.js', capabilities: { browserName: 'phantomjs', shardTestFiles: true, maxInstances: 4, 'phantomjs.binary.path': './node_modules/phantomjs-prebuilt/bin/phantomjs' }, seleniumServerJar: 'node_modules/protractor/node_modules/webdriver-manager/selenium/selenium-server-standalone-3.4.0.jar', chromeDriver: './node_modules/protractor/node_modules/webdriver-manager/selenium/chromedriver_2.29', onPrepare: function () { browser.driver.manage().window().setSize(1024, 768); global.dp = require('./e2e/helpers/datapunt'); // dp.navigate requires that other helpers are already loaded, just making sure the others are initialized first global.dp.navigate = require('./e2e/helpers/navigate'); } };
JavaScript
0.000001
@@ -102,12 +102,16 @@ */*. -test +disabled .js'
d6b10175ccf46854262231efc9a6a22041153fa5
Fix example
packages/ag-grid-docs/src/javascript-grid-charts-customisation/saving-user-preferences/main.js
packages/ag-grid-docs/src/javascript-grid-charts-customisation/saving-user-preferences/main.js
var columnDefs = [ {field: "country", chartDataType: 'category'}, {field: "sugar", chartDataType: 'series'}, {field: "fat", chartDataType: 'series'}, {field: "weight", chartDataType: 'series'}, ]; var gridOptions = { defaultColDef: { width: 180, resizable: true }, popupParent: document.body, columnDefs: columnDefs, rowData: createRowData(), enableRangeSelection: true, enableCharts: true, createChartContainer: createChartContainer, processChartOptions: processChartOptions, onChartOptionsChanged: onChartOptionsChanged, onFirstDataRendered: onFirstDataRendered, }; // used to keep track of chart options per chart type var savedUserPreferenceByChartType = {}; // used to keep track of user's legend preferences var savedLegendUserPreference = undefined; function onChartOptionsChanged(event) { var chartOptions = event.chartOptions; // changes made by users via the format panel are being saved locally here, // however applications can choose to persist them across user sessions. savedLegendUserPreference = { legend: chartOptions.legend, legendPosition: chartOptions.legendPosition, legendPadding: chartOptions.legendPadding }; savedUserPreferenceByChartType[event.chartType] = chartOptions; } function processChartOptions(params) { var overriddenChartOptions = params.options; // use saved chart options for specific chart type if (savedUserPreferenceByChartType[params.type]) { overriddenChartOptions = savedUserPreferenceByChartType[params.type]; } // used shared legend user preference for all chart types if (savedLegendUserPreference) { overriddenChartOptions.legend = savedLegendUserPreference.legend; overriddenChartOptions.legendPosition = savedLegendUserPreference.legendPosition; overriddenChartOptions.legendPadding = savedLegendUserPreference.legendPadding; } // here we fix the chart and axis titles when a bubble chart is selected. if (params.type === 'bubble') { overriddenChartOptions.title = { text: 'Weights for individuals Sugar vs Fat intake', fontStyle: 'italic', fontWeight: 'bold', fontSize: 18, fontFamily: 'Arial, sans-serif', color: 'black' }; overriddenChartOptions.xAxis.title = { text: 'Sugar (g)', fontWeight: 'bold', fontSize: 14, fontFamily: 'Arial, sans-serif', color: 'black' }; overriddenChartOptions.yAxis.title = { text: 'Fat (g)', fontWeight: 'bold', fontSize: 14, fontFamily: 'Arial, sans-serif', color: 'black' }; } return overriddenChartOptions; } let currentChartRef; function createChartContainer(chartRef) { // destroy existing chart if (currentChartRef) { currentChartRef.destroyChart(); } var eChart = chartRef.chartElement; var eParent = document.querySelector('#myChart'); eParent.appendChild(eChart); currentChartRef = chartRef; } function onFirstDataRendered() { let params = { cellRange: { columns: ['sugar', 'fat', 'weight'] }, chartContainer: document.querySelector('#myChart'), chartType: 'bubble', suppressChartRanges: true }; chartRef = gridOptions.api.createRangeChart(params); } function createRowData() { let countries = ["Ireland", "Spain", "United Kingdom", "France", "Germany", "Luxembourg", "Sweden", "Norway", "Italy", "Greece", "Iceland", "Portugal", "Malta", "Brazil", "Argentina", "Colombia", "Peru", "Venezuela", "Uruguay", "Belgium"]; let rowData = []; countries.forEach( function(country) { rowData.push({ country: country, sugar: Math.floor(Math.floor(Math.random()*50)), fat: Math.floor(Math.floor(Math.random()*100)), weight: Math.floor(Math.floor(Math.random()*200)) }); }); return rowData; } // setup the grid after the page has finished loading document.addEventListener('DOMContentLoaded', function() { var gridDiv = document.querySelector('#myGrid'); new agGrid.Grid(gridDiv, gridOptions); });
JavaScript
0.998536
@@ -3207,16 +3207,39 @@ endered( +firstDataRenderedParams ) %7B%0A @@ -3465,24 +3465,31 @@ %7D;%0A%0A c +urrentC hartRef = gr @@ -3486,26 +3486,38 @@ rtRef = -gridOption +firstDataRenderedParam s.api.cr
3690bb2fc7b19bff7b578b2ab791d5a3698bf50a
fix module name
sample_project/demo/app.js
sample_project/demo/app.js
angular.bootstrap(document, ['grunt-angular-toolbox-sample']);
JavaScript
0.000005
@@ -32,26 +32,23 @@ runt --a +A ngular --t +T oolbox --s +S ampl
830ba79fe3bd5052923357cbb2b67e6fa9abac63
Update gulpfile
gulpfile.js
gulpfile.js
'use strict'; let gulp = require('gulp'), less = require('gulp-less'), sourcemaps = require('gulp-sourcemaps'), autoprefixer = require('gulp-autoprefixer'), concat = require('gulp-concat'), gutil = require('gulp-util'), chalk = require('chalk'); gulp.task('css-dev', function(){ gulp.src('assets/less/**/*.less') .pipe(sourcemaps.init()) .pipe(less()).on('error', function(error) { gutil.log('Error Less: ', '\'' + chalk.red(error.message)); }) .pipe(autoprefixer({ browsers: ['last 25 versions'], cascade: true })) .pipe(sourcemaps.init()) .pipe(concat('style.css')) .pipe(sourcemaps.write('./')) .pipe(gulp.dest('public/css')).on('end', function() { gutil.log(chalk.green('Success Less Compilation')); }); }); gulp.task('js-dev', function(){ gulp.src('assets/js/**/*.js') .pipe(sourcemaps.init()) .pipe(sourcemaps.write('./')) .pipe(gulp.dest('public/js')); }); gulp.task('watch', function(){ gulp.watch('assets/less/index.less', ['css-dev']); });
JavaScript
0.000001
@@ -249,24 +249,83 @@ ('chalk');%0A%0A +// %D0%98%D1%81%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D1%83%D0%B5%D0%BC Enter Point %D0%B4%D0%BB%D1%8F %D0%BF%D0%BE%D1%81%D0%BB%D0%B5%D0%B4%D0%BE%D0%B2%D0%B0%D1%82%D0%B5%D0%BB%D1%8C%D0%BD%D0%BE%D0%B9 %D0%BA%D0%BE%D0%BC%D0%BF%D0%B8%D0%BB%D1%8F%D1%86%D0%B8%D0%B8%0A%0A gulp.task('c @@ -368,20 +368,21 @@ ts/less/ -**/* +index .less')%0A
734467e27501e6c324165a3af90187578011df0a
fix linting errors
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var fs = require('fs'); var sourcemaps = require('gulp-sourcemaps'); var babel = require('gulp-babel'); var eslint = require('gulp-eslint'); var jscs = require('gulp-jscs'); gulp.task('build-npm', [ 'setupNpm', 'babel', 'lint' ]); // ----------------------------------------------------------------------------- // setup for development use gulp.task('setupDev', () => { getDevPluginXML(); setIosNpmOrDev('dev'); }) // setup for npm deployment gulp.task('setupNpm', () => { genNpmPluginXML(); setIosNpmOrDev('npm'); }); // generate plugin.xml for use as a cordova plugin // here we explode the contents of the frameworks function genNpmPluginXML() { var xml = fs.readFileSync('plugin.template.xml', 'utf-8'); var files = []; var root = 'src/ios/dependencies/'; files = files.concat(emitFiles(root + 'Fabric/')); files = files.concat(emitFiles(root + 'Branch-SDK/')); files = files.concat(emitFiles(root + 'Branch-SDK/Requests/')); var newLineIndent = '\n '; xml = xml.replace('<!--[Branch Framework Reference]-->', newLineIndent + files.join(newLineIndent)); fs.writeFileSync('plugin.xml', xml); }; // generate plugin.xml for local development // here we reference the frameworks instead of all the files directly function getDevPluginXML() { var xml = fs.readFileSync('plugin.template.xml', 'utf-8'); xml = xml.replace('<!--[Branch Framework Reference]-->', '<framework custom="true" src="src/ios/dependencies/Branch.framework" />'); fs.writeFileSync('plugin.xml', xml); }; function setIosNpmOrDev(npmOrDev) { if (npmOrDev === 'npm') { content = '#define BRANCH_NPM true'; } else if (npmOrDev === 'dev') { content = '//empty'; } else { throw new Error('expected deployed|local, not ' + deployedOrLocal); } fs.writeFileSync('src/ios/BranchNPM.h', content + '\n'); } // emit array of cordova file references for all .h/.m files in path function emitFiles(path) { var ret = []; for (filename of fs.readdirSync(path)) { var fileType = null; if (filename.match(/\.m$/)) { fileType = 'source'; } else if (filename.match(/\.h$/) || filename.match(/\.pch$/)) { fileType = 'header'; } if (fileType) { ret.push('<' + fileType + '-file src="' + path + filename + '" />'); } } ret.push(''); return ret; } // ----------------------------------------------------------------------------- // copy resources and compile es6 from corresponding directories babelTasks = []; // list of all babel tasks so we can build all of them function babelize(taskName, dir) { babelTasks.push(taskName + '-babel'); if (!dir) { dir = taskName; } var srcDir = dir + '.es6/'; var srcPattern = dir + '.es6/**/*.js' var destDir = dir + '/'; gulp.task(taskName + '-copy', () => { return gulp.src(srcDir + '**/*.*').pipe(gulp.dest(destDir)); }); gulp.task(taskName + '-babel', [ taskName + '-copy' ], () => { return gulp.src(srcPattern) .pipe(sourcemaps.init()) .pipe(babel({ presets: [ 'es2015', 'stage-2' ], plugins: [ 'transform-runtime' ] // needed for generators etc })) .pipe(sourcemaps.write('.')) .pipe(gulp.dest(destDir)); }); } babelize('hooks'); babelize('www'); babelize('tests'); babelize('testbed', 'testbed/www/js'); gulp.task('babel', babelTasks); // ----------------------------------------------------------------------------- // linting gulp.task('lint', [ 'eslint', 'jscs-lint' ]); var srcs = [ '**/*.js', '!node_modules/**', '!testbed/platforms/ios/cordova/node_modules/**' ]; gulp.task('eslint', () => { return gulp.src(srcs) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); }); function jscsTask(fix) { var ret = gulp.src('gulpfile.js') .pipe(jscs({ fix: fix })) .pipe(jscs.reporter()) .pipe(jscs.reporter('fail')); if (fix) { ret.pipe(gulp.dest('.')); } return ret; } gulp.task('jscs-fix', jscsTask.bind(null, true)); gulp.task('jscs-lint', jscsTask.bind(null, false));
JavaScript
0.000006
@@ -4088,12 +4088,13 @@ ll, false)); +%0A
0ad1722f173dc29a0228208c7e7ef886f0f906b2
Add overall gulp lint task.
gulpfile.js
gulpfile.js
'use strict'; var gulp = require('gulp'); var exec = require('child_process').exec; var sass = require('gulp-sass'); var merge = require('merge2'); var sourcemaps = require('gulp-sourcemaps'); var embedTemplates = require('gulp-angular-embed-templates'); var typescript = require('gulp-typescript'); var tsconfig = require('./tsconfig.json'); var tsProject = typescript.createProject(tsconfig.compilerOptions); var tslint = require('gulp-tslint'); var sassLint = require('gulp-sass-lint'); var sass_path = './strassengezwitscher/**/css/*.scss'; var ts_path = './frontend/**/*.ts'; var static_npm_file_paths = [ 'node_modules/bootstrap/dist/css/bootstrap.min.css', 'node_modules/bootstrap/dist/css/bootstrap.min.css.map', 'node_modules/rxjs/**/*', 'node_modules/angular2-in-memory-web-api/**/*', 'node_modules/@angular/**/*', 'node_modules/es6-shim/es6-shim.min.js', 'node_modules/zone.js/dist/zone.js', 'node_modules/reflect-metadata/Reflect.js', 'node_modules/systemjs/dist/system.src.js' ]; var static_lib_path = 'strassengezwitscher/static/lib/'; var static_complied_path = 'strassengezwitscher/static/compiled/'; gulp.task('copy:staticnpmfiles', function() { return gulp.src(static_npm_file_paths, {base: 'node_modules/'}) .pipe(gulp.dest(static_lib_path)); }); gulp.task('compile:sass', function() { return gulp.src(sass_path) .pipe(sourcemaps.init()) .pipe(sass().on('error', sass.logError)) .pipe(sourcemaps.write()) .pipe(gulp.dest(static_complied_path)); }); gulp.task('compile:typescript', function() { var tsResult = gulp.src(ts_path) .pipe(sourcemaps.init()) .pipe(typescript(tsProject)); return merge([ tsResult.dts.pipe(gulp.dest(static_complied_path)), tsResult.js .pipe(embedTemplates()) .pipe(sourcemaps.write()) .pipe(gulp.dest(static_complied_path)) ]); }); gulp.task('lint:python', function() { exec('prospector strassengezwitscher --uses django --strictness high', function (err, stdout, stderr) { console.log(stdout); console.log(stderr); }); }); gulp.task('lint:typescript', function() { return gulp.src(ts_path) .pipe(tslint()) .pipe(tslint.report("prose", { emitError: false, summarizeFailureOutput: true })); }); gulp.task('lint:sass', function() { return gulp.src(sass_path) .pipe(sassLint()) .pipe(sassLint.format()); }); gulp.task('watch:sass', ['compile:sass'], function() { return gulp.watch(sass_path, ['compile:sass']); }); gulp.task('watch:typescript', ['compile:typescript'], function() { return gulp.watch(ts_path, ['compile:typescript']); }); gulp.task('watch', ['watch:sass', 'watch:typescript']); gulp.task('default', function() { // place code for your default task here });
JavaScript
0
@@ -2501,32 +2501,101 @@ format());%0A%7D);%0A%0A +gulp.task('lint', %5B'lint:python', 'lint:typescript', 'lint:sass'%5D);%0A%0A gulp.task('watch
9f629c90c806f90e7bcd8e4862745629412c4051
test 1
gulpfile.js
gulpfile.js
var gulp = require('gulp'), del = require('del'), shell = require('gulp-shell'), ghPages = require('gulp-gh-pages'), argv = require('yargs').argv, gulpif = require('gulp-if'); /// Repo initialiazation, syncronization and cleanup gulp.task('sync', ['init'], shell.task('repo sync --no-tags -c')); gulp.task('init', shell.task('repo init -u https://github.com/azure/ref-docs')); gulp.task('clean', function(){ return del(['./.repo', './azure', './dist', './.publish']); }); /// Javadoc generation and publication gulp.task('java:pom', ['sync'], function(){ return gulp.src('./src/pom.xml').pipe(gulp.dest('./azure/java')); }); gulp.task('java:build', ['java:pom'], shell.task('mvn package javadoc:aggregate -DskipTests=true -q', {cwd: './azure/java'})); gulp.task('java:stage', ['java:build'], function(){ return gulp.src('./azure/java/target/site/apidocs/**/*').pipe(gulp.dest('./dist/java')); }); /// Top level build entry point gulp.task('stage', ['java:staget']); gulp.task('publish', ['stage'], function(){ return gulp.src('./dist/**/*').pipe(gulpif(!argv.dryrun, ghPages())); }); gulp.task('default', ['publish']);
JavaScript
0.000201
@@ -1124,16 +1124,17 @@ ', %5B'publish'%5D); +%0A
91e26432d55afb0847111c34eaa50f9fbcf86649
remove global for audio context
public/examples/scripts/audio.js
public/examples/scripts/audio.js
"use strict"; define(function() { // To play a sound, simply call audio.playSound(id), where id is // one of the keys of the g_sound_files array, e.g. "damage". var AudioManager = function(sounds, log) { var g_context; var g_audioMgr; var g_soundBank = {}; var g_canPlay = false; var g_canPlayOgg; var g_canPlayMp3; var g_canPlayWav; var g_canPlayAif; var g_createFn; var changeExt = function(filename, ext) { return filename.substring(0, filename.length - 3) + ext; }; function WebAudioSound(name, filename, samples, opt_callback) { this.name = name; var that = this; var req = new XMLHttpRequest(); req.open("GET", filename, true); req.responseType = "arraybuffer"; req.onload = function() { g_context.decodeAudioData(req.response, function onSuccess(decodedBuffer) { // Decoding was successful, do something useful with the audio buffer that.buffer = decodedBuffer; if (opt_callback) { opt_callback(); } }, function onFailure() { console.error("failed to decoding audio buffer: " + filename); }); } req.addEventListener("error", function(e) { console.error("failed to load:", filename, " : ", e.target.status); }, false); req.send(); } WebAudioSound.prototype.play = function(when) { if (!this.buffer) { console.log(this.name, " not loaded"); return; } var src = g_context.createBufferSource(); src.buffer = this.buffer; src.connect(g_context.destination); src.start(when); }; function AudioTagSound(name, filename, samples, opt_callback) { this.waiting_on_load = samples; this.samples = samples; this.name = name; this.play_idx = 0; this.audio = {}; for (var i = 0; i < samples; i++) { var audio = new Audio(); var that = this; audio.addEventListener("canplaythrough", function() { that.waiting_on_load--; if (opt_callback) { opt_callback(); } }, false); audio.src = filename; //audio.onerror = handleError(filename, audio); audio.load(); this.audio[i] = audio; } }; AudioTagSound.prototype.play = function(when) { if (this.waiting_on_load > 0) { console.log(this.name, " not loaded"); return; } this.play_idx = (this.play_idx + 1) % this.samples; var a = this.audio[this.play_idx]; // console.log(this.name, ":", this.play_idx, ":", a.src); var b = new Audio(); b.src = a.src; // TODO: use when b.addEventListener("canplaythrough", function() { b.play(); }, false); b.load(); }; var handleError = function(filename, audio) { return function(e) { console.error("can't load ", filename); } }; this.playSound = function(name, when) { if (!g_canPlay) return; var sound = g_soundBank[name]; if (!sound) { console.error("audio: '" + name + "' not known."); return; } sound.play(when); }.bind(this); this.getTime = function() { return g_context ? g_context.currentTime : Date.now() * 0.001; }.bind(this); // on iOS and possibly other devices you can't play any // sounds in the browser unless you first play a sound // in response to a user gesture. So, make something // to respond to a user gesture. var setupGesture = function() { var iOS = ( navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false ); var needUserGesture = iOS; if (needUserGesture) { var count = 0; var div = document.createElement('div'); div.style.position = "absolute"; div.style.left = "0px"; div.style.top = "0px"; div.style.width = window.innerWidth + "px"; div.style.height = window.innerHeight + "px"; div.style.zIndex = 10000000; div.style.overflow = "none"; div.style.backgroundColor = "rgba(128,128,255, 0.5)"; div.style.display = "flex"; div.style.textAlign = "center"; div.style.alignItems = "center"; div.style.justifyContent = "center"; div.style.fontSize = "4em"; div.style.color = "white"; div.innerText = "Tap Twice To Start"; var that = this; div.addEventListener('click', function() { ++count; if (count == 2) { // just playing any sound does not seem to work. var source = g_context.createOscillator(); source.frequency.value = 1; source.connect(g_context.destination); source.start(0); setTimeout(function() { source.disconnect(); }, 100); div.parentNode.removeChild(div); } }); document.body.appendChild(div); } }; this.loadSound = function(soundName, filename, samples, opt_callback) { var ext = filename.substring(filename.length - 3); if (ext == 'ogg' && !g_canPlayOgg) { filename = changeExt(filename, "mp3"); } else if (ext == 'mp3' && !g_canPlayMp3) { filename = changeExt(filename, "ogg"); } g_soundBank[soundName] = new g_createFn(soundName, filename, samples, opt_callback); }.bind(this); this.init = function(sounds) { var a = new Audio() g_canPlayOgg = a.canPlayType("audio/ogg"); g_canPlayMp3 = a.canPlayType("audio/mp3"); g_canPlayWav = a.canPlayType("audio/wav"); g_canPlayAif = a.canPlayType("audio/aif") || a.canPlayType("audio/aiff"); g_canPlay = g_canPlayOgg || g_canPlayMp3; if (!g_canPlay) return; var webAudioAPI = window.AudioContext || window.webkitAudioContext || window.mozAudioContext; if (webAudioAPI) { console.log("Using Web Audio API"); g_context = new webAudioAPI(); window.a = g_context; g_createFn = WebAudioSound; } else { console.log("Using Audio Tag"); g_createFn = AudioTagSound; } if (sounds) { for (var sound in sounds) { var data = sounds[sound]; this.loadSound(sound, data.filename, data.samples) } } if (webAudioAPI) { setupGesture(); } }.bind(this); this.init(sounds); }; return AudioManager; });
JavaScript
0.001374
@@ -6040,30 +6040,8 @@ ();%0A -window.a = g_context;%0A