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
2f86000c11a60ebae469095f604338e0052df3dd
Check if type main files exist before copying types to dist
scripts/templates/build.js
scripts/templates/build.js
const shell = require("shelljs"); const pino = require("pino")({ prettyPrint: { forceColor: true } }); const yargs = require("yargs"); const fs = require("fs"); const path = require("path"); const { paths, mergeDirectories } = require("../../lib/node"); const concat = require("../../lib/node/concatJs"); const { runScript } = require("../../lib/node/scripts"); const copyTypesToDist = function({ nameSpaceId }) { const typesSrcPath = paths.project(`typings/${nameSpaceId}`); const typesExist = fs.existsSync(typesSrcPath); if (!typesExist) { return; } const typesOutPath = paths.dist(`${nameSpaceId}/types`); if (!fs.existsSync(typesOutPath)) { return; } shell.cp("-r", typesSrcPath, typesOutPath); const mainFiles = fs.readdirSync(path.join(typesOutPath, "main")); mainFiles.forEach(fileName => { if (!fileName.endsWith("ts")) { return; } const typeProxyCode = `export * from "./types/main/${fileName.replace( ".d.ts", "" )}"`; fs.writeFileSync(paths.dist(`${nameSpaceId}/${fileName}`), typeProxyCode); }); }; const checkStaticTypes = function({ nameSpaceId }) { const result = require("./type")({ nameSpaceId: nameSpaceId }); return result.code === 0; }; const buildRawJsBundles = function({ minify = true, nameSpaceId, rawJsBundles }) { Object.entries(rawJsBundles).forEach(([fileName, bundle]) => { const outputPath = paths.dist(`${nameSpaceId}/${fileName}`); const concatOptions = Object.assign( { destination: outputPath, minify: minify }, bundle ); concat(concatOptions); }); }; const runWebpack = function({ testing, argv, useDevServer, nameSpaceId, endOfOptions }) { // Create webpack command let command = ""; command += "npx cross-env"; if (testing) { command += " TEST=1"; } if (argv.development) { command += " NODE_ENV=development"; } else { command += " NODE_ENV=production"; } if (argv.bundleAnalyzer) { command += " BUNDLE_ANALYZER=1"; } if (argv.watch) { command += " WATCH=1"; if (!testing && useDevServer) { command += " npx webpack-dev-server"; // To access the server from other devices command += " --host 0.0.0.0"; command += " --color"; } else { command += " npx webpack"; command += " --watch"; command += " --colors"; } } else { command += " npx webpack"; command += " --colors"; } command += ` --config ${paths.config(`${nameSpaceId}/webpack.config.js`)}`; command += ` ${endOfOptions}`; pino.info(command); shell.exec(command); }; const build = function({ nameSpaceId, useDevServer = false, useBundleAnalyzer = false, // Creates extra bundles with files which will be concatinated without webpack rawJsBundles = false, testing = false }) { let yargsOptions = { w: { alias: "watch", type: "boolean" }, d: { alias: "development", default: false, type: "boolean" }, t: { alias: "test", type: "boolean" } }; if (useBundleAnalyzer) { yargsOptions["bundle-analyzer"] = { type: "boolean" }; } const argv = yargs.options(yargsOptions).argv; const endOfOptions = argv._.join(" "); testing = testing || argv.test; if (!testing && !argv.watch) { if (!checkStaticTypes({ nameSpaceId })) { pino.error( "Error while checking the static types, please check previous logs" ); return; } } const outputPath = !testing ? paths.dist(nameSpaceId) : paths.testDist(nameSpaceId); // Custom version of clean-webpack-plugin =) shell.rm("-rf", outputPath); shell.mkdir("-p", outputPath); // Create raw js file bundles if (!testing) { if (rawJsBundles) { pino.info("Building raw js bundles"); buildRawJsBundles({ nameSpaceId, rawJsBundles, minify: !argv.development }); } // For "node" namespaces the svg script doesnt exist, we just ignore the err for now try { pino.info("Building svg sprites"); runScript({ scriptType: "svg", nameSpaceId }); } catch (err) {} } if (!testing && !argv.watch) { const staticDir = paths.static(nameSpaceId); if (fs.existsSync(staticDir)) { mergeDirectories({ sourceDir: staticDir, destinationDir: outputPath }); } } runWebpack({ testing, argv, nameSpaceId, useDevServer, endOfOptions }); if (!testing && !argv.watch) { copyTypesToDist({ nameSpaceId }); } }; module.exports = build;
JavaScript
0
@@ -573,56 +573,61 @@ nst -typesOutPath = paths.dist(%60$%7BnameSpaceId%7D/types%60 +mainTypeFilesSrcPath = path.join(typesSrcPath, %22main%22 );%0A @@ -646,24 +646,32 @@ stsSync( -typesOut +mainTypeFilesSrc Path)) %7B @@ -686,16 +686,76 @@ urn;%0A %7D +%0A%0A const typesOutPath = paths.dist(%60$%7BnameSpaceId%7D/types%60); %0A shell
909be0fe839a61616bc62e93176a7ceb7f8fdd55
Fix title rendering in redux example
example/redux/client/routes.js
example/redux/client/routes.js
/* @flow */ import React from 'react'; import { Route, IndexRoute } from 'react-router'; import { App, NotFound } from './components/App.js'; import Home, { Who, How } from './components/Pages.js'; import { LogIn, SignUp } from './components/SignUp.js'; /** * The route configuration for the whole app. */ export const routes = ( <Route path='/' title='Redux Example | Home' component={App}> <IndexRoute component={Home} /> {/* Pages */} <Route path='who' title='Redux Example | Who' component={Who} /> <Route path='how' title='Redux Example | How' component={How} /> {/* Account */} <Route path='log-in' title='Redux Example | Log In' component={LogIn} /> <Route path='sign-up' title='Redux Example | Sign Up' component={SignUp} /> {/* Not Found */} <Route path='*' title='Redux Example | Not Found' component={NotFound} /> </Route> ); export default routes;
JavaScript
0.000001
@@ -349,37 +349,8 @@ ='/' - title='Redux Example %7C Home' com @@ -378,16 +378,45 @@ dexRoute + title='Redux Example %7C Home' compone
88054912159f83017885f4c56c1978dbd4b4ccea
Fix loading... label (XHR)
data/console/xhr/response-tab.js
data/console/xhr/response-tab.js
/* See license.txt for terms of usage */ define(function(require, exports, module) { const React = require("react"); // Firebug SDK const { createFactories } = require("reps/rep-utils"); const { TreeView } = require("reps/tree-view"); const { Reps } = require("reps/repository"); // XHR Spy const { Json } = require("./json.js"); const { XhrUtils } = require("./xhr-utils.js"); // Shortcuts const DOM = React.DOM; /** * This template represents the 'Response' panel and is responsible * for rendering HTTP response body. */ var ResponseTab = React.createClass({ displayName: "ResponseTab", getInitialState: function() { return { data: {} }; }, isJson: function(content) { return Json.isJSON(content.mimeType, content.text); }, parseJson: function(file) { var content = file.response.content; var jsonString = new String(content.text); return Json.parseJSONString(jsonString, "http://" + file.request.url); }, isImage: function(content) { return XhrUtils.isImage(content.mimeType); }, isXml: function(content) { return false; }, render: function() { var actions = this.props.actions; var file = this.props.data; if (file.discardResponseBody) { return DOM.span({className: "netInfoBodiesDiscarded"}, Locale.$STR("xhrSpy.responseBodyDiscarded") ); } var content = file.response.content; if (!content.text) { actions.requestData("responseContent"); // xxxHonza: localization, real spinner return ( DOM.div("Loading...") ); } if (this.isImage(content)) { if (typeof content.text == "object") { // xxxHonza: localization, real spinner return ( DOM.div("Loading image...") ); } var dataUri = "data:" + content.mimeType + ";base64," + content.text; return ( DOM.img({src: dataUri}) ) } if (this.isJson(content)) { var json = this.parseJson(file); if (json) { return TreeView({ data: json, mode: "tiny" }); } } return ( DOM.div({className: "ResponseTabBox"}, DOM.div({className: "panelContent netInfoResponseContent"}, content.text ) ) ); } }); // Exports from this module exports.ResponseTab = ResponseTab; });
JavaScript
0
@@ -1408,24 +1408,36 @@ if (!content + %7C%7C !content .text) %7B%0A @@ -1549,32 +1549,36 @@ DOM.div( +%7B%7D, %22Loading...%22)%0A @@ -1752,16 +1752,20 @@ DOM.div( +%7B%7D, %22Loading
47ff752408b6688c155f84fee05393c6af0b82e5
Use POST
app.js
app.js
// Import express and request modules var express = require('express'); var request = require('request'); // Store our app's ID and Secret. These we got from Step 1. // For this tutorial, we'll keep your API credentials right here. But for an actual app, you'll want to store them securely in environment variables. var clientId = '200533262887.201265587335'; var clientSecret = '5b73aec95924431571f61471018e0228'; // Instantiates Express and assigns our app variable to it var app = express(); // Again, we define a port we want to listen to var port = process.env.PORT || 3000; // Lets start our server app.listen(port, function () { //Callback triggered when server is successfully listening. Hurray! console.log("Example app listening on port " + port); }); // This route handles GET requests to our root ngrok address and responds with the same "Ngrok is working message" we used before app.get('/', function(req, res) { res.send({ "Message": "Server up and running!", "RequestPath": req.url }) }); // Test route app.get('/test', function(req, res) { res.send("Chunk Norris is testing..."); }); // This route handles get request to a /oauth endpoint. We'll use this endpoint for handling the logic of the Slack oAuth process behind our app. app.get('/oauth', function(req, res) { // When a user authorizes an app, a code query parameter is passed on the oAuth endpoint. If that code is not there, we respond with an error message if (!req.query.code) { res.status(500); res.send({"Error": "Looks like we're not getting code."}); console.log("Looks like we're not getting code."); } else { // If it's there... // We'll do a GET call to Slack's `oauth.access` endpoint, passing our app's client ID, client secret, and the code we just got as query parameters. request({ url: 'https://slack.com/api/oauth.access', //URL to hit qs: {code: req.query.code, client_id: clientId, client_secret: clientSecret}, //Query string data method: 'GET', //Specify the method }, function (error, response, body) { if (error) { console.log(error); } else { res.json(body); } }) } }); // Route the endpoint that our slash command will point to and send back a simple response to indicate that ngrok is working app.post('/command', function(req, res) { res.send({"Message": "Server up and running!"}) });
JavaScript
0
@@ -1052,26 +1052,27 @@ t route%0Aapp. -ge +pos t('/test', f
16cd4c86e3081608e359346577dc1d07f6bed312
Add 'DOMContentLoaded' listeners for phantomJS
test/unit/modules/browser-events-spec.js
test/unit/modules/browser-events-spec.js
var assert = require('proclaim'); var Keen = require('../../../lib/browser'); describe('Keen.listenTo', function() { beforeEach(function(){ Keen.domEvents = {}; }); it('should be a function', function(){ assert.isFunction(Keen.listenTo); }); it('should create a Keen.domEvents object', function(){ Keen.listenTo({}); assert.isObject(Keen.domEvents); }); it('should set window events', function(){ var noop = function(e){ return false; }; Keen.listenTo({ 'click window': noop, 'keydown window': noop, 'keypress window': noop, 'keyup window': noop, 'mousedown window': noop, 'mousemove window': noop, 'mouseout window': noop, 'mouseover window': noop, 'mouseup window': noop, 'blur window': noop, 'focus window': noop, 'hashchange window': noop, 'resize window': noop, 'scroll window': noop }); assert.deepEqual(Keen.domEvents, { 'click window': noop, 'keydown window': noop, 'keypress window': noop, 'keyup window': noop, 'mousedown window': noop, 'mousemove window': noop, 'mouseout window': noop, 'mouseover window': noop, 'mouseup window': noop, 'blur window': noop, 'focus window': noop, 'hashchange window': noop, 'resize window': noop, 'scroll window': noop }); }); it('should set `<a>` events', function(){ var noop = function(e){ return false; }; Keen.listenTo({ 'click a': noop, 'mousedown a': noop, 'mousemove a': noop, 'mouseout a': noop, 'mouseover a': noop, 'mouseup a': noop }); assert.deepEqual(Keen.domEvents, { 'click a': noop, 'mousedown a': noop, 'mousemove a': noop, 'mouseout a': noop, 'mouseover a': noop, 'mouseup a': noop }); }); it('should set `<form>` events', function(){ var noop = function(e){ return false; }; Keen.listenTo({ 'submit form': noop, 'keydown form': noop, 'keypress form': noop, 'keyup form': noop, 'mousedown form': noop, 'mousemove form': noop, 'mouseout form': noop, 'mouseover form': noop, 'mouseup form': noop }); assert.deepEqual(Keen.domEvents, { 'submit form': noop, 'keydown form': noop, 'keypress form': noop, 'keyup form': noop, 'mousedown form': noop, 'mousemove form': noop, 'mouseout form': noop, 'mouseover form': noop, 'mouseup form': noop }); }); it('should handle `<a>` click events', function(){ var btn = document.getElementById('listen-to-anchor'); Keen.listenTo({ 'click a#listen-to-anchor': function(e){ Keen.log('click a#listen-to-anchor'); assert.ok(true); return false; } }); btn.click(); }); it('should handle `<form>` submit events', function(){ // var form = document.getElementById('listen-to-form'); var btn = document.getElementById('listen-to-form-btn'); Keen.listenTo({ 'submit form#listen-to-form': function(e){ Keen.log('submit form#listen-to-form'); assert.ok(true); return false; } }); btn.click(); // form.submit(); }); });
JavaScript
0
@@ -2601,32 +2601,163 @@ s', function()%7B%0A + if (window.mochaPhantomJS && document.addEventListener) %7B%0A document.addEventListener('DOMContentLoaded', function() %7B%0A var btn = do @@ -2795,24 +2795,28 @@ o-anchor');%0A + Keen.lis @@ -2821,32 +2821,36 @@ istenTo(%7B%0A + 'click a#listen- @@ -2874,32 +2874,36 @@ ion(e)%7B%0A + + Keen.log('click @@ -2916,32 +2916,36 @@ en-to-anchor');%0A + assert.o @@ -2953,32 +2953,36 @@ (true);%0A + return false;%0A @@ -2981,34 +2981,46 @@ alse;%0A -%7D%0A + %7D%0A + %7D);%0A + btn.clic @@ -3020,24 +3020,47 @@ tn.click();%0A + %7D, false);%0A %7D%0A %7D);%0A%0A it( @@ -3119,65 +3119,135 @@ -// var form = document.getElementById('listen-to-form');%0A +if (window.mochaPhantomJS && document.addEventListener) %7B%0A document.addEventListener('DOMContentLoaded', function() %7B%0A @@ -3303,24 +3303,28 @@ -btn');%0A + + Keen.listenT @@ -3319,32 +3319,36 @@ Keen.listenTo(%7B%0A + 'submit fo @@ -3380,32 +3380,36 @@ ion(e)%7B%0A + Keen.log('submit @@ -3432,32 +3432,36 @@ form');%0A + + assert.ok(true); @@ -3461,32 +3461,36 @@ (true);%0A + return false;%0A @@ -3483,24 +3483,28 @@ turn false;%0A + %7D%0A @@ -3499,28 +3499,36 @@ %7D%0A -%7D);%0A + %7D);%0A btn.clic @@ -3540,25 +3540,26 @@ -// form.submit(); + %7D, false);%0A %7D %0A %7D
2e390794edea210d70b64dbcbca932a70e788d4e
Use change event in device-orientation example
examples/device-orientation.js
examples/device-orientation.js
goog.require('ol.DeviceOrientation'); goog.require('ol.Map'); goog.require('ol.View2D'); goog.require('ol.dom.Input'); goog.require('ol.layer.Tile'); goog.require('ol.source.OSM'); var view = new ol.View2D({ center: [0, 0], zoom: 2 }); var map = new ol.Map({ layers: [ new ol.layer.Tile({ source: new ol.source.OSM() }) ], renderer: exampleNS.getRendererFromQueryString(), target: 'map', view: view }); var deviceOrientation = new ol.DeviceOrientation(); var track = new ol.dom.Input(document.getElementById('track')); track.bindTo('checked', deviceOrientation, 'tracking'); deviceOrientation.on('propertychange', function(event) { // event.key is the changed property name var element = document.getElementById(event.key); if (element) { element.innerHTML = deviceOrientation.get(event.key); } }); // tilt the map deviceOrientation.on(['change:beta', 'change:gamma'], function(event) { var center = view.getCenter(); var resolution = view.getResolution(); var beta = event.target.getBeta() || 0; var gamma = event.target.getGamma() || 0; center[0] -= resolution * gamma * 25; center[1] += resolution * beta * 25; view.setCenter(center); });
JavaScript
0
@@ -621,24 +621,16 @@ ion.on(' -property change', @@ -654,180 +654,251 @@ %7B%0A -// event.key is the changed property name%0A var element = document.getElementById(event.key);%0A if (element) %7B%0A element.innerHTML = deviceOrientation.get(event.key);%0A %7D +$('#alpha').text(deviceOrientation.getAlpha() + ' %5Brad%5D');%0A $('#beta').text(deviceOrientation.getBeta() + ' %5Brad%5D');%0A $('#gamma').text(deviceOrientation.getGamma() + ' %5Brad%5D');%0A $('#heading').text(deviceOrientation.getHeading() + ' %5Brad%5D'); %0A%7D);
770b16660503dea4a67675aaff0191eee1c272a3
remove unused comma
src/rules.js
src/rules.js
// rules // TODO: // Waiting for URL Pattern specs // https://developer.mozilla.org/en-US/docs/Web/API/URLPattern export const rules = [ { patterns: [ /http(s?):\/\/thanhnien.vn\/*/ ], unwanted: [ '.morenews', '.zone--media', '.zone--timeline' ] }, { patterns: [ /http(s?):\/\/zingnews.vn\/*/ ], unwanted: [ '.the-article-category', '.the-article-meta', '.the-article-tags' ] }, { patterns: [ /http(s?):\/\/([\w]+.)?vnexpress.net\/*/ ], unwanted: [ '.header-content' ] }, { patterns: [ /http(s?):\/\/([\w]+.)?vietnamnet.vn\/*/, /http(s?):\/\/([\w]+.)?vnn.vn\/*/ ], selector: '#ArticleContent', unwanted: [ '.inner-article', '.article-relate' ] }, { patterns: [ /thehill.com\/*/ ], unwanted: [ '.rollover-people-block' ] }, { patterns: [ /http(s?):\/\/([\w]+.)?digitaltrends.com\/*/ ], unwanted: [ '.h-editors-recs-title', 'ul.h-editors-recs' ] }, { patterns: [ /http(s?):\/\/([\w]+.)?techradar.com\/*/ ], unwanted: [ 'nav.breadcrumb' ] }, ]
JavaScript
0.004075
@@ -1202,12 +1202,11 @@ %5D%0A %7D -, %0A%5D%0A
9cf300b99893d86338d849c8b6d134bb181881b6
test for port
app.js
app.js
// Clapp.Kerberos // v. 0.1.0 console.log('\n\t\t\t\t== Clapp.Kerberos =='); // ======================= // libraries ========= // ======================= var express = require("express"); var app = express(); var path = require('path'); var http = require('http').Server(app); var io = require("socket.io")(http); var bodyParser = require('body-parser'); var morgan = require('morgan'); var mongoose = require('mongoose'); var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens var checkInternet = require('is-online'); var globals = require('./app/controllers/global'); var frontend = require('./app/controllers/frontend'); var routes = require('./app/controllers/routes'); var socketController = require('./app/controllers/socket'); console.log('\nLibs imported'); // ======================= // configuration ========= // ======================= var port = 5000; var isOnline = true; // use body parser so we can get info from POST and/or URL parameters app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); // ======================= // initialize modules ========= // ======================= frontend.initialize(app, express, path); routes.initialize(app, express); socketController.initialize(io, globals); console.log('modules initialized'); // ======================= // listening app ========= // ======================= io.listen(app.listen(port)); console.log('Listening on port ' + port);
JavaScript
0.000001
@@ -916,9 +916,9 @@ t = -5 +3 000;
b2521a5a0d14e1c5dc717054d8e645f1e1c17ee6
Add more endpoints, and default to US if none provided
app.js
app.js
// See https://github.com/yagop/node-telegram-bot-api var TelegramBot = require('node-telegram-bot-api'); // See https://github.com/t3chnoboy/amazon-product-api var amazon = require('amazon-product-api'); // List of supported Amazon endpoints var amazonEndpoints = { 'IT' : 'webservices.amazon.it' }; // Telegram API Token var token = process.env.TELEGRAM_API_TOKEN || ''; // Create the Bot var bot = new TelegramBot( token, { webHook: { port: process.env.PORT || '3000' } } ); // Listen on WebHooks bot .setWebHook( process.env.BASE_URL + '/' + process.env.WEBHOOK_TOKEN ); // Once the user is searching... bot .on( 'inline_query', function ( message ){ if ( message.query ) { // Get the country where to query var query = message.query.split('@')[0], country = ( message.query.split('@')[1] || '').toUpperCase(); if ( country in amazonEndpoints ) { // Create the Amazon Client var client = amazon.createClient({ awsId: process.env.AMAZON_ACCESS_ID || '', awsSecret: process.env.AMAZON_SECRET_ACCESS_KEY || '', awsTag: process.env['AMAZON_ASSOCIATE_TAG_' + country] || '' }); client.itemSearch( { keywords: query, searchIndex: 'All', responseGroup: 'Images,ItemAttributes,OfferSummary', domain: amazonEndpoints[ country ] }, function (error, results) { if (error) { // Craft error message answerUser( message, [{ type: 'article', id: '000', title: 'Unknown Error', input_message_content: { message_text: "Sorry, something bad happened. Please try later :(" }, url: '', hide_url: true, thumb_url: '', thumb_width: 64, thumb_height: 64 }] ) } else { var answers = []; for ( var k in results ) { var item = results[k]; answers .push( { type: 'article', id: item.ASIN[0], title: '[' + item.OfferSummary[0].LowestNewPrice[0].FormattedPrice[0] + '] ' + item.ItemAttributes[0].Title[0], input_message_content: { message_text: item.ItemAttributes[0].Title[0] + '\n\n*Lowest Price:* ' + item.OfferSummary[0].LowestNewPrice[0].FormattedPrice[0] + '\n[See Article](' + item.DetailPageURL[0] + ')', parse_mode: 'Markdown' }, url: item.DetailPageURL[0], hide_url: false, thumb_url: item.ImageSets[0].ImageSet[0].SmallImage[0].URL[0], thumb_width: parseInt( item.ImageSets[0].ImageSet[0].SmallImage[0].Width[0]['_'] ), thumb_height: parseInt( item.ImageSets[0].ImageSet[0].SmallImage[0].Height[0]['_'] ) } ); } answerUser( message, answers ) } } ) } else { // Craft unsupported message answerUser( message, [{ type: 'article', id: '000', title: 'Unsupported country', input_message_content: { message_text: "Sorry, I do not support the country you're asking for :(" }, url: '', hide_url: true, thumb_url: '', thumb_width: 64, thumb_height: 64 }] ) } } }); var answerUser = function ( message, answer ) { // Craft answer bot .answerInlineQuery( message.id, answer ); }
JavaScript
0
@@ -269,36 +269,244 @@ %0A ' -IT' : 'webservices.amazon.it +US' : 'webservices.amazon.com',%0A 'CA' : 'webservices.amazon.ca',%0A 'IT' : 'webservices.amazon.it',%0A 'DE' : 'webservices.amazon.de',%0A 'UK' : 'webservices.amazon.co.uk',%0A 'ES' : 'webservices.amazon.es',%0A 'FR' : 'webservices.amazon.fr '%0A%7D; @@ -1061,24 +1061,181 @@ perCase();%0A%0A + // Force the Amazon.com search if no country given%0A if ( !country ) country = 'US';%0A%0A // If the country is given, always check if it's in the list%0A if ( cou @@ -1258,24 +1258,25 @@ dpoints ) %7B%0A +%0A // Cre
8e36afd1e50b91efcbf606cddbc5aa1dcc59430d
disable ubidots, enable beebotte
app.js
app.js
/* * before anything else, make __root available */ // global.$__root = __dirname; var config = require('./config'); // console.log('CONFIG', config) // var express = require('./lib/liveio'); var express = require('express'); //Configure DB require('./lib/setup/db')(config.db); //MODELS require('./models')(); var app = express(); // Bootstrap passport config require('./models/user'); //TODO: Break loading models from RESTful require('./lib/setup/authentication')(app, config); require('./lib/setup/server')(app, config); //SOCKETS.IO app.on('app.pre', function(payload){ require('./middleware/sockets')(app, payload.server); require('./clients/ubidots')(app, payload.server); }); //ROUTES require('./routes/index')(app); require('./routes/users')(app); require('./routes/sensor')(app); require('./controllers')(app, config); require('./config/advertise')(config.advertise); //We include error handler routes after MODELS //because, for now, we handle RESTul API there. //TODO: Refactor! require('./routes/errors')(app); module.exports = app;
JavaScript
0
@@ -634,24 +634,83 @@ server);%0A + require('./clients/beebotte')(app, payload.server);%0A // require('./
0ac146c6b6f0b54a355275d6d4ecfec6c2d2cb3e
use 2 space as tab indention
app.js
app.js
var restify = require('restify'); var mongoose = require('mongoose'); var config = require('./config'); var restifyRoutes = require('restify-routes'); var server = restify.createServer({ name: 'lybica', version: '1.0.0' }); server.use(restify.acceptParser(server.acceptable)); server.use(restify.queryParser()); server.use(restify.bodyParser()); server.use(function(req, res, next) { res.header('Access-Control-Allow-Origin', '*'); return next(); }); restifyRoutes.set(server, __dirname + '/routes'); mongoose.connect(config.DB_URL); server.listen(config.PORT, function() { console.log('%s listening at %s', server.name, server.url); });
JavaScript
0
@@ -181,18 +181,16 @@ erver(%7B%0A - name: @@ -199,18 +199,16 @@ ybica',%0A - versio @@ -384,18 +384,16 @@ next) %7B%0A - res.he @@ -434,18 +434,16 @@ , '*');%0A - return @@ -581,18 +581,16 @@ ion() %7B%0A - consol
446e2d08020fa51c1077a137b3c3bd6e9d94bf9f
Add empty line at the end of file
test/acceptance/mvt.js
test/acceptance/mvt.js
require('../support/test_helper'); const assert = require('../support/assert'); const TestClient = require('../support/test-client'); function createMapConfig (sql = TestClient.SQL.ONE_POINT) { return { version: '1.6.0', layers: [{ type: "cartodb", options: { sql: sql, cartocss: TestClient.CARTOCSS.POINTS, cartocss_version: '2.3.0', interactivity: 'cartodb_id' } }] }; } describe('mvt', function () { const testCases = [ { desc: 'should get empty mvt with code 204 (no content)', coords: { z: 0, x: 0, y: 0 }, format: 'mvt', status: 204, mapConfig: createMapConfig(TestClient.SQL.EMPTY) }, { desc: 'should get mvt tile with code 200 (ok)', coords: { z: 0, x: 0, y: 0 }, format: 'mvt', status: 200, mapConfig: createMapConfig() } ]; testCases.forEach(function (test) { it(test.desc, done => { const testClient = new TestClient(test.mapConfig, 1234); const { z, x, y } = test.coords; const { format, status } = test; testClient.getTile(z, x, y, { format, status }, (err, res) => { assert.ifError(err); assert.equal(res.statusCode, test.status); testClient.drain(done); }); }); }); });
JavaScript
0.000006
@@ -1507,8 +1507,9 @@ %7D);%0A%7D); +%0A
719afc5779ee929c4c1c84cae50a4ca85605f112
Fix redis inconsistencies
app.js
app.js
// Require dependencies var express = require('express'); var app = express(); var http = require('http'); var server = http.createServer(app); var io = require('socket.io').listen(server); var redis = require('redis'); var client = redis.createClient(); // assuming io is the Socket.IO server object io.configure(function () { io.set("transports", ["xhr-polling"]); io.set("polling duration", 10); }); var storeMessage = function(name, data) { var message = JSON.stringify({name: name, data: data}); redisClient.lpush("messages", message, function(err, response) { redisClient.ltrim("messages", 0, 10); }); }; // Listen for connections io.sockets.on('connection', function(socket) { socket.on('join', function(name) { redisClient.lrange("messages", 0, -1, function(err, messages){ messages = messages.reverse(); messages.forEach(function(message) { message = JSON.parse(message); socket.emit("messages", '<div id="messagecontainer"><div class="username">' + message.name + ': </div><div class="usermessage">' + message.data + '</div></div>'); }); }); console.log("Someone is connecting..."); socket.set('nickname', name); console.log(name+" has connected!"); socket.emit("connected", name + " joined the chat"); }); // Receive messages from the client and broadcast them to everyone socket.on('messages', function(data) { data = data.replace(/\n/g, '<br />'); socket.get('nickname', function(err, name) { storeMessage(name, data); socket.emit("messages", '<div id="messagecontainer"><div class="username">' + name + ': </div><div class="usermessage">' + data + '</div></div>'); }); }); }); // Without this line, the CSS will not work app.use('/public', express.static(__dirname + '/public')); // Route index.html to the root path app.get('/', function(request, response) { response.sendfile(__dirname + "/index.html"); }); // Listen for GET requests to the server var port = process.env.PORT || 5000; server.listen(port, function() { console.log("Listening on port " + port); });
JavaScript
0.999973
@@ -216,28 +216,8 @@ is') -;%0Avar client = redis .cre @@ -493,22 +493,16 @@ %0A redis -Client .lpush(%22 @@ -556,22 +556,16 @@ redis -Client .ltrim(%22 @@ -715,22 +715,16 @@ redis -Client .lrange(
8c913b06eafdf3491e3bb3336e764d1e6eadf15d
Fix #16 Add next() to routes for files ending in .html, corrects the bug where headers were already sent before Express could set basic headers for terminal server messages.
app.js
app.js
/* NOTE: Does NOT work when placed in the js folder, even when adding /../ before routes! */ // require the express module, set to variable called app var express = require('express'), app = express(), path = require('path'), port = 3000; // set a route for the root of the server app.get('/', function(req, res) { res.sendFile(path.join(__dirname + '/index.html')); }); // other routes app.get('/index.html', function(req, res) { res.sendFile(path.join(__dirname + '/index.html')); }); app.get('/about-us.html', function(req, res) { res.sendFile(path.join(__dirname + '/about-us.html')); }); app.get('/package.json', function(req, res) { res.sendFile(path.join(__dirname + '/package.json')); }); // CSS app.use('/css', function(req, res, next) { res.sendFile(path.join(__dirname + '/css/default.css')); next(); }); // static server to serve CSS files app.use('/css', express.static('css')); // Javascript app.use('/js', function(req, res, next) { // console.log(req.path + " was requested."); next(); }); // static server to serve js files app.use('/js', express.static('js')); // static server to serve image files app.use('/images', express.static('images')); // requires the api.js file for later implementation of snoCountry API // var api = require('/api.js'); // app.use('/api', api); ////////////////////////////////////////////////////////// // hosted locally & listening for requests on port 3000 // app.listen( port, function() { console.log("Front-end server is running." + " " + "Go to localhost:" + port + " to view SnowTracks!"); } );
JavaScript
0
@@ -310,32 +310,38 @@ unction(req, res +, next ) %7B%0A res.sendFi @@ -378,24 +378,34 @@ ex.html'));%0A + next();%0A %7D);%0A%0A// othe @@ -445,32 +445,38 @@ unction(req, res +, next ) %7B%0A res.sendFi @@ -509,32 +509,42 @@ /index.html'));%0A + next();%0A %7D);%0A%0Aapp.get('/a @@ -567,32 +567,38 @@ unction(req, res +, next ) %7B%0A res.sendFi @@ -638,24 +638,34 @@ us.html'));%0A + next();%0A %7D);%0A%0Aapp.get
87fc902b6f2d8c2e7e59244be1c4f783bf559ab3
Test /style.css
test/app/index.test.js
test/app/index.test.js
const app = require('../../app') const request = require('supertest') const t = require('tap') const { version } = require('../../package.json') t.test('/healthz') t.test('/version', (t) => request(app) .get('/version') .expect('Content-Type', /text\/plain/) .expect(200) .expect(version) ) t.test('/style.css') t.test('/hooks/reload/posts') t.test('/feed', (t) => request(app) .get('/feed') .expect('Content-Type', /rss/) .expect(200) .expect(/Feed of the front page/) .expect(/my birthday today/) .expect(/A verb./) .expect(/Install mosh/) ) t.test('/', (t) => request(app) .get('/') .expect('Content-Type', /html/) .expect(200) .expect(/article class/) ) t.test('/tag/:tag', (t) => request(app) .get('/tag/linux') .expect('Content-Type', /html/) .expect(200) .expect(/Tag: linux/) .expect(/Ever encountered this/) ) t.test('/2014/may/04/today', (t) => request(app) .get('/2014/may/04/today') .expect('Content-Type', /html/) .expect(200) .expect(/#StarWarsDay/) .expect(/<title>\s*Today/) ) t.test('/not-found', (t) => request(app) .get('/not-found') .expect('Content-Type', /html/) .expect(404) .expect(/<title>\s*Not Found/) ) t.test('/2010/jan/10/not-found', (t) => request(app) .get('/2010/jan/10/not-found') .expect('Content-Type', /html/) .expect(404) .expect(/<title>\s*Not Found/) )
JavaScript
0.000001
@@ -314,17 +314,144 @@ yle.css' -) +, (t) =%3E request(app)%0A .get('/style.css')%0A .expect('Content-Type', /css/)%0A .expect(200)%0A .expect(/%5C*%5Cs*%5C%7B%5Cs*box-sizing:/)%0A)%0A %0At.test(
832b9bc1d5cacf67f1882c6f821f0b0ed4b7cdf8
Update mood calculation
app.js
app.js
// Connecting dependencies var Twitter = require('twitter'); var dotenv = require('dotenv'); var five = require('johnny-five'); var board = new five.Board(); // Loading environment variables dotenv.load(); // Connecting to Twitter var client = new Twitter({ consumer_key: process.env.TWITTER_CONSUMER_KEY, consumer_secret: process.env.TWITTER_CONSUMER_SECRET, access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY, access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET, }); var tweetsPerPage = 100; // Maximum of 100 var count; // Used as Mood Count // Static declaration of moods var moodNames = [ "love", "joy", "suprise", "anger", "envy", "sadness", "fear" ]; // Assigns colors to moods var moodColors = { love: '#ff9cce', joy: '#ffff94', suprise: '#ffa500', anger: '#ff4d4d', envy: '#009a00', sadness: '#1e90ff', fear: '#ffffff' } // Levels data to comparable numbers var moodAmplifier = { love: 0.87, joy: 0.85, suprise: 0.75, anger: 0.86, envy: 0.84, sadness: 0.88, fear: 0.90 } // Queries corresponding to certain moods var queries = { love: '\"i+love+you\"+OR+\"i+love+her\"+OR+\"i+love+him\"+OR+\"all+my+love\"+OR+\"i\'m+in+love\"+OR+\"i+really+love\"', joy: '\"happiest\"+OR+\"so+happy\"+OR+\"so+excited\"+OR+\"i\'m+happy\"+OR+\"woot\"+OR+\"w00t\"', suprise: '\"wow\"+OR+\"O_o\"+OR+\"can\'t+believe\"+OR+\"wtf\"+OR+\"unbelievable\"', anger: '\"i+hate\"+OR+\"really+angry\"+OR+\"i+am+mad\"+OR+\"really+hate\"+OR+\"so+angry\"', envy: '\"i+wish+i\"+OR+\"i\'m+envious\"+OR+ \"i\'m+jealous\"+OR+\"i+want+to+be\"+OR+\"why+can\'t+i\"', sadness: '\"i\'m+so+sad\"+OR+\"i\'m+heartbroken\"+OR+\"i\'m+so+upset\"+OR+\"i\'m+depressed\"+OR+\"i+can\'t+stop+crying\"', fear: '\"i\'m+so+scared\"+OR+\"i\'m+really+scared\"+OR+\"i\'m+terrified\"+OR+\"i\'m+really+afraid\"+OR+\"so+scared+i\"' }; // Determines if Tweet was posted in the last 30 seconds function parseTwitterDate(tdate) { var system_date = new Date(Date.parse(tdate)); var user_date = new Date(); var diff = Math.floor((user_date - system_date) / 1000); if (diff <= 30) { return true; // 30 sec or less } else { return false; // More 30 sec } } // Updates LED color according to Results function analyzeResults(results) { var worldMood = 'love'; moodNames.forEach(function(mood) { if (results[mood] > results[worldMood]) { worldMood = mood; } }); console.log(results); // Change LED color // var led = new five.Led.RGB([6, 5, 3]); // led.color(moodColors[worldMood]); console.log("Changing the LED color to " + moodColors[worldMood] + ", or " + worldMood); } // Searches for Tweets function findWorldMood() { var results = { love: 0, joy: 0, suprise: 0, anger: 0, envy: 0, sadness: 0, fear: 0 }; count = 0; moodNames.forEach(function(mood) { var today = (new Date()).toISOString().slice(0,10); var yesterday = (new Date(new Date() - 24*60*60*1000)).toISOString().slice(0,10); client.get('search/tweets', {q: queries[mood] + "since:" + yesterday, result_type: 'recent', count: tweetsPerPage}, function(error, tweets, response) { if (error) { console.error(error); process.exit(1); } count++; tweets.statuses.forEach(function(tweet) { if(parseTwitterDate(tweet.created_at)) { results[mood]++; // Increment Tweet Count } }); if (count === moodNames.length) { moodNames.forEach(function(mood) { results[mood] *= moodAmplifier[mood]; // Level Results }); analyzeResults(results); } }); }); } setInterval(findWorldMood, 35 * 1000); // Runs every 35 seconds (Not to exceed API Request Limit of 180 requests per 15 minutes) board.on('ready', function() { // setInterval(findWorldMood, 35 * 1000); // Runs every 35 seconds (Not to exceed API Request Limit of 180 requests per 15 minutes) });
JavaScript
0
@@ -923,25 +923,23 @@ var mood -Amplifier +Compare = %7B%0A l @@ -947,12 +947,10 @@ ve: +8 0 -.87 ,%0A @@ -954,19 +954,17 @@ %0A joy: -0.8 +2 5,%0A sup @@ -973,12 +973,10 @@ se: +8 0 -.75 ,%0A @@ -986,12 +986,10 @@ er: -0.86 +28 ,%0A @@ -998,12 +998,9 @@ vy: -0.84 +1 ,%0A @@ -1012,12 +1012,9 @@ ss: -0.88 +1 ,%0A @@ -1023,12 +1023,9 @@ ar: -0.90 +1 %0A%7D%0A%0A @@ -2091,18 +2091,18 @@ diff %3C= -30 +25 ) %7B%0A @@ -2287,19 +2287,22 @@ Mood = ' -lov +supris e';%0A mo @@ -2420,32 +2420,8 @@ %7D);%0A - console.log(results);%0A // @@ -3509,24 +3509,22 @@ od%5D -* +- = mood -Amplifier +Compare %5Bmoo @@ -3633,34 +3633,34 @@ (findWorldMood, -35 +40 * 1000); // Run @@ -3659,34 +3659,34 @@ ; // Runs every -35 +40 seconds (Not to
24e00a8da594e11061a5bd9f3c49913caf7ef03e
remove views and change error handling
app.js
app.js
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var http = require ('http'); var mongoose = require('mongoose'); var uristring = process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || 'mongodb://localhost/GroupCollab'; var theport = process.env.PORT || 5000; mongoose.connect(uristring, function (err, res) { if (err) { console.log ('ERROR connecting to: ' + uristring + '. ' + err); } else { console.log ('Successfully connected to: ' + uristring); } }); var app = express(); var api = require('./routes/api'); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/api', api); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = app;
JavaScript
0
@@ -209,24 +209,60 @@ y-parser');%0A +var passport = require('passport');%0A var http = r @@ -741,111 +741,8 @@ );%0A%0A -// view engine setup%0Aapp.set('views', path.join(__dirname, 'views'));%0Aapp.set('view engine', 'jade');%0A%0A // u @@ -997,76 +997,51 @@ use( -express.static(path.join(__dirname, 'public')));%0Aapp.use('/api', api +'/api', api);%0Aapp.use(passport.initialize() );%0A%0A @@ -1389,80 +1389,44 @@ -res.rende +console.erro r( -' err -or', %7B%0A message: err.message,%0A error: err%0A %7D +);%0A res.send(err );%0A @@ -1573,73 +1573,50 @@ ;%0A -res.render('error', %7B%0A message: err.message,%0A error: %7B%7D%0A %7D +console.error(err);%0A res.send(err.message );%0A%7D
9ea654138d4de9fd373de46bee83396cde8a6a05
fix a test for ws
test/arraybuffer/ws.js
test/arraybuffer/ws.js
var expect = require('expect.js'); var eio = require('../../'); describe('arraybuffer', function() { this.timeout(30000); it('should be able to receive binary data when bouncing it back (ws)', function(done) { var binaryData = new Int8Array(5); for (var i = 0; i < 5; i++) { binaryData[i] = i; } var socket = new eio.Socket(); socket.on('open', function() { socket.on('upgrade', function() { socket.send(binaryData); socket.on('message', function (data) { if (typeof data === 'string') return; expect(data).to.be.an(ArrayBuffer); expect(new Int8Array(data)).to.eql(binaryData); socket.close(); done(); }); }); }); }); it('should be able to receive binary data and a multibyte utf-8 string (ws)', function(done) { var binaryData = new Int8Array(5); for (var i = 0; i < 5; i++) { binaryData[i] = i; } var msg = 0; var socket = new eio.Socket({ transports: ['polling'] }); socket.on('open', function() { socket.send(binaryData); socket.send('cash money €€€'); socket.on('message', function (data) { if (data === 'hi') return; if (msg == 0) { expect(data).to.be.an(ArrayBuffer); expect(new Int8Array(data)).to.eql(binaryData); msg++; } else { expect(data).to.be('cash money €€€'); socket.close(); done(); } }); }); }); it('should be able to receive binary data when bouncing it back and forcing base64 (ws)', function(done) { var binaryData = new Int8Array(5); for (var i = 0; i < 5; i++) { binaryData[i] = i; } var socket = new eio.Socket({ forceBase64: true }); socket.on('open', function() { socket.on('upgrade', function() { socket.send(binaryData); socket.on('message', function (data) { if (typeof data === 'string') return; expect(data).to.be.an(ArrayBuffer); expect(new Int8Array(data)).to.eql(binaryData); socket.close(); done(); }); }); }); }); });
JavaScript
0.003096
@@ -993,35 +993,8 @@ ket( -%7B transports: %5B'polling'%5D %7D );%0A @@ -1019,32 +1019,74 @@ ', function() %7B%0A + socket.on('upgrade', function() %7B%0A socket.sen @@ -1096,24 +1096,26 @@ inaryData);%0A + socket @@ -1141,24 +1141,26 @@ %E2%82%AC%E2%82%AC');%0A + socket.on('m @@ -1190,24 +1190,26 @@ ) %7B%0A + if (data === @@ -1228,24 +1228,26 @@ n;%0A%0A + + if (msg == 0 @@ -1246,24 +1246,26 @@ msg == 0) %7B%0A + ex @@ -1290,32 +1290,34 @@ n(ArrayBuffer);%0A + expect @@ -1372,15 +1372,19 @@ + msg++;%0A + @@ -1398,32 +1398,34 @@ lse %7B%0A + + expect(data).to. @@ -1448,32 +1448,34 @@ %E2%82%AC%E2%82%AC');%0A + socket.close();%0A @@ -1466,32 +1466,34 @@ socket.close();%0A + done() @@ -1498,25 +1498,39 @@ ();%0A -%7D + %7D%0A %7D); %0A %7D);%0A
8baf6d090174c104e3053153bbf0cf27f7acd13d
add body-parser
server/index.js
server/index.js
const React = require('react'); const { renderToStaticMarkup } = require('react-dom/server'); const { match, RouterContext } = require('react-router'); const express = require('express'); const path = require('path'); const pug = require('pug'); const webpack = require('webpack'); const { port, isDev } = require('./config'); const webpackConfig = require('../webpack/client.dev.js'); const api = require('./api'); const initDb = require('./db'); const compiler = webpack(webpackConfig); const app = express(); app.use(express.static('public')); app.use('/api', api); app.set('view engine', 'pug'); app.set('port', port); if (isDev) { app.use(require('webpack-hot-middleware')(compiler)); app.use(require('webpack-dev-middleware')(compiler, { noInfo: true, publicPath: webpackConfig.output.publicPath })); } initDb(() => { app.get('*', (req, res) => { res.render('index', {}); }); app.listen(port, 'localhost', (err) => { if (err) { if (isDev) { console.log(err); } return false; } console.log(`Listening at http://localhost:${port}`); }); });
JavaScript
0.002976
@@ -274,16 +274,59 @@ bpack'); +%0Aconst bodyParser = require('body-parser'); %0A%0Aconst @@ -559,16 +559,96 @@ app.use( +bodyParser.urlencoded(%7B extended: true %7D));%0Aapp.use(bodyParser.json());%0Aapp.use( express. @@ -667,30 +667,8 @@ ic') -);%0Aapp.use('/api', api );%0Aa @@ -719,16 +719,38 @@ , port); +%0Aapp.use('/api', api); %0A%0Aif (is
1921bfddb726eac93abd89e8b7668bf912cd38fb
change ip detection
app.js
app.js
//Required modules var request = require('request'); var express = require('express'); var app = express(); var server = require('http').createServer(app); var io = require('socket.io')(server); app.set('port', (process.env.PORT || 5000)); app.use(express.static(__dirname + '/public')); //Routes app.get('/', function(req, res) { console.log('new connection: ' + request.connection.remoteAddress); res.sendFile(__dirname + '/index.html'); }); /* CODE */ var users = []; io.on('connection', function(socket) { var address = socket.handshake.address; //Event 'join' socket.on('join', function(data) { socket.nickname = data; console.log(socket.nickname + " joins from " + address); var url = 'http://api.hostip.info/get_json.php?ip=' + address; //we call the api to get the country request.get(url, function(error, response, body) { var location = JSON.parse(body); var newUser = { 'nickname': data, 'loginDate': Date.now(), 'address': address, 'country': location.country_name } users.push(newUser); io.emit('join', newUser); //i send the event 'join' to all users }); }); //Event 'sound' socket.on('sound', function(data) { var msg = socket.nickname + ' playing sound ' + data; var sendData = { 'number': data, 'message': msg }; console.log(msg); io.emit('sound', sendData); //i send the sound to all }); //Event 'disconnect' socket.on('disconnect', function() { var msg = socket.nickname + ' has gone'; console.log(msg); io.emit('exit', msg); }); }); //Run web server server.listen(app.get('port'), function() { console.log("Node app is running at localhost:" + app.get('port')); });
JavaScript
0.000001
@@ -549,19 +549,27 @@ ket. -handshake.a +client.conn.remoteA ddre @@ -727,24 +727,69 @@ address);%0A%0A + //we call the api to get the country%0A var @@ -852,53 +852,8 @@ s;%0A%0A - //we call the api to get the country%0A
ccf8c7044ebd4118bb80defea8c67c80bd0701a7
add user class
server/index.js
server/index.js
// PiMonitor.js var http = require("http"), https = require("https"), crypt3 = require("crypt3"), express = require('express'), url = require("url"), path = require("path"), fs = require("fs"), os = require("os"), colors = require("colors"), optimist = require("optimist").argv, config = require("./config.json"), port = optimist.p || config.port, exec = require('child_process').exec, https_pos = config.forceSSL; function PiDash() { 'use strict' // Set up server this.app = express(); this.https_keys = { key: "", cert: "" }; this.checkSystem(); this.checkOptions(); this.setupServer(); this.RaspberryStats = { GPUstat: { temperature: 0 }, RAMstat: { free: 0, used: 0, total: 0 }, CPUstat: { us: 0, sy: 0, ni: 0, id: 0, wa: 0, hi: 0, si: 0, st: 0, temperature: 0 } }; //this.exec = require('child_process').exec, // child; } PiDash.prototype.setupServer = function() { this.app.use("/static", express.static(__dirname + "/../public")); if (https_pos) { var httpsOptions = { key: fs.readFileSync(this.https_keys.key).toString(), cert: fs.readFileSync(this.https_keys.cert).toString() }; https.createServer(httpsOptions, this.app).listen(port, this.bindingSuccess); } else { http.createServer(this.app).listen(port, this.bindingSuccess); } } PiDash.prototype.authUser = function(username, password, cb) { fs.readFile("/etc/shadow", function(err, data) { if(err) { console.error("You need to be root!".red); process.exit(1); } var reg = new RegExp(username+".*\\n"); data = data.toString(); var line = data.match(reg)[0]; var salt = line.match(/\$.*\$.*\$/)[0]; var truePass = line.split(":")[1]; if(crypt3(password, salt) === truePass) { cb(null, new User(username)) } else { cb(new Error("PasswordError"), null); } }); } PiDash.prototype.systemOverview = function() { return { "hostname":os.hostname(), "type": os.type(), "platform" : os.platform(), "arch": os.arch(), "release": os.release(), "uptime": os.uptime(), "loadavg": os.loadavg(), "totalmem": os.totalmem(), "freemem": os.freemem(), "cpus": os.cpus(), "netwok": os.networkInterfaces(), } } PiDash.prototype.updateStats = function() { var data = this.systemOverview() this.RAMstat = { free: data.freemem, used: data.totalmam - data.freemem, total: data.totalmem } } PiDash.prototype.checkSystem = function() { if(os.type() != "Linux") { console.error("You are not running Linux. Exiting ... \n".red); process.exit(0); } } PiDash.prototype.checkOptions = function() { if(optimist.help || optimist.h) { console.log("\n--------------------------- HELP -----------------------------".red + "\n " + "--- PiDashboard.js ---\n".green.bold.underline + "A Monitoring server for Raspberry Pi and other Linux computers." + "\nUsage: \n".bold ); process.exit(0); } if(optimist.cert || optimist.key || https_pos) { https_pos = true; var cert = "", key = ""; if (optimist.cert) cert = optimist.cert; if (optimist.key) key = optimist.key; if (!cert.length) cert = "./keys/server.crt"; if (!key.length) key = "./keys/server.key"; if (!fs.existsSync(key)) { console.error("File ".red+ key.red.bold + " " + "doesn't exists!".red.underline ); console.log("Can not start https server. Exiting ...".red); process.exit(1); } if (!fs.existsSync(cert)) { console.error("File ".red + cert.red.bold + " " +"doesn't exists!".red.underline ); console.log("Can not start https server. Exiting ...".red); process.exit(1); } this.https_keys = { cert: cert, key: key } } } PiDash.prototype.bindingSuccess = function() { if(https_pos) { console_sufix = "s:/"; } else { console_sufix = ":/"; } console.log("Server running at => ".green + "http" + console_sufix +"/localhost:" + port); } function getStdOutput(cmd,cb) { exec(cmd,function (error, stdout, stderr) { if (error !== null) { console.log('exec error: ' + error); } cb(stdout); }); } /* var getData = setInterval(function() { getStdOutput('cat /sys/class/thermal/thermal_zone0/temp',function(out) { var temp = out/1000 CPUstat.temperature = temp }); getStdOutput('ps -aux',function(out) { console.log(out) }); //console.log(CPUstat) },1000) */ raspberry = new PiDash();
JavaScript
0.000001
@@ -5883,16 +5883,77 @@ %0A%0A%0A%0A*/%0A%0A +function User(username)%0A%7B%0A this.username = username;%0A%7D%0A%0A%0A%0A raspberr
3e792945afad3194f42f570b4116c020f0e33d1a
Update for returning details.
app.js
app.js
var express = require('express'); var app = express(); // var redis = require('redis'); // var client = redis.createClient(); var pg = require('pg'); var connString = 'postgres://vil:kzciaMUwTvd4y9Q0KYI6@localhost/namesandsongs'; app.get('/namesandsongs/api/song', function(request, response) { //this starts initializes a connection pool //it will keep idle connections open for a (configurable) 30 seconds //and set a limit of 20 (also configurable) pg.connect(connString, function(err, client, done) { var results = []; if(err) { return console.error('error fetching client from pool', err); } // client.query('SELECT $1::int AS number', ['1'], function(err, result) { client.query('SELECT * FROM song', function(err, result) { //call `done()` to release the client back to the pool done(); if(err) { return console.error('error running query', err); } return response.json(result.rows); }); }); }); app.get('/namesandsongs/api/song/:id', function(request, response) { //this starts initializes a connection pool //it will keep idle connections open for a (configurable) 30 seconds //and set a limit of 20 (also configurable) pg.connect(connString, function(err, client, done) { var id = request.params.id; if(err) { return console.error('error fetching client from pool', err); } // client.query('SELECT $1::int AS number', ['1'], function(err, result) { client.query('SELECT * FROM song WHERE id = $1', [id], function(err, result) { //call `done()` to release the client back to the pool done(); if(err) { return console.error('error running query', err); } return response.json(result.rows[0]); }); }); }); app.listen(3000, function() { console.log('Listening on port 3000'); });
JavaScript
0
@@ -236,38 +236,24 @@ p.get('/ -namesandsongs/ api/song ', funct @@ -240,24 +240,25 @@ t('/api/song +s ', function( @@ -317,33 +317,32 @@ connection pool - %0A%09//it will keep @@ -387,33 +387,32 @@ able) 30 seconds - %0A%09//and set a li @@ -432,33 +432,32 @@ so configurable) - %0A%09pg.connect(con @@ -695,33 +695,49 @@ t.query('SELECT -* +id, artist, title FROM song', fun @@ -730,16 +730,25 @@ ROM song + LIMIT 20 ', funct @@ -817,33 +817,32 @@ back to the pool - %0A%09 done();%0A%09 @@ -831,37 +831,32 @@ ol%0A%09 done();%0A -%09 %0A%09 if(err) %7B%0A @@ -938,32 +938,40 @@ n response.json( +%7Bsongs: result.rows);%0A%0A%09 @@ -965,16 +965,17 @@ ult.rows +%7D );%0A%0A%09 %7D @@ -1001,30 +1001,16 @@ t('/ -namesandsongs/ api/song /:id @@ -1005,16 +1005,17 @@ api/song +s /:id', f @@ -1090,17 +1090,16 @@ ion pool - %0A%09//it w @@ -1160,17 +1160,16 @@ seconds - %0A%09//and @@ -1205,17 +1205,16 @@ gurable) - %0A%09pg.con @@ -1595,17 +1595,16 @@ the pool - %0A%09 do @@ -1609,21 +1609,16 @@ done();%0A -%09 %0A%09 if @@ -1681,32 +1681,88 @@ ', err);%0A%09 %7D%0A + console.log(%22Returned %22 + result.rows%5B0%5D.artist);%0A return res @@ -1772,16 +1772,23 @@ se.json( +%7Bsong: result.r @@ -1793,16 +1793,17 @@ .rows%5B0%5D +%7D );%0A%0A%09 %7D
a89ceb6a4ccfd0936d4bdc886d17ac4eae9b3582
Update app logic to better handle websockets
app.js
app.js
const express = require('express'); const http = require('http'); const request = require('request'); const path = require('path'); const WebSocket = require('ws'); const compression = require('compression'); const app = express(); require('dotenv').config(); app.set('view engine', 'hbs'); app.use(compression()); app.use(require('node-sass-middleware')({ src: path.join(__dirname, 'public'), dest: path.join(__dirname, 'public'), sourceMap: true })); app.use(express.static(path.join(__dirname, 'public'))); app.get('/', function (req, res) { const ws = new WebSocket(`ws://localhost:2080`); let headers = { 'Authorization': `Basic ${process.env.AUTH}`, 'Content-Type': 'application/json', }; let options = { rejectUnauthorized: false, // not ideal url: `${process.env.JIRA_URL}/rest/api/latest/search?jql=${process.env.JIRA_JQL}`, headers: headers }; function callback(error, response, body) { // only send the issues over if (!error) { let parsedData = JSON.parse(body); let data = { meta: { total: parsedData.total, max: parsedData.maxResults }, issues: parsedData.issues } ws.send(JSON.stringify(data)); } } request(options, callback); res.render('index'); }); app.post('/jira/blocked/:project/:ticket/', function (req, res) { let headers = { 'Authorization': `Basic ${process.env.AUTH}`, 'Content-Type': 'application/json', }; const ws = new WebSocket(`ws://localhost:2080`); let options = { rejectUnauthorized: false, // not ideal url: `${process.env.JIRA_URL}/rest/api/latest/search?jql=${process.env.JIRA_JQL}`, headers: headers }; function callback(error, response, body) { // only send the issues over if (!error) { let parsedData = JSON.parse(body); let data = { meta: { total: parsedData.total, max: parsedData.maxResults }, issues: parsedData.issues, alert: [] } ws.send(JSON.stringify(data)); } else { console.log(error); } } ws.on('open', function open() { let data = { alert: [{ key: req.params['project'], id: req.params['ticket'], user: req.params['user'] }] }; ws.send(JSON.stringify(data)); request(options, callback); }); res.send("ok"); }); const server = http.createServer(app); const wss = new WebSocket.Server({ server }); wss.on('connection', function connection(ws) { ws.on('open', function open() { console.log('WS: open'); }); ws.on('close', function close() { console.log('WS: connection closed'); }); ws.on('message', function incoming(data) { wss.clients.forEach(function each(client) { client.send(data) }); }); }); server.listen(process.env.PORT || 3000, function listening() { console.log('Listening on %d', server.address().port); });
JavaScript
0.000001
@@ -224,16 +224,65 @@ press(); +%0Aconst ws = new WebSocket(%60ws://localhost:2080%60); %0A%0Arequir @@ -601,58 +601,8 @@ s) %7B -%0A%09const ws = new WebSocket(%60ws://localhost:2080%60); %0A%0A%09l @@ -1415,59 +1415,8 @@ %7D;%0A%0A -%09const ws = new WebSocket(%60ws://localhost:2080%60);%0A%0A %09let
4900bfaebb302dc130b2f4a6aac97c9e909fa552
Fix typo and path issue; uncomment default intent
app.js
app.js
var restify = require('restify'), builder = require('botbuilder'), nconf = require('nconf'); // Create nconf environment to load keys and connections strings // which should not end up on GitHub nconf .file({ file: './config.json' }) .env(); //========================================================= // Bot Setup //========================================================= // Setup Restify Server var server = restify.createServer(); server.listen(process.env.port || process.env.PORT || 3978, function () { console.log('%s listening to %s', server.name, server.url); }); // Create chat bot var connector = new builder.ChatConnector({ appId: nconf.get("MICROSOFT_APP_ID"), appPassword: nconf.get("MICROSOFT_APP_PASSWORD") }); var bot = new builder.UniversalBot(connector); server.post('/api/messages', connector.listen()); server.get(/.*/, restify.serveStatic({ 'directory' : '.', 'default' : 'index.html' })); //========================================================= // Bots Dialogs //========================================================= // Create LUIS recognizer that points at our model var model = nconf.get("LUIS_model_URL"); var recognizer = new builder.LuisRecognizer(model); var intents = new builder.IzntentDialog({ recognizers: [recognizer] }); bot.dialog('/', intents); intents .onBegin(builder.DialogAction.send("Hi, I'm your startup assistant!")) // Simple regex commands .matches(/^hello/i, function (session) { session.send("Hi there!"); }) .matches(/^help/i, function (session) { session.send("You asked for help."); }) //LUIS intent matches .matches('AzureCompliance', '/compliance') //.onDefault(builder.DialogAction.send("I'm sorry. I didn't understand, but I'm learning.")); bot.dialog('/compliance', function (session, args) { session.send("You asked about Azure Compliance."); session.endDialog(); });
JavaScript
0
@@ -952,16 +952,23 @@ t' : ' +static/ index.ht @@ -1285,17 +1285,16 @@ uilder.I -z ntentDia @@ -1729,18 +1729,16 @@ e')%0A -// .onDefau
fca73783eb69bf65a4bdff37e2ecc1a7c1e41118
test filename as variable
app.js
app.js
#!/usr/bin/env node // // Detects triangles and quadrilaterals // // sourced from: https://github.com/peterbraden/node-opencv/tree/master/examples var cv = require('opencv'), colors = require("colors"), Spacebrew = require('./sb-1.3.0').Spacebrew, sb, config = require("./machine"), fs = require("fs"), PNG = require("png").Png; /** * * Spacebrew setup * **/ sb = new Spacebrew.Client( config.server, config.name, config.description ); // create spacebrew client object // create the spacebrew subscription channels sb.addPublish("config", "string", ""); // publish config for handshake sb.addSubscribe("config", "boolean"); // subscription for config handshake sb.addSubscribe("image", "binary.png"); // subscription for receiving image binary sb.addPublish("src", "string", ""); // publish image url for handshake sb.onBooleanMessage = onBooleanMessage; sb.onCustomMessage = onCustomMessage; sb.onOpen = onOpen; // connect to spacbrew sb.connect(); /** * Function that is called when Spacebrew connection is established */ function onOpen(){ console.log( "Connected through Spacebrew as: " + sb.name() + "." ); } function onCustomMessage( name, value, type ){ switch(type){ case "binary.png": if(name == "image"){ console.log('png buffer recieved'); var b64_buf = new Buffer(value, 'base64').toString('binary'); var buf = new Buffer(b64_buf, 'binary'); fs.writeFile('image.png', buf, 'binary', function(err, filename){ console.log(filename + ' written'); }); } } } /** * onStringMessage Function that is called whenever new spacebrew string messages are received. * It accepts two parameters: * @param {String} name Holds name of the subscription feed channel * @param {String} value Holds value received from the subscription feed */ function onBooleanMessage( name, value ){ console.log("[onBooleanMessage] value: " + value + " name: " + name); switch(name){ case "config": console.log([ // Timestamp String(+new Date()).grey, // Message String("sending config").cyan ].join(" ")); sb.send("config", "string", JSON.stringify( config ) ); break; } } var lowThresh = 0; var highThresh = 100; var nIters = 2; var minArea = 2000; var BLUE = [0, 255, 0]; //B, G, R var RED = [0, 0, 255]; //B, G, R var GREEN = [0, 255, 0]; //B, G, R var WHITE = [255, 255, 255]; //B, G, R /* cv.readImage('../test/square2.jpg', function(err, im) { var out = new cv.Matrix(im.height(), im.width()); // convert the image to grey scale im.convertGrayscale(); //make a copy of the image called im_canny (not sure why?) im_canny = im.copy(); im_canny.canny(lowThresh, highThresh); im_canny.dilate(nIters); //uses a for loop to find number of contours contours = im_canny.findContours(); for(i = 0; i < contours.size(); i++) { if(contours.area(i) < minArea) continue; // arcLength tells you how long each face is, so that you can cut out any small shape var arcLength = contours.arcLength(i, true); contours.approxPolyDP(i, 0.01 * arcLength, true); // chooses a drawing color based on number of contours switch(contours.cornerCount(i)) { case 3: out.drawContour(contours, i, GREEN); break; case 4: out.drawContour(contours, i, RED); break; case 5: out.drawContour(contours,i, BLUE); break; default: out.drawContour(contours, i, WHITE); } } //saves image out.save('../test/out.png'); }); */
JavaScript
0.000054
@@ -339,16 +339,45 @@ .Png;%0A%0A%0A +var filepath = './files/';%0A%0A%0A /**%0A*%0A* @@ -1468,32 +1468,77 @@ -fs.writeFile('image.png' +var filename = filepath + 'image.png';%0A%0A fs.writeFile(filename , bu @@ -1566,18 +1566,8 @@ (err -, filename )%7B%0A
52a268ed63f934878aab3c5bd05f18c3c62748c4
add dummy errorhandler
app.js
app.js
var express = require('express') var url = require('url') var telldus = require('telldus') var ws = require("nodejs-websocket") var port = process.env.PORT || 9000 var portWs = 9001 var app = express() app.set('port', port) app.use(express.static(__dirname + '/public')) app.get('/api/on', function(request, response) { var query = url.parse(request.url, true).query if (query && query.id) { telldus.turnOn(parseInt(query.id), function(err) { var res = "OK: turn on id:" + query.id console.log(res) response.send(res) }) } }) app.get('/api/off', function(request, response) { var query = url.parse(request.url, true).query if (query && query.id) { telldus.turnOff(parseInt(query.id), function(err) { var res = "OK: turn off id:" + query.id console.log(res) response.send(res) }) } }) app.get("/api/list", function(request, response) { telldus.getDevices(function(err,devices) { if (err) { console.log('Error: ' + err) } else { console.log(devices) response.send(devices) } }) }) app.listen(app.get('port'), function() { console.log("Node app is running at localhost:" + app.get('port')) }) var server = ws.createServer(function (conn) { sendState(conn) conn.on("text", function (str) { console.log("Received "+str) }) conn.on("close", function (code, reason) { }) }) server.listen(portWs) var sensorState = { temp1: "", humidity1: "", temp2: "", humidity2: "" } var listener = telldus.addSensorEventListener(function(deviceId,protocol,model,type,value,timestamp) { updateSensorState(deviceId, type, value) server.connections.forEach(function (conn) { sendState(conn) }) }) function updateSensorState(deviceId, type, value) { if (deviceId == "11" && type == 1) sensorState.temp1 = value else if (deviceId == "11" && type == 2) sensorState.humidity1 = value else if (deviceId == "21" && type == 1) sensorState.temp2 = value else if (deviceId == "21" && type == 2) sensorState.humidity2 = value else console.log("unknown sensor info: " + deviceId + "," + type + "," + value) } function sendState(conn) { conn.sendText(JSON.stringify(sensorState)) }
JavaScript
0.000001
@@ -1295,40 +1295,59 @@ ) %7B%0A +%0A +%7D)%0A con -sole.log(%22Received %22+str) +n.on(%22close%22, function (code, reason) %7B%0A %0A %7D @@ -1351,37 +1351,37 @@ %7D)%0A conn.on(%22 -close +error %22, function (cod @@ -1377,32 +1377,54 @@ nction ( -code, reason) %7B%0A +err) %7B%0A console.log(%22Error %22 + err) %0A %7D)%0A%7D)
04b849c2c3d019654b24a7a8aa469f8dd08d602e
fix UTC String in details view to really show a UTC time string
app.js
app.js
'use strict'; const cluster = require('cluster'); const express = require('express'); const sqlite3 = require('sqlite3').verbose(); const db = global.db = new sqlite3.Database('./soon.db'); const bodyParser = require('body-parser'); const compression = require('compression'); const exphbs = require('express-handlebars'); const moment = require('moment'); const countdown = require('countdown'); require('moment-countdown'); const SQL_STATEMENTS = require('./sqlStatements'); const createHelpers = require('./createHelpers'); const twitterHelpers = require('./twitterHelpers'); const handlebarsHelpers = require('./handlebarsHelpers'); if (cluster.isMaster) { db.serialize(() => { SQL_STATEMENTS.init.forEach(statement => { db.run(statement); }); }); // Fork a single worker. // sqlite does not support more than one worker. cluster.fork(); cluster.on('exit', (worker, code, signal) => { // restart worker on crash. console.log('worker %d died (%s). restarting...', worker.process.pid, signal || code); cluster.fork(); }); } else { // worker var app = express(); app.engine('handlebars', exphbs({defaultLayout: 'main', helpers: handlebarsHelpers})); app.set('view engine', 'handlebars'); app.use(compression()); app.use(express.static('public')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.get(['/', 'index'], function (req, res) { //TODO: move function to other location/file let queryAllPromise = function(sqlStatement) { return new Promise((resolve, reject) => { db.all(sqlStatement, (error, rows) => { if (error) { reject(error); } else { resolve(rows); } }); }); }; let renderContext = { title: "Soon" }; queryAllPromise(SQL_STATEMENTS.select.endingCountdowns).then((rows) => { renderContext.ending = rows; return queryAllPromise(SQL_STATEMENTS.select.featuredCountdowns); }).then((rows) => { renderContext.featured = rows; return queryAllPromise(SQL_STATEMENTS.select.recentCountdowns); }).then((rows) => { renderContext.recent = rows; res.render('index', renderContext); // render index }).catch((err) => { console.log(err); res.end("Internal Server Error!"); }); }); app.get('/create', function (req, res) { res.render('create', { title: "Create Countdown - Soon" }); }); app.post('/create', function(req, res) { createHelpers.validateInput(req, res, function(isValid, errors) { if (isValid) { let values = createHelpers.generateValues(req, res); let hashtagsArray = createHelpers.generateHashtagArray(req.body.twitterHashtags); createHelpers.createCountdown(values, hashtagsArray).then(countdownId => { console.log('countdown created'); //TODO: restructure create process let selectCountdownStatement = SQL_STATEMENTS.select.countdown; db.get(selectCountdownStatement, [countdownId], (error, row) => { //TODO: error handling res.redirect(`/c/${row.uuid}`); }); }).catch(error => { console.error('error in createCountdown chain: ', error); }); } else { let cdIsRel = (req.body.cdType == 'rel') ? true : false; res.render('create', {'body': req.body, 'cdIsRel': cdIsRel, 'errors': errors}); // render create page with current values and errors } }); }); app.get('/c/:uuid', function (req, res) { let uuid = req.params.uuid; console.log(`detail view for uuid ${uuid} requested...`); let selectCountdownStatement = SQL_STATEMENTS.select.countdownByUUID; let selectHashtagsStatement = SQL_STATEMENTS.select.hashtagsForCountdown; db.all(selectCountdownStatement, [uuid], (error, infos) => { if (error || infos.length !== 1) { console.log(`could not fetch uuid ${uuid}`); res.status(404); // TODO: Implement 404 page res.end('Countdown not found'); return; } let now = new Date().getTime(); let info = infos[0]; let end = info.endTimestamp; let isRelativeCountdown = info.startTimestamp != null; let hashtagsArray = []; let percentage = null; let animationSeconds = (info.endTimestamp - info.startTimestamp) / 1000; animationSeconds = Math.ceil(animationSeconds); animationSeconds = animationSeconds < 0 ? 0 : animationSeconds; // calculate current downlaod progress percentage if (isRelativeCountdown) { let start = info.startTimestamp; let totalDiff = end - start; let currentDiff = end - now; if (totalDiff > 0 && currentDiff < totalDiff) { percentage = 100 - (100*(currentDiff/totalDiff)); percentage = Math.round(percentage); percentage = percentage > 100 ? 100 : percentage; } } let countdown = moment().countdown(end).toString(); let endDate = moment(end).format('dddd, MMMM Do YYYY, h:mm:ss a') + ' (UTC)'; // Fetch associated hashtags let id = info.id; db.each(selectHashtagsStatement, [id], (error, hashtag) => { if (error) { throw error; } hashtagsArray.push(`#${hashtag.name}`); }, () => { let render = (tweets) => { console.log('rendering details view'); debugger; let hashtagsString = hashtagsArray.join(' '); let tweetsVisible = tweets && tweets.length > 0; res.render('detail', { title: `${info.title} - Soon`, cTitle: info.title, cDescription: info.description, cEndDate: endDate, cHashtags: hashtagsString, cPercentage: percentage, cPercentageBarValue: percentage/2, cCountdown: countdown, percentageVisible: percentage != null, animationSeconds: animationSeconds, tweetsVisible: tweetsVisible, tweets: tweets, isRelativeCountdown: isRelativeCountdown, metaRefresh: { delay: 30, //in seconds url: `/c/${info.uuid}` } }); } if (hashtagsArray.length > 0) { twitterHelpers.getTweetsForHashtags(hashtagsArray) .catch((error) => { console.error(error); }).then((tweets) => { let statuses = tweets.statuses; twitterHelpers.patchStatuses(statuses); debugger; return render(tweets.statuses); }); } else { render(); } }); }); }); app.listen(3000, function () { console.log('Soon is available on port 3000!'); }); // // function cleanup() { // console.log('Shutting down...'); // db.close(); // } // // process.on('exit', (code) => { // cleanup(); // process.exit(code); // }); // // process.on('SIGINT', (code) => { // cleanup(); // process.exit(code); // }); }
JavaScript
0
@@ -4767,16 +4767,20 @@ = moment +.utc (end).fo
a8c002ad34880876b92ffa8001a786cf150ffa60
Fix app.js, make it actually listen
app.js
app.js
var express = require('express') , app = express() app.get('/', function(req, res) { res.send('./app/index.html') })
JavaScript
0
@@ -45,16 +45,52 @@ xpress() +%0A , port = process.env.PORT %7C%7C 8080 %0A%0Aapp.ge @@ -150,8 +150,81 @@ tml')%0A%7D) +%0A%0Aapp.listen(port, function () %7B%0A console.log('Listening on ' + port)%0A%7D)
2021e0f3d70220579579b451540b622446b5104e
use new body parsers
app.js
app.js
'use strict'; var a127 = require('a127-magic'); var express = require('express'); var app = express(); // configure usergrid-objects var config = a127.config.load(); var Usergrid = require('usergrid-objects')(config.usergrid); // ensure body is parsed var bodyParser = require('body-parser'); app.use(bodyParser); // use apigee-127 app.use(a127.middleware()); var server = app.listen(process.env.PORT || 10010, function() { console.log('Listening on port %d', server.address().port); });
JavaScript
0.000001
@@ -307,16 +307,76 @@ dyParser +.urlencoded(%7B extended: false %7D));%0Aapp.use(bodyParser.json() );%0A%0A// u
d0afbdb071b73f8612777ab9fa803762bd9aae7f
Fix health check path
app.js
app.js
/** * Copyright 2017 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const express = require('express'); const statusCodes = require('http-status-codes'); const errorTracker = require('./routes/error-tracker'); const querystring = require('./utils/query-string'); const parseErrorHandling = require('./utils/parse-error-handling'); const json = require('./utils/json'); const app = express(); const port = parseInt(process.env.PORT, 10) || 8080; app.set('etag', false); app.set('trust proxy', true); app.set('query parser', querystring.parse); app.get(['/readiness_check', '/liveness_check', '_ah/health'], function( req, res ) { res.sendStatus(statusCodes.OK); }); app.get('/r', (req, res) => { return errorTracker(req, res, req.query); }); app.post('/r', json, (req, res) => { // Allow non-credentialed posts from anywhere. // Not strictly necessary, but it avoids an error being reported by the // browser. res.set('Access-Control-Allow-Origin', '*'); return errorTracker(req, res, req.body); }); // Handle BodyParser PayloadTooLargeError errors app.use(parseErrorHandling); if (process.env.NODE_ENV !== 'test') { app.listen(port, function() { console.log('App Started on port ' + port); }); } module.exports = app;
JavaScript
0.000008
@@ -1149,16 +1149,17 @@ heck', ' +/ _ah/heal
8849a0ce33321062ec0c04ce5bfbe55c38a57199
Add refresh delay of 30 seconds.
app.js
app.js
var request = require('request'); var fetchfeed = require('./fetchfeed.js'); var nxws = new fetchfeed(); var feeds = require('./feeds.json').remote; var checkNewsInterval; var db = require('monk')('localhost/newsdb'); var db_items = db.get('items'); function fetchFeeds() { // console.log('Fetching', feeds.length, 'feeds'); nxws.fetchSourceFromStream(feeds, request, storeContentsOfFeed); } fetchFeeds(); setInterval(function() { fetchFeeds(); }, 10000); /* Storage */ function storeContentsOfFeed(err, x) { if (err) { console.error(err); return; } var newItem = { title: x.title, author: x.author, date: new Date(x.date), guid: x.guid, link: x.link, metatitle: x.meta.title, metalink: x.meta.link } if (newItem.date > new Date()) newItem.date = new Date(); db_items.findOne({guid: newItem.guid}, function(e, d){ if (err) throw err; if (null == d) { console.log("(" + new Date() + ") inserting and sending: ", newItem.title); db_items.insert(newItem, function(err, d) { if (err) throw err; io.emit('nxws items', JSON.stringify([d])); }); } }); } /* Server */ var express = require('express'); var app = express(); var http = require('http').Server(app); var io = require('socket.io')(http); app.use(express.static(__dirname + '/public')); http.listen(3000, function() { console.log('listening on *:3000'); }); /* Socket */ io.on('connection', function(socket) { console.log("User connected", socket.id); emitNumberOfUsers(io.sockets.sockets.length); socket.beginTime = new Date(); socket.on('request news', function() { sendAllNews(socket); }); socket.on('disconnect', function() { console.log("User disconnected", socket.id); emitNumberOfUsers(io.sockets.sockets.length); }); }); /* Broadcasting */ function sendAllNews(socket) { db_items.find({}, {sort: {date: -1}}) .on('success', createNewsEmitterForSocket(socket)); } function emitNumberOfUsers(num) { console.log('User count', io.sockets.sockets.length) io.emit('nxws readers', num); } function createNewsEmitterForSocket(socket) { return function (docs) { console.log('Sending ' + docs.length + ' items to ' + socket.id); socket.emit('nxws items', JSON.stringify(docs)); } }
JavaScript
0
@@ -239,15 +239,47 @@ et(' -items') +rss_guids');%0A%0Avar REFRESH_DELAY = 30000 ;%0A%0Af @@ -486,13 +486,21 @@ %0A%7D, -10000 +REFRESH_DELAY );%0A%0A @@ -792,16 +792,17 @@ link%0A %7D +; %0A if (n @@ -955,16 +955,17 @@ (null == += d) %7B%0A @@ -1066,23 +1066,36 @@ .insert( +%7Bguid: newItem +.guid%7D , functi @@ -1181,17 +1181,23 @@ ingify(%5B -d +newItem %5D));%0A @@ -2141,16 +2141,17 @@ .length) +; %0A io.em @@ -2377,11 +2377,12 @@ s));%0A %7D +; %0A%7D%0A
6cba999a52c5791b2eeb721c62617e20b7791bcf
Fix no res.locals.user in api_v2
app.js
app.js
/* * This file is part of SYZOJ. * * Copyright (c) 2016 Menci <[email protected]> * * SYZOJ 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. * * SYZOJ 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 SYZOJ. If not, see <http://www.gnu.org/licenses/>. */ 'use strict'; let fs = require('fs'), path = require('path'); global.syzoj = { rootDir: __dirname, config: require('./config.json'), models: [], modules: [], db: null, log(obj) { console.log(obj); }, async run() { let Express = require('express'); global.app = Express(); syzoj.production = app.get('env') === 'production'; app.listen(parseInt(syzoj.config.port), syzoj.config.hostname, () => { this.log(`SYZOJ is listening on ${syzoj.config.hostname}:${parseInt(syzoj.config.port)}...`); }); // Set assets dir app.use(Express.static(__dirname + '/static')); // Set template engine ejs app.set('view engine', 'ejs'); // Use body parser let bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({ extended: true, limit: '50mb' })); app.use(bodyParser.json({ limit: '50mb' })); // Use cookie parser app.use(require('cookie-parser')()); let multer = require('multer'); app.multer = multer({ dest: syzoj.utils.resolvePath(syzoj.config.upload_dir, 'tmp') }); // Trick to bypass CSRF for APIv2 app.use((() => { let router = new Express.Router(); app.apiRouter = router; require('./modules/api_v2'); return router; })()); let csurf = require('csurf'); app.use(csurf({ cookie: true })); await this.connectDatabase(); this.loadHooks(); this.loadModules(); }, async connectDatabase() { let Sequelize = require('sequelize'); this.db = new Sequelize(this.config.db.database, this.config.db.username, this.config.db.password, { host: this.config.db.host, dialect: this.config.db.dialect, storage: this.config.db.storage ? this.utils.resolvePath(this.config.db.storage) : null, logging: syzoj.production ? false : syzoj.log }); global.Promise = Sequelize.Promise; this.db.countQuery = async (sql, options) => (await this.db.query(`SELECT COUNT(*) FROM (${sql}) AS \`__tmp_table\``, options))[0][0]['COUNT(*)']; this.loadModels(); }, loadModules() { fs.readdir('./modules/', (err, files) => { if (err) { this.log(err); return; } files.filter((file) => file.endsWith('.js')) .forEach((file) => this.modules.push(require(`./modules/${file}`))); }); }, loadModels() { fs.readdir('./models/', (err, files) => { if (err) { this.log(err); return; } files.filter((file) => file.endsWith('.js')) .forEach((file) => require(`./models/${file}`)); this.db.sync(); }); }, model(name) { return require(`./models/${name}`); }, loadHooks() { let Session = require('express-session'); let FileStore = require('session-file-store')(Session); let sessionConfig = { secret: this.config.session_secret, cookie: {}, rolling: true, saveUninitialized: true, resave: true, store: new FileStore }; if (syzoj.production) { app.set('trust proxy', 1); sessionConfig.cookie.secure = true; } app.use(Session(sessionConfig)); app.use((req, res, next) => { // req.session.user_id = 1; let User = syzoj.model('user'); if (req.session.user_id) { User.fromID(req.session.user_id).then((user) => { res.locals.user = user; next(); }).catch((err) => { this.log(err); res.locals.user = null; req.session.user_id = null; next(); }) } else { if (req.cookies.login) { let obj; try { obj = JSON.parse(req.cookies.login); User.findOne({ where: { username: obj[0], password: obj[1] } }).then(user => { if (!user) throw null; res.locals.user = user; req.session.user_id = user.id; next(); }).catch(err => { console.log(err); res.locals.user = null; req.session.user_id = null; next(); }); } catch (e) { res.locals.user = null; req.session.user_id = null; next(); } } else { res.locals.user = null; req.session.user_id = null; next(); } } }); // Active item on navigator bar app.use((req, res, next) => { res.locals.active = req.path.split('/')[1]; next(); }); app.use((req, res, next) => { res.locals.req = req; res.locals.res = res; next(); }); }, utils: require('./utility') }; syzoj.run();
JavaScript
0.000002
@@ -1837,24 +1837,115 @@ 'tmp') %7D);%0A%0A + // This should before load api_v2, to init the %60res.locals.user%60%0A this.loadHooks();%0A // Trick @@ -2237,38 +2237,16 @@ base();%0A - this.loadHooks();%0A this
29071eee23739d47dd9957b7fbdfacd5dd2918d7
Fix issue with old express usage
app.js
app.js
//var http = require('http'); var express = require('express'); var app = module.exports = express(); /*http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain; charset=utf-8'}); res.end('Can i haz app.js host another one or probably?'); }).listen(4080);*/ app.get('/', function(req,res){ res.send('Hello from express'); }); app.listen(4000); console.log('Server running at http://*:4080/');
JavaScript
0.000003
@@ -381,16 +381,59 @@ ten(4000 +, function() %7B%0A console.log('srv OK');%0A%7D );%0Aconso
821993d9d9853bacc985650eb41acd0b7f57150c
Allow dynamic port
app.js
app.js
'use strict'; require('rootpath')(); var app = require('express')(); // Setup database connection require('app/middleware/db'); // Setup extra stuff for express require('app/middleware/express')(app); // Load all routes require('app/routes')(app); app.listen(5000, function() { console.log('Server listening at http://localhost:5000.'); }); exports = module.exports = app;
JavaScript
0.000001
@@ -62,16 +62,53 @@ ess')(); +%0Avar port = process.env.PORT %7C%7C%C2%A05000; %0A%0A// Set @@ -294,20 +294,20 @@ .listen( -5000 +port , functi @@ -368,14 +368,18 @@ ost: -5000.' +%25s.', port );%0A%7D
6d0574b3934728f3396f721d605953152d8d8b2e
remove empty line
app.js
app.js
var restify = require('restify'); var builder = require('botbuilder'); var cheerio = require('cheerio'); var request = require('request'); var PDFParser = require('pdf2json'); var textract = require('textract'); //========================================================= // Bot Setup //========================================================= // Setup Restify Server var server = restify.createServer(); server.listen(process.env.port || process.env.PORT || 3978, function() { console.log('%s listening to %s', server.name, server.url); }); // Create chat bot var connector = new builder.ChatConnector({ appId: process.env.MICROSOFT_APP_ID, appPassword: process.env.MICROSOFT_APP_PASSWORD }); var bot = new builder.UniversalBot(connector); server.post('/api/messages', connector.listen()); var intents = new builder.IntentDialog(); //========================================================= // Bots Dialogs //========================================================= bot.dialog('/', intents); intents.matches(/^rk/i, [ function (session) { menu_rk(function(result) { session.send(result); }); } ]); intents.matches(/^gkk/i, [ function (session) { menu_gkk(function(result) { session.send(result); }); } ]); intents.matches(/^eiserne hand/i, [ function (session) { menu_eisernehand(function(result) { session.send(result); }); } ]); intents.matches(/^all/i, [ function (session) { //TODO maybe reuse other dialogs menu_eisernehand(function(result) { session.send(result); }); menu_gkk(function(result) { session.send(result); }); menu_rk(function(result) { session.send(result); }); } ]); intents.onDefault([ function (session, args, next) { session.send("I know about: rk, eiserne hand, gkk.\n\nTeach me more here: <github>"); } ]); //parse the rk menu function menu_rk(callback) { var url = 'http://www.mandis-kantine.at/men1908-23082013'; request(url, function(error, response, html) { if (!error) { var day = new Date().getDay(); var row = day + 4; //thats just how their table is laid out //console.log("date: " + day + "; row: " + row); var $ = cheerio.load(html); var result = $(`#pagetext > table > tbody > tr:nth-child(${row})`).text().replace(/\r\n\s*/g, '\n').trim(); //console.log(result); callback("**RK**\n\n" + result); } }) } //parse eiserne hand menu function menu_eisernehand(callback) { var url = 'https://manager.yamigoo.com/public/weekly-menu/html/25'; request(url, function(error, response, html) { var day = new Date().getDay(); if (day < 1 || day > 5) { console.log("no menu today"); callback("no menu today"); return; } if (!error) { var $ = cheerio.load(html); var result = $(`#content > div.row > div > div.weeklymenu > div:nth-child(${day})`).text().replace(/\n\s*/g, '\n').trim(); callback("**Eiserne Hand**\n\n" + result); } }) } function menu_lack(callback) { var url = 'http://www.fleischerei-lackinger.at/lackinger/speiseplan/aktuellerspeiseplan'; request(url, function(error, response, html) { if (!error) { } }) } function menu_gkk(callback) { var url = 'http://www.caseli.at/content/download/1363/6617/file/Speiseplan_O%C3%96_GKK_Hauptstelle.pdf' textract.fromUrl(url, function(error, text) { if (error) { console.log(error); callback(error); return; } else { var day = new Date().getDay(); if (day < 1 || day > 5) { console.log("no menu today"); callback("no menu today"); return; } var results = text.split(/(MONTAG|DIENSTAG|MITTWOCH|DONNERSTAG|FREITAG)/) /* 0...empty 1...MONTAG 2...<monday menu> 3...DIENSTAG 4...<tuesday menu> 5...WEDNESDAY 6...<wednesday menu> 7...THURSDAY 8...<thursday menu> 9...FRIDAY 10..<friday menu> Monday -> day==1 --> day+day==2 --> monday menu Tuesday -> day==2 --> day+day==4 --> tuesday menu */ var index = day+day; var menu = results[index].trim().replace(/Classic/g, "\n\nClassic").replace(/^, /g, ""); //console.log(results[index]); callback("**GKK**\n\n" + menu); } }) }
JavaScript
0.999999
@@ -704,16 +704,17 @@ ORD%0A%7D);%0A +%0A var bot @@ -3398,16 +3398,22 @@ r) %7B%0A%09%09%09 +//TODO %0A%09%09%7D%0A%09%7D)
d50965da4ea2c0d91a44bb55439332477b78d592
Change public folder location
app.js
app.js
var express = require('express'); var path = require('path'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var routes = require('./routes/index'); var app = express(); // Serve the Parse API on the /parse URL prefix var parse = require('./parse/api') app.use('/parse', parse); app.ParseServer = parse //Serve the Parse Dashboard on the /dashboard URL prefix var dashboard = require('./parse/dashboard') app.use('/dashboard', dashboard); //Socket.io // uncomment if you want to use it // app.io = require('socket.io')() // require('./sockets/sockets.js')(app.io) // Serve static assets from the /public folder app.use('/', express.static(path.join(__dirname, '/client/build'))); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); // app.use('/', routes) // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.send(err) }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.send(err.message) }); module.exports = app;
JavaScript
0.000001
@@ -736,15 +736,8 @@ , '/ -client/ buil
3d610d1d588d41f7dcfaffd4e30f4c998fdad144
Test fixes
test/direction.spec.js
test/direction.spec.js
describe('Direction parameter', function () { before(function () { fixture.setBase("test/fixtures"); fixture.load("static_position.html"); this.element = document.getElementById('static'); this.timeout = (Scrollmarks.config().scrollThrottle + 1) / 60 * 1000; // excepted execution + 1 frame }); after(function () { fixture.cleanup(); }); beforeEach(function () { this.callback = sinon.spy(); }); afterEach(function () { Scrollmarks.stop(); }); it('should trigger in both directions when param is missing', function (done) { var mark = Scrollmarks.add({ element: this.element, callback: this.callback }); window.scrollWithEvent(100); window.scrollWithEvent(0); setTimeout(function () { this.callback.should.have.been.calledTwice; Scrollmarks.remove(mark); done(); }.bind(this), this.timeout); }); it('should not trigger when direction is \'up\' and scrolling down', function (done) { var mark = Scrollmarks.add({ element: this.element, callback: this.callback, direction: 'up' }); window.scrollWithEvent(100); setTimeout(function () { this.callback.should.not.have.been.called; Scrollmarks.remove(mark); window.scrollWithEvent(0); done(); }.bind(this), this.timeout); }); it('should trigger when direction is \'up\' and scrolling up', function (done) { window.scrollTo(0, 100); var mark = Scrollmarks.add({ element: this.element, callback: this.callback, direction: 'up' }); window.scrollWithEvent(0); setTimeout(function () { this.callback.should.have.been.calledOnce; Scrollmarks.remove(mark); done(); }.bind(this), this.timeout); }); it('should trigger when direction is \'down\' and scrolling down', function (done) { var mark = Scrollmarks.add({ element: this.element, callback: this.callback, direction: 'down' }); window.scrollWithEvent(100); setTimeout(function () { this.callback.should.have.been.calledOnce; Scrollmarks.remove(mark); window.scrollWithEvent(0); done(); }.bind(this), this.timeout); }); it('should not trigger when direction is \'down\' and scrolling up', function (done) { window.scrollWithEvent(100); var mark = Scrollmarks.add({ element: this.element, callback: this.callback, direction: 'down' }); // it should be called once as the page is scrolled down when the mark is added setTimeout(function () { this.callback.should.have.been.calledOnce; this.callback.reset(); window.scrollWithEvent(0); setTimeout(function () { // but it should not be called when we scroll up this.callback.should.not.have.been.called; Scrollmarks.remove(mark); done(); }.bind(this), this.timeout); }.bind(this), this.timeout); }); });
JavaScript
0.000001
@@ -1738,32 +1738,57 @@ nction (done) %7B%0A +%09%09window.scrollTo(0, 0);%0A %09%09var mark = Scr @@ -2034,34 +2034,30 @@ indow.scroll -WithEvent( +To(0, 0);%0A%09%09%09done( @@ -2195,34 +2195,30 @@ indow.scroll -WithEvent( +To(0, 100);%0A%0A%09%09var
d033c4f693c607c73df51463750396ddb02af65e
change shut down sequence
app.js
app.js
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var session = require('express-session'); var config = require('./config'); var cleanup = require('./cleanup'); var RedisStore = require('connect-redis')(session); var index = require('./routes/index'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'hbs'); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(require('node-sass-middleware')({ src: path.join(__dirname, 'public'), dest: path.join(__dirname, 'public'), indentedSyntax: true, sourceMap: true })); app.use(express.static(path.join(__dirname, 'public'))); if (config.session.useRedis == true) { app.use(session({ secret: config.session.secret, resave: false, saveUninitialized: true, store: new RedisStore(config.redis) })); } else { app.use(session({ secret: config.session.secret, resave: false, saveUninitialized: true })); } app.use('/', index); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error'); }); process.on( "SIGINT", function(){ cleanup.deleteFiles(); setTimeout(function() { console.log("The server has been manually stopped\n"); process.exit(); }, 10); }); module.exports = app;
JavaScript
0.000014
@@ -1946,16 +1946,18 @@ +// console.
f42695f11faaafa7b9239d4643aa4d301fbfd242
Add patch
app.js
app.js
const express = require('express'); const bodyParser = require('body-parser'); const mongoose = require('mongoose'); const { Schema } = mongoose; const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017'; mongoose.connect(MONGODB_URI); const app = express(); app.use(express.static(`${__dirname}/public`)); app.use(bodyParser.json()); const AntibodySchema = new Schema({ target: String, catalogNumber: String, hostSpecies: String, reactivity: [String], clarity: String, switch: String, map: String, vendorWebsite: String, publication: String, image: String }); const Antibody = mongoose.model('antibody', AntibodySchema); const AWS = require('aws-sdk'); AWS.config.update({region: 'us-west-2'}); app.get('/antibodies', (req, res) => { Antibody.find({}).then((antibodies) => { res.json(antibodies.map(a => a.toJSON())); }).catch((err) => res.json({ error: err })); }); app.get('/antibodies/:id', (req, res) => { Antibody.findOne({ _id: req.params.id }).then((antibody) => { res.json(antibody.toJSON()); }).catch((err) => res.json({ error: err })); }); app.post('/antibodies', (req, res) => { const antibody = new Antibody(req.body); antibody.save().then((doc) => { res.json(doc.toJSON()); }).catch((err) => res.json({ error: err })); }); const PORT = process.env.PORT || 3008; app.listen(PORT, () => { console.log(`Listening on port ${PORT}`); });
JavaScript
0.000001
@@ -1101,24 +1101,308 @@ r %7D));%0A%7D);%0A%0A +app.put('/antibodies/:id', (req, res) =%3E %7B%0A Antibody.remove(%7B _id: req.params.id %7D).then(() =%3E %7B%0A const antibody = new Antibody(req.body);%0A return antibody.save();%0A %7D).then((doc) =%3E %7B%0A res.json(doc.toJSON());%0A %7D).catch((err) =%3E res.json(%7B error: err %7D));%0A%7D);%0A%0A app.post('/a
46520ef8bba0c8db73df621104f9994db2d735d7
Rename voucher qualification API method, allow for optional query params
src/Vouchers.js
src/Vouchers.js
'use strict' const { encode, isFunction, isObject } = require('./helpers') module.exports = class Vouchers { constructor (client, balance) { this.client = client // public this.balance = balance } create (voucher, callback) { return this.client.post(`/vouchers/${encode(voucher.code)}`, voucher, callback) } get (code, callback) { return this.client.get(`/vouchers/${encode(code)}`, null, callback) } update (voucher, callback) { return this.client.put(`/vouchers/${encode(voucher.code)}`, voucher, callback) } delete (code, params = {}, callback = null) { if (isFunction(params)) { callback = params params = {} } return this.client.delete(`/vouchers/${encode(code)}`, callback, { qs: { force: !!params.force } }) } list (params, callback) { if (isFunction(params)) { callback = params params = {} } return this.client.get('/vouchers', params, callback) } enable (params, callback) { if (isObject(params)) { return this.client.post('/vouchers/enable', params, callback) } // Enable by code return this.client.post(`/vouchers/${encode(params)}/enable`, null, callback) } disable (params, callback) { if (isObject(params)) { return this.client.post('/vouchers/disable', params, callback) } // Disable by code return this.client.post(`/vouchers/${encode(params)}/disable`, null, callback) } import (vouchers, callback) { return this.client.post('/vouchers/import', vouchers, callback) } qualificationRequest (params, callback) { return this.client.post('/vouchers/qualification', params, callback) } }
JavaScript
0
@@ -1566,28 +1566,20 @@ %0A%0A -q +getQ ualifi -cationRequest +ed (pa @@ -1575,32 +1575,36 @@ alified (params, + qs, callback) %7B%0A @@ -1592,32 +1592,98 @@ qs, callback) %7B%0A + if (isFunction(qs)) %7B%0A callback = qs%0A qs = %7B%7D%0A %7D%0A return this. @@ -1733,20 +1733,28 @@ ms, callback +, %7B qs %7D )%0A %7D%0A%7D%0A
415c0fb0d6c564e08a2b046c12fe230df0ec9bbe
change inline function declaration
app.js
app.js
const lc = require('node-lending-club-api') const loanUtils = require('./lib/loanUtils') const nconf = require('nconf') const moment = require('moment') const winston = require('winston') nconf.argv().file('global', './global.json').env() const logger = new (winston.Logger)({ transports: [ new (winston.transports.Console)() ] }) const minLoanScore = Number(nconf.get('minLoanScore')) || 70 lc.init({ apiKey: nconf.get('apiKey') }) lc.loans.listing(true, function (err, data) { handleError(err) logger.info(data.loans.length + ' loans being funded') const investorId = nconf.get('investorId') const loansOfInterest = [] for (let i = 0; i < data.loans.length; i++) { if (matchesCriteria(data.loans[i])) { loansOfInterest.push({ loan: data.loans[i], loanScore: loanUtils.scoreLoan(data.loans[i]) }) } } loansOfInterest.sort(function (a, b) { if (a.loanScore > b.loanScore) { return -1 } else if (a.loanScore < b.loanScore) { return 1 } else { return 0 } }) lc.accounts.availableCash(investorId, function (err, data) { handleError(err) logger.info('Funds available: ' + data.availableCash) const loansToInvestIn = Math.floor(data.availableCash / nconf.get('amountToInvest')) lc.accounts.notes(investorId, function (err, data) { handleError(err) const loansOwned = {} const loansToBuy = [] for (let i = 0; i < data.myNotes.length; i++) { loansOwned[data.myNotes[i].loanId] = 1 } logger.info('Found ' + loansOfInterest.length + ' loans of interest') for (let i = 0; i < loansOfInterest.length; i++) { let reason = 'would buy' if (loansOwned[loansOfInterest[i].loan.id]) { reason = 'already owned' } else if (loansOfInterest[i].loanScore < minLoanScore) { reason = 'low scoring loan' } else if (!(loansToInvestIn > 0 && loansToBuy.length < loansToInvestIn)) { reason = 'out of budget' } else { loansToBuy.push(loansOfInterest[i]) } logger.info(loanIdToUrl(loansOfInterest[i].loan.id), loansOfInterest[i].loanScore, reason) } if (nconf.get('buy') && loansToBuy.length) { logger.info('Buying ' + loansToBuy.length + ' loans.') const portfolioName = moment().format('YYYY-MM-DD') lc.accounts.createPortfolio(investorId, investorId, portfolioName, null, function (err, data) { handleError(err) const portfolioId = data.portfolioId const orders = [] for (let i = 0; i < loansToBuy.length; i++) { orders.push(lc.accounts.createOrderObject(loansToBuy[i].loan.id, nconf.get('amountToInvest'), portfolioId)) } lc.accounts.submitOrder(investorId, orders, function (err, res) { handleError(err) logger.info(JSON.stringify(res)) }) }) } else if (loansToBuy.lengh > 0) { logger.info('*** Virtual Mode (to act, pass the --buy flag) ***') logger.info('Would have purchased: ') for (let i = 0; i < loansToBuy.length; i++) { logger.info(loanIdToUrl(loansToBuy[i].loan.id)) } } }) }) }) function matchesCriteria (loan) { if (loan.empLength < 47) { return false } if (loan.grade < 'C') { return false } if (loan.addrState === 'CA') { return false } if (loan.homeOwnership === 'RENT') { return false } if (loan.totalAcc < 6) { return false } if (!(loan.purpose === 'debt_consolidation' || loan.purpose === 'wedding' || loan.purpose === 'moving' || loan.purpose === 'house')) { return false } if (loan.accNowDelinq !== 0) { return false } if (loan.chargeoffWithin12Mths !== 0) { return false } if (loan.pubRecBankruptcies !== 0) { return false } if (loan.taxLiens !== 0) { return false } if (loan.accNowDelinq !== 0) { return false } if (loan.installment / (loan.annualInc / 12) > 0.1075) { return false } if (loan.annualInc > 120000) { return false } return true } function handleError (err) { if (err) { logger.error(err) throw err } } function loanIdToUrl (loanId) { return 'https://www.lendingclub.com/browse/loanDetail.action?loan_id=' + loanId }
JavaScript
0.000001
@@ -461,25 +461,16 @@ ng(true, - function (err, d @@ -469,24 +469,27 @@ (err, data) + =%3E %7B%0A handleE @@ -881,23 +881,17 @@ ort( -function (a, b) + =%3E %7B%0A @@ -1076,33 +1076,24 @@ (investorId, - function (err, data) @@ -1088,24 +1088,27 @@ (err, data) + =%3E %7B%0A handl @@ -1302,25 +1302,16 @@ estorId, - function (err, d @@ -1306,32 +1306,35 @@ rId, (err, data) + =%3E %7B%0A handleE @@ -2428,25 +2428,16 @@ e, null, - function (err, d @@ -2440,16 +2440,19 @@ r, data) + =%3E %7B%0A @@ -2824,17 +2824,8 @@ ers, - function (er @@ -2831,16 +2831,19 @@ rr, res) + =%3E %7B%0A
ea0c1e3dbcf9ce04b8fa54c2a9a15e000d67ecc8
tests should be expecting false not true on errors
test/exceptionTests.js
test/exceptionTests.js
var metaconfirm = require('../../meta-confirm'); var expect = require('chai').expect; describe('meta-confirm Exceptions', function () { "use strict"; describe('parameter exceptions', function () { it('return an error if sending a null url without waiting for the timeout', function (done) { var url = null; var searchMetaType = "name"; var searchTag = "description"; var content = "Caspar Computer Services Inc. Providing Innovative Solutions since 1984. Passionate about Agile Development"; metaconfirm.FindInPage(url, searchMetaType, searchTag, content, function callback(err, result) { //if we have no result and no error, it's not completed! if (err) { expect(err.message).equals("url cannot be null"); done(); } if (result) { expect(result).equals(true, "Expecting a True result from Meta Search"); done(); } }); }); it('return an error if sending a null searchTag without needing to do an unnecessary request and wait for timeout', function (done) { var url = "http://www.caspar.com"; var searchMetaType = "name"; var searchTag = null; var content = "Caspar Computer Services Inc. Providing Innovative Solutions since 1984. Passionate about Agile Development"; metaconfirm.FindInPage(url, searchMetaType, searchTag, content, function callback(err, result) { //if we have no result and no error, it's not completed! if (err) { expect(err.message).equals("searchTag cannot be null"); done(); } if (result) { expect(result).equals(true, "Expecting a True result from Meta Search"); done(); } }); }); it('return an error if sending a null content without needing to do an unnecessary request and wait for timeout', function (done) { var url = "http://www.caspar.com"; var searchMetaType = "name"; var searchTag = "description"; var content = null; metaconfirm.FindInPage(url, searchMetaType, searchTag, content, function callback(err, result) { //if we have no result and no error, it's not completed! if (err) { expect(err.message).equals("searchContent cannot be null"); done(); } if (result) { expect(result).equals(true, "Expecting a True result from Meta Search"); done(); } }); }); it('returns an error if sending a null searchType without needing to do an unnecessary request and wait for timeout', function (done) { var url = "http://www.caspar.com"; var searchMetaType = null; var searchTag = "description"; var content = "test"; metaconfirm.FindInPage(url, searchMetaType, searchTag, content, function callback(err, result) { //if we have no result and no error, it's not completed! if (err) { expect(err.message).equals("searchMetaType cannot be null"); done(); } if (result) { expect(result).equals(true, "Expecting a True result from Meta Search"); done(); } }); }); }); });
JavaScript
0.99999
@@ -966,35 +966,36 @@ e, %22Expecting a -Tru +fals e result from Me @@ -1885,35 +1885,36 @@ (result).equals( -tru +fals e, %22Expecting a @@ -1905,35 +1905,36 @@ e, %22Expecting a -Tru +fals e result from Me @@ -2730,35 +2730,36 @@ (result).equals( -tru +fals e, %22Expecting a @@ -2748,37 +2748,36 @@ lse, %22Expecting -a Tru +fals e result from Me @@ -3577,35 +3577,36 @@ (result).equals( -tru +fals e, %22Expecting a @@ -3609,11 +3609,12 @@ g a -Tru +fals e re
d516ac97ba76dc5b98e799e2267c0e467141dda6
update test case for #18
test/extra_carriage.js
test/extra_carriage.js
var net = require('net'), tap = require('tap'), carrier = require('../lib/carrier.js'); tap.test("strips CR", function(t) { var server; var port = 4001; var to_be_sents = ["ONE\r\nTWO\r", "\nTHREE\r\n"]; var expected = ["ONE", "TWO", "THREE"] t.plan(3); server = net.createServer(function(conn) { carrier.carry(conn, function(line) { var e = expected.shift(); t.equal(line, e); }, 'utf8', /\r?\n/); }); server.listen(port); var client = net.createConnection(port); client.once('connect', function() { while(to_be_sents.length) client.write(to_be_sents.shift()); client.end(); }); t.once("end", function() { server.close(); }); });
JavaScript
0
@@ -522,30 +522,21 @@ ;%0A -client.once('connect', +var sendOne = fun @@ -544,22 +544,20 @@ tion + () %7B%0A - while +%09if (to_ @@ -571,18 +571,26 @@ s.length -) +%3E 0) %7B%0A%09%09 client.w @@ -620,29 +620,101 @@ ));%0A - client.end();%0A %7D +%09%09setTimeout(sendOne, 100);%0A%09%7D else %7B%0A%09%09client.end();%0A%09%7D%0A %7D%0A client.once('connect', sendOne );%0A%0A
139d6ef820e0bd8df469c87e6f52d3020dbd62a4
Add waitFor after resize. @bug W-4011728@ @rev bvenkataraman@
aura-components/src/test/components/uitest/virtualDataGrid_resizeTest/virtualDataGrid_resizeTestTest.js
aura-components/src/test/components/uitest/virtualDataGrid_resizeTest/virtualDataGrid_resizeTestTest.js
/* * Copyright (C) 2013 salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ ({ browsers: ["-IE7","-IE8"], WIDTHS : { initialWidths : [200, 400, 100, 50], smallerWidths : [100, 300, 75, 50], smallestWidths : [50, 50, 50, 50] }, COLUMNS : ["Id", "Name", "Grade", "Actions"], testHandlesExist : { test : function(cmp) { var grid = cmp.find("grid"); var columns = grid.getElement().querySelector('th'); for (var i=0; i<columns.length; i++) { $A.test.assertDefined(columns[i].querySelector('.handle'), "Column " + i + " doesn't have a handle."); } } }, testResizeEvent : { test : [function(cmp) { cmp.find("grid").resizeColumns(this.WIDTHS.smallerWidths); }, function(cmp) { var prevResize = cmp.get("v.prevResize"); var lastIndex = this.COLUMNS.length - 1; var columns = cmp.find("grid").getElement().querySelectorAll('th'); $A.test.assertEquals(prevResize.src.label, this.COLUMNS[lastIndex], "Name of last resized column does not match"); $A.test.assertEquals(prevResize.src.index, lastIndex, "Index of last resized column does not match"); $A.test.assertEquals(prevResize.width, columns[lastIndex].clientWidth); }] }, testProgrammaticResizing : { test : [function(cmp) { cmp.find("grid").resizeColumns(this.WIDTHS.smallerWidths); }, function(cmp) { var grid = cmp.find("grid"); var columns = grid.getElement().querySelectorAll('th'); for (var i=0; i<columns.length; i++) { $A.test.assertEquals(columns[i].clientWidth, this.WIDTHS.smallerWidths[i], "Column " + i + " has an incorrect width."); } }] }, testResizingWhenInitializing : { test : [function(cmp) { cmp.find("grid").resizeColumns([300, 500, 400]); }, function(cmp) { var grid = cmp.find("grid"); var columns = grid.getElement().querySelectorAll('th'); for (var i=0; i<columns.length; i++) { $A.test.assertTrue(columns[i].clientWidth >= this.WIDTHS.initialWidths[i], "Column " + i + " should not have resized from " + this.WIDTHS.initialWidths[i] + " to " + columns[i].clientWidth + " since value was -1"); } } ] }, testNegativeResizing : { test : [function(cmp) { cmp.find("grid").resizeColumns([-1, -1, -1]); }, function(cmp) { var grid = cmp.find("grid"); var columns = grid.getElement().querySelectorAll('th'); for (var i=0; i<columns.length; i++) { $A.test.assertTrue(columns[i].clientWidth > -1, "Column " + i + " should not be resized if width is -1"); } } ] }, testTinyResizing : { test : [function(cmp) { cmp.find("grid").resizeColumns([1, 1, 1]); }, function(cmp) { var grid = cmp.find("grid"); var columns = grid.getElement().querySelectorAll('th'); for (var i=0; i<columns.length; i++) { $A.test.assertTrue(columns[i].clientWidth >= this.WIDTHS.smallestWidths[i], "Column " + i + " is smaller than the minWidth value: " + this.WIDTHS.smallestWidths[i]); } }] } })
JavaScript
0.000001
@@ -1857,32 +1857,117 @@ function(cmp) %7B%0A +%09%09 this.waitForResize(cmp, 0, this.WIDTHS.initialWidths%5B0%5D);%0A%09%09%7D, function(cmp) %7B%0A %09%09%09var grid = cm @@ -3680,11 +3680,419 @@ %0A%09%09%7D%5D%0A%09%7D +,%0A%09%0A%09waitForResize : function(cmp, columnIndex, initialSize) %7B%0A $A.test.addWaitForWithFailureMessage(true, function()%7B%0A var columns = cmp.find('grid').getElement().querySelectorAll('th');%0A return columns%5BcolumnIndex%5D.clientWidth !== initialSize;%0A %7D, 'Column width did not change at columnIndex = ' + columnIndex +%0A ' and initial size was ' + initialSize);%0A %7D %0A%7D)
8bd20d16623dbfdfb083052626e6490e66d76e96
Fix email
src/back/app.js
src/back/app.js
var nodemailer = require('nodemailer'); var express = require('express'); var ses = require('nodemailer-ses-transport'); var bodyParser = require('body-parser'); var app = express(); var router = express.Router(); // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: false })); // parse application/json app.use(bodyParser.json()); app.use('/api', router); router.post('/send-email', handleSendEmail); // handle the route at yourdomain.com/sayHello app.listen(4000, function () { console.log('Example app listening on port 4000!') }); console.log('Connecting to ses'); var transporter = nodemailer.createTransport(ses({ accessKeyId: 'AKIAJSPBGMEGVWBE6PKQ', secretAccessKey: 'MMCImyJqTaGPEIoznJ5dCKKSCT8w6qhr5Nn9oTJr', "region": "us-east-1" })); function handleSendEmail(req, res) { if (!req.body) return res.sendStatus(400); var text = `Contacto de: <b>${req.body.name || ''}</b> Teléfono: ${req.body.phone || ''} ${req.body.message}`; var mailOptions = { from: '[email protected]', // sender address to: '[email protected]', // list of receivers subject: `Contacto de ${req.body.name || ''} desde echaurivinos.com.ar`, // Subject line replyTo: req.body.email, text: text//, // plaintext body }; console.log('Sending email from ' + req.body.email); transporter.sendMail(mailOptions, function(error, info){ if (error) { console.log(error); res.json({yo: 'error'}); } else { console.log('Message sent: ' + info.response); res.json({yo: info.response}); } }); }
JavaScript
0.999999
@@ -1633,32 +1633,38 @@ res. -json(%7Byo: info.response%7D +redirect('echaurivinos.com.ar' );%0A
c19071f6930ed3c6e80d50582c0a390544f606c3
No empty lines
app.js
app.js
'use strict' const fs = require('fs') const express = require('express') const http = require('http') const socketio = require('socket.io') const PROD = process.env.NODE_ENV === 'production' const ASSETS_BASE = PROD? '/' : 'http://localhost:3000/' const app = express() const server = http.Server(app) const io = socketio(server) const users = require('./server/users')() const createPoemLines = () => { const poem = fs.readFileSync('poem.txt', 'utf8').split('\n') let index = 0 return () => poem[index > poem.length - 1? (index = 0) : index++] } const poemLine = createPoemLines() let history = [] let i = 0 const tick = () => { setTimeout(tick, 1000) const line = poemLine() history = [...history.slice(-39), { line }] io.emit('text-line', { line }) } tick() io.on('connection', socket => { console.log('Hi ' + socket.id) // Emit the updated list of users io.emit('users', users.add(socket.id)) // Emit the history socket.emit('text-history', history) socket.on('start-bet', letter => { console.log(`${socket.id} started a bet on ${letter}`) io.emit('users', users.addBet(socket.id, letter)) }) socket.on('end-bet', letter => { console.log(`${socket.id} ended a bet on ${letter}`) io.emit('users', users.rmBet(socket.id, letter)) }) socket.on('disconnect', () => { console.log('Bye ' + socket.id) io.emit('users', users.rm(socket.id)) }) }) const homepage = fs.readFileSync(__dirname + '/public/index.html', 'utf8') .replace(/\{BASE\}/g, ASSETS_BASE) app.get('/', (req, res) => { res.send(homepage) }) app.use(express.static(__dirname + '/public')) const port = 8080 server.listen(port) console.log('Express server started on port %s', port)
JavaScript
0.998611
@@ -456,19 +456,65 @@ f8') -.split('%5Cn' +%0A .split('%5Cn').filter(line =%3E line.trim() )%0A
ead8ac8efa1f33dc37c92ceae4b46e45ebc49766
Update noop with a for range loop.
app.js
app.js
#!/usr/bin/env node var express = require('express') var cors = require('cors') var fs = require('fs'); var app = express(); var exec = require('child_process').exec; var sha1 = require('sha1'); var bodyParser = require('body-parser'); var multer = require('multer'); var upload = multer(); const MAX_CODE_LENGTH = 20000; const WRITE_PATH = '/data'; const PREFIX_CODE_1 = `#include <benchmark/benchmark.h> `; const SUFFIX_CODE_1 = ` static void Noop(benchmark::State& state) { while (state.KeepRunning()); } BENCHMARK(Noop); BENCHMARK_MAIN()`; app.use(bodyParser.json()); app.use(cors()); function write(fileName, code) { return new Promise((resolve, reject) => { fs.writeFile(fileName, code, (err) => { if (err) { reject(err); } else { resolve(); } }); }); } function read(fileName, acceptMissing) { return new Promise((resolve, reject) => { fs.readFile(fileName, 'utf8', (err, data) => { if (err) { if (acceptMissing && err.code === 'ENOENT') { resolve(null); } else { reject(err); } } else { resolve(data); } }); }); } function runDockerCommand(fileName, request) { return './run-docker ' + fileName + ' ' + request.compiler + ' ' + request.optim + ' ' + request.cppVersion + ' ' + (request.isAnnotated || false) + ' ' + request.force; } function optionsToString(request) { let options = { "protocolVersion": request.protocolVersion, "compiler": request.compiler, "optim": request.optim, "cppVersion": request.cppVersion, "isAnnotated": request.isAnnotated }; return JSON.stringify(options); } function execute(fileName, request) { let options = { timeout: 60000, killSignal: 'SIGKILL' } return new Promise((resolve, reject) => { exec(runDockerCommand(fileName, request), options, function (err, stdout, stderr) { if (err) { exec("./kill-docker " + fileName); reject("\u001b[0m\u001b[0;1;31mError or timeout\u001b[0m\u001b[1m<br>" + stdout + "<br>" + stderr); } else { resolve({ res: fs.readFileSync(fileName + '.out'), stdout: stderr, id: encodeName(makeName(request)), annotation: request.isAnnotated ? fs.readFileSync(fileName + '.perf', 'utf8') : null }); } }); }); } function groupResults(results) { return new Promise((resolve, reject) => { let code = unwrapCode(results[0]); let options = results[1]; let graph = results[2]; let annotation = results[3]; resolve({ code: code, options: JSON.parse(options), graph: JSON.parse(graph), annotation: annotation }); }); } function makeName(request) { if (request.protocolVersion === 1) return sha1(request.code + request.compiler + request.optim + request.cppVersion + request.protocolVersion); return sha1(request.code + request.compiler + request.optim + request.cppVersion + request.isAnnotated + request.protocolVersion); } function wrapCode(inputCode) { return PREFIX_CODE_1 + inputCode + SUFFIX_CODE_1; } function unwrapCode(inputCode) { if (inputCode.startsWith(PREFIX_CODE_1)) { inputCode = inputCode.slice(PREFIX_CODE_1.length); } if (inputCode.endsWith(SUFFIX_CODE_1)) { inputCode = inputCode.slice(0, -SUFFIX_CODE_1.length); } return inputCode; } function encodeName(id) { let short = new Buffer(id, 'hex').toString('base64'); short = short.replace(new RegExp('/', 'g'), '-').replace(new RegExp('\\+', 'g'), '_'); return short.slice(0, -1); } function decodeName(short) { short = short.replace(new RegExp('\\-', 'g'), '/').replace(new RegExp('_', 'g'), '+ ') + '='; return new Buffer(short, 'base64').toString('hex'); } function getFunctions(code) { RE = /BENCHMARK\s*\(\s*([A-Za-z0-9_]+)\s*\)/g; let content=''; let res; while ((res = RE.exec(code)) !== null) { content+= res[1] + '\n'; } return content; } function benchmark(request) { if (request.code.length > MAX_CODE_LENGTH) { return Promise.reject('\u001b[0m\u001b[0;1;31mError: Unauthorized code length.\u001b[0m\u001b[1m'); } let name = makeName(request); var dir = WRITE_PATH + '/' + name.substr(0, 2); var fileName = dir + '/' + name; return Promise.resolve(write(fileName + '.cpp', wrapCode(request.code))) .then(() => write(fileName + '.func', getFunctions(request.code))) .then(() => write(fileName + '.opt', optionsToString(request))) .then(() => execute(fileName, request)); } function reload(encodedName) { let name = decodeName(encodedName); var dir = WRITE_PATH + '/' + name.substr(0, 2); var fileName = dir + '/' + name; return Promise.all([read(fileName + '.cpp'), read(fileName + '.opt'), read(fileName + '.out'), read(fileName + '.perf', true)]) .then((values) => groupResults(values)); } function makeGraphResult(values, message, id, annotation) { let result = { context: values.context }; let noopTime = values.benchmarks[values.benchmarks.length - 1].cpu_time; result.benchmarks = values.benchmarks.map(obj => { return { name: obj.name, cpu_time: obj.cpu_time / noopTime } }); return { result: result, message: message, id: id, annotation: annotation } } function makeWholeResult(done) { let result = { code: done.code, compiler: done.options.compiler, optim: done.options.optim, cppVersion: done.options.cppVersion, isAnnotated: done.options.isAnnotated, protocolVersion: done.options.protocolVersion }; return Object.assign(result, makeGraphResult(done.graph, '', encodeName(makeName(result)), done.annotation)); } app.post('/', upload.array(), function (req, res) { Promise.resolve(benchmark(req.body)) .then((done) => res.json(makeGraphResult(JSON.parse(done.res), done.stdout, done.id, done.annotation))) .catch((err) => res.json({ message: err })); }); app.get('/get/:id', upload.array(), function (req, res) { Promise.resolve(reload(req.params.id)) .then((done) => res.json(makeWholeResult(done))) .catch(() => res.json({ message: 'Could not load given id' })); }); app.listen(3000, function () { console.log('Listening to commands'); }); exports.makeName = makeName; exports.encodeName = encodeName; exports.decodeName = decodeName; exports.wrapCode = wrapCode; exports.unwrapCode = unwrapCode; exports.groupResults = groupResults; exports.getFunctions = getFunctions;
JavaScript
0
@@ -480,34 +480,55 @@ %7B%0A -while (state.KeepRunning() +for (auto _ : state) benchmark::DoNotOptimize(0 );%0A%7D
f49471d422a9682c73b03d5c3d053f8c972500ad
update tests
test/game-time-test.js
test/game-time-test.js
const assert = require("chai").assert; const HangMan = require("../lib/game-time"); describe("HangMan", function(){ it('should be a function', function(){ assert.isFunction(HangMan); }); it('should instantiate a new Hangman game', function () { var hangman = new HangMan(); assert.isObject(hangman); }); }); describe("hangman", function(){ it('should have a method called "getRandomIndex()"', function(){ var hangman = new HangMan(); assert.isFunction(hangman.getRandomIndex); }); it('should return a random number integer between 0 and 5', function(){ var hangman = new HangMan(); assert.isNumber(hangman.getRandomIndex()); }); it('should return an array with string values', function(){ var hangman = new HangMan(); assert.isString(hangman.getWord()); }); it('should have a function called newGame()"', function(){ var hangman = new HangMan(); assert.isFunction(hangman.newGame); }); it('should have a method called "placeUnderscores()"', function(){ var hangman = new HangMan(); assert.isFunction(hangman.placeUnderscores); }); });
JavaScript
0.000001
@@ -78,18 +78,16 @@ ime%22);%0A%0A -%0A%0A describe @@ -512,32 +512,37 @@ ex);%0A %7D);%0A%0A it +.skip ('should return @@ -583,9 +583,10 @@ and -5 +10 ', f @@ -679,32 +679,37 @@ ());%0A %7D);%0A%0A it +.skip ('should return @@ -827,32 +827,37 @@ ));%0A %7D);%0A%0A%0A it +.skip ('should have a @@ -977,21 +977,25 @@ %0A %7D);%0A%0A -%0A it +.skip ('should
dac9fddc65cc4208db3d0fd88384d136c8d6491c
add get & set event
src/state.js
src/state.js
import Store from './store'; import ListenerTree from './listener-tree'; import { parsePath, stringifyPath, arrayFromAllowNullOrUndefined, } from './utils'; export default class State { constructor({ store = new Store(), cursor = [], emitter = new ListenerTree(), } = {}) { this.__store = store; this.__cursor = cursor; this.__emitter = emitter; } // basic operators cursor(subPath = []) { const { __store, __cursor, __emitter } = this; subPath = parsePath(subPath); return new State({ store: __store, cursor: __cursor.concat(subPath), emitter: __emitter, }); } get(subPath = []) { const { length } = arguments; if (length !== 0) { return this.cursor(subPath).get(); } return this.__store.read(this.__cursor); } set(subPath, value) { const { length } = arguments; if (length < 1) { throw new TypeError('value argument must be set'); } if (length === 1) { [subPath, value] = [undefined, subPath]; } if (subPath !== undefined) { return this.cursor(subPath).set(value); } this.__store.write(this.__cursor, value); this.__emitter.emit(this.__generateEventMessage('change'), { path: stringifyPath(this.__cursor), value, }); } // tree event emitter __generateEventMessage(message) { switch (message) { case 'change': return this.__cursor; default: throw new Error('only change event allow'); } } on(message, callback) { const generatedMessage = this.__generateEventMessage(message); return this.__emitter.on(generatedMessage, callback); } addEventListener(message, callback) { return this.on(message, callback); } off(message, callback) { const generatedMessage = this.__generateEventMessage(message); this.__emitter.off(generatedMessage, callback); } removeEventListener(message, callback) { this.off(message, callback); } // snapshot support snapshot() { return this.__store.snapshot(); } canUndo() { return this.__store.canUndo(); } undo() { return this.__store.undo(); } canRedo() { return this.__store.canRedo(); } redo() { return this.__store.redo(); } // immutable Array operators __arrayOperator(operator, values) { const array = arrayFromAllowNullOrUndefined(this.get()); Array.prototype[operator].apply(array, values); this.set(array); } push(...values) { this.__arrayOperator('push', values); } pop() { this.__arrayOperator('pop'); } unshift(...values) { this.__arrayOperator('unshift', values); } shift() { this.__arrayOperator('shift'); } fill(value) { this.__arrayOperator('fill', [value]); } reverse() { this.__arrayOperator('reverse'); } splice(...values) { this.__arrayOperator('splice', values); } }
JavaScript
0
@@ -157,16 +157,252 @@ tils';%0A%0A +const generateEmitterName = message =%3E %7B%0A if (message === 'get') %7B%0A return 'get';%0A %7D%0A // compatible legacy event%0A if (message === 'set' %7C%7C message === 'change') %7B%0A return 'set';%0A %7D%0A throw new Error('event not allowed');%0A%7D;%0A%0A export d @@ -492,18 +492,32 @@ emitter +s = + %7B%0A get: new Lis @@ -529,16 +529,54 @@ Tree(),%0A + set: new ListenerTree(),%0A %7D,%0A %7D = %7B%7D @@ -651,16 +651,17 @@ _emitter +s = emitt @@ -662,16 +662,17 @@ emitter +s ;%0A %7D%0A%0A @@ -756,16 +756,17 @@ _emitter +s %7D = thi @@ -900,16 +900,17 @@ emitter +s : __emit @@ -912,16 +912,17 @@ _emitter +s ,%0A %7D) @@ -1055,30 +1055,37 @@ ;%0A %7D%0A -return +const value = this.__stor @@ -1107,16 +1107,143 @@ ursor);%0A + this.__emitters.get.emit(this.__cursor, %7B%0A path: stringifyPath(this.__cursor),%0A value,%0A %7D);%0A return value;%0A %7D%0A%0A s @@ -1608,16 +1608,21 @@ _emitter +s.set .emit(th @@ -1630,38 +1630,14 @@ s.__ -generateEventMessage('change') +cursor , %7B%0A @@ -1710,299 +1710,74 @@ %0A%0A -// tree event emitter%0A __generateEventMessage(message) %7B%0A switch (message) %7B%0A case 'change':%0A return this.__cursor;%0A default:%0A throw new Error('only change event allow');%0A %7D%0A %7D%0A%0A on(message, callback) %7B%0A const generatedMessage = this.__generateEventMessag +on(message, callback) %7B%0A const emitterName = generateEmitterNam e(me @@ -1813,28 +1813,39 @@ tter -.on(generatedMessage +s%5BemitterName%5D.on(this.__cursor , ca @@ -1983,104 +1983,102 @@ nst -generatedMessage = this.__generateEventMessage(message);%0A this.__emitter.off(generatedMessage +emitterName = generateEmitterName(message);%0A this.__emitters%5BemitterName%5D.off(this.__cursor , ca
a8dbe4a4af8f40be19593c4c1ed12a6e1651975d
Add Access-Control-Allow-Origin Header for localhost
app.js
app.js
"use strict"; const koa = require("koa"); const cash = require("koa-cash"); const stats = require("./lib"); const favicon = require("koa-favicon"); const cache = require("lru-cache")({ maxAge: 1000 * 60 * 60 * 24 // global max age = 1 Day }); const port = process.env.PORT || 9090; const app = koa(); app.use(favicon()); app.use(require("koa-cash")({ get: function* (key) { return cache.get(key) }, set: function* (key, value) { cache.set(key, value) } })); app.use(function* (next) { try { yield next; } catch (err) { this.status = err.status || 500; this.body = err.message; this.app.emit("error", err, this); } }); app.use(function* (next) { if (yield* this.cashed()) return; yield next; }); app.use(function* (next) { let modules; if (this.query.user) { this.state.modules = yield stats.findModulesByUser(this.query.user); } if (this.query.modules) { this.state.modules = this.state.modules || []; modules = this.query.modules.split(","); if (!Array.isArray(modules)) { modules = [modules]; } this.state.modules = this.state.modules.concat(modules); } this.state.duration = this.query.duration || "month"; if (!this.state.modules) { throw new Error("You have to pass modules via query args: ?user=peerigon&modules=less-loader"); } yield next; }); app.use(function* fetchModules(next) { this.state.modules = yield stats.getStatsForModules(this.state.modules, this.state.duration); yield next; }); app.use(function* stripFields(next) { if (this.query.fields) { this.state.fields = this.query.fields.split(","); } const fields = this.state.fields || ["name", "description", "downloads"]; this.state.downloads = 0; this.state.modules = this.state.modules.map((module) => { const res = {}; fields.forEach(function (field) { res[field] = module[field]; }); if (module.downloads && module.downloads.downloads) { this.state.downloads += module.downloads.downloads; } return res; }); yield next; }); app.use(function* respond() { this.body = { downloads: this.state.downloads, modules: this.state.modules }; }); app.listen(port, function() { console.log(`npm stats listening on port ${port}`); });
JavaScript
0.000001
@@ -2250,24 +2250,89 @@ respond() %7B%0A + this.set(%22Access-Control-Allow-Origin%22, %22http://localhost%22);%0A this.bod @@ -2511,12 +2511,13 @@ port%7D%60);%0A%7D); +%0A
5f9d454f3b07c31839c12ac87437d77e7e9c7f75
Make loader tests dependent on base load
test/js/loader-test.js
test/js/loader-test.js
//window.LocalCache && LocalCache.reset(); function getSelector(sheetNum, ruleNum) { var sheet = document.styleSheets[sheetNum] || {}, rules = sheet.cssRules || sheet.rules || {}, rule = rules[ruleNum] || {}; return rule.selectorText; } // Use setTimeout rather than $.ready to test the loader in the no jquery/zepto case setTimeout(function(){ window.module("Base Loader"); asyncTest('load base', function() { expect(6); equal(undefined, window.LoaderTest, 'Core application module is not loaded'); Loader.loader.loadModule('base', function(err) { notEqual(window.LoaderTest, undefined, 'Core application module is loaded'); equal(document.styleSheets.length, 2, 'Core application stylesheet is loaded'); equal(getSelector(1, 0), '.base', 'stylesheet is expected'); equal(err, undefined); LoaderTest.init(module.exports); start(); }); equal(undefined, window.LoaderTest, 'Core application module is not loaded'); }); window.module("Route Loader"); asyncTest('load module1', function() { expect(8); stop(2); // Add additional stops for the two expected load events notEqual(window.LoaderTest, undefined, 'Core application module is loaded'); equal(window.LoaderTest.module1, undefined, 'module is not loaded'); Loader.loader.unbind(); Loader.loader.bind('load:start', function(moduleName) { equal(moduleName, 'module1', 'Load start occurred'); start(); }); Loader.loader.bind('load:end', function(moduleName) { equal(moduleName, 'module1', 'Load end occurred'); start(); }); LoaderTest.unbind('load'); LoaderTest.bind('load', function(fragment) { equal('module1', fragment, 'Fragment is correct module'); notEqual(window.LoaderTest.module1, undefined, 'module is loaded'); equal(document.styleSheets.length, 3, 'stylesheet is loaded'); equal(getSelector(2, 0), '.module1', 'stylesheet is expected'); Backbone.history.navigate(''); start(); }); Backbone.history.navigate('module1', true); }); asyncTest('load moduleNoRoute', function() { expect(10); stop(2); // Add additional stops for the two expected load events notEqual(window.LoaderTest, undefined, 'Core application module is loaded'); equal(window.LoaderTest.moduleNoRoute, undefined, 'module is not loaded'); equal(window.failedModules.length, 0); Loader.loader.unbind(); Loader.loader.bind('load:start', function(moduleName) { equal(moduleName, 'moduleNoRoute', 'Load start occurred'); start(); }); Loader.loader.bind('load:end', function(moduleName) { equal(moduleName, 'moduleNoRoute', 'Load end occurred'); start(); }); var runCount = 0; Backbone.history.unbind('route'); Backbone.history.bind('route', function(fragment) { runCount || setTimeout(function() { equal(runCount, 2, 'route event occurs only twice'); equal('moduleNoRoute', fragment, 'Fragment is correct module'); notEqual(window.LoaderTest.moduleNoRoute, undefined, 'module is loaded'); equal(window.failedModules.length, 1); equal(window.failedModules[0], 'module was not loaded properly (no route replacement): moduleNoRoute'); Backbone.history.unbind('route'); Backbone.history.navigate(''); start(); }, 500); runCount++; }); Backbone.history.navigate('moduleNoRoute', true); }); document.getElementById('lumbar-modules-loaded').innerHTML = 'modules loaded'; }, 500);
JavaScript
0.000001
@@ -252,118 +252,8 @@ %0A%7D%0A%0A -// Use setTimeout rather than $.ready to test the loader in the no jquery/zepto case%0AsetTimeout(function()%7B%0A wind @@ -270,34 +270,32 @@ %22Base Loader%22);%0A - asyncTest('load @@ -306,34 +306,32 @@ ', function() %7B%0A - expect(6);%0A%0A @@ -328,18 +328,16 @@ ct(6);%0A%0A - equal( @@ -406,26 +406,24 @@ loaded');%0A - - Loader.loade @@ -455,26 +455,24 @@ tion(err) %7B%0A - notEqual @@ -536,34 +536,32 @@ s loaded');%0A - - equal(document.s @@ -616,34 +616,32 @@ et is loaded');%0A - equal(getSel @@ -689,26 +689,24 @@ cted');%0A - equal(err, u @@ -713,26 +713,24 @@ ndefined);%0A%0A - LoaderTe @@ -755,26 +755,24 @@ orts);%0A%0A - start();%0A @@ -770,24 +770,20 @@ rt();%0A - - %7D);%0A - equal( @@ -854,22 +854,106 @@ aded');%0A - %7D);%0A +%0AlumbarLoader.loadComplete = function(name) %7B%0A if (name !== 'base') %7B%0A return;%0A %7D %0A windo @@ -3523,16 +3523,10 @@ aded';%0A%7D -, 500) ;%0A
44526fd288e52be0707e9a3aed6ab2b25f338b1d
fix missing ;
test/lib/pageLoader.js
test/lib/pageLoader.js
/** * Created by Eric Wu on 7/26/14. */ var pageLoader = require('../../lib/pageLoader'); var should = require('should'); var url = "http://www.google.com" describe("pageLoader", function( ){ it('Should load the web page', function (done) { pageLoader(url, function (err, body) { if(err) throw err; body.should.not.be.empty; done(); }); }); it('Should using promise if no callback', function (done) { pageLoader(url) .then(function(body){ body.should.not.be.empty; done(); }) .catch(function(error){ throw error; }) }); });
JavaScript
0.000003
@@ -153,16 +153,17 @@ gle.com%22 +; %0A%0Adescri
702a332ab9a55f2d7a72d82781414c9d7075acbb
Revert "試験的に async を使用するようにした"
src/store.js
src/store.js
import Vue from 'vue' import Vuex from 'vuex' import createPersistedState from 'vuex-persistedstate' import { baseURL, getCall, postCall } from './rest' Vue.use(Vuex) export const mutations = { setItem(state, newItem) { state.item = newItem }, setRecipe(state, newRecipe) { state.recipe = newRecipe }, addCharacter(state, newChar) { Vue.set(state.characters, newChar.name, newChar) }, deleteCharacter(state, char) { Vue.delete(state.characters, char) }, setPrice(state, payload) { Vue.set(state.prices, payload.item, payload.price) }, deletePrice(state, item) { Vue.delete(state.prices, item) } } export const actions = { async setItem({ commit, state }, newItem) { postCall(baseURL+newItem.詳細, { "調達価格": state.prices }, (xhr) => { if (xhr.readyState==4 && xhr.status==200) { commit('setItem', JSON.parse(xhr.response)) } else if (xhr.status==404) { commit('setItem', { アイテム名: newItem.アイテム名, 英名: "", info: "", 重さ: 0.0, NPC売却価格: 0, 参考価格: 0, 特殊条件: [], ペットアイテム: { 種別: '不明' }, レシピ: [], 備考: "細かいことは\nわかりません(´・ω・`)", }) } }) }, async setRecipe({ commit }, newRecipe) { getCall(baseURL+newRecipe.詳細, (xhr) => { if (xhr.readyState==4 && xhr.status==200) { commit('setRecipe', JSON.parse(xhr.response)) } else if (xhr.status==404) { commit('setRecipe', { レシピ名: this.recipe.レシピ名, テクニック: ['わからん'], 必要スキル: { 'わからん': 0 }, 収録バインダー: [{バインダー名: 'わからん'}], レシピ必須: false, 材料: { 'わからん': 0 }, 生成物: { 'わからん': 0 }, 備考: '細かいことは\nわかりません(´・ω・`)', }) } }) }, async setPrice({ commit }, payload) { commit('setPrice', payload) }, async deletePrice({ commit }, item) { commit('deletePrice', item) }, } export default new Vuex.Store({ state: { item: { アイテム名: '', 特殊条件: [], ペットアイテム: { 種別: '不明' }, レシピ: [], info: '', 備考: '', }, recipe: { レシピ名: '', テクニック: ['わからん'], 必要スキル: { 'わからん': 0 }, 収録バインダー: [{バインダー名: 'わからん'}], レシピ必須: false, 材料: { 'わからん': 0 }, 生成物: { 'わからん': 0 }, 備考: 'よくわからん(´・ω・`)', }, characters: { しらたま: { name: 'しらたま' }, }, prices: { }, }, mutations: mutations, actions: actions, plugins: [createPersistedState()] })
JavaScript
0
@@ -669,22 +669,16 @@ s = %7B%0A -async setItem( @@ -703,24 +703,24 @@ newItem) %7B%0A + postCall @@ -1217,22 +1217,16 @@ %0A %7D,%0A -async setRecip @@ -1754,22 +1754,16 @@ %0A %7D,%0A -async setPrice @@ -1827,16 +1827,10 @@ %7D,%0A + -async dele
7aa6e38fdabfcd22242a195fd42fe558346e1043
Fix reply callback
app.js
app.js
'use strict'; let https = require('https'); let db_query = require('./db'); function setWebhook() { let options = { host: "api.telegram.org", path: `/bot${process.env.TELEGRAM_TOKEN}/setWebhook`, method: "POST", headers: { 'Content-Type': "application/json" } }; let post_data = { url: `https://${process.env.SELF_HOSTNAME}/${process.env.TELEGRAM_TOKEN}`, allowed_updates: [ "message" ] }; let post_req = https.request(options, function (res) { res.setEncoding('utf8'); res.on('data', function (chunk) { console.log('Setting Webhook: ' + chunk); }); }); // post the data post_req.write(JSON.stringify(post_data)); post_req.end(); } function serverCallback(req, res) { if(req.url !== `/${process.env.TELEGRAM_TOKEN}`) res.end(JSON.stringify({status: 'not ok', error: 'Wrong request url'})); let data=''; req.on('data', (chunk) => { data+=chunk; }); req.on('end', ()=>{ data = JSON.parse(data); try { onMessage(data.message, (reply_data, callback)=>{ try { sendMessage(data.chat.id, reply_data.text); }catch (err){ callback(err); } }); res.end(JSON.stringify({status: 'ok'})); }catch (err){ res.end(JSON.stringify( {status: 'not ok', error: "Update does not contain message"})); } }); req.on('err', (err)=>{ console.log(err); res.end(JSON.stringify({status: 'not ok', error: err})); }); } function onMessage(msg, reply){ let text = msg.text; let chat_id = msg.chat.id; try { if (text.indexOf("등록") >= 0) { db_query(1, chat_id, function cb(err, exists) { if (err) reply({text: "오류가 발생했습니다. 다시 시도해 주시겠어요?"}, (err) => { if (err) console.log(err); }); else if (exists) reply({text: "이미 등록하셨습니다."}, (err) => { if (err) console.log(err); }); else { let name = msg.from.first_name; let additional_greeting = ''; if(name) additional_greeting = `안녕하세요, ${name}님! `; reply({text: additional_greeting+"등록해주셔서 감사합니다. 앞으로 급식/간식 정보를 보내드릴게요!"}, (err) => { if (err) console.log(err) }); } }); } else if (text.indexOf("해지") >= 0) { db_query(-1, chat_id, function cb(err, exists) { if (err) reply({text: "오류가 발생했습니다. 다시 시도해 주시겠어요?"}, (err) => { if (err) console.log(err); }); else if (exists) reply({text: "해지되었습니다. 그동안 이용해 주셔서 감사합니다."}, (err) => { if (err) console.log(err); }); else reply({text: "음...등록하시지 않으셨는데요?"}, (err) => { if (err) console.log(err) }); }); } }catch (exception){ reply({text: "꾸?"}, (err) => { if (err) console.log(err); }); } } function sendMessage(chat_id, text){ let options = { host: "api.telegram.org", path: `/bot${process.env.TELEGRAM_TOKEN}/sendMessage`, method: "POST", headers: { 'Content-Type': "application/json" } }; let post_data = { "chat_id": chat_id, "text": text }; let post_req = https.request(options, function (res) { res.setEncoding('utf8'); res.on('data', function (chunk) { console.log('Sending message: ' + chunk); }); }); // post the data post_req.write(JSON.stringify(post_data)); post_req.end(); } setWebhook(); https.createServer(serverCallback(req, res)).listen(process.env.PORT || 8080);
JavaScript
0.000002
@@ -1210,16 +1210,24 @@ ge(data. +message. chat.id,
a403c921fe4aca5fb2f9762a5cd2cd5729c453c0
Fix default
src/store.js
src/store.js
import React from 'react' import { reduce } from 'lodash' import { Provider } from 'react-redux' import persistState from 'redux-devtools/lib/persistState' import promiseMiddleware from 'redux-promise' import extendify from 'extendify' import thunkMiddleware from './context-thunk' import asyncMiddleware from './async-tracker' import { compose, createStore, combineReducers, applyMiddleware } from 'redux' const merge = extendify({ inPlace: false, isDeep: true, arrays: 'concat' }) export default class Store { static defaults = { devTools: true, apiClient: {}, reducers: {}, middleware: [], composers: [], buildContext: ({}), createMiddleware: middleware => middleware, createComposers: comp => comp } constructor(opts) { this.options = merge(Store.defaults, opts) this.reducers = this.options.reducers this.middleware = this.options.middleware this.composers = this.options.composers } addReducer(name, reducer) { this.reducers[name] = reducer } upgradeWithRouting(reducers, routingMiddleware) { this.routing = true this.reducers = { ...this.reducers, ...reducers } this.routingMiddleware = routingMiddleware } removeReducer(name) { delete this.reducers[name] } getInitialState() { let state = {} if (__SERVER__) { return state } if (global[this.options.rootVar]) { state = global[this.options.rootVar] } return state } getWrappedComponent(store, instance) { return <Provider store={store} key="provider">{instance}</Provider> } finalize(http) { const initialState = this.getInitialState() let middleware = [ ...this.options.middleware ] if (this.routing) { middleware.push(this.routingMiddleware) } middleware.push(thunkMiddleware(this.options.buildContext, this.options, http)) middleware.push(asyncMiddleware) middleware.push(promiseMiddleware) middleware = this.options.createMiddleware(middleware, http) const reducer = combineReducers({ ...this.reducers }) this.composers.push(applyMiddleware(...middleware)) if (__CLIENT__ && this.options.devTools && global.devToolsExtension) { this.composers.push( global.devToolsExtension(), persistState(global.location.href.match(/[?&]debug_session=([^&]+)\b/)) ) } const composers = this.options.createComposers(this.composers) const finalCreateStore = compose(...composers)(createStore) const finalStore = finalCreateStore(reducer, initialState) if (this.options.auth && typeof this.options.auth.initialize === 'function') { this.options.auth.initialize(finalStore, http) } return finalStore } }
JavaScript
0.00001
@@ -722,16 +722,41 @@ Context: + (store, options, http)=%3E (%7B%7D),%0A
56baef81fe70398eca2e9c1a353ef11d9b0b9ca3
fix `undefined` test
test/napi/lib/hello.js
test/napi/lib/hello.js
var addon = require('../native'); var assert = require('chai').assert; describe('hello', function() { it('should export a greeting', function () { assert.equal(addon.greeting, "Hello, World!"); assert.equal(addon.greeting, addon.greetingCopy); }); it('should export global singletons for JS primitives', function () { assert.equal(addon.undefined, undefined); assert.equal(addon.null, null); assert.equal(addon.true, true); assert.equal(addon.false, false); }); });
JavaScript
0.000248
@@ -373,16 +373,66 @@ fined);%0A + assert.ok(addon.hasOwnProperty('undefined'));%0A asse
937a0e20bd93fb91c5cc5a7ca9445e8fa6c447df
Fix the key call to req.query
app.js
app.js
var http = require('http'); var hellobot = require('./hellobot'); var express = require('express'); var bodyParser = require('body-parser'); //var $ = require('jQuery'); var ig = require('instagram-node').instagram({}); var Slack = require('node-slack'); var slack = new Slack("https://hooks.slack.com/services/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"); var app = express(); var port = process.env.PORT || 3000; // body parser middleware app.use(bodyParser.urlencoded({ extended: true})); app.use(bodyParser.json()); // -------------------------------- // Instagram Authentification // Overide instagram authentification ig.use({ client_id: "bd09eab6bd9b4c9daf691a550faf04a9", client_secret: "e37f5afad6e74ac5906380de076da0d4" }); // Slash command login app.post('/slash', function (req, res) { if (req.query.text == "login") { slack.send({ text: "<https://lit-journey-12058.herokuapp.com/authorize_user|Sign in from here!>" }); res.send("Login slash tag detected") } else { slack.send({ text: "Can't recognize the tag. Try something else plz." }); res.send("Slash tag can't be recognized"); } }); // Below links kept here for testing purposes //https://lit-journey-12058.herokuapp.com/handleauth //http://localhost:3000/handleauth var redirect_uri = "https://lit-journey-12058.herokuapp.com/handleauth"; // Authorize the user by redirecting user to sign in page exports.authorize_user = function(req, res) { res.redirect(ig.get_authorization_url(redirect_uri, { scope: ['likes'], state: 'a state' })); }; // Send message on #general that the user is signed in exports.handleauth = function(req, res) { ig.authorize_user(req.query.code, redirect_uri, function(err, result) { if (err) { console.log(err.body); res.send("Didn't work"); slack.send({ text: "Login Unseccessful :(" }); } else { console.log('Yay! Access token is ' + result.access_token); slack.send({ text: "Log in Successful!\n Welcome to Go Outside Challenge!" }); // Instagram subscription ig.subscriptions(function(err, result, remaining, limit){}); ig.add_user_subscription('https://lit-journey-12058.herokuapp.com/user', function(err, result, remaining, limit){}); } }); }; // This is where pi initially send users to authorize app.get('/authorize_user', exports.authorize_user); // This is redirect URI app.get('/handleauth', exports.handleauth); // --------------------------------- // Instagram subscrription API endpoints app.get('/user', function(req, res) { console.log(req.query); slack.send({ text: req.query }); res.send(req.query.'hub.challenge'); ig.subscriptions(function(err, subscriptions, remaining, limit){ console.log(subscriptions); }); res.send("Subscription Added"); }); app.post('/user', function(req, res) { slack.send({ text: "There's a new picture!" }); res.send("New activity from the subcription detected"); } ); // ---------------------------------- // test route app.get('/', function (req, res) { res.status(200).send('Hello World!') }); // error handler app.use(function (err, req, res, next) { console.error(err.stack); res.status(400).send(err.message); }); app.listen(port, function () { console.log('Slack bot listening on port ' + port); }) // handle the "hello" api call (test case) app.post('/hello', hellobot);
JavaScript
0.999452
@@ -2849,17 +2849,17 @@ eq.query -. +%5B 'hub.cha @@ -2865,16 +2865,17 @@ allenge' +%5D );%0A i
06672372eb6502e2ef2125c5adb608d54f0717d9
Add an ASCII Art Playa logo on startup - Since ASCII art is awesome
app.js
app.js
/** * Module dependencies. */ var express = require('express'); var io = require('socket.io'); var http = require('http'); var app = express(); var server = http.createServer(app); var playa = require('./shared/playa'); var port = process.argv[2]; if(port == undefined) { port = 3000; } // Configuration app.configure(function(){ app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.set('view options', { layout: false }); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(__dirname + '/public')); }); app.configure('development', function(){ app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); app.configure('production', function(){ app.use(express.errorHandler()); }); // Routes app.get('/', playa.index); app.get('/artist/:id', playa.artist); app.get('/album/:id', playa.album); app.get('/status', playa.ok); app.get('/upload', playa.ok); app.post('/upload', playa.ok); // Queue Control app.get('/queue', playa.queue); app.post('/queue/song/:id', playa.addSongToQueue); app.post('/queue/album/:id', playa.addAlbumToQueue); app.post('/queue/remove/:id', playa.removeIdFromQueue) app.post('/queue/clear', playa.clearQueue); app.get('/queue.json', playa.getQueue); app.get('/nowplaying.json', playa.getNowPlaying); // Player Control Routes app.post('/player/play', playa.playMusic); app.post('/player/pause', playa.pauseMusic); app.post('/player/next', playa.nextSong); app.post('/player/stop', playa.stop); // I don't support previous songs yet // app.post('/player/prev', playa.ok); server.listen(port); var io_server = io.listen(server); io_server.set('log level', 0); // reduce logging // Pass Playa.js our io instance playa.setSocketIO(io_server); printLogo(); console.log("Playa server listening on port %d in %s mode", port, app.settings.env); function printLogo() { console.log(" _____ _ "); console.log("| __ \| | "); console.log("| |__) | | __ _ _ _ __ _ "); console.log("| ___/| |/ _` | | | |/ _` |"); console.log("| | | | (_| | |_| | (_| |"); console.log("|_| |_|\__,_|\__, |\__,_|"); console.log(" __/ | "); console.log(" |___/ "); console.log(" "); }
JavaScript
0
@@ -2011,16 +2011,17 @@ (%22%7C __ +%5C %5C%7C %7C @@ -2209,20 +2209,23 @@ %7C_%7C%5C +%5C __,_%7C%5C +%5C __, %7C%5C +%5C __,_
047138d5c2d3b96b03a5dacafa7520da24f4d03b
Make grid smarter
app.js
app.js
import React from 'react'; import ReactDOM from 'react-dom'; import LazyLoad from 'react-lazy-load'; import Lightbox from 'react-image-lightbox'; import JustifiedLayout from 'react-justified-layout'; import Promise from 'es6-promise'; // For older browsers http://caniuse.com/#feat=promises import fetch from 'whatwg-fetch'; import yaml from 'js-yaml'; class Photo { constructor(data) { this.data = data; } getAspectRatio() { return 1.0 * this.data.size.width_o / this.data.size.height_o } inferLargeImage() { let url = this.data.image; if (url.indexOf(".staticflickr.com/") >= 0) { return url.replace(".jpg", "_b.jpg"); // b => 1024 } else if (url.indexOf(".googleusercontent.com/") >= 0) { return url.replace("/s500/", "/s1024/"); } else { return url; } } } class App extends React.Component{ constructor(){ super(); this.state = {photos:null, message:"Loading"}; this.handleResize = this.updateContainerWidth.bind(this) } componentDidMount() { this.updateContainerWidth(); window.addEventListener('resize', this.handleResize); this.loadPhotos('kt-kitty'); } componentDidUpdate(){ this.updateContainerWidth(); } componentWillUnmount(){ window.removeEventListener('resize', this.handleResize, false); } updateContainerWidth(){ let newWidth = ReactDOM.findDOMNode(this).clientWidth; if (newWidth !== this.state.containerWidth){ this.setState({containerWidth: newWidth}); } } loadPhotos(file){ window.fetch(file + '.yaml').then( res => { if (res.ok) { return res.text(); } else { let error = new Error(res.statusText); error.response = res; throw error; } }).then(text => { let data = yaml.load(text); let photos = data.map(obj => {return new Photo(obj)}); this.setState({ allPhotos: photos, photos: photos.slice(0), message: null }); }).catch(ex => { this.setState({ photos: null, message: ex.toString() }); }); } render(){ return( <div className="App"> {this.state.message ? <div>{this.state.message}</div> : null} {this.state.photos ? this.renderGallery() : null} {this.state.isOpen ? this.renderLightbox() : null } </div> ); } renderGallery() { let imgStyle = { width: "100%", height: "100%"}; let imgs = this.state.photos.map((p,i) => { return ( <div aspectRatio={p.getAspectRatio()} style={{backgroundColor: "silver"}}> <a href="#" onClick={this.openLightbox.bind(this, i)}> <LazyLoad offset="200"> <img src={p.data.image} style={imgStyle} /> </LazyLoad> </a> </div> ); }); return <JustifiedLayout targetRowHeight="80" containerWidth={this.state.containerWidth}>{imgs}</JustifiedLayout>; } renderLightbox() { let index = this.state.index; let len = this.state.photos.length; let main = this.state.photos[index]; let next = this.state.photos[(index + 1)%len]; let prev = this.state.photos[(index + len - 1) % len]; let description = ( <div> <span>{main.data.title}</span> {this.state.showDescription ? <ul style={{whiteSpace:"normal", lineHeight:"1em"}}> {main.data.notes.map( n => { return <li>{n}</li> })} </ul> : null} </div> ); return <Lightbox mainSrc={main.inferLargeImage()} nextSrc={next.inferLargeImage()} prevSrc={prev.inferLargeImage()} mainSrcThumbnail={main.data.image} nextSrcThumbnail={next.data.image} prevSrcThumbnail={prev.data.image} onCloseRequest={this.closeLightbox.bind(this)} onMovePrevRequest={this.movePrev.bind(this)} onMoveNextRequest={this.moveNext.bind(this)} toolbarButtons={[ <a href={main.data.source} target="_blank">Web</a>, <a href="#" onClick={this.toggleDescription.bind(this)}>Desc</a> ]} imageTitle={description} />; } openLightbox(i, e) { e.preventDefault(); this.setState({ isOpen: true, index: i }); } closeLightbox() { this.setState({ isOpen: false }); } moveNext() { this.setState({ index: (this.state.index + 1) % this.state.photos.length }); } movePrev() { this.setState({ index: (this.state.index + this.state.photos.length - 1) % this.state.photos.length }); } toggleDescription(e) { e.preventDefault(); let val = this.state.showDescription; this.setState({ showDescription: !val }); } }; ReactDOM.render(<App />, document.getElementById('app'));
JavaScript
0.000002
@@ -3238,12 +3238,48 @@ ght= -%2280%22 +%7B72%7D containerPadding=%7B0%7D boxSpacing=%7B6%7D con
9f7ce20759b6790a844b1aac92cfbd183cbea319
修改抓取检测频率,预防因为服务器问题而出现未抓取的情况
app.js
app.js
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var request = require('superagent'); var session = require('express-session'); var index = require('./routes/index'); var weibo = require('./routes/weibo'); var v1 = require('./routes/v1'); // 设置与安全相关的HTTP头的中间件 var helmet = require('helmet'); // express的消息提示中间件 var flash = require('express-flash'); // 定时器 var schedule = require('node-schedule'); // 各种工具类 var dbUtils = require('./utils/dbUtils'); var bingUtils = require('./utils/bingUtils'); var mailUtils = require('./utils/mailUtils'); var qiniuUtils = require('./utils/qiniuUtils'); var weiboUtils = require('./utils/weiboUtils'); // 每天 01:00 从Bing抓取数据 schedule.scheduleJob('0 0 1 * * *', function() { var date = new Date(); var year = date.getFullYear(); var month = date.getMonth() + 1; var day = date.getDate(); var now = year + '' + month + '' + day; // 查询是否已经抓取并插入数据库,如果已插入就不重复抓取 dbUtils.get('bing', { body: { enddate: now } }, function(rows) { if (rows.length === 0) { bingUtils.fetchPicture({}, function(data) { dbUtils.set('bing', data, function(rows) { data.id = rows.insertId || 0; mailUtils.send({ message: '从Bing抓取成功', title: '从Bing抓取成功', stack: JSON.stringify(data, '', 4) }); }) }); } }); }); // 每天 6:30,10:30,14:30,18:30,21:30 定时发送微博 schedule.scheduleJob('0 30 6,10,14,18,21 * * *', function() { weiboUtils.update(function(data) { if (data && data.id) { mailUtils.send({ message: '发送微博成功', title: '发送微博成功', stack: JSON.stringify(data, '', 4) }); } else { mailUtils.send({ message: '发送微博失败', title: '发送微博失败', stack: JSON.stringify(data, '', 4) }); } }, true); }); // 每隔十分钟检查数据库中是否存在未上传到骑牛的图片,如果存在则上传图片到骑牛 schedule.scheduleJob('0 0,10,20,30,40,50 * * * *', function() { dbUtils.get('bing', 'ISNULL(qiniu_url) || qiniu_url=""', function(rows) { if (rows.length > 0) { var data = rows[0]; var url = data.url; qiniuUtils.fetchToQiniu(url, function() { var _temp = url.substr(url.lastIndexOf('/') + 1, url.length); var qiniu_url = _temp.substr(0, _temp.lastIndexOf('_')); dbUtils.update('bing', { body: { qiniu_url: qiniu_url }, condition: { id: data.id } }, function(rs) { // nsole.log(rs); }); }); } }); }) var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'pug'); app.enable('trust proxy'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(cookieParser('bing.ioliu.cn')); app.use(session({ secret: 'bing app', //secret的值建议使用随机字符串 cookie: { secure: true, maxAge: 60 * 30 * 1000 // 过期时间(毫秒) }, resave: false })); // 设置日志 app.use(logger('combined', { skip: function(req, res) { return res.statusCode < 400 } })); // 启用 helmet app.use(helmet()); app.use(flash()); //sass //app.use(sassMiddleware({ // src: __dirname // , dest: __dirname // , sourceMap: false // , outputStyle: 'compressed' // , debug: true //})); app.use('/static', express.static(path.join(__dirname, 'static'))); app.use(favicon(__dirname + '/static/images/bing.ico')); /** * 全局过滤 */ app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,Access-Control-Allow-Origin"); res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS"); // 处理OPTIONS请求 if (req.method === 'OPTIONS') { res.send(200); } else next(); }); app.use('/', index); app.use('/weibo', weibo); app.use('/v1', v1); /** * Robots.txt */ app.use('/robots.txt', function(req, res, next) { res.header('content-type', 'text/plain'); res.send('User-Agent: * \nAllow: /'); }); app.get('/test', function(req, res, next) { var images = []; bingUtils.fetchPicture(function(data) { dbUtils.get('bing', data, function(data) { res.send(data); }); }); }); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('啊( ⊙ o ⊙ ),你发现了新大陆 ∑(っ °Д °;)っ'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = app;
JavaScript
0
@@ -838,17 +838,35 @@ / %E6%AF%8F%E5%A4%A9 01: -0 +10,05:10,09:10,13:1 0 %E4%BB%8EBing%E6%8A%93 @@ -898,11 +898,19 @@ ('0 +1 0 1 +,5,9,13 * *
1c2456553e1a00e7ff13b196867f0a5ce17a3e4e
Fix initial object list loading. Closes #11.
app.js
app.js
var codeObjects = {}; var express = require('express'); var path = require('path'); var favicon = require('static-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var home = require('./routes/index')(codeObjects); var playground = require('./routes/playground'); var create = require('./routes/create'); var app = require('express.io')(); var cons = require('consolidate'); // view engine setup app.set('views', path.join(__dirname, 'views')); app.engine('hbs', cons.handlebars); app.set('view engine', 'hbs'); app.use(favicon()); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded()); app.use(cookieParser()); app.use(require('less-middleware')(path.join(__dirname, 'public'))); app.use(express.static(path.join(__dirname, 'public'))); app.use('/playground/', playground); app.use('/list', home); app.use('/', create); // app.use(function(req, res, next) { // var err = new Error('Not Found'); // err.status = 404; // next(err); // }); // /// error handlers // // development error handler // // will print stacktrace // if (app.get('env') === 'development') { // app.use(function(err, req, res, next) { // res.status(err.status || 500); // res.render('error', { // message: err.message, // error: err // }); // }); // } // // production error handler // // no stacktraces leaked to user // app.use(function(err, req, res, next) { // res.status(err.status || 500); // res.render('error', { // message: err.message, // error: {} // }); // }); // attach socket.io to the http server app.http().io(); app.io.route('programmer up', function (req) { // server gets notified when programmer.html page is loaded var playground = req.data, objectIds; req.io.join(req.data); // have client (req) join the room named after Playground Id if (codeObjects[playground]) { objectIds = Object.keys(codeObjects[playground]); req.io.emit('objects full update', objectIds); } }); app.io.route('playground up', function(req) { console.log(req.data + " from playground renderer"); req.io.join(req.data); if (!codeObjects[req.data]) return; req.io.emit('playground full update', codeObjects[req.data]); }); app.io.route('code update', function(req) { // Broadcast the code update event on the playground up route, only to the room (playground) concerned. var playground = req.data.playgroundid, objectIds, data; console.log(playground + " from programmer"); req.io.join(playground); // it seems we need to join the room to broadcast if (!codeObjects[playground]) codeObjects[playground] = {}; codeObjects[playground][req.data.codeid] = req.data.code; req.io.room(playground).broadcast('code update', req.data); objectIds = Object.keys(codeObjects[playground]); data = {playgroundId: playground, objectIds: objectIds}; app.io.room(playground).broadcast('objects full update', data); }); app.io.route('request code', function (req) { var playground = req.data.playgroundId, objectId = req.data.objectId, code = getCode(playground, objectId), data = {playgroundId: playground, objectId: objectId, code: code}; req.io.emit('source code', data); }); var getCode = function (playground, objectId) { if (! codeObjects[playground]) return ""; if (! codeObjects[playground][objectId]) return ""; return codeObjects[playground][objectId]; }; module.exports = app;
JavaScript
0
@@ -1707,24 +1707,180 @@ tp().io();%0A%0A +function makeFullUpdate(playground) %7B%0A var objectIds = Object.keys(codeObjects%5Bplayground%5D);%0A return %7BplaygroundId: playground, objectIds: objectIds%7D;%0A%7D%0A%0A app.io.route @@ -2005,25 +2005,8 @@ data -,%0A objectIds ;%0A%0A @@ -2128,62 +2128,8 @@ ) %7B%0A - objectIds = Object.keys(codeObjects%5Bplayground%5D);%0A @@ -2163,25 +2163,42 @@ pdate', -objectIds +makeFullUpdate(playground) );%0A %7D%0A%7D @@ -2247,18 +2247,16 @@ (req) %7B%0A - consol @@ -2296,34 +2296,32 @@ d renderer%22);%0A - - req.io.join(req. @@ -2328,18 +2328,16 @@ data);%0A%0A - if (!c @@ -2367,18 +2367,16 @@ eturn;%0A%0A - req.io @@ -2436,17 +2436,16 @@ );%0A%7D);%0A%0A -%0A app.io.r @@ -2584,18 +2584,16 @@ cerned.%0A - var pl @@ -2628,48 +2628,13 @@ ndid -,%0A objectIds,%0A data ;%0A%0A - - cons @@ -2675,18 +2675,16 @@ mmer%22);%0A - req.io @@ -2753,18 +2753,16 @@ adcast%0A%0A - if (!c @@ -2817,18 +2817,16 @@ = %7B%7D;%0A - - codeObje @@ -2876,18 +2876,16 @@ .code;%0A%0A - req.io @@ -2942,126 +2942,8 @@ a);%0A -%0A objectIds = Object.keys(codeObjects%5Bplayground%5D);%0A data = %7BplaygroundId: playground, objectIds: objectIds%7D;%0A ap @@ -2993,28 +2993,50 @@ ll update', -data +makeFullUpdate(playground) );%0A%7D);%0A%0Aapp. @@ -3509,18 +3509,16 @@ d%5D;%0A%7D;%0A%0A - module.e
8baf0b8be353485a859970a7ea066dd9004fbe8a
Change back mongodb URI
app.js
app.js
const express = require('express'); const bodyParser = require('body-parser'); const mongoose = require('mongoose'); const contactRoutes = require('./routes/contactsRouter'); const userRoutes = require('./routes/usersRouter'); const app = express(); // Use body-parser middleware app.use(bodyParser.json()); // Use Express Router app.use('/api/contacts', contactRoutes); app.use('/api/users', userRoutes); // Create database variable outside of the connection var db; // Connect to mongoose (Change the URI or localhost path for mongodb as needed) mongoose.connect(process.env.MONGODB_URI || 'Database address go here', { useMongoClient: true }, function(err) { // Exit process if unable to connect to db if (err) { console.log(err); process.exit(1); } // Save databse object db = mongoose.connection; console.log("Database connection ready"); // Serve the app var server = app.listen(process.env.PORT || 8080, function() { var port = server.address().port; console.log("App now running on port", port); }); }); // API home app.get('/', function(req, res) { res.send('Use /api/contacts, or /api/users'); });
JavaScript
0.000014
@@ -594,32 +594,93 @@ %7C%7C ' -Database address go here +mongodb://achowdhury2015:[email protected]:25263/achowdhury-mean-contact ', %7B
c63f4f9dfb8f3156740a9067265fa409ec133854
edit of app.js
app.js
app.js
"use strict"; var path = require("path"); var express = require("express"); var config = require('./config') var fs = require("fs"); var https = require("https"); var app = express(); var http = express(); var clavePrivada = fs.readFileSync(config.private_key).; var certificado = fs.readFileSync(config.certificate); app.set("view engine", "ejs"); app.set("views", path.join(__dirname, "views")); app.use(express.static(path.join(__dirname, "public"))); var servidor = https.createServer({ key: clavePrivada, cert: certificado }, app); http.get("*",(req,res) => { res.redirect("https://carmargut.com"); }); app.get("/",(req, res) => { res.render("index",{}); }); http.listen(80,() => {}); servidor.listen(config.port, () => { console.log("Servidor corriendo en el puerto " + config.port); });
JavaScript
0.000001
@@ -265,17 +265,16 @@ ate_key) -. ;%0D%0Avar c
12f84e9753b73f326c7c32a840c9ccf00168e5ec
Make sure mocha.done function call is without arguments.
test/removeListener.js
test/removeListener.js
/*jslint node: true */ "use strict"; var H = require('../index').EventEmitter; var _ = require('underscore'); var assert = require('assert'); describe('HevEmitter on', function () { describe('removeListener', function () { it('should NOT trigger one level method after one level removal', function (done) { var h = new H(); var f = function () { assert(false); }; h.on(['son'], f); h.removeListener(['son'], f); h.emit(['son']) .then(done); }); it('SHOULD trigger one level method after one level removal of different function', function (done) { var h = new H(); var f = function () { done(); }; h.on(['son'], f); h.removeListener(['son'], function () {}); h.emit(['son']); }); it('should NOT trigger one level method after one star removal', function (done) { var h = new H(); var f = function () { assert(false); }; h.on(['circus'], f); h.removeListener(['*'], f); h.emit(['circus']) .then(done); }); it('SHOULD trigger one level method after one star removal of different function ', function (done) { var h = new H(); var f = function () { done(); }; h.on(['circus'], f); h.removeListener(['*'], function () {}); h.emit(['circus']); }); it('SHOULD trigger two level method after one star removal', function (done) { var h = new H(); var f = function () { done(); }; h.on(['gore', 'leena'], f); h.removeListener(['*'], f); h.emit(['gore', 'leena']); }); it('should NOT trigger two level method after one star removal', function (done) { var h = new H(); var f = function () { assert(false); }; h.on(['squirrel', 'snake'], f); h.removeListener(['*', 'snake'], f); h.emit(['squirrel', 'snake']) .then(done); }); it('SHOULD trigger two level method after one star removal of different function', function (done) { var h = new H(); var f = function () { done(); }; h.on(['squirrel', 'snake'], f); h.removeListener(['*', 'snake'], function () {}); h.emit(['squirrel', 'snake']); }); it('should NOT trigger one level method after two star removal', function (done) { var h = new H(); var f = function () { assert(false); }; h.on(['sadface'], f); h.removeListener(['**'], f); h.emit(['sadface']) .then(done); }); it('should NOT trigger one level method after two star removal', function (done) { var h = new H(); var f = function () { done(); }; h.on(['sadface'], f); h.removeListener(['**'], function() {}); h.emit(['sadface']); }); it('should NOT trigger two level method after two star removal', function (done) { var h = new H(); var f = function () { assert(false); }; h.on(['cash', 'act'], f); h.removeListener(['**'], f); h.emit(['cash', 'act']) .then(done); }); it('SHOULD trigger two level method after two star removal of different function', function (done) { var h = new H(); var f = function () { done(); }; h.on(['cash', 'act'], f); h.removeListener(['**'], function () {}); h.emit(['cash', 'act']); }); }); });
JavaScript
0.000001
@@ -539,36 +539,55 @@ .then( -done +function () %7B done(); %7D );%0A %7D);%0A%0A @@ -1244,36 +1244,55 @@ .then( -done +function () %7B done(); %7D );%0A %7D);%0A%0A @@ -2304,36 +2304,55 @@ .then( -done +function () %7B done(); %7D );%0A %7D);%0A%0A @@ -3045,36 +3045,55 @@ .then( -done +function () %7B done(); %7D );%0A %7D);%0A%0A @@ -3755,20 +3755,39 @@ .then( -done +function () %7B done(); %7D );%0A
75507fac15ad30b8fd378eff1f850e80ad877b79
Question 6 number game
app.js
app.js
var userName = prompt ('Hello what\'s your name?').toUpperCase(); console.log ('Hello ' + userName + ' , nice to meet you!'); alert ('Hello' + ' ' + userName + ' ' + 'nice to meet you! I have a guessing game I would like you to play. Click the "ok" button to contiune.'); var counterRight = 0; var counterWrong = 0; var counterScore = ' Your current score is '; var question1 = prompt ('Would you believe, I\'ve raised four chickens from little chicks to hens?').toUpperCase(); var sp = ' '; if (question1 === 'Y' || question1 === 'YES' ){ counterRight ++; console.log ('Yep, Yep' + ' ' + question1 + sp + counterRight); alert ('I did, their names were Sunny, Scritch, Sammy, Scratch!' + ' ' + question1 + sp + counterRight); }else{ counterWrong ++; console.log ('Well actually I did, crazy I know; they even had names: Sammy, Sunny, Scritch, Scratch.' + sp + counterWrong); alert('Well actually I did, crazy I know; they even had names: Sammy, Sunny, Scritch, Scratch.' + sp + counterWrong); } alert('Ok, you know about my chickens, I have another question for you'); var question2 = prompt ('Do you think I think cooking is one of the most relaxing thing ever?').toUpperCase(); if (question2 === 'YES' || question2 === 'Y'){ counterRight ++; console.log ('Yea, great guess' + ' ' + question2 + counterRight); alert ('That\'s right, great guess!, one of the most relaxing things for me to do is cook dinner!' + sp + counterRight); }else{ counterWrong ++; console.log ('I thinking cooking is one of the best things ever!' + ' ' + question2 + sp + counterWrong); alert ('I thinking cooking is one of the best things ever!' + sp + counterWrong); } var question3 = prompt ('The most fun I have in any of my days is playing with my kids(Yes) or wash dishes after dinner(No)?').toUpperCase(); if (question3 === 'YES' || question3 === 'Y'){ counterRight ++; console.log ('Yep, nothing more fun' + ' ' + question3 + sp + counterRight); alert('Yep, nothing more fun in the world!' + sp + counterRight ); }else{ counterWrong ++; console.log ('Come on, dishes are the worst!' + ' ' + question3 + sp + counterWrong); alert('Come on, dishes are the worst!' + sp + counterWrong); } var question4 = prompt ('Yes or No, I currently have a garden project in my new place?').toUpperCase(); if (question4 === 'YES' || 'Y'){ counterRight ++; console.log ('Yess, I love fresh vegies they taste so much better' + ' ' + question4 + sp + counterRight); alert('Yesss, I love fresh veg\'s they taste so much better!' + sp + counterRight); }else{ counterWrong ++; console.log('Well, the truth is I currently have the biggest garden I\'ve ever had!' + ' ' + question4 + sp + counterWrong); alert('Well, the truth is I currently have the biggest garden I\'ve ever had!' + sp + counterWrong); } var question5 = prompt ('This is the final question to guess. The books I read most often are sci-fyi military novels!').toUpperCase(); if (question5 === 'YES' || question5 === 'Y'){ console.log('That\'s right' + ' ' + question5 + sp + counterRight); alert ('You guessed right!' + sp + counterRight); } else { console.log('Well, actually I do like those types of novels' + ' ' + question5 + sp + counterWrong); alert ('Well, actually I do like that those types of novels' + sp + counterWrong); } var petArray = ['MONKEY', 'FISH', 'HEN']; var guessTries = 0; var question7; while (guessTries < 6) { question7 = prompt ('In this question I\'ll give you 6 tries to guess one of these. ' + 'What is a pet I had other than a cat or dog?').toUpperCase(); for (i = 0; i < petArray.length; i++) { if (question7 === petArray[i]) { alert ('That\'s right!' + ' ' + petArray + counterRight); console.log('Correct answer was',question7); i = petArray.length; guessTries = 6; console.log([i], 'is i'); } } guessTries ++; } prompt ( 'Yeaaaa, ' + userName + ' you finished! Your total score for this game is ' + counterRight + sp + 'Thanks for playing!');
JavaScript
0.999984
@@ -3319,16 +3319,221 @@ ong);%0A%7D%0A +var question6 = prompt ('Guess a number between 1 and 20, I%5C'll give you 4 tries');%0Awhile (guessNumberGame %3C 4 ) %7B%0A alert ('Guess again');%0A if (question6 === 8) %7B%0A alert ('Yep, you got it! ');%0A %7D%0A%7D%0A%0A var petA
173cd401af093ac30884f670e09e7bd254107c13
Remove invalid removeListener test.
test/removeListener.js
test/removeListener.js
/*jslint node: true */ "use strict"; var H = require('../index').EventEmitter; var _ = require('underscore'); var assert = require('assert'); describe('HevEmitter on', function () { describe('removeListener', function () { it('should NOT trigger one level method after one level removal', function (done) { var h = new H(); var f = function () { assert(false); }; h.on(['son'], f); h.removeListener(['son'], f); h.emit(['son']) .then(function () { done(); }); }); it('SHOULD trigger one level method after one level removal of different function', function (done) { var h = new H(); var f = function () { done(); }; h.on(['son'], f); h.removeListener(['son'], function () {}); h.emit(['son']); }); it('should NOT trigger one level method after one star removal', function (done) { var h = new H(); var f = function () { assert(false); }; h.on(['circus'], f); h.removeListener(['*'], f); h.emit(['circus']) .then(function () { done(); }); }); it('SHOULD trigger one level method after one star removal of different function ', function (done) { var h = new H(); var f = function () { done(); }; h.on(['circus'], f); h.removeListener(['*'], function () {}); h.emit(['circus']); }); it('SHOULD trigger two level method after one star removal', function (done) { var h = new H(); var f = function () { done(); }; h.on(['gore', 'leena'], f); h.removeListener(['*'], f); h.emit(['gore', 'leena']); }); it('should NOT trigger two level method after one star removal', function (done) { var h = new H(); var f = function () { assert(false); }; h.on(['squirrel', 'snake'], f); h.removeListener(['*', 'snake'], f); h.emit(['squirrel', 'snake']) .then(function () { done(); }); }); it('SHOULD trigger two level method after one star removal of different function', function (done) { var h = new H(); var f = function () { done(); }; h.on(['squirrel', 'snake'], f); h.removeListener(['*', 'snake'], function () {}); h.emit(['squirrel', 'snake']); }); it('should NOT trigger one level method after two star removal', function (done) { var h = new H(); var f = function () { assert(false); }; h.on(['sadface'], f); h.removeListener(['**'], f); h.emit(['sadface']) .then(function () { done(); }); }); it('should NOT trigger one level method after two star removal', function (done) { var h = new H(); var f = function () { done(); }; h.on(['sadface'], f); h.removeListener(['**'], function() {}); h.emit(['sadface']); }); it('should NOT trigger two level method after two star removal', function (done) { var h = new H(); var f = function () { assert(false); }; h.on(['cash', 'act'], f); h.removeListener(['**'], f); h.emit(['cash', 'act']) .then(function () { done(); }); }); it('SHOULD trigger two level method after two star removal of different function', function (done) { var h = new H(); var f = function () { done(); }; h.on(['cash', 'act'], f); h.removeListener(['**'], function () {}); h.emit(['cash', 'act']); }); }); });
JavaScript
0
@@ -3096,334 +3096,8 @@ );%0A%0A - it('should NOT trigger one level method after two star removal', function (done) %7B%0A var h = new H();%0A var f = function () %7B%0A done();%0A %7D;%0A h.on(%5B'sadface'%5D, f);%0A h.removeListener(%5B'**'%5D, function() %7B%7D);%0A h.emit(%5B'sadface'%5D);%0A %7D);%0A%0A
1ea29ccc0760f9060d1c6eea2bfc42d435381509
handle ? in path
app.js
app.js
// deprecating, replacing with serverless mode var RUNNING_LOCAL = (document.location.host == 'localhost' || document.location.host == '127.0.0.1' || document.location.protocol == 'file:'); var API_URL = RUNNING_LOCAL ? 'http://0.0.0.0:5000/' : 'http://opentaba-server.herokuapp.com/'; // var API_URL = '/'; // serverless, bitches! just store the JSON in the directory and grab it from there. function show_data(url){ if (url.indexOf('.pdf', url.length - 4) !== -1) { // endsWith('.pdf')? new PDFObject({ url: url }).embed("modal-doc"); } else { $("#modal-doc").html('<iframe src="' + url + '"></iframe>'); } $("#doc_new_window").attr("href", url); $("#docModal").modal().css({ width: '90%', height: '80%', 'margin-left': function () { return -($(this).width() / 2); } }); } function render_plans(plans) { var out = '<h3 style="color: grey;">גוש ' + plans[0].gush_id + '</h3>'; // html brought to you courtsey of 1998 out += "<table>"; for (var i = 0 ; i<plans.length ; i++) { p = plans[i]; //plan_link = 'http://www.mmi.gov.il/IturTabot/taba2.asp?Gush=' + p.gush_id + '&MisTochnit=' + escape(p.number) plan_link = 'http://mmi.gov.il/IturTabot/taba4.asp?kod=3000&MsTochnit=' + escape(p.number) out+='<tr style="vertical-align:top" class="item">' + ' <td><b>' + [p.day, p.month, p.year].join('/') + '</b></td>' + ' <td>' + p.status + '</td>'+ ' <td><b>' + p.essence + '</b></td>'+ '</tr>' + '<tr class="details">' + ' <td colspan="2">' + ' <a href="' + plan_link + '" target="_blank" rel="tooltip" title="פתח באתר ממי"><!-- i class="icon-share"></i -->'+ ' תוכנית ' + p.number + '</a>' + ' </td>' + ' <td>'; for (var j=0 ; j<p.tasrit_link.length ; j++) out += '<a onclick="show_data('+ "'" + p.tasrit_link[j] + "')" + '" rel="tooltip" title="תשריט"><i class="icon-globe"></i></a>' for (var j=0 ; j<p.takanon_link.length ; j++) out += '<a onclick="show_data('+ "'" + p.takanon_link[j] + "')" + '" rel="tooltip" title="תקנון"><i class="icon-file"></i></a>' for (var j=0 ; j<p.nispahim_link.length ; j++) out += '<a onclick="show_data('+ "'" + p.nispahim_link[j] + "')" + '" rel="tooltip" title="נספחים"><i class="icon-folder-open"></i></a>' for (var j=0 ; j<p.files_link.length ; j++) out += '<a href="http://mmi.gov.il' + p.files_link[j] + '" rel="tooltip" title="קבצי ממג"><i class="icon-download-alt"></i></a>' out+=' </td>' + '</tr>' + '<tr style="height: 10px"><td colspan="3">&nbsp;</td></tr>'; } out += '</table>'; $("#info").html(out); // activate Boostrap tooltips on attachment icons $("[rel='tooltip']").tooltip({'placement' : 'bottom'}); $(".item").hover( function () { $(this).css("background","#fff"); $(this).next(".details").css("background","#fff"); }, //#f7f7f9 function () { $(this).css("background","") ; $(this).next(".details").css("background",""); } ); $(".details").hover( function () { $(this).css("background","#fff"); $(this).prev(".item").css("background","#fff"); }, function () { $(this).css("background","") ; $(this).prev(".item").css("background",""); } ); // $(".item").click( // function () { $(this).next().toggle(); } // ); } function get_gush(gush_id) { console.log("get_gush: " + API_URL + 'gush/' + gush_id + '/plans') $.getJSON( API_URL + 'gush/' + gush_id + '/plans', function(d) { render_plans(d); } ) } // find a rendered gush based on ID function find_gush(gush_id){ g = gushim.features.filter( function(f){ return (f.properties.Name == gush_id); } ) return g[0]; } function onEachFeature(feature, layer) { layer.bindPopup(feature.properties.Name + " גוש "); layer.on({ 'mouseover' : function() { this.setStyle({ opacity: 0 , color: "red" }) }, 'mouseout' : function() { this.setStyle({ opacity: 0.95, color: "#777" }) }, 'click' : function() { $("#info").html("עוד מעט..."); location.hash = "#/gush/" + feature.properties.Name; // get_gush(feature.properties.Name); } }); } // jQuery startup funcs $(document).ready(function(){ // comment out for serverless // wake up possibly-idling heroku dyno to make sure later requests aren't too slow $.getJSON( API_URL + "wakeup" , function(){ // do nothing }); // setup a path.js router to allow distinct URLs for each block Path.map("#/gush/:gush_id").to( function(){ $("#docModal").modal('hide'); get_gush(this.params['gush_id']); } ); Path.listen(); }); var map = L.map('map', { scrollWheelZoom: false }).setView([31.765, 35.17], 13); tile_url = 'http://{s}.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/{z}/{x}/{y}.png'; L.tileLayer(tile_url, { maxZoom: 18, }).addTo(map); L.geoJson(gushim, { onEachFeature: onEachFeature, style : { "color" : "#777", "weight": 1, "opacity": 0.9 } } ).addTo(map);
JavaScript
0.999987
@@ -4464,19 +4464,63 @@ ush_id'%5D -); +.split('?')%5B0%5D); // remove '?params' if exists %0A%09%09%7D%0A%09);
8b995288d853136cd69fe293a7e2285f14ce17a9
Remove empty module.
app.js
app.js
var processManager = require('./controllers/process-manager'); processManager.fork('/controllers/api'); processManager.fork('/controllers/fetching'); processManager.fork('/controllers/streaming'); module.exports = processManager;
JavaScript
0
@@ -146,55 +146,8 @@ g'); -%0AprocessManager.fork('/controllers/streaming'); %0A%0Amo
7ff6c20240a6384b0c318138278d6770187fc578
remove unused log
stackfanatic.js
stackfanatic.js
var args = require('system').args; var page = require('webpage').create(); var env = require('system').env; var googleEmail = args[1] || env.GOOGLE_EMAIL; var googlePassword = args[2] || env.GOOGLE_PASSWORD; var landingUrl = "http://stackoverflow.com/"; var loginUrl = "https://stackoverflow.com/users/login"; var googleLoginUrl = "https://accounts.google.com"; if (!googleEmail && !googlePassword) { console.log("either give google email and password as parameter, either use GOOGLE_EMAIL and GOOGLE_PASSWORD env variables."); phantom.exit(); } page.onConsoleMessage = function (msg) { console.log(msg); }; page.onNavigationRequested = function (url, type, willNavigate, main) { console.log(url); if (url == landingUrl) { console.log("success"); console.log("lets enjoy the view here a bit..."); setTimeout(function () { console.log("bye bye"); phantom.exit(); }, 10000); } else if (url.indexOf(googleLoginUrl) == 0) { trySignIn(); } }; page.open(loginUrl, function(status) { page.evaluate(function () { var divs = document.getElementsByClassName("google-login"); if (divs != null && divs.length > 0) { console.log("loging in with google"); divs[0].click(); } }); }); function trySignIn() { if (enterEmail()) { setTimeout(function () { enterPassword(); console.log("entered password"); }, 1000); } } function enterEmail() { return page.evaluate(function (googleEmail) { var emailInput = document.getElementById("Email"); var nextButton = document.getElementById("next"); if (emailInput && nextButton) { emailInput.value = googleEmail; nextButton.click(); console.log("enter email sucess"); return true; } console.log("enter email failure"); return false; }, googleEmail); } function enterPassword() { page.evaluate(function (googlePassword) { var passwordInput = document.getElementById("Passwd"); var signInButton = document.getElementById("signIn"); if (passwordInput && signInButton) { passwordInput.value = googlePassword; signInButton.click(); console.log("enter password sucess"); return true; } console.log("enter password failure"); return false; }, googlePassword); }
JavaScript
0.000002
@@ -1430,53 +1430,8 @@ ();%0A - console.log(%22entered password%22);%0A
2add17f98b95b2beac50579b93da31a81c351675
disable seedDB
server/config/environment/development.js
server/config/environment/development.js
'use strict'; // Development specific configuration // ================================== module.exports = { // MongoDB connection options mongo: { uri: 'mongodb://localhost/jagen-dev' }, // Seed database on startup seedDB: true };
JavaScript
0.000001
@@ -238,11 +238,12 @@ DB: -tru +fals e%0A%0A%7D
77562c06cfe6ca4f3635285f408e4bd746c84d3b
add ca to coverage
test/servers/server.js
test/servers/server.js
'use strict'; const sinon = require('sinon'); const http = require('http'); const https = require('https'); const server = require('../../servers/server'); const path = require('path'); const fs = require('fs'); const FIXTURE_PATH = path.join(__dirname, 'fixtures'); const CERT_FIXTURE_PATH = path.join(FIXTURE_PATH, 'servercert.pem'); const KEY_FIXTURE_PATH = path.join(FIXTURE_PATH, 'serverkey.pem'); const CA_PATH = path.join(FIXTURE_PATH, 'cas'); const sandbox = sinon.sandbox.create(); const app = {}; const mockServer = { listen: sandbox.spy() }; function stubFsForDefaultCerts() { sandbox.stub(fs, 'readFileSync').withArgs(path.join(process.cwd(), 'certs', 'serverkey.pem')).returns('defaultkey'); fs.readFileSync.withArgs(path.join(process.cwd(), 'certs', 'servercert.pem')).returns('defaultcert'); } describe('server', () => { beforeEach(() => { sandbox.stub(http, 'createServer').returns(mockServer); sandbox.stub(https, 'createServer').returns(mockServer); }); afterEach(() => { sandbox.restore(); }); describe('unsecured server', () => { it('does not start by default', (done) => { server.start(app, { securedServer: { enabled: false } }); sinon.assert.notCalled(http.createServer); done(); }); it('creates an HTTP server on port 8080 with supplied application by default', (done) => { server.start(app, { unsecuredServer: { enabled: true }, securedServer: { enabled: false } }); sinon.assert.calledWith(http.createServer, sandbox.match(app)); sinon.assert.calledWith(mockServer.listen, sinon.match(8080)); done(); }); it('creates an HTTP server on specified port', (done) => { const port = 6969; server.start(app, { unsecuredServer: { enabled: true, port: port }, securedServer: { enabled: false } }); sinon.assert.calledWith(http.createServer, sandbox.match(app)); sinon.assert.calledWith(mockServer.listen, sandbox.match(port)); done(); }); }); describe('secured server', () => { it('creates an HTTPS server on port 4443 with supplied application and defaults', (done) => { const expectedOptions = { key: 'defaultkey', cert: 'defaultcert', passphrase: '' }; stubFsForDefaultCerts(); server.start(app); sinon.assert.calledWith(https.createServer, sandbox.match(expectedOptions), sandbox.match(app)); sinon.assert.calledWith(mockServer.listen, sinon.match(4443)); done(); }); it('does not start an HTTPS server when disabled', (done) => { server.start(app, { securedServer: { enabled: false } }); sinon.assert.notCalled(https.createServer); done(); }); it('creates an HTTPS server on the specified port', (done) => { stubFsForDefaultCerts(); server.start(app, { securedServer: { port: 6969 } }); sinon.assert.calledWith(https.createServer, sandbox.match(app)); sinon.assert.calledWith(mockServer.listen, sinon.match(6969)); done(); }); it('creates an HTTPS server with specified cert, key and passphrase', (done) => { const expectedOptions = { cert: fs.readFileSync(CERT_FIXTURE_PATH), key: fs.readFileSync(KEY_FIXTURE_PATH), passphrase: 'passphrase' }; server.start(app, { securedServer: { serverCertPath: CERT_FIXTURE_PATH, serverKeyPath: KEY_FIXTURE_PATH, passphrase: 'passphrase' } }); sinon.assert.calledWith(https.createServer, sandbox.match(expectedOptions), sandbox.match(app)); done(); }); // TODO: test loading root cas it('creates an HTTPS server with specified ca certs', (done) => { stubFsForDefaultCerts(); const expectedOptions = { ca: [ fs.readFileSync(path.join(CA_PATH, 'ca1.pem')), fs.readFileSync(path.join(CA_PATH, 'ca2.pem')) ] }; server.start(app, { securedServer: { caPath: CA_PATH } }); sinon.assert.calledWith(https.createServer, sandbox.match(expectedOptions), sandbox.match(app)); done(); }); it('should allow tlsServer options to be passed through', (done) => { const expectedOptions = { cert: 'tlscert', key: 'tlskey', passphrase: 'tlspassphrase', crl: 'tlscrl' }; server.start(app, { securedServer: { tlsOptions: { cert: 'tlscert', key: 'tlskey', passphrase: 'tlspassphrase', crl: 'tlscrl' } } }); sinon.assert.calledWith(https.createServer, sandbox.match(expectedOptions), sandbox.match(app)); done(); }); it('should override tlsServer options with simple cert options', (done) => { const expectedOptions = { ca: [ fs.readFileSync(path.join(CA_PATH, 'ca1.pem')), fs.readFileSync(path.join(CA_PATH, 'ca2.pem')) ], cert: fs.readFileSync(CERT_FIXTURE_PATH), key: fs.readFileSync(KEY_FIXTURE_PATH), passphrase: 'passphrase' }; server.start(app, { securedServer: { serverCertPath: CERT_FIXTURE_PATH, serverKeyPath: KEY_FIXTURE_PATH, passphrase: 'passphrase', caPath: CA_PATH, tlsOptions: { cert: 'tlscert', key: 'tlskey', passphrase: 'tlspassphrase', crl: 'tlscrl' } } }); sinon.assert.calledWith(https.createServer, sandbox.match(expectedOptions), sandbox.match(app)); done(); }); // TODO: tests around also starting a redirecting unsecured server // TODO: rename underlying module unsecured server? }); });
JavaScript
0
@@ -4560,32 +4560,50 @@ tlspassphrase',%0A + ca: 'ca',%0A crl: 'tl @@ -4782,32 +4782,54 @@ tlspassphrase',%0A + ca: 'ca',%0A crl: @@ -5723,35 +5723,30 @@ c -rl: 'tlscrl +a: 'ca '%0A
f877ac56a4c7becd3639a4fce6e01d972f84b273
make auto join check log current settings
server/discord/utils/collection/index.js
server/discord/utils/collection/index.js
const r = require('./../../../db'); const client = require('./../../'); const config = require('config'); function guildStats(guild) { // Guild stats! const bots = guild.members.filter(member => member.user.bot).length; const users = guild.memberCount - bots; const percentage = Math.floor((bots / guild.memberCount) * 100); const timestamp = Date.now(); const collection = percentage > config.get('collection').percentage && guild.memberCount > config.get('collection').users; // Owner! const owner = client.users.get(guild.ownerID); return { guildID: guild.id, ownerID: owner.id, owner: { id: guild.ownerID, avatar: owner.dynamicAvatarURL('webp', 2048), name: owner.username, discriminator: owner.discriminator, bot: owner.bot, createdAt: owner.createdAt, }, guild: { id: guild.id, name: guild.name, createdAt: guild.createdAt, icon: guild.iconURL, members: guild.memberCount, region: guild.region, users, bots, collection, }, timestamp }; } function banGuild(id, reason) { const guild = client.guilds.get(id); const stats = guildStats(guild); stats.reason = reason; r.table('collection') .insert(guildStats(guild)) .run(r.conn, (err) => { if (err) throw new Error('Couldn\'t save banned guild.'); console.log(`Banned ${client.guilds.get(id).name}`); guild.leave(); }); } function checkGuilds(bot) { bot.guilds.filter(guild => guildStats(guild).guild.collection).forEach(guild => banGuild(guild.id, { message: 'Bot collection guild', maxUsers: config.get('collection').users, maxPercentage: config.get('collection').percentage })); } client.on('guildCreate', (guild) => { const report = guildStats(guild); console.log(report); if (report.guild.collection) { console.log(`${guild.name} failed the authentication test`); banGuild(guild.id); } else { r.table('collection') .filter( r.row('guildID').eq(guild.id).or(r.row('ownerID').eq(guild.ownerID)) ) .run(r.conn, (err1, cursor) => { if (err1) throw new Error('Failed to search banned guild database.'); cursor.toArray((err2, result) => { if (err2) throw new Error('Failed to convert banned cursor to results.'); if (result.length < 1) { console.log(`${guild.name} passed the authentication test`); } else { console.log(`${guild.name} was already banned!`); banGuild(guild.id, { message: 'Already banned', refer: result.map(reason => reason.id) || [] }); } }); }); } }); exports.ban = banGuild; exports.check = checkGuilds;
JavaScript
0
@@ -391,32 +391,42 @@ e %3E config.get(' +discord'). collection').per @@ -411,34 +411,32 @@ ord').collection -') .percentage && g @@ -458,32 +458,42 @@ t %3E config.get(' +discord'). collection').use @@ -482,26 +482,24 @@ ).collection -') .users;%0A%0A%09// @@ -1558,32 +1558,42 @@ rs: config.get(' +discord'). collection').use @@ -1586,18 +1586,16 @@ llection -') .users,%0A @@ -1623,16 +1623,26 @@ ig.get(' +discord'). collecti @@ -1643,18 +1643,16 @@ llection -') .percent @@ -1855,16 +1855,16 @@ test%60);%0A - %09%09banGui @@ -1874,16 +1874,174 @@ guild.id +, %7B%0A%09%09%09message: 'Bot collection guild',%0A%09%09%09maxUsers: config.get('discord').collection.users,%0A%09%09%09maxPercentage: config.get('discord').collection.percentage%0A%09%09%7D );%0A%09%7D el
02e5c568c15034ee8f69c96372764703446e85a9
Fix stepPaths resolution
server/services/business-process-flow.js
server/services/business-process-flow.js
// Service that propagates business process flow changes 'use strict'; var aFrom = require('es5-ext/array/from') , ensureIterable = require('es5-ext/iterable/validate-object') , ensureCallable = require('es5-ext/object/valid-callable') , Set = require('es6-set') , ensureType = require('dbjs/valid-dbjs-type') , debug = require('debug-ext')('business-process-flow') , resolveStepPath = require('../../utils/resolve-processing-step-full-path') , setupTriggers = require('../_setup-triggers'); module.exports = function (BusinessProcessType, stepShortPaths/*, options*/) { var businessProcesses = ensureType(BusinessProcessType).instances .filterByKey('isFromEregistrations', true).filterByKey('isDemo', false); var options = Object(arguments[2]), customStepReturnHandler, onStepRedelegate, onStepStatus , onUserProcessingEnd; if (options.customStepReturnHandler != null) { customStepReturnHandler = ensureCallable(options.customStepReturnHandler); } if (options.onStepRedelegate != null) onStepRedelegate = ensureCallable(options.onStepRedelegate); if (options.onStepStatus != null) onStepStatus = ensureCallable(options.onStepStatus); if (options.onUserProcessingEnd != null) { onUserProcessingEnd = ensureCallable(options.onUserProcessingEnd); } var stepPaths = aFrom(ensureIterable(stepShortPaths)).map(resolveStepPath); // Business process: isSubmitted setupTriggers({ trigger: businessProcesses.filterByKey('isSubmittedReady', true) .filterByKey('isSubmitted', false) }, function (businessProcess) { debug('%s submitted', businessProcess.__id__); businessProcess.isSubmitted = true; }); var businessProcessesSubmitted = businessProcesses.filterByKey('isSubmitted', true); // Business process: sentBack finalization setupTriggers({ trigger: businessProcessesSubmitted.filterByKey('isSubmittedReady', true) .filterByKey('isSentBack', true) }, function (businessProcess) { debug('%s finalize sentBack', businessProcess.__id__); businessProcess.delete('isSentBack'); }); // Business process: isUserProcessing initialization setupTriggers({ trigger: businessProcessesSubmitted.filterByKey('isUserProcessingReady', true) .filterByKey('isUserProcessing', false) }, function (businessProcess) { debug('%s initialize user processing', businessProcess.__id__); businessProcess.submissionForms.delete('isAffidavitSigned'); businessProcess.isUserProcessing = true; }); // Business process: isUserProcessing finalization setupTriggers({ trigger: businessProcessesSubmitted.filterByKey('isSubmittedReady', true) .filterByKey('isUserProcessing', true) }, function (businessProcess) { debug('%s finalize user processing', businessProcess.__id__); if (onUserProcessingEnd) onUserProcessingEnd(businessProcess); businessProcess.delete('isUserProcessing'); }); // Processing steps: stepPaths.forEach(function (stepPath, index) { // status setupTriggers({ trigger: businessProcessesSubmitted.filterByKeyPath(stepPath + '/status', function (value) { return value && (value !== 'pending'); }) }, function (businessProcess) { var step = businessProcess.getBySKeyPath(stepPath); if (step.getOwnDescriptor('status').hasOwnProperty('_value_')) return; // Already shadowed debug('%s processing step (%s) status set to %s', businessProcess.__id__, step.shortPath, step.status); if (onStepStatus) onStepStatus(step); step.set('status', step.status); if (step.status === 'sentBack') { if (businessProcess.isSentBack) return; // Sent back initialization debug('%s sent back by %s step', businessProcess.__id__, step.shortPath); businessProcess.submissionForms.delete('isAffidavitSigned'); businessProcess.isSentBack = true; } else if (step.status === 'redelegated') { // Redelegation initialization debug('%s redelegated to %s from %s', businessProcess.__id__, step.redelegatedTo.shortPath, step.shortPath); if (onStepRedelegate) onStepRedelegate(step); step.redelegatedTo.delete('revisionOfficialStatus'); step.redelegatedTo.delete('officialStatus'); step.redelegatedTo.delete('status'); step.redelegatedTo.delete('isSatisfied'); } else if (step.status === 'rejected') { // Business process rejection debug('%s rejected at %s', businessProcess.__id__, step.shortPath); businessProcess.isRejected = true; } }); // isSatisfied setupTriggers({ trigger: businessProcessesSubmitted.filterByKeyPath(stepPath + '/isSatisfiedReady', true) .filterByKeyPath(stepPath + '/isSatisfied', false) }, function (businessProcess) { var step = businessProcess.getBySKeyPath(stepPath); debug('%s processing step (%s) satisfied', businessProcess.__id__, step.shortPath); step.isSatisfied = true; }); // Valid returns var returnStatuses = new Set(['sentBack', 'redelegated']); setupTriggers({ preTrigger: businessProcessesSubmitted .filterByKeyPath(stepPath + '/isPreviousStepsSatisfiedDeep', false), trigger: businessProcessesSubmitted .filterByKeyPath(stepPath + '/isPreviousStepsSatisfiedDeep', true) }, function (businessProcess) { var step = businessProcess.getBySKeyPath(stepPath); if (!step.isApplicable) return; if (!step.status || (step.status === 'pending')) return; if (customStepReturnHandler) customStepReturnHandler(step); if (step.statusComputed && (step.statusComputed !== 'pending') && !returnStatuses.has(step.status)) { return; } debug('%s processing step (%s) reset from %s to pending state', businessProcess.__id__, step.shortPath, step.status); step.delete('revisionOfficialStatus'); step.delete('officialStatus'); step.delete('status'); step.delete('isSatisfied'); }); }); };
JavaScript
0.000002
@@ -1375,31 +1375,103 @@ s)).map( -resolveStepPath +function (shortPath) %7B%0A%09%09return 'processingSteps/map/' + resolveStepPath(shortPath);%0A%09%7D );%0A%0A%09//
47a27fd5a27139b392d3050d5759097d1b9d91c9
Refactor card rest api response
server/src/api/v1/card/cardController.js
server/src/api/v1/card/cardController.js
'use strict'; const async = require ('async'); const models = require ('../../../models/index'); const config = require ('../../../config/config'); const log = require ('../../../libs/winston')(module); const cardItemModel = models.cardItemModel; const cardsModel = models.cardsModel; const cardModel = models.cardModel; const objectIdRegex = /^(?=[a-f\d]{24}$)(\d+[a-f]|[a-f]+\d)/i; let cardController = {}; cardController.getUserBoardCards = (req, res) => { if (!objectIdRegex.test(req.params.idBoard)) { return res.status(400).json({ data: { error: 'Please enter a valid board id' } }); } else { async.waterfall([ (callback) => { cardsModel.findOne({ userId: req.user._id, boardId: req.params.idBoard }, callback); }, (cards, callback) => { if (!cards) { callback('The board associated to that user does not exist'); } else { callback(null, cards); } } ], (error, cards) => { if (error) { return res.status(404).json({ data: { error } }); } return res.status(200).json({ data: cards.cards }); }); } } cardController.updateUserBoardCards = (req, res) => { if (!objectIdRegex.test(req.params.idBoard)) { return res.status(400).json({ data: { error: 'Please enter a valid board id' } }); } else { async.waterfall([ (callback) => { cardsModel.findOne({ userId: req.user._id, boardId: req.params.idBoard }, callback); }, (cards, callback) => { if (!cards) { callback('The board associated to that user does not exist'); } else { cards.cards = req.body.cards; cards.save(callback); } }, (cards, numRowAffected, callback) => { if (!cards) { callback('Error while saving the card'); } else { callback(null, cards); } } ], (error, cards) => { if (error) { return res.status(404).json({ data: { error } }); } return res.status(200).json({ data: cards.cards }); }); } } // TODO : test boardId is a valid existing board cardController.saveUserBoardCard = (req, res) => { if (!req.body.name) { return res.status(400).json({ data: { uiError: 'Please enter a card name' } }); } else { async.waterfall([ (callback) => { cardsModel.findOne({ userId: req.user._id, boardId: req.params.idBoard }, callback); }, (cards, callback) => { let card = new cardModel({ header: req.body.name }) if (cards) { cards.cards.push(card); cards.save(callback); } else { let cards = new cardsModel({ boardId: req.params.idBoard, userId: req.user._id, cards: card }); cards.save(callback); } }, (cards, numRowAffected, callback) => { if (!cards) { callback('Error while saving the card'); } else { callback(null, cards); } } ], (error, cards) => { if (error) { return res.status(400).json({ data: { error } }); } return res.status(200).json({ data: cards.cards }); }); } }; cardController.saveUserBoardCardItem = (req, res) => { if (!req.body.name) { return res.status(400).json({ data: { uiError: 'Please enter a card item name' } }); } else { async.waterfall([ (callback) => { cardsModel.findOne({ userId: req.user._id, boardId: req.params.idBoard }, callback); }, (cards, callback) => { if (cards === undefined) { callback('This user does not have any cards'); } else { let card = cards.cards.id(req.params.idCard); if (card === undefined) { callback('That card does not exist'); } else { let cardItem = new cardItemModel({ name: req.body.name }) card.cardItems.push(cardItem); cards.save(callback); } } }, (cards, numRowAffected, callback) => { if (!cards) { callback('Error while saving the card'); } else { callback(null, cards); } } ], (error, cards) => { if (error) { return res.status(400).json({ data: { error } }); } return res.status(200).json({ data: cards.cards }); }); } }; module.exports = cardController;
JavaScript
0
@@ -1044,33 +1044,33 @@ rn res.status(40 -4 +0 ).json(%7B%0A @@ -1425,32 +1425,162 @@ %7D%0A %7D);%0A + %7D else if (!req.body.cards) %7B%0A return res.status(400).json(%7B%0A data: %7B%0A error: 'Please add cards'%0A %7D%0A %7D);%0A %7D else %7B%0A a @@ -2217,17 +2217,17 @@ tatus(40 -4 +0 ).json(%7B
5a58c5ca2ee62ce13b20ce951f75485e9eb79bda
Rewrite tests for Tree constructor
test/spec/tree.spec.js
test/spec/tree.spec.js
describe ("Tree", function() { it("should return a tree object", function(){ var tree=new Tree() expect(tree).toBeDefined(); }); xit("should return tree with age 0 when created", function() { var tree=new Tree(); expect(tree.age).toEqual(0); }); xit("should have height 0 when created", function() { var tree=new Tree(); expect(tree.height).toEqual(0); }); xit("should have 0 oranges when created", function() { var tree=new Tree(); expect(tree.orangeCount).toEqual(0); }); describe("grow", function() { xit("should increase the age of the tree by 1 year", function() { var tree=new Tree(); tree.grow(); expect(tree.age).toEqual(1); }); xit("should increase the height of the tree by 10 inches", function() { var tree=new Tree(); tree.grow(); expect(tree.height).toEqual(10); }); xit("should add a random number of oranges if age = FRUIT_BEARING_AGE", function() { var tree=new Tree(); while (tree.age < FRUIT_BEARING_AGE) { tree.grow(); } expect(tree.orangeCount).toBeGreaterThan(0); }); xit("should have 0 oranges if age < FRUIT_BEARING_AGE", function() { var tree=new Tree(); while (tree.age < (FRUIT_BEARING_AGE-1)) { tree.grow(); } expect(tree.orangeCount).toEqual(0); }); }); describe ("die",function() { xit("should be alive when age <= MAX_AGE",function() { var tree=new Tree(); while (tree.age < (MAX_AGE-1)) { tree.grow(); } tree.grow(); expect(tree.isAlive).toEqual(true); }); xit("should die when age > MAX_AGE",function() { var tree=new Tree(); while (tree.age < MAX_AGE) { tree.grow(); } tree.grow(); expect(tree.isAlive).toEqual(false); }); }); describe("dropOrange", function() { xit("should return the orange that is removed from oranges", function() { var tree=new Tree(); while (tree.age< FRUIT_BEARING_AGE) { tree.grow(); } expect(tree.dropOrange()).toBeDefined(); }); }); describe ("pickOrange", function() { xit("should return a orange object", function() { expect(pickOrange()).toBeDefined(); }); xit("should return an orange with a random diameter > 0", function() { var orange = pickOrange(); expect(orange.diameter).toBeGreaterThan(0); }); }); });
JavaScript
0.000001
@@ -24,16 +24,19 @@ ion() %7B%0A +%0A it(%22sh @@ -40,24 +40,33 @@ %22should -return a +instantiate a new tree ob @@ -84,16 +84,20 @@ tion()%7B%0A + var @@ -92,33 +92,35 @@ var tree -= + = new Tree()%0A e @@ -113,21 +113,31 @@ w Tree() +; %0A +%0A expect(t @@ -156,25 +156,29 @@ ined();%0A + %7D);%0A +%0A -x + it(%22shou @@ -180,22 +180,33 @@ %22should -return +instantiate a new tree wi @@ -212,30 +212,21 @@ ith age -0 when created +=== 0 %22, funct @@ -225,32 +225,36 @@ %22, function() %7B%0A + var tree=new @@ -241,33 +241,35 @@ var tree -= + = new Tree();%0A @@ -260,32 +260,41 @@ new Tree();%0A +%0A expect(tree.age) @@ -302,33 +302,37 @@ toEqual(0);%0A + %7D);%0A +%0A -x + it(%22should h @@ -334,34 +334,48 @@ uld -have height 0 when created +instantiate a new tree with height === 0 %22, f @@ -378,32 +378,36 @@ %22, function() %7B%0A + var tree=new @@ -394,33 +394,35 @@ var tree -= + = new Tree();%0A @@ -413,32 +413,41 @@ new Tree();%0A +%0A expect(tree.heig @@ -466,17 +466,21 @@ 0);%0A + %7D);%0A +%0A -x + it(%22 @@ -490,35 +490,53 @@ uld -have 0 oranges when created +instantiate a new tree with orangeCount === 0 %22, f @@ -543,24 +543,28 @@ unction() %7B%0A + var tree @@ -555,33 +555,35 @@ var tree -= + = new Tree();%0A @@ -578,24 +578,33 @@ Tree();%0A +%0A expect(tree. @@ -628,24 +628,29 @@ ual(0);%0A + %7D);%0A +%0A + describe @@ -651,20 +651,23 @@ scribe(%22 +. grow +() %22, funct @@ -675,25 +675,28 @@ on() %7B%0A%0A -x + it(%22should i @@ -750,32 +750,38 @@ n() %7B%0A + + var tree =new Tree(); @@ -760,33 +760,35 @@ var tree -= + = new Tree();%0A @@ -781,32 +781,45 @@ w Tree();%0A +%0A tree.grow();%0A @@ -813,32 +813,45 @@ e.grow();%0A +%0A expect(tree.age) @@ -863,16 +863,20 @@ ual(1);%0A + %7D);%0A
8bd3a36c6a1bb63583b4ade50c8c3c3b44096e38
remove openDir when import from database
main-process.js
main-process.js
const ipcMain = require('electron').ipcMain; const dialog = require('electron').dialog; const async = require('async'); const path = require('path'); const nedb = require('nedb'), db = new nedb({filename: path.join(__dirname, 'live.db'), autoload: true, onload: (err) => {}}); const ajax = require('./ajax'); function initDB(localdb) { localdb.ensureIndex({fieldName: 'id', unique: true}, (err) => {}); } function loadIDs(localdb, cb) { localdb.find({}, {id: 1, subject: 1, _id: 0}, function(err, docs) { cb(err, docs); }); } function mergeDB(localdb, srcdb, cb) { srcdb.find({}, {_id:0}, function(err, docs) { if (err) cb(err); else { async.each(docs, function(eachdoc, callback) { localdb.update({id: eachdoc.id}, eachdoc, {upsert: true}, callback); }, cb); } }); } // AJAX (function() { initDB(db); ipcMain.on('loadList', function(event, arg) { loadIDs(db, function(err, ret) { if (err) event.sender.send('loadList-error', err); else event.sender.send('loadList-reply', ret); }); }); ipcMain.on('getZhihuLivesList', function(event, arg) { ajax.getUserLives(arg.userid, arg.z_c0, function (err, ret) { if (err) event.sender.send('getZhihuLivesList-error', err); else event.sender.send('getZhihuLivesList-reply', ret); }); }); ipcMain.on('getZhihuLivesData', function(event, arg) { async.each(arg.list, function (item, cb) { ajax.getLiveMessages(item.id, arg.z_c0, function (err, ret) { if (err) cb(err); else { // save in db db.update({id: item.id}, { id: item.id, status: item.status, subject: item.subject, speaker: item.speaker, description: item.description, message: ret }, { upsert: true }, cb); } }) }, function (err) { if (err) event.sender.send('getZhihuLivesData-error', err); else event.sender.send('getZhihuLivesData-reply'); }); }); ipcMain.on('deleteData', function(event, arg) { async.each(arg, function (liveid, cb) { db.remove({id: liveid}, {}, cb); }, function (err) { if (err) console.log(err); }); }) ipcMain.on('importDatabase', function(event) { dialog.showOpenDialog({ properties: ['openFile', 'openDirectory'] }, function (files) { if (files) { // only process files[0] var ndb = new nedb({filename: files[0], autoload: true, onload: function (err) { if (err) event.sender.send('importDatabase-error', err); }}); mergeDB(db, ndb, (err) => { if (err) event.sender.send('importDatabase-error', err); else event.sender.send('importDatabase-reply'); }); } }); }); ipcMain.on('getLiveDetail', function(event, args) { db.find({id: args}, {_id: 0}, function(err, docs) { if (err) event.sender.send('getLiveDetail-error', err); else event.sender.send('getLiveDetail-reply', docs[0]); }); }); })();
JavaScript
0.000001
@@ -2674,25 +2674,8 @@ ile' -, 'openDirectory' %5D%0A
2641e59cd0015c936f0a1c13cb9c5cb1a9174eaa
Modify bind port: 8080 -> 8000 (test.websocket.js)
test/test.websocket.js
test/test.websocket.js
var should = require('should') , ServerResponse = require('http').ServerResponse , WebSocket = require('ws') , WebSocketHandler = require('../lib/websocket'); describe('WebSocketHandler', function() { var handler, ws; beforeEach(function() { handler = new WebSocketHandler({}, { port: 8080 }); ws = new WebSocket('ws://localhost:8080'); }); afterEach(function() { handler.close(); handler = ws = undefined; }); it('should handle new connection', function(done) { handler.clients.should.be.lengthOf(0); ws.on('open', function() { ws.send('{ "command": "hello" }'); }); ws.on('message', function(data, flags) { var msg = JSON.parse(data); msg.should.have.property('command', 'hello'); msg.protocols.should.be.an.instanceOf(Array); msg.protocols.should.include('http://livereload.com/protocols/official-7'); handler.clients.should.be.lengthOf(1); done(); }); }); it('should notify to clients', function(done) { ws.on('open', function() { ws.send('{ "command": "hello" }'); }); ws.on('message', function(data, flags) { var msg = JSON.parse(data); if (msg.command == 'hello') { handler.send('/test.html', '{ "command": "reload", "path": "/test.html" }'); } else if (msg.command == 'reload') { msg.path.should.equal('/test.html') done(); } }); }); });
JavaScript
0
@@ -296,17 +296,17 @@ port: 80 -8 +0 0 %7D);%0A @@ -344,17 +344,17 @@ lhost:80 -8 +0 0');%0A %7D
852d2fd7a8bad7d329d49d2d9a70399e39691f0c
Test sending notification to an unregistered token
test/testUnregister.js
test/testUnregister.js
var mercurius = require('../index.js'); var request = require('supertest'); var assert = require('assert'); var nock = require('nock'); var crypto = require('crypto'); var urlBase64 = require('urlsafe-base64'); var testUtils = require('./testUtils.js'); var userCurve = crypto.createECDH('prime256v1'); var userPublicKey = userCurve.generateKeys(); var userPrivateKey = userCurve.getPrivateKey(); describe('mercurius unregister', function() { var token; before(function() { return mercurius.ready .then(() => testUtils.register(mercurius.app, 'machine_1', 'https://android.googleapis.com/gcm/send/someSubscriptionID', '')) .then(gotToken => token = gotToken); }); it('returns 404 if bad token provided', function(done) { request(mercurius.app) .post('/unregister') .send({ token: 'notexisting', machineId: 'machine of a not existing token', endpoint: 'endpoint', key: urlBase64.encode(userPublicKey), }) .expect(404, done); }); it('successfully unregisters users', function(done) { request(mercurius.app) .post('/unregister') .send({ token: token, }) .expect(200, done); }); it('replies with 404 when trying to unregister a non registered user', function(done) { request(mercurius.app) .post('/unregister') .send({ token: token, }) .expect(404, done); }); });
JavaScript
0
@@ -1381,13 +1381,223 @@ );%0A %7D); +%0A%0A it('replies with 404 on %60notify%60 after a registration has been removed', function(done) %7B%0A request(mercurius.app)%0A .post('/notify')%0A .send(%7B%0A token: token,%0A %7D)%0A .expect(404, done);%0A %7D); %0A%7D);%0A
1a6edc458b5ccba82d8988c599a0ba3d5a01b0f3
Enable another script injection test
chrome/test/data/extensions/api_test/executescript/removed_frames/test.js
chrome/test/data/extensions/api_test/executescript/removed_frames/test.js
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // A simple helper to keep track of how many responses are received, and fail // if it receives a "fail" message. It's unfortunate that these are never // cleaned up, but, realistically, doesn't matter. function ResponseCounter() { this.responsesReceived = 0; chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { if (request == 'fail') { chrome.test.fail(); } else { chrome.test.assertEq('complete', request); ++this.responsesReceived; } }.bind(this)); } var waitForCommittedAndRun = function(functionToRun, numCommits, url) { var committedCount = 0; var counter = new ResponseCounter(); // Every test gets a counter. var onCommitted = function(details) { if (++committedCount == numCommits) { functionToRun(counter, details.tabId); chrome.webNavigation.onCommitted.removeListener(onCommitted); } }; chrome.webNavigation.onCommitted.addListener(onCommitted); chrome.tabs.create({url: url}); }; chrome.test.getConfig(function(config) { var url = 'http://a.com:' + config.testServer.port + '/extensions/api_test/executescript/removed_frames/outer.html'; // Regression tests for crbug.com/500574. chrome.test.runTests([ function() { waitForCommittedAndRun(injectAndDeleteIframeFromMainFrame, 2, url); } // This is another great test to have, but currently it crashes in blink. // TODO(devlin): Fix the crash in blink and enable this! // function() { // waitForCommittedAndRun(injectAndDeleteIframeFromIframe, 2, url); // } ]); }); function injectAndDeleteIframeFromMainFrame(counter, tabId) { // Inject code into each frame. If it's the parent frame, it removes the child // frame from the DOM (invalidating it). The child frame's code shouldn't // finish executing, since it's been removed. var injectFrameCode = [ 'if (window === window.top) {', ' iframe = document.getElementsByTagName("iframe")[0];', ' iframe.parentElement.removeChild(iframe);', ' chrome.runtime.sendMessage("complete");', '}' ].join('\n'); chrome.tabs.executeScript( tabId, {code: injectFrameCode, allFrames: true, runAt: 'document_idle'}, function() { chrome.test.assertEq(1, counter.responsesReceived); chrome.test.succeed(); }); }; function injectAndDeleteIframeFromIframe(counter, tabId) { // Inject code into each frame. Have the child frame remove itself, deleting // the frame while it's still executing. var injectFrameCode = [ 'if (window.self !== window.top) {', ' var iframe = window.top.document.getElementsByTagName("iframe")[0];', ' if (!iframe || iframe.contentWindow !== window)', ' chrome.runtime.sendMessage("fail");', ' else', ' window.top.document.body.removeChild(iframe);', '} else {', ' chrome.runtime.sendMessage("complete");', '}' ].join('\n'); // We also use two "executeScript" calls here so that we have a pending script // execution on a frame that gets deleted. chrome.tabs.executeScript( tabId, {code: injectFrameCode, allFrames: true, runAt: 'document_idle'}); chrome.tabs.executeScript( tabId, {code: injectFrameCode, allFrames: true, runAt: 'document_idle'}, function() { // Script execution, all other things equal, should happen in the order it // was received, so we only need a check in the second callback. chrome.test.assertEq(2, counter.responsesReceived); chrome.test.succeed(); }); }
JavaScript
0
@@ -1490,154 +1490,13 @@ %7D +, %0A - // This is another great test to have, but currently it crashes in blink.%0A // TODO(devlin): Fix the crash in blink and enable this!%0A // fun @@ -1508,19 +1508,16 @@ () %7B%0A - // waitF @@ -1579,19 +1579,16 @@ rl);%0A - // %7D%0A %5D);
580a00a3679713a6c548b38ab37507536e183669
remove console
static/index.js
static/index.js
seajs.use(['$', 'placeholder', 'sticky', 'word-color', 'autocomplete'], function($, Placeholder, Sticky, wordColor, Autocomplete) { Sticky.stick('#document-wrapper', 0); var modules = []; var urls = [ 'http://spmjs.org/repository/arale/?define', 'http://spmjs.org/repository/gallery/?define', 'http://spmjs.org/repository/jquery/?define' ]; seajs.use(urls, function(arale, gallery, jquery) { $('.modules-utility').empty(); modules = modules.concat(arale); modules = modules.concat(gallery); modules = modules.concat(jquery); insertModules(arale); insertModules(gallery); insertModules(jquery); color('.module'); }); seajs.use('http://yuan.alipay.im/repository/alipay/?define', function(alipay) { if (alipay) { modules = modules.concat(alipay); insertModules(alipay); color('.module'); } }); function insertModules(data) { if ($('#module-wrapper').length === 0) { return; } data = data.sort(function(a, b) { return a.name[0] > b.name[0]; }); for (var i = 0; i < data.length; i++) { var item = $('<div class="module">\ <a class="module-name" target="_blank" href="#"></a>\ <span class="module-version"></span>\ <p class="module-description"></p>\ </div>'); var pkg = data[i]; var family = pkg.family || pkg.root; item.find(".module-name").html(pkg.name) .attr('href', '/' + pkg.name + '/') .attr('title', pkg.name); item.find(".module-version").html(pkg.version); item.find(".module-description").html(pkg.description) .attr('title', pkg.description); if (family === 'gallery' || family === 'jquery') { item.find(".module-name").attr('href', pkg.homepage); $('.modules-' + family).append(item).prev().show(); } else if (family === 'arale') { if (pkg.keywords) { $('.modules-' + pkg.keywords[0]).append(item).prev().show(); } else { $('.modules-widget').append(item).prev().show(); } } else if (family === 'alipay') { var url = [ 'http://arale.alipay.im', (pkg.family || pkg.root), pkg.name ].join('/') + '/'; item.find(".module-name").attr('href', url); $('.modules-alipay').append(item).prev().show(); } } } function color(items) { items = $(items); items.each(function(index, item) { item = $(item); item.css('border-left-color', toRgba(wordColor(item.find('.module-name').html()), 0.65)); }); } function toRgba(rgb, opacity) { if (!$.support.opacity) { return rgb; } return rgb.replace('rgb', 'rgba').replace(')', ',' + opacity + ')'); } var ac = new Autocomplete({ trigger: '#search', selectFirst: true, template: '<div class="{{classPrefix}}">\ <ul class="{{classPrefix}}-ctn" data-role="items">\ {{#each items}}\ <li data-role="item" class="{{../classPrefix}}-item" data-value="{{matchKey}}">\ <div>{{highlightItem ../classPrefix matchKey}}</div>\ <div class="ui-autocomplete-desc">{{desc}}</div>\ </li>\ {{/each}}\ </ul>\ </div>', dataSource: function() { this.trigger('data', modules); }, filter: function(data, query) { var result = []; query = query.toLowerCase(); $.each(data, function(index, value) { value.description = (value.description || '').toLowerCase(); value.family = value.family.toLowerCase(); value.name = value.name.toLowerCase(); var FamilyAndName = value.family + '.' + value.name; var item = { matchKey: FamilyAndName, desc: value.description, url: value.homepage, score: 0 //匹配度 }; if (FamilyAndName.indexOf(query) > -1) { item.score += 1; } if (value.description.indexOf(query) > -1) { item.score += 0.1; } if (value.family.indexOf(query) > -1) { item.score += 5; } if (value.family.indexOf(query) === 0 && query.length > 1) { item.score += 10; } if (value.name.indexOf(query) > -1) { item.score += 5; } if (value.name.indexOf(query) === 0 && query.length > 1) { item.score += 100; item.score -= value.name.length; // shorter would be better } if (item.score > 0) { result.push(item); } }); console.log(result); result = result.sort(function(a, b) { return b.score - a.score; }); console.log(result); return result; } }).render(); ac.on('itemSelect', function(item) { ac.get('trigger').val('正转到 ' + item.matchKey).attr('disabled', 'disabled'); var value = item.matchKey.split('.'); if (value[0] === 'arale') { location.href = '/' + value[1]; } else if (value[0] === 'alipay') { location.href = 'http://arale.alipay.im/alipay/' + value[1]; } else { location.href = item.url; } }); });
JavaScript
0.000002
@@ -4736,36 +4736,8 @@ );%0A%0A - console.log(result);%0A%0A @@ -4825,42 +4825,8 @@ );%0A%0A - console.log(result);%0A %0A
1c372f7892199b84f128662fd71dc5795ec64348
Remove extra debug lines in item test
test/tests/itemTest.js
test/tests/itemTest.js
describe("Zotero.Item", function() { describe("#getField()", function () { it("should return false for valid unset fields on unsaved items", function* () { var item = new Zotero.Item('book'); assert.equal(item.getField('rights'), false); }); it("should return false for valid unset fields on unsaved items after setting on another field", function* () { var item = new Zotero.Item('book'); item.setField('title', 'foo'); assert.equal(item.getField('rights'), false); }); it("should return false for invalid unset fields on unsaved items after setting on another field", function* () { var item = new Zotero.Item('book'); item.setField('title', 'foo'); assert.equal(item.getField('invalid'), false); }); }); describe("#parentID", function () { it("should create a child note", function () { return Zotero.DB.executeTransaction(function* () { var item = new Zotero.Item('book'); var parentItemID = yield item.save(); item = new Zotero.Item('note'); item.parentID = parentItemID; var childItemID = yield item.save(); item = yield Zotero.Items.getAsync(childItemID); Zotero.debug('=-=-='); Zotero.debug(item.parentID); assert.ok(item.parentID); assert.equal(item.parentID, parentItemID); }.bind(this)); }); }); });
JavaScript
0
@@ -1146,68 +1146,8 @@ D);%0A -%09%09%09%09Zotero.debug('=-=-=');%0A%09%09%09%09Zotero.debug(item.parentID);%0A %09%09%09%09
c0df6bc5f0959ae08aae1d723db115c51069fea9
Fix test
test/tick-converter.js
test/tick-converter.js
"use strict"; const tickConverter = require("../src/tick-converter"); describe("tick-converter", function () { it("is a function", () => { assert("function" === typeof tickConverter); }); [{ label: "No elapsed time", tick: 0, sequence: [1000], expectedStep: 0, expectedRemaining: 1000 }, { label: "Elapsed in first step", tick: 123, sequence: [1000], expectedStep: 0, expectedRemaining: 877 }, { label: "First step fully elapsed", tick: 1000, sequence: [1000], expectedStep: 1, expectedRemaining: 0 }].forEach(test => { let {label, tick, sequence, expectedStep, expectedRemaining} = test; it(`gives remaining time from sequence: ${label}`, () => { let result = tickConverter(tick, sequence); assert(result.step === expectedStep); assert(result.remaining = expectedRemaining); }); }); });
JavaScript
0.000004
@@ -832,22 +832,33 @@ let -result +%7Bstep, remaining%7D = tickC @@ -902,23 +902,16 @@ assert( -result. step === @@ -949,15 +949,8 @@ ert( -result. rema @@ -956,16 +956,18 @@ aining = +== expecte
a49379d216b33595525e796bddccfb4aed209a2b
Fix eslint
test/trailpack.test.js
test/trailpack.test.js
'use strict' const assert = require('assert') const _ = require('lodash') const WebServerTrailpack = require('../') const Trailpack = require('trailpack') describe('Web Server Trailpack', () => { let pack before(() => { pack = global.app.packs.webservertest }) it('should load', () => { assert(pack) }) it('should be an instance of Trailpack', () => { assert(pack instanceof Trailpack) }) it('should be an instance of WebServerTrailpack', () => { assert(pack instanceof WebServerTrailpack) }) describe('#getCriteriaFromQuery', () => { it('should extract criteria from the query object', () => { const query = { foo: 'bar', populate: 'foo', limit: 100, offset: 0 } const criteria = pack.getCriteriaFromQuery(query) assert.equal(criteria.foo, 'bar') assert(!criteria.populate) assert(!criteria.limit) assert(!criteria.offset) }) it('should parse criteria from the query object', () => { const query = { foo: 'bar', boolTrue: 'true', boolFalse: 'false', nullOk: 'null', numberOk: '10', numberDecimalOk: '10.50' } const criteria = pack.getCriteriaFromQuery(query) assert.equal(criteria.foo, 'bar') assert.equal(criteria.boolTrue, true) assert.equal(criteria.boolFalse, false) assert.equal(criteria.nullOk, null) assert.equal(criteria.numberOk, 10) assert.equal(criteria.numberDecimalOk, 10.50) }) }) describe('#getOptionsFromQuery', () => { it('should extract non-criteria options from the query object', () => { const query = { foo: 'bar', populate: 'foo', limit: 100, offset: 0 } const options = pack.getOptionsFromQuery(query) assert(!options.foo) assert.equal(options.populate, 'foo') assert.equal(options.limit, 100) assert.equal(options.offset, 0) }) it('should leave a query with no options untouched', () => { const query = { foo: 'bar' } const options = pack.getOptionsFromQuery(query) assert.equal(query.foo, 'bar') assert(_.isEmpty(options)) }) it('should parse non-criteria options from the query object', () => { const query = { foo: 'bar', populate: 'foo', limit: "100", offset: "0" } const options = pack.getOptionsFromQuery(query) assert(!options.foo) assert.equal(options.populate, 'foo') assert.equal(options.limit, 100) assert.equal(options.offset, 0) }) }) })
JavaScript
0.999541
@@ -2377,13 +2377,13 @@ it: -%22100%22 +'100' ,%0A @@ -2400,11 +2400,11 @@ et: -%220%22 +'0' %0A
2e0f3de72c9781491ed572ad84b80776b07c9843
add missing util require
test/transformation.js
test/transformation.js
var transform = require("../lib/6to5/transform"); var sourceMap = require("source-map"); var helper = require("./_helper"); var assert = require("assert"); var chai = require("chai"); var _ = require("lodash"); var run = function (task) { var actual = task.actual; var expect = task.expect; var opts = task.options; var exec = task.exec; var getOpts = function (filename) { return _.merge({ whtiespace: true, filename: filename }, opts); }; var execCode = exec.code; var result; if (execCode) { result = transform(execCode, getOpts(exec.filename)); execCode = result.code; require("../polyfill"); try { var fn = new Function("assert", execCode); fn(assert); } catch (err) { err.message += util.codeFrame(execCode); throw err; } } else { var actualCode = actual.code; var expectCode = expect.code; result = transform(actualCode, getOpts(actual.filename)); actualCode = result.code; chai.expect(actualCode).to.be.equal(expectCode, actual.loc + " !== " + expect.loc); } if (task.sourceMap) { chai.expect(result.map).to.deep.equal(task.sourceMap); } if (task.sourceMappings) { var consumer = new sourceMap.SourceMapConsumer(result.map); _.each(task.sourceMappings, function (mapping, i) { var expect = mapping.original; var actual = consumer.originalPositionFor(mapping.generated); chai.expect({ line: actual.line, column: actual.column }).to.deep.equal(expect); }); } }; _.each(helper.get("transformation"), function (testSuite) { suite("transformation/" + testSuite.title, function () { _.each(testSuite.tests, function (task) { test(task.title, function () { var runTask = function () { run(task); }; var throwMsg = task.options.throws; if (throwMsg) { // internal api doesn't have this option but it's best not to pollute // the options object with useless options delete task.options.throws; assert.throws(runTask, new RegExp(throwMsg)); } else { runTask(); } }); }); }); });
JavaScript
0.000002
@@ -184,24 +184,69 @@ re(%22chai%22);%0A +var util = require(%22../lib/6to5/util%22);%0A var _
17f04695e0548e093533d8b498d2b741bdc9daeb
Add user helpers to test service
test/twitterService.js
test/twitterService.js
'use strict'; class TwitterService { // House Keeping of our connection/server constructor() { this.server = undefined; } start(done) { require('../server').then((server) => { this.server = server; done(); }).catch(done); } clearDB() { this.server.db.dropDatabase(); } stop() { this.server.db.close(); } // Sample API getAPISample() { return this.server.hapiSever.inject('/api/sample'); } // Sample Static page getStaticSample() { return this.server.hapiSever.inject('/'); } } module.exports = TwitterService;
JavaScript
0.000001
@@ -8,16 +8,61 @@ rict';%0A%0A +const User = require('../app/models/user');%0A%0A class Tw @@ -588,16 +588,709 @@ /');%0A %7D +%0A%0A // User API%0A getAPIUsers() %7B%0A return this.server.hapiServer.inject('/api/users');%0A %7D%0A%0A getAPIUser(id) %7B%0A return this.server.hapiSever.inject(%60/api/users/$%7Bid%7D%60);%0A %7D%0A%0A createAPIUser(user) %7B%0A return this.server.hapiSever.inject(%7B url: '/api/users', method: 'POST', payload: user %7D);%0A %7D%0A%0A deleteAPIUser(id) %7B%0A return this.server.hapiSever.inject(%7B url: '/api/users/$%7Bid%7D', method: 'DELETE' %7D);%0A %7D%0A%0A // User DB%0A getDBUsers() %7B%0A return User.find(%7B%7D);%0A %7D%0A%0A getDBUser(id) %7B%0A return User.findOne(%7B _id: id %7D);%0A %7D%0A%0A createDBUser(user) %7B%0A const newUser = new User(user);%0A return newUser.save();%0A %7D%0A%0A deleteDBUser(id) %7B%0A return User.remove(%7B _id: id %7D);%0A %7D %0A%7D%0A%0Amodu
b6b03af002043a6b3d813d84315dde2365a5732e
Update search.js
store/search.js
store/search.js
/** * Methods for search functionality * */ const async = require('async'); const db = require('./db'); /** * @param db - database object * @param search - object for where parameter of query * @param cb - callback */ function findPlayer(search, cb) { db.first(['account_id', 'personaname', 'avatarfull']).from('players').where(search).asCallback(cb); } function search(options, cb) { const query = options.q; async.parallel({ account_id(callback) { if (Number.isNaN(Number(query))) { return callback(); } return findPlayer({ account_id: Number(query), }, callback); }, personaname(callback) { db.raw(` SELECT * FROM (SELECT account_id, avatarfull, personaname, last_match_time, similarity(personaname, ?) AS similarity FROM players WHERE personaname % ? AND similarity(personaname, ?) >= ? ORDER BY last_match_time DESC LIMIT 150) search ORDER BY similarity DESC, last_match_time DESC NULLS LAST; `, [query, query, query, options.similarity || 0.51]).asCallback((err, result) => { if (err) { return callback(err); } return callback(err, result.rows); }); }, }, (err, result) => { if (err) { return cb(err); } let ret = []; Object.keys(result).forEach((key) => { if (result[key]) { ret = ret.concat(result[key]); } }); return cb(null, ret); }); } module.exports = search;
JavaScript
0.000001
@@ -902,46 +902,8 @@ = ?%0A - ORDER BY last_match_time DESC%0A @@ -912,17 +912,17 @@ LIMIT -1 +2 50) sear @@ -923,17 +923,16 @@ ) search - %0A
c9df22ea4e5934e01c12ec8903ae9b0df6fe25c1
Remove image.
share/spice/chuck_norris/chuck_norris.js
share/spice/chuck_norris/chuck_norris.js
function ddg_spice_chuck_norris(api_result) { if (api_result.type !== 'success') return; Spice.render({ data : api_result.value, source_url : 'http://www.icndb.com', source_name : 'Internet Chuck Norris Database', image : 'https://upload.wikimedia.org/wikipedia/commons/thumb/9/93/ChuckNorris200611292256.jpg/48px-ChuckNorris200611292256.jpg', template_normal : 'chuck_norris', force_no_icon : true }); }
JavaScript
0
@@ -267,157 +267,8 @@ e',%0A - image : 'https://upload.wikimedia.org/wikipedia/commons/thumb/9/93/ChuckNorris200611292256.jpg/48px-ChuckNorris200611292256.jpg',%0A
01d5e5149b23565ab91ee7b7c8ca3719eb5aea69
Fix isPlainObject
src/utils.js
src/utils.js
'use strict'; const cuid = require('cuid'); const { createHash } = require('crypto'); module.exports = { toPlainOrEmptyObject: (obj) => typeof obj === 'object' && !Array.isArray(obj) ? obj : {}, nullIfEmpty: (o) => o && (Object.keys(o).length > 0 ? o : null), isPlainObject: (obj) => typeof obj === 'object' && !Array.isArray(obj), normalizeQuery: (query) => // foreach key, get the last element if it's an array Object.keys(query).reduce((q, param) => { q[param] = [].concat(query[param]).pop(); return q; }, {}), normalizeMultiValueQuery: (query) => // foreach key, ensure that the value is an array Object.keys(query).reduce((q, param) => { q[param] = [].concat(query[param]); return q; }, {}), capitalizeKeys: (o) => { const capitalized = {}; for (const key in o) { capitalized[key.replace(/((?:^|-)[a-z])/g, (x) => x.toUpperCase())] = o[key]; } return capitalized; }, // Detect the toString encoding from the request headers content-type // enhance if further content types need to be non utf8 encoded. detectEncoding: (request) => typeof request.headers['content-type'] === 'string' && request.headers['content-type'].includes('multipart/form-data') ? 'binary' : 'utf8', createDefaultApiKey() { return createHash('md5').digest('hex'); }, createUniqueId() { return cuid(); }, };
JavaScript
0.003597
@@ -290,16 +290,20 @@ (obj) =%3E +%0A typeof @@ -341,16 +341,31 @@ ray(obj) + && obj != null ,%0A%0A nor
f996fef098eb561869c5e78488ada080be551577
Handle unopened file descriptor 3
src/utils.js
src/utils.js
import fs from "fs"; import repeat from "lodash.repeat"; import memoize from "lodash.memoize"; import types from "./types"; class TextStream { constructor(input) { this.input = input; this.length = input.length; this.char = 0; this.consumed = null; } consume(regex) { // Will return even when the regex is empty (empty string match) let result = regex.exec(this.input.slice(this.char)); if (result && result.index === 0) { this.consumed = result[0]; this.char += this.consumed.length; return true; } return false; } consumeWhitespace() { return this.consume(/^\s+/); } consumeShebang() { return this.consume(/(^#!.*\n)|(^#!.*$)/); } consumeLineComment() { return this.consume(/^\/\/[^\n]*/); } consumeBlockComment() { return this.consume(/^\/\*[\W\S]*?\*\//); } atEnd() { return this.char >= this.length; } } export const isGreyspace = memoize(function (string) { let stream = new TextStream(string); while (!stream.atEnd()) { let consumed = stream.consumeWhitespace() || stream.consumeLineComment() || stream.consumeBlockComment() || stream.consumeShebang(); if (!consumed) return false; } return stream.atEnd(); }); export const parseGreyspace = memoize(function (string) { let parsedNodes = []; let stream = new TextStream(string); while (!stream.atEnd()) { if (stream.consumeWhitespace()) { parsedNodes.push({ type: "whitespace", value: stream.consumed }); } else if (stream.consumeLineComment()) { parsedNodes.push({ type: "lineComment", value: stream.consumed }); } else if (stream.consumeBlockComment()) { parsedNodes.push({ type: "blockComment", value: stream.consumed }); } else if (stream.consumeShebang()) { parsedNodes.push({ type: "shebang", value: stream.consumed }); } else { return false; } } return parsedNodes; }); export const nestingLevelType = memoize(function (type) { const typeObj = { type }; if (types.isExpression(typeObj) || types.isPattern(typeObj) || types.isSingleItem(typeObj)) return "_expression_"; if (types.isExpressionLike(typeObj)) return `_expression_like_${type}`; return type; }); export const getIndentString = memoize(function (indentLevel) { return repeat(" ", indentLevel * 4); }); export const isWhitespace = function (string) { return /^\s*$/.test(string); }; export const isSingleLineWhitespace = function (string) { return /^[^\S\n]*\n?$/.test(string); }; export let shouldWrite = true; export function log(...messages) { if (!shouldWrite) return; let data = messages.join(" ") + "\n"; try { fs.writeSync(3, data); } catch (error) { shouldWrite = false; if (error.code === "EBADF") { return; } else { throw error; } } } let prettyTime; let lastTime = process.hrtime(); export function timeLogStart(event) { lastTime = process.hrtime(); if (event) { timeLog(event); } } const LOG_TIMING = process.env.LOG_TIMING; if (LOG_TIMING) { try { if (require.resolve("pretty-hrtime")) { prettyTime = require("pretty-hrtime"); } } catch (e) { console.error("Attempted to log timing events, but pretty-hrtime was not installed."); } } export function timeLog(event) { let diff = process.hrtime(lastTime); if (LOG_TIMING && prettyTime) { if (lastTime !== null) { console.error(prettyTime(diff) + ":", event); } lastTime = process.hrtime(); } }
JavaScript
0.000042
@@ -3031,16 +3031,41 @@ %22EBADF%22 + %7C%7C error.code == %22ENXIO%22 ) %7B%0A
ea729df83823a204c7d4bdabd8cb97af2e54fdad
switch from Spice.render to Spice.add
share/spice/mass_on_time/mass_on_time.js
share/spice/mass_on_time/mass_on_time.js
function ddg_spice_mass_on_time (api_result) { if (api_result.error) return; var details = api_result['query-details']; // Check the URL if we passed in the "current" word. // This says if we should check for relevancy or not. var script = $('[src*="/js/spice/mass_on_time/"]')[0]; var source = $(script).attr("src"); var generate_header = function (query_details) { var type; //Convert the query type to plural and capitalize if (query_details.type == "mass") { type = "Masses"; } else if (query_details.type == "parish") { type = "Parishes"; } else if (query_details.type == "any") { type = "Services"; } else { type = query_details.type.charAt(0).toUpperCase() + query_details.type.slice(1) + "s"; } return type; }; //Parishes return different info than events, so a different template is in order for those var pick_item_template = function (query_details) { if (query_details.type == "parish") { return Spice.mass_on_time.parish; } else { return Spice.mass_on_time.events; } }; //Return if service couldn't find the address given if (details.location.lat == 0 && details.location.lng == 0) return; //Filter results with no address var results = []; for(var i = api_result.results.length - 1; i >= 0; i--) { var result = api_result.results[i]; // Check if it's the current location. If it is, don't check the relevancy. if (result.address !== null && result.address !== "" && (/current$/.test(source) || DDG.stringsRelevant(details.address, result.formateaddress))) { results.unshift(result); } } if (results.length < 1) return; Spice.render({ id: 'mass', data: results, name: "Parishes", meta: { itemType: generate_header(details), sourceName: "Mass On Time", sourceUrl: 'http://massontime.com/nearest/' + details.type + "/25?lat=" + details.location.lat + "&lng=" + details.location.lng }, normalize: function(item) { return { title: item.churchname, url: item.webaddress }; }, templates: { group: 'base', options: { content: pick_item_template(details) }, detail: false } }); } /* ### Handlebars Helpers ### */ //Event types are returns as integers. This converts them to their string reps. Handlebars.registerHelper( "MassOnTime_format_eventtypeid", function (eventtypeid) { var event_type_name = { 1 : "Adoration", 2 : "Confession", 3 : "Devotion", 5 : "Holy Day Mass", 6 : "Holy Day Mass (Vigil)", 7 : "Weekday Mass", 8 : "Weekend Mass" }; return event_type_name[eventtypeid] || "Service"; }); Handlebars.registerHelper( "MassOnTime_backup_link", function (webaddress, parish_id) { return "http://massontime.com/parish/" + parish_id; }); Handlebars.registerHelper( "MassOnTime_format_parish_address", function (address, city, province) { if (address && city && province) { return address + ", " + city + ", " + province; } else if (address && city) { return address + ", " + city; } else if (address) { return address; } else { return ""; } });
JavaScript
0
@@ -1665,14 +1665,11 @@ ice. -render +add (%7B%0A%09
e454c110a52b55ac7ab0fb583e3560da42b7481f
active verbs
spec/data-table-spec.js
spec/data-table-spec.js
describe('dc.dataTable', function() { var id, chart, data; var dateFixture; var dimension, group; var countryDimension; beforeEach(function() { dateFixture = loadDateFixture(); data = crossfilter(dateFixture); dimension = data.dimension(function(d) { return d3.time.day(d.dd); }); countryDimension = data.dimension(function(d) { return d.countrycode; }); id = "data-table"; appendChartID(id); chart = dc.dataTable("#" + id) .dimension(dimension) .group(function(d) { return "Data Table"; }) .transitionDuration(0) .size(3) .sortBy(function(d){return d.id;}) .order(d3.descending) .columns( [function(d) { return d.id; }, function(d) { return d.status; }] ); chart.render(); }); describe('creation', function() { it('should generate something', function() { expect(chart).not.toBeNull(); }); it('should be registered', function() { expect(dc.hasChart(chart)).toBeTruthy(); }); it('size should be set', function() { expect(chart.size()).toEqual(3); }); it('sortBy should be set', function() { expect(chart.sortBy()).not.toBeNull(); }); it('order should be set', function() { expect(chart.order()).toBe(d3.descending); }); it('should have column span set on group tr', function() { expect(chart.selectAll("tr.dc-table-group td")[0][0].getAttribute("colspan")).toEqual("2"); }); it('should have id column created', function() { expect(chart.selectAll("td._0")[0][0].innerHTML).toEqual('9'); expect(chart.selectAll("td._0")[0][1].innerHTML).toEqual('8'); expect(chart.selectAll("td._0")[0][2].innerHTML).toEqual('3'); }); it('should have status column created', function() { expect(chart.selectAll("td._1")[0][0].innerHTML).toEqual("T"); expect(chart.selectAll("td._1")[0][1].innerHTML).toEqual("F"); expect(chart.selectAll("td._1")[0][2].innerHTML).toEqual("T"); }); }); describe('external filter', function() { beforeEach(function() { countryDimension.filter("CA"); chart.redraw(); }); it('should only render filtered data set', function() { expect(chart.selectAll("td._0")[0].length).toEqual(2); }); it('should render the correctly filtered records', function() { expect(chart.selectAll("td._0")[0][0].innerHTML).toEqual('7'); expect(chart.selectAll("td._0")[0][1].innerHTML).toEqual('5'); }); }); describe('renderlet', function() { var derlet; beforeEach(function() { derlet = jasmine.createSpy('renderlet', function(chart) { chart.selectAll("td.dc-table-label").text("changed"); }); derlet.and.callThrough(); chart.renderlet(derlet); }); it('custom renderlet should be invoked with render', function() { chart.render(); expect(chart.selectAll("td.dc-table-label").text()).toEqual("changed"); expect(derlet).toHaveBeenCalled(); }); it('custom renderlet should be invoked with redraw', function() { chart.redraw(); expect(chart.selectAll("td.dc-table-label").text()).toEqual("changed"); expect(derlet).toHaveBeenCalled(); }); }); afterEach(function() { dimension.filterAll(); countryDimension.filterAll(); }); });
JavaScript
0.000032
@@ -1068,23 +1068,16 @@ it(' -should generate som @@ -1072,16 +1072,17 @@ generate +s somethi @@ -1169,26 +1169,16 @@ it(' -should be register ed', @@ -1173,18 +1173,17 @@ register -ed +s ', funct @@ -1272,25 +1272,16 @@ t('s -ize should be set +ets size ', f @@ -1366,27 +1366,18 @@ t('s +ets s ortBy - should be set ', f @@ -1467,27 +1467,18 @@ it(' +sets order - should be set ', f @@ -1569,26 +1569,19 @@ it('s -hould have +ets column @@ -1744,27 +1744,23 @@ it(' -should have +creates id colu @@ -1757,32 +1757,24 @@ es id column - created ', function( @@ -2030,19 +2030,15 @@ it(' -should have +creates sta @@ -2051,16 +2051,8 @@ lumn - created ', f @@ -2485,26 +2485,20 @@ it(' -should only render +s only fil @@ -2622,21 +2622,15 @@ it(' -should render +s the
6c086d41b64a01e622b57b5e20845f82846f14f0
Add check for java that gives a good error message.
bin.js
bin.js
#!/usr/bin/env node /* * Copyright 2016 Malte Ubl. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var argv = require('minimist')(process.argv.slice(2)); var splittable = require('./index'); var fs = require('fs'); var USAGE = 'Usage: splittable [options] path/to/module1.js path/to/module2.js\n\n' + 'Options:\n' + ' --write-to Directory to which the output bundles are written.'; var modules = argv._; if (argv['h'] || argv['help']) { console.log(USAGE); process.exit(0); } if (argv['v'] || argv['version']) { console.log(require('./package.json').version); process.exit(0); } if (!modules.length) { console.log(USAGE); process.exit(1); } // Bundle using splittable. splittable({ modules: modules, writeTo: argv['write-to'], }).then(function(info) { if (info.warnings) { console.warn(info.warnings); console.log('Compilation successful with warnings.'); } else { console.log('Compilation successful.'); } }, function(reason) { console.error('Compilation failed: ', reason.message); process.exit(1); });
JavaScript
0
@@ -1115,24 +1115,415 @@ exit(0);%0A%7D%0A%0A +var javaCheck = require('child_process').spawnSync('java', %5B'-version'%5D);%0Aif (javaCheck.error) %7B%0A console.log('Splittable currently requires java to be installed and the ' +%0A 'command %60java%60 to work.%5Cn' +%0A 'Please install it for now and follow ' +%0A 'https://github.com/cramforce/splittable/issues/26 for when java ' +%0A 'becomes no longer needed.')%0A process.exit(1);%0A%7D%0A%0A if (!modules
09f0f40ed124c8d86044819a717d0970f57f1ed1
Fix admin api URL
_js/admin/weight-app.js
_js/admin/weight-app.js
export { WeightApp } function getMiddayOfDate(date) { var middayOnDate = new Date(date); middayOnDate.setHours(12); middayOnDate.setMinutes(0); middayOnDate.setSeconds(0); middayOnDate.setMilliseconds(0); return middayOnDate; } function cleanWeightResult(weight) { if(weight) { return weight.toFixed(1); } else { return '-'; } } class WeightClient { constructor(token) { this.token = token; } fetchHistory() { return fetch(ENV.apiBaseUrl + '/health/weight/log') .then(response => { if(response.ok) { return response.json(); } else { throw Error('unable to load data: ' + response.statusText); } }) .then(results => { results.sort((b,a) => a.date.localeCompare(b.date)); return results.filter(e => e.weightAm || e.weightPm); }); } updateDay(req) { let date = req.date; let period = req.period; let weight = req.weight; let url = `${ENV.apiBaseUrl}/health/weight/log/${date}/${period}`; let payload = { weight: weight }; let authHeaderValue = 'Bearer ' + this.token; let headers = new Headers({ 'Content-Type': 'application/json', 'Authorization': authHeaderValue }); let init = { credentials: 'include', method: 'PUT', headers: headers, mode: 'cors', body: JSON.stringify(payload) } return fetch(url, init) .then(response => { if(response.ok) { return response.json(); } else { throw Error('unable submit data: ' + response.statusText); } }); } } class WeightApp { constructor(token) { this.token = token; this.client = new WeightClient(token); } setupFormInputs() { var now = new Date(); var middayToday = getMiddayOfDate(now); document.getElementById('entry-date').value = now.toISOString().substring(0,10); if(now < middayToday) { document.getElementById("entry-period").value = "AM"; } else { document.getElementById("entry-period").value = "PM"; } function getCookie(name) { match = document.cookie.match(new RegExp(name + '=([^;]+)')); if (match) return match[1]; }; } setupFormEvents() { let weightForm = document.getElementById('weight-form'); weightForm.addEventListener('submit', e => { e.preventDefault(); let date = weightForm['entry-date'].value; let period = weightForm['entry-period'].value; let weight = weightForm['entry-value'].value; this.client.updateDay({ date: date, period: period, weight: weight }).then(result => { console.log(result); document.getElementById('result-date').textContent = result.localDate; document.getElementById('result-period').textContent = result.entryPeriod; document.getElementById('result-value').textContent = result.weight; let resultsElement = document.getElementById('results'); resultsElement.classList.remove('error'); resultsElement.classList.add('success'); }).catch(error => { document.getElementById('result-error').textContent = error.message; let resultsElement = document.getElementById('results'); resultsElement.classList.remove('success'); resultsElement.classList.add('error'); }).then(() => { this.loadWeightHistory(); }); }); } loadWeightHistory() { document.getElementById('weight-history-table-body').innerHTML = ''; this.client.fetchHistory() .then(results => { let resultsText = results.reduce((a, r) => { return a + ` <tr> <td>${r.date}</td> <td>${cleanWeightResult(r.weightAm)}</td> <td>${cleanWeightResult(r.weightPm)}</td> </tr> ` }, ''); document.getElementById('weight-history-table-body').innerHTML = resultsText; }); } run() { this.setupFormInputs(); this.setupFormEvents(); this.loadWeightHistory(); } }
JavaScript
0.000001
@@ -473,16 +473,22 @@ .apiBase +Health Url + '/ @@ -993,16 +993,22 @@ .apiBase +Health Url%7D/hea
3b8d1780b324bbc3c19812acba44e354530af4d7
Fix mac-only enter key regression
front_end/ui/ActionRegistry.js
front_end/ui/ActionRegistry.js
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import {Action} from './Action.js'; import {Context} from './Context.js'; // eslint-disable-line no-unused-vars /** * @unrestricted */ export class ActionRegistry { constructor() { /** @type {!Map.<string, !Action>} */ this._actionsById = new Map(); this._registerActions(); } _registerActions() { self.runtime.extensions('action').forEach(registerExtension, this); /** * @param {!Root.Runtime.Extension} extension * @this {ActionRegistry} */ function registerExtension(extension) { const actionId = extension.descriptor()['actionId']; console.assert(actionId); console.assert(!this._actionsById.get(actionId)); const action = new Action(extension); if (!action.category() || action.title()) { this._actionsById.set(actionId, action); } else { console.error(`Category actions require a title for command menu: ${actionId}`); } } } /** * @return {!Array.<!Action>} */ availableActions() { return this.applicableActions([...this._actionsById.keys()], self.UI.context); } /** * @return {!Array.<!Action>} */ actions() { return [...this._actionsById.values()]; } /** * @param {!Array.<string>} actionIds * @param {!Context} context * @return {!Array.<!Action>} */ applicableActions(actionIds, context) { const extensions = []; actionIds.forEach(function(actionId) { const action = this._actionsById.get(actionId); if (action) { extensions.push(action.extension()); } }, this); return [...context.applicableExtensions(extensions)].map(extensionToAction.bind(this)); /** * @param {!Root.Runtime.Extension} extension * @return {!Action} * @this {ActionRegistry} */ function extensionToAction(extension) { return ( /** @type {!Action} */ (this.action(extension.descriptor()['actionId']))); } } /** * @param {string} actionId * @return {?Action} */ action(actionId) { return this._actionsById.get(actionId) || null; } }
JavaScript
0.000557
@@ -1092,24 +1092,107 @@ %60);%0A %7D%0A + if (!extension.canInstantiate()) %7B%0A action.setEnabled(false);%0A %7D%0A %7D%0A %7D%0A%0A @@ -1749,16 +1749,36 @@ (action + && action.enabled() ) %7B%0A
06535708691f02ba4b8c739f50b32cf0a76eba98
add prod url
frontend/config/environment.js
frontend/config/environment.js
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'frontend', 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; ENV.APP.API_HOST = 'http://localhost:8000'; } 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.000001
@@ -1092,16 +1092,115 @@ ion') %7B%0A + ENV.baseURL = '/grocerylist/';%0A ENV.APP.API_HOST = 'http://internetfett.pythonanywhere.com'; %0A %7D%0A%0A
4acbec33eca0289a5a17d656d09d1e6179aeeb9e
add chosen congrat to logging
bot.js
bot.js
'use strict' require('dotenv').config() var createMonitor = require('micro-monitor'); var procMetrics = require('numbat-process'); var Emitter = require('numbat-emitter'); var bole = require('bole'); var Twit = require('twit'); var congrats = require('./congrats'); const ellipsize = require('ellipsize'); var settings = require('./settings'); Array.prototype.pick = function() { return this[Math.floor(Math.random()*this.length)]; }; createMonitor(settings.monitor_port); var logger = bole('bot'); bole.output({ level: 'info', stream: process.stdout }); var T = new Twit({ access_token_secret: settings.access_token_secret, access_token: settings.access_token, consumer_secret: settings.consumer_secret, consumer_key: settings.consumer_key }); var stream = T.stream('user'); var myFirstPublishSearch = {q: "#myfirstpublish", count: 10, result_type: "recent"}; var metrics = new Emitter({ app: settings.name, uri: settings.metrics }); Emitter.setGlobalEmitter(metrics); procMetrics(metrics, 1000 * 30); stream.on('tweet', function (message) { const screenName = message.user.screen_name; const congrat = congrats.pick(); if (message.in_reply_to_screen_name === 'myfirstpublish') { const status = ellipsize(`@${screenName} ${congrat}`, 140); T.post('statuses/update', { status: status }, function(err, data, response) { if (err) { logger.error(`failed congratulating @${screenName}`) logger.error(err); } else { logger.info(`sent congrats to @${screenName}`); } process.emit('metric', { name: 'post', success: Boolean(err) }); }) } })
JavaScript
0
@@ -1405,22 +1405,32 @@ led -congratulating +to send %22$%7Bcongrat%7D%22 to @$%7B @@ -1517,24 +1517,28 @@ o(%60sent +%22$%7B congrat -s +%7D%22 to @$%7Bs
2a780f2132c867a996e78c1c0f1e9ef92d4a86fa
Add support for new @mention command syntax
bot.js
bot.js
/* Require modules */ var nodeTelegramBot = require('node-telegram-bot') , config = require('./config.json') , request = require("request") , cheerio = require("cheerio"); /* Functions */ /** * Uses the request module to return the body of a web page * @param {string} url * @param {callback} callback * @return {string} */ function getWebContent(url, callback){ request({ uri: url, }, function(error, response, body) { callback(body); }); } /* Logic */ var recipeURL = 'http://www.cookstr.com/searches/surprise'; var bot = new nodeTelegramBot({ token: config.token }) .on('message', function (message) { /* Process "/random" command */ if (message.text == "/dinner") { console.log(message); getWebContent(recipeURL, function(data){ // Parse DOM and recipe informations var $ = cheerio.load(data) , recipeName = $("meta[property='og:title']").attr('content') , recipeURL = $("meta[property='og:url']").attr('content'); // Send bot reply bot.sendMessage({ chat_id: message.chat.id, text: 'What about "' + recipeName + '"? ' + recipeURL }); }); } }) .start();
JavaScript
0
@@ -661,14 +661,14 @@ s %22/ -random +dinner %22 co @@ -707,16 +707,58 @@ /dinner%22 + %7C%7C message.text == %22/dinner@WhatToEatBot%22 ) %7B%0A
ea5c8c45463757f9ad50be55353489b0711f792f
fix option name: "nextBtnHtml" to "closeBtnHtml"
abigimage.jquery.min.js
abigimage.jquery.min.js
(function(c){c.fn.abigimage=function(r){var f=c.extend(true,c.fn.abigimage.defaults,r);this.overlay=c("<div>").attr(f.overlayAttrs).css(f.overlayCSS).appendTo("body"),this.layout=c("<div>").attr(f.layoutAttrs).css(f.layoutCSS).appendTo("body"),this.wrapper=c("<div>").attr(f.wrapperAttrs).css(f.wrapperCSS).appendTo(this.layout),this.box=c("<div>").attr(f.boxAttrs).css(f.boxCSS).appendTo(this.wrapper),this.prevBtn=c("<div>").attr(f.prevBtnAttrs).css(f.prevBtnCSS).appendTo(this.box).html(f.prevBtnHtml),this.body=c("<div>").attr(f.bodyAttrs).css(f.bodyCSS).appendTo(this.box),this.closeBtn=c("<div>").attr(f.closeBtnAttrs).css(f.closeBtnCSS).appendTo(this.box).html(f.nextBtnHtml),this.top=c("<div>").attr(f.topAttrs).css(f.topCSS).appendTo(this.body),this.img=c("<img>").attr(f.imgAttrs).css(f.imgCSS).appendTo(this.body),this.imgNext=c("<img>").attr(f.imgNextAttrs).css(f.imgNextCSS).appendTo(this.body),this.imgPrev=c("<img>").attr(f.imgPrevAttrs).css(f.imgPrevCSS).appendTo(this.body),this.bottom=c("<div>").attr(f.bottomAttrs).css(f.bottomCSS).appendTo(this.body);var q=this,m=0,j=null;function n(){var i=j+1;if(i===q.length){i=0}return i}function g(){var i=j-1;if(i===-1){i=q.length-1}return i}function l(){if(m===q.length-1){return p()}else{++m;return k(n())}}function h(){if(m===1-q.length){return p()}else{--m;return k(g())}}function o(i){if(f.keyNext.indexOf(i.which)!==-1){i.preventDefault();l()}else{if(f.keyPrev.indexOf(i.which)!==-1){i.preventDefault();h()}else{if(f.keyClose.indexOf(i.which)!==-1){i.preventDefault();p()}}}}function p(){m=0;q.overlay.fadeOut(f.fadeOut);q.layout.fadeOut(f.fadeOut);c(document).unbind("keydown",o);return false}function k(i){if(i<0||i>q.length-1){return}j=i;q.img.attr("src",c(q[j]).attr("href"));q.imgNext.attr("src",c(q[n()]).attr("href"));q.imgPrev.attr("src",c(q[g()]).attr("href"));q.overlay.fadeIn(f.fadeIn);q.layout.fadeIn(f.fadeIn);q.layout.css({top:c(document).scrollTop()+"px",height:c(window).height()+"px"});c(document).unbind("keydown",o).bind("keydown",o);f.onopen.call(q,q[j]);return false}this.img.click(function(){return l()});this.prevBtn.click(function(){return h()});this.closeBtn.click(function(){return p()});this.closeBtn.hover(function(){c(this).css(f.closeBtnHoverCSS)},function(){c(this).css(f.closeBtnCSS)});this.prevBtn.hover(function(){c(this).css(f.prevBtnHoverCSS)},function(){c(this).css(f.prevBtnCSS)});return this.each(function(s){c(this).click(function(){return k(s)})})};var b={color:"#808080",display:"table-cell",verticalAlign:"middle",textAlign:"center",fontSize:"2em",fontWeight:"bold",cursor:"pointer",padding:".75em"},a={color:"#c0c0c0"},e={position:"absolute",top:"-10000px",width:"100px"},d={color:"#c0c0c0"};c.fn.abigimage.defaults={fadeIn:"normal",fadeOut:"fast",prevBtnHtml:"◄",nextBtnHtml:"✖",keyNext:[13,32,39,40],keyPrev:[8,37,38],keyClose:[27,35,36],onopen:function(){},overlayCSS:{backgroundColor:"#404040",opacity:0.95,zIndex:2,position:"fixed",left:0,top:0,width:"100%",height:"100%",display:"none"},layoutCSS:{zIndex:2,position:"absolute",top:0,left:0,width:"100%",margin:"0 auto",display:"none","-webkit-user-select":"none","-moz-user-select":"none","user-select":"none"},wrapperCSS:{display:"table",width:"100%",height:"100%"},boxCSS:{display:"table-row"},bodyCSS:{display:"table-cell",verticalAlign:"middle",textAlign:"center",width:"1%"},prevBtnCSS:b,prevBtnHoverCSS:a,closeBtnCSS:b,closeBtnHoverCSS:a,imgCSS:{maxWidth:"800px",cursor:"pointer",display:"block",margin:"1ex 0"},imgNextCSS:e,imgPrevCSS:e,topCSS:d,bottomCSS:d,overlayAttrs:{},layoutAttrs:{},wrapperAttrs:{},boxAttrs:{},bodyAttrs:{},prevBtnAttrs:{},closeBtnAttrs:{},imgAttrs:{},imgNextAttrs:{},imgPrevAttrs:{},topAttrs:{},bottomAttrs:{}}}(jQuery));
JavaScript
0.997724
@@ -663,20 +663,21 @@ .html(f. -next +close BtnHtml) @@ -2772,12 +2772,13 @@ %22%E2%97%84%22, -next +close BtnH @@ -3713,8 +3713,9 @@ Query)); +%0A
639c111e8825b6278b11662da54485e7d18065fd
FIX error with 2 bodies in answer
bot.js
bot.js
var config = require ('./config.js'), xmpp = require('node-xmpp'), fs = require('fs'), cl = new xmpp.Client({jid: config.jid, password: config.password}); var plugins = {}; fs.readdirSync("./plugins").forEach(function(file) { var p = require("./plugins/" + file); for (var name in p) { if (p[name].enabled != 1) { continue; } plugins[name.toLowerCase()] = p[name]; if (p[name].aliases) { for (var i in p[name].aliases) { plugins[p[name].aliases[i].toLowerCase()] = p[name]; } } } }); cl.on('online', function() { console.log("Connected successfully"); cl.send(new xmpp.Element('presence', {}). c('show').t('online').up(). c('status').t('Happily echoing your <message/> stanzas') ); }); cl.on('stanza', function(stanza) { if (stanza.is('message') && stanza.attrs.type !== 'error') { // Important: never reply to errors! var message = stanza.getChildText('body'); if (!message) { return; } console.log('Message from ' + stanza.attrs.from + ': ' + message); var params = message.split(' '); var command = params.shift().toLowerCase(); console.log('Command ' + command); if (typeof plugins[command] == 'object' && plugins[command].max_access) { var jid = new xmpp.JID(stanza.attrs.from); if (config.adminJID.indexOf(jid.user + '@' + jid.domain) == -1) { console.log('Access denied for user ' + jid.user + '@' + jid.domain); return; } } if (typeof plugins[command] != 'object') { // check for admin commands if (typeof plugins['unknown'] == 'object') { console.log('Unknown command'); command = 'unknown'; } else { console.log('can not process this message'); return; } } if (typeof plugins[command].run != 'function') { console.log('Bad format of plugin ' + command); return; } // Swap addresses... stanza.attrs.to = stanza.attrs.from; delete stanza.attrs.from; var body = null; try { body = plugins[command].run(params, stanza, plugins, cl); } catch (e) { console.log(e); body = 'There is an error. Try again later'; } if (body) { stanza.c('body').t(body); // and send back. cl.send(stanza); } } }); cl.on('error', function(e) { console.error(e); });
JavaScript
0
@@ -2254,16 +2254,47 @@ rs.from; +%0A stanza.remove('body'); %0A%0A
a68a1ddfdb888b03ce3fa2403da6acfc71100844
Use js instead of php script for extracing csv data
export-csv.js
export-csv.js
/** * A small plugin for getting the CSV of a categorized chart */ (function (Highcharts) { var each = Highcharts.each; Highcharts.Chart.prototype.getCSV = function () { var columns = [], line, tempLine, csv = "", row, col, maxRows, options = (this.options.exporting || {}).csv || {}, // Options dateFormat = options.dateFormat || '%Y-%m-%d %H:%M:%S', itemDelimiter = options.itemDelimiter || ',', // use ';' for direct import to Excel lineDelimiter = options.lineDelimiter || '\n'; each (this.series, function (series) { if (series.options.includeInCSVExport !== false) { if (series.xAxis) { var xData = series.xData.slice(), xTitle = 'X values'; if (series.xAxis.isDatetimeAxis) { xData = Highcharts.map(xData, function (x) { return Highcharts.dateFormat(dateFormat, x) }); xTitle = 'DateTime'; } else if (series.xAxis.categories) { xData = Highcharts.map(xData, function (x) { return Highcharts.pick(series.xAxis.categories[x], x); }); xTitle = 'Category'; } columns.push(xData); columns[columns.length - 1].unshift(xTitle); } columns.push(series.yData.slice()); columns[columns.length - 1].unshift(series.name); } }); // Transform the columns to CSV maxRows = Math.max.apply(this, Highcharts.map(columns, function (col) { return col.length; })); for (row = 0; row < maxRows; row++) { line = []; for (col = 0; col < columns.length; col++) { line.push(columns[col][row]); } csv += line.join(itemDelimiter) + lineDelimiter; } return csv; }; // Now we want to add "Download CSV" to the exporting menu. We post the CSV // to a simple PHP script that returns it with a content-type header as a // downloadable file. // The source code for the PHP script can be viewed at // https://raw.github.com/highslide-software/highcharts.com/master/studies/csv-export/csv.php if (Highcharts.getOptions().exporting) { Highcharts.getOptions().exporting.buttons.contextButton.menuItems.push({ text: Highcharts.getOptions().lang.downloadCSV || "Download CSV", onclick: function () { Highcharts.post('http://www.highcharts.com/studies/csv-export/csv.php', { csv: this.getCSV() }); } }); } }(Highcharts));
JavaScript
0.000616
@@ -636,13 +636,68 @@ %7C%7C -'%5Cn'; +%22%250A%22; // '%5Cn' isn't working with the js csv data extraction %0A%0A @@ -2555,16 +2555,240 @@ csv.php%0A + // Instead of the php script on server side we get the csv info on client side%0A // original code from %0A // http://stackoverflow.com/questions/17836273/export-javascript-data-to-csv-file-without-server-interaction%0A if ( @@ -3015,32 +3015,40 @@ ction () %7B%0A +%09%09%09var a Highc @@ -3044,140 +3044,255 @@ - Highcharts.post('http://www.highcharts.com/studies/csv-export/csv.php', %7B%0A csv: this.getCSV()%0A %7D += document.createElement('a');%0A %09%09%09a.href = 'data:attachment/csv,' + this.getCSV();%0A %09%09%09a.target = '_blank';%0A %09%09%09a.download = this.title.text + '.csv';%0A %09%09%09document.body.appendChild(a);%0A %09%09%09a.click();%0A %09%09%09a.remove( );%0A