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
|
---|---|---|---|---|---|---|---|
1257a858e307fd731a9efc046fd1ba87331be7ae | test contribute | app.js | app.js | /**
* Module dependencies.
*/
var express = require('./opt/lib/node_modules/express');
var routes = require('./routes');
var user = require('./routes/user');
var device = require('./routes/device');
var monitor = require('./routes/monitor');
var http = require('http');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
//app.get('/users', user.index);
//device
app.get('/device', device.index);
app.get('/device_add', device.add);
app.post('/device_doAdd', device.addData);
app.get('/device_update', device.update);
app.post('/device_doUpdate', device.updateData);
app.post('/device_doDelete', device.deleteData);
//monitor
app.get('/monitor', monitor.index);
app.get('/monitor_add', monitor.add);
app.post('/monitor_doAdd', monitor.addData);
app.get('/monitor_update', monitor.update);
app.post('/monitor_doUpdate', monitor.updateData);
app.get('/monitor_doDelete', monitor.delelteData);
//monitor_attr
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
| JavaScript | 0 | @@ -26,17 +26,16 @@
s.%0A */%0A%0A
-%0A
var expr
|
472d58bfb296d77e1a79701a64596bdd3ae0f950 | Add compression to app | app.js | app.js | /**
* Module dependencies.
*/
const express = require('express');
/**
* Express configuration.
*/
const app = express();
/**
* Express configuration.
*/
app.set('port', process.env.PORT || 3000);
/**
* Catch all error requests
*/
app.use(function(err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
/**
* Start Express server.
*/
app.listen(app.get('port'), () => {
console.log('Express server listening on port %d in %s mode', app.get('port'), app.get('env'));
});
module.exports = app;
| JavaScript | 0.000001 | @@ -60,16 +60,60 @@
press');
+%0Aconst compression = require('compression');
%0A%0A/**%0A *
@@ -162,16 +162,40 @@
press();
+%0Aapp.use(compression());
%0A%0A/**%0A *
|
c18875bd5bc73807bec4c20197cce275e08bce46 | update root route | app.js | app.js | var
express = require('express'),
app = express(),
ejs = require('ejs'),
ejsLayouts = require('express-ejs-layouts'),
mongoose = require('mongoose'),
flash = require('connect-flash'),
logger = require('morgan'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
session = require('express-session'),
passport = require('passport'),
passportConfig = require('./config/passport.js'),
userRoutes = require('./routes/users.js'),
apiRoutes = require('./routes/api.js'),
path = require('path'),
request = require('request')
app.use("/public", express.static(path.join(__dirname, 'public')));
// environment port
var port = process.env.PORT || 3000
// mongoose connection
mongoose.connect('mongodb://localhost/gift-db', function(err){
if(err) return console.log('Cannot connect :(')
console.log('Connected to MongoDB. Sweet!')
})
// middleware
app.use(logger('dev'))
app.use(cookieParser())
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())
app.use(session({
secret: "boomchakalaka",
cookie: {_expires: 6000000}
}))
app.use(passport.initialize())
app.use(passport.session())
app.use(flash())
// ejs configuration
app.set('view engine', 'ejs')
app.use(ejsLayouts)
//root route
app.get('/', function(req,res){
res.render('index')
})
// user routes
app.use('/', userRoutes)
//product/order Routes
//api routes
app.get('/api', apiRoutes)
//========================================================================
app.listen(port, function(){
console.log("Server running on port", port)
})
| JavaScript | 0.000001 | @@ -688,9 +688,8 @@
')))
-;
%0A%0A//
@@ -920,16 +920,26 @@
. Sweet!
+ (gift-db)
')%0A%7D)%0A%0A/
@@ -1354,21 +1354,47 @@
res.
-render('index
+sendFile(_dirname + '/views/roulette.js
')%0A%7D
@@ -1439,16 +1439,17 @@
tes)%0A%0A//
+
product/
@@ -1464,16 +1464,17 @@
utes%0A%0A//
+
api rout
|
796174d58262bafa0157684ae6e28e455dec82b3 | Fix 'template' error replacing View with Template (suggested in blog comments) | app.js | app.js | import {Component, View, bootstrap} from 'angular2/angular2';
// Annotation section
@Component({
selector: 'my-app'
})
@View({
inline: '<h1>Hello {{ name }}</h1>'
})
// Component controller
class MyAppComponent {
constructor() {
this.name = 'Alice'
}
}
bootstrap(MyAppComponent); | JavaScript | 0 | @@ -12,20 +12,24 @@
ponent,
-View
+Template
, bootst
@@ -126,12 +126,16 @@
%7D)%0A@
-View
+Template
(%7B%0A
|
8c927966da6778c0a7400e5769b13d92a3da8752 | Add a comment for test purposes | app.js | app.js | var express = require('express')
, http = require('http')
, fs = require('fs')
, passport = require('passport')
, LocalStrategy = require('passport-local').Strategy
, path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 4000);
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({ secret: 'Keyboard cat' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
};
// User schema
var mongoose = require('mongoose');
var userschema = new mongoose.Schema({
username: {type: String, unique: true},
password: String
});
var User = mongoose.model('user', userschema);
function findById (id, fn) {
var user = {id: 1, username: 'bob', password: 'secret', email: 'bob@example.com'};
return fn(null, user);
};
function findByUsername (username, fn) {
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
User.find({'username' : username}, function(err,users) {
var instance = users[0];
mongoose.connection.close();
return fn(null, instance);
});
});
};
// User session handling
passport.use(new LocalStrategy(
function(username, password, done) {
process.nextTick(function () {
findByUsername(username, function(err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false, { message: 'Unknown user ' + username }); }
if (user.password != password) { return done(null, false, { message: 'Invalid password' }); }
return done(null, user);
})
});
}
));
passport.serializeUser(function(user, done) {
done(null, user._id);
});
passport.deserializeUser(function(id, done) {
findById(id, function(err, user) {
done(err, user);
});
});
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
res.redirect('/login');
};
// add user
function addUser(newUsername, newPassword) {
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
var newuser = new User({username: newUsername, password: newPassword});
newuser.save(function () {
util.log("new user added:\nusername: " + newUsername +
"\npassword: " + newPassword);
});
mongoose.connection.close();
});
};
function findByUserid (userid, fn) {
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
User.find({'_id' : userid}, function(err,users) {
var instance = users[0];
mongoose.connection.close();
return fn(null, instance);
});
});
};
app.get('/', ensureAuthenticated, function(req, res) {
fs.readFile('./public/main.html', function(error, content) {
if (error) {
res.writeHead(500);
res.end();
} else {
res.writeHead(200, { 'Content-Type':'text/html' });
res.end(content, 'utf-8');
}
});
});
// routes
app.get('/signup', function(req, res) {
fs.readFile('./views/form.html', function(error, content) {
if (error) {
res.writeHead(500);
res.end();
} else {
res.writeHead(200, { 'Content-Type':'text/html' });
res.end(content, 'utf-8');
}
});
});
app.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});
app.get('/login', function(req, res) {
fs.readFile('./views/login.html', function(error, content) {
if (error) {
res.writeHead(500);
res.end();
} else {
res.writeHead(200, { 'Content-Type':'text/html' });
res.end(content, 'utf-8');
}
});
});
function prettyJSON(obj) {
return JSON.stringify(obj.username, null, 2);
}
app.get('/getusername', ensureAuthenticated, function(req, res) {
var userid = req.session.passport.user;
findByUserid(userid, function(err, user) {
res.writeHead(200, { 'Content-Type':'text/html' });
res.end(prettyJSON(user), 'utf-8');
});
});
app.get('/gameroom', ensureAuthenticated, function(req, res) {
fs.readFile('./views/gameroom.html', function(error, content) {
if (error) {
res.writeHead(500);
res.end();
} else {
util.log(util.inspect(req.session.passport.user));
res.writeHead(200, { 'Content-Type':'text/html' });
res.end(content, 'utf-8');
}
});
});
//login post
app.post('/login',
passport.authenticate('local', {failureRedirect: '/login'}),
function(req, res) {
res.redirect('/gameroom');
});
app.get('/game', function(req, res) {
fs.readFile('./public/main.html', function(error, content) {
if (error) {
res.writeHead(500);
res.end();
} else {
res.writeHead(200, { 'Content-Type':'text/html' });
res.end(content, 'utf-8');
}
});
});
app.post('/signup', function(req, res) {
var username = req.body.username;
var password = req.body.password;
addUser(username, password);
res.redirect('/login');
});
// routes
http.createServer(app).listen(app.get('port'), function() {
util.log('Express server listening on port ' + app.get('port'));
});
// game logic
var util = require("util");
// chat rooms
var Chatroom = require('./chatroom.js');
var chatroom1 = new Chatroom(5000);
chatroom1.init();
var Gameroom = require('./gameroom.js');
var gameroom1 = new Gameroom(3000);
gameroom1.init();
var gameroom2 = new Gameroom(3001);
gameroom2.init();
var gameroom3 = new Gameroom(3002);
gameroom3.init();
| JavaScript | 0 | @@ -1023,24 +1023,79 @@
user);%0A%7D;%0A%0A
+// returns user object by finding username by username%0A
function fin
|
0ac45ef7e26d54ca5089b423aa38b9b3b386bd66 | add fs module | app.js | app.js | const express = require("express");
const bodyParser = require("body-parser");
const flash = require("connect-flash");
const mongoose = require("mongoose");
const session = require("express-session");
const path = require("path");
const passport = require("passport");
const cookieParser = require("cookie-parser");
const setUpPassport = require("./setuppassport");
const routes = require("./routes");
const app = express();
const http = require("http").Server(app);
mongoose.connect("mongodb://localhost:27017/test");
setUpPassport();
app.set("port", process.env.PORT || 3000);
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
secret: "ninanung",
resave: true,
saveUninitialized: true
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(routes);
http.listen(app.get("port"), function() {
console.log("server started on port: " + app.get("port"));
});
| JavaScript | 0.000001 | @@ -308,16 +308,42 @@
arser%22);
+%0Aconst fs = require(%22fs%22);
%0A%0Aconst
|
688a5bb432a7c03cceec9770bd454bd2ca47e5a2 | update app details yet again | app.js | app.js | 'use strict';
// Module Dependencies
// -------------------
var express = require('express');
var http = require('http');
var JWT = require('./lib/jwtDecoder');
var path = require('path');
var request = require('request');
var routes = require('./routes');
var activity = require('./routes/activity');
var trigger = require('./routes/trigger');
var app = express();
// Register configs for the environments where the app functions
// , these can be stored in a separate file using a module like config
var APIKeys = {
appId : 'a6e7140c-2606-4bd1-889d-af8cfa63976f',
clientId : 'ek91sy2mc1v4ng6u013p8ato',
clientSecret : 'QyJeUpjAHkiudlTIwHPUKb31',
appSignature : 'zna4wbti5chwjgoxuqv4kldru0v5xeippzps5eprvtjdmkeyxcq25ij5nlhgsulraz3m3vkxaczjb4ki5nyrq3zn5wa34fvurikkphuxuiqdo3ahtkevhorc0lmsmmjcmqmez2mlrcvvl1lbzeyxjg4gg2gahkjo0dbr41tvmm1fwto2yxsumstq2klvqnrvfqdtmreks2beqt3mvlqfhs4qcre2kpjaocbezcappjlsm1pdszgno0eihh3qp3f',
authUrl : 'https://auth.exacttargetapis.com/v1/requestToken?legacy=1'
};
// Simple custom middleware
function tokenFromJWT( req, res, next ) {
// Setup the signature for decoding the JWT
var jwt = new JWT({appSignature: APIKeys.appSignature});
// Object representing the data in the JWT
var jwtData = jwt.decode( req );
// Bolt the data we need to make this call onto the session.
// Since the UI for this app is only used as a management console,
// we can get away with this. Otherwise, you should use a
// persistent storage system and manage tokens properly with
// node-fuel
req.session.token = jwtData.token;
next();
}
// Use the cookie-based session middleware
app.use(express.cookieParser());
// TODO: MaxAge for cookie based on token exp?
app.use(express.cookieSession({secret: "HelloWorld-CookieSecret"}));
// Configure Express
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.favicon());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// Express in Development Mode
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
// HubExchange Routes
app.get('/', routes.index );
app.post('/login', tokenFromJWT, routes.login );
app.post('/logout', routes.logout );
// Custom Hello World Activity Routes
app.post('/ixn/activities/hello-world/save/', activity.save );
app.post('/ixn/activities/hello-world/validate/', activity.validate );
app.post('/ixn/activities/hello-world/publish/', activity.publish );
app.post('/ixn/activities/hello-world/execute/', activity.execute );
// Custom Hello World Trigger Route
app.post('/ixn/triggers/hello-world/', trigger.edit );
// Abstract Event Handler
app.post('/fireEvent/:type', function( req, res ) {
var data = req.body;
var triggerIdFromAppExtensionInAppCenter = '__insert_your_trigger_key_here__';
var JB_EVENT_API = 'https://www.exacttargetapis.com/interaction-experimental/v1/events';
var reqOpts = {};
if( 'helloWorld' !== req.params.type ) {
res.send( 400, 'Unknown route param: "' + req.params.type +'"' );
} else {
// Hydrate the request
reqOpts = {
url: JB_EVENT_API,
method: 'POST',
headers: {
'Authorization': 'Bearer ' + req.session.token
},
body: JSON.stringify({
ContactKey: data.alternativeEmail,
EventDefinitionKey: triggerIdFromAppExtensionInAppCenter,
Data: data
})
};
request( reqOpts, function( error, response, body ) {
if( error ) {
console.error( 'ERROR: ', error );
res.send( response, 400, error );
} else {
res.send( body, 200, response);
}
}.bind( this ) );
}
});
app.get('/clearList', function( req, res ) {
// The client makes this request to get the data
activity.logExecuteData = [];
res.send( 200 );
});
// Used to populate events which have reached the activity in the interaction we created
app.get('/getActivityData', function( req, res ) {
// The client makes this request to get the data
if( !activity.logExecuteData.length ) {
res.send( 200, {data: null} );
} else {
res.send( 200, {data: activity.logExecuteData} );
}
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
| JavaScript | 0 | @@ -582,43 +582,43 @@
: '
-a6e7140c-2606-4bd1-889d-af8cfa63976
+2421d8a7-6578-44cc-9725-7728e2a4644
f',%0A
@@ -644,32 +644,32 @@
: '
-ek91sy2mc1v4ng6u013p8ato
+c0ynecuc5r28dad1umbtbj7t
',%0A
@@ -694,32 +694,32 @@
: '
-QyJeUpjAHkiudlTIwHPUKb31
+Yfv74IZTfTlTccaq86nhmyvH
',%0A
@@ -744,263 +744,263 @@
: '
-zna4wbti5chwjgoxuqv4kldru0v5xeippzps5eprvtjdmkeyxcq25ij5nlhgsulraz3m3vkxaczjb4ki5nyrq3zn5wa34fvurikkphuxuiqdo3ahtkevhorc0lmsmmjcmqmez2mlrcvvl1lbzeyxjg4gg2gahkjo0dbr41tvmm1fwto2yxsumstq2klvqnrvfqdtmreks2beqt3mvlqfhs4qcre2kpjaocbezcappjlsm1pdszgno0eihh3qp3f
+rqd1hndzqiwhirmcahjyonapo2ifx5j4xo1ifrfc2trwp11k0ef1texxzlp1x3splfkqnaryqe4soes0f5pe01gin1wztp533dor551gb1foau4o0vwrrebcfu1jlhl2sbzfnjtl2hjmpbj1mejy2z01rxu5ktjaecgpyqyrf3fots2gqf5oxzp0oviajrpdruyqld0qxabnxitbn0bl5uoglvvzuiuqqxefftkgxar2pbrtkwe15s5vigjsq5u
',%0A
|
fa4b23bde87a0b420c7fe79e8a434ce9fd47146f | reorganized the init-functions as a Marionette-module | app.js | app.js | var stringify = require('json-stringify-safe');
var _ = require('underscore');
var domify = require('domify');
var templates = require('./templates/compiled');
var domReady = require('domready');
var User = require('./models/user');
var PlayRouter = require('./routers/playrouter');
var MainLayout = require('./views/marionette/main_layout');
var HeaderView = require('./views/marionette/header_view');
var SidebarView = require('./views/marionette/sidebar_view');
var MainView = require('./views/marionette/main_view');
module.exports = {
init: function(){
var self = window.playground = this;
self.stringify = stringify; //this is the 'circular-dependency-free' version of stringify
self.User = User; //for console testing
self.user = new User(); //for displaying the 'two-way data-binding' example
document.head.appendChild(domify(templates.htmlhead()));
domReady(function(){
console.log('Welcome to the Backbone Playground');
document.body.appendChild(domify(templates.marionette.app()));
self.initApp();
});
},
initApp: function(){
var App = window.app = new Marionette.Application();
//add App region
App.addInitializer(function(){
App.addRegions({
main: '#app'
});
});
//add router
App.addInitializer(function(){
//currently without an explicit Marionette-Controller
App.Router = new PlayRouter();
});
//add layout and base regions (header, sidebar, main)
App.addInitializer(function(){
window.playground.initLayout();
});
//start backbone history
App.on("start", function(){
if (Backbone.history){
Backbone.history.start({pushState: true});
console.log('Backbone.History started.');
}
});
//start marionette
App.start();
},
initLayout: function(){
var layout = new MainLayout();
layout.on('show', function(){
this.headerRegion.show(new HeaderView());
this.sidebarRegion.show(new SidebarView());
this.mainRegion.show(new MainView());
});
app.main.show(layout);
}
};
module.exports.init();
| JavaScript | 0.999394 | @@ -547,16 +547,18 @@
ts = %7B%0D%0A
+%0D%0A
init
@@ -618,16 +618,78 @@
this;%0D%0A
+ var App = window.app = new Marionette.Application();%0D%0A
@@ -1194,19 +1194,51 @@
elf.init
-App
+Module(App);%0D%0A App.start
();%0D%0A
@@ -1265,19 +1265,22 @@
init
-App
+Module
: functi
@@ -1274,32 +1274,35 @@
odule: function(
+app
)%7B%0D%0A var
@@ -1301,60 +1301,16 @@
-var App = window.app = new Marionette.Application();
+if(app)%7B
%0D%0A
@@ -1311,24 +1311,28 @@
)%7B%0D%0A
+
//add App re
@@ -1337,33 +1337,37 @@
region%0D%0A
-A
+ a
pp.addInitialize
@@ -1389,25 +1389,29 @@
-A
+ a
pp.addRegion
@@ -1431,16 +1431,20 @@
+
main: '#
@@ -1453,32 +1453,36 @@
p'%0D%0A
+
%7D);%0D%0A %7D);
@@ -1470,37 +1470,140 @@
%7D);%0D%0A
+
%7D);%0D%0A
+%0D%0A app.module('MyModule', function(MyModule, App, Backbone, Marionette, $, _)%7B%0D%0A
//add ro
@@ -1608,35 +1608,48 @@
router%0D%0A
-App
+ MyModule
.addInitializer(
@@ -1653,32 +1653,40 @@
er(function()%7B%0D%0A
+
//cu
@@ -1748,19 +1748,32 @@
-App
+ MyModule
.Router
@@ -1793,37 +1793,53 @@
ter();%0D%0A
-%7D);%0D%0A
+ %7D);%0D%0A
//add la
@@ -1893,19 +1893,32 @@
-App
+ MyModule
.addInit
@@ -1954,37 +1954,363 @@
-window.playground.initL
+ var layout = new MainLayout();%0D%0A layout.on('show', function()%7B%0D%0A this.headerRegion.show(new HeaderView());%0D%0A this.sidebarRegion.show(new SidebarView());%0D%0A this.mainRegion.show(new MainView());%0D%0A %7D);%0D%0A App.main.show(l
ayout
-(
);%0D%0A
@@ -2309,32 +2309,40 @@
yout);%0D%0A
+
%7D);%0D%0A //s
@@ -2330,32 +2330,40 @@
%7D);%0D%0A
+
//start backbone
@@ -2376,24 +2376,32 @@
ry%0D%0A
+
App.on(%22star
@@ -2429,16 +2429,24 @@
+
if (Back
@@ -2457,24 +2457,32 @@
.history)%7B%0D%0A
+
@@ -2537,32 +2537,40 @@
+
console.log('Bac
@@ -2608,19 +2608,16 @@
-%7D%0D%0A
@@ -2609,34 +2609,32 @@
%7D
-);
%0D%0A //star
@@ -2631,372 +2631,141 @@
-//start marionette%0D%0A App.start();%0D%0A %7D,%0D%0A initLayout: function()%7B%0D%0A var layout = new MainLayout();%0D%0A layout.on('show', function()%7B%0D%0A this.headerRegion.show(
+ %7D);%0D%0A %7D);%0D%0A%0D%0A %7Delse%7B%0D%0A throw
new
-HeaderView());%0D%0A this.sidebarRegion.show(new SidebarView());%0D%0A this.mainRegion.show(new MainView());%0D%0A %7D);%0D%0A app.main.show(layout);
+Error('Marionette.Application was not initialized.')%0D%0A %7D
%0D%0A
|
b520f43511738eefaa0d48c734dff9c7ffe6f2e3 | Fix weird redirect upon login | app.js | app.js | /**
* Module dependencies.
*/
const express = require('express');
const compression = require('compression');
const session = require('express-session');
const bodyParser = require('body-parser');
const logger = require('morgan');
const chalk = require('chalk');
const errorHandler = require('errorhandler');
const lusca = require('lusca');
const dotenv = require('dotenv');
const MongoStore = require('connect-mongo')(session);
const flash = require('express-flash');
const path = require('path');
const mongoose = require('mongoose');
const passport = require('passport');
const expressValidator = require('express-validator');
const expressStatusMonitor = require('express-status-monitor');
const sass = require('node-sass-middleware');
const multer = require('multer');
const upload = multer({ dest: path.join(__dirname, 'uploads') });
/**
* Load environment variables from .env file, where API keys and passwords are configured.
*/
if (process.env.CI) {
dotenv.load({ path: '.env.example'});
} else {
dotenv.load({ path: '.env' });
}
/**
* Controllers (route handlers).
*/
const homeController = require('./controllers/home');
const userController = require('./controllers/user');
const apiController = require('./controllers/api');
/**
* API keys and Passport configuration.
*/
const passportConfig = require('./config/passport');
/**
* Create Express server.
*/
const app = express();
/**
* Connect to MongoDB.
*/
mongoose.Promise = global.Promise;
mongoose.connect(process.env.MONGODB_URI || process.env.MONGOLAB_URI);
mongoose.connection.on('error', () => {
console.log('%s MongoDB connection error. Please make sure MongoDB is running.', chalk.red('✗'));
process.exit();
});
/**
* Express configuration.
*/
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(expressStatusMonitor());
app.use(compression());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());
app.use(session({
resave: true,
saveUninitialized: true,
secret: process.env.SESSION_SECRET,
store: new MongoStore({
url: process.env.MONGODB_URI || process.env.MONGOLAB_URI,
autoReconnect: true
})
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
// app.use((req, res, next) => {
// if (req.path === '/api/upload') {
// next();
// } else {
// lusca.csrf()(req, res, next);
// }
// });
app.use(lusca.xframe('SAMEORIGIN'));
app.use(lusca.xssProtection(true));
app.use((req, res, next) => {
res.locals.user = req.user;
next();
});
app.use((req, res, next) => {
// After successful login, redirect back to the intended page
if (!req.user &&
req.path !== '/login' &&
req.path !== '/signup' &&
!req.path.match(/^\/auth/) &&
!req.path.match(/\./)) {
req.session.returnTo = req.path;
} else if (req.user &&
req.path == '/account') {
req.session.returnTo = req.path;
}
next();
});
app.use(express.static(path.join(__dirname, 'public'), { maxAge: 31557600000 }));
/**
* Primary app routes.
*/
app.get('/', homeController.index);
app.get('/config', homeController.config);
app.get('/login', userController.getLogin);
app.post('/login', userController.postLogin);
app.get('/logout', userController.logout);
app.get('/forgot', userController.getForgot);
app.post('/forgot', userController.postForgot);
app.get('/reset/:token', userController.getReset);
app.post('/reset/:token', userController.postReset);
app.get('/signup', userController.getSignup);
app.post('/signup', userController.postSignup);
app.get('/account', passportConfig.isAuthenticated, userController.getAccount);
app.post('/account/profile', passportConfig.isAuthenticated, userController.postUpdateProfile);
app.post('/account/password', passportConfig.isAuthenticated, userController.postUpdatePassword);
app.post('/account/delete', passportConfig.isAuthenticated, userController.postDeleteAccount);
app.get('/account/unlink/:provider', passportConfig.isAuthenticated, userController.getOauthUnlink);
app.get('/api/github', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getGithub);
app.get('/auth/github', passport.authenticate('github'));
app.get('/auth/github/callback', passport.authenticate('github', { failureRedirect: '/login' }), (req, res) => {
res.redirect(req.session.returnTo || '/');
});
app.get('/api/monitors', apiController.getAllMonitors);
app.get('/api/monitors/active', apiController.getAllMonitorsActive);
app.get('/api/monitors/raw', apiController.getAllMonitorsRaw);
app.get('/api/monitors/me', apiController.getMyMonitors);
app.post('/api/monitors', apiController.postMonitor);
app.get('/api/stopSchedule', apiController.getStopSchedule);
/**
* Error Handler.
*/
app.use(errorHandler());
/**
* Start Express server.
*/
app.listen(app.get('port'), () => {
console.log('%s App is running at http://localhost:%d in %s mode', chalk.green('✓'), app.get('port'), app.get('env'));
console.log(' Press CTRL-C to stop\n');
});
module.exports = app;
| JavaScript | 0 | @@ -3571,102 +3571,8 @@
t);%0A
-app.get('/signup', userController.getSignup);%0Aapp.post('/signup', userController.postSignup);%0A
app.
@@ -4042,340 +4042,8 @@
);%0A%0A
-app.get('/api/github', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getGithub);%0A%0Aapp.get('/auth/github', passport.authenticate('github'));%0Aapp.get('/auth/github/callback', passport.authenticate('github', %7B failureRedirect: '/login' %7D), (req, res) =%3E %7B%0A res.redirect(req.session.returnTo %7C%7C '/');%0A%7D);%0A%0A
app.
@@ -4398,16 +4398,326 @@
hedule);
+%0A%0Aapp.get('/api/github', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getGithub);%0A%0Aapp.get('/auth/github', passport.authenticate('github'));%0Aapp.get('/auth/github/callback', passport.authenticate('github', %7B failureRedirect: '/login' %7D), (req, res) =%3E %7B%0A res.redirect('/');%0A%7D);%0A%0A
%0A/**%0A *
|
461084cc72f3012905527dde321808e28d1020c0 | Add missing shebang | bin.js | bin.js | function usage () {/*
Usage
http-file-store --config=/path/to/config.json
Options
--config | -c Path to the JSON configuration file
--verbose | -v Enable verbosity pass in the module list to debug.
Config
The configuration is a plain json object describing several options to
apply to your instance of http-file-store.
{
"base": "/path/to/the/directory/to/read/write/files",
"url_base": "/base/url/to/serve/files",
"upload_path": "/base/to/temp/uploaded/files",
"ssl": {
"port": "a number, or null for a random port",
"host": "a host value to listen for https requests",
"key": "a path to an SSL key",
"ca": "a path to the SSL CA file",
"cert": "a path to the SSL cert file",
},
"clear": {
"port": "a number, or null for a random port",
"host": "a host value to listen for http requests",
}
}
*/}
var pkg = require('./package.json')
var argv = require('minimist')(process.argv.slice(2));
var help = require('@maboiteaspam/show-help')(usage, argv.h||argv.help, pkg)
var debug = require('@maboiteaspam/set-verbosity')(pkg.name, argv.v || argv.verbose);
var fs = require('fs')
const configPath = argv.config || argv.c || false;
(!configPath) && help.print(usage, pkg) && help.die(
"Wrong invokation"
);
var config = {}
try{
config = require(configPath)
}catch(ex){
help.die(
"Config path must exist and be a valid JSON file.\n" + ex
);
}
(!config) && help.print(usage, pkg)
&& help.die(
"The configuration could not be loaded, please double check the file"
);
(!config.base) && help.print(usage, pkg)
&& help.die(
"Configuration options are wrong : base is missing"
);
(!config.url_base)
&& help.print(usage, pkg)
&& help.die(
"Configuration options are wrong : url_base is missing"
);
(!config.upload_path)
&& help.print(usage, pkg)
&& help.die(
"Configuration options are wrong : upload_path is missing"
);
(!config.clear || !config.ssl)
&& help.print(usage, pkg)
&& help.die(
"Configuration options are wrong : you must provide one of clear or ssl options"
);
(!fs.existsSync(config.base))
&& help.print(usage, pkg)
&& help.die(
"Configuration options are wrong : base directory must exist"
);
(config.ssl && !fs.existsSync(config.ssl.key))
&& help.print(usage, pkg)
&& help.die(
"Configuration options are wrong : SSL key file must exist"
);
(config.ssl && config.ssl.ca && !fs.existsSync(config.ssl.ca))
&& help.print(usage, pkg)
&& help.die(
"Configuration options are wrong : SSL ca file must exist"
);
(config.ssl && !fs.existsSync(config.ssl.cert))
&& help.print(usage, pkg)
&& help.die(
"Configuration options are wrong : SSL cert file must exist"
);
var http = require('http');
var https = require('https');
var express = require('express');
var bodyParser = require('body-parser');
var multer = require('multer');
var fileStore = require('./index.js');
var upload = multer({ dest: config.upload_path });
var app = express();
app.get(config.base_url, fileStore.read(config.base));
app.post(config.base_url,
upload.single('file'),
fileStore.write(config.base, config.allowOverwrite));
if ( config.ssl && config.ssl.key && config.ssl.cert ) {
var SSL = https.createServer( {
key: fs.readFileSync( config.ssl.key ),
cert: fs.readFileSync( config.ssl.cert ),
ca: config.ssl.ca || []
}, app );
SSL.listen(config.ssl.port, config.ssl.host);
}
var CLEAR = http.createServer( app );
CLEAR.listen(config.lear.port, config.clear.host);
| JavaScript | 0.99982 | @@ -1,8 +1,29 @@
+#!/usr/bin/env node%0A%0A
function
|
83ed66786a4ceeed0a4fac71163b67ec7fd2229a | change channel | bot.js | bot.js | var botkit = require('botkit');
var token = process.env.BOTKIT_SLACK_VERIFY_TOKEN;
var controller = botkit.slackbot({
debug: false
}).configureSlackApp({
clientId: process.env.BOTKIT_SLACK_CLIENT_ID,
clientSecret: process.env.BOTKIT_SLACK_CLIENT_SECRET,
scopes: ['commands']
}
);
controller.setupWebserver(process.env.PORT,function(err,webserver){
controller.createWebhookEndpoints(controller.webserver);
controller.createOauthEndpoints(controller.webserver, function(err, req, res) {
if (err) {
res.status(500).send('Error: ' + JSON.stringify(err));
} else {
res.send('Success!');
}
});
});
controller.on('slash_command', function(bot, message) {
if (message.token !== token) {
return bot.res.send(401, 'Unauthorized');
}
switch (message.command) {
case '/remindja':
var choices = message.text.split(',');
var choice = choices[Math.random() * choices.length | 0];
bot.replyPrivate(message, '/remind #team-alpha to update the project status every Monday at 9am');
break;
}
}); | JavaScript | 0.000002 | @@ -965,18 +965,15 @@
nd #
-team-alpha
+general
to
|
610bcfe56f8fef1d2d0b097eabf55703d1ef5fca | Set bot game status | bot.js | bot.js | const commando = require('discord.js-commando');
const path = require('path');
const oneLine = require('common-tags').oneLine;
const CalendarSequelize = require('./src/calendar/CalendarSequelize.js');
const EventCalendar = require('./src/calendar/EventCalendar.js');
let config
try {
config = require('./config.json')
} catch (err) {
config = {
db: process.env['DATABASE_URL'],
auth: {
token: process.env['TOKEN'],
admins: (process.env['ADMINS'] || '').split(',')
}
}
}
const client = new commando.Client({
'owner': config.auth.admins,
'commandPrefix': '$',
'unknownCommandResponse': false
})
client
.on('error', console.error)
.on('warn', console.warn)
.on('debug', console.log)
.on('ready', () => {
console.log(`Client ready; logged in as ${client.user.username}#${client.user.discriminator} (${client.user.id})`);
})
.on('disconnect', () => { console.warn('Disconnected!'); })
.on('reconnecting', () => { console.warn('Reconnecting...'); })
.on('commandError', (cmd, err) => {
if (err instanceof commando.FriendlyError) return;
console.error(`Error in command ${cmd.groupID}:${cmd.memberName}`, err);
})
.on('commandBlocked', (msg, reason) => {
console.log(oneLine`
Command ${msg.command ? `${msg.command.groupID}:${msg.command.memberName}` : ''}
blocked; ${reason}
`);
})
.on('commandPrefixChange', (guild, prefix) => {
console.log(oneLine`
Prefix ${prefix === '' ? 'removed' : `changed to ${prefix || 'the default'}`}
${guild ? `in guild ${guild.name} (${guild.id})` : 'globally'}.
`);
})
.on('commandStatusChange', (guild, command, enabled) => {
console.log(oneLine`
Command ${command.groupID}:${command.memberName}
${enabled ? 'enabled' : 'disabled'}
${guild ? `in guild ${guild.name} (${guild.id})` : 'globally'}.
`);
})
.on('groupStatusChange', (guild, group, enabled) => {
console.log(oneLine`
Group ${group.id}
${enabled ? 'enabled' : 'disabled'}
${guild ? `in guild ${guild.name} (${guild.id})` : 'globally'}.
`);
});
// client.setProvider(
// sqlite.open(path.join(__dirname, 'settings.sqlite3')).then(db => new commando.SQLiteProvider(db))
// ).catch(console.error);
db = new CalendarSequelize(config.db);
eventCalendar = new EventCalendar(db);
client.EventCalendar = eventCalendar;
client.registry
.registerGroup('moderation', 'Moderation')
.registerGroup('calendar', 'Calendar')
.registerDefaults()
.registerCommandsIn(path.join(__dirname, 'src/commands'));
client.login(config.auth.token); | JavaScript | 0 | @@ -936,24 +936,107 @@
er.id%7D)%60);%0D%0A
+ client.user.setGame('You must be tired after today %7C Let%E2%80%99s go to sleep.')%0D%0A
%7D)%0D%0A
|
c881da66272c39db888ef6c25dc59b4cddbdb0ef | add cli alias: `-h`. | cli.js | cli.js | #!/usr/bin/env node
/**
* @file cli
* @author junmer
*/
/* eslint-env node */
'use strict';
var fs = require('fs');
var meow = require('meow');
var path = require('path');
var stdin = require('get-stdin');
var Fontmin = require('./');
var _ = require('lodash');
var cli = meow({
help: [
'Usage',
' $ fontmin <file> <directory>',
' $ fontmin <directory> <output>',
' $ fontmin <file> > <output>',
' $ cat <file> | fontmin > <output>',
'',
'Example',
' $ fontmin fonts/* build',
' $ fontmin fonts build',
' $ fontmin foo.ttf > foo-optimized.ttf',
' $ cat foo.ttf | fontmin > foo-optimized.ttf',
'',
'Options',
' -t, --text require glyphs by text',
' -b, --basic-text require glyphs with base chars',
' -d, --deflate-woff deflate woff',
' -f, --font-family font-family for @font-face CSS',
' -T, --show-time show time fontmin cost'
].join('\n')
}, {
'boolean': [
'basic-text',
'show-time',
'deflate-woff'
],
string: [
'text'
],
alias: {
t: 'text',
b: 'basic-text',
d: 'deflate-woff',
T: 'show-time'
}
});
function isFile(path) {
if (/^[^\s]+\.\w*$/.test(path)) {
return true;
}
try {
return fs.statSync(path).isFile();
}
catch (err) {
return false;
}
}
function run(src, dest) {
cli.flags.showTime && console.time('fontmin use');
var pluginOpts = _.extend({
clone: true
}, cli.flags, {
deflate: cli.flags.deflateWoff
});
var fontmin = new Fontmin()
.src(src)
.use(Fontmin.glyph(pluginOpts))
.use(Fontmin.ttf2eot(pluginOpts))
.use(Fontmin.ttf2svg(pluginOpts))
.use(Fontmin.ttf2woff(pluginOpts))
.use(Fontmin.css(pluginOpts));
if (process.stdout.isTTY) {
fontmin.dest(dest ? dest : 'build');
}
fontmin.run(function (err, files) {
if (err) {
console.error(err.message);
process.exit(1);
}
if (!process.stdout.isTTY) {
files.forEach(function (file) {
process.stdout.write(file.contents);
});
}
cli.flags.showTime && console.timeEnd('fontmin use');
});
}
if (process.stdin.isTTY) {
var src = cli.input;
var dest;
if (!cli.input.length) {
console.error([
'Provide at least one file to optimize',
'',
'Example',
' fontmin font/* build',
' fontmin foo.ttf > foo-optimized.ttf',
' cat foo.ttf | fontmin > foo-optimized.ttf'
].join('\n'));
process.exit(1);
}
if (src.length > 1 && !isFile(src[src.length - 1])) {
dest = src[src.length - 1];
src.pop();
}
src = src.map(function (s) {
if (!isFile(s) && fs.existsSync(s)) {
return path.join(s, '**/*');
}
return s;
});
run(src, dest);
}
else {
stdin.buffer(run);
}
| JavaScript | 0 | @@ -1344,16 +1344,35 @@
ow-time'
+,%0A h: 'help'
%0A %7D%0A%7D
@@ -2851,16 +2851,90 @@
zed.ttf'
+,%0A '',%0A 'See %60fontmin --help%60 for more information.'
%0A
|
06c417181cf4b0b0235a5a79cb02528252d5f93c | Add a short flags for `help` and `version` options (#14) | cli.js | cli.js | #!/usr/bin/env node
'use strict';
const chalk = require('chalk');
const meow = require('meow');
const githubRepos = require('./');
const cli = meow(`
Usage
$ github-repositories kevva
$ github-repositories kevva --token 523ef69119eadg12
Options
-f, --forks Only list forks
-r, --repos Only display repository names
-s, --sources Only list sources
-t, --token GitHub authentication token
-u, --urls Only display URL
`, {
boolean: [
'forks',
'repos',
'sources',
'urls'
],
string: [
'token'
],
alias: {
f: 'forks',
r: 'repos',
s: 'sources',
t: 'token',
u: 'urls'
}
});
if (cli.input.length === 0) {
console.error('User required');
process.exit(1);
}
githubRepos(cli.input[0], cli.flags).then(data => {
for (const x of data) {
if (cli.flags.forks && !x.fork) {
return;
}
if (cli.flags.sources && x.fork) {
return;
}
if (!cli.flags.forks && !cli.flags.sources && x.fork) {
x.name += chalk.dim(' (fork)');
}
if (cli.flags.repos) {
console.log(x.name);
return;
}
if (cli.flags.urls) {
console.log(x.html_url);
return;
}
console.log(`${x.name} ${chalk.dim(x.html_url)}`);
}
});
| JavaScript | 0 | @@ -547,16 +547,29 @@
lias: %7B%0A
+%09%09h: 'help',%0A
%09%09f: 'fo
@@ -629,16 +629,32 @@
: 'urls'
+,%0A%09%09v: 'version'
%0A%09%7D%0A%7D);%0A
|
060b87db47058cdd3941b5a716f49dd95c8eb785 | Disable the file name without a extension and add the error message on the case of the config file not found | cli.js | cli.js | #! /usr/bin/env node
'use strict';
var Liftoff = require('liftoff');
var argv = require('minimist')(process.argv.slice(2));
var Stubbatti = require('./');
// construct stubbatti DSL vocabulary
var stubbatti = new Stubbatti();
Stubbatti.methods.forEach(function (method) {
global[method] = function (path, body, opts) {
stubbatti.register(method, path, body, opts);
};
});
/**
* ```
* port(12345);
* ```
* Sets the stub server's port.
*/
global.port = function (port) {
stubbatti.setPort(port);
};
// set up liftoff params
var cli = new Liftoff({
name: 'stubbatti',
moduleName: 'stubbatti',
configName: '{,.}stubbatti',
extensions: {
'.js': null,
'': null
},
processTitle: 'stubbatti',
});
// main
var main = function (env) {
// load user defined stubbatti file
require(env.configPath);
// if `--kill` option is specified then don't launch a stub server but kill the existing sevrer.
if (argv.kill) {
stubbatti.killExistingServer();
return;
}
console.log('Stubbatti server version %s.', Stubbatti.version);
// launch a stub server
stubbatti.start();
};
cli.launch({
cwd: argv.cwd,
configPath: argv.config
}, main);
| JavaScript | 0.000001 | @@ -150,16 +150,67 @@
('./');%0A
+var homepage = require('./package.json').homepage;%0A
%0A%0A// con
@@ -751,26 +751,8 @@
js':
- null,%0A '':
nul
@@ -831,24 +831,293 @@
on (env) %7B%0A%0A
+ console.log('Stubbatti server version %25s.', Stubbatti.version);%0A%0A if (!env.configPath) %7B%0A console.log('Error: %60stubbatti%60 file not found.');%0A console.log('see %25s', homepage);%0A%0A return;%0A %7D%0A%0A console.log('Loading %25s.', env.configPath);%0A%0A
// load
@@ -1357,84 +1357,15 @@
rn;%0A
+
%7D%0A%0A
- console.log('Stubbatti server version %25s.', Stubbatti.version);%0A%0A
|
8b9fc3a40d2d6f4d53f8dadf1c565461e57d5678 | Update CLI help | cli.js | cli.js | #!/usr/bin/env node
'use strict'
const meow = require('meow')
const ghDescription = require('./')
const Promise = require('bluebird')
const gitconfig = require('gitconfiglocal')
const pify = require('pify')
const ghauth = Promise.promisify(require('ghauth'))
const authOptions = {
configName: 'gh-description',
note: 'Set and get a GitHub repository description',
userAgent: 'github.com/RichardLitt/gh-description',
scope: ['repo']
}
var cli = meow([`
Usage
$ gh-description [input]
Examples
$ gh-description
Current description: Set and get a GitHub repository description
$ gh-description RichardLitt/gh-description 'ponies and unicorns'
New description: ponies and unicorns
`, {
alias: {}
}])
Promise.try(() => {
return pify(gitconfig)(process.cwd())
}).then(config => {
if (config && config.remote && config.remote.origin && config.remote.origin.url) {
var url = config.remote.origin.url
if (!url.match(/^https:\/\/github.com/)) {
return url.split(':')[1].split('.git')[0]
} else {
return url.split('github.com/')[1]
}
}
}).then((res) => {
if (res && cli.input.length === 0) {
cli.input[0] = res
}
return (cli.input[1]) ? ghauth(authOptions) : { token: null }
}).then((authData) => {
return ghDescription(cli.input[0], cli.input[1], cli.flags, authData.token)
}).then(function (response) {
if (!response.method) {
console.log(response)
} else if (response.method === 'patch') {
console.log(`New description:\n${response.description}`)
} else if (response.method === 'get') {
console.log(`${response.description}`)
}
})
| JavaScript | 0 | @@ -533,16 +533,88 @@
-Current
+Set and get a GitHub repository description%0A $ gh-description RichardLitt/gh-
desc
@@ -620,17 +620,20 @@
cription
-:
+%0A
Set and
|
09870f4b58bfc99060c6ad9915336f16e3e6833e | fix code style | cli.js | cli.js | #!/usr/bin/env node
'use strict';
var fs = require('fs');
var meow = require('meow');
var path = require('path');
var stdin = require('get-stdin');
var Fontmin = require('./');
var cli = meow({
help: [
'Usage',
' $ fontmin <file> <directory>',
' $ fontmin <directory> <output>',
' $ fontmin <file> > <output>',
' $ cat <file> | fontmin > <output>',
'',
'Example',
' $ fontmin fonts/* build',
' $ fontmin fonts build',
' $ fontmin foo.ttf > foo-optimized.ttf',
' $ cat foo.ttf | fontmin > foo-optimized.ttf',
'',
'Options',
' -t, --text require glyphs by text',
' -b, --basic-text require glyphs with base chars',
' -f, --font-family font-family for @font-face CSS',
' -T, --show-time show time fontmin cost'
].join('\n')
}, {
boolean: [
'basic-text',
'show-time'
],
string: [
'text'
],
alias: {
t: 'text',
b: 'basic-text',
T: 'show-time'
}
});
function isFile(path) {
if (/^[^\s]+\.\w*$/g.test(path)) {
return true;
}
try {
return fs.statSync(path).isFile();
} catch (err) {
return false;
}
}
function run(src, dest) {
cli.flags['showTime'] && console.time('fontmin use');
var fontmin = new Fontmin()
.src(src)
.use(Fontmin.glyph(cli.flags))
.use(Fontmin.ttf2eot({clone: true}))
.use(Fontmin.ttf2svg({clone: true}))
.use(Fontmin.ttf2woff({clone: true}))
.use(Fontmin.css(cli.flags));
if (process.stdout.isTTY) {
fontmin.dest(dest ? dest : 'build');
}
fontmin.run(function (err, files) {
if (err) {
console.error(err.message);
process.exit(1);
}
if (!process.stdout.isTTY) {
files.forEach(function (file) {
process.stdout.write(file.contents);
});
}
cli.flags['showTime'] && console.timeEnd('fontmin use');
});
}
if (process.stdin.isTTY) {
var src = cli.input;
var dest;
if (!cli.input.length) {
console.error([
'Provide at least one file to optimize',
'',
'Example',
' fontmin font/* build',
' fontmin foo.ttf > foo-optimized.ttf',
' cat foo.ttf | fontmin > foo-optimized.ttf'
].join('\n'));
process.exit(1);
}
if (src.length > 1 && !isFile(src[src.length - 1])) {
dest = src[src.length - 1];
src.pop();
}
src = src.map(function (s) {
if (!isFile(s) && fs.existsSync(s)) {
return path.join(s, '**/*');
}
return s;
});
run(src, dest);
} else {
stdin.buffer(run);
}
| JavaScript | 0.000022 | @@ -13,16 +13,80 @@
nv node%0A
+%0A/**%0A * @file cli%0A * @author junmer%0A */%0A%0A/* eslint-env node */%0A%0A
'use str
@@ -1031,15 +1031,17 @@
+'
boolean
+'
: %5B%0A
@@ -1263,17 +1263,16 @@
+%5C.%5Cw*$/
-g
.test(pa
@@ -1364,16 +1364,20 @@
);%0A %7D
+%0A
catch (
@@ -1451,34 +1451,33 @@
cli.flags
-%5B'
+.
showTime
'%5D && consol
@@ -1456,34 +1456,32 @@
i.flags.showTime
-'%5D
&& console.time
@@ -2167,18 +2167,17 @@
lags
-%5B'
+.
showTime
'%5D &
@@ -2176,10 +2176,8 @@
Time
-'%5D
&&
@@ -2935,17 +2935,17 @@
dest);%0A%7D
-
+%0A
else %7B%0A
|
6367e728b8d93227e79da5806d94ff0e402a6c6c | more verbose output | cli.js | cli.js | #!/usr/bin/env node
var fs = require("fs");
var path = require('path');
var chalk = require('chalk');
var Table = require('cli-table');
var async = require('async');
var theGit = require('git-state');
var Spinner = require('cli-spinner').Spinner;
var spinner = null;
var table = null;
var cwd = null;
var debug = false;
process.on('uncaughtException', (err) => {
console.log(`Caught exception: ${err}`);
});
function init() {
//either passed from CLI or take the current directory
cwd = process.argv[2] || process.cwd();
//Spinners
spinner = new Spinner('%s');
spinner.setSpinnerString(18);
spinner.start();
//Console Tables
table = new Table({
head: [chalk.cyan('Directory'), chalk.cyan('Current Branch/NA')]
});
}
function prettyPath(pathString) {
var p = pathString.split('/');
return p[p.length - 1];
}
var fileIndex = 0;
function processDirectory(stat, callback) {
var pathString = path.join(cwd, stat.file);
if( stat.stat.isDirectory() ){
theGit.isGit(pathString, function(isGit){
if(isGit){
theGit.check( pathString, function(e, gitStatus){
if(e) callback(e);
insert(pathString, gitStatus)
callback(null, true)
if(debug) console.log(fileIndex++, stat.file)
if(debug) console.log(gitStatus)
})
} else {
var gitStatus = {branch: '-', issues: false};
insert(pathString, gitStatus)
callback(null, false)
if(debug) console.log(fileIndex++, stat.file)
if(debug) console.log(gitStatus)
}
})
} else {
if(debug) console.log(fileIndex++, stat.file)
if(debug) console.log(false)
callback(null, false)
}
}
function insert(pathString, status){
table.push([prettyPath(pathString), status.issues ? chalk.red(status.branch) : chalk.green(status.branch)]);
}
function finish(){
spinner.stop();
console.log( table.toString() );
}
init();
console.log( chalk.green( cwd ) )
// processDirectory(cwd)
fs.readdir(cwd, function (err, files) {
async.map(files, function (file, statCallback) {
fs.stat(path.join(cwd, file), function (err, stat) {
if(err) return statCallback(err);
statCallback( null, {
file: file,
stat: stat
})
})
}, function(err, statuses){
if(err) throw new Error(err);
if(debug) console.log(statuses.length);
async.filter(statuses, processDirectory, function () {
finish();
})
})
}); | JavaScript | 0.999977 | @@ -677,16 +677,23 @@
head: %5B
+%0A
chalk.cy
@@ -709,16 +709,23 @@
tory'),
+%0A
chalk.cy
@@ -747,16 +747,139 @@
nch/NA')
+, %0A chalk.cyan('Ahead'), %0A chalk.cyan('Dirty'), %0A chalk.cyan('Untracked'), %0A chalk.cyan('Stashes')%0A
%5D%0A %7D);%0A
@@ -1870,16 +1870,210 @@
tatus)%7B%0A
+ var method = status.dirty === 0%0A ? status.ahead === 0%0A ? status.untracked === 0%0A ? chalk.grey%0A : chalk.yellow%0A : chalk.green%0A : chalk.red%0A
table.
@@ -2078,16 +2078,23 @@
e.push(%5B
+%0A
prettyPa
@@ -2113,77 +2113,483 @@
g),
-status.issues ? chalk.re
+%0A method( status.branch !== undefined && status.branch !== null ? status.branch : '-' ),%0A method( status.ahead !== undefined && status.ahead !== null ? status.ahead : '-' ),%0A method( status.dirty !== undefined && status.dirty !== null ? status.dirty : '-' ),%0A metho
d(
+
status.
-branch) : chalk.green(status.branch)
+untracked !== undefined && status.untracked !== null ? status.untracked : '-' ),%0A method( status.stashes !== undefined && status.stashes !== null ? status.stashes : '-' )%0A
%5D);%0A
@@ -3201,11 +3201,12 @@
%7D)%0A %7D)%0A
-
%7D);
+%0A
|
5d17767bc10f9f27a512fef1b7dd908b99d40f37 | Formatted summary output | cli.js | cli.js | /*eslint no-console: ["error", {allow: ["log"]}] */
var validate = require('./index.js');
var colors = require('colors/safe');
var fs = require('fs');
module.exports = function (dir, options) {
options.filesPerIssueMax = 10;
if (fs.existsSync(dir)) {
validate.BIDS(dir, options, function (errors, warnings, summary) {
if (errors === 'Invalid') {
console.log(colors.red("This does not appear to be a BIDS dataset. For more info go to http://bids.neuroimaging.io/"));
} else if (errors.length >= 1 || warnings.length >= 1) {
logIssues(errors, 'red', options);
logIssues(warnings, 'yellow', options);
}
else {
console.log(colors.green("This dataset appears to be BIDS compatible."));
}
logSummary(summary);
});
} else {
console.log(colors.red(dir + " does not exist"));
}
};
function logIssues (issues, color, options) {
for (var i = 0; i < issues.length; i++) {
var issue = issues[i];
console.log('\t' + colors[color]((i + 1) + ': ' + issue.reason + ' (code: ' + issue.code + ')'));
for (var j = 0; j < issue.files.length; j++) {
var file = issues[i].files[j];
if (!file) {continue;}
console.log('\t\t' + file.file.relativePath);
if (options.verbose) {console.log('\t\t\t' + file.reason);}
if (file.line) {
var msg = '\t\t\t@ line: ' + file.line;
if (file.character) {
msg += ' character: ' + file.character;
}
console.log(msg);
}
if (file.evidence) {
console.log('\t\t\tEvidence: ' + file.evidence);
}
if (!options.verbose && (j+1) >= options.filesPerIssueMax) {
var remaining = issue.files.length - (j+1);
console.log('\t\t'+colors[color]('... and '+remaining+' more files having this issue (Use --verbose to see them all).'));
break;
}
}
console.log();
}
}
function logSummary (summary) {
console.log(colors.blue.underline('\t' + 'Summary:'));
console.log('\t' + summary.subjects.length + '\t- Subjects');
console.log('\t' + summary.sessions.length + '\t- Sessions');
console.log('\t' + summary.runs.length + '\t- Runs');
console.log();
console.log(colors.grey('\t' + 'Tasks'));
for (var i = 0; i < summary.tasks.length; i++) {
console.log('\t' + summary.tasks[i]);
}
console.log();
console.log(colors.grey('\t' + 'Modalities'));
for (var i = 0; i < summary.modalities.length; i++) {
console.log('\t' + summary.modalities[i]);
}
console.log();
} | JavaScript | 0.999793 | @@ -59,16 +59,17 @@
alidate
+
= requir
@@ -96,16 +96,19 @@
colors
+
= requir
@@ -129,18 +129,97 @@
');%0Avar
-fs
+cliff = require('cliff');%0Avar pluralize = require('pluralize');%0Avar fs
= requi
@@ -2268,221 +2268,238 @@
) %7B%0A
+%0A
-console.log(colors.blue.underline('%5Ct' + 'Summary:'));%0A console.log('%5Ct' + summary.subjects.length + '%5Ct- Subjects');%0A console.log('%5Ct' + summary.sessions.length + '%5Ct- Sessions');%0A console.log('%5Ct' +
+// data%0A var column1 = %5B%0A summary.subjects.length + ' - ' + pluralize('Subject', summary.subjects.length),%0A summary.sessions.length + ' - ' + pluralize('Session', summary.sessions.length),%0A
sum
@@ -2526,244 +2526,389 @@
+ '
-%5Ct- Runs');%0A console.log();%0A console.log(colors.grey('%5Ct' + 'Tasks'));%0A for (var i = 0; i %3C summary.tasks.length; i++) %7B%0A console.log('%5Ct' + summary.tasks%5Bi%5D);%0A %7D%0A console.log();%0A console.log(colors.grey('%5Ct' +
+ - ' + pluralize('Run', summary.runs.length)%0A %5D,%0A column2 = summary.tasks,%0A column3 = summary.modalities;%0A%0A var longestColumn = Math.max(column1.length, column2.length, column3.length);%0A var pad = ' ';%0A%0A // headers%0A var headers = %5Bpad, colors.blue.underline('Summary:') + pad, colors.blue.underline('Tasks:') + pad, colors.blue.underline(
'Mod
@@ -2918,127 +2918,375 @@
ties
+:
')
-);%0A for (var i = 0; i %3C summary.modalities.length; i++) %7B%0A console.log('%5Ct' + summary.modalities%5Bi%5D);%0A %7D
+%5D%0A%0A // rows%0A var rows = %5Bheaders%5D;%0A for (var i = 0; i %3C longestColumn; i++) %7B%0A var val1, val2, val3;%0A val1 = column1%5Bi%5D ? column1%5Bi%5D + pad : '';%0A val2 = column2%5Bi%5D ? column2%5Bi%5D + pad : '';%0A val3 = column3%5Bi%5D ? column3%5Bi%5D : '';%0A rows.push(%5B' ', val1, val2, val3%5D);%0A %7D%0A console.log(cliff.stringifyRows(rows));%0A
%0A
|
d0cc6914cb40d19e2c40abb0e3185b26d52509c6 | Drop support for really old browsers | grunt/autoprefixer-settings.js | grunt/autoprefixer-settings.js | module.exports = {
browsers: [
//
// Official browser support mirrors Bootstrap's policy:
// http://v4-alpha.getbootstrap.com/getting-started/browsers-devices/#supported-browsers
//
'Chrome >= 35', // Exact version number here is kinda arbitrary
// Rather than using Autoprefixer's native "Firefox ESR" version specifier string,
// we deliberately hardcode the number. This is to avoid unwittingly severely breaking the previous ESR in the event that:
// (a) we happen to ship a new Bootstrap release soon after the release of a new ESR,
// such that folks haven't yet had a reasonable amount of time to upgrade; and
// (b) the new ESR has unprefixed CSS properties/values whose absence would severely break webpages
// (e.g. `box-sizing`, as opposed to `background: linear-gradient(...)`).
// Since they've been unprefixed, Autoprefixer will stop prefixing them,
// thus causing them to not work in the previous ESR (where the prefixes were required).
'Firefox >= 38', // Current Firefox Extended Support Release (ESR); https://www.mozilla.org/en-US/firefox/organizations/faq/
// Note: Edge versions in Autoprefixer & Can I Use refer to the EdgeHTML rendering engine version,
// NOT the Edge app version shown in Edge's "About" screen.
// For example, at the time of writing, Edge 20 on an up-to-date system uses EdgeHTML 12.
// See also https://github.com/Fyrd/caniuse/issues/1928
'Edge >= 12',
'Explorer >= 9',
// Out of leniency, we prefix these 1 version further back than the official policy.
'iOS >= 8',
'Safari >= 8',
// The following remain NOT officially supported, but we're lenient and include their prefixes to avoid severely breaking in them.
'Android 2.3',
'Android >= 4',
'Opera >= 12'
]
};
| JavaScript | 0 | @@ -32,191 +32,8 @@
: %5B%0A
- //%0A // Official browser support mirrors Bootstrap's policy:%0A // http://v4-alpha.getbootstrap.com/getting-started/browsers-devices/#supported-browsers%0A //%0A
@@ -51,10 +51,10 @@
%3E=
-35
+49
', /
@@ -103,73 +103,38 @@
rary
-%0A // Rather than using Autoprefixer's native %22Firefox ESR%22
+ ~ equivalent release to first
ver
@@ -142,16 +142,19 @@
ion
+of
specifie
r st
@@ -153,749 +153,167 @@
ifie
-r string,%0A // we deliberately hardcode the number. This is to avoid unwittingly severely breaking the previous ESR in the event that:%0A // (a) we happen to ship a new Bootstrap release soon after the release of a new ESR,%0A // such that folks haven't yet had a reasonable amount of time to upgrade; and%0A // (b) the new ESR has unprefixed CSS properties/values whose absence would severely break webpages%0A // (e.g. %60box-sizing%60, as opposed to %60background: linear-gradient(...)%60).%0A // Since they've been unprefixed, Autoprefixer will stop prefixing them,%0A // thus causing them to not work in the previous ESR (where the prefixes were required).%0A 'Firefox %3E= 38', // Current
+d Firefox ESR.%0A // Go back 1 version futher for current Firefox ESR, rather than using Autoprefixer's native %22Firefox ESR%22 version specifier.%0A //
Fir
@@ -406,16 +406,41 @@
ns/faq/%0A
+ 'Firefox %3E= 45',%0A
@@ -920,25 +920,25 @@
'iOS %3E=
-8
+9
',%0A '
@@ -947,17 +947,17 @@
fari %3E=
-8
+9
',%0A
@@ -1111,58 +1111,12 @@
oid
-2.3',%0A 'Android %3E= 4',%0A 'Opera %3E= 12
+%3E= 4
'%0A
|
7da5833c957ccfb52c82fe6073476c81c7e88b87 | Fix path.join error in Node 7.1; added support for enabling/disabling transforms via env variables | register.js | register.js | var fs = require( 'fs' );
var path = require( 'path' );
var crypto = require( 'crypto' );
var homedir = require( 'os-homedir' );
var buble = require( './' );
var original = require.extensions[ '.js' ];
var nodeModulesPattern = path.sep === '/' ? /\/node_modules\// : /\\node_modules\\/;
var nodeVersion = /(?:0\.)?\d+/.exec( process.version )[0];
var versions = [ '0.10', '0.12', '4', '5', '6' ];
if ( !~versions.indexOf( nodeVersion ) ) {
if ( +nodeVersion > 6 ) {
nodeVersion = 6;
} else {
throw new Error( 'Unsupported version (' + nodeVersion + '). Please raise an issue at https://gitlab.com/Rich-Harris/buble/issues' );
}
}
var options = {
target: {
node: nodeVersion
}
};
function mkdirp ( dir ) {
var parent = path.dirname( dir );
if ( dir === parent ) return;
mkdirp( parent );
try {
fs.mkdirSync( dir );
} catch ( err ) {
if ( err.code !== 'EEXIST' ) throw err;
}
}
var home = homedir();
if ( home ) {
var cachedir = path.join( home, '.buble-cache', nodeVersion );
mkdirp( cachedir );
fs.writeFileSync( path.join( home, '.buble-cache/README.txt' ), 'These files enable a faster startup when using buble/register. You can safely delete this folder at any time. See https://buble.surge.sh/guide/ for more information.' );
}
require.extensions[ '.js' ] = function ( m, filename ) {
if ( nodeModulesPattern.test( filename ) ) return original( m, filename );
var source = fs.readFileSync( filename, 'utf-8' );
var hash = crypto.createHash( 'sha256' );
hash.update( source );
var key = hash.digest( 'hex' ) + '.json';
var cachepath = path.join( cachedir, key );
var compiled;
if ( cachedir ) {
try {
compiled = JSON.parse( fs.readFileSync( cachepath, 'utf-8' ) );
} catch ( err ) {
// noop
}
}
if ( !compiled ) {
try {
compiled = buble.transform( source, options );
if ( cachedir ) {
fs.writeFileSync( cachepath, JSON.stringify( compiled ) );
}
} catch ( err ) {
if ( err.snippet ) {
console.log( 'Error compiling ' + filename + ':\n---' );
console.log( err.snippet );
console.log( err.message );
console.log( '' )
process.exit( 1 );
}
throw err;
}
}
m._compile( '"use strict";\n' + compiled.code, filename );
};
| JavaScript | 0 | @@ -688,16 +688,421 @@
%0A%09%7D%0A%7D;%0A%0A
+function configTransform (transforms, enabled) %7B%0A%09options.transforms = options.transforms %7C%7C %7B%7D; %0A%09transforms.forEach(function (transform) %7B%0A%09%09options.transforms%5Btransform.trim()%5D = enabled;%0A%09%7D);%0A%7D%0A%0Aif (process.env.BUBLE_OPTION_YES) %7B%0A%09configTransform(process.env.BUBLE_OPTION_YES.split(','), true);%0A%7D%0Aif (process.env.BUBLE_OPTION_NO) %7B%0A%09configTransform(process.env.BUBLE_OPTION_NO.split(','), false);%0A%7D%0A%0A
function
@@ -1386,16 +1386,21 @@
-cache',
+ '' +
nodeVer
|
a226e7e6c8a63c6ed3f37ea69bfa4fb9fb9050d8 | clean whitespace | renderer.js | renderer.js | // This file is required by the index.html file and will
// be executed in the renderer process for that window.
// All of the Node.js APIs are available in this process.
const electron = require('electron')
const request = require('request')
// handler to get company name
let companyNameHandler = debounce(function() {
let input = getInput()
if (input) {
getCompanyName(input)
} else {
getCompanyName()
}
}, 250)
// add event listeners for ticker input field
let tickerInput = document.getElementById("stockTicker")
tickerInput.addEventListener('keyup', companyNameHandler, false)
tickerInput.addEventListener('search', companyNameHandler, false)
// get latest stock data for a given stock symbol every second
setInterval(function() {
let input = getInput()
if (input) {
getStockPrice(input)
} else {
getStockPrice()
}
}, 1000)
/*
* Core Functions
*/
// get stock data by ticker symbol
function getStockPrice(ticker = 'goog') {
try {
request(`http://finance.google.com/finance/info?q=${ticker}`, function(error, response, body) {
body = body.slice(3)
body = JSON.parse(body)
newPrice(body)
})
} catch(e) {
console.log(e)
}
}
// get company name by ticker symbol
function getCompanyName(ticker = 'goog') {
try {
request(`http://d.yimg.com/aq/autoc?query=${ticker}®ion=US&lang=en-US`, function(error, response, body) {
body = JSON.parse(body)
body = body.ResultSet.Result[0].name
document.getElementById('companyName').innerHTML = body
})
} catch(e) {
console.log(e)
}
}
// display latest price data
function newPrice(arr) {
const currentPrice = arr[0]['l']
const points = arr[0]['c']
const yield = arr[0]['cp']
const isPositive = /[+]/i.test(points)
document.getElementById('stockPrice').innerHTML = currentPrice
document.getElementById('stockPoints').innerHTML = points
document.getElementById('stockYield').innerHTML = `(${yield}%)`
if (isPositive) {
document.getElementById('stockYield').classList.remove('red')
document.getElementById('stockYield').classList.add('green')
document.getElementById('stockPoints').classList.remove('red')
document.getElementById('stockPoints').classList.add('green')
} else {
document.getElementById('stockYield').classList.remove('green')
document.getElementById('stockYield').classList.add('red')
document.getElementById('stockPoints').classList.remove('green')
document.getElementById('stockPoints').classList.add('red')
}
}
// get current input data for stockTicker element
function getInput() {
return document.getElementById('stockTicker').value !== '' ? document.getElementById('stockTicker').value : false
}
/*
* Helper Functions
*/
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
var timeout
return function() {
var context = this, args = arguments
var later = function() {
timeout = null
if (!immediate) func.apply(context, args)
}
var callNow = immediate && !timeout
clearTimeout(timeout)
timeout = setTimeout(later, wait)
if (callNow) func.apply(context, args)
}
}
| JavaScript | 0.999541 | @@ -3064,17 +3064,18 @@
iate) %7B%0A
-%09
+
var time
@@ -3078,17 +3078,18 @@
timeout%0A
-%09
+
return f
@@ -3100,18 +3100,20 @@
ion() %7B%0A
-%09%09
+
var cont
@@ -3141,18 +3141,20 @@
guments%0A
-%09%09
+
var late
@@ -3170,19 +3170,22 @@
ion() %7B%0A
-%09%09%09
+
timeout
@@ -3195,11 +3195,14 @@
ull%0A
-%09%09%09
+
if (
@@ -3243,14 +3243,18 @@
gs)%0A
-%09%09%7D%0A%09%09
+ %7D%0A
var
@@ -3285,18 +3285,20 @@
timeout%0A
-%09%09
+
clearTim
@@ -3311,18 +3311,20 @@
imeout)%0A
-%09%09
+
timeout
@@ -3353,10 +3353,12 @@
it)%0A
-%09%09
+
if (
@@ -3396,9 +3396,10 @@
gs)%0A
-%09
+
%7D%0A%7D%0A
|
54a5a792025ebd324f01e6ac386b0412ed97d122 | Change window size | app/main.js | app/main.js | /**
* @module drivshare-gui/main
*/
'use strict';
var app = require('app');
var BrowserWindow = require('browser-window');
var main = null;
app.on('ready', function () {
var ipc = require('electron-safe-ipc/host');
var dialog = require('dialog');
var ApplicationMenu = require('./lib/menu');
var menu = new ApplicationMenu();
main = new BrowserWindow({
width: 620,
height: 720
});
menu.render();
main.loadUrl('file://' + __dirname + '/driveshare.html');
main.on('close', function(e) {
if (process.platform === 'darwin') {
if (!main.forceClose) {
e.preventDefault();
main.hide();
}
}
});
app.on('window-all-closed', function() {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('before-quit', function() {
main.forceClose = true;
});
app.on('activate', function() {
main.show();
});
ipc.on('selectStorageDirectory', function() {
dialog.showOpenDialog({
properties: ['openDirectory']
}, function(path) {
if (path) {
ipc.send('storageDirectorySelected', path);
}
});
});
});
| JavaScript | 0.000001 | @@ -375,17 +375,17 @@
width: 6
-2
+0
0,%0A h
@@ -395,11 +395,11 @@
ht:
-720
+635
%0A %7D
|
8b3bb16c3afccedf5570a015f370d9299c917182 | create the otone_data folder incase it doesn't already exist | app/main.js | app/main.js | if (require('electron-squirrel-startup')) return;
const fs = require('fs')
const child_process = require('child_process')
const http = require('http')
const path = require('path')
const electron = require('electron')
const {app, BrowserWindow, powerSaveBlocker} = electron
const autobahn = require('autobahn')
const $ = jQuery = require('jquery')
const nightlife = require('nightlife-rabbit')
const winston = require('winston')
const addMenu = require('./menu').addMenu;
const initAutoUpdater = require('./update_helpers').initAutoUpdater;
let backendProcess = undefined
let powerSaverID = undefined
if (process.env.NODE_ENV == 'development'){
require('electron-debug')({showDevTools: true});
}
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow
function createWindow () {
mainWindow = new BrowserWindow({width: 1200, height: 900})
mainWindow.loadURL("file://" + __dirname + "/src/index.html")
mainWindow.on('closed', function () {
mainWindow = null
app.quit();
})
}
function startWampRouter() {
// winston seems to not create the file if it doesn't exist already
// to avoid this, .appendFileSync() will create the file incase it's not there
fs.appendFileSync(app.getPath('userData') + '/otone_data/router_logfile.txt', '');
var wamp_logger = new (winston.Logger)({
transports: [
new (winston.transports.File)({
level: 'verbose',
name: 'wamp-router',
filename: app.getPath('userData') + '/otone_data/router_logfile.txt',
json: false,
maxsize: 10*1024*1024,
maxFiles: 5,
timestamp: function(){
const d = new Date();
return d.toISOString();
}
})
]
});
var router = nightlife.createRouter({
httpServer: http.createServer(),
port: 31947,
path: '/ws',
autoCreateRealms: true,
logger: wamp_logger
});
}
/**
* Starts an executable in a separate process
* @param {param} filePath - path to an executable
* @param {Array} extraArgs - Array of arguments to pass during invocation of file
*/
function execFile(filePath, extraArgs) {
backendProcess = child_process.execFile(filePath, extraArgs, {stdio: 'ignore' }, function(error, stdout, stderr){
console.log(stdout);
console.log(stderr);
if (error) {
throw error;
}
});
var backendProcessName = path.basename(backendProcess.spawnfile)
console.log(
'Backend process successfully started with PID', backendProcess.pid,
'and using spawnfile', backendProcessName
)
backendProcess.shutdown = function (){
if (process.platform == "darwin") {
child_process.spawnSync('pkill', ['-9', backendProcessName]);
}
else if (process.platform == "win32") {
child_process.spawnSync('taskkill', ['/T', '/F', '/IM', backendProcessName]);
}
console.log('Backend process successfully shutdown')
}
}
/**
* Starts otone_client backend executable; kills existing process if any
*/
function startBackend() {
const userDataPath = app.getPath('userData');
console.log('User Data Path', userDataPath)
if (process.platform == "darwin") {
var backend_path = app.getAppPath() + "/backend-dist/mac/otone_client";
execFile(backend_path, [userDataPath]);
}
else if (process.platform == "win32") {
var backend_path = app.getAppPath() + "\\backend-dist\\win\\otone_client.exe";
execFile(backend_path, [userDataPath]);
}
else{
console.log('\n\n\n\nunknown OS: '+process.platform+'\n\n\n\n');
}
}
function blockPowerSaver() {
powerSaverID = powerSaveBlocker.start('prevent-display-sleep')
}
function createContainersFolder() {
try{
fs.mkdirSync(app.getUserContainersPath());
}
catch(e) {
//file already exists
}
}
app.getUserContainersPath = function(){
return path.join(app.getPath('userData'), 'containers');
}
app.getUserJSONFiles = function(){
var filenames = fs.readdirSync(app.getUserContainersPath());
return filenames.map(function(fileName){
return path.join(app.getUserContainersPath(), fileName);
});
}
app.on('ready', createWindow)
app.on('ready', startWampRouter)
app.on('ready', startBackend)
app.on('ready', addMenu)
app.on('ready', blockPowerSaver)
app.on('ready', initAutoUpdater)
app.on('ready', createContainersFolder)
app.on('window-all-closed', function () {
app.quit()
})
app.on('quit', function(){
process.once("uncaughtException", function (error) {
// Ugly but convenient. If we have more than one uncaught exception
// then re-raise. Otherwise Do nothing as that exception is caused by
// an attempt to shutdown the backend process
if (process.listeners("uncaughtException").length > 1) {
throw error;
}
});
backendProcess.shutdown();
if (powerSaveBlocker.isStarted(powerSaverID)) {
powerSaveBlocker.stop(powerSaverID);
}
});
| JavaScript | 0 | @@ -1301,16 +1301,144 @@
t there%0A
+%0A try %7B%0A fs.mkdirSync(app.getPath('userData') + '/otone_data');%0A %7D%0A catch(e) %7B%0A //file already exists%0A %7D%0A%0A
fs.a
|
ab6834a41a90a1983715bd4d8f550600ecca7417 | Remove dead code. | app/site.js | app/site.js | /**
* Module dependencies.
*/
var kerouac = require('kerouac')
, fs = require('fs')
, path = require('path');
var DASHED_REGEX = /^(\d+)-(\d+)-(\d+)-(.*)/;
exports = module.exports = function(
postHandler,
atomFeed, rssFeed, rdfFeed, jsonFeed,
postsDB) {
var dir, options;
if (typeof dir == 'object') {
options = dir;
dir = options.dir;
}
dir = dir || 'blog';
options = options || {};
var site = kerouac();
site.on('mount', function onmount(parent) {
// inherit settings
this.set('layout engine', parent.get('layout engine'));
this.locals.pretty = parent.locals.pretty;
});
site.page('/:year/:month/:day/:slug.html', postHandler);
// FIXME: pretty URL isn't catching this
//site.page('/index.html', require('./handlers/index')(options.layout));
// https://github.com/jshttp/mime-db
// https://help.github.com/articles/mime-types-on-github-pages/
site.page('/feed.atom', atomFeed);
site.page('/feed.rss', rssFeed);
site.page('/feed.rdf', rdfFeed);
site.page('/feed.json', jsonFeed);
// TODO: implement a news-specific sitemap:
// https://support.google.com/webmasters/answer/74288
// include it as a separate sitemap-news.xml
site.page('/sitemap.xml', require('kerouac-sitemap')());
site.bind(function(done) {
var self = this;
postsDB.list(function(err, posts) {
if (err) { return done(err); }
var el, i, len
, url, year, month, day, slug;
for (i = 0, len = posts.length; i < len; ++i) {
el = posts[i];
year = el.publishedAt.getUTCFullYear()
month = (el.publishedAt.getUTCMonth() + 1)
day = el.publishedAt.getUTCDate()
slug = el.slug;
month = (month < 10) ? ('0' + month) : month;
day = (day < 10) ? ('0' + day) : day;
url = '/' + [ year, month, day, slug + '.html' ].join('/');
self.add(url);
}
done();
});
return;
fs.readdir(dir, function(err, files) {
if (err && err.code == 'ENOENT') {
return done();
} else if (err) { return done(err); }
var idx = 0
, file, base, ext
, url;
(function iter(err) {
if (err) { return done(err); }
file = files[idx++];
if (!file) {
return done();
}
file = path.join(dir, file);
ext = path.extname(file);
base = path.basename(file, ext);
console.log('GOT FILE!');
console.log(file);
fs.stat(file, function(err, stats) {
if (err) { return iter(err); }
if (!stats.isFile()) { return iter(); }
var year = stats.birthtime.getUTCFullYear()
, month = (stats.birthtime.getUTCMonth() + 1)
, day = stats.birthtime.getUTCDate()
, slug = base;
month = (month < 10) ? ('0' + month) : month;
day = (day < 10) ? ('0' + day) : day;
var match;
if (match = DASHED_REGEX.exec(base)) {
year = match[1];
month = match[2];
day = match[3];
slug = match[4];
}
var url = '/' + [ year, month, day, slug + '.html' ].join('/');
self.add(url);
iter();
});
})();
});
});
return site;
}
exports['@implements'] = [
'http://i.kerouacjs.org/Site',
'http://i.kerouacjs.org/blog/Site'
];
exports['@require'] = [
'./handlers/post',
'./handlers/feed/atom',
'./handlers/feed/rss',
'./handlers/feed/rdf',
'./handlers/feed/json',
'http://i.kerouacjs.org/blog/PostsDatabase'
];
| JavaScript | 0.00001 | @@ -1993,1428 +1993,8 @@
%7D);%0A
- %0A return;%0A %0A %0A fs.readdir(dir, function(err, files) %7B%0A if (err && err.code == 'ENOENT') %7B%0A return done();%0A %7D else if (err) %7B return done(err); %7D%0A %0A var idx = 0%0A , file, base, ext%0A , url;%0A %0A (function iter(err) %7B%0A if (err) %7B return done(err); %7D%0A %0A file = files%5Bidx++%5D;%0A if (!file) %7B%0A return done();%0A %7D%0A %0A file = path.join(dir, file);%0A ext = path.extname(file);%0A base = path.basename(file, ext);%0A %0A console.log('GOT FILE!');%0A console.log(file);%0A %0A fs.stat(file, function(err, stats) %7B%0A if (err) %7B return iter(err); %7D%0A if (!stats.isFile()) %7B return iter(); %7D%0A %0A var year = stats.birthtime.getUTCFullYear()%0A , month = (stats.birthtime.getUTCMonth() + 1)%0A , day = stats.birthtime.getUTCDate()%0A , slug = base;%0A month = (month %3C 10) ? ('0' + month) : month;%0A day = (day %3C 10) ? ('0' + day) : day;%0A %0A var match;%0A if (match = DASHED_REGEX.exec(base)) %7B%0A year = match%5B1%5D;%0A month = match%5B2%5D;%0A day = match%5B3%5D;%0A slug = match%5B4%5D;%0A %7D%0A %0A var url = '/' + %5B year, month, day, slug + '.html' %5D.join('/');%0A self.add(url);%0A iter();%0A %7D);%0A %7D)();%0A %7D);%0A
%7D)
|
118a051aa1573af86b83fcb5f465cbfca1c1c093 | update tests | app/test.js | app/test.js | 'use strict';
/* eslint max-nested-callbacks:[2,5] */
const path = require('path'),
test = require('yeoman-test'),
assert = require('yeoman-assert'),
folder = path.join('components', 'foo'),
tpl = 'template.nunjucks',
all = 'all.css',
print = 'print.css',
schema = 'schema.yml',
bootstrap = 'bootstrap.yml';
/**
* run the generator with various options
* note: options and prompts are interchangeable because of `yeoman-option-or-prompt`
* @param {object} options (could be empty)
* @param {Function} done async callback
*/
function run(options, done) {
test.run(path.join(__dirname, 'index.js'))
.withArguments(['foo'])
.withOptions(options)
.on('end', done);
}
describe('clay-component', function () {
describe('always', function () {
before(function (done) {
run({}, done);
});
it('creates component folder', function () {
assert.file(folder);
});
it('adds all.css', function () {
const file = path.join(folder, all);
assert.file(file);
assert.fileContent(file, '.foo {');
});
it('adds print.css', function () {
const file = path.join(folder, print);
assert.file(file);
assert.fileContent(file, '.foo {');
});
it('adds template.nunjucks', function () {
const file = path.join(folder, tpl);
assert.file(file);
assert.fileContent(file, 'class="foo"');
});
it('adds schema.yml', function () {
assert.file(path.join(folder, schema));
// schema gets a description, but no name passed in
});
it('adds bootstrap.yml', function () {
const file = path.join(folder, bootstrap);
assert.file(file);
assert.fileContent(file, 'foo:');
});
});
describe('with element', function () {
before(function (done) {
run({tag: 'aside'}, done);
});
it('sets tag', function () {
assert.fileContent(path.join(folder, tpl), /^<aside/);
});
});
describe('with comment', function () {
before(function (done) {
run({tag: 'comment'}, done);
});
it('sets tag', function () {
assert.fileContent(path.join(folder, tpl), '<!-- data-uri="{{ _ref or _self }}" -->');
});
});
describe('with description', function () {
before(function (done) {
run({desc: 'cool'}, done);
});
it('sets description', function () {
assert.fileContent(path.join(folder, schema), 'cool');
});
});
describe('with client', function () {
before(function (done) {
run({client: true}, done);
});
it('creates client js', function () {
let file = path.join(folder, 'client.js');
assert.file(file);
assert.fileContent(file, 'DS.controller(\'foo\',');
});
});
describe('with server', function () {
before(function (done) {
run({server: true}, done);
});
it('creates server js', function () {
assert.file(path.join(folder, 'server.js'));
});
it('creates server test js', function () {
assert.file(path.join(folder, 'server.test.js'));
});
});
});
| JavaScript | 0.000001 | @@ -227,42 +227,26 @@
,%0A
-all = 'all.css',%0A print = 'print.
+styles = 'styles.s
css'
@@ -916,12 +916,16 @@
dds
-all.
+styles.s
css'
@@ -977,19 +977,22 @@
folder,
-all
+styles
);%0A%0A
@@ -1085,11 +1085,14 @@
rint
-.cs
+ style
s',
@@ -1142,21 +1142,22 @@
folder,
-print
+styles
);%0A%0A
@@ -1201,36 +1201,44 @@
eContent(file, '
-.foo
+@media print
%7B');%0A %7D);%0A%0A
|
533833d77577306c8250410dba1ef3332cc4c1e6 | Add master to admins when added to group | handlers/middlewares/addedToGroup.js | handlers/middlewares/addedToGroup.js | 'use strict';
// Bot
const bot = require('../../bot');
const { replyOptions } = require('../../bot/options');
const { addGroup, managesGroup } = require('../../stores/group');
const { masterID } = require('../../config.json');
const addedToGroupHandler = async (ctx, next) => {
const msg = ctx.message;
const wasAdded = msg.new_chat_members.some(user =>
user.username === ctx.me);
if (wasAdded && ctx.from.id === masterID) {
if (!await managesGroup(ctx.chat)) {
const link = await bot.telegram.exportChatInviteLink(ctx.chat.id);
ctx.chat.link = link ? link : '';
await addGroup(ctx.chat);
}
ctx.reply('🛠 <b>Ok, I\'ll help you manage this group from now.</b>',
replyOptions);
}
return next();
};
module.exports = addedToGroupHandler;
| JavaScript | 0 | @@ -101,24 +101,72 @@
options');%0A%0A
+const %7B admin %7D = require('../../stores/user');%0A
const %7B addG
@@ -475,16 +475,35 @@
erID) %7B%0A
+%09%09admin(ctx.from);%0A
%09%09if (!a
|
442068ba85a93ff8cf79dc645bc35993d0c50c2b | switch to vercel and netlify path | public/former/js/script.js | public/former/js/script.js | $(document).ready(function () {
// initialize tab
$('#tabs').tabs();
/** binding */
// select url when focus on #url [text input]
$('#url').bind('click', function () {
this.select();
});
// select lyric all
$('#select').bind('click', function (e) {
$('#lyric_div > textarea').focus();
$('#lyric_div > textarea').select();
});
// copy lyric
if (window.clipboardData) {
$('#copy').bind('click', function (e) {
var text = $('#lyric_div > textarea').val();
window.clipboardData.clearData();
window.clipboardData.setData('Text', text);
window.alert('Lyric has copied to Clipboard.');
});
} else {
$('#copy').attr('disabled', 'disabled');
}
// binding examples URL
$('#examples a').click(function (e) {
e.preventDefault();
var url = e.target.href;
$('#url').val(url);
$('#btn_submit').submit();
});
// submit url to get episode list
$('#query_form').bind('submit', function (e) {
// no form submit action
e.preventDefault();
var url = jQuery.trim($('#url').val());
// check input
if (url == '' || url == $('#url').attr('title')) {
return false;
}
// show waiting dialog
$('#btn_submit').attr('disabled', 'disabled');
$('#lyric_div').hide();
$('#lyric_div > textarea').empty();
$('#loading_div').html('Loading...');
$('#loading_div').show();
// JSON query
$.getJSON('/app', { url: url }, function (data) {
var lyric = data['lyric'];
if (!lyric) {
// failed to get lyric
$('#loading_div').html(
'<span style="color: red;">Failed to get lyric. Please contact franklai.</span>'
);
$('#btn_submit').removeAttr('disabled');
return;
}
var count = lyric.split('\n');
//alert(tmp.length);
//lyric = tmp.join("<br/>");
//$("#lyric_div > div").html(lyric);
$('#lyric_div > textarea').val(lyric);
$('#lyric_div > textarea').css('height', 14 * count.length + 'pt');
$('#loading_div').hide();
$('#lyric_div').show();
$('#btn_submit').removeAttr('disabled');
});
});
$('#loading_div').ajaxError(function (event, request, settings) {
$(this).html('<span style="color: red;">Error.</span>');
$('#btn_submit').removeAttr('disabled');
});
});
| JavaScript | 0 | @@ -1389,24 +1389,303 @@
').show();%0A%0A
+ var appPath = '/app';%0A var host = window.location.hostname.toLowerCase();%0A if (host.endsWith('.vercel.app')) %7B%0A appPath = 'api/lyric/get/' + encodeURIComponent(url);%0A %7D%0A if (host.endsWith('.netlify.app')) %7B%0A appPath = '.netlify/functions/lyric';%0A %7D%0A%0A
// JSON
@@ -1704,22 +1704,23 @@
getJSON(
-'/
app
-'
+Path
, %7B url:
|
4403c1c0371aac63c0e79731f70c3faa8aa22f92 | Decrease timeout of retry | config/configuration.js | config/configuration.js | 'use strict';
/**
* @file Defines the provider settings.
*
* Will set the path to Mongo, and applications id
* Most of the configuration can be done using system environment variables.
*/
// Load environment variables from .env file
var dotenv = require('dotenv');
dotenv.load();
// node_env can either be "development" or "production"
var node_env = process.env.NODE_ENV || "development";
var default_port = 8000;
if(node_env === "production") {
default_port = 80;
}
var mandatories = ['GMAIL_API_ID', 'GMAIL_API_SECRET', 'ANYFETCH_API_ID', 'ANYFETCH_API_SECRET'];
mandatories.forEach(function(mandatory) {
if(!process.env[mandatory]) {
console.log(mandatory + " missing, the provider may fail.");
}
});
// Exports configuration
module.exports = {
env: node_env,
port: process.env.PORT || default_port,
maxSize: process.env.MAX_SIZE || 50,
mongoUrl: process.env.MONGO_URL || process.env.MONGOLAB_URI,
redisUrl: process.env.REDIS_URL || process.env.REDISCLOUD_URL,
usersConcurrency: process.env.GMAIL_USERS_CONCURRENCY || 1,
concurrency: process.env.GMAIL_CONCURRENCY || 10,
googleId: process.env.GMAIL_API_ID,
googleSecret: process.env.GMAIL_API_SECRET,
appId: process.env.ANYFETCH_API_ID,
appSecret: process.env.ANYFETCH_API_SECRET,
appName: process.env.APP_NAME,
providerUrl: process.env.PROVIDER_URL,
testRefreshToken: process.env.GMAIL_TEST_REFRESH_TOKEN,
testAccount: process.env.GMAIL_TEST_ACCOUNT_NAME,
imapTimeout: process.env.IMAP_TIMEOUT || 20000,
retry: 2,
retryDelay: 20 * 1000,
opbeat: {
organizationId: process.env.OPBEAT_ORGANIZATION_ID,
appId: process.env.OPBEAT_APP_ID,
secretToken: process.env.OPBEAT_SECRET_TOKEN
}
};
| JavaScript | 0.000018 | @@ -1538,18 +1538,17 @@
yDelay:
-20
+4
* 1000,
|
8e1c8c4be843f18f30a1b3bbb1b10a03cd37c759 | Add config.appName | config/configuration.js | config/configuration.js | /**
* @file Defines the provider settings.
*
* Will set the path to Mongo, and applications id
* Most of the configuration can be done using system environment variables.
*/
// Load environment variables from .env file
var dotenv = require('dotenv');
dotenv.load();
// node_env can either be "development" or "production"
var node_env = process.env.NODE_ENV || "development";
// Port to run the app on. 8000 for development
// (Vagrant syncs this port)
// 80 for production
var default_port = 8000;
if(node_env === "production") {
default_port = 80;
}
var defaultEvernoteRoot = (node_env === 'development' || node_env === 'test') ? 'https://sandbox.evernote.com' : 'https://www.evernote.com';
var config = {
env: node_env,
port: process.env.PORT || default_port,
workers: process.env.WORKERS || 1, // Number of workers for upload tasks
evernoteKey: process.env.EVERNOTE_API_ID,
evernoteSecret: process.env.EVERNOTE_API_SECRET,
evernoteRoot: process.env.EVERNOTE_DOMAINROOT || defaultEvernoteRoot,
usersConcurrency: process.env.EVERNOTE_USERS_CONCURRENCY || 1,
concurrency: process.env.EVERNOTE_CONCURRENCY || 1,
appId: process.env.ANYFETCH_API_ID,
appSecret: process.env.ANYFETCH_API_SECRET,
providerUrl: process.env.PROVIDER_URL,
testToken: process.env.EVERNOTE_TEST_TOKEN || (process.env.EVERNOTE_TEST_TOKEN_PART1 + process.env.EVERNOTE_TEST_TOKEN_PART2),
retry: 2,
retryDelay: 20 * 1000,
opbeat: {
organizationId: process.env.OPBEAT_ORGANIZATION_ID,
appId: process.env.OPBEAT_APP_ID,
secretToken: process.env.OPBEAT_SECRET_TOKEN
}
};
config.clientConfig = {
consumerKey: config.evernoteKey,
consumerSecret: config.evernoteSecret,
sandbox: (config.env === "development" || config.env === "test")
};
// Exports configuration for use by app.js
module.exports = config;
| JavaScript | 0.000009 | @@ -1221,16 +1221,49 @@
ECRET,%0A%0A
+ appName: process.env.APP_NAME,%0A
provid
|
9501e6d5f050bdb3ad7a80a625d13c30fc4cf51b | Allow htmltemplate option for photon (#151) | src/geocoders/photon.js | src/geocoders/photon.js | var L = require('leaflet'),
Util = require('../util');
module.exports = {
class: L.Class.extend({
options: {
serviceUrl: 'https://photon.komoot.de/api/',
reverseUrl: 'https://photon.komoot.de/reverse/',
nameProperties: [
'name',
'street',
'suburb',
'hamlet',
'town',
'city',
'state',
'country'
]
},
initialize: function(options) {
L.setOptions(this, options);
},
geocode: function(query, cb, context) {
var params = L.extend({
q: query,
}, this.options.geocodingQueryParams);
Util.getJSON(this.options.serviceUrl, params, L.bind(function(data) {
cb.call(context, this._decodeFeatures(data));
}, this));
},
suggest: function(query, cb, context) {
return this.geocode(query, cb, context);
},
reverse: function(latLng, scale, cb, context) {
var params = L.extend({
lat: latLng.lat,
lon: latLng.lng
}, this.options.geocodingQueryParams);
Util.getJSON(this.options.reverseUrl, params, L.bind(function(data) {
cb.call(context, this._decodeFeatures(data));
}, this));
},
_decodeFeatures: function(data) {
var results = [],
i,
f,
c,
latLng,
extent,
bbox;
if (data && data.features) {
for (i = 0; i < data.features.length; i++) {
f = data.features[i];
c = f.geometry.coordinates;
latLng = L.latLng(c[1], c[0]);
extent = f.properties.extent;
if (extent) {
bbox = L.latLngBounds([extent[1], extent[0]], [extent[3], extent[2]]);
} else {
bbox = L.latLngBounds(latLng, latLng);
}
results.push({
name: this._deocodeFeatureName(f),
center: latLng,
bbox: bbox,
properties: f.properties
});
}
}
return results;
},
_deocodeFeatureName: function(f) {
var j,
name;
for (j = 0; !name && j < this.options.nameProperties.length; j++) {
name = f.properties[this.options.nameProperties[j]];
}
return name;
}
}),
factory: function(options) {
return new L.Control.Geocoder.Photon(options);
}
};
| JavaScript | 0 | @@ -1631,16 +1631,112 @@
ame(f),%0A
+%09%09%09%09%09%09html: this.options.htmlTemplate ?%0A%09%09%09%09%09%09%09this.options.htmlTemplate(f)%0A%09%09%09%09%09%09%09: undefined,%0A
%09%09%09%09%09%09ce
|
ec34ddc5fb99d80bdb07a33a09450e7c9e0f022d | Reformat code | src/geometry/Polygon.js | src/geometry/Polygon.js | U.Polygon = U.Collection.extend({
init:function (outRing, innerRings) {
this.outRing = outRing;
this.innerRings = innerRings;
// add it to the geometries collection for maintain.
if(this.outRing){
this.addGeometry(this.outRing,0);
}
if(this.innerRings){
this.addGeometries(this.innerRings);
}
},
getArea: function() {
var area = 0.0;
if ( this.geometries && (this.geometries.length > 0)) {
area += Math.abs(this.geometries[0].getArea());
for (var i=1, len=this.geometries.length; i<len; i++) {
area -= Math.abs(this.geometries[i].getArea());
}
}
return area;
},
containsPoint: function(point) {
var numRings = this.geometries.length;
var contained = false;
if(numRings > 0) {
// check exterior ring - 1 means on edge, boolean otherwise
contained = this.geometries[0].containsPoint(point);
if(contained !== 1) {
if(contained && numRings > 1) {
// check interior rings
var hole;
for(var i=1; i<numRings; ++i) {
hole = this.geometries[i].containsPoint(point);
if(hole) {
if(hole === 1) {
// on edge
contained = 1;
} else {
// in hole
contained = false;
}
break;
}
}
}
}
}
return contained;
},
intersects: function(geometry) {
var intersect = false;
var i, len;
if(geometry instanceof U.Point) {
intersect = this.containsPoint(geometry);
} else if(geometry instanceof U.Line || geometry instanceof U.Ring) {
// check if rings/Line intersect
for(i=0, len=this.geometries.length; i<len; ++i) {
intersect = geometry.intersects(this.geometries[i]);
if(intersect) {
break;
}
}
if(!intersect) {
// check if this poly contains points of the ring/linestring
for(i=0, len=geometry.geometries.length; i<len; ++i) {
intersect = this.containsPoint(geometry.geometries[i]);
if(intersect) {
break;
}
}
}
} else {
for(i=0, len=geometry.geometries.length; i<len; ++ i) {
intersect = this.intersects(geometry.geometries[i]);
if(intersect) {
break;
}
}
}
// check case where this poly is wholly contained by another
if(!intersect && geometry instanceof U.Polygon) {
// exterior ring points will be contained in the other geometry
var ring = this.geometries[0];
for(i=0, len=ring.geometries.length; i<len; ++i) {
intersect = geometry.containsPoint(ring.geometries[i]);
if(intersect) {
break;
}
}
}
return intersect;
}
})
U.Polygon.createRegularPolygon = function(origin, radius, sides, rotation) {
var angle = Math.PI * ((1/sides) - (1/2));
if(rotation) {
angle += (rotation / 180) * Math.PI;
}
var rotatedAngle, x, y;
var points = [];
for(var i=0; i<sides; ++i) {
rotatedAngle = angle + (i * 2 * Math.PI / sides);
x = origin.x + (radius * Math.cos(rotatedAngle));
y = origin.y + (radius * Math.sin(rotatedAngle));
points.push(new U.Point(x, y));
}
var ring = new U.Line(points);
return new U.Polygon([ring]);
}; | JavaScript | 0 | @@ -3992,24 +3992,25 @@
ne(points);%0A
+%0A
return n
|
089acd688aa2332386d3240f4c89f2da653a21ab | Fix remaining specs | lib/directory-view.js | lib/directory-view.js | const {CompositeDisposable} = require('atom')
const getIconServices = require('./get-icon-services')
const Directory = require('./directory')
const FileView = require('./file-view')
module.exports =
class DirectoryView {
constructor(directory) {
this.directory = directory
this.subscriptions = new CompositeDisposable()
this.subscriptions.add(this.directory.onDidDestroy(() => this.subscriptions.dispose()))
this.subscribeToDirectory()
this.element = document.createElement('li')
this.element.setAttribute('is', 'tree-view-directory')
this.element.classList.add('directory', 'entry', 'list-nested-item', 'collapsed')
this.header = document.createElement('div')
this.header.classList.add('header', 'list-item')
this.directoryName = document.createElement('span')
this.directoryName.classList.add('name', 'icon')
this.entries = document.createElement('ol')
this.entries.classList.add('entries', 'list-tree')
this.updateIcon()
this.subscriptions.add(getIconServices().onDidChange(() => this.updateIcon()))
this.directoryName.dataset.path = this.directory.path
if (this.directory.squashedNames != null) {
this.directoryName.dataset.name = this.directory.squashedNames.join('')
this.directoryName.title = this.directory.squashedNames.join('')
const squashedDirectoryNameNode = document.createElement('span')
squashedDirectoryNameNode.classList.add('squashed-dir')
squashedDirectoryNameNode.textContent = this.directory.squashedNames[0]
this.directoryName.appendChild(squashedDirectoryNameNode)
this.directoryName.appendChild(document.createTextNode(this.directory.squashedNames[1]))
} else {
this.directoryName.dataset.name = this.directory.name
this.directoryName.title = this.directory.name
this.directoryName.textContent = this.directory.name
}
this.element.appendChild(this.header)
this.header.appendChild(this.directoryName)
this.element.appendChild(this.entries)
if (this.directory.isRoot) {
this.element.classList.add('project-root')
this.header.classList.add('project-root-header')
} else {
this.element.draggable = true
}
this.subscriptions.add(this.directory.onDidStatusChange(() => this.updateStatus()))
this.updateStatus()
if (this.directory.expansionState.isExpanded) {
this.expand()
}
this.element.collapse = this.collapse.bind(this)
this.element.expand = this.expand.bind(this)
this.element.toggleExpansion = this.toggleExpansion.bind(this)
this.element.reload = this.reload.bind(this)
this.element.isExpanded = this.isExpanded
this.element.updateStatus = this.updateStatus.bind(this)
this.element.isPathEqual = this.isPathEqual.bind(this)
this.element.getPath = this.getPath.bind(this)
this.element.directory = this.directory
this.element.header = this.header
this.element.entries = this.entries
this.element.directoryName = this.directoryName
}
updateIcon() {
getIconServices().updateDirectoryIcon(this)
}
updateStatus() {
this.element.classList.remove('status-ignored', 'status-ignored-name', 'status-modified', 'status-added')
if (this.directory.status != null) {
this.element.classList.add(`status-${this.directory.status}`)
}
}
subscribeToDirectory() {
this.subscriptions.add(this.directory.onDidAddEntries(addedEntries => {
if (!this.isExpanded) return
const numberOfEntries = this.entries.children.length
for (let entry of addedEntries) {
const view = this.createViewForEntry(entry)
const insertionIndex = entry.indexInParentDirectory
if (insertionIndex < numberOfEntries) {
this.entries.insertBefore(view.element, this.entries.children[insertionIndex])
} else {
this.entries.appendChild(view.element)
}
}
}))
}
getPath() {
return this.directory.path
}
isPathEqual(pathToCompare) {
return this.directory.isPathEqual(pathToCompare)
}
createViewForEntry(entry) {
const view = entry instanceof Directory ? new DirectoryView(entry) : new FileView(entry)
<<<<<<< HEAD
const subscription = this.directory.onDidRemoveEntries(removedEntries => {
=======
this.subscriptions.add(this.directory.onDidRemoveEntries(removedEntries => {
>>>>>>> Start to fix specs
if (removedEntries.has(entry)) {
view.element.remove()
subscription.dispose()
}
<<<<<<< HEAD
})
this.subscriptions.add(subscription)
=======
}))
>>>>>>> Start to fix specs
return view
}
reload() {
if (this.isExpanded) {
this.directory.reload()
}
}
toggleExpansion(isRecursive) {
if (isRecursive == null) {
isRecursive = false
}
if (this.isExpanded) {
this.collapse(isRecursive)
} else {
this.expand(isRecursive)
}
}
expand(isRecursive) {
if (isRecursive == null) {
isRecursive = false
}
if (!this.isExpanded) {
this.isExpanded = true
this.element.isExpanded = this.isExpanded
this.element.classList.add('expanded')
this.element.classList.remove('collapsed')
this.directory.expand()
}
if (isRecursive) {
for (let entry of this.entries.children) {
if (entry.classList.contains('directory')) {
entry.expand(true)
}
}
}
}
collapse(isRecursive) {
if (isRecursive == null) isRecursive = false
this.isExpanded = false
this.element.isExpanded = false
if (isRecursive) {
for (let entry of this.entries.children) {
if (entry.isExpanded) {
entry.collapse(true)
}
}
}
this.element.classList.remove('expanded')
this.element.classList.add('collapsed')
this.directory.collapse()
this.entries.innerHTML = ''
}
}
| JavaScript | 0.000001 | @@ -4186,16 +4186,29 @@
entry)%0A%0A
+%3C%3C%3C%3C%3C%3C%3C HEAD%0A
%3C%3C%3C%3C%3C%3C%3C
@@ -4407,16 +4407,131 @@
x specs%0A
+=======%0A const subscription = this.directory.onDidRemoveEntries(removedEntries =%3E %7B%0A%3E%3E%3E%3E%3E%3E%3E Fix remaining specs%0A
if
@@ -4639,24 +4639,37 @@
%3C%3C%3C%3C%3C%3C HEAD%0A
+%3C%3C%3C%3C%3C%3C%3C HEAD%0A
%7D)%0A%0A
@@ -4721,16 +4721,16 @@
%7D))%0A
-
%3E%3E%3E%3E%3E%3E%3E
@@ -4747,16 +4747,101 @@
ix specs
+%0A=======%0A %7D)%0A%0A this.subscriptions.add(subscription)%0A%3E%3E%3E%3E%3E%3E%3E Fix remaining specs
%0A%0A re
|
a0bb86b3c40b93523253aa422bd37275ca100ae9 | Update dashboard-controller.js | www/dashboard/dashboard-controller.js | www/dashboard/dashboard-controller.js | 'use strict';
angular.module('MyApp.controllers')
.value('BASE_URL', 'https://noticeapp.firebaseio.com/')
.controller('DashboardCtrl', function($firebase, $scope, Auth, md5, $ionicModal, User, $http) {
var noticeRef = new Firebase('https://trynotice.firebaseio.com/notifications');
$scope.notifications = $firebase(noticeRef);
$scope.email = Auth.currentUser.email;
$scope.message = '';
$scope.activityName = '';
$scope.isStudent = /([\._a-zA-Z0-9-]+@students.d211.org)/.test($scope.email);
$scope.dataLoaded = false;
$scope.dataLoad = function() {
$http.get(User.getSubscriptions())
.success(function(data) {
if(data == null) {
$scope.subscriptions = [{ id: 1, name: 'Math Team', color: '#43cee6', isChecked: false },
{ id: 2, name: 'Basketball', color: '#4a87ee', isChecked: false },
{ id: 3, name: 'Horticulture Club', color: '#ef4e3a', isChecked: false },
{ id: 4, name: 'Science Olympiad', color: '#8a6de9', isChecked: false }];
}
else {
$scope.subscriptions = data;
}
$scope.dataLoaded = true
filterSubscriptions();
});
}
$scope.gravatarURL = 'http://www.gravatar.com/avatar/' + md5.createHash($scope.email);
$scope.manage = function() {
User.manageSubscriptions($scope.subscriptions);
};
$scope.postNotification = function(message, tag, color) {
$scope.notifications.$add({message: message, createdBy: $scope.email, gravatarURL: $scope.gravatarURL, dateCreated: Date.now(), tag: tag, color: color});
$scope.message = null;
};
$scope.getGravatar = function(md5) {
return 'http://www.gravatar.com/avatar/' + notifications.md5;
};
$ionicModal.fromTemplateUrl('templates/modal.html', {
scope: $scope
}).then(function(modal) {
$scope.modal = modal;
});
$scope.filterSubscriptions = function(index) {
console.log(index);
console.log("subs: " + $scope.subscriptions)
console.log("notifs: " + $scope.notifications)
if ($scope.dataLoaded) {
if($scope.subscriptions[index].tagName == $scope.notifications[index].tag) {
return true;
}
else {
return false;
}
}
else {
dataLoad();
}
};
})
.filter('reverse', function() {
function toArray(list) {
var k, out = [];
if( list ) {
if( angular.isArray(list) ) {
out = list;
}
else if( typeof(list) === 'object' ) {
for (k in list) {
if (list.hasOwnProperty(k)) { out.push(list[k]); }
}
}
}
return out;
}
return function(items) {
return toArray(items).slice().reverse();
};
});
| JavaScript | 0.000001 | @@ -2444,16 +2444,23 @@
+$scope.
dataLoad
|
79dcb4083ee3520bdfd4de08dd1d1cdaeb06497c | Update dashboard-controller.js | www/dashboard/dashboard-controller.js | www/dashboard/dashboard-controller.js | 'use strict';
angular.module('MyApp.controllers')
.value('BASE_URL', 'https://noticeapp.firebaseio.com/')
.controller('DashboardCtrl', function($firebase, $scope, Auth, md5) {
var noticeRef = new Firebase('https://noticeapp.firebaseio.com/notifications');
$scope.notifications = $firebase(noticeRef);
$scope.email = Auth.currentUser.email;
$scope.message = '';
$scope.activityName = '""''';
$scope.clubs = [
{ id: 1, name: 'Math Team', color: '#43cee6' },
{ id: 2, name: 'Basketball', color: '#4a87ee' },
{ id: 3, name: 'Horticulture Club', color: '#ef4e3a' },
{ id: 4, name: 'Science Olympiad', color: '#8a6de9'}];
$scope.gravatarURL = 'http://www.gravatar.com/avatar/' + md5.createHash($scope.email);
$scope.postNotification = function(message, tag, color) {
console.log($scope.message);
$scope.notifications.$add({message: message, createdBy: $scope.email, gravatarURL: $scope.gravatarURL, dateCreated: Date.now(), tag: tag, color: color});
$scope.message = null;
};
$scope.getGravatar = function(md5) {
return 'http://www.gravatar.com/avatar/' + notifications.md5;
};
})
.filter('reverse', function() {
function toArray(list) {
var k, out = [];
if( list ) {
if( angular.isArray(list) ) {
out = list;
}
else if( typeof(list) === 'object' ) {
for (k in list) {
if (list.hasOwnProperty(k)) { out.push(list[k]); }
}
}
}
return out;
}
return function(items) {
return toArray(items).slice().reverse();
};
});
| JavaScript | 0.000001 | @@ -404,12 +404,8 @@
e =
-'%22%22'
'';%0A
|
9b75c8804f946d4ad476dadb42cd85942c4ec9f5 | Fix scroll bug in tabs.js | public/javascripts/tabs.js | public/javascripts/tabs.js | TAB_HEADINGS = 'h2';
TAB_CLASS = 'tab';
SECTION_CLASS = 'section';
QUERY_SECTION_ARG = 'section';
TAB_SELECTED_CLASS = 'selected';
TAB_NOT_SELECTED_CLASS = 'not-selected';
LOADING_ELM_ID = 'loading';
CONTENT_HOLDER_ID = 'content-holder';
lastSection = -1
function checkHash() {
var section = get_selected();
if(section != lastSection) {
show_section(section);
lastSection = section;
}
}
function get_elements() {
var divs = document.getElementsByTagName("div");
var htags = document.getElementsByTagName(TAB_HEADINGS);
sections = [];
tabs = [];
headings = []
for(var i=0; i<divs.length; i++) {
if(divs[i].className == SECTION_CLASS) sections.push(divs[i]);
}
for(var i=0; i<htags.length; i++) {
if(htags[i].className == TAB_CLASS) {
var span = document.createElement("span");
span.innerHTML = htags[i].innerHTML;
tabs.push(span);
headings.push(htags[i]);
}
}
};
function combine_tabs(){
if(headings.length == 0)return;
headings[0].innerHTML = '';
for(var i=0; i<tabs.length; i++) {
headings[0].appendChild(tabs[i]);
if(i > 0) headings[i].parentNode.removeChild(headings[i]);
}
// hack to fix tab alignment
var div = document.createElement('div');
div.style.fontSize = '1pt';
div.style.lineHeight = '1pt';
div.style.margin = '0';
div.innerHTML = ' '
headings[0].parentNode.insertBefore(div, headings[0]);
};
function hide_all(){
for(var i=0; i<sections.length; i++) {
sections[i].style.display = "none";
}
for(var i=0; i<tabs.length; i++) {
tabs[i].className = TAB_NOT_SELECTED_CLASS
}
};
function show_section(index){
hide_all()
if(sections.length == 0) return;
var section = sections[index];
if(!section) var section = sections[index=0];
section.style.display = "block";
tabs[index].className = TAB_SELECTED_CLASS;
var id = headings[index].getAttribute('id') || sections[index].getAttribute('id');
if(id && index != lastSection) {
var y = typeof window.pageYOffset != 'undefined' ? window.pageYOffset : document.documentElement.scrollTop;
if(!navigator.userAgent.match(/Safari/) && (location.hash == null || lastSection != -1)) location.hash = '#' + id;
window.scrollTo(0, y);
if(typeof load_tab == 'function') load_tab(id);
}
lastSection = index;
};
function tab_click(e){
var target = e && e.target || event.srcElement;
for(var i=0; i<tabs.length; i++) {
if(target == tabs[i] || target.parentNode == tabs[i]){
show_section(i);
}
}
};
function set_handlers(){
for(var i=0; i<tabs.length; i++) {
tabs[i].onclick = tab_click;
}
};
function get_selected(){
var selected = 0;
if(location.hash) {
selected = location.hash.substring(1);
} else if(location.search) {
var args = location.search.substring(1).split('&');
for(var i=0; i<args.length; i++) {
var name = args[i].split('=')[0];
var value = args[i].split('=')[1];
if(name == QUERY_SECTION_ARG){
selected = value;
break;
}
}
}
if(isNaN(selected)){
for(var i=0; i<sections.length; i++){
if(sections[i].getAttribute('id') == selected || headings[i].getAttribute('id') == selected){
selected = i;
break;
}
}
}
return selected;
};
function set_up() {
get_elements();
combine_tabs();
var loadingElm = document.getElementById(LOADING_ELM_ID);
if(loadingElm){
loadingElm.style.display = "none";
}
var contentHolderElm = document.getElementById(CONTENT_HOLDER_ID);
if(contentHolderElm) {
contentHolderElm.style.display = "block";
}
var selected = get_selected();
show_section(selected);
set_handlers();
if(!navigator.userAgent.match(/Safari/)) setInterval(checkHash, 100);
}; | JavaScript | 0.000001 | @@ -1229,24 +1229,110 @@
adings%5Bi%5D);%0A
+ headings%5Bi%5D.setAttribute('origId', headings%5Bi%5D.id)%0A headings%5Bi%5D.id = null;%0A
%7D%0A //
@@ -2098,25 +2098,29 @@
tAttribute('
-i
+origI
d') %7C%7C secti
@@ -2189,24 +2189,26 @@
on) %7B%0A
+//
var y = type
@@ -2430,16 +2430,18 @@
;%0A
+//
window.s
@@ -3472,33 +3472,37 @@
%5D.getAttribute('
-i
+origI
d') == selected)
|
26b9b6d75edb0c974339ae1aa9396804268b5c5f | Update forum.js | developer/forum.js | developer/forum.js | //todo write angular scripts for developer page.
var developerKingdomModule = angular.module('app', []).
controller("forumCtrl", function forumCtrl($scope, $window, $http){
$scope.forum = {
threads: [{subject: "blah blah blah", posts: [{user: "user1", time: (new Date()).toLocaleString(), message: "hi how u doing"}, {user: "user2", time: (new Date()).toLocaleString(), message: "lol wassup"}]},
{subject: "how to add your own functions", posts: [{user: "user1", time: (new Date()).toLocaleString(), message: "asdfasdf"}, {user: "user2", time: (new Date()).toLocaleString(), message: "j jajajajajajh"}]}]
};
$scope.fetch = function(){
var additionalPosts = [];
$http({method: "GET", url: "http://localhost:3000/posts"})
.success(function(data, status){
additionalPosts = data;
console.log(additionalPosts);
for(var i = 0; i < additionalPosts.length; i++){
$scope.forum.threads[0].posts.push(additionalPosts[i]);
}
})
.error(function(data, status){
additionalPosts = data || "Request failed";
console.log(additionalPosts);
});
};
$scope.fetch();
$scope.currentThread = {};
$scope.currentThreadOn = false;
$scope.setThread = function(thread){
$scope.currentThread = thread;
$scope.currentThreadOn = true;
}
$scope.backToForum = function(){
$scope.currentThreadOn = false;
}
$scope.addPost = function(thread){
if($scope.currentUser == "" || $scope.currentUser == null){
$scope.currentUser = "Guest";
}
var postObject = {user: $scope.currentUser, message: $scope.newPost, time: (new Date()).toLocaleString()};
$scope.currentThread.posts.push(postObject);
var stringifiedPost = JSON.stringify(postObject);
$http({method: "POST", url: "http://localhost:3000/posts", data: stringifiedPost})
$scope.newPost = "";
}
$scope.addThread = function(){
if($scope.currentUser == "" || $scope.currentUser == null){
$scope.currentUser = "Guest";
}
$scope.forum.threads.push({
subject: $scope.newSubject,
posts: [{user: $scope.currentUser, message: $scope.newPost, time: (new Date()).toLocaleString()}]
});
$scope.newSubject = "";
$scope.newPost = "";
}
$scope.currentUser = "";
$scope.newPost = "";
$scope.newSubject = "";
$scope.predicate = '';
});
| JavaScript | 0 | @@ -244,382 +244,73 @@
s: %5B
-%7Buser: %22user1%22, time: (new Date()).toLocaleString(), message: %22hi how u doing%22%7D, %7Buser: %22user2%22, time: (new Date()).toLocaleString(), message: %22lol wassup%22%7D%5D%7D,%0A%09%09%09%09%7Bsubject: %22how to add your own functions%22, posts: %5B%7Buser: %22user1%22, time: (new Date()).toLocaleString(), message: %22asdfasdf%22%7D, %7Buser: %22user2%22, time: (new Date()).toLocaleString(), message: %22j jajajajajajh%22%7D%5D%7D
+%5D%7D,%0A%09%09%09%09%7Bsubject: %22how to add your own functions%22, posts: %5B%5D%7D%0A%09%09%09
%5D%0A%09%09
|
7b42a4e5b7f077cda8b636076c7e7ce48304b12f | Move default plot to AAB | public/scripts/fireplot.js | public/scripts/fireplot.js | //Set Default Values
var region = 'Boreal';
var replicate = '0';
var simfile = "/json/alfresco/1.00.json";
var obsfile = "/json/alfresco/Historical.json";
//var obsfile = "/json/alfresco/Observed.json";
var plot = "DFN";
var maxreps = 200;
var startyear = 1950;
var endyear = 2014;
var ppk = 1; // Pixels Per Kilometer
$(document).ready( function() {
$.getJSON( obsfile, function( data ) {
var $rl = $("#region");
$.each( data._default['1']['avg_fire_size'], function( key, val ) {
$rl.append($("<option></option>").attr("value", key).text(key));
});
});
var $rc = $("#rep");
for (var i = 0; i < maxreps; i++){
$rc.append($("<option></option>").attr("value", i).text(i));
}
var $tc = $("#fileList");
var flist = myFiles.split(",");
for (var i = 0; i < flist.length; i++){
$tc.append($("<option></option>").attr("value", "/json/alfresco/" + flist[i]).text(flist[i]));
}
$("#plotfile").val(simfile);
drawPlot(plot, region, replicate);
$("#region").on("change", function(){
drawPlot(plot, $( this ).find("option:selected").text(), replicate);
});
$("#rep").on("change", function(){
drawPlot(plot, region, $( this ).find("option:selected").text());
});
$("#plotStyle").change( function(){
drawPlot($(this).find('option:selected').val(), region, replicate);
});
//$("#plotfile").change( function(){
// simfile = $(this).val();
// drawPlot(plot, region, replicate);
//});
$("#fileList").change( function(){
simfile = $(this).val();
drawPlot(plot, region, replicate);
});
});
function drawPlot(p, reg, rep){
plot = p;
if (plot == "CAB"){
drawCumulativeAreaBurned(reg, rep);
} else if (plot == "AAB"){
drawAnnualAreaBurned(reg, rep);
} else if (plot == "DFN"){
drawDecadalFireNum(reg, rep);
} else if (plot == "DFS"){
drawDecadalFireSize(reg, rep);
} else if (plot == "VEG"){
drawVegetation(reg, rep);
}
}
| JavaScript | 0 | @@ -208,19 +208,19 @@
plot = %22
-DFN
+AAB
%22;%0Avar m
|
f91c581a0af24b202585be11108576b10de1651f | update allowances | public/scripts/hkTaxCal.js | public/scripts/hkTaxCal.js | if (typeof define !== 'function') {
var define = require('amdefine')(module);
}
define([], function() {
//TODO rename as this is more than tax but also living feeds
var _calculator = {};
var rates = {
"y2013": {
"0": {
"limit": 40000,
"rate": 0.02
},
"1": {
"limit": 40000,
"rate": 0.07
},
"2": {
"limit": 40000,
"rate": 0.12
},
"3": {
"limit": Number.MAX_VALUE,
"rate": 0.17
},
"standard": {
"limit": -1,
"rate": 0.15
}
},
"y2014": {
"0": {
"limit": 40000,
"rate": 0.02
},
"1": {
"limit": 40000,
"rate": 0.07
},
"2": {
"limit": 40000,
"rate": 0.12
},
"3": {
"limit": Number.MAX_VALUE,
"rate": 0.17
},
"standard": {
"limit": -1,
"rate": 0.15
}
}
};
//TODO married
//resided with
var allowances = {
"y2013": {
"basic": 120000,
"married": 240000,
"child": 70000,
"bornChild": 140000,
"dependentSiblings": 33000,
// "dependentDisabledParents": 38000,
// "dependentDisabledParentsResidedWith": 76000,
"dependent60Parents": 38000,
"dependent60ParentsResidedWith": 76000,
"dependent55Parents": 19000,
"dependent55ParentsResidedWith": 38000,
"singleParent": 120000,
"disabledDependent": 66000
},
"y2014": {
"basic": 120000,
"married": 240000,
"child": 70000,
"bornChild": 140000,
"dependentSiblings": 33000,
// "dependentDisabledParents": 40000,
"dependent60Parents": 40000,
"dependent60ParentsResidedWith": 80000,
"dependent55Parents": 20000,
"dependent55ParentsResidedWith": 40000,
"singleParent": 120000,
"disabledDependent": 66000
}
};
var reduction = {
"y2013": {
"percent": 0.75,
"maximum":"10000",
"cases":["salary","profits","personal"]
},
"y2014": {
"percent": 0.75,
"maximum":"10000",
"cases":["salary","profits","personal"]
},
"y2015": {
"percent": 0.75,
"maximum":"20000",
"cases":["salary","profits","personal"]
}
};
_calculator.calReductions = function(year,taxPayable) {
var exceedMax = taxPayable > reduction[year]["maximum"];
return exceedMax ? reduction[year]["maximum"] : (taxPayable * reduction[year]["percent"]) ;
};
_calculator.calAllowances=function(year,key,count) {
return allowances[year][key]*(count|0);
};
//not same as deduction
_calculator.calProgressive = function(income,year) {
var taxable = [];
var tax = [];
var r = [];
var calSeg = function(remain, i) {
remain = remain > 0 ? remain : 0;
r[i] = remain - rates[year][i]["limit"];
taxable[i] = r[i] > 0 ? rates[year][i]["limit"] : remain;
tax[i] = (taxable[i] * rates[year][i]["rate"]).toFixed();
};
calSeg(income, 0);
calSeg(r[0], 1);
calSeg(r[1], 2);
calSeg(r[2], 3);
console.log("Tax:" + tax);
console.log("taxable" + taxable);
var totalTax = tax.reduce(function(p, c) {
return (p | 0) + (c | 0)
});
console.log(totalTax);
return totalTax;
};
_calculator.calStandardRate = function(incomeBeforeDeduction,year) {
return (incomeBeforeDeduction * rates[year]["standard"]["rate"]).toFixed();;
};
// totalAllowances
//Tax payable is calculated at progressive ratees on your net chargeable income
//or at standard rate on your net income ( before deduction of allowances), whichever is lower
_calculator.calculateTax = function(year, income,deduction,totalAllowances) {
var deductedIncome =income-deduction;
deductedIncome = Math.max(deductedIncome,0);
var netChargeableIncome = Math.max(deductedIncome - totalAllowances,0);
netChargeableIncome = netChargeableIncome>0 ?netChargeableIncome :0;
var taxProgressive = _calculator.calProgressive(netChargeableIncome,year);
var taxStandardRate = _calculator.calStandardRate(deductedIncome,year);
return taxProgressive <=taxStandardRate ?taxProgressive : taxStandardRate;
};
_calculator.calculateElectricty = function() {
};
// _calculator.calTaxableIncomeTax = function(taxableIncome) {
// return calProgressive(taxableIncome);
// };
// return _calculator;
if(typeof exports == 'undefined'){
var exports = _calculator;
}
return exports;
}); | JavaScript | 0.000001 | @@ -2064,17 +2064,510 @@
00%0A %7D
-%0A
+,%0A %22y2015%22: %7B%0A //only update child, another just copy%0A %22basic%22: 120000,%0A %22married%22: 240000,%0A %22child%22: 100000,%0A %22bornChild%22: 140000,%0A %22dependentSiblings%22: 33000,%0A //%22dependentDisabledParents%22: 40000,%0A %22dependent60Parents%22: 40000,%0A %22dependent60ParentsResidedWith%22: 80000,%0A %22dependent55Parents%22: 20000,%0A %22dependent55ParentsResidedWith%22: 40000,%0A %22singleParent%22: 120000,%0A %22disabledDependent%22: 66000%0A %7D
%0A%7D;%0A%0Avar
|
1a52500134a75735d740f3502a6dd3905ad64a2e | fix display example | lib/gamejs/display.js | lib/gamejs/display.js | var Surface = require('gamejs').Surface;
/**
* @fileoverview Methods to create, access and manipulate the display Surface.
* Drawing to the screen is as simple as this:
*
* $r.preload(["images/sunflower.png"),
* $r.ready(function() {
* // init
* gamejs.display.setMode([800, 600]);
* var displaySurface = gamejs.display.getSurface();
* // blit sunflower picture in top left corner of display
* var sunflower = gamejs.image.load("images/sunflower");
* displaySurface.blit(sunflower);
* // and a little bit below that rotated
* var rotatedSunflower = gamejs.transform.rotate(gamejs.sunflower, 45);
* displaySurface.blit(rotatedSunflower, [0, 100]);
* });
*
*/
/**
* Create the master Canvas plane.
* @ignore
*/
exports.init = function() {
// create canvas element if not yet present
var jsGameCanvas = null;
if ((jsGameCanvas = getCanvas()) === null) {
jsGameCanvas = document.createElement("canvas");
jsGameCanvas.setAttribute("id", CANVAS_ID);
document.body.appendChild(jsGameCanvas);
};
//jsGameCanvas.setAttribute("style", "width:95%;height:85%");
return;
};
/**
* Set the width and height of the Display. Conviniently this will
* return the actual display Surface - the same as calling [gamejs.display.getSurface()](#getSurface))
* later on.
* @param {Number[]} width and height the surface should be
*/
exports.setMode = function(rect) {
var canvas = getCanvas();
canvas.width = rect[0];
canvas.height = rect[1];
return getSurface();
};
/**
* Set the Caption of the Display (document.title)
* @param {String} title the title of the app
* @param {gamejs.Image} icon FIXME implement favicon support
*/
exports.setCaption = function(title, icon) {
document.title = title;
};
var CANVAS_ID = "jsgamecanvas";
var SURFACE = null;
/**
* The Display (the canvas element) is most likely not in the top left corner
* of the browser due to CSS styling. To calculate the mouseposition within the
* canvas we need this offset.
* @see {gamejs.event}
* @ignore
*
* @returns {Number[]} x and y offset of the canvas
*/
exports._getCanvasOffset = function() {
var boundRect = getCanvas().getBoundingClientRect();
return [boundRect.left, boundRect.top];
};
/**
* Drawing on the Surface returned by `getSurface()` will draw on the screen.
* @returns {gamejs.Surface} the display Surface
*/
var getSurface = exports.getSurface = function() {
if (SURFACE == null) {
var canvas = getCanvas();
var SURFACE = new Surface([canvas.clientWidth, canvas.clientHeight]);
SURFACE._canvas = canvas;
// NOTE this is a hack. setting _canvas directly for the special main display surface
}
return SURFACE;
};
/**
* @returns {document.Element} the canvas dom element
*/
var getCanvas = function() {
var jsGameCanvas = null;
var canvasList = Array.prototype.slice.call(document.getElementsByTagName("canvas"));
canvasList.every(function(canvas) {
if (canvas.getAttribute("id") == CANVAS_ID) {
jsGameCanvas = canvas;
return false;
}
return true;
});
return jsGameCanvas;
};
| JavaScript | 0.000001 | @@ -177,18 +177,62 @@
*
-$r
+var gamejs = require('gamejs');%0A * gamejs
.preload
@@ -270,10 +270,14 @@
-$r
+gamejs
.rea
@@ -296,28 +296,8 @@
) %7B%0A
- * // init%0A
*
@@ -402,16 +402,17 @@
face();%0A
+%0A
*
@@ -538,16 +538,16 @@
ower%22);%0A
-
*
@@ -582,16 +582,18 @@
lower);%0A
+ %0A
*
|
15fb3424222cff5bfe2d32938af72f8d6f3d515e | fix rename property and add docs on filter | filter-widget/Filter.js | filter-widget/Filter.js | import DefineMap from 'can-define/map/map';
import DefineList from 'can-define/list/list';
export const Filter = DefineMap.extend('Filter', {
value: {
type: '*'
},
name: {
type: 'string',
value: ''
},
operator: {
type: 'string',
value: 'like'
},
opField: {
serialize: false
}
});
export const FilterList = DefineList.extend('FilterList', {
'#': Filter
});
export const FilterOptions = [{
label: 'Does not contain',
value: 'not_like',
types: ['string']
}, {
label: 'Contains',
value: 'like',
types: ['string'],
filterFactory (filter) {
filter.value = ['%', filter.value, '%'].join('');
return filter;
}
}, {
label: 'Starts with',
value: 'starts_with',
types: ['string'],
filterFactory (filter) {
filter.value = [filter.value, '%'].join('');
return filter;
}
}, {
label: 'Ends with',
value: 'ends_with',
types: ['string'],
filterFactory (filter) {
filter.value = ['%', filter.value].join('');
return filter;
}
}, {
label: 'Exactly equal to',
value: 'equals'
}, {
label: 'Not exactly equal to',
operator: 'not_equal_to',
value: 'not_equal_to'
}, {
label: 'Greater Than',
value: 'greater_than',
types: ['number'],
filterFactory (filter) {
filter.value = parseFloat(filter.value);
return filter;
}
}, {
label: 'Less Than',
value: 'less_than',
types: ['number'],
filterFactory (filter) {
filter.value = parseFloat(filter.value);
return filter;
}
}, {
label: 'Before',
value: 'before',
types: ['date'],
valueField: {
name: 'value',
alias: 'Value',
fieldType: 'date',
properties: {
placeholder: 'Select a date'
}
}
}, {
label: 'After',
value: 'after',
types: ['date'],
valueField: {
name: 'value',
alias: 'Value',
fieldType: 'date',
properties: {
placeholder: 'Select a date'
}
}
}];
| JavaScript | 0 | @@ -89,233 +89,1091 @@
';%0A%0A
-export const Filter = DefineMap.extend('Filter', %7B%0A value: %7B%0A type: '*'%0A %7D,%0A name: %7B%0A type: 'string',%0A value: ''%0A %7D,%0A operator: %7B%0A type: 'string',%0A value: 'like'%0A %7D,%0A op
+/**%0A * @constructor filter-widget.Filter Filter%0A * @parent filter-widget%0A * @group filter-widget.Filter.props Properties%0A *%0A * @description Creates a new filter object%0A * @signature %60new Filter(properties)%60%0A */%0Aexport const Filter = DefineMap.extend('Filter', %7B%0A /**%0A * A value to filter on. Can be any primitive type%0A * @property %7B*%7D Filter.value%0A */%0A value: %7B%0A type: '*'%0A %7D,%0A /**%0A * The name of the field to filter on%0A * @property %7BString%7D Filter.name%0A * @parent Filter.props%0A */%0A name: %7B%0A type: 'string',%0A value: ''%0A %7D,%0A /**%0A * The operator to filter with. The default is %60like%60.%0A *%0A * @property %7BString%7D Filter.operator%0A * @parent Filter.props%0A */%0A operator: %7B%0A type: 'string',%0A value: 'like'%0A %7D,%0A /**%0A * A field object that defines the available operator options and properties.%0A * This is used to create the dropdown choice for each filter in the filter-widget%0A * @property %7BObject%7D Filter.operatorField%0A * @parent Filter.props%0A */%0A operator
Fiel
|
82819f222e6c46606ec0c9350ec20a450a6b5e92 | Add An Unpublished debugMode Flag | lib/gocodeprovider.js | lib/gocodeprovider.js | 'use babel'
import {CompositeDisposable} from 'atom'
import path from 'path'
import _ from 'lodash'
class GocodeProvider {
constructor (goconfigFunc, gogetFunc) {
this.goconfig = goconfigFunc
this.goget = gogetFunc
this.subscriptions = new CompositeDisposable()
this.subscribers = []
this.selector = '.source.go'
this.inclusionPriority = 1
this.excludeLowerPriority = atom.config.get('autocomplete-go.suppressBuiltinAutocompleteProvider')
this.suppressForCharacters = []
this.disableForSelector = atom.config.get('autocomplete-go.scopeBlacklist')
let suppressSubscrition = atom.config.observe('autocomplete-go.suppressActivationForCharacters', (value) => {
this.suppressForCharacters = _.map(value, (c) => {
let char = c ? c.trim() : ''
char = (() => {
switch (false) {
case char.toLowerCase() !== 'comma':
return ','
case char.toLowerCase() !== 'newline':
return '\n'
case char.toLowerCase() !== 'space':
return ' '
case char.toLowerCase() !== 'tab':
return '\t'
default:
return char
}
})()
return char
})
this.suppressForCharacters = _.compact(this.suppressForCharacters)
})
this.subscriptions.add(suppressSubscrition)
this.funcRegex = /^(?:func[(]{1})([^\)]*)(?:[)]{1})(?:$|(?:\s)([^\(]*$)|(?: [(]{1})([^\)]*)(?:[)]{1}))/i
}
dispose () {
if (this.subscriptions) {
this.subscriptions.dispose()
}
this.subscriptions = null
this.goconfig = null
this.subscribers = null
this.selector = null
this.inclusionPriority = null
this.excludeLowerPriority = null
this.suppressForCharacters = null
this.disableForSelector = null
this.funcRegex = null
}
ready () {
if (!this.goconfig) {
return false
}
let config = this.goconfig()
if (!config) {
return false
}
return true
}
isValidEditor (editor) {
if (!editor || !editor.getGrammar) {
return false
}
let grammar = editor.getGrammar()
if (!grammar) {
return false
}
if (grammar.scopeName === 'source.go') {
return true
}
return false
}
characterIsSuppressed (char) {
return this.suppressForCharacters.indexOf(char) !== -1
}
getSuggestions (options) {
let p = new Promise((resolve) => {
if (!options || !this.ready() || !this.isValidEditor(options.editor)) {
return resolve()
}
let config = this.goconfig()
let buffer = options.editor.getBuffer()
if (!buffer || !options.bufferPosition) {
return resolve()
}
let index = buffer.characterIndexForPosition(options.bufferPosition)
let text = options.editor.getText()
if (index > 0 && this.characterIsSuppressed(text[index - 1])) {
return resolve()
}
let offset = Buffer.byteLength(text.substring(0, index), 'utf8')
let locatorOptions = {
file: options.editor.getPath(),
directory: path.dirname(options.editor.getPath())
}
let args = ['-f=json', 'autocomplete', buffer.getPath(), offset]
config.locator.findTool('gocode', locatorOptions).then((cmd) => {
if (!cmd) {
resolve()
return false
}
let cwd = path.dirname(buffer.getPath())
let env = config.environment(locatorOptions)
config.executor.exec(cmd, args, {cwd: cwd, env: env, input: text}).then((r) => {
if (r.stderr && r.stderr.trim() !== '') {
console.log('autocomplete-go: (stderr) ' + r.stderr)
}
let messages = []
if (r.stdout && r.stdout.trim() !== '') {
messages = this.mapMessages(r.stdout, options.editor, options.bufferPosition)
}
if (!messages || messages.length < 1) {
return resolve()
}
resolve(messages)
}).catch((e) => {
console.log(e)
resolve()
})
})
})
if (this.subscribers && this.subscribers.length > 0) {
for (let subscriber of this.subscribers) {
subscriber(p)
}
}
return p
}
onDidGetSuggestions (s) {
if (this.subscribers) {
this.subscribers.push(s)
}
}
mapMessages (data, editor, position) {
if (!data) {
return []
}
let res
try {
res = JSON.parse(data)
} catch (e) {
if (e && e.handle) {
e.handle()
}
atom.notifications.addError('gocode error', {
detail: data,
dismissable: true
})
console.log(e)
return []
}
let numPrefix = res[0]
let candidates = res[1]
if (!candidates) {
return []
}
let prefix = editor.getTextInBufferRange([[position.row, position.column - numPrefix], position])
let suffix = false
try {
suffix = editor.getTextInBufferRange([position, [position.row, position.column + 1]])
} catch (e) {
console.log(e)
}
let suggestions = []
for (let c of candidates) {
let suggestion = {
replacementPrefix: prefix,
leftLabel: c.type || c.class,
type: this.translateType(c.class)
}
if (c.class === 'func' && (!suffix || suffix !== '(')) {
suggestion = this.upgradeSuggestion(suggestion, c)
} else {
suggestion.text = c.name
}
if (suggestion.type === 'package') {
suggestion.iconHTML = '<i class="icon-package"></i>'
}
suggestions.push(suggestion)
}
return suggestions
}
translateType (type) {
if (type === 'func') {
return 'function'
}
if (type === 'var') {
return 'variable'
}
if (type === 'const') {
return 'constant'
}
if (type === 'PANIC') {
return 'panic'
}
return type
}
upgradeSuggestion (suggestion, c) {
if (!c || !c.type || c.type === '') {
return suggestion
}
let match = this.funcRegex.exec(c.type)
if (!match || !match[0]) { // Not a function
suggestion.snippet = c.name + '()'
suggestion.leftLabel = ''
return suggestion
}
suggestion.leftLabel = match[2] || match[3] || ''
suggestion.snippet = this.generateSnippet(c.name, match)
return suggestion
}
generateSnippet (name, match) {
let signature = name
if (!match || !match[1] || match[1] === '') {
// Has no arguments, shouldn't be a snippet, for now
return signature + '()'
}
let args = match[1].split(/, /)
args = _.map(args, (a) => {
if (!a || a.length <= 2) {
return a
}
if (a.substring(a.length - 2, a.length) === '{}') {
return a.substring(0, a.length - 1) + '\\}'
}
return a
})
if (args.length === 1) {
return signature + '(${1:' + args[0] + '})'
}
let i = 1
for (let arg of args) {
if (i === 1) {
signature = signature + '(${' + i + ':' + arg + '}'
} else {
signature = signature + ', ${' + i + ':' + arg + '}'
}
i = i + 1
}
signature = signature + ')'
return signature
// TODO: Emit function's result(s) in snippet, when appropriate
}
}
export {GocodeProvider}
| JavaScript | 0 | @@ -3464,16 +3464,169 @@
ptions)%0A
+ let debugMode = atom.config.get('autocomplete-go.debugMode')%0A if (debugMode) %7B%0A console.log(cmd + '' + args.join(' '))%0A %7D%0A
|
4e4cfac6ab5bfd4d8d263bc7def4488c7634932e | Use UTC time when updating dates | lib/daterangepicker/daterangepicker.timesupport.js | lib/daterangepicker/daterangepicker.timesupport.js | (function(root, factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
define(['jquery', 'underscore', 'moment', 'timepicker'], function($, _, moment) {
return factory($, _, moment);
});
} else {
root.daterangepicker.timeSupport = factory(root.jQuery, root._, root.moment);
}
})(this, function($, _, moment) {
'use strict';
var TIME_REGEX = /^([01]\d|2[0-3]):([0-5]\d)$/,
TIME_FORMAT = 'HH:mm';
function isValidTime(time) {
return TIME_REGEX.exec(time);
}
function setupTimePanelEvents(panel) {
panel.$el.on('change.time-panel', panel.$input, function() {
if (panel.isValidTime()) {
panel.updateCalendarDate();
}
});
}
function getTimePanel() {
return $('<div class="time-support__panel"><input name="time" class="time-support__field field rounded" /></div>');
}
function getTimePanelWrapper() {
var html = '<div class="time-support">' +
'<div class="time-support__panel-wrapper"></div>' +
'<label class="time-support__specify-time"><input type="checkbox" name="specifyTime"> Specify time</label>' +
'</div>';
return $(html);
}
function TimePanel(options) {
if (!options.calendar) {
throw new Error('Time panel must be instantiated with options.calendar');
}
this.$el = getTimePanel();
this.$input = this.$el.find('input[name="time"]').timepicker();
this.calendar = options.calendar;
setupTimePanelEvents(this);
}
_.extend(TimePanel.prototype, {
isValidTime: function() {
var panel = this,
time = panel.$input.val();
panel.$input.removeClass('invalid-time');
if (!time || !TIME_REGEX.test(time)) {
panel.$input.addClass('invalid-time');
return false;
}
return true;
},
getTime: function() {
var time = this.$input.val();
return moment.utc(time, TIME_FORMAT);
},
setTime: function(time) {
this.$input.val(time);
},
updateCalendarDate: function(options) {
var panel = this,
date,
hours = 0,
minutes = 0,
time = panel.getTime(),
currentDate = panel.calendar.selectedDate;
options = options || {};
if (time) {
hours = time.hours();
minutes = time.minutes();
}
date = moment.utc([
currentDate.year(),
currentDate.month(),
currentDate.date(),
hours,
minutes
]);
panel.calendar.updateSelectedDate(date, options);
},
destroy: function() {
var panel = this;
if (panel.$el) {
panel.$el.remove();
panel.$el.off('.time-panel');
}
}
});
function TimeSupport(options) {
var plugin = this,
isSpecifyTimeChecked = (options || {}).specifyTimeChecked;
plugin.$el = getTimePanelWrapper();
plugin.$specifyTime = plugin.$el.find('[name=specifyTime]');
plugin.$specifyTime.prop('checked', isSpecifyTimeChecked);
plugin.$specifyTime.on('change', _.bind(plugin.setPanelState, plugin));
}
TimeSupport.pluginName = 'timeSupport';
_.extend(TimeSupport.prototype, {
resetCalendars: function(){
var plugin = this;
plugin.startPanel.updateCalendarDate({silent: true});
plugin.endPanel.updateCalendarDate({silent: true});
plugin.picker.trigger('refresh', {
startDate: plugin.startPanel.calendar.selectedDate,
endDate: plugin.endPanel.calendar.selectedDate
});
},
setPanelState: function () {
var plugin = this;
if (plugin.$specifyTime.prop('checked')) {
plugin.openPanel();
} else {
plugin.closePanel();
}
},
render: function(daterangepicker) {
var plugin = this;
plugin.$el.insertBefore(daterangepicker.$el.find('.calendar-footer'));
plugin.$panelWrapper = plugin.$el.find('.time-support__panel-wrapper');
plugin.$panelWrapper.html(plugin.startPanel.$el);
if (plugin.endPanel) {
plugin.$panelWrapper.append(plugin.endPanel.$el);
}
plugin.setPanelState();
},
updateStartTime: function(time) {
this.startPanel.setTime(time.format(TIME_FORMAT));
},
updateEndTime: function(time) {
this.endPanel.setTime(time.format(TIME_FORMAT));
},
openPanel: function() {
var plugin = this;
plugin.$panelWrapper.addClass('isOpen');
plugin.updateStartTime(plugin.startPanel.calendar.selectedDate.utc());
plugin.updateEndTime(plugin.endPanel.calendar.selectedDate.utc());
plugin.resetCalendars();
},
closePanel: function() {
var plugin = this,
startOfDay = moment().startOf('day');
plugin.$panelWrapper.removeClass('isOpen');
plugin.updateStartTime(startOfDay);
plugin.updateEndTime(startOfDay);
plugin.resetCalendars();
},
attach: function(daterangepicker) {
var plugin = this,
startCalendar = daterangepicker.startCalendar,
endCalendar = daterangepicker.endCalendar;
plugin.picker = daterangepicker;
plugin.startPanel = new TimePanel({
calendar: startCalendar
});
$('<label class="time-support__from">From</label>').insertBefore(plugin.startPanel.$input);
if (endCalendar) {
plugin.endPanel = new TimePanel({
calendar: endCalendar
});
$('<label class="time-support__to">To</label>').insertBefore(plugin.endPanel.$input);
$('<span class="time-support__zone">(UTC)</span>').insertAfter(plugin.endPanel.$input);
}
daterangepicker.bind('render', function() {
plugin.render(daterangepicker);
});
daterangepicker.bind('startDateSelected', function(args) {
plugin.updateEndTime(args.endDate);
endCalendar.updateSelectedDate(args.endDate, {
silent: true
});
});
daterangepicker.bind('endDateSelected', function(args) {
plugin.updateStartTime(args.startDate);
startCalendar.updateSelectedDate(args.startDate, {
silent: true
});
});
daterangepicker.bind('presetSelected', function(args) {
var specifyTime = (args.specifyTime === true) ? true : false;
plugin.$specifyTime.prop('checked', specifyTime).trigger('change');
plugin.updateStartTime(args.startDate);
plugin.updateEndTime(args.endDate);
startCalendar.updateSelectedDate(args.startDate, {
silent: true
});
endCalendar.updateSelectedDate(args.endDate, {
silent: true
});
});
/* calendar.updateSelectedDate is called when a day table cell ('td.day')
* is clicked and it passes date as a string e.g. "2014-09-12".
* When that happens the current time entered by the user is lost.
*
* This wrapper function ensures that calendar.updateSelectedDate
* is always called with both date and time if specify time is checked.
*/
function updateSelectedDateWrapper(panel, originalUpdateSelectedDate, date, options) {
var time;
if (plugin.$specifyTime.prop('checked')) {
time = panel.getTime();
date = moment(date).hours(time.hours()).minutes(time.minutes());
}
originalUpdateSelectedDate.call(panel.calendar, date, options);
}
startCalendar.updateSelectedDate = _.wrap(startCalendar.updateSelectedDate, function(originalFunc, date, options) {
updateSelectedDateWrapper(plugin.startPanel, originalFunc, date, options);
});
if (endCalendar) {
endCalendar.updateSelectedDate = _.wrap(endCalendar.updateSelectedDate, function(originalFunc, date, options) {
updateSelectedDateWrapper(plugin.endPanel, originalFunc, date, options);
});
}
},
detach: function() {
var plugin = this;
plugin.$el.remove();
plugin.startPanel.destroy();
if (plugin.endPanel) {
plugin.endPanel.destroy();
}
}
});
return TimeSupport;
}); | JavaScript | 0.000002 | @@ -8366,16 +8366,20 @@
= moment
+.utc
(date).h
@@ -9345,8 +9345,9 @@
ort;%0A%7D);
+%0A
|
914ac72df7fb2cc99a724b447ae549180f64dbb8 | disable find dialog in ace (#1134) | ui/client/components/graph/node-modal/editors/expression/ExpressionSuggest.js | ui/client/components/graph/node-modal/editors/expression/ExpressionSuggest.js | import cn from "classnames"
import _ from "lodash"
import PropTypes from "prop-types"
import React from "react"
import ReactDOMServer from "react-dom/server"
import {connect} from "react-redux"
import ActionsUtils from "../../../../../actions/ActionsUtils"
import ProcessUtils from "../../../../../common/ProcessUtils"
import HttpService from "../../../../../http/HttpService"
import ValidationLabels from "../../../../modals/ValidationLabels"
import AceEditor from "./ace"
import ExpressionSuggester from "./ExpressionSuggester"
import {allValid} from "../Validators"
import {reducer as nodeDetails} from "../../../../../reducers/nodeDetailsState"
//to reconsider
// - respect categories for global variables?
// - maybe ESC should be allowed to hide suggestions but leave modal open?
var inputExprIdCounter = 0
const identifierRegexpsWithoutDot = [/[#a-z0-9-_]/]
const identifierRegexpsIncludingDot = [/[#a-z0-9-_.]/]
class ExpressionSuggest extends React.Component {
static propTypes = {
inputProps: PropTypes.object.isRequired,
validators: PropTypes.array,
showValidation: PropTypes.bool,
processingType: PropTypes.string,
isMarked: PropTypes.bool,
variableTypes: PropTypes.object,
}
customAceEditorCompleter = {
getCompletions: (editor, session, caretPosition2d, prefix, callback) => {
this.expressionSuggester.suggestionsFor(this.state.value, caretPosition2d).then(suggestions => {
// This trick enforce autocompletion to invoke getCompletions even if some result found before - in case if list of suggestions will change during typing
editor.completer.activated = false
// We have dot in identifier pattern to enable live autocompletion after dots, but also we remove it from pattern just before callback, because
// otherwise our results lists will be filtered out (because entries not matches '#full.property.path' but only 'path')
this.customAceEditorCompleter.identifierRegexps = identifierRegexpsWithoutDot
try {
callback(null, _.map(suggestions, (s) => {
const methodName = s.methodName
const returnType = ProcessUtils.humanReadableType(s.refClazz)
return {
name: methodName,
value: methodName,
score: 1,
meta: returnType,
description: s.description,
parameters: s.parameters,
returnType: returnType,
}
}))
} finally {
this.customAceEditorCompleter.identifierRegexps = identifierRegexpsIncludingDot
}
})
},
// We adds hash to identifier pattern to start suggestions just after hash is typed
identifierRegexps: identifierRegexpsIncludingDot,
getDocTooltip: (item) => {
if (item.description || !_.isEmpty(item.parameters)) {
const paramsSignature = item.parameters.map(p => `${ProcessUtils.humanReadableType(p.refClazz)} ${p.name}`).join(", ")
const javaStyleSignature = `${item.returnType} ${item.name}(${paramsSignature})`
item.docHTML = ReactDOMServer.renderToStaticMarkup((
<div className="function-docs">
<b>{javaStyleSignature}</b>
<hr/>
<p>{item.description}</p>
</div>
))
}
},
}
constructor(props) {
super(props)
inputExprIdCounter += 1
this.state = {
value: props.inputProps.value,
id: `inputExpr${inputExprIdCounter}`,
}
this.expressionSuggester = this.createExpressionSuggester(props)
}
//fixme is this enough?
//this shouldComponentUpdate is for cases when there are multiple instances of suggestion component in one view and to make them not interfere with each other
//fixme maybe use this.state.id here?
shouldComponentUpdate(nextProps, nextState) {
return !_.isEqual(this.state.value, nextState.value) ||
!_.isEqual(this.state.editorFocused, nextState.editorFocused) ||
!_.isEqual(this.props.validators, nextProps.validators) ||
!_.isEqual(this.props.variableTypes, nextProps.variableTypes)
}
componentDidUpdate(prevProps, prevState) {
this.expressionSuggester = this.createExpressionSuggester(this.props)
if (!_.isEqual(this.state.value, prevState.value)) {
this.props.inputProps.onValueChange(this.state.value)
}
}
createExpressionSuggester = (props) => {
return new ExpressionSuggester(props.typesInformation, props.variableTypes, props.processingType, HttpService)
}
onChange = (newValue) => {
this.setState({
value: newValue,
})
}
render() {
if (this.props.dataResolved) {
const {isMarked, showValidation, inputProps, validators} = this.props
const {editorFocused, value} = this.state
const THEME = "nussknacker"
//monospace font seems to be mandatory to make ace cursor work well,
const FONT_FAMILY = "'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace"
return (
<React.Fragment>
<div className={cn([
"row-ace-editor",
showValidation && !allValid(validators, [value]) && "node-input-with-error",
isMarked && "marked",
editorFocused && "focused",
inputProps.readOnly && "read-only",
])}
>
<AceEditor
mode={inputProps.language}
width={"100%"}
minLines={1}
maxLines={50}
theme={THEME}
onChange={this.onChange}
value={value}
showPrintMargin={false}
cursorStart={-1} //line start
showGutter={false}
highlightActiveLine={false}
highlightGutterLine={false}
wrapEnabled={true}
editorProps={{
// eslint-disable-next-line i18next/no-literal-string
$blockScrolling: "Infinity",
}}
className={inputProps.readOnly ? " read-only" : ""}
setOptions={{
indentedSoftWrap: false, //removes weird spaces for multiline strings when wrapEnabled=true
enableBasicAutocompletion: [this.customAceEditorCompleter],
enableLiveAutocompletion: true,
enableSnippets: false,
showLineNumbers: false,
fontSize: 16,
fontFamily: FONT_FAMILY,
readOnly: inputProps.readOnly,
}}
onFocus={this.setEditorFocus(true)}
onBlur={this.setEditorFocus(false)}
/>
</div>
{showValidation && <ValidationLabels validators={validators} values={[value]}/>}
</React.Fragment>
)
} else {
return null
}
}
setEditorFocus = (focus) => () => this.setState({editorFocused: focus})
}
function mapState(state) {
const processDefinitionData = !_.isEmpty(state.settings.processDefinitionData) ? state.settings.processDefinitionData : {processDefinition: {typesInformation: []}}
const dataResolved = !_.isEmpty(state.settings.processDefinitionData)
const typesInformation = processDefinitionData.processDefinition.typesInformation
return {
typesInformation: typesInformation,
dataResolved: dataResolved,
processingType: state.graphReducer.processToDisplay.processingType,
}
}
export default connect(mapState, ActionsUtils.mapDispatchWithEspActions)(ExpressionSuggest)
| JavaScript | 0 | @@ -918,16 +918,137 @@
-_.%5D/%5D%0A%0A
+const commandFindConfiguration = %7B%0A name: %22find%22,%0A bindKey: %7Bwin: %22Ctrl-F%22, mac: %22Command-F%22%7D,%0A exec: () =%3E false,%0A%7D%0A%0A
class Ex
@@ -6612,32 +6612,84 @@
%7D%7D%0A
+ commands=%7B%5BcommandFindConfiguration%5D%7D%0A
on
|
103f3a82fdd6b076232fc761a3f43345cc787a51 | Fix Break | templates/controller.template.js | templates/controller.template.js | /**
* @description
* <%= Controllername %>. Controller
* <%= whatIsThis %>
**/
angular.module('<%= controllerName %>.controller', [
'humpback.controllers'
])
.controller( '<%= ControllerName %>', function <%= ControllerNameLong %> ( $scope ) {
}); | JavaScript | 0.000001 | @@ -15,25 +15,25 @@
tion %0A* %3C%25=
-C
+c
ontrollernam
@@ -33,18 +33,17 @@
ller
-n
+N
ame %25%3E.
- C
+c
ontr
|
8f11635b399f14980386deda7e63f14f7e1a6c0c | implement route /verifyEmail #13 | src/routes/UserRoute.js | src/routes/UserRoute.js | import Express from 'express';
import Model from '../models/model';
import Utils from '../utils';
let router = Express.Router();
//POST URL: localhost:8080/api/user?username=testusername&email=testemail&password=testpassword&api_key=testapikey&api_secret=testapisecret
router.route('/user')
.post(function(req, res) {
Model.User
.build({
Username: req.body.username,
Firstname: req.body.firstname,
Lastname: req.body.lastname,
Email: req.body.email,
AccountCreation_Timestamp: new Date().getTime(),
Description: req.body.description
})
.save()
.then(function(result) {
res.send(result);
})
.catch(function(error) {
console.log(error);
res.send(error);
})
})
.get(function(req, res) {
try{
Model.User.findAll()
.then(function(result) {
res.send(result);
})
}
catch(error) {
res.send(error);
}
});
router.route('/showEditableUserFields')
.post(function(req, res) {
try{
Model.User.findOne({
where: {
GUID: req.body.userguid
},
attributes: ['Username', 'Firstname', 'Lastname', 'Email', 'Email_verified', 'Description']
})
.then(function(result) {
res.send(result);
})
}
catch(error) {
res.send(error);
}
});
router.route('/editUser')
.post(function(req, res) {
try{
Model.User.update({
Username: req.body.username,
Firstname: req.body.firstname,
Lastname: req.body.lastname,
Email: req.body.email,
Email_verified: req.body.email_verified,
Description: req.body.description
},
{
where: {
GUID: req.body.userguid
}
})
.then(function(result) {
res.send(result);
})
}
catch(error) {
res.send(error);
}
});
module.exports = router; | JavaScript | 0.000002 | @@ -1793,16 +1793,323 @@
%0A%09%09%7D);%0A%0A
+router.route('/verifyEmail')%0A%09%09.post(function(req, res) %7B%0A%09%09%09try%7B%0A%09%09%09%09Model.User.update(%7B%0A%09%09%09%09%09Email_verified: true,%0A%09%09%09%09%7D,%0A%09%09%09%09%7B%0A%09%09%09%09%09where: %7B%0A%09%09%09%09%09%09GUID: req.body.userguid%0A%09%09%09%09%09%7D%0A%09%09%09%09%7D)%0A%09%09%09%09.then(function(result) %7B%0A%09%09%09%09%09res.send(result);%0A%09%09%09%09%7D)%0A%09%09%09%7D%0A%09%09%09catch(error) %7B%0A%09%09%09%09res.send(error);%0A%09%09%09%7D%0A%09%09%7D);%0A%09%09%09%0A%0A
module.e
|
72bcff83f71a0fd9cb04a05386e43898c6fbf75b | Fix hook to remove build.gradle config on uninstall. | hooks/lib/android-helper.js | hooks/lib/android-helper.js |
var fs = require("fs");
var path = require("path");
var utilities = require("./utilities");
module.exports = {
addFabricBuildToolsGradle: function() {
var buildGradle = utilities.readBuildGradle();
buildGradle += [
"// Fabric Cordova Plugin - Start Fabric Build Tools ",
"buildscript {",
" repositories {",
" maven { url 'https://maven.fabric.io/public' }",
" }",
" dependencies {",
" classpath 'io.fabric.tools:gradle:1.+'",
" }",
"}",
"",
"apply plugin: 'io.fabric'",
"// Fabric Cordova Plugin - End Fabric Build Tools",
].join("\n");
utilities.writeBuildGradle(buildGradle);
},
removeFabricBuildToolsFromGradle: function() {
var buildGradle = utilities.readBuildGradle();
buildGradle = buildGradle.replace(/\n\/\/ Fabric Cordova Plugin - Start Fabric Build Tools[\s\S]*\/\/ Fabric Cordova Plugin - End Fabric Build Tools\n/, "");
utilities.writeBuildGradle(buildGradle);
}
};
| JavaScript | 0 | @@ -234,16 +234,32 @@
e += %5B%0A
+ %22%22,%0A
@@ -1072,18 +1072,16 @@
ld Tools
-%5Cn
/, %22%22);%0A
|
cbaefd8dcbb8b940ab373c4c1e29f55f01682541 | Update removeDesc.js (#798) | plugins/removeDesc.js | plugins/removeDesc.js | 'use strict';
exports.type = 'perItem';
exports.active = true;
exports.params = {
removeAny: false
};
exports.description = 'removes <desc> (only non-meaningful by default)';
var standardDescs = /^Created with/;
/**
* Removes <desc>.
* Removes only standard editors content or empty elements 'cause it can be used for accessibility.
* Enable parameter 'removeAny' to remove any description.
*
* https://developer.mozilla.org/en-US/docs/Web/SVG/Element/desc
*
* @param {Object} item current iteration item
* @return {Boolean} if false, item will be filtered out
*
* @author Daniel Wabyick
*/
exports.fn = function(item, params) {
return !item.isElem('desc') || !(params.removeAny || item.isEmpty() ||
standardDescs.test(item.content[0].text));
};
| JavaScript | 0 | @@ -199,16 +199,17 @@
scs = /%5E
+(
Created
@@ -212,16 +212,31 @@
ted with
+%7CCreated using)
/;%0A%0A/**%0A
|
8d1f37df3b597e5fe53374a3c2ec37d0ca54816e | Make benchmark result electron output friendly | benchmarks/message-registry.js | benchmarks/message-registry.js | 'use babel'
import {MessageRegistry} from '../lib/message-registry'
import {getLinter, getMessage} from '../spec/common'
import {timeNow, timeDiff, getMessages} from './common'
const messageRegistry = new MessageRegistry()
messageRegistry.debouncedUpdate = function() {}
const linter = getLinter()
function benchmarkRegistry(i) {
let timeKey = 'iteration #' + i
messages = getMessages(5000)
const start = performance.now()
messageRegistry.set({linter, messages, buffer: null})
messageRegistry.update()
return performance.now() - start
}
module.exports = function() {
let sum = 0
let count = 500
for (let i = 0; i < count; ++i) {
sum += benchmarkRegistry(i)
}
console.log('average message registry diff time for 5k messages', sum / (count - 1))
}
| JavaScript | 0.000001 | @@ -748,11 +748,15 @@
ages
-',
+: ' + (
sum
@@ -769,11 +769,12 @@
nt - 1))
+)
%0A%7D%0A
|
209e8325b79f3ad74d4a377bba8dd7965602401c | update toObject to check proper values when cleaning associations | lib/waterline/model/lib/defaultMethods/toObject.js | lib/waterline/model/lib/defaultMethods/toObject.js |
/**
* Module dependencies
*/
var _ = require('lodash'),
utils = require('../../../utils/helpers'),
hasOwnProperty = utils.object.hasOwnProperty;
/**
* Model.toObject()
*
* Returns a cloned object containing just the model
* values. Useful for doing operations on the current values
* minus the instance methods.
*
* @param {Object} context, Waterline collection instance
* @param {Object} proto, model prototype
* @api public
* @return {Object}
*/
var toObject = module.exports = function(context, proto) {
this.context = context;
this.proto = proto;
this.object = Object.create(proto.__proto__);
this.addAssociations();
this.addProperties();
this.makeObject();
this.filterJoins();
this.filterFunctions();
return this.object;
};
/**
* Add Association Keys
*
* If a showJoins flag is active, add all association keys.
*
* @param {Object} keys
* @api private
*/
toObject.prototype.addAssociations = function() {
var self = this;
if(!this.proto._properties) return;
if(!this.proto._properties.showJoins) return;
// Copy prototype over for attributes
for(var association in this.proto.associations) {
// Handle hasMany attributes
if(hasOwnProperty(this.proto.associations[association], 'value')) {
var records = [];
var values = this.proto.associations[association].value;
values.forEach(function(record) {
var item = Object.create(record.__proto__);
Object.keys(record).forEach(function(key) {
item[key] = _.cloneDeep(record[key]);
});
records.push(item);
});
this.object[association] = records;
continue;
}
// Handle belongsTo attributes
var record = this.proto[association];
if(_.isObject(record) && !Array.isArray(record)) {
var item = Object.create(record.__proto__);
Object.keys(record).forEach(function(key) {
item[key] = _.cloneDeep(record[key]);
});
this.object[association] = item;
} else {
this.object[association] = record;
}
}
};
/**
* Add Properties
*
* Copies over non-association attributes to the newly created object.
*
* @api private
*/
toObject.prototype.addProperties = function() {
var self = this;
Object.keys(this.proto).forEach(function(key) {
if(hasOwnProperty(self.object, key)) return;
self.object[key] = _.cloneDeep(self.proto[key]);
});
};
/**
* Make Object
*
* Runs toJSON on all associated values
*
* @api private
*/
toObject.prototype.makeObject = function() {
var self = this;
if(!this.proto._properties) return;
if(!this.proto._properties.showJoins) return;
// Handle Belongs-To Joins
Object.keys(this.proto.associations).forEach(function(association) {
// Don't run toJSON on records that were not populated
if(self.proto._properties && self.proto._properties.joins) {
// Build up a join key name based on the attribute's model/collection name
var joinsName = association;
if(self.proto.associations[association].model) joinsName = self.proto.associations[association].model.toLowerCase();
if(self.proto.associations[association].collection) joinsName = self.proto.associations[association].collection.toLowerCase();
// Check if the join was used
if(self.proto._properties.joins.indexOf(joinsName) < 0) return;
} else {
return;
}
// Call toJSON on each associated record
if(Array.isArray(self.object[association])) {
var records = [];
self.object[association].forEach(function(item) {
if(!hasOwnProperty(item, 'toJSON')) return;
records.push(item.toJSON());
});
self.object[association] = records;
return;
}
if(!hasOwnProperty(self.object[association].__proto__, 'toJSON')) return;
self.object[association] = self.object[association].toJSON();
});
};
/**
* Remove Non-Joined Associations
*
* @api private
*/
toObject.prototype.filterJoins = function() {
var attributes = this.context._attributes;
var properties = this.proto._properties;
for(var attribute in attributes) {
if(!hasOwnProperty(attributes[attribute], 'model') && !hasOwnProperty(attributes[attribute], 'collection')) continue;
// If no properties and a collection attribute, delete the association and return
if(!properties && hasOwnProperty(attributes[attribute], 'collection')) {
delete this.object[attribute];
continue;
}
// If showJoins is false remove the association object
if(properties && !properties.showJoins) {
// Don't delete belongs to keys
if(!attributes[attribute].model) delete this.object[attribute];
}
if(properties && properties.joins) {
// Build up a join key name based on the attribute's model/collection name
var joinsName = attribute;
if(attributes[attribute].model) joinsName = attributes[attribute].model.toLowerCase();
if(attributes[attribute].collection) joinsName = attributes[attribute].collection.toLowerCase();
if(properties.joins.indexOf(joinsName) < 0) {
// Don't delete belongs to keys
if(!attributes[attribute].model) delete this.object[attribute];
}
}
}
};
/**
* Filter Functions
*
* @api private
*/
toObject.prototype.filterFunctions = function() {
for(var key in this.object) {
if(typeof this.object[key] === 'function') {
delete this.object[key];
}
}
};
| JavaScript | 0 | @@ -575,16 +575,74 @@
proto;%0A%0A
+ // Hold joins used in the query%0A this.usedJoins = %5B%5D;%0A%0A
this.o
@@ -2723,19 +2723,8 @@
dle
-Belongs-To
Join
@@ -3052,33 +3052,34 @@
if(self.
-proto.association
+context._attribute
s%5Bassoci
@@ -3109,33 +3109,34 @@
= self.
-proto.association
+context._attribute
s%5Bassoci
@@ -3177,33 +3177,34 @@
if(self.
-proto.association
+context._attribute
s%5Bassoci
@@ -3239,33 +3239,34 @@
= self.
-proto.association
+context._attribute
s%5Bassoci
@@ -3395,24 +3395,121 @@
ame) %3C 0
-) return
+ && self.proto._properties.joins.indexOf(association) %3C 0) return;%0A self.usedJoins.push(association)
;%0A %7D
@@ -3743,16 +3743,26 @@
rty(item
+.__proto__
, 'toJSO
@@ -4886,362 +4886,48 @@
) %7B%0A
-%0A // Build up a join key name based on the attribute's model/collection name%0A var joinsName = attribute;%0A if(attributes%5Battribute%5D.model) joinsName = attributes%5Battribute%5D.model.toLowerCase();%0A if(attributes%5Battribute%5D.collection) joinsName = attributes%5Battribute%5D.collection.toLowerCase();%0A%0A if(properties.joins.indexOf(joinsNam
+ if(this.usedJoins.indexOf(attribut
e) %3C
|
f07c60613e7c5907e937fd821a61cc136d3f270e | Fix wait for socket test | test/lib/test-wait-for-socket.js | test/lib/test-wait-for-socket.js | var waitForSocket = require('../../lib/wait-for-socket');
describe('waitForSocket', function(){
before(function() {
// chill winston
winston.remove(winston.transports.Console);
});
after(function() {
winston.add(winston.transports.Console);
});
before(function () {
this.port = 65535;
});
beforeEach(function () {
this.mockSocket = new EventEmitter();
this.mockSocket.connect = sinon.spy();
this.mockSocket.setTimeout = sinon.spy();
});
describe('#connect', function() {
it('returns a promise for a connected socket', function () {
var waitFor = waitForSocket.create(this.port);
var promise = waitFor.connect();
assert.equal(promise.isPending(), true);
});
it('resolves the promise on connect', function () {
var waitFor = waitForSocket.create(this.port, this.mockSocket);
var promise = waitFor.connect();
this.mockSocket.emit('connect');
assert.equal(promise.isFulfilled(), true);
});
it('sets a timeout on the socket', function () {
this.mockSocket.setTimeout = sinon.spy();
waitForSocket.create(this.port, this.mockSocket);
assert(this.mockSocket.setTimeout.calledWith(2500));
});
it('tries again on failure', function () {
var clock = sinon.useFakeTimers(),
timeout = 10;
var waitFor = waitForSocket.create(this.port, this.mockSocket);
var promise = waitFor.connect();
this.mockSocket.emit('error');
clock.tick(timeout + 1);
assert.equal(this.mockSocket.connect.calledTwice, true);
this.mockSocket.emit('connect');
assert.equal(promise.isFulfilled(), true);
clock.restore();
});
});
describe('#_addHandlers()', function(){
it('should bind a socket to connect and error events', function(){
this.mockSocket.on = sinon.spy();
var waitFor = waitForSocket.create(this.port, this.mockSocket);
waitFor._addHandlers();
assert.equal(this.mockSocket.on.calledTwice, true);
assert.equal(this.mockSocket.on.calledWith('connect'), true);
assert.equal(this.mockSocket.on.calledWith('error'), true);
});
});
});
| JavaScript | 0.000001 | @@ -94,179 +94,8 @@
()%7B%0A
- before(function() %7B%0A // chill winston%0A winston.remove(winston.transports.Console);%0A %7D);%0A%0A after(function() %7B%0A winston.add(winston.transports.Console);%0A %7D);%0A%0A
be
@@ -1047,17 +1047,16 @@
%7D);%0A%0A
-%0A
it('
@@ -1157,16 +1157,18 @@
out = 10
+00
;%0A%0A
|
e28431b3a4252d02b7b487ae4b03668e1bd3950e | clean up | popup/popup-script.js | popup/popup-script.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/. */
let powerPara = document.getElementById("power");
let settings = document.getElementById("settings");
let powerBttn = document.querySelector("input[type=checkbox]");
let isAlive = window.localStorage.getItem("alive") || "true";
//**BootUp **
if(isAlive === "true"){
on();
}
else{
off();
}
//**Settings**
settings.onclick = function () {
browser.runtime.openOptionsPage();
}
//**Power**
powerBttn.onclick = function () {
if (powerBttn.checked) {
on();
browser.alarms.clearAll();
browser.alarms.create(
"",
{ periodInMinutes: parseInt(interval) }
);
}
else {
off();
browser.alarms.clearAll();
}
}
function on() {
powerBttn.checked = true;
window.localStorage.setItem("alive", "true");
powerPara.textContent = "ON";
browser.browserAction.setIcon({ path: "../icons/logo.svg" });
}
function off(params) {
powerBttn.checked = false;
window.localStorage.setItem("alive", "false");
powerPara.textContent = "OFF";
browser.browserAction.setIcon({ path: "../icons/logo-off.svg" });
} | JavaScript | 0.000001 | @@ -498,13 +498,8 @@
();%0A
- %0A
%7D%0A%0A/
|
4e17e8e9034541aefafc91ec396cf516d6cc27d6 | check for azure and check for value | env.js | env.js | 'use strict';
var env = { };
var crypto = require('crypto');
var consts = require('./lib/constants');
var fs = require('fs');
// Module to constrain all config and environment parsing to one spot.
function config ( ) {
/*
* First inspect a bunch of environment variables:
* * PORT - serve http on this port
* * MONGO_CONNECTION, CUSTOMCONNSTR_mongo - mongodb://... uri
* * CUSTOMCONNSTR_mongo_collection - name of mongo collection with "sgv" documents
* * CUSTOMCONNSTR_mongo_settings_collection - name of mongo collection to store configurable settings
* * API_SECRET - if defined, this passphrase is fed to a sha1 hash digest, the hex output is used to create a single-use token for API authorization
* * NIGHTSCOUT_STATIC_FILES - the "base directory" to use for serving
* static files over http. Default value is the included `static`
* directory.
*/
var software = require('./package.json');
var git = require('git-rev');
if (readENV('APPSETTING_ScmType') == readENV('ScmType')) {
env.head = require('./scm-commit-id.json');
console.log("SCM COMMIT ID", env.head);
} else {
git.short(function record_git_head (head) {
console.log("GIT HEAD", head);
env.head = head;
});
}
env.version = software.version;
env.name = software.name;
env.DISPLAY_UNITS = readENV('DISPLAY_UNITS', 'mg/dl');
env.PORT = readENV('PORT', 1337);
env.mongo = readENV('MONGO_CONNECTION') || readENV('MONGO') || readENV('MONGOLAB_URI');
env.mongo_collection = readENV('MONGO_COLLECTION', 'entries');
env.settings_collection = readENV('MONGO_SETTINGS_COLLECTION', 'settings');
env.treatments_collection = readENV('MONGO_TREATMENTS_COLLECTION', 'treatments');
env.profile_collection = readENV('MONGO_PROFILE_COLLECTION', 'profile');
env.devicestatus_collection = readENV('MONGO_DEVICESTATUS_COLLECTION', 'devicestatus');
env.enable = readENV('ENABLE');
env.SSL_KEY = readENV('SSL_KEY');
env.SSL_CERT = readENV('SSL_CERT');
env.SSL_CA = readENV('SSL_CA');
env.ssl = false;
if (env.SSL_KEY && env.SSL_CERT) {
env.ssl = {
key: fs.readFileSync(env.SSL_KEY)
, cert: fs.readFileSync(env.SSL_CERT)
};
if (env.SSL_CA) {
env.ca = fs.readFileSync(env.SSL_CA);
}
}
var shasum = crypto.createHash('sha1');
/////////////////////////////////////////////////////////////////
// A little ugly, but we don't want to read the secret into a var
/////////////////////////////////////////////////////////////////
var useSecret = (readENV('API_SECRET') && readENV('API_SECRET').length > 0);
env.api_secret = null;
// if a passphrase was provided, get the hex digest to mint a single token
if (useSecret) {
if (readENV('API_SECRET').length < consts.MIN_PASSPHRASE_LENGTH) {
var msg = ["API_SECRET should be at least", consts.MIN_PASSPHRASE_LENGTH, "characters"];
var err = new Error(msg.join(' '));
// console.error(err);
throw err;
process.exit(1);
}
shasum.update(readENV('API_SECRET'));
env.api_secret = shasum.digest('hex');
}
env.thresholds = {
bg_high: readIntENV('BG_HIGH', 260)
, bg_target_top: readIntENV('BG_TARGET_TOP', 180)
, bg_target_bottom: readIntENV('BG_TARGET_BOTTOM', 80)
, bg_low: readIntENV('BG_LOW', 55)
};
//NOTE: using +/- 1 here to make the thresholds look visibly wrong in the UI
// if all thresholds were set to the same value you should see 4 lines stacked right on top of each other
if (env.thresholds.bg_target_bottom >= env.thresholds.bg_target_top) {
console.warn('BG_TARGET_BOTTOM(' + env.thresholds.bg_target_bottom + ') was >= BG_TARGET_TOP(' + env.thresholds.bg_target_top + ')');
env.thresholds.bg_target_bottom = env.thresholds.bg_target_top - 1;
console.warn('BG_TARGET_BOTTOM is now ' + env.thresholds.bg_target_bottom);
}
if (env.thresholds.bg_target_top <= env.thresholds.bg_target_bottom) {
console.warn('BG_TARGET_TOP(' + env.thresholds.bg_target_top + ') was <= BG_TARGET_BOTTOM(' + env.thresholds.bg_target_bottom + ')');
env.thresholds.bg_target_top = env.thresholds.bg_target_bottom + 1;
console.warn('BG_TARGET_TOP is now ' + env.thresholds.bg_target_top);
}
if (env.thresholds.bg_low >= env.thresholds.bg_target_bottom) {
console.warn('BG_LOW(' + env.thresholds.bg_low + ') was >= BG_TARGET_BOTTOM(' + env.thresholds.bg_target_bottom + ')');
env.thresholds.bg_low = env.thresholds.bg_target_bottom - 1;
console.warn('BG_LOW is now ' + env.thresholds.bg_low);
}
if (env.thresholds.bg_high <= env.thresholds.bg_target_top) {
console.warn('BG_HIGH(' + env.thresholds.bg_high + ') was <= BG_TARGET_TOP(' + env.thresholds.bg_target_top + ')');
env.thresholds.bg_high = env.thresholds.bg_target_top + 1;
console.warn('BG_HIGH is now ' + env.thresholds.bg_high);
}
//if any of the BG_* thresholds are set, default to "simple" otherwise default to "predict" to preserve current behavior
var thresholdsSet = readIntENV('BG_HIGH') || readIntENV('BG_TARGET_TOP') || readIntENV('BG_TARGET_BOTTOM') || readIntENV('BG_LOW');
env.alarm_types = readENV('ALARM_TYPES') || (thresholdsSet ? "simple" : "predict");
// For pushing notifications to Pushover.
env.pushover_api_token = readENV('PUSHOVER_API_TOKEN');
env.pushover_user_key = readENV('PUSHOVER_USER_KEY') || readENV('PUSHOVER_GROUP_KEY');
// TODO: clean up a bit
// Some people prefer to use a json configuration file instead.
// This allows a provided json config to override environment variables
var DB = require('./database_configuration.json'),
DB_URL = DB.url ? DB.url : env.mongo,
DB_COLLECTION = DB.collection ? DB.collection : env.mongo_collection,
DB_SETTINGS_COLLECTION = DB.settings_collection ? DB.settings_collection : env.settings_collection;
env.mongo = DB_URL;
env.mongo_collection = DB_COLLECTION;
env.settings_collection = DB_SETTINGS_COLLECTION;
env.static_files = readENV('NIGHTSCOUT_STATIC_FILES', __dirname + '/static/');
return env;
}
function readIntENV(varName, defaultValue) {
return parseInt(readENV(varName)) || defaultValue;
}
function readENV(varName, defaultValue) {
//for some reason Azure uses this prefix, maybe there is a good reason
var value = process.env['CUSTOMCONNSTR_' + varName]
|| process.env['CUSTOMCONNSTR_' + varName.toLowerCase()]
|| process.env[varName]
|| process.env[varName.toLowerCase()];
return value || defaultValue;
}
module.exports = config;
| JavaScript | 0 | @@ -1036,16 +1036,50 @@
cmType')
+ && readENV('ScmType') == 'GitHub'
) %7B%0A
|
ba70555a2dab6f162b82d754a9e956e2a67eb803 | remove loging | eq3.js | eq3.js | 'use strict'
const eq3device = require('./lib/eq3device')
module.exports = function(RED) {
function eq3(config) {
var node = this;
RED.nodes.createNode(this, config);
this.serverConfig = RED.nodes.getNode(config.server);
eq3device.discoverByAddress(config.eq3device ,function(device) {
node.device = device
})
setInterval(() => {
if(node.device) {
node.status({fill:"green",shape:"ring",text:"connected"});
} else {
node.status({fill:"red",shape:"ring",text:"disconnected"});
}
}, 10000)
node.on('input', function(msg) {
var device = node.device
var setCommand = function() {
setTimeout(() => {
device.getInfo()
.then(a => {
msg.payload = a
node.send(msg)
})
}, 2000)
if (typeof msg.payload !== 'object') return
switch (msg.payload.setState) {
case 'on':
device.turnOn()
break;
case 'off':
device.turnOff()
break;
case 'manual':
device.manualMode()
break;
case 'auto':
device.automaticMode()
break;
default:
break;
}
switch (msg.payload.boost) {
case '0':
device.setBoost(false)
break;
case '1':
device.setBoost(true)
break;
default:
break;
}
console.log(msg.payload.setTemperature)
if (msg.payload.setTemperature)
device.setTemperature(msg.payload.setTemperature)
}
if(!node.device.connectedAndSetUp)
node.device.connectAndSetup()
.then(() => setCommand())
else
setCommand()
});
}
RED.nodes.registerType("eq3-bluetooth", eq3);
}
| JavaScript | 0.000001 | @@ -1495,56 +1495,8 @@
%7D%0A%0A
- console.log(msg.payload.setTemperature)%0A
|
6478e252063641a2b78e157e6beddf3370aa58f8 | add device | eq3.js | eq3.js | 'use strict'
const eq3device = require('./lib/eq3device')
const devices = {}
module.exports = function(RED) {
RED.httpNode.get('/eq3', function(req,res) {
res.send(Object.keys(devices))
});
eq3device.discover((device) => {
device.connectAndSetUp()
.then(() => {
devices[device.id] = device
})
})
function eq3in(config) {
var node = this;
RED.nodes.createNode(this, config);
this.serverConfig = RED.nodes.getNode(config.server);
setInterval(() => {
node.eq3BleDevice = devices[config.eq3devicein]
if(this.eq3BleDevice) {
node.status({fill:"green",shape:"ring",text:"connected"});
} else {
node.status({fill:"red",shape:"ring",text:"disconnected"});
}
}, 10000)
node.on('input', function(msg) {
if(msg.payload.targetTemperature) {
this.eq3BleDevice.setTemperature(msg.payload.targetTemperature)
}
if(msg.payload.targetHeatingCoolingState) {
if (msg.payload.targetHeatingCoolingState === 0)
this.eq3BleDevice.turnOn()
if (msg.payload.targetHeatingCoolingState === 1)
this.eq3BleDevice.turnOff()
}
})
}
RED.nodes.registerType("eq3-bluetooth in", eq3in);
function eq3out(config) {
var node = this;
RED.nodes.createNode(this, config);
this.serverConfig = RED.nodes.getNode(config.server);
this.eq3BleDeviceId = config.eq3deviceout
setInterval(() => {
node.eq3BleDevice = devices[node.eq3BleDeviceId]
if(this.eq3BleDevice) {
node.status({fill:"green",shape:"ring",text:"found"});
} else {
node.status({fill:"red",shape:"ring",text:"not found"});
}
}, 2000)
node.on('input', function(msg) {
node.eq3BleDevice.getInfo((data) => {
msg.payload = data
node.send(msg)
})
});
}
RED.nodes.registerType("eq3-bluetooth out", eq3out);
}
| JavaScript | 0.000001 | @@ -263,28 +263,8 @@
p()%0A
- .then(() =%3E %7B%0A
@@ -291,23 +291,16 @@
device%0A
- %7D)%0A
%7D)%0A%0A
|
261b4a90a24506649e3e480f812f25c8f3c12e68 | Fix date offset issue. | assets/js/modules/analytics/components/module/ModulePopularPagesWidget/index.js | assets/js/modules/analytics/components/module/ModulePopularPagesWidget/index.js | /**
* ModulePopularPagesWidget component.
*
* Site Kit by Google, Copyright 2021 Google LLC
*
* 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
*
* https://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.
*/
/**
* External dependencies
*/
import PropTypes from 'prop-types';
/**
* Internal dependencies
*/
import Data from 'googlesitekit-data';
import { CORE_USER } from '../../../../../googlesitekit/datastore/user/constants';
import { MODULES_ANALYTICS } from '../../../datastore/constants';
import PreviewTable from '../../../../../components/PreviewTable';
import Header from './Header';
import Table from './Table';
import Footer from './Footer';
const { useSelect } = Data;
export default function ModulePopularPagesWidget( { Widget, WidgetReportError } ) {
const { startDate, endDate } = useSelect( ( select ) => select( CORE_USER ).getDateRangeDates() );
const args = {
startDate,
endDate,
dimensions: [
'ga:pageTitle',
'ga:pagePath',
],
metrics: [
{
expression: 'ga:pageviews',
alias: 'Pageviews',
},
{
expression: 'ga:uniquePageviews',
alias: 'Unique Pageviews',
},
{
expression: 'ga:bounceRate',
alias: 'Bounce rate',
},
],
orderby: [
{
fieldName: 'ga:pageviews',
sortOrder: 'DESCENDING',
},
],
limit: 10,
};
const report = useSelect( ( select ) => select( MODULES_ANALYTICS ).getReport( args ) );
const loaded = useSelect( ( select ) => select( MODULES_ANALYTICS ).hasFinishedResolution( 'getReport', [ args ] ) );
const error = useSelect( ( select ) => select( MODULES_ANALYTICS ).getErrorForSelector( 'getReport', [ args ] ) );
if ( error ) {
return <WidgetReportError error={ error } />;
}
return (
<Widget
Header={ Header }
Footer={ Footer }
noPadding
>
{ ! loaded && (
<PreviewTable padding />
) }
{ loaded && (
<Table report={ report } />
) }
</Widget>
);
}
ModulePopularPagesWidget.propTypes = {
Widget: PropTypes.elementType.isRequired,
WidgetReportError: PropTypes.elementType.isRequired,
};
| JavaScript | 0.000001 | @@ -885,16 +885,35 @@
import %7B
+ DATE_RANGE_OFFSET,
MODULES
@@ -1328,16 +1328,55 @@
geDates(
+ %7B%0A%09%09offsetDays: DATE_RANGE_OFFSET,%0A%09%7D
) );%0A%0A%09c
|
adf8cf4de707ce8898dafe15e8dec67bbeba34da | add lazy load html | lml.js | lml.js | /**
* LMLJS Framework
* Copyright (c) 2014 http://lmlphp.com All rights reserved.
* Licensed ( http://mit-license.org/ )
* Author: leiminglin <leiminglin@126.com>
*
* A lovely javascript framework.
*
* $id: $
*
*/
(function(win, doc, undf){
var deferred = {};
deferred.queue = [];
deferred.promise = function(){
if( deferred.queue.length ){
deferred.queue.shift()();
}
};
deferred.then = function(e){
deferred.queue.push(e);
};
function getElementViewTop(element){
var actualTop = element.offsetTop
,offsetParentElement = element.offsetParent;
if( offsetParentElement == null && element.parentNode ){
/* when style display is none */
var parentNode = element.parentNode;
while( offsetParentElement == null ){
offsetParentElement = parentNode.offsetParent;
parentNode = parentNode.parentNode;
if( !parentNode ){
break;
}
}
}
while ( offsetParentElement !== null /* document.body */ ){
actualTop += (offsetParentElement.offsetTop+offsetParentElement.clientTop);
offsetParentElement = offsetParentElement.offsetParent;
}
var elementScrollTop = document.documentElement.scrollTop
? document.documentElement.scrollTop : document.body.scrollTop;
return actualTop - elementScrollTop;
}
function getViewport(){
if( document.compatMode == "BackCompat" ){
return { width:document.body.clientWidth,
height:document.body.clientHeight }
}else{
return { width:document.documentElement.clientWidth,
height:document.documentElement.clientHeight }
}
}
/**
* Lazy load img
*/
deferred.then(function(){
var i, length, src, m = doc.getElementsByTagName('IMG'),
viewport=getViewport(), count=0;
window.onresize = function(){
viewport = getViewport();
};
var loadImg = function(){
if( count >= m.length ){
/* remove event */
if( window.addEventListener ){
document.removeEventListener( 'scroll', loadImg, false );
}else if( window.attachEvent ){
window.detachEvent(event, loadImg);
}
return;
}
for(i=0,j=m.length; i<j; i++){
if( m[i].getAttribute('src') ){
continue;
}
var viewtop = getElementViewTop(m[i])
,imgHeight = m[i].getAttribute('height')||0;
if( viewtop>=-imgHeight && viewtop < viewport.height
&& (src=m[i].getAttribute('osrc')) ){
m[i].setAttribute('src',src);
m[i].onerror=function(){
if( src=this.getAttribute('osrc-bak') ){
this.setAttribute('src',src);
this.onerror=null;
}
};
m[i].onload = function(){
count++;
}
}
}
};
if( window.addEventListener ){
document.addEventListener( 'scroll', loadImg, false );
}else if( window.attachEvent ){
window.attachEvent("onscroll", loadImg);
}
loadImg();
deferred.promise();
});
if( typeof document.getElementsByClassName != 'function' ){
document.getElementsByClassName = function( classname ){
var d = doc, e = d.getElementsByTagName('*'),
c = new RegExp('\\b'+classname+'\\b'), r = [];
for( var i=0,l=e.length; i<l; i++ ){
var classname = e[i].className;
if( c.test(classname) ){
r.push( e[i] );
}
}
return r;
}
}
var addLazyCss = function( css ) {
var style = doc.createElement('style');
style.type='text/css';
if (style.styleSheet) {
style.styleSheet.cssText = css;
}else{
style.innerHTML = css;
}
doc.getElementsByTagName('head')[0].appendChild(style);
};
/**
* Lazy load CSS
*/
deferred.then( function(){
var e = document.getElementsByClassName('lazyCss');
for( var i=0; i<e.length; i++ ) {
addLazyCss( e[i].value || e[i].innerHTML );
}
deferred.promise();
});
var loadJs = function( src, callback, script, stag ) {
script = doc.createElement('script'),
stag = doc.getElementsByTagName('script')[0];
script.async = 1;
script.src = src;
try{
stag.parentNode.insertBefore( script, stag );
callback = callback || function(){
deferred.promise();
};
if( window.addEventListener ){
script.addEventListener( 'load', callback, false );
}else if( window.attachEvent ){
script.onreadystatechange = function(){
if(this.readyState.match(/loaded|complete/i)){
callback();
}
}
}else{
script.onload = function(){
callback();
}
}
}catch(e){
callback();
}
};
var lml = {};
lml.deferred = deferred;
lml.loadJs = loadJs;
win.lml = lml;
})(window, document);
| JavaScript | 0.000002 | @@ -3672,16 +3672,371 @@
();%0A%09%7D);
+%0A%09%0A%09/**%0A%09 * Lazy load HTML%0A%09 */%0A%09deferred.then( function()%7B%0A%09%09var e = document.getElementsByClassName('lazyHtml');%0A%09%09for( var i=0; i%3Ce.length; i++ ) %7B%0A%09%09%09if(e%5Bi%5D.tagName == 'TEXTAREA')%7B%0A%09%09%09%09var wrapdiv = document.createElement('DIV');%0A%09%09%09%09wrapdiv.innerHTML = e%5Bi%5D.value;%0A%09%09%09%09e%5Bi%5D.parentNode.insertBefore(wrapdiv, e%5Bi%5D);%0A%09%09%09%7D%0A%09%09%7D%0A%09%09deferred.promise();%0A%09%7D);
%0A%0A%09var l
|
3d1b561fe060994345de22cca17b87a5534a5067 | Add a marker for a point in Flatiron and highlight the neighborhood. | map.js | map.js | var map = L.mapbox.map('map').setView([40.775,-73.98], 12);
// Set base style of vector data
function style(feature) {
return {
weight: 0,
fillOpacity: 0.5,
fillColor: '#FFEDA0'
};
}
// Set hover colors
function highlightFeature(e) {
var layer = e.target;
layer.setStyle({
weight: 10,
opacity: 1,
color: '#09F',
dashArray: '3',
fillOpacity: 0.7,
fillColor: '#FEB24C'
});
}
// A function to reset the colors when a neighborhood is not longer 'hovered'
function resetHighlight(e) {
geojson.resetStyle(e.target);
}
// Tell MapBox.js what functions to call when mousing over and out of a neighborhood
function onEachFeature(feature, layer) {
layer.on({
mouseover: highlightFeature,
mouseout: resetHighlight
});
}
// Add vector data to map
geojson = L.geoJson(neighborhoods, {
style: style,
onEachFeature: onEachFeature
}).addTo(map);
// Here is where the magic happens: Manipulate the z-index of tile layers,
// this makes sure our vector data shows up above the background map and
// under roads and labels.
var topPane = map._createPane('leaflet-top-pane', map.getPanes().mapPane);
var topLayer = L.mapbox.tileLayer('bobbysud.map-3inxc2p4').addTo(map);
topPane.appendChild(topLayer.getContainer());
topLayer.setZIndex(7);
console.log(leafletPip.pointInLayer([40.744034,-73.99624], geojson));
| JavaScript | 0 | @@ -202,28 +202,8 @@
%0A%7D%0A%0A
-// Set hover colors%0A
func
@@ -228,38 +228,16 @@
ure(
-e) %7B%0A var layer = e.target;
+layer) %7B
%0A
@@ -254,16 +254,20 @@
Style(%7B%0A
+
weig
@@ -278,16 +278,20 @@
10,%0A
+
+
opacity:
@@ -294,16 +294,20 @@
ity: 1,%0A
+
colo
@@ -317,16 +317,20 @@
'#09F',%0A
+
dash
@@ -341,16 +341,20 @@
y: '3',%0A
+
fill
@@ -367,16 +367,20 @@
y: 0.7,%0A
+
fill
@@ -403,24 +403,184 @@
%0A %7D);%0A%7D%0A%0A
+function resetHighlight(layer) %7B%0A geojson.resetStyle(layer);%0A%7D%0A%0A// Set hover colors%0Afunction highlightFeatureHandler(e) %7B%0A highlightFeature(e.target);%0A%7D%0A%0A
// A functio
@@ -668,16 +668,23 @@
ighlight
+Handler
(e) %7B%0A
@@ -685,34 +685,30 @@
) %7B%0A
-geojson.resetStyle
+resetHighlight
(e.targe
@@ -890,16 +890,23 @@
tFeature
+Handler
,%0A
@@ -931,16 +931,23 @@
ighlight
+Handler
%0A %7D);
@@ -1475,75 +1475,783 @@
);%0A%0A
-console.log(leafletPip.pointInLayer(%5B40.744034,-73.99624%5D, geojson));%0A%0A
+%0Afunction layerFromLatLng(latLng) %7B%0A return leafletPip.pointInLayer(latLng, geojson)%5B0%5D;%0A%7D%0A%0Afunction neighborhoodFromPoint(point) %7B%0A return layerFromLatLng(L.latLng(point)).feature.properties.NTAName;%0A%7D%0A%0Avar ll = L.latLng(40.744034,-73.99624);%0A%0AL.mapbox.markerLayer(%7B%0A // this feature is in the GeoJSON format: see geojson.org%0A // for the full specification%0A type: 'Feature',%0A geometry: %7B%0A type: 'Point',%0A // coordinates here are in longitude, latitude order because%0A // x, y is the standard for GeoJSON and many formats%0A coordinates: %5B-73.99624,40.744034%5D%0A %7D,%0A properties: %7B%0A 'marker-size': 'small',%0A 'marker-color': '#00a'%0A %7D%0A%7D).addTo(map);%0A%0AhighlightFeature(layerFromLatLng(L.latLng(40.744034, -73.99634)));
|
091cecaf4331aa00fc12cdcf46fd34543a0f233a | Add class iterator support | src.js | src.js | (function() {
function dup(pairs){
var a=JSON.parse(JSON.stringify(pairs));
return a;
}
function pullData() {
this.data = {};
this.pull = function(name) {
return this.data[name];
}
}
function iterator_former(fn) {
this.fn = fn;
this.data = new pullData();
this.yield = function(pairs) {
this.data.data = dup(pairs);
return this.fn.call(this.data);
}
}
function iterator(fn){
return function(args,funct){
var block=new iterator_former(funct);
fn.call(block,args);
}
}
window.iterator=function(fn){
return iterator(fn);
}
})();
| JavaScript | 0.000001 | @@ -223,26 +223,25 @@
ormer(fn
+,x
) %7B%0A%09%09
-this
+x
.fn = fn
@@ -244,20 +244,17 @@
= fn;%0A%09%09
-this
+x
.data =
@@ -271,20 +271,17 @@
ta();%0A%09%09
-this
+x
.yield =
@@ -366,24 +366,36 @@
.data);%0A%09%09%7D%0A
+%09%09return x;%0A
%09%7D%0A%0A%09functio
@@ -454,20 +454,16 @@
r block=
-new
iterator
@@ -473,20 +473,42 @@
rmer
-(funct);%0A%09%09%09
+.call(this,funct,this);%0A%09%09%09return
fn.c
@@ -589,14 +589,174 @@
fn);%0A%09%7D%0A
+%09%0A%09Function.prototype.iterator=function(fn,name)%7B%0A%09%09this.prototype%5Bname%5D=function(args,funct)%7B%0A%09%09%09var a=iterator(fn);%0A%09%09%09return a.call(this,args,funct);%0A%09%09%7D%0A%09%7D%0A
%7D)();%0A
|
02f939d7dcb9b07b7bed0b194d85e2aa4eefbad8 | Update GraticuleLayerSpec.js | test/mapboxgl/overlay/GraticuleLayerSpec.js | test/mapboxgl/overlay/GraticuleLayerSpec.js | import { GraticuleLayer } from '../../../src/mapboxgl/overlay/GraticuleLayer';
import mapboxgl from 'mapbox-gl';
import { Feature } from '@supermap/iclient-common';
var url = GlobeParameter.ChinaURL + '/zxyTileImage.png?z={z}&x={x}&y={y}';
describe('mapboxgl_GraticuleLayer', () => {
var originalTimeout;
var testDiv, map, graticuleLayer;
beforeAll(() => {
testDiv = window.document.createElement('div');
testDiv.setAttribute('id', 'map');
testDiv.style.styleFloat = 'left';
testDiv.style.marginLeft = '8px';
testDiv.style.marginTop = '50px';
testDiv.style.width = '500px';
testDiv.style.height = '500px';
window.document.body.appendChild(testDiv);
map = new mapboxgl.Map({
container: 'map',
style: {
version: 8,
sources: {
'raster-tiles': {
type: 'raster',
tiles: [url],
tileSize: 256
}
},
layers: [
{
id: 'simple-tiles',
type: 'raster',
source: 'raster-tiles',
minzoom: 0,
maxzoom: 22
}
]
},
center: [112, 37.94],
zoom: 3
});
});
beforeEach(() => {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 50000;
if (!map.getLayer('graticuleLayer_1')) {
graticuleLayer = new GraticuleLayer(map);
graticuleLayer.onAdd(map);
}
});
afterEach(() => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
});
afterAll(() => {
if (map.getLayer('graticuleLayer_1')) {
map.removeLayer('graticuleLayer_1');
}
document.body.removeChild(testDiv);
map = null;
});
it('_initialize', done => {
setTimeout(() => {
expect(graticuleLayer).not.toBeNull();
expect(graticuleLayer.canvas).not.toBeNull();
expect(graticuleLayer.map).not.toBeNull();
expect(graticuleLayer.mapContainer).not.toBeNull();
expect(graticuleLayer.features).not.toBeNull();
expect(graticuleLayer.options).not.toBeNull();
done();
}, 6000);
});
it('setVisibility', () => {
graticuleLayer.setVisibility(false);
var visible = map.getLayoutProperty('graticuleLayer_1', 'visibility');
expect(visible).toBe('none');
graticuleLayer.setVisibility(true);
visible = map.getLayoutProperty('graticuleLayer_1', 'visibility');
expect(visible).toBe('visible');
});
it('setMinZoom', () => {
graticuleLayer.setMinZoom(0);
expect(graticuleLayer.options.minZoom).toEqual(0);
});
it('setMaxZoom', () => {
graticuleLayer.setMaxZoom(10);
expect(graticuleLayer.options.maxZoom).toEqual(10);
});
it('setShowLabel', () => {
graticuleLayer.setShowLabel(false);
expect(graticuleLayer.options.showLabel).toEqual(false);
});
it('setExtent', () => {
graticuleLayer.setExtent([
[0, 0],
[50, 50]
]);
expect(graticuleLayer.options.extent[0]).toEqual(0);
expect(graticuleLayer.options.extent[3]).toEqual(50);
});
it('setStrokeStyle', () => {
graticuleLayer.setStrokeStyle({ lineWidth: 3 });
expect(graticuleLayer.options.strokeStyle.lineWidth).toEqual(3);
});
it('setLngLabelStyle', () => {
graticuleLayer.setLngLabelStyle({ textSize: '12px' });
expect(graticuleLayer.options.lngLabelStyle.textSize).toEqual('12px');
});
it('setLatLabelStyle', () => {
graticuleLayer.setLatLabelStyle({ textSize: '12px' });
expect(graticuleLayer.options.latLabelStyle.textSize).toEqual('12px');
});
it('setIntervals', () => {
graticuleLayer.setIntervals(5);
expect(graticuleLayer.options.interval).toEqual(5);
});
it('_calcInterval', () => {
const interval = map.getZoom();
const calcInterval = map => {
return map.getZoom();
};
graticuleLayer._calcInterval(calcInterval);
expect(graticuleLayer._currLngInterval).toBe(interval);
});
it('_getLatPoints', () => {
const features = [
{
type: 'Feature',
geometry: {
coordinates: [
[160, 80],
[180, 80]
],
type: 'LineString'
}
}
];
const points = graticuleLayer._getLatPoints([170, 180], '', 180, features);
expect(points[0][0]).toEqual(180);
expect(points[0][1]).toEqual(80);
});
it('removeFromMap', () => {
graticuleLayer.removeFromMap();
expect(graticuleLayer.canvas).toBeNull();
});
});
| JavaScript | 0 | @@ -1664,19 +1664,45 @@
leLayer(
-map
+%7BlayerID :'graticuleLayer_1'%7D
);%0A
|
fa14d066dc97c24f329cea0cc83a6559039285c2 | Extend clearing of jasmine noise to jessie/jasmine.js | lib/jessie/jasmine.js | lib/jessie/jasmine.js | // Great trick by mhevery
global.window = {
setTimeout: setTimeout,
clearTimeout: clearTimeout,
setInterval: setInterval,
clearInterval: clearInterval
};
var filename = __dirname + '/../../vendor/jasmine.js';
var src = require('fs').readFileSync(__dirname + '/../../vendor/jasmine.js');
// Load up jasmine
require('vm').runInThisContext(src + "\njasmine;", filename);
// Remove the global window to not pollute the global namespace
delete global.window
// Extend the fail to extract the proper stacktrace
jasmine.Spec.prototype.fail = function (e) {
var expectationResult = new jasmine.ExpectationResult({
passed: false,
message: e ? jasmine.util.formatException(e) : 'Exception'
});
// Extract the stacktrace and remove the jasmine noise
expectationResult.stacktrace = []
var parts = e.stack.split(/\n\s+/)
expectationResult.stacktrace.push(parts.shift())
var regex = /vendor\/jasmine\.js:\d+:\d+\)*/
for (var i = 0, len = parts.length; i < len; i++) {
var line = parts[i]
if (regex.test(line)) continue
expectationResult.stacktrace.push(line)
}
expectationResult.stacktrace = expectationResult.stacktrace
this.results_.addResult(expectationResult);
};
// Modify iterateObject to skip should_ properties
jasmine.PrettyPrinter.prototype.iterateObject = function(obj, fn) {
var should_regex = /should_\w+/
for (var property in obj) {
if (property == '__Jasmine_been_here_before__') continue;
if (should_regex.test(property)) continue;
fn(property, obj.__lookupGetter__ ? (obj.__lookupGetter__(property) != null) : false);
}
};
// Add missing reportSuiteStarting to Suite
jasmine.Suite.prototype.execute = function(onComplete) {
this.env.reporter.reportSuiteStarting(this);
var self = this;
this.queue.start(function () {
self.finish(onComplete);
});
}; | JavaScript | 0.000005 | @@ -904,22 +904,31 @@
egex = /
+(
vendor
+%7Cjessie)
%5C/jasmin
|
8d202e481bc623f839a3566a3abab7528909c9e3 | fix aspect's select_all deselect_all | app/assets/javascripts/app/views/aspects_list_view.js | app/assets/javascripts/app/views/aspects_list_view.js | app.views.AspectsList = app.views.Base.extend({
templateName: 'aspects-list',
el: '#aspects_list',
events: {
'click .toggle_selector' : 'toggleAll'
},
postRenderTemplate: function() {
this.collection.each(this.appendAspect, this);
this.$('a[rel*=facebox]').facebox();
},
appendAspect: function(aspect) {
$("#aspects_list > *:last").before(new app.views.Aspect({
model: aspect, attributes: {'data-aspect_id': aspect.get('id')}
}).render().el);
},
toggleAll: function(evt){
if (evt) { evt.preventDefault(); };
if (this.collection.allSelected()) {
this.collection.deselectAll();
this.$('li:not(:last)').removeClass("active");
} else {
this.collection.selectAll();
this.$('li:not(:last)').addClass("active");
}
this.toggleSelector();
app.router.aspects_stream();
},
toggleSelector: function(){
var selector = this.$('a.toggle_selector');
if (this.collection.allSelected()) {
selector.text(Diaspora.I18n.t('aspect_navigation.deselect_all'));
} else {
selector.text(Diaspora.I18n.t('aspect_navigation.select_all'));
}
}
})
| JavaScript | 0.000005 | @@ -159,16 +159,109 @@
'%0A %7D,%0A%0A
+ initialize: function()%7B%0A this.collection.on('change', this.toggleSelector, this);%0A %7D,%0A%0A
postRe
@@ -375,24 +375,51 @@
.facebox();%0A
+ this.toggleSelector();%0A
%7D,%0A%0A appe
|
00f83b17b7bf6d1f7f5494b01440446d5fc21473 | remove console log statement in logicadBidAdapter unit tests (#4021) | test/spec/modules/logicadBidAdapter_spec.js | test/spec/modules/logicadBidAdapter_spec.js | import {expect} from 'chai';
import {spec} from '../../../modules/logicadBidAdapter';
import * as utils from 'src/utils';
describe('LogicadAdapter', function () {
const bidRequests = [{
bidder: 'logicad',
bidId: '51ef8751f9aead',
params: {
tid: 'PJ2P',
page: 'http://www.logicad.com/'
},
adUnitCode: 'div-gpt-ad-1460505748561-0',
transactionId: 'd7b773de-ceaa-484d-89ca-d9f51b8d61ec',
sizes: [[300, 250], [300, 600]],
bidderRequestId: '418b37f85e772c',
auctionId: '18fd8b8b0bd757',
mediaTypes: {
banner: {
sizes: [[300, 250], [300, 600]]
}
}
}];
const bidderRequest = {
refererInfo: {
referer: 'fakeReferer',
reachedTop: true,
numIframes: 1,
stack: []
},
auctionStart: 1563337198010
};
const serverResponse = {
body: {
seatbid:
[{
bid: {
requestId: '51ef8751f9aead',
cpm: 101.0234,
width: 300,
height: 250,
creativeId: '2019',
currency: 'JPY',
netRevenue: true,
ttl: 60,
ad: '<div>TEST</div>'
}
}],
userSync: {
type: 'image',
url: 'https://cr-p31.ladsp.jp/cookiesender/31'
}
}
};
describe('isBidRequestValid', function () {
it('should return true if the tid parameter is present', function () {
expect(spec.isBidRequestValid(bidRequests[0])).to.be.true;
});
it('should return false if the tid parameter is not present', function () {
let bidRequest = utils.deepClone(bidRequests[0]);
delete bidRequest.params.tid;
expect(spec.isBidRequestValid(bidRequest)).to.be.false;
});
it('should return false if the params object is not present', function () {
let bidRequest = utils.deepClone(bidRequests);
delete bidRequest[0].params;
expect(spec.isBidRequestValid(bidRequest)).to.be.false;
});
});
describe('buildRequests', function () {
it('should generate a valid single POST request for multiple bid requests', function () {
const request = spec.buildRequests(bidRequests, bidderRequest)[0];
expect(request.method).to.equal('POST');
expect(request.url).to.equal('https://pb.ladsp.com/adrequest/prebid');
expect(request.data).to.exist;
});
});
describe('interpretResponse', function () {
it('should return an empty array if an invalid response is passed', function () {
const interpretedResponse = spec.interpretResponse({}, {});
expect(interpretedResponse).to.be.an('array').that.is.empty;
});
it('should return valid response when passed valid server response', function () {
const request = spec.buildRequests(bidRequests, bidderRequest)[0];
const interpretedResponse = spec.interpretResponse(serverResponse, request);
expect(interpretedResponse).to.have.lengthOf(1);
expect(interpretedResponse[0].requestId).to.equal(serverResponse.body.seatbid[0].bid.requestId);
expect(interpretedResponse[0].cpm).to.equal(serverResponse.body.seatbid[0].bid.cpm);
expect(interpretedResponse[0].width).to.equal(serverResponse.body.seatbid[0].bid.width);
expect(interpretedResponse[0].height).to.equal(serverResponse.body.seatbid[0].bid.height);
expect(interpretedResponse[0].creativeId).to.equal(serverResponse.body.seatbid[0].bid.creativeId);
expect(interpretedResponse[0].currency).to.equal(serverResponse.body.seatbid[0].bid.currency);
expect(interpretedResponse[0].netRevenue).to.equal(serverResponse.body.seatbid[0].bid.netRevenue);
expect(interpretedResponse[0].ad).to.equal(serverResponse.body.seatbid[0].bid.ad);
expect(interpretedResponse[0].ttl).to.equal(serverResponse.body.seatbid[0].bid.ttl);
});
});
describe('getUserSyncs', function () {
it('should perform usersync', function () {
let syncs = spec.getUserSyncs({pixelEnabled: false}, [serverResponse]);
expect(syncs).to.have.length(0);
console.log(serverResponse);
syncs = spec.getUserSyncs({pixelEnabled: true}, [serverResponse]);
expect(syncs).to.have.length(1);
expect(syncs[0]).to.have.property('type', 'image');
expect(syncs[0]).to.have.property('url', 'https://cr-p31.ladsp.jp/cookiesender/31');
});
});
});
| JavaScript | 0 | @@ -4029,42 +4029,8 @@
0);%0A
- console.log(serverResponse);
%0A
|
f2869aeb8de2832f071fe614ba0e692988558686 | use getInstallments to get the correct section of credit_card | app/assets/javascripts/catarse_pagarme/credit_card.js | app/assets/javascripts/catarse_pagarme/credit_card.js | App.views.PagarmeForm.addChild('PaymentCard', {
el: '#payment_type_credit_card_section',
events: {
'keyup input[type="text"]' : 'creditCardInputValidator',
'keyup #payment_card_number' : 'onKeyupPaymentCardNumber',
'click input#credit_card_submit' : 'onSubmit',
'click a.use_another-card': 'showCreditCardForm'
},
activate: function(options){
var that = this;
this.pagarmeForm = this.parent;
this.$('input#payment_card_date').mask('99/99');
},
showCreditCardForm: function(e) {
var that = this;
e.preventDefault();
that.$('ul.my_credit_cards').hide();
that.$('a.use_another-card ').hide();
that.$('.type_card_data').show();
that.$('.save_card').show();
$.each(that.$('.my_credit_cards input:radio[name=payment_subscription_card]'), function(i, item) {
$(item).prop('checked', false);
});
},
getUrl: function(){
var that = this;
var url = '';
if(that.$('input#payment_save_card').prop('checked') || that.hasSelectedSomeCard()) {
url = '/payment/pagarme/'+that.parent.contributionId+'/pay_with_subscription';
} else {
url = '/payment/pagarme/'+that.parent.contributionId+'/pay_credit_card';
}
return url;
},
getAjaxType: function() {
var type = 'POST';
if(this.hasSelectedSomeCard()) {
type = 'PUT'
}
return type;
},
selectedCard: function() {
return this.$('.my_credit_cards input:radio[name=payment_subscription_card]:checked');
},
hasSelectedSomeCard: function() {
return this.selectedCard().length > 0;
},
getPaymentData: function() {
var data = {};
if(this.hasSelectedSomeCard()) {
data = {
subscription_id: this.selectedCard().val(),
payment_card_installments: this.$('.my_credit_cards select#payment_card_installments').val()
}
} else {
data = {
payment_card_number: this.$('input#payment_card_number').val(),
payment_card_name: this.$('input#payment_card_name').val(),
payment_card_date: this.$('input#payment_card_date').val(),
payment_card_source: this.$('input#payment_card_source').val(),
payment_card_installments: this.$('select#payment_card_installments').val()
}
}
return data;
},
onSubmit: function(e) {
var that = this;
e.preventDefault();
$(e.currentTarget).hide();
that.parent.loader.show();
$.ajax({
type: that.getAjaxType(),
url: that.getUrl(),
data: that.getPaymentData(),
success: function(response){
that.parent.loader.hide();
if(response.payment_status == 'failed'){
that.parent.message.find('p').html(response.message);
that.parent.message.fadeIn('fast')
$(e.currentTarget).show();
} else {
var thank_you = $('#project_review').data('thank-you-path');
if(thank_you){
location.href = thank_you;
} else {
location.href = '/';
}
}
}
});
},
onKeyupPaymentCardNumber: function(e){
this.$('input#payment_card_flag').val(this.getCardFlag($(e.currentTarget).val()))
},
getCardFlag: function(number) {
var cc = (number + '').replace(/\s/g, ''); //remove space
if ((/^(34|37)/).test(cc) && cc.length == 15) {
return 'AmericanExpress'; //AMEX begins with 34 or 37, and length is 15.
} else if ((/^(51|52|53|54|55)/).test(cc) && cc.length == 16) {
return 'Mastercard'; //MasterCard beigins with 51-55, and length is 16.
} else if ((/^(4)/).test(cc) && (cc.length == 13 || cc.length == 16)) {
return 'Visa'; //VISA begins with 4, and length is 13 or 16.
} else if ((/^(300|301|302|303|304|305|36|38)/).test(cc) && cc.length == 14) {
return 'Diners'; //Diners Club begins with 300-305 or 36 or 38, and length is 14.
} else if ((/^(38)/).test(cc) && cc.length == 19) {
return 'Hipercard';
}
return 'Desconhecido';
}
});
| JavaScript | 0 | @@ -1775,74 +1775,25 @@
his.
-$('.my_credit_cards select#payment_card_installments').val()%0A
+getInstallments()
%7D%0A
@@ -2139,19 +2139,179 @@
s: this.
-$('
+getInstallments()%0A %7D%0A %7D%0A%0A return data;%0A %7D,%0A%0A getInstallments: function() %7B%0A if(this.hasSelectedSomeCard()) %7B%0A return this.$('.my_credit_cards
select#p
@@ -2342,32 +2342,33 @@
').val()
+;
%0A
-
%7D
-%0A %7D%0A%0A
+ else %7B%0A
retu
@@ -2362,37 +2362,103 @@
%7B%0A return
-data;
+this.$('.type_card_data select#payment_card_installments').val();%0A %7D
%0A %7D,%0A%0A onSubmi
|
23211975e27104cd93916a622b355c566f14af8a | Remove bem-site-logger dependency from base.test.js test file | test/src/tasks-libraries/model/base.test.js | test/src/tasks-libraries/model/base.test.js | var fsExtra = require('fs-extra'),
Logger = require('bem-site-logger'),
Base = require('../../../../lib/tasks-libraries/model/base');
describe('Base', function() {
var sandbox = sinon.sandbox.create(),
base;
beforeEach(function() {
sandbox.stub(console, 'error');
sandbox.stub(fsExtra, 'outputJSON');
sandbox.stub(fsExtra, 'outputFile');
base = new Base();
});
afterEach(function() {
sandbox.restore();
});
it('should have empty data after initialization', function() {
base.getData().should.be.instanceOf(Object).and.be.empty;
});
it('should set value for given key', function() {
base.setValue('foo', 'bar');
base.getData().foo.should.equal('bar');
});
describe('saveFile', function() {
it('should call valid method for saving JSON file', function() {
fsExtra.outputJSON.yields(null, './file.json');
base.saveFile('./file.json', {foo: 'bar'}, true).then(function() {
fsExtra.outputJSON.should.be.calledOnce();
});
});
it('should call valid method for saving text/html file', function() {
fsExtra.outputFile.yields(null, './file.txt');
base.saveFile('./file.json', {foo: 'bar'}, false).then(function() {
fsExtra.outputFile.should.be.calledOnce();
});
});
it('should return file path of saved file on successfully saving', function() {
fsExtra.outputJSON.yields(null, './file.json');
base.saveFile('./file.json', {foo: 'bar'}, true).should.eventually.equal('./file.json');
});
it('should trow error if error was occur while saving file', function() {
fsExtra.outputJSON.yields(new Error('file error'));
base.saveFile('./file.json', {foo: 'bar'}, true).should.be.rejectedWith('file error');
});
});
});
| JavaScript | 0.000001 | @@ -32,49 +32,8 @@
'),%0A
- Logger = require('bem-site-logger'),%0A
|
6e4986cbb24789aa0a03d4bbe04d9241181a7150 | Clean Commit. | app/assets/javascripts/client/controllers/HomeCtrl.js | app/assets/javascripts/client/controllers/HomeCtrl.js | PDRClient.controller('HomeCtrl', ['$scope','ToolKit', 'SessionService', '$timeout',
function($scope, ToolKit, SessionService, $timeout) {
$scope.toolKits = []
$scope.user = SessionService.getCurrentUser();
ToolKit.query({}, function(t) {
$scope.toolKits = t;
setToolTip();
});
function setToolTip() {
$timeout(function() {
$('ul.tool').find('li')
.popover({
placement: 'right',
html: true,
trigger: 'manual'
}).on('show.bs.popover', function(){
$('ul.tool').find('li').not(this).popover('hide');
}).mouseenter(function(e) {
$(this).popover('show');
}).on('click', function(){
$('ul.tool').find('li').popover('hide');
});
});
}
$scope.setPopovers = function(tool){
if(typeof tool.description === "undefined") {
tool.description = "This item is currently under development. Please stay tuned.";
}
return "<div><div class='row'><div class='col-md-12'><p class='greeting'>" + tool.title + "</p>" + tool.description + "</div></div>" +
"<div class='row second'><div class='col-md-9 icons'><span class='fa-stack'><i class='fa fa-circle fa-stack-2x'></i><i class='fa fa-font fa-stack-1x'></i></span><span class='fa-stack'><i class='fa fa-circle fa-stack-2x'></i><i class='fa fa-users fa-stack-1x'></i></span><span class='fa-stack'><i class='fa fa-circle fa-stack-2x'></i><i class='fa fa-comments fa-stack-1x'></i></span></div>" +
"<div class='col-md-3'><a href='/assessments' class='btn btn-primary'>Go</a></div></div>" + "</div>"
}
SessionService.setUserTemplate(
$scope,
'client/views/home/home_user.html',
'client/views/home/home_anon.html'
);
}
]);
| JavaScript | 0 | @@ -313,24 +313,25 @@
%0A %7D);%0A%0A
+%0A
functi
|
1fbf2b2549bbad612d2deeec96f45dca292611fd | fix localStorage specific tests | test/stash/drivers/local_storage_browser.js | test/stash/drivers/local_storage_browser.js | describe('Stash::Drivers::LocalStorage', function () {
var namespace = 'test';
var cacheManager = new Stash.Drivers.LocalStorage(namespace);
var pool = new Stash.Pool(cacheManager);
var item = pool.getItem('foo');
pool.flush();
it('should commit to localStorage', function () {
item.set('bar');
expect(localStorage.getItem(namespace))
.to.contain('bar');
});
it('should share cache between instances', function () {
var content = 'foo bar baz';
item.set(content);
expect(new Stash.Drivers.LocalStorage(namespace).get(item.key).value)
.to.be.equal(content);
});
});
| JavaScript | 0.000001 | @@ -307,19 +307,75 @@
ar')
-;%0A %0A
+.then(function (done) %7B%0A catching(done, function () %7B%0A
+
expe
@@ -412,24 +412,28 @@
ace))%0A
+
.to.contain(
@@ -440,16 +440,38 @@
'bar');%0A
+ %7D);%0A %7D)%0A %0A
%7D);%0A%0A
@@ -516,32 +516,36 @@
ces', function (
+done
) %7B%0A var cont
@@ -590,22 +590,41 @@
ent)
-;%0A%0A expect(
+.then(function () %7B%0A return
new
@@ -678,22 +678,101 @@
key)
+;%0A %7D).then(function (data) %7B%0A catching(done, function () %7B%0A expect(data
.value)
-%0A
.to.
@@ -790,16 +790,34 @@
ntent);%0A
+ %7D);%0A %7D);%0A
%7D);%0A%7D)
|
c9b1e95d27e9e5bc150576cd02a2e4769a073f8f | Add password validation to client side | public/js/register.js | public/js/register.js | $(function() {
$("#register").submit(function() {
var password = $("#password").val();
if (password !== $("#confirm").val()) {
return false;
}
var hashedPassword = CryptoJS.SHA256(password).toString();
$("#hashedPassword").val(hashedPassword);
return true;
})
}); | JavaScript | 0.000002 | @@ -8,18 +8,18 @@
ion() %7B%0A
-
+%0A%09
$(%22#regi
@@ -45,20 +45,19 @@
ion() %7B%0A
-
+%0A%09%09
var pass
@@ -89,27 +89,27 @@
();%0A
- if (password !=
+%09%09var confirmation
= $(
@@ -129,42 +129,297 @@
al()
-) %7B%0A return false;%0A %7D%0A
+;%0A%0A%09%09clearErrors();%0A%0A%09%09if (!passwordValid(password)) %7B%0A%09%09%09addValidationError(%22Password must be at least 6 characters long%22);%0A%09%09%09return false;%0A%09%09%7D%0A%0A%09%09if (!passwordConfirmed(password, confirmation)) %7B%0A%09%09%09addValidationError(%22Password and confirmation did not match%22);%0A%09%09%09return false;%0A%09%09%7D%0A%0A%09%09
var
@@ -473,20 +473,18 @@
ring();%0A
-
+%09%09
$(%22#hash
@@ -521,29 +521,381 @@
d);%0A
- return true;%0A %7D)
+%09%09return true;%0A%0A%09%7D);%0A%0A%09function clearErrors() %7B%0A%09%09$(%22#errors%22).children().remove();%0A%09%7D%0A%0A%09function passwordValid(password) %7B%0A%09%09return password && password.length %3E 5;%0A%09%7D%0A%0A%09function passwordConfirmed(password, confirmation) %7B%0A%09%09return password === confirmation;%0A%09%7D%0A%0A%09function addValidationError(msg) %7B%0A%09%09$('%3Cdiv/%3E', %7B class: 'error', text: msg %7D).appendTo($(%22#errors%22));%0A%09%7D%0A
%0A%7D);
+%0A
|
fe9d0b8afc6bfa47a92c8e33bb5fecfce4caeb28 | Solve IE incompatibility with es6 promises and fetch | public/src/actions.js | public/src/actions.js | /**
* Solve IE incompatibility with es6 promises and featch
*/
import Promise from 'es6-promise';
import 'whatwg-fetch';
window.Promise = window.Promise || Promise;
/**
* Actions:
* - ADD_DECK
* - SHOW_ADD_DECK
* - HIDE_ADD_DECK
*/
export const addDeck = name => ({ type: 'ADD_DECK', data: name });
export const showAddDeck = () => ({ type: 'SHOW_ADD_DECK' });
export const hideAddDeck = () => ({ type: 'HIDE_ADD_DECK' });
/**
* Actions:
* - ADD_CARD
* - UPDATE_CARD
* - DELETE_CARD
*/
export const addCard = card => ({ type: 'ADD_CARD', data: card });
export const updateCard = card => ({ type: 'UPDATE_CARD', data: card });
export const deleteCard = cardId => ({ type: 'DELETE_CARD', data: cardId });
export const filterCards = query => ({ type: 'FILTER_CARDS', data: query });
export const setShowBack = back => ({ type: 'SHOW_BACK', data: back });
export const receiveData = data => ({ type: 'RECEIEVE_DATA', data: data });
export const failedRequest = error => ({ type: 'RECEIEVE_DATA_ERROR', data: error });
export const startedCall = () => ({ type: 'START_FETCH_DATA'});
export const fetchData = () => {
return dispatch => {
dispatch(startedCall())
fetch('/api/data')
.then(res => res.json())
.then(json => dispatch(receiveData(json)))
.catch(err => dispatch(failedRequest(err)));
}
}; | JavaScript | 0.000026 | @@ -49,17 +49,16 @@
s and fe
-a
tch%0A */%0A
@@ -160,16 +160,17 @@
omise;%0A%0A
+%0A
/**%0A * A
|
51db8f3cbac019a9446b167112736b73c16cca9d | Add workplaces validator. | app/routes/joblistings/components/JoblistingEditor.js | app/routes/joblistings/components/JoblistingEditor.js | // @flow
import React from 'react';
import styles from './JoblistingEditor.css';
import LoadingIndicator from 'app/components/LoadingIndicator';
import { reduxForm, Field, change } from 'redux-form';
import { Form, SelectInput } from 'app/components/Form';
import Button from 'app/components/Button';
import moment from 'moment';
import config from 'app/config';
import { FlexRow, FlexColumn } from 'app/components/FlexBox';
import {
DatePickerComponent,
YearPickerComponent,
FieldComponent,
TextEditorComponent
} from './JoblistingEditorItems';
import { places } from '../constants';
type Props = {
joblistingId?: string,
joblisting?: Object,
handleSubmit: () => void,
submitJoblisting: () => void,
company?: Object,
dispatch: () => void,
isNew: boolean
};
function JoblistingEditor({
handleSubmit,
joblistingId,
joblisting,
isNew,
submitJoblisting,
company,
dispatch
}: Props) {
const onSubmit = newJoblisting => {
const workplaces = newJoblisting.workplaces
? newJoblisting.workplaces.map(obj => ({ town: obj.value }))
: null;
submitJoblisting({
...newJoblisting,
workplaces
});
};
if (!isNew && !joblisting.company.id) {
return <LoadingIndicator loading />;
}
return (
<div className={styles.root}>
<h1 className={styles.heading}>
{!isNew ? 'Rediger jobbannonse' : 'Legg til jobbannonse'}
</h1>
<Form onSubmit={handleSubmit(onSubmit)}>
<FieldComponent text="Tittel: " name="title" placeholder="Tittel" />
<FlexRow className={styles.row}>
<FlexColumn className={styles.des}>Bedrift: </FlexColumn>
<FlexColumn className={styles.textfield}>
<Field
placeholder={'Bedrift'}
name="company"
component={SelectInput.AutocompleteField}
filter={['companies.company']}
onChange={() =>
dispatch(
change('joblistingEditor', 'responsible', {
label: 'Ingen',
value: null
})
)}
/>
</FlexColumn>
</FlexRow>
<DatePickerComponent text="Deadline:" name="deadline" />
<DatePickerComponent text="Synlig fra:" name="visibleFrom" />
<DatePickerComponent text="Synlig til:" name="visibleTo" />
<FlexRow className={styles.row}>
<FlexColumn className={styles.des}>Jobbtype: </FlexColumn>
<FlexColumn className={styles.textfield}>
<Field name="jobType" component="select">
<option value="summer_job">Sommerjobb</option>
<option value="part_time">Deltid</option>
<option value="full_time">Fulltid</option>
</Field>
</FlexColumn>
</FlexRow>
<FlexRow className={styles.row}>
<FlexColumn className={styles.des}>Arbeidssteder: </FlexColumn>
<FlexColumn className={styles.textfield}>
<Field
placeholder={'Arbeidssteder'}
name="workplaces"
component={SelectInput.Field}
options={places}
tags
/>
</FlexColumn>
</FlexRow>
<YearPickerComponent text="Fra år: " name="fromYear" />
<YearPickerComponent text="Til år: " name="toYear" />
<FieldComponent
text="Søknadslenke: "
name="applicationUrl"
placeholder="Søknadslenke"
/>
<TextEditorComponent
text="Søknadsintro: "
name="description"
placeholder="Søknadsintro"
/>
<TextEditorComponent
text="Søknadstekst: "
name="text"
placeholder="Søknadstekst"
/>
<FlexRow className={styles.row}>
<FlexColumn className={styles.des}>Kontaktperson: </FlexColumn>
<FlexColumn className={styles.textfield}>
<Field
placeholder="Kontaktperson"
name="responsible"
component={SelectInput.AutocompleteField}
filter={['companies.companycontact']}
/>
</FlexColumn>
</FlexRow>
<Button className={styles.submit} submit>
Lagre
</Button>
</Form>
</div>
);
}
export default reduxForm({
form: 'joblistingEditor',
enableReinitialize: true,
validate(values) {
const errors = {};
if (!values.title) {
errors.title = 'Du må gi jobbannonsen en tittel';
}
if (!values.company || values.company.value == null) {
errors.company = 'Du må angi en bedrift for jobbannonsen';
}
if (parseInt(values.fromYear, 10) > parseInt(values.toYear, 10)) {
errors.toYear = "'Til år' kan ikke være lavere enn 'Fra år'";
}
const visibleFrom = moment.tz(values.visibleFrom, config.timezone);
const visibleTo = moment.tz(values.visibleTo, config.timezone);
if (visibleFrom > visibleTo) {
errors.visibleTo = 'Sluttidspunkt kan ikke være før starttidspunkt';
}
return errors;
}
})(JoblistingEditor);
| JavaScript | 0 | @@ -4801,24 +4801,121 @@
%C3%A5r'%22;%0A %7D%0A
+ if (!values.workplaces) %7B%0A errors.workplaces = 'Arbeidssteder kan ikke v%C3%A6re tom';%0A %7D%0A
const vi
|
ce07374e6770d201494592a5242ae76711236d9f | remove not needed expicit injection | app/templates/src/components/navbar/_navbar.controller.js | app/templates/src/components/navbar/_navbar.controller.js | 'use strict';
angular.module('<%= appname %>')
.controller('NavbarCtrl', ['$scope', function ($scope) {
$scope.date = new Date();
}]);
| JavaScript | 0.000001 | @@ -72,19 +72,8 @@
rl',
- %5B'$scope',
fun
@@ -126,8 +126,7 @@
%0A %7D
-%5D
);%0A
|
7870e1b52dee3195dbe730bb5ff6bfd3e31de82d | remove unnecessarily strict constraint in helper | tests/pages/services/DeploymentsModal-cy.js | tests/pages/services/DeploymentsModal-cy.js | describe("Deployments Modal", function() {
function openDeploymentsModal(numDeployments = 1) {
cy.get(".button")
.contains(numDeployments + " deployment")
.click();
}
beforeEach(function() {
cy.configureCluster({
mesos: "1-for-each-health",
deployments: "one-deployment",
nodeHealth: true
});
cy.visitUrl({ url: "/services/overview/" });
});
context("Modal Trigger", function() {
it("has a deployments button", function() {
cy.get(".button")
.contains("1 deployment")
.should("to.have.length", 1);
});
it("opens the modal when clicking the deployments button", function() {
openDeploymentsModal();
cy.get(".modal").then(function($modal) {
expect($modal.get().length).to.equal(1);
});
});
});
context("Modal Content", function() {
beforeEach(function() {
openDeploymentsModal();
});
it("closes when the close button is clicked", function() {
cy.get(".modal").then(function($modal) {
expect($modal.get().length).to.equal(1);
});
cy.get(".modal-footer button")
.contains("Close")
.click();
cy.wait(700).then(function() {
expect(document.querySelectorAll(".modal").length).to.equal(0);
});
});
it("renders the deployments count", function() {
cy.get(".modal-header").then(function($header) {
expect($header.get(0).textContent).to.equal("1 Active Deployment");
});
});
it("renders one row per deployment", function() {
cy.get(".modal tbody tr:visible").then(function($tableRows) {
expect($tableRows.get().length).to.equal(1);
});
});
it("renders the `id` column", function() {
cy.get(".modal tbody tr:visible td").then(function($tableCells) {
cy.getAPIResponse("marathon/v2/deployments", function(response) {
expect(
$tableCells.get(0).querySelector(".collapsing-string-full-string")
.textContent
).to.equal(response[0].id);
});
});
});
it("renders the `started` column", function() {
cy.get(".modal tbody tr:visible td").then(function($tableCells) {
cy.getAPIResponse("marathon/v2/deployments", function(response) {
expect(
$tableCells
.get(1)
.querySelector("time")
.getAttribute("datetime")
).to.equal(response[0].version);
});
});
});
it("renders the `status` column", function() {
cy.get(".modal tbody tr:visible td").then(function($tableCells) {
expect(
$tableCells.get(2).querySelectorAll(".status-bar").length
).to.equal(1);
});
});
it("is auto-expanded to show services", function() {
cy.get(
".modal tbody tr:visible td .expanding-table-child .table-cell-value"
).then(function($expandedChildText) {
cy.getAPIResponse("marathon/v2/deployments", function(response) {
expect($expandedChildText.get(0).textContent).to.equal(
response[0].affectedApps[0].replace(/^\//, "")
);
});
});
});
it("dismisses both modals when the rollback is performed", function() {
cy.getAPIResponse("marathon/v2/deployments", function(response) {
cy.route({
method: "DELETE",
url: /marathon\/v2\/deployments/,
status: 400,
response: {
version: response[0].version,
deploymentId: response[0].id
}
});
cy.get(".modal tbody tr:visible td .dropdown").click();
cy.get(".dropdown-menu-items")
.contains("Rollback")
.click();
cy.get(".modal button")
.contains("Continue Rollback")
.click();
cy.wait(700).then(function() {
expect(document.querySelectorAll(".modal").length).to.equal(0);
});
});
});
});
context("Rollback modal", function() {
it("displays the rollback modal when clicked", function() {
openDeploymentsModal();
cy.get(".modal tbody tr:visible td .dropdown").click();
cy.get(".dropdown-menu-items")
.contains("Rollback")
.click();
cy.get(".modal").then(function($modals) {
expect($modals.get().length).to.equal(2);
});
});
it("displays a revert message for a non-starting deployment", function() {
openDeploymentsModal();
cy.get(".modal tbody tr:visible td .dropdown").click();
cy.get(".dropdown-menu-items")
.contains("Rollback")
.click();
cy.contains("revert the affected service");
});
it("displays a removal message for a starting deployment", function() {
cy.server().route(
/marathon\/v2\/deployments/,
"fx:deployments/starting-deployment"
);
openDeploymentsModal();
cy.get(".modal tbody tr:visible td .dropdown").click();
cy.get(".dropdown-menu-items")
.contains("Rollback")
.click();
cy.contains("delete the affected service");
});
});
context("Stale Deployments", function() {
beforeEach(function() {
cy.route(
/marathon\/v2\/deployments/,
"fx:deployments/two-deployments-one-stale"
);
openDeploymentsModal();
});
it("shows stale deployment in modal", function() {
cy.get(".deployments-table-column-id").contains("spark-history-stale");
});
it("shows status of stale deployment", function() {
cy.get(".deployments-table-column-status").contains("StopApplication");
});
});
});
| JavaScript | 0.00001 | @@ -72,26 +72,8 @@
dal(
-numDeployments = 1
) %7B%0A
@@ -114,27 +114,9 @@
ins(
-numDeployments + %22
+%22
depl
@@ -5160,24 +5160,33 @@
%7B%0A cy.
+server().
route(%0A
|
92874b50078867ce6688f193ae8e5acaa8c9228d | Update MainTabNavigator.js | apps/native-component-list/navigation/MainTabNavigator.js | apps/native-component-list/navigation/MainTabNavigator.js | import React from 'react';
import { Platform, StyleSheet } from 'react-native';
import { createBottomTabNavigator } from 'react-navigation';
import { createMaterialBottomTabNavigator } from 'react-navigation-material-bottom-tabs';
import TabIcon from '../components/TabIcon';
import { Colors, Layout } from '../constants';
import ExpoApisStackNavigator from './ExpoApisStackNavigator';
import ExpoComponentsStackNavigator from './ExpoComponentsStackNavigator';
import ReactNativeCoreStackNavigator from './ReactNativeCoreStackNavigator';
const styles = StyleSheet.create({
tabBar: {
backgroundColor: Colors.tabBar,
},
});
const createTabNavigator = Platform.select({
default: createBottomTabNavigator,
android: createMaterialBottomTabNavigator,
});
ExpoApisStackNavigator.path = '';
ExpoApisStackNavigator.navigationOptions = {
title: 'Expo API',
};
ExpoComponentsStackNavigator.path = '';
ExpoComponentsStackNavigator.navigationOptions = {
title: 'Expo Components',
};
ReactNativeCoreStackNavigator.path = '';
ReactNativeCoreStackNavigator.navigationOptions = {
title: 'React Native Core',
};
const MainTabNavigator = createTabNavigator(
{
ExpoApis: ExpoApisStackNavigator,
ExpoComponents: ExpoComponentsStackNavigator,
ReactNativeCore: ReactNativeCoreStackNavigator,
},
{
defaultNavigationOptions: ({ navigation }) => {
let tabBarLabel;
const { routeName } = navigation.state;
if (routeName === 'ReactNativeCore') {
tabBarLabel = Layout.isSmallDevice ? 'RN Core' : 'React Native Core';
} else if (routeName === 'ExpoComponents') {
tabBarLabel = Layout.isSmallDevice ? 'Components' : 'Expo Components';
} else if (routeName === 'ExpoApis') {
tabBarLabel = Layout.isSmallDevice ? 'APIs' : 'Expo APIs';
}
return {
header: null,
tabBarLabel,
tabBarIcon: ({ focused }) => {
const { routeName } = navigation.state;
if (routeName === 'ReactNativeCore') {
return <TabIcon name="group-work" focused={focused} />;
} else if (routeName === 'ExpoComponents') {
return <TabIcon name="filter" focused={focused} size={25} />;
} else if (routeName === 'ExpoApis') {
return <TabIcon name="functions" focused={focused} size={28} />;
}
},
};
},
/* Below applies to material bottom tab navigator */
activeTintColor: Colors.tabIconSelected,
inactiveTintColor: Colors.tabIconDefault,
shifting: true,
barStyle: {
backgroundColor: Colors.tabBar,
borderTopWidth: StyleSheet.hairlineWidth,
borderTopColor: Colors.tabIconDefault,
},
/* Below applies to bottom tab navigator */
tabBarOptions: {
style: styles.tabBar,
labelStyle: styles.tabBarLabel,
activeTintColor: Colors.tabIconSelected,
inactiveTintColor: Colors.tabIconDefault,
},
}
);
MainTabNavigator.path = '';
MainTabNavigator.navigationOptions = {
title: 'Native Component List',
};
export default MainTabNavigator;
| JavaScript | 0 | @@ -786,27 +786,30 @@
tor.path = '
+API
';%0A
-
ExpoApisStac
@@ -903,16 +903,26 @@
path = '
+Components
';%0AExpoC
@@ -999,16 +999,16 @@
s',%0A%7D;%0A%0A
-
ReactNat
@@ -1037,16 +1037,27 @@
path = '
+ReactNative
';%0AReact
|
c587cf8477c4f8a0c6abd3b7b436c722dda554bc | Add persona avatar image for placeholder card | app/views/components/item-column/placeholder-cards.js | app/views/components/item-column/placeholder-cards.js | import _ from 'lodash';
import React from 'react';
import OwnerAvatar from '../item-card/owner';
// Flux
import HeaderActions from '../../../actions/header-actions'
import HeaderStore from '../../../stores/header-store'
const CURRENT_COL_STATUS = 'in-progress';
var PlaceholderCards = React.createClass({
propTypes: {
status: React.PropTypes.string.isRequired
},
ipsumBlocks() {
var length = _.sample([1, 2, 3]);
return _.times(length, (n) => {
var width = (n === length-1) ? Math.floor((Math.random() * (100 - 50) + 50)) : 100;
return <div style={ {width: `${width}%`} } className="ipsum-block"></div>
})
},
actionContent() {
return ([
<div className="prompt__create-item">Add an Item to get started!</div>,
<button style={ {width: "100%"} } className="btn btn-primary" onClick={this.triggerModal}>Add an Item</button>
]
)
},
triggerModal() {
// Future: navigation.transitionTo('add-item');
HeaderActions.openAddModal();
},
placeholderCards() {
return _.times(8, (n) => {
var content;
if (n === 2 && this.props.status === CURRENT_COL_STATUS) {
content = this.actionContent();
} else {
content = this.ipsumBlocks();
}
return (
<div className="item-card placeholder">
<div className="row">
<div className="item-card__header col-sm-12">
<div className="item-card__header-right">
<span><OwnerAvatar person="placeholder" /></span>
</div>
</div>
<div className="item-card__title col-sm-12">
{content}
</div>
</div>
</div>
)
})
},
render() {
return (
<div className='placeholder-cards'>
{this.placeholderCards()}
</div>
);
}
});
module.exports = PlaceholderCards;
| JavaScript | 0 | @@ -922,60 +922,8 @@
) %7B%0A
- // Future: navigation.transitionTo('add-item');%0A
|
62c1c2993842c5ef4a92ea28b65360b1b17929f8 | reset after submit. | apps/social/themes/default/js/custom/comment-input.js | apps/social/themes/default/js/custom/comment-input.js | var QueryString = function () {
// This function is anonymous, is executed immediately and
// the return value is assigned to QueryString!
var query_string = {};
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
// If first entry with this name
if (typeof query_string[pair[0]] === "undefined") {
query_string[pair[0]] = pair[1];
// If second entry with this name
} else if (typeof query_string[pair[0]] === "string") {
var arr = [ query_string[pair[0]], pair[1] ];
query_string[pair[0]] = arr;
// If third or later entry with this name
} else {
query_string[pair[0]].push(pair[1]);
}
}
return query_string;
}();
$('.auto-submit-star').rating({
callback: function (value) {
}
});
$('#btn-post').click(function (e) {
e.preventDefault();
var textArea = '#com-body';
var rating = Number($('input.star-rating-applied:checked').val());
if (!rating) {
} else {
var activity = {"verb": "post",
"object": {"type": "rating", "content": $(textArea).val(), rating: rating},
"target": {"id": QueryString.target}
};
var body = $(textArea).val();
$.get('apis/comments.jag', {
activity: JSON.stringify(activity)
}, function () {
location.reload();
});
}
});
| JavaScript | 0 | @@ -858,16 +858,29 @@
;%0A%7D();%0A%0A
+var $radio =
$('.auto
@@ -893,16 +893,24 @@
t-star')
+;%0A$radio
.rating(
@@ -955,16 +955,27 @@
%7D%0A%7D);%0A%0A
+var $btn =
$('#btn-
@@ -980,16 +980,22 @@
n-post')
+;%0A$btn
.click(f
@@ -1040,16 +1040,17 @@
var
+$
textArea
@@ -1052,16 +1052,18 @@
tArea =
+$(
'#com-bo
@@ -1065,16 +1065,17 @@
om-body'
+)
;%0A va
@@ -1266,25 +1266,24 @@
tent%22: $
-(
textArea
).val(),
@@ -1270,25 +1270,24 @@
%22: $textArea
-)
.val(), rati
@@ -1384,17 +1384,16 @@
= $
-(
textArea
).va
@@ -1388,17 +1388,16 @@
textArea
-)
.val();%0A
@@ -1393,24 +1393,67 @@
rea.val();%0A%0A
+ $btn.attr('disabled', 'disabled');%0A
$.ge
@@ -1545,24 +1545,141 @@
nction () %7B%0A
+ $btn.removeAttr('disabled');%0A $radio.rating('select',null) ;%0A $textArea.val('');%0A//
@@ -1717,14 +1717,15 @@
%0A %7D%0A%0A
+%0A
%7D);%0A%0A%0A
|
71585af269745d1abad71f8ea487ac0742ceaed1 | Add /news to userpath controller | trails-log/app/assets/javascripts/trails.js | trails-log/app/assets/javascripts/trails.js | $(document).on("ready", function() {
L.mapbox.accessToken = 'pk.eyJ1IjoidGlzZGVyZWsiLCJhIjoiNDQ5Y2JiODdiZDZmODM0OWI0NmRiNDI5OGQzZWE4ZWIifQ.rVJW4H9TC1cknmRYoZE78w';
var userMap = L.mapbox.map('user-map', 'mapbox.run-bike-hike')
.addControl(L.mapbox.geocoderControl('mapbox.places'))
.setView([37.7833, -122.4167], 12);
// getUsersTrails() is returning the result of .featureLayer.loadURL.addTo which grabs the marker coordinates and adds to the map.
userTrailsLayer = getUsersTrails(userMap);
// When the layer is ready, it zooms in the map to show all markers.
userTrailsLayer.on("ready", function() {
userMap.fitBounds(userTrailsLayer.getBounds());
})
// This creates a featuregroup and adds it to the map
var featureGroup = L.featureGroup().addTo(userMap);
// This creates a draw controls menu with an edit option to "save" the new pin, this only makes the pin non-draggable and a able to be added to the featureGroup variable from line 17.
var drawControl = new L.Control.Draw({
edit: {
featureGroup: featureGroup
}
}).addTo(userMap);
// When a draw feature is created, this adds it as a layer to the featureGroup variable on line 17. It also saves to variables the lat/lon of the marker.
userMap.on('draw:created', function(e) {
featureGroup.addLayer(e.layer);
var markerLat = e.layer._latlng["lat"]
var markerLng = e.layer._latlng["lng"]
});
});
// This loads from /trails.json and adds markers to the map
// It is reaturning this as the variable featureLayer to be used later as userTrailsLayer
var getUsersTrails = function(userMap) {
var featureLayer = L.mapbox.featureLayer()
.loadURL(userPath())
.addTo(userMap);
return featureLayer
};
// Show map from either /users/:id or /users/:id/trails
var userPath = function(){
var windowLocation = window.location.pathname
if (windowLocation.includes('trails')) {
return windowLocation + ".json"
}
else {
return windowLocation + "/trails.json"
}
}
/////// drop pin pseudocode ///////
// Place draggable pin on the map
// User drags pin to desired trailhead
// User clicks button to save the pin
// Draggable marker is hidden
// Single marker is created at the click location
// Marker location is added to the add trail form
// New marker/trailhead created.
// OLD AJAX CALL
// $.ajax({
// url: userPath,
// dataType: 'JSON'
// })
// .done(function(response){
// console.log(response);
// L.geoJson(response, {
// onEachFeature: function(feature, layer) {
// layer.bindPopup("Trail: " + feature.properties.title + " Review: " + feature.properties.review);
// }
// }).addTo(userMap)
// })
// .fail(function(response){
// console.log(response);
// });
| JavaScript | 0 | @@ -1900,16 +1900,124 @@
cludes('
+/new')) %7B%0A return windowLocation.replace('/new', '.json')%0A %7D%0A else if (windowLocation.includes('/
trails')
@@ -2054,15 +2054,15 @@
n +
-%22
+'
.json
-%22
+'
%0A
|
2b1a4c06edadb864b40c498b0d8d9e90302c3969 | Disable forceHttps | run.js | run.js | 'use strict';
const dne = 10000;
const configuration = {
keyPublishable: process.env.PUBLISHABLE_KEY || 'pk_test_DZkclA7Lk0U2szChf0u7RV8U',
keySecret: process.env.SECRET_KEY || 'sk_test_JvHrW5FfszUh49X5eMW5ZKU5',
port: process.env.PORT || 1111,
dne,
priceMultiplier: 1.022,
priceAddition: 0.60,
gst: 1.05,
products: {
'Almonds': {
image: 'almonds.jpg',
description: 'Unsalted classics. Roasted in Victora, BC.',
price: 5.73,
amount: 0,
},
'Cashews': {
image: 'cashews.jpg',
description: 'Unsalted halves and pieces. Roasted in Victoria, BC.',
price: 8.99,
amount: 0,
},
'Walnuts': {
image: 'walnuts.jpg',
description: 'Unsalted halves and pieces. Roasted in Victoria, BC.',
price: 6.11,
amount: 0,
},
'Raisins': {
image: 'raisins.jpg',
description: 'Certified Organic, Thompsons, oil free.',
price: 2.86,
amount: 0,
},
'Figs': {
image: 'figs.jpg',
description: 'Certified Organic, Turkish.',
price: 7.27,
amount: 0,
},
'Apricots': {
image: 'apricots.jpg',
description: 'Certified Organic, Turkish, Pitted, Unsulfured.',
price: 7.66,
amount: 0,
}
},
prices: {
'Competitors': [ 'Independent', 'Save On Foods', 'Nesters', 'Walmart' ],
'Almonds': [ 13.06, 13.59, 15.86, 19.19 ],
'Cashews': [ 11.35, 13.59, 17.50, 11.57 ],
'Walnuts': [ 15.90, 10.41, 15.95, 9.09 ],
'Raisins': [ 4.60, 9.05, 6.32, dne ],
'Figs': [ dne, dne, 14.53, dne ],
'Apricots': [ 12.86, 10.41, dne, 8.29 ],
},
forceHttps: process.env.FORCE_HTTPS || true,
};
const express = require('express');
const app = express();
app.set('view engine', 'pug');
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
const stripe = require("stripe")(configuration.keySecret);
const router = express.Router();
app.use(express.static('public'));
if (configuration.forceHttps) {
app.all('*', function(req, res) {
if (!req.connection.encrypted) {
return res.redirect("https://" + req.headers["host"] + req.url);
}
});
}
app.get('/', function(req, res) {
res.render('index', { configuration: JSON.stringify(configuration) });
});
app.post("/charge", (req, res) => {
let amount = (getPriceFromProducts(configuration.products, req.body) * 100).toFixed(0);
stripe.customers.create({
email: req.body.stripeEmail,
source: req.body.stripeToken,
})
.then(customer =>
stripe.charges.create({
amount,
currency: 'cad',
description: 'Website Charge',
customer: customer.id,
metadata: req.body,
}))
.then(charge => {
res.status(200);
res.send({ });
});
});
app.listen(configuration.port);
console.log(`Started on port: ${configuration.port}`);
function getPriceFromProducts(products, source) {
const productNames = Object.keys(products);
return productNames.map(p => {
const units = source[p] || 0;
const unitPrice = Math.ceil((products[p].price * configuration.priceMultiplier + configuration.priceAddition) * 10) / 10;
return units * unitPrice;
}).reduce((a, b) => a + b) * configuration.gst;
}
| JavaScript | 0.000065 | @@ -1653,19 +1653,20 @@
TTPS %7C%7C
-tru
+fals
e,%0A%7D;%0A%0Ac
|
75356786a3801cb44ec3728af9fe56d3a2164bdd | remove linting from prepare release task | build/tasks/prepare-release.js | build/tasks/prepare-release.js | var gulp = require('gulp');
var runSequence = require('run-sequence');
var paths = require('../paths');
var changelog = require('conventional-changelog');
var fs = require('fs');
var bump = require('gulp-bump');
var args = require('../args');
gulp.task('bump-version', function(){
return gulp.src(['./package.json', './bower.json'])
.pipe(bump({type:args.bump })) //major|minor|patch|prerelease
.pipe(gulp.dest('./'));
});
gulp.task('changelog', function(callback) {
var pkg = JSON.parse(fs.readFileSync('./package.json', 'utf-8'));
return changelog({
repository: pkg.repository.url,
version: pkg.version,
file: paths.doc + '/CHANGELOG.md'
}, function(err, log) {
fs.writeFileSync(paths.doc + '/CHANGELOG.md', log);
});
});
gulp.task('prepare-release', function(callback){
return runSequence(
'build',
'lint',
'bump-version',
'doc',
'changelog',
callback
);
}); | JavaScript | 0.000119 | @@ -843,20 +843,8 @@
d',%0A
- 'lint',%0A
|
1735abcd21404e32dd79ef7c1a09399a3dff9e0f | Disable rollup uglify for now as it breaks for some reason | config/plugin/rollup.js | config/plugin/rollup.js | var babel = require('rollup-plugin-babel');
var uglify = require('rollup-plugin-uglify');
var resolve = require('rollup-plugin-node-resolve');
var paths = require('./paths');
var babelConfig = require('./babel');
var plugins = [
resolve({module: false}),
babel(babelConfig),
];
if (process.env.NODE_ENV === 'production') {
plugins.push(uglify());
}
module.exports = {
// Tell rollup our main entry point
entry: paths.entry,
exports: 'none',
format: 'cjs',
treeshake: false, // This is important in this case, otherwise handlers won't get output
plugins: plugins,
sourceMap: true
}
| JavaScript | 0 | @@ -278,16 +278,75 @@
g),%0A%5D;%0A%0A
+// Uglify breaks the build process, so disabled for now%0A//
if (proc
@@ -382,16 +382,19 @@
ion') %7B%0A
+//
plugin
@@ -411,16 +411,19 @@
ify());%0A
+//
%7D%0A%0Amodul
|
bb95cb816f06f936254befcb7187cd631553cd15 | disable eslint | src/AnimateGroup.js | src/AnimateGroup.js | import React, { Children } from 'react';
import { TransitionGroup } from 'react-transition-group';
import PropTypes from 'prop-types';
import AnimateGroupChild from './AnimateGroupChild';
function AnimateGroup(props) {
const {
component, children, appear, enter, leave,
} = props;
return (
<TransitionGroup component={component}>
{
Children.map(children, (child, index) => ((
<AnimateGroupChild
appearOptions={appear}
enterOptions={enter}
leaveOptions={leave}
key={`child-${index}`}
>
{child}
</AnimateGroupChild>
)))
}
</TransitionGroup>
);
}
AnimateGroup.propTypes = {
appear: PropTypes.object,
enter: PropTypes.object,
leave: PropTypes.object,
children: PropTypes.oneOfType([PropTypes.array, PropTypes.element]),
component: PropTypes.any,
};
AnimateGroup.defaultProps = {
component: 'span',
};
export default AnimateGroup;
| JavaScript | 0.000025 | @@ -563,16 +563,39 @@
index%7D%60%7D
+ // eslint-disable-line
%0A
|
8fff3f4efaeb2a140c980cf0fa85d403052c0ccc | Fix hexBytes | any_sha1.js | any_sha1.js | /*global Rusha hex_sha1 jsSHA sjcl forge CryptoJS*/
/*any_sha1 Copyright (c) 2014 Stuart P. Bentley
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.
*/
(function(){
"use strict";
var crypto, rusha;
function charCodes(s) {
var l = s.length;
var a = new Array(l);
for (var i = 0; i < l; ++i) {
a[i] = s.charCodeAt(i);
}
return a;
}
function hexBytes(s) {
var l = s.length / 2;
var a = new Array(l);
for (var i = 0; i < l; ++i) {
a[i] = parseInt(s.slice(i*2, 2), 16);
}
return a;
}
function from(opts) {
if (typeof module != "undefined") {
crypto = crypto || require('crypto');
return opts.node;
} else if (typeof(Rusha) != "undefined") {
rusha = rusha || new Rusha();
return opts.rusha;
} else if (typeof(forge) != "undefined") {
return opts.forge;
} else if (typeof(sjcl) != "undefined" && sjcl.hash.sha1) {
return opts.sjcl;
} else if (typeof(jsSHA) != "undefined") {
return opts.jsSHA;
} else if (typeof(hex_sha1) != "undefined") {
return opts.paj;
} else if (typeof(CryptoJS) != "undefined") {
return opts.cryptoJS;
} else if (window.polycrypt) {
return opts.polycrypt;
} else return null;
}
var any_sha1 = { utf8: {
bytes: {
node: function sha1Node(content) {
crypto = crypto || require('crypto');
return Array.apply([],
crypto.createHash('sha1').update(content, 'utf8').digest());
},
rusha: function sha1Rusha(content) {
rusha = rusha || new Rusha();
return Array.apply([], new Uint8Array(
rusha.rawDigest(unescape(encodeURIComponent(content))).buffer));
},
forge: function sha1Forge(content) {
return charCodes(forge.md.sha1.create()
.update(unescape(encodeURIComponent(content))).digest().bytes());
},
sjcl: function sha1Sjcl(content) {
var result = sjcl.hash.sha1.hash(unescape(encodeURIComponent(content)));
var a = new Array(20);
for (var i = 0; i < 5; ++i) {
a[i*4] = result[i] & 0xFF;
a[i*4+1] = result[i] >> 8 & 0xFF;
a[i*4+2] = result[i] >> 16 & 0xFF;
a[i*4+3] = result[i] >> 24;
}
return a;
},
jsSHA: function sha1JsSHA(content) {
return hexBytes(new jsSHA(unescape(encodeURIComponent(content)),'TEXT')
.getHash('SHA-1','HEX'));
},
paj: function sha1Paj(content) {
return hexBytes(hex_sha1(content));
},
cryptoJS: function sha1CryptoJS(content) {
return hexBytes(CryptoJS.SHA1(unescape(encodeURIComponent(content))));
},
polycrypt: function sha1Polycrypt(content) {
return hexBytes(window.polycrypt.digest('SHA-1',
unescape(encodeURIComponent(content))));
}
}},
define: function define(opts, obj, key, chooser) {
obj = obj || window;
key = key || 'sha1';
chooser = chooser || from;
if (typeof(Rusha) != "undefined")
rusha = new Rusha();
if (obj[key]) {
return obj[key];
}
var f = chooser(opts);
if (f) {
return obj[key] = f;
} else {
return obj[key] = function sha1LateBinding(content) {
var f = chooser(opts);
obj[key] = f;
return f(content);
};
}
},
from: from, charCodes: charCodes, hexBytes: hexBytes
};
if(typeof module != "undefined") {
module.exports = any_sha1;
crypto = require('crypto');
} else {
window.any_sha1 = any_sha1;
}
})();
| JavaScript | 0.001032 | @@ -1454,16 +1454,22 @@
ce(i*2,
+(i*2)+
2), 16);
|
72eee9d90451e9e898312a5915b33e8ed0769cae | Allow Text to be positioned and styled | src/Hexagon/Text.js | src/Hexagon/Text.js | import React, { Component } from 'react';
import PropTypes from 'prop-types';
// TODO Text is a separate component so that it could wrap the given text inside the surrounding hexagon
class Text extends Component {
static propTypes = {
children: PropTypes.string
};
render() {
const { children } = this.props;
return (
<text x="0" y="0.3em" textAnchor="middle">{children}</text>
);
}
}
export default Text;
| JavaScript | 0 | @@ -244,16 +244,99 @@
hildren:
+ PropTypes.string,%0A x: PropTypes.number,%0A y: PropTypes.number,%0A className:
PropTyp
@@ -384,16 +384,33 @@
children
+, x, y, className
%7D = thi
@@ -449,21 +449,58 @@
t x=
-%220%22 y=%220.3em%22
+%7Bx %7C%7C 0%7D y=%7By ? y : '0.3em'%7D className=%7BclassName%7D
tex
|
7a53d008fd7414fbb1e1045ee65a3d5eee88b23e | Add Object.assign to polyfill.js | src/main/resources/static/js/polyfill.js | src/main/resources/static/js/polyfill.js | var global = this;
var console = {};
console.debug = print;
console.warn = print;
console.log = print;
console.error = print;
console.trace = print;
| JavaScript | 0.000002 | @@ -134,16 +134,1306 @@
.trace = print;%0A
+%0A// https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Polyfill%0Aif (!Object.assign) %7B%0A Object.defineProperty(Object, 'assign', %7B%0A enumerable: false,%0A configurable: true,%0A writable: true,%0A value: function(target) %7B%0A 'use strict';%0A if (target === undefined %7C%7C target === null) %7B%0A throw new TypeError('Cannot convert first argument to object');%0A %7D%0A%0A var to = Object(target);%0A for (var i = 1; i %3C arguments.length; i++) %7B%0A var nextSource = arguments%5Bi%5D;%0A if (nextSource === undefined %7C%7C nextSource === null) %7B%0A continue;%0A %7D%0A nextSource = Object(nextSource);%0A%0A var keysArray = Object.keys(nextSource);%0A for (var nextIndex = 0, len = keysArray.length; nextIndex %3C len; nextIndex++) %7B%0A var nextKey = keysArray%5BnextIndex%5D;%0A var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);%0A if (desc !== undefined && desc.enumerable) %7B%0A to%5BnextKey%5D = nextSource%5BnextKey%5D;%0A %7D%0A %7D%0A %7D%0A return to;%0A %7D%0A %7D);%0A%7D
|
c8bec8ae1213dcd96e05c2a69dbc72c3a9d00b67 | Add delete queue | src/schema/sqs/index.js | src/schema/sqs/index.js | import AWS from 'aws-sdk';
import Promise from 'bluebird';
import {
GraphQLObjectType,
GraphQLNonNull,
GraphQLList,
GraphQLString,
GraphQLInt,
GraphQLEnumType
} from 'graphql/lib/type';
const sqs = new Promise.promisifyAll(new AWS.SQS());
const attributeNamesType = new GraphQLEnumType({
name: 'Queue Attribute Names',
description: 'Attribute names for the queue',
values: {
Policy: {
value: 'Policy'
},
VisibilityTimeout: {
value: 'VisibilityTimeout'
},
MaximumMessageSize: {
value: 'MaximumMessageSize'
},
MessageRetentionPeriod: {
value: 'MessageRetentionPeriod'
},
ApproximateNumberOfMessages: {
value: 'ApproximateNumberOfMessages'
},
ApproximateNumberOfMessagesNotVisible: {
value: 'ApproximateNumberOfMessagesNotVisible'
},
CreatedTimestamp: {
value: 'CreatedTimestamp'
},
LastModifiedTimestamp: {
value: 'LastModifiedTimestamp'
},
QueueArn: {
value: 'QueueArn'
},
ApproximateNumberOfMessagesDelayed: {
value: 'ApproximateNumberOfMessagesDelayed'
},
DelaySeconds: {
value: 'DelaySeconds'
},
ReceiveMessageWaitTimeSeconds: {
value: 'ReceiveMessageWaitTimeSeconds'
},
RedrivePolicy: {
value: 'RedrivePolicy'
}
}
});
const type = new GraphQLObjectType({
name: 'Queue',
description: 'Represents an Amazon SQS message queue.',
fields: () => ({
url: {
type: new GraphQLNonNull(GraphQLString),
description: 'The url for the message queue.',
resolve: (root) => { return root.url || root; }
},
visibilityTimeout: {
type: new GraphQLNonNull(GraphQLInt),
description: 'The visiblity timeout for the message queue.'
}
})
});
exports.queries = {
// TODO: Not sure if you are meant / better off create queries
// to do individual API calls to populate attributes
queueAttributes: {
type: type,
args: {
url: {
name: 'url',
type: new GraphQLNonNull(GraphQLString)
},
attributeNames: {
name: 'attributeNames',
type: new GraphQLList(attributeNamesType)
}
},
// TODO: Unsure of best way to do this.
// could create an attribute object type instead and map it.
resolve: (root, {url, attributeNames}) => {
return sqs.getQueueAttributesAsync({
QueueUrl: url,
AttributeNames: attributeNames
}).then(() => {
return {
url: url
};
});
}
},
queues: {
type: new GraphQLList(type),
args: {
prefix: {
name: 'prefix',
type: GraphQLString
}
},
resolve: (root, {prefix}) => {
return sqs.listQueuesAsync(prefix).then((result) => {
return result.QueueUrls;
});
}
}
};
exports.mutations = {
createQueue: {
type: type,
args: {
name: {
name: 'name',
type: new GraphQLNonNull(GraphQLString)
}
},
resolve: (obj, {name}) => {
return sqs.createQueueAsync({ QueueName: name }).then((result) => {
return result.QueueUrl;
});
}
}
};
| JavaScript | 0.000002 | @@ -2840,16 +2840,361 @@
ons = %7B%0A
+ deleteQueue: %7B%0A type: new GraphQLNonNull(GraphQLString),%0A args: %7B%0A url: %7B%0A name: 'url',%0A type: new GraphQLNonNull(GraphQLString)%0A %7D%0A %7D,%0A resolve: (obj, %7Burl%7D) =%3E %7B%0A return sqs.deleteQueueAsync(%7B QueueUrl: url %7D).then((result) =%3E %7B%0A return result.ResponseMetadata.RequestId;%0A %7D);%0A %7D%0A %7D,%0A
create
|
236f72ac16f836181ca041ff07a3fb5fc2977090 | tag values are now sorted alphabetically | app/Data.js | app/Data.js | var THREE = require("three");
var parsedPoints = [],
parsedTags = [],
tagColors = new Map(),
total = 0;
var Data = module.exports = {
pointSize: 2,
pointSizeMultiplier: 1,
cloudSize2D: 1.5,
loadData: function(data) {
parsedPoints = [];
parsedTags = [];
total = data.length;
var i;
for (i = 0; i < data.length; i++) {
var dataPoint = new THREE.Vector3(data[i][1], data[i][2], data[i][3]);
dataPoint.url = "audio/" + data[i][4];
dataPoint.meta = this.parseTags(data[i][5], i);
dataPoint.color = new THREE.Color(data[i][6]);
this.parseTagColors(dataPoint, 'phonem');
parsedPoints.push(dataPoint);
}
},
/**
* Parses tag JSON into tag objects.
* @param {array} tags - array of {key: foo, value: bar} objects
* @param {number} pointIndex - index of current dataPoint
* @returns {array} Array that includes tag information for a point {key: foor, values: []}
*/
parseTags: function(tags, pointIndex) {
var meta = [],
tagKey,
tagVal,
tagIndex,
values,
valueIndex;
for (var i = 0; i < tags.length; i++) {
tagKey = tags[i].key;
tagVal = tags[i].val;
// Parse tag for a point object
tagIndex = this.addTwoPropertyObject(meta, 'key', tagKey, 'values', new Array());
meta[tagIndex].values.push(tagVal);
// Parse tag for parsedTag array
tagIndex = this.addTwoPropertyObject(parsedTags, 'key', tagKey, 'values', new Array());
values = parsedTags[tagIndex].values;
valueIndex = this.addTwoPropertyObject(values, 'value', tagVal, 'points', new Array());
values[valueIndex].points.push(pointIndex);
}
// Returns array of tag objects for use as a property of a point object
return meta;
},
/**
* Function that maps the color to the correct tag value. Wanted tag is usually the one
* that was used to compute the color og the point.
* @param {any} dataPoint - data point object
* @param {any} tagKey - key value of tag that was used to determine color of the point
*/
parseTagColors: function(dataPoint, tagKey) {
var metaData = dataPoint.meta,
value,
tag;
for (var i = 0; i < metaData.length; i++) {
tag = metaData[i];
if (tag.key === tagKey) {
value = tag.values[0];
}
}
if (!tagColors.has(value)) {
tagColors.set(value, dataPoint.color);
}
},
/**
* Computes color for every datapoint and sets the color of each point.
* Used when no color information is provided in data JSON
* @param {JSON} data - data in JSON format
*/
computeColorInformation: function(data) {
var maxEuc = 0,
minEuc = Number.MAX_VALUE,
maxZ = 0,
hueOffset = 20,
hues = [];
for (i = 0; i < data.length; i++) {
var x = Math.pow(parsedPoints[i].x, 2);
var y = Math.pow(parsedPoints[i].y, 2);
var z = Math.pow(parsedPoints[i].z, 2);
var hue = Math.sqrt(x + y + z);
hues.push(hue);
maxZ = Math.max(maxZ, z);
maxEuc = Math.max(maxEuc, hue);
minEuc = Math.min(minEuc, hue);
}
for (i = 0; i < data.length; i++) {
var color = new THREE.Color();
var lightness = parsedPoints[i].z / (2 * maxZ);
color.setHSL((hues[i] - minEuc + hueOffset) / (maxEuc - minEuc), 1, lightness + 0.5);
parsedPoints[i].color = color;
}
},
/**
* Adds an object with two properties to an array, if it doesnt exist, and returns index of that object.
* @param {array} array - array to wich object will be added
* @param {string} firstKey - name (key) of the first property
* @param {any} firstValue - value of the first property
* @param {string} secondKey - name (key) of the second property
* @param {any} secondValue - value of the second property
* @returns {number} Index of the object
*/
addTwoPropertyObject: function(array, firstKey, firstValue, secondKey, secondValue) {
var valueIndex = this.getObjectIndex(array, firstKey, firstValue);
if (valueIndex === -1) {
var metaTag = {};
metaTag[firstKey] = firstValue;
metaTag[secondKey] = secondValue;
array.push(metaTag);
return array.length - 1;
}
return valueIndex;
},
/**
* Returns index of an object with desired value of a property
* @param {array} array - array that will be searched
* @param {string} propertyName - name of the attribute that will be compared
* @param {any} value - wanted value of the attribute
* @returns {number} Index of an object
*/
getObjectIndex: function(array, propertyName, value) {
for (var i = 0; i < array.length; i++) {
var object = array[i];
if (array[i][propertyName] === value) {
return i;
}
}
return -1;
},
getTag: function(key) {
var index = this.getObjectIndex(parsedTags, 'key', key)
if (index === -1) {
return undefined;
}
return parsedTags[index];
},
getTotalPoints: function() {
return total;
},
getUrl: function(index) {
return parsedPoints[index].url;
},
getPoint: function(index) {
return parsedPoints[index];
},
getColor: function(index) {
return parsedPoints[index].color;
},
getTags: function() {
return parsedTags;
},
getTagColor: function(tag) {
return tagColors.get(tag);
}
};
| JavaScript | 0.000002 | @@ -733,32 +733,62 @@
int);%0A %7D%0A
+ this.sortTagValues();%0A
%7D,%0A%0A /**%0A
@@ -5358,32 +5358,498 @@
urn -1;%0A %7D,%0A%0A
+ /**%0A * Sorts tag values alphabetically%0A */%0A sortTagValues: function() %7B%0A for (var i = 0; i %3C parsedTags.length; i++) %7B%0A var values = parsedTags%5Bi%5D.values;%0A values.sort(function(a, b) %7B%0A if (a.value %3C b.value) %7B%0A return -1%0A %7D%0A if (a.value %3E b.value) %7B%0A return 1;%0A %7D%0A return 0;%0A %7D)%0A %7D%0A %7D,%0A%0A
getTag: func
|
29cb67b3a7b126ee57864c1df35fcc40a8588f5a | undo the change just done | modules/core/client/services/core.model.service.js | modules/core/client/services/core.model.service.js | 'use strict';
// =========================================================================
//
// this is intended to be a sort of base class for all crud services in the
// client, just to avoid retyping everything over and over again
//
// =========================================================================
angular.module('core').factory ('ModelBase', ['EsmLog', '$http', '_', function (log, $http, _) {
var ModelBase = function (o) {
this.model = null; // the current loaded model
this.collection = null; // the current loaded collection
this.modelIsNew = true;
this._init (o);
};
_.extend (ModelBase.prototype, {
//
// this must be extended, it is used to build the service URLs
//
urlName : 'somemodel',
// -------------------------------------------------------------------------
//
// initialize the object, set some instance vars
//
// -------------------------------------------------------------------------
_init : function (o) {
this.urlall = '/api/'+this.urlName;
this.urlbase = '/api/'+this.urlName+'/';
this.urlnew = '/api/new/'+this.urlName;
_.bindAll (this);
},
// -------------------------------------------------------------------------
//
// gets the listing of all whatever things this is and sets the local
// collection to that. The collection can then be pivoted on or somehow
// else manipulated for display purposes. also returns the listing through
// the promise resolution.
//
// -------------------------------------------------------------------------
getCollection: function () {
var self = this;
return new Promise (function (resolve, reject) {
self.all ().then (function (res) {
self.collection = res.data;
resolve (res.data);
}).catch (function (res) {
reject (res.data);
});
});
},
// -------------------------------------------------------------------------
//
// load a model from the server, set the local and resolve it
//
// -------------------------------------------------------------------------
getModel: function (id) {
var self = this;
return new Promise (function (resolve, reject) {
self.get (id).then (function (res) {
self.model = res.data;
self.modelIsNew = false;
resolve (res.data);
}).catch (function (res) {
reject (res.data);
});
});
},
// -------------------------------------------------------------------------
//
// load a query result from the server, set the local and resolve it
//
// -------------------------------------------------------------------------
getQuery: function (q) {
var self = this;
return new Promise (function (resolve, reject) {
self.query (q).then (function (res) {
self.collection = res.data;
resolve (res.data);
}).catch (function (res) {
reject (res.data);
});
});
},
// -------------------------------------------------------------------------
//
// get a new empty model
//
// -------------------------------------------------------------------------
getNew: function () {
var self = this;
return new Promise (function (resolve, reject) {
self.new ().then (function (res) {
self.model = res.data;
self.modelIsNew = true;
resolve (res.data);
}).catch (function (res) {
reject (res.data);
});
});
},
// -------------------------------------------------------------------------
//
// get a copy of the current model
//
// -------------------------------------------------------------------------
getCopy: function () {
return _.cloneDeep (this.model);
},
// -------------------------------------------------------------------------
//
// set the current model
//
// -------------------------------------------------------------------------
setModel: function (obj) {
this.modelIsNew = false;
this.model = obj;
},
// -------------------------------------------------------------------------
//
// short hand for saving a copy
//
// -------------------------------------------------------------------------
saveCopy: function (obj) {
this.model = obj;
this.modelIsNew = false;
return this.saveModel ();
},
// -------------------------------------------------------------------------
//
// Save the current model
//
// -------------------------------------------------------------------------
saveModel: function () {
var self = this;
console.log('save or add', self.modelIsNew, this);
return new Promise (function (resolve, reject) {
var p = (self.modelIsNew) ? self.add (self.model) : self.save (self.model);
p.then (function (res) {
console.log ('model saved, setting model to ',res.data);
self.model = res.data;
self.modelIsNew = false;
resolve (res.data);
}).catch (function (res) {
reject (res.data);
});
});
},
// -------------------------------------------------------------------------
//
// pivot the collection on some field. return an object with keys that are
// the unique values of the field and values that are arrays of the models
// that have that field value
//
// -------------------------------------------------------------------------
pivot: function (field) {
this.pivot = {};
this.pivotField = field || null;
if (!this.pivotField) return null;
var value;
_.each (this.collection, function (model) {
value = model[field];
if (_.isNil (value)) value = '_empty_';
if (!this.pivot[value]) this.pivot[value] = [];
this.pivot[value].push (model);
});
return this.pivot;
},
// -------------------------------------------------------------------------
//
// a bunch of crud stuff
//
// -------------------------------------------------------------------------
new : function () {
return this.mget (this.urlnew);
},
all : function () {
return this.mget (this.urlall);
},
delete : function (id) {
return this.mdel (this.urlbase+id);
},
get : function (id) {
console.log ('this.urlbase = ', this.urlbase);
return this.mget (this.urlbase+id);
},
save : function (obj) {
return this.put (this.urlbase+obj._id, obj);
},
add : function (obj) {
return this.post (this.urlall, obj);
},
query : function (obj) {
return this.put (this.urlall, obj);
},
put : function (url, data) {
return this.talk ('PUT', url, data);
},
post : function (url, data) {
return this.talk ('POST', url, data);
},
mget : function (url) {
console.log ('getting: ', url);
return this.talk ('GET', url, null);
},
mdel : function (url) {
return this.talk ('DELETE', url, null);
},
talk : function (method, url, data) {
return new Promise (function (resolve, reject) {
$http ({method:method, url:url, data:data })
.then (resolve, log.reject (reject));
});
}
});
ModelBase.extend = function (protoProps, staticProps) {
var parent = this; var child;
if (protoProps && _.has(protoProps, 'constructor')) {child = protoProps.constructor;}
else {child = function(){ return parent.apply(this, arguments); }; }
_.extend(child, parent, staticProps);
var Surrogate = function(){ this.constructor = child; };
Surrogate.prototype = parent.prototype;
child.prototype = new Surrogate ();
if (protoProps) _.extend(child.prototype, protoProps);
child.__super__ = parent.prototype;
return child;
};
return ModelBase;
}]);
| JavaScript | 0.000002 | @@ -4161,36 +4161,8 @@
bj;%0A
-%09%09%09this.modelIsNew = false;%0A
%09%09%09r
|
30e5d13006577c45c354efb998c9389e71329063 | rename Warning to WarningType | modules/gob-object-student/find-course-warnings.js | modules/gob-object-student/find-course-warnings.js | // @flow
import flatten from 'lodash/flatten'
import compact from 'lodash/compact'
import some from 'lodash/some'
import zip from 'lodash/zip'
import ordinal from 'ord'
import oxford from 'listify'
import {findTimeConflicts} from '@gob/schedule-conflicts'
import {expandYear, semesterName} from '@gob/school-st-olaf-college'
import type {Course, CourseError} from '@gob/types'
import type {ScheduleType} from './schedule'
export type WarningTypeEnum =
| 'invalid-semester'
| 'invalid-year'
| 'time-conflict'
export type Warning = {
warning: true,
type: WarningTypeEnum,
msg: string,
}
export function checkForInvalidYear(
course: Course,
scheduleYear: number,
): ?Warning {
if (course.semester === 9 || course.semester === undefined) {
return null
}
let thisYear = new Date().getFullYear()
if (course.year !== scheduleYear && scheduleYear <= thisYear) {
const yearString = expandYear(course.year, true, '–')
return {
warning: true,
type: 'invalid-year',
msg: `Wrong Year (originally from ${yearString})`,
}
}
return null
}
export function checkForInvalidSemester(
course: Course,
scheduleSemester: number,
): ?Warning {
if (course.semester === undefined) {
return null
}
if (course.semester !== scheduleSemester) {
const semString = semesterName(course.semester)
return {
warning: true,
type: 'invalid-semester',
msg: `Wrong Semester (originally from ${semString})`,
}
}
return null
}
export function checkForInvalidity(
courses: Array<Course>,
{year, semester}: {year: number, semester: number},
): Array<[?Warning, ?Warning]> {
return courses.map(course => {
let invalidYear = checkForInvalidYear(course, year)
let invalidSemester = checkForInvalidSemester(course, semester)
return [invalidYear, invalidSemester]
})
}
export function checkForTimeConflicts(courses: Array<Course>): Array<?Warning> {
let conflicts = findTimeConflicts(courses)
conflicts = conflicts.map(conflictSet => {
if (some(conflictSet)) {
// +1 to the indices because humans don't 0-index lists
const conflicts = compact(
conflictSet.map(
(possibility, i) => (possibility === true ? i + 1 : false),
),
)
const conflicted = conflicts.map(i => `${i}${ordinal(i)}`)
const conflictsStr = oxford(conflicted, {oxfordComma: true})
const word = conflicts.length === 1 ? 'course' : 'courses'
return {
warning: true,
type: 'time-conflict',
msg: `Time conflict with the ${conflictsStr} ${word}`,
}
}
return null
})
return conflicts
}
export function findWarnings(
courses: Array<Course | CourseError>,
schedule: ScheduleType,
): Array<Array<?Warning>> {
let {year, semester} = schedule
let onlyCourses: Array<Course> = (courses.filter(
(c: any) => !c.error,
): Array<any>)
let warningsOfInvalidity = checkForInvalidity(onlyCourses, {year, semester})
let timeConflicts = checkForTimeConflicts(onlyCourses)
let nearlyMerged: Array<Array<Array<?Warning>>> = (zip(
warningsOfInvalidity,
timeConflicts,
): Array<any>)
let allWarnings = nearlyMerged.map(flatten)
return allWarnings
}
| JavaScript | 0 | @@ -532,13 +532,17 @@
ning
+Type
= %7B%0A
-
%09war
@@ -674,32 +674,36 @@
ber,%0A): ?Warning
+Type
%7B%0A%09if (course.s
@@ -1161,16 +1161,20 @@
?Warning
+Type
%7B%0A%09if (
@@ -1590,16 +1590,20 @@
?Warning
+Type
, ?Warni
@@ -1604,16 +1604,20 @@
?Warning
+Type
%5D%3E %7B%0A%09re
@@ -1889,16 +1889,20 @@
?Warning
+Type
%3E %7B%0A%09let
@@ -2673,16 +2673,20 @@
?Warning
+Type
%3E%3E %7B%0A%09le
@@ -2943,16 +2943,16 @@
urses)%0A%0A
-
%09let nea
@@ -2988,16 +2988,20 @@
?Warning
+Type
%3E%3E%3E = (z
|
1433a2c013aa6b9c2d5956f84a5b76d39632a73a | remove a blank line | modules/gob-web/components/area-of-study/picker.js | modules/gob-web/components/area-of-study/picker.js | // @flow
import React from 'react'
import Select from 'react-select'
import uniqueId from 'lodash/uniqueId'
import type {OptionType} from 'react-select/src/types'
import {AreaOfStudyProvider} from './provider'
import type {ParsedHansonFile} from '@gob/hanson-format'
import {filterAreaList} from '@gob/object-student'
export type Selection = {
name: string,
type: string,
revision?: string,
label: string,
value: string,
}
type Props = {
selections: Array<Selection>,
type: string,
label?: string,
onChange: (Array<Selection>) => any,
availableThrough?: number,
}
export function getOptions(
areas: Array<ParsedHansonFile>,
type: string,
availableThrough?: number,
): Array<OptionType> {
areas = areas.filter(a => a.type === type)
let filtered = areas
if (availableThrough != null) {
filtered = filterAreaList(areas, availableThrough)
}
return filtered.map(({name, type, revision}) => ({
name,
type,
revision,
value: `${name} (${revision})`,
label: `${name}`,
}))
}
export class AreaPicker extends React.PureComponent<Props> {
id = uniqueId()
render() {
let {selections, type, label, availableThrough} = this.props
let id = `area-picker-${this.id}`
return (
<AreaOfStudyProvider>
{({areas, loading}) => {
let options = getOptions(areas, type, availableThrough)
return (
<>
{label && <label htmlFor={id}>{label}</label>}
<Select
className="react-select"
isClearable={false}
isMulti={true}
isLoading={loading}
name={id}
options={options}
onChange={this.props.onChange}
value={selections}
/>
</>
)
}}
</AreaOfStudyProvider>
)
}
}
| JavaScript | 1 | @@ -1151,17 +1151,16 @@
s.props%0A
-%0A
%09%09let id
|
289e4b5dc1e79259fe3b53b75567d3fc0dd655d1 | Tweak Summary.toText doc | lib/models/summary.js | lib/models/summary.js | var is = require('is');
var Immutable = require('immutable');
var error = require('../utils/error');
var LocationUtils = require('../utils/location');
var File = require('./file');
var SummaryPart = require('./summaryPart');
var SummaryArticle = require('./summaryArticle');
var parsers = require('../parsers');
var Summary = Immutable.Record({
file: File(),
parts: Immutable.List()
}, 'Summary');
Summary.prototype.getFile = function() {
return this.get('file');
};
Summary.prototype.getParts = function() {
return this.get('parts');
};
/**
Return a part by its index
@param {Number}
@return {Part}
*/
Summary.prototype.getPart = function(i) {
var parts = this.getParts();
return parts.get(i);
};
/**
Return an article using an iterator to find it.
if "partIter" is set, it can also return a Part.
@param {Function} iter
@param {Function} partIter
@return {Article|Part}
*/
Summary.prototype.getArticle = function(iter, partIter) {
var parts = this.getParts();
return parts.reduce(function(result, part) {
if (result) return result;
if (partIter && partIter(part)) return part;
return SummaryArticle.findArticle(part, iter);
}, null);
};
/**
Return a part/article by its level
@param {String} level
@return {Article}
*/
Summary.prototype.getByLevel = function(level) {
function iterByLevel(article) {
return (article.getLevel() === level);
}
return this.getArticle(iterByLevel, iterByLevel);
};
/**
Return an article by its path
@param {String} filePath
@return {Article}
*/
Summary.prototype.getByPath = function(filePath) {
return this.getArticle(function(article) {
return (LocationUtils.areIdenticalPaths(article.getPath(), filePath));
});
};
/**
Return the first article
@return {Article}
*/
Summary.prototype.getFirstArticle = function() {
return this.getArticle(function(article) {
return true;
});
};
/**
Return next article of an article
@param {Article} current
@return {Article}
*/
Summary.prototype.getNextArticle = function(current) {
var level = is.string(current)? current : current.getLevel();
var wasPrev = false;
return this.getArticle(function(article) {
if (wasPrev) return true;
wasPrev = article.getLevel() == level;
return false;
});
};
/**
Return previous article of an article
@param {Article} current
@return {Article}
*/
Summary.prototype.getPrevArticle = function(current) {
var level = is.string(current)? current : current.getLevel();
var prev = undefined;
this.getArticle(function(article) {
if (article.getLevel() == level) {
return true;
}
prev = article;
return false;
});
return prev;
};
/**
Render summary as text
@return {Promise<String>}
*/
Summary.prototype.toText = function(parser) {
var file = this.getFile();
var parts = this.getParts();
parser = parser? parsers.getByExt(parser) : file.getParser();
if (!parser) {
throw error.FileNotParsableError({
filename: file.getPath()
});
}
return parser.renderSummary({
parts: parts.toJS()
});
};
/**
Return all articles as a list
@return {List<Article>}
*/
Summary.prototype.getArticlesAsList = function() {
var accu = [];
this.getArticle(function(article) {
accu.push(article);
});
return Immutable.List(accu);
};
/**
Create a new summary for a list of parts
@param {Lust|Array} parts
@return {Summary}
*/
Summary.createFromParts = function createFromParts(file, parts) {
parts = parts.map(function(part, i) {
if (part instanceof SummaryPart) {
return part;
}
return SummaryPart.create(part, i + 1);
});
return new Summary({
file: file,
parts: new Immutable.List(parts)
});
};
module.exports = Summary;
| JavaScript | 0 | @@ -2892,16 +2892,76 @@
s text%0A%0A
+ @param %7BString%7D parseExt Extension of the parser to use%0A
@ret
@@ -3022,25 +3022,27 @@
nction(parse
-r
+Ext
) %7B%0A var
@@ -3102,16 +3102,20 @@
);%0A%0A
+var
parser =
@@ -3120,17 +3120,19 @@
= parse
-r
+Ext
? parser
@@ -3147,17 +3147,19 @@
xt(parse
-r
+Ext
) : file
|
157f55f59a86d0012863fcc328f6487cc139831b | fix reference errors | src/server/game_list.js | src/server/game_list.js | import { v4 } from "uuid"
import Board from "alekhine"
export default class GameList {
constructor() {
this.nodes = {}
this.length = 0
this.head = null
this.tail = null
}
mk(white, black) {
let gid = v4()
// create game object in two parts for closure
this.nodes[gid] = {
next: null,
prev: null,
gid,
state: {
private: {
white,
black,
board: new Board(),
watchers: []
}
}
}
this.nodes[gid].state.public = {
gid,
fen: this.nodes[gid].state.private.board.getFen(),
/*
black: this.clients[black].name,
white: this.clients[white].name,
*/
stashWhite: "",
stashBlack: ""
}
// structural changes
if (this.length === 0) {
this.head = this.nodes[gid]
this.tail = this.nodes[gid]
} else {
this.tail.next = this.nodes[gid]
this.nodes[gid].prev = this.tail
this.tail = this.nodes[gid]
}
this.length++
return gid
}
rm(gid) {
const node = this.nodes[gid]
if (node == null) return; // opponent already quit
if (node.next == null) {
tail = node.prev
} else if (node.prev == null) {
head = node.next
} else {
node.prev.next = node.next
node.next.prev = node.prev
}
delete this.nodes[gid]
this.length--
}
// etc
get_node(gid) {
return this.nodes[gid]
}
get_position(gid) {
if (this.nodes[gid].prev) return this.get_position(this.nodes[gid].prev.gid) + 1
else return 1
}
get_next_or_head(gid) {
return (this.nodes[gid].next) ? this.nodes[gid].next : head
}
get_prev_or_tail(gid) {
return (this.nodes[gid].prev) ? this.nodes[gid].prev : tai
}
add_watcher(sid) {
if (head) {
head.state.private.watchers.push(sid)
//log.debug("added watcher " + sid + "; game_id " + head.state.public.gid)
return head.state.public.gid
} else {
//log.debug("added watcher " + sid + "; no games to watch")
return null
}
}
mv_watcher(sid, from, to) {
const node = this.games.get_node(from)
const watchers = node.state.private.watchers
const watcher_index = watchers.indexOf(sid)
let new_gid = null
if (watcher_index > -1) node.state.private.watchers = watchers.splice(watcher_index, 1)
if (to == "h") {
head.state.private.watchers.push(sid)
new_gid = head.gid
} else if (to == "l") {
if (node.prev) {
node.prev.state.private.watchers.push(sid)
new_gid = node.prev.gid
} else {
tail.state.private.watchers.push(sid)
new_gid = tail.gid
}
} else if (to == "r") {
if (node.next) {
node.next.state.private.watchers.push(sid)
new_gid = node.next.gid
} else {
head.state.private.watchers.push(sid)
new_gid = head.gid
}
} else if (to == "t") {
tail.state.private.watchers.push(sid)
new_gid = tail.gid
}
return new_gid
}
set_board(gid, board) {
this.nodes[gid].state.private.board = board
}
carry_over(gid, piece) {
const ascii = piece.charCodeAt(0)
const node = this.nodes[gid]
let to_gid
if (node.next) {
to_node = node.next
} else if (head.gid != gid) {
to_node = head
} else {
return; // there is only one game in progress, no carry over
}
if (ascii > 64 && ascii < 91) {
to_node.state.public.s_w += piece
} else if (ascii > 96 && ascii < 123) {
to_node.state.public.s_b += piece
}
}
get_states(gid) {
const node = this.nodes[gid]
const states = {}
if (!node) return
states["c"] = node.state.public
if (node.next) {
states["r"] = node.next.state.public
} else if (this.head && this.head.gid != node.gid && (node.prev && this.head.gid != node.prev.gid)) {
states["r"] = head.state.public
} else {
states["r"] = null
}
if (node.prev) {
states["l"] = node.prev.state.public
} else if (this.tail && this.tail.gid != node.gid && (node.next && this.tail.gid != node.next.gid)) {
states["l"] = tail.state.public
} else {
states["l"] = null
}
return states
}
get_watchers(game) {
const node = this.nodes[game]
const watchers = []
if (!node) return
watchers.concat(node.state.private.watchers)
// TODO: add adjacent players
if (node.next) {
watchers.concat(node.next.state.private.watchers)
} else if (head) {
watchers.concat(head.state.private.watchers)
}
if (node.prev) {
watchers.concat(node.prev.state.private.watchers)
} else if (tail) {
watchers.concat(tail.state.private.watchers)
}
return watchers
}
}
| JavaScript | 0.000002 | @@ -3921,16 +3921,21 @@
%5B%22r%22%5D =
+this.
head.sta
@@ -4179,16 +4179,21 @@
%5B%22l%22%5D =
+this.
tail.sta
|
412328629652c4ce3d0af4912ccc3194e24142ce | make ssr properly return 404 | src/server/ssr/index.js | src/server/ssr/index.js | /**
* @flow
* @desc
*/
import React from 'react'
import _ from 'lodash'
import {renderToNodeStream} from 'react-dom/server'
import {ServerStyleSheet, StyleSheetManager} from 'styled-components'
import {configureRootComponent, configureApp} from 'common/app'
import asyncBootstrapper from 'react-async-bootstrapper'
import {AsyncComponentProvider, createAsyncContext} from 'react-async-component'
import HTMLComponent from './HTMLComponent'
import getI18nData from 'server/i18n'
import {matchPath} from 'react-router'
import getStats from './stats'
export default async (req: express$Request, res: express$Response) => {
// probably, it'd better to define these objs in global scope
const {assets, faviconsAssets} = await getStats()
const {isLoggedIn, language} = req.user
const authState = {auth: {isLoggedIn}}
const initialState: Object = {...authState}
const i18n = getI18nData(language)
const sheet = new ServerStyleSheet()
const location: string = req.url
const context = {}
const {store, history, routes} = configureApp(initialState)
const RootComponent: React$Node = configureRootComponent({
store,
history,
routes,
i18n,
SSR: {location, context}
})
const asyncContext = createAsyncContext()
const app = (
<AsyncComponentProvider asyncContext={asyncContext}>
<StyleSheetManager sheet={sheet.instance}>
{RootComponent}
</StyleSheetManager>
</AsyncComponentProvider>
)
// if true - > throw 404, if match found -> 200
const noRequestURLMatch = !_.find(routes, a => matchPath(req.url, a.path))
asyncBootstrapper(app).then(() => {
const appStream = renderToNodeStream(app)
const css: string = sheet.getStyleTags()
const preloadedState: Object = store.getState()
const asyncState = asyncContext.getState()
const props = {
css,
assets,
faviconsAssets,
asyncState,
initialState: preloadedState,
i18n
}
const {beforeAppTag, afterAppTag} = HTMLComponent(props)
const responseStatusCode = noRequestURLMatch ? 404 : 200
res.writeHead(responseStatusCode, {
'Content-Type': 'text/html'
})
res.write(beforeAppTag)
res.write(`<div id="app">`)
appStream.pipe(res, {end: false})
appStream.on('end', () => {
res.write('</div>')
res.write(afterAppTag)
res.end()
})
})
}
| JavaScript | 0.000259 | @@ -49,31 +49,8 @@
ct'%0A
-import _ from 'lodash'%0A
impo
@@ -1388,16 +1388,56 @@
er%3E%0A%09)%0A%0A
+%09// match url against browseable routes%0A
%09// if t
@@ -1509,24 +1509,43 @@
= !
-_.find(routes, a
+routes.filter(r =%3E !!r.path).find(r
=%3E
@@ -1567,14 +1567,9 @@
rl,
-a.path
+r
))%0A%0A
|
ec32a5f5ad4127498808f69dd65918b04cf9c005 | move some variable declarations | src/server/transport.js | src/server/transport.js | var _ = require('../utility');
var logger = require('./logger');
var http = require('http');
var https = require('https');
var jsonBackup = require('json-stringify-safe');
/*
* accessToken may be embedded in payload but that should not be assumed
*
* options: {
* hostname
* protocol
* path
* port
* method
* }
*
* params is an object containing key/value pairs to be
* appended to the path as 'key=value&key=value'
*
* payload is an unserialized object
*/
function get(accessToken, options, params, callback, transportFactory) {
if (!callback || !_.isFunction(callback)) {
callback = function() {};
}
options = options || {};
_.addParamsAndAccessTokenToPath(accessToken, options, params);
options.headers = _headers(accessToken, options);
var t;
if (transportFactory) {
t = transportFactory(options);
} else {
t = _transport(options);
}
if (!t) {
logger.error('Unknown transport based on given protocol: ' + options.protocol);
return callback(new Error('Unknown transport'));
}
var req = t.request(options, function(resp) {
_handleResponse(resp, callback);
});
req.on('error', function(err) {
callback(err);
});
req.end();
}
function post(accessToken, options, payload, callback, transportFactory) {
if (!callback || !_.isFunction(callback)) {
callback = function() {};
}
options = options || {};
if (!payload) {
return callback(new Error('Cannot send empty request'));
}
var stringifyResult = _.stringify(payload, jsonBackup);
if (stringifyResult.error) {
logger.error('Problem stringifying payload. Giving up');
return callback(stringifyResult.error);
}
var writeData = stringifyResult.value;
options.headers = _headers(accessToken, options, writeData);
var t;
if (transportFactory) {
t = transportFactory(options);
} else {
t = _transport(options);
}
if (!t) {
logger.error('Unknown transport based on given protocol: ' + options.protocol);
return callback(new Error('Unknown transport'));
}
var req = t.request(options, function(resp) {
_handleResponse(resp, _wrapPostCallback(callback));
});
req.on('error', function(err) {
callback(err);
});
if (writeData) {
req.write(writeData);
}
req.end();
}
/** Helpers **/
function _headers(accessToken, options, data) {
var headers = (options && options.headers) || {};
headers['Content-Type'] = 'application/json';
if (data) {
try {
headers['Content-Length'] = Buffer.byteLength(data, 'utf8');
} catch (e) {
logger.error('Could not get the content length of the data');
}
}
headers['X-Rollbar-Access-Token'] = accessToken;
return headers;
}
function _transport(options) {
return {http: http, https: https}[options.protocol];
}
function _handleResponse(resp, callback) {
var respData = [];
resp.setEncoding('utf8');
resp.on('data', function(chunk) {
respData.push(chunk);
});
resp.on('end', function() {
respData = respData.join('');
_parseApiResponse(respData, callback);
});
}
function _parseApiResponse(data, callback) {
parsedData = _.jsonParse(data);
if (parsedData.error) {
logger.error('Could not parse api response, err: ' + parsedData.error);
return callback(parsedData.error);
}
data = parsedData.value;
if (data.err) {
logger.error('Received error: ' + data.message);
return callback(new Error('Api error: ' + (data.message || 'Unknown error')));
}
callback(null, data);
}
function _wrapPostCallback(callback) {
return function(err, data) {
if (err) {
return callback(err);
}
if (data.result && data.result.uuid) {
logger.log([
'Successful api response.',
' Link: https://rollbar.com/occurrence/uuid/?uuid=' + data.result.uuid
].join(''));
} else {
logger.log('Successful api response');
}
callback(null, data.result);
}
}
module.exports = {
get: get,
post: post
};
| JavaScript | 0.000002 | @@ -546,32 +546,41 @@
sportFactory) %7B%0A
+ var t;%0A
if (!callback
@@ -601,32 +601,32 @@
on(callback)) %7B%0A
-
callback = f
@@ -787,25 +787,16 @@
tions);%0A
- var t;%0A
if (tr
@@ -1286,16 +1286,25 @@
tory) %7B%0A
+ var t;%0A
if (!c
@@ -1724,16 +1724,16 @@
.value;%0A
+
option
@@ -1787,25 +1787,16 @@
eData);%0A
- var t;%0A
if (tr
|
1a3e591ed192cb334e6d9ea48a0635788a29f59d | Replace UTF-8 with hex in digests and salts | app/main.js | app/main.js | module.exports = function() {
console.log('Initializing...');
const bodyParser = require('body-parser');
const cors = require('cors');
const crypto = require('crypto');
const express = require('express');
const mongoose = require('mongoose');
const morgan = require('morgan');
const passport = require('passport');
const PassportBasicStrategy = require('passport-http').BasicStrategy;
const pbkdf2 = require('pbkdf2');
const basicStrategyConfigurer = require('./auth/basic.js');
const config = require('./config.js');
const dotQueryParser = require('./middleware/dot-query-parser.js');
const errorHandler = require('./middleware/error-handler.js');
const mongooseConnector = require('./database/mongoose-connector.js');
const router = require('./router.js');
const mongooseConnection = mongooseConnector(config, mongoose);
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cors());
app.use(passport.initialize());
if (config.ENVIRONMENT === 'development') {
app.set('json spaces', 2);
app.use(morgan('dev'));
} else {
app.use(morgan('common'));
}
app.use(dotQueryParser);
const digester = function(pw, salt) {
return pbkdf2
.pbkdf2Sync(pw, salt, 16384, 128, 'sha512')
.toString('utf8');
};
basicStrategyConfigurer(
passport,
PassportBasicStrategy,
digester,
mongooseConnection.schemas.User
);
router(
mongooseConnection.schemas,
passport,
app,
digester,
() => crypto.randomBytes(128).toString('utf8')
);
app.use(errorHandler);
app.listen(config.EXPRESS_PORT, () => console.log('Server up!'));
};
| JavaScript | 0.000049 | @@ -1323,20 +1323,19 @@
String('
-utf8
+hex
');%0A %7D;
@@ -1587,12 +1587,11 @@
ng('
-utf8
+hex
')%0A
|
3e11b423a17bbb7516a6df09ed310723aefc78ab | remove operator cache | lib/operator/index.js | lib/operator/index.js | 'use strict'
var Observable = require('../observable')
var _emitInternal = Observable.prototype.emitInternal
var obs = new Observable({
bind: 'parent', // fix the bind -- also do for emitters (fn)
properties: {
operator: '_operator',
order: '_order'
},
define: {
emitInternal: function (data, event, bind, key, trigger, ignore) {
if (this._parent && this._parent.emit && this._parent !== event.origin) {
this._parent.emit(data, event, bind, key, trigger, ignore)
}
return _emitInternal.call(this, data, event, bind, key, trigger, ignore)
}
}
})
module.exports = obs.Constructor
// this is dirty (requiring at the bottom, val uses Operator for instanceof checks)
obs.inject(require('./val'))
| JavaScript | 0.000001 | @@ -591,11 +591,358 @@
%0A %7D
+,%0A on: %7B%0A parent: %7B%0A operatorCache: removeOperatorsCache%0A %7D,%0A remove: %7B%0A operatorCache: function () %7B%0A var parent = this.parent%0A if (parent) %7B%0A removeOperatorsCache(parent)%0A %7D%0A %7D%0A %7D%0A %7D%0A%7D)%0A%0Afunction removeOperatorsCache (parent) %7B%0A if (parent._operators) %7B%0A delete parent._operators%0A %7D
%0A%7D
-)
%0A%0Amo
@@ -972,17 +972,16 @@
tructor%0A
-%0A
// this
|
8748966e817a006bf9878f6ff59d02a579df31f3 | Update the bounce sample | example/bounce.js | example/bounce.js | exports.run = function() {
var w = Ti.UI.createWindow({
backgroundColor: "white",
title: "Rotate and Bounce",
fullscreen: false
}),
view1 = Ti.UI.createView({
backgroundColor: "red",
top: "16dp", left: "32dp",
right: "32dp", height: "280dp"
}),
view2 = Ti.UI.createView({
backgroundColor: "blue",
top: "0dp", left: "0dp",
width: "30dp", height: "30dp"
}),
view3 = Ti.UI.createView({
backgroundColor: "blue",
top: "0dp", right: "0dp",
width: "30dp", height: "30dp"
}),
button = Ti.UI.createButton({
top: "312dp", left: "32dp", width: "150dp",
height: "48dp", title: "Animate"
}),
animMod = require("com.billdawson.timodules.animation");
w.add(button);
w.add(view1);
view1.add(view2);
view1.add(view3);
function runAnimation() {
animMod.viewPropertyAnimator.animate(view2)
.setInterpolator(animMod.BOUNCE_INTERPOLATOR)
.setDuration(3000)
.xBy("200dp")
.yBy("250dp")
.rotationBy(360 * 4)
.withEndAction(function() {
animMod.viewPropertyAnimator.animate(view2)
.setDuration(800)
.setInterpolator(animMod.LINEAR_INTERPOLATOR)
.setStartDelay(2000)
.xBy("-200dp")
.yBy("-250dp")
.rotationBy(-360*4);
});
animMod.viewPropertyAnimator.animate(view3)
.setInterpolator(animMod.BOUNCE_INTERPOLATOR)
.setDuration(3000)
.xBy("-200dp")
.yBy("250dp")
.rotationBy(-360 * 4)
.withEndAction(function() {
animMod.viewPropertyAnimator.animate(view3)
.setDuration(800)
.setInterpolator(animMod.LINEAR_INTERPOLATOR)
.setStartDelay(2000)
.xBy("200dp")
.yBy("-250dp")
.rotationBy(360*4);
});
}
button.addEventListener("click", runAnimation);
w.open();
};
| JavaScript | 0 | @@ -790,16 +790,42 @@
ion() %7B%0A
+%09%09button.enabled = false;%0A
%09%09animMo
@@ -862,16 +862,16 @@
(view2)%0A
-
%09%09%09.setI
@@ -925,32 +925,53 @@
tDuration(3000)%0A
+%09%09%09.setStartDelay(0)%0A
%09%09%09.xBy(%22200dp%22)
@@ -1245,24 +1245,91 @@
onBy(-360*4)
+%0A%09%09%09%09.withEndAction(function() %7B%0A%09%09%09%09%09button.enabled = true;%0A%09%09%09%09%7D)
;%0A%09%09%09%7D);%0A%09%09a
@@ -1438,24 +1438,45 @@
ation(3000)%0A
+%09%09%09.setStartDelay(0)%0A
%09%09%09.xBy(%22-20
@@ -1728,32 +1728,32 @@
%09.yBy(%22-250dp%22)%0A
-
%09%09%09%09.rotationBy(
@@ -1758,16 +1758,83 @@
y(360*4)
+%0A%09%09%09%09.withEndAction(function() %7B%0A%09%09%09%09%09button.enabled = true;%0A%09%09%09%09%7D)
;%0A%09%09%09%7D);
|
bcd77361cd13268157578c87bd0b02c8a4e03330 | fix invalid `envs` option | example/config.js | example/config.js | 'use strict';
// npm install gulp gulp-eslint
const gulp = require('gulp');
const eslint = require('..');
/**
* Simple example of using ESLint and a formatter
* Note: ESLint does not write to the console itself.
* Use format or formatEach to print ESLint results.
* @returns {stream} gulp file stream
*/
gulp.task('basic', () => {
return gulp.src('../test/fixtures/**/*.js')
// default: use local linting config
.pipe(eslint())
// format ESLint results and print them to the console
.pipe(eslint.format());
});
/**
* Inline ESLint configuration
* @returns {stream} gulp file stream
*/
gulp.task('inline-config', () => {
return gulp.src('../test/fixtures/**/*.js')
.pipe(eslint({
rules: {
'no-alert': 0,
'no-bitwise': 0,
'camelcase': 1,
'curly': 1,
'eqeqeq': 0,
'no-eq-null': 0,
'guard-for-in': 1,
'no-empty': 1,
'no-use-before-define': 0,
'no-obj-calls': 2,
'no-unused-vars': 0,
'new-cap': 1,
'no-shadow': 0,
'strict': 2,
'no-invalid-regexp': 2,
'comma-dangle': 2,
'no-undef': 1,
'no-new': 1,
'no-extra-semi': 1,
'no-debugger': 2,
'no-caller': 1,
'semi': 1,
'quotes': 0,
'no-unreachable': 2
},
globals: ['$'],
envs: {
'node': true
}
}))
.pipe(eslint.format());
});
/**
* Load configuration file
* @returns {stream} gulp file stream
*/
gulp.task('load-config', () => {
return gulp.src('../test/fixtures/**/*.js')
.pipe(eslint({
// Load a specific ESLint config
configFile: 'config.json'
}))
.pipe(eslint.format());
});
/**
* Shorthand way to load a configuration file
* @returns {stream} gulp file stream
*/
gulp.task('load-config-shorthand', () => {
return gulp.src('../test/fixtures/**/*.js')
// Load a specific ESLint config
.pipe(eslint('config.json'))
.pipe(eslint.format());
});
/**
* The default task will run all above tasks
*/
gulp.task('default', [
'basic',
'inline-config',
'load-config',
'load-config-shorthand'
], () => {
console.log('All tasks completed successfully.');
});
| JavaScript | 0 | @@ -1247,32 +1247,16 @@
vs:
-%7B%0A%09%09%09%09'node': true%0A%09%09%09%7D%0A
+%5B'node'%5D
%0A%09%09%7D
|
c2c711f7896ad4cf405e239a4d37dd8112fd288a | Handle 404 from BitBucket API | chrome-extension/app/scripts/bitbucket.js | chrome-extension/app/scripts/bitbucket.js | var BitBucket = {
hasLogin: function () {
return !!localStorage['bitbucketLogin'] && !!localStorage['bitbucketRepo'];
},
getLastChangeset: function (user, repo, callback, fail) {
var url = "https://bitbucket.org/api/1.0/repositories/" + user + "/" + repo + "/changesets/";
$.ajax({
dataType: "json",
url: url,
data: {limit: 1},
success: callback,
statusCode: {
403: function () {
fail("Forbidden: please, sign in into your accout")
}
}
});
},
requestStatus: function () {
if (!this.hasLogin()) return;
var user = localStorage['bitbucketLogin'];
var repo = localStorage['bitbucketRepo'];
console.log("BitBucket.requestStatus")
BitBucket.getLastChangeset(user, repo, function (response) {
console.log("Got BitBucket changesets:", response);
var changesets = response.changesets;
console.log("timestamp", changesets[0].timestamp);
console.log(Date.parse(changesets[0].timestamp));
chrome.runtime.sendMessage({
requestType: 'status',
name: 'bitbucket',
okDate: changesets.length? Date.parse(changesets[0].timestamp) : null
});
}, function (reason) {
console.log("BB error", reason);
chrome.runtime.sendMessage({
requestType: 'status',
name: 'bitbucket',
okDate: null,
error: reason
});
});
}
}
| JavaScript | 0 | @@ -493,16 +493,124 @@
ccout%22)%0A
+ %7D,%0A 404: function () %7B%0A fail(%22Not found: please, sign in or check repository name%22)%0A
|
a9334fe87488a74410f502a0ced8c2df0145f042 | Support for david.nhachot.info and dl.nhachot.info | src/sites/link/adfly.js | src/sites/link/adfly.js | (function () {
'use strict';
var hostRule = /^(www\.)?adf\.(ly|acb\.im|sazlina\.com)|[jq]\.gs|go\.(phpnulledscripts|nicoblog-games)\.com|ay\.gy|(chathu|alien)\.apkmania\.co|ksn\.mx|goto\.adflytutor\.com|dl\.apkpro\.net|adf(ly\.itsrinaldo|\.tuhoctoan)\.net|.*\.gamecopyworld\.com$/;
$.register({
rule: {
host: hostRule,
path: /\/locked$/,
query: /url=([^&]+)/,
},
start: function (m) {
$.resetCookies();
$.openLink('/' + m.query[1]);
},
});
$.register({
rule: {
host: hostRule,
// FIXME this pattern is not stable
path: /^\/([a-z\/]{2,})?$/,
},
});
$.register({
rule: {
host: hostRule,
},
ready: function () {
$.removeNodes('iframe');
var h = unsafeWindow.eu;
if (!h) {
h = $('#adfly_bar');
unsafeWindow.close_bar();
return;
}
var a = h.indexOf('!HiTommy'), b = '';
if (a >= 0) {
h = h.substring(0, a);
}
a = '';
for (var i = 0; i < h.length; ++i) {
if (i % 2 === 0) {
a = a + h.charAt(i);
} else {
b = h.charAt(i) + b;
}
}
h = atob(a + b);
h = h.substr(2);
if (location.hash) {
h += location.hash;
}
$.openLink(h);
},
});
$.register({
rule: 'http://ad7.biz/*.php',
});
$.register({
rule: 'http://ad7.biz/*',
ready: function () {
$.removeNodes('iframe');
$.resetCookies();
var script = $.$$('script').find(function (v) {
if (v.innerHTML.indexOf('var r_url') < 0) {
return _.nop;
}
return v.innerHTML;
});
var url = script.payload.match(/&url=([^&]+)/);
url = url[1];
$.openLink(url);
},
});
})();
// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
| JavaScript | 0 | @@ -276,16 +276,42 @@
rld%5C.com
+%7C(dl%7Cdavid)%5C.nhachot%5C.info
$/;%0A%0A $
|
0333a3d9584cae798d9cd6274dddf02e15fef20d | Fix lint errors | example/script.js | example/script.js | var tabs = require('../'),
events = require('chi-events');
var myTabs = tabs(document.querySelector('#my-tabs'));
events(document.querySelector('#select-first')).on('click', function() {
myTabs.select(0);
});
events(document.querySelector('#select-dogs')).on('click', function() {
myTabs.select(document.querySelector('#dogs'));
}); | JavaScript | 0.000396 | @@ -54,16 +54,48 @@
events')
+,%0A document = window.document
;%0A%0Avar m
@@ -368,12 +368,13 @@
dogs'));%0A%7D);
+%0A
|
3340af44e4fafcf4510b9212ea92aceeb1d306a5 | Fix localstorage bug | backends/browser_localstorage.js | backends/browser_localstorage.js | var cache = false;
module.exports = {
write: function(str) {
if(typeof window == 'undefined' || !window.localStorage ||
typeof JSON == 'undefined' || !JSON.stringify) return;
if(!cache) { cache = window.localStorage.minilog || []; }
cache.push(new Date().toString() + ' '+ str);
window.localStorage.minilog = JSON.stringify(cache);
},
end: function() {}
};
| JavaScript | 0.000002 | @@ -172,16 +172,31 @@
tringify
+ %7C%7C !JSON.parse
) return
@@ -222,16 +222,17 @@
cache =
+(
window.l
@@ -255,13 +255,55 @@
log
-%7C%7C
+? JSON.parse(window.localStorage.minilog) :
%5B%5D
+)
; %7D%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.