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
a487939efae93507dfd5d95d7effa99acd952a9f
Fix field name
mac/resources/open_CNTL.js
mac/resources/open_CNTL.js
define(['mac/roman'], function(macintoshRoman) { 'use strict'; return function(resource) { var dv = new DataView(resource.data.buffer, resource.data.byteOffset, resource.data.byteLength); resource.dataObject = { rectangle: { top: dv.getInt16(0, false), left: dv.getInt16(2, false), bottom: dv.getInt16(4, false), right: dv.getInt16(6, false), }, initialSetting: dv.getUint16(8, false), visible: !!resource.data[10], closeBox: !!resource.data[11], maximumSetting: dv.getInt16(12, false), minimumSetting: dv.getInt16(14, false), cdefID: dv.getInt16(16, false), referenceConstant: dv.getInt32(18, false), text: macintoshRoman(resource.data, 23, resource.data[22]), }; }; });
JavaScript
0.000003
@@ -491,16 +491,12 @@ -closeBox +fill : !!
c2c721a971a04cc308a3c68432c259486f1cd6d0
modify variable name
mock/getData.js
mock/getData.js
import * as homeList from './home/list' import * as cityData from './city/city' const setpromise = data => { return new Promise((resolve, reject) => { resolve(data) }) } var homeListData = ()=>setpromise(homeList.data) var cityData = () => setpromise(cityData.searchdata) export {homeListData,cityData}
JavaScript
0.000037
@@ -50,20 +50,16 @@ as city -Data from '. @@ -250,20 +250,16 @@ ise(city -Data .searchd
e55405e2864cf63073ce1d96274a60702047ffef
Change Florence bar
src/main/web/js/main.js
src/main/web/js/main.js
( function($) { var intIntervalTime = 100; var newpage; var pageurl = window.location.href; setupFlorence(); renderPage(); var checkLocation = function() { if (pageurl != window.location.href) { pageurl = window.location.href; $(window.location).trigger("change", { newpage: getPageData() }); console.log("got here"); } } function getPageData(){ // var pageurl = window.location.href; pageurldata = pageurl.replace("#!", "data"); $.ajax({ url:pageurldata, // url:"http://localhost:7000/json/home.json", dataType: 'json', // Notice! JSONP <-- P (lowercase) crossDomain: true, // jsonpCallback: 'callback', // type: 'GET', success:function(data){ // do stuff with json (in this case an array) // console.log("Success"); console.log(data); if(data.level === 't1'){ console.log('t1 page'); t1(data); } if(data.level === 't2'){ console.log('t2 page'); t2(data); } }, error:function(){ console.log('Error'); } }); } function t1(data){ // var content; // $.each(data.sections, function() { // content += "<section><h1>" + this.name + "</h1><h2>" + this.items[0].name + "</h2>" + this.items[0].uri + "</section>"; // }); var editabledata; $('.slate--home--hero-banner .grid-wrap').prepend('<div class="florence-editarea-home"><a href="#" class="florence-editbtn">Edit</a><div class="florence-editform"><a href="#" class="florence-cancelbtn">Cancel</a><form onsubmit="return false;"><textarea id="json"></textarea><button class="florence-update" >Update</button></form></div></div>'); $('.florence-editbtn').click(function(){ $('.florence-editform').show(); }); $('.florence-cancelbtn').click(function(){ $('.florence-editform').hide(); }); $('.florence-update').click(function(){ updatePage(); }); $("#json").val(JSON.stringify(data, null, 3)); } function t2(data){ // var content; // $.each(data.sections, function() { // content += "<section><h1>" + this.name + "</h1><h2>" + this.items[0].name + "</h2>" + this.items[0].uri + "</section>"; // }); var editabledata; $('.panel .grid-wrap').prepend('<div class="florence-editarea-home"><a href="#" class="florence-editbtn">Edit</a><div class="florence-editform"><a href="#" class="florence-cancelbtn">Cancel</a><form onsubmit="return false;"><textarea id="json"></textarea><button class="florence-update" >Update</button></form></div></div>'); $('.florence-editbtn').click(function(){ $('.florence-editform').show(); }); $('.florence-cancelbtn').click(function(){ $('.florence-editform').hide(); }); $('.florence-update').click(function(){ updatePage(); }); $("#json").val(JSON.stringify(data)); } function renderPage(){ getPageData(); } function setupFlorence(){ $('head').prepend('<link href="http://localhost:8081/css/main.css" rel="stylesheet" type="text/css">'); var bodycontent = $('body').html(); var florence_bar = '<div class="florence-head">Florence v0.1</div>' + '<nav class="florence-nav">' + '<ul>' + '<li href="">Edit</li>' + '<ul>' + '<li>Save changes</li>' + '<li>Cancel changes</li>' + '</ul>' + '<li href="">Versions</li>' + '<li href="">Tasks</li>' + '<li href="">Site map</li>' + '</ul>' + '</nav>'; $('body').wrapInner('<div class="florence-content-wrap"></div>'); $('body').prepend(florence_bar); } function updatePage(url){ $.ajax({ url:"http://localhost:8081/data", type:"POST", data: JSON.stringify({ json:$('#json').val() }), contentType:"application/json; charset=utf-8", dataType:"text" }).done(function(){ console.log("Done!") }).fail(function(jqXHR, textStatus){ alert(textStatus); }) } setInterval(checkLocation, intIntervalTime); })(jQuery);
JavaScript
0
@@ -2988,16 +2988,45 @@ e_bar =%0A +%09%09%09'%3Cdiv class=%22florence%22%3E'%0A%09 %09%09%09'%3Cdiv @@ -3134,23 +3134,27 @@ '%3Cli +%3E%3Ca href=%22 +# %22%3EEdit%3C/ li%3E' @@ -3149,16 +3149,20 @@ %22%3EEdit%3C/ +a%3E%3C/ li%3E' +%0A%09 @@ -3189,16 +3189,28 @@ %09%09%09'%3Cli%3E +%3Ca href=%22#%22%3E Save cha @@ -3207,32 +3207,36 @@ %22%3ESave changes%3C/ +a%3E%3C/ li%3E' +%0A%09%09%09%09%09%09%09%09' @@ -3239,16 +3239,28 @@ %09%09%09'%3Cli%3E +%3Ca href=%22#%22%3E Cancel c @@ -3267,16 +3267,20 @@ hanges%3C/ +a%3E%3C/ li%3E' +%0A%09 @@ -3305,24 +3305,16 @@ %09%09%09%09'%3Cli - href=%22%22 %3EVersion @@ -3333,24 +3333,16 @@ %09%09%09%09'%3Cli - href=%22%22 %3ETasks%3C/ @@ -3362,16 +3362,8 @@ '%3Cli - href=%22%22 %3ESit @@ -3403,16 +3403,30 @@ '%3C/nav%3E' + +%0A%09%09%09'%3C/div%3E' ;%0A%09%09$('b
734bfc1fb7ef9202294bba5058ea7102dd103e74
Fix case: tostring to toString
mac/resources/open_VWSC.js
mac/resources/open_VWSC.js
define(function() { 'use strict'; return function(item) { return item.getBytes().then(function(bytes) { var dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); if (dv.getUint32(0, false) !== bytes.length) { return Promise.reject('length does not match data'); } var previousData = new Uint8Array(256 * 2); var dataObject = []; var pos = 4; while (pos < bytes.length) { var endPos = pos + dv.getUint16(pos); if (endPos === pos) break; pos += 2; while (pos < endPos) { var patchLength = bytes[pos] * 2, patchOffset = bytes[pos + 1] * 2; pos += 2; var patch = bytes.subarray(pos, pos + patchLength); pos += patchLength; dataObject.push({ offset: patchOffset, patch: [].map.call(patch, function(v) { return ('0' + v.tostring(16)).slice(-2); }).join(' '), }); } } item.setDataObject(dataObject); }); }; });
JavaScript
0.999999
@@ -908,17 +908,17 @@ ' + v.to -s +S tring(16
8d0ddf5e8940b5946f06a1f301cfad7103232afe
fix variable resource: add query parameter handlng
lib/api-client/resources/variable.js
lib/api-client/resources/variable.js
'use strict'; var AbstractClientResource = require('./../abstract-client-resource'); /** * Variable Resource * @class * @memberof CamSDK.client.resource * @augments CamSDK.client.AbstractClientResource */ var Variable = AbstractClientResource.extend(); /** * Path used by the resource to perform HTTP queries * @type {String} */ Variable.path = 'variable-instance'; /** * Get variable instances * * @param {Object} params * * @param {String} [params.variableName] Filter by variable instance name. * * @param {String} [params.variableNameLike] Filter by the variable instance name. * The parameter can include the wildcard % * to express like-strategy such as: * - starts with (%name) * - ends with (name%) * - contains (%name%). * * @param {String[]} [params.processInstanceIdIn] Only include variable instances which * belong to one of the passed and * comma-separated process instance ids. * * @param {String[]} [params.executionIdIn] Only include variable instances which * belong to one of the passed and * comma-separated execution ids. * * @param {String[]} [params.caseInstanceIdIn] Only include variable instances which * belong to one of the passed * case instance ids. * * @param {String[]} [params.caseExecutionIdIn] Only include variable instances which * belong to one of the passed * case execution ids. * * @param {String[]} [params.taskIdIn] Only include variable instances which * belong to one of the passed and * comma-separated task ids. * * @param {String[]} [params.activityInstanceIdIn] Only include variable instances which * belong to one of the passed and * comma-separated activity instance ids. * * @param {String} [params.variableValues] Only include variable instances that * have the certain values. Value filtering * expressions are comma-separated and are * structured as follows: * A valid parameter value has the form * key_operator_value. * key is the variable name, * operator is the comparison operator to * be used and value the variable value. * *Note*: Values are always treated as * String objects on server side. * Valid operator values are: * - eq - equal to * - neq - not equal to * - gt - greater than * - gteq - greater than or equal to * - lt - lower than * - lteq - lower than or equal to * key and value may not contain underscore * or comma characters. * * @param {String} [params.sortBy] Sort the results lexicographically by a * given criterion. Valid values are * variableName, variableType and * activityInstanceId. * Must be used in conjunction with the * sortOrder parameter. * * @param {String} [params.sortOrder] Sort the results in a given order. * Values may be asc for ascending order or * desc for descending order. * Must be used in conjunction with the * sortBy parameter. * * @param {String} [params.firstResult] Pagination of results. Specifies the * index of the first result to return. * * @param {String} [params.maxResults] Pagination of results. Specifies the * maximum number of results to return. * Will return less results if there are no * more results left. * * @param {String} [params.deserializeValues] Determines whether serializable variable * values (typically variables that store * custom Java objects) should be * deserialized on server side * (default true). * If set to true, a serializable variable * will be deserialized on server side and * transformed to JSON using * Jackson's POJO/bean property * introspection feature. * Note that this requires the Java classes * of the variable value to be on the * REST API's classpath. * If set to false, a serializable variable * will be returned in its serialized * format. * For example, a variable that is * serialized as XML will be returned as a * JSON string containing XML. * Note:While true is the default value for * reasons of backward compatibility, we * recommend setting this parameter to * false when developing web applications * that are independent of the Java process * applications deployed to the engine. * * @param {RequestCallback} done */ Variable.instances = function(data, done) { return this.http.post(this.path, { data: data, done: done }); }; module.exports = Variable;
JavaScript
0.000001
@@ -8552,21 +8552,280 @@ ion( -data, done) %7B +params, done) %7B%0A%0A var body = %7B%7D;%0A var query = %7B%7D;%0A var queryParams = %5B'firstResult', 'maxResults', 'deserializeValues'%5D;%0A%0A for (var p in params) %7B%0A if (queryParams.indexOf(p) %3E -1) %7B%0A query%5Bp%5D = params%5Bp%5D;%0A %7D%0A else %7B%0A body%5Bp%5D = params%5Bp%5D;%0A %7D%0A %7D%0A %0A r @@ -8868,20 +8868,38 @@ data: -data +body,%0A query: query ,%0A do
adccf6fef394bece02436cb0b786684125d1efc9
Fix spelling
lib/coffeeBreak.js
lib/coffeeBreak.js
var ProjectScanner = require('./projectScanner'), pkg = require('../package.json'); module.exports = function() { // "use strict"; var CoffeeBreak = function() { }; CoffeeBreak.prototype.runTests = function() { var projectScanner = new ProjectScanner(); projectScanner.scan(process.cwd(), function() { }); }; /** * Print CoffeeBreak status * * @method printStatus */ CoffeeBreak.prototype.printStatus = function() { var bean = ''; bean += ' ____ __ __ _ _ \n'; bean += ' .⎼⎼⎼⎼⎼⎼⎼. / ___|___ / _|/ _| ___| |__ _ __ ___ __ _| | __ \n'; bean += ' / // \\.⎼⎼⎼⎼⎼⎼. | | / _ \\| |_| |_ / _ \\ \'_ \\| \'__/ _ \\/ _` | |/ / \n'; bean += ' / || / // \\ | |__| (_) | _| _| __/ |_) | | | __/ (_| | < \n'; bean += '▕ || / || \\ \\____\\___/|_| |_| \\___|_.__/|_| \\___|\\__,_|_|\\_\\ \n'; bean += '▕ ||▕ || ▕ \n'; bean += '▕ ||▕ || ▕ Version: ' + pkg.version + ' \n'; bean += ' \\ ||▕ || ▕ Server status: down \n'; bean += ' \\ // \\ || / Tests: 100 \n'; bean += ' `⎻⎻⎻⎻⎻⎻´\\ // / \n'; bean += ' `⎻⎻⎻⎻⎻⎻⎻´ \n'; bean += '\n'; bean += '01000011·01101111·01100110·01100110·01100101·01100010·01110010·01100101·01100001·01101011\n'; bean += ' \n'; console.log(bean); }; return CoffeeBreak; }();
JavaScript
0.999999
@@ -517,24 +517,29 @@ __ __ + _ @@ -544,27 +544,24 @@ _ - %5Cn';%0A%09%09b @@ -616,16 +616,21 @@ / _%7C/ _%7C + ___ ___%7C %7C_ @@ -652,19 +652,16 @@ _%7C %7C __ - %5Cn';%0A%09%09b @@ -721,16 +721,22 @@ %7C %7C_ / _ + %5C%5C/ _ %5C%5C %5C'_ @@ -760,19 +760,16 @@ %60 %7C %7C/ / - %5Cn';%0A%09%09b @@ -830,16 +830,21 @@ _%7C __/ + __/ %7C_) %7C %7C @@ -860,19 +860,16 @@ _%7C %7C %3C - %5Cn';%0A%09%09 @@ -924,24 +924,30 @@ __/%7C_%7C %7C_%7C +%5C%5C___%7C %5C%5C___%7C_.__/%7C @@ -970,20 +970,16 @@ %7C_%7C%5C%5C_%5C%5C - %5Cn';%0A%09%09b
6483177be47b8e39add53823bc53f48541eecb80
add option to emit to all to socket
lib/bundles/socket/helpers/socket.js
lib/bundles/socket/helpers/socket.js
/** * Created by Awesome on 3/13/2016. */ // use strict 'use strict'; // require dependencies var helper = require ('helper'); // require local dependencies var config = require ('app/config'); /** * build socket helper class */ class socket extends helper { /** * construct socket helper class */ constructor () { // run super super (); // bind methods this.room = this.room.bind (this); this.user = this.user.bind (this); this.emit = this.emit.bind (this); this.alert = this.alert.bind (this); } /** * emits to room * * @param {String} name * @param {String} type * @param {*} data */ room (name, type, data) { // emit to socket this.eden.emit ('socket:room', { 'room' : name, 'type' : type, 'data' : data }, true); } /** * emits to user * * @param {user} User * @param {String} type * @param {*} data */ user (User, type, data) { // emit to socket this.eden.emit ('socket:user', { 'to' : (User ? User.get ('_id').toString () : true), 'type' : type, 'data' : data }, true); } /** * emit information * * @param type * @param data * @param User */ emit (type, data) { // emit to socket this.eden.emit ('socket:emit', { 'type' : type, 'data' : data }, true); } /** * create socketio alert * * @param {User} User * @param {String} message * @param {String} type */ alert (User, message, type, options) { // create alert object var alert = { 'type' : type, 'message' : message }; // set variables if (options) { alert.options = options; } // emit to redis this.user (User, 'alert', alert); } } /** * export socket helper * * @type {socket} */ module.exports = new socket ();
JavaScript
0
@@ -675,16 +675,17 @@ %7BString%7D + name%0D%0A @@ -698,32 +698,33 @@ @param %7BString%7D + type%0D%0A * @p @@ -724,32 +724,33 @@ * @param %7B*%7D + data%0D%0A @@ -737,32 +737,62 @@ %7B*%7D data%0D%0A + * @param %7BBoolean%7D all%0D%0A */%0D%0A roo @@ -802,32 +802,37 @@ name, type, data +, all ) %7B%0D%0A // @@ -974,36 +974,35 @@ ata%0D%0A %7D, -true +all );%0D%0A %7D%0D%0A%0D%0A @@ -1057,24 +1057,25 @@ m %7Buser%7D + User%0D%0A * @@ -1083,32 +1083,33 @@ @param %7BString%7D + type%0D%0A * @p @@ -1113,24 +1113,25 @@ @param %7B*%7D + data%0D%0A @@ -1126,24 +1126,54 @@ data%0D%0A + * @param %7BBoolean%7D all%0D%0A */%0D%0A @@ -1187,32 +1187,37 @@ User, type, data +, all ) %7B%0D%0A // @@ -1400,36 +1400,35 @@ ata%0D%0A %7D, -true +all );%0D%0A %7D%0D%0A%0D%0A @@ -1480,16 +1480,27 @@ @param + %7BString%7D type%0D%0A @@ -1511,16 +1511,27 @@ @param + %7B*%7D data%0D%0A @@ -1542,22 +1542,63 @@ @param + %7Buser%7D User%0D%0A + * @param %7BBoolean%7D all%0D%0A */%0D @@ -1618,16 +1618,21 @@ pe, data +, all ) %7B%0D%0A @@ -1760,20 +1760,19 @@ %7D, -true +all );%0D%0A
0ba3891e4a92f69d6ef7a2d2a8617d859b5075b1
Set default value for channel.is_private to false
lib/collections/ChannelCollection.js
lib/collections/ChannelCollection.js
"use strict"; const Constants = require("../Constants"); const Events = Constants.Events; const ChannelTypes = Constants.ChannelTypes; const Utils = require("../core/Utils"); const BaseCollection = require("./BaseCollection"); const Channel = require("../models/Channel"); const PermissionOverwrite = require("../models/PermissionOverwrite"); const IPermissions = require("../interfaces/IPermissions"); function convertOverwrites(channel) { const overwrites = channel.permission_overwrites || []; // note: @everyone overwrite does not exist by default // this will add one locally if (channel.guild_id) { const everyone = overwrites.find(o => o.id == channel.guild_id); if (!everyone) { overwrites.push({ id: channel.guild_id, type: "role", allow: IPermissions.NONE, deny: IPermissions.NONE }); } } return overwrites.map(o => new PermissionOverwrite(o)); } function createChannel(channel) { return new Channel({ id: channel.id, name: channel.name || "", topic: channel.topic || "", position: channel.position || 0, recipient_id: channel.is_private ? channel.recipient.id : null, type: channel.type || ChannelTypes.TEXT, guild_id: channel.guild_id, is_private: channel.is_private, permission_overwrites: convertOverwrites(channel), bitrate: channel.bitrate || Constants.BITRATE_DEFAULT, user_limit: channel.user_limit || 0 }); } function handleConnectionOpen(data) { this.clear(); data.guilds.forEach(guild => handleGuildCreate.call(this, guild)); data.private_channels.forEach(channel => { this.set(channel.id, createChannel(channel)); }); return true; } function handleCreateOrUpdateChannel(channel) { this.mergeOrSet(channel.id, createChannel(channel)); return true; } function handleChannelDelete(channel) { this.delete(channel.id); return true; } function handleGuildCreate(guild) { if (!guild || guild.unavailable) return true; guild.channels.forEach(channel => { channel.guild_id = guild.id; this.set(channel.id, createChannel(channel)); }); return true; } function handleGuildDelete(guild) { this.forEach((channel, id) => { if (channel.guild_id == guild.id) this.delete(id); }); return true; } class ChannelCollection extends BaseCollection { constructor(discordie, gateway) { super(); if (typeof gateway !== "function") throw new Error("Gateway parameter must be a function"); discordie.Dispatcher.on(Events.GATEWAY_DISPATCH, e => { if (e.socket != gateway()) return; Utils.bindGatewayEventHandlers(this, e, { READY: handleConnectionOpen, GUILD_CREATE: handleGuildCreate, GUILD_DELETE: handleGuildDelete, CHANNEL_CREATE: handleCreateOrUpdateChannel, CHANNEL_UPDATE: handleCreateOrUpdateChannel, CHANNEL_DELETE: handleChannelDelete }); }); this._discordie = discordie; Utils.privatify(this); } *getPrivateChannelIterator() { for (let channel of this.values()) { if (channel.is_private) yield channel; } } *getGuildChannelIterator() { for (let channel of this.values()) { if (!channel.is_private) yield channel; } } getPrivateChannel(channelId) { var channel = this.get(channelId); if (!channel) return null; return channel.is_private ? channel : null; } getGuildChannel(channelId) { var channel = this.get(channelId); if (!channel) return null; return !channel.is_private ? channel : null; } isPrivate(channelId) { const channel = this.get(channelId); if (channel) return channel.is_private; return null; } getChannelType(channelId) { const channel = this.get(channelId); if (channel) return channel.type; return null; } update(channel) { handleCreateOrUpdateChannel.call(this, channel); } updatePermissionOverwrite(channelId, overwrite) { const channel = this.get(channelId); if (!channel) return; const newOverwrites = channel.permission_overwrites .filter(o => o.id != overwrite.id && o.type != overwrite.type); newOverwrites.push(new PermissionOverwrite(overwrite)); this.set(channelId, channel.merge({ permission_overwrites: newOverwrites })); } } module.exports = ChannelCollection;
JavaScript
0.001731
@@ -1279,16 +1279,25 @@ _private + %7C%7C false ,%0A pe
140cf9e6c556fb9351960ae2afad30186858a6b3
Fix error message
lib/core/filter/util/moduleLoader.js
lib/core/filter/util/moduleLoader.js
const glob = require('glob'); const path = require('path'); const DEEP_EXT_JS = "/**/*.js"; class ModuleLoader { constructor(folder) { const files = glob.sync(path.resolve(path.join(folder, DEEP_EXT_JS))); this.modules = files.map(file => require(path.resolve(file))); } getModuleByName(name) { const findedModule = this.modules.find(oneModule => oneModule.name === name); if (findedModule) { return findedModule; } throw new Error("Misspelling of " + name + " or missing module " + name); } } module.exports = ModuleLoader;
JavaScript
0.000012
@@ -461,17 +461,16 @@ ling of - %22 + name
96a65a57d041490772af9c1615356cffd0b640b1
Use global constants
common/models/recall.js
common/models/recall.js
var request = require('request'); var log4js = require('log4js'); log4js.configure('server/log4js_configuration.json', {}); var logger = log4js.getLogger('recall'); module.exports = function(Recall) { //Implementation of Rest End Point for '/recalls' path, return Response with "response" JSON object with matadata and //an array of recall details given a brand or generic drug name Recall.getRecallDetails = function(q, typ, limit, skip, cb){ var fdaRecallURL = 'https://api.fda.gov/drug/enforcement.json?api_key=yiv5ZoikJg3kSSZ5edvsiqnJa9yvHoxrm6EWT8yi&search='; if(typ === 'generic') fdaRecallURL = fdaRecallURL + 'openfda.generic_name.exact:"'+ q +'"' ; if(typ === 'brand') fdaRecallURL = fdaRecallURL + 'openfda.brand_name.exact:"'+ q +'"' ; var lim = parseInt(limit); if(!isNaN(lim)) { fdaRecallURL = fdaRecallURL + '&limit=' + lim; } var start = parseInt(skip); if(!isNaN(start)) { fdaRecallURL = fdaRecallURL + '&skip=' + start; } logger.debug('fdaRecallURL:: '+ fdaRecallURL); request(fdaRecallURL, function (error, response, body) { if(error){ logger.debug('Error happened in retrieving the drug recall information'); return cb(error); } else if (!error && response.statusCode == 200) { var responseOBJ = JSON.parse(body); var results = responseOBJ.results; var meta = responseOBJ.meta; var recalls = []; var response = {}; if(results.length != 0){ var recallObj = {}; //Set results metadata response.count = meta.results.total; response.skip = meta.results.skip; response.limit = meta.results.limit; for(var i=0; i < results.length; i++) { //Set Recall details var recallDetails = {}; recallDetails.recall_number = results[i].recall_number; if(results[i].recall_initiation_date){ var date = results[i].recall_initiation_date; recallDetails.recall_initiation_date = date.substring(0,4)+'-'+date.substring(4,6)+'-'+date.substring(6,8); } recallDetails.reason_for_recall = results[i].reason_for_recall; recallDetails.distribution_pattern = results[i].distribution_pattern; recallDetails.recalling_firm = results[i].recalling_firm; recallDetails.product_description = results[i].product_description; recallDetails.product_quantity = results[i].product_quantity; recalls.push(recallDetails); } response.recalls = recalls; return cb(null, response); } }else{ return cb(null, {}); } }); }; Recall.remoteMethod( 'getRecallDetails', { description: 'Fetch drug recall details for the given drug brand_name', accepts: [{arg: 'q', type: 'string', required: true},{arg: 'typ', type: 'string', required: true},{arg: 'limit', type: 'string', required: true},{arg: 'skip', type: 'string', required: true}], returns: {arg: 'response', type: 'object'}, http: {path: '/', verb: 'get'} } ); };
JavaScript
0.000003
@@ -374,20 +374,17 @@ ic drug -name + %0ARecall. @@ -463,35 +463,32 @@ L = -'https://api.fda.gov/drug/e +Recall.app.get('fdaDrugE nfor @@ -497,62 +497,61 @@ ment -.json?api_key=yiv5ZoikJg3kSSZ5edvsiqnJa9yvHoxrm6EWT8yi +Api') + 'api_key=' + Recall.app.get('fdaApiKey') + ' &sea
dfc2e001d39d228f3ae1f286e3b6c73480fcd5a1
fix middleware error message
src/middleware/error.js
src/middleware/error.js
const errorUtil = require('../../util/error'); class Error { handle(err, req, res, next) { this.logger.error(req.url + ' ' + err.message + '"', null, errorUtil.stack(err)); return res.render('core/middleware/error'); } } module.exports = Error;
JavaScript
0.000013
@@ -147,14 +147,8 @@ sage - + '%22' , nu
f76a8fe82f62848e79bbeb5fdbf2e17f018ae59f
Fix System.getFirebugVersion
lib/core/system.js
lib/core/system.js
/* See license.txt for terms of usage */ "use strict"; const { Cu, Ci } = require("chrome"); const { getMostRecentBrowserWindow } = require("sdk/window/utils"); const { devtools } = Cu.import("resource://gre/modules/devtools/Loader.jsm", {}); const { Services } = Cu.import("resource://gre/modules/Services.jsm", {}); const currentBrowserVersion = Services.appinfo.platformVersion; let System = {}; /** * Compare the current browser version with the provided version argument. * * @param version string to compare with. * @returns {Integer} Possible result values: * is smaller than 0, the current version < version * equals 0 then the current version == version * is bigger than 0, then the current version > version */ System.compare = function(version) { return Services.vc.compare(currentBrowserVersion, version); } /** * Returns true if the current browser version is equal or bigger than * the giver version. The version can be specified as a string or number. * * @param version {String|Number} string that must correspond * to the version format. Read the following pages: * https://developer.mozilla.org/en/docs/Toolkit_version_format * https://addons.mozilla.org/en-US/firefox/pages/appversions/ * The version can be also specified as a simple number that is converted * to the version string. * * @returns {Boolean} True if the current browser version is equal or bigger. */ System.versionIsAtLeast = function(version) { if (typeof version == "number") { version = version + ".0a1"; } return System.compare(version) >= 0; } /** * Returns true if the current browser comes from Developer Edition channel * (formerly Aurora). */ System.isDeveloperBrowser = function() { try { let value = Services.prefs.getCharPref("app.update.channel"); // xxxHonza: "nightly-gum" can be removed at some point. return (value == "aurora") || (value == "nightly-gum"); } catch (err) { // Exception is thrown when the preference doesn't exist } return false; } /** * Returns true if the current browser supports multiprocess feature * (known also as Electrolysis & e10s) */ System.isMultiprocessEnabled = function(browserDoc) { if (Services.appinfo.browserTabsRemoteAutostart) { return true; } if (browserDoc) { let browser = browserDoc.getElementById("content"); if (browser && browser.mCurrentBrowser.isRemoteBrowser) { return true; } } let browser = getMostRecentBrowserWindow(); if (browser && browser.gBrowser.isRemoteBrowser) { return true; } return false; } /** * Returns true if Firebug is installed. */ System.isFirebugInstalled = function() { let bootstrappedAddons = Services.prefs.getCharPref("extensions.bootstrappedAddons"); return bootstrappedAddons.indexOf("[email protected]") != -1; } System.getFirebugVersion = function() { let bootstrappedAddons = Services.prefs.getCharPref("extensions.bootstrappedAddons"); return bootstrappedAddons["[email protected]"].version; } /** * Safe require for devtools modules. */ System.devtoolsRequire = function(uri) { try { return devtools["require"](uri); } catch (err) { return {}; } } // Exports from this module exports.System = System;
JavaScript
0
@@ -2961,67 +2961,146 @@ ;%0A -return bootstrappedAddons%5B%[email protected]%22%5D +let addons = JSON.parse(bootstrappedAddons);%0A let firebug = addons%5B%[email protected]%22%5D;%0A if (firebug) %7B%0A return firebug .ver @@ -3105,16 +3105,20 @@ ersion;%0A + %7D%0A %7D%0A%0A/**%0A
e705353443991aa012c7fbd03dc229fcd3849f9b
Fix syntax error in 'requiresSecure' middleware.
src/middleware/index.js
src/middleware/index.js
function requiresLogin(req, res, next) { if (!req.session.account) { return res.redirect('/'); } next(); } function requiresLogout(req, res, next) { if (req.session.account) { return res.redirect('/maker'); } next(); } function requiresSecure(req, res, next) { if (req.headers.x-forwarded-proto != 'https') { return res.redirect('https://' + req.host + req.url); } next(); } function bypassSecure(req, res, next) { next(); } module.exports.requiresLogin = requiresLogin; module.exports.requiresLogout = requiresLogout; if (process.env.NODE_ENV === 'production') { module.exports.requiresSecure = requiresSecure; } else { module.exports.requiresSecure = bypassSecure; }
JavaScript
0
@@ -295,17 +295,18 @@ .headers -. +%5B' x-forwar @@ -314,16 +314,18 @@ ed-proto +'%5D != 'htt
b9f908e3152711a5be0616814c584c92251edcac
Allow refresh tokens to retrieve download links
lib/credentials.js
lib/credentials.js
"use strict"; var querystring = require("querystring"); var WebHelper = require("./webhelper.js"); const _accessToken = new WeakMap(); const _apiKey = new WeakMap(); const _apiSecret = new WeakMap(); const _username = new WeakMap(); const _password = new WeakMap(); const _refreshToken = new WeakMap(); const _hostName = new WeakMap(); class Credentials { constructor(apiKey, apiSecret, username, password, refreshToken, hostName) { this.apiKey = apiKey; this.apiSecret = apiSecret; this.username = username; this.password = password; this.refreshToken = refreshToken; this.hostName = hostName; } get apiKey() { return _apiKey.get(this); } set apiKey(value) { _apiKey.set(this,value); } get accessToken() { return _accessToken.get(this); } set accessToken(value) { _accessToken.set(this,value); } get apiSecret() { return _apiSecret.get(this); } set apiSecret(value) { _apiSecret.set(this,value); } get password() { return _password.get(this); } set password(value) { _password.set(this,value); } get username() { return _username.get(this); } set username(value) { _username.set(this,value); } get refreshToken() { return _refreshToken.get(this); } set refreshToken(value) { _refreshToken.set(this,value); } get hostName() { return _hostName.get(this); } set hostName(value) { _hostName.set(this,value); } getAccessToken(next) { var apiKey = this.apiKey; var apiSecret = this.apiSecret; var username = this.username; var password = this.password; var accessToken = this.accessToken; var hostName = this.hostName; if (!this.shouldRefreshToken()) { return next(null, accessToken); } if (this.refreshToken || (accessToken && accessToken.refresh_token)) { return this.refreshAccessToken(next); } var params = { client_id: apiKey, client_secret: apiSecret, grant_type: "client_credentials" }; if (username && password) { params.username = username; params.password = password; params.grant_type = "password"; } var postData = querystring.stringify(params); var path = "/oauth2/token"; var self = this; var webHelper = new WebHelper(self, hostName); webHelper.postForm(postData, path, function (err, response) { if (err) { return next(err, null); } else { var expireTime = new Date(); expireTime.setSeconds(expireTime.getSeconds() + Number(response.expires_in)); response.expiration = expireTime; self.accessToken = response; return next(null, self.accessToken); } }); } refreshAccessToken(next) { var apiKey = this.apiKey; var apiSecret = this.apiSecret; var refreshToken = this.refreshToken || this.accessToken.refresh_token; var hostName = this.hostName; var params = { client_id: apiKey, client_secret: apiSecret, refresh_token: refreshToken, grant_type: "refresh_token" }; var postData = querystring.stringify(params); var path = "/oauth2/token"; var webHelper = new WebHelper(this, hostName); //Allows the scope of the class to be used inside the callback function //otherwise this is undefined at the time the function is executed. //https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this var self = this; webHelper.postForm(postData, path, function (err, response) { if (err) { return next(err, null); } else { var expireTime = new Date(); expireTime.setSeconds(expireTime.getSeconds() + Number(response.expires_in)); response.expiration = expireTime; response.refresh_token = refreshToken; self.accessToken = response; return next(null, self.accessToken); } }); } shouldRefreshToken() { var accessToken = this.accessToken; if (accessToken && accessToken.expiration) { // Must have at least 5 seconds left return new Date(Date.now() + 5000) > accessToken.expiration; } else { return true; } } } module.exports = Credentials;
JavaScript
0
@@ -4496,18 +4496,8 @@ %7D%0A - %0A%0A %0A
9e51340926cf4d97e9a35bd600bf4ae4e8d66bd8
Fix thunk signature having anonymous functions
src/middleware/thunk.js
src/middleware/thunk.js
import isObservable from '../util/isObservable' import isPromise from '../util/isPromise' export function createThunkMiddleware(...extraArgs) { return dispatcher => agenda => agenda.map(thunkish => { if (typeof thunkish === 'function') { const res = thunkish( x => dispatcher.next(x), x => dispatcher.reduce(x), ...extraArgs ) if (isObservable(res) || isPromise(res)) { dispatcher.next(res) } return null } return thunkish }) } export default createThunkMiddleware()
JavaScript
0.000003
@@ -265,37 +265,32 @@ hunkish(%0A - x =%3E dispatcher.next @@ -289,18 +289,32 @@ her.next -(x +.bind(dispatcher ),%0A @@ -319,13 +319,8 @@ - x =%3E dis @@ -337,10 +337,24 @@ duce -(x +.bind(dispatcher ),%0A @@ -372,23 +372,16 @@ xtraArgs -%0A )%0A%0A
057c04cf2d4e5b03fb7bed7761ab62b1c2361fd8
Make Sequelize use settings from config file.
models/index.js
models/index.js
var Sequelize = require('sequelize'); var fs = require('fs'); var path = require('path'); var sequelize = new Sequelize('cacophony_metadata', 'test', 'pass', { host: '192.168.33.10', port: '5432', dialect: 'postgres' }); var models = {}; models.sequelize = sequelize; var modelFiles = fs.readdirSync(__dirname); modelFiles.splice(modelFiles.indexOf('index.js'), 1); // Remove self from list. //modelFiles.splice(modelFiles.indexOf('util.js'), 1); // Remove util from list. for (i in modelFiles) { var model = sequelize.import(path.join(__dirname, modelFiles[i])); models[model.name] = model } Object.keys(models).forEach(function(modelName) { if ("addAssociations" in models[modelName]) { models[modelName].addAssociations(models) } }) module.exports = models;
JavaScript
0
@@ -87,141 +87,208 @@ ');%0A -%0Avar sequelize = new Sequelize('cacophony_metadata', 'test', 'pass', %7B%0A host: '192.168.33.10',%0A port: '5432',%0A dialect: 'postgres' +var config = require('../config');%0A%0Avar sequelize = new Sequelize(config.db.name, config.db.username, config.db.password, %7B%0A host: config.db.host,%0A port: config.db.port,%0A dialect: config.db.dialect %0A%7D);
ec059db257403eef4810d9fbe5e5b9f73c0fd568
remove useless extension to Sequelize, semicolons
models/index.js
models/index.js
'use strict'; var Sequelize = require('sequelize'), path = require('path'), fs = require('fs'); var assert = require('assert'), debug = require('debug')('bshed:models'); // Sequelize extensions~ Sequelize.prototype.Model.prototype.findStrict = function findStrict () { var args = arguments; return new Promise(function findStrictPromise (resolve, reject) { this.find.apply(this, args) .then(function (result) { if (!result) { reject(new Sequelize.prototype.Error('no result')); } else { resolve(result); } }, reject); }.bind(this)); }; /** * Model loader * * requires opts.database * returns models object */ module.exports = function modelsLoader (opts) { assert(opts); assert(opts.database); debug('loader:start'); var models = {}, config = opts.database, sequelize = new Sequelize(config.database, config.username, config.password, config); // Load models fs.readdirSync(__dirname) .filter(function (file) { return file.indexOf('.') !== 0 && file !== 'index.js'; }) .forEach(function (file) { var modelPath = path.join(__dirname, file); var model = sequelize.import(modelPath); models[model.name] = model; debug('%s loaded from file %s', model.name, modelPath); }); // Associate and initialize models Object.keys(models) .forEach(function (name) { if ('associate' in models[name]) { debug('associate %s', name); models[name].associate(models); } if ('initialize' in models[name]) { debug('initialize %s', name); models[name].initialize(opts); } }); models.sequelize = sequelize; models.Sequelize = Sequelize; debug('loader:end'); return models; };
JavaScript
0.000001
@@ -5,17 +5,16 @@ strict' -; %0A%0Avar Se @@ -91,17 +91,16 @@ re('fs') -; %0A%0Avar as @@ -171,428 +171,8 @@ ls') -;%0A%0A// Sequelize extensions~%0ASequelize.prototype.Model.prototype.findStrict = function findStrict () %7B%0A var args = arguments;%0A return new Promise(function findStrictPromise (resolve, reject) %7B%0A this.find.apply(this, args)%0A .then(function (result) %7B%0A if (!result) %7B%0A reject(new Sequelize.prototype.Error('no result'));%0A %7D else %7B%0A resolve(result);%0A %7D%0A %7D, reject);%0A %7D.bind(this));%0A%7D; %0A%0A/* @@ -309,17 +309,16 @@ rt(opts) -; %0A asser @@ -333,17 +333,16 @@ atabase) -; %0A debug @@ -357,17 +357,16 @@ :start') -; %0A%0A var @@ -494,17 +494,16 @@ config) -; %0A%0A // L @@ -626,17 +626,16 @@ ndex.js' -; %0A %7D)%0A @@ -707,17 +707,16 @@ e, file) -; %0A var @@ -751,17 +751,16 @@ delPath) -; %0A mod @@ -782,17 +782,16 @@ = model -; %0A deb @@ -845,15 +845,13 @@ ath) -; %0A %7D) -; %0A%0A @@ -1000,33 +1000,32 @@ ciate %25s', name) -; %0A models%5Bna @@ -1045,17 +1045,16 @@ (models) -; %0A %7D%0A @@ -1126,17 +1126,16 @@ ', name) -; %0A m @@ -1162,17 +1162,16 @@ ze(opts) -; %0A %7D%0A @@ -1173,17 +1173,16 @@ %7D%0A %7D) -; %0A%0A mode @@ -1205,17 +1205,16 @@ equelize -; %0A model @@ -1236,17 +1236,16 @@ equelize -; %0A%0A debu @@ -1259,17 +1259,16 @@ er:end') -; %0A retur @@ -1279,10 +1279,7 @@ dels -; %0A%7D -;%0A %0A
1894a929007dd9bec9b35f6efc8352954ad5de75
apply webpack 2.2.0 config to karma config
test/karma.config.js
test/karma.config.js
var webpackConfig = require('../webpack/dev/webpack.config'); var isTravis = !!process.env.TRAVIS var webpack = require('webpack') delete webpackConfig.entry module.exports = function (config) { config.set({ browsers: ['PhantomJS'], singleRun: isTravis, frameworks: ['mocha', 'chai', 'sinon'], reporters: ['mocha'], // mochaReporter: { // output: 'autowatch' // }, files: [ './index.js', ], client: { captureConsole: false }, plugins: [ 'karma-phantomjs-launcher', 'karma-chai', 'karma-mocha', 'karma-webpack', 'karma-sinon', 'karma-mocha-reporter', 'karma-chrome-launcher', 'karma-sourcemap-loader' ], preprocessors: { './index.js': ['webpack', 'sourcemap'] }, webpack: { devtool: 'inline-source-map', entry: './test/index.js', output: { path: __dirname, filename: 'test-bundle.js' }, module: { loaders: [ { test: /sinon.js$/, loader: "imports?define=>false" }, { test: /\.js$/, loader: 'babel', query: { compact: false, presets: ['es2015', 'stage-2'] }, exclude: /node_modules/ } ] } }, webpackMiddleware: { noInfo: true } }); };
JavaScript
0.000001
@@ -999,22 +999,20 @@ -loader +rule s: %5B%0A @@ -1173,16 +1173,23 @@ : 'babel +-loader ',%0A
1c8266dc34b64c101bd807ea35bf2cd235138a07
Update the login model unit test.
test/models/login.js
test/models/login.js
/* global describe, it */ import 'should'; import model from '../utils/model'; const session = { login: { provider: 'models', user: 'tester', }, }; describe('model login', () => { it('should pass validation when user match', () => model('login').validate({ provider: 'models', user: 'tester', session, }) .then(() => 'everything'.should.be.ok())); it('should fail validation when user not match', () => model('login').validate({ provider: 'models', user: 'hacker', session, }) .catch(error => error.should.have.properties(['code', 'message']))); it('should return true when logged user is the owner of repo', () => model('login').isLoggedIn({ provider: 'models', user: 'tester', session, }) .then(result => result.should.equal(true))); it('should return false when logged user is not the owner of repo', () => model('login').isLoggedIn({ provider: 'models', user: 'hacker', session, }) .catch(result => result.should.equal(false))); });
JavaScript
0
@@ -599,27 +599,87 @@ ies( -%5B'code', 'message'%5D +%7B%0A statusCode: 401,%0A message: 'Unanthorized, please login in.',%0A %7D )));
118472c1bfc0df76a1f0aef457bcf71d4abce29e
Check author before reading config:
src/modules/banwords.js
src/modules/banwords.js
const Confax = require('../bot.js') const fs = require('fs') const bot = Confax.bot const warnedUserIds = Confax.warnedUserIds bot.on('message', (message) => { if (message.guild === null) { return message } const config = Confax.getConfig(message.guild.id) const bannedWords = config.bannedWords if (message.author.bot) return const lowercaseMessage = message.content.toLowerCase() for (const word in bannedWords) { if (lowercaseMessage.split(' ').indexOf(bannedWords[word]) > -1) { const apiCommands = ['addbannedword', 'abw', 'removebannedword', 'rbw'] if (apiCommands.some(x => { return lowercaseMessage.indexOf(x) >= 0 })) { const roles = message.guild.member(message.author.id).roles.array() const accepted = ['Bot Commander', 'Moderator'] for (let i = 0; i < roles.length; i++) { if (accepted.includes(roles[i].name)) { return } } } message.reply(config.muteWarningMessage.replace('{bannedWord}', bannedWords[word])) checkUser(message, config) } } }) const checkUser = (message, config) => { if (warnedUserIds.includes(message.member.user.id)) { addMutedRole(message, config) } else { warnedUserIds.push(message.member.user.id) } } const addMutedRole = (message, config) => { const role = message.guild.roles.find(role => role.name === config.roleMuted) if (!role) { console.log('The role ' + config.roleMuted + ' does not exists on this server') return } message.member.addRole(role) } const persistWarnedUsers = () => { fs.writeFileSync(`${__dirname}/../core/warneduserids.json`, JSON.stringify(warnedUserIds)) } setInterval(persistWarnedUsers, 10000)
JavaScript
0
@@ -172,48 +172,27 @@ age. -guild === null) %7B%0A return message%0A %7D +author.bot) return%0A %0A c @@ -286,41 +286,8 @@ ds%0A%0A - if (message.author.bot) return%0A co
e2da4f7803a0ac6cea71c0bea19de92ae9cb43c6
add timeout debounce
component/CopyButton.js
component/CopyButton.js
import React, { Component, PropTypes } from 'react'; import { findDOMNode } from 'react-dom'; import ZeroClipboard from 'zeroclipboard'; import classNames from 'classnames'; export default class CopyButton extends Component { constructor(props) { super(props); this.state = { copied: false }; } componentDidMount() { this.clipboard = new ZeroClipboard(findDOMNode(this)); this.clipboard.on('copy', () => { this.setState({ copied: true }); setTimeout(() => { this.setState({ copied: false }); }, 1500); }); } render() { return ( <a className="copy-button" href="#" data-clipboard-text={this.props.text}> <div className={classNames({ "copy-button__tip": true, "copy-button__tip--active": this.state.copied })}>コピーしました</div> <svg className="copy-icon" height="17" width="17" version="1.1" xmlns="http://www.w3.org/2000/svg"> <g transform="scale(0.035,0.035) translate(0,-60)"> <path d="M314.099,250H186.901c-12.536,0-22.713,10.175-22.713,22.715 c0,12.537,10.177,22.712,22.713,22.712h127.198c12.537,0,22.716-10.175,22.716-22.712C336.814,260.175,326.636,250,314.099,250z M314.099,331.771H186.901c-12.536,0-22.713,10.175-22.713,22.711s10.177,22.716,22.713,22.716h127.198 c12.537,0,22.716-10.18,22.716-22.716S326.636,331.771,314.099,331.771z M73.333,431.711c0,20.078,16.264,36.34,36.343,36.34 h281.648c20.078,0,36.345-16.262,36.345-36.34V122.802c0-20.077-16.267-36.341-36.345-36.341h-74.049 c-6.263-31.071-33.797-54.512-66.774-54.512c-32.98,0-60.512,23.441-66.774,54.512h-74.051c-20.079,0-36.343,16.264-36.343,36.341 V431.711z M138.75,131.889h43.607v16.353c0,11.081,8.909,19.989,19.991,19.989h96.301c11.08,0,19.991-8.909,19.991-19.989v-16.353 h43.607c11.081,0,19.992,8.909,19.992,19.991v250.754c0,11.084-8.911,19.99-19.992,19.99H138.75 c-11.083,0-19.989-8.906-19.989-19.99V151.879C118.761,140.797,127.667,131.889,138.75,131.889z M227.787,100.089 c0-12.537,10.177-22.714,22.713-22.714c12.537,0,22.715,10.177,22.715,22.714c0,12.538-10.178,22.713-22.715,22.713 C237.964,122.802,227.787,112.627,227.787,100.089z" fill="#fff"/> </g> </svg> <span>コピー</span> </a> ); } } CopyButton.propTypes = {text: PropTypes.string}; CopyButton.defaultProps = {text: ''}; ZeroClipboard.config( { swfPath: "/node_modules/zeroclipboard/dist/ZeroClipboard.swf" } );
JavaScript
0.000001
@@ -262,16 +262,40 @@ rops);%0A%0A + this.timer = null;%0A%0A this @@ -487,21 +487,129 @@ rue %7D);%0A +%0A + if (this.timer) %7B%0A clearTimeout(this.timer);%0A this.timer = null;%0A %7D%0A%0A this.timer = setTime
51dbeaa2ef3f3b06d703de1e2cebbacf1ee0c65e
Test for property parsing.
test/spec/mmg_csv.js
test/spec/mmg_csv.js
describe('mmg csv', function() { it('can parse a simple csv file', function() { var csv = 'lat,lon\n10,15'; expect(mmg_csv(csv)[0].geometry.coordinates).toEqual([15, 10]); }); });
JavaScript
0
@@ -192,13 +192,202 @@ %0A %7D); +%0A%0A it('can parse the properties of a csv file csv file', function() %7B%0A var csv = 'lat,lon,name%5Cn10,15,Tom';%0A expect(mmg_csv(csv)%5B0%5D.properties.name).toEqual('Tom');%0A %7D); %0A%7D);%0A
01a37c4c4759818ac7a54527ffddee40391774d6
Handle only left click
modules/main.js
modules/main.js
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ load('lib/WindowManager'); Components.utils.import('resource://gre/modules/Services.jsm'); var bundle = require('lib/locale') .get('chrome://launch-file-link/locale/launch-file-link.properties'); var lastState = new WeakMap(); function handleLinkClick(aEvent) { var target = aEvent.originalTarget; while (target && !target.href) { target = target.parentNode; } if (!target || !target.parentNode) return true; var url = target.href; if (url.indexOf('file:') != 0) return true; aEvent.stopPropagation(); aEvent.preventDefault(); var FileHandler = Services.io.getProtocolHandler('file') .QueryInterface(Ci.nsIFileProtocolHandler); try { var file = FileHandler.getFileFromURLSpec(url); file = file.QueryInterface(Ci.nsILocalFile); var view = target.ownerDocument.defaultView; var confirmed = lastState.get(view); if (confirmed == undefined) { let messageType = file.isDirectory() ? 'folder' : 'file'; let checked = { value: false }; confirmed = Services.prompt.confirmCheck( view, bundle.getString('confirm.title'), bundle.getFormattedString('confirm.message.' + messageType, [file.parent.path, file.leafName]), bundle.getString('confirm.check'), checked ); if (checked.value) lastState.set(view, confirmed); } if (!confirmed) return false; file.launch(); } catch(aError) { Cu.reportError(new Error('failed to open a file URL <' + url + '>\n' + aError.message)); } finally { return false; } } function handleSubWindowUnload(aEvent) { var view = aEvent.originalTarget; view = view.ownerDocument || view; view = view.defaultView; lastState.delete(view); } function handleWindowUnload(aEvent) { var view = aEvent.originalTarget; view = view.ownerDocument || view; view = view.defaultView; lastState.delete(view); view.removeEventListener('unload', handleSubWindowUnload, true); view.removeEventListener('click', handleLinkClick, true); } function handleWindow(aWindow) { aWindow.addEventListener('click', handleLinkClick, true); aWindow.addEventListener('unload', handleSubWindowUnload, true); aWindow.addEventListener('unload', handleWindowUnload, false); } WindowManager.getWindows().forEach(handleWindow); WindowManager.addHandler(handleWindow); function shutdown() { WindowManager.getWindows().forEach(function(aWindow) { aWindow.removeEventListener('click', handleLinkClick, true); aWindow.removeEventListener('unload', handleSubWindowUnload, true); aWindow.removeEventListener('unload', handleWindowUnload, false); }); WindowManager.removeHandler(handleWindow); handleWindow = undefined; handleLinkClick = undefined; bundle = undefined; lastState = undefined; Services = undefined; WindowManager = undefined; }
JavaScript
0
@@ -490,24 +490,71 @@ (aEvent) %7B%0D%0A + if (aEvent.button != 0)%0D%0A return true;%0D%0A%0D%0A var target
bf8326a312a82e8015c4c8171cafbeff543d9197
fix eslint error.
test/src/04-media.js
test/src/04-media.js
const chai = require('chai'); const Vast = require('../../src/main.js'); const expect = chai.expect; let vast; let url; describe('Mediafile', () => { beforeEach(() => { vast = new Vast(document.getElementById('target')); url = '../data/simple.xml'; }); it('mp4 w/ dedfault parameters', (done) => { vast.load(url).then(() => { const media = vast.media('video/mp4'); expect(media).to.equal('medias/1000.mp4'); done(); }).catch((error) => { done(error); }); }); it('mp4 w/ 6000kbps', (done) => { vast.load(url).then(() => { const media = vast.media('video/mp4', 6000); expect(media).to.equal('medias/5226.mp4'); done(); }).catch((error) => { done(error); }); }); it('webm w/ dedfault parameters', (done) => { vast.load(url).then(() => { const media = vast.media('video/webm'); expect(media).to.equal('medias/1500.webm'); done(); }).catch((error) => { done(error); }); }); it('mp4 w/ too small bps', (done) => { vast.load(url).then(() => { const media = vast.media('video/mp4', 100); expect(media).to.be.null; done(); }).catch((error) => { done(error); }); }); });
JavaScript
0.000001
@@ -1150,15 +1150,19 @@ .to. -be. +equal( null +) ;%0A
68aaf0c82bac88ab7d447e6012ba08e1bf2be583
fix url
modules/menu.js
modules/menu.js
var reserveUrl = encodeURIComponent('http://115.159.119.199:8080/meeting/src/html/app.html#search') module.exports = { "button": [{ "type": "view", "name": "预定", "url": 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx65cfe45c2c6fad4a&redirect_uri=http://115.159.119.199:8080/meeting/src/html/app.html#search&response_type=code&scope=snsapi_userinfo&state=reserve#wechat_redirect' }] }
JavaScript
0.86565
@@ -1,18 +1,16 @@ var -reserveUrl +jumpPage = e @@ -291,61 +291,22 @@ p:// -115.159.119.199:8080/meeting/src/html/app.html#search +roscoe.cn/info &res @@ -353,15 +353,24 @@ ate= -reserve +' + jumpPage + ' #wec
524a70e5d525c7dac765f4250c2b89e27afa2dad
fix path for latest browserify
test/test-adapter.js
test/test-adapter.js
/*global RSVP*/ var assert = require('assert'); var g = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : this; var RSVP = g.RSVP || require('./rsvp.js'); var defer = RSVP.defer; var resolve = RSVP.resolve; var reject = RSVP.reject; module.exports = g.adapter = { resolved: resolve, rejected: reject, deferred: defer, RSVP: RSVP };
JavaScript
0.000001
@@ -189,16 +189,10 @@ e('. +. / -rsvp.js ');%0A
e5924fcea2dfbcfbb2fde4c6d5370d475c84a3a5
add bidi tests
mobile/tests/doh/module.js
mobile/tests/doh/module.js
define([ "doh/runner", "dojo/sniff", "require", "./accordion/module", "./badge/module", "./button/module", "./checkbox/module", "./combobox/module", "./contentpane/module", "./edgetoedgecategory/module", "./edgetoedgedatalist/module", "./edgetoedgelist/module", "./edgetoedgestorelist/module", "./expandingtextarea/module", "./filteredlistmixin/module", "./fixedsplitter/module", "./heading/module", "./iconcontainer/module", "./iconmenu/module", "./listitem/module", "./longlistmixin/module", "./pageindicator/module", "./progressindicator/module", "./radiobutton/module", "./roundrect/module", "./roundrectdatalist/module", "./roundrectlist/module", "./roundrectstorelist/module", "./slider/module", "./spinwheel/module", "./spinwheeldatepicker/module", "./swapview/module", "./switch/module", "./tabbar/module", "./templating/module", "./textarea/module", "./textbox/module", "./toolbarbutton/module", "./transition/module", "./valuepickerdatepicker/module", "./valuepickertimepicker/module", "./view/module" ], function(doh, has, require){ try{ doh.registerUrl("dojox.mobile.tests.doh.URLProperty", require.toUrl("./TestURLProp.html"),999999); doh.registerUrl("dojox.mobile.tests.doh.URLProperty", require.toUrl("./TestURLProp2.html"),999999); doh.registerUrl("dojox.mobile.tests.doh.CustomFixedBarsTests", require.toUrl("./CustomFixedBarsTests.html"),999999); }catch(e){ doh.debug(e); } });
JavaScript
0
@@ -1214,16 +1214,38 @@ /module%22 +,%0A %22./bidi/module%22 %0A%5D, func
f867fcfeb78a182f772b600e8046fe2e6d0481c7
remove script node, after "onload" event
lib/flow.client.js
lib/flow.client.js
var Flow = require('./flow/flow'); var server = require('./socket'); // init flow with core module var flow = Flow({ // load module bundles and return the entry-point exports // USED IN flow.js module: function (name, callback) { // crate script dom element var node = document.createElement('script'); node.onload = function () { callback(null, require(name)); }; // set url and append dom script elm to the document head node.src = '/' + name + '/client.js'; document.head.appendChild(node); node.remove(); }, // load composition // USED IN flow.js composition: function (name, callback) { this.flow('C/' + (name || 'new'), { net: 'http' }, function (err, composition) { composition = JSON.parse(composition); composition._roles = {'*': true}; callback(err, composition); }); }, request: server.request, /** * Load html snippets. * * @public * @param {array} The array containing html snippet file urls. */ // USED IN instance.js markup: function (urls) { // TODO use xhr2 to benefit from browser caching // TODO request/response events //this.flow('/M', url, function () {}); // TODO load all urls //urls.forEach(function (url) {}); }, /** * Load css files. * * @public * @param {array} The array containing css file urls. */ // USED IN instance.js styles: function (urls) { urls.forEach(function (url) { var link = document.createElement('link'); link.setAttribute('rel', 'stylesheet'); link.setAttribute('href', url); global.document.head.appendChild(link); }); }, // USED IN flow.js log: function (err) {return err}, //require('./logs') || // USED IN flow.js reset: function () { // reset DOM body document.body.innerHTML = ''; // remove styles var styles = document.head.querySelectorAll('link[rel=stylesheet]'); if (styles) { styles.forEach(function (stylesheet) { stylesheet.remove(); }); } // reset server server.reset(); } }); server.start(flow); flow.load('*');
JavaScript
0.000001
@@ -360,24 +360,51 @@ nction () %7B%0A + node.remove();%0A @@ -599,39 +599,16 @@ (node);%0A - node.remove();%0A %7D,%0A%0A
61a360217759f2c19381fae906a6978ec9bc891b
Allow for a little more clock skew
lib/flow/oauth2.js
lib/flow/oauth2.js
var crypto = require('crypto') var qs = require('qs') var request = require('../client') exports.authorize = async ({provider, input}) => { var url = provider.authorize_url var params = { client_id: provider.key, response_type: 'code', redirect_uri: provider.redirect_uri, scope: provider.scope, state: provider.state, nonce: provider.nonce } if (provider.pkce) { params.code_challenge_method = 'S256' params.code_challenge = provider.code_challenge } if (provider.custom_params) { for (var key in provider.custom_params) { params[key] = provider.custom_params[key] } } if (provider.basecamp) { params.type = 'web_server' } if (provider.freelancer && params.scope) { params.advanced_scopes = params.scope delete params.scope } if (provider.instagram && /^\d+$/.test(provider.key)) { params.app_id = params.client_id delete params.client_id params.scope = (params.scope || '').replace(/ /g, ',') || undefined } if (provider.optimizely && params.scope) { params.scopes = params.scope delete params.scope } if (provider.visualstudio) { params.response_type = 'Assertion' } if (provider.wechat) { params.appid = params.client_id delete params.client_id } if (provider.subdomain) { url = url.replace('[subdomain]', provider.subdomain) } var querystring = qs.stringify(params) if (provider.unsplash && params.scope) { var scope = params.scope delete params.scope querystring = qs.stringify(params) + '&scope=' + scope } return {provider, input, output: `${url}?${querystring}`} } exports.access = ({request:client}) => async ({provider, input, input:{query, body, session}}) => { query = Object.keys(query).length ? query : body if (!query.code) { var output = Object.keys(query).length ? query : {error: 'Grant: OAuth2 missing code parameter'} return {provider, input, output} } else if ((query.state && session.state) && (query.state !== session.state)) { var output = {error: 'Grant: OAuth2 state mismatch'} return {provider, input, output} } var options = { method: 'POST', url: provider.access_url, form: { grant_type: 'authorization_code', code: query.code, client_id: provider.key, client_secret: provider.secret, redirect_uri: provider.redirect_uri } } if (provider.pkce) { options.form.code_verifier = session.code_verifier } if (provider.basecamp) { options.form.type = 'web_server' } if (provider.concur) { delete options.form options.qs = { code: query.code, client_id: provider.key, client_secret: provider.secret } } if (/ebay|fitbit|homeaway|hootsuite|reddit/.test(provider.name) || provider.token_endpoint_auth_method === 'client_secret_basic' ) { delete options.form.client_id delete options.form.client_secret options.auth = {user: provider.key, pass: provider.secret} } if (provider.token_endpoint_auth_method === 'private_key_jwt') { var jwt = ({kid, x5t, secret}) => ({ header: { typ: 'JWT', alg: provider.token_endpoint_auth_signing_alg || 'RS256', kid, x5t }, payload: { iss: provider.key, sub: provider.key, aud: provider.access_url, jti: crypto.randomBytes(20).toString('hex'), exp: Math.round(Date.now() / 1000) + 300, iat: Math.round(Date.now() / 1000), nbf: Math.round(Date.now() / 1000) }, secret }) var assertion = (() => { var oidc = require('../oidc') var {public_key, private_key} = provider return oidc.sign(jwt({ kid: private_key.kty ? oidc.kid(private_key) : undefined, x5t: public_key ? public_key.kty ? public_key.x5t : oidc.x5t(public_key) : undefined, secret: private_key.kty ? oidc.pem(private_key) : private_key, })) })() options.form.client_assertion_type = 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer' options.form.client_assertion = assertion delete options.form.client_id delete options.form.client_secret } if (provider.instagram && /^\d+$/.test(provider.key)) { options.form.app_id = options.form.client_id delete options.form.client_id options.form.app_secret = options.form.client_secret delete options.form.client_secret } if (provider.qq) { options.method = 'GET' options.qs = options.form delete options.form } if (provider.wechat) { options.method = 'GET' options.qs = options.form delete options.form options.qs.appid = options.qs.client_id options.qs.secret = options.qs.client_secret delete options.qs.client_id delete options.qs.client_secret } if (provider.smartsheet) { delete options.form.client_secret var hash = crypto.createHash('sha256') hash.update(provider.secret + '|' + query.code) options.form.hash = hash.digest('hex') } if (provider.surveymonkey) { options.qs = {api_key: provider.custom_params.api_key} } if (provider.visualstudio) { options.form = { client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer', client_assertion: provider.secret, grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', assertion: query.code, redirect_uri: provider.redirect_uri } } if (provider.subdomain) { options.url = options.url.replace('[subdomain]', provider.subdomain) } try { var {body:output} = await request({...client, ...options}) if (provider.intuit) { output.realmId = query.realmId } } catch (err) { var output = {error: err.body || err.message} } return {provider, input, output} }
JavaScript
0
@@ -3484,16 +3484,22 @@ / 1000) + - 120 ,%0A @@ -3534,16 +3534,22 @@ / 1000) + - 120 %0A %7D
e1a460fe867d7072c2dcfbfe213d36d697ba9ab2
Add type check to response.body
src/nylas-connection.js
src/nylas-connection.js
import clone from 'lodash/clone'; import request from 'request'; import RestfulModel from './models/restful-model'; import RestfulModelCollection from './models/restful-model-collection'; import RestfulModelInstance from './models/restful-model-instance'; import Account from './models/account'; import ManagementAccount from './models/management-account'; import ManagementModelCollection from './models/management-model-collection'; import Thread from './models/thread'; import Contact from './models/contact'; import Message from './models/message'; import Draft from './models/draft'; import File from './models/file'; import Calendar from './models/calendar'; import Event from './models/event'; import Delta from './models/delta'; import { Label, Folder } from './models/folder'; const PACKAGE_JSON = require('../package.json'); const SDK_VERSION = PACKAGE_JSON.version; const SUPPORTED_API_VERSION = '2.0'; module.exports = class NylasConnection { constructor(accessToken, { clientId }) { this.accessToken = accessToken; this.clientId = clientId; this.threads = new RestfulModelCollection(Thread, this); this.contacts = new RestfulModelCollection(Contact, this); this.messages = new RestfulModelCollection(Message, this); this.drafts = new RestfulModelCollection(Draft, this); this.files = new RestfulModelCollection(File, this); this.calendars = new RestfulModelCollection(Calendar, this); this.events = new RestfulModelCollection(Event, this); this.deltas = new Delta(this); this.labels = new RestfulModelCollection(Label, this); this.folders = new RestfulModelCollection(Folder, this); this.account = new RestfulModelInstance(Account, this); } requestOptions(options) { if (!options) { options = {}; } options = clone(options); const Nylas = require('./nylas'); if (!options.method) { options.method = 'GET'; } if (options.path) { if (!options.url) { options.url = `${Nylas.apiServer}${options.path}`; } } if (!options.formData) { if (!options.body) { options.body = {}; } } if (options.json == null) { options.json = true; } if (!options.downloadRequest) { options.downloadRequest = false; } // For convenience, If `expanded` param is provided, convert to view: // 'expanded' api option if (options.qs && options.qs.expanded) { if (options.qs.expanded === true) { options.qs.view = 'expanded'; } delete options.qs.expanded; } const user = options.path.substr(0, 3) === '/a/' ? Nylas.clientSecret : this.accessToken; if (user) { options.auth = { user: user, pass: '', sendImmediately: true, }; } if (options.headers == null) { options.headers = {}; } if (options.headers['User-Agent'] == null) { options.headers['User-Agent'] = `Nylas Node SDK v${SDK_VERSION}`; } options.headers['Nylas-SDK-API-Version'] = SUPPORTED_API_VERSION; options.headers['X-Nylas-Client-Id'] = this.clientId; return options; } _getWarningForVersion(sdkApiVersion = null, apiVersion = null) { let warning = ''; if (sdkApiVersion != apiVersion) { if (sdkApiVersion && apiVersion) { warning += `WARNING: SDK version may not support your Nylas API version.` + ` SDK supports version ${sdkApiVersion} of the API and your application` + ` is currently running on version ${apiVersion} of the API.`; const apiNum = parseInt(apiVersion.split('-')[0]); const sdkNum = parseInt(sdkApiVersion.split('-')[0]); if (sdkNum > apiNum) { warning += ` Please update the version of the API that your application is using through the developer dashboard.`; } else if (apiNum > sdkNum) { warning += ` Please update the sdk to ensure it works properly.`; } } } return warning; } request(options) { if (!options) { options = {}; } options = this.requestOptions(options); return new Promise((resolve, reject) => { return request(options, (error, response, body = {}) => { // node headers are lowercase so this refers to `Nylas-Api-Version` const apiVersion = response.headers['nylas-api-version']; const warning = this._getWarningForVersion( SUPPORTED_API_VERSION, apiVersion ); if (warning) { console.warn(warning); } // raw MIMI emails have json === false and the body is a string so // we need to turn into JSON before we can access fields if (options.json === false) { body = JSON.parse(body); } if (error || response.statusCode > 299) { if (!error) { error = new Error(body.message); } if (body.missing_fields) { error.message = `${body.message}: ${body.missing_fields}`; } if (body.server_error) { error.message = `${error.message} (Server Error: ${body.server_error} )`; } if (response.statusCode) { error.statusCode = response.statusCode; if (!error.hasOwnProperty('message')) { error.message = response.body; } } return reject(error); } else { if (options.downloadRequest) { return resolve(response); } else { return resolve(body); } } }); }); } };
JavaScript
0
@@ -5331,16 +5331,53 @@ essage') + && typeof response.body === 'string' ) %7B%0A
0dd448c9636ffe6c973a61b544e48f49ed537c7f
Handle errors getting the body
lib/generic-app.js
lib/generic-app.js
'use strict'; const querystring = require('querystring'); class GenericApp { constructor(options, emit) { this.options = options; this.emit = emit; } handle_404(req, res) { if (res.finished) { return; } res.writeHead(404); res.end(); } handle_405(req, res, methods) { res.writeHead(405, { 'Allow': methods.join(', ') }); res.end(); } handle_error(req, res, x) { if (res.finished) { return; } if (typeof x === 'object' && 'status' in x) { res.writeHead(x.status); res.end(x.message || ''); } else { try { res.writeHead(500); res.end('500 - Internal Server Error'); } catch (x) { this.log('error', `Exception on "${req.method} ${req.url}" in filter "${req.last_fun}":\n${x.stack || x}`); } } } log_request(req, res, _head, next) { const td = Date.now() - req.start_date; this.log('info', `${req.method} ${req.url} ${td}ms ${res.finished ? res.statusCode : '(unfinished)'}`); next(); } log(severity, line) { this.options.log(severity, line); } h_no_cache(req, res, _head, next) { res.setHeader('Cache-Control', 'no-store, no-cache, no-transform, must-revalidate, max-age=0'); next(); } _getBody(req, cb) { let body = []; req.on('data', d => { body.push(d); }); req.once('end', () => { cb(null, Buffer.concat(body).toString('utf8')); }); req.once('error', cb); req.once('close', () => { body = null; }); } expect_form(req, res, _head, next) { this._getBody(req, (err, body) => { switch ((req.headers['content-type'] || '').split(';')[0]) { case 'application/x-www-form-urlencoded': req.body = querystring.parse(body); break; case 'text/plain': case '': req.body = body; break; default: this.log('error', `Unsupported content-type ${req.headers['content-type']}`); break; } next(); }); } expect_xhr(req, res, _head, next) { this._getBody(req, (err, body) => { switch ((req.headers['content-type'] || '').split(';')[0]) { case 'text/plain': case 'T': case 'application/json': case 'application/xml': case '': case 'text/xml': req.body = body; break; default: this.log('error', `Unsupported content-type ${req.headers['content-type']}`); break; } next(); }); } } module.exports = GenericApp;
JavaScript
0
@@ -1600,32 +1600,84 @@ err, body) =%3E %7B%0A + if (err) %7B%0A return next(err);%0A %7D%0A%0A switch ((r @@ -2139,24 +2139,76 @@ body) =%3E %7B%0A + if (err) %7B%0A return next(err);%0A %7D%0A%0A switch
9d9f2d3aaf899e7094e3e1871b86da46802b1c70
buzzer beep
modules/@amperka/buzzer.js
modules/@amperka/buzzer.js
var Buzzer = function(pin) { this._pin = pin; this._on = false; this._frequency = 2000; this._pin.mode('output'); }; Buzzer.prototype.toggle = function() { if (arguments.length === 0) { return this.toggle(!this._on); } this._on = !!arguments[0]; this._update(); return this; }; Buzzer.prototype.turnOn = function() { return this.toggle(true); }; Buzzer.prototype.turnOff = function() { return this.toggle(false); }; Buzzer.prototype.isOn = function() { return this._on; }; Buzzer.prototype.frequency = function() { if (arguments.length === 0) { return this._frequency; } this._frequency = Math.clip(arguments[0], 0.0, 20000.0); this._update(); return this; }; Buzzer.prototype._update = function() { analogWrite(this._pin, 0.5 * this._on, {freq: this._frequency}); }; exports.connect = function(pin) { return new Buzzer(pin); };
JavaScript
0.999999
@@ -89,16 +89,96 @@ 2000;%0A%0A + this._beepTimeoutID = null;%0A this._beepOnTime = 0;%0A this._beepOffTime = 0;%0A%0A this._ @@ -197,16 +197,16 @@ tput');%0A - %7D;%0A%0ABuzz @@ -308,24 +308,45 @@ ._on);%0A %7D%0A%0A + this._clearBeep();%0A this._on = @@ -573,32 +573,32 @@ = function() %7B%0A - return this._o @@ -600,24 +600,767 @@ is._on;%0A%7D;%0A%0A +Buzzer.prototype._clearBeep = function() %7B%0A if (this._beepTimeoutID) %7B%0A clearTimeout(this._beepTimeoutID);%0A this._beepTimeoutID = null;%0A %7D%0A%7D;%0A%0ABuzzer.prototype._beepOn = function() %7B%0A this._on = true;%0A this._update();%0A this._beepTimeoutID = setTimeout(%0A this._beepOff.bind(this),%0A this._beepOnTime * 1000);%0A%7D;%0A%0ABuzzer.prototype._beepOff = function() %7B%0A this._on = false;%0A this._update();%0A%0A if (this._beepOffTime) %7B%0A this._beepTimeoutID = setTimeout(%0A this._beepOn.bind(this),%0A this._beepOffTime * 1000);%0A %7D else %7B%0A this._beepTimeoutID = null;%0A %7D%0A%7D;%0A%0ABuzzer.prototype.beep = function(onTime, offTime) %7B%0A this._clearBeep();%0A this._beepOnTime = onTime;%0A this._beepOffTime = offTime;%0A this._beepOn();%0A%7D;%0A%0A Buzzer.proto
a1b64a4af2c4ccf23d1d29c73bf2675824905b36
Comment in english
lib/google-plus.js
lib/google-plus.js
var fs = require('fs'), ejs = require('ejs'), jsdom = require('jsdom') var htmlToText = function(html) { // Add line breaks for block elements ['br', 'div', 'p'].forEach(function(tag) { var elements = html.getElementsByTagName(tag) for (var i = 0; i < elements.length; i++) { var newline = html.ownerDocument.createTextNode('\n') elements[i].parentNode.insertBefore(newline, elements[i]) } }) // Remove "* va compartir originalment aquesta publicació:" element var elements = html.getElementsByClassName('Ux') for (var i = 0; i < elements.length; i++) { elements[i].parentNode.removeChild(elements[i]) } return html.textContent } var userPosts = function(userId, callback) { jsdom.env({ html: 'https://plus.google.com/' + userId + '/posts', done: function(errors, window) { if (errors) console.log(errors) var posts = [] var postElements = window.document.getElementsByClassName('Ve') for (var i = 0; i < postElements.length; i++) { var post = postElements[i] var body = post.getElementsByClassName('Us')[0] posts.push({ url: 'https://plus.google.com/' + post.getElementsByClassName('c-G-j')[0].href, title: htmlToText(body).trim().split('\n')[0], lastModification: new Date }) } callback(null, posts) } }) } exports.userFeed = function(userId, callback) { userPosts(userId, function(error, posts) { if (error) return callback(error) fs.readFile(__dirname + '/../views/feed.ejs', 'utf8', function(error, template) { if (error) return callback(error) var feed = ejs.render(template, { locals: { profileUrl: 'https://plus.google.com/' + userId, posts: posts } }) callback(null, feed) }) }) }
JavaScript
0
@@ -474,55 +474,42 @@ ove -%22* va compartir originalment aquesta publicaci%C3%B3 +the %22* originally shared this post :%22 e
3edee260fdc95ae1140e467811f7623fb8d9d38e
add strict checks
lib/groups/help.js
lib/groups/help.js
const chalk = require('chalk'); class HelpGroup { b() { const b = chalk.blue; } l() { const c = chalk.cyan; } outputHelp(command=null) { if (command != null) { const commands = require('../utils/commands').info; const options = commands.find(cmd => (cmd.name == command || cmd.alias == command)); const { bold } = chalk.white; const usage = chalk.keyword('orange')('webpack ' + options.usage); const description = options.description; process.stdout.write(`${bold('Usage')}: ${usage}\n${bold('Description')}: ${description}\n`); } else { process.stdout.write(this.run().outputOptions.help); } process.stdout.write('\n Made with ♥️ by the webpack team \n'); } outputVersion() { const pkgJSON = require('../../package.json'); const webpack = require('webpack'); process.stdout.write(`\nwebpack-cli ${pkgJSON.version}`); process.stdout.write(`\nwebpack ${webpack.version}\n`); } run() { const { underline, bold } = chalk.white const o = s => chalk.keyword('orange')(s); const commandLineUsage = require('command-line-usage'); const options = require('../utils/cli-flags'); const title = bold('⬡ ') + underline('webpack') + bold(' ⬡'); const desc = 'The build tool for modern web applications'; const websitelink = ' ' + underline('https://webpack.js.org'); const usage = bold('Usage') + ': ' + '`' + o('webpack [...options] | <command>') + '`'; const examples = bold('Example') + ': ' + '`' + o('webpack help --flag | <command>') + '`'; const hh = ` ${title}\n ${websitelink}\n ${desc}\n ${usage}\n ${examples}\n `; const sections = commandLineUsage([ { content: hh, raw: true, }, { header: 'Available Commands', content: options.commands.map(e => { return { name: e.name, summary: e.description }; }), }, { header: 'Options', optionList: options.core, }, ]); return { outputOptions: { help: sections, }, }; } } module.exports = HelpGroup;
JavaScript
0.000437
@@ -190,16 +190,17 @@ mmand != += null) %7B @@ -325,16 +325,17 @@ .name == += command @@ -350,16 +350,17 @@ alias == += command
a91c95ac46a2f0f0c6a42dfce2822624c2410edd
add a hacky and direct workaround to fix #525
lib/http-server.js
lib/http-server.js
'use strict'; var fs = require('fs'), union = require('union'), ecstatic = require('ecstatic'), auth = require('basic-auth'), httpProxy = require('http-proxy'), corser = require('corser'), secureCompare = require('secure-compare'); // // Remark: backwards compatibility for previous // case convention of HTTP // exports.HttpServer = exports.HTTPServer = HttpServer; /** * Returns a new instance of HttpServer with the * specified `options`. */ exports.createServer = function (options) { return new HttpServer(options); }; /** * Constructor function for the HttpServer object * which is responsible for serving static files along * with other HTTP-related features. */ function HttpServer(options) { options = options || {}; if (options.root) { this.root = options.root; } else { try { fs.lstatSync('./public'); this.root = './public'; } catch (err) { this.root = './'; } } this.headers = options.headers || {}; this.cache = ( options.cache === undefined ? 3600 : // -1 is a special case to turn off caching. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control#Preventing_caching options.cache === -1 ? 'no-cache, no-store, must-revalidate' : options.cache // in seconds. ); this.showDir = options.showDir !== 'false'; this.autoIndex = options.autoIndex !== 'false'; this.showDotfiles = options.showDotfiles; this.gzip = options.gzip === true; this.brotli = options.brotli === true; this.contentType = options.contentType || 'application/octet-stream'; if (options.ext) { this.ext = options.ext === true ? 'html' : options.ext; } var before = options.before ? options.before.slice() : []; before.push(function (req, res) { if (options.logFn) { options.logFn(req, res); } res.emit('next'); }); if (options.username || options.password) { before.push(function (req, res) { var credentials = auth(req); // We perform these outside the if to avoid short-circuiting and giving // an attacker knowledge of whether the username is correct via a timing // attack. if (credentials) { var usernameEqual = secureCompare(options.username, credentials.name); var passwordEqual = secureCompare(options.password, credentials.pass); if (usernameEqual && passwordEqual) { return res.emit('next'); } } res.statusCode = 401; res.setHeader('WWW-Authenticate', 'Basic realm=""'); res.end('Access denied'); }); } if (options.cors) { this.headers['Access-Control-Allow-Origin'] = '*'; this.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Range'; if (options.corsHeaders) { options.corsHeaders.split(/\s*,\s*/) .forEach(function (h) { this.headers['Access-Control-Allow-Headers'] += ', ' + h; }, this); } before.push(corser.create(options.corsHeaders ? { requestHeaders: this.headers['Access-Control-Allow-Headers'].split(/\s*,\s*/) } : null)); } if (options.robots) { before.push(function (req, res) { if (req.url === '/robots.txt') { res.setHeader('Content-Type', 'text/plain'); var robots = options.robots === true ? 'User-agent: *\nDisallow: /' : options.robots.replace(/\\n/, '\n'); return res.end(robots); } res.emit('next'); }); } before.push(ecstatic({ root: this.root, cache: this.cache, showDir: this.showDir, showDotfiles: this.showDotfiles, autoIndex: this.autoIndex, defaultExt: this.ext, gzip: this.gzip, brotli: this.brotli, contentType: this.contentType, handleError: typeof options.proxy !== 'string' })); if (typeof options.proxy === 'string') { var proxy = httpProxy.createProxyServer({}); before.push(function (req, res) { proxy.web(req, res, { target: options.proxy, changeOrigin: true }, function (err, req, res, target) { if (options.logFn) { options.logFn(req, res, { message: err.message, status: res.statusCode }); } res.emit('next'); }); }); } var serverOptions = { before: before, headers: this.headers, onError: function (err, req, res) { if (options.logFn) { options.logFn(req, res, err); } res.end(); } }; if (options.https) { serverOptions.https = options.https; } this.server = union.createServer(serverOptions); } HttpServer.prototype.listen = function () { this.server.listen.apply(this.server, arguments); }; HttpServer.prototype.close = function () { return this.server.close(); };
JavaScript
0
@@ -199,24 +199,52 @@ ('corser'),%0A + path = require('path'),%0A secureCo @@ -279,16 +279,577 @@ are');%0A%0A +// a hacky and direct workaround to fix https://github.com/http-party/http-server/issues/525%0Afunction getCaller() %7B%0A try %7B%0A var stack = new Error().stack;%0A var stackLines = stack.split('%5Cn');%0A var callerStack = stackLines%5B3%5D;%0A return callerStack.match(/at (.+) %5C(/)%5B1%5D;%0A %7D%0A catch (error) %7B%0A return '';%0A %7D%0A%7D%0A%0Avar _pathNormalize = path.normalize;%0Apath.normalize = function (p) %7B%0A var caller = getCaller();%0A var result = _pathNormalize(p);%0A if (caller === 'decodePathname') %7B%0A result = result.replace(/%5C%5C/g, '/');%0A %7D%0A return result;%0A%7D;%0A%0A //%0A// Re
620d5285a7c0d9aed306460d2e58baf633fb692e
Replace mode should only replace first encountered instance
nestableview.js
nestableview.js
/*! * Backbone.CWM.NestableView v0.1.0 * * (c) 2014 Michael Spencer * Released under the MIT license */ ;(function(exports, BaseView) { var NestableView = BaseView.extend({ template: _.template('[NestableView:{data:<%- JSON.stringify(data) %>}]'), views: function() { return []; }, constructor: function(options) { if (options && options.views) { this.views = options.views; delete options.views; } if (_.isObject(this.views)) { this.views = _.result(this, 'views'); } BaseView.apply(this, arguments); }, renderTemplate: function(data) { data = data || (this.model && this.model.toJSON()) || {}; return this.template({ data: data }); }, addView: function(selector, view, replace) { var meta = { selector: selector || '', view: view, replace: !!replace, renderEnabled: true, attachEnabled: true }; if (!this.views) { this.views = []; } this.views.push(meta); return meta; }, detachViews: function() { // Detach child views (in reverse order) if (this.views && this.views.length) { var viewFragments = {}; for (var i = this.views.length - 1; i >= 0; i--) { var meta = this.views[i]; var selector = meta.selector || ''; if (meta.replace && selector) { // Attached views meta.view.$el.detach(); } else { // Nested views if (!('attachEnabled' in meta) || meta.attachEnabled) { var viewFragment = viewFragments[selector]; if (!viewFragment) { viewFragment = document.createDocumentFragment(); viewFragments[selector] = viewFragment; } // insert at beginning since we are iterating backwards viewFragment.insertBefore(meta.view.el, viewFragment.firstChild); } else { meta.view.$el.detach(); } } } this._viewFragments = viewFragments; } }, renderViews: function() { if (this.views && this.views.length) { _.each(this.views, function(meta) { if (!('renderEnabled' in meta) || meta.renderEnabled) { meta.view.render(); } }); } }, attachViews: function() { // Attach child views if (this.views && this.views.length) { _.each(this.views, function(meta) { if (!('attachEnabled' in meta) || meta.attachEnabled) { var selector = meta.selector || ''; var $selectorEl = selector ? this.$el.find(selector) : this.$el; if ($selectorEl.length) { if (meta.replace && selector) { // Attached views // Replace the selector element with the view element $selectorEl.replaceWith(meta.view.el); } else { // Nested views // Append the fragment to the selector element (if it hasn't already been added) var viewFragment = this._viewFragments[selector]; if (viewFragment) { $selectorEl.append(viewFragment); delete this._viewFragments[selector]; } } } } }, this); } delete this._viewFragments; }, render: function(data) { this.undelegateEvents(); this.detachViews(); this.$el.html(this.renderTemplate(data)); this.renderViews(); this.attachViews(); this.delegateEvents(); return this; } }); exports.NestableView = NestableView; }.call(this, Backbone.CWM = Backbone.CWM || {}, Backbone.View));
JavaScript
0
@@ -2714,32 +2714,81 @@ torEl.length) %7B%0A + $selectorEl = $selectorEl.first();%0A if
466c13b3fc9a62ef0a6fe87619f6c9c3beda298a
Fix support of fill option.
lib/image-proxy.js
lib/image-proxy.js
// @see https://devcenter.heroku.com/articles/nodejs#write-your-app var express = require('express') , fs = require('fs') // node , gm = require('gm') , http = require('http') // node , https = require('https') // node , mime = require('mime') , url = require('url') // node // @see http://aaronheckmann.posterous.com/graphicsmagick-on-heroku-with-nodejs , app = express() , imageMagick = gm.subClass({imageMagick: true}) , whitelist = process.env.WHITELIST || [] // [/\.gov$/, /google\.com$/] , delay = parseInt(process.env.DELAY) || 5000 , mimeTypes = [ 'image/gif', 'image/jpeg', 'image/png', // Common typos 'image/jpg' ]; function retrieveRemote(res, next, remote, width, height, extension) { console.log('DEBUG - remote=' + remote); console.log('DEBUG - width=' + width); console.log('DEBUG - height=' + height); // @see http://nodejs.org/api/url.html#url_url var options = url.parse(remote); // @see https://github.com/substack/hyperquest options.agent = false; if (options.protocol !== 'http:' && options.protocol !== 'https:') { return res.status(404).send('Expected URI scheme to be HTTP or HTTPS'); } if (!options.hostname) { return res.status(404).send('Expected URI host to be non-empty'); } options.headers = {'User-Agent': 'image-proxy/0.0.6'} var agent = options.protocol === 'http:' ? http : https , timeout = false // @see http://nodejs.org/api/http.html#http_http_get_options_callback , request = agent.get(options, function (response) { if (timeout) { // Status code 504 already sent. return; } // @see http://nodejs.org/api/http.html#http_response_statuscode if ((response.statusCode === 301 || response.statusCode === 302) && response.headers['location']) { var redirect = url.parse(response.headers['location']); // @see https://tools.ietf.org/html/rfc7231#section-7.1.2 if (!redirect.protocol) { redirect.protocol = options.protocol; } if (!redirect.hostname) { redirect.hostname = options.hostname; } if (!redirect.port) { redirect.port = options.port; } if (!redirect.hash) { redirect.hash = options.hash; } return retrieveRemote(res, next, url.format(redirect), weight, height, extension); } // The image must return status code 200. if (response.statusCode !== 200) { return res.status(404).send('Expected response code 200, got ' + response.statusCode); } // The image must be a valid content type. // @see http://nodejs.org/api/http.html#http_request_headers var mimeType; if (extension) { mimeType = mime.lookup(extension); } else { mimeType = (response.headers['content-type'] || '').replace(/;.*/, ''); extension = mime.extension(mimeType); } if (mimeTypes.indexOf(mimeType) === -1) { return res.status(404).send('Expected content type ' + mimeTypes.join(', ') + ', got ' + mimeType); } // @see https://github.com/aheckmann/gm#constructor var im = imageMagick(response, 'image.' + extension); // @see http://www.imagemagick.org/Usage/thumbnails/#cut // Avoid resizing gif, any git, since resizing animated gifs does not work properly. if (mimeType !== 'image/gif') { if (width && width !== 'undefined') { if (height && height !== 'undefined') { im.resize(width, height, '>'); } else { im.resize(width, null, '>'); } } else if (height && height !== 'undefined') { im.resize(null, height, '>'); } } im.gravity('Center'); // faces are most often near the center if (width && height && width !== 'undefined' && height !== 'undefined') { im.extent(width, height); } im.stream(function (err, stdout, stderr) { if (err) return next(err); // Log errors in production. stderr.pipe(process.stderr); // @see http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html res.writeHead(200, { 'Content-Type': mimeType, 'Cache-Control': 'max-age=31536000, public', // 1 year }); stdout.pipe(res); }); }).on('error', next); // Timeout after five seconds. Better luck next time. request.setTimeout(delay, function () { timeout = true; // if we abort, we'll get a "socket hang up" error return res.status(504).send(); }); } function handleRequest(req, res, next, width, height, extension) { // Validate parameters. if (whitelist.length) { var parts = url.parse(req.params.url); if (parts.hostname) { var any = false, _i, _len; if (typeof whitelist === 'string') { whitelist = whitelist.split(','); } for (_i = 0, _len = whitelist.length; _i < _len; _i++) { if (typeof whitelist[_i] === 'string') { // Escape periods and add anchor. whitelist[_i] = new RegExp(whitelist[_i].replace('.', '\\.') + '$') } if (whitelist[_i].test(parts.hostname)) { any = true; break; } } if (!any) { // if none return res.status(404).send('Expected URI host to be whitelisted'); } } } retrieveRemote(res, next, 'http://s3.amazonaws.com/qmerce-static-media/' + req.params.url, width, height, extension); } module.exports = function () { app.get('/:url', function (req, res, next) { var defaultWidth = 1200; handleRequest(req, res, next, defaultWidth, null, null); }); app.get('/:url/:width/:height.:extension?', function (req, res, next) { var width = req.params.width , height = req.params.height , extension = req.params.extension; if (isNaN(parseInt(width)) && width !== 'undefined') { return res.status(404).send('Expected width to be an integer'); } if (isNaN(parseInt(height)) && height !== 'undefined') { return res.status(404).send('Expected height to be an integer'); } handleRequest(req, res, next, width, height, extension); }); return app; };
JavaScript
0
@@ -3653,32 +3653,33 @@ width, height, ' +%5E %3E');%0A @@ -3718,22 +3718,16 @@ e(width, - null, '%3E');%0A @@ -3833,16 +3833,17 @@ eight, ' +%5E %3E');%0A
31f26b2adfede0b2abeea349458514ab43912384
change port
SevernStatus.Server/server.js
SevernStatus.Server/server.js
var http = require('http'); var requestImport = require('request'); var url = require('url'); var xpath = require('xpath') var dom = require('xmldom').DOMParser const PORT=5001; //We need a function which handles requests and send response function handleRequest(request, response){ if( request.url.indexOf('favicon.ico') > -1) { console.log('facicon request cancelled'); response.end(); return; } var queryData = url.parse(request.url, true).query; var road = queryData.road.toUpperCase(); requestImport('http://hatrafficinfo.dft.gov.uk/feeds/datex/England/UnplannedEvent/content.xml', function (error, innerResponse, body) { //console.log('Inside request body'); // //console.log('' + innerResponse ==null); //console.log('error:' + error); //console.log('statusCode' + innerResponse.statusCode); if (!error && innerResponse.statusCode === 200) { console.log('200 OK'); var xml = body.replace('&nbsp;','').replace('&copy;','').replace(' xmlns="http://datex2.eu/schema/1_0/1_0" modelBaseVersion="1.0"', ''); //console.log(xml); console.log("contains " + road + ": " + (xml.indexOf(road) > -1)); var doc = new dom().parseFromString(xml); //console.log(doc); var nodes = xpath.select('//situation[.//groupOfLocations//descriptor/value="' + road + '"]//nonGeneralPublicComment/comment/value', doc); console.log('length: ' + nodes.length); if(nodes.length===0) { console.log("No notifications found for " + road); response.end("No notifications found for " + road); return; } console.log('nodes[0].data: ' + nodes[0].firstChild.data); // console.log("node: " + nodes[0].toString()) response.end(nodes[0].firstChild.data); } }); } //Create a server var server = http.createServer(handleRequest); //Lets start our server server.listen(PORT, function(){ console.log("Server listening on port: %s", PORT); });
JavaScript
0.000001
@@ -170,17 +170,17 @@ PORT=500 -1 +0 ; %0A%0A%0A%0A//
9c14912c6826d0631669692dabe1df4947c16693
Work around for buggy oninput in IE9.
src/pat/edit-tinymce.js
src/pat/edit-tinymce.js
define([ "jquery", "../core/parser", "../core/logger", "../registry", "../utils", "jquery.textchange", "tinymce" ], function($, Parser, logger, registry, utils) { var log = logger.getLogger("pat.editTinyMCE"), parser = new Parser("edit-tinymce"); parser.add_argument("tinymce-baseurl"); var _ = { name: "editTinyMCE", trigger: "form textarea.pat-edit-tinymce", init: function($el, opts) { var $form = $el.parents("form"), id = $el.attr("id"); // make sure the textarea has an id if (!id) { var formid = $form.attr("id"), name = $el.attr("name"); if (!formid) { log.error("Textarea or parent form needs an id", $el, $form); return false; } if (!name) { log.error("Textarea needs a name", $el); return false; } id = formid + "_" + name; if ($("#"+id).length > 0) { log.error("Textarea needs an id", $el); return false; } $el.attr({id: id}); } // read configuration var cfg = $el.data("tinymce-json"); if (!cfg) { log.info("data-tinymce-json empty, using default config", $el); cfg = {}; } cfg.elements = id; cfg.mode = "exact"; cfg.readonly = Boolean($el.attr("readonly")); // get arguments var args = parser.parse($el, opts); if (!args.tinymceBaseurl) { log.error("tinymce-baseurl has to point to TinyMCE resources"); return false; } var base_url = window.location.toString(), idx; if ((idx=base_url.indexOf("?"))!==-1) base_url=base_url.slice(0, idx); // handle rebasing of own urls if we were injected var parents = $el.parents().filter(function() { return $(this).data("pat-injected"); }); if (parents.length) base_url = utils.rebaseURL(base_url, parents.first().data("pat-injected").origin); if (cfg.content_css) cfg.content_css = utils.rebaseURL(base_url, cfg.content_css); if (args.tinymceBaseurl.indexOf("://")!==-1 || args.tinymceBaseurl[0]==="/") { // tinyMCE.baseURL must be absolute tinyMCE.baseURL = window.location.protocol + '//' + window.location.host+'/' + args.tinymceBaseurl; } else { tinyMCE.baseURL = utils.rebaseURL(base_url, args.tinymceBaseurl); } tinyMCE.baseURI = new tinyMCE.util.URI(tinyMCE.baseURL); cfg.oninit = function() { var $tinymce, $tinyifr; // find tiny's iframe and edit field $tinyifr = $("#" + id + "_ifr"); $tinymce = $tinyifr.contents().find("#tinymce"); // XXX: add events for undo, redo, ... if ("oninput" in window) { $tinymce.on("input.pat-tinymce", function() { log.debug('translating tiny input'); tinyMCE.editors[id].save(); $el.trigger("input-change"); }); } else { // this is the legacy code path for IE8 $tinymce.on("change.pat-tinymce textchange.pat-tinymce", function() { log.debug('translating tiny change and textchange'); tinyMCE.editors[id].save(); $el.trigger("input-change"); }); } }; // initialize editor tinyMCE.init(cfg); return $el; }, destroy: function() { // XXX } }; registry.register(_); return _; }); // jshint indent: 4, browser: true, jquery: true, quotmark: double // vim: sw=4 expandtab
JavaScript
0
@@ -2443,28 +2443,16 @@ t_css);%0A - %0A @@ -3251,16 +3251,82 @@ n window + %7C%7C%0A ($.browser.msie && $.browser.version %3C 10) ) %7B%0A @@ -3699,27 +3699,8 @@ on(%22 -change.pat-tinymce text
c0b8247358cafd13a107428a66e9691a19d6df54
Fix regression in buildModuleUrl.
Source/Core/buildModuleUrl.js
Source/Core/buildModuleUrl.js
/*global define*/ define([ 'require', './defined', './DeveloperError', '../ThirdParty/Uri' ], function( require, defined, DeveloperError, Uri) { "use strict"; /*global CESIUM_BASE_URL*/ var cesiumScriptRegex = /((?:.*\/)|^)cesium[\w-]*\.js(?:\W|$)/i; function getBaseUrlFromCesiumScript() { var scripts = document.getElementsByTagName('script'); for ( var i = 0, len = scripts.length; i < len; ++i) { var src = scripts[i].getAttribute('src'); var result = cesiumScriptRegex.exec(src); if (result !== null) { return result[1]; } } return undefined; } var baseUrl; function getCesiumBaseUrl() { if (defined(baseUrl)) { return baseUrl; } var baseUrlString; if (typeof CESIUM_BASE_URL !== 'undefined') { baseUrlString = CESIUM_BASE_URL; } else { baseUrlString = getBaseUrlFromCesiumScript(); } if (!defined(baseUrl)) { throw new DeveloperError('Unable to determine Cesium base URL automatically, try defining a global variable called CESIUM_BASE_URL.'); } baseUrl = new Uri(baseUrlString).resolve(new Uri(document.location.href)); return baseUrl; } function buildModuleUrlFromRequireToUrl(moduleID) { //moduleID will be non-relative, so require it relative to this module, in Core. return require.toUrl('../' + moduleID); } function buildModuleUrlFromBaseUrl(moduleID) { return new Uri(moduleID).resolve(getCesiumBaseUrl()).toString(); } var implementation; var a; /** * Given a non-relative moduleID, returns an absolute URL to the file represented by that module ID, * using, in order of preference, require.toUrl, the value of a global CESIUM_BASE_URL, or * the base URL of the Cesium.js script. * * @private */ var buildModuleUrl = function(moduleID) { if (!defined(implementation)) { //select implementation if (defined(require.toUrl)) { implementation = buildModuleUrlFromRequireToUrl; } else { implementation = buildModuleUrlFromBaseUrl; } } if (!defined(a)) { a = document.createElement('a'); } var url = implementation(moduleID); a.href = url; a.href = a.href; // IE only absolutizes href on get, not set return a.href; }; // exposed for testing buildModuleUrl._cesiumScriptRegex = cesiumScriptRegex; return buildModuleUrl; });
JavaScript
0
@@ -1083,32 +1083,38 @@ !defined(baseUrl +String )) %7B%0A
240d90b1bbde53a32e55dc49075ab6adf76e0018
update tests to acommodate new api structure
tests/search.spec.js
tests/search.spec.js
var chai = require('chai'), chaiHttp = require('chai-http'), server = require('../server/app'), should = chai.should(); chai.use(chaiHttp); describe('Search', function(){ it('should return a 200 status code', function(done){ chai.request(server) .get('/search') .end(function(err, res){ res.should.have.status(200); done(); }) }); it('should return a list of N results', function(done){ var n = 5; chai.request(server) .get('/search') .query({limit:n}) .query({type: 'artist', genre: 'rap'}) .end(function(err, res){ res.should.have.lengthOf(n); done(); }) }); it('should return no more than 20 results if no limit is specified', function(done){ chai.request(server) .get('/search') .query({limit:''}) .query({type: 'artist', genre: 'rap'}) .end(function(err, res){ res.should.have.length.below(21); done(); }) }); describe('Artists', function(){ it('should get a list of Artists by genre')//, function(done){ // chai.request(server) // .get('/search/artists') // .query({type: 'artist', genre: 'pop'}) // .end(function(err, res){ // res.should.have.status(200); // done(); // }) // }); it('should get a list of Artists that match a name'); }); describe('Albums', function(){ // search/albums it('should get a list of albums by genre'); it('should get a list of albums that match a certain name'); }) })
JavaScript
0
@@ -95,16 +95,40 @@ /app'),%0A +%09expect%09%09= chai.expect,%0A %09should @@ -491,28 +491,8 @@ h')%0A -%09%09.query(%7Blimit:n%7D)%0A %09%09.q @@ -509,36 +509,32 @@ : 'artist', -genre: 'rap' +limit: n %7D)%0A%09%09.end(fu @@ -550,34 +550,38 @@ r, res)%7B%0A%09%09%09 -res.should +expect(res).to .have.length @@ -587,11 +587,10 @@ hOf( -n); +5) %0A%09%09%09 @@ -597,24 +597,25 @@ done();%0A%09%09%7D) +; %0A%0A%09%7D);%0A%09it(' @@ -785,22 +785,8 @@ ist' -, genre: 'rap' %7D)%0A%09 @@ -875,533 +875,6 @@ );%0A%0A -%09describe('Artists', function()%7B%0A%0A%09%09it('should get a list of Artists by genre')//, function(done)%7B%0A%09%09%09// chai.request(server)%0A%09%09%09// .get('/search/artists')%0A%09%09%09// .query(%7Btype: 'artist', genre: 'pop'%7D)%0A%09%09%09// .end(function(err, res)%7B%0A%09%09%09// %09res.should.have.status(200);%0A%09%09%09// %09done();%0A%09%09%09// %7D)%0A%09%09// %7D);%0A%09%09it('should get a list of Artists that match a name');%0A%09%7D);%0A%0A%09describe('Albums', function()%7B%0A%09%09// search/albums%0A%09%09it('should get a list of albums by genre');%0A%09%09it('should get a list of albums that match a certain name');%0A%09%7D)%0A %7D)
40ec777c8a53da1eca2a3ec87bf4a7a2fb7ddaf0
fix lint
lib/merge-files.js
lib/merge-files.js
'use strict'; // We need the yui name to be available in all modules (as a global variable). // This only happens if we remove the 'var' keyword or add it to the "global" // variable. global.YUI = require('yui').YUI; var path = require('path'); var child_process = require('child_process'); var UglifyJS = require('uglify-js'); YUI().use(['yui'], function(Y) { var fs = require('fs'), syspath = require('path'), compressor = require('node-minify'); function throw_error(err) { if (err) { throw err; } } // Combine one or more CSS files. function combineCSS(files, outputFile) { var unused = new compressor.minify({ type: 'sqwish', fileIn: files, fileOut: outputFile, callback: throw_error }); } exports.combineCSS = combineCSS; // Combine one or more JavaScript files. function combineJs(files, outputFile) { var sourceMapName = syspath.basename(outputFile) + '.map'; // We feed the minifier relative path names so the source map will map to // relative URLs that can be easily served. var relative_files = []; Y.Array.each(files, function(inputFile) { relative_files.push(syspath.relative(process.cwd(), inputFile)); }); var result = UglifyJS.minify(relative_files, { compress: false, mangle: false, outSourceMap: sourceMapName, sourceRoot: 'source' }); // The uglifyjs script does this instead of the library, so we have to do // it ourselves since we are using uglify as a library and not a script. result.code += "\n//@ sourceMappingURL=" + sourceMapName; fs.writeFileSync(outputFile, result.code, 'utf8', throw_error); fs.writeFileSync(sourceMapName, result.map, 'utf8', throw_error); } exports.combineJs = combineJs; // It gets the name of all the files under 'path', recursively. It ignores // files and directories included in the "ignore" array. These will // typically be set to ignore our assets and our module file. function readdir(path, ignore) { var result = []; // These are the filenames we will return. var dirs = []; // These are the directories into which we will recurse. var files = fs.readdirSync(path); ignore = ignore || []; function shouldNotIgnore(fileName) { return ignore.indexOf(fileName) === -1; } function isJavascriptFile(fileName) { return syspath.extname(fileName).toLowerCase() === '.js'; } Y.Array.each(files, function(value) { var fileName, file; fileName = path + '/' + value; file = fs.statSync(fileName); if (shouldNotIgnore(fileName)) { if (file.isFile() && isJavascriptFile(fileName)) { result.push(fileName); } else if (file.isDirectory()) { dirs.push(fileName); } } }); // We have read all the filenames and all the directory names. Now // it is time to recurse into the directories that we have collected. Y.Array.each(dirs, function(directory) { result.push.apply(result, readdir(directory, ignore)); }); return result; } exports.readdir = readdir; // It reads the YUI 'requires' attribute of all our custom js files // (as assembled by readdir) and returns the YUI modules on which we // directly depend. function loadRequires(paths) { var originalAdd, modules, yuiReqs; modules = {}; originalAdd = YUI.add; // This is a trick to get the 'requires' value from the module // definition. YUI.add = function(name, fn, version, details) { if (details && details.requires) { modules[name] = details.requires; } }; Y.Array.each(paths, function(path) { // It triggers the custom 'add' method above require(path); }); YUI.add = originalAdd; // Getting all the YUI dependencies that we need yuiReqs = []; Y.Object.each(modules, function(requires) { Y.Array.each(requires, function(value) { if (!modules[value]) { // This is not one of our modules but a yui one. if (yuiReqs.indexOf(value) < 0) { // avoid duplicates yuiReqs.push(value); } } }); }); return yuiReqs; } exports.loadRequires = loadRequires; // Using the example http://yuilibrary.com/yui/docs/yui/loader-resolve.html // Given a list of direct YUI requirements, return the filenames of these // modules and their dependencies (indirect and direct). function getYUIFiles(reqs) { var loader, out; // The loader automatically handles following our dependencies. loader = new Y.Loader({ // The base tells the loader where to look for the YUI files. We // look directly in the npm YUI package, but we could just as well look // in the symbolic link app/assets/javascripts/yui. base: './node_modules/yui/', ignoreRegistered: true, filter: 'RAW', // We do not want minified source because we minify it in // uglify, when we also produce the source maps. require: reqs}); out = loader.resolve(true); return out; } exports.getYUIFiles = getYUIFiles; });
JavaScript
0.000013
@@ -1565,17 +1565,17 @@ code += -%22 +' %5Cn//@ so @@ -1589,17 +1589,17 @@ pingURL= -%22 +' + sourc
245c9e7ad3b9ce038881ab97346d7eee1dc01d24
fix bug with sciebo public shares
controllers/download.js
controllers/download.js
/* * (C) Copyright 2016 o2r project * * 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. * */ // General modules var c = require('../config/config'); var debug = require('debug')('loader'); var fs = require('fs'); var Compendium = require('../lib/model/compendium'); var Loader = require('../lib/loader').Loader; var url = require('url'); var validator = require('validator'); exports.create = (req, res) => { // check user level if (!req.isAuthenticated()) { res.status(401).send('{"error":"user is not authenticated"}'); return; } if (req.user.level < c.user.level.create_compendium) { res.status(401).send('{"error":"user level does not allow compendium creation"}'); return; } // check for ZENODO url -> start zenodo loader if(req.body.zenodo_url !== null){ //start zenodo loader // validate zenodo_url if(!validator.isURL(req.body.zenodo_url)) { debug('Invalid zenodo_url:', req.body.zenodo_url); res.status(404).send('{"error":"zenodo URL is invalid"}'); return; } if (!req.body.filename) { // validate filename parameter exists debug('Filename missing'); res.status(404).send('{"error":"filename is missing"}'); return; } // get zenodo record ID from Zenodo URL // e.g. https://sandbox.zenodo.org/record/59917 // todo: accept DOI, zenodo record id as well -> parser let parsedURL = url.parse(req.body.zenodo_url); let zenodoPaths = parsedURL.path.split('/'); let zenodoID = zenodoPaths[zenodoPaths.length - 1]; req.body.zenodo_id = zenodoID; //validate host (must be zenodo or sandbox.zenodo) switch (parsedURL.host) { case 'sandbox.zenodo.org': req.body.base_url = c.zenodo.sandbox_url; break; case 'zenodo.org': req.body.base_url = c.zenodo.url; break; default: debug('Invalid hostname:', parsedURL.host); res.status(403).send('{"error":"host is not allowed"}'); return; } // validate zenodoID if (!validator.isNumeric(String(zenodoID))){ debug('Invalid zenodoID:', zenodoID); res.status(404).send('{"error":"zenodo ID is not a number"}'); return; } // validate content_type if (req.body.content_type === 'compendium_v1') { debug('Creating new %s for user %s)', req.body.content_type, req.user.id); var loader = new Loader(req, res); loader.loadZenodo((id, err) => { if (err) { debug('Error during public share load: %s', err.message); } else { debug('New compendium %s successfully loaded', id); } }); } else { res.status(500).send('Provided content_type not yet implemented, only "compendium_v1" is supported.'); debug('Provided content_type "%s" not implemented', req.body.content_type); } return; } // validate share_url if(!validator.isURL(req.body.share_url)) { debug('Invalid share_url:', req.body.share_url); res.status(404).send('{"error":"public share URL is invalid"}'); return; } // only allow sciebo shares, see https://www.sciebo.de/de/login/index.html let validURL = url.parse(req.body.share_url); let hostname = validURL.hostname.split('.'); hostname = hostname[hostname.length - 2]; if (c.webdav.allowedHosts.indexOf(hostname) === -1) { //if hostname is not in allowedHosts debug('Public share host "%s" is not allowed.', hostname); res.status(403).send('{"error":"public share host is not allowed"}'); debug('public share host is not allowed, supported is: %s', c.webdav.allowedHosts.toString()); return; } if (!req.body.path) { // set default value for path ('/') req.body.path = '/'; } // validate content_type if (req.body.content_type === 'compendium_v1') { debug('Creating new %s for user %s)', req.body.content_type, req.user.id); var loader = new Loader(req, res); loader.load((id, err) => { if (err) { debug('Error during public share load: %s', err.message); } else { debug('New compendium %s successfully loaded', id); } }); } else { res.status(500).send('Provided content_type not yet implemented, only "compendium_v1" is supported.'); debug('Provided content_type "%s" not implemented', req.body.content_type); } };
JavaScript
0
@@ -1210,24 +1210,87 @@ eturn;%0A %7D%0A%0A + //TODO here: write function for webdav and zenodo + cleanup%0A%0A // check f @@ -1359,12 +1359,17 @@ !== -null +undefined )%7B%0A
d95aa512bedfb87f5e52af99e3827ad377226576
minus 1
controllers/homeCtrl.js
controllers/homeCtrl.js
var express = require('express'); var router = express.Router(); var jsonfile = require('jsonfile') var MongoClient = require('mongodb').MongoClient var url = 'mongodb://localhost:27017/Measurements'; exports.index = (req, res) => { getBuilding(res, getPies); }; function getPies(res, buildings){ MongoClient.connect(url, function(err, db){ if(err){ console.log('error:' + err); } else{ var collection = db.collection('Pi'); collection.find().toArray(function(err, result){ if(err){ res.send(err); } else if(result.length){ console.log('and the number is ********' + result.length) res.render('home', {title: 'Home', buildings : buildings, pies : result, readings : {} }); } else{ res.send('no thing found'); } }) } db.close(); }); } function getBuilding(res, callback){ MongoClient.connect(url, function(err, db){ if(err){ console.log('error:' + err); } else{ var collection = db.collection('Building'); collection.find().toArray(function(err, result){ if(err){ res.send(err); } else if(result.length){ console.log('and the number is ********' + result.length) callback(res, result) } else{ res.send('no thing found'); } }) } db.close(); }); } exports.getReadings = (req, res) => { var buildingId = req.body.building; var piId = req.body.pi; var sensor = req.body.sensor; var batch = parseInt(req.body.batch); MongoClient.connect(url, function(err, db){ if(err){ console.log('error:' + err); } else{ var collection = db.collection(sensor); collection.find({"ip": piId}).sort({"createdAt":-1}).limit(batch).toArray(function(err, result){ if(err){ res.send(err); } else if(result.length){ console.log('and the number is ********' + result.length) res.render('partials/valTable', { readings : result }); } else{ res.send('no thing found'); } }) } db.close(); }); }; exports.getPies = (req, res) => { var building = req.body.building; MongoClient.connect(url, function(err, db){ if(err){ console.log('error:' + err); } else{ var collection = db.collection("Pi"); collection.find({"group": building}).toArray(function(err, result){ if(err){ res.send(err); } else if(result.length){ console.log('and the number is ********' + result.length) res.render('home', {title: 'Home', pies : result, readings : {} }); } else{ res.send('no thing found'); } }) } db.close(); }); } // .sort({"group": building})
JavaScript
0.999994
@@ -2069,9 +2069,8 @@ At%22: -- 1%7D). @@ -2258,32 +2258,49 @@ d the number is +from getReadings ********' + resu
1e22bd5d47d74153f498c04c06ae1878e0725293
fix compilation of named route functions
lib/namedroutes.js
lib/namedroutes.js
var _ = require('underscore'); var assert = require('assert'); var path = require('path'); //expand source and target then merge, //if source and target are both have route recurse //XXX if one or the the have route replace target with source //otherwise merge source keys into target, if source key has falsy value, remove the key //if handle is being added assume its the current app unless app is specified? function update(app, target, source) { for (var prop in source) { if (!source.hasOwnProperty(prop)) continue; var def = expandDefinition(app, prop, source[prop]); if (prop in target) { if (!def) { delete target[prop]; } else if (def.route) { debugger; //XXX } else if (def.pathonly) { target[prop].path = def.path; } else { //use defaults() instead of extends() so undefined are skipped target[prop] = _.defaults({}, def, target[prop]); } } else if (!def.pathonly) { if (typeof def.path === 'undefined') def.path = prop; //use name as path target[prop] = def; } } return target; } function applyRoute(route, base, pre) { base = base || '/'; if (base.slice(-1) != '/') base += '/'; var path = base + route.path; if (pre) route = pre(route); if (route.route) { //nested routes applyRoutes(route.route, path, pre); } else { var app = route.app; assert(app); for (var key in route) { if (key == "path" || key == 'app' || !app[key]) continue; //call app.METHOD(path, ...route[METHOD]): app[key].apply(app, [path].concat(route[key])); } } } function applyRoutes(routes, base, pre) { for (var route in routes) { if (!routes.hasOwnProperty(route)) continue; applyRoute(routes[route], base, pre); } } module.exports = NamedRoutes = function() {} NamedRoutes.prototype = { //XXXs use PATH_REGEXP in https://github.com/component/path-to-regexp/blob/master/index.js for a complete solution PARAMREGEX: /(?:[^\\]|^)\:(\w+)/, applyRoutes: function(pre) { if (pre && Array.isArray(pre)) { if (pre.length) { //chain functions pre = pre.reduce(function(ff, f) { return function(route) { return ff(f(route));}}); } else { pre = null; } } return applyRoutes(this, null, pre); }, updateRoutes: function(app, source) { return update(app, this, source); }, getUrlMap: function() { var PARAMREGEX = this.PARAMREGEX, PARAMREGEXG = new RegExp(PARAMREGEX.source, 'g'); return _.object(_.map(this, function(value, key){ var urlpath = path.join('/', value.path); var resolved; if (value.path.match(PARAMREGEX)) { //generate a function that builds the url given an object resolved = function(obj) { return urlpath.replace(PARAMREGEXG, function(param) { return obj[param]; }); } } else { resolved = urlpath; } return [key, resolved]; })); }, getUrlMapSource: function() { var PARAMREGEX = this.PARAMREGEX; return JSON.stringify(_.object(_.map(this, function(value, key){ var urlpath = path.join('/', value.path); var resolved; if (value.path.match(PARAMREGEX)) { resolved = "@@@"+ urlpath + "@@@"; } else { resolved = urlpath; } return [key, resolved]; }))).replace(/"@@@(.+?)@@@"/g, 'function(obj) {return "$1".replace(/' + PARAMREGEX.source +'/g, function(param) { return obj[param];});}' ); } }; /* If path is omitted the name of the route is used as the path If method is ommitted, GET is used */ function expandDefinition(app, name, route) { if (!route) return null; if (typeof route === 'function') { return { app: app, get: [route] } } else if (Array.isArray(route)) { var path = undefined, funcs; if (typeof route[0] !== 'string') { funcs = route; } else { path = route[0]; funcs = route.slice(1); } return { app: app, path: path, get: funcs } } else if (route.route) { //nested routes debugger; //XXX } else { var def = { app: app, path: route.path }; var found = false; for (var key in route) { if (key == "path" || key == 'app' || !app[key]) continue; def[key] = (!route[key] || Array.isArray(route[key])) ? route[key] : [route[key]]; found = true; } if (!found) { def.pathonly = true; if (typeof route.path === 'undefined') def.path = name } return def; } }
JavaScript
0.000001
@@ -2114,17 +2114,17 @@ GEX: /(? -: += %5B%5E%5C%5C%5D%7C%5E) @@ -2988,16 +2988,22 @@ on(param +, name ) %7B%0A @@ -3023,21 +3023,20 @@ urn obj%5B -par +n am +e %5D;%0A @@ -3680,20 +3680,19 @@ nction(p -aram +, n ) %7B retu @@ -3698,21 +3698,17 @@ urn obj%5B -param +n %5D;%7D);%7D'%0A
e60cddd798827804c24370321be8d5146d4a22e9
check ngrok binary file existence
lib/ngrok/index.js
lib/ngrok/index.js
/** * Ngrok wrapper script * http://www.ngrok.com * * it will generate random subdomain if you don't provide subdomain name in -subdomain svh option * * Created by Equan Pr. on 10/12/13. */ var spawn = require('child_process').spawn , message = require('../middleware/message') , generator = require('../middleware/randname') , arg_log = '-log=stdout' , argsArray = [] , ngrok_output , ngrok_subdomain; exports.expose = function (options) { argsArray.push(arg_log); if (options.auth !== '') argsArray.push('-httpauth=' + options.auth); if (options.subdomain !== null) { argsArray.push('-subdomain=' + options.subdomain); ngrok_output = 'ngrok url at http://' + options.subdomain + '.ngrok.com'; message.output(ngrok_output); ngrok(options, argsArray); } else { // take random name so ngrok will always use words generator.generate(function (err, words) { ngrok_subdomain = words; ngrok_output = 'ngrok url at http://' + ngrok_subdomain + '.ngrok.com'; message.output(ngrok_output); argsArray.push('-subdomain=' + ngrok_subdomain); ngrok(options, argsArray); }); } } var ngrok = function (options, argsArray) { argsArray.push(options.port); var ngrokproc = spawn(options.ngrokpath, argsArray, {detached: true, stdio: 'ignore'}); ngrokproc.on('close', function (code) { // cleanup }); }
JavaScript
0
@@ -331,24 +331,49 @@ /randname')%0A + , fs = require('fs')%0A , arg_lo @@ -488,25 +488,261 @@ (options) %7B%0A -%0A + if (fs.exists(options.ngrokpath, function (exist) %7B%0A exist ? startngrok(options) : message.output('ngrok not found...%5Cn please download from https://ngrok.com/download');%0A %7D));%0A%7D;%0A%0Avar startngrok = function (options) %7B%0A argsArra @@ -758,16 +758,20 @@ g_log);%0A + if ( @@ -837,24 +837,28 @@ auth);%0A%0A + + if (options. @@ -875,24 +875,28 @@ !== null) %7B%0A + args @@ -942,32 +942,36 @@ omain);%0A + ngrok_output = ' @@ -1028,32 +1028,36 @@ k.com';%0A + + message.output(n @@ -1070,32 +1070,36 @@ utput);%0A + ngrok(options, a @@ -1105,24 +1105,28 @@ argsArray);%0A + %7D else %7B @@ -1134,16 +1134,20 @@ + // take @@ -1197,16 +1197,20 @@ + generato @@ -1252,24 +1252,28 @@ + + ngrok_subdom @@ -1285,16 +1285,20 @@ words;%0A + @@ -1377,32 +1377,36 @@ m';%0A + message.output(n @@ -1423,32 +1423,36 @@ t);%0A + + argsArray.push(' @@ -1488,32 +1488,36 @@ n);%0A + ngrok(options, a @@ -1539,24 +1539,37 @@ + + %7D);%0A + %7D%0A -%7D%0A%0Avar + %7D%0A , ngr @@ -1606,24 +1606,28 @@ ray) %7B%0A%0A + + argsArray.pu @@ -1641,24 +1641,28 @@ ons.port);%0A%0A + var ngro @@ -1738,24 +1738,28 @@ ignore'%7D);%0A%0A + ngrokpro @@ -1798,16 +1798,20 @@ + + // clean @@ -1817,13 +1817,21 @@ nup%0A -%7D);%0A + %7D);%0A %7D
d0632143b36edb56d0306793216b8026b351091a
Fix typo
lib/parser/name.js
lib/parser/name.js
/*! * Snakeskin * https://github.com/SnakeskinTpl/Snakeskin * * Released under the MIT license * https://github.com/SnakeskinTpl/Snakeskin/blob/master/LICENSE */ import { $C } from '../deps/collection'; import { Parser } from './constructor'; import { ALIASES } from '../consts/cache'; import { applyDefEscape } from '../helpers/escape' /** * Returns a real directive name * * @param {?string} name - the source name * @return {?string} */ Parser.prototype.getDirName = function (name) { return ALIASES[name] || name; }; /** * Returns a function name from a string * * @param {string} str - the source string * @param {?boolean=} [opt_empty=false] - if is true, then function name can be empty * @return {string} */ Parser.prototype.getFnName = function (str, opt_empty) { const tmp = /^[^(]+/.exec(str), val = tmp ? tmp[0].trim() : ''; if (!opt_empty && !val) { this.error(`invalid "${this.name}" declaration`); } return val; }; /** * Replaces all find blocks %fileName% to the active file name * and returns a new string * * @param {string} str - the source string * @return {string} */ Parser.prototype.replaceFileNamePatterns = function (str) { const file = this.info.file; let basename; str = this.replaceDangerBlocks(str.replace(/(.?)%fileName%/g, (sstr, $1) => { if (!file) { this.error('the placeholder %fileName% can\'t be used without "file" option'); return ''; } if (!IS_NODE) { this.error('the placeholder %fileName% can\'t be used with live compilation in browser'); return ''; } if (!basename) { const path = require('path'); basename = path.basename(file, path.extname(file)); } let str = basename; if ($1) { if ($1 !== '.') { str = `${$1}'${str}'`; } else { str = $1 + str; } } return str; })); return str; }; const nmRgxp = /\.|\[/, nmssRgxp = /^\[/, nmsRgxp = /\[/g, nmeRgxp = /]/g; /** * Prepares a template declaration string * (evaluation of expressions, etc.) * * @param {string} name - the source string * @return {string} */ Parser.prototype.prepareNameDecl = function (name) { name = this.replaceFileNamePatterns(name); if (nmRgxp.test(name)) { name = $C( name .replace(nmssRgxp, '%') .replace(nmsRgxp, '.%') .replace(nmeRgxp, '') .split('.') ).reduce((str, el) => { const custom = el[0] === '%'; if (custom) { el = el.substring(1); } if (custom) { str += /* cbws */`['${ applyDefEscape( this.returnEvalVal( this.prepareOutput(el, true) ) ) }']`; return str; } return str += str ? `.${el}` : el; }, ''); } return name.trim(); };
JavaScript
0.999999
@@ -1389,16 +1389,20 @@ without +the %22file%22 o @@ -1529,16 +1529,18 @@ tion in +a browser'
43e7c853b834dc7ced0f81ee5f4b130444d85e95
Fix ws reconnect piling up previd param.
modules/xmpp/ResumeTask.js
modules/xmpp/ResumeTask.js
import { getLogger } from 'jitsi-meet-logger'; import { default as NetworkInfo, NETWORK_INFO_EVENT } from '../connectivity/NetworkInfo'; import { getJitterDelay } from '../util/Retry'; const logger = getLogger(__filename); /** * The class contains the logic for triggering connection resume via XEP-0198 stream management. * It does two things, the first one is it tracks the internet online/offline status and it makes sure that * the reconnect is attempted only while online. The seconds thing is that it tracks the retry attempts and extends * the retry interval using the full jitter pattern. */ export default class ResumeTask { /** * Initializes new {@code RetryTask}. * @param {Strophe.Connection} stropheConnection - The Strophe connection instance. */ constructor(stropheConnection) { this._stropheConn = stropheConnection; /** * The counter increased before each resume retry attempt, used to calculate exponential backoff. * @type {number} * @private */ this._resumeRetryN = 0; this._retryDelay = undefined; } /** * @returns {number|undefined} - How much the app will wait before trying to resume the XMPP connection. When * 'undefined' it means that no resume task was not scheduled. */ get retryDelay() { return this._retryDelay; } /** * Called by {@link XmppConnection} when the connection drops and it's a signal it wants to schedule a reconnect. * * @returns {void} */ schedule() { this._cancelResume(); this._resumeRetryN += 1; this._networkOnlineListener = NetworkInfo.addEventListener( NETWORK_INFO_EVENT, ({ isOnline }) => { if (isOnline) { this._scheduleResume(); } else { this._cancelResume(); } }); NetworkInfo.isOnline() && this._scheduleResume(); } /** * Schedules a delayed timeout which will execute the resume action. * @private * @returns {void} */ _scheduleResume() { if (this._resumeTimeout) { // NO-OP return; } // The retry delay will be: // 1st retry: 1.5s - 3s // 2nd retry: 3s - 9s // 3rd and next retry: 4.5s - 27s this._resumeRetryN = Math.min(3, this._resumeRetryN); this._retryDelay = getJitterDelay( /* retry */ this._resumeRetryN, /* minDelay */ this._resumeRetryN * 1500, 3); logger.info(`Will try to resume the XMPP connection in ${this.retryDelay}ms`); this._resumeTimeout = setTimeout(() => this._resumeConnection(), this.retryDelay); } /** * Cancels the delayed resume task. * * @private * @returns {void} */ _cancelResume() { if (this._resumeTimeout) { logger.info('Canceling connection resume task'); clearTimeout(this._resumeTimeout); this._resumeTimeout = undefined; this._retryDelay = undefined; } } /** * Resumes the XMPP connection using the stream management plugin. * * @private * @returns {void} */ _resumeConnection() { const { streamManagement } = this._stropheConn; const resumeToken = streamManagement.getResumeToken(); // Things may have changed since when the task was scheduled if (!resumeToken) { return; } logger.info('Trying to resume the XMPP connection'); const url = new URL(this._stropheConn.service); let { search } = url; search += search.indexOf('?') === -1 ? `?previd=${resumeToken}` : `&previd=${resumeToken}`; url.search = search; this._stropheConn.service = url.toString(); streamManagement.resume(); } /** * Cancels the retry task. It's called by {@link XmppConnection} when it's no longer interested in reconnecting for * example when the disconnect method is called. * * @returns {void} */ cancel() { this._cancelResume(); this._resumeRetryN = 0; if (this._networkOnlineListener) { this._networkOnlineListener(); this._networkOnlineListener = null; } } }
JavaScript
0
@@ -3772,16 +3772,113 @@ = url;%0A%0A + // adds previd param only if missing%0A if (search.indexOf('previd=') === -1) %7B%0A @@ -3968,16 +3968,26 @@ Token%7D%60; +%0A %7D %0A%0A
250240abf4b4c63f9d31c1569e895506f89d2208
convert galleries[i].media.src from array to string
lib/sort-static.js
lib/sort-static.js
var config = require('../config.json'); var parse = require('./parse'); var staticAssets = parse(config.staticAssetMap); var exports = {}; exports.sections = function getSections() { var sections = []; for (var i in staticAssets) { var section = {}; if (!(staticAssets[i].galleries.length > 1)) { section.title = staticAssets[i].galleries[0].title; section.link = staticAssets[i].galleries[0].id; sections.push(section); } else { section.title = staticAssets[i].title; section.galleries = []; for (var g in staticAssets[i].galleries) { var gallery = {}; gallery.title = staticAssets[i].galleries[g].title; gallery.link = staticAssets[i].galleries[g].id; section.galleries.push(gallery); } sections.push(section); } } return sections; } exports.galleries = function getGalleries() { var galleries = []; for (var i in staticAssets) { for (var g in staticAssets[i].galleries) { var thisGal = staticAssets[i].galleries[g]; var gallery = {}; gallery.link = thisGal.id; gallery.media = []; for (var m in thisGal.data) { var thisObj = thisGal.data[m]; var object = {}; if (thisObj.hasOwnProperty('caption')) { object.caption = thisObj.caption; } var src = thisObj.staticMedia; object.src = src; gallery.media.push(object); } galleries.push(gallery); } } return galleries; } module.exports = exports;
JavaScript
0.999827
@@ -1360,16 +1360,19 @@ ticMedia +%5B0%5D ;%0A
a56006b6d5ec075813112d94a5d9ab7205864b50
fix getKickoffTime method
lib/srs-widgets.js
lib/srs-widgets.js
'use strict'; /** * Created by chregi on 2/28/15. * v0.2 - 17.9.2015 * - new: season id needed for schedule * - new: next game endpoint changed * - fixed: removed ".json" from all API calls * v0.1 - 13.4.2015 * - fixed: Kickoff time daylight saving independent * - new: put Day in schedule table */ // parse a date in yyyy-mm-dd format function parseDate(input) { var parts = input.match(/(\d+)/g); // new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]]) return new Date(parts[0], parts[1]-1, parts[2], parts[3], parts[4]); // months are 0-based } function getDateString(date){ return ("0" + date.getDate()).slice(-2) +"."+ ("0"+(date.getMonth()+1)).slice(-2) +"."+ date.getFullYear(); } function getKickoffTimeString(date){ return (date.getHours() + getHourCorrection(date)) + ":"+ ("0" + date.getMinutes()).slice(-2) + " Uhr"; } // get hours to add / subtract to date to fix timezone errors function getHourCorrection(date) { return - (date.getTimezoneOffset() / 60); } // Get day of week from a date as String function getDayOfWeek(date) { var dow = ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"]; return dow[date.getDay()]; } var getSchedule = function(team_id, season_id) { var selector = '.srs-schedule[data-teamid='+team_id+'][data-seasonid='+season_id+']'; jQuery.ajax({ url: "http://api.swissrugbystats.ch/teams/"+team_id+"/games/season/"+season_id, success: function(data){ /* build schedule table * TODO: * - set links */ var tableStr = ""; tableStr = "<table class='srs-scheduletable'><thead><tr><th>Datum</th><th>Host</th><th>Guest</th><th>Kickoff / Result</th></tr></thead><tbody>"; for (var i = 0; i < data.length; i++) { // parse the date var d = parseDate(data[i].date); var dStr = getDateString(d); // game result if ((data[i].host.score != null) && (data[i].guest.score != null)) { var result = data[i].host.score + " : " + data[i].guest.score; } else { var result = getKickoffTimeString(data[i].date); } tableStr += "<tr><td>" + getDayOfWeek(d) +", "+ dStr + "</td><td>" + data[i].host.team.name + "</td><td>" + data[i].guest.team.name + "</td><td>" + result + "</td></tr>"; } tableStr += "</tbody></table>"; jQuery(selector).html(tableStr); jQuery(selector).append("<br/><p>All game data provided by <a href='http://swissrugbystats.ch' target='_blank'>Swiss Rugby Stats</a>"); } }); } var getSchedules = function() { var scheduleTags = jQuery('.srs-schedule'); jQuery('.srs-schedule').each(function( index ) { var team_id = jQuery( this ).attr('data-teamid'); var season_id = jQuery( this ).attr('data-seasonid'); getSchedule(team_id, season_id); }); } var getNextGame = function() { var id = jQuery('.srs-next_game').attr('data-teamid'); jQuery.ajax({ url: "http://api.swissrugbystats.ch/teams/"+id+"/games/next", success: function(data){ var d = parseDate(data.date); var dStr = getDayOfWeek(d) +", "+getDateString(d); jQuery('.srs-next_game').html(dStr + "<br/>" + data.host.team.name + " vs " + data.guest.team.name); } }); } var getNextGames = function() { var nextGameTags = jQuery('.srs-next_game'); jQuery('.srs-next_game').each(function( index ) { var team_id = jQuery( this ).attr('data-teamid'); getNextGame(team_id); }); } /* execute as soon as DOM is ready * TODO: check for existing tags first to reduce ajax calls to minimum */ window.onload = function() { getSchedules(); getNextGames(); };
JavaScript
0.000004
@@ -368,16 +368,80 @@ nput) %7B%0A + if (input instanceof Date) %7B%0A return input;%0A %7D else %7B%0A var pa @@ -469,16 +469,20 @@ d+)/g);%0A + // new @@ -547,16 +547,20 @@ s%5D%5D%5D%5D%5D)%0A + return @@ -644,16 +644,20 @@ 0-based%0A + %7D%0A %7D%0A%0Afunct @@ -693,19 +693,19 @@ return ( -%220%22 +'0' + date. @@ -730,17 +730,17 @@ 2) + -%22.%22+ (%220%22 +'.'+ ('0' +(da @@ -772,11 +772,11 @@ 2) + -%22.%22 +'.' + da @@ -825,32 +825,105 @@ meString(date)%7B%0A + if (!(date instanceof Date)) %7B%0A date = parseDate(date);%0A %7D%0A return (date @@ -967,17 +967,17 @@ ) + -%22:%22+ (%220%22 +':'+ ('0' + d @@ -1010,14 +1010,14 @@ ) + -%22 +' Uhr -%22 +' ;%0A%7D%0A @@ -1253,48 +1253,48 @@ = %5B -%22So%22, %22Mo%22, %22Di%22, %22Mi%22, %22Do%22, %22Fr%22, %22Sa%22 +'So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa' %5D;%0A @@ -1485,33 +1485,33 @@ jax(%7B%0A%09 url: -%22 +' http://api.swiss @@ -1530,17 +1530,17 @@ h/teams/ -%22 +' +team_id @@ -1540,17 +1540,17 @@ team_id+ -%22 +' /games/s @@ -1555,17 +1555,17 @@ /season/ -%22 +' +season_ @@ -1742,10 +1742,10 @@ r = -%22%22 +'' ;%0A
dd2a21fcd2b9790993a38ba06e4e06a764c95d7f
Fix default plugins initializing Fixe #852, close #853
lib/svgo/config.js
lib/svgo/config.js
'use strict'; var FS = require('fs'); var yaml = require('js-yaml'); /** * Read and/or extend/replace default config file, * prepare and optimize plugins array. * * @param {Object} [config] input config * @return {Object} output config */ module.exports = function(config) { var defaults; config = typeof config == 'object' && config || {}; if (config.plugins && !Array.isArray(config.plugins)) { return { error: 'Error: Invalid plugins list. Provided \'plugins\' in config should be an array.' }; } if (config.full) { defaults = config; if (Array.isArray(defaults.plugins)) { defaults.plugins = preparePluginsArray(defaults.plugins); } } else { defaults = Object.assign({}, yaml.safeLoad(FS.readFileSync(__dirname + '/../../.svgo.yml', 'utf8'))); defaults.plugins = preparePluginsArray(defaults.plugins); defaults = extendConfig(defaults, config); } if ('floatPrecision' in config && Array.isArray(defaults.plugins)) { defaults.plugins.forEach(function(plugin) { if (plugin.params && ('floatPrecision' in plugin.params)) { // Don't touch default plugin params plugin.params = Object.assign({}, plugin.params, { floatPrecision: config.floatPrecision }); } }); } if ('datauri' in config) { defaults.datauri = config.datauri; } if (Array.isArray(defaults.plugins)) { defaults.plugins = optimizePluginsArray(defaults.plugins); } return defaults; }; /** * Require() all plugins in array. * * @param {Array} plugins input plugins array * @return {Array} input plugins array of arrays */ function preparePluginsArray(plugins) { var plugin, key; return plugins.map(function(item) { // {} if (typeof item === 'object') { key = Object.keys(item)[0]; // custom if (typeof item[key] === 'object' && item[key].fn && typeof item[key].fn === 'function') { plugin = setupCustomPlugin(key, item[key]); } else { plugin = Object.assign({}, require('../../plugins/' + key)); // name: {} if (typeof item[key] === 'object') { plugin.params = Object.assign({}, plugin.params || {}, item[key]); plugin.active = true; // name: false } else if (item[key] === false) { plugin.active = false; // name: true } else if (item[key] === true) { plugin.active = true; } plugin.name = key; } // name } else { plugin = Object.assign({}, require('../../plugins/' + item)); plugin.name = item; } return plugin; }); } /** * Extend plugins with the custom config object. * * @param {Array} plugins input plugins * @param {Object} config config * @return {Array} output plugins */ function extendConfig(defaults, config) { var key; // plugins if (config.plugins) { config.plugins.forEach(function(item) { // {} if (typeof item === 'object') { key = Object.keys(item)[0]; // custom if (typeof item[key] === 'object' && item[key].fn && typeof item[key].fn === 'function') { defaults.plugins.push(setupCustomPlugin(key, item[key])); } else { defaults.plugins.forEach(function(plugin) { if (plugin.name === key) { // name: {} if (typeof item[key] === 'object') { plugin.params = Object.assign({}, plugin.params || {}, item[key]); plugin.active = true; // name: false } else if (item[key] === false) { plugin.active = false; // name: true } else if (item[key] === true) { plugin.active = true; } } }); } } }); } defaults.multipass = config.multipass; // svg2js if (config.svg2js) { defaults.svg2js = config.svg2js; } // js2svg if (config.js2svg) { defaults.js2svg = config.js2svg; } return defaults; } /** * Setup and enable a custom plugin * * @param {String} plugin name * @param {Object} custom plugin * @return {Array} enabled plugin */ function setupCustomPlugin(name, plugin) { plugin.active = true; plugin.params = Object.assign({}, plugin.params || {}); plugin.name = name; return plugin; } /** * Try to group sequential elements of plugins array. * * @param {Object} plugins input plugins * @return {Array} output plugins */ function optimizePluginsArray(plugins) { var prev; return plugins.reduce(function(plugins, item) { if (prev && item.type == prev[0].type) { prev.push(item); } else { plugins.push(prev = [item]); } return plugins; }, []); }
JavaScript
0
@@ -884,32 +884,38 @@ defaults.plugins + %7C%7C %5B%5D );%0A defau
734f0d82edfa98cdbc3ed649e618e14b7f0f60f1
Fix addons build with valid path for require-tools
core/cb.addons/addon.js
core/cb.addons/addon.js
var _ = require('lodash'); var fs = require('fs'); var path = require('path'); var wrench = require('wrench'); var child_process = require('child_process'); var Q = require("q"); var requirejs = require("requirejs"); var exec = function(command, options) { var deferred = Q.defer(); var childProcess; var args = Array.prototype.slice.call(arguments, 0); args.push(function(err, stdout, stderr) { if (err) { err.message += command + ' (exited with error code ' + err.code + ')'; err.stdout = stdout; err.stderr = stderr; deferred.reject(err); } else { deferred.resolve({ childProcess: childProcess, stdout: stdout, stderr: stderr }); } }); childProcess = child_process.exec.apply(child_process, args); return deferred.promise; } var Addon = function(_rootPath, options) { this.root = _rootPath; this.infos = {}; this.options = _.defaults(options || {}, { blacklist: [], logger: console }); var logger = this.options.logger; // Load addon infos from an addon's directory this.load = Q.fbind(function(addonDir) { addonDir = addonDir || this.root; // Check addon var packageJsonFile = path.join(addonDir, "package.json"); if (!fs.existsSync(packageJsonFile)) { throw new Error("No 'package.json' in this repository: "+addonDir); } this.infos = JSON.parse(fs.readFileSync(packageJsonFile, 'utf8')); if (!this.isValid()) { throw new Error("Invalid 'package.json' file: "+packageJsonFile); } return this; }); // Valid the addon this.isValid = function() { return !(!this.infos.name || !this.infos.version || (!this.infos.main && !this.infos.client && !this.infos.client.main)); }; // Test is symlink this.isSymlink = function() { return Q.nfcall(fs.lstat, this.root).then(function(stats) { return stats.isSymbolicLink(); }); }; // Check if an addon is client side this.isClientside = function() { return (this.infos.client && this.infos.client.main); }; // Check if an addon is node addon this.isNode = function() { return (this.infos.main); }; // Check if an addon is already optimized this.isOptmized = function() { return fs.existsSync(path.join(this.root, "addon-built.js")); }; // Check if an addon has node dependencies this.hasDependencies = function() { return _.size(this.infos.dependencies || {}) > 0; }; // Check if an addon has npm scripts this.hasScripts = function() { return _.size(this.infos.scripts || {}) > 0; }; // Check if the addon is blacklisted this.isBlacklisted = function() { return _.contains(this.options.blacklist, this.infos.name); }; // Optimize the addon this.optimizeClient = function(force) { var that = this; var d = Q.defer(); if (!this.isClientside() || (this.isOptmized() && !force)) { return Q(this); } // Base directory for the addon var addonPath = this.root; // Path to the require-tools var requiretoolsPath = path.resolve(__dirname, "../../client/build/static/require-tools"); // Base main var main = this.infos.client.main; // Output file var output = path.resolve(addonPath, "addon-built.js"); // Build config var optconfig = { 'baseUrl': addonPath, 'name': main, 'out': output, 'paths': { 'require-tools': requiretoolsPath }, 'optimize': "uglify", 'map': { '*': { 'css': "require-tools/css/css", 'less': "require-tools/less/less", 'text': "require-tools/text/text" } } }; // Run optimization logger.log("Optimizing", this.infos.name); return Q.nfcall(fs.unlink, output).fail(function() { return Q(); }).then(function() { var d = Q.defer(); requirejs.optimize(optconfig, function(resp) { d.resolve(resp); }, function(err) { d.reject(err); }); return d.promise; }).then(function() { logger.log("Finished", that.infos.name, "optimization"); return Q(that); }, function(err) { logger.error("error for optimization of", that.infos.name); logger.error("options=", optconfig); logger.error(err); return Q.reject(err); }); }; // Install dependencies for this addon this.installDependencies = function(force) { var that = this; if (!force) { if (!this.hasDependencies() && !this.hasScripts()) { return Q(this); } } logger.log("Install dependencies for", this.root); return exec("cd "+this.root+" && npm install .").then(function() { return Q(that); }); }; // Transfer to a new root directory this.transfer = function(newRoot, options) { var that = this; options = _.defaults({}, options || {}, { forceDelete: true, excludeHiddenUnix: false, preserveFiles: false }); var addonPath = path.join(newRoot, this.infos.name); return Q.nfcall(wrench.copyDirRecursive, this.root, addonPath, options).then(function() { var addon = new Addon(addonPath, that.options); return addon.load(); }); }; // Symlink this addons this.symlink = function(newRoot) { var that = this; var addonPath = path.join(newRoot, this.infos.name); return Q.nfcall(fs.symlink, this.root, addonPath, 'dir').then(function() { var addon = new Addon(addonPath, that.options); return addon.load(); }); }; // Unlink this addon this.unlink = function() { return Q.nfcall(fs.unlink, this.root); }; // Start the node process this.start = function(app) { var that = this; if (!this.isNode()) { return Q(this); } logger.log("start addon", this.root); return app.load([ { 'packagePath': this.root } ]).then(function() { return Q(that); }); }; // Return addons cache resources list this.resources = function() { return ["addon-built.js"].concat(this.infos.client ? (this.infos.client.resources || []) : []); }; // Return addons network resources list this.network = function() { return [].concat(this.infos.client ? (this.infos.client.network || []) : []); }; }; module.exports = Addon;
JavaScript
0
@@ -3400,34 +3400,8 @@ e, %22 -../../client/build/static/ requ
8dea3ff7de61a19bff31a91ca87f057b4c92899d
Remove error constrctors from stack traces
lib/utils/error.js
lib/utils/error.js
'use strict'; var format = require('util').format; function error(){ return new Error(format.apply(null, arguments)); } function syntaxError(){ return new SyntaxError(format.apply(null, arguments)); } module.exports = error; module.exports.syntax = syntaxError;
JavaScript
0.000001
@@ -63,30 +63,33 @@ error()%7B%0A -return +var err = new Error(f @@ -119,16 +119,69 @@ ents));%0A + Error.captureStackTrace(err, error);%0A return err;%0A %7D%0A%0Afunct @@ -201,22 +201,25 @@ or()%7B%0A -return +var err = new Syn @@ -259,16 +259,75 @@ ents));%0A + Error.captureStackTrace(err, syntaxError);%0A return err;%0A %7D%0A%0A%0A%0Amod
24a2519bc22a72e7d88a6b94f09d58204b91b63a
add fixme about agent:false
lib/utils/fetch.js
lib/utils/fetch.js
/** * Fetch an HTTP url to a local file. **/ var http = require("http") , https = require("https") , url = require("url") , sys = require("./sys") , fs = require("./graceful-fs") , get = require("./get") , set = require("./set") , log = require("./log") , npm = require("../../npm") , consts , path = require("path") , mkdir = require("./mkdir-p") , consts = require("constants") , proxyify = require("./proxyify") module.exports = fetch function fetch (remote, local, headers, cb) { if (typeof cb !== "function") cb = headers, headers = {} log.info(remote, "fetch") log.verbose(local, "fetch to") mkdir(path.dirname(local), function (er) { if (er) return cb(er) fetch_(remote, local, headers, cb) }) } function fetch_ (remote, local, headers, cb) { var fstr = fs.createWriteStream(local, { mode : 0755 }) fstr.on("error", function (er) { fs.close(fstr.fd, function () {}) if (fstr._ERROR) return cb(fstr._ERROR = er) }) fstr.on("open", function () { fetchAndWrite(remote, fstr, headers) }) fstr.on("close", function () { if (fstr._ERROR) return cb() }) } function fetchAndWrite (remote, fstr, headers, maxRedirects, redirects) { if (!redirects) redirects = 0 if (!maxRedirects) maxRedirects = 10 var remote = url.parse(remote) , opts = { headers: headers , path: (remote.pathname||"/")+(remote.search||"")+(remote.hash||"") , host: remote.hostname , port: remote.port , secure: remote.protocol.toLowerCase() === "https:" , agent: false } if (!opts.port) opts.port = opts.secure ? 443 : 80 delete headers.host // this will get changed automatically if (remote.auth) { headers["authorization"] = (new Buffer(remote.auth).toString("base64")) delete remote.href delete remote.host delete remote.auth } opts = proxyify(remote, opts) if (!opts) return cb(new Error("Bad proxy config: "+npm.config.get("proxy"))) ;(opts.secure ? https : http).get(opts, function (response) { // handle redirects. var loc = get(response.headers, "location") if (Math.floor(response.statusCode / 100) === 3 && loc && redirects < maxRedirects) { // This is a laughably naïve way to handle this situation. // @TODO: Really need a full curl or wget style module that would // do all this kind of stuff for us. var cookie = get(response.headers, "Set-Cookie") if (cookie) { cookie = (cookie + "").split(";").shift() set(opts.headers, "Cookie", cookie) } remote = url.parse(loc) log.verbose(response.statusCode+" "+loc, "fetch") return fetchAndWrite(remote, fstr, headers, maxRedirects, redirects + 1) } if (response.statusCode !== 200) { return fstr.emit("error", new Error(response.statusCode + " " + (sys.inspect(response.headers)))) } // this is the one we want. response.pipe(fstr) }).on("error", function (e) { fstr.emit("error", e) }) } if (module === require.main) { log("testing", "fetch") var exec = require("./exec") , urls = [ "http://github.com/isaacs/npm/tarball/master" , "http://registry.npmjs.org/npm/-/npm-0.2.18.tgz" , "http://registry.npmjs.org/less/-/less-1.0.41.tgz" , "http://nodejs.org/dist/node-latest.tar.gz" ] , path = require("path") , assert = require("assert") urls.forEach(function (url) { var fetchFile = path.basename(url, ".tgz")+"_fetch.tgz" , wgetFile = path.basename(url, ".tgz")+"_wget.tgz" fetch(url, fetchFile, function (e) { if (e) { log.error(e, fetchFile) ; throw e } exec( "wget" , ["--no-check-certificate", "-O", wgetFile, url] , null, false , function (er, code, stdout, stderr) { if (e) { log.error(e, wgetFile) ; throw e } exec("md5", ["-q", wgetFile], function (er, _, wghash, __) { if (e) { log.error(e, "md5 "+wgetFile) ; throw e } exec("md5", ["-q", fetchFile], function (er, _, fhash, __) { if (e) { log.error(e, "md5 "+fetchFile) ; throw e } assert.equal(wghash, fhash, fetchFile + " == " + wgetFile) }) }) } ) }) }) }
JavaScript
0.000065
@@ -1543,16 +1543,43 @@ https:%22%0A + //FIXME: this sucks.%0A ,
66dfbd9e2a2e8afa6088e57a9940ceb69eef0787
Fix _flush: the _flushed callback must be called *after* the GridFS file is really written (ie after _store.close()
lib/writestream.js
lib/writestream.js
/** * Module dependencies */ var util = require('util'); //var Writable = require('stream').Writable; // This is a workaround to implement a _flush method for Writable (like for Transform) to emit the 'finish' event only after all data has been flushed to the underlying system (GridFS). See https://www.npmjs.com/package/flushwritable and https://github.com/joyent/node/issues/7348 var FlushWritable = require('flushwritable'); /** * expose * @ignore */ module.exports = exports = GridWriteStream; /** * GridWriteStream * * @param {Grid} grid * @param {Object} options (optional) */ function GridWriteStream (grid, options) { if (!(this instanceof GridWriteStream)) return new GridWriteStream(grid, options); FlushWritable.call(this); this._opened = false; this._opening = false; this._writable = true; this._closing = false; this._grid = grid; // a bit backwards compatible if (typeof options === 'string') { options = { filename: options }; } this.options = options || {}; if(options._id) { this.id = grid.tryParseObjectId(options._id); if(!this.id) { this.id = options._id; } } this.name = this.options.filename; // This may be undefined, that's okay if (!this.id) { //_id not passed or unparsable? This is a new file! this.id = new grid.mongo.ObjectID(); this.name = this.name || ''; // A new file needs a name } this.mode = 'w'; //Mongodb v2 driver have disabled w+ because of possible data corruption. So only allow `w` for now. // The value of this.name may be undefined. GridStore treats that as a missing param // in the call signature, which is what we want. this._store = new grid.mongo.GridStore(grid.db, this.id, this.name, this.mode, this.options); this._delayedWrite = null; this._delayedFlush = null; var self = this; self._open(); } /** * Inherit from stream.Writable (FlushWritable for workaround to defer finish until all data flushed) * @ignore */ util.inherits(GridWriteStream, FlushWritable); // private api /** * _open * * @api private */ GridWriteStream.prototype._open = function () { if (this._opened) return; if (this._opening) return; this._opening = true; var self = this; this._store.open(function (err, gs) { self._opening = false; if (err) return self._error(err); self._opened = true; self.emit('open'); // If _flush was called during _store opening, then it was delayed until now, so do the flush now (it's necessarily an empty GridFS file, no _write could have been called and have finished) if (self._delayedFlush) { var flushed = self._delayedFlush; self._delayedFlush = null; self._flushInternal(flushed); } // If _write was called during _store opening, then it was delayed until now, so do the write now if (self._delayedWrite) { var delayedWrite = self._delayedWrite; self._delayedWrite = null; return self._writeInternal(delayedWrite.chunk, delayedWrite.encoding, delayedWrite.done); } }); } /** * _writeInternal * * @api private */ GridWriteStream.prototype._writeInternal = function (chunk, encoding, done) { // If destroy or error no more data will be written. if (!this._writable) return; var self = this; // Write the chunk to the GridStore. The write head automatically moves along with each write. this._store.write(chunk, function (err, store) { if (err) return self._error(err); // Emit the write head position self.emit('progress', store.position); // We are ready to receive a new chunk from the writestream - call done(). done(); }); } /** * _write * * @api private */ GridWriteStream.prototype._write = function (chunk, encoding, done) { if (this._opening) { // if we are still opening the store, then delay the write until it is open. this._delayedWrite = {chunk: chunk, encoding: encoding, done: done}; return; } // otherwise, do the write now this._writeInternal(chunk, encoding, done); } /** * _flushInternal * * @api private */ GridWriteStream.prototype._flushInternal = function (flushed) { flushed(); this._close(); } /** * _flush * * @api private */ GridWriteStream.prototype._flush = function (flushed) { // _flush is called when all _write() have finished (even if no _write() was called (empty GridFS file)) if (this._opening) { // if we are still opening the store, then delay the flush until it is open. this._delayedFlush = flushed; return; } // otherwise, do the flush now this._flushInternal(flushed); } /** * _close * * @api private */ GridWriteStream.prototype._close = function _close () { if (!this._opened) return; if (this._closing) return; this._closing = true; var self = this; this._store.close(function (err, file) { if (err) return self._error(err); self.emit('close', file); }); } /** * _error * * @api private */ GridWriteStream.prototype._error = function _error (err) { // Stop receiving more data to write, emit `error` and close the store this._writable = false; this.emit('error', err); this._close(); } // public api /** * destroy * * @api public */ GridWriteStream.prototype.destroy = function destroy () { // Stop receiving more data to write and close the store this._writable = false; this._close(); }
JavaScript
0.000001
@@ -4143,21 +4143,8 @@ ) %7B%0A - flushed();%0A th @@ -4149,24 +4149,31 @@ this._close( +flushed );%0A%7D%0A%0A/**%0A * @@ -4681,16 +4681,18 @@ _close ( +cb ) %7B%0A if @@ -4899,16 +4899,35 @@ , file); +%0A%0A if (cb) cb(); %0A %7D);%0A%7D
12311016c04f72eb1363ea567c98643fa391e05a
fix bug
ChartGenerator/Repositories/DataRepository.js
ChartGenerator/Repositories/DataRepository.js
let Promise = require('bluebird') let mapify = require('es6-mapify') let projectRepository = require('./ProjectRepository') let model = require('../connect') let calPayOutDistribution = function (tableIndex, projectId, request) { let table = ['overall', 'basegame', 'freegame'] let size = request.size let distributions = JSON.parse(request.distribution) let result = new Map() let key = [] for (let distribution of distributions) { for (let i = distribution.lower; i < distribution.upper; i = Math.round((i + distribution.space) * 10) / 10) { key.push(i) result.set(i, 0) } } return new Promise((resolve, reject) => { projectRepository.getProjectById(projectId).then(project => { return model.knex(table[tableIndex] + projectId).select(model.knex.raw('round((`netWin` / ? + 1) * 10) / 10 as payOut', [project.betCost])).where('id', '<=', size).orderBy('payOut', 'asc') }).then(rows => { let i = 0 for (let row of rows) { while (key[i++] < row.payOut) {} i-- result.set(key[i], result.get(key[i]) + 1) } resolve(mapify.demapify(result)) }).catch(error => { console.log(error) reject() }) }) } let getOverAll = function (projectId, request) { return new Promise((resolve, reject) => { calPayOutDistribution(0, projectId, request).then(result => { resolve(result) }).catch(() => { reject() }) }) } let getBaseGame = function (projectId, request) { return new Promise((resolve, reject) => { calPayOutDistribution(1, projectId, request).then(result => { resolve(result) }).catch(() => { reject() }) }) } let getFreeGame = function (projectId, request) { return new Promise((resolve, reject) => { calPayOutDistribution(2, projectId, request).then(result => { resolve(result) }).catch(() => { reject() }) }) } let getRTP = function (projectId, request) { return new Promise((resolve, reject) => { let size = request.size let step = request.step let range = request.range let result = new Map() projectRepository.getProjectById(projectId).then(project => { console.log(project.betcost) return model.knex('overall' + projectId).select(model.knex.raw('(avg(`netWin` + ?) as rtp, floor((`id` - 1) / ?) as `group`', [project.betCost, step])).where('id', '<=', size).groupBy('group').orderBy('rtp', 'asc') }).then(rtpSet => { for (let rtp of rtpSet) { let tmp = Math.floor(rtp.rtp / range) while (tmp >= result.size) { result.set(range * result.size, 0) } result.set(range * tmp, result.get(range * tmp) + 1) } resolve(mapify.demapify(result)) }).catch(error => { console.log(error) reject() }) }) } let getTotalNetWin = function (projectId, request) { return new Promise((resolve, reject) => { let size = request.size let range = request.range let result = new Map() result.set(0, 0) model.knex('overall' + projectId).select().where('id', '<=', size).then(rows => { let min = 0 let max = 0 let netWin = 0 for (let row of rows) { if (row.triger === 0) { netWin += row.netWin } else { let tmp = Math.floor(netWin / range) while (tmp < min || tmp > max) { if (tmp < min) { result.set((--min) * range, 0) } else { result.set((++max) * range, 0) } } netWin = 0 result.set(range * tmp, result.get(range * tmp) + 1) } } resolve(mapify.demapify(result)) }).catch(error => { console.log(error) reject() }) }) } let getSurvivalRate = function (projectId, request) { let handle = request.handle let bet = request.bet let lowerBound = request.lowerBound let upperBound = request.upperBound let round = request.round return new Promise((resolve, reject) => { let result = {} }) } module.exports = { getOverAll: getOverAll, getBaseGame: getBaseGame, getFreeGame: getFreeGame, getRTP: getRTP, getTotalNetWin: getTotalNetWin, getSurvivalRate: getSurvivalRate }
JavaScript
0.000001
@@ -2317,11 +2317,12 @@ w('( -avg +(sum (%60ne @@ -2330,13 +2330,19 @@ Win%60 +) + ?) + / ?) as @@ -2397,16 +2397,29 @@ .betCost + * step, step , step%5D)
c9bb4f3dfc803430cb94d554279e54f2cee6ce8c
add searchString function
MusicFinder/www/js/controllers.js
MusicFinder/www/js/controllers.js
angular.module('starter.controllers', []) .controller('SearchCtrl', [ '$scope', '$ionicGesture', '$state' ,function($scope, $ionicGesture, $state) { $scope.hideHeader = function() { console.log("Hide"); $( ".tabs" ).slideUp( 200, function() { $( ".bar" ).slideUp(200); }); } $scope.showHeader = function() { console.log("Show"); $( ".bar" ).slideDown( 200, function() { $( ".tabs" ).slideDown(200); }); } $scope.goLeft = function(){ console.log("Left"); //$(".view-container").hide('slide',{direction:'right'},200); $state.go("tab.player"); } }]) .controller('PlayerCtrl', [ '$scope', '$ionicGesture', '$state', function($scope, $ionicGesture, $state) { $scope.hideHeader = function() { console.log("Hide"); $( ".tabs" ).slideUp( 200, function() { $( ".bar" ).slideUp(200); }); } $scope.showHeader = function() { console.log("Show"); $( ".bar" ).slideDown( 200, function() { $( ".tabs" ).slideDown(200); }); } $scope.goLeft = function(){ console.log("Left"); $state.go("tab.aboutme"); } $scope.goRight = function(){ console.log("Right"); $state.go("tab.search"); } }]) .controller('AboutMeCtrl', [ '$scope', '$ionicGesture', '$state', function($scope, $ionicGesture, $state) { $scope.hideHeader = function() { console.log("Hide"); $( ".tabs" ).slideUp( 200, function() { $( ".bar" ).slideUp(200); }); } $scope.showHeader = function() { console.log("Show"); $( ".bar" ).slideDown( 200, function() { $( ".tabs" ).slideDown(200); }); } $scope.goRight = function(){ console.log("Right"); $state.go("tab.player"); } }]) ;
JavaScript
0.000003
@@ -669,32 +669,128 @@ r%22);%0A %7D%0A %0A + $scope.searchString = function(searchString)%7B%0A console.log(searchString);%0A %7D%0A %0A %7D%5D)%0A%0A.controller
5bebe165a1a9d743acf3e2272f0bf6a970370225
Parse json
libs/cloudflare.js
libs/cloudflare.js
(function(module){ var http = require('https'); var _ = require("underscore"); function Cloudflare(zoneId, authEmail, authKey) { this.zoneId = zoneId; this.authEmail = authEmail; this.authKey = authKey; } var fn = Cloudflare.prototype; fn.fetch = function() { http.get({ hostname: 'api.cloudflare.com', path: '/client/v4/zones/' + this.zoneId + '/logs/requests' + this._params(), headers: this._headers() }, this._readResponse); }; fn._params = function() { return '?count=100000&start=' + this.startTime(); }; fn.startTime = function() { return Math.floor((new Date().getTime() / 1000) - 120) }; fn._readResponse = function(response) { var body = ''; response.on('end', function() { console.info(body); }); response.on('data', function(chunk) { body += chunk; }); }; fn._headers = function() { var headers = {}; //headers['Accept-Encoding'] = 'gzip'; headers['X-Auth-Email'] = this.authEmail; headers['X-Auth-Key'] = this.authKey; return headers; }; module.exports = Cloudflare; })(module);
JavaScript
0.999252
@@ -533,13 +533,8 @@ nt=1 -00000 &sta @@ -779,13 +779,25 @@ nfo( +JSON.parse( body) +) ;%0A
9429c38c1caf5906449ea0380bca2c0851025d4e
add solution
Algorithms/JS/arrays/shortestWordDifferenceTwo.js
Algorithms/JS/arrays/shortestWordDifferenceTwo.js
// This is a follow up of Shortest Word Distance. // The only difference is now you are given the list of words // and your method will be called repeatedly many times with different parameters. How would you optimize it? // Design a class which receives a list of words in the constructor, // and implements a method that takes two words word1 and word2 and // return the shortest distance between these two words in the list. // For example, // Assume that words = ["practice", "makes", "perfect", "coding", "makes"]. // Given word1 = “coding”, word2 = “practice”, return 3. // Given word1 = "makes", word2 = "coding", return 1. // Note: // You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
JavaScript
0.000003
@@ -721,20 +721,869 @@ e both in the list.%0A +%0A%0A/**%0A * @constructor%0A * @param %7Bstring%5B%5D%7D words%0A */%0Avar WordDistance = function(words) %7B%0A this.lib = %7B%7D;%0A for( var i=0; i%3Cwords.length; i++ )%7B%0A if( this.lib%5Bwords%5Bi%5D%5D )%7B%0A this.lib%5Bwords%5Bi%5D%5D.push(i);%0A %7D else %7B%0A this.lib%5Bwords%5Bi%5D%5D = %5Bi%5D;%0A %7D%0A %7D%0A%7D;%0A%0A/**%0A * @param %7Bstring%7D word1%0A * @param %7Bstring%7D word2%0A * @return %7Binteger%7D%0A */%0A%0AWordDistance.prototype.shortest = function(word1, word2) %7B%0A var distance = Number.MAX_VALUE,%0A arr1 = this.lib%5Bword1%5D,%0A arr2 = this.lib%5Bword2%5D;%0A for( var i=0, j=0; i %3C arr1.length && j %3C arr2.length; )%7B%0A if( arr1%5Bi%5D %3C arr2%5Bj%5D )%7B%0A distance = Math.min( distance, arr2%5Bj%5D-arr1%5Bi%5D );%0A i++;%0A %7D else %7B%0A distance = Math.min( distance, arr1%5Bi%5D-arr2%5Bj%5D );%0A j++;%0A %7D%0A %7D%0A return distance;%0A%7D;%0A
0c1db18cb13e1e333f0af5dd1b2e44bdd7a4fc78
make button stick to corner
lib/OpenLayers/Control/Popout.js
lib/OpenLayers/Control/Popout.js
/** * @requires OpenLayers/Control.js */ OpenLayers.Control.Popout = OpenLayers.Class( OpenLayers.Control, { initialize: function(options) { OpenLayers.Control.prototype.initialize.apply(this,[options]); }, draw: function () { var imgLocation, wrapper, img; OpenLayers.Control.prototype.draw.apply(this, arguments); img = document.createElement('div'); img.innerHTML = OpenLayers.Util.hideFromOldIE('<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="20px" height="20px" preserveAspectRatio="xMidYMid meet" viewBox="0 0 20 20" class="icon fullscreen"><path d="M14.949,3.661l1.429,1.428l1.539-1.54l1.612,1.612V0.485h-4.676l1.636,1.636L14.949,3.661z M17.894,16.6l-1.54-1.539l-1.428,1.428l1.539,1.54l-1.611,1.612h4.676v-4.676L17.894,16.6z M4.895,16.465l-1.428-1.428l-1.54,1.539l-1.612-1.611v4.676h4.675l-1.636-1.637L4.895,16.465z M3.491,5.064l1.428-1.428l-1.54-1.539l1.612-1.612H0.315v4.675l1.636-1.635L3.491,5.064zM15.769,12.033V8.199c0-1.587-1.288-2.875-2.875-2.875H6.907c-1.588,0-2.875,1.287-2.875,2.875v3.834c0,1.588,1.287,2.875,2.875,2.875h5.987C14.48,14.908,15.769,13.621,15.769,12.033z" /></svg>'); img.style["position"]="fixed"; img.style["padding"]="5px"; img["className"]="panel toolbar"; img.style["right"]="5px"; img.style["bottom"]="5px"; wrapper = document.createElement('div'); var link = document.createElement('a'); url = window.location.href; url = "http://www.norgeskart.no#"+url.split("#")[1]; if (!url) {link.href = "http://www.norgeskart.no";} else {link.href = url;} link.target = "_blank"; self.link = link; link.appendChild(img); wrapper.appendChild(link); OpenLayers.Element.addClass(wrapper, 'logoDiv'); if (this.div === null) { this.div = wrapper; } else { this.div.appendChild(wrapper); } return this.div; }, // draw updateLink: function (url) { self.link.href = url; }, CLASS_NAME: "OpenLayers.Control.Popout" }); // OpenLayers.Control.Popout
JavaScript
0.000001
@@ -1314,27 +1314,25 @@ e%5B%22right%22%5D=%22 -5px +0 %22;%0A i @@ -1347,27 +1347,25 @@ %5B%22bottom%22%5D=%22 -5px +0 %22;%0A w
4da0ffc55d7ca1bf4276ca2cc96515ee523e9e54
Fix Talk sidebar in public share pages without header actions
src/mainPublicShareSidebar.js
src/mainPublicShareSidebar.js
/** * @copyright Copyright (c) 2020 Daniel Calviño Sánchez <[email protected]> * * @license GNU AGPL version 3 or any later version * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ import Vue from 'vue' import PublicShareSidebar from './PublicShareSidebar' // Store import Vuex from 'vuex' import store from './store' // Utils import { generateFilePath } from '@nextcloud/router' import { getRequestToken } from '@nextcloud/auth' // plugins import browserDetect from 'vue-browser-detect-plugin' // Directives import { translate, translatePlural } from '@nextcloud/l10n' import VueShortKey from 'vue-shortkey' // CSP config for webpack dynamic chunk loading // eslint-disable-next-line __webpack_nonce__ = btoa(getRequestToken()) // Correct the root of the app for chunk loading // OC.linkTo matches the apps folders // OC.generateUrl ensure the index.php (or not) // We do not want the index.php since we're loading files // eslint-disable-next-line __webpack_public_path__ = generateFilePath('spreed', '', 'js/') Vue.prototype.t = translate Vue.prototype.n = translatePlural Vue.prototype.OC = OC Vue.prototype.OCA = OCA Vue.use(Vuex) Vue.use(VueShortKey, { prevent: ['input', 'textarea', 'div'] }) Vue.use(browserDetect) function adjustLayout() { document.querySelector('#app-content').append(document.querySelector('footer')) const talkSidebarElement = document.createElement('div') talkSidebarElement.setAttribute('id', 'talk-sidebar') document.querySelector('#content').append(talkSidebarElement) } adjustLayout() // An "isOpen" boolean should be passed to the component, but as it is a // primitive it would not be reactive; it needs to be wrapped in an object and // that object passed to the component to get reactivity. const sidebarState = { isOpen: false, } // Open the sidebar by default based on the window width using the same // threshold as in the main Talk UI (in Talk 7). if (window.innerWidth > 1111) { sidebarState.isOpen = true } function addTalkSidebarTrigger() { const talkSidebarTriggerElement = document.createElement('button') talkSidebarTriggerElement.setAttribute('id', 'talk-sidebar-trigger') talkSidebarTriggerElement.setAttribute('class', 'icon-menu-people-white') talkSidebarTriggerElement.addEventListener('click', () => { sidebarState.isOpen = !sidebarState.isOpen }) document.querySelector('.header-right').append(talkSidebarTriggerElement) } addTalkSidebarTrigger() function getShareToken() { const shareTokenElement = document.getElementById('sharingToken') return shareTokenElement.value } const talkSidebarVm = new Vue({ store, id: 'talk-chat-tab', propsData: { shareToken: getShareToken(), state: sidebarState, }, ...PublicShareSidebar, }) talkSidebarVm.$mount(document.querySelector('#talk-sidebar'))
JavaScript
0
@@ -2954,16 +2954,358 @@ pen%0A%09%7D)%0A +%0A%09// The %22.header-right%22 element may not exist in the public share page if%0A%09// there are no header actions.%0A%09if (!document.querySelector('.header-right')) %7B%0A%09%09const headerRightElement = document.createElement('div')%0A%09%09headerRightElement.setAttribute('class', 'header-right')%0A%09%09document.querySelector('#header').append(headerRightElement)%0A%09%7D%0A%0A %09documen
25f95e71ee7844af7fc7eb31c8eafb8cb225a403
Comment out unused NPM publication tasks.
Jakefile.js
Jakefile.js
/* * Jakefile for toast.js (https://github.com/srackham/toast.js). */ 'use strict'; var pkg = require('./package.json'); var shelljs = require('shelljs'); var child_process = require('child_process'); /* Inputs and outputs */ var TOAST_JS = 'toast.js'; var TOAST_TS = 'toast.ts'; var TOAST_MIN_JS = 'toast.min.js'; /* Utility functions. */ /* Execute shell commands in parallel then run the callback when they have all finished. `callback` defaults to the Jake async `complete` function. Abort if an error occurs. Write command output to the inherited stdout (unless the Jake --quiet option is set). Print a status message when each command starts and finishes (unless the Jake --quiet option is set). NOTE: This function is similar to the built-in jake.exec function but is twice as fast. */ function exec(commands, callback) { if (typeof commands === 'string') { commands = [commands]; } callback = callback || complete; var remaining = commands.length; if (remaining === 0) { callback(); } else { commands.forEach(function(command) { jake.logger.log('Starting: ' + command); child_process.exec(command, function(error, stdout, stderr) { jake.logger.log('Finished: ' + command); if (!jake.program.opts.quiet) { process.stdout.write(stdout); } if (error !== null) { fail(error, error.code); } remaining--; if (remaining === 0) { callback(); } }); }); } } /* Tasks All tasks are synchronous (another task will not run until the current task has completed). Consequently all task dependencies are executed asynchronously in declaration order. The `exec` function ensures shell commands within each task run in parallel. */ desc('Run test task.'); task('default', ['test']); desc('compile, lint, test'); task('build', ['test']); desc('Lint source files.'); task('lint', {async: true}, function() { var commands = []; commands.push('jsonlint --quiet package.json'); commands.push('tslint -f ' + TOAST_TS); exec(commands); }); desc('Run tests (recompile if necessary).'); task('test', ['compile', 'lint'], {async: true}, function() { var commands = []; // TODO: Unit tests. exec(commands); }); desc('Compile Typescript to JavaScript then uglify.'); task('compile', [TOAST_JS, TOAST_MIN_JS]); file(TOAST_JS, [TOAST_TS], {async: true}, function() { exec('tsc --noImplicitAny --out ' + TOAST_JS + ' ' + TOAST_TS); }); file(TOAST_MIN_JS, [TOAST_JS], {async: true}, function() { var preamble = '/* ' + pkg.name + ' ' + pkg.version + ' (' + pkg.repository.url + ') */'; var command = 'uglifyjs --preamble "' + preamble + '" --output ' + TOAST_MIN_JS + ' ' + TOAST_JS; exec(command); }); desc('Validate HTML documents with W3C Validator.'); task('validate-html', {async: true}, function() { var commands = []; commands.push('w3cjs validate toast-examples.html'); exec(commands); }); desc('Display or update the project version number. Use vers=x.y.z syntax to set a new version number.'); task('version', function() { var version = process.env.vers; if (!version) { console.log('\nversion: ' + pkg.version); } else { if (!version.match(/^\d+\.\d+\.\d+$/)) { fail('Invalid version number: ' + version + '\n'); } shelljs.sed('-i', /(\n\s*"version"\s*:\s*)"\d+\.\d+\.\d+"/, '$1' + '"' + version + '"', 'package.json'); } }); desc('Create tag ' + pkg.version); task('tag', ['test'], {async: true}, function() { exec('git tag -a -m "Tag ' + pkg.version + '" ' + pkg.version); }); desc('Commit changes to local Git repo.'); task('commit', ['test'], {async: true}, function() { jake.exec('git commit -a', {interactive: true}, complete); }); desc('push, publish-npm.'); task('publish', ['push', 'publish-npm']); desc('Push local commits to Github.'); task('push', ['test'], {async: true}, function() { exec('git push -u --tags origin master'); }); /* desc('Publish to npm.'); task('publish-npm', {async: true}, ['test'], function() { exec('npm publish'); }); */
JavaScript
0
@@ -3756,24 +3756,27 @@ lete);%0A%7D);%0A%0A +/*%0A desc('push, @@ -3828,24 +3828,27 @@ lish-npm'%5D); +%0A*/ %0A%0Adesc('Push
973bc1ddc88fa16102c2ba78ce02f8a5f41ce07c
Make sure to always return array (#1851)
packages/gatsby/src/internal-plugins/query-runner/page-query-runner.js
packages/gatsby/src/internal-plugins/query-runner/page-query-runner.js
/** * Jobs of this module * - Ensure on bootstrap that all invalid page queries are run and report * when this is done * - Watch for when a page's query is invalidated and re-run it. */ const _ = require(`lodash`) const Promise = require(`bluebird`) const { store, emitter } = require(`../../redux`) const queryRunner = require(`./query-runner`) let queuedDirtyActions = [] let active = false exports.runQueries = async () => { active = true const state = store.getState() // Run queued dirty nodes now that we're active. queuedDirtyActions = _.uniq(queuedDirtyActions, a => a.payload.id) const dirtyIds = findDirtyIds(queuedDirtyActions) await runQueriesForIds(dirtyIds) // Find ids without data dependencies and run them (just in case?) const cleanIds = findIdsWithoutDataDependencies() // Run these pages await runQueriesForIds(cleanIds) return } emitter.on(`CREATE_NODE`, action => { queuedDirtyActions.push(action) }) const runQueuedActions = async () => { if (active) { queuedDirtyActions = _.uniq(queuedDirtyActions, a => a.payload.id) await runQueriesForIds(findDirtyIds(queuedDirtyActions)) queuedDirtyActions = [] } } // Wait until all plugins have finished running (e.g. various // transformer plugins) before running queries so we don't // query things in a 1/2 finished state. emitter.on(`API_RUNNING_QUEUE_EMPTY`, runQueuedActions) const findIdsWithoutDataDependencies = () => { const state = store.getState() const allTrackedIds = _.uniq( _.flatten( _.concat( _.values(state.componentDataDependencies.nodes), _.values(state.componentDataDependencies.connections) ) ) ) // Get list of paths not already tracked and run the queries for these // paths. return _.difference( [ ...state.pages.map(p => p.path), ...state.layouts.map(l => `LAYOUT___${l.id}`), ], allTrackedIds ) } const runQueriesForIds = ids => { if (ids.length < 1) { return Promise.resolve() } const state = store.getState() return Promise.all( ids.map(id => { const pagesAndLayouts = [...state.pages, ...state.layouts] const plObj = pagesAndLayouts.find( pl => pl.path === id || `LAYOUT___${pl.id}` === id ) if (plObj) { return queryRunner(plObj, state.components[plObj.component]) } }) ) } const findDirtyIds = actions => { const state = store.getState() return actions.reduce((dirtyIds, action) => { const node = state.nodes[action.payload.id] // Check if the node was deleted if (!node) { return } // find invalid pagesAndLayouts dirtyIds = dirtyIds.concat(state.componentDataDependencies.nodes[node.id]) // Find invalid connections dirtyIds = dirtyIds.concat( state.componentDataDependencies.connections[node.internal.type] ) return _.compact(dirtyIds) }, []) }
JavaScript
0.000003
@@ -2594,16 +2594,25 @@ return + dirtyIds %0A %7D%0A%0A
1b980864bac64c4e4f067a13e61f8e5d37dc74f9
Fix a bug
tarsier.js
tarsier.js
; /*! * Tarsier JavaScript Library v1.0.1 * http://moky.github.com/Tarsier/ * * Includes jquery.js * http://jquery.com/ * * Copyright 2013 moKy at slanissue.com * Released under the MIT license * http://jquery.org/license * * Date: 2013-12-11 T10:43Z */ if (typeof(window.tarsier) != "object") { window.tarsier = { version: "1.0.1" }; } // base functions (function(tarsier) { // count of current importing tasks tarsier.importings = -1; // init /** * Import javascript file */ tarsier.importJS = function(args) { var src = args.src; var callback = args.callback; var doc = args.document || window.document; if (tarsier.importings < 0) { tarsier.importings = 0; // start } var script = doc.createElement("script"); if (script) { script.type = "text/javascript"; script.src = src; // callback script.onload = function() { tarsier.importings--; if (callback) callback(); } script.onreadystatechange = function() { // IE if (this.readyState == "complete") { --tarsier.importings; if (callback) callback(); } } // load var head = doc.getElementsByTagName("head"); if (head) { tarsier.importings++; head.item(0).appendChild(script); } } }; /** * Import css file */ tarsier.importCSS = function(args) { var href = args.href; var doc = args.document || window.document; var link = doc.createElement("link"); if (link) { link.rel = "stylesheet"; link.type = "text/css"; link.href = href; var head = doc.getElementsByTagName("head"); if (head) { head.item(0).appendChild(link); } } }; // importing finished? tarsier.isReady = function() { return tarsier.importings == 0; } tarsier.readys = []; // window.onLoad tarsier.ready = function(func) { if (func) { tarsier.readys[tarsier.readys.length] = func; } if (this.isReady()) { for (var i = 0; i < tarsier.readys.length; ++i) { tarsier.readys[i](); } tarsier.readys = []; } }; window.onload = function() { tarsier.ready(); } //-------------------------------------------------------------------------- /** * Environment variables */ var __FILE__ = "https://raw.github.com/moky/Tarsier/master/tarsier.js"; // current filename var __PATH__ = "https://raw.github.com/moky/Tarsier/master/"; // current filepath var scripts = document.getElementsByTagName("script"); if (scripts && scripts.length > 0) { __FILE__ = scripts[scripts.length - 1].src; var pos = __FILE__.lastIndexOf("/"); if (pos >= 0) { __PATH__ = __FILE__.substr(0, pos + 1); __FILE__ = __FILE__.substr(pos + 1); } } // include all dependences tarsier.importJS({src: "http://code.jquery.com/jquery.min.js"}); tarsier.importJS({src: "http://borismoore.github.io/jquery-tmpl/jquery.tmpl.min.js"}); // tarsier.importJS({src: __PATH__ + "3rd/jquery.js"}); // tarsier.importJS({src: __PATH__ + "3rd/jquery.tmpl.js"}); tarsier.importJS({src: __PATH__ + "3rd/jquery.xml2json.js"}); tarsier.importJS({src: __PATH__ + "http.js"}); tarsier.importJS({src: __PATH__ + "xml.js"}); tarsier.importJS({src: __PATH__ + "template.js"}); tarsier.importJS({src: __PATH__ + "widget.js"}); })(tarsier);
JavaScript
0.000192
@@ -2681,16 +2681,18 @@ ndences%0A +// %09tarsier @@ -2741,32 +2741,34 @@ uery.min.js%22%7D);%0A +// %09tarsier.importJ @@ -2843,12 +2843,8 @@ %7D);%0A -%09%0A// %09tar @@ -2886,25 +2886,27 @@ /jquery. +min. js%22%7D);%0A -// %09tarsier @@ -2949,16 +2949,20 @@ ry.tmpl. +min. js%22%7D);%0A%09
12a5fd5211e69d469ac28c6c17a75c46ae281d6e
Update UserIdTransaction.post.js
lib/routes/UserIdTransaction.post.js
lib/routes/UserIdTransaction.post.js
var util = require('util'); var seq = require('seq'); var Route = require('../routing/Route'); var errors = require('../errors'); var Result = require('../result/Result'); var MountPoint = require('../routing/MountPoint'); var configuration = require('../configuration'); function TransactionCreate (persistence, mqttWrapper) { Route.call(this); this._persistence = persistence; this._mqttWrapper = mqttWrapper; } util.inherits(TransactionCreate, Route); TransactionCreate.prototype.mountPoint = function () { return new MountPoint('post', '/user/:userId/transaction', ['UserId.get']); }; TransactionCreate.prototype.route = function (req, res, next) { var that = this; var value = parseFloat(req.body.value); var userId = req.params.userId; if (isNaN(value)) { return next(new errors.InvalidRequestError('not a number: ' + req.body.value)); } if (value === 0) { return next(new errors.InvalidRequestError('value must not be zero')); } if (!req.strichliste.result) { return next(new errors.InternalServerError('previous stage result missing')); } if (value < configuration.boundaries.transaction.lower) { return next(new errors.ForbiddenError('transaction value of ' + value + ' falls below the transaction minimum of ' + configuration.boundaries.transaction.lower)); } if (value > configuration.boundaries.transaction.upper) { return next(new errors.ForbiddenError('transaction value of ' + value + ' exceeds the transaction maximum of ' + configuration.boundaries.transaction.upper)); } var user = req.strichliste.result.content(); var newBalance = user.balance + value; if (newBalance < configuration.boundaries.account.lower) { return next(new errors.ForbiddenError('transaction value of ' + value + ' leads to an overall account balance of ' + newBalance + ' which goes below the lower account limit of ' + configuration.boundaries.account.lower)); } if (newBalance > configuration.boundaries.account.upper) { return next(new errors.ForbiddenError('transaction value of ' + value + ' leads to an overall account balance of ' + newBalance + ' which goes beyond the upper account limit of ' + configuration.boundaries.account.upper)); } seq() .seq(function () { that._persistence.createTransaction(userId, value, this); }) .seq(function (transactionId) { that._persistence.loadTransaction(transactionId, function (error, result) { if (error) return next(new errors.InternalServerError('error retrieving transaction: ' + transactionId)); that._mqttWrapper.publishTransactionValue(value); req.strichliste.result = new Result(result, Result.CONTENT_TYPE_JSON, 201); next(); }); }) .catch(function (error) { next(new errors.InternalServerError('unexpected: ' + error.message)); }); }; TransactionCreate.routeName = 'UserIdTransaction.post'; module.exports = TransactionCreate;
JavaScript
0
@@ -1282,24 +1282,33 @@ s below the +negative transaction @@ -1308,18 +1308,18 @@ action m -in +ax imum of @@ -3106,8 +3106,9 @@ nCreate; +%0A
9bc0bbc4a5431d9806151a64908680c16e972e55
Fix typo (#908)
quickstarts/uppercase-firestore/functions/index.js
quickstarts/uppercase-firestore/functions/index.js
/** * Copyright 2017 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // [START all] // [START import] // The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers. const functions = require('firebase-functions'); // The Firebase Admin SDK to access Firestore. const admin = require('firebase-admin'); admin.initializeApp(); // [END import] // [START addMessage] // Take the text parameter passed to this HTTP endpoint and insert it into // Firestore under the path /messages/:documentId/original // [START addMessageTrigger] exports.addMessage = functions.https.onRequest(async (req, res) => { // [END addMessageTrigger] // Grab the text parameter. const original = req.query.text; // [START adminSdkAdd] // Push the new message into Firestore using the Firebase Admin SDK. const writeResult = await admin.firestore().collection('messages').add({original: original}); // Send back a message that we've successfully written the message res.json({result: `Message with ID: ${writeResult.id} added.`}); // [END adminSdkAdd] }); // [END addMessage] // [START makeUppercase] // Listens for new messages added to /messages/:documentId/original and creates an // uppercase version of the message to /messages/:documentId/uppercase // [START makeUppercaseTrigger] exports.makeUppercase = functions.firestore.document('/messages/{documentId}') .onCreate((snap, context) => { // [END makeUppercaseTrigger] // [START makeUppercaseBody] // Grab the current value of what was written to Firestore. const original = snap.data().original; // Access the parameter `{documentId}` with `context.params` functions.logger.log('Uppercasing', context.params.documentId, original); const uppercase = original.toUpperCase(); // You must return a Promise when performing asynchronous tasks inside a Functions such as // writing to Firestore. // Setting an 'uppercase' field in Firestore document returns a Promise. return snap.ref.set({uppercase}, {merge: true}); // [END makeUppercaseBody] }); // [END makeUppercase] // [END all]
JavaScript
0.00158
@@ -732,16 +732,17 @@ and set + up trigg
518e029356259b63432ff9f4f5f7547ba291c980
Update note
lib/blog_comment_form_helpers.js
lib/blog_comment_form_helpers.js
/****************************************************************************** www.averylawfirm.com Copyright (c) 2014 Jeffrey Carpenter <[email protected]> ALL RIGHTS RESERVED Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ // Site dependencies var express = require('express'); var app = express(); var router = express.Router(); var validator = require('express-validator'); // Blogger API back-end helper var BloggerCommentFeed = require('./blogger/feed.js'); var blog_comment_form_helpers = module.exports = { process_form: function process_form( req, res, callback ) { // Save the state of the form input fields upon submission res.locals.blog_comment = req.body.blog_comment; // CAPTCHA accessor variables var challenge_field = res.locals.blog_comment['captcha_challenge_field']; var challenge_response_field = req.session.captcha['challenge_response_field']; // Equality check validator.validator.extend('eq', function(str, comp) { if( str != comp ) return false; return true; }); // Do user input sanity checks req.checkBody( 'blog_comment.name', res.locals.input_errs['blog_comment'].name ).len(1,255); if( res.locals.blog_comment['email'] != '' ) { req.checkBody( 'blog_comment.email', res.locals.input_errs['blog_comment'].email ).len(1,255); } if( res.locals.blog_comment['website_url'] != '' ) { req.checkBody( 'blog_comment.website_url', res.locals.input_errs['blog_comment'].website_url ).len(1,255); } req.checkBody( 'blog_comment.message', res.locals.input_errs['blog_comment'].message ).len(1,4096); // CAPTCHA verification req.checkBody( 'blog_comment.captcha_challenge_field', res.locals.input_errs['blog_comment'].captcha ).eq( challenge_response_field ); // Check the validation object for errors var errors = req.validationErrors(); if( errors ) { if( app.get('env') === 'development' || app.get('env') === 'testing' ) { console.info( 'Blog Comment Form Errors:'); console.info( errors ); } // Store the validation errors inside a session store for user // notification; sessions grant us application state. for( var i = 0; i != errors.length; ++i ) { req.flash('notifications', { type: 'err', message: errors[i].msg } ); } // WARNING: Logging req.flash messages will result in the clearing of the // notifications, thus never being shown to the web app. This is a // nightmare for debugging when we forget about this warning! // console.log(req.flash('notifications')); callback( { notifications: req.flash('notifications') } ); } else { // Successful form validation logic // HTTP request var request = {}; // Additional cURL options var options = {}; // TODO: if 'development' || 'testing' options.verbose = true; options.stderr = true; // Control state of whether or not to actually send the API request to // Blogger's servers; in other words: a 'dry run' toggle. options.pretend = false; request.blog_id = res.locals.blog_comment['blog_id'] request.post_id = res.locals.blog_comment['post_id'] // Note that this does not require authentication to post to a comments // feed, due to the fact that anonymous comments are enabled. // request.token = req.session.tokens.auth.access_token; // console.log(req.session.tokens); // Container elements var post = {}; post.author = {}; // NOTE: The maximal post title length is 48; anything > 48 is clipped off // by by padding period symbols until the given title length == 51 post.title = 'TODO'; // NOTE: Maximal comment post size is 4096 characters post.content = res.locals.blog_comment['message']; // post.published = new Date().toString(); // RFC 3339 // post.updated = new Date().toString(); // RFC 3339 post.author.name = res.locals.blog_comment['name']; if( res.locals.blog_comment['email'] != '' ) { post.author.email = res.locals.blog_comment['email']; } else { post.author.email = '[email protected]' } if( res.locals.blog_comment['website_url'] != '' ) { post.author.url = res.locals.blog_comment['website_url']; } // Initialize Blogger comment feed var feed = new BloggerCommentFeed( {} ); feed.addPost( post ); // console.log( feed.render() ); feed.send( request, options ); // Processed form successfully callback( { notifications: [] } ); } // End else (successful form validation) }, // End function declaration };
JavaScript
0
@@ -4997,28 +4997,77 @@ +//%0A // We let Google create the post -. + title -= 'TODO'; +for us automatically. %0A%0A
85d9c226ab076ef65fb5b269a74932a75e5c6471
add created at to file sanitisation function
lib/bundles/media/models/file.js
lib/bundles/media/models/file.js
/** * Created by Awesome on 2/23/2016. */ // use strict 'use strict'; // require dependencies var fs = require ('fs'); var path = require ('path'); var model = require ('model'); // require local dependencies var config = require ('app/config'); /** * create file model */ class file extends model { /** * construct file model * * @param a * @param b */ constructor (a, b) { // run super super (a, b); // bind methods this.file = this.file.bind (this); this.buffer = this.buffer.bind (this); this.sanitise = this.sanitise.bind (this); // bind private methods this._path = this._path.bind (this); this._check = this._check.bind (this); this._remove = this._remove.bind (this); // configure this.before ('remove', '_remove'); } /** * upload with buffer * * @param {Buffer} buffer * @param {String} name */ async buffer (buffer, name) { // set hash this.set ('ext', path.extname (name)); // get path var hash = await this._rand (); var exists = true; // loop to check while (exists) { // check database for image var File = await file.count ({ 'path' : this._path (), 'hash' : hash }); // check if image exists if (!File) { exists = false; } else { hash = await this._rand (); } } // set name this.set ('name', name || hash + this.get ('ext')); this.set ('hash', hash); // check directory exists await this._check (); // write file fs.writeFileSync (this._path (true) + '/' + this.get ('hash') + this.get ('ext'), buffer); // set size this.set ('size', fs.statSync (this._path (true) + '/' + this.get ('hash') + this.get ('ext')).size); // save await this.save () // return this for chainable return this; } /** * set image * * @param {String} file * @param {String} name */ async file (loc, name) { // check if file exists if (!fs.existsSync (loc)) { // throw error throw new Error ('Image file does not exist in ' + loc); } // set hash this.set ('ext', path.extname (name)); // get path var hash = await this._rand (); var exists = true; // loop to check while (exists) { // check database for image var File = await file.count ({ 'path' : this._path (), 'hash' : hash }); // check if image exists if (!File) { exists = false; } else { hash = await this._rand (); } } // set name this.set ('name', name || (hash + this.get ('ext'))); // set hash this.set ('hash', hash); // check directory exists await this._check (); // move to correct directory fs.renameSync (loc, this._path (true) + '/' + this.get ('hash') + this.get ('ext')); // set size this.set ('size', fs.statSync (this._path (true) + '/' + this.get ('hash') + this.get ('ext')).size); // save await this.save () // set image return this; } /** * sanitise image * * @return {Object} sanitised */ async sanitise () { // return image return { 'id' : this.get ('_id') ? this.get ('_id').toString () : false, 'file' : this.get ('hash') + this.get ('ext'), 'name' : this.get ('name'), 'path' : this._path (), 'size' : this.get ('size') }; } /** * get path * * @param {Boolean} full * * @return {String} path */ _path (full) { // set date var date = new Date ().toISOString ().slice (0, 10).split ('-').join (''); // get path this.set ('dir', this.get ('dir') || config.media.dir); this.set ('sub', this.get ('sub') || (date + '/' + this._rand ())); this.set ('type', this.get ('type') || 'file'); // get path var pth = this.get ('dir') + '/' + this.get ('type') + '/' + this.get ('sub'); // set path this.set ('path', pth); // return path if (!full) return pth; // return full path return global.appRoot + '/www/public/' + pth; } /** * check directory */ async _check () { // check directory exists var full = this._path (true); var parts = full.replace (/\/$/, '').split ('/'); // loop parts for (var i = 1; i <= parts.length; i++) { // get segment var segment = parts.slice (0, i).join ('/'); // check segment if (segment.length === 0) continue; // check if exists then create if (!fs.existsSync (segment)) fs.mkdirSync (segment, '0755'); } } /** * generate random string * * @return {String} random */ _rand () { var text = ''; var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; // loop possible for (var i = 0; i < 10; i++) { // add character text += possible.charAt (Math.floor (Math.random () * possible.length)); } // return text return text; } /** * remove image */ async _remove (next) { // check if exists if (fs.existsSync (global.appRoot + '/www/public/' + this._path () + '/' + this.get ('hash') + this.get ('ext'))) { fs.unlinkSync (global.appRoot + '/www/public/' + this._path () + '/' + this.get ('hash') + this.get ('ext')); } // check if files if (!fs.readdirSync (global.appRoot + '/www/public/' + this._path ()).length) { // remove directory fs.rmdirSync (global.appRoot + '/www/public/' + this._path ()); } // check if files if (!fs.readdirSync (path.dirname (global.appRoot + '/www/public/' + this._path ())).length) { // remove directory fs.rmdirSync (path.dirname (global.appRoot + '/www/public/' + this._path ())); } // await next await next; } } /** * export file model * * @type {file} */ module.exports = file;
JavaScript
0
@@ -3396,16 +3396,19 @@ 'id' + : thi @@ -3474,16 +3474,19 @@ 'file' + : this. @@ -3531,16 +3531,19 @@ 'name' + : this. @@ -3561,32 +3561,35 @@ ),%0D%0A 'path' + : this._path () @@ -3603,16 +3603,19 @@ 'size' + : this. @@ -3626,16 +3626,60 @@ ('size') +,%0D%0A 'created' : this.get ('created_at') %0D%0A %7D;
b28e198e5d9a79098d66938f266ea00267d26dbf
change mode on login model
lib/bundles/user/models/login.js
lib/bundles/user/models/login.js
/** * Created by Awesome on 2/28/2016. */ // require local dependencies const model = require ('model'); /** * create login model */ class login extends model { /** * construct login model * * @param attrs * @param options */ constructor (attrs, options) { // run super super (attrs, options); } } /** * export login model * * @type {login} */ exports = module.exports = login;
JavaScript
0.000001
a0a4e6d4fc68297913c1726356c9a3c40bbe03de
fix lint
modules/contacts/server/routes/contact.routes.js
modules/contacts/server/routes/contact.routes.js
'use strict'; // ========================================================================= // // Routes for contacts // // ========================================================================= var policy = require ('../policies/contact.policy'); var Contact = require ('../controllers/contact.controller'); var helpers = require ('../../../core/server/controllers/core.helpers.controller'); var fs = require ('fs'); var CSVParse = require('csv-parse'); var loadContacts = function(file, req, res) { // Now parse and go through this thing. fs.readFile(file.path, 'utf8', function(err, data) { if (err) { return console.log(err); } // console.log("FILE DATA:",data); var colArray = ['PERSON_ID','EAO_STAFF_FLAG','PROPONENT_FLAG','SALUTATION','FIRST_NAME','MIDDLE_NAME','LAST_NAME','TITLE','ORGANIZATION_NAME','DEPARTMENT','EMAIL_ADDRESS','PHONE_NUMBER','FAX_NUMBER','CELL_PHONE_NUMBER','ADDRESS_LINE_1','ADDRESS_LINE_2','CITY','PROVINCE_STATE','COUNTRY','POSTAL_CODE','NOTES']; var parse = new CSVParse(data, {delimiter: ',', columns: colArray}, function(err, output){ // Skip this many rows var skip = 1; var length = Object.keys(output).length; console.log("length",length); Object.keys(output).forEach(function(key) { if (skip !== 0) { skip--; // console.log("skipping"); } else { var row = output[key]; // console.log("rowData:",row); var c = new Contact (req.user); c.new().then(function(model) { // console.log("MODEL:",model); // LATER // model.project = row.TITLE; // model.groupId = row.TITLE; // model.contactName = row.TITLE; model.personId = row.PERSON_ID; model.orgName = row.ORGANIZATION_NAME; model.title = row.TITLE; model.firstName = row.FIRST_NAME; model.middleName = row.MIDDLE_NAME; model.lastName = row.LAST_NAME; model.phoneNumber = row.PHONE_NUMBER; model.email = row.EMAIL_ADDRESS; model.eaoStaffFlag = row.EAO_STAFF_FLAG; model.proponentFlag = row.PROPONENT_FLAG; model.salutation = row.SALUTATION; model.department = row.DEPARTMENT; model.faxNumber = row.FAX_NUMBER; model.cellPhoneNumber = row.CELL_PHONE_NUMBER; model.address1 = row.ADDRESS_LINE_1; model.address2 = row.ADDRESS_LINE_2; model.city = row.CITY; model.province = row.PROVINCE_STATE; model.country = row.COUNTRY; model.postalCode = row.POSTAL_CODE; model.notes = row.NOTES; model.save(); }); } }); }); }); } module.exports = function (app) { helpers.setCRUDRoutes (app, 'contact', Contact, policy); app.route ('/api/contact/for/project/:projectid').all (policy.isAllowed) .get (function (req, res) { var p = new Contact (req.user); p.getForProject (req.params.projectid) .then (helpers.success(res), helpers.failure(res)); }); app.route ('/api/contacts/import')//.all (policy.isAllowed) .post (function (req, res) { var file = req.files.file; if (file) { // console.log("Received contact import file:",file); console.log("job submitted"); return new Promise (function (resolve, reject) { loadContacts(file, req, res).then(resolve, reject); }); } }); app.route ('/api/groupcontacts/import')//.all (policy.isAllowed) .post (function (req, res) { var file = req.files.file; if (file) { console.log("Received contact import file:",file); // Now parse and go through this thing. fs.readFile(file.path, 'utf8', function(err, data) { if (err) { return console.log(err); } // console.log("FILE DATA:",data); var colArray = ['GROUP_ID','NAME','ORGANIZATION_NAME','TITLE','FIRST_NAME','MIDDLE_NAME','LAST_NAME','PHONE_NUMBER','EMAIL_ADDRESS','PROJECT_ID']; var parse = new CSVParse(data, {delimiter: ',', columns: colArray}, function(err, output){ var skip = 1; Object.keys(output).forEach(function(key) { if (skip !== 0) { skip--; console.log("skipping"); // Skip the first header } else { var row = output[key]; console.log("rowData:",row); // TODO: 1. First try to find the existing group contact or person contact (create/check params incoming) // 2. Create new if not existing // Object.keys(obj).forEach(function(key) { // var val = obj[key]; // console.log("key:"+key+" ",val); // }); } }); }); helpers.success(res); }); } }); };
JavaScript
0.000013
@@ -3122,16 +3122,17 @@ ;%0A%09%7D);%0A%7D +; %0A%0Amodule
f0d8466a3534ed196f7d90e1ab86126a0c6c7e79
fix error
test/db.js
test/db.js
/* ======================================================================== * DBH-PG: test * ======================================================================== * Copyright 2014 Sapienlab * Licensed under MIT (https://github.com/sapienlab/dbh-pg/blob/master/LICENSE) * ======================================================================== */ describe('DBH', function() { 'use strict'; var assert = require('assert'), DBH = require('../'), Promise = require('bluebird'), using = Promise.using, db = new DBH('postgres://postgres@localhost/db2test'), people = [ {name: 'Aaron', age: 10}, {name: 'Brian', age: 20}, {name: 'Chris', age: 30}, {name: 'David', age: 40}, {name: 'Elvis', age: 50}, {name: 'Frank', age: 60}, {name: 'Grace', age: 70}, {name: 'Haley', age: 80}, {name: 'Irma', age: 90}, {name: 'Jenny', age: 100}, {name: 'Kevin', age: 110}, {name: 'Larry', age: 120}, {name: 'Michelle', age: 130}, {name: 'Nancy', age: 140}, {name: 'Olivia', age: 150}, {name: 'Peter', age: 160}, {name: 'Quinn', age: 170}, {name: 'Ronda', age: 180}, {name: 'Shelley', age: 190}, {name: 'Tobias', age: 200}, {name: 'Uma', age: 210}, {name: 'Veena', age: 220}, {name: 'Wanda', age: 230}, {name: 'Xavier', age: 240}, {name: 'Yoyo', age: 250}, {name: 'Zanzabar', age: 260} ]; before(function() { Promise.longStackTraces(); db.verbose = true; return using(db.conn(), function (conn) { return conn.exec( 'create table person(\ id serial primary key,\ name varchar(10),\ age integer\ )' ).then(function () { var me = this, prepared = DBH.prepare('insert into person(name, age) values ($1, $2)'); return Promise.all(people.map(function (person) { return me.exec(prepared([person.name, person.age])); })); }); }); }); describe('elemental', function() { it('db is instance of DBH', function() { assert.equal(db instanceof DBH, true); }); it('DBH.using is strict equals Promise.using', function() { assert.equal(DBH.using === Promise.using, true); }); }); describe('#conn', function() { it('create connection', function() { return using(db.conn(), function (conn) { return true; }); }); it('exec "select count(age) from person" whith conn.exec', function() { return using(db.conn(), function (conn) { return conn.exec('select count(age) from person') .then(function (result) { assert.equal(result.rows[0].count, 26); }); }); }); it('exec "select count(age) from person" whith conn.count', function() { return using(db.conn(), function (conn) { return conn.count('person') .then(function (count) { assert.equal(count, 26); }); }); }); it('exec "select count(age) from person" whith conn.fetchScalar', function() { return using(db.conn(), function (conn) { return conn.fetchScalar('select count(age) from person') .then(function (count) { assert.equal(count, 26); }); }); }); }); describe('transactions', function () { it('without commit', function() { var id = 2, oldName = 'Old Name', newName = 'New Name', query = 'select name from person where id=' + id; return using(db.conn(), function (conn) { return conn.update('person', { name: oldName }, { id : id }) .then(DBH.fetchScalar(query)) .then(function (name) { assert.equal(name, oldName); }) .then(DBH.begin()) // start transaction .then(DBH.update('person', { name: newName }, { id: id })); // because not commit is here, then auto rollback must be called }).then(function () { return using(db.conn(), function (conn) { return conn.fetchScalar(query) .then(function (name) { assert.equal(oldName, name); assert.notEqual(name, newName); }); }); }); }); it('with commit', function() { var id = 3, oldName = 'Old Name', newName = 'New Name', query = 'select name from person where id=' + id; return using(db.conn(), function (conn) { return conn.update('person', { name: oldName }, { id : id }) .then(DBH.fetchScalar(query)) .then(function (name) { assert.equal(name, oldName); }) .then(DBH.begin()) // start transaction .then(DBH.update('person', { name: newName }, { id: id })) .then(DBH.commit()); }).then(function () { return using(db.conn(), function (conn) { return conn.fetchScalar(query) .then(function (name) { assert.notEqual(oldName, name); assert.equal(name, newName); }); }); }); }); }); describe('fetchOne', function () { var person1 = people[0]; person1.id = 1; it('simple', function() { return using(db.conn(), function(conn) { return conn.fetchOne('select id, name, age from person where id=1'); }).then(function(person) { assert.equal(person, person1); }); }); it('named param', function() { return using(db.conn(), function(conn) { return conn.fetchOne('select id, name, age from person where id=$id', { id: 1 }); }).then(function(person) { assert.equal(person, person1) }); }); it('numeric param', function() { return using(db.conn(), function(conn) { return conn.fetchOne('select id, name, age from person where id=$1', [1]); }).then(function(person) { assert.equal(person, person1) }); }); it('first', function() { return using(db.conn(), function(conn) { return conn.fetchOne('select id, name, age from person'); }).then(function(person) { assert.equal(person, person1) }); }); it('not exists', function() { return using(db.conn(), function(conn) { return conn.fetchOne('select id, name, age from person where id=99999'); }).then(function(person) { assert.equal(person, null) }); }); }); });
JavaScript
0.000002
@@ -6639,33 +6639,37 @@ assert. -e +deepE qual(person, per @@ -6948,33 +6948,37 @@ assert. -e +deepE qual(person, per @@ -7251,33 +7251,37 @@ assert. -e +deepE qual(person, per @@ -7529,33 +7529,37 @@ assert. -e +deepE qual(person, per @@ -7830,25 +7830,29 @@ assert. -e +deepE qual(person,
4c8f1526e4c22032b63cab546f1966a004429199
test fileExistSync
test/fs.js
test/fs.js
'use strict'; var expect = require('chai').expect; var fs = require('fs'); describe('method qfs.fileExists', function() { beforeEach(function() { }); it('file exist tmp', function() { var promise = fs.existsSync('/tmp'); console.log(promise); }); });
JavaScript
0.000001
@@ -74,40 +74,633 @@ ');%0A -%0Adescribe('method qfs.fileE +var path = require(%22path%22);%0A%0A/**%0A * https://gist.github.com/tkihira/2367067%0A */%0Avar rmdir = function(dir) %7B%0A var list = fs.readdirSync(dir);%0A for(var i = 0; i %3C list.length; i++) %7B%0A var filename = path.join(dir, list%5Bi%5D);%0A var stat = fs.statSync(filename);%0A %0A if(filename == %22.%22 %7C%7C filename == %22..%22) %7B%0A // pass these files%0A %7D else if(stat.isDirectory()) %7B%0A // rmdir recursively%0A rmdir(filename);%0A %7D else %7B%0A // rm fiilename%0A fs.unlinkSync(filename);%0A %7D%0A %7D%0A fs.rmdirSync(dir);%0A%7D;%0A%0Adescribe('method fs.e xists +Sync ', f @@ -748,126 +748,894 @@ -%7D);%0A%0A it('file exist tmp', function() %7B%0A%0A var promise = fs.existsSync('/tmp');%0A%0A console.log(promise) + if(true === fs.existsSync('/tmp/vfs-test'))%7B%0A rmdir('/tmp/vfs-test');%0A %7D%0A%0A fs.mkdirSync('/tmp/vfs-test');%0A fs.mkdirSync('/tmp/vfs-test/exist');%0A fs.writeFileSync('/tmp/vfs-test/message.txt', 'Hello Node.js', 'utf8');%0A %7D);%0A%0A it('succeed on existing dir', function() %7B%0A%0A var exist = fs.existsSync('/tmp/vfs-test/exist');%0A%0A expect(exist).to.be.true;%0A%0A %7D);%0A%0A it('fail on not existing dir', function() %7B%0A%0A var exist = fs.existsSync('/tmp/vfs-test/not-exist');%0A%0A expect(exist).to.be.false;%0A%0A %7D);%0A%0A it('succeed on existing file', function() %7B%0A%0A var exist = fs.existsSync('/tmp/vfs-test/message.txt');%0A%0A expect(exist).to.be.true;%0A%0A %7D);%0A%0A it('fail on not existing file', function() %7B%0A%0A var exist = fs.existsSync('/tmp/vfs-test/no-message.txt');%0A%0A expect(exist).to.be.false ;%0A%0A
49afbd2c70aa7af98bc5dd0911c1301aae5e7a88
Use a dummy form submission instead of logging out via xhr.
src/redux/navigation.js
src/redux/navigation.js
const keyMirror = require('keymirror'); const defaults = require('lodash.defaults'); const api = require('../lib/api'); const log = require('../lib/log.js'); const sessionActions = require('./session.js'); const Types = keyMirror({ SET_SEARCH_TERM: null, SET_ACCOUNT_NAV_OPEN: null, TOGGLE_ACCOUNT_NAV_OPEN: null, SET_LOGIN_ERROR: null, SET_LOGIN_OPEN: null, TOGGLE_LOGIN_OPEN: null, SET_CANCELED_DELETION_OPEN: null, SET_REGISTRATION_OPEN: null }); module.exports.getInitialState = () => ({ accountNavOpen: false, canceledDeletionOpen: false, loginError: null, loginOpen: false, registrationOpen: false, searchTerm: '' }); module.exports.navigationReducer = (state, action) => { if (typeof state === 'undefined') { state = module.exports.getInitialState(); } switch (action.type) { case Types.SET_SEARCH_TERM: return defaults({searchTerm: action.searchTerm}, state); case Types.SET_ACCOUNT_NAV_OPEN: return defaults({accountNavOpen: action.isOpen}, state); case Types.TOGGLE_ACCOUNT_NAV_OPEN: return defaults({accountNavOpen: !state.accountNavOpen}, state); case Types.SET_LOGIN_ERROR: return defaults({loginError: action.loginError}, state); case Types.SET_LOGIN_OPEN: return defaults({loginOpen: action.isOpen}, state); case Types.TOGGLE_LOGIN_OPEN: return defaults({loginOpen: !state.loginOpen}, state); case Types.SET_CANCELED_DELETION_OPEN: return defaults({canceledDeletionOpen: action.isOpen}, state); case Types.SET_REGISTRATION_OPEN: return defaults({registrationOpen: action.isOpen}, state); default: return state; } }; module.exports.setAccountNavOpen = isOpen => ({ type: Types.SET_ACCOUNT_NAV_OPEN, isOpen: isOpen }); module.exports.handleToggleAccountNav = () => ({ type: Types.TOGGLE_ACCOUNT_NAV_OPEN }); module.exports.setCanceledDeletionOpen = isOpen => ({ type: Types.SET_CANCELED_DELETION_OPEN, isOpen: isOpen }); module.exports.setLoginError = loginError => ({ type: Types.SET_LOGIN_ERROR, loginError: loginError }); module.exports.setLoginOpen = isOpen => ({ type: Types.SET_LOGIN_OPEN, isOpen: isOpen }); module.exports.toggleLoginOpen = () => ({ type: Types.TOGGLE_LOGIN_OPEN }); module.exports.setRegistrationOpen = isOpen => ({ type: Types.SET_REGISTRATION_OPEN, isOpen: isOpen }); module.exports.setSearchTerm = searchTerm => ({ type: Types.SET_SEARCH_TERM, searchTerm: searchTerm }); module.exports.handleCompleteRegistration = () => (dispatch => { dispatch(sessionActions.refreshSession()); dispatch(module.exports.setRegistrationOpen(false)); }); module.exports.closeAccountMenus = () => (dispatch => { dispatch(module.exports.setAccountNavOpen(false)); dispatch(module.exports.setRegistrationOpen(false)); }); module.exports.handleLogIn = (formData, callback) => (dispatch => { dispatch(module.exports.setLoginError(null)); formData.useMessages = true; // NOTE: this may or may not be being used anywhere else api({ method: 'post', host: '', uri: '/accounts/login/', json: formData, useCsrf: true }, (err, body) => { if (err) dispatch(module.exports.setLoginError(err.message)); if (body) { body = body[0]; if (body.success) { dispatch(module.exports.setLoginOpen(false)); body.messages.forEach(message => { if (message.message === 'canceled-deletion') { dispatch(module.exports.setCanceledDeletionOpen(true)); } }); dispatch(sessionActions.refreshSession()); callback({success: true}); } else { if (body.redirect) { window.location = body.redirect; } // Update login error message to a friendlier one if it exists dispatch(module.exports.setLoginError(body.msg)); // JS error already logged by api mixin callback({success: false}); } } else { // JS error already logged by api mixin callback({success: false}); } }); }); module.exports.handleLogOut = () => (dispatch => { api({ host: '', method: 'post', uri: '/accounts/logout/', useCsrf: true }, err => { if (err) log.error(err); dispatch(module.exports.setLoginOpen(false)); dispatch(module.exports.setAccountNavOpen(false)); window.location = '/'; }); });
JavaScript
0
@@ -110,24 +110,59 @@ /lib/api');%0A +const jar = require('../lib/jar');%0A const log = @@ -4415,32 +4415,26 @@ ut = () =%3E ( -dispatch +() =%3E %7B%0A ap @@ -4435,122 +4435,234 @@ -api(%7B%0A host: '',%0A method: 'post',%0A uri: '/accounts/logout/',%0A useCsrf: true%0A %7D +// POST to /accounts/logout using a dummy form instead of XHR. This ensures%0A // logout only happens AFTER onbeforeunload has the chance to prevent nagivation.%0A jar.use('scratchcsrftoken', '/csrf_token/' , +( err +, csrftoken) =%3E @@ -4679,16 +4679,23 @@ if (err) + return log.err @@ -4701,156 +4701,530 @@ ror( -err);%0A dispatch(module.exports.setLoginOpen(false));%0A dispatch(module.exports.setAccountNavOpen(false));%0A window.location = '/' +'Error while retrieving CSRF token', err);%0A const form = document.createElement('form');%0A form.setAttribute('method', 'POST');%0A form.setAttribute('action', '/accounts/logout/');%0A const csrfField = document.createElement('input');%0A csrfField.setAttribute('type', 'hidden');%0A csrfField.setAttribute('name', 'csrfmiddlewaretoken');%0A csrfField.setAttribute('value', csrftoken);%0A form.appendChild(csrfField);%0A document.body.appendChild(form);%0A form.submit() ;%0A
b8acab6bcc1f207c77b3f825e12f2fe9d41d924b
Tweak d3.geo.eisenlohr.invert.
geo/projection/eisenlohr.js
geo/projection/eisenlohr.js
// @import august function eisenlohr(λ, φ) { var s0 = Math.sin(λ /= 2), c0 = Math.cos(λ), k = Math.sqrt(Math.cos(φ)), c1 = Math.cos(φ /= 2), t = Math.sin(φ) / (c1 + Math.SQRT2 * c0 * k), c = Math.sqrt(2 / (1 + t * t)), v = Math.sqrt((Math.SQRT2 * c1 + (c0 + s0) * k) / (Math.SQRT2 * c1 + (c0 - s0) * k)); return [ eisenlohrK * (c * (v - 1 / v) - 2 * Math.log(v)), eisenlohrK * (c * t * (v + 1 / v) - 2 * Math.atan(t)) ]; } eisenlohr.invert = function(x, y) { var p = d3.geo.august.raw.invert(x, y); if (!p) return null; var λ = p[0], φ = p[1], i = 50, sqrt2 = Math.SQRT2; if (Math.abs(φ) > 89 * radians) λ = sgn(λ) * π; x /= eisenlohrK, y /= eisenlohrK; do { var _0 = λ / 2, _1 = φ / 2, s0 = Math.sin(_0), c0 = Math.cos(_0), s1 = Math.sin(_1), c1 = Math.cos(_1), cos1 = Math.cos(φ), k = Math.sqrt(cos1), t = s1 / (c1 + sqrt2 * c0 * k), t2 = t * t, c = Math.sqrt(2 / (1 + t2)), v0 = (Math.SQRT2 * c1 + (c0 + s0) * k), v1 = (Math.SQRT2 * c1 + (c0 - s0) * k), v = Math.sqrt(v0 / v1), fx = c * (v - 1 / v) - 2 * Math.log(v) - x, fy = c * t * (v + 1 / v) - 2 * Math.atan(t) - y, δtδλ = s1 && Math.SQRT1_2 * k * s0 * t2 / s1, δtδφ = (Math.SQRT2 * c0 * c1 + k) / (2 * (c1 + sqrt2 * c0 * k) * (c1 + sqrt2 * c0 * k) * k), δcδt = -.5 * t * c * c * c, δcδλ = δcδt * δtδλ, δcδφ = δcδt * δtδφ, A = (A = 2 * c1 + Math.SQRT2 * k * (c0 - s0)) * A * v, δvδλ = (Math.SQRT2 * c0 * c1 * k + cos1) / A, δvδφ = -(Math.SQRT2 * s0 * s1) / (k * A), δxδλ = (v - 1 / v) * δcδλ - 2 * δvδλ / v + c * (δvδλ + δvδλ / (v * v)), δxδφ = (v - 1 / v) * δcδφ - 2 * δvδφ / v + c * (δvδφ + δvδφ / (v * v)), δyδλ = t * (1 / v + v) * δcδλ - 2 * δtδλ / (1 + t * t) + c * (1 / v + v) * δtδλ + c * t * (δvδλ - δvδλ / (v * v)), δyδφ = t * (1 / v + v) * δcδφ - 2 * δtδφ / (1 + t * t) + c * (1 / v + v) * δtδφ + c * t * (δvδφ - δvδφ / (v * v)), denominator = δxδφ * δyδλ - δyδφ * δxδλ, δλ = (fy * δxδφ - fx * δyδφ) / denominator, δφ = (fx * δyδλ - fy * δxδλ) / denominator; λ = Math.max(-π, Math.min(π, λ - δλ)); φ = Math.max(-π / 2, Math.min(π / 2, φ - δφ)); } while ((Math.abs(δλ) > ε || Math.abs(δφ) > ε2) && --i > 0); return Math.abs(Math.abs(φ) - π / 2) < ε ? [0, φ] : i && [λ, φ]; }; var eisenlohrK = 3 + 2 * Math.SQRT2; (d3.geo.eisenlohr = function() { return projection(eisenlohr); }).raw = eisenlohr;
JavaScript
0
@@ -540,19 +540,33 @@ invert(x -, y + / 1.2, y * 1.065 );%0A if @@ -629,86 +629,10 @@ i = -50,%0A sqrt2 = Math.SQRT2;%0A if (Math.abs(%CF%86) %3E 89 * radians) %CE%BB = sgn(%CE%BB) * %CF%80 +20 ;%0A @@ -897,28 +897,33 @@ s1 / (c1 + -sqrt +Math.SQRT 2 * c0 * k), @@ -1320,36 +1320,41 @@ k) / (2 * (c1 + -sqrt +Math.SQRT 2 * c0 * k) * (c @@ -1357,20 +1357,25 @@ * (c1 + -sqrt +Math.SQRT 2 * c0 * @@ -2100,25 +2100,54 @@ %CF%86 * %CE%B4x%CE%B4%CE%BB -, +; %0A - +if (!denominator) break;%0A var %CE%B4%CE%BB = (f @@ -2245,43 +2245,13 @@ %CE%BB -= Math.max(-%CF%80, Math.min(%CF%80, %CE%BB - += %CE%B4%CE%BB -)) ;%0A @@ -2299,16 +2299,16 @@ - %CE%B4%CF%86));%0A + %7D whil @@ -2347,17 +2347,16 @@ (%CE%B4%CF%86) %3E %CE%B5 -2 ) && --i
ea4ed864c87ddb6c92351298fd1fcfbc082887f9
Fix content-length bug for api.js Well, it finally happened. I made an assumption about text and it bit me in the butt. Protip: not everything is 1 byte per character!
api.js
api.js
/* The MIT License (MIT) Copyright (c) 2013 Calvin Montgomery Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ var Auth = require("./auth.js"); var Server = require("./server.js"); var Logger = require("./logger.js"); var apilog = new Logger.Logger("api.log"); var jsonHandlers = { "channeldata": handleChannelData, "listloaded" : handleChannelList }; function handle(path, req, res) { var parts = path.split("/"); var last = parts[parts.length - 1]; var params = {}; if(last.indexOf("?") != -1) { parts[parts.length - 1] = last.substring(0, last.indexOf("?")); var plist = last.substring(last.indexOf("?") + 1).split("&"); for(var i = 0; i < plist.length; i++) { var kv = plist[i].split("="); if(kv.length != 2) { res.send(400); return; } params[unescape(kv[0])] = unescape(kv[1]); } } for(var i = 0; i < parts.length; i++) { parts[i] = unescape(parts[i]); } if(parts.length != 2) { res.send(400); return; } if(parts[0] == "json") { if(!(parts[1] in jsonHandlers)) { res.end(JSON.stringify({ error: "Unknown endpoint: " + parts[1] }, null, 4)); return; } jsonHandlers[parts[1]](params, req, res); } else { res.send(400); } } exports.handle = handle; function handleChannelData(params, req, res) { var clist = params.channel || ""; clist = clist.split(","); var data = []; for(var j = 0; j < clist.length; j++) { var cname = clist[j]; if(!cname.match(/^[a-zA-Z0-9]+$/)) { continue; } var d = { name: cname, loaded: (cname in Server.channels) }; if(d.loaded) { var chan = Server.channels[cname]; d.title = chan.media ? chan.media.title : "-"; d.usercount = chan.users.length; d.users = []; for(var i = 0; i < chan.users.length; i++) { if(chan.users[i].name) { d.users.push(chan.users[i].name); } } d.chat = []; for(var i = 0; i < chan.chatbuffer.length; i++) { d.chat.push(chan.chatbuffer[i]); } } data.push(d); } var response = JSON.stringify(data, null, 4); res.setHeader("Content-Type", "application/json"); res.setHeader("Content-Length", response.length); res.end(response); } function handleChannelList(params, req, res) { var name = params.name || ""; var pw = params.pw || ""; if(!Auth.login(name, pw)) { res.send(403); return; } var clist = []; for(var key in Server.channels) { clist.push(key); } handleChannelData({channel: clist.join(",")}, req, res); }
JavaScript
0
@@ -3417,16 +3417,77 @@ ull, 4); +%0A var len = unescape(encodeURIComponent(response)).length; %0A%0A re @@ -3575,23 +3575,11 @@ h%22, -response.length +len );%0A
19e1866dbd2ae7ef23cf8a5667e45c8f7e4551d7
add comments
src/routes/Zen/index.js
src/routes/Zen/index.js
import { injectReducer } from '../../store/reducers' export default (store) => ({ path: 'zen', /* Async getComponent is only invoked when route matches */ getComponent (nextState, cb) { require.ensure([], (require) => { const Zen = require('./containers/ZenContainer').default const reducer = require('./modules/zen').default injectReducer(store, { key: 'zen', reducer }) cb(null, Zen) }) } })
JavaScript
0
@@ -189,16 +189,147 @@ , cb) %7B%0A + /* Webpack - use 'require.ensure' to create a split point%0A and embed an async module loader (jsonp) when bundling */%0A requ
82bfaaa4de3c1b2118e7c365a05e6e6c32f84dde
Use debug log level instead of info.
lib/middleware/authentication.js
lib/middleware/authentication.js
/** * Copyright 2012 Tomaz Muraus * * 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 async = require('async'); var log = require('logmagic').local('lib.middleware.authentication'); var sprintf = require('sprintf').sprintf; var client = require('../database').getClient(); var request = require('../util/request').request; var KeystoneClient = require('../util/keystone_client').KeystoneClient; /** * Middleware for authenticating against the Rackspace Cloud Auth API. * * If a valid token is provided is also cached in Redis until it expires. */ function cacheToken(cacheKey, tenantId, token, expires, callback) { var expiresTs = misc.dateStrToUnixTimestamp(expires), nowTs = new Date().getTime() / 1000, ttl = (expiresTs - nowTs), data = { 'token': token, 'tenantId': tenantId }, multi = client.multi(); if (ttl < 1) { log.info('Token already expired, not caching it...'); callback(); return; } log.info('Caching new auth token', {'tenantId': tenantId, 'expires': expires}); multi.set(key, value); expire.ttl(key, ttl); multi.exec(callback); } function verifyToken(tenantId, token, callback) { var settings = config.middleware.authentication.settings, settings, clientOptions = {'username': settings.username, 'password': settings.password}, clientParams = [{'url': settings.us_url, 'options': clientOptions}, {'url': settings.uk_url, 'options': clientOptions}], result = {}; async.some(clientParams, function(params, callback) { var client = new KeystoneClient(params.url, params.options); client.validateTokenForTenant(tenantId, token, function(err, data) { if (err) { log.error('Auth service returned an error', {'url': params.url, 'err': err}); callback(false); return; } if (!err && data) { log.debug('Auth service returned that a token is valid', {'url': params.url}); result.username = data.token.userId; result.expires = data.token.expires; callback(true); } }); }, function(valid) { if (!valid) { callback(new Error('invalid or expired authentication token')); return; } callback(null, result); }); } exports.processRequest = function(req, res, callback) { var tenantId = req._tenantId, token = req.headers['x-auth-token'], cacheKey; if (!token) { res.writeHead(401, {'Content-Type': 'text/plain'}); res.end('No authentication token provided'); callback(new Error('No authentication token provided')); return; } cacheKey = 'auth-token-' + token + '-' + tenantId async.waterfall([ function getTokenFromCache(callback) { client.get(cacheKey, callback); }, function maybeVerifyToken(data, callback) { if (data) { log.info('Token already in the cache, skipping verification via API server...'); callback(null, null); return; } verifyToken(tenantId, token, callback); }, function cacheToken(result, callback) { if (!result) { // Token is already in the cache. callback(); return; } cacheToken(cacheKey, tenantId, token, result.expires, callback); } ], function(err) { if (err) { res.writeHead(401, {'Content-Type': 'text/plain'}); res.end(err.message); callback(err); return; } callback(); }); };
JavaScript
0
@@ -1403,36 +1403,37 @@ %3C 1) %7B%0A log. -info +debug ('Token already @@ -1501,20 +1501,21 @@ %0A%0A log. -info +debug ('Cachin @@ -1578,17 +1578,16 @@ ires%7D);%0A -%0A multi. @@ -3372,12 +3372,13 @@ log. -info +debug ('To @@ -3497,24 +3497,104 @@ n;%0A %7D%0A%0A + log.debug('Token not in cache, verifying it against the keystone API...')%0A verify
879652d45f41efefb56f41f49ef7ad5973bdae5c
fix redirect after registration
resources/assets/app/view-models/users/register.js
resources/assets/app/view-models/users/register.js
import {inject} from 'aurelia-framework'; import {Router} from 'aurelia-router'; import {Validation} from 'aurelia-validation'; import {UserService} from 'services/users/user-service'; import {Notification} from 'services/notification'; @inject(Router, Validation, UserService, Notification) export class Register { constructor(router, validation, userService, notification) { this.router = router; this.userService = userService; this.notification = notification; this.validation = validation.on(this) .ensure('username', (config) => { config.useDebounceTimeout(150); }) .isNotEmpty() .hasLengthBetween(3, 25) .passes((newValue) => { // Todo: Simplify this? return new Promise((accept, reject) => { this.userService.isUsernameExisting(newValue).then(data => { if (data.length !== 0) { reject('is already taken'); } else { accept(); } }); }); }) .ensure('email', (config) => { config.useDebounceTimeout(150); }) .isNotEmpty() .isEmail() .passes((newValue) => { // Todo: Simplify this? return new Promise((accept, reject) => { this.userService.isEmailExisting(newValue).then(data => { if (data.length !== 0) { reject('is already taken'); } else { accept(); } }); }); }) .ensure('password') .isNotEmpty() .hasLengthBetween(8, 32) .isStrongPassword() .ensure('password_repeat', (config) => { config.computedFrom(['password']); }) .isNotEmpty() .isEqualTo(() => { return this.password; }, 'the entered password'); } register() { this.validation.validate().then( () => { let user = { 'username': this.username, 'email': this.email, 'password': this.password, 'password_repeat': this.password_repeat }; this.userService.register(user).then(data => { if (!data.id) { this.notification.danger('You have got errors in your registration.'); } else { this.notification.success('You have been registered successfully.'); this.router.navigate('/users/signin'); } }); }, () => { this.notification.danger('You have got errors in your registration.'); } ); } }
JavaScript
0.001422
@@ -2355,21 +2355,20 @@ igate('/ -users +auth /signin'
001d0e252c3c3e1427d0e2e39af519f0fbec164c
Clear token before trying to log in.
lib/passport-userapp/strategy.js
lib/passport-userapp/strategy.js
/** * Module dependencies. */ var passport = require('passport'), UserApp = require('userapp'), util = require('util'); /** * `Strategy` constructor. * * The local authentication strategy authenticates requests based on the * credentials submitted through an HTML-based login form, or using a * session token sent as a cookie. * * Applications must supply a `verify` callback which accepts `username` and * `password` credentials, and then calls the `done` callback supplying a * `user`, which should be set to `false` if the credentials are not valid. * If an exception occured, `err` should be set. * * Optionally, `options` can be used to change the fields in which the * credentials are found. * * Options: * - `usernameField` field name where the username is found, defaults to _username_ * - `passwordField` field name where the password is found, defaults to _password_ * - `sessionCookie` cookie name where the session token is found, defaults to _ua_session_token_ * - `appId` the UserApp App Id to connect to * * Examples: * * passport.use(new LocalStrategy( * function(username, password, done) { * User.findOne({ username: username, password: password }, function (err, user) { * done(err, user); * }); * } * )); * * @param {Object} options * @param {Function} verify * @api public */ function Strategy(options, verify) { if (typeof options == 'function') { verify = options; options = {}; } if (!verify) throw new Error('userapp authentication strategy requires a verify function'); if (!options.appId) throw new Error('userapp strategy requires an app id'); this._appId = options.appId; this._usernameField = options.usernameField || 'username'; this._passwordField = options.passwordField || 'password'; this._sessionCookie = options.sessionCookie || 'ua_session_token'; this._realm = options.realm || 'Users'; passport.Strategy.call(this); this.name = 'userapp'; this._verify = verify; // Initialize UserApp UserApp.initialize({ appId: this._appId }); } /** * Inherit from `passport.Strategy`. */ util.inherits(Strategy, passport.Strategy); /** * Authenticate request based on the contents of a form submission * or session cookie. * * @param {Object} req * @api protected */ Strategy.prototype.authenticate = function (req, options, next) { var self = this; options = options || {}; var username = lookup(req.body, this._usernameField) || lookup(req.query, this._usernameField); var password = lookup(req.body, this._passwordField) || lookup(req.query, this._passwordField); var sessionToken = req.cookies ? req.cookies[this._sessionCookie] : null; var authorization = req.headers['authorization']; if (authorization) { var parts = authorization.split(' '); if (parts.length < 2) { return this.fail(400); } var scheme = parts[0], credentials = new Buffer(parts[1], 'base64').toString().split(':'); if (!/Basic/i.test(scheme)) { return this.fail(this._challenge()); } if (credentials.length < 2) { return this.fail(400); } username = credentials[0]; password = credentials[1]; if (!username && password) { sessionToken = password; } else if (!username || !password) { return this.fail(this._challenge()); } } if ((!username || !password) && !sessionToken && !authorization) { //return this.fail(this._challenge()); return this.fail('Missing credentials or session cookie'); } function verified(err, user, info) { if (err) { return self.error(err); } if (!user) { return self.fail(info); } self.success(user, info); } function parseProfile(userappUser) { return { provider: 'userapp', id: userappUser.user_id, username: userappUser.login, name: { familyName: userappUser.last_name, givenName: userappUser.first_name }, email: userappUser.email, emails: [ { value: userappUser.email } ], permissions: userappUser.permissions, features: userappUser.features, properties: userappUser.properties, subscription: userappUser.subscription, lastLoginAt: userappUser.last_login_at, updatedAt: userappUser.updated_at, createdAt: userappUser.created_at, token: UserApp.global.token, _raw: userappUser }; } function lookup(obj, field) { if (!obj) { return null; } var chain = field.split(']').join('').split('['); for (var i = 0, len = chain.length; i < len; i++) { var prop = obj[chain[i]]; if (typeof(prop) === 'undefined') { return null; } if (typeof(prop) !== 'object') { return prop; } obj = prop; } return null; } function getUser() { UserApp.User.get({ user_id: 'self' }, function(error, users) { if (!error && users && users.length > 0) { self._verify(parseProfile(users[0]), verified); } else { self._verify(false, verified); } }); } if (sessionToken && req.isAuthenticated()) { self._verify(req.user, verified); return; } if (sessionToken && !username) { UserApp.setToken(sessionToken); getUser(); } else { UserApp.User.login({ login: username, password: password }, function(error) { if (error) { self._verify(false, verified); } else { getUser(); } }); } }; /** * Authentication challenge. * * @api private */ Strategy.prototype._challenge = function() { return 'Basic realm="' + this._realm + '"'; } /** * Expose `Strategy`. */ module.exports = Strategy;
JavaScript
0
@@ -5748,32 +5748,64 @@ );%0A %7D else %7B%0A + UserApp.setToken(null);%0A UserApp. @@ -6238,8 +6238,9 @@ trategy; +%0A
ffadc5ded81c6e8a42a4ac03673341f73f65e65b
remove strayed console.log
src/showdown-youtube.js
src/showdown-youtube.js
/** * Youtube Extension. * Uses image syntax to embed videos * Usage: * ![youtube video][http://youtu.be/dQw4w9WgXcQ] * * or * * ![youtube video][1] * [1]: http://youtu.be/dQw4w9WgXcQ */ (function (extension) { 'use strict'; if (showdown) { // global (browser or nodejs global) extension(showdown); } else if (typeof define === 'function' && define.amd) { // AMD define(['showdown'], extension); } else if (typeof exports === 'object') { // Node, CommonJS-like module.exports = extension(require('showdown')); } else { // showdown was not found so we throw throw Error('Could not find showdown library'); } }(function (showdown) { var svg = '<div class="youtube-preview" style="width:%2; height:%3; background-color:#333; position:relative;">' + '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" ' + ' width="100" height="70" viewBox="0 0 100 70"' + ' style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);">' + ' <defs>' + ' <linearGradient id="grad1" x1="0%" x2="0%" y1="0%" x2="0%" y2="100%">' + ' <stop offset="0%" style="stop-color:rgb(229,45,49);stop-opacity:1" />' + ' <stop offset="100%" style="stop-color:rgb(191,23,29);stop-opacity:1" />' + ' </linearGradient>' + ' </defs>' + ' <rect width="100%" height="100%" rx="26" fill="url(#grad1)"/>' + ' <polygon points="35,20 70,35 35,50" fill="#fff"/>' + ' <polygon points="35,20 70,35 64,37 35,21" fill="#e8e0e0"/>' + '</svg>' + '<div style="text-align:center; padding-top:10px; color:#fff"><a href="//youtu.be/%1">youtu.be/%1</a></div>' + '</div>', iframe = '<iframe width="%2" height="%3" src="//www.youtube.com/embed/%1?rel=0" frameborder="0" allowfullscreen></iframe>', img = '<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs=" width="%2" height="%3">', imgRegex = /(?:<p>)?<img.*?src="(.+?)"(.*?)\/?>(?:<\/p>)?/gi, fullLinkRegex = /(?:(?:https?:)?(?:\/\/)?)(?:(?:www)?\.)?youtube\.(?:.+?)\/(?:(?:watch\?v=)|(?:embed\/))([a-zA-Z0-9_-]{11})/i, shortLinkRegex = /(?:(?:https?:)?(?:\/\/)?)?youtu\.be\/([a-zA-Z0-9_-]{11})/i; function parseDimensions(rest) { var width, height, d; if (rest) { width = (d = /width="(.+?)"/.exec(rest)) ? d[1] : '420'; height = (d = /height="(.+?)"/.exec(rest)) ? d[1] : '315'; } // add units so they can be used in css if (/^\d+$/gm.exec(width)) { width += 'px'; } if (/^\d+$/gm.exec(height)) { height += 'px'; } return { width: width, height: height }; } /** * Replace with video iframes */ showdown.extension('youtube', function () { return [ { // It's a bit hackish but we let the core parsers replace the reference image for an image tag // then we replace the full img tag in the output with our iframe type: 'output', filter: function (text, converter, options) { var tag = iframe; if (options.smoothLivePreview) { tag = (options.youtubeUseImg) ? img : svg; } return text.replace(imgRegex, function (match, url, rest) { var d = parseDimensions(rest), m; if ((m = shortLinkRegex.exec(url)) || (m = fullLinkRegex.exec(url))) { console.log(m[1]); return tag.replace(/%1/g, m[1]).replace('%2', d.width).replace('%3', d.height); } else { return match; } }); } } ]; }); }));
JavaScript
0.000001
@@ -3440,41 +3440,8 @@ ) %7B%0A - console.log(m%5B1%5D);%0A
b1046970650c12651bf62c7db403a49c90beebe0
call it a day
app.js
app.js
// Import the discord.js module const Discord = require('discord.js'); const fs = require('fs') var schedule = require('node-schedule'); var tools = require('./tools') const CHAN_ID_DKC_GENERAL = "349976478538268674"; const CHAN_ID_DKC_FLAAMLOGS = "350728940501073924"; const CHAN_ID_QGS_FLAAMCHAN = "330420560972742656"; // Create an instance of a Discord client var client = new Discord.Client(); tools.client = client; tools.CHAN_ID_DKC_FLAAMLOGS = CHAN_ID_DKC_FLAAMLOGS; client.on('ready', () => { var revision = require('child_process') .execSync('git rev-parse HEAD') .toString().trim(); var bootMessage = ""; bootMessage += ":smirk_cat: Flaambot starting :smirk_cat:"+"\n" bootMessage += "**revision : **" + revision+"\n" bootMessage += "ready \:heart_eyes_cat:" tools.sendToLogChannel(bootMessage) fs.stat('./images/today.jpg', function(err, stat) { if(err == null) { console.log(stat.birthdate) filetime = Date(stat.birthtimeMs).toLocaleFormat('%m/%d/%Y'); today = new Date(); dd = today.getDate(); mm = today.getMonth()+1; //January is 0! yyyy = today.getFullYear(); if(dd<10){ dd='0'+dd; } if(mm<10){ mm='0'+mm; } today = yyyy+'/'+mm+'/'+dd; if(filetime < today) { tools.sendToLogChannel(":smirk_cat: Replacing the picture :smirk_cat:") } else { tools.sendToLogChannel(":smirk_cat: No need to change the picture yet :smirk_cat:") } } else { fs.readdir('./images/available/', function (err, files) { if(files.length > 0) { key = Math.floor(Math.random() * files.length) target = files[key] fs.rename('./images/available/'+target, './images/today.jpg'), function (success) { fs.stat('./images/today.jpg', function(err, stat) { if(err == null) { tools.sendToLogChannel(":smirk_cat: today.jpg updated :smirk_cat:") } else { tools.sendToLogChannel(":scream_cat: Could not create today.jpg :scream_cat:") } }) } } else { tools.sendToLogChannel(":scream_cat: No more pics :scream_cat:"); } }) } }); var rule = new schedule.RecurrenceRule(); rule.minute = 0; rule.hour = 6; // rule.second =30; var j = schedule.scheduleJob(rule, function() { client.channels.get(CHAN_ID_DKC_GENERAL).send("Testing change"); /* * client.channels.get("330420560972742656").send({ "embed": { title: * 'Photo de Flaam du jour <3', image: { "url" : * "http://172.104.154.243/pics/today.jpg" } } }); console.log('Pics * sent to channel !'); */ }); }); // Create an event listener for messages client.on('message', message => { if (message.content === '!availableImages') { // Send "pong" to the same channel message.channel.send('Here is a list of available images :'); } if (message.content === '!usedImages') { // Send "pong" to the same channel message.channel.send('Here is a list of used images :'); } }); // Log our bot in client.login(process.env.FLAAMBOT_DISCORD_TOKEN);
JavaScript
0.000014
@@ -916,20 +916,22 @@ at.birth -date +timeMs )%0A%09%09%09fil @@ -982,20 +982,45 @@ t('%25 -m/%25d/%25Y +Y/%25m/%25d ');%0A%0A +%09%09%09console.log(filetime)%0A %09%09%09t
4dfdb2eaea2a16b7775ef8723fe3ac08696d3b7f
Fix example
app.js
app.js
#!/usr/bin/env node /* * SQL API loader * =============== * * node app [environment] * * environments: [development, test, production] * */ var fs = require('fs'); var path = require('path'); var argv = require('yargs') .usage('Usage: $0 <environment> [options]') .help('h') .example( '$0 production -c /etc/windshaft/config.js', 'start server in production environment with /etc/windshaft/config.js as configuration file' ) .alias('h', 'help') .alias('c', 'config') .nargs('c', 1) .describe('c', 'Load configuration from path') .argv; var environmentArg = argv._[0] || process.env.NODE_ENV || 'development'; var configurationFile = path.resolve(argv.config || './config/environments/' + environmentArg + '.js'); if (!fs.existsSync(configurationFile)) { console.error('Configuration file "%s" does not exist', configurationFile); process.exit(1); } global.settings = require(configurationFile); var ENVIRONMENT = argv._[0] || process.env.NODE_ENV || global.settings.environment; process.env.NODE_ENV = ENVIRONMENT; var availableEnvironments = ['development', 'production', 'test', 'staging']; // sanity check arguments if (availableEnvironments.indexOf(ENVIRONMENT) === -1) { console.error("node app.js [environment]"); console.error("Available environments: " + availableEnvironments.join(', ')); process.exit(1); } global.settings.api_hostname = require('os').hostname().split('.')[0]; global.log4js = require('log4js'); var log4jsConfig = { appenders: [], replaceConsole: true }; if ( global.settings.log_filename ) { var logFilename = path.resolve(global.settings.log_filename); var logDirectory = path.dirname(logFilename); if (!fs.existsSync(logDirectory)) { console.error("Log filename directory does not exist: " + logDirectory); process.exit(1); } console.log("Logs will be written to " + logFilename); log4jsConfig.appenders.push( { type: "file", absolute: true, filename: logFilename } ); } else { log4jsConfig.appenders.push( { type: "console", layout: { type:'basic' } } ); } global.log4js.configure(log4jsConfig); global.logger = global.log4js.getLogger(); // kick off controller if ( ! global.settings.base_url ) { global.settings.base_url = '/api/*'; } var version = require("./package").version; var server = require('./app/server')(); server.listen(global.settings.node_port, global.settings.node_host, function() { console.info('Using configuration file "%s"', configurationFile); console.log( "CartoDB SQL API %s listening on %s:%s PID=%d (%s)", version, global.settings.node_host, global.settings.node_port, process.pid, ENVIRONMENT ); }); process.on('uncaughtException', function(err) { global.logger.error('Uncaught exception: ' + err.stack); }); process.on('SIGHUP', function() { global.log4js.clearAndShutdownAppenders(function() { global.log4js.configure(log4jsConfig); global.logger = global.log4js.getLogger(); console.log('Log files reloaded'); }); }); process.on('SIGTERM', function () { server.batch.stop(); server.batch.drain(function (err) { if (err) { console.log('Exit with error'); return process.exit(1); } console.log('Exit gracefully'); process.exit(0); }); });
JavaScript
0.998536
@@ -319,33 +319,31 @@ ion -c /etc/ -windshaft +sql-api /config.js', @@ -405,17 +405,15 @@ etc/ -windshaft +sql-api /con @@ -424,31 +424,24 @@ js as config -uration file'%0A )
90b2b9938b48bfbf25671d1e0418939b8b79e24e
remove extra console.log
app.js
app.js
/* * REQUIRES */ var express = require('express'); var session = require('express-session'); var http = require('http'); var path = require('path'); var fs = require('fs'); var _ = require('underscore'); var bodyParser = require('body-parser'); var PATH_SEP = path.sep; var protectStaticPath = require(path.join(__dirname, PATH_SEP + 'lib' + PATH_SEP + 'protectStaticPath')); var logFn = require(path.join(__dirname, PATH_SEP + 'lib' + PATH_SEP + 'logFn')); /* * VARS */ var assetPath = path.join(__dirname, PATH_SEP + 'assets'); var publicPath = assetPath + PATH_SEP + 'public'; var loginHtmlPath = publicPath + PATH_SEP + 'login.html'; var loginHtml = fs.readFileSync(loginHtmlPath, 'utf8'); /* * READ CONFIG FILE */ var config; try { config = require(path.join(__dirname, PATH_SEP + 'config')); } catch (err) { logFn('ERROR: could not load `./config.js` (TIP: create a config file from `./config_example.js`)\n'); logFn(err, true); process.exit(1); } /* * PROCESS CONFIG */ //get unique protected paths var paths = _.uniq(_.pluck(config.users, 'path')); /* * EXPRESS INIT */ var app = express(); //middleware: session app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: true, name: 'gdm.sid', cookie: { path: '/', maxAge: null, secure: false, //https only httpOnly: true, }, })); //middleware: for parsing application/json app.use(bodyParser.json()); //middleware: for parsing application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: true })); /* * EXPRESS ROUTES */ //the root route is the login page app.get('/', function(req, res) { logFn('Serving login page to: ' + req.ip); res.end(loginHtml); }); //mount protected paths paths.forEach(function(path) { app.use(protectStaticPath(path)); app.use('/' + path, express.static(assetPath + PATH_SEP + path)); }); //otherwise, serve public static assets app.use('/', express.static(publicPath)); //post login route app.post('/login', function(req, res) { console.log(req.session); //look up user var result = _.find(config.users, function(user) { if (user.username === req.body.username) { return true; } else { return false; } }); //check if we found a user if (_.isUndefined(result)) { logFn('failed login from ' + req.ip); logFn(req.body, true); res.send({ sc: 1 }); //check users password } else if (result.password === req.body.password) { req.session.user = result; req.session.loggedIn = true; logFn('successful login for ' + result.username + ' (' + req.ip + ')'); res.send({ sc: 0 }); //password did not match } else { logFn('failed login from ' + req.ip); logFn(req.body, true); res.send({ sc: 1 }); } }); //post login route app.post('/logout', function(req, res) { req.session.loggedIn = false; logFn('successful logout for ' + req.session.user.username + ' (' + req.ip + ')'); res.send({ sc: 0 }); }); /* * WEB SERVER INIT */ http.createServer(app).listen(config.port, function() { logFn('listening on port ' + config.port); });
JavaScript
0.000002
@@ -2024,37 +2024,8 @@ ) %7B%0A - console.log(req.session);%0A%0A //
53f247d1a590623306ac697ac275fb09413ed587
Revert FB service
lib/services/facebook.service.js
lib/services/facebook.service.js
var serviceName = "facebook"; var request = require("request"); var serviceConfig = require("./../config/services.config.json"); function facebook (cb) { var result = { service: serviceName, status: false }; request({ url: serviceConfig[serviceName], method: "GET", headers: { "User-Agent": 'request' } }, function(error, response, body) { if(error) { result["message"] = "Problem with the connection."; result["data"] = error; return cb(result); } if(body) { try { body = JSON.parse(body); } catch (e) { result["message"] = "Could not parse the response."; return cb(result); } if(body.current.health != 1) { result["message"] = body.current.subject; return cb(result); } result["status"] = true; result["message"] = body.current.subject; return cb(result); } result["message"] = "Empty response. Try Again."; return cb(result); }); } module.exports = facebook;
JavaScript
0
@@ -154,37 +154,8 @@ );%0A%0A -function facebook (cb) %7B%0A var @@ -169,20 +169,16 @@ = %7B%0A - - service: @@ -191,20 +191,16 @@ ceName,%0A - stat @@ -213,14 +213,35 @@ lse%0A - %7D; +%7D%0A%0Afunction facebook (cb) %7B %0A%0A
4a3d3d9f844ff4eab0df2419dc62c2b5de55d87e
Store cookies for 200 hours
app.js
app.js
var config = require('./config'); var logger = require('./lib/logger'); var http = require('http'); var path = require('path'); var HttpError = require('error').HttpError; // ExpressJS & modules var express = require('express'); var expressSessions = require('express-session'); var MongoStore = require('connect-mongo')(expressSessions); var bodyParser = require('body-parser'); var favicon = require('serve-favicon'); var morgan = require('morgan'); // logger var cookieParser = require('cookie-parser'); //var errorHandler = require('errorhandler'); var app = express(); if (! config.get('cookie_secret')) { throw new Error('You should specify "cookie_secret" in config'); } if (config.get('cookie_secret') == "pew-pew") { throw new Error('You should change "cookie_secret" in config'); } // all environments app.engine('ejs', require('ejs-locals')); app.set('port', config.get('port')); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.use(require('middleware/sendHTTPError')); app.use(favicon(__dirname + '/public/favicon.ico')); morgan.token('sr-user', function(req, res) { return req.user && req.user.username; }); app.use(morgan(':remote-addr - :sr-user [:date[clf]] ":method :url :status :response-time ms')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(cookieParser(config.get('cookie_secret'))); app.use(expressSessions({ secret: config.get('cookie_secret'), saveUninitialized: false, // don't create session until something stored resave: false, //don't save session if unmodified store: new MongoStore({ url : config.get('mongoose:uri'), touchAfter: 3600 // time period in seconds }), cookie: { maxAge: 20*3600000 // 20*hour } })); app.use(require('middleware/loadUser')); app.use(require('middleware/resLocals')); app.use(express.static(path.join(__dirname, 'public'))); // development only //if ('development' == app.get('env')) { // app.use(express.errorHandler()); //} require('./routes')(app); // Error handler app.use(function (err, req, res, next) { console.log(err); if (typeof err == 'number') { err = new HttpError(err); } if (err instanceof HttpError) { res.sendHttpError(err); } else { err = new HttpError(500); res.sendHttpError(err); } }); http.createServer(app).listen(config.get('port'), function(){ console.log('Express server listening on port ' + config.get('port')); });
JavaScript
0
@@ -1746,16 +1746,17 @@ xAge: 20 +0 *3600000 @@ -1761,16 +1761,17 @@ 00 // 20 +0 *hour%0A
46427bc82d3c0c9b030844a802263608036112eb
fix #546
app.js
app.js
/*! * nodeclub - app.js */ /** * Module dependencies. */ var config = require('./config'); if (!config.debug) { require('newrelic'); } require('colors'); var path = require('path'); var Loader = require('loader'); var express = require('express'); var session = require('express-session'); var passport = require('passport'); require('./middlewares/mongoose_log'); // 打印 mongodb 查询日志 require('./models'); var GitHubStrategy = require('passport-github').Strategy; var githubStrategyMiddleware = require('./middlewares/github_strategy'); var webRouter = require('./web_router'); var apiRouterV1 = require('./api_router_v1'); var auth = require('./middlewares/auth'); var errorPageMiddleware = require('./middlewares/error_page'); var proxyMiddleware = require('./middlewares/proxy'); var RedisStore = require('connect-redis')(session); var _ = require('lodash'); var csurf = require('csurf'); var compress = require('compression'); var bodyParser = require('body-parser'); var busboy = require('connect-busboy'); var errorhandler = require('errorhandler'); var cors = require('cors'); var requestLog = require('./middlewares/request_log'); var renderMiddleware = require('./middlewares/render'); var logger = require('./common/logger'); var helmet = require('helmet'); // 静态文件目录 var staticDir = path.join(__dirname, 'public'); // assets var assets = {}; if (config.mini_assets) { try { assets = require('./assets.json'); } catch (e) { console.log('You must execute `make build` before start app when mini_assets is true.'); throw e; } } var urlinfo = require('url').parse(config.host); config.hostname = urlinfo.hostname || config.host; var app = express(); // configuration in all env app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'html'); app.engine('html', require('ejs-mate')); app.locals._layoutFile = 'layout.html'; app.enable('trust proxy'); // Request logger。请求时间 app.use(requestLog); if (config.debug) { // 渲染时间 app.use(renderMiddleware.render); } // 静态资源 app.use(Loader.less(__dirname)); app.use('/public', express.static(staticDir)); app.use('/agent', proxyMiddleware.proxy); // 通用的中间件 app.use(require('response-time')()); app.use(helmet.frameguard('sameorigin')); app.use(bodyParser.json({limit: '1mb'})); app.use(bodyParser.urlencoded({ extended: true, limit: '1mb' })); app.use(require('method-override')()); app.use(require('cookie-parser')(config.session_secret)); app.use(compress()); app.use(session({ secret: config.session_secret, store: new RedisStore({ port: config.redis_port, host: config.redis_host, }), resave: true, saveUninitialized: true, })); // oauth 中间件 app.use(passport.initialize()); // custom middleware app.use(auth.authUser); app.use(auth.blockUser()); if (!config.debug) { app.use(function (req, res, next) { if (req.path.indexOf('/api') === -1) { csurf()(req, res, next); return; } next(); }); app.set('view cache', true); } // for debug // app.get('/err', function (req, res, next) { // next(new Error('haha')) // }); // set static, dynamic helpers _.extend(app.locals, { config: config, Loader: Loader, assets: assets }); app.use(errorPageMiddleware.errorPage); _.extend(app.locals, require('./common/render_helper')); app.use(function (req, res, next) { res.locals.csrf = req.csrfToken ? req.csrfToken() : ''; next(); }); // github oauth passport.serializeUser(function (user, done) { done(null, user); }); passport.deserializeUser(function (user, done) { done(null, user); }); passport.use(new GitHubStrategy(config.GITHUB_OAUTH, githubStrategyMiddleware)); app.use(busboy({ limits: { fileSize: 10 * 1024 * 1024 // 10MB } })); // routes app.use('/api/v1', cors(), apiRouterV1); app.use('/', webRouter); // error handler if (config.debug) { app.use(errorhandler()); } else { app.use(function (err, req, res, next) { console.error('server 500 error:', err); return res.status(500).send('500 status'); }); } app.listen(config.port, function () { logger.log('NodeClub listening on port', config.port); logger.log('God bless love....'); logger.log('You can debug your app with http://' + config.hostname + ':' + config.port); logger.log(''); }); module.exports = app;
JavaScript
0
@@ -2845,16 +2845,39 @@ req.path + === '/api' %7C%7C req.path .indexOf
d4b6bcd3eaae128360ffaec528991f94df6d4a2e
fix folder
app.js
app.js
"use strict"; (function(){ Vue.config.devtools = true; new Vue({ el: '#app', data: { loading: 0, downloading: false, downloadedFiles: 0, tree: null, filetypes: [{ id: 'pdf', name: 'PDF', number: 0, checked: true, }, { id: 'doc', name: 'Document', number: 0, checked: true, }, { id: 'slides', name: 'Slides', number: 0, checked: true, }, { id: 'spreadsheet', name: 'Spreadsheet', number: 0, checked: true, }, { id: 'calc', name: 'Calc', number: 0, checked: true, }, { id: 'other', name: 'Other', number: 0, checked: false, }], filterTypes: [{ id: 'string', name: 'String', }, { id: 'wildcard', name: 'Wildcard', }, { id: 'regex', name: 'RegEx', }], filter: { type: 'wildcard', pattern: '', }, }, computed: { totalFiles() { return this.filetypes.filter(x => x.checked).map(x => x.number).reduce((x, y) => x + y, 0); }, pattern() { switch (this.filter.type) { case 'string': return new RegExp(escapeRegExp(this.filter.pattern), 'i'); break; case 'wildcard': return new RegExp(escapeRegExp(this.filter.pattern).replace(/\\\*/g, '.*').replace(/\\\?/g, '.'), 'i'); break; case 'regexp': try { return new RegExp(this.filter.pattern, 'i'); } catch (e) { return /$^/; // match nothing } break; default: return /$^/; } }, }, methods: { addFiles(filetypeId, number) { for (const filetype of this.filetypes) { if (filetype.id === filetypeId) { filetype.number += number; break; } } }, startLoading() { ++this.loading; }, stopLoading() { this.loading && --this.loading; }, download: co.wrap(function*() { if (!this.totalFiles) { return; } this.downloadedFiles = 0; this.downloading = true; this.startLoading(); yield this.$refs.fileList.download(); this.stopLoading(); chrome.downloads.showDefaultFolder(); this.downloading = false; }), addDownloaded(n) { this.downloadedFiles += n; }, }, created() { chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => { let currentTab = tabs[0]; let match; if (match = currentTab.url.match(/^http:\/\/moodle.nottingham.ac.uk\/mod\/folder\/view\.php\?id=(\d+)$/)) { this.tree = { type: 'root', fetched: false, id: match[1], children: [], }; Vue.nextTick(() => { this.$refs.fileList.fetch(); }); } else if (currentTab.url.startsWith('http://moodle.nottingham.ac.uk/course/view.php?id=')) { this.startLoading(); chrome.tabs.sendMessage(tabs[0].id, 'requestData', (response) => { this.tree = response; this.stopLoading(); }); } }); }, }); function escapeRegExp(str) { return str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); } })();
JavaScript
0.000002
@@ -2391,16 +2391,26 @@ id: +%60folder-$%7B match%5B1%5D ,%0A%09%09 @@ -2405,16 +2405,18 @@ match%5B1%5D +%7D%60 ,%0A%09%09%09%09%09c
3eaec4797a699727f97c5e7f82a5884cfe4c4762
save errors as strings
app.js
app.js
'use strict' const signatures = require('sodium-signatures') const identity = require('./lib/identity') const replicate = require('./lib/gce/index') const getClaims = require('./lib/getClaims') const replicationRequest = require('./lib/replicationRequest') const uuid = require('uuid') const https = require('https') const selfsigned = require('selfsigned') const Koa = require('koa') const _ = require('koa-route') const bodyParser = require('koa-bodyparser') const app = new Koa() app.use(bodyParser()) const generation = process.env.CELULA_GEN ? process.env.CELULA_GEN : 'gen:0' let keys = null const celula = { getId: (ctx) => { ctx.body = { publicKey: keys.publicKey.toString('base64'), generation: keys.generation } }, getClaims: (ctx, uuid) => { return getClaims(uuid) .then((value) => { ctx.body = value }) .catch((err) => { if (err && err.notFound) { return ctx.throw(404) } if (err && err.statusCode) { return ctx.throw(err.statusCode, err.message) } return ctx.throw(500, err) }) }, sign: (ctx) => { let signature = signatures.sign(Buffer.from(JSON.stringify(ctx.request.body)), keys.secretKey) ctx.body = signature.toString('base64') }, verify: (ctx) => { let verified = signatures.verify(Buffer.from(JSON.stringify(ctx.request.body.claim)), Buffer.from(ctx.request.body.signature, 'base64'), keys.publicKey) ctx.body = verified }, replicate: (ctx) => { ctx.request.body.keys = keys ctx.request.body.uuid = uuid.v4() // return inmediately with replication request id and then process return replicationRequest.save(ctx.request.body, 'processing') .then((data) => { ctx.body = data replicate(ctx.request.body) .then((value) => { replicationRequest.save(ctx.request.body, 'success') }) .catch((err) => { replicationRequest.save(ctx.request.body, err) }) }) .catch((err) => { return ctx.throw(500, err) }) }, getReplicationRequest: (ctx, uuid) => { return replicationRequest.get(uuid) .then((value) => { ctx.body = value }) .catch((err) => { if (err && err.notFound) { return ctx.throw(404) } if (err && err.statusCode) { return ctx.throw(err.statusCode, err.message) } return ctx.throw(500, err) }) } } app.use(_.get('/id', celula.getId)) app.use(_.get('/claims/:uuid', celula.getClaims)) app.use(_.get('/replicate/:uuid', celula.getReplicationRequest)) app.use(_.post('/sign', celula.sign)) app.use(_.post('/verify', celula.verify)) app.use(_.post('/replicate', celula.replicate)) identity(generation) .then((value) => { keys = value // create ssl certs and server let pems = selfsigned.generate([{ name: 'commonName', value: 'celula' }], { days: 10000 }) https.createServer({ key: pems.private, cert: pems.cert }, app.callback()).listen(3141) console.log('listening over https on port 3141') }) .catch((err) => { console.error('identityError:', err) })
JavaScript
0.000001
@@ -1944,24 +1944,35 @@ st.body, err +.toString() )%0A %7D)%0A
3f91a352c4bdfc537eabd12591461b48b35ca0a2
fix email logging
app.js
app.js
var express = require('express') , http = require('http') , app = express() , connect = require('express/node_modules/connect') , fs = require('fs') , winston = require('winston'); if(!app.settings.env || app.settings.env == ''){ throw new Error('The environment variable NODE_ENV is not configured.'); } global.winston = winston; global.ENV_CONFIG = require('./lib/config/config_'+app.settings.env); require('./lib/orm').setup('./lib/models'); app.set('port', ENV_CONFIG.App.port); app.configure(function(){ // view rendering app.engine('ejs', require('ejs-locals')); app.set('views', __dirname + '/views'); app.locals({ _layoutFile : '/layouts/site' }); app.locals.open = '{{'; app.locals.close = '}}'; app.set('view engine', 'ejs'); // allow req.body app.use(express.bodyParser()); app.use(express.cookieParser(ENV_CONFIG.App.sessionSecret)); // enable PUT and DELETE request methods app.use(express.methodOverride()); // enable event logging to database. NOTE: only designed to log events which contain metadata winston.add(require('./lib/winston-sequelize').WinstonSequelize, { level : 'info', handleExceptions : false }); }); if(ENV_CONFIG.Logging.console.enabled){ winston.remove(winston.transports.Console); winston.add(winston.transports.Console, { level : ENV_CONFIG.Logging.console.level, handleExceptions : ENV_CONFIG.Logging.console.handleExceptions }); winston.info('Logging: enabled console logging at level: '+ENV_CONFIG.Logging.console.level); } if(ENV_CONFIG.Logging.file.enabled){ if(!fs.existsSync(ENV_CONFIG.Logging.file.folder)){ fs.mkdirSync(ENV_CONFIG.Logging.file.folder); } winston.add(winston.transports.File, { filename : ENV_CONFIG.Logging.file.folder+'/'+ENV_CONFIG.Logging.file.filename, maxsize : ENV_CONFIG.Logging.file.maxsize, maxFiles : ENV_CONFIG.Logging.file.maxFiles, handleExceptions : ENV_CONFIG.Logging.file.handleExceptions, level : ENV_CONFIG.Logging.file.level }); winston.info('Logging: enabled file logging at level: '+ENV_CONFIG.Logging.file.level); } if(ENV_CONFIG.Logging.email.enabled){ winston.add(require('winston-mail').Mail, { to : ENV_CONFIG.Email.recipient, from : ENV_CONFIG.Email.sender, host : ENV_CONFIG.Email.host, port : ENV_CONFIG.Email.port, username : ENV_CONFIG.Email.user, password : ENV_CONFIG.Email.password, tls : true, level : ENV_CONFIG.Logging.email.level, handleExceptions : ENV_CONFIG.Logging.email.handleExceptions }); winston.info('Logging: enabled email logging at level: '+ENV_CONFIG.Logging.email.level); } if(app.settings.env == 'development' || app.settings.env == 'test'){ app.use(express.errorHandler({ dumpExceptions : true, showStack : true })); app.use(express.session({ store : new connect.middleware.session.MemoryStore(), secret : ENV_CONFIG.App.sessionSecret })); // prioritize router before public directory app.use(express.static(__dirname + '/public')); } app.configure('production', function(){ app.use(express.errorHandler()); /// TODO: Take out before hitting production /* Authentication module to prevent authorized access to factory var auth = require('http-auth'); var basic = auth.basic({ realm : "Authenticated Area.", file : "./data/users.htpasswd" // [email protected]/test }); app.use(auth.connect(basic)); */ // stop exit after an uncaughtException winston.exitOnError = false; // store sessions to redis var RedisStore = require('connect-redis')(express); var redisDB = require('redis').createClient(ENV_CONFIG.Redis); app.use(express.session({ secret : ENV_CONFIG.App.sessionSecret, store : new RedisStore({ client : redisDB, secret : ENV_CONFIG.App.sessionSecret }) })); // minify client side code and set router to build path require('requirejs').optimize(require('./lib/config/ClientBuild'), function(){ winston.info('Requirejs: successfully optimized client javascript'); }); // prioritize router before public directory, use minified public directory app.use(express.static(__dirname + '/public-build')); }); // Routes require('./routes')(app); // Run Webserver var server = http.createServer(app); server.listen(app.get('port'), function(){ winston.info("Express: server listening on port %d in %s mode", app.get('port'), app.settings.env); });
JavaScript
0.00009
@@ -2432,25 +2432,33 @@ ENV_CONFIG. -E +Logging.e mail.recipie @@ -2496,25 +2496,33 @@ ENV_CONFIG. -E +Logging.e mail.sender, @@ -2557,25 +2557,33 @@ ENV_CONFIG. -E +Logging.e mail.host,%0D%0A @@ -2616,25 +2616,33 @@ ENV_CONFIG. -E +Logging.e mail.port,%0D%0A @@ -2675,25 +2675,33 @@ ENV_CONFIG. -E +Logging.e mail.user,%0D%0A @@ -2738,17 +2738,25 @@ _CONFIG. -E +Logging.e mail.pas
8d5a5830bf4724c792b14ac355f68baa9a358117
Handle speech selection
app.js
app.js
simply.setText({title: 'Loading...'}, true); function secsToMMSS(secs) { var minutes = 0; while (secs >= 60) { secs -= 60; minutes += 1; } if (minutes < 10) minutes = '0' + minutes; if (secs < 10) secs = '0' + secs; return minutes + ':' + secs; } function displaySection(sectionData) { var mmss = secsToMMSS(sectionData.seconds); simply.setText({title: mmss}, true); simply.subtitle(sectionData.topic); } function displaySpeech(speechData) { simply.setText({title: speechData.title}, true); simply.subtitle(speechData.sections.length + ' sections'); } function sectionData(speechData, sectionNum) { return speechData.sections[sectionNum]; } function loadSpeeches(url, callback) { var allSpeeches = [ { title: 'Pet animals', sections: [ {seconds: 60, topic: 'Kittens'}, {seconds: 20, topic: 'Puppies'}, {seconds: 30, topic: 'Birdies'} ] }, { title: 'Deadly animals', sections: [ {seconds: 29, topic: 'Snakes'}, {seconds: 255, topic: 'Sharks'} ] }, { title: 'Awesome foods', sections: [ {seconds: 100, topic: 'Chaat'}, {seconds: 601, topic: 'Pizza'}, {seconds: 331, topic: 'Salmon'}, {seconds: 33, topic: 'Filet mignon'} ] }, ]; callback(allSpeeches); } loadSpeeches('http://www.whatever.com/', function(speeches) { var currSpeech = 0; simply.on('singleClick', function(event) { if (event.button === 'up') { if (currSpeech > 0) { currSpeech--; displaySpeech(speeches[currSpeech]); } } else if (event.button === 'down') { if (currSpeech + 1 < speeches.length) { currSpeech++; displaySpeech(speeches[currSpeech]); } } }); displaySpeech(speeches[0]); });
JavaScript
0.000001
@@ -1,28 +1,123 @@ +var speeches;%0Avar currSpeech = 0;%0Avar currentMode = 'loading'; // 'speechSelect', 'speechRun'%0A%0A simply.setText(%7Btitle: 'Load @@ -1446,137 +1446,240 @@ %0A%7D%0A%0A -%0AloadSpeeches('http://www.whatever.com/', function(speeches) %7B%0A var currSpeech = 0;%0A simply.on('singleClick', function(event) %7B +function selectSpeech(speech) %7B%0A currentMode = 'speechRun';%0A simply.setText(%7Btitle: 'Speech selected'%7D, true);%0A simply.subtitle(speech.title);%0A%7D%0A%0Asimply.on('singleClick', function(event) %7B%0A if (currentMode === 'speechSelect') %7B%0A %0A @@ -1983,13 +1983,242 @@ %7D -%0A %7D) + else if (event.button === 'select') %7B%0A selectSpeech(speeches%5BcurrSpeech%5D);%0A %7D%0A %0A %7D%0A%7D);%0A%0AloadSpeeches('http://www.whatever.com/', function(speechesRetrieved) %7B%0A currentMode = 'speechSelect';%0A speeches = speechesRetrieved ;%0A
8b1c55d9c181ef6459855e4077549bf2f55e00e0
comment added in app.js
app.js
app.js
//////////////////////////////////////////////////////////////////////// // Modules // //////////////////////////////////////////////////////////////////////// var express = require('express'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var http = require('http'); //////////////////////////////////////////////////////////////////////// // Dependencies // //////////////////////////////////////////////////////////////////////// var index = require('./routes/index'); var config = require('config'); var processor = require('./routes/processor'); var app = express();// app init //////////////////////////////////////////////////////////////////////// // App configuration // //////////////////////////////////////////////////////////////////////// app.use(logger('dev')); app.use(bodyParser.json({limit: '2mb'})); app.use(bodyParser.urlencoded({limit: '1mb', extended: true})); app.use(cookieParser()); app.post('/ping', function (req, res) { res.send(200, {}, { pong: true }); }); //////////////////////////////////////////////////////////////////////// // Server configuration // //////////////////////////////////////////////////////////////////////// httpServer = http.createServer(app).listen(config.get('httpPort'), function() { console.log('Express HTTP server listening on port ' + config.get('httpPort')); }); module.exports = app;
JavaScript
0
@@ -828,16 +828,33 @@ pp init%0A +//added a comment %0A///////
df73378d4e93ec8381f629cc39177527d9d4b514
remove process set env
app.js
app.js
process.env.NODE_ENV = 'development'; /*---------- Module exports ----------*/ module.exports = require('./builder/querybuilder');
JavaScript
0.000002
@@ -1,43 +1,4 @@ -process.env.NODE_ENV = 'development';%0A%0A /*-- @@ -87,8 +87,9 @@ ilder'); +%0A
4ab09f278695ab8757e16d9d568a5189526ab242
fix and remove useless and old apis
app.js
app.js
/** * Module dependencies */ var express = require('express'), api = require('./routes/api'), http = require('http'), path = require('path'), hostName = "http://sandbox.evernote.com", passport = require('passport'), routes = require('./routes'), Evernote = require('evernote'); var app = module.exports = express(); // mongoose.connect(configDB.url) /** * Configuration */ // app.configure(function(){ // app.set('port', process.env.PORT || 3000); // // app.set('views', __dirname + '/views'); // // app.set('view engine', 'jade'); // app.use(express.favicon()); // app.use(express.logger('dev')); // app.use(express.bodyParser()); // app.use(express.methodOverride()); // app.use(express.cookieParser('secret')); // app.use(express.session()); // app.use(function(req, res, next) { // res.locals.session = req.session; // next(); // }); // app.use(app.router); // // app.use(require('less-middleware')({src: __dirname + '/public'})); // app.use(express.static(path.join(__dirname, 'public'))); // }); // all environments app.set('port', process.env.PORT || 3000); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.cookieParser('secret')); app.use(express.session()); app.set('views', __dirname + '/views'); app.engine('html', require('ejs').renderFile); // app.use(passport.initialize()); app.use(express.session()); // development only if (app.get('env') === 'development') { app.use(express.errorHandler()); } // production only if (app.get('env') === 'production') { // TODO }; /** * Routes */ // serve all asset files from necessary directories app.use("/js", express.static(__dirname + "/public/js")); app.use("/css", express.static(__dirname + "/public/css")); app.use("/img", express.static(__dirname + "/public/img")); app.use("/partials", express.static(__dirname + "/public/partials")); app.use("/lib", express.static(__dirname + "/public/lib")); // JSON API app.get('/api/name', api.name); // Routes // app.get('/', routes.index); app.get('/notes', routes.getNotes); app.get('/oauth', routes.oauth); app.get('/oauth_callback', routes.oauth_callback); app.get('/clear', routes.clear); // redirect all others to the index (HTML5 history) app.all("/*", function(req, res, next) { res.sendfile("index.html", { root: __dirname + "/public" }); }); /** * Start Server */ http.createServer(app).listen(app.get('port'), function () { console.log('Express server listening on port ' + app.get('port')); });
JavaScript
0
@@ -2036,16 +2036,19 @@ SON API%0A +// app.get(
b68f7f38405c3e74e9b7a9450ae09cd8b9e3b874
add 111111
app.js
app.js
const express = require('express') const app = express() app.get('/', function (req, res) { res.send('Hello World!') }) app.listen(3000, function () { console.log('Example app listening on port 3000!') })
JavaScript
0.999999
@@ -110,16 +110,21 @@ o World! +11111 ')%0A%7D)%0A%0Aa
911865c60bf4073ed78731326784802843029505
add debug prints
app.js
app.js
var fs = require('fs'); var proc = require('child_process'); var express = require('express'); var bodyParser = require('body-parser'); var path = require('path'); var app = express(); var base_dir = __dirname; var hosts = require('./config') app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded var gitupdate = function(data, callback){ var command = ''; var repo_name = data.branch+'__'+data.repository_url.split('/').pop(); if(!fs.existsSync(data.destination)){ fs.mkdirSync(data.destination); } if(!fs.existsSync(path.join(data.bare_repo,repo_name))){ // bare mirroring of the repository command+= 'mkdir -p '+data.bare_repo+' && cd '+data.bare_repo+' && '; command+= '/usr/bin/git clone --mirror '+data.repository_url+' && '; command+= '/bin/mv '+data.repository_url.split('/').pop()+' '+repo_name+' && '; command+= 'cd '+repo_name+' && '; command+= 'GIT_WORK_TREE='+data.destination+' /usr/bin/git checkout -f '+data.branch+' && '; } command+= 'cd '+path.join(data.bare_repo,repo_name)+' && '; command+= '/usr/bin/git fetch && '; command+= 'GIT_WORK_TREE='+data.destination+' /usr/bin/git checkout -f'; if(data.postcmd){ command+= ' && cd '+data.destination+' && '+data.postcmd; } var timeout = (typeof data.timeout !== 'undefined') ? data.timeout : '600'; // 10 minutes command = '( flock -x -w '+timeout+' 200 || exit 1; su - '+data.user+' -c "'+command+'"; ) 200>/tmp/gitDeploy.lock'; //console.log(command); proc.exec(command,function(error,stdout,stderr){ if (error === null) { callback(true); } else { callback(false); } }); }; var update = function(req,data,callback){ console.log('======================================'); console.log('data=',data); console.log('body=',req.body); var toupdate = false; var changes = req.body.push.changes || false; if(changes){ for(var i=0; i<changes.length; i++){ if(changes[i].new.name == data.branch){ toupdate=true; break; } } } if(toupdate){ gitupdate(data,function(result){ callback(result); return; }); } else { console.log('Unhandled!!!',req.body); callback(true); } }; for(var i=0;i<hosts.length;i++){ var domain_data = hosts[i]; (function(domain_data){ app.post('/'+domain_data.route, function (req, res) { console.log('Processing '+domain_data.name); update(req, domain_data ,function(result){ if(result){ console.log('sync done'); res.sendStatus(200); } else { console.log('sync failed'); res.sendStatus(500); } }); }); })(domain_data); } app.get('/', function (req, res) { res.send('GitDeploy - https://github.com/matteomattei/gitdeploy'); }); app.get('/:otherpage', function(req, res){ if(req.params.otherpage != 'favicon.ico'){ res.send('Not implemented'); console.log('Not implemented: '+req.params.otherpage); } }); var server = app.listen(8888, function () { var host = server.address().address; var port = server.address().port; console.log('gitDeploy app is listening at http://%s:%s', host, port); });
JavaScript
0.000001
@@ -1617,18 +1617,16 @@ k';%0A -// console. @@ -1639,16 +1639,16 @@ mmand);%0A + proc @@ -1759,32 +1759,78 @@ %7D else %7B%0A + console.log(error,stdout,stderr);%0A call @@ -2074,16 +2074,24 @@ hanges = + (typeof req.bod @@ -2109,16 +2109,93 @@ ges -%7C%7C false +!== 'undefined') ? req.body.push.changes : false;%0A console.log('changes=',changes) ;%0A @@ -2408,16 +2408,16 @@ pdate)%7B%0A - @@ -2441,32 +2441,85 @@ nction(result)%7B%0A + console.log('gitupdate result=',result);%0A call
004003928d16b76b2662b3800a64e180c873149e
Switch to hello jenkins
app.js
app.js
var express = require('express'); var app = express(); app.get('/', function (req, res) { res.send('hello world'); }); app.listen(process.env.PORT || 5000); module.exports = app;
JavaScript
0.000273
@@ -109,13 +109,15 @@ llo -world +jenkins ');%0A
6fab2755af140d039045ed6c56cb122be60e2e40
Fix module, remove old code
app.js
app.js
const slackClient = require('./client/slackClient.js'); const googleClient = require('./client/googleClient.js'); const CLIENT_EVENTS = require('@slack/client').CLIENT_EVENTS; const RTM_EVENTS = require('@slack/client').RTM_EVENTS; const bunyan = require('bunyan'); const log = bunyan.createLogger({name: 'SlackToGcal'}); const GOOGLE_PATH_TO_KEY = process.env.GOOGLE_PATH_TO_KEY; const SLACK_API_TOKEN = process.env.SLACK_API_TOKEN; const CALENDAR_ID = process.env.GOOGLE_CALENDAR_ID; const SLACK_BOT_ID = process.env.SLACK_BOT_ID; const SLACK_AT_BOT =`<@${SLACK_BOT_ID}>`; if (_.some([ GOOGLE_PATH_TO_KEY, SLACK_API_TOKEN, CALENDAR_ID, SLACK_BOT_ID ], (env) => !env)) { log.error(`Cannot have missing env vars: GOOGLE_PATH_TO_KEY: ${GOOGLE_PATH_TO_KEY}, SLACK_API_TOKEN: ${SLACK_API_TOKEN}, GOOGLE_CALENDAR_ID: ${CALENDAR_ID}, SLACK_BOT_ID: ${SLACK_BOT_ID} `); throw new Error("Startup failed validation, missing required env vars"); } if (!GOOGLE_PATH_TO_KEY || !SLACK_API_TOKEN || !CALENDAR_ID || !SLACK_BOT_ID) { } const onGcalEventAdd = (slackMessage, gcalResponse, gcalSlackClient) => { if (gcalResponse && gcalResponse.htmlLink) { gcalSlackClient.sendMessage(`Created event, edit or view here: ${gcalResponse.htmlLink}`, slackMessage.channel); } else { log.warn(`Failed to write GCal event for slackMessage: ${JSON.stringify(slackMessage)} and GCal response: ${JSON.stringify(gcalResponse)}`); gcalSlackClient.sendMessage("I couldn't create this event, sorry :(", slackMessage.channel); } }; const initClients = () => { const gcalClient = googleClient.createGoogleClient(googleJwtClient); const addEvent = googleClient.quickAddEvent(gcalClient, CALENDAR_ID); const gcalSlackClient = slackClient.createSlackClient(SLACK_API_TOKEN, addEvent); gcalSlackClient.start(); gcalSlackClient.on(CLIENT_EVENTS.RTM.AUTHENTICATED, (rtmStartData) => { log.info(`Logged in as ${rtmStartData.self.name} of team ${rtmStartData.team.name}`); }); gcalSlackClient.on(RTM_EVENTS.MESSAGE, (slackMessage) => { if (slackMessage && slackMessage.text && slackMessage.text.includes(SLACK_AT_BOT)) { log.info(`Received Slack message ${JSON.stringify(slackMessage)}`); addEvent(slackMessage.text.split(SLACK_AT_BOT)[1].trim(), (gcalResponse) => { onGcalEventAdd(slackMessage, gcalResponse, gcalSlackClient); }); } }); }; const googleJwtClient = googleClient.createJwtClient(GOOGLE_PATH_TO_KEY); googleJwtClient.authorize((error, tokens) => { if (error) { throw new Error(`Could not authorize Google client with JWT, error: ${error}`); } log.info('Initialized Google JWT client, starting other clients'); initClients(); });
JavaScript
0.000001
@@ -1,12 +1,41 @@ +const _ = require('lodash');%0A const slackC @@ -1009,91 +1009,8 @@ %0A%7D%0A%0A -if (!GOOGLE_PATH_TO_KEY %7C%7C !SLACK_API_TOKEN %7C%7C !CALENDAR_ID %7C%7C !SLACK_BOT_ID) %7B%0A%7D%0A%0A cons
efba420d79805396183ff5c190b79e3931cf3eec
Set leds to lila-blass-blau.
app.js
app.js
'use strict'; var Blinkt = require('node-blinkt'), leds = new Blinkt(); var NUM_LEDS = 8; var brightness = 0.1; leds.setup(); leds.clearAll(); var lightsOff = function () { leds.setAllPixels(0, 0, 0, 0.1); leds.sendUpdate(); leds.sendUpdate(); } var signals = { 'SIGINT': 2, 'SIGTERM': 15 }; function shutdown(signal, value) { console.log('Stopped by ' + signal); lightsOff(); process.nextTick(function () { process.exit(0); }); } Object.keys(signals).forEach(function (signal) { process.on(signal, function () { shutdown(signal, signals[signal]); }); }); // ---- animation-loop var offset = 0; setInterval(function () { let red, green, blue; for (var i = 0; i < NUM_LEDS; i++) { [red, green, blue] = wheel(((i * 256 / NUM_LEDS) + offset) % 256); leds.setPixel(i, red, green, blue, brightness) } offset++; leds.sendUpdate(); }, 1000 / 30); console.log('Rainbow started. Press <ctrl>+C to exit.'); // generate rainbow colors accross 0-255 positions. function wheel(pos) { pos = 255 - pos; if (pos < 85) { return [255 - pos * 3, 0, pos * 3]; } else if (pos < 170) { pos -= 85; return [0, pos * 3, 255 - pos * 3]; } else { pos -= 170; return [pos * 3, 255 - pos * 3, 0]; } }
JavaScript
0
@@ -396,36 +396,24 @@ ;%0A -process.nextTick(function () +setTimeout(() =%3E %7B p @@ -429,16 +429,22 @@ it(0); %7D +, 1000 );%0A%7D%0A%0AOb @@ -706,16 +706,19 @@ +) %7B%0A + // %5Bred, g @@ -780,16 +780,19 @@ 56);%0A + // leds.se @@ -831,16 +831,55 @@ htness)%0A + leds.setPixel(i, 100, 50, 200, .5)%0A %7D%0A%0A%09of
4bac8624b91e3db4366db3af1c37bfeef5dbaffc
add restful routes for tracks
app.js
app.js
var express = require('express'); var partials = require('express-partials'); var bodyParser = require('body-parser'); var session = require('express-session'); var util = require('./server/lib/utility'); var mongoose = require('mongoose'); var db = require('./server/config'); //User model var User = require('./server/models/user.js'); var app = express(); // Parse JSON (uniform resource locators) app.use(bodyParser.json()); // Parse forms (signup/login) app.use(bodyParser.urlencoded({ extended: true })); app.use(express.static(__dirname + '/public')); app.use(session({ secret: 'we\'re making music together', resave: false, saveUninitialized: true })); app.use('/api/songs', require('./server/api/song')); //serve up index on root app.get('/', function(req, res) { res.sendFile('index.html'); }); //test authentication with a route app.get('/secret', util.checkUser, function(req, res){ res.json({message: "super secret place"}); }); /************************************************************/ // Write your authentication routes here /************************************************************/ app.post('/login', function(req, res) { var username = req.body.username; var password = req.body.password; User.findOne({ username: username }) .exec(function(err, user) { if (err){ res.send(401, err); } if (!user) { console.log("User does not exist"); res.redirect('/'); } else { user.comparePassword(password, function(match) { if (match) { util.createSession(req, res, user); console.log("successfully logged in"); } else { console.log("incorrect pasword"); res.redirect('/'); } }) } }); }); app.get('/logout', function(req, res) { req.session.destroy(function(){ console.log("logged out"); res.redirect('/'); }); }); app.post('/signup', function(req, res) { var username = req.body.username; var password = req.body.password; console.log(req.body); User.findOne({ username: username }) .exec(function(err, user) { if (err) { res.send(400, err); } if (!user) { var newUser = new User({ username: username, password: password }); newUser.save(function(err, newUser) { if (err) { res.send(400, err); } util.createSession(req, res, newUser); }); console.log('User successfully created'); // res.json({user_id: newUser._id}); } else { console.log('Account already exists'); res.redirect('/'); } }) }); /************************************************************/ // Handle the wildcard route last - if all other routes fail // send the user to '/' /************************************************************/ app.get('/*', function(req, res) { res.redirect('/'); }); console.log('listening on port 9000'); app.listen(9000);
JavaScript
0
@@ -718,16 +718,71 @@ song')); +%0Aapp.use('/api/tracks', require('./server/api/track')); %0A%0A//serv
a65b5d8cc453738cd669beab00aba340571e4af3
fix cannot post
app.js
app.js
/** * Module dependencies. */ var express = require('express'); var http = require('http'); var path = require('path'); var handlebars = require('express3-handlebars'); var add = require('./routes/add.js'); var index = require('./routes/index'); var home = require('./routes/home'); var createNewTask = require('./routes/createNewTask'); var profile = require('./routes/profile'); var task = require('./routes/task'); var settings = require('./routes/settings'); var signup = require('./routes/signup'); var submit_new_task = require('./routes/submit_new_task'); // Example route // var user = require('./routes/user'); var app = express(); // all environments app.set('port', process.env.PORT || 3000); app.set('views', path.join(__dirname, 'views')); app.engine('handlebars', handlebars()); app.set('view engine', 'handlebars'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.json()); app.use(express.urlencoded()); app.use(express.methodOverride()); app.use(express.cookieParser('Intro HCI secret key')); app.use(express.session()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); // development only if ('development' == app.get('env')) { app.use(express.errorHandler()); } // Add routes here app.get('/add',index.view, home.view, createNewTask.view, task.view, profile.view, settings.view) app.get('/', index.view); app.get('/home2', home.view2); app.get('/home', home.view); // app.get('/grid', home.viewGrid); app.get('/createNewTask', createNewTask.view); app.get('/task', task.view); app.get('/profile', profile.view); app.get('/settings', settings.view); app.get('/signup', signup.view); app.get('/submit_new_task', submit_new_task.view); // Example route // app.get('/users', user.list); app.use(express.static('public/')); http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); });
JavaScript
0
@@ -1418,26 +1418,88 @@ view2);%0Aapp. -ge +post('/home2', home.view2);%0Aapp.get('/home', home.view);%0Aapp.pos t('/home', h @@ -1778,16 +1778,17 @@ view);%0A%0A +%0A %0A%0A// Exa