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
|
---|---|---|---|---|---|---|---|
09771caf4c859b39327ed886c572c1a1faef1bbd
|
Add github status report
|
app.js
|
app.js
|
var express = require('express'), app = express(), swig = require('swig');
var bodyParser = require('body-parser');
app.engine('html', swig.renderFile);
app.set('view engine', 'html');
app.set('views', __dirname + '/pages');
app.set('view cache', false);
swig.setDefaults({ cache: false });
app.use(express.static(__dirname + '/public'));
app.use(bodyParser());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.get('/', function(req, res){
res.render('index', { 'foo': 'hi' });
});
app.post('/hook', function(req, res){
console.log(req.body);
res.end();
});
app.listen(2345);
|
JavaScript
| 0.000001 |
@@ -108,16 +108,76 @@
arser');
+%0Avar https = require('https'), config = require('./config');
%0A%0Aapp.en
@@ -515,16 +515,17 @@
eq, res)
+
%7B%0A%09res.r
@@ -598,18 +598,55 @@
eq, res)
+ %7B%0A%09if (req.body && req.body.after)
%7B%0A
+%09
%09console
@@ -654,18 +654,267 @@
log(
-req.body);
+%22checking: %22 + req.body.after);%0A%09%09var request = https.request(%7B 'host': 'api.github.com', %0A%09%09%09'path': '/repos/' + config.repoURL + '/status/' + req.body.after,%0A%09%09%09'method': 'POST'%7D);%0A%09%09request.write(JSON.stringify(%7B 'state': 'pending' %7D));%0A%09%09request.end();%0A%09%7D
%0A%09re
|
728d6f1240d992d31733e2f5c6d47161df3afff0
|
Change mongodb IP
|
app.js
|
app.js
|
var express = require('express');
var app = express();
var csvjson = require('csvjson');
var traverse = require('traverse');
//var knayi = require("knayi-myscript");
// Retrieve
var MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID;
var dbhost="mongodb://10.240.33.97:27017/elecapi";
var pagesize=20;
var page=1;
var fixDate=function(item){
if(item===null) return item;
if(item.establishment_approval_date!==null) item.establishment_approval_date =new Date(item.establishment_approval_date).getTime();
if(item.registration_application_date!==null) item.registration_application_date =new Date(item.registration_application_date).getTime();
if(item.registration_approval_date!==null) item.registration_approval_date =new Date(item.registration_approval_date).getTime();
if(item.establishment_date!==null) item.establishment_date =new Date(item.establishment_date).getTime();
item.created_at=new Date(item.created_at).getTime();
item.updated_at=new Date(item.updated_at).getTime();
return item;
};
app.use(express.static('app'));
app.get('/',function(req,res){
pagesize=20;
page=1;
if(typeof req.query.per_page!=='undefined'){
pagesize=parseInt(req.query.per_page);
}
if(typeof req.query.page!=='undefined'){
page=parseInt(req.query.page);
}
MongoClient.connect(dbhost, function(err, db) {
var collection = db.collection('party');
collection.count(function(err, count) {
if(err)
res.json({
_meta:{
status:"error"
}
});
else{
collection.find({},{_id:0}).skip(pagesize*(page-1)).limit(pagesize).toArray(function(err, items) {
if(err)
res.json({
_meta:{
status:"error"
}
});
else{
for (var i = 0; i < items.length; i++) {
items[i]=fixDate(items[i]);
}
respond(req,res,items,count);
}
});
}
});
});
});
app.get('/:id',function(req,res){
pagesize=1;
page=1;
var id=parseInt(req.params.id);
MongoClient.connect(dbhost, function(err, db) {
var collection = db.collection('party');
collection.findOne({id:id},{fields:{_id:0}},function(err, item) {
if(err)
res.json({
_meta:{
status:"error"
}
});
else{
item=fixDate(item);
respond(req,res,item,null);
}
});
});
});
var server = app.listen(process.env.PORT || '8080', '0.0.0.0', function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
function respond(req,res,data,total){
var length=1;
var unicode=true;
var format="unicode";
var total_pages=Math.ceil(total/pagesize);
var links={
next:'?page='+(page+1),
previous:'?page='+(page-1)
};
if(total===null){
links=null;
total_pages=1;
}
else {
if(page===1){
links.previous=null;
}
if(page===total_pages){
links.next=null;
}
}
if(Array.isArray(data)) length=data.length;
var resp={
_meta:{
status:"ok",
count:total,
api_version: 1,
unicode:unicode,
format:format,
per_page:pagesize,
current_page:page,
total_pages:total_pages,
links:links
},
data:data
};
res.header("Access-Control-Allow-Origin", "*");
res.json(resp);
}
function zawuni(obj){
traverse(obj).forEach(function (x) {
if (typeof x !== "object") {
this.update(knayi(x).fontConvertSync('unicode5'));
}
});
return obj;
}
function unizaw(obj){
traverse(obj).forEach(function (x) {
if (typeof x !== "object") {
this.update(knayi(x).fontConvertSync('zawgyi'));
}
});
return obj;
}
module.exports = app;
|
JavaScript
| 0.000001 |
@@ -298,13 +298,11 @@
240.
-33.97
+0.2
:270
|
504789b1900f097fc7d7b9e0c301d64bab5b77a6
|
Comment out d3
|
app.js
|
app.js
|
//require('newrelic');
var INSTANCE = {
processVerisons: process.versions,
processTitle: process.title,
processPID: process.pid,
startTime: process.hrtime(),
platform: process.platform,
arch: process.arch,
memory: process.memoryUsage(),
uptime: process.uptime(),
network: require('os').networkInterfaces(),
};
console.log(INSTANCE);
//ENV Vars and application arguments
var env = process.env.NODE_ENV || 'development';
//console.log(process.env);
// all environments
var appPort = process.argv[2];
// print process.argv
process.argv.forEach(function (val, index, array) {
console.log(index + ': ' + val);
});
//DEPENDS Vars
//var ghost = require('ghost');
var favicon = require('favicon');
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
//var _io = require('socket.io');
//var passport = require('passport');
var d3 = require('d3');
//var cradle = require('cradle');
//DB config
//cradle.setup({
// host: 'localhost',
// cache: true,
// raw: false,
// forceSave: true
//});
//var dbconnection = new(cradle.Connection)('http://localhost', 5984, {
// cache: true,
// raw: false,
// forceSave: true
//});
//var db = dbconnection.database('funkytown');
//db.exists(function(err, exists) {
// if (err) {
// console.log('error', err);
// } else if (exists) {
// console.log('the force is with you.');
// } else {
// console.log('database does not exists.');
// db.create();
// }
//});
//Application config
var app = express();
app.set('port', process.env.PORT ||3001);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
//app.use(favicon());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
//Application routing
app.get('/', routes.index);
app.get('/users', user.list);
//Maybe use ghost as a blog?
//ghost();
//Create the server instance
var server = http.createServer(app);
server.listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});
//Bind to the websocket
//var io = _io.listen(server);
//
////var geoip = require('geoip-lite');
//
//io.on('connection', function(socket) {
// console.log('a user connected');
// //var address = socket.handshake.address;
// //var geo = geoip.lookup(address.address);
// // console.log(address)
// // console.log(geo);
// socket.emit('news', {
// hello: 'world'
// });
//
// socket.on('windowEvent', function(event) {
// console.log("Event");
//// db.save({
//// dateCreated: new Date().getTime(),
//// headers: socket.client.request.headers,
//// ip: socket.handshake.address,
//// event: event
//// }, function(err, res) {
//// // Handle response
//// console.log(err);
//// });
//
// console.log(event.type);
// });
// socket.on('disconnect', function() {
// db.save({
// headers: socket.client.request.headers,
// ip: socket.handshake.address,
// event: "disconnect"
// }, function(err, res) {
// // Handle response
// });
//
// console.log('disconnected');
// });
//
//});
|
JavaScript
| 0 |
@@ -954,24 +954,26 @@
passport');%0A
+//
var d3 = req
|
5b0a12108d829f4cd397141aa977d776374a33f9
|
send me a body
|
app.js
|
app.js
|
var r = require("request");
var express = require("express");
var app = express();
var path = require('path');
//var twilio = require('twilio')(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);
var twilio = require('twilio');
var moment = require('moment');
var _ = require('lodash');
var qs = require('querystring');
app.use(express.static(path.join(__dirname, 'public')));
// serve public
app.get('/', function (req,res) {
res.redirect(301, 'http://hrtb.us');
});
// app.post('/msg', function (req,res) {
// res.writeHead(200, {'Content-Type': 'text/xml'});
// console.log(JSON.stringify(req.params));
// res.end(getResponse(req.query));
// });
app.post('/msg', function (req,res) {
if (req.method == 'POST') {
var body = '';
req.on('data', function (data) {
body += data;
});
req.on('end', function () {
var POST = qs.parse(body);
//validate incoming request is from twilio using your auth token and the header from Twilio
var token = process.env.TWILIO_AUTH_TOKEN,
header = req.headers['x-twilio-signature'];
res.writeHead(200, { 'Content-Type':'text/xml' });
res.end((getResponse(req.query)));
});
}
else {
res.writeHead(404, { 'Content-Type':'text/plain' });
res.end('send a POST');
}
});
//EVMS/NORFOLK will be here in about 10, the next one in 15
//NEWTOWN ROAD will be here in about 5 minutes and the next
app.set('port', process.env.PORT || 3000);
app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});
function getResponse(message) {
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Response>\n<Message>" + message + "</Message>\n</Response>";
}
function debugging() {
r.get("http://api.hrtb.us/api/stop_times/8004", function (err, response, body) {
console.log("http://api.hrtb.us/api/stop_times/8004");
var test = _.groupBy(JSON.parse(body),"destination");
console.log(test);
});
}
debugging();
|
JavaScript
| 0 |
@@ -1242,16 +1242,21 @@
eq.query
+.Body
)));%0A%0A
|
222c4445ff9a20a2a1aa01dd355bdead37b786a7
|
Add app.js file.
|
app.js
|
app.js
|
var express = require('express');
var app = express();
app.use(express.static('public'));
// app.get('/', function (req, res) {
// res.send(__dirname + 'public/index.html');
// });
app.post('/', function (req, res){
res.send('Got a POST request');
})
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
|
JavaScript
| 0 |
@@ -85,16 +85,98 @@
ic'));%0A%0A
+// TODO: Hook up get route. For when querying by current location is implemented.%0A
// app.g
@@ -183,33 +183,32 @@
et('/', function
-
(req, res) %7B%0A//
@@ -200,18 +200,22 @@
req, res
+ponse
)
-
%7B%0A// r
@@ -216,21 +216,30 @@
// res
+ponse
.send
+File
(__dirna
@@ -277,81 +277,8 @@
);%0A%0A
-app.post('/', function (req, res)%7B%0A res.send('Got a POST request');%0A%7D)%0A%0A
var
@@ -317,17 +317,16 @@
on () %7B%0A
-%0A
var ho
@@ -392,17 +392,16 @@
).port;%0A
-%0A
consol
@@ -464,8 +464,439 @@
t);%0A
-%0A
%7D
+);%0A%0A// =========================================%0A// PROXY SERVER-SIDE CODE%0A// =========================================%0A%0A// var express = require('express');%0A%0A// var portNumber = 3001;%0A// var app = express();%0A%0A// app.get(%22/%22, function (req, res) %7B%0A// res.send(%7B response: %22This is data returned from the server, proxy style!%22 %7D);%0A// %7D)%0A%0A// app.listen(portNumber);%0A%0A// console.log(%22Responding server listening on port %22+portNumber
);
|
682913d8f55caf61c9d0ac1c7a9f3bddcc2968fa
|
Rename the convert command to original name to simplify the setup steps
|
app.js
|
app.js
|
'use strict';
var express = require('express');
var fs = require('fs');
var mkdirp = require('mkdirp');
var path = require('path');
var app = express();
var imageDir = 'image';
mkdirp(imageDir, function (err) {
// path is already exists
});
var avatarGenerator = require('avatar-generator')({
order: 'background face clothes head hair eye mouth'.split(' '),
images: path.join(__dirname, 'node_modules/avatar-generator/img'),
convert: 'convert-image'
});
var avatar = function (id, size, sex) {
size = size || 80;
sex = sex || 'male';
return new Promise(function(resolve) {
var filename = path.join(imageDir, id + '-' + size + '.jpg');
if (fs.existsSync(filename)) {
resolve(filename);
return;
}
avatarGenerator(id, sex, size)
.write(filename, function (err) {
if (err) {
console.log(err);
return;
}
resolve(filename);
});
});
}
app.get('/avatar/:id', function(req, res) {
var id = req.params.id;
var size = req.query.s || req.query.size;
var sex = req.query.x || req.query.sex;
res.header("Content-Type", "image/jpeg");
avatar(id, size, sex).then(function(filename) {
fs.readFile(filename, function (err,data) {
if (err) {
console.log(err);
return;
}
res.send(data);
});
});
});
app.listen(3000);
|
JavaScript
| 0.000008 |
@@ -451,14 +451,8 @@
vert
--image
'%0A%7D)
|
3986653fc115b13075cb81d563fc01cd8b30dda9
|
Clean up confirmation code
|
app.js
|
app.js
|
var restify = require('restify'),
builder = require('botbuilder'),
nconf = require('nconf');
// Create nconf environment to load keys and connections strings
// which should not end up on GitHub
nconf
.file({ file: './config.json' })
.env();
//=========================================================
// Bot Setup
//=========================================================
// Setup Restify Server
var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
console.log('%s listening to %s', server.name, server.url);
});
// Create chat bot
var connector = new builder.ChatConnector({
appId: nconf.get("MICROSOFT_APP_ID"),
appPassword: nconf.get("MICROSOFT_APP_PASSWORD")
});
var bot = new builder.UniversalBot(connector);
server.post('/api/messages', connector.listen());
server.get('/', restify.serveStatic({
'directory' : '.',
'default' : 'static/index.html'
}));
//=========================================================
// Bots Dialogs
//=========================================================
// Create LUIS recognizer that points at our model
var model = nconf.get("LUIS_model_URL");
var recognizer = new builder.LuisRecognizer(model);
var intents = new builder.IntentDialog({ recognizers: [recognizer] });
bot.dialog('/', intents);
intents
//.onBegin(builder.DialogAction.send("Hi, I'm your startup assistant!"))
// Simple regex commands
.matches(/^hello/i, function (session) {
session.send("Hi there!");
})
.matches(/^help/i, function (session) {
session.send("You asked for help.");
})
//LUIS intent matches
.matches('AzureCompliance', '/compliance')
.matches('OfficeHours', '/officehours')
.matches('SupportRequest', '/support')
.matches('Documentation', '/documentation')
.matches('Rude', '/rude')
.onDefault('/didnotunderstand');
bot.dialog('/compliance', [
function (session, args) {
builder.Prompts.text(session, "You asked about Azure Compliance. Is that correct?");
},
function (session, results) {
if (results.response.toLowerCase() == 'y' || results.response.toLowerCase() == 'yes') {
session.endDialog("Ok, I'm getting the hang of things.");
} else {
session.endDialog("Darn. Ok, I've logged this for review.");
}
}
]);
bot.dialog('/officehours', function (session, args) {
session.endDialog("It seems like you want to schedule office hours.");
});
bot.dialog('/support', function (session, args) {
session.endDialog("Sounds like you're having a problem. This is a support request.");
});
bot.dialog('/documentation', function (session, args) {
session.endDialog("It sounds like you're asking for documentation.");
});
bot.dialog('/rude', function (session, args) {
session.endDialog("Well, you're just being rude.");
});
bot.dialog('/didnotunderstand', [
function (session, args) {
builder.Prompts.text(session, "I'm sorry. I didn't understand, but I'm learning. What was your intent here?");
},
function (session, results) {
console.log(session.message.text);
session.endDialog("Ok, I've logged this for review. Please ask another question.");
}
]);
// Install First Run middleware and dialog
bot.use(builder.Middleware.firstRun({ version: 1.0, dialogId: '*:/firstRun' }));
bot.dialog('/firstRun', [
function (session) {
builder.Prompts.text(session, "Hello... What's your name?");
},
function (session, results) {
// We'll save the users name and send them an initial greeting. All
// future messages from the user will be routed to the root dialog.
session.userData.name = results.response;
session.endDialog("Hi %s, ask me a startup question and I'll try to correctly map it to an intent.", session.userData.name);
}
]);
|
JavaScript
| 0 |
@@ -2096,328 +2096,21 @@
-function (session, results) %7B%0A if (results.response.toLowerCase() == 'y' %7C%7C results.response.toLowerCase() == 'yes') %7B%0A session.endDialog(%22Ok, I'm getting the hang of things.%22);%0A %7D else %7B%0A session.endDialog(%22Darn. Ok, I've logged this for review.%22);%0A %7D %0A %0A %7D%0A
+confirmIntent
%0A%5D);
@@ -2136,16 +2136,22 @@
ehours',
+ %5B%0A
functio
@@ -2178,80 +2178,123 @@
-session.endDialog(%22It seems like you want to schedule office hours.%22);%0A%7D
+ builder.Prompts.text(session, %22You asked about Azure Compliance. Is that correct?%22);%0A %7D,%0A confirmIntent%0A%5D
);%0Ab
@@ -2314,16 +2314,22 @@
upport',
+ %5B%0A
functio
@@ -2356,95 +2356,117 @@
-session.endDialog(%22Sounds like you're having a problem. This is a s
+ builder.Prompts.text(session, %22You made a S
upport
-r
+R
equest.
-%22);%0A%7D
+ Is that correct?%22);%0A %7D,%0A confirmIntent%0A%5D
);%0Ab
@@ -2492,16 +2492,22 @@
tation',
+ %5B%0A
functio
@@ -2534,79 +2534,120 @@
-session.endDialog(%22It sounds like you're asking for documentation.%22);%0A%7D
+ builder.Prompts.text(session, %22You asked about Documentation. Is that correct?%22);%0A %7D,%0A confirmIntent%0A%5D
);%0Ab
@@ -2809,32 +2809,75 @@
ession, args) %7B%0A
+ console.log(session.message.text);%0A
builder.
@@ -2977,26 +2977,16 @@
here?%22)
-;%0A
%0A %7D,
@@ -3789,16 +3789,319 @@
ame); %0A %7D%0A%5D);
+%0A%0Afunction confirmIntent (session, results) %7B%0A if (results.response.toLowerCase() == 'y' %7C%7C results.response.toLowerCase() == 'yes') %7B%0A session.endDialog(%22Ok, I'm getting the hang of things.%22);%0A %7D else %7B%0A session.endDialog(%22Darn. Ok, I've logged this for review.%22);%0A %7D %0A%7D
|
3398f26792939a7f86f404eeebbc201be6fa84ec
|
Load NewRelic before any other requirements
|
app.js
|
app.js
|
'use strict';
var express = require('express');
var http = require('http');
var path = require('path');
var io = require('socket.io');
var logger = require('morgan');
var bodyParser = require('body-parser');
var errorHandler = require('errorhandler');
var config = require('./config');
var db = require('./db');
var analytics = require('./analytics');
if (config.newrelic.license_key) {
require('newrelic');
}
var indexRoute = require('./routes/index');
var roomsRoute = require('./routes/rooms');
var app = express();
var server = http.createServer(app);
app.set('port', config.express.port);
app.set('views', path.join(__dirname, '/views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(bodyParser.json({ limit: config.express.request_limit }));
app.use(express.static(path.join(__dirname, 'public')));
if (config.env == 'development') {
app.use(errorHandler());
app.use(function(req, res, next) {
res.locals.isDev = true;
next();
});
} else {
if (analytics.trackingId) {
app.use(analytics.middleware(analytics.trackingId));
}
}
app.use('/', indexRoute);
db.connect(config.mongodb.uri, function(err) {
if (err) {
console.log('Unable to connect to Mongo.');
process.exit(1);
}
server.listen(app.get('port'), config.express.host);
io = io.listen(server);
app.use('/r', roomsRoute('/r', io));
});
|
JavaScript
| 0 |
@@ -8,16 +8,112 @@
rict';%0A%0A
+var config = require('./config');%0A%0Aif (config.newrelic.license_key) %7B%0A require('newrelic');%0A%7D%0A%0A
var expr
@@ -347,42 +347,8 @@
);%0A%0A
-var config = require('./config');%0A
var
@@ -414,68 +414,8 @@
);%0A%0A
-if (config.newrelic.license_key) %7B%0A require('newrelic');%0A%7D%0A
%0Avar
|
de12a9bbff95fa0e27ce94acd00331f73840203f
|
Fix log
|
app.js
|
app.js
|
'use strict';
var http = require('http');
var config = require('./lib/configLoader');
var api = require('./lib/api');
var logger = config.logger;
// Inspired from https://github.com/mojombo/semver/issues/110#issuecomment-19433284, but more permissive (allow leading zeros) and non capturing
var versionRegexp = '(\\d+\\.\\d+\\.\\d+(?:-(?:0|[1-9]\\d*|\\d*[a-zA-Z-][a-zA-Z0-9-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][a-zA-Z0-9-]*))*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?)';
var tarballRegexp = new RegExp('^(\\/@([^/]+))?\\/([^/]+)\\/-\\/[^/]+?-' + versionRegexp + '\\.tgz$');
var moduleRegexp = new RegExp('^\\/[^/]+$');
process.on('uncaughtException', function(err) {
logger.error('Uncaught exception: %s', err);
});
http.createServer(function(req, resp) {
try {
var isGet = req.method === 'GET';
var isTarball = req.url.match(tarballRegexp) != null;
var isModule = req.url.match(moduleRegexp) != null;
if (isGet && isTarball) {
api.manageAttachment(req, resp);
} else if (isGet && isModule) {
api.manageModule(req, resp);
} else {
api.proxyToCentralRepository(req, resp);
}
} catch (error) {
logger.error(error);
}
}).listen(config.port, function() {
logger.info('Server running at http://localhost:%s with config:\n%s', config.port, JSON.stringify(config, null, 4));
});
|
JavaScript
| 0.000002 |
@@ -710,19 +710,44 @@
n: %25s',
-err
+JSON.stringify(err, null, 4)
);%0A%7D);%0A%0A
|
4534166e0363211c16215b3fc3aef5ca26da5a63
|
put access log into file
|
app.js
|
app.js
|
/**
* Module dependencies.
*/
var express = require('express'),
routes = require('./routes'),
about = require('./routes/about'),
builder = require('./routes/builder'),
test = require('./routes/test'),
http = require('http'),
Client = require('cas.js'),
path = require('path');
var app = express();
var cas = new Client({
base_url: 'https://liud-dev.nscl.msu.edu/cas',
service: 'http://localhost:3001',
version: 1.0
});
app.configure(function(){
app.set('port', process.env.PORT || 3001);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon(__dirname + '/public/favicon.ico'));
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('cable_secret'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/about', about.index);
app.get('/', ensureAuthenticated, routes.main);
app.get('/logout', routes.logout);
app.get('/builder', builder.index);
app.get('/test', test.index);
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
function ensureAuthenticated(req, res, next) {
if (req.session.username) {
next();
} else if (req.param('ticket')) {
cas.validate(req.param('ticket'), function(err, status, username) {
if (err) {
res.send(401, err.message);
} else {
req.session.username = username;
next();
}
});
} else {
res.redirect('https://' + cas.hostname + cas.base_path + '/login?service=' + encodeURIComponent(cas.service));
}
}
|
JavaScript
| 0.000001 |
@@ -262,16 +262,38 @@
s.js'),%0A
+ fs = require('fs'),%0A
path =
@@ -329,24 +329,103 @@
express();%0A%0A
+var access_logfile = fs.createWriteStream('./logs/access.log', %7Bflags: 'a'%7D);%0A%0A
var cas = ne
@@ -779,13 +779,32 @@
ger(
-'dev'
+%7Bstream: access_logfile%7D
));%0A
@@ -1362,16 +1362,89 @@
tion()%7B%0A
+ // logger.info(%22Express server listening on port %22 + app.get('port'));%0A
consol
|
cf3374f3a6cea5fdc719a2c45061dad0243e26ca
|
Remove database require
|
app.js
|
app.js
|
'use strict';
require('dotenv').config();
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var express = require('express');
var logger = require('morgan');
var path = require('path');
var database = require('./config/database');
var routes = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
|
JavaScript
| 0 |
@@ -243,53 +243,8 @@
);%0A%0A
-var database = require('./config/database');%0A
var
@@ -250,18 +250,16 @@
routes
-
= requir
|
0c18d156fc58d2e9d6bf18468c1b8209a5aeccf6
|
load mongoose models alongside sequelize models
|
app.js
|
app.js
|
/**
* Not Another Budget App
* 0.0.0
*
*/
// deps
var express = require('express')
var fs = require('fs')
var path = require('path')
var favicon = require('serve-favicon')
var logger = require('morgan')
var cookieParser = require('cookie-parser')
var bodyParser = require('body-parser')
var db = require('mongoose')
/**
* init
*/
// app
var app = express()
app.use(favicon(path.join(__dirname, 'public', 'images', 'favicon.png')))
app.use(logger('dev'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(require('node-sass-middleware')({
src: path.join(__dirname, 'public', 'stylesheets'),
dest: path.join(__dirname, 'public', 'stylesheets'),
outputStyle: 'compressed',
sourceMap: false,
prefix: '/stylesheets'
}))
app.use(express.static(path.join(__dirname, 'public')))
// routes
var routes = require('./routes/index')
app.use('/', routes)
// views
var hbs = require('./config/handlebars')
app.set('views', path.join(__dirname, 'views'))
app.engine('.hbs', hbs.engine)
app.set('view engine', '.hbs')
// models
require('./models').sequelize.sync()
// mongoose models
// fs.readdirSync(__dirname + '/models')
// .map(function(fn) {
// if (~fn.indexOf('.mongoose.js')) require('./models/' + fn)
// })
// import
var importCSV = require('./config/import')
// importCSV(fs.readFileSync('./csv/transactions.csv', 'utf-8'))
// db
db.Promise = global.Promise
db.connect('mongodb://localhost/nab-app')
module.exports = app
|
JavaScript
| 0 |
@@ -1,59 +1,4 @@
-/**%0A * Not Another Budget App%0A * 0.0.0%0A *%0A */%0A%0A// deps%0A
var
@@ -234,18 +234,24 @@
r')%0Avar
-db
+mongoose
= requi
@@ -270,25 +270,8 @@
')%0A%0A
-/**%0A * init%0A */%0A%0A
// a
@@ -1075,18 +1075,14 @@
ose
-models%0A//
+setup%0A
fs.r
@@ -1119,43 +1119,22 @@
s')%0A
-//
+
.map(f
-unction(fn) %7B%0A// if (
+ =%3E
~f
-n
.ind
@@ -1153,17 +1153,19 @@
ose.js')
-)
+ &&
require
@@ -1157,33 +1157,33 @@
js') && require(
-'
+%60
./models/' + fn)
@@ -1179,150 +1179,25 @@
els/
-' + fn)%0A// %7D)%0A%0A// import%0Avar importCSV = require('./config/import')%0A// importCSV(fs.readFileSync('./csv/transactions.csv', 'utf-8'))%0A%0A// db%0Adb
+$%7Bf%7D%60))%0A%0Amongoose
.Pro
@@ -1218,18 +1218,24 @@
Promise%0A
-db
+mongoose
.connect
|
b427e3ba8bc4f04e0b92d6966fd9ce1ce3b9f561
|
allow line break in non code text
|
app.js
|
app.js
|
/**
* Observe DOM mutations and convert monospace code blocks
* @author Tyler Chen, Jesse Mu
*/
var observerConfig = {
childList: true,
subtree: true,
characterData: false,
attributes: false
};
var cfx = []; //ideally array containing all '_3hi clearfix' div
//there is probably a way to avoid having to recreate this every mutation.
function monospaceListen() {
var monospaceObserver = new MutationObserver(function(ms) {
ms.forEach(function(m) {
if (m.addedNodes.length > 0) { //do we even need this part?
console.log(m.addedNodes);
for(l=0; l<m.addedNodes.length; l++){
console.log(m.addedNodes[l].getElementsByClassName( "_38" ));
//there is probably a quicker way to get these elements.
var cfx = m.addedNodes[l].getElementsByClassName( "_38" );
for(c=0; c<cfx.length; c++){
draw(cfx[c].firstChild.firstChild);
//%div._38 -> %span -> %p
}
//cfx = cfx.concat( m.addedNodes[l].getElementsByClassName( "_3hi clearfix" )[0] ); //Y I AM DUM??
}
}
});
});
monospaceObserver.observe(document.getElementById('webMessengerRecentMessages'), observerConfig);
}
//this should return nothing if only one line
function nBuild(newtext) {
n = "";
for (m = 1; m < newtext.split('\n').length + 1; m++) {
n += "<br/>" + m;
}
return n.substring(5, n.length);
}
var del = "```";
var rev = del.split('').reverse().join('');
var text = [];
function draw(em) {
text = em.innerText;
console.log( text );
var stop_index = text.lastIndexOf(rev);
var start_index = text.indexOf(del);
if (stop_index > start_index && start_index > -1) {
var regexExpression = "("+del+"|"+rev+")";
var regex = new RegExp(regexExpression, "g");
var texts = text.split( regex );
var codes = text.match( regex );
var newtext = "";
var text_hold = "";
var code_hold = "";
var state = 0; //1: after code start delimiter but before stop
var words = text.split( regex );
console.log( words );
//http://jsfiddle.net/m9eLk17a/1/
function write(){
for(i = 0; i < words.length; i++){
if( state == 0){
if( words[i] == del){
newtext += "<p>" + text_hold + "</p>";
state = 1;
text_hold = "";
} else {
text_hold += words[i];
}
} else { //state == 1
if( words[i] == rev ){
num = nBuild( code_hold );
if( num == 1){
newtext += "<div class='code inline'>"; //linebreaks next to delimiter not transferring.
} else {
newtext += "<div class='code'><div class='block_container'><div class='numbers'>" + nBuild( code_hold ) +"</div>";
}
newtext += "<pre class='text'>" + code_hold + "</pre></div></div>";
console.log( code_hold );
state = 0;
code_hold = "";
} else {
code_hold += words[i];
}
}
}
newtext += "<p>" + text_hold + code_hold + "</p>"; //would prefer not to change <p> to inline. Either add class or change tag
console.log( newtext );
}
write();
//extra line breaks in block causes it to break...
//extra line breaks of regular text are deleted. This is probably reason for above issue
//two inline blocks in a row have no padding/margin between them.
em.outerHTML = newtext;
console.log(em);
//highlight at some point...
}
}
var checkForMsg = setInterval(function() {
var msgWindow = document.getElementById('webMessengerRecentMessages');
if (msgWindow !== null) {
console.log('found!');
monospaceListen(msgWindow, observerConfig);
clearInterval(checkForMsg);
}
}, 50);
|
JavaScript
| 0.000604 |
@@ -1086,128 +1086,8 @@
%7D%0A
- //cfx = cfx.concat( m.addedNodes%5Bl%5D.getElementsByClassName( %22_3hi clearfix%22 )%5B0%5D ); //Y I AM DUM?? %0A
@@ -1363,10 +1363,13 @@
it('
-%5Cn
+%3Cbr/%3E
').l
@@ -1537,16 +1537,245 @@
= %5B%5D;%0A%0A
+//This function can be redone redone. It's not really that good.%0A//for some reason something like %0A/*%0A%60%60%60code%0A%0Acode%60%60%60%0Abecomes %60%60%60codecode%60%60%60%0Ai think the extra line break means it is split into separate elements or something.%0A*/
%0Afunctio
@@ -1810,16 +1810,40 @@
nnerText
+.replace(/%5Cn/g, %22%3Cbr/%3E%22)
;%0A co
@@ -2473,16 +2473,97 @@
Lk17a/1/
+ %0A //search for %22/n%22 and change to %22%3Cbr/%3E%22. perhaps before creating words
%0A
|
8d8e1a34260484c2ff175a695f0d63c8bbf6ec7a
|
Fix program name in the usage string
|
bin.js
|
bin.js
|
#!/usr/bin/env node
'use strict';
var concat = require('concat-stream')
, prompt = require('cli-prompt')
, uniq = require('uniq')
, output = require('simple-output');
var spawn = require('child_process').spawn
, util = require('util');
output.stdout = output.stderr;
(function (argv) {
if (argv.length != 1) {
output.info('Usage: ' + process.argv[1] + ' <name>');
process.exit(1);
}
var procname = argv[0];
spawn('pgrep', ['-x', procname], {
stdio: 'pipe'
}).stdout.pipe(concat({ encoding: 'string' }, function (pids) {
pids = pids.trim().split(/\s+/).map(Number);
(function printPstrees(pids, index, cb) {
if (index < pids.length) {
spawn('pstree', [pids[index]], {
stdio: 'pipe'
}).stdout.pipe(concat({ encoding: 'string' }, function (tree) {
util.puts(index + ') ' + tree.trim().replace(/\n/g, '\n '));
printPstrees(pids, index + 1, cb);
}));
}
else {
cb();
}
}(pids, 0, function () {
prompt('kill: ', function (indices) {
// If there are no more than 10 matches, a string of digits is a perfectly valid input.
// Otherwise, choices must be separated by commas or spaces.
if (pids.length <= 10) {
indices = indices.match(/\d/g);
}
else {
indices = indices.replace(/,/g, ' ')
.replace(/[^\d\s]+/g, '')
.trim()
.split(/\s+/)
// Mapping to Number will equate 1 and 01.
.map(Number);
}
indices = uniq(indices);
(function killLoop() {
if (indices.length) {
spawn('kill', [pids[indices.shift()]]).on('exit', killLoop);
}
}());
});
}));
}));
}(process.argv.slice(2)));
|
JavaScript
| 0.999996 |
@@ -278,108 +278,139 @@
;%0A%0A%0A
-(function (argv) %7B%0A if (argv.length != 1) %7B%0A output.info('Usage: ' + process.argv%5B1%5D + ' %3Cname%3E'
+var usage = function () %7B%0A output.message('Usage: killsome %3Cname%3E');%0A%7D;%0A%0A%0A(function (argv) %7B%0A if (argv.length != 1) %7B%0A usage(
);%0A
|
4fc926f52a9181f600c83a9352adb6455b899062
|
clarify auto-prefix logic
|
bot.js
|
bot.js
|
'use strict';
const Bot = require('node-telegram-bot-api');
const validator = require('validator');
const TinyURL = require('tinyurl');
const symbols = require('log-symbols');
const bot = new Bot(process.env.TOKEN, {
polling: true
});
const prefixProtocol = url => !/^(?:f|ht)tps?\:\/\//.test(url) ? 'http://' + url : url;
bot.onText(/^\/start$/, msg => {
bot.sendMessage(msg.chat.id, 'Just send me a url and I\'ll shorten it!');
});
bot.onText(/^\/shorten (.+)$/, (msg, match) => {
let url = match[1];
if (validator.isURL(url)) {
TinyURL.shorten(prefixProtocol(url), r => {
bot.sendMessage(msg.chat.id, r);
console.log(symbols.success, url, '-->', r);
});
} else {
bot.sendMessage(msg.chat.id, 'Sorry, that\'s not a vaid URL :(');
console.log(symbols.error, url);
}
});
console.log(symbols.info, 'bot server started...');
|
JavaScript
| 0.008361 |
@@ -301,16 +301,17 @@
(url) ?
+(
'http://
@@ -317,16 +317,17 @@
/' + url
+)
: url;%0A
|
15621444af8aea31b649a1e148ef261b8c1aa573
|
Fix staging logic to check for one or more comments rather than exactly one
|
bot.js
|
bot.js
|
// https://github.com/octokit/core.js#readme
const { Octokit } = require('@octokit/core');
const octokit = new Octokit({auth: process.env.GITHUB});
const constants = require('./constants.json');
const markdown = require('./audits/markdown.js');
// const psi = require('./audits/psi.js');
// const dom = require('./audits/dom.js');
const instructions = require('./instructions.json');
// The keys of this object match the names of the relevant GitHub webhook event
// that we're responding to.
const actions = {
// Pull request was opened.
opened: data => {
audit(data.number);
},
// A new comment was created on the pull request.
created: data => {
// TODO(kaycebasques): Check if it was Netlify and only re-run audit if so.
audit(data.issue.number);
},
// A comment on the pull request was edited.
edited: data => {
audit(data.issue.number)
},
// Some of the code in the pull request changed.
synchronize: data => {
audit(data.number);
}
};
const audit = async number => {
// Store data about the pull request.
let data = {
files: {},
number
};
// Get the files that are affected by the pull request.
const files = await octokit.request({
method: 'GET',
url: `/repos/googlechrome/web.dev/pulls/${number}/files`
});
// Check for new content, modified content, or images.
const newContent =
files.data.filter(file => file.status === constants.files.added &&
file.filename.toLowerCase().endsWith('.md'));
const modifiedContent =
files.data.filter(file => file.status === constants.files.modified &&
file.filename.toLowerCase().endsWith('.md'));
const images =
files.data.filter(file => file.filename.toLowerCase().endsWith('.png') ||
file.filename.toLowerCase().endsWith('.jpg'));
// Bail if the PR doesn't touch any content files.
if (newContent.length === 0 && modifiedContent.length === 0) return;
// Function for converting Markdown files that the PR is creating/editing into URLs.
const getStagingUrl = (number, path) => {
const s1 = path.substring(0, path.lastIndexOf('/'));
const s2 = s1.substring(s1.lastIndexOf('/') + 1);
return `https://deploy-preview-${number}--web-dev-staging.netlify.app/${s2}/`;
};
// Store data about the new or modified content.
if (newContent.length > 0) {
newContent.forEach(file => {
data.files[file.filename] = {
status: constants.files.added,
url: getStagingUrl(number, file.filename),
raw: file.raw_url,
audits: {}
};
});
}
if (modifiedContent.length > 0) {
modifiedContent.forEach(file => {
data.files[file.filename] = {
status: constants.files.modified,
url: getStagingUrl(number, file.filename),
raw: file.raw_url,
audits: {}
};
});
}
// Audit the files.
for (const path in data.files) {
const file = data.files[path];
file.audits.markdown = await markdown.audit(file.raw, path);
}
// Get the comments on the pull request.
const comments = await octokit.request({
accept: 'application/vnd.github.v3+json',
method: 'GET',
url: `/repos/googlechrome/web.dev/issues/${number}/comments`
});
// Check for the auto-generated staging URLs comment.
const shouldShowStagingUrls =
comments.data.filter(comment => comment.body.includes(constants.comments.staging)).length === 1;
// Check for the auto-generated reviewbot comment.
const reviewBotComment = comments.data.filter(comment => {
return comment.body.includes(constants.comments.reviewbot);
});
// Function for creating the automated comment.
const createComment = (data, showStagingUrls) => {
const createStagingUrlsContent = data => {
let comment = '## Staging URLs\n\n';
comment += 'For your convenience, here are direct links (on our staging site) to the content you created or updated:\n\n';
for (const path in data.files) {
const file = data.files[path];
comment += `* ${file.url}\n`;
}
return comment;
};
const createFileContent = (pathname, data) => {
let content = `### \`${pathname}\`\n\n`;
let sentinel = true;
for (const key in data.audits.markdown) {
const audit = data.audits.markdown[key];
if (!audit.pass) {
content += `* ${instructions[key]} Affected lines: ${audit.lines.join(', ')}\n`;
sentinel = false;
}
}
if (sentinel) content += '* This file passed all of our automated Markdown audits.\n\n';
return content;
};
let comment = 'Hello! This is an automated review by our custom [reviewbot](https://github.com/kaycebasques/reviewbot). It updates automatically when code or GitHub comments in this pull request are created or updated.\n\n';
if (showStagingUrls) comment += createStagingUrlsContent(data);
comment += '## Requested changes\n\n';
comment += 'If there are any common problems with the content files you created or modified, they will be listed here.\n\n';
for (const path in data.files) {
comment += createFileContent(path, data.files[path]);
}
comment += `<!-- Comment ID: ${constants.comments.reviewbot} -->`;
return comment;
};
// Create the comment if it doesn't exist.
if (reviewBotComment.length === 0) {
await octokit.request({
accept: 'application/vnd.github.v3+json',
method: 'POST',
url: `/repos/googlechrome/web.dev/issues/${data.number}/comments`,
body: createComment(data, shouldShowStagingUrls)
});
}
// Otherwise just update it.
if (reviewBotComment.length === 1) {
await octokit.request({
accept: 'application/vnd.github.v3+json',
method: 'PATCH',
url: `/repos/googlechrome/web.dev/issues/comments/${reviewBotComment[0].id}`,
body: createComment(data, shouldShowStagingUrls)
});
}
// Return the final data. Only for debugging purposes.
return data;
};
module.exports = {
actions,
audit
}
|
JavaScript
| 0 |
@@ -3408,21 +3408,19 @@
.length
-=== 1
+%3E 0
;%0A // C
|
4156ce7edb364ae5069ed9358af37973362e2ca5
|
Restructure where bot posts
|
bot.js
|
bot.js
|
var slackbot = require('node-slackbot'),
slackApiKey = process.env.SLACK_KEY,
bot = new slackbot(slackApiKey);
bot.use(function(message, cb) {
var botChannel = message.channel ? message.channel === 'D0NARQRGA' : false,
msgType = message.type ? message.type === 'message' : false,
toUser = message.text ? message.text.includes('<@') : false;
if (botChannel && msgType && toUser) {
bot.sendMessage('C0NANKWF7', message.text);
}
cb();
});
bot.connect();
|
JavaScript
| 0.000003 |
@@ -151,84 +151,8 @@
var
-botChannel = message.channel ? message.channel === 'D0NARQRGA' : false,%0A
msgT
@@ -284,22 +284,8 @@
if (
-botChannel &&
msgT
@@ -325,33 +325,300 @@
age(
-'C0NANKWF7', message.text
+message.channel, %22Posted to #you-guys-are-awesome!%22)%0A bot.sendMessage('C0NANKWF7', message.text);%0A %7D else if (msgType && message.channel !== 'C0NANKWF7') %7B%0A bot.sendMessage(%0A message.channel,%0A 'You need to @ mention a user in your message in order to send a compliment!'%0A
);%0A
|
23669d9aab5d242282b4299de7c0724ab34f3bd8
|
handle no answer, reply w/ error on error
|
bot.js
|
bot.js
|
var constants = require('./constants')
// Loads environment files
require('envc')({})
var request = require('request')
if (!process.env.token) {
console.log('Error: Specify token in environment')
process.exit(1)
}
var Botkit = require('./lib/Botkit.js')
var os = require('os')
var controller = Botkit.slackbot({
debug: true
})
var bot = controller.spawn({
token: process.env.token
}).startRTM()
function logError (err, msg) {
if (err) {
var message = msg || 'Danger Will Robinson!'
bot.botkit.log(message, err)
}
}
controller.hears([constants.LOOKUP], constants.ADDRESSED, function (bot, message) {
var text = message.text
// Verify first word is lookup
var firstWord = text.substr(0, text.indexOf(' '))
if (firstWord === constants.LOOKUP) {
var search = text.substr(text.indexOf(' ') + 1)
var questionQS = {
order: 'desc',
q: search,
site: constants.API.stack.site,
sort: 'relevance'
}
request.get({
url: `${constants.API.stack.url}/search/advanced`,
gzip: true,
qs: questionQS,
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
}, (err, res, body) => {
if (err) {
logError('Error With Stack Response', err)
}
var results = JSON.parse(body)
// Answer exists
if (results.items.length) {
var question = results.items.find((item) => item.is_answered)
if (!question) {
bot.reply('No answered result found!')
return
}
var resultQuestion = question.title
var answerQS = {
filter: 'withbody',
order: 'desc',
site: constants.API.stack.site,
sort: 'activity'
}
request.get({
url: `${constants.API.stack.url}/answers/${question.accepted_answer_id}`,
gzip: true,
qs: answerQS,
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
}, (err, res, body) => {
if (err) {
logError('Error With Stack Response', err)
}
var answers = JSON.parse(body)
if (answers.items.length) {
var answer = answers.items[0]
bot.reply(message, `*Q:* \`${resultQuestion}\``)
bot.reply(message, `*A:*\n\`\`\`${answer.body}\`\`\``)
}
})
}
})
}
})
controller.hears(['hello', 'hi'], constants.ADDRESSED, function (bot, message) {
bot.api.reactions.add({
timestamp: message.ts,
channel: message.channel,
name: 'robot_face'
}, function (err, res) {
if (err) {
bot.botkit.log('Failed to add emoji reaction :(', err)
}
})
controller.storage.users.get(message.user, function (err, user) {
logError(err, 'Failed to get user')
if (user && user.name) {
bot.reply(message, 'Hello ' + user.name + '!!')
} else {
bot.reply(message, 'Hello.')
}
})
})
controller.hears(['call me (.*)'], constants.ADDRESSED, function (bot, message) {
var matches = message.text.match(/call me (.*)/i)
var name = matches[1]
controller.storage.users.get(message.user, function (err, user) {
logError(err, 'Failed to get user')
if (!user) {
user = {
id: message.user
}
}
user.name = name
controller.storage.users.save(user, function (err, id) {
logError(err, 'Failed to save user')
bot.reply(message, 'Got it. I will call you ' + user.name + ' from now on.')
})
})
})
controller.hears(['shutdown'], constants.ADDRESSED, function (bot, message) {
bot.startConversation(message, function (err, convo) {
logError(err, 'Failed to start conversation')
convo.ask('Are you sure you want me to shutdown?', [
{
pattern: bot.utterances.yes,
callback: function (response, convo) {
convo.say('Bye!')
convo.next()
setTimeout(function () {
process.exit()
}, 3000)
}
},
{
pattern: bot.utterances.no,
default: true,
callback: function (response, convo) {
convo.say('*Phew!*')
convo.next()
}
}
])
})
})
controller.hears(['uptime', 'identify yourself', 'who are you', 'what is your name'], constants.ADDRESSED, function (bot, message) {
var hostname = os.hostname()
var uptime = formatUptime(process.uptime())
bot.reply(message, ':robot_face: I am a bot named <@' + bot.identity.name + '>. I have been running for ' + uptime + ' on ' + hostname + '.')
})
function formatUptime (uptime) {
var unit = 'second'
if (uptime > 60) {
uptime = uptime / 60
unit = 'minute'
}
if (uptime > 60) {
uptime = uptime / 60
unit = 'hour'
}
if (uptime !== 1) {
unit = unit + 's'
}
uptime = uptime + ' ' + unit
return uptime
}
|
JavaScript
| 0 |
@@ -1243,24 +1243,105 @@
onse', err)%0A
+ bot.reply('Error: You must construct additional pylons!')%0A return%0A
%7D%0A
@@ -1499,16 +1499,43 @@
answered
+ && item.accepted_answer_id
)%0A
@@ -2180,32 +2180,121 @@
Response', err)%0A
+ bot.reply('Error: You must construct additional pylons!')%0A return%0A
%7D%0A
@@ -2330,16 +2330,17 @@
e(body)%0A
+%0A
|
30dfd62c51de7f8dbecadf44cd009e15ebcf7464
|
add `rm` as alias for `del`
|
cli.js
|
cli.js
|
#!/usr/bin/env node
var path = require('path');
var fs = require('fs');
var program = require('commander');
var npmconf = require('npmconf');
var ini = require('ini');
var echo = require('node-echo');
var extend = require('extend');
var open = require('open');
var async = require('async');
var request = require('request');
var only = require('only');
var registries = require('./registries.json');
var PKG = require('./package.json');
var NRMRC = path.join(process.env.HOME, '.nrmrc');
program
.version(PKG.version);
program
.command('ls')
.description('list all the registries')
.action(onList);
program
.command('use <registry>')
.description('change registry to registry')
.action(onUse);
program
.command('add <registry> <url> [home]')
.description('add one custom registry')
.action(onAdd);
program
.command('del <registry>')
.description('delete one custom registry')
.action(onDel);
program
.command('home <registry> [browser]')
.description('open the homepage of registry with optional browser')
.action(onHome);
program
.command('test [registry]')
.description('show response time for specific or all registries')
.action(onTest);
program
.command('help')
.description('print this help')
.action(program.help);
program
.parse(process.argv);
/*//////////////// cmd methods /////////////////*/
function onList() {
getCurrentRegistry(function (cur) {
var info = [''];
var allRegistries = getAllRegistry();
Object.keys(allRegistries).forEach(function(key){
var item = allRegistries[key];
var prefix = item.registry === cur ? '* ' : ' ';
info.push(prefix + key + line(key, 8) + item.registry);
});
info.push('');
printMsg(info);
});
}
function onUse(name){
var allRegistries = getAllRegistry();
if(allRegistries.hasOwnProperty(name)){
var registry = allRegistries[name];
npmconf.load(function(err, conf){
if(err){
exit(err);
}
conf.set('registry', registry.registry, 'user');
conf.save('user', function(err){
if(err){
exit(err);
}
printMsg([
''
, ' Registry has been set to: ' + registry.registry
, ''
]);
});
});
}else{
printMsg([
''
, ' Not find registry: ' + name
, ''
]);
}
}
function onDel(name){
var customRegistries = getCustomRegistry();
if(!customRegistries.hasOwnProperty(name)){
return;
}
getCurrentRegistry(function (cur) {
if (cur === customRegistries[name].registry) {
onUse('npm');
}
delete customRegistries[name];
setCustomRegistry(customRegistries, function(err){
if(err){
exit(err);
}
printMsg([
''
, ' delete registry ' + name + ' success'
, ''
]);
});
});
}
function onAdd(name, url, home){
var customRegistries = getCustomRegistry();
if(customRegistries.hasOwnProperty(name)){
return;
}
var config = customRegistries[name] = {};
if (url[url.length-1] !== '/') url += '/'; // ensure url end with /
config.registry = url;
if(home){
config.home = home;
}
setCustomRegistry(customRegistries, function(err){
if(err){
exit(err);
}
printMsg([
''
, ' add registry ' + name + ' success'
, ''
]);
});
}
function onHome(name, browser){
var allRegistries = getAllRegistry();
var home = allRegistries[name] && allRegistries[name].home;
if (home) {
var args = [home];
if (browser) args.push(browser);
open.apply(null, args);
}
}
function onTest(registry){
var allRegistries = getAllRegistry();
var toTest;
if(registry){
if(!allRegistries.hasOwnProperty(registry)){
return;
}
toTest = only(allRegistries, registry);
}else{
toTest = allRegistries;
}
async.map(Object.keys(toTest), function(name, cbk){
var registry = toTest[name];
var start = +new Date();
request(registry.registry, function(error){
cbk(null, {
name: name
, registry: registry.registry
, time: (+new Date() - start)
, error: error ? true : false
});
});
}, function(err, results){
getCurrentRegistry(function(cur){
var msg = [''];
results.forEach(function(result){
var prefix = result.registry === cur ? '* ' : ' ';
var suffix = result.error ? 'Fetch Error' : result.time + 'ms';
msg.push(prefix + result.name + line(result.name, 8) + suffix);
});
msg.push('');
printMsg(msg);
});
});
}
/*//////////////// helper methods /////////////////*/
/*
* get current registry
*/
function getCurrentRegistry (cbk) {
npmconf.load(function(err, conf){
if(err){
exit(err);
}
cbk(conf.get('registry'));
});
}
function getCustomRegistry(){
return fs.existsSync(NRMRC) ? ini.parse(fs.readFileSync(NRMRC, 'utf-8')) : {};
}
function setCustomRegistry(config, cbk){
echo(ini.stringify(config), '>', NRMRC, cbk);
}
function getAllRegistry(){
return extend({}, registries, getCustomRegistry());
}
function printErr(err){
console.error('an error occured: ' + err);
}
function printMsg(infos){
infos.forEach(function(info){
console.log(info);
});
}
/*
* print message & exit
*/
function exit (err) {
printErr(err);
process.exit(1);
}
function line (str, len) {
var line = new Array(len - str.length).join('-');
return ' ' + line + ' ';
}
|
JavaScript
| 0.000001 |
@@ -951,24 +951,130 @@
on(onDel);%0A%0A
+program%0A .command('rm %3Cregistry%3E')%0A .description('delete one custom registry')%0A .action(onDel);%0A%0A
program%0A
|
c604f5a056f4eaff8195928c8894c70a2b2af197
|
clean up experimental data-store code
|
cli.js
|
cli.js
|
#!/usr/bin/env node
'use strict';
process.title = 'expand-object';
var argv = require('minimist')(process.argv.slice(2));
var stdin = require('get-stdin');
var Store = require('data-store');
var store = new Store('expand-object');
var expand = require('./index');
var pkg = require('./package.json');
function help() {
console.log();
console.log(' ' + pkg.description);
console.log();
console.log(' Usage: cli [options] <string>');
console.log();
console.log(' -h, --help output usage information');
console.log(' -V, --version output the version number');
console.log(' -r, --raw output as raw javascript object - don\'t stringify');
console.log();
console.log(' Examples:');
console.log('');
console.log(' $ expand-object "a:b"');
console.log(' $ expand-object --raw "a:b"');
console.log(' $ echo "a:b" | expand-object');
console.log('');
}
if (argv._.length === 0 && Object.keys(argv).length === 1 || argv.help) {
help();
}
function run(contents) {
if (argv.get) {
output = store.get(argv.get);
console.log(output);
return;
}
var output = contents;
if (argv.set) {
output = expand(argv.set);
store.set(output);
} else {
output = expand(contents);
if (!argv.raw) {
output = JSON.stringify(output);
}
}
console.log(output);
process.exit(0);
}
if (!process.stdin.isTTY) {
return stdin(function(contents) {
run(contents);
});
}
run(argv._[0] || '');
|
JavaScript
| 0.000094 |
@@ -156,84 +156,8 @@
');%0A
-var Store = require('data-store');%0Avar store = new Store('expand-object');%0A%0A
var
@@ -945,211 +945,11 @@
%7B%0A
-if (argv.get) %7B%0A output = store.get(argv.get);%0A console.log(output);%0A return;%0A %7D%0A%0A var output = contents;%0A if (argv.set) %7B%0A output = expand(argv.set);%0A store.set(output);%0A %7D else %7B%0A
+var
out
@@ -974,18 +974,16 @@
nts);%0A
-
-
if (!arg
@@ -991,18 +991,16 @@
.raw) %7B%0A
-
outp
@@ -1032,14 +1032,8 @@
t);%0A
- %7D%0A
%7D%0A
@@ -1112,15 +1112,8 @@
%7B%0A
-return
stdi
@@ -1161,18 +1161,26 @@
%0A %7D);%0A%7D
-%0A%0A
+ else %7B%0A
run(argv
@@ -1189,12 +1189,14 @@
%5B0%5D %7C%7C '');%0A
+%7D%0A
|
d1d4573c6c71ff51c1523807d7f9bb69742cfe22
|
add default and version
|
cli.js
|
cli.js
|
#!/usr/bin/env node
'use strict'
const Makenova = require('./')
const makenova = new Makenova()
const yargs = require('yargs')
.usage('$0 <cmd>')
.command('name', 'Display name', {}, () => console.log(makenova.name))
.command('title', 'Display title', {}, () => console.log(makenova.title))
.help('h')
.alias('h', 'help')
.argv
|
JavaScript
| 0 |
@@ -327,16 +327,42 @@
'help')%0A
+ .version()%0A .demand(1)%0A
.argv%0A
|
f7d1362573277aba0a4599603bce65e7432897d5
|
add opnr trigger
|
cli.js
|
cli.js
|
#!/usr/bin/env node
const summary = require('server-summary')
const cliclopts = require('cliclopts')
const isStream = require('is-stream')
const minimist = require('minimist')
const router = require('./build')
const http = require('http')
const path = require('path')
const url = require('url')
const copts = cliclopts([
{
name: 'port',
abbr: 'p',
default: 1337,
help: 'port for the server to listen on'
}
])
const argv = minimist(process.argv.slice(2), copts.options())
const cmd = argv._[0]
// help
if (argv.help || !cmd) {
console.log('Usage: command [options]')
copts.print()
process.exit()
}
// listen
if (cmd === 'start') server().listen(argv.port, summary)
// build
if (cmd === 'build') {
router.build(__dirname + '/build', function (err, res) {
if (err) {
console.log('error:', err)
process.exit(1)
}
process.exit()
})
}
// create a server
// null -> null
function server () {
return http.createServer(function (req, res) {
var pathname = url.parse(req.url).pathname
pathname = pathname === '/' ? '/index.html' : pathname
const ext = path.extname(pathname)
console.log(JSON.stringify({url: pathname, type: 'static'}))
if (ext === '.css') res.setHeader('Content-Type', 'text/css')
if (ext === '.js') res.setHeader('Content-Type', 'application/javascript')
router.match(pathname, function (err, body) {
if (err) {
err = (typeof err === 'object') ? err.toString() : err
const ndj = JSON.stringify({level: 'error', url: pathname, message: err})
console.log(ndj)
}
if (isStream(body)) return body.pipe(res)
res.end(body)
})
})
}
|
JavaScript
| 0 |
@@ -651,16 +651,20 @@
'start')
+ %7B%0A
server(
@@ -687,16 +687,167 @@
rt,
-summary)
+function () %7B%0A const addr = 'localhost:' + this.address().port%0A console.log(JSON.stringify(%7B type: 'connect', url: addr %7D))%0A summary.call(this)%0A %7D)%0A%7D
%0A%0A//
|
01c9eed5fa583ae06869227d1967cfb0b36baf74
|
update cli
|
cli.js
|
cli.js
|
#!/usr/bin/env node
const Listr = require('listr');
const inquirer = require('inquirer')
const fs = require('fs')
const exec = require('child_process').exec;
const { getOfficialStations } = require('./lib/station')
getOfficialStations().then(() => {
console.log('hey');
})
fs.readdir(__dirname + '/stations', (err, files) => {
const b = files.filter(file => !/(.DS_Store|_shared)/.test(file))
var questions = [{
type: 'list',
name: 'station',
message: 'Choose your station',
choices: []
.concat(b)
// if .takeoff folder found in project
.concat([new inquirer.Separator(`Found custom stations in "${process.cwd().split('/').pop()}"`)])
.concat(['A', 'B']),
filter: val => val.toLowerCase()
}]
inquirer.prompt(questions).then(function (answers) {
console.log('\nOrder receipt:');
console.log(JSON.stringify(answers));
});
})
// const tasks = new Listr([{
// title: 'Git',
// task: () => new Promise((resolve) => {
// setTimeout(() => resolve(), 1000)
// })
// },{
// title: 'bar',
// task: () => new Promise((resolve) => {
// setTimeout(() => resolve(), 2000)
// })
// }]);
//
// tasks.run().catch(err => {
// console.error(err);
// });
|
JavaScript
| 0 |
@@ -23,397 +23,203 @@
nst
-Listr = require('listr');%0Aconst inquirer = require('inquirer')%0Aconst fs = require('fs')%0Aconst exec = require('child_process').exec;%0A%0Aconst %7B getOfficialStations %7D = require('./lib/station')%0A%0AgetOfficialStations().then(() =%3E %7B%0A console.log('hey');%0A%7D)%0A%0Afs.readdir(__dirname + '/stations', (err, files) =%3E %7B%0A const b = files.filter(file =%3E !/(.DS_Store%7C_shared)/.test(file))%0A%0A var question
+inquirer = require('inquirer')%0A%0Aconst %7B getOfficialStations %7D = require('./lib/station')%0A%0Aconst TakeOff = async () =%3E %7B%0A const officialStations = await getOfficialStations()%0A%0A const takeOffStep
s =
@@ -316,24 +316,26 @@
%5B%5D%0A
+
.concat(
b)%0A /
@@ -330,355 +330,120 @@
cat(
-b)%0A // if .takeoff folder found in project%0A .concat(%5Bnew inquirer.Separator(%60Found custom stations in %22$%7Bprocess.cwd().split('/').pop()%7D%22%60)%5D)%0A .concat(%5B'A', 'B'%5D),%0A filter: val =%3E val.toLowerCase()%0A %7D%5D%0A%0A inquirer.prompt(questions).then(function (answers) %7B%0A console.log('%5CnOrder receipt:');%0A console.log(JSON.stringify(
+officialStations)%0A %7D%5D%0A%0A const answers = await inquirer.prompt(takeOffSteps)%0A%0A console.log('-------',
answers)
);%0A
@@ -442,22 +442,22 @@
ers)
-)
;%0A
- %7D);%0A%7D)%0A
+%7D%0A%0ATakeOff()
%0A%0A%0A%0A
|
6cbce4e38b9b0907c7d41fc9c989409240930e40
|
fix absolute path resolving for appDirectory
|
cli.js
|
cli.js
|
#! /usr/bin/env node
/*
* electron-builder
* https://github.com/loopline-systems/electron-builder
*
* Licensed under the MIT license.
*/
'use strict';
var fs = require( 'fs' );
var meow = require( 'meow' );
var assign = require( 'lodash.assign' );
var path = require( 'path' );
var builder = ( require( './' ) ).init();
var usage = fs.readFileSync( path.join( __dirname, 'usage.txt' ) ).toString();
var cli = meow( usage, {
help : usage,
alias : {
h : 'help'
}
} );
if ( cli.input[ 0 ] == null ) {
console.error( usage );
throw new Error( 'Path to electron app not provided' );
}
var appPath = path.join( process.cwd(), cli.input[ 0 ] );
builder.build( assign( {
appPath : appPath
}, cli.flags ), function( error ) {
if ( error ) {
throw error;
}
console.log( '- Created installer for ' + cli.flags.platform + ' -' );
} );
|
JavaScript
| 0.000001 |
@@ -635,20 +635,23 @@
= path.
-join
+resolve
( proces
|
8cf19ceac824134daa67b6d48e3b0e3ebfc8a64b
|
Remove obsolete temp dir creation
|
cmd.js
|
cmd.js
|
#!/usr/bin/env node
var amok = require('./');
var async = require('async');
var cmd = require('commander');
var fs = require('fs');
var path = require('path');
var temp = require('temp');
var repl = require('repl');
var util = require('util');
var pkg = require('./package.json');
cmd.usage('[options] <script>');
cmd.version(pkg.version);
cmd.option('--host <HOST>', 'specify http host', 'localhost');
cmd.option('--port <PORT>', 'specify http port', 9966);
cmd.option('--debugger-host <HOST>', 'specify debugger host', 'localhost');
cmd.option('--debugger-port <PORT>', 'specify debugger port', 9222);
cmd.option('-i, --interactive', 'enable interactive mode');
cmd.option('--client <CMD>', 'specify the client to spawn');
cmd.option('--compiler <CMD>', 'specify the compiler to spawn');
cmd.option('-v, --verbose', 'enable verbose logging mode');
cmd.parse(process.argv);
cmd.cwd = process.cwd();
function compiler(callback, data) {
if (cmd.compiler) {
if (cmd.verbose) {
console.info('Spawning compiler...');
}
temp.track();
temp.mkdir('amok', function(error, dirpath) {
if (error) {
return callback(error);
}
var compiler = amok.compile(cmd, function(error, stdout, stderr) {
if (error) {
return callback(error);
}
stdout.pipe(process.stdout);
stderr.pipe(process.stderr);
cmd.scripts = {
'bundle.js': compiler.output,
};
callback(null, compiler);
});
});
} else {
cmd.scripts = cmd.args.reduce(function(object, value, key) {
object[value] = path.resolve(value);
return object;
}, {});
callback(null, null);
}
}
function watcher(callback, data) {
var watcher = amok.watch(cmd, function() {
if (cmd.verbose) {
console.info('File watcher ready');
}
watcher.on('change', function(filename) {
if (cmd.verbose) {
console.info(filename, 'changed');
}
var script = Object.keys(cmd.scripts)
.filter(function(key) {
return cmd.scripts[key] === filename
})[0];
if (script) {
if (cmd.verbose) {
console.info('Re-compiling', script, '...');
}
fs.readFile(filename, 'utf-8', function(error, contents) {
if (error) {
return console.error(error);
}
data.bugger.source(script, contents, function(error) {
if (error) {
return console.error(error);
}
if (cmd.verbose) {
console.info('Re-compilation succesful');
}
});
});
}
});
callback(null, watcher);
});
}
function server(callback, data) {
if (cmd.verbose) {
console.info('Starting server...');
}
var server = amok.serve(cmd, function() {
var address = server.address();
if (cmd.verbose) {
console.info('Server listening on http://%s:%d', address.address,
address.port);
}
callback(null, server);
});
}
function client(callback, data) {
if (cmd.client) {
if (cmd.verbose) {
console.log('Spawning client...');
}
var client = amok.open(cmd, function(error, stdout, stderr) {
if (error) {
return callback(error);
}
stdout.pipe(process.stdout);
stderr.pipe(process.stderr);
callback(null, client);
});
} else {
callback(null, null);
}
}
function bugger(callback, data) {
if (cmd.verbose) {
console.info('Attaching debugger...');
}
var bugger = amok.debug(cmd, function(error, target) {
if (error) {
return callback(error);
}
if (cmd.verbose) {
console.info('Debugger attached to', target.title);
}
bugger.console.on('data', function(message) {
if (message.parameters) {
var parameters = message.parameters.map(function(parameter) {
return parameter.value;
});
if (console[message.level]) {
console[message.level].apply(console, parameters);
}
}
});
callback(null, bugger);
});
}
function prompt(callback, data) {
if (cmd.interactive) {
var options = {
prompt: '> ',
input: process.stdin,
output: process.stdout,
writer: function(result) {
if (result.value) {
return util.inspect(result.value, {
colors: true,
});
} else if (result.objectId) {
return util.format('[class %s]\n%s', result.className, result.description);
}
},
eval: function(cmd, context, filename, write) {
data.bugger.evaluate(cmd, function(error, result) {
write(error, result);
});
},
};
var prompt = repl.start(options);
callback(null, prompt);
} else {
callback(null, null);
}
}
async.auto({
'compiler': [compiler],
'server': ['compiler', server],
'client': ['server', client],
'bugger': ['client', bugger],
'watcher': ['bugger', watcher],
'prompt': ['bugger', prompt],
}, function(error, data) {
if (error) {
console.error(error);
process.exit(1);
}
});
|
JavaScript
| 0.000001 |
@@ -1040,138 +1040,8 @@
%7D%0A%0A
- temp.track();%0A temp.mkdir('amok', function(error, dirpath) %7B%0A if (error) %7B%0A return callback(error);%0A %7D%0A%0A
@@ -1109,26 +1109,24 @@
rr) %7B%0A
-
if (error) %7B
@@ -1118,34 +1118,32 @@
if (error) %7B%0A
-
return c
@@ -1160,31 +1160,27 @@
ror);%0A
-
%7D%0A%0A
-
stdout
@@ -1204,26 +1204,24 @@
out);%0A
-
stderr.pipe(
@@ -1244,18 +1244,16 @@
%0A%0A
-
cmd.scri
@@ -1268,18 +1268,16 @@
-
-
'bundle.
@@ -1304,24 +1304,20 @@
,%0A
-
%7D;%0A%0A
-
ca
@@ -1348,21 +1348,12 @@
-
%7D);%0A
- %7D);
%0A%0A
|
cfadc97e3d12551be06e41f9fd0df5c2736cefe8
|
Fix bootstrapping to use __dirname
|
cmd.js
|
cmd.js
|
#!/usr/bin/env node
var path = require('path')
var fs = require('fs')
var rimraf = require('rimraf')
var resolve = require('./').resolve
var install = require('./').install
var flags = {}
var targets = process.argv.slice(2).filter(function (target, i, arr) {
var match = /^--?(.*)$/.exec(target)
if (!match) return true
flags[match[1]] = arr.slice(i + 1)
})
function handleError (err) {
if (!err) return
throw err
}
var entry
if (flags.help || flags.h) {
fs.createReadStream(path.join(__dirname, 'USAGE.txt')).pipe(process.stdout)
} else if (flags.bootstrap || flags.b) {
entry = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'package.json')))
rimraf.sync(path.join(__dirname, 'node_modules'))
install(__dirname, entry, {}, true, 0, handleError)
} else if (targets.length) {
targets.forEach(function (target) {
resolve(target, target.split('@')[1] || '*', function (err, what) {
handleError(err)
install(path.join(process.cwd(), 'node_modules', what.name), what, {}, false, 1, handleError)
})
})
} else {
entry = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'package.json')))
install(process.cwd(), entry, {}, true, 0, handleError)
}
|
JavaScript
| 0.000037 |
@@ -625,37 +625,33 @@
c(path.join(
-process.cwd()
+__dirname
, 'package.j
|
30f8411b423becbf01a80cd0c6ba7f9ee60711ff
|
Fix Link Error
|
dir.js
|
dir.js
|
var fileHierarchy={};
const API_PREFIX="http://api.github.com/";
function getRepos() {
$.getJSON(API_PREFIX+"users/viethtran/repos", function (result) {
if (result["message"]==="Not Found") {
println("Error getting data from github");
return;
}
for (var i=0; i<result.length; ++i) {
fileHierarchy[result[i]["path"]]=result[i];
}
});
}
function getContent(repo,path) {
}
getRepos();
|
JavaScript
| 0.000001 |
@@ -37,16 +37,17 @@
IX=%22http
+s
://api.g
|
bcc2984a78c55b18a40ab13ff28ca7eff373fd8f
|
Optimize loops by storing this.length which is assumed to be invariant.
|
es5.js
|
es5.js
|
// ECMAScript 5 compatibility functions
//
// Copyright (c) 2011, Jean Vincent
//
// Licensed under the MIT license
//
Object.create || ( Object.create = function ( o ) {
if ( arguments.length > 1 ) {
throw new Error( 'Object.create implementation only accepts the first parameter.' );
}
function O() {}
O.prototype = o;
return new O();
} );
Function.prototype.bind || ( Function.prototype.bind = function( o ) {
if ( typeof this !== "function" ) {
throw new TypeError( "Function.prototype.bind - what is trying to be bound is not callable" )
}
var that = this
, slice = Array.prototype.slice
, a = slice.call( arguments, 1 )
, bound = function() {
return that.apply( o || {}, a.concat( slice.call( arguments ) ) );
}
;
bound.prototype = this.prototype;
return bound;
} );
Array.prototype.indexOf || ( Array.prototype.indexOf = function( v, i ) {
var l = this.length; if ( l === 0 ) return -1;
if ( i === undefined ) {
i = 0
} else if( i < 0 && ( i += l ) < 0 ) i = 0;
i -= 1; while( ++i < l ) if ( this[ i ] === v ) return i;
return -1;
} );
Array.prototype.lastIndexOf || ( Array.prototype.lastIndexOf = function( v, i ) {
var l = this.length; if ( l === 0 ) return -1;
if ( i === undefined ) {
i = l - 1
} else if( i < 0 && ( i += l ) < 0 ) {
return -1
} else if ( i >= l ) i = l - 1;
i += 1; while( --i >= 0 && this[ i ] !== v );
return i;
} );
Array.prototype.forEach || ( Array.prototype.forEach = function( c, t ) {
t || ( t = window );
var i = -1; while( ++i < this.length ) c.call( t, this[i], i, this );
} );
Array.prototype.every || ( Array.prototype.every = function( c, t ) {
t || ( t = window );
var i = -1; while( ++i < this.length ) if ( c.call( t, this[i], i, this ) === false ) return false;
return true;
} );
Array.prototype.some || ( Array.prototype.some = function( c, t ) {
t || ( t = window );
var i = -1; while( ++i < this.length ) if ( c.call( t, this[i], i, this ) === true ) return true;
return false;
} );
Array.prototype.map || ( Array.prototype.map = function( c, t ) {
t || ( t = window );
var a = [], i = -1; while( ++i < this.length ) a [i] = c.call( t, this[i], i, this );
return a;
} );
Array.prototype.filter || ( Array.prototype.filter = function( c, t ) {
t || ( t = window );
var a = [], i = -1; while( ++i < this.length ) c.call( t, this[i], i, this ) && a.push( this[i] );
return a;
} );
Array.prototype.reduce || ( Array.prototype.reduce = function( c, v ) {
var i = -1; if ( v === undefined ) v = this[++i];
while( ++i < this.length ) v = c( v, this[i], i, this );
return v;
} );
Array.prototype.reduceRight || ( Array.prototype.reduceRight = function( c, v ) {
var i = this.length; if ( v === undefined ) v = this[--i];
while( --i >= 0 ) v = c( v, this[i], i, this );
return v;
} );
|
JavaScript
| 0 |
@@ -1551,33 +1551,52 @@
);%0A var i = -1
-;
+, l = this.length;%0A
while( ++i %3C th
@@ -1589,35 +1589,25 @@
hile( ++i %3C
-this.length
+l
) c.call( t
@@ -1731,33 +1731,52 @@
);%0A var i = -1
-;
+, l = this.length;%0A
while( ++i %3C th
@@ -1769,35 +1769,25 @@
hile( ++i %3C
-this.length
+l
) if ( c.ca
@@ -1958,25 +1958,44 @@
var i = -1
-;
+, l = this.length;%0A
while( ++i
@@ -1996,27 +1996,17 @@
( ++i %3C
-this.length
+l
) if (
@@ -2182,33 +2182,52 @@
r a = %5B%5D, i = -1
-;
+, l = this.length;%0A
while( ++i %3C th
@@ -2224,27 +2224,17 @@
( ++i %3C
-this.length
+l
) a %5Bi%5D
@@ -2400,17 +2400,36 @@
, i = -1
-;
+, l = this.length;%0A
while(
@@ -2434,27 +2434,17 @@
( ++i %3C
-this.length
+l
) c.cal
@@ -2592,17 +2592,36 @@
r i = -1
-;
+, l = this.length;%0A
if ( v
@@ -2666,27 +2666,17 @@
( ++i %3C
-this.length
+l
) v = c
@@ -2908,29 +2908,28 @@
i, this );%0A return v;%0A%7D );%0A
-%0A
|
841454515dfbc1825bc6c5e1e6b6e77806255bf8
|
修复fiz-web-template名称问题
|
fiz.js
|
fiz.js
|
#!/usr/bin/env node
// vi fiz/bin/fiz.js
var Liftoff = require("liftoff");
var argv = require("minimist")(process.argv.slice(2));
var path = require("path");
var fs = require("fs");
var cli = new Liftoff({
name: "fiz",
processTitle: "fiz",
moduleName: "fiz",
configName: "fis-conf",
//only js supported
extensions: {
".js": null
}
});
cli.launch({
cwd: argv.r || argv.root,
configPath: argv.f || argv.file
}, function(env){
//捕获命令行
var command = argv["_"];
switch(command[0]){
// fiz get
case "get":
//提供的服务
var targetHash = {
"web": {
name: "web-template",
url: "https://github.com/luozt/fiz-web-template.git"
}
};
//检测是否存在该服务
var cmd1 = command[1];
var targetObj = targetHash[cmd1];
if(!targetObj){
console.log("Not such \"" + cmd1 + "\" get-target!");
return false;
}
var noDir = !!argv["n"];
var folder = targetObj.name;
var childProcess = require("child_process");
var exec = childProcess.exec;
console.log("start get [ " + cmd1 + " ]");
var child = exec("git clone " + targetObj.url, function(err, stdout, stderr){
if(err){
console.log("git clone err: " + err);
return;
}
console.log("get [ " + cmd1 + " ] success");
var child2 = exec("rm -rf " + folder + "/.git", function(err, stdout){
if (err){
console.log("rm "+ folder +"/.git error");
return;
}
if (noDir){
var child3 = exec("cp -rf " + folder + "/* ./", function(err, stdout){
if(err){
console.log("cp " + folder + " folder error");
return;
}
var child4 = exec("rm -rf " + folder, function(err, stdout){
if (err){
console.log("rm "+ folder +" folder error")
return;
}
});
});
}
});
});
break;
// 移动文件夹,不支持文件
case "mvDirContent":
var childProcess, exec, dest, folder, child, cwd;
cwd = process.cwd();
folder = argv["src"];
dest = argv["to"];
if(!dest || "string" != typeof dest){
console.log("dest: "+dest+", operate destination required!");
return false;
}
if(!folder || "string" !== typeof folder){
folder = cwd;
}
childProcess = require("child_process");
exec = childProcess.exec;
if(!fs.existsSync(folder)){
console.log("source: "+folder+", not such a source Foler!");
return;
}
if("/" === folder.slice(-1)){
folder = folder.slice(0,-1);
}
console.log("source folder: "+folder);
console.log("destination folder: "+dest);
child = exec("mv -f "+folder+"/** "+dest, function(err, stdout){
var child2;
if(err){
console.log(err);
console.log("mv "+folder+" folder content error when execing: "+"mv -f "+folder+"/** "+dest);
return;
}
child2 = exec("rm -rf "+folder, function(err, stdout){
var child3, clearFolder;
if(err){
console.log(err);
console.log("rm "+folder+" folder error");
return;
}
// 检测是否还有要删除的文件夹
clearFolder = argv["clear"];
if(clearFolder){
child3 = exec("rm -rf "+clearFolder, function(err, stdout){
if(err){
console.log(err);
console.log("rm "+clearFolder+" folder error");
return;
}
});
}
});
});
break;
// 引用fis
default:
var fis;
if(!env.modulePath){
fis = require("./");
}else{
fis = require(env.modulePath);
}
fis.set("system.localNPMFolder", path.join(env.cwd, "node_modules/fiz"));
// fis.set('system.globalNPMFolder', path.dirname(__dirname));
fis.cli.run(argv, env);
}
});
|
JavaScript
| 0 |
@@ -546,16 +546,61 @@
//%E6%8F%90%E4%BE%9B%E7%9A%84%E6%9C%8D%E5%8A%A1%0A
+ var WEB_GIT_NAME = %22fiz-web-template%22;%0A
va
@@ -653,22 +653,20 @@
me:
-%22web-template%22
+WEB_GIT_NAME
,%0A
@@ -704,32 +704,32 @@
m/luozt/
-fiz-web-template
+%22+WEB_GIT_NAME+%22
.git%22%0A
|
0b9c80cdd50a78a8008aa1152b3dc8c35ff4e2cf
|
Fix warning on docs deploy.
|
docs/web_modules/app/routes.js
|
docs/web_modules/app/routes.js
|
import React, {Component, PropTypes} from "react";
import {Route} from "react-router";
import PhenomicPageContainer from "phenomic/lib/PageContainer";
import LayoutContainer from "../LayoutContainer";
import OptimisationContainer from "../layouts/Optimisations/show";
import * as layouts from '../layouts';
class PageContainer extends Component {
static propTypes = {
params: PropTypes.object.isRequired,
};
render () {
const {props} = this;
return (
<PhenomicPageContainer
{...props}
layouts={layouts}
/>
);
}
componentWillReceiveProps (props) {
if (props.params.splat !== this.props.params.splat && !window.location.hash) {
window.scrollTo(0, 0);
}
}
}
export default (
<Route component={LayoutContainer}>
<Route
path="/optimisations/:optimisation"
component={OptimisationContainer}
/>
<Route
path="*"
component={PageContainer}
/>
</Route>
);
|
JavaScript
| 0 |
@@ -87,16 +87,34 @@
%0Aimport
+%7BPageContainer as
Phenomic
@@ -130,23 +130,24 @@
iner
+%7D
from
-%22
+'
phenomic
/lib
@@ -146,27 +146,9 @@
omic
-/lib/PageContainer%22
+'
;%0Aim
|
9beebf50a4a6c7e4b7ac8b7d780b805c45d84988
|
remove entity DB cache
|
ringojs-convinient/app/models.js
|
ringojs-convinient/app/models.js
|
var {Store, ConnectionPool, Cache} = require('ringo-sqlstore');
// DO NOT TOUCH THE FOLLOWING LINE.
// THIS VARIABLE IS REGEX REPLACED BY setup.py
var dbHost = 'localhost';
// create and configure store
var connectionPool = module.singleton("connectionPool", function() {
return new ConnectionPool({
"url": "jdbc:mysql://" + dbHost + "/hello_world",
"driver": "com.mysql.jdbc.Driver",
"username": "benchmarkdbuser",
"password": "benchmarkdbpass"
});
});
var store = exports.store = new Store(connectionPool);
var entityCache = module.singleton("entityCache", function() {
return new Cache(10000);
});
var queryCache = module.singleton("queryCache", function() {
return new Cache(10000);
});
store.setEntityCache(entityCache);
store.setQueryCache(queryCache);
// define entities in DB
exports.World = store.defineEntity('World', {
table: 'World',
properties: {
randomNumber: 'integer'
}
});
var Fortune = exports.Fortune = store.defineEntity('Fortune', {
table: 'Fortune',
properties: {
message: 'string'
}
});
Fortune.sort = function(a, b) {
return (a.message < b.message) ? -1 : (a.message > b.message) ? 1 : 0;
};
|
JavaScript
| 0.000003 |
@@ -548,104 +548,8 @@
l);%0A
-var entityCache = module.singleton(%22entityCache%22, function() %7B%0A return new Cache(10000);%0A%7D);%0A
var
@@ -642,43 +642,8 @@
%7D);%0A
-store.setEntityCache(entityCache);%0A
stor
@@ -1041,8 +1041,9 @@
: 0;%0A%7D;
+%0A
|
4501a79341cf2255b8da277ef30ca441ae0c2c20
|
add back html decode to mojim
|
lyric_engine_js/modules/mojim.js
|
lyric_engine_js/modules/mojim.js
|
const Sentry = require('@sentry/node');
const LyricBase = require('../include/lyric-base');
const keyword = 'mojim';
class Lyric extends LyricBase {
get_lang(url) {
const pattern = /com\/([a-z]{2})y/;
return this.get_first_group_by_pattern(url, pattern);
}
filter_ad(lyric) {
const separator = '<br />';
const lines = lyric.split(separator);
const filtered = lines.filter((line) => !line.includes('Mojim.com'));
return filtered.join(separator);
}
filter_thank(lyric) {
const pattern = /<ol>.*?<\/ol>/;
return lyric.replace(pattern, '');
}
async find_lyric(url, html) {
const prefix = "<dt id='fsZx2'";
const suffix = '</dl>';
const lyricPrefix = '<br /><br />';
const block = this.find_string_by_prefix_suffix(html, prefix, suffix, true);
let lyric = this.find_string_by_prefix_suffix(
block,
lyricPrefix,
suffix,
false
);
lyric = this.filter_ad(lyric);
lyric = this.filter_thank(lyric);
lyric = lyric.replace(/<br \/>/g, '\n');
lyric = this.sanitize_html(lyric);
this.lyric = lyric;
return true;
}
async find_info(url, html) {
const prefix = "<dl id='fsZx1'";
const suffix = '</dl>';
const block = this.find_string_by_prefix_suffix(
html,
prefix,
suffix,
true
).replace(/\n/g, '');
Sentry.withScope((scope) => {
scope.setLevel('info');
scope.setExtra(block);
Sentry.captureMessage('Mojim.com info block');
});
const keys = {
lyricist: '作詞',
composer: '作曲',
arranger: '編曲',
};
const lang = this.get_lang(url);
if (lang === 'cn') {
keys.lyricist = '作词';
keys.arranger = '编曲';
} else if (lang === 'us') {
keys.lyricist = 'Lyricist';
keys.composer = 'Composer';
keys.arranger = 'Arranger';
}
const patterns = {
title: "<dt id='fsZx2'.*?>(.+?)<br",
artist: "<dl id='fsZx1'.*?>(.+?)<br",
lyricist: `${keys.lyricist}:(.+?)<br`,
composer: `${keys.composer}:(.+?)<br`,
arranger: `${keys.arranger}:(.+?)<br`,
};
this.fill_song_info(block, patterns);
}
async parse_page() {
let { url } = this;
if (url.startsWith('https://')) {
url = url.replace(/^https:/, 'http:');
}
const html = await this.get_html(url);
this.find_lyric(url, html);
this.find_info(url, html);
return true;
}
}
exports.keyword = keyword;
exports.Lyric = Lyric;
if (require.main === module) {
(async () => {
const url = 'https://mojim.com/twy105842x18x5.htm';
const object = new Lyric(url);
const lyric = await object.get();
console.log(lyric);
})();
}
|
JavaScript
| 0.000132 |
@@ -1,12 +1,57 @@
+const %7B decode %7D = require('html-entities');%0A
const Sentry
@@ -2348,20 +2348,19 @@
const
-html
+raw
= await
@@ -2379,16 +2379,46 @@
ml(url);
+%0A const html = decode(raw);
%0A%0A th
|
16457b8e7f6bde133088d444466d2e374076f768
|
build issues
|
config/test/protractor.conf.js
|
config/test/protractor.conf.js
|
// FIRST TIME ONLY- run:
// ./node_modules/.bin/webdriver-manager update
//
// Try: `npm run webdriver:update`
//
// AND THEN EVERYTIME ...
// 1. Compile with `tsc`
// 2. Make sure the test server (e.g., http-server: localhost:8080) is running.
// 3. ./node_modules/.bin/protractor protractor.config.js
//
// To do all steps, try: `npm run e2e`
var fs = require('fs');
var path = require('canonical-path');
var _ = require('lodash');
// const SpecReporter = require("jasmine-spec-reporter");
const SpecReporter = require('jasmine-spec-reporter').SpecReporter;
exports.config = {
// Capabilities to be passed to the webdriver instance.
capabilities: {
browserName: 'chrome'
},
// Protractor will run tests in parallel against each set of capabilities.
// Please note that if multiCapabilities is defined, the runner will ignore the capabilities configuration.
//
// Framework to use. Jasmine is recommended.
framework: 'jasmine2',
// framework: 'jasmine2', supposedly a workaround of some sort? jasmine also is for jasmine versions +2.x
// Spec patterns are relative to this config file
specs: ['**/*e2e-spec.js' ],
// timeout stuff
allScriptsTimeout: 120000,
getPageTimeout: 120000,
// Base URL for application server .. http-serve
baseUrl: 'http://localhost:8080',
// Base URL for application server .. webdriver server
// directConnect: true,
seleniumAddress: 'http://localhost:4444/wd/hub',
// For angular2 tests
useAllAngular2AppRoots: true,
// rootElement: 'app-sac-gwh',
onPrepare: function() {
//// SpecReporter
jasmine.getEnv().addReporter(new SpecReporter());
// jasmine.getEnv().addReporter(new SpecReporter({
// displayStacktrace: true,
// displayFailuresSummary: true,
// displayFailedSpec: true,
// displaySuiteNumber: true,
// displaySpecDuration: true
// }));
// debugging
console.log('browser.params:' + JSON.stringify(browser.params));
global.sendKeys = sendKeys;
// Allow changing bootstrap mode to NG1 for upgrade tests, AK 20170425 not necessary anymore?
// global.setProtractorToNg1Mode = function() {
// browser.useAllAngular2AppRoots = false;
// browser.rootEl = 'body';
// };
},
jasmineNodeOpts: {
defaultTimeoutInterval: 120000,
// defaultTimeoutInterval: 10000,
showTiming: true,
print: function() {}
}
};
// Hack - because of bug with protractor send keys
function sendKeys(element, str) {
return str.split('').reduce(function (promise, char) {
return promise.then(function () {
return element.sendKeys(char);
});
}, element.getAttribute('value'));
// better to create a resolved promise here but ... don't know how with protractor;
}
// Custom reporter
function Reporter(options) {
var _defaultOutputFile = path.resolve(process.cwd(), './_test-output', 'protractor-results.txt');
options.outputFile = options.outputFile || _defaultOutputFile;
initOutputFile(options.outputFile);
options.appDir = options.appDir || './';
var _root = { appDir: options.appDir, suites: [] };
log('AppDir: ' + options.appDir, +1);
var _currentSuite;
this.suiteStarted = function(suite) {
_currentSuite = { description: suite.description, status: null, specs: [] };
_root.suites.push(_currentSuite);
log('Suite: ' + suite.description, +1);
};
this.suiteDone = function(suite) {
var statuses = _currentSuite.specs.map(function(spec) {
return spec.status;
});
statuses = _.uniq(statuses);
var status = statuses.indexOf('failed') >= 0 ? 'failed' : statuses.join(', ');
_currentSuite.status = status;
log('Suite ' + _currentSuite.status + ': ' + suite.description, -1);
};
this.specStarted = function(spec) {
};
this.specDone = function(spec) {
var currentSpec = {
description: spec.description,
status: spec.status
};
if (spec.failedExpectations.length > 0) {
currentSpec.failedExpectations = spec.failedExpectations;
}
_currentSuite.specs.push(currentSpec);
log(spec.status + ' - ' + spec.description);
};
this.jasmineDone = function() {
outputFile = options.outputFile;
//// Alternate approach - just stringify the _root - not as pretty
//// but might be more useful for automation.
// var output = JSON.stringify(_root, null, 2);
var output = formatOutput(_root);
fs.appendFileSync(outputFile, output);
};
function initOutputFile(outputFile) {
var header = "Protractor results for: " + (new Date()).toLocaleString() + "\n\n";
fs.writeFileSync(outputFile, header);
}
// for output file output
function formatOutput(output) {
var indent = ' ';
var pad = ' ';
var results = [];
results.push('AppDir:' + output.appDir);
output.suites.forEach(function(suite) {
results.push(pad + 'Suite: ' + suite.description + ' -- ' + suite.status);
pad+=indent;
suite.specs.forEach(function(spec) {
results.push(pad + spec.status + ' - ' + spec.description);
if (spec.failedExpectations) {
pad+=indent;
spec.failedExpectations.forEach(function (fe) {
results.push(pad + 'message: ' + fe.message);
});
pad=pad.substr(2);
}
});
pad = pad.substr(2);
results.push('');
});
results.push('');
return results.join('\n');
}
// for console output
var _pad;
function log(str, indent) {
_pad = _pad || '';
if (indent == -1) {
_pad = _pad.substr(2);
}
console.log(_pad + str);
if (indent == 1) {
_pad = _pad + ' ';
}
}
}
|
JavaScript
| 0 |
@@ -687,14 +687,15 @@
e: '
-chrome
+firefox
'%0A
|
7a27fe459a306be837be6d935cd72802570906d5
|
Format output from graphql list command a little better
|
packages/@sanity/core/src/actions/graphql/listApisAction.js
|
packages/@sanity/core/src/actions/graphql/listApisAction.js
|
module.exports = async function listApisAction(args, context) {
const {apiClient, output} = context
const client = apiClient({
requireUser: true,
requireProject: true
})
let endpoints
try {
endpoints = await client.request({
url: `/apis/graphql`,
method: 'GET'
})
} catch (err) {
if (err.statusCode === 404) {
endpoints = []
} else {
throw err
}
}
if (endpoints && endpoints.length > 0) {
output.print('Here are the GraphQL endpoints deployed for this project:')
endpoints.forEach((endpoint, index) => {
output.print(`* [${index + 1}] `)
output.print(` ** Dataset: ${endpoint.dataset}`)
output.print(` ** Tag: ${endpoint.tag}`)
output.print(` ** Generation: ${endpoint.generation}`)
output.print(` ** Playground: ${endpoint.playgroundEnabled}\n`)
})
}
output.print("This project doesn't have any GraphQL endpoints deployed.")
}
|
JavaScript
| 0 |
@@ -83,16 +83,23 @@
, output
+, chalk
%7D = cont
@@ -417,16 +417,239 @@
%7D%0A %7D%0A%0A
+ endpoints = %5B%7B%0A dataset: 'production',%0A tag: 'default',%0A generation: 'gen1',%0A playgroundEnabled: false%0A %7D, %7B%0A dataset: 'staging',%0A tag: 'next',%0A generation: 'gen2',%0A playgroundEnabled: true%0A %7D%5D%0A%0A
if (en
@@ -830,11 +830,8 @@
nt(%60
-* %5B
$%7Bin
@@ -842,46 +842,33 @@
+ 1%7D
-%5D %60)%0A output.print(%60 **
+. $%7Bchalk.bold('
Dataset:
@@ -863,16 +863,19 @@
Dataset:
+')%7D
$%7Be
@@ -919,15 +919,31 @@
(%60
-**
+ $%7Bchalk.bold('
Tag:
+')%7D
@@ -987,19 +987,32 @@
rint(%60
-**
+ $%7Bchalk.bold('
Generati
@@ -1014,16 +1014,19 @@
eration:
+')%7D
$%7Bendp
@@ -1070,11 +1070,24 @@
(%60
-**
+ $%7Bchalk.bold('
Play
@@ -1093,16 +1093,19 @@
yground:
+')%7D
$%7Bendp
|
dc3edae3167c5e6784c41a6d8555dbb00b4de49d
|
Fix css-vars issue on preview refresh.
|
modules/css-vars/script.js
|
modules/css-vars/script.js
|
/* global kirkiCssVarFields */
var kirkiCssVars = {
/**
* Get styles.
*
* @since 3.0.28
* @returns {Object}
*/
getStyles: function() {
var style = jQuery( '#kirki-css-vars' ),
styles = style.html().replace( ':root{', '' ).replace( '}', '' ).split( ';' ),
stylesObj = {};
// Format styles as a object we can then tweak.
_.each( styles, function( style ) {
style = style.split( ':' );
if ( style[0] && style[1] ) {
stylesObj[ style[0] ] = style[1];
}
} );
return stylesObj;
},
/**
* Builds the styles from an object.
*
* @since 3.0.28
* @param {Object} vars - The vars.
* @returns {string}
*/
buildStyle: function( vars ) {
var style = '';
_.each( vars, function( val, name ) {
style += name + ':' + val + ';';
} );
return ':root{' + style + '}';
}
};
jQuery( document ).ready( function() {
_.each( kirkiCssVarFields, function( field ) {
wp.customize( field.settings, function( value ) {
value.bind( function( newVal ) {
var styles = kirkiCssVars.getStyles();
_.each( field.css_vars, function( cssVar ) {
if ( 'object' === typeof newVal ) {
if ( cssVar[2] && newVal[ cssVar[2] ] ) {
styles[ cssVar[0] ] = cssVar[1].replace( '$', newVal[ cssVar[2] ] );
}
} else {
styles[ cssVar[0] ] = cssVar[1].replace( '$', newVal );
}
} );
jQuery( '#kirki-css-vars' ).html( kirkiCssVars.buildStyle( styles ) ) ;
} );
} );
} );
} );
|
JavaScript
| 0 |
@@ -1429,20 +1429,737 @@
yles ) )
-%09%09%09%09
+;%0A%09%09%09%7D );%0A%09%09%7D );%0A%09%7D );%0A%7D );%0A%0Awp.customize.bind( 'preview-ready', function() %7B%0A%09wp.customize.preview.bind( 'active', function() %7B%0A%09%09_.each( kirkiCssVarFields, function( field ) %7B%0A%09%09%09wp.customize( field.settings, function( value ) %7B%0A%09%09%09%09var styles = kirkiCssVars.getStyles(),%0A%09%09%09%09%09newVal = window.parent.wp.customize( value.id ).get();%0A%09%09%09%09_.each( field.css_vars, function( cssVar ) %7B%0A%09%09%09%09%09if ( 'object' === typeof newVal ) %7B%0A%09%09%09%09%09%09if ( cssVar%5B2%5D && newVal%5B cssVar%5B2%5D %5D ) %7B%0A%09%09%09%09%09%09%09styles%5B cssVar%5B0%5D %5D = cssVar%5B1%5D.replace( '$', newVal%5B cssVar%5B2%5D %5D );%0A%09%09%09%09%09%09%7D%0A%09%09%09%09%09%7D else %7B%0A%09%09%09%09%09%09styles%5B cssVar%5B0%5D %5D = cssVar%5B1%5D.replace( '$', newVal );%0A%09%09%09%09%09%7D%0A%09%09%09%09%7D );%0A%09%09%09%09jQuery( '#kirki-css-vars' ).html( kirkiCssVars.buildStyle( styles ) )
;%0A%09%09%09%7D )
|
1f38dcdf8a85955b44a71bd006263ed6992400df
|
Set the correct node type in helper-remap-async-to-generator
|
packages/babel-helper-remap-async-to-generator/src/index.js
|
packages/babel-helper-remap-async-to-generator/src/index.js
|
/* @flow */
import type { NodePath } from "babel-traverse";
import nameFunction from "babel-helper-function-name";
import template from "babel-template";
import * as t from "babel-types";
let buildWrapper = template(`
(function () {
var ref = FUNCTION;
return function (PARAMS) {
return ref.apply(this, arguments);
};
})
`);
let awaitVisitor = {
Function(path) {
path.skip();
},
AwaitExpression({ node }) {
node.type = "YieldExpression";
}
};
function classOrObjectMethod(path: NodePath, callId: Object) {
let node = path.node;
let body = node.body;
node.async = false;
let container = t.functionExpression(null, [], t.blockStatement(body.body), true);
container.shadow = true;
body.body = [
t.returnStatement(t.callExpression(
t.callExpression(callId, [container]),
[]
))
];
}
function plainFunction(path: NodePath, callId: Object) {
let node = path.node;
if (path.isArrowFunctionExpression()) {
path.arrowFunctionToShadowed();
}
node.async = false;
node.generator = true;
let asyncFnId = node.id;
node.id = null;
let built = t.callExpression(callId, [node]);
let container = buildWrapper({
FUNCTION: built,
PARAMS: node.params.map(() => path.scope.generateUidIdentifier("x"))
}).expression;
let retFunction = container.body.body[1].argument;
if (path.isFunctionDeclaration()) {
let declar = t.variableDeclaration("let", [
t.variableDeclarator(
t.identifier(asyncFnId.name),
t.callExpression(container, [])
)
]);
declar._blockHoist = true;
retFunction.id = asyncFnId;
path.replaceWith(declar);
} else {
if (asyncFnId && asyncFnId.name) {
retFunction.id = asyncFnId;
} else {
nameFunction({
node: retFunction,
parent: path.parent,
scope: path.scope
});
}
if (retFunction.id || node.params.length) {
// we have an inferred function id or params so we need this wrapper
path.replaceWith(t.callExpression(container, []));
} else {
// we can omit this wrapper as the conditions it protects for do not apply
path.replaceWith(built);
}
}
}
export default function (path: NodePath, callId: Object) {
let node = path.node;
if (node.generator) return;
path.traverse(awaitVisitor);
if (path.isClassMethod() || path.isObjectMethod()) {
return classOrObjectMethod(path, callId);
} else {
return plainFunction(path, callId);
}
}
|
JavaScript
| 0.000016 |
@@ -1391,24 +1391,63 @@
ration()) %7B%0A
+ node.type = %22FunctionExpression%22;%0A%0A
let decl
|
b93a481d099d827ea1706dc848adecb86e670945
|
Range Not satisfiable error fix
|
config/express.js
|
config/express.js
|
'use strict';
var express = require('express'),
path = require('path'),
config = require('./config'),
serveIndex = require('serve-index');
var favicon = require('serve-favicon'), //express middleware
errorHandler = require('errorhandler'),
logger = require('morgan'),
methodOverride = require('method-override'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser');
//CORS middleware , add more controls for security like site names, timeout etc.
var allowCrossDomain = function (req, res, next) {
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Expose-Headers', 'Content-Length');
res.header('Access-Control-Allow-Methods', 'HEAD,GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, X-Requested-With,origin,accept,Authorization');
if (req.method == 'OPTIONS') {
res.sendStatus(200);
}
else {
next();
}
}
var basicHttpAuth = function(req,res,next) {
var auth = req.headers['authorization']; // auth is in base64(username:password) so we need to decode the base64
if(!auth) { // No Authorization header was passed in so it's the first time the browser hit us
// Sending a 401 will require authentication, we need to send the 'WWW-Authenticate' to tell them the sort of authentication to use
res.statusCode = 401;
res.setHeader('WWW-Authenticate', 'Basic realm="Secure Area"');
res.end('<html><body>Authentication required to access this path</body></html>');
} else {
var tmp = auth.split(' '); // Split on a space, the original auth looks like "Basic Y2hhcmxlczoxMjM0NQ==" and we need the 2nd part
var buf = new Buffer(tmp[1], 'base64'); // create a buffer and tell it the data coming in is base64
var plain_auth = buf.toString(); // read it back out as a string
//console.log("Decoded Authorization ", plain_auth);
// At this point plain_auth = "username:password"
var creds = plain_auth.split(':'); // split on a ':'
var username = creds[0];
var password = creds[1];
var pathComponents = req.path.split('/');
//console.log(pathComponents);
require('../app/controllers/licenses').getSettingsModel(function(err,settings){
if( (!settings.authCredentials) ||
(!settings.authCredentials.user || username == settings.authCredentials.user) &&
(!settings.authCredentials.password || password == settings.authCredentials.password)) {
//console.log("http request authorized for download for "+req.path);
next();
} else {
console.log("http request rejected for download for "+req.path);
res.statusCode = 401; // or alternatively just reject them altogether with a 403 Forbidden
res.setHeader('WWW-Authenticate', 'Basic realm="Secure Area"');
res.end('<html><body>Authentication required to access this path</body></html>');
}
})
}
}
module.exports = function (app) {
//CORS related http://stackoverflow.com/questions/7067966/how-to-allow-cors-in-express-nodejs
app.use(allowCrossDomain);
if (process.env.NODE_ENV == 'development') {
// Disable caching of scripts for easier testing
app.use(function noCache(req, res, next) {
if (req.url.indexOf('/scripts/') === 0) {
res.header('Cache-Control', 'no-cache, no-store, must-revalidate');
res.header('Pragma', 'no-cache');
res.header('Expires', 0);
}
next();
});
app.use(errorHandler());
app.locals.pretty = true;
app.locals.compileDebug = true;
}
if (process.env.NODE_ENV == 'production') {
app.use(favicon(path.join(config.root, 'public', 'favicon.ico')));
};
//app.use(auth.connect(digest)); //can specify specific routes for auth also
app.use(basicHttpAuth);
app.use('/sync_folders',serveIndex(config.syncDir));
app.use('/sync_folders',express.static(config.syncDir));
app.use('/releases',express.static(config.releasesDir));
app.use('/licenses',express.static(config.licenseDir));
app.use('/media', express.static(path.join(config.mediaDir)));
app.use(express.static(path.join(config.root, 'public')));
app.set('view engine', 'jade');
app.locals.basedir = config.viewDir; //for jade root
app.set('views', config.viewDir);
//app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride());
app.use(cookieParser());
app.use(require('./routes'));
// custom error handler
app.use(function (err, req, res, next) {
if (~err.message.indexOf('not found')) return next();
//ignore range error as well
if (~err.message.indexOf('Requested Range Not Satisfiable')) return res.send();
console.error(err.stack)
res.status(500).render('500')
})
app.use(function (req, res, next) {
//res.redirect('/');
res.status(404).render('404', {url: req.originalUrl})
})
};
|
JavaScript
| 0.000003 |
@@ -4992,33 +4992,32 @@
) %7B%0A if (
-~
err.message.inde
@@ -5032,16 +5032,20 @@
found')
+ %3E=0
) return
@@ -5106,9 +5106,8 @@
if (
-~
err.
@@ -5127,18 +5127,8 @@
Of('
-Requested
Rang
@@ -5146,16 +5146,21 @@
fiable')
+ %3E=0
) return
|
3b88ae1224f5462e33db9fbaa579379ebd786eba
|
remove log
|
modules/gulp-nuget-pack.js
|
modules/gulp-nuget-pack.js
|
const temp = require("temp"),
xml2js = require("xml2js"),
Vinyl = require("vinyl"),
fs = require("./fs"),
path = require("path"),
parseXml = function(data) {
return new Promise((resolve, reject) => {
xml2js.parseString(data, (err, result) => {
if (err) {
return reject(err);
}
resolve(result);
});
});
},
looksLikeAPromise = requireModule("looks-like-a-promise"),
gutil = require("gulp-util"),
spawnNuget = requireModule("spawn-nuget"),
es = require("event-stream");
async function grokNuspec(xmlString) {
const pkg = await parseXml(xmlString),
metadata = pkg.package.metadata[0];
return {
packageName: metadata.id[0],
packageVersion: metadata.version[0]
};
}
async function resolveAll(obj) {
const result = {};
for (const key of Object.keys(obj)) {
if (looksLikeAPromise(obj[key])) {
result[key] = await obj[key];
} else {
result[key] = obj[key];
}
}
return result;
}
function resolveRelativeBasePathOn(options, nuspecPath) {
console.log({
options
});
if (!options.basePath) {
return;
}
if (options.basePath.indexOf("~") === 0) {
const
packageDir = path.dirname(nuspecPath).replace(/\\/g, "/"),
sliced = options.basePath.substr(1).replace(/\\/g, "/");
options.basePath = path.join(packageDir, sliced);
}
}
function addOptionalParameters(options, args) {
if (options.basePath) {
gutil.log(`packaging with base path: ${options.basePath}`);
args.splice(args.length, 0, "-BasePath", options.basePath);
}
if (options.excludeEmptyDirectories) {
args.splice(args.length, 0, "-ExcludeEmptyDirectories");
}
if (options.version) {
gutil.log(`Overriding package version with: ${options.version}`);
args.splice(args.length, 0, "-version", options.version);
}
}
function gulpNugetPack(options) {
options = Object.assign({}, options);
options.basePath = process.env.PACK_BASE_PATH || options.basePath;
options.excludeEmptyDirectories = process.env.PACK_INCLUDE_EMPTY_DIRECTORIES
? false
: options.excludeEmptyDirectories === undefined
? true
: false;
options.version = options.version || process.env.PACK_VERSION;
const tracked = temp.track();
(workDir = tracked.mkdirSync()), (promises = []);
return es.through(
function write(file) {
promises.push(
new Promise(async (resolve, reject) => {
options = await resolveAll(options);
resolveRelativeBasePathOn(options, file.path);
const { packageName, packageVersion } = await grokNuspec(
file.contents.toString()
),
version = options.version || packageVersion,
expectedFileName = path.join(
workDir,
`${packageName}.${version}.nupkg`
),
args = ["pack", file.path, "-OutputDirectory", workDir];
await fs.ensureDirectoryExists(workDir);
addOptionalParameters(options, args);
await spawnNuget(args, {
stdout: () => {
/* suppress stdout: it's confusing anyway because it mentions temp files */
}
});
const outputExists = await fs.exists(expectedFileName);
if (!outputExists) {
const err = `file not found: ${expectedFileName}`;
this.emit("error", err);
reject(err);
} else {
logBuilt(expectedFileName);
this.emit(
"data",
new Vinyl({
path: path.basename(expectedFileName),
contents: await fs.readFile(expectedFileName)
})
);
resolve();
}
})
);
},
async function end() {
await Promise.all(promises);
tracked.cleanupSync();
this.emit("end");
}
);
}
function logBuilt(packagePath) {
gutil.log(
gutil.colors.yellow(`build package: ${path.basename(packagePath)}`)
);
}
module.exports = gulpNugetPack;
|
JavaScript
| 0 |
@@ -1051,42 +1051,8 @@
) %7B%0A
- console.log(%7B%0A options%0A %7D);%0A
if
|
472c9d3a88180b474c98a015914154110cb054b1
|
Fix U4-4779: Media Picker not working as single picker
|
src/Umbraco.Web.UI.Client/src/views/propertyeditors/mediapicker/mediapicker.controller.js
|
src/Umbraco.Web.UI.Client/src/views/propertyeditors/mediapicker/mediapicker.controller.js
|
//this controller simply tells the dialogs service to open a mediaPicker window
//with a specified callback, this callback will receive an object with a selection on it
angular.module('umbraco').controller("Umbraco.PropertyEditors.MediaPickerController",
function($rootScope, $scope, dialogService, mediaResource, mediaHelper, $timeout) {
//check the pre-values for multi-picker
var multiPicker = $scope.model.config.multiPicker !== '0' ? true : false;
if (!$scope.model.config.startNodeId)
$scope.model.config.startNodeId = -1;
function setupViewModel() {
$scope.images = [];
$scope.ids = [];
if ($scope.model.value) {
var ids = $scope.model.value.split(',');
mediaResource.getByIds(ids).then(function (medias) {
//img.media = media;
_.each(medias, function (media, i) {
//only show non-trashed items
if(media.parentId >= -1){
if(!media.thumbnail){
media.thumbnail = mediaHelper.resolveFile(media, true);
}
//media.src = mediaHelper.getImagePropertyValue({ imageModel: media });
//media.thumbnail = mediaHelper.getThumbnailFromPath(media.src);
$scope.images.push(media);
$scope.ids.push(media.id);
}
});
$scope.sync();
});
}
}
setupViewModel();
$scope.remove = function(index) {
$scope.images.splice(index, 1);
$scope.ids.splice(index, 1);
$scope.sync();
};
$scope.add = function() {
dialogService.mediaPicker({
startNodeId: $scope.model.config.startNodeId,
multiPicker: multiPicker,
callback: function(data) {
//it's only a single selector, so make it into an array
if (!multiPicker) {
data = [data];
}
_.each(data, function(media, i) {
if(!media.thumbnail){
media.thumbnail = mediaHelper.resolveFile(media, true);
}
$scope.images.push(media);
$scope.ids.push(media.id);
});
$scope.sync();
}
});
};
$scope.sortableOptions = {
update: function(e, ui) {
var r = [];
//TODO: Instead of doing this with a half second delay would be better to use a watch like we do in the
// content picker. THen we don't have to worry about setting ids, render models, models, we just set one and let the
// watch do all the rest.
$timeout(function(){
angular.forEach($scope.images, function(value, key){
r.push(value.id);
});
$scope.ids = r;
$scope.sync();
}, 500, false);
}
};
$scope.sync = function() {
$scope.model.value = $scope.ids.join();
};
$scope.showAdd = function () {
if (!multiPicker) {
if ($scope.model.value && $scope.model.value !== "") {
return false;
}
}
return true;
};
//here we declare a special method which will be called whenever the value has changed from the server
//this is instead of doing a watch on the model.value = faster
$scope.model.onValueChanged = function (newVal, oldVal) {
//update the display val again if it has changed from the server
setupViewModel();
};
});
|
JavaScript
| 0.000004 |
@@ -416,16 +416,51 @@
Picker =
+ $scope.model.config.multiPicker &&
$scope.
@@ -4309,12 +4309,14 @@
;%0D%0A%0D%0A %7D);
+%0D%0A
|
20ad79c5cf36e84c7e003af77782956d7dd462b0
|
add option entriesFilter
|
lib/util/ensureConfigHasEntry.js
|
lib/util/ensureConfigHasEntry.js
|
function ensureConfigHasEntry (webpackConfig, entry, entryQuery, options = {}) {
if (Array.isArray(webpackConfig)) {
return webpackConfig.map((value) => ensureConfigHasEntry(value, entry, entryQuery, options))
}
if (Array.isArray(entry)) {
entry.forEach((e) => ensureConfigHasEntry(webpackConfig, e, entryQuery, options))
return webpackConfig
}
return insertEntry(webpackConfig, 'entry', entry, entryQuery, options)
}
function formatPathWithQuery (path, query) {
if (query && typeof query === 'object') {
query = Object.keys(query)
.map((key) => `${key}=${query[key]}`)
.join('&')
}
if (query) {
path = `${path}?${query}`
}
return path
}
function inModule (moduleName, entry) {
if (typeof entry !== 'string') {
return false
}
while (entry.endsWith('/') || entry.endsWith('\\')) {
entry = entry.substring(0, entry.length - 1)
}
return entry === moduleName
|| entry.startsWith(moduleName + '/')
|| entry.startsWith(moduleName + '\\')
|| entry.startsWith(moduleName + '?')
|| (moduleName.test && moduleName.test(entry))
}
function insertEntry (obj, key, entry, entryQuery, options = {}) {
if (!obj[key]) {
obj[key] = []
}
if (typeof obj[key] === 'string') {
obj[key] = [obj[key]]
}
if (!Array.isArray(obj[key])) {
Object.keys(obj[key]).forEach((entryName) => {
insertEntry(obj[key], entryName, entry, entryQuery, options)
})
return obj
}
const entries = obj[key]
let {
append,
topModuleEntries
} = options
if (entry[0] === '+') {
entry = entry.substring(1)
append = true
}
const hasEntry = entries.find((e) => inModule(entry, e))
if (!hasEntry) {
entry = formatPathWithQuery(entry, entryQuery)
topModuleEntries = [].concat(topModuleEntries || [])
const topEntries = entries.filter((e) => {
return topModuleEntries.find((topEntry) => inModule(topEntry, e))
})
const nextEntries = entries.filter((e) => {
return topEntries.indexOf(e) === -1
})
nextEntries[append ? 'push' : 'unshift'].call(nextEntries, entry)
if (topEntries.length) {
nextEntries.unshift.apply(nextEntries, topEntries)
}
entries.length = 0
entries.push.apply(entries, nextEntries)
}
return obj
}
module.exports = Object.assign(ensureConfigHasEntry.bind(), {
ensureConfigHasEntry,
formatPathWithQuery,
inModule,
insertEntry
})
|
JavaScript
| 0 |
@@ -1328,28 +1328,242 @@
-Object.keys(obj%5Bkey%5D
+let %7B%0A entriesFilter = () =%3E true%0A %7D = options%0A%0A if (Array.isArray(entriesFilter)) %7B%0A entriesFilter = (entryName) =%3E options.entriesFilter.indexOf(entryName) !== -1%0A %7D%0A%0A Object.keys(obj%5Bkey%5D).filter(entriesFilter
).fo
|
53cb773a3781196dd9535c21662fd0fd085f7d2e
|
fix indention
|
lib/utils/parse-platform-opts.js
|
lib/utils/parse-platform-opts.js
|
var _kebabCase = require('lodash').kebabCase;
var _forEach = require('lodash').forEach;
var IOS_OPTS = [
'codeSignIdentity',
'provisioningProfile',
'codesignResourceRules'
];
var ANDROID_OPTS = [
'keystore',
'provisioningProfile',
'storePassword',
'alias',
'password',
'keystoreType',
'gradleArg',
'cdvBuildMultipleApks',
'cdvVersionCode',
'cdvReleaseSigningPropertiesFile',
'cdvDebugSigningPropertiesFile',
'cdvMinSdkVersion',
'cdvBuildToolsVersion',
'cdvCompileSdkVersion'
];
module.exports = function(platform, options) {
var optsKeys = [];
var parsedOptions = {};
if (platform === 'ios') { optsKeys = IOS_OPTS; }
else if (platform === 'android') { optsKeys = ANDROID_OPTS; }
_forEach(optsKeys, function(key) {
var _key = _kebabCase(key)
parsedOptions[key] = options[_key];
});
return parsedOptions;
}
|
JavaScript
| 0.000001 |
@@ -626,24 +626,28 @@
=== 'ios') %7B
+%0A
optsKeys =
@@ -659,12 +659,12 @@
PTS;
- %7D
%0A
+ %7D
els
@@ -694,16 +694,20 @@
roid') %7B
+%0A
optsKey
@@ -723,16 +723,18 @@
ID_OPTS;
+%0A
%7D%0A%0A _f
|
b87e40b5cf7fed9fba170f01840aaa2586f62ea6
|
fix case of import
|
server/controllers/AdditionalReviewerController.js
|
server/controllers/AdditionalReviewerController.js
|
/*
The Conflict of Interest (COI) module of Kuali Research
Copyright © 2015 Kuali, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
*/
import * as AdditionalReviewerDB from '../db/AdditionalReviewerDB';
import Log from '../Log';
import { COIConstants } from '../../COIConstants';
import { OK, FORBIDDEN } from '../../HTTPStatusCodes';
export const init = app => {
/**
@Role: admin
*/
app.post('/api/coi/additional-reviewers', (req, res, next) => {
if (req.userInfo.coiRole !== COIConstants.ROLES.ADMIN) {
res.sendStatus(FORBIDDEN);
return;
}
AdditionalReviewerDB.createAdditionalReviewer(req.dbInfo, req.body).then(result => {
res.send(result);
})
.catch(err => {
Log.error(err);
next(err);
});
});
/**
@Role: admin
*/
app.delete('/api/coi/additional-reviewers/:id', (req, res, next) => {
if (req.userInfo.coiRole !== COIConstants.ROLES.ADMIN) {
res.sendStatus(FORBIDDEN);
return;
}
AdditionalReviewerDB.deleteAdditionalReviewer(req.dbInfo, req.params.id).then(() => {
res.sendStatus(OK);
})
.catch(err => {
Log.error(err);
next(err);
});
});
};
|
JavaScript
| 0.000275 |
@@ -794,17 +794,17 @@
eviewerD
-B
+b
';%0Aimpor
|
dcc29edb76cccab78de102bc9bf4f33029cdc090
|
remove debugging element
|
packages/react-router-website/modules/components/APIDocs.js
|
packages/react-router-website/modules/components/APIDocs.js
|
import React from 'react'
import ReactDOM from 'react-dom'
import { Route } from 'react-router-dom'
import { I, H, B, PAD, lightGray, red } from './bricks'
import MarkdownViewer from './MarkdownViewer'
import ScrollToMe from './ScrollToMe'
export const API = [
{ name: 'BrowserRouter',
html: require('../api/BrowserRouter.md')
},
{ name: 'HashRouter',
html: require('../api/HashRouter.md')
},
{ name: 'MemoryRouter',
html: require('../api/MemoryRouter.md')
},
{ name: 'NativeRouter',
html: require('../api/NativeRouter.md')
},
{ name: 'StaticRouter',
html: require('../api/StaticRouter.md')
},
{ name: 'Router',
html: require('../api/Router.md')
},
{ name: 'Route',
html: require('../api/Route.md')
},
{ name: 'Switch',
html: require('../api/Switch.md')
},
{ name: 'Link',
html: require('../api/Link.md')
},
{ name: 'Redirect',
html: require('../api/Redirect.md')
},
{ name: 'Prompt',
html: require('../api/Prompt.md')
},
{ name: 'withRouter',
html: require('../api/withRouter.md')
},
{ name: 'context.router',
html: require('../api/context.router.md')
},
{ name: 'history',
html: require('../api/history.md')
},
{ name: 'match',
html: require('../api/match.md')
}
]
const $ = (node, selector) => (
[].slice.call(node.querySelectorAll(selector))
)
class APIDocs extends React.Component {
state = {
overflow: 'hidden'
}
listenToWindowScroll() {
window.addEventListener('scroll', this.handleWindowScroll)
}
handleWindowScroll = () => {
const top = this.root.offsetTop
const bottom = top + this.root.offsetHeight
const fold = window.innerHeight + window.scrollY
const topIsVisible = top <= fold && window.scrollY <= top
const bottomIsVisible = bottom <= fold
console.log('BLAH')
if (topIsVisible && bottomIsVisible) {
this.setState({ overflow: 'auto' })
} else if (this.state.overflow === 'auto') {
this.setState({ overflow: 'hidden' })
}
}
componentDidMount() {
this.listenToWindowScroll()
const items = $(this.root, '.api-entry').map(entry => {
const name = $(entry, 'h1')[0].childNodes[1].textContent.trim()
const hash = $(entry, 'h1 a')[0].hash
const children = $(entry, 'h2').map(node => ({
name: node.childNodes[1].textContent.trim(),
hash: $(node, 'a')[0].hash
}))
return { name, hash, children }
})
this.renderMenu(items)
}
renderMenu(items) {
const element = (
<B fontFamily="Monaco, monospace">
{items.map(item => (
<B key={item.hash} margin="10px">
<B component="a" props={{ href: item.hash }} fontWeight="bold" color={red} hoverTextDecoration="underline">{item.name}</B>
<B marginLeft="20px">
{item.children.map(({ hash, name }) => (
<B key={hash} component="a" props={{ href: hash }} color={lightGray} hoverTextDecoration="underline">{name}</B>
))}
</B>
</B>
))}
</B>
)
ReactDOM.render(element, this.menu)
}
render() {
const { overflow } = this.state
return (
<B props={{ ref: node => this.root = node }}>
<Route exact path="/api" component={ScrollToMe}/>
<H height="95vh">
<B props={{ ref: node => this.menu = node }} height="100%" overflow={overflow} fontSize="80%" padding="40px" background="#f0f0f0"/>
<B flex="1" height="100%" overflow={overflow}>
<B>{this.state.overflow}</B>
{API.map((doc, i) => (
<B className="api-entry" key={i} padding="40px 60px">
<MarkdownViewer html={doc.html}/>
</B>
))}
</B>
</H>
</B>
)
}
}
export default APIDocs
|
JavaScript
| 0.000016 |
@@ -3522,49 +3522,8 @@
w%7D%3E%0A
- %3CB%3E%7Bthis.state.overflow%7D%3C/B%3E%0A
|
b004fb2752abf26bc1b087d54d17016aa22ca4f3
|
add Flow
|
src/synthesizeImages.js
|
src/synthesizeImages.js
|
function loadImage(dataUrl) {
return new Promise(resolve => {
const image = new Image();
image.onload = () => resolve(image);
image.src = dataUrl;
});
}
function generateBaseCanvas(baseImage) {
return loadImage(baseImage).then(image => {
const canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(image, 0, 0, image.width, image.height);
return {canvas, ctx};
});
}
export default function synthesizeImages(dataUrlList) {
return generateBaseCanvas(dataUrlList[0])
.then(({canvas, ctx}) => {
dataUrlList.shift();
return Promise.all(
dataUrlList.map(data => loadImage(data))
).then(images => ({canvas, ctx, images}));
})
.then(({canvas, ctx, images}) => {
images.forEach(image => {
ctx.drawImage(image, 0, 0, image.width, image.height);
});
return canvas.toDataURL();
});
}
|
JavaScript
| 0.000001 |
@@ -1,16 +1,25 @@
+// @flow%0A
function loadIma
@@ -28,17 +28,41 @@
(dataUrl
-)
+: string): Promise%3CImage%3E
%7B%0A ret
@@ -224,16 +224,19 @@
eCanvas(
+%0A
baseImag
@@ -236,17 +236,95 @@
aseImage
-)
+: string%0A): Promise%3C%7Bcanvas: HTMLCanvasElement, ctx: CanvasRenderingContext2D%7D%3E
%7B%0A ret
@@ -659,16 +659,19 @@
eImages(
+%0A
dataUrlL
@@ -673,17 +673,45 @@
aUrlList
-)
+: string%5B%5D%0A): Promise%3Cstring%3E
%7B%0A ret
|
29a3753ece812af0f57ee36132e50375a609ee00
|
Debug Quelltext entfernt.
|
invertika/index.js
|
invertika/index.js
|
/*!
*
* Invertika.js - Web-based 2D MMORPG
* http://invertika.org
*
*/
// Variablen
var ip = "127.0.0.1";
var accountServerConnectionString=sprintf("ws://%s:9601", ip);
var accountServer;
var PROTOCOL_VERSION=1;
var _username;
var _password;
//Debug
function debug()
{
//login("seeseekey", "geheim");
//login("schnee", "geheim");
login("florian", "geheim");
//register("florian", "geheim", "[email protected]", "IGNORE");
}
// Message Handler
function onMessage(message)
{
var responseMessage=new MessageIn(message.data);
switch(responseMessage.id)
{
case Protocol.APMSG_REGISTER_RESPONSE:
{
var registerReturnCode=responseMessage.getPart(0);
alert("Return code from register is: " + registerReturnCode);
break;
}
case Protocol.APMSG_LOGIN_RNDTRGR_RESPONSE: //Login Response
{
var token=responseMessage.getPart(0);
//Login Kommando zusammenbauen
var msg=new MessageOut(Protocol.PAMSG_LOGIN);
msg.addValue(PROTOCOL_VERSION); //Client Version
msg.addValue(username);
msg.addValue(sha256_digest(sha256_digest(sha256_digest(username + password))+token));
//BuildPW
// var a=sha256_digest(username + password);
// var b=sha256_digest(a);
// var c=sha256_digest(b+token);
// msg.addValue(c);
accountServer.send(msg.getString());
break;
}
default:
{
alert("Unbekannte Nachricht: " + message.data);
break;
}
}
}
// Funktionen
function login(username, password)
{
accountServer = new WebSocket(accountServerConnectionString);
//Login Paket zusammenbauen
var loginMsg=new MessageOut(Protocol.PAMSG_LOGIN_RNDTRGR);
loginMsg.addValue(username);
this.username=username;
this.password=password;
// when the connection is established, this method is called
accountServer.onopen = function () {
accountServer.send(loginMsg.getString());
};
// when data is comming from the server, this metod is called
accountServer.onmessage = onMessage;
}
function register(username, password, email, captchaResponse)
{
accountServer = new WebSocket(accountServerConnectionString);
//Register Kommando zusammenbauen
var registerMsg=new MessageOut(Protocol.PAMSG_REGISTER);
registerMsg.addValue(PROTOCOL_VERSION); //Client Version
registerMsg.addValue(username);
registerMsg.addValue(sha256_digest(username + password)); // Use a hashed password for privacy reasons
registerMsg.addValue(email);
registerMsg.addValue(captchaResponse);
// when the connection is established, this method is called
accountServer.onopen = function () {
accountServer.send(registerMsg.getString());
};
// when data is comming from the server, this metod is called
accountServer.onmessage = onMessage;
}
|
JavaScript
| 0 |
@@ -1116,162 +1116,8 @@
));%0A
-%09%09%09%0A%09%09%09//BuildPW%0A%09%09%09// var a=sha256_digest(username + password);%0A%09%09%09// var b=sha256_digest(a);%0A%09%09%09// var c=sha256_digest(b+token);%0A%09%09%09// msg.addValue(c);%0A
%09%09%09%09
|
6665c4693f2b677e4bc9b7aef5f6c3d71ef77e1c
|
Clear hang timeout timer when LibreOffice exits
|
src/node/utils/LibreOffice.js
|
src/node/utils/LibreOffice.js
|
/**
* Controls the communication with LibreOffice
*/
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var async = require("async");
var fs = require("fs");
var log4js = require('log4js');
var os = require("os");
var path = require("path");
var settings = require("./Settings");
var spawn = require("child_process").spawn;
// Conversion tasks will be queued up, so we don't overload the system
var queue = async.queue(doConvertTask, 1);
var libreOfficeLogger = log4js.getLogger('LibreOffice');
/**
* Convert a file from one type to another
*
* @param {String} srcFile The path on disk to convert
* @param {String} destFile The path on disk where the converted file should be stored
* @param {String} type The type to convert into
* @param {Function} callback Standard callback function
*/
exports.convertFile = function(srcFile, destFile, type, callback) {
// Used for the moving of the file, not the conversion
var fileExtension = type;
if (type === "html") {
// "html:XHTML Writer File:UTF8" does a better job than normal html exports
if (path.extname(srcFile).toLowerCase() === ".doc") {
type = "html";
}
// PDF files need to be converted with LO Draw ref https://github.com/ether/etherpad-lite/issues/4151
if (path.extname(srcFile).toLowerCase() === ".pdf") {
type = "html:XHTML Draw File"
}
}
// soffice can't convert from html to doc directly (verified with LO 5 and 6)
// we need to convert to odt first, then to doc
// to avoid `Error: no export filter for /tmp/xxxx.doc` error
if (type === 'doc') {
queue.push({
"srcFile": srcFile,
"destFile": destFile.replace(/\.doc$/, '.odt'),
"type": 'odt',
"callback": function () {
queue.push({"srcFile": srcFile.replace(/\.html$/, '.odt'), "destFile": destFile, "type": type, "callback": callback, "fileExtension": fileExtension });
}
});
} else {
queue.push({"srcFile": srcFile, "destFile": destFile, "type": type, "callback": callback, "fileExtension": fileExtension});
}
};
function doConvertTask(task, callback) {
var tmpDir = os.tmpdir();
async.series([
/*
* use LibreOffice to convert task.srcFile to another format, given in
* task.type
*/
function(callback) {
libreOfficeLogger.debug(`Converting ${task.srcFile} to format ${task.type}. The result will be put in ${tmpDir}`);
var soffice = spawn(settings.soffice, [
'--headless',
'--invisible',
'--nologo',
'--nolockcheck',
'--writer',
'--convert-to', task.type,
task.srcFile,
'--outdir', tmpDir
]);
// Soffice/libreoffice is buggy and often hangs.
// To remedy this we kill the spawned process after a while.
setTimeout(function(){
soffice.stdin.pause(); // required to kill hanging threads
soffice.kill();
}, 120000);
var stdoutBuffer = '';
// Delegate the processing of stdout to another function
soffice.stdout.on('data', function(data) {
stdoutBuffer += data.toString();
});
// Append error messages to the buffer
soffice.stderr.on('data', function(data) {
stdoutBuffer += data.toString();
});
soffice.on('exit', function(code) {
if (code != 0) {
// Throw an exception if libreoffice failed
return callback(`LibreOffice died with exit code ${code} and message: ${stdoutBuffer}`);
}
// if LibreOffice exited succesfully, go on with processing
callback();
})
},
// Move the converted file to the correct place
function(callback) {
var filename = path.basename(task.srcFile);
var sourceFilename = filename.substr(0, filename.lastIndexOf('.')) + '.' + task.fileExtension;
var sourcePath = path.join(tmpDir, sourceFilename);
libreOfficeLogger.debug(`Renaming ${sourcePath} to ${task.destFile}`);
fs.rename(sourcePath, task.destFile, callback);
}
], function(err) {
// Invoke the callback for the local queue
callback();
// Invoke the callback for the task
task.callback(err);
});
}
|
JavaScript
| 0 |
@@ -3312,31 +3312,46 @@
-setTimeout(function()%7B
+const hangTimeout = setTimeout(() =%3E %7B
%0A
@@ -3842,24 +3842,59 @@
ion(code) %7B%0A
+ clearTimeout(hangTimeout);%0A
if (
|
fb39a8ba49a28f777eb01bdecd8f988ce5f70e54
|
Update w/ api changes.
|
ios/example/app.js
|
ios/example/app.js
|
// This is a test harness for your module
// You should do something interesting in this harness
// to test out the module and to provide instructions
// to users on how to use it by example.
// open a single window
var win = Ti.UI.createWindow({
backgroundColor:'white'
});
var label = Ti.UI.createLabel();
win.add(label);
win.open();
var SYNC_URL = "http://checkers.sync.couchbasecloud.com/checkers";
var CBLite = require('com.couchbase.cbl');
var manager = CBLite.createManager();
var database = manager.createDatabase("checkers");
//database.deleteDatabase();
var userId = "test1";
var userDocId = "user:" + userId;
var voteDocId = "vote:" + userId;
// Replicators
var replications = database.replicate(SYNC_URL, true);
for (var i=0; i<replications.length; i++) {
var replication = replications[i];
replication.continuous = true;
// NOTE: There are issues w/ persistent=true during cold-start.
replication.persistent = true;
if(replication.pull) {
replication.filter = "sync_gateway/bychannel";
replication.query_params = {"channels":"game"};
} else {
database.defineFilter("pushItems", function(properties, params) {
return (properties._id == userDocId || properties._id == voteDocId);
});
replication.filter = "pushItems";
}
}
// Team
var userDoc = database.getDocument(userDocId);
if (!userDoc.currentRevision) userDoc.putProperties({});
userDoc.update(function(newRevision) {
newRevision.putProperties({
"team":0
});
return true;
});
// Vote
var voteDoc = database.getDocument(voteDocId);
if (!voteDoc.currentRevision) voteDoc.putProperties({});
voteDoc.update(function(newRevision) {
newRevision.putProperties({
"game":1,
"turn":1,
"team":0,
"piece":7,
"locations":[11,15]
});
return true;
});
// Create view for games by start time.
var gamesByStartTime = database.getView("gamesByStartTime");
if (!gamesByStartTime.map) {
gamesByStartTime.setMapAndReduce(function(doc, emitter) {
if (doc["_id"].indexOf("game:") == 0 && doc.startTime) {
emitter.emit(doc.startTime, doc);
}
}, null, "1.0");
}
// Create/observe live query for the latest game.
var liveQuery = gamesByStartTime.createQuery().toLiveQuery();
liveQuery.limit = 1;
liveQuery.descending = true;
liveQuery.addEventListener(liveQuery.CHANGE_EVENT, function(e) {
Ti.API.info("### liveQuery.rowschange: " + e.source + ", " + e.source.rows + "[" + e.source.rows.count + "]");
});
/*var query = database.queryAllDocuments;
var rows = query.rows;
label.text = rows.count;
var row = rows.nextRow;
while (row) {
Ti.API.info(row.documentID);
row = rows.nextRow;
}*/
/*setTimeout(function() {
CBLite.runCurrentRunLoop();
}, 100);*/
var i = 0;
setInterval(function() {
var query = database.queryAllDocuments;
var rows = query.rows;
label.text = rows.count + " - " + ++i;
/*var row = rows.nextRow;
while (row) {
Ti.API.info(row.documentID);
row = rows.nextRow;
}*/
}, 1000);
/*setInterval(function() {
Ti.API.info("runCurrentRunLoop");
CBLite.runCurrentRunLoop();
}, 1000);*/
//label.text = replications[0].running + ", " + replications[0].running;
try {
//label.text = manager.directory;
//label.text = database.name;
//label.text = CBLite.HTTP_ERROR_DOMAIN;
} catch (e) {
//label.text = e;
}
/*// TODO: write your module tests here
var CouchbaseLiteTitanium = require('com.couchbase.cbl');
Ti.API.info("module is => " + CouchbaseLiteTitanium);
label.text = CouchbaseLiteTitanium.example();
Ti.API.info("module exampleProp is => " + CouchbaseLiteTitanium.exampleProp);
CouchbaseLiteTitanium.exampleProp = "This is a test value";
if (Ti.Platform.name == "android") {
var proxy = CouchbaseLiteTitanium.createExample({
message: "Creating an example Proxy",
backgroundColor: "red",
width: 100,
height: 100,
top: 100,
left: 150
});
proxy.printMessage("Hello world!");
proxy.message = "Hi world!. It's me again.";
proxy.printMessage("Hello world!");
win.add(proxy);
}*/
|
JavaScript
| 0 |
@@ -562,24 +562,183 @@
atabase();%0A%0A
+database.addEventListener(database.CHANGE_EVENT, function(e) %7B%0A%09var query = e.source.queryAllDocuments;%0A%09%0A%09label.text = %22Documents: %22 + query.rows.count;%0A%7D);%0A%0A
var userId =
@@ -981,17 +981,19 @@
ication.
-c
+isC
ontinuou
@@ -1083,17 +1083,19 @@
ication.
-p
+isP
ersisten
@@ -1128,17 +1128,19 @@
ication.
-p
+isP
ull) %7B%0A
@@ -1222,10 +1222,9 @@
uery
-_p
+P
aram
@@ -2543,20 +2543,16 @@
veQuery.
-rows
change:
@@ -2879,16 +2879,18 @@
00);*/%0A%0A
+/*
var i =
@@ -3028,110 +3028,8 @@
+i;%0A
-%09%0A%09/*var row = rows.nextRow;%0A%09while (row) %7B%0A%09%09Ti.API.info(row.documentID);%0A%09%09row = rows.nextRow;%0A%09%7D*/%0A
%7D, 1
@@ -3033,16 +3033,18 @@
, 1000);
+*/
%0A%0A/*setI
|
cc3f5941a490d19544ab5e5d5ff959f90119a4d5
|
Update secrets.js
|
config/secrets.js
|
config/secrets.js
|
/**
* IMPORTANT IMPORTANT IMPORTANT IMPORTANT IMPORTANT IMPORTANT IMPORTANT
*
* You should never commit this file to a public repository on GitHub!
* All public code on GitHub can be searched, that means anyone can see your
* uploaded secrets.js file.
*
* I did it for your convenience using "throw away" API keys and passwords so
* that all features could work out of the box.
*
* Use config vars (environment variables) below for production API keys
* and passwords. Each PaaS (e.g. Heroku, Nodejitsu, OpenShift, Azure) has a way
* for you to set it up from the dashboard.
*
* Another added benefit of this approach is that you can use two different
* sets of keys for local development and production mode without making any
* changes to the code.
* IMPORTANT IMPORTANT IMPORTANT IMPORTANT IMPORTANT IMPORTANT IMPORTANT
*/
module.exports = {
desktop: true,
PORT: 9000,
db: process.env.MONGODB || process.env.MONGOLAB_URI || 'mongodb://localhost:27017/test',
runtime: "mssql", //"sqlite" or "mssql",
onlineLocation: "http://localhost:9000", //only used for desktop version navigation
sessionSecret: process.env.SESSION_SECRET || 'Your Session Secret goes here',
mailgun: {
user: process.env.MAILGUN_USER || '[email protected]',
password: process.env.MAILGUN_PASSWORD || '29eldds1uri6'
},
sqlite: {
db : 'db/database'
},
msSQL : {
user: '',
password: '',
server: '', // You can use 'localhost\\instance' to connect to named instance
database: 'cleansheetnode',
stream: false, // You can enable streaming globally
options: {
encrypt: false // Use this if you're on Windows Azure
}
},
mandrill: {
user: process.env.MANDRILL_USER || 'hackathonstarterdemo',
password: process.env.MANDRILL_PASSWORD || 'E1K950_ydLR4mHw12a0ldA'
},
sendgrid: {
user: process.env.SENDGRID_USER || 'hslogin',
password: process.env.SENDGRID_PASSWORD || 'hspassword00'
},
facebook: {
clientID: process.env.FACEBOOK_ID || '754220301289665',
clientSecret: process.env.FACEBOOK_SECRET || '41860e58c256a3d7ad8267d3c1939a4a',
callbackURL: '/auth/facebook/callback',
passReqToCallback: true
},
api: {
port: '',
root: 'http://localhost'
}
};
|
JavaScript
| 0.000001 |
@@ -1577,21 +1577,23 @@
e: '
-cleansheetnod
+yourdatabasaher
e',%0A
@@ -2318,8 +2318,9 @@
'%0A %7D%0A%7D;
+%0A
|
883e5f52ea4a18c912234904ed2561e557f79e5a
|
Fix linting
|
src/patch/operators/string.js
|
src/patch/operators/string.js
|
// eslint-disable-next-line no-underscore-dangle
export const _replace = {
attribute: ['string'],
argument: ['string[]'],
check({ arg: opVal }) {
// eslint-disable-next-line no-magic-numbers
const isValid = opVal.length <= 3 && opVal.length >= 2
if (!isValid) {
return 'the argument must be an array with one regular expression, then a string, then an optional list of flags'
}
return validateRegExp({ opVal })
},
apply({ value: attrVal = '', arg: [regExp, str, flags] }) {
const regExpA = getRegExp({ regExp, flags })
return attrVal.replace(regExpA, str)
},
}
const validateRegExp = function({ opVal }) {
const [regExp, , flags] = opVal
try {
getRegExp({ regExp, flags })
return
} catch {}
try {
getRegExp({ regExp })
return "the regular expression's flags are invalid"
} catch {
return 'the regular expression is invalid'
}
}
const getRegExp = function({ regExp, flags = 'gi' }) {
return new RegExp(regExp, flags)
}
|
JavaScript
| 0.000004 |
@@ -151,57 +151,8 @@
) %7B%0A
- // eslint-disable-next-line no-magic-numbers%0A
|
bb7eae5c5382bb0d31972e46198a81ca47a0e638
|
Call sendMessage in iOS ClearableTextInput onBlur
|
native/components/clearable-text-input.react.ios.js
|
native/components/clearable-text-input.react.ios.js
|
// @flow
import type { ClearableTextInputProps } from './clearable-text-input';
import type { KeyPressEvent } from '../types/react-native';
import * as React from 'react';
import { TextInput, View, StyleSheet } from 'react-native';
import invariant from 'invariant';
type State = {|
textInputKey: number,
|};
class ClearableTextInput extends React.PureComponent<
ClearableTextInputProps,
State,
> {
state = {
textInputKey: 0,
};
pendingMessage: ?{| value: string, resolve: (value: string) => void |};
lastKeyPressed: ?string;
lastTextInputSent = -1;
currentTextInput: ?React.ElementRef<typeof TextInput>;
focused = false;
sendMessage() {
if (this.pendingMessageSent) {
return;
}
const { pendingMessage } = this;
invariant(pendingMessage, 'cannot send an empty message');
pendingMessage.resolve(pendingMessage.value);
const textInputSent = this.state.textInputKey - 1;
if (textInputSent > this.lastTextInputSent) {
this.lastTextInputSent = textInputSent;
}
}
get pendingMessageSent() {
return this.lastTextInputSent >= this.state.textInputKey - 1;
}
onOldInputChangeText = (text: string) => {
const { pendingMessage, lastKeyPressed } = this;
invariant(
pendingMessage,
'onOldInputChangeText should have a pendingMessage',
);
if (
!this.pendingMessageSent &&
lastKeyPressed &&
lastKeyPressed.length > 1
) {
// This represents an autocorrect event on blur
pendingMessage.value = text;
}
this.lastKeyPressed = null;
this.sendMessage();
this.updateTextFromOldInput(text);
};
updateTextFromOldInput(text: string) {
const { pendingMessage } = this;
invariant(
pendingMessage,
'updateTextFromOldInput should have a pendingMessage',
);
const pendingValue = pendingMessage.value;
if (!pendingValue || !text.startsWith(pendingValue)) {
return;
}
const newValue = text.substring(pendingValue.length);
if (this.props.value === newValue) {
return;
}
this.props.onChangeText(newValue);
}
onOldInputKeyPress = (event: KeyPressEvent) => {
const { key } = event.nativeEvent;
if (this.lastKeyPressed && this.lastKeyPressed.length > key.length) {
return;
}
this.lastKeyPressed = key;
this.props.onKeyPress && this.props.onKeyPress(event);
};
onOldInputBlur = () => {
this.sendMessage();
};
onOldInputFocus = () => {
// It's possible for the user to press the old input after the new one
// appears. We can prevent that with pointerEvents="none", but that causes a
// blur event when we set it, which makes the keyboard briefly pop down
// before popping back up again when textInputRef is called below. Instead
// we try to catch the focus event here and refocus the currentTextInput
if (this.currentTextInput) {
this.currentTextInput.focus();
}
};
textInputRef = (textInput: ?React.ElementRef<typeof TextInput>) => {
if (this.focused && textInput) {
textInput.focus();
}
this.currentTextInput = textInput;
this.props.textInputRef(textInput);
};
async getValueAndReset(): Promise<string> {
const { value } = this.props;
this.props.onChangeText('');
if (!this.focused) {
return value;
}
return await new Promise(resolve => {
this.pendingMessage = { value, resolve };
this.setState(prevState => ({
textInputKey: prevState.textInputKey + 1,
}));
});
}
onFocus = () => {
this.focused = true;
};
onBlur = () => {
this.focused = false;
};
render() {
const { textInputRef, ...props } = this.props;
const textInputs = [];
if (this.state.textInputKey > 0) {
textInputs.push(
<TextInput
{...props}
style={[props.style, styles.invisibleTextInput]}
onChangeText={this.onOldInputChangeText}
onKeyPress={this.onOldInputKeyPress}
onBlur={this.onOldInputBlur}
onFocus={this.onOldInputFocus}
key={this.state.textInputKey - 1}
/>,
);
}
textInputs.push(
<TextInput
{...props}
onFocus={this.onFocus}
onBlur={this.onBlur}
onChangeText={this.props.onChangeText}
key={this.state.textInputKey}
ref={this.textInputRef}
/>,
);
return <View style={styles.textInputContainer}>{textInputs}</View>;
}
}
const styles = StyleSheet.create({
invisibleTextInput: {
opacity: 0,
position: 'absolute',
},
textInputContainer: {
flex: 1,
},
});
export default ClearableTextInput;
|
JavaScript
| 0 |
@@ -3627,16 +3627,453 @@
false;%0A
+ if (this.pendingMessage) %7B%0A // This is to catch a race condition where somebody hits the send button%0A // and then blurs the TextInput before the textInputKey increment can%0A // rerender this component. With this.focused set to false, the new%0A // TextInput won't focus, and the old TextInput won't blur, which means%0A // nothing will call sendMessage unless we do it right here.%0A this.sendMessage();%0A %7D%0A
%7D;%0A%0A
|
b50a648e8b205dadb34ceb5dd42c1dd9841ffd13
|
delete some console.log Please enter the commit message for your changes. Lines starting
|
packages/telescope-custom-post-form/lib/stripe-post-form.js
|
packages/telescope-custom-post-form/lib/stripe-post-form.js
|
// secret key: sk_test_G77gaaVCcCaEFTccvZx04IFC --> keep in server side
// publishable key: pk_test_GpmbjLyT5iOAfAPK7zT7DkF1 --> keep in client side
// href="https://connect.stripe.com/oauth/authorize?response_type=code&client_id=ca_7NQ3TnZveKPdFms4tlzUx5wswjPDubGN&scope=read_write
if(Meteor.isServer){
Meteor.methods({
fetchFromService: function(authentication_key) {
console.log("===========================================");
console.log("authentication_key : ", authentication_key);
var url = "https://connect.stripe.com/oauth/token";
Meteor.http.post(url, {content:
"client_secret=sk_test_G77gaaVCcCaEFTccvZx04IFC&"+
"code="+authentication_key+"&"+
"grant_type=authorization_code" },
function(error, result) {
var access_token = result.data.access_token;
var stripe_publishable_key = result.data.stripe_publishable_key;
var stripe_user_id = result.data.stripe_user_id;
console.log("access_token :",access_token);
console.log("stripe_publishable_key :",stripe_publishable_key);
console.log("stripe_user_id :",stripe_user_id);
var current_user = Meteor.user();
Users.update(current_user._id,{$set: {Access_token: access_token}});
Users.update(current_user._id,{$set: {Public_key: stripe_publishable_key}});
Users.update(current_user._id,{$set: {Stripe_user_id: stripe_user_id }});
if(result.statusCode==200) {
console.log("response received.");
}else if(result.statusCode===null){
console.log("There response is null")
}
else {
console.log("Response issue: ", result.statusCode);
}
});
}
});
}
if (Meteor.isClient) {
Template.post_submit.events({
'click #special-stripe-button': function(e) {
e.preventDefault();
StripeCheckout.open({
key: 'pk_test_GpmbjLyT5iOAfAPK7zT7DkF1',
amount: 1000, // this is equivalent to $10
name: 'Project Name',
description: 'On how to use Stripe ($10.00)',
panelLabel: 'Pay Now',
token: function(res) {
stripeToken = res.id;
console.info(res);
Meteor.call('chargeCard', stripeToken);
}
});
}
});
}
if (Meteor.isServer) {
Meteor.methods({
'chargeCard': function(stripeToken) {
check(stripeToken, String);
var Stripe = StripeAPI('sk_test_G77gaaVCcCaEFTccvZx04IFC');
Stripe.charges.create({
source: stripeToken,
amount: 1000, // this is equivalent to $10
currency: 'usd'
}, function(err, charge) {
console.log(charge);
if (charge.status === "succeeded"){
console.log("Sucessssssss");
// here I need to show my button of post my product
}
else {
console.log("not accepatble payment");
}
});
}
});
}
|
JavaScript
| 0.000003 |
@@ -149,19 +149,16 @@
ent side
-%0A%0A%0A
%0A// hr
@@ -1527,34 +1527,32 @@
) %7B%0A
-
console.log(%22res
@@ -1688,34 +1688,32 @@
else %7B%0A
-
cons
|
326416a891fd52f2c3911d47e36fd471bef47d58
|
Remove redundant sign in toggle
|
public/js/popit.js
|
public/js/popit.js
|
$(document).ready(function() {
/*
Enlarge and shrink the search box on focus
*/
$('#person-search').focus(function(event) {
$('.person-header-nav').addClass('focus-search');
}).blur(function(event) {
$('.person-header-nav').removeClass('focus-search');
});
/*
Design State Demos
- the different sized headers, toggle by clicking on logo
- Sign-in box toggle states, logged in / logged out
*/
$('.logo').click(function(e) { $('body').toggleClass('brand_page'); });
$('#user_menu a').click(function(e) { $('body').toggleClass('signed_in'); });
});
|
JavaScript
| 0.000001 |
@@ -267,17 +267,16 @@
%0A%09%7D);%0A%09%0A
-%09
%0A%09/*%0A%09%09D
@@ -358,62 +358,8 @@
ogo%0A
-%09%09- Sign-in box toggle states, logged in / logged out%0A
%09*/
@@ -436,87 +436,8 @@
%7D);%0A
-%09$('#user_menu a').click(function(e) %7B $('body').toggleClass('signed_in'); %7D);%0A
%09%0A%7D)
|
700b200b1affa68babb4955df52e2fab378dad37
|
Implement detectLocation through ajax promise.
|
library/CM/FormField/Location.js
|
library/CM/FormField/Location.js
|
/**
* @class CM_FormField_Location
* @extends CM_FormField_SuggestOne
*/
var CM_FormField_Location = CM_FormField_SuggestOne.extend({
_class: 'CM_FormField_Location',
events: {
'click .detectLocation': 'detectLocation'
},
ready: function() {
CM_FormField_SuggestOne.prototype.ready.call(this);
this.on('change', function() {
this.updateDistanceField();
}, this);
this.updateDistanceField();
},
/**
* @returns {CM_FormField_Integer|Null}
*/
getDistanceField: function() {
if (!this.getOption("distanceName")) {
return null;
}
return this.getForm().getField(this.getOption("distanceName"));
},
updateDistanceField: function() {
if (this.getDistanceField()) {
var distanceEnabled = false;
var items = this.getValue();
if (items.length > 0) {
distanceEnabled = items[0].id.split(".")[0] >= this.getOption("distanceLevelMin");
}
this.getDistanceField().$("input").prop("disabled", !distanceEnabled);
}
},
detectLocation: function() {
if (!'geolocation' in navigator) {
cm.error.triggerThrow('Geolocation support unavailable');
}
this.$('.detect-location').addClass('waiting');
var self = this;
var deferred = $.Deferred();
navigator.geolocation.getCurrentPosition(deferred.resolve, deferred.reject);
deferred.then(function(position) {
self._lookupCoordinates(position.coords.latitude, position.coords.longitude);
}, function(error) {
cm.error.trigger('Unable to detect location: ' + error.message);
});
deferred.always(function() {
self.$('.detect-location').removeClass('waiting');
});
return deferred;
},
/**
* @param {Number} lat
* @param {Number} lon
*/
_lookupCoordinates: function(lat, lon) {
this.ajax('getSuggestionByCoordinates', {lat: lat, lon: lon, levelMin: this.getOption('levelMin'), levelMax: this.getOption('levelMax')})
.then(function(data) {
if (data) {
this.setValue(data);
}
});
}
});
|
JavaScript
| 0 |
@@ -1236,41 +1236,62 @@
is;%0A
+%0A
-var deferred = $.Deferred();%0A
+return new Promise(function(resolve, reject) %7B%0A
@@ -1335,35 +1335,17 @@
ion(
-deferred.resolve, deferred.
+resolve,
reje
@@ -1349,29 +1349,22 @@
eject);%0A
-%0A
-deferred
+%7D)
.then(fu
@@ -1384,24 +1384,33 @@
on) %7B%0A
+ return
self._lookup
@@ -1479,19 +1479,126 @@
e);%0A
-%7D,
+ %7D).then(function(data) %7B%0A if (data) %7B%0A self.setValue(data);%0A %7D%0A %7D)%0A .catch(
function
@@ -1603,24 +1603,26 @@
on(error) %7B%0A
+
cm.err
@@ -1688,31 +1688,20 @@
-%7D);%0A deferred.always
+ %7D).finally
(fun
@@ -1706,24 +1706,26 @@
unction() %7B%0A
+
self.$
@@ -1777,33 +1777,13 @@
+
%7D);
-%0A%0A return deferred;
%0A %7D
@@ -1890,24 +1890,31 @@
lon) %7B%0A
+return
this.ajax('g
@@ -2042,107 +2042,8 @@
')%7D)
-%0A .then(function(data) %7B%0A if (data) %7B%0A this.setValue(data);%0A %7D%0A %7D)
;%0A
|
7407ac1a4560940fd8bf2f5b924e647d2c406b89
|
Fix traffic info formatting.
|
traffic.js
|
traffic.js
|
var rest = require('restler');
var jf = require('jsonfile');
var util = require('./util');
var ltaCredFile = './private/lta_credentials.json';
var ltaCredentials = jf.readFileSync(ltaCredFile);
var busStops = [19059, 19051, 17099, 17091];
var defaultBusStop = 19059;
var busStopUrl =
'http://datamall2.mytransport.sg/ltaodataservice/BusArrival?BusStopID=';
var busStopHeaders = {
'AccountKey': ltaCredentials.AccountKey,
'UniqueUserID': ltaCredentials.UniqueUserID
};
function busStop(id, callback) {
if (callback === undefined) {
callback = console.log;
}
var reqUrl = busStopUrl + id.toString();
var reqOptions = {
'headers': busStopHeaders
};
var response = send(reqUrl, reqOptions, callback);
return response;
}
function send(reqUrl, reqOptions, callback) {
return rest.get(reqUrl, reqOptions).on('complete', function(data) {
processInfo(data, callback);
});
}
function processInfo(data, callback) {
var busTimingsList;
var header;
data.Services.forEach(function(bus) {
if (bus.Status === 'In Operation') {
var nextBusTime = new Date(bus.NextBus.EstimatedArrival);
var subseqBusTime = new Date(bus.SubsequentBus.EstimatedArrival);
busTimingsList = bus.ServiceNo + ' - ' +
util.timeLeftMin(nextBusTime) + ', ' +
util.timeLeftMin(subseqBusTime);
}
});
header = (busTimingsList) ? "Buses in operation: \n" : "Go walk home 😜.\n"
busTimingsList = (busTimingsList) ? busTimingsList : "";
callback(header + busTimingsList);
}
module.exports = {
'busStopQuery': busStop,
'defaultBusStop': defaultBusStop
};
|
JavaScript
| 0.000002 |
@@ -998,16 +998,21 @@
ingsList
+ = %22%22
;%0A va
@@ -1283,16 +1283,17 @@
ngsList
++
= bus.Se
@@ -1412,16 +1412,23 @@
BusTime)
+ + '%5Cn'
;%0A
@@ -1471,58 +1471,61 @@
List
-) ? %22Buses in operation: %5Cn%22 : %22Go walk home %F0%9F%98%9C.%5Cn%22
+ === %22%22) ? %22Go walk home %F0%9F%98%9C.%22 : %22Buses in operation:%22;
%0A
@@ -1603,16 +1603,23 @@
header +
+ '%5Cn' +
busTimi
|
38f35b567691b7db3474e595653799d08616735c
|
mark simpleavatar.js as dependency for the main avatar application js.
|
bin/scenes/Avatar/avatarapplication.js
|
bin/scenes/Avatar/avatarapplication.js
|
// Avatar application. Will handle switching logic between avatar & freelook camera (clientside), and
// spawning avatars for clients (serverside). Note: this is not a startup script, but is meant to be
// placed in an entity in a scene that wishes to implement avatar functionality.
var avatar_area_size = 10;
var avatar_area_x = 0;
var avatar_area_y = 0;
var avatar_area_z = 20;
var isserver = server.IsRunning();
if (isserver == false) {
var inputmapper = me.GetOrCreateComponentRaw("EC_InputMapper");
inputmapper.SetTemporary(true);
inputmapper.contextPriority = 102;
inputmapper.RegisterMapping("Ctrl+Tab", "ToggleCamera", 1);
me.Action("ToggleCamera").Triggered.connect(ClientHandleToggleCamera);
} else {
server.UserAboutToConnect.connect(ServerHandleUserAboutToConnect);
server.UserConnected.connect(ServerHandleUserConnected);
server.UserDisconnected.connect(ServerHandleUserDisconnected);
}
function ClientHandleToggleCamera() {
// For camera switching to work, must have both the freelookcamera & avatarcamera in the scene
var freelookcameraentity = scene.GetEntityByNameRaw("FreeLookCamera");
var avatarcameraentity = scene.GetEntityByNameRaw("AvatarCamera");
var freecameralistener = freelookcameraentity.GetComponentRaw("EC_SoundListener");
var avatarent = scene.GetEntityByNameRaw("Avatar" + client.GetConnectionID());
var avatarlistener = avatarent.GetComponentRaw("EC_SoundListener");
if ((freelookcameraentity == null) || (avatarcameraentity == null))
return;
var freelookcamera = freelookcameraentity.ogrecamera;
var avatarcamera = avatarcameraentity.ogrecamera;
if (avatarcamera.IsActive()) {
freelookcameraentity.placeable.transform = avatarcameraentity.placeable.transform;
freelookcamera.SetActive();
freecameralistener.active = true;
avatarlistener.active = false;
} else {
avatarcamera.SetActive();
avatarlistener.active = true;
freecameralistener.active = false;
}
// Ask entity to check his camera state
avatarent.Exec(1, "CheckState");
}
function ServerHandleUserAboutToConnect(connectionID, user) {
// Uncomment to test access control
//if (user.GetProperty("password") != "xxx")
// user.DenyConnection();
}
function ServerHandleUserConnected(connectionID, user) {
var avatarEntityName = "Avatar" + connectionID;
var avatarEntity = scene.CreateEntityRaw(scene.NextFreeId(), ["EC_Script", "EC_Placeable", "EC_AnimationController"]);
avatarEntity.SetTemporary(true); // We never want to save the avatar entities to disk.
avatarEntity.SetName(avatarEntityName);
if (user != null) {
avatarEntity.SetDescription(user.GetProperty("username"));
}
var script = avatarEntity.script;
script.type = "js";
script.runOnLoad = true;
var r = script.scriptRef;
r.ref = "local://simpleavatar.js";
script.scriptRef = r;
// Set random starting position for avatar
var placeable = avatarEntity.placeable;
var transform = placeable.transform;
transform.pos.x = (Math.random() - 0.5) * avatar_area_size + avatar_area_x;
transform.pos.y = (Math.random() - 0.5) * avatar_area_size + avatar_area_y;
transform.pos.z = avatar_area_z;
placeable.transform = transform;
scene.EmitEntityCreatedRaw(avatarEntity);
if (user != null) {
print("[Avatar Application] Created avatar for " + user.GetProperty("username"));
}
}
function ServerHandleUserDisconnected(connectionID, user) {
var avatarEntityName = "Avatar" + connectionID;
var avatartEntity = scene.GetEntityByNameRaw(avatarEntityName);
if (avatartEntity != null) {
var entityID = avatartEntity.Id;
scene.RemoveEntityRaw(entityID);
if (user != null) {
print("[Avatar Application] User " + user.GetProperty("username") + " disconnected, destroyed avatar entity.");
}
}
}
|
JavaScript
| 0 |
@@ -1,12 +1,46 @@
+// !ref: local://simpleavatar.js%0A%0A
// Avatar ap
|
01ca1e56562692510e3ed76ecd6b9693417adfd1
|
Add itemizing class only on addItem
|
itemObjectModel.js
|
itemObjectModel.js
|
define(function() {
'use strict';
var _BYTESOURCE = Symbol('byteSource');
var itemObjectModel = {
createItem: function(title) {
var itemElement = document.createElement('SECTION');
itemElement.classList.add('item');
itemElement.appendChild(itemElement.titleElement = document.createElement('HEADER'));
itemElement.titleTextElement = itemElement.titleElement;
Object.defineProperties(itemElement, this.itemProperties);
if (title) itemElement.itemTitle = title;
itemElement.addEventListener('click', clickItem);
return itemElement;
},
itemProperties: {
itemTitle: {
get: function() {
return this.titleTextElement.innerText;
},
set: function(text) {
this.titleTextElement.innerText = text;
},
enumerable: true,
},
byteSource: {
get: function() {
return this[_BYTESOURCE];
},
set: function(byteSource) {
this[_BYTESOURCE] = byteSource;
if (!byteSource) {
this.titleElement.innerText = this.titleTextElement.innerText;
this.titleTextElement = this.titleElement;
}
else {
var link = document.createElement('A');
link.href = '#';
link.classList.add('item-download');
link.download = this.itemTitle.replace(/[\\\/:"<>\*\?\|]/g, '_');
link.innerText = this.titleTextElement.innerText;
this.titleElement.innerHTML = '';
this.titleElement.appendChild(this.titleTextElement = link);
}
},
},
startAddingItems: {
value: function() {
this.classList.add('itemizing');
if (!this.classList.contains('has-subitems')) {
this.classList.add('has-subitems');
this.appendChild(this.subitemsElement = document.createElement('SECTION'));
this.subitemsElement.classList.add('subitems');
}
},
},
addItem: {
value: function(item) {
this.startAddingItems();
this.subitemsElement.appendChild(item);
},
},
confirmAllItemsAdded: {
value: function() {
this.classList.remove('itemizing');
this.classList.add('itemized');
},
},
},
};
function clickItem(e) {
e.stopPropagation();
if (e.target.classList.contains('item-download')) {
if (e.target.href === '#') {
e.preventDefault();
this.byteSource.getURL().then(function(url) {
e.target.href = url;
e.target.click();
});
}
return;
}
if (this.classList.contains('has-subitems')) {
if (this.classList.toggle('open')) {
this.dispatchEvent(new Event(itemObjectModel.EVT_POPULATE));
}
}
}
Object.defineProperties(itemObjectModel, {
EVT_POPULATE: {value:'item-populate'},
});
return itemObjectModel;
});
|
JavaScript
| 0 |
@@ -1723,51 +1723,8 @@
) %7B%0A
- this.classList.add('itemizing');%0A
@@ -2085,24 +2085,67 @@
ingItems();%0A
+ this.classList.add('itemizing');%0A
th
|
750731b2adc3bdb8bf256764510ea3330c4222f3
|
Modify basic-demo
|
demos/basic/main.js
|
demos/basic/main.js
|
var mainWorkspace, nested1, nested11, nested12, nested121, nested2, nested21, nested22, nested221, block1, block2, block3, block4;
var main = function() {
mainWorkspace = new BB.Workspace('main', 'mainWorkspaceDiv');
nested1 = mainWorkspace.addWorkspace('nested1', {width : 300, height: 300, x: 10, y: 10});
nested2 = mainWorkspace.addWorkspace('nested2', {width : 300, height: 300});
nested21 = nested2.addWorkspace('nested21', {width : 100, height: 100, x: 10, y: 10});
//BB.Workspace.prototype.colorPalette = BB.colorPalettes.workspace.dark;
//BB.Block.prototype.colorPalette = BB.colorPalettes.block.dark;
// alternate color palette for workspace backgrounds
BB.Workspace.prototype.stylingFunction = function() {
this.bgColor = this.colorPalette.background[(this.level % 2 == 1) ? 'nested' : 'main'];
};
mainWorkspace.render();
block1 = mainWorkspace.addBlock('block1', test_blocks.test_dev);
block1.render();
block1.move(100, 100);
block2 = mainWorkspace.addBlock('block2', example_blocks.example);
block2.render();
block2.move(50, 170);
block3 = nested2.addBlock('block3', test_blocks.test);
block3.render();
block3.move(100, 100);
nested2.move(350,50);
block4 = nested2.addBlock('block4', example_blocks.example);
block4.render();
block4.move(50, 170);
//field button fires animation
block2.fields[5].ondown = block1.methods.animation;
block1.methods.animationStart = function () {
block2.fields[5].ondown = null;
}
block1.methods.animationEnd = function () {
block2.fields[5].ondown = block1.methods.animation;
}
};
|
JavaScript
| 0.000004 |
@@ -286,17 +286,18 @@
ht:
-3
+4
00, x:
-1
+35
0, y
@@ -375,17 +375,17 @@
height:
-3
+4
00%7D);%0A%09n
@@ -436,18 +436,18 @@
width :
+2
1
-0
0, heigh
@@ -450,17 +450,17 @@
eight: 1
-0
+4
0, x: 10
@@ -814,16 +814,38 @@
'%5D;%0A%09%7D;%0A
+ // Main Workspace%0A
%09mainWor
@@ -1088,241 +1088,8 @@
0);%0A
- block3 = nested2.addBlock('block3', test_blocks.test);%0A%09block3.render();%0A%09block3.move(100, 100);%0A nested2.move(350,50);%0A block4 = nested2.addBlock('block4', example_blocks.example);%0A%09block4.render();%0A%09block4.move(50, 170);%0A
@@ -1375,16 +1375,610 @@
mation;%0A
-
%7D%0A
+ // Nested workspace 1%0A block3 = nested1.addBlock('block3', test_blocks.test);%0A%09block3.render();%0A block3.rotate(0);%0A%09block3.move(20, 30);%0A nested2.move(350,400);%0A block4 = nested1.addBlock('block4', example_blocks.example);%0A%09block4.render();%0A%09block4.move(20, 100);%0A // Nested workspace 2%0A nested2.move(660,10);%0A block6 = nested2.addBlock('block5', example_blocks.example);%0A%09block6.render();%0A%09block6.move(50, 165);%0A // Nested workspace 2 - 1%0A nested21.move(10,10);%0A block5 = nested21.addBlock('block6', test_blocks.test);%0A%09block5.render();%0A%09block5.move(50, 10);%0A
%7D;
|
94c90f640e4c0d0554b9c18acf5e74c79246cb81
|
add dark mode bottom border to sidebar
|
pkg/interface/link/src/js/components/lib/channel-sidebar.js
|
pkg/interface/link/src/js/components/lib/channel-sidebar.js
|
import React, { Component } from 'react';
import { Route, Link } from 'react-router-dom';
import { ChannelsItem } from '/components/lib/channels-item';
export class ChannelsSidebar extends Component {
// drawer to the left
render() {
const { props, state } = this;
let privateChannel =
Object.keys(props.groups)
.filter((path) => {
return (path === "/~/default")
})
.map((path) => {
let name = "Private"
let selected = (props.selected === path);
let linkCount = !!props.links[path] ? props.links[path].totalItems : 0;
const unseenCount = !!props.links[path]
? props.links[path].unseenCount
: linkCount
return (
<ChannelsItem
key={path}
link={path}
memberList={props.groups[path]}
selected={selected}
linkCount={linkCount}
unseenCount={unseenCount}
name={name}/>
)
})
let channelItems =
Object.keys(props.groups)
.filter((path) => {
return (!path.startsWith("/~/"))
})
.map((path) => {
let name = path.substr(1);
let nameSeparator = name.indexOf("/");
name = name.substr(nameSeparator + 1);
let selected = (props.selected === path);
let linkCount = !!props.links[path] ? props.links[path].totalItems : 0;
const unseenCount = !!props.links[path]
? props.links[path].unseenCount
: linkCount
return (
<ChannelsItem
key={path}
link={path}
memberList={props.groups[path]}
selected={selected}
linkCount={linkCount}
unseenCount={unseenCount}
name={name}/>
)
});
let activeClasses = (this.props.active === "channels") ? " " : "dn-s ";
let hiddenClasses = true;
// probably a more concise way to write this
if (this.props.popout) {
hiddenClasses = false;
} else {
hiddenClasses = this.props.sidebarShown;
}
return (
<div className={`bn br-m br-l br-xl b--gray4 b--gray2-d lh-copy h-100
flex-shrink-0 mw5-m mw5-l mw5-xl pt3 pt0-m pt0-l pt0-xl
relative ` + activeClasses + ((hiddenClasses)
? "flex-basis-100-s flex-basis-30-ns"
: "dn")}>
<a className="db dn-m dn-l dn-xl f8 pb3 pl3" href="/">⟵ Landscape</a>
<div className="overflow-y-scroll h-100">
<h2 className={`f8 f9-m f9-l f9-xl
pt1 pt4-m pt4-l pt4-xl
pr4 pb3 pb3-m pb3-l pb3-xl
pl3 pl4-m pl4-l pl4-xl
black-s gray2 white-d c-default
bb b--gray4 mb2 mb0-m mb0-l mb0-xl`}>
Your Collections
</h2>
{privateChannel}
{channelItems}
</div>
</div>
);
}
}
|
JavaScript
| 0 |
@@ -2491,17 +2491,17 @@
ssName=%7B
-%60
+%22
f8 f9-m
@@ -2510,16 +2510,20 @@
-l f9-xl
+ %22 +
%0A
@@ -2526,16 +2526,17 @@
+%22
pt1 pt4-
@@ -2545,24 +2545,28 @@
pt4-l pt4-xl
+ %22 +
%0A
@@ -2565,16 +2565,17 @@
+%22
pr4 pb3
@@ -2592,16 +2592,20 @@
l pb3-xl
+ %22 +
%0A
@@ -2608,16 +2608,17 @@
+%22
pl3 pl4-
@@ -2631,16 +2631,20 @@
l pl4-xl
+ %22 +
%0A
@@ -2647,16 +2647,17 @@
+%22
black-s
@@ -2679,16 +2679,20 @@
-default
+ %22 +
%0A
@@ -2695,16 +2695,17 @@
+%22
bb b--gr
@@ -2708,16 +2708,27 @@
--gray4
+b--gray2-d
mb2 mb0-
@@ -2741,17 +2741,17 @@
l mb0-xl
-%60
+%22
%7D%3E%0A
|
2ee89538eeb5193a5fba07e9c07468824782b59f
|
Add babel-register
|
truffle.js
|
truffle.js
|
var DefaultBuilder = require("truffle-default-builder");
module.exports = {
networks: {
development: {
host: "localhost",
port: 8545,
network_id: "*" // Match any network id
},
testnet: {
host: "localhost",
port: 8545,
network_id: 3
}
}
};
|
JavaScript
| 0 |
@@ -1,58 +1,81 @@
-var DefaultBuilder = require(%22truffle-default-builder%22
+// Allows us to use ES6 in our migrations and tests.%0Arequire('babel-register'
);%0A%0A
|
2e2b5398a87624bcd3a3636ed981163262d42921
|
modify poitem model
|
src/po/purchase-order-item.js
|
src/po/purchase-order-item.js
|
'use strict'
var BaseModel = require('capital-models').BaseModel;
var Product = require('../core/product');
module.exports = class PurchaseOrderItem extends BaseModel {
constructor(source) {
super(type || 'purchase-order-item', '1.0.0');
this.qty = 0;
this.price = 0;
this.product = new Product();
this.copy(source);
}
}
|
JavaScript
| 0 |
@@ -185,16 +185,22 @@
r(source
+, type
) %7B%0A
@@ -250,24 +250,16 @@
.0.0');%0A
-
%0A
|
b776f561c5d83a2c5fc4d26cf49569a571b950b3
|
Fix minification
|
mediaexperience.js
|
mediaexperience.js
|
/*!
* mediaexperienceJS v0.2.0
*
* Copyright 2014 Martin Adamko
* Released under the MIT license
*
*/
;(function( $, window, document ){
/**
* @constructor
*/
var MediaExperience = function( elem, options ){
this.elem = elem;
this.$elem = $(elem);
this.options = options;
// Distinc
this.$elem.addClass('responds-to-media-experience');
// Customization of the plugin on a per-element basis.
// <div data-mediaexperience-options='{prefix: "device"}'></div>
this.metadata = this.$elem.data( 'mediaexperience-options' );
},
// Array of all media experience instances
allMediaExperienceElements = [],
// timeout for onresize events
windowResizeTimeout;
// the plugin prototype
MediaExperience.prototype = {
timeout: 200,
defaults: {
horizontalModule: 80,
verticalModule: 80,
prefix: "media-experience",
useBreakpoints: true,
calculateVertical: false,
useSince: 'since',
// Columns to be true
breakpoints: {
'phone': 0, // mobile first
'phone--small': 4, // 80 x 0...4 = 0 <= ? < 320
'phone--medium': 6, // 80 x 5...6 = 320 <= ? < 480
'phone--large': 9, // 80 x 7...9 = 480 <= ? < 720
'tablet': 9, // 80 x 9 = 720
'tablet--small': 10, // 80 x 9...10 = 720 <= ? < 800
'tablet--medium': 11, // 80 x 9...10 = 720 <= ? < 800
'tablet--large': 13, // 80 x 11...12 = 800 <= ? < 960
'desktop': 13, // 80 x 13 = 960
'desktop--small': 14, // 80 x 13...14 = 960 <= ? < 1120
'desktop--medium': 18, // 80 x 15...18 = 1120 <= ? < 1440
'desktop--large': 24, // 80 x 17...24 = 1440 <= ? < 1920
'oversized-desktop': 24 // 80 x 24 = 1920
}
},
init: function() {
// Introduce defaults that can be extended either
// globally or using an object literal.
this.config = $.extend({}, this.defaults, this.options, this.metadata);
this.regex = new RegExp('\\b'+ this.config.prefix + '-\\S+', 'g');
this.resize();
return this;
},
resize: function() {
var self = this;
if ($(self.$elem).hasClass('media-experience-disabled')) {
return;
}
var classes = [];
var widths = parseInt($(self.$elem).width() / self.config.horizontalModule, 10);
classes.push(self.config.prefix+'-width-'+widths);
if (!! self.config.calculateVertical) {
var heights = parseInt($(self.$elem).height() / self.config.verticalModule, 10);
classes.push(self.config.prefix+'-height-'+heights);
}
if (self.config.useBreakpoints) {
var lastBreakpoint = 0;
var lastMajorBreakpoint = 0;
for (var attrname in self.config.breakpoints) {
// console.log('lastMajorBreakpoint', lastMajorBreakpoint, 'lastBreakpoint', lastBreakpoint, 'widths', widths, attrname, self.config.breakpoints[attrname])
if (attrname.match(/--/)) {
// Variations of the major breakpoint
if (lastBreakpoint <= widths && widths < self.config.breakpoints[attrname]) {
classes.unshift(self.config.prefix+'-'+attrname);
}
} else if (self.config.breakpoints[attrname] <= widths) {
// Major breakpoints
if (self.config.useSince && typeof self.config.useSince === 'string') {
// All major breakpoints: mobile first approach
classes.push(self.config.prefix+'-'+self.config.useSince+'-'+attrname);
}
if (self.config.breakpoints[attrname] <= widths) {
// Only current major breakpoint (remember it)
lastMajorBreakpoint = attrname;
}
}
lastBreakpoint = self.config.breakpoints[attrname];
}
}
// Add current major breakpoint
classes.unshift(self.config.prefix+'-'+lastMajorBreakpoint);
// Build the classes
classes = classes.join(' ');
// Remove old prefix-matching classes and add new
self.$elem.removeClass(function (index, css) {
return (css.match(self.regex) || []).join(' ');
}).addClass(classes);
// console.log(widths, heights, self.config.horizontalModule, self.config.verticalModule);
// console.log('resize();');
}
}
MediaExperience.defaults = MediaExperience.prototype.defaults;
// Fire only after all window.on('resize') events finished.
$(window).on('resize', function runOnWindowResize(){
// Remove previous timer if still within previous timeout
clearTimeout(windowResizeTimeout);
// Set new timeout to call function
windowResizeTimeout = setTimeout(triggerResize, MediaExperience.prototype.timeout);
});
// Function to call after timeout on window resize
function triggerResize() {
var i, // iterator
j, // iterator
l, // length
n, // length
// groups of active instances by number of parents
mediaExperienceParents = {
'indexes': [],
'indexItems': []
},
// stores count of parents (num of instances depending on)
parentsCount;
l = allMediaExperienceElements.length;
for (i = 0; i < l; i++) {
parentsCount = allMediaExperienceElements[i].$elem.parents('.responds-to-media-experience').length;
if (typeof mediaExperienceParents.indexItems[parentsCount]==='undefined') {
mediaExperienceParents.indexItems[parentsCount] = [];
mediaExperienceParents.indexes.push(parentsCount);
}
mediaExperienceParents.indexItems[parentsCount].push(i);
}
// Sort number of parents
mediaExperienceParents.indexes.sort();
// console.log(mediaExperienceParents);
l = mediaExperienceParents.indexes.length;
for (i = 0; i < l; i++) {
parentsCount = mediaExperienceParents.indexes[i];
// console.log('parentsCount:' + parentsCount);
n = mediaExperienceParents.indexItems[parentsCount].length;
for (j = 0; j < n; j++) {
// console.log('iteration: ' + j);
allMediaExperienceElements[j].resize();
}
}
}
$.fn.mediaExperience = function newMediaExperience(options) {
var newElement = this.each(function() {
var v = new MediaExperience(this, options).init();
allMediaExperienceElements.push(v);
});
return this;
};
// Allows overwriting of any sitewide plugin aspect like timeout
window.MediaExperience = MediaExperience;
})( jQuery, window , document );
|
JavaScript
| 0.000019 |
@@ -5085,24 +5085,25 @@
%7D%0A %7D
+;
%0A%0A MediaE
|
20c4f082f52ecda48a974c3652fd0193431b6f01
|
remove unnecessary providers
|
src/test-utils/index.js
|
src/test-utils/index.js
|
/* eslint-disable import/no-extraneous-dependencies */
import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import { node } from 'prop-types';
import { TypographyProvider } from '../components/Typography';
import { BoxProvider } from '../components/Box';
const propTypes = {
children: node.isRequired,
};
const Wrapper = ({ children }) => (
<BoxProvider>
<TypographyProvider>
<>{children}</>
</TypographyProvider>
</BoxProvider>
);
Wrapper.propTypes = propTypes;
const customRender = (ui, options) =>
render(ui, { wrapper: Wrapper, ...options });
export { customRender as render, fireEvent };
|
JavaScript
| 0.000001 |
@@ -236,57 +236,8 @@
hy';
-%0Aimport %7B BoxProvider %7D from '../components/Box';
%0A%0Aco
@@ -327,26 +327,8 @@
%3E (%0A
- %3CBoxProvider%3E%0A
%3CT
@@ -346,18 +346,16 @@
ovider%3E%0A
-
%3C%3E%7Bc
@@ -366,18 +366,16 @@
ren%7D%3C/%3E%0A
-
%3C/Typo
@@ -394,25 +394,8 @@
er%3E%0A
- %3C/BoxProvider%3E%0A
);%0A%0A
|
74f6dec5d20fa74c9562d8daabd2a7f66337e482
|
Update jasmine tests runner.
|
tests/js/runner.js
|
tests/js/runner.js
|
require.config({
baseUrl: '../../www/',
paths: {
underscore: 'lib/underscore/underscore',
jquery: 'lib/jquery/jquery',
bootstrap: 'lib/bootstrap/dist/js/bootstrap',
contextmenu:'lib/bootstrap-contextmenu/bootstrap-contextmenu',
moment: 'lib/moment/moment',
angular: 'lib/angular/angular',
ngCookies: 'lib/angular-cookies/angular-cookies',
ngAnimate: 'lib/angular-animate/angular-animate',
ngMoment: 'lib/angular-moment/angular-moment',
bionode: 'lib/bionode/lib/bionode'
},
shim: {
underscore: {
exports: '_'
},
jquery: {
exports: '$'
},
bootstrap: {
deps: ['jquery']
},
contextmenu: {
deps: ['bootstrap']
},
moment: {
exports: 'moment'
},
angular: {
exports: 'angular',
deps: ['jquery']
},
ngCookies: {
deps: ['angular']
},
ngAnimate: {
deps: ['angular']
},
ngMoment: {
deps: ['angular', 'moment']
}
},
packages:[{
name: 'jasmine',
location: "../../www/lib/jasmine/lib/jasmine-core"
},
{
name: 'dojo',
location: 'lib/dojo'
},
{
name: 'dijit',
location: 'lib/dijit'
},
{
name: 'dojox',
location: 'lib/dojox'
},
{
name: 'jszlib',
location: 'lib/jszlib'
},
{
name: 'dgrid',
location: 'lib/dgrid'
},
{
name: 'xstyle',
location: 'lib/xstyle'
},
{
name: 'put-selector',
location: 'lib/put-selector'
},
{
name: 'FileSaver',
location: 'lib/FileSaver'
},
{
name: 'jDataView',
location: 'lib/jDataView/src',
main: 'jdataview'
},
{
name: 'jqueryui',
location: 'lib/jquery.ui/jqueryui'
}],
map: {
'*': {
'less': 'lib/require-less/less',
'html': 'lib/requirejs-text/text'
}
}
});
require(['jasmine/jasmine']
, function () {
require(['jasmine/jasmine-html']
, function () {
/*******************************
* copied from jasmine/boot.js *
*******************************/
/**
* ## Require & Instantiate
*
* Require Jasmine's core files. Specifically, this requires and attaches all of Jasmine's code to the `jasmine` reference.
*/
window.jasmine = jasmineRequire.core(jasmineRequire);
/**
* Since this is being run in a browser and the results should populate to an HTML page, require the HTML-specific Jasmine code, injecting the same reference.
*/
jasmineRequire.html(jasmine);
/**
* Create the Jasmine environment. This is used to run all specs in a project.
*/
var env = jasmine.getEnv();
/**
* ## The Global Interface
*
* Build up the functions that will be exposed as the Jasmine public interface. A project can customize, rename or alias any of these functions as desired, provided the implementation remains unchanged.
*/
var jasmineInterface = jasmineRequire.interface(jasmine, env);
/**
* Add all of the Jasmine global/public interface to the proper global, so a project can use the public interface directly. For example, calling `describe` in specs instead of `jasmine.getEnv().describe`.
*/
if (typeof window == "undefined" && typeof exports == "object") {
extend(exports, jasmineInterface);
} else {
extend(window, jasmineInterface);
}
/**
* ## Runner Parameters
*
* More browser specific code - wrap the query string in an object and to allow for getting/setting parameters from the runner user interface.
*/
var queryString = new jasmine.QueryString({
getWindowLocation: function() { return window.location; }
});
var catchingExceptions = queryString.getParam("catch");
env.catchExceptions(typeof catchingExceptions === "undefined" ? true : catchingExceptions);
/**
* ## Reporters
* The `HtmlReporter` builds all of the HTML UI for the runner page. This reporter paints the dots, stars, and x's for specs, as well as all spec names and all failures (if any).
*/
var htmlReporter = new jasmine.HtmlReporter({
env: env,
onRaiseExceptionsClick: function() { queryString.setParam("catch", !env.catchingExceptions()); },
getContainer: function() { return document.body; },
createElement: function() { return document.createElement.apply(document, arguments); },
createTextNode: function() { return document.createTextNode.apply(document, arguments); },
timer: new jasmine.Timer()
});
/**
* The `jsApiReporter` also receives spec results, and is used by any environment that needs to extract the results from JavaScript.
*/
env.addReporter(jasmineInterface.jsApiReporter);
env.addReporter(htmlReporter);
/**
* Filter which specs will be run by matching the start of the full name against the `spec` query param.
*/
var specFilter = new jasmine.HtmlSpecFilter({
filterString: function() { return queryString.getParam("spec"); }
});
env.specFilter = function(spec) {
return specFilter.matches(spec.getFullName());
};
/**
* Setting up timing functions to be able to be overridden. Certain browsers (Safari, IE 8, phantomjs) require this hack.
*/
window.setTimeout = window.setTimeout;
window.setInterval = window.setInterval;
window.clearTimeout = window.clearTimeout;
window.clearInterval = window.clearInterval;
/**
* Helper function for readability above.
*/
function extend(destination, source) {
for (var property in source) destination[property] = source[property];
return destination;
}
require([
'JBrowse/Browser',
"ExportGFF3.spec.js",
"ExportGFF3.spec.js",
"LazyArray.spec.js",
"FeatureLayout.spec.js",
"BigWig.spec.js",
"ConfigManager.spec.js",
"BAM.spec.js",
"RemoteBinaryFile.spec.js",
"Util.spec.js",
"AddFiles.spec.js",
"GBrowseParser.spec.js",
"NestedFrequencyTable.spec.js",
"TabixIndex.spec.js",
"TabixIndexedFile.spec.js",
"RESTStore.spec.js",
"RegularizeRefSeqs.spec.js",
"GFF3.spec.js"
]
, function () {
htmlReporter.initialize();
env.execute();
});
});
});
|
JavaScript
| 0 |
@@ -131,16 +131,21 @@
/jquery/
+dist/
jquery',
@@ -365,25 +365,25 @@
ng
-Cookies:
+Sanitize:
'lib/an
@@ -388,23 +388,24 @@
angular-
-cookies
+sanitize
/angular
@@ -409,15 +409,16 @@
lar-
-cookies
+sanitize
',%0A
@@ -483,27 +483,33 @@
-ngM
+'angular-m
oment
+'
:
-
'lib/an
@@ -571,19 +571,19 @@
bionode/
-lib
+amd
/bionode
@@ -857,71 +857,8 @@
%7D,%0A
- moment: %7B%0A exports: 'moment'%0A %7D,%0A
@@ -964,17 +964,17 @@
ng
-Cookies:
+Sanitize:
%7B%0A
@@ -1075,84 +1075,8 @@
r'%5D%0A
- %7D,%0A ngMoment: %7B%0A deps: %5B'angular', 'moment'%5D%0A
@@ -1966,22 +1966,16 @@
uery.ui/
-jquery
ui'%0A
|
375ad7e7b2c2ebe250a84eb7afa24152b593625e
|
add default WP version for E2E tests (#10574)
|
packages/e2e-test-utils/src/minWPVersionRequired.js
|
packages/e2e-test-utils/src/minWPVersionRequired.js
|
/*
* 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.
*/
/**
* Internal dependencies
*/
import checkVersion from './checkVersion';
/**
* Check minimum version of WordPress.
*
* @param {string} minVersion Minimum require WordPress version.
*/
function minWPVersionRequired(minVersion) {
const WPVersion = process.env?.WP_VERSION;
if ('latest' !== WPVersion && !checkVersion(WPVersion, minVersion)) {
//eslint-disable-next-line jest/no-focused-tests
test.only('minimum WordPress requirement not met', () => {});
}
}
export default minWPVersionRequired;
|
JavaScript
| 0 |
@@ -868,16 +868,28 @@
_VERSION
+ %7C%7C 'latest'
;%0A if (
|
b9384e989faa4f971928274da4c67cbad47fd7f7
|
replace `method` with `type`
|
jquery.fajax.js
|
jquery.fajax.js
|
;(function ($) {
$.fn.fajax = function (options) {
var settings = $.extend({
beforeSend: function(){},
success: function(){},
error: function(){},
complete: function(){},
}, options);
return this.each(function() {
$(this).on('submit', function(e){
e.preventDefault();
var action = $(this).attr('action');
var method = $(this).attr('method');
var data = $(this).serialize();
$.ajax({
url: action,
method: method,
data: data,
beforeSend: function(data){
settings.beforeSend(data);
},
success: function(data){
settings.success(data);
},
error: function(data){
settings.error(data);
},
complete: function(data){
settings.complete(data);
},
});
});
});
};
})(jQuery);
|
JavaScript
| 0.998672 |
@@ -621,22 +621,20 @@
-method
+type
: method
|
1dcdf50396006f49d84b01c934e13513d6a2a8df
|
Add repository URL in a comment.
|
jquery.wheel.js
|
jquery.wheel.js
|
/**
* Author & Copyright: Michał Gołębiowski <[email protected]>
* License: MIT
*
* Thanks to Brandon Aaron (http://brandonaaron.net) for the idea of this plugin.
*/
(function ($) {
'use strict';
if ($.fn.wheel) { // already polyfilled
return;
}
// Modern browsers support `wheel`, WebKit & Opera - `mousewheel`.
var nativeEvent =
// IE>=9 supports `wheel` via `addEventListener` but exposes no `onwheel` attribute on DOM elements
// making feature detection impossible :(
('onwheel' in document.createElement('div') || document.documentMode > 8) ?
'wheel' :
'mousewheel';
// Normalizing event properties for the 'wheel' event (like event.which etc.).
if (nativeEvent === 'wheel') {
$.event.fixHooks.wheel = $.event.mouseHooks;
} else {
// We can't attach hooks to 'wheel' only since we need a type matching to originalEvent.type
// and this field is non-mutable.
$.event.fixHooks.mousewheel = $.event.mouseHooks;
}
function handler(orgEvent) {
/* jshint validthis: true */ // event handler
var args = [].slice.call(arguments, 0),
event = $.event.fix(orgEvent);
if (nativeEvent === 'wheel') {
event.deltaMode = orgEvent.deltaMode;
event.deltaX = orgEvent.deltaX;
event.deltaY = orgEvent.deltaY;
event.deltaZ = orgEvent.deltaZ;
} else {
event.type = 'wheel';
event.deltaMode = 0; // deltaMode === 0 => scrolling in pixels (in Chrome default wheelDeltaY is 120)
event.deltaX = -1 * orgEvent.wheelDeltaX;
event.deltaY = -1 * orgEvent.wheelDeltaY;
event.deltaZ = 0; // not supported
}
// Exchange original event for the modified one in arguments list.
args[0] = event;
return $.event.dispatch.apply(this, args);
}
// Implementing 'wheel' using non-standard 'mousewheel' event.
$.event.special.wheel = {
setup: function () {
this.addEventListener(nativeEvent, handler, false);
},
teardown: function () {
this.removeEventListener(nativeEvent, handler, false);
}
};
// Implement `$object.wheel()` and `$object.wheel(handler)`.
$.fn.wheel = function (data, fn) {
return arguments.length > 0 ?
this.on('wheel', null, data, fn) :
this.trigger('wheel');
};
})(jQuery);
|
JavaScript
| 0 |
@@ -75,16 +75,69 @@
se: MIT%0A
+ * Repository: https://github.com/mzgol/jquery-wheel%0A
*%0A * Th
|
25ba8186e636679f8d875db96e37e7967a085d52
|
make init function for car model
|
models/car.model.js
|
models/car.model.js
|
const validator = require('../utils').validator;
const size = require('../utils').constants.size;
const convert = require('../utils/inputConverter').convert;
class Car {
constructor(model, photoLink) {
this._makemodel = model.makemodel;
this._category = model.category;
this._carphotolink = photoLink;
this._adultscount = model.adultscount;
this._bagscount = model.bagscount;
this._doorscount = model.doorscount;
this._fueltype = model.fueltype;
this._transmission = model.transmission;
this._mileage = model.mileage;
this._yearofmanufacture = model.yearofmanufacture;
this._airconditioner = model.airconditioner;
this._baseprice = model.baseprice;
this._specialprice = model.specialprice;
this._specialpriceactivated = model.specialpriceactivated;
this.comments = [];
this.booked = [];
}
get id() {
return this._id;
}
get _makemodel() {
return this.makemodel;
}
set _makemodel(value) {
const name = convert(value);
if (validator.validateString(name, size.MIN_NAME, size.MAX_NAME)) {
this.makemodel = name;
} else {
throw new Error('Invalid car make and model');
}
}
get _category() {
return this.category;
}
set _category(value) {
const name = convert(value);
if (validator.validateString(name, size.MIN_NAME, size.MAX_NAME)) {
this.category = name;
} else {
throw new Error('Invalid category name');
}
}
get _carphotolink() {
return this.carphotolink;
}
set _carphotolink(value) {
const link = convert(value).replace(///g, '/');
if (validator.validateImageExtension(link)) {
this.carphotolink = link;
} else {
throw new Error('Invalid photo link - only jpg or png');
}
}
get _adultscount() {
return this.adultscount;
}
set _adultscount(value) {
const count = parseInt(value, 10);
if (Number.isNaN(Number(count)) || (count < 2 || count > 20)) {
throw new Error('Invalid adultscount - must be in range 2-20');
}
this.adultscount = count;
}
get _bagscount() {
return this.bagscount;
}
set _bagscount(value) {
const count = parseInt(value, 10);
if (Number.isNaN(Number(count)) || (count < 2 || count > 20)) {
throw new Error('Invalid bagscount - must be in range 2-20');
}
this.bagscount = count;
}
get _doorscount() {
return this.doorscount;
}
set _doorscount(value) {
const count = parseInt(value, 10);
if (Number.isNaN(Number(count)) || (count < 2 || count > 5)) {
throw new Error('Invalid doorscount - must be in range 2-5');
}
this.doorscount = count;
}
get _fueltype() {
return this.fueltype;
}
set _fueltype(value) {
const fuelType = convert(value);
if (validator.validateString(fuelType, size.MIN_NAME, size.MAX_NAME)) {
this.fueltype = fuelType;
} else {
throw new Error('Invalid fuel type name');
}
}
get _transmission() {
return this.transmission;
}
set _transmission(value) {
const transmissionType = convert(value);
if (validator.validateString(transmissionType, size.MIN_NAME, size.MAX_NAME)) {
this.transmission = transmissionType;
} else {
throw new Error('Invalid transmission type');
}
}
get _mileage() {
return this.mileage;
}
set _mileage(value) {
const mpg = parseInt(value, 10);
if (Number.isNaN(Number(mpg)) || (mpg < 1 || mpg > 200)) {
throw new Error('Invalid mileage - must be in range 1-200');
}
this.mileage = mpg;
}
get _yearofmanufacture() {
return this.yearofmanufacture;
}
set _yearofmanufacture(value) {
const year = parseInt(value, 10);
if (Number.isNaN(Number(year)) || (year < 2010 || year > 2020)) {
throw new Error('Invalid year of manufacture - must be in range 2010-2020');
}
this.yearofmanufacture = year;
}
get _airconditioner() {
return this.airconditioner;
}
set _airconditioner(value) {
if (typeof value === 'undefined') {
value = 0;
}
if (value < 0 || value > 1) {
throw new Error('Invalid feature air conditioner');
}
this.airconditioner = value;
}
get _baseprice() {
return this.baseprice;
}
set _baseprice(value) {
const price = parseFloat(value, 10);
if (Number.isNaN(Number(price)) || (price < 0 || price > 2000)) {
throw new Error('Invalid base price - must be in range 0-2000');
}
this.baseprice = price;
}
get _specialprice() {
return this.specialprice;
}
set _specialprice(value) {
const price = parseFloat(value, 10);
if (Number.isNaN(Number(price)) || (price < 0 || price > 2000)) {
throw new Error('Invalid special price - must be in range 0-2000');
}
this.specialprice = price;
}
get _specialpriceactivated() {
return this.specialpriceactivated;
}
set _specialpriceactivated(value) {
if (typeof value === 'undefined') {
value = 0;
}
if (value < 0 || value > 1) {
throw new Error('Invalid feature air conditioner');
}
this.specialpriceactivated = value;
}
}
module.exports = Car;
|
JavaScript
| 0.000006 |
@@ -5758,16 +5758,99 @@
%7D%0A%7D%0A%0A
+%0Aconst initCar = (model, photoLink) =%3E %7B%0A return new Car(model, photoLink);%0A%7D;%0A%0A
module.e
@@ -5857,14 +5857,27 @@
xports =
+ %7B
Car
+, initCar %7D
;%0A
|
7e2e96cbee78d8b9c62401953a9f905e4dd36373
|
use native findIndex if supported
|
src/popper/utils/findIndex.js
|
src/popper/utils/findIndex.js
|
/**
* Return the index of the matching object
* @method
* @memberof Popper.Utils
* @argument {Array} arr
* @argument prop
* @argument value
* @returns index or -1
*/
export default function findIndex(arr, prop, value) {
// use filter instead of find because find has less cross-browser support
const match = arr.filter((obj) => (obj[prop] === value))[0];
return arr.indexOf(match);
}
|
JavaScript
| 0.000001 |
@@ -221,16 +221,161 @@
alue) %7B%0A
+ // use native findIndex if supported%0A if (Array.prototype.findIndex) %7B%0A return arr.findIndex((cur) =%3E cur%5Bprop%5D === value);%0A %7D%0A%0A
// u
|
9925672d517dc7d8ec72e11a57cdd8ce24cfebb2
|
format #59
|
js/StatusBar.js
|
js/StatusBar.js
|
// Copyright 2018, University of Colorado Boulder
/**
* Status bar that runs along the top of a game
*
* @author Andrea Lin
*/
define( function( require ) {
'use strict';
// modules
var BackButton = require( 'SCENERY_PHET/buttons/BackButton' );
var inherit = require( 'PHET_CORE/inherit' );
var Node = require( 'SCENERY/nodes/Node' );
var Rectangle = require( 'SCENERY/nodes/Rectangle' );
var vegas = require( 'VEGAS/vegas' );
/**
* @param {Property} visibleBoundsProperty - for layout
* @param {Node} messageNode - to the right of the back button, typically Text
* @param {Node} scoreDisplay - intended to be one of the ScoreDisplay* nodes but can be any custom Node provided
* by the client
* @param {Object} [options]
* @constructor
*/
function StatusBar( visibleBoundsProperty, messageNode, scoreDisplay, options ) {
options = _.extend( {
backButtonListener: null,
xMargin: 20,
yMargin: 10,
backgroundFill: 'rgb( 49, 117, 202 )',
spacing: 8,
alwaysInsideLayoutBounds: true // otherwise, moves with the edges of browser window
}, options );
assert && assert( !options.children, 'ScoreDisplayNumber sets children' );
var backButton = new BackButton( { listener: options.backButtonListener } );
var backgroundHeight = _.max( [ backButton.height, messageNode.height, scoreDisplay.height ] ) + 2 * options.yMargin;
var backgroundNode = new Rectangle(
visibleBoundsProperty.get().minX,
visibleBoundsProperty.minY,
visibleBoundsProperty.get().maxX - visibleBoundsProperty.get().minX,
backgroundHeight, {
fill: options.backgroundFill
} );
// layout
backButton.left = backgroundNode.left + options.xMargin;
backButton.centerY = backgroundNode.centerY;
messageNode.left = backButton.right + options.spacing;
messageNode.centerY = backgroundNode.centerY;
scoreDisplay.right = backgroundNode.right - options.xMargin;
scoreDisplay.centerY = backgroundNode.centerY;
var boundsListener = function( bounds ) {
backgroundNode.setRectX( bounds.minX );
backgroundNode.setRectWidth( bounds.maxX - bounds.minX );
if ( !options.alwaysInsideLayoutBounds ) {
backButton.left = backgroundNode.left + options.xMargin;
messageNode.left = backButton.right + options.spacing;
scoreDisplay.right = backgroundNode.right - options.xMargin;
}
};
visibleBoundsProperty.link( boundsListener );
// @private
this.disposeStatusBar = function() {
backButton.dispose();
visibleBoundsProperty.unlink( boundsListener );
};
options.children = [ backgroundNode, backButton, messageNode, scoreDisplay ];
Node.call( this, options );
}
vegas.register( 'StatusBar', StatusBar );
return inherit( Node, StatusBar, {
// @public
dispose: function() {
this.disposeStatusBar;
Node.prototype.dispose.call( this );
}
} );
} );
|
JavaScript
| 0.000013 |
@@ -185,19 +185,16 @@
modules%0A
- %0A
var Ba
@@ -1290,20 +1290,16 @@
er %7D );%0A
-
%0A var
@@ -1665,16 +1665,18 @@
undFill%0A
+
%7D );
|
1f2027b62c5531d40ef0da436f228e52270a410d
|
Update app.js
|
javascripts/app.js
|
javascripts/app.js
|
var main = function(){
//Dropdown menu
$(''.dropdown-toggle').click(function(){
$(''.dropdown-menu').toggle();
});
//For the about toggle
$('#pagetopic').click(function(){
$('#pagetopic').fadeOut(1000);
});
};
$(document).ready(main);
|
JavaScript
| 0.000002 |
@@ -33,25 +33,24 @@
wn menu%0A $('
-'
.dropdown-to
|
8912c190268c7d718efba7418e6a4671cd9866ea
|
changed to shorter date
|
WebKit/scripts/lib/Timeago.js
|
WebKit/scripts/lib/Timeago.js
|
define([
"jquery"
],
function($) {
/**
* Timeago is a jQuery plugin that makes it easy to support automatically
* updating fuzzy timestamps (e.g. "4 minutes ago" or "about 1 day ago").
*
* @name timeago
* @version 0.11.4
* @requires jQuery v1.2.3+
* @author Ryan McGeary
* @license MIT License - http://www.opensource.org/licenses/mit-license.php
*
* For usage and examples, visit:
* http://timeago.yarp.com/
*
* Copyright (c) 2008-2012, Ryan McGeary (ryan -[at]- mcgeary [*dot*] org)
*/
$.timeago = function(timestamp) {
if (timestamp instanceof Date) {
return inWords(timestamp);
} else if (typeof timestamp === "string") {
return inWords($.timeago.parse(timestamp));
} else if (typeof timestamp === "number") {
return inWords(new Date(timestamp));
} else {
return inWords($.timeago.datetime(timestamp));
}
};
var $t = $.timeago;
$.extend($.timeago, {
settings: {
refreshMillis: 60000,
allowFuture: false,
strings: {
prefixAgo: null,
prefixFromNow: null,
suffixAgo: "ago",
suffixFromNow: "from now",
seconds: "less than a minute",
minute: "about a minute",
minutes: "%d minutes",
hour: "about an hour",
hours: "about %d hours",
day: "a day",
days: "%d days",
month: "about a month",
months: "%d months",
year: "about a year",
years: "%d years",
wordSeparator: " ",
numbers: []
}
},
inWords: function(distanceMillis) {
var $l = this.settings.strings;
var prefix = $l.prefixAgo;
var suffix = $l.suffixAgo;
if (this.settings.allowFuture) {
if (distanceMillis < 0) {
prefix = $l.prefixFromNow;
suffix = $l.suffixFromNow;
}
}
var seconds = Math.abs(distanceMillis) / 1000;
var minutes = seconds / 60;
var hours = minutes / 60;
var days = hours / 24;
var years = days / 365;
function substitute(stringOrFunction, number) {
var string = $.isFunction(stringOrFunction) ? stringOrFunction(number, distanceMillis) : stringOrFunction;
var value = ($l.numbers && $l.numbers[number]) || number;
return string.replace(/%d/i, value);
}
var words = seconds < 45 && substitute($l.seconds, Math.round(seconds)) ||
seconds < 90 && substitute($l.minute, 1) ||
minutes < 45 && substitute($l.minutes, Math.round(minutes)) ||
minutes < 90 && substitute($l.hour, 1) ||
hours < 24 && substitute($l.hours, Math.round(hours)) ||
hours < 42 && substitute($l.day, 1) ||
days < 30 && substitute($l.days, Math.round(days)) ||
days < 45 && substitute($l.month, 1) ||
days < 365 && substitute($l.months, Math.round(days / 30)) ||
years < 1.5 && substitute($l.year, 1) ||
substitute($l.years, Math.round(years));
var separator = $l.wordSeparator === undefined ? " " : $l.wordSeparator;
return $.trim([prefix, words, suffix].join(separator));
},
parse: function(iso8601) {
var s = $.trim(iso8601);
s = s.replace(/\.\d+/,""); // remove milliseconds
s = s.replace(/-/,"/").replace(/-/,"/");
s = s.replace(/T/," ").replace(/Z/," UTC");
s = s.replace(/([\+\-]\d\d)\:?(\d\d)/," $1$2"); // -04:00 -> -0400
return new Date(s);
},
datetime: function(elem) {
var iso8601 = $t.isTime(elem) ? $(elem).attr("datetime") : $(elem).attr("title");
return $t.parse(iso8601);
},
isTime: function(elem) {
// jQuery's `is()` doesn't play well with HTML5 in IE
return $(elem).get(0).tagName.toLowerCase() === "time"; // $(elem).is("time");
}
});
$.fn.timeago = function() {
var self = this;
self.each(refresh);
var $s = $t.settings;
if ($s.refreshMillis > 0) {
setInterval(function() { self.each(refresh); }, $s.refreshMillis);
}
return self;
};
function refresh() {
var data = prepareData(this);
if (!isNaN(data.datetime)) {
$(this).text(inWords(data.datetime));
}
return this;
}
function prepareData(element) {
element = $(element);
if (!element.data("timeago")) {
element.data("timeago", { datetime: $t.datetime(element) });
var text = $.trim(element.text());
if (text.length > 0 && !($t.isTime(element) && element.attr("title"))) {
element.attr("title", text);
}
}
return element.data("timeago");
}
function inWords(date) {
return $t.inWords(distance(date));
}
function distance(date) {
return (new Date().getTime() - date.getTime());
}
// fix for IE6 suckage
document.createElement("abbr");
document.createElement("time");
});
|
JavaScript
| 0.999126 |
@@ -1087,14 +1087,11 @@
o: %22
-ago
%22,%0A
+
@@ -1143,26 +1143,14 @@
s: %22
-less than a minute
+%25d sec
%22,%0A
@@ -1169,22 +1169,13 @@
e: %22
-about a
+1
min
-ute
%22,%0A
@@ -1197,20 +1197,16 @@
%22%25d min
-utes
%22,%0A
@@ -1219,21 +1219,11 @@
r: %22
-about an hour
+1 h
%22,%0A
@@ -1241,22 +1241,12 @@
s: %22
-about %25d hours
+%25d h
%22,%0A
@@ -1258,17 +1258,17 @@
day: %22
-a
+1
day%22,%0A
@@ -1287,17 +1287,16 @@
%22%25d day
-s
%22,%0A
@@ -1306,23 +1306,17 @@
month: %22
-about a
+1
month%22,
@@ -1364,15 +1364,9 @@
r: %22
-about a
+1
yea
|
4e829853e46937f11261ec0de2d28a68f8f40bd9
|
Fix cached files paths.
|
build/serviceworker.js
|
build/serviceworker.js
|
'use strict';
importScripts('serviceworker-cache-polyfill.js');
var CACHE_NAME = 'react-boilerplate-cache-v1';
// The files we want to cache
var urlsToCache = ['/', '/css/main.css', '/js/bundle.js'];
// Set the callback for the install step
self.addEventListener('install', function (event) {
// Perform install steps
// event.waitUntil(
caches.open(CACHE_NAME).then(function (cache) {
console.log('Opened cache');
return cache.addAll(urlsToCache);
});
});
// Set the callback when the files get fetched
self.addEventListener('fetch', function (event) {
event.respondWith(caches.match(event.request).then(function (response) {
// Cached files available, return those
if (response) {
return response;
}
// IMPORTANT: Clone the request. A request is a stream and
// can only be consumed once. Since we are consuming this
// once by cache and once by the browser for fetch, we need
// to clone the response
var fetchRequest = event.request.clone();
// Start request again since there are no files in the cache
return fetch(fetchRequest).then(function (response) {
// If response is invalid, throw error
if (!response || response.status !== 200 || response.type !== 'basic') {
return response;
}
// IMPORTANT: Clone the response. A response is a stream
// and because we want the browser to consume the response
// as well as the cache consuming the response, we need
// to clone it so we have 2 stream.
var responseToCache = response.clone();
// Otherwise cache the downloaded files
caches.open(CACHE_NAME).then(function (cache) {
cache.put(event.request, responseToCache);
});
// And return the network response
return response;
});
}));
});
|
JavaScript
| 0 |
@@ -161,16 +161,21 @@
%5B'/', '
+build
/css/mai
@@ -183,16 +183,21 @@
.css', '
+build
/js/bund
@@ -1811,12 +1811,13 @@
;%0A %7D));%0A%7D);
+%0A
|
b28087d046371069028af24de4b20adabd4dc9bd
|
FIX : bad systemjs-router-bundler parameter
|
build/tasks/release.js
|
build/tasks/release.js
|
var gulp = require('gulp');
var insert = require('gulp-insert');
var concatFile = require('gulp-concat');
var runSequence = require('run-sequence');
var routeBundler = require('systemjs-route-bundler');
var paths = require('../paths');
gulp.task('cache-bust', function () {
var cacheBust = "var systemLocate = System.locate; System.locate = function(load) { var cacheBust = '?bust=' + " + Math.round(new Date() / 1000) +"; return Promise.resolve(systemLocate.call(this, load)).then(function(address) { if (address.indexOf('bust') > -1 || address.indexOf('css') > -1 || address.indexOf('json') > -1) return address; return address + cacheBust; });}\n"
return gulp.src('dist/app/app.js')
.pipe(insert.prepend("window.prod = true;\n"))
.pipe(insert.prepend(cacheBust))
.pipe(gulp.dest('dist/app'));
});
gulp.task('inline-systemjs', function () {
return gulp.src([
'./jspm_packages/es6-module-loader.js',
'./jspm_packages/system.js',
'./system.config.js',
'dist/app/app.js'
])
//.pipe(uglify())
.pipe(concatFile('app/app.js'))
.pipe(gulp.dest(paths.output));
});
gulp.task('release', function (callback) {
return runSequence(
'clean',
'build',
'bundle',
'cache-bust',
'replace',
'inline-systemjs',
callback
);
});
gulp.task('bundle', function () {
var routes = require('../../dist/app/routes.json');
routes = routes.map(function (r) {
return r.src;
});
var config = {
dest: 'dist',
main: 'app/app.js',
destMain: 'dist/app',
routes: routes,
bundleThreshold: 0.6,
systemConfig: './system.config.js',
sourceMaps: false,
minify: true,
mangle: true,
verboseOutput: true,
ignoredPaths: [
'jspm_packages',
'npm:',
'github:'
]
};
return routeBundler.build(config);
});
|
JavaScript
| 0.000001 |
@@ -1570,20 +1570,22 @@
-syste
+jsp
mConfig
+Path
: '.
|
1a779cdbef531036ccbd1f39d7d900cbb0dd0955
|
Revert "changed chmod/chown target to sim directory #146"
|
js/grunt/dev.js
|
js/grunt/dev.js
|
// Copyright 2017, University of Colorado Boulder
/**
* Deploys a dev version after incrementing the test version number.
*
* @author Jonathan Olson <[email protected]>
*/
'use strict';
// modules
const _ = require( 'lodash' ); // eslint-disable-line
const assert = require( 'assert' );
const booleanPrompt = require( '../common/booleanPrompt' );
const build = require( '../common/build' );
const buildLocal = require( '../common/buildLocal' );
const devDirectoryExists = require( '../common/devDirectoryExists' );
const devScp = require( '../common/devScp' );
const devSsh = require( '../common/devSsh' );
const getBranch = require( '../common/getBranch' );
const getRepoVersion = require( '../common/getRepoVersion' );
const gitIsClean = require( '../common/gitIsClean' );
const gitPush = require( '../common/gitPush' );
const getRemoteBranchSHAs = require( '../common/getRemoteBranchSHAs' );
const gitRevParse = require( '../common/gitRevParse' );
const grunt = require( 'grunt' );
const lintAllRunnable = require( '../common/lintAllRunnable' );
const npmUpdate = require( '../common/npmUpdate' );
const setRepoVersion = require( '../common/setRepoVersion' );
const SimVersion = require( '../common/SimVersion' );
const updateDependenciesJSON = require( '../common/updateDependenciesJSON' );
const vpnCheck = require( '../common/vpnCheck' );
const writePhetioHtaccess = require( '../common/writePhetioHtaccess' );
/**
* Deploys a dev version after incrementing the test version number.
* @public
*
* @param {string} repo
* @param {Array.<string>} brands
* @param {boolean} noninteractive
* @param {string} branch - 'master' for normal dev deploys, otherwise is the name of a one-off branch
* @param {string} [message] - Optional message to append to the version-increment commit.
* @returns {Promise}
*/
module.exports = async function( repo, brands, noninteractive, branch, message ) {
const isOneOff = branch !== 'master';
const testType = isOneOff ? branch : 'dev';
if ( isOneOff ) {
assert( !branch.includes( '-' ), 'One-off versions should be from branches that do not include hyphens' );
}
if ( !( await vpnCheck() ) ) {
grunt.fail.fatal( 'VPN or being on campus is required for this build. Ensure VPN is enabled, or that you have access to phet-server.int.colorado.edu' );
}
const currentBranch = await getBranch( repo );
if ( currentBranch !== branch ) {
grunt.fail.fatal( `${testType} deployment should be on the branch ${branch}, not: ` + ( currentBranch ? currentBranch : '(detached head)' ) );
}
const previousVersion = await getRepoVersion( repo );
if ( previousVersion.testType !== testType ) {
if ( isOneOff ) {
grunt.fail.fatal( `The current version identifier is not a one-off version (should be something like ${previousVersion.major}.${previousVersion.minor}.${previousVersion.maintenance}-${testType}.${previousVersion.testNumber === null ? '0' : previousVersion.testNumber}), aborting.` );
}
else {
grunt.fail.fatal( 'The current version identifier is not a dev version, aborting.' );
}
}
const isClean = await gitIsClean( repo );
if ( !isClean ) {
throw new Error( `Unclean status in ${repo}, cannot deploy` );
}
const currentSHA = await gitRevParse( repo, 'HEAD' );
const latestSHA = ( await getRemoteBranchSHAs( repo ) )[ branch ];
if ( currentSHA !== latestSHA ) {
// See https://github.com/phetsims/chipper/issues/699
grunt.fail.fatal( `Out of date with remote, please push or pull repo. Current SHA: ${currentSHA}, latest SHA: ${latestSHA}` );
}
// Ensure we don't try to request an unsupported brand
const supportedBrands = grunt.file.readJSON( `../${repo}/package.json` ).phet.supportedBrands;
brands.forEach( brand => assert( supportedBrands.includes( brand ), `Brand ${brand} not included in ${repo}'s supported brands: ${supportedBrands.join( ',' )}` ) );
// Ensure that the repository and its dependencies pass lint before continuing.
// See https://github.com/phetsims/perennial/issues/76
await lintAllRunnable( repo );
// Bump the version
const version = new SimVersion( previousVersion.major, previousVersion.minor, previousVersion.maintenance, {
testType: testType,
testNumber: previousVersion.testNumber + 1
} );
const versionString = version.toString();
const simPath = buildLocal.devDeployPath + repo;
const versionPath = simPath + '/' + versionString;
const simPathExists = await devDirectoryExists( simPath );
const versionPathExists = await devDirectoryExists( versionPath );
if ( versionPathExists ) {
grunt.fail.fatal( `Directory ${versionPath} already exists. If you intend to replace the content then remove the directory manually from ${buildLocal.devDeployServer}.` );
}
if ( !await booleanPrompt( `Deploy ${versionString} to ${buildLocal.devDeployServer}`, noninteractive ) ) {
grunt.fail.fatal( `Aborted ${testType} deploy` );
}
await setRepoVersion( repo, version, message );
await gitPush( repo, branch );
// Make sure our correct npm dependencies are set
await npmUpdate( repo );
await npmUpdate( 'chipper' );
grunt.log.writeln( await build( repo, {
brands: brands,
allHTML: true,
debugHTML: true
} ) );
// Create (and fix permissions for) the main simulation directory, if it didn't already exist
if ( !simPathExists ) {
await devSsh( `mkdir -p "${simPath}" && echo "IndexOrderDefault Descending Date\n" > "${simPath}/.htaccess"` );
// await devSsh( `chmod -R g+w "${simPath}"` );
}
// Create the version-specific directory
await devSsh( `mkdir -p "${versionPath}"` );
// Copy the build contents into the version-specific directory
for ( const brand of brands ) {
await devScp( `../${repo}/build/${brand}`, `${versionPath}/` );
}
// If there is a protected directory and we are copying to the dev server, include the .htaccess file
// This is for PhET-iO simulations, to protected the password protected wrappers, see
// https://github.com/phetsims/phet-io/issues/641
if ( brands.includes( 'phet-io' ) && buildLocal.devDeployServer === 'bayes.colorado.edu' ) {
const htaccessLocation = `../${repo}/build/phet-io/`;
await writePhetioHtaccess( htaccessLocation, null, versionPath );
}
// Permissions fixes so others can write over it later
await devSsh( `chmod -R g+w "${simPath}"` );
await devSsh( `chown -R :phet "${simPath}"` );
// Move over dependencies.json and commit/push
await updateDependenciesJSON( repo, brands, versionString, branch );
const versionURL = `https://phet-dev.colorado.edu/html/${repo}/${versionString}`;
if ( brands.includes( 'phet' ) ) {
grunt.log.writeln( `Deployed: ${versionURL}/phet/${repo}_en_phet.html` );
}
if ( brands.includes( 'phet-io' ) ) {
grunt.log.writeln( `Deployed: ${versionURL}/phet-io/` );
}
};
|
JavaScript
| 0 |
@@ -6380,35 +6380,39 @@
chmod -R g+w %22$%7B
-sim
+version
Path%7D%22%60 );%0A awa
@@ -6437,27 +6437,31 @@
-R :phet %22$%7B
-sim
+version
Path%7D%22%60 );%0A%0A
|
d6b22176bbd4cbe8bd29980b1c60a8325e409656
|
Add File.ShortPath
|
_emulator/FileSystemObject.js
|
_emulator/FileSystemObject.js
|
var controller = require("../_controller");
function TextStream(filename) {
this.buffer = controller.readFile(filename) || "";
this.uuid = controller.getUUID();
this.filename = filename;
this.Write = this.WriteLine = line => {
this.buffer = this.buffer + line;
controller.writeFile(filename, this.buffer);
controller.logResource(this.uuid, this.filename, this.buffer);
}
this.ReadAll = () => {
return this.buffer;
}
this.Close = () => {};
this.BufferArray = [];
this.ReadLine = function() {
if (this.BufferArray.length == 0)
this.BufferArray = this.buffer.split("\n");
return this.BufferArray.shift();
}
}
function ProxiedTextStream(filename) {
return new Proxy(new TextStream(filename), {
get: function(target, name) {
switch (name) {
default:
if (!(name in target)) {
controller.kill(`TextStream.${name} not implemented!`)
}
return target[name];
}
}
})
}
function File(contents) {
this.OpenAsTextStream = () => ProxiedTextStream(contents);
}
function ProxiedFile(filename) {
return new Proxy(new File(filename), {
get: function(target, name) {
switch (name) {
default:
if (!(name in target)) {
controller.kill(`File.${name} not implemented!`)
}
return target[name];
}
}
})
}
function FileSystemObject() {
this.CreateTextFile = this.OpenTextFile = filename => new ProxiedTextStream(filename);
this.BuildPath = function() {
return Array.prototype.slice.call(arguments, 0).join("\\");
}
this.FileExists = this.DeleteFile = () => true;
this.GetFile = function(filename) {
return new ProxiedFile(filename);
}
this.GetSpecialFolder = function(id) {
switch (id) {
case 0:
case "0":
return "C:\\WINDOWS\\"
case 1:
case "1":
return "(System folder)"
case 2:
case "2":
return "(Temporary folder)"
default:
return "(Special folder " + id + ")"
}
}
this.GetTempName = () => "(Temporary file)"
}
module.exports = function() {
return new Proxy(new FileSystemObject(), {
get: function(target, name) {
switch (name) {
default:
if (!(name in target)) {
controller.kill(`FileSystemObject.${name} not implemented!`)
}
return target[name];
}
}
})
}
|
JavaScript
| 0.000001 |
@@ -624,16 +624,71 @@
t();%0A%09%7D%0A
+%09this.ShortPath = function() %7Bconsole.log(arguments);%7D%0A
%7D%0A%0Afunct
@@ -1057,16 +1057,68 @@
tents);%0A
+%09this.ShortPath = %22C:%5C%5CPROGRA~1%5C%5Cexample-file.exe%22;%0A
%7D%0A%0Afunct
|
57a0666c000d72902e4b7965c1438e42c9e235bf
|
modify default zoom
|
mobile/ol3map/js/map.js
|
mobile/ol3map/js/map.js
|
var baseLayer = new ol.layer.Tile({
source: new ol.source.OSM()
});
var countries = new ol.layer.Vector({
source: new ol.source.GeoJSON({
projection: 'EPSG:3857',
url: '../data/shanghai.json'
})
});
var center = ol.proj.transform([114.01,22.51],'EPSG:4326','EPSG:3857');
//-122.0312186,37.33233141
var view = new ol.View({
center: center,
zoom: 9
});
var map = new ol.Map({
target: 'map',
layers: [baseLayer,countries],
view: view,
controls: []
});
function onMouseMove(event){
var coordinate = event.coordinate;
var pixel = map.getPixelFromCoordinate(coordinate);
var name = $('#name')[0];
name.innerHTML = '';
map.forEachFeatureAtPixel(pixel, function(feature){
name.innerHTML += feature.get('name') + '<br>';
});
}
map.on('click', onMouseMove);
function setCenter(lat,lon){
var location = ol.proj.transform([lon,lat],'EPSG:4326','EPSG:3857');
map.getView().setCenter(location);
}
|
JavaScript
| 0.000001 |
@@ -362,9 +362,10 @@
om:
-9
+12
%0A%7D);
|
8f3a114bc2e20fad3d338a9c670785bdda3f50e3
|
add comments to the top of each function
|
js/news/news.js
|
js/news/news.js
|
// A lot of this code is from the original feedToJson function that was included with this project
// The new code allows for multiple feeds to be used but a bunch of variables and such have literally been copied and pasted into this code and some help from here: http://jsfiddle.net/BDK46/
// The original version can be found here: http://airshp.com/2011/jquery-plugin-feed-to-json/
var news = {
feed: config.news.feed || null,
newsLocation: '.news',
newsItems: [],
seenNewsItem: [],
_yqURL: 'http://query.yahooapis.com/v1/public/yql',
_yqlQS: '?format=json&q=select%20*%20from%20rss%20where%20url%3D',
_cacheBuster: Math.floor((new Date().getTime()) / 1200 / 1000),
_failedAttempts: 0,
fetchInterval: config.news.fetchInterval || 60000,
updateInterval: config.news.interval || 5500,
fadeInterval: 2000,
intervalId: null,
fetchNewsIntervalId: null
}
news.buildQueryString = function (feed) {
return this._yqURL + this._yqlQS + '\'' + encodeURIComponent(feed) + '\'';
}
news.fetchNews = function () {
// Reset the news feed
this.newsItems = [];
this.feed.forEach(function (_curr) {
var _yqUrlString = this.buildQueryString(_curr);
this.fetchFeed(_yqUrlString);
}.bind(this));
}
news.fetchFeed = function (yqUrl) {
$.ajax({
type: 'GET',
datatype:'jsonp',
url: yqUrl,
success: function (data) {
if (data.query.count > 0) {
this.parseFeed(data.query.results.item);
} else {
console.error('No feed results for: ' + yqUrl);
}
}.bind(this),
error: function () {
// non-specific error message that should be updated
console.error('No feed results for: ' + yqUrl);
}
});
}
news.parseFeed = function (data) {
var _rssItems = [];
for (var i = 0, count = data.length; i < count; i++) {
_rssItems.push(data[i].title);
}
this.newsItems = this.newsItems.concat(_rssItems);
return true;
}
news.showNews = function () {
// If all items have been seen, swap seen to unseen
if (this.newsItems.length === 0 && this.seenNewsItem.length !== 0) {
if (this._failedAttempts === 20) {
console.error('Failed to show a news story 20 times, stopping any attempts');
return false;
}
this._failedAttempts++;
setTimeout(function () {
this.showNews();
}.bind(this), 3000);
} else if (this.newsItems.length === 0 && this.seenNewsItem.length !== 0) {
this.newsItems = this.seenNewsItem.splice(0);
}
var _location = Math.floor(Math.random() * this.newsItems.length);
var _item = news.newsItems.splice(_location, 1)[0];
this.seenNewsItem.push(_item);
$(this.newsLocation).updateWithText(_item, this.fadeInterval);
}
news.init = function () {
if (this.feed === null || (this.feed instanceof Array === false && typeof this.feed !== 'string')) {
return false;
} else if (typeof this.feed === 'string') {
this.feed = [this.feed];
}
this.fetchNews();
this.showNews();
this.fetchNewsIntervalId = setInterval(function () {
this.fetchNews()
}.bind(this), this.fetchInterval)
this.intervalId = setInterval(function () {
this.showNews();
}.bind(this), this.updateInterval);
}
|
JavaScript
| 0 |
@@ -855,24 +855,275 @@
Id: null%0A%7D%0A%0A
+/**%0A * Creates the query string that will be used to grab a converted RSS feed into a JSON object via Yahoo%0A * @param %7Bstring%7D feed The original location of the RSS feed%0A * @return %7Bstring%7D The new location of the RSS feed provided by Yahoo%0A */%0A
news.buildQu
@@ -1229,24 +1229,94 @@
+ '%5C'';%0A%0A%7D%0A%0A
+/**%0A * Fetches the news for each feed provided in the config file%0A */%0A
news.fetchNe
@@ -1521,24 +1521,156 @@
this));%0A%0A%7D%0A%0A
+/**%0A * Runs a GET request to Yahoo's service%0A * @param %7Bstring%7D yqUrl The URL being used to grab the RSS feed (in JSON format)%0A */%0A
news.fetchFe
@@ -2084,24 +2084,210 @@
%09%7D%0A%09%7D);%0A%0A%7D%0A%0A
+/**%0A * Parses each item in a single news feed%0A * @param %7BObject%7D data The news feed that was returned by Yahoo%0A * @return %7Bboolean%7D Confirms that the feed was parsed correctly%0A */%0A
news.parseFe
@@ -2494,24 +2494,387 @@
n true;%0A%0A%7D%0A%0A
+/**%0A * Loops through each available and unseen news feed after it has been retrieved from Yahoo and shows it on the screen%0A * When all news titles have been exhausted, the list resets and randomly chooses from the original set of items%0A * @return %7Bboolean%7D Confirms that there is a list of news items to loop through and that one has been shown on the screen%0A */%0A
news.showNew
@@ -3539,16 +3539,16 @@
item);%0A%0A
-
%09$(this.
@@ -3604,16 +3604,31 @@
rval);%0A%0A
+%09return true;%0A%0A
%7D%0A%0Anews.
|
353e4ab7978ec1359b275f7a2cae8c019a2e66b9
|
Update count value to Number type.
|
models/AkamaiLogData.js
|
models/AkamaiLogData.js
|
var mongoose = require('mongoose');
require('./projectModel');
var AkamaiSchema = new mongoose.Schema({
Day : { type: String, index: true},
URL: String,
Completed : Number,
Initiated : String,
EDGE_VOLUME : String,
OK_EDGE_VOLUME : String,
ERROR_EDGE_VOLUME : String,
EDGE_HITS : String,
OK_EDGE_HITS : String,
ERROR_EDGE_HITS : String,
R_0XX : String,
R_2XX : String,
R_200 : String,
R_206 : String,
R_3XX : String,
R_302 : String,
R_304 : String,
R_4XX : String,
R_404 : String,
OFFLOADED_HITS : String,
ORIGIN_HITS : String,
ORIGIN_VOLUME : String,
MT : String,
Project: String
});
mongoose.model('AkamaiLog', AkamaiSchema);
|
JavaScript
| 0 |
@@ -190,22 +190,22 @@
iated :
-String
+Number
,%0D%0A%09EDGE
@@ -210,30 +210,30 @@
GE_VOLUME :
-String
+Number
,%0D%0A%09OK_EDGE_
@@ -237,30 +237,30 @@
GE_VOLUME :
-String
+Number
,%0D%0A%09ERROR_ED
@@ -267,30 +267,30 @@
GE_VOLUME :
-String
+Number
,%0D%0A%09EDGE_HIT
@@ -289,30 +289,30 @@
EDGE_HITS :
-String
+Number
,%0D%0A%09OK_EDGE_
@@ -314,30 +314,30 @@
EDGE_HITS :
-String
+Number
,%0D%0A%09ERROR_ED
@@ -342,30 +342,30 @@
EDGE_HITS :
-String
+Number
,%0D%0A%09R_0XX :
@@ -360,30 +360,30 @@
,%0D%0A%09R_0XX :
-String
+Number
,%0D%0A%09R_2XX :
@@ -378,30 +378,30 @@
,%0D%0A%09R_2XX :
-String
+Number
,%0D%0A%09R_200 :
@@ -400,22 +400,22 @@
R_200 :
-String
+Number
,%0D%0A%09R_20
@@ -418,22 +418,22 @@
R_206 :
-String
+Number
,%0D%0A%09R_3X
@@ -432,30 +432,30 @@
,%0D%0A%09R_3XX :
-String
+Number
,%0D%0A%09R_302 :
@@ -454,22 +454,22 @@
R_302 :
-String
+Number
,%0D%0A%09R_30
@@ -468,30 +468,30 @@
,%0D%0A%09R_304 :
-String
+Number
,%0D%0A%09R_4XX :
@@ -490,22 +490,22 @@
R_4XX :
-String
+Number
,%0D%0A%09R_40
@@ -508,22 +508,22 @@
R_404 :
-String
+Number
,%0D%0A%09OFFL
@@ -527,38 +527,38 @@
FFLOADED_HITS :
-String
+Number
,%0D%0A%09ORIGIN_HITS
@@ -559,22 +559,22 @@
_HITS :
-String
+Number
,%0D%0A%09ORIG
@@ -585,22 +585,22 @@
OLUME :
-String
+Number
,%0D%0A%09MT :
|
f8e13c372e12cd0ca6b6292116376bdece63eb81
|
use channel.id?
|
modules/checkforcode.js
|
modules/checkforcode.js
|
/*
Systematically search through Discord comments to find unformatted Code.
* Look for lines ending in ;
* Look for lines ending in )
* Look for lines ending in { or }
* If found, Locate the first Code Block Line
* If found, Locate the last Code Block Line
* RePost the message surrounded by ```csharp ```
EXAMPLE
```csharp
using UnityEngine;
/// <summary>
/// Class for holding Navigation variables. Used for the main game
/// logic by PlayerNavigate to
/// </summary>
public class ChangeDirection
{
/// <summary> The angle by which we should rotate. </summary>
public float newAngle;
/// <summary> The time at which we should change direction.</summary>
public float changeTime;
public ChangeDirection(float _newAngle, float _changeTime)
{
this.newAngle = _newAngle;
this.changeTime = _changeTime;
}
}
```
*/
// Import the discord.js module
const Discord = require('discord.js');
// Guess this was for name and whatnot
const Confax = require('../bot.js')
// This is the bot
const bot = Confax.bot
// Prob dont need config
const config = Confax.config
var isFormatted = false
var totalLinesOfCode = 0
var originalLines = []
var lines = []
var codeLines = []
// Create an event listener for messages to parse
bot.on('message', message => {
if (message.author.bot){
//console.log("This is a bot message :D")
return
}
if(message.content.length > 1900){
return
}
isFormatted = false
totalLinesOfCode = 0;
lines = message.content.split('\n')
originalLines = message.content.split('\n')
checkMessageForCode(lines)
if(isBadCode() && !isFormatted){
let firstLine = Math.min.apply(Math, codeLines)
console.log(firstLine)
let lastLine = Math.max.apply(Math, codeLines) + 2
console.log(lastLine)
originalLines.splice(firstLine, 0, '```csharp\n')
originalLines.splice(lastLine, 0, '\n```\n')
let strmessage = ""
for (let j = 0; j < originalLines.length; j++){
strmessage += originalLines[j]+'\n'
}
let channel = message.guild.channels.find("name", "programing_help")
if(channel != null && channel != message.channel){
message.channel.send('`Your unformatted code has been formatted and moved to`' + channel.mention + '.\n`Which makes sense...` :doggo:')
channel.send('`I have formated your code and placed it here. Good Luck!.` :doggo:')
channel.send(strmessage);
}
else{
message.channel.send('`I see you forgot to format your code... Let me help you.` :doggo:')
//message.channel.send('```csharp\n' + message.content + '\n```')
message.channel.send(strmessage)
}
return
}
return
});
function checkMessageForCode(inputLines){
//console.log("Starting to check for code")
for(let i = 0; i < inputLines.length; i++){
let line = inputLines[i].replace(/\s"/,'')
if(line.search("```") >= 0){
//console.log("This code is A Okay!")
isFormatted = true
return
}
else{
checkLastCharacter(i, line, ';')
checkLastCharacter(i, line, '{')
checkLastCharacter(i, line, '}')
checkLastCharacter(i, line, ')')
}
}
return
}
function checkLastCharacter(index, inLine, inChar){
if(inLine.charAt(inLine.length-1).valueOf() == inChar.valueOf()){
codeLines.push(index)
//console.log(inLine)
totalLinesOfCode += 1
//console.log("Total Lines of Code: " + totalLinesOfCode)
return
}
return
}
function isBadCode(){
if (totalLinesOfCode >= 5){
//console.log("Bad code")
return true
}
else{
return false
}
}
|
JavaScript
| 0 |
@@ -2470,15 +2470,10 @@
nel.
-mention
+id
+ '
|
8876cb99b1294be0ce7f0ed9c9378e925002f550
|
Update sub.js
|
modules/commands/sub.js
|
modules/commands/sub.js
|
const Discord = require("discord.js");
const config = require('../../config.json');
const prefix = config.prefix;
const request = require('request')
const ytkey = config.youtube_api_key;
module.exports = (bot) => {
bot.addCommand("sub ", (payload) => {
var message = payload.message
var id = message.content.split(" ").slice(1).join(" ");
request("https://www.googleapis.com/youtube/v3/search?part=snippet&q="+id+"&key="+ytkey, function(err, resp, body) {
try{
var parsed = JSON.parse(body);
if(parsed.pageInfo.resultsPerPage != 0){
for(var i = 0; i < parsed.items.length; i++){
if(parsed.items[i].id.channelId) {
request("https://www.googleapis.com/youtube/v3/channels?part=statistics&id="+parsed.items[i].id.channelId+"&key="+ytkey, function(err, resp, body) {
var sub = JSON.parse(body);
if(sub.pageInfo.resultsPerPage != 0){
let embed = new Discord.RichEmbed();
embed.setColor(0x9900FF)
embed.setTitle( id + " Youtube Channel!")
embed.setURL("http://youtube.com/" + id)
embed.setThumbnail("https://www.youtube.com/yt/brand/media/image/YouTube-icon-full_color.png")
embed.addField("Name: ", parsed.items[i].snippet.channelTitle, true)
embed.addField("Subscribers: ", sub.items[0].statistics.subscriberCount, true)
embed.addField("Videos on YouTube!: ", sub.items[0].statistics.videoCount, true)
embed.addField("Active Viewer: ", sub.items[0].statistics.viewCount, true)
message.channel.send({embed});
}else message.channel.send("Nothing found");
})
break;
}
}
}else message.channel.send("Nothing found");
}catch(e){
message.channel.send(e);
}
})
})
}
|
JavaScript
| 0.000001 |
@@ -170,16 +170,24 @@
.youtube
+.youtube
_api_key
|
701f8306911fa625557fa8c0a735eec3ba0b774b
|
Add optional syncCallback argument to worker.postMessage()
|
modules/ringo/worker.js
|
modules/ringo/worker.js
|
var engine = require("ringo/engine").getRhinoEngine();
var {Semaphore: JavaSemaphore, TimeUnit} = java.util.concurrent;
export("Worker", "Semaphore");
function Worker(module) {
if (!(this instanceof Worker)) {
return new Worker(module);
}
var worker;
var self = this;
var onmessage = function(e) {
if (typeof self.onmessage === "function") {
self.onmessage(e);
}
};
var onerror = function(e) {
if (typeof self.onerror === "function") {
self.onerror(e);
}
};
this.postMessage = function(data, semaphore) {
worker = worker || engine.getWorker();
var target = {
postMessage: function(data) {
currentWorker.submit(self, onmessage, {data: data, target: self});
}
};
var currentWorker = engine.getCurrentWorker();
var event = {data: data, target: target, semaphore: semaphore};
worker.submit(self, function() {
try {
worker.invoke(module, "onmessage", event);
} catch (error) {
currentWorker.submit(self, onerror, {data: error, target: self});
} finally {
// fixme - release worker if no pending scheduled tasks;
// we want to do better than that.
if (worker.countScheduledTasks() == 0) {
engine.releaseWorker(worker);
worker = null;
}
}
});
};
this.terminate = function() {
if (worker) {
worker.terminate();
engine.releaseWorker(worker);
worker = null;
}
}
}
function Semaphore(permits) {
if (!(this instanceof Semaphore)) {
return new Semaphore(permits);
}
if (typeof permits === "undefined") permits = 0;
var s = new JavaSemaphore(permits);
this.wait = function(permits) {
if (typeof permits === "undefined") permits = 1;
s.acquire(permits);
};
this.tryWait = function(timeout, permits) {
if (typeof permits === "undefined") permits = 1;
return s.tryAcquire(permits, timeout, TimeUnit.MILLISECONDS);
};
this.signal = function(permits) {
if (typeof permits === "undefined") permits = 1;
s.release(permits);
};
}
|
JavaScript
| 0 |
@@ -593,24 +593,28 @@
(data, s
-emaphore
+yncCallbacks
) %7B%0A
@@ -648,32 +648,203 @@
ne.getWorker();%0A
+ var invokeCallback = function(callback, arg) %7B%0A if (syncCallbacks) callback(arg);%0A else currentWorker.submit(self, callback, arg);%0A %7D%0A
var targ
@@ -912,35 +912,23 @@
-currentWorker.submit(self,
+invokeCallback(
onme
@@ -1094,30 +1094,8 @@
rget
-, semaphore: semaphore
%7D;%0A
@@ -1261,35 +1261,23 @@
-currentWorker.submit(self,
+invokeCallback(
oner
|
d614747f1c241ed84146e9246a945879d9cbea6d
|
add items in features tree
|
js/autocomplete.js
|
js/autocomplete.js
|
var autocomplete = {
autocompleteTree: {
pathKey: {
empty : ['coverage', 'places', 'journeys', 'coord'],
all : ['addresses',
'commercial_modes',
'companies',
'departures',
'disruptions',
'lines',
'networks',
'physical_modes',
'places',
'places_nearby',
'poi_types',
'pois',
'route_schedule',
'routes',
'stop_areas',
'stop_points',
'stop_schedules',
'vehicles_journeys',
],
},
features: {
all: ['addresses',
'commercial_modes',
'companies',
'departures',
'disruptions',
'lines',
'networks',
'physical_modes',
'places_nearby',
'poi_types',
'pois',
'route_schedule',
'routes',
'stop_areas',
'stop_points',
'stop_schedules',
'vehicles_journeys',
'places',
]
},
paramKey: {
journeys : ['from', 'to', 'datetime', 'datetime_represents', 'traveler_type', 'forbidden_uris[]', 'data_freshness', 'count'],
places: ['q', 'type[]', 'count'],
pt_objects: ['q', 'type[]', 'count'],
}
},
addKeyAutocomplete: function(input, key) {
var source;
if (key === 'pathKey' && ! $('#pathFrame').find('.toDelete').length) {
source = this.autocompleteTree[key].empty;
} else if (key === 'paramKey'){
var feature = $('#featureInput').val();
source = this.autocompleteTree[key][feature];
source = source ? source : [];
}else {
source = this.autocompleteTree[key].all;
}
$(input).autocomplete({
source: source,
minLength: 0,
scroll: true,
delay: 500,
select: function (event, ui) {
$(input).parent().find('button.add').prop('disabled', false);
}
}).focus(function() {
$(this).autocomplete('search', '');
});
},
staticAutocompleteTypes : ['coverage',
'physical_modes',
'poi_types'
],
staticAutocomplete : function (input, staticType){
var api = $('#api input.api').attr('value');
var token = $('#token input.token').val();
var cov = getCoverage();
var request = '';
if (staticType === 'coverage') {
request = api + '/coverage/';
} else {
request = api + '/coverage/' + cov + '/' + staticType;
}
$.ajax({
headers: isUndefined(token) ? {} : { Authorization: 'Basic ' + btoa(token) },
dataType: 'json',
url: request,
success: function(data) {
var res = [];
summary(staticType, data);
staticType = (staticType==='coverage') ? 'regions' : staticType;
data[staticType].forEach(function(elt){
res.push({ value: elt.id, label: elt.name });
});
$(input).autocomplete({source: res,
minLength: 0,
scroll: true,
delay: 500
}).focus(function() {
$(input).autocomplete('search', '');
});
if ($(input).is(':focus')) {
$(input).autocomplete('search', '');
}
}
});
},
dynamicAutocompleteTypes : [
'addresses',
'administrative_regions',
'commercial_modes',
'coord',
'lines',
'networks',
'places',
'pois',
'routes',
'stop_areas',
'stop_points',
],
dynamicAutocomplete: function (elt, dynamicType) {
var formatPtReq = function (v){
return sprintf('pt_objects/?type[]=%s&q=', v);
};
var formatPlacesReq = function (v){
return sprintf('places/?type[]=%s&q=', v);
};
var dynamicTypeRequest = {
addresses:formatPlacesReq('address'),
administrative_regions: formatPlacesReq('administrative_region'),
commercial_modes: formatPtReq('commercial_mode'),
coord: formatPlacesReq('address'),
lines: formatPtReq('line'),
networks: formatPtReq('network'),
places: 'places/?&q=',
pois: formatPlacesReq('poi'),
routes: formatPtReq('route'),
stop_areas: formatPtReq('stop_area'),
stop_points: formatPlacesReq('stop_point'),
};
var httpReq = dynamicTypeRequest[dynamicType];
if (! httpReq) {
return;
}
$(elt).autocomplete({
delay: 200,
source: function (request, response) {
var token = $('#token input.token').val();
var url = $('#api input.api').val();
var cov = getCoverage();
// cov can be null in case where coverage is not specifeid
cov = cov ? ('coverage/' + cov) : '';
$.ajax({
url: sprintf('%s/%s/%s%s', url, cov, httpReq, encodeURIComponent(request.term)),
headers: isUndefined(token) ? {} : { Authorization: 'Basic ' + btoa(token) },
success: function (data) {
var res = [];
var search = null;
if ('places' in data) {
search = data.places;
}else if ('pt_objects' in data) {
search = data.pt_objects;
}
if (search) {
search.forEach(function(s) {
res.push({ value: s.id, label: s.name });
});
}
response(res);
},
error: function() {
response([]);
}
});
}
});
}
}
|
JavaScript
| 0 |
@@ -454,35 +454,36 @@
'route_schedule
+s
',%0A
-
'rou
@@ -967,16 +967,17 @@
schedule
+s
',%0A
@@ -1172,24 +1172,118 @@
paramKey: %7B%0A
+ departures : %5B'from_datetime', 'duration', 'forbidden_uris%5B%5D', 'data_freshness'%5D,%0A
@@ -1424,38 +1424,403 @@
-places: %5B'q', 'type%5B%5D', 'count
+route_schedule : %5B'from_datetime', 'duration', 'items_per_schedule', 'forbidden_uris%5B%5D', 'data_freshness'%5D,%0A stop_schedules : %5B'from_datetime', 'duration', 'items_per_schedule', 'forbidden_uris%5B%5D', 'data_freshness'%5D,%0A places_nearby : %5B'distance', 'type%5B%5D', 'admin_uri%5B%5D', 'filter'%5D,%0A places: %5B'q', 'type%5B%5D', 'count', 'admin_uri%5B%5D'%5D,%0A pois : %5B'distance
'%5D,%0A
|
7ac5f9a60307b02fb1bb1dcafd2a9ed1efd932c0
|
refactor ternary
|
js/base/Precise.js
|
js/base/Precise.js
|
'use strict'
const zero = BigInt (0)
const minusOne = BigInt (-1)
class Precise {
constructor (number, decimals = 0) {
const isBigInt = typeof number === 'bigint'
const isString = typeof number === 'string'
if (!(isBigInt || isString)) {
throw new Error ('Precise initiated with something other than a string or BN')
}
if (isBigInt) {
this.integer = number
this.decimals = decimals
} else {
if (decimals) {
throw new Error ('Cannot set decimals when initializing with a string')
}
let modifier = 0
number = number.toLowerCase ()
if (number.indexOf ('e') > -1) {
[ number, modifier ] = number.split ('e')
modifier = parseInt (modifier)
}
const decimalIndex = number.indexOf ('.')
this.decimals = (decimalIndex > -1) ? number.length - decimalIndex - 1 : 0
const integerString = number.replace ('.', '')
this.integer = BigInt (integerString)
this.decimals = this.decimals - modifier
}
this.base = 10
this.reduce ()
}
mul (other) {
// other must be another instance of Precise
const integerResult = this.integer * other.integer
return new Precise (integerResult, this.decimals + other.decimals)
}
div (other, precision = 18) {
const distance = precision - this.decimals + other.decimals
let numerator
if (distance === 0) {
numerator = this.integer
} else if (distance < 0) {
const exponent = BigInt (this.base) ** BigInt (-distance)
numerator = this.integer / exponent
} else {
const exponent = BigInt (this.base) ** BigInt (distance)
numerator = this.integer * exponent
}
const result = numerator / other.integer
return new Precise (result, precision)
}
add (other) {
if (this.decimals === other.decimals) {
const integerResult = this.integer + other.integer
return new Precise (integerResult, this.decimals)
} else {
const [ smaller, bigger ] =
(this.decimals > other.decimals) ? [ other, this ] : [ this, other ]
const exponent = bigger.decimals - smaller.decimals
const normalised = smaller.integer * (BigInt (this.base) ** BigInt (exponent))
const result = normalised + bigger.integer
return new Precise (result, bigger.decimals)
}
}
sub (other) {
const negative = new Precise (-other.integer, other.decimals)
return this.add (negative)
}
abs () {
return new Precise (this.integer < 0 ? this.integer * minusOne : this.integer, this.decimals)
}
neg () {
return new Precise (-this.integer, this.decimals)
}
reduce () {
if (this.integer === zero) {
this.decimals = 0
return this
}
const base = BigInt (this.base)
let mod = this.integer % base
while (mod === zero) {
this.integer = this.integer / base
mod = this.integer % base
this.decimals--
}
return this
}
toString () {
const sign = this.integer < 0 ? '-' : ''
const integerArray = Array.from ((this.integer < 0 ? this.integer * minusOne : this.integer).toString (this.base).padStart (this.decimals, '0'))
const index = integerArray.length - this.decimals
let item
if (index === 0) {
// if we are adding to the front
item = '0.'
} else if (this.decimals < 0) {
item = '0'.repeat (-this.decimals)
} else if (this.decimals === 0) {
item = ''
} else {
item = '.'
}
integerArray.splice (index, 0, item)
return sign + integerArray.join ('')
}
static stringMul (string1, string2) {
if ((string1 === undefined) || (string2 === undefined)) {
return undefined
}
return (new Precise (string1)).mul (new Precise (string2)).toString ()
}
static stringDiv (string1, string2, precision = 18) {
if ((string1 === undefined) || (string2 === undefined)) {
return undefined
}
return (new Precise (string1)).div (new Precise (string2), precision).toString ()
}
static stringAdd (string1, string2) {
if ((string1 === undefined) && (string2 === undefined)) {
return undefined
}
if (string1 === undefined) {
return string2
} else if (string2 === undefined) {
return string1
}
return (new Precise (string1)).add (new Precise (string2)).toString ()
}
static stringSub (string1, string2) {
if ((string1 === undefined) || (string2 === undefined)) {
return undefined
}
return (new Precise (string1)).sub (new Precise (string2)).toString ()
}
static stringAbs (string) {
if (string === undefined) {
return undefined
}
return (new Precise (string)).abs ().toString ()
}
static stringNeg (string) {
if (string === undefined) {
return undefined
}
return (new Precise (string)).neg ().toString ()
}
}
module.exports = Precise;
|
JavaScript
| 0.999904 |
@@ -3362,149 +3362,244 @@
-cons
+le
t sign
- = this.integer %3C 0 ? '-' : ''%0A const integerArray = Array.from ((this.integer %3C 0 ? this.integer * minusOne : this.integer)
+%0A let abs%0A if (this.integer %3C 0) %7B%0A sign = '-'%0A abs = -this.integer%0A %7D else %7B%0A sign = ''%0A abs = this.integer%0A %7D%0A const integerArray = Array.from (abs
.toS
|
44f6ae48c51898202ffc53453c787d8d59a5c87d
|
fix typo in Link response header
|
ldp.js
|
ldp.js
|
/*jshint node:true*/
// ldp.js
// This file contains the server side JavaScript code for your application.
// This sample application uses express as web application framework (http://expressjs.com/),
// and jade as template engine (http://jade-lang.com/).
var express = require('express');
var rdfstore = require('rdfstore');
// setup middleware
var app = express();
app.set('view engine', 'jade');
app.set('views', __dirname + '/views'); //optional since express defaults to CWD/views
// setup rdfstore/mongo
var storage='mongodb';
var store;
if (storage === 'mongodb') {
store = new rdfstore.Store({persistent:true,
engine:'mongodb',
name:'ldpjs',
overwrite:false,
mongoDomain:'localhost',
mongoPort:27017
}, function(ldpjsDB){
store = ldpjsDB;
});
} else {
store = rdfstore.create();
}
app.use(function(err, req, res, next){
console.error(err.stack);
res.send(500, 'Something broke!');
});
app.route('/resources/*')
.all(function(req, res, next) {
res.links({
type: '<http://www.w3.org/ns/ldp#Resource'
});
next();
})
.get(function(req, res, next) {
res.send('GET ' + req.path);
})
.put(function(req, res, next) {
res.send('PUT ' + req.path);
})
.post(function(req, res, next) {
res.send('POST ' + req.path);
})
.delete(function(req, res, next) {
res.send('DELETE ' + req.path);
});
// render index page
app.get('/', function(req, res){
res.render('index');
});
// There are many useful environment variables available in process.env.
// VCAP_APPLICATION contains useful information about a deployed application.
var appInfo = JSON.parse(process.env.VCAP_APPLICATION || "{}");
// TODO: Get application information and use it in your app.
// VCAP_SERVICES contains all the credentials of services bound to
// this application. For details of its content, please refer to
// the document or sample of each service.
var services = JSON.parse(process.env.VCAP_SERVICES || "{}");
// TODO: Get service credentials and communicate with bluemix services.
// The IP address of the Cloud Foundry DEA (Droplet Execution Agent) that hosts this application:
var host = (process.env.VCAP_APP_HOST || 'localhost');
// The port on the DEA for communication with the application:
var port = (process.env.VCAP_APP_PORT || 3000);
// Start server
app.listen(port, host);
console.log('App started on port ' + port);
|
JavaScript
| 0.00004 |
@@ -1156,9 +1156,8 @@
e: '
-%3C
http
|
05135bb205993c55da3edc8354fa2b49c5bf3c39
|
Fix issue #127, reset button does not persist accurately
|
js/editable-css.js
|
js/editable-css.js
|
(function(global) {
var exampleChoiceList = document.getElementById('example-choice-list');
var exampleChoices = exampleChoiceList.querySelectorAll('.example-choice');
var header = document.querySelector('header');
var initialChoice = 0;
var originalChoices = [];
var output = document.getElementById('output');
var CSSEditorUtils = {
applyCode: function(code, choice, targetElement) {
// http://regexr.com/3fvik
var cssCommentsMatch = /(\/\*)[\s\S]+(\*\/)/g;
var element =
targetElement || document.getElementById('example-element');
// strip out any CSS comments before applying the code
code.replace(cssCommentsMatch, '');
element.style.cssText = code;
if (!element.style.cssText) {
choice.classList.add('invalid');
} else {
choice.classList.remove('invalid');
}
}
};
function choose(choice) {
var codeBlock = choice.querySelector('pre');
choice.classList.add('selected');
/* If the newly chosen example is in an invalid state,
ensure that the reset buttton is visible */
if (choice.classList.contains('invalid')) {
window.mceUtils.toggleReset(choice);
}
codeBlock.setAttribute('contentEditable', true);
codeBlock.setAttribute('spellcheck', false);
codeBlock.focus();
CSSEditorUtils.applyCode(choice.textContent, choice);
}
function copyTextOnly(e) {
var selection = window.getSelection();
var range = selection.getRangeAt(0);
e.clipboardData.setData('text/plain', range.toString());
e.clipboardData.setData('text/html', range.toString());
e.preventDefault();
e.stopPropagation();
}
/**
* Enables and initializes the live code editor
*/
function enableLiveEditor() {
header.classList.remove('hidden');
exampleChoiceList.classList.add('live');
output.classList.remove('hidden');
document.addEventListener('cut', copyTextOnly);
document.addEventListener('copy', copyTextOnly);
for (let i = 0, l = exampleChoices.length; i < l; i++) {
var exampleChoice = exampleChoices[i];
var resetButton = exampleChoice.querySelector('.reset');
originalChoices.push(
exampleChoice.querySelector('code').textContent
);
if (exampleChoice.getAttribute('initial-choice')) {
initialChoice = indexOf(exampleChoices, exampleChoice);
}
exampleChoice.addEventListener('click', onChoose);
exampleChoice.addEventListener('keyup', onEdit);
resetButton.addEventListener('click', function(e) {
var choice = e.target.parentNode;
var replacementText =
originalChoices[indexOf(exampleChoices, choice)];
var highlighted = Prism.highlight(
replacementText,
Prism.languages.css
);
exampleChoices[i].classList.remove('invalid');
mceUtils.toggleReset(exampleChoices[i]);
choice.querySelector('pre').innerHTML = highlighted;
});
}
}
function indexOf(exampleChoices, choice) {
for (var i = 0, l = exampleChoices.length; i < l; i++) {
if (exampleChoices[i] === choice) {
return i;
}
}
return -1;
}
function onChoose(e) {
var selected = document.querySelector('.selected');
// highlght the code we are leaving
if (selected && e.currentTarget !== selected) {
var highlighted = Prism.highlight(
selected.firstChild.textContent,
Prism.languages.css
);
selected.firstChild.innerHTML = highlighted;
mceAnalytics.trackCSSExampleSelection();
resetDefault();
choose(e.currentTarget);
}
}
function onEdit(e) {
CSSEditorUtils.applyCode(e.currentTarget.textContent, e.currentTarget);
}
/**
* Resets the default example to visible but, only if it is currently hidden
*/
function resetDefault() {
var defaultExample = document.getElementById('default-example');
// only reset to default if the default example is hidden
if (defaultExample.classList.value.indexOf('hidden') > -1) {
var sections = output.querySelectorAll('section');
// loop over all sections and set to hidden
for (var i = 0, l = sections.length; i < l; i++) {
sections[i].classList.add('hidden');
sections[i].setAttribute('aria-hidden', true);
}
// show the default example
defaultExample.classList.remove('hidden');
defaultExample.setAttribute('aria-hidden', false);
}
resetUIState();
}
/**
* Resets the UI state by deselcting all example choice, and
* hiding all reset buttons.
*/
function resetUIState() {
var resetButtons = exampleChoiceList.querySelectorAll('.reset');
for (var resetButton of resetButtons) {
resetButton.classList.add('hidden');
resetButton.classList.remove('fade-in');
resetButton.setAttribute('aria-hidden', true);
}
for (var exampleChoice of exampleChoices) {
exampleChoice.classList.remove('selected');
}
}
// only show the live code view if JS is enabled and the property is supported
if (mceUtils.isPropertySupported(exampleChoiceList.dataset['property'])) {
enableLiveEditor();
choose(exampleChoices[initialChoice]);
}
global.cssEditorUtils = CSSEditorUtils;
})(window);
|
JavaScript
| 0 |
@@ -1052,24 +1052,163 @@
tor('pre');%0A
+ var currentChoiceText = choice.textContent.trim();%0A var originalChoice = originalChoices%5BindexOf(exampleChoices, choice)%5D;%0A%0A
choi
@@ -1300,27 +1300,76 @@
d state,
-%0A
+ or the code%0A does not match the original example,
ensure
@@ -1390,16 +1390,27 @@
buttton
+%0A
is visi
@@ -1428,16 +1428,29 @@
if (
+%0A
choice.c
@@ -1477,16 +1477,77 @@
nvalid')
+ %7C%7C%0A currentChoiceText !== originalChoice%0A
) %7B%0A
|
64e39ac713a2b22ba52b87fbecfc7cd600226b20
|
add data to report
|
lib.js
|
lib.js
|
// this is a proof of concept implementation of a code duplication finder
// that will find the highest threshold and create an array of reports.
//
// using https://github.com/danielstjules/jsinspect to find duplicated code
const child_process = require("child_process")
var results = []
function inspector(file, threshold, callback) {
// TODO: switch from exec to code use of the jsinspect package.
// this was the fastest way to build this proof of concept demo
var command = `./node_modules/.bin/jsinspect -t ${threshold} -r json ${file}`
child_process.exec(command, (err, stdout, stderr) => {
var result = JSON.parse(stdout)
if (result.length === 0) {
var report = {
highestThreshold: 0,
result: null
}
if (results.length !== 0) {
report.highestThreshold = threshold-1
report.result = results[results.length-1].data
// report.data = resultsm // add all reports to the returned data
}
callback(report)
} else {
results.push({threshold: threshold, data: result})
inspector(file, threshold+1, callback)
}
})
}
module.exports = inspector
|
JavaScript
| 0 |
@@ -333,16 +333,72 @@
back) %7B%0A
+ // console.log('inspect with threshold', threshold);%0A%0A
// TOD
@@ -947,19 +947,16 @@
%0A
- //
report.
@@ -969,17 +969,16 @@
results
-m
// add
|
5ed5968b767357ab31a8b8bb6604dc04ede3286c
|
fix reverting tag values
|
js/id/ui/preset.js
|
js/id/ui/preset.js
|
iD.ui.preset = function(context, entity, preset) {
var original = context.graph().base().entities[entity.id],
event = d3.dispatch('change', 'close'),
fields = [],
tags = {},
formwrap,
formbuttonwrap;
function UIField(field, show) {
field = _.clone(field);
field.input = iD.ui.preset[field.type](field, context)
.on('close', event.close)
.on('change', event.change);
field.reference = iD.ui.TagReference(entity, {key: field.key});
if (field.type === 'address' ||
field.type === 'wikipedia' ||
field.type === 'maxspeed') {
field.input.entity(entity);
}
field.keys = field.keys || [field.key];
field.show = show;
field.shown = function() {
return field.id === 'name' || field.show || _.any(field.keys, function(key) { return !!tags[key]; });
};
field.modified = function() {
return _.any(field.keys, function(key) {
return original ? tags[key] !== original.tags[key] : tags[key];
});
};
return field;
}
fields.push(UIField(context.presets().field('name')));
var geometry = entity.geometry(context.graph());
preset.fields.forEach(function(field) {
if (field.matchGeometry(geometry)) {
fields.push(UIField(field, true));
}
});
context.presets().universal().forEach(function(field) {
if (preset.fields.indexOf(field) < 0) {
fields.push(UIField(field));
}
});
function fieldKey(field) {
return field.id;
}
function shown() {
return fields.filter(function(field) { return field.shown(); });
}
function notShown() {
return fields.filter(function(field) { return !field.shown(); });
}
function show(field) {
field.show = true;
render();
field.input.focus();
}
function revert(field) {
d3.event.stopPropagation();
d3.event.preventDefault();
var t = {};
field.keys.forEach(function(key) {
t[key] = original ? original.tags[key] : undefined;
});
event.change(t);
}
function toggleReference(field) {
d3.event.stopPropagation();
d3.event.preventDefault();
_.forEach(shown(), function(other) {
if (other.id === field.id) {
other.reference.toggle();
} else {
other.reference.hide();
}
});
render();
}
function render() {
var selection = formwrap.selectAll('.form-field')
.data(shown(), fieldKey);
var enter = selection.enter()
.insert('div', '.more-buttons')
.style('opacity', 0)
.attr('class', function(field) {
return 'form-field form-field-' + field.id + ' fillL col12';
});
enter.transition()
.style('max-height', '0px')
.style('padding-top', '0px')
.style('opacity', '0')
.transition()
.duration(200)
.style('padding-top', '20px')
.style('max-height', '240px')
.style('opacity', '1')
.each('end', function(d) {
d3.select(this).style('max-height', '');
});
var label = enter.append('label')
.attr('class', 'form-label')
.attr('for', function(field) { return 'preset-input-' + field.id; })
.text(function(field) { return field.label(); });
label.append('button')
.attr('class', 'tag-reference-button minor')
.attr('tabindex', -1)
.on('click', toggleReference)
.append('span')
.attr('class', 'icon inspect');
label.append('button')
.attr('class', 'modified-icon minor')
.attr('tabindex', -1)
.on('click', revert)
.append('div')
.attr('class','icon undo');
enter.each(function(field) {
d3.select(this)
.call(field.input)
.call(field.reference);
});
selection
.each(function(field) {
field.input.tags(tags);
})
.classed('modified', function(field) {
return field.modified();
});
selection.exit()
.remove();
var addFields = formbuttonwrap.selectAll('.preset-add-field')
.data(notShown(), fieldKey);
addFields.enter()
.append('button')
.attr('class', 'preset-add-field')
.on('click', show)
.call(bootstrap.tooltip()
.placement('top')
.title(function(d) { return d.label(); }))
.append('span')
.attr('class', function(d) { return 'icon ' + d.icon; });
addFields.exit()
.transition()
.style('opacity', 0)
.remove();
return selection;
}
function presets(selection) {
selection.html('');
formwrap = selection;
formbuttonwrap = selection.append('div')
.attr('class', 'col12 more-buttons inspector-inner');
render();
}
presets.rendered = function() {
return _.flatten(shown().map(function(field) { return field.keys; }));
};
presets.preset = function(_) {
if (!arguments.length) return preset;
preset = _;
return presets;
};
presets.change = function(_) {
tags = _;
render();
return presets;
};
return d3.rebind(presets, event, 'on');
};
|
JavaScript
| 0 |
@@ -2198,19 +2198,18 @@
ey%5D
-: undefined
+%7C%7C '' : ''
;%0A
|
16804b22e67bebf64670f3b1dde3703fe0b77003
|
Update English.js
|
js/lang/English.js
|
js/lang/English.js
|
const language = {
"unknown_error" : "Unknown error from server",
"newJoin" : "%nick joined the channel",
"onTitle" : "Title: %title",
"op" : "Set op to %nick",
"voice" : "Set voice to %nick",
"deop" : "Removed op from %nick",
"devoice" : "Removed voice from %nick",
"kick" : "Kick",
"ban" : "Ban",
"inaktiv" : "%nick is now inaktiv",
"uninaktiv" : "%nick is no longer inaktiv",
"myLeave" : "You leave %channel",
"onLeave" : "%nick leave the channel",
"writeConsole" : "You can`t write in the console",
"updateNick" : "%old change nick to %new",
"onAvatar" : "You avatar is now updated",
"changeNick" : "Change nick",
"writeNick" : "Write you new nick",
"onIgnore" : "You are now ignore %nick",
"onUnignore" : "You dont ignore %nick any longer",
"onKick" : "%nick kicked %kicked: %message",
"myKick" : "%nick kicked you out of %channel: %message",
"ban" : "%nick is now banned from the channel",
"unban" : "%nick is no longer bannet from the channel",
"noPlugin" : "There are 0 plugin",
"pluginlist" : "Plugin list: ",
"error" : {
"invalidJoin" : "You typed a invalid join command",
"joinBan" : "You are banned from the channel",
"isMember" : "You are allredy member of the channel",
"unknownModePrefix" : "Unknown prefix on mode",
"nickShort" : "Nick length is to short",
"nickLong" : "Nick length is to long",
"invaldNick" : "Nick is invalid",
"unkownCommand" : "Unkown command",
"flood" : "You has typed message to fast. Please wait",
"isIgnore" : "You are allready ignore the user",
"invalidMsg" : "The msg command was not correct",
"unknownUser" : "Unknown user",
"invalidIgnore" : "Invalid ignore command",
"notIgnore" : "You don`t ignore the user",
"invalidUnignore" : "Invalid unignore command",
"accessDeniad" : "Access denaid",
"invalidKick" : "Invalid kick kommand",
"invalidMode" : "Invalid mode command",
"unknownPlugin" : "Unknown plugin",
"pluginInstalled" : "The plugin is allready installed",
"pluginNotInstalled" : "The plugin is not installed"
}
};
|
JavaScript
| 0.000002 |
@@ -29,16 +29,18 @@
n_error%22
+
: %22Unkn
@@ -73,32 +73,34 @@
%22newJoin%22
+
: %22%25nick joined
@@ -127,24 +127,26 @@
itle%22
+
+
: %22Title: %25t
@@ -158,16 +158,18 @@
,%0A %22op%22
+
@@ -198,24 +198,26 @@
%22,%0A %22voice%22
+
: %22
@@ -251,24 +251,26 @@
p%22
+
: %22Removed o
@@ -291,24 +291,26 @@
%0A %22devoice%22
+
: %22Re
@@ -352,16 +352,18 @@
+
+
: %22Kick%22
@@ -363,32 +363,34 @@
%22Kick%22,%0A %22ban%22
+
: %22Ba
@@ -403,32 +403,34 @@
%22inaktiv%22
+
+
: %22%25nick is now
@@ -448,24 +448,26 @@
%22uninaktiv%22
+
: %22%25nic
@@ -498,24 +498,26 @@
%0A %22myLeave%22
+
: %22Yo
@@ -545,32 +545,34 @@
%22onLeave%22
+
: %22%25nick leave t
@@ -600,16 +600,18 @@
Console%22
+
: %22You
@@ -654,24 +654,26 @@
ateNick%22
+
+
: %22%25old chan
@@ -702,16 +702,18 @@
nAvatar%22
+
:
@@ -751,24 +751,26 @@
%22changeNick%22
+
: %22Chang
@@ -796,16 +796,18 @@
ck%22
+
: %22Write
@@ -830,24 +830,26 @@
%22onIgnore%22
+
: %22You
@@ -886,24 +886,26 @@
nignore%22
+
: %22You dont
@@ -940,32 +940,34 @@
%22onKick%22
+
: %22%25nick kicked
@@ -996,32 +996,34 @@
%22myKick%22
+
+
: %22%25nick kicked
@@ -1064,32 +1064,34 @@
%22ban%22
+
: %22%25nick is now
@@ -1121,24 +1121,26 @@
%22,%0A %22unban%22
+
: %22
@@ -1198,24 +1198,26 @@
lugin%22
+
: %22There are
@@ -1246,16 +1246,18 @@
ist%22
+
: %22Plugi
@@ -1267,16 +1267,116 @@
ist: %22,%0A
+ %22pluginInstalled%22 : %22Plugin is now installed%22,%0A %22pluginRemoved%22 : %22Plugin is now uninstalled%22,%0A
%22error
|
193969611510d47008e1dcba2e844c70b187dde1
|
Update action-builder.js
|
src/application/action-builder.js
|
src/application/action-builder.js
|
const dispatcher = require('../dispatcher');
const {manageResponseErrors} = require('../network/error-parsing');
const {isArray} = require('lodash/lang');
const {identity} = require('lodash/utility');
/**
* Method call before the service.
* @param {Object} config - The action builder config.
*/
function _preServiceCall({node, type, preStatus, callerId, shouldDumpStoreOnActionCall}, payload){
//There is a problem if the node is empty. //Node should be an array
let data = {};
let status = {};
const STATUS = {name: preStatus, isLoading: true};
// When there is a multi node update it should be an array.
if(isArray(node)){
node.forEach((nd)=>{
data[nd] = shouldDumpStoreOnActionCall ? null : (payload && payload[nd]) || null;
status[nd] = STATUS;
});
}else{
data[node] = shouldDumpStoreOnActionCall ? null : (payload || null);
status[node] = STATUS;
}
//Dispatch store cleaning.
dispatcher.handleViewAction({data, type, status, callerId});
}
/**
* Method call after the service call.
* @param {Object} config - Action builder config.
* @param {object} json - The data return from the service call.
*/
function _dispatchServiceResponse({node, type, status, callerId}, json){
const isMultiNode = isArray(node);
const data = isMultiNode ? json : {[node]: json};
const postStatus = {name: status, isLoading: false};
let newStatus = {};
if(isMultiNode){
node.forEach((nd)=>{newStatus[nd] = postStatus; });
}else {
newStatus[node] = postStatus;
}
dispatcher.handleServerAction({
data,
type,
status: newStatus,
callerId
});
}
/**
* The main objective of this function is to cancel the loading state on all the nodes concerned by the service call.
*/
function _dispatchFieldErrors({node, callerId}, errorResult){
const isMultiNode = isArray(node);
const data = errorResult;
const errorStatus = {
name: 'error',
isLoading: false
};
let newStatus = {};
if(isMultiNode){
node.forEach((nd)=>{newStatus[nd] = errorStatus; });
}else {
newStatus[node] = errorStatus;
}
dispatcher.handleServerAction({
data,
type: 'updateError',
status: errorStatus,
callerId
});
}
function _dispatchGlobalErrors(conf , errors){
//console.warn('NOT IMPLEMENTED', conf, errors);
}
/**
* Method call when there is an error.
* @param {object} config - The action builder configuration.
* @param {object} err - The error from the API call.
* @return {object} - The data from the manageResponseErrors function.
*/
function _errorOnCall(config, err){
const errorResult = manageResponseErrors(err, config);
_dispatchGlobalErrors(config, errorResult.globals);
_dispatchFieldErrors(config, errorResult.fields);
}
/**
* Action builder function.
* @param {object} config - The action builder configuration should contain:
* - type(:string) - Is the action an update, a load, a save.
* - preStatus(:string) The status to dispatch before the calling.
* - service(:function) The service to call for the action. Should return a Promise.
* - status(:string)} The status after the action.
* @return {function} - The build action from the configuration. This action dispatch the preStatus, call the service and dispatch the result from the server.
*/
module.exports = function actionBuilder(config = {}){
config.type = config.type || 'update';
config.preStatus = config.preStatus || 'loading';
config.shouldDumpStoreOnActionCall = config.shouldDumpStoreOnActionCall || false;
if(!config.service){
throw new Error('You need to provide a service to call');
}
if(!config.status){
throw new Error('You need to provide a status to your action');
}
if(!config.node){
throw new Error('You shoud specify the store node name impacted by the action');
}
return function actionBuilderFn(payload) {
const conf = {callerId: this._identifier, postService: identity, ...config};
const {postService} = conf;
_preServiceCall(conf, payload);
return conf.service(payload).then(postService).then((jsonData)=>{
return _dispatchServiceResponse(conf, jsonData);
}, (err) => {
_errorOnCall(conf, err);
});
};
};
|
JavaScript
| 0.000001 |
@@ -1963,16 +1963,35 @@
orResult
+ %7C%7C %7B%5Bnode%5D : null%7D
;%0A co
|
992ebfe166457a8e59d64638da77a3a2416642b0
|
bump version to 0.0.3
|
classes.js
|
classes.js
|
/*global atom, module*/
(function (atom) {
// Establish the root object
var
root = this, // 'window' or 'global'
classes = { VERSION: '0.0.2' },
previous = root.classes
;
if (typeof module !== 'undefined' && module.exports) {
module.exports = classes;
}
root.classes = classes;
classes.noConflict = function () {
root.classes = previous;
return this;
};
// Convenience methods
var isArray = Array.isArray || function (obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
};
function inArray(arr, value) {
for (var i = arr.length; --i >= 0;) {
if (arr[i] === value) {
return true;
}
}
}
function toArray(obj) {
return isArray(obj) ? obj : [obj];
}
function dedupe(list) {
var uniques = [], i = -1, item, len = list.length;
while (++i < len) {
item = list[i];
if (!inArray(uniques, item)) {
uniques.push(item);
}
}
return uniques;
}
function exposer(exposed) {
return function expose() {
for (var i = arguments.length; --i >= 0;) {
var arr = toArray(arguments[i]);
for (var j = arr.length; --j >= 0;) {
exposed[arr[j]] = true;
}
}
};
}
function resolve(exposed, prot) {
for (var p in exposed) {
if (exposed.hasOwnProperty(p) && prot.hasOwnProperty(p)) {
exposed[p] = prot[p];
}
}
return exposed;
}
function shallowCopy(item) {
var copy = {};
for (var p in item) {
if (item.hasOwnProperty(p)) {
copy[p] = item[p];
}
}
return copy;
}
// A `namespace` is the taxonomical scope within which classes are defined.
// This allows us to instanciate different sets of classes from different
// sources and avoid class-name space collisions.
classes.namespace = function () {
var a = atom.create();
function ancestors(list) {
var anc = [], i = -1, len = list.length, item;
while (++i < len) {
item = list[i];
anc = anc.concat(ancestors(a.get(item).extend));
anc.push(item);
}
return anc;
}
var me = {
// Define a class
define: function (name, extend, func) {
a.need(extend, function () {
if (a.get(name)) {
return;
}
var superNames = dedupe(ancestors(extend)), superClass,
superClasses = a.get(superNames), i, len, p, exposed = {},
superExposed, superSingleton, protoClass = {}, thisClass = {},
expose = exposer(exposed);
for (i = 0, len = superClasses.length; i < len; i++) {
superClass = superClasses[i];
superExposed = superClass.exposed;
for (p in superExposed) {
if (superExposed.hasOwnProperty(p)) {
expose(p);
}
}
superSingleton = superClass.singleton;
for (p in superSingleton) {
if (superSingleton.hasOwnProperty(p)) {
thisClass[p] = protoClass[p] = superSingleton[p];
}
}
}
func(thisClass, protoClass, expose);
expose('instance');
a.set(name, {
singleton: thisClass,
exposed: resolve(exposed, thisClass),
extend: extend
});
});
},
// Return the specified class objects. Note that classes are not
// defined until all of their prerequisites have been defined... So
// unless you *know* your classes are defined, it is safer to use
// `once()` intead.
get: function (classOrList, func) {
var classes = a.get(toArray(classOrList)), exposed = [], i = -1,
len = classes.length;
while (++i < len) {
exposed.push(classes[i] && classes[i].exposed || undefined);
}
return func ? func.apply({}, exposed) :
typeof classOrList == 'string' ? exposed[0] : exposed;
},
// Request instances of a class or classes. If provided, `func` will
// be called with the instances as args. If all the necessary classes
// have been defined, then the return value will also be the instance
// (or array of instances) requested.
instanciate: function (classOrList, func) {
var instances = [];
a.need(classOrList, function () {
a.each(classOrList, function (name, cl) {
var classNames = dedupe(ancestors(cl.extend)).concat([name]),
classDef, classDefs = a.get(classNames), p,
i = -1, len = classDefs.length, exposed = {},
instanciator, thisInstance = {}, expose = exposer(exposed);
while (++i < len) {
classDef = classDefs[i];
instanciator = classDef && classDef.singleton &&
classDef.singleton.instance;
if (instanciator) {
instanciator(thisInstance, shallowCopy(thisInstance),
expose);
}
}
instances.push(resolve(exposed, thisInstance));
});
if (func) {
func.apply({}, instances);
}
});
return (instances.length == 1) ? instances[0] : instances;
},
// Call `func` as soon as all of the specified classes have been
// defined.
once: function (classOrList, func) {
a.once(classOrList, function () {
me.get(classOrList, func);
});
}
};
return me;
};
// Set up the default namespace
var defaultNamespace = classes.namespace();
classes.define = defaultNamespace.define;
classes.get = defaultNamespace.get;
classes.instanciate = defaultNamespace.instanciate;
classes.once = defaultNamespace.once;
}(atom));
|
JavaScript
| 0.000001 |
@@ -143,9 +143,9 @@
0.0.
-2
+3
' %7D,
|
06462c96a33307bef2e7dd231774960da3e8dab3
|
test require config
|
tests/test-main.js
|
tests/test-main.js
|
var allTestFiles = [];
var TEST_REGEXP = /(spec|test)\.js$/i;
// Get a list of all the test files to include
var tests = [];
for (var file in window.__karma__.files) {
if (window.__karma__.files.hasOwnProperty(file)) {
if (TEST_REGEXP.test(file)) {
// Normalize paths to RequireJS module names.
// If you require sub-dependencies of test files to be loaded as-is (requiring file extension)
// then do not normalize the paths
var normalizedTestModule = file.replace(/^\/base\/|\.js$/g, '');
allTestFiles.push(normalizedTestModule);
}
}
}
require.config({
// Karma serves files under /base, which is the basePath from your config file
baseUrl: '/base',
paths: {
"angular": "wwwroot/lib/angular.min",
"angular-animate": "wwwroot/lib/angular-animate.min",
"angular-cookies": "wwwroot/lib/angular-cookies.min",
"angular-mocks": "bower_components/angular-mocks/angular-mocks",
"angular-route": "wwwroot/lib/angular-route.min",
"angular-sanitize": "wwwroot/lib/angular-sanitize.min",
"angular-translate": "wwwroot/lib/angular-translate.min",
"bootstrap": "wwwroot/lib/bootstrap.min",
"jquery": "wwwroot/lib/jquery.min",
"modernizr": "wwwroot/lib/modernizr"
},
shim: {
"angular": {
deps: ["jquery"],
exports: "angular"
},
"angular-animate": ["angular"],
"angular-cookies": ["angular"],
"angular-mocks": ["angular"],
"angular-route": ["angular"],
"angular-sanitize": ["angular"],
"angular-translate": ["angular"],
"bootstrap": {
deps: ["jquery"]
}
},
// dynamically load all test files
deps: allTestFiles,
// we have to kickoff jasmine, as it is asynchronous
callback: lazyStart
});
function lazyStart() {
requirejs(["angular",
"angular-animate",
"angular-cookies",
"angular-mocks",
"angular-route",
"angular-sanitize",
"angular-translate",
"bootstrap"], function() {
window.__karma__.start();
});
}
// // load angular dependencies
// requirejs([ "angular",
// "angular-animate",
// "angular-cookies",
// "angular-mocks",
// "angular-route",
// "angular-sanitize",
// "angular-translate",
// "bootstrap"], function() {
// }
// );
|
JavaScript
| 0.00001 |
@@ -1739,24 +1739,26 @@
t files%0A
+//
deps: allTes
@@ -2124,24 +2124,81 @@
nction() %7B%0A%0A
+ requirejs(allTestFiles, function() %7B%0A
@@ -2227,16 +2227,36 @@
tart();%0A
+ %7D)%0A%0A
|
2639b4bffb3e7282ae863bd58c5d3457f08efd0e
|
correct mapping of Observable methods (#20518)
|
packages/common/http/rollup.config.js
|
packages/common/http/rollup.config.js
|
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const globals = {
'@angular/core': 'ng.core',
'@angular/platform-browser': 'ng.platformBrowser',
'@angular/common': 'ng.common',
'rxjs/Observable': 'Rx',
'rxjs/Observer': 'Rx',
'rxjs/Subject': 'Rx',
'rxjs/observable/of': 'Rx.Observable.prototype',
'rxjs/operator/concatMap': 'Rx.Observable.prototype',
'rxjs/operator/filter': 'Rx.Observable.prototype',
'rxjs/operator/map': 'Rx.Observable.prototype',
};
module.exports = {
entry: '../../../dist/packages-dist/common/esm5/http.js',
dest: '../../../dist/packages-dist/common/bundles/common-http.umd.js',
format: 'umd',
exports: 'named',
amd: {id: '@angular/common/http'},
moduleName: 'ng.common.http',
external: Object.keys(globals),
globals: globals
};
|
JavaScript
| 0 |
@@ -447,26 +447,16 @@
servable
-.prototype
',%0A%0A 'r
|
552d157251e4d473b65af0031bfe90905685fe39
|
improve postcss-necsst configurability
|
packages/config/lib/postcss-necsst.js
|
packages/config/lib/postcss-necsst.js
|
'use strict';
var postcss = require('postcss');
var autoprefixer = require('autoprefixer');
var isSupported = require('caniuse-api').isSupported;
var features = [
['css-variables', 'postcss-custom-properties'],
['css-image-set', 'postcss-image-set-polyfill'],
'postcss-nesting',
'postcss-custom-media',
'postcss-media-minmax',
'postcss-custom-selectors',
['css-case-insensitive', 'postcss-attribute-case-insensitive'],
['css-rebeccapurple', 'postcss-color-rebeccapurple'],
'postcss-color-hwb',
'postcss-color-hsl',
'postcss-color-rgb',
'postcss-color-gray',
['css-rrggbbaa', 'postcss-color-hex-alpha'],
'postcss-color-function',
'postcss-font-family-system-ui',
'postcss-font-variant',
['css-all', 'css-initial-value', 'postcss-initial'],
['css-matches-pseudo', 'postcss-selector-matches'],
['css-not-sel-list', 'postcss-selector-not'],
'postcss-pseudo-class-any-link',
['wordwrap', 'postcss-replace-overflow-wrap']
];
module.exports = postcss.plugin('postcss-necsst', function (options) {
var processor = postcss();
features.forEach(function (feature) {
var conditions = [].concat(feature);
feature = conditions.pop();
if (!conditions.length || conditions.find(function (condition) {
return !isSupported(condition, options.browsers);
})) {
processor.use(require(feature)());
}
});
processor.use(
autoprefixer(options.browsers ? { browsers: options.browsers } : {})
);
return processor;
});
|
JavaScript
| 0 |
@@ -139,16 +139,52 @@
pported;
+%0Avar camelize = require('camelize');
%0A%0Avar fe
@@ -1378,16 +1378,83 @@
eature)(
+%0A options%5Bcamelize(feature.replace(/%5Epostcss-/, ''))%5D%0A
));%0A
@@ -1495,16 +1495,37 @@
refixer(
+Object.assign(%0A
options.
@@ -1570,16 +1570,50 @@
s %7D : %7B%7D
+,%0A options.autoprefixer%0A )
)%0A );%0A
|
36b4c385a0bb88a1ca03f830f70e8e3538d95c2b
|
Use a jenkins hash algorithm as it varys the hash result far more significantly for minor value changes (old hash looked too similar for strings of the same length)
|
js/rgb_password.js
|
js/rgb_password.js
|
/*
*
* RGB Password
* @author: James White
* @date: 20/11/11
*
*/
// http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/
String.prototype.hashCode = function(){
var hash = 0;
if (this.length == 0) return hash;
for (i = 0; i < this.length; i++) {
char = this.charCodeAt(i);
hash = ((hash<<5)-hash)+char;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}
// Based on http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
function hslToRgb(h, s, l){
var r, g, b;
if(s == 0){
r = g = b = l; // achromatic
}else{
function hue2rgb(p, q, t){
if(t < 0) t += 1;
if(t > 1) t -= 1;
if(t < 1/6) return p + (q - p) * 6 * t;
if(t < 1/2) return q;
if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
return p;
}
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
r = hue2rgb(p, q, h + 1/3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1/3);
}
function finalise(color) {
return Math.round(color * 255)
}
return {r:finalise(r), g:finalise(g), b:finalise(b)};
}
window.onload = function() {
var password = {
selector: document.getElementById("password"),
boxes: [
document.getElementById("one"),
document.getElementById("two"),
document.getElementById("three")
],
saturation: 0.5,
lightness: 0.5,
salts: [
2462,
3637,
7432
]
};
password.selector.onkeyup = function() {
var hashCode = password.selector.value.hashCode();
for(var i in password.boxes) {
var box = password.boxes[i];
var salt = password.salts[i];
var hue = (hashCode % salt)/salt;
var color = hslToRgb(hue, password.saturation, password.lightness);
box.style.backgroundColor = "rgb("
+ color.r + ", "
+ color.g + ", "
+ color.b +
")";
}
}
}
|
JavaScript
| 0 |
@@ -74,33 +74,65 @@
p://
-werxltd.com/wp
+findingscience.com/javascript/hashing/memcache
/2010/
-05/13
+12/28
/jav
@@ -162,77 +162,70 @@
of-j
-avas-string
+enkins
-hash
-code-method/%0AString.prototype.hashCode = function()
+.html%0Afunction jenkins_hash(key, interval_size)
%7B%0A
+
va
@@ -242,65 +242,28 @@
;%0A
-if (this.length == 0) return hash;%0A for (i = 0; i %3C this
+ for (var i=0; i%3Ckey
.len
@@ -271,19 +271,19 @@
th;
-i
++
+i
) %7B%0A
char
@@ -282,19 +282,21 @@
-char = this
+ hash += key
.cha
@@ -315,94 +315,184 @@
+
hash
++
=
-(
(hash
+
%3C%3C
-5)-hash)+char
+ 10);%0A hash %5E= (hash %3E%3E 6);%0A %7D%0A hash += (hash %3C%3C 3)
;%0A
-
hash
+%5E
=
+(
hash
-& hash; // Convert to 32bit integer%0A %7D%0A
+%3E%3E 11);%0A hash += (hash %3C%3C 15);%0A // make unsigned and modulo interval_size%0A
re
@@ -496,20 +496,44 @@
return
+(
hash
+ %3E%3E%3E 0) %25 interval_size
;%0A%7D%0A%0A//
@@ -1740,68 +1740,8 @@
) %7B%0A
- var hashCode = password.selector.value.hashCode();%0A %0A
@@ -1767,24 +1767,24 @@
rd.boxes) %7B%0A
+
var bo
@@ -1863,19 +1863,45 @@
e =
-(hashCode %25
+jenkins_hash(password.selector.value,
sal
@@ -1983,22 +1983,16 @@
tness);%0A
-
%0A b
|
d54a1edbb6491532acf30e5c1531513ac4bcdee0
|
move fn.openActive() code to fn.treemenu()
|
jquery.treemenu.js
|
jquery.treemenu.js
|
/*
treeMenu - jQuery plugin
version: 0.4.2
Copyright 2014 Stepan Krapivin
*/
(function($){
$.fn.openActive = function(activeSel) {
activeSel = activeSel || ".active";
var c = this.attr("class");
this.find(activeSel).each(function(){
var el = $(this).parent();
while (el.attr("class") !== c) {
el.find('> ul').show();
if(el.prop("tagName") === 'UL') {
el.show();
} else if (el.prop("tagName") === 'LI') {
el.removeClass('tree-closed');
el.addClass("tree-opened");
el.show();
}
el = el.parent();
}
});
return this;
}
$.fn.treemenu = function(options) {
options = options || {};
options.delay = options.delay || 0;
options.openActive = options.openActive || false;
options.closeOther = options.closeOther || false;
options.activeSelector = options.activeSelector || "";
this.addClass("treemenu");
if (!options.nonroot) {
this.addClass("treemenu-root");
}
options.nonroot = true;
this.find("> li").each(function() {
e = $(this);
var subtree = e.find('> ul');
var button = e.find('.toggler').eq(0);
if(button.length == 0) {
// create toggler
var button = $('<span>');
button.addClass('toggler');
e.prepend(button);
}
if(subtree.length > 0) {
subtree.hide();
e.addClass('tree-closed');
e.find(button).click(function() {
var li = $(this).parent('li');
if (options.closeOther && li.hasClass('tree-closed')) {
var siblings = li.parent('ul').find("li:not(.tree-empty)");
siblings.removeClass("tree-opened");
siblings.addClass("tree-closed");
siblings.removeClass(options.activeSelector);
siblings.find('> ul').slideUp(options.delay);
}
li.find('> ul').slideToggle(options.delay);
li.toggleClass('tree-opened');
li.toggleClass('tree-closed');
li.toggleClass(options.activeSelector);
});
$(this).find('> ul').treemenu(options);
} else {
$(this).addClass('tree-empty');
}
});
if (options.openActive) {
this.openActive(options.activeSelector);
}
return this;
}
})(jQuery);
|
JavaScript
| 0.000001 |
@@ -38,11 +38,9 @@
: 0.
-4.2
+6
%0A%0A C
@@ -73,17 +73,16 @@
vin%0A%0A*/%0A
-%0A
(functio
@@ -91,682 +91,8 @@
$)%7B%0A
- $.fn.openActive = function(activeSel) %7B%0A activeSel = activeSel %7C%7C %22.active%22;%0A%0A var c = this.attr(%22class%22);%0A%0A this.find(activeSel).each(function()%7B%0A var el = $(this).parent();%0A%0A while (el.attr(%22class%22) !== c) %7B%0A el.find('%3E ul').show();%0A if(el.prop(%22tagName%22) === 'UL') %7B%0A el.show();%0A %7D else if (el.prop(%22tagName%22) === 'LI') %7B%0A el.removeClass('tree-closed');%0A el.addClass(%22tree-opened%22);%0A el.show();%0A %7D%0A%0A el = el.parent();%0A %7D%0A %7D);%0A%0A return this;%0A %7D%0A%0A
@@ -312,32 +312,32 @@
Other %7C%7C false;%0A
-
options.
@@ -380,16 +380,23 @@
tor %7C%7C %22
+.active
%22;%0A%0A
@@ -2024,46 +2024,626 @@
-this.openActive(options.activeSelector
+var cls = this.attr(%22class%22);%0A%0A this.find(options.activeSelector).each(function()%7B%0A var el = $(this).parent();%0A%0A while (el.attr(%22class%22) !== cls) %7B%0A el.find('%3E ul').show();%0A if(el.prop(%22tagName%22) === 'UL') %7B%0A el.show();%0A %7D else if (el.prop(%22tagName%22) === 'LI') %7B%0A el.removeClass('tree-closed');%0A el.addClass(%22tree-opened%22);%0A el.show();%0A %7D%0A%0A el = el.parent();%0A %7D%0A %7D
);%0A
|
e177613b2ced752015f67e396b7d306a5f133d11
|
Add a way to play through a sequence of board events
|
js/screens/game.js
|
js/screens/game.js
|
import board from 'board';
import display from 'display';
var cursor = {};
function setCursor (x = 0, y = 0, selected = false) {
cursor = { x, y, selected };
}
function selectJewel (x = cursor.x, y = cursor.y) {
if (!cursor.selected) {
setCursor(x, y, true);
return;
}
var dx = Math.abs(x - cursor.x);
var dy = Math.abs(y - cursor.y);
var dist = dx + dy;
switch (dist) {
case 0:
// deselect the selected jewel
setCursor(x, y, false);
break;
case 1:
// selected an adjacent jewel: swap them
board.swap(cursor.x, cursor.y, x, y, playBoardEvents);
setCursor(x, y, false);
break;
default:
// selected a different jewel
setCursor(x, y, true);
break;
}
}
function redrawDisplay (jewels) {
display.redraw(jewels, function () {
// do nothing for now
});
}
function getBoard () {
board.getBoard(redrawDisplay);
}
function initializeDisplay () {
display.initialize(function () {
setCursor(0, 0, false);
getBoard();
});
}
export function run () {
board.initialize(initializeDisplay);
}
|
JavaScript
| 0.002545 |
@@ -70,16 +70,571 @@
= %7B%7D;%0A%0A
+function playBoardEvents (events) %7B%0A if (events.length === 0) %7B%0A redrawBoard();%0A return;%0A %7D%0A%0A var boardEvent = events.shift();%0A var next = function () %7B%0A playBoardEvents(events);%0A %7D;%0A%0A switch (boardEvent.type) %7B%0A case 'move':%0A display.moveJewels(boardEvent.data, next);%0A break;%0A case 'remove':%0A display.removeJewels(boardEvent.data, next);%0A break;%0A case 'refill':%0A display.refill(boardEvent.data, next);%0A break;%0A default:%0A next();%0A break;%0A %7D%0A%7D%0A%0A
function
@@ -1468,19 +1468,22 @@
unction
-get
+redraw
Board ()
@@ -1632,19 +1632,22 @@
-get
+redraw
Board();
|
84edd7c3fe6c2b744c92e01ef123a1d8b02e7a18
|
Add case to update state on navigation
|
src/reducers/FridgeReducer.js
|
src/reducers/FridgeReducer.js
|
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2020
*/
import moment from 'moment';
import { UIDatabase } from '../database';
import { FRIDGE_ACTIONS } from '../actions/FridgeActions';
const initialState = () => {
const sensors = UIDatabase.objects('Sensor');
const locations = UIDatabase.objects('Location');
const locationsWithASensor = sensors.length
? locations.filtered(sensors.map(({ location }) => `id == '${location.id}'`).join(' OR '))
: [];
return {
fridges: locationsWithASensor,
selectedFridge: locationsWithASensor[0],
fromDate: moment(new Date())
.subtract(30, 'd')
.toDate(),
toDate: new Date(),
};
};
export const FridgeReducer = (state = initialState(), action) => {
const { type } = action;
switch (type) {
case FRIDGE_ACTIONS.SELECT: {
const { payload } = action;
const { fridge } = payload;
return { ...state, selectedFridge: fridge };
}
case FRIDGE_ACTIONS.CHANGE_FROM_DATE: {
const { payload } = action;
const { date } = payload;
return { ...state, fromDate: date };
}
case FRIDGE_ACTIONS.CHANGE_TO_DATE: {
const { payload } = action;
const { date } = payload;
return { ...state, toDate: date };
}
default:
return state;
}
};
|
JavaScript
| 0.000001 |
@@ -189,16 +189,62 @@
ctions';
+%0Aimport %7B ROUTES %7D from '../navigation/index';
%0A%0Aconst
@@ -1305,24 +1305,212 @@
e %7D;%0A %7D%0A%0A
+ case 'Navigation/BACK':%0A case 'Navigation/NAVIGATE': %7B%0A const %7B routeName %7D = action;%0A%0A if (routeName === ROUTES.VACCINES) return initialState;%0A return state;%0A %7D%0A%0A
default:
|
96ec8ce9bd8a4367fe70efa4dcde594bb23f05bc
|
Add args test
|
tests/scripts/unit/wee-events.js
|
tests/scripts/unit/wee-events.js
|
import $ from 'wee-dom';
import $events from 'wee-events';
import { createSingleDiv, createMultiDiv, resetDOM } from '../helpers/dom';
function triggerEvent(el, type) {
if ('createEvent' in document) {
// modern browsers, IE9+
let e = document.createEvent('HTMLEvents');
e.initEvent(type, false, true);
el.dispatchEvent(e);
} else {
// IE 8
let e = document.createEventObject();
e.eventType = type;
el.fireEvent('on' + e.eventType, e);
}
}
describe('Events', () => {
describe('on', () => {
beforeEach(() => {
createSingleDiv();
createMultiDiv();
});
afterEach(resetDOM);
it('should bind a single event to a single element', () => {
$events.on('.test', 'click', () => {
$('.test')[0].style.backgroundColor = 'red';
});
triggerEvent($('.test')[0], 'click');
expect($('.test')[0].style.backgroundColor).to.equal('red');
});
it('should bind multiple events to a single element', () => {
$events.on({
'.test': {
click() {
$('.test')[0].style.backgroundColor = 'red';
},
mouseenter() {
$('.test')[0].style.backgroundColor = 'purple';
}
}
});
triggerEvent($('.test')[0], 'click');
expect($('.test')[0].style.backgroundColor).to.equal('red');
triggerEvent($('.test')[0], 'mouseenter');
expect($('.test')[0].style.backgroundColor).to.equal('purple');
});
it('should bind multiple events to multiple elements', () => {
$events.on({
'#first': {
click() {
$('#first')[0].style.backgroundColor = 'red';
},
mouseenter() {
$('#first')[0].style.backgroundColor = 'purple';
}
},
'.other-class': {
click() {
$('.other-class')[0].style.backgroundColor = 'red';
},
mouseenter() {
$('.other-class')[0].style.backgroundColor = 'purple';
}
}
});
triggerEvent($('#first')[0], 'click');
expect($('#first')[0].style.backgroundColor).to.equal('red');
triggerEvent($('#first')[0], 'mouseenter');
expect($('#first')[0].style.backgroundColor).to.equal('purple');
triggerEvent($('.other-class')[0], 'click');
expect($('.other-class')[0].style.backgroundColor).to.equal('red');
triggerEvent($('.other-class')[0], 'mouseenter');
expect($('.other-class')[0].style.backgroundColor).to.equal('purple');
});
it('should inject the event and element into the callback', () => {
$events.on('.test', 'click', (e, el) => {
expect(el.className).to.equal('test');
expect(e.type).to.equal('click');
});
triggerEvent($('.test')[0], 'click');
})
describe('once', () => {
it('should bind an event that fires only once', () => {
$events.on('.test', 'click', () => {
let bgColor = $('.test')[0].style.backgroundColor;
$('.test')[0].style.backgroundColor =
bgColor === 'red' ? 'purple' : 'red';
}, {
once: true
});
triggerEvent($('.test')[0], 'click');
triggerEvent($('.test')[0], 'click');
expect($('.test')[0].style.backgroundColor).to.equal('red');
});
});
});
});
|
JavaScript
| 0.000017 |
@@ -3076,16 +3076,319 @@
);%0A%09%09%7D);
+%0A%0A%09%09describe('args', () =%3E %7B%0A%09%09%09it('can add injected arguments', () =%3E %7B%0A%09%09%09%09$events.on('.test', 'click', (e, el, arg1, arg2) =%3E %7B%0A%09%09%09%09%09expect(arg1).to.equal('arg1');%0A%09%09%09%09%09expect(arg2).to.equal('arg2');%0A%09%09%09%09%7D, %7B%0A%09%09%09%09%09args: %5B'arg1', 'arg2'%5D%0A%09%09%09%09%7D);%0A%0A%09%09%09%09triggerEvent($('.test')%5B0%5D, 'click');%0A%09%09%09%7D);%0A%09%09%7D);
%0A%09%7D);%0A%7D)
|
5b8ea4f56acc009fbd866ac49a4eebb4bc0e9041
|
Add ability to find work
|
js/auto-puuller.js
|
js/auto-puuller.js
|
var _ = require('underscore')
, fs = require('fs')
, async = require('async')
;
module.exports = function(db, puush){
var record = function(p){
if (!p.isDeleted && !p.isPrivate) {
fs.writeFile('./db/store/' + p.md5, p.body);
}
p.tags = [];
db.insert(_.omit(p, 'body'));
return p;
};
var workQueue = async.queue(function(pid, cb){
puush.fetch(pid)
.then(record)
.then(function(){ console.log('Fetched PID:', pid); cb(); })
.catch(function(err){ console.log('Caught err:', err); cb(); });
}, 5);
var findWork = function(){
console.log('Work queue empty. Finding work to do.');
// TODO: find min/max pids, push to the queue
puush.getEnd().then(function(pid){
for (var i = 0; i < 100; i++) {
workQueue.push(pid - 500 - i);
}
});
};
workQueue.drain = findWork;
findWork();
var pause = function(){
workQueue.pause();
};
var resume = function(){
workQueue.resume();
};
return {
pause: pause,
resume: resume
};
};
|
JavaScript
| 0.000002 |
@@ -75,16 +75,50 @@
async')%0A
+ , Promise = require('bluebird')%0A
;%0A %0Am
@@ -641,32 +641,377 @@
%7D, 5);%0A %0A
+ var lastRecordedPid = function()%7B%0A return new Promise(function(resolve, reject)%7B%0A db.find(%7B%7D).sort(%7Bpid:-1%7D).limit(1).exec(function(err, rows)%7B%0A if (err) return reject(err);%0A if (!rows.length) return resolve(null);%0A resolve(rows%5B0%5D.pid);%0A %7D);%0A %7D);%0A %7D;%0A %0A
var findWork
@@ -1087,24 +1087,25 @@
do.');%0A
+%0A
// TODO:
@@ -1100,54 +1100,57 @@
-// TODO: find min/max pids, push to the queue%0A
+Promise.all(%5B%0A lastRecordedPid(),%0A
@@ -1167,21 +1167,34 @@
getEnd()
-.then
+%0A %5D).spread
(functio
@@ -1199,14 +1199,231 @@
ion(
-pid
+min, max
)%7B%0A
+ max -= 500; // we don't want the very latest, as many won't have actually finished uploading yet%0A if (!min) min = max - 500; // if we have an empty datastore, we'll need to start somewhere%0A
@@ -1447,18 +1447,20 @@
i =
-0
+min
; i %3C
-100
+max
; i+
@@ -1499,20 +1499,8 @@
ush(
-pid - 500 -
i);%0A
|
63321b7bec4768a5eca050a01ab6f18c58bf0844
|
Clean up and simplify iD.svg.Areas
|
js/id/svg/areas.js
|
js/id/svg/areas.js
|
iD.svg.Areas = function(projection) {
// Patterns only work in Firefox when set directly on element
var patterns = {
wetland: 'wetland',
beach: 'beach',
scrub: 'scrub',
construction: 'construction',
cemetery: 'cemetery',
grave_yard: 'cemetery',
meadow: 'meadow',
farm: 'farmland',
farmland: 'farmland',
orchard: 'orchard'
};
var patternKeys = ['landuse', 'natural', 'amenity'];
function setPattern(selection) {
selection.each(function(d) {
for (var i = 0; i < patternKeys.length; i++) {
if (patterns.hasOwnProperty(d.tags[patternKeys[i]])) {
this.style.fill = 'url("#pattern-' + patterns[d.tags[patternKeys[i]]] + '")';
return;
}
}
this.style.fill = '';
});
}
return function drawAreas(surface, graph, entities, filter) {
var path = d3.geo.path().projection(projection),
areas = {},
multipolygon;
for (var i = 0; i < entities.length; i++) {
var entity = entities[i];
if (entity.geometry(graph) !== 'area') continue;
if (multipolygon = iD.geo.isSimpleMultipolygonOuterMember(entity, graph)) {
areas[multipolygon.id] = {
entity: multipolygon.mergeTags(entity.tags),
area: Math.abs(path.area(entity.asGeoJSON(graph, true)))
};
} else if (!areas[entity.id]) {
areas[entity.id] = {
entity: entity,
area: Math.abs(path.area(entity.asGeoJSON(graph, true)))
};
}
}
areas = d3.values(areas);
areas.sort(function(a, b) { return b.area - a.area; });
function drawPaths(group, areas, filter, klass, closeWay) {
var tagClasses = iD.svg.TagClasses();
if (klass === 'stroke') {
tagClasses.tags(iD.svg.MultipolygonMemberTags(graph));
}
var paths = group.selectAll('path.area')
.filter(filter)
.data(areas, iD.Entity.key);
paths.enter()
.append('path')
.attr('class', function(d) { return d.type + ' area ' + klass + ' ' + d.id; });
paths
.order()
.attr('d', function(entity) { return path(entity.asGeoJSON(graph, closeWay)); })
.call(tagClasses)
.call(iD.svg.MemberClasses(graph));
if (klass === 'fill') paths.call(setPattern);
paths.exit()
.remove();
return paths;
}
areas = _.pluck(areas, 'entity');
var strokes = areas.filter(function(area) {
return area.type === 'way';
});
var shadow = surface.select('.layer-shadow'),
fill = surface.select('.layer-fill'),
stroke = surface.select('.layer-stroke');
drawPaths(shadow, strokes, filter, 'shadow');
drawPaths(fill, areas, filter, 'fill', true);
drawPaths(stroke, strokes, filter, 'stroke');
};
};
|
JavaScript
| 0.000002 |
@@ -1833,24 +1833,171 @@
a.area; %7D);
+%0A areas = _.pluck(areas, 'entity');%0A%0A var strokes = areas.filter(function(area) %7B%0A return area.type === 'way';%0A %7D);
%0A%0A fu
@@ -2017,28 +2017,13 @@
ths(
-group, areas, filter
+areas
, kl
@@ -2242,13 +2242,58 @@
s =
-group
+surface.select('.layer-' + klass)%0A
.sel
@@ -2933,309 +2933,38 @@
-areas = _.pluck(areas, 'entity');%0A%0A var strokes = areas.filter(function(area) %7B%0A return area.type === 'way';%0A %7D);%0A%0A var shadow = surface.select('.layer-shadow'),%0A fill = surface.select('.layer-fill'),%0A stroke = surface.select('.layer-stroke
+drawPaths(strokes, 'shadow
');%0A
-%0A
@@ -2982,43 +2982,28 @@
hs(s
-hadow, strokes, filter, 'shadow
+trokes, 'stroke
');%0A
+%0A
@@ -3020,28 +3020,14 @@
ths(
-fill,
areas,
- filter,
'fi
@@ -3042,62 +3042,8 @@
e);%0A
- drawPaths(stroke, strokes, filter, 'stroke');%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.