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
|
---|---|---|---|---|---|---|---|
24f64e48635f7059887cb63528da8cc4112a3e6c
|
append exception about Dooray connection
|
app.js
|
app.js
|
import express from 'express'
import bodyParser from 'body-parser'
import request from 'request'
import menubot from 'menubot'
import commitbot from 'commitbot'
import { FIREBASE_URL } from './config'
const app = express()
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())
app.route('/')
// .all(requireAuthentication)
// .get((req, res) => {
// res.send('This is Dooray Hooker!')
// })
.post([checkHookType], (req, res) => {
handleSendMessage(req.body)
})
app.use((req, res, next) => {
res.status(404).send("Sorry can't find that!")
})
app.use((err, req, res, next) => {
console.error(err.stack)
res.status(500).send('Server Error!')
})
app.listen(3030, () => {
console.log('Run to 3030 port.')
getDataTimer()
setInterval(() => {
getDataTimer()
}, 60000)
})
function getDataTimer () {
request({
uri: `${FIREBASE_URL}/data.json`,
method: 'GET'
}, (error, response, body) => {
if (error) {
console.error(error)
} else {
let count = 0
const date = new Date()
const currentTime = (date.getHours() <= 9 ? '0' : '') + date.getHours() + ':' + (date.getMinutes() <= 9 ? '0' : '') + date.getMinutes()
console.log('current time : ' + currentTime)
const res = JSON.parse(response.body)
for (const data in res) {
console.log(`setting time[ ${count++} ] : ${res[data].hookTime}, hook term: ${(res[data].hookTerm === '0') ? 'no term' : res[data].hookTerm}`)
if (checkTimeToHome(date)) {
if (currentTime === res[data].hookTime || checkHookTerm(currentTime, res[data].hookTime, res[data].hookTerm)) {
if (res[data].hookType === 'dooray-message') {
sendMessage(res[data].id, res[data].name, res[data].image, res[data].data)
} if (res[data].hookType === 'dooray-commit') {
sendTodayCommit(res[data].id, res[data].name, res[data].image, res[data].data, res[data].githubIds)
} else if (res[data].hookType === 'dooray-menu') {
sendMenu(res[data].id, res[data].name, res[data].image, res[data].hookMenuType, res[data].data)
}
}
}
}
console.log('\n=========================\n')
}
})
}
function checkTimeToHome (date) {
if (date.getHours() > 19 || date.getHours() < 10) { // Off work
console.log('<<< Today work was done. >>>')
return false
}
if (date.getDay() === 0 || date.getDay() === 6) { // weekends
console.log('<<< Today is weekends. >>>')
return false
}
return true
}
function checkHookTerm (currentTime, hookTime, hookTerm) {
const currentMin = Number(currentTime.split(':')[1])
const hookMin = Number(hookTime.split(':')[1])
const term0 = hookMin
const term1 = hookMin % 10
const term2 = (hookMin + 5) % 10
const term3 = (hookMin + 15) % 60
const term4 = (hookMin + 30) % 60
const term5 = (hookMin + 45) % 60
if (Number(hookTerm) === 5) {
if (currentMin % 10 === term1 || currentMin % 10 === term2) {
return true
}
} else if (Number(hookTerm) === 10) {
if (currentMin % 10 === term1) {
return true
}
} else if (Number(hookTerm) === 15) {
if (currentMin === term0 || currentMin === term3 ||
currentMin === term4 || currentMin === term5) {
return true
}
} else if (Number(hookTerm) === 30) {
if (currentMin === term0 || currentMin === term4) {
return true
}
} else if (Number(hookTerm) === 60) {
if (currentMin === term0) {
return true
}
}
return false
}
function checkHookType (req, res, next) {
if (req.body.hookType === 'dooray-message') {
next()
} else {
res.send('not message.')
}
}
function handleSendMessage (body) {
const hookId = body.hookId
const data = body.data
const botName = body.name
const botIconImage = body.image
sendMessage(hookId, botName, botIconImage, data)
}
function sendMessage (hookId, botName, botIconImage, data) {
request({
uri: hookId,
method: 'POST',
json: {
botName,
botIconImage,
text: data.text,
attachments: data.attachments
}
}, (error, response, body) => {
if (error) {
console.error(error)
} else {
console.log('success')
}
})
}
function sendTodayCommit (hookId, botName, botIconImage, data, githubIds) {
let result = {}
githubIds = githubIds.split(',')
Promise.all(
githubIds.map(id => {
id = id.trim()
return commitbot.checkTodayCommit(id).then(res => {
result[id] = res
})
})
).then(() => {
console.log(result)
let committers = ''
let nonecommitters = ''
for (var id in result) {
result[id] ? committers += id + ', ' : nonecommitters += id + ', '
}
committers = committers.trim().slice(0, -1)
nonecommitters = nonecommitters.trim().slice(0, -1)
if (committers) {
if (!nonecommitters) {
data.text += `\n\n${data.committer}\nToday commit users - ${committers}`
} else {
data.text += `\n\n${data.committer}\nToday commit users - ${committers}\n\n${data.nonecommitter}\nToday none commit users = ${nonecommitters}`
}
} else {
data.text += `\n\n${data.nonecommitter}\nToday none commit users = EVERYONE!!!!`
}
sendMessage(hookId, botName, botIconImage, data)
})
}
function sendMenu (hookId, botName, botIconImage, menuType, data) {
menubot.sendMenu(hookId, menuType, {
src: './img/all_menu/menu.png',
dst: './img/daily_menu/menu_part.png'
}, {
botName,
botIconImage,
attachments: [{
text: data.text
}]
})
}
|
JavaScript
| 0.00007 |
@@ -1261,45 +1261,186 @@
-const res = JSON.parse(response.body)
+let res = null%0A if (response && response.body) %7B%0A res = JSON.parse(response.body)%0A %7D else %7B%0A console.error('Connection err!')%0A return false%0A %7D
%0A
|
16ca2a5440571a1a41a5bb7e9ed917a14cc27f06
|
Remove test links
|
app.js
|
app.js
|
var express = require("express");
var req = require('request');
var async = require('async');
var bodyParser = require('body-parser');
var app = express();
var ejs = require('ejs');
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/views'));
app.use('/assets', express.static('static'));
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json())
app.get('/', function(request, response) {
var opts = {};
if (request.query.apitoken && request.query.projectid && request.query.diagramid) {
opts = { 'apitoken': request.query.apitoken, 'projectid': request.query.projectid, 'diagramid': request.query.diagramid, 'cteamid': '0', 'synthesisid': '0' };
// var baseurl = 'https://www.geodesignhub.com/api/v1/projects/';
var baseurl = 'http://local.dev:8000/api/v1/projects/';
var apikey = request.query.apitoken;
var cred = "Token " + apikey;
var projectid = request.query.projectid;
var diagramid = request.query.diagramid;
var diagramdetailurl = baseurl + projectid + '/diagrams/' + diagramid + '/';
var URLS = [diagramdetailurl];
async.map(URLS, function(url, done) {
req({
url: url,
headers: {
"Authorization": cred,
"Content-Type": "application/json"
}
}, function(err, response, body) {
if (err || response.statusCode !== 200) {
return done(err || new Error());
}
return done(null, JSON.parse(body));
});
}, function(err, results) {
var gj = JSON.stringify(results[0]['geojson']);
// console.log(gj);
if (err) return response.sendStatus(500);
// response.contentType('application/json');
// response.send({
// "status": 1,
// "results": results
// });
opts['result'] = gj;
response.render('index', opts);
});
}
if (request.query.apitoken && request.query.projectid && request.query.synthesisid && request.query.cteamid) {
opts = { 'apitoken': request.query.apitoken, 'projectid': request.query.projectid, 'synthesisid': request.query.synthesisid, 'cteamid': request.query.cteamid, 'diagramid': '0' };
// var baseurl = 'https://www.geodesignhub.com/api/v1/projects/';
var baseurl = 'http://local.dev:8000/api/v1/projects/';
var apikey = request.query.apitoken;
var cred = "Token " + apikey;
var projectid = request.query.projectid;
var cteamid = request.query.cteamid;
var synthesisid = request.query.synthesisid;
var synprojectsurl = baseurl + projectid + '/cteams/' + cteamid + '/' + synthesisid + '/projects/';
var URLS = [synprojectsurl];
async.map(URLS, function(url, done) {
req({
url: url,
headers: {
"Authorization": cred,
"Content-Type": "application/json"
}
}, function(err, response, body) {
if (err || response.statusCode !== 200) {
return done(err || new Error());
}
return done(null, JSON.parse(body));
});
}, function(err, results) {
var gj = JSON.stringify(results);
if (err) return response.sendStatus(500);
opts['result'] = gj;
response.render('index', opts);
});
} else {
opts = { 'apitoken': '0', 'projectid': '0', 'diagramid': '0', 'result': '0', 'cteamid': '0', 'synthesisid': '0' };
response.render('index', opts);
}
});
app.listen(process.env.PORT || 5001);
|
JavaScript
| 0 |
@@ -704,35 +704,32 @@
'0' %7D;%0A%0A
- //
var baseurl = '
@@ -775,32 +775,35 @@
jects/';%0A
+ //
var baseurl = '
@@ -2378,35 +2378,32 @@
'0' %7D;%0A%0A
- //
var baseurl = '
@@ -2449,32 +2449,35 @@
jects/';%0A
+ //
var baseurl = '
|
9b13eb9a3d477516a950fcd43bb32b4b10113a86
|
add guests to local storage
|
app.js
|
app.js
|
var eventInput = document.querySelector('#eventInput');
var typeEventInput = document.querySelector('#typeEventInput');
var hostInput = document.querySelector('#hostInput');
var startTimeInput = document.querySelector('#startTimeInput');
var endTimeInput = document.querySelector('#endTimeInput');
var guestInput = document.querySelector('#guestInput');
var locationInput = document.querySelector('#locationInput');
var passwordInput = document.querySelector('#passwordInput');
var confirmedPassword= document.querySelector('#passwordConfirmationInput');
var messageInput= document.querySelector('#messageInput');
var addEventButton = document.querySelector('#addEvent');
var events = [];
class Event {
constructor(name,eventType,host,startDateTime,endDateTime,guestList,location,optMessage=''){
this.name = name;
this.eventType = eventType;
this.host = host;
this.startDateTime = startDateTime;
this.endDateTime=endDateTime;
this.guestList=guestList;
this.location=location;
this.optMessage = optMessage;
}
}
addEventButton.addEventListener('click',addEvent);
var addGuestButton = document.querySelector('#addGuest');
addGuestButton.addEventListener('click',addGuest);
passwordInput.addEventListener('input',checkPassword);
confirmedPassword.addEventListener('blur',samePassword);
function addGuest(){
let formGuestLabel = document.querySelector('label[for="guestInput"]');
let guestList = document.querySelector('label[for="guestInput"] ul');
let guestName = formGuestLabel.querySelector('input').value;
let newItem = document.createElement('li');
newItem.innerHTML=guestName;
guestList.appendChild(newItem);
formGuestLabel.querySelector('input').value='';
}
function checkPassword(){
let password = this.value;
let message = '';
if(!/[a-z]/.test(password)){
message = ' Please add a lower case letter to the password.';
this.setCustomValidity(message);
}
else if(!/[A-Z]/.test(password)){
message = ' Please add a upper case letter to the password.';
this.setCustomValidity(message);
}
else if(!/[0-9]/.test(password)){
message = ' Please add a number to the password.';
this.setCustomValidity(message);
}
else if(!/[&%$*?!]/.test(password)){
message = ' Please add one of the following characters to the password: &%$*?! .';
this.setCustomValidity(message);
}
else if(!/.{10}/.test(password)){
message = ' The password should be at least 10 characters long.';
this.setCustomValidity(message);
}
else{
message='Great password!';
this.setCustomValidity('');
}
let passwordTip = document.querySelector('#passwordTip1');
passwordTip.innerHTML = message;
}
function samePassword(){
let confirmedPassword = this.value;
let passwordInput = document.querySelector('#passwordInput');
let password = passwordInput.value;
let passwordTip = document.querySelector('#passwordTip2');
let message = '';
if(confirmedPassword!==password){
message = 'The two passwords have to match.';
this.setCustomValidity(message);
}
else{
message='Passwords match!';
this.setCustomValidity('');
}
passwordTip.innerHTML = message;
}
function addEvent(){
let name = eventInput.value;
let type = typeEventInput.value;
let host = hostInput.value;
let startTime = startTimeInput.value;
let endTime = endTimeInput.value;
let guests = guestInput.value;
let location = locationInput.value;
let message = messageInput.value;
let event = new Event(name,type,host,startTime,endTime,guests,location,message);
console.log(event)
}
|
JavaScript
| 0 |
@@ -1315,16 +1315,41 @@
ord);%0A%0A%0A
+%0Avar guestListArray = %5B%5D;
%0A%0Afuncti
@@ -1726,16 +1726,49 @@
lue='';%0A
+%09guestListArray.push(guestName);%0A
%0A%0A%7D%0A%0A%0A%0A%0A
@@ -3423,27 +3423,25 @@
= guest
-Input.value
+ListArray
;%0A%09let l
@@ -3593,26 +3593,382 @@
);%0A%09
-console.log(event)
+localStorage.setItem(name,JSON.stringify(event));%0A%09%0A%09eventInput.value = '';%0A%09typeEventInput.value = '';%0A%09hostInput.value = '';%0A%09startTimeInput.value = '';%0A%09endTimeInput.value = '';%0A%09guestListArray = '';%0A%09locationInput.value = '';%0A%09messageInput.value = '';%0A%0A%09let guestList = document.querySelector('label%5Bfor=%22guestInput%22%5D ul');%0A%09guestList.innerHTML='';%0A%09guestListArray=%5B%5D;%0A%0A
%0A%7D%0A%0A
|
bf1afcc2bd58b63fe19319f370e0fa061ccfbef6
|
add robots.txt
|
app.js
|
app.js
|
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var request = require('superagent');
var session = require('express-session');
var index = require('./routes/index');
var weibo = require('./routes/weibo');
var v1 = require('./routes/v1');
// 设置与安全相关的HTTP头的中间件
var helmet = require('helmet');
// express的消息提示中间件
var flash = require('express-flash');
// 定时器
var schedule = require('node-schedule');
// 各种工具类
var dbUtils = require('./utils/dbUtils');
var bingUtils = require('./utils/bingUtils');
var mailUtils = require('./utils/mailUtils');
var qiniuUtils = require('./utils/qiniuUtils');
var weiboUtils = require('./utils/weiboUtils');
// 每天 0:30 从Bing抓取数据
schedule.scheduleJob('0 30 0 * * *', function() {
bingUtils.fetchPicture({}, function(data) {
dbUtils.set('bing', data, function(rows) {
data.id = rows.insertId || 0;
mailUtils.send({
message: '从Bing抓取成功',
title: '从Bing抓取成功',
stack: JSON.stringify(data, '', 4)
});
})
});
});
// 每天 6:30,9:30,12:30,15:30,18:30 定时发送微博
schedule.scheduleJob('0 30 6,9,12,15,18 * * *', function() {
weiboUtils.update(function(data) {
if (data && data.id) {
mailUtils.send({
message: '发送微博成功',
title: '发送微博成功',
stack: JSON.stringify(data, '', 4)
});
} else {
mailUtils.send({
message: '发送微博失败',
title: '发送微博失败',
stack: JSON.stringify(data, '', 4)
});
}
}, true);
});
// 每隔十分钟检查数据库中是否存在未上传到骑牛的图片,如果存在则上传图片到骑牛
schedule.scheduleJob('0 0,10,20,30,40,50 * * * *', function() {
dbUtils.get('bing', 'ISNULL(qiniu_url) || qiniu_url=""', function(rows) {
if (rows.length > 0) {
var data = rows[0];
var url = data.url;
qiniuUtils.fetchToQiniu(url, function() {
var _temp = url.substr(url.lastIndexOf('/') + 1, url.length);
var qiniu_url = _temp.substr(0, _temp.lastIndexOf('_'));
dbUtils.update('bing', {
body: {
qiniu_url: qiniu_url
},
condition: {
id: data.id
}
}, function(rs) {
console.log(rs);
});
});
}
});
})
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.enable('trust proxy');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser('bing.ioliu.cn'));
app.use(session({
secret: 'bing app', //secret的值建议使用随机字符串
cookie: {
secure: true,
maxAge: 60 * 30 * 1000 // 过期时间(毫秒)
},
resave: false
}));
// 设置日志
app.use(logger('combined', {
skip: function(req, res) { return res.statusCode < 400 }
}));
// 启用 helmet
app.use(helmet());
app.use(flash());
//sass
//app.use(sassMiddleware({
// src: __dirname
// , dest: __dirname
// , sourceMap: false
// , outputStyle: 'compressed'
// , debug: true
//}));
app.use('/static', express.static(path.join(__dirname, 'static')));
app.use(favicon(__dirname + '/static/images/bing.ico'));
app.use('/', index);
app.use('/weibo', weibo);
app.use('/v1', v1);
/**
* Robots.txt
*/
app.use('/robots.txt', function(req, res, next) {
res.header('content-type', 'text/plain');
res.send('User-Agent: * \n\r Allow: /');
});
app.get('/test', function(req, res, next) {
var images = [];
bingUtils.fetchPicture(function(data) {
dbUtils.get('bing', data, function(data) {
res.send(data);
});
});
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('啊( ⊙ o ⊙ ),你发现了新大陆 ∑(っ °Д °;)っ');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
|
JavaScript
| 0.000001 |
@@ -3824,11 +3824,8 @@
* %5Cn
-%5Cr
Allo
|
ed30becc07e45083dfb16a51bced79aff6d57a0e
|
update app and use list as index static route
|
app.js
|
app.js
|
var express = require('express');
var app = express();
app.use(express.compress());
app.use(express.static(__dirname + '/public'));
app.listen(process.env.PORT || 3000);
|
JavaScript
| 0 |
@@ -1,12 +1,55 @@
+%0A/**%0A * material demo%0A * @type %7B%5Btype%5D%7D%0A */
%0Avar express
@@ -163,14 +163,12 @@
+ '/
-public
+dist
'));
|
3f9de041e77fe460d729c42a00707e92a5669290
|
remove some messages
|
app.js
|
app.js
|
import express from 'express';
import bodyParser from 'body-parser';
import EnvConfig from './env.config.json';
import { Logger, postMessage, parseCommand, Constants } from './lib';
import { executeCommand, helpOptions } from './command';
const logger = Logger('app.js');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const receivedMessage = (event) => {
logger.info('Message data', event);
parseCommand(event.message.text)
.then(executeCommand)
.then(({ response }) => postMessage(event.sender.id, response))
.catch((error) => {
switch (error.message || error) {
case Constants.INVALID_COMMAND:
case Constants.INVALID_INPUT:
return postMessage(event.sender.id, helpOptions.messages);
case Constants.NO_SUCH_TRAINEE:
return postMessage(event.sender.id, '找不到這個學員');
case Constants.COMMAND_FAILED:
default:
return postMessage(event.sender.id, error.stack);
}
});
};
app.get('/privacy', (req, res) => {
res.status(200).send('我們收集你提供給機器人的資訊、並只提供台大救生班內部管理使用。').end();
});
app.get('/webhook', (req, res) => {
if (req.query['hub.verify_token'] === EnvConfig.Facebook.webhookToken) {
res.send(req.query['hub.challenge']);
} else {
res.send('Error, wrong validation token');
}
});
app.post('/webhook', (req, res) => {
const data = req.body;
logger.info('got webhook data', data);
// Make sure this is a page subscription
if (data.object === 'page') {
// Iterate over each entry - there may be multiple if batched
data.entry.forEach((entry) => {
// const pageID = entry.id;
// const timeOfEvent = entry.time;
// Iterate over each messaging event
entry.messaging.forEach((event) => {
if (event.message) {
receivedMessage(event);
} else {
logger.info('Webhook received unknown event', event);
}
});
});
// Assume all went well.
//
// You must send back a 200, within 20 seconds, to let us know
// you've successfully received the callback. Otherwise, the request
// will time out and we will keep trying to resend.
res.sendStatus(200);
}
});
app.get('/', (req, res) => {
res.status(200).send('歡迎來到漢堡王!').end();
});
// Start the server
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
logger.info(`App listening on port ${PORT}`);
});
|
JavaScript
| 0.000003 |
@@ -1387,49 +1387,8 @@
ody;
-%0A logger.info('got webhook data', data);
%0A%0A
|
6b5758303844acff0787cfe77142618c8c0338a1
|
add json lookup mechanism
|
app.js
|
app.js
|
// Copyright 2016, Google, Inc.
// Licensed under the Apache License, Version 2.0 (the 'License');
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
'use strict';
process.env.DEBUG = 'actions-on-google:*';
let Assistant = require('actions-on-google').ApiAiAssistant;
let express = require('express');
let bodyParser = require('body-parser');
let app = express();
app.use(bodyParser.json({type: 'application/json'}));
const CONFIRM_TYPE_CONTEXT = 'confirm_type';
const CLIENT_CODE_ACTION = 'get_client_code';
const EXPENSES_TYPE_ACTION = 'ask_expenses_or_services';
const EXPENSES_TYPE_ARGUMENT = 'codetype';
const CLIENT_NAME_ARGUMENT = 'clientname';
var data = {
"BioTeSys" : {
"ExpenseCode": "1 1",
"ServiceCode": "2 2"
}
};
app.post('/', function (req, res) {
const assistant = new Assistant({request: req, response: res});
console.log('Request headers: ' + JSON.stringify(req.headers));
console.log('Request body: ' + JSON.stringify(req.body));
function askExpensesOrServices(assistant){
let name = assistant.getArgument(CLIENT_NAME_ARGUMENT);
assistant.setContext(CONFIRM_TYPE_CONTEXT);
assistant.data.clientName = name;
assistant.ask('You asked about ' + name + '. Do you need an expenses or services code?');
}
function getClientCode (assistant) {
let type = assistant.getArgument(EXPENSES_TYPE_ARGUMENT);
let name = assistant.data.clientName;
var key = name;
var clientNameKeyIndex = data[key];
let code = clientNameKeyIndex.ExpenseCode;
assistant.tell('The ' + type + ' code for ' + name + ' is ' + code + '.');
//assistant.tell('I\'ll try to get the ' + assitant.data.clientName + ' ' + type + ' code.');
/*if (name === 'CRS'){
assistant.tell('The CRS services code is 1 2 5 0 0 0 2 3');
}
else{
assistant.ask ('Sorry, I dont know any ' + name + ' client codes. Try again.');*/
}
let actionMap = new Map();
actionMap.set(CLIENT_CODE_ACTION, getClientCode);
actionMap.set(EXPENSES_TYPE_ACTION, askExpensesOrServices);
assistant.handleRequest(actionMap);
});
if (module === require.main) {
// [START server]
// Start the server
let server = app.listen(process.env.PORT || 8080, function () {
let port = server.address().port;
console.log('App listening on port %s', port);
});
// [END server]
}
module.exports = app;
|
JavaScript
| 0.000001 |
@@ -943,32 +943,28 @@
ode';%0Aconst
-EXPENSES
+CODE
_TYPE_ACTION
@@ -1000,24 +1000,20 @@
;%0Aconst
-EXPENSES
+CODE
_TYPE_AR
@@ -1761,24 +1761,20 @@
rgument(
-EXPENSES
+CODE
_TYPE_AR
@@ -1884,16 +1884,50 @@
a%5Bkey%5D;%0A
+ if (type === 'Expenses')%7B%0A
let
@@ -1965,16 +1965,115 @@
seCode;%0A
+ %7D %0A else if (type === 'Services')%7B%0A let code = clientNameKeyIndex.ServiceCode;%0A %7D%0A
assi
@@ -2540,16 +2540,12 @@
set(
-EXPENSES
+CODE
_TYP
|
0754f71209cc93499474844e4fcb236382d46e8d
|
Add options to create https server.
|
app.js
|
app.js
|
const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const http = require('http')
const https = require('https')
const config = require('./config')
const routers = require('./routers')
const constants = require('./utils')
const env = constants.constants.env
// error handler
onerror(app)
// middlewares
app.use(bodyparser({
enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))
app.use(views(__dirname + '/views', {
extension: 'ejs'
}))
// logger
app.use(async (ctx, next) => {
const start = new Date()
await next()
const ms = new Date() - start
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})
// routes
app.use(routers.routes(), routers.allowedMethods())
if (process.env.NODE_ENV === env.DEV) {
server = http.createServer(app.callback()).listen(3000)
} else if (process.env.NODE_ENV === env.PROD) {
server = https.createServer(app.callback()).listen(443)
}
|
JavaScript
| 0 |
@@ -931,17 +931,16 @@
hods())%0A
-%0A
if (proc
@@ -1027,12 +1027,41 @@
ten(
-3000
+config%5Bprocess.env.NODE_ENV%5D.port
)%0A%7D
@@ -1102,24 +1102,179 @@
env.PROD) %7B%0A
+ const options = %7B%0A key: fs.readFileSync('/home/ssl/www.keisei.top.key', 'utf8'),%0A cert: fs.readFileSync('/home/ssl/www.keisei.top.pem', 'utf8')%0A%7D;%0A
server = h
@@ -1283,32 +1283,41 @@
ps.createServer(
+options,
app.callback()).
@@ -1327,11 +1327,41 @@
ten(
-443
+config%5Bprocess.env.NODE_ENV%5D.port
)%0A%7D%0A
|
81b05cc44c075c2b7fd2e67656f24055c01707ac
|
Change port
|
app.js
|
app.js
|
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, http = require('http')
, path = require('path')
, log4js = require('log4js');
log4js.configure({
appenders: [{
'type' : 'dateFile',
'filename': __dirname + '/logs/access.log',
'pattern': '-yyyy-MM-dd'
}]
});
var logger = log4js.getLogger('dateFile');
var accesslog = function() {
return function(req, res, next) {
logger.info([
req.headers['x-forwarded-for'] || req.client.remoteAddress,
new Date().toLocaleString(),
req.method,
req.url,
req.statusCode,
req.headers.referer || '-',
req.headers['user-agent'] || '-'
].join('\t'));
next();
}
};
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 10002);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(accesslog());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
// route
app.get('/', routes.index);
app.get('/builds/:project', routes.builds);
app.get('/apps/:project/:build', routes.apps);
app.get('/plist/:project/:build/:app', routes.plist);
app.get('/apk/:project/:build/:app', routes.apk);
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
|
JavaScript
| 0.000001 |
@@ -811,13 +811,12 @@
%7C%7C
-1
+3
000
-2
);%0A
|
527944bf91fae599723b15ac09534bc3116d003d
|
Add CORS
|
app.js
|
app.js
|
/**
* Created by jan on 15.05.15.
*/
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var autoIncrement = require('mongoose-auto-increment');
var app = express(); //Create the Express app
//connect to our database
//Ideally you will obtain DB details from a config file
var dbName = 'abirechner';
var host = process.env.OPENSHIFT_MONGODB_DB_HOST || "127.0.0.1";
var port = process.env.OPENSHIFT_MONGODB_DB_PORT || "27017";
var username = process.env.OPENSHIFT_MONGODB_DB_USERNAME || "";
var password = process.env.OPENSHIFT_MONGODB_DB_PASSWORD || "";
var opts = {
user: username,
pass: password
};
var connectionString = 'mongodb://'+host+':'+port+'/' + dbName;
var connection = mongoose.connect(connectionString, opts);
autoIncrement.initialize(connection);
//configure body-parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
var studienplaene = require('./routes/studienplaene'); //routes are defined here
app.use('/api', studienplaene); //This is our route middleware
module.exports = app;
|
JavaScript
| 0.000446 |
@@ -826,16 +826,271 @@
ction);%0A
+%0Avar allowCrossDomain = function(req, res, next) %7B%0A res.header('Access-Control-Allow-Origin', '*');%0A res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');%0A res.header('Access-Control-Allow-Headers', 'Content-Type');%0A%0A next();%0A%7D;%0A%0A
//config
@@ -1183,16 +1183,43 @@
rue%7D));%0A
+app.use(allowCrossDomain);%0A
var stud
|
f9fa1afca8392404f4811c9b3f35d123601d9313
|
add restify-validator import inside app
|
app.js
|
app.js
|
var restify = require('restify')
var server = restify.createServer()
var setup = require('./controllers/setup.js')
var userController = require('./controllers/userController.js')
setup(server, restify)
userController(server)
server.listen(8080, function () {
console.log('listening at', server.name, server.url)
})
|
JavaScript
| 0 |
@@ -171,16 +171,68 @@
ler.js')
+%0Avar restifyValidator = require('restify-validator')
%0A%0Asetup(
@@ -246,16 +246,34 @@
restify
+, restifyValidator
)%0AuserCo
|
71454264aaa2ba9c9c48621a4038b402b25072d7
|
validate data
|
app.js
|
app.js
|
var http = require('http');
var default_port = 1771;
var util = require('util')
var exec = require('child_process').exec;
function puts(error, stdout, stderr) { util.puts(stdout) }
http.createServer(function (req, res) {
var urlSplitOnSegment = req.url.split('?')[1];
if (urlSplitOnSegment != undefined) {
var urlSplit = urlSplitOnSegment.split('&');
if (urlSplit != undefined) {
var output = "",
houseCode = "",
unitCode = "",
statusCode = "",
command = "";
for (i = 0; i < urlSplit.length; i++) {
var name = urlSplit[i].split('=')[0],
value = urlSplit[i].split('=')[1];
if (name == "houseCode") {
houseCode = value;
} else if (name == "unitCode") {
unitCode = value;
} else if (name == "statusCode") {
statusCode = value;
}
}
res.writeHead ("200", {'Content-Type': 'text/plain'});
res.end (
exec("echo " + statusCode + houseCode + unitCode + " > /home/pi/pycm19a/cm19a/in", puts).toString()
);
} else {
res.writeHead ("500", {'Content-Type': 'text/plain'});
res.end ("Error");
}
} else {
var output = "no params passes";
res.writeHead ("500", {'Content-Type': 'text/plain'});
console.log (output);
res.end (output);
}
}).listen(default_port);
|
JavaScript
| 0.001283 |
@@ -500,16 +500,137 @@
= %22%22
+,%0A%09%09%09 validHouseCodes = %5B'a', 'b', 'c'%5D,%0A%09%09%09 validUnitCodes = %5B'1', '2', '3'%5D,%0A%09%09%09 validStatusCodes = %5B'-', '+'%5D
;%0A%0A%09%09%09fo
@@ -799,32 +799,42 @@
ouseCode = value
+.toLower()
;%0A%09%09%09%09%7D else if
@@ -955,16 +955,245 @@
%7D%0A%09%09%09%7D%0A%0A
+%09%09%09if ( validHouseCodes.indexOf(houseCode) %3E= 0 ) %7B%0Aconsole.log (%22A%22);%0A%0A%09%09%09%09if (validUnitCodes.indexOf(unitCode) %3E= 0) %7B%0A%09%09%09%09%09console.log (%22B%22);%0A%0A%09%09%09%09%09if (validStatusCodes.indexOf(statusCode) %3E= 0) %7B%0A%09%09%09%09%09%09console.log (%22C%22);%0A%0A%09%09%09
%09%09%09res.w
@@ -1242,17 +1242,19 @@
ain'%7D);%0A
-%0A
+%09%09%09
%09%09%09res.e
@@ -1258,16 +1258,19 @@
s.end (%0A
+%09%09%09
%09%09%09%09exec
@@ -1368,16 +1368,135 @@
ng()%0A%09%09%09
+%09%09%09);%0A%09%09%09%09%09%7D%0A%09%09%09%09%7D%0A%09%09%09%7D%0A%0A%09%09%09res.writeHead (%22300%22, %7B'Content-Type': 'text/plain'%7D);%0A%09%09%09res.end (%22Error: invalid code(s)%22
);%0A%09%09%7D e
|
c72eaa304ac2332ed97092a1e8012745f40bf360
|
remove screens when no clients are attached
|
app.js
|
app.js
|
var express = require("express"),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(process.env.PORT || 3000);
app.use(express.bodyParser());
var screens = {};
app.get('/api/screens', function(req, res){
//list screens along with current status
var list = [];
for(s in screens){
list.push(s);
}
res.send({"screens":list});
});
app.post('/api/screens/:name/reload', function(req, res){
if(screens[req.params.name] !== undefined){
for(s in screens[req.params.name]){
var socket = screens[req.params.name][s];
socket.emit('reload');
}
}
res.send({"status": "ok"});
});
app.post('/api/screens/:name', function(req, res){
if(screens[req.params.name] !== undefined){
for(s in screens[req.params.name]){
var socket = screens[req.params.name][s];
socket.emit('display', req.body);
}
}
res.send({"status": "ok"});
});
app.get('/screen/:name', function(req, res){
res.sendfile('index.html');
});
app.use('/', express.static(__dirname + '/'));
io.sockets.on('connection', function (socket) {
socket.on('screen', function (data) {
if(screens[data.screenName] === undefined)
screens[data.screenName] = [];
screens[data.screenName].push(socket)
socket.screenName = data.screenName;
});
socket.on('disconnect', function () {
if(screens[socket.screenName].indexOf(socket) >=0)
delete screens[socket.screenName][screens[socket.screenName].indexOf(socket)];
console.log("disconnect");
});
});
|
JavaScript
| 0 |
@@ -1386,24 +1386,106 @@
nction () %7B%0A
+ //console.log(%22disconect%22, socket, screens%5Bsocket.screenName%5D.indexOf(socket))
%0A if(scre
@@ -1538,15 +1538,8 @@
-delete
scre
@@ -1560,17 +1560,24 @@
eenName%5D
-%5B
+.splice(
screens%5B
@@ -1610,19 +1610,113 @@
(socket)
+, 1);%0A%0A if(screens%5Bsocket.screenName%5D.length === 0)%0A delete screens%5Bsocket.screenName
%5D;%0A
+%0A
cons
|
f0d6c9060968834681290b7e0d71d5718237bfb2
|
change /commit route to a root post
|
app.js
|
app.js
|
var express = require('express'),
app = express.createServer(),
io = require('socket.io').listen(app),
sounds = require('./sounds'),
port = process.env.PORT || 5000;
// Config
io.configure(function () {
io.set('transports', ['xhr-polling']);
io.set('polling duration', 10);
});
app.configure(function(){
app.use(express.bodyParser());
});
// Start Server
app.listen(port);
// Helpers
var getMessageUrl = function(data) {
var message = data.commits[0].author.name + ' pushed ' + data.commits.length +
(data.commits.length > 1 ? ' commits' : ' commit') + ' to ' + data.repository.name;
return 'http://speech.jtalkplugin.com/api/?speech=' + encodeURI(message);
};
var getCoderSoundUrl = function(data) {
return sounds.user[data.commits[0].author.username];
};
// Routes
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
app.post('/commit', function (req, res) {
var payload = JSON.parse(req.body.payload),
data = {
"messageUrl": getMessageUrl(payload),
"coderSoundUrl": getCoderSoundUrl(payload)
};
io.sockets.emit('commit', data);
res.send('thanks github!');
});
|
JavaScript
| 0 |
@@ -895,22 +895,16 @@
.post('/
-commit
', funct
|
f1686d6d96342e967aca7e97ddba34b306d18391
|
Fix bug on get first word
|
app.js
|
app.js
|
const tjbot = require('./tjbotlib');
const config = require('./config/configs');
const credentials = config.credentials;
const WORKSPACEID = config.conversationWorkspaceId;
const hardware = ['microphone', 'speaker'];
const configuration = {
listen: {
microphoneDeviceId: 'plughw:1,0',
inactivityTimeout: 60,
language: 'pt-BR'
},
wave: {
servoPin: 7
},
speak: {
language: 'pt-BR'
},
verboseLogging: true
};
const tj = new tjbot(hardware, configuration, credentials);
tj.listen((msg) => {
// send to the conversation service
tj.converse(WORKSPACEID, turn, (response) => {
// speak the result
tj.speak(response.description);
});
console.log('Message logger', msg);
// check to see if they are talking to TJBot
if (msg.startsWith('Sara')) {
// remove our name from the message
var turn = msg.toLowerCase().replace('Sara'.toLowerCase(), "");
console.log('Turn logger', turn);
// send to the conversation service
tj.converse(WORKSPACEID, turn, (response) => {
// speak the result
tj.speak(response.description);
});
}
})
|
JavaScript
| 0 |
@@ -766,34 +766,57 @@
t%0A
-if (msg.startsW
+const name = msg.spl
it
-h
('
-Sara')
+ ')%5B0%5D.join();%0A if (name
) %7B%0A
@@ -863,11 +863,13 @@
-var
+const
tur
@@ -880,54 +880,41 @@
msg.
-toLowerCase().replace('Sara'.toLowerCase(), %22%22
+replace(/(sara,vara,sarah)*/i, ''
);%0A%0A
|
295f3a144a728d996bcbeaf574cca8e6cf642e22
|
fix server hooking for self-signed paypro testing.
|
app.js
|
app.js
|
var express = require('express');
var http = require('http');
var app = express();
app.use('/', express.static(__dirname + '/'));
app.get('*', function(req, res) {
return res.sendfile('index.html');
});
app.start = function(port, callback) {
app.set('port', port);
app.use(express.static(__dirname));
if (process.env.USE_HTTPS) {
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';
var fs = require('fs');
var path = require('path');
var bc = path.dirname(require.resolve('bitcore/package.json'));
var server = require('https').createServer({
key: fs.readFileSync(bc + '/test/data/x509.key'),
cert: fs.readFileSync(bc + '/test/data/x509.crt')
});
var pserver = require(bc + '/examples/PayPro/server.js');
server.on('request', function(req, res) {
app(req, res);
pserver.app(res, res);
});
app.listen(port, function() {
callback('https://localhost:' + port);
});
return;
}
app.listen(port, function() {
callback('http://localhost:' + port);
});
};
module.exports = app;
// if we are running in the copay shell context, initialize the shell bindings
if (process.versions && process.versions['atom-shell']) {
require('./shell')(app);
}
|
JavaScript
| 0 |
@@ -757,104 +757,1410 @@
-server.on('request', function(req, res) %7B%0A app(req, res);%0A pserver.app(res, re
+pserver.removeListener('request', pserver.app);%0A pserver.on('request', function(req, res) %7B%0A var statusCode = res.statusCode;%0A%0A var headers = Object.keys(res._headers %7C%7C %7B%7D).reduce(function(out, key) %7B%0A out%5Bkey%5D = res._headers%5Bkey%5D;%0A return out;%0A %7D, %7B%7D);%0A%0A var headerNames = Object.keys(res._headerNames %7C%7C %7B%7D).reduce(function(out, key) %7B%0A out%5Bkey%5D = res._headerNames%5Bkey%5D;%0A return out;%0A %7D, %7B%7D);%0A%0A var writeHead = res.writeHead;%0A var write = res.write;%0A var end = res.end;%0A var status;%0A%0A res.writeHead = function(s) %7B%0A status = s;%0A if (status %3E 400) %7B%0A return;%0A %7D%0A return writeHead.apply(this, arguments);%0A %7D;%0A%0A res.write = function() %7B%0A if (status && status %3E 400) %7B%0A return true;%0A %7D%0A return write.apply(this, arguments);%0A %7D;%0A%0A res.end = function() %7B%0A var self = this;%0A var args = Array.prototype.slice.call(arguments);%0A process.nextTick(function() %7B%0A self.statusCode = statusCode;%0A self._headers = headers;%0A self._headerNames = headerNames;%0A self.writeHead = writeHead;%0A self.write = write;%0A self.end = end;%0A if ((status %7C%7C self.statusCode) %3E 400) %7B%0A return pserver.app(req, res);%0A %7D%0A return end.apply(self, arg
s);%0A
%7D);%0A
@@ -2155,24 +2155,28 @@
s);%0A
+
+
%7D);%0A
app.list
@@ -2167,19 +2167,91 @@
%7D);%0A
-app
+ return true;%0A %7D;%0A%0A return app(req, res);%0A %7D);%0A%0A pserver
.listen(
@@ -2318,24 +2318,25 @@
t);%0A %7D);%0A
+%0A
return;%0A
|
270a3bea694c07cdc556562a95761413330cb497
|
use gzip when serving statics for express
|
app.js
|
app.js
|
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('less-middleware')({ src: path.join(__dirname, 'public') }));
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
|
JavaScript
| 0 |
@@ -601,24 +601,53 @@
blic') %7D));%0A
+app.use(express.compress());%0A
app.use(expr
|
9b9ebb2879412fcdc34f8989687514d5b56321b8
|
Test again
|
app.js
|
app.js
|
var express = require('express');
var playsApp = require('radio-plays');
var streamManager = require('stream-data');
var logfmt = require("logfmt");
var app = express();
var http = require('http');
var moment = require('moment');
var googleapis = require('googleapis');
var pg = require('pg');
var google_tokens = null;
var plays = playsApp({
source: 'Spinitron',
spinitron: {
station: process.env.SPIN_STATION,
userid: process.env.SPIN_USERID,
secret: process.env.SPIN_SECRET
},
maxAge: Number(process.env.CACHE_TIME || 15000)
});
var OAuth2 = googleapis.auth.OAuth2;
var auth = new OAuth2(
process.env.GOOGLE_CLIENT_ID,
process.env.GOOGLE_CLIENT_SECRET,
process.env.GOOGLE_REDIRECT_URL
);
googleapis.options({ auth: auth });
var calendar = googleapis.calendar('v3');
var schedule = {
timestamp: 0,
events: {},
current: {}
};
var isStale = function(timestamp) {
diff = new Date() - timestamp;
if (diff > 15000) {
return true;
}
return false;
}
var processGCalV3 = function (response) {
var events = response.items;
var newEvents = [];
var now = moment();
for (i in events) {
var e = {
title: events[i].summary,
content: '',
startTime: events[i].start.dateTime,
endTime: events[i].end.dateTime
}
var startMoment = moment(e.startTime);
var endMoment = moment(e.endTime);
if (startMoment.isBefore(now) && now.isBefore(endMoment)) {
schedule.current = e;
}
newEvents.push(e);
}
schedule.events = newEvents;
schedule.timestamp = new Date();
}
var saveTokens = function (tokens) {
// Save tokens to database
pg.connect(process.env.DATABASE_URL, function(err, client) {
if(err) {
return console.error('could not connect to postgres', err);
}
client.query('TRUNCATE TABLE tokens', function(err, result) {
if(err) {
return console.error('error truncating token table', err);
}
client.query('INSERT INTO tokens (ACCESS, REFRESH) VALUES($1, $2)',
[tokens.access_token, tokens.refresh_token], function(err, result) {
if(err) {
return console.error('error saving tokens', err);
}
client.end();
});
});
});
}
var getSchedule = function() {
if (isStale(schedule.timestamp)) {
console.log('Fetching new calendar');
schedule.timestamp = new Date();
// make call to api
calendar.events.list({
'calendarId': process.env.SCHEDULE_ID,
'singleEvents': true,
'orderBy': 'startTime',
'timeMin': schedule.timestamp.toISOString()
}, function (err, response) {
if (err) {
auth.refreshAccessToken(function(err, tokens) {
// your access_token is now refreshed and stored in oauth2Client
if (err) {
console.log("Error refreshing tokens: ", err);
return;
}
saveTokens(tokens);
});
console.log("Got calendar error: ", err);
return;
}
processGCalV3(response);
});
}
}
var streams = streamManager({});
app.use(logfmt.requestLogger());
pg.connect(process.env.DATABASE_URL, function(err, client) {
if(err) {
return console.error('could not connect to postgres', err);
}
client.query('CREATE TABLE IF NOT EXISTS tokens (\
ID SERIAL PRIMARY KEY,\
REFRESH TEXT NOT NULL,\
ACCESS TEXT NOT NULL)', function(err, result) {
if(err) {
return console.error('error running query', err);
}
client.query('SELECT * FROM tokens', function(err, result) {
if(err) {
return console.error('error running token query', err);
}
if (result.rows.length > 0) {
google_tokens = {
access_token: result.rows[0].access,
refresh_token: result.rows[0].refresh
}
auth.setCredentials(google_tokens);
getSchedule();
}
client.end();
});
});
});
app.get('/nowplaying', function(req, res){
res.jsonp(null);
var data = plays.recentPlays(1);
var dataResponse = null;
if (Array.isArray(data) === true) {
dataResponse = data[0];
}
res.jsonp(dataResponse);
});
app.get('/recentplays/:num', function(req, res){
res.jsonp(null);
var data = plays.recentPlays(Number(req.params.num));
var dataResponse = null;
if (Array.isArray(data) === true) {
dataResponse = data;
}
res.jsonp(dataResponse);
});
app.get('/streams', function(req, res){
res.jsonp(streams.streams());
});
app.get('/schedule', function(req, res){
getSchedule();
res.jsonp(schedule);
});
// Authenticate with google.
app.get('/api_auth', function(req, res){
if (google_tokens == null) {
var url = auth.generateAuthUrl({
access_type: 'offline',
approval_prompt: 'force',
scope: process.env.GOOGLE_SCOPE
});
res.redirect(url);
} else {
// We've already authenticated.
res.redirect('/schedule');
}
});
app.get(process.env.GOOGLE_REDIRECT_PATH, function(req, res){
auth.getToken(req.query.code, function(err, tokens) {
if(!err) {
auth.setCredentials(tokens);
google_tokens = tokens;
saveTokens(tokens);
res.redirect('/schedule');
} else {
console.error('error getting auth tokens', err);
}
});
});
var port = Number(process.env.PORT || 3000);
var server = app.listen(port, function() {
console.log('Listening on port %d', server.address().port);
});
|
JavaScript
| 0 |
@@ -4186,32 +4186,39 @@
es.jsonp(null);%0A
+ /*%0A
var data = p
@@ -4238,16 +4238,16 @@
ays(1);%0A
-
var
@@ -4365,32 +4365,39 @@
(dataResponse);%0A
+ */%0A
%7D);%0A%0Aapp.get('/r
@@ -4451,24 +4451,31 @@
sonp(null);%0A
+ /*%0A
var data
@@ -4615,32 +4615,32 @@
= data;%0A %7D %0A
-
res.jsonp(da
@@ -4648,24 +4648,31 @@
aResponse);%0A
+ */%0A
%7D);%0A%0Aapp.get
|
14ebd1431ba58c0cad021a95cde1a8cb73de783d
|
Send out timestamp to new clients within the callback which sends out the old tweets
|
app.js
|
app.js
|
/*jshint
node: true,
globalstrict: true,
laxcomma: true
*/
'use strict';
/* Tiny */
var tiny = require('tiny');
var db;
tiny('latest_tweets.tiny', function openDatabase (err, tinydb) {
if (err) {
console.error('Error occurred when trying to open database:');
console.error(err);
console.error('Quitting!');
}
db = tinydb;
});
function storeTweet (tweet) {
db.set(tweet.id_str, {
id: tweet.id_str,
timestamp: Date.now(),
tweet: tweet
}, function afterSave (err) {
if (err) {
console.error('Error when saving tweet in database:');
console.error(err);
}
});
}
function tweetDeleted (err) {
if (err) {
console.error('Error deleting tweet:');
console.error(err);
}
}
setInterval(function removeOldTweets () {
db.find({
timestamp: {
$lt: Date.now() - 604800000 // One week
}
})
.shallow()(function deleteTweets (err, tweets) {
var timer = Date.now();
for (var i = 0; i < tweets.length; i++) {
db.remove(tweets[i].id, tweetDeleted);
}
console.log('Deleted ' + tweets.length + ' old tweets in ' + (Date.now() - timer) + ' seconds');
});
}, 21600000); // Every six hours
/* Socket.IO */
var io = require('socket.io').listen(3000);
io.enable('browser client minification');
io.enable('browser client gzip');
io.set('log level', 2);
var clients = 0;
io.sockets.on('connection', function clientConnected (socket) {
// Sends out new user count when a new client is connected
clients++;
socket.emit('users', { count: clients });
socket.broadcast.emit('users', { count: clients });
// Sends out the latest tweets (max 20) to new users
db.find({
timestamp: {
$gt: Date.now() - 604800000 // One week
}
})
.asc('timestamp')
.limit(20)(function sendOldTweets (err, tweets) {
for (var i = 0; i < tweets.length; i++) {
socket.emit('tweet', { html: renderTweet(tweets[i].tweet), tweetId: tweets[i].id });
}
});
// Sends out the server time to the new client, in order for goFuzzy() to be called
socket.emit('time', { now: new Date().getTime() });
// Sends out new user count when a client disconnect
socket.on('disconnect', function clientDisconnected () {
clients--;
socket.broadcast.emit('users', { count: clients });
});
});
/* Twitter */
try {
var twitter_options = require('./twitter_options.json');
} catch (e) {
console.error('Could not read "twitter_options.json", reason: ' + e.message);
console.error('Quitting!');
process.exit(1);
}
var t = require('immortal-ntwitter').create(twitter_options.oauth_credentials);
t.verifyCredentials(function testCredentials (err, data) {
if (err) {
console.error('Got the following error when testing Twitter credentials:');
console.error(err);
console.error('Quitting!');
process.exit(1);
}
});
t.immortalStream('statuses/filter', twitter_options.filter, function twitterStream (ts) {
ts.on('data', function processNewTweet (tweet) {
io.sockets.emit('tweet', { html: renderTweet(tweet), tweetId: tweet.id_str });
storeTweet(tweet);
});
ts.on('delete', function deleteTweet (tweet) {
console.log('Delete event received, content:'); // Debugging
console.log(tweet);
io.sockets.emit('delete', { tweetId: tweet['delete'].status.id_str });
db.remove(tweet['delete'].status.id_str, function deleteTweet (err) {
if (err) {
console.error('Error deleting tweet:');
console.error(err);
}
});
});
ts.on('limit', function limitReceived (data) {
console.log('Limit event received, content:');
console.log(data);
});
ts.on('scrub_geo', function scrubGeoReceived (data) {
console.log('Scrub Geo event received, content:');
console.log(data);
});
});
/* Rendering */
var mustache = require('mustache');
function renderTweet (tweet) {
tweet.timestamp = new Date(tweet.created_at).toJSON();
return mustache.to_html(
'@<a class="screenname" href="http://twitter.com/{{user.screen_name}}">{{user.name}}</a><br />' +
'<a href="http://twitter.com/{{user.screen_name}}/status/{{id_str}}"><time datetime="{{timestamp}}">Less than a minute ago</time></a><br />' +
'{{text}}<br />'
, tweet);
}
/* Update time since */
// Time is pushed from the server to the clients, in order to avoid clients with wrong time settings
setInterval(function updateTime() {
io.sockets.emit('time', { now: new Date().getTime() });
}, 15000);
|
JavaScript
| 0 |
@@ -1957,23 +1957,19 @@
;%0A %7D%0A
+%0A
-%7D);%0A%0A
// Sen
@@ -2046,16 +2046,18 @@
called%0A
+
socket
@@ -2097,24 +2097,30 @@
etTime() %7D);
+%0A %7D);
%0A%0A // Sends
|
c01e93393277593c69a1a8cc4c5e489bff83e129
|
Switch from ffmpeg to music-metadata as has proper support for musicbrainz tags incl. mbid
|
app.js
|
app.js
|
var express = require('express');
var XMLHttpRequest = require('xhr2');
var ffmpeg = require('fluent-ffmpeg');
var bodyParser = require('body-parser');
var api_key = require('./private');
var app = express();
ffmpeg.setFfmpegPath('ffmpeg.exe')
ffmpeg.setFfprobePath('ffprobe.exe')
// Need to specify static content to use
app.use(express.static(__dirname + '/public'));
app.get('/', function(request, response){
response.sendFile(__dirname + '/index.html');
});
// Use body parser to see request
app.use(bodyParser.json());
// It's working just I can't push back to client
//(need different xhr plan, like http or something)
app.post('/', function(request, response){
//console.log('Message received, sending meta');
var playing_file = JSON.stringify(request.body.file_name).replace(/"/g,"")
console.log('Request received. Reading meta for ' + playing_file);
ffmpeg.ffprobe('./public/' + playing_file, function(err, metadata) {
var tags = metadata['format']['tags'];
console.log(tags);
var xhr = new XMLHttpRequest();
var url = 'https://api.listenbrainz.org/1/submit-listens'
var payload = JSON.stringify(
{"listen_type": "single",
"payload": [
{
"listened_at": Math.floor(Date.now()/1000),
"track_metadata": {
"additional_info": {
"release_mbid": tags['MusicBrainz Album Id'],
"artist_mbids": [
tags['MusicBrainz Artist Id']
],
"recording_mbid": tags['MusicBrainz Release Track Id']
},
"artist_name": tags['artist'],
"track_name": tags['title'],
"release_name": tags['album']
}
}
]
}
)
console.log('Sending payload to listenbrainz...');
console.log(payload);
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-type', 'application/json');
xhr.setRequestHeader('Authorization', 'OAuth ' + api_key['api_key']);
xhr.onload = function () {
console.log(xhr.responseText);
};
xhr.send(payload);
});
});
var server = app.listen(8080, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
|
JavaScript
| 0 |
@@ -69,47 +69,8 @@
');%0A
-var ffmpeg = require('fluent-ffmpeg');%0A
var
@@ -167,81 +167,74 @@
();%0A
-%0Affmpeg.setFfmpegPath('ffmpeg.exe')%0Affmpeg.setFfprobePath('ffprobe.exe
+var mm = require('music-metadata');%0Aconst util = require('util
')%0A
+
%0A//
@@ -824,21 +824,19 @@
);%0A%09
-ffmpeg.ffprob
+mm.parseFil
e('.
@@ -861,24 +861,50 @@
g_file,
+%7Bnative: true%7D)%0A .then(
function
(err, me
@@ -899,14 +899,10 @@
tion
-(err,
+(
meta
@@ -909,18 +909,24 @@
data) %7B%0A
-%09%09
+
var tags
@@ -942,22 +942,14 @@
ta%5B'
-format'%5D%5B'tags
+common
'%5D;%0A
@@ -1286,27 +1286,26 @@
gs%5B'
-M
+m
usic
-B
+b
rainz
- A
+_a
lbum
- I
+i
d'%5D,
@@ -1350,28 +1350,27 @@
gs%5B'
-M
+m
usic
-B
+b
rainz
- A
+_a
rtist
- I
+i
d'%5D%0A
@@ -1416,35 +1416,30 @@
gs%5B'
-M
+m
usic
-B
+b
rainz
- Release Track I
+_recordingi
d'%5D%0A
@@ -1922,16 +1922,81 @@
ad); %0A%09
+ %7D)%0A .catch(function (err) %7B%0A console.error(err.message);%0A
%7D);%0A%7D);%09
|
34dc3bdb159e72391161a88b450eac3ff7d92a4a
|
fix typo
|
app.js
|
app.js
|
/*
This bot waits patiently for the user to request a cat picture and then picks one at random from http://thecatapi.com/ for his/her viewing pleasure!
Created using:
- Microsoft's Bot Framework (https://docs.botframework.com/)
- BotBuilder for Node.js (https://github.com/Microsoft/BotBuilder, https://docs.botframework.com/en-us/node/builder/overview/)
- The Cat API (http://thecatapi.com/)
- LUIS - Language Understanding Intelligent Service (https://www.luis.ai/)
*/
var restify = require('restify');
var builder = require('botbuilder');
var xml2js = requre("xml2js");
//=========================================================
// Bot Setup
//=========================================================
// Setup Restify Server for local debugging
var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
console.log('%s listening to %s', server.name, server.url);
});
// Create chat bot
var connector = new builder.ChatConnector({
appId: process.env.MICROSOFT_APP_ID,
appPassword: process.env.MICROSOFT_APP_PASSWORD
});
var bot = new builder.UniversalBot(connector);
server.post('/api/messages', connector.listen());
// Create LUIS recognizer that points to the intent detection model (trained via https://www.luis.ai/).
// Add "&verbose=true" to the end of the url as a workaround for https://github.com/Microsoft/BotBuilder/issues/1633.
var model = "https://api.projectoxford.ai/luis/v2.0/apps/" + process.env.LUIS_APP_ID + "?subscription-key=" + process.env.LUIS_APP_KEY + "&verbose=true";
var recognizer = new builder.LuisRecognizer(model);
var intentDialog = new builder.IntentDialog({ recognizers: [recognizer] });
var showCatPictureTodo = "Try asking for a cat picture. For instance, type: Show me a cat picture.";
// Add intent handlers
intentDialog.onDefault(builder.DialogAction.send("How embarrassing! I didn't understand that. I'm still a young bot. " + showCatPictureTodo));
intentDialog.matches("Greeting", [
function (session, args) {
session.beginDialog('/greeting');
}
]);
intentDialog.matches("RequestObject", [
function (session, args) {
session.beginDialog('/request', args);
}
]);
intentDialog.matches("Like", builder.DialogAction.send("Yay! I'm glad you like this. I have more cats for you. :) " + showCatPictureTodo));
intentDialog.matches("Dislike", builder.DialogAction.send("Oh no! I'm sorry you don't like this. We can try another cat. :( " + showCatPictureTodo));
var http = require("https");
var options = {
host: "thecatapi.com",
path: "/api/images/get?format=xml"
};
var catSynonyms = ["CAT", "KITTY", "KITTEN", "FELINE", "MEOW", "FLOOF", "FLUFFY", "PUSSY", "PUSS", "ANOTHER", "MORE"];
var pictureSynonyms = ["PICTURE", "PHOTO", "PHOTOGRAPH", "IMAGE", "PIC", "PICCY", "PIX", "SNAPSHOT"];
var deliveryPhrases = [
"Here's your cat!", "One cat coming right up!", "Ask and you shall receive. Meow!", "I picked this cat just for you.",
"I think you will like this one.", "There you go! One cat.", "Here's a cat for you!"]
//=========================================================
// Bots Dialogs
//=========================================================
bot.dialog('/', intentDialog);
bot.dialog('/greeting', [
function (session) {
if (!session.userData.introComplete) {
session.userData.introComplete = true;
session.endDialog("Meow! >^o.o^< I have pictures of cats that I think you'll love. " + showCatPictureTodo);
}
else {
session.endDialog("Meow! I feel good and hope you do too. >^o_o^< " + showCatPictureTodo);
}
}
]);
bot.dialog("/request", [
function (session, args) {
var shouldGetCatPicture = true;
var requestedObject = builder.EntityRecognizer.findEntity(args.entities, "Object"); // The requested object, like "cat"
var requestedMedium = builder.EntityRecognizer.findEntity(args.entities, "Medium"); // The requested medium, like "picture"
if (requestedObject) {
shouldGetCatPicture = (requestedMedium) ?
// If both object and medium exist, verify object is a cat and medium is a picture.
verifyEntity(requestedObject, catSynonyms, session, "I only have pictures of cats. So how about a cat? " + showCatPictureTodo) &&
verifyEntity(requestedMedium, pictureSynonyms, session, "I only have cat pictures. So how about a picture? " + showCatPictureTodo) :
// If only object exists, verify that it is either a cat or a picture.
verifyEntity(requestedObject, catSynonyms.concat(pictureSynonyms), session, "I only have cat pictures. " + showCatPictureTodo);
}
else if (requestedMedium) {
// If only medium exists, verify that it is a picture.
shouldGetCatPicture =
verifyEntity(requestedMedium, pictureSynonyms, session, "I only have cat pictures. So how about a picture? " + showCatPictureTodo);
}
else {
// Must have at least a an object or a medium.
session.endDialog("I only have cat pictures. " + showCatPictureTodo);
shouldGetCatPicture = false;
}
// Create callback for response from TheCatApi.
callback = function(response) {
var responseXML = "";
response.on("data", function (chunk) {
responseXML += chunk;
})
response.on("end", function() {
// TheCatApi returns XML, so convert to JSON then parse.
var responseJSON;
var parseString = xml2js.parseString;
parseString(responseXML, function (err, result) {
responseJSON = JSON.stringify(result);
});
var jsonObject = JSON.parse(responseJSON);
// Assume at least one cat picture exists. Since we're doing a random selection from the
// entire cat database, this is a safe assumption. Also call String constructor, since image
// attachment won't work below for some channels unless catImageUrl is explicitly a string.
var catImageUrl = String(jsonObject.response.data[0].images[0].image[0].url);
var msg = new builder.Message(session)
.text(deliveryPhrases[Math.floor(Math.random()*deliveryPhrases.length)]) // Pick a random phrase from the list.
.attachments([{
contentType: "image/jpeg",
contentUrl: catImageUrl
}]);
session.endDialog(msg);
})
};
// Now call TheCatAPI.
http.request(options, callback).end();
}
]);
function verifyEntity(requestedEntityObject, synonymsList, session, invalidEntityMessage) {
// Convert to all uppercase and remove trailing 's' and 'z' to account for plural words.
// No need to remove trailing punctuation since LUIS will handle that.
var wordToCheck = requestedEntityObject.entity.toUpperCase().replace(/[sz]$/ig, "");
if (synonymsList.indexOf(wordToCheck) < 0)
{
session.endDialog(invalidEntityMessage);
return false;
}
return true;
}
|
JavaScript
| 0.999991 |
@@ -566,16 +566,17 @@
s = requ
+i
re(%22xml2
|
b07d6fa00bde297bb7cd8ae7cb2e18d09ab1be2c
|
update the state of the requests[id] after each iteration
|
app.js
|
app.js
|
'use strict';
console.log('Launching…');
var exec = require('child_process').exec;
var meta = require('./package.json');
var express = require('express');
var compression = require('compression');
var bodyParser = require('body-parser');
var path = require('path');
var Fs = require('fs');
var Map = require('immutable').Map;
var Uuid = require('node-uuid');
var Job = require('./lib/job');
var Orchestrator = require('./lib/orchestrator');
var RequestState = require('./lib/request-state');
var SpecberusWrapper = require('./lib/specberus-wrapper');
// Configuration file
require('./config.js');
var app = express();
var requests = {};
var port = process.argv[4] || global.DEFAULT_PORT;
var argTempLocation = process.argv[2] || global.DEFAULT_TEMP_LOCATION;
var argHttpLocation = process.argv[3] || global.DEFAULT_HTTP_LOCATION;
var argResultLocation = process.argv[5] || global.DEFAULT_RESULT_LOCATION;
app.use(compression());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(corsHandler);
app.use(express.static('assets/'));
// Index Page
app.get('/', function (request, response) {
response.sendFile(__dirname + '/views/index.html');
});
// API methods
app.get('/api/version', function (req, res) {
res.send(meta.version);
});
app.get('/api/version-specberus', function (req, res) {
res.send(SpecberusWrapper.version);
});
app.get('/api/status', function (req, res) {
var id = req.query ? req.query.id : null;
var file = argResultLocation + path.sep + id + '.json';
if (id) {
Fs.exists(file, function (exists) {
if (exists) res.status(200).sendFile(file);
else if (requests && requests[id]) {
res.status(200).json(requests[id]);
}
else res.status(404).send('No job found with ID “' + id + '”.');
});
}
else res.status(400).send('Missing required parameter “ID”.');
});
function dumpJobResult(dest, result) {
Fs.writeFile(dest, JSON.stringify(result, null, 2) + '\n', function (err) {
if (err) return console.error(err);
});
}
app.post('/api/request', function (req, res) {
var url = req.body ? req.body.url : null;
var decision = req.body ? req.body.decision : null;
var token = req.body ? req.body.token : null;
var id = Uuid.v4();
if (!url || !decision || !token) {
res.status(500).send(
'Missing required parameters “url”, “decision” and/or “token”.'
);
}
else {
requests[id] = {
id: id,
url: url,
version: meta.version,
'version-specberus': SpecberusWrapper.version,
decision: decision,
results: new RequestState(
'',
new Map({
'retrieve-resources': new Job(),
'specberus': new Job(),
'token-checker': new Job(),
'third-party-checker': new Job(),
'publish': new Job(),
'tr-install': new Job(),
'update-tr-shortlink': new Job()
})
)
};
var tempLocation = argTempLocation + path.sep + id + path.sep;
var httpLocation = argHttpLocation + '/' + id + '/Overview.html';
var orchestrator = new Orchestrator(
url,
token,
tempLocation,
httpLocation,
argResultLocation
);
Orchestrator.iterate(
function (state) {
return orchestrator.next(state);
},
Orchestrator.hasFinished,
function () {
console.log(JSON.parse(JSON.stringify(requests[id])));
console.log('----------');
},
requests[id].results
).then(function (state) {
var cmd = global.SENDMAIL + ' ' + state.get('status').toUpperCase() +
' ' + global.MAILING_LIST;
if (state.get('status') === Orchestrator.STATUS_ERROR) {
cmd += ' ' + url + ' \'' + JSON.stringify(requests[id], null, 2) + '\'';
}
else {
cmd += ' ' + state.get('metadata').get('thisVersion') +
' \'Echidna ' + meta.version +
'; Specberus ' + SpecberusWrapper.version + '\'';
}
console.log('[' + state.get('status').toUpperCase() + '] ' + url);
exec(cmd, function (err, _, stderr) { if (err) console.error(stderr); });
dumpJobResult(argResultLocation + path.sep + id + '.json', requests[id]);
}).done();
res.status(202).send(id);
}
});
/**
* Add CORS headers to responses if the client is explicitly allowed.
*
* First, this ensures that the testbed page on the test server, listening on a different port, can GET and POST to Echidna.
* Most importantly, this is necessary to attend publication requests from third parties, eg GitHub.
*/
function corsHandler(req, res, next) {
if (req && req.headers && req.headers.origin) {
if (global.ALLOWED_CLIENTS.some(function (regex) {
return regex.test(req.headers.origin);
})) {
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Methods', 'GET,POST');
res.header('Access-Control-Allow-Headers', 'Content-Type');
}
}
next();
}
app.listen(process.env.PORT || port).on('error', function (err) {
if (err) {
console.error('Error while trying to launch the server: “' + err + '”.');
}
});
console.log(
meta.name +
' version ' + meta.version +
' running on ' + process.platform +
' and listening on port ' + port +
'. The server time is ' + new Date().toLocaleTimeString() + '.'
);
|
JavaScript
| 0.000001 |
@@ -3324,19 +3324,62 @@
nction (
-) %7B
+state) %7B%0A requests%5Bid%5D.results = state;
%0A
|
6605fe14815a23fd3fb96f3ae25697f5ec3b349a
|
Fix blow_show path in app.get id:
|
app.js
|
app.js
|
// Module dependencies.
var express = require('express');
//var ArticleProvider = require('./articleprovider-memory').ArticleProvider;
var ArticleProvider = require('./articleprovider-mongodb').ArticleProvider;
var app = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var errorHandler = require('errorhandler');
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride());
app.use(require('stylus').middleware({ src: __dirname + '/public' }));
/*app.configure('production', function(){
app.use(express.errorHandler());
});*/
var articleProvider= new ArticleProvider('localhost', 27017);
app.get('/', function(req, res){
articleProvider.findAll( function(error,docs){
res.render('index.jade', {
title: 'Blog',
articles:docs
});
})
});
app.get('/blog/new', function(req, res) {
res.render('blog_new.jade', { locals: {
title: 'New Post'
}
});
});
app.post('/blog/new', function(req, res){
articleProvider.save({
title: req.param('title'),
body: req.param('body')
}, function( error, docs) {
res.redirect('/')
});
});
app.get('/blog/:id', function(req, res) {
articleProvider.findById(req.params.id, function(error, article) {
res.render('blog_show.jade',
{ locals: {
title: article.title,
article:article
}
});
});
});
app.post('/blog/addComment', function(req, res) {
articleProvider.addCommentToArticle(req.param('_id'), {
person: req.param('person'),
comment: req.param('comment'),
created_at: new Date()
} , function( error, docs) {
res.redirect('/blog/' + req.param('_id'))
});
});
app.get('/blog/:id', function(req, res) {
articleProvider.findById(req.params.id, function(error, article) {
res.render('blog_show-final.jade',
{ locals: {
title: article.title,
article:article
}
});
});
});
app.use(express.static(__dirname + '/public'));
app.use(errorHandler({ dumpExceptions: true, showStack: true }));
app.listen(3000);
|
JavaScript
| 0 |
@@ -2106,14 +2106,8 @@
show
--final
.jad
|
0e41c7f493642b970e64a27a40cfb2750f1dc326
|
remove uri encode
|
app.js
|
app.js
|
var _ = require('lodash');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser());
app.set('port', (process.env.PORT || 5000));
// 生きてるか確認するためのHello World
app.get('/', function(req, res) {
res.send('Hello World!');
});
// LineからのコールバックURL
app.post('/callback', function(req, res) {
var results = req.body.result;
_.each(results, function(msg){
var request = require('superagent');
require('superagent-proxy')(request);
request
.post('https://chatbot-api.userlocal.jp/api/chat')
.send({
key: process.env.USER_LOCAL_API_KEY,
message: encodeURI(msg.content),
bot_name: "めぐみん",
platform: "line",
user_id: msg.content.from.toString()
})
.end(function(err, res){
if (err || !res.ok) {
console.error(err);
} else {
console.log(res)
request
.post('https://trialbot-api.line.me/v1/events')
.proxy(process.env.FIXIE_URL) // IPの固定化
.send({
to: [msg.content.from.toString()],
toChannel: 1383378250,
eventType: "138311608800106203",
content: {
contentType: 1,
toType: 1,
text: res.body.result
}
})
.set('Content-Type', 'application/json; charset=UTF-8')
.set('X-Line-ChannelID', process.env.CHANNEL_ID)
.set('X-Line-ChannelSecret', process.env.SECRET)
.set('X-Line-Trusted-User-With-ACL', process.env.MID)
.end(function(err, res){
if (err || !res.ok) {
console.error(err);
} else {
// Nothing
}
});
}
});
})
res.status(200).send("ok")
});
app.listen(app.get('port'), function() {
console.log("Node app is running at localhost:" + app.get('port'))
});
|
JavaScript
| 0.71068 |
@@ -714,18 +714,8 @@
ge:
-encodeURI(
msg.
@@ -721,17 +721,16 @@
.content
-)
,%0D%0A
|
2cdcad80068419360b0d5235e50ad777075f6fe6
|
make file executeable
|
bin.js
|
bin.js
|
#!/usr/bin/env node
var link = require('./')
var path = require('path')
var fs = require('fs')
if (!process.env.npm_package_name) {
console.error('You should run link-bin as an npm install hook')
process.exit(1)
}
var filenames = [].concat(process.argv[2] || [])
if (!filenames.length) {
try {
var pkg = require(path.resolve('./package.json'))
if (typeof pkg.bin === 'string') {
filenames.push(pkg.bin)
} else {
Object.keys(pkg.bin).forEach(function (key) {
filenames.push(pkg.bin[key])
})
}
} catch (err) {
// ...
}
}
filenames.forEach(function (filename) {
link(filename, function (err, bin) {
if (err) throw err
var target = path.join(path.dirname(filename), 'link-bin-' + path.basename(filename))
if (!fs.existsSync(target)) fs.rename(filename, target)
fs.writeFileSync(filename, bin)
})
})
|
JavaScript
| 0.000002 |
@@ -861,16 +861,50 @@
e, bin)%0A
+ fs.chmodSync(filename, 33261)%0A
%7D)%0A%7D)%0A
|
3cfff710ae2848f9175ce5baec7e24fe171f3d6a
|
add --domain option
|
bin.js
|
bin.js
|
#!/usr/bin/env node
var discovery = require('./')
var minimist = require('minimist')
var argv = minimist(process.argv.slice(2), {
alias: {port: 'p', host: 'h', server: 's'}
})
var rcvd = {}
var cmd = argv._[0]
var disc = discovery(argv)
if (cmd === 'listen') {
disc.listen(argv.port, onlisten)
} else if (cmd === 'lookup') {
disc.on('peer', onpeer)
lookup()
setInterval(lookup, 1000)
} else if (cmd === 'announce') {
if (!argv.port) throw new Error('You need to specify --port')
announce()
setInterval(announce, 1000)
} else {
console.error(
'dns-discovery [command]\n' +
' announce [name]\n' +
' --port=(port)\n' +
' --host=(optional host)\n' +
' --peer=(optional peer-id)\n' +
' --server=(optional discovery server)\n' +
' lookup [name]\n' +
' --server=(optional discovery server)\n' +
' listen\n' +
' --push\n' +
' --port=(optional port)\n' +
' --ttl=(optional ttl in seconds)\n'
)
process.exit(1)
}
function lookup () {
disc.lookup(argv._[1])
}
function announce () {
disc.announce(argv._[1], argv)
}
function onpeer (name, peer) {
var addr = peer.host + ':' + peer.host
if (rcvd[addr]) return
rcvd[addr] = true
console.log(name, peer)
}
function onlisten (err) {
if (err) throw err
console.log('Server is listening on port %d', argv.port || 53)
}
|
JavaScript
| 0.000001 |
@@ -168,16 +168,29 @@
ver: 's'
+, domain: 'd'
%7D%0A%7D)%0A%0Ava
@@ -780,32 +780,85 @@
ry server)%5Cn' +%0A
+ ' --domain=(optional authoritative domain)%5Cn'%0A
' lookup %5Bn
@@ -868,25 +868,24 @@
%5D%5Cn' +%0A '
-
--server
@@ -914,24 +914,77 @@
erver)%5Cn' +%0A
+ ' --domain=(optional authoritative domain)%5Cn'%0A
' liste
@@ -991,25 +991,24 @@
n%5Cn' +%0A '
-
--push%5Cn
@@ -1012,25 +1012,24 @@
h%5Cn' +%0A '
-
--port=(
@@ -1057,17 +1057,16 @@
'
-
--ttl=(o
@@ -1091,16 +1091,71 @@
onds)%5Cn'
+ +%0A ' --domain=(optional authoritative domain)%5Cn'
%0A )%0A p
|
903f1a2d2ad83f00d02bfb6f268a9c4092b086d7
|
fix help
|
bin.js
|
bin.js
|
#!/usr/bin/env node
const explain = require('explain-error')
const mapLimit = require('map-limit')
const resolve = require('resolve')
const garnish = require('garnish')
const mkdirp = require('mkdirp')
const subarg = require('subarg')
const bole = require('bole')
const http = require('http')
const path = require('path')
const pump = require('pump')
const opn = require('opn')
const fs = require('fs')
const bankai = require('./')
const argv = subarg(process.argv.slice(2), {
string: [ 'open', 'port' ],
boolean: [ 'optimize', 'verbose' ],
default: {
optimize: false,
open: false,
port: 8080
},
alias: {
css: 'c',
js: 'j',
open: 'o',
optimize: 'O',
port: 'p',
verbose: 'V',
version: 'v'
}
})
const usage = `
Usage:
$ bankai <command> [options]
Commands:
<default> Run 'bankai start'
start <filename> Start a bankai server
build <filename> <directory> Compile and export files to a directory
Options:
-c, --css=<subargs> Pass subarguments to sheetify
-h, --help Print usage
-j, --js=<subargs> Pass subarguments to browserify
-o, --open=<browser> Open html in a browser [default: system default]
-O, --optimize Optimize assets served by bankai [default: false]
-p, --port=<n> Bind bankai to <n> [default: 8080]
-V, --verbose Include debug messages
Examples:
$ bankai index.js -p 8080 # start bankai on port 8080
$ bankai index.js --open # open html in the browser
$ bankai -c [ -u sheetify-cssnext ] # use cssnext in sheetify
$ bankai -j [ -t brfs ] # use brfs in browserify
$ bankai build index.js dist/ # compile and export to dist/
$ bankai build -O index.js dist/ # optimize compiled files
`
main(argv)
function main (argv) {
if ((argv._[0] !== 'build') && (argv._[0] !== 'start')) {
argv._.unshift('start')
}
const cmd = argv._[0]
const _entry = argv._[1] || 'index.js'
const localEntry = './' + _entry.replace(/^.\//, '')
const entry = resolve.sync(localEntry, { basedir: process.cwd() })
const outputDir = argv._[2] || 'dist'
startLogging(argv.verbose)
if (argv.h) {
console.info(usage)
return process.exit()
}
if (argv.v) {
console.info(require('../package.json').version)
return process.exit()
}
if (cmd === 'start') {
start(entry, argv, handleError)
} else if (cmd === 'build') {
build(entry, outputDir, argv, function (err) {
if (err) throw err
process.exit()
})
} else {
console.error(usage)
return process.exit(1)
}
function handleError (err) {
if (err) throw err
}
}
function start (entry, argv, done) {
const assets = bankai(entry)
const port = argv.port
http.createServer((req, res) => {
switch (req.url) {
case '/': return assets.html(req, res).pipe(res)
case '/bundle.js': return assets.js(req, res).pipe(res)
case '/bundle.css': return assets.css(req, res).pipe(res)
default: return (res.statusCode = 404 && res.end('404 not found'))
}
}).listen(port, function () {
const relative = path.relative(process.cwd(), entry)
const addr = 'http://localhost:' + port
console.info('Started bankai for', relative, 'on', addr)
if (argv.open !== false) {
const app = (argv.open.length) ? argv.open : 'system browser'
opn(addr, { app: argv.open || null })
.catch((err) => done(explain(err, `err running ${app}`)))
.then(done)
}
})
}
function build (entry, outputDir, argv, done) {
mkdirp.sync(outputDir)
const assets = bankai(entry, argv)
const files = [ 'index.html', 'bundle.js', 'bundle.css' ]
mapLimit(files, Infinity, iterator, done)
function iterator (file, done) {
const file$ = fs.createWriteStream(path.join(outputDir, file))
const source$ = assets[file.replace(/^.*\./, '')]()
pump(source$, file$, done)
}
}
function startLogging (verbose) {
const level = (verbose) ? 'debug' : 'info'
const pretty = garnish({ level: level, name: 'bankai' })
pretty.pipe(process.stdout)
bole.output({ stream: pretty, level: level })
}
|
JavaScript
| 0.000002 |
@@ -537,16 +537,35 @@
verbose'
+, 'help', 'version'
%5D,%0A de
@@ -669,16 +669,31 @@
s: 'j',%0A
+ help: 'h',%0A
open
|
21c8470b66f800793a8d9f5855bf27d92cb71a15
|
Fix ping, attempting to make embedded about
|
bot.js
|
bot.js
|
client.login("")
var prefix = "px;"
client.on("message", function(message) {
if (message.author.equals(client.user)) return;
if (!message.content.startsWith(prefix)) return;
var args = message.content.substring(prefix.length).split(" ");
switch (args[0]) {
//ping command
case "ping":
const embed = new Discord.RichEmbed()
.setColor("#940000")
.addField(":ping_pong: Pong!", "Response time:" + client.ping + "ms")
.setFooter("Requested by " + message.author.username, message.author.displayAvatarURL)
.setTimestamp()
message.channel.send({embed});
break;
// about command
case "about":
message.channel.send("A Discord bot that features games, image manipulation, moderation and music commands; written in JavaScript Here are the developers: Rain , Kaiss, Inkydink, Yottabyte Inside")
break;
var version = "0.2 ";
// version command
case "version":
message.channel.send("The current version of PixaBot is " + 0.2 + " beta 1")
break;
case "kick":
message.channel.send("Coming Soon!")
break;
case "ban":
message.channel.send("Coming Soon!")
break;
case "help":
message.channel.send("coming soon!")
break;
case "coming soon":
message.channel.send("kick: px;kick ban: px;ban and help command")
break;
case "CanIbeMod?":
message.channel.send("no but you can be jailed if you want (from kaiss)")
break;
}
})
|
JavaScript
| 0 |
@@ -374,25 +374,25 @@
%0A
-
+%09
.setColor(%22#
@@ -415,18 +415,18 @@
- .addField
+%09.setTitle
(%22:p
@@ -458,16 +458,17 @@
se time:
+
%22 + clie
@@ -490,25 +490,25 @@
%0A
-
+%09
.setFooter(%22
@@ -593,17 +593,17 @@
-
+%09
.setTime
@@ -610,28 +610,18 @@
stamp()%0A
-
+%09%09
message.
@@ -643,28 +643,18 @@
mbed%7D);%0A
-
+%09%09
break;%0A%09
@@ -689,43 +689,126 @@
t%22:%0A
+%09
- message.channel.send(%22A
+const embed = new Discord.RichEmbed()%0A%09 .setColor(%22#940000%22)%0A %09%09.setTitle(%22About PixaBot%22, %22PixaBot is a
Dis
@@ -886,17 +886,16 @@
commands
-;
written
@@ -912,108 +912,170 @@
ript
- Here are the developers: Rain , Kaiss, Inkydink, Yottabyte Inside%22)%0A%09%09%09break;%0A%09var version = %220.2 %22
+.%22)%0A %09.setFooter(%22Requested by %22 + message.author.username, message.author.displayAvatarURL)%0A %09.setTimestamp()%0A%09%09message.channel.send(%7Bembed%7D)
;%0A%09/
|
e2a14760e0a695e90075abe68140b72b5f73a3ee
|
add comment
|
bot.js
|
bot.js
|
var http = require('http');
var createHandler = require('github-webhook-handler');
var handler = createHandler({ path: '/webhook', secret: 'sekrit' });
var host = (process.env.VCAP_APP_HOST || 'localhost');
var port = (process.env.VCAP_APP_PORT || 7777);
// Start server
http.createServer(function (req, res) {
handler(req, res, function (err) {
res.statusCode = 404
res.end('no such location');
console.log("oops?");
console.log(req.rawHeaders);
});
}).listen(port, host);
handler.on('error', function (err) {
console.error('Error:', err.message);
});
handler.on('pull_request', function (event) {
console.log('Received an %s pull_request event for %s PR #%s',
event.payload.action,
event.payload.repository.name,
event.payload.pull_request.number);
console.log('event.payload.pull_request.body');
});
|
JavaScript
| 0 |
@@ -1,12 +1,16 @@
+// %0A
var http = r
|
2ff29dbca6ddd5039e3f9a3ddf7cf93020b8f551
|
Remove replying to mentions
|
bot.js
|
bot.js
|
/**
* srifqi's Bot for Telegram
* License: MIT License
*/
console.log("srifqi's Bot for Telegram")
console.log('License: MIT License')
console.log('Initialising bot...')
const BOT_NAME = 'srifqiBot'
const TelegramBot = require('node-telegram-bot-api')
const math = require('mathjs')
const fetch = require('node-fetch')
const express = require('express')
const PORT = process.env.PORT || 80
const server = express()
const httpserver = server.listen(PORT)
console.log('Listening on PORT ' + PORT)
server.use(express.static('./public/'))
const app = new TelegramBot(process.env.BOT_TOKEN, {polling: true})
// Using Markdown
const ABOUT = '@srifqiBot\n' +
"srifqi's Bot on Telegram\n" +
'License: MIT License\n\n' +
'Found a bug or have ideas? Go to [issue tracker](https://github.com/srifqi/srifqiBotTelegram/issues).'
/*
about - About this bot
calc - Do simple math calculation
help - Display command list
nameplease - Give random name
rolldice - Roll a or n dice
tosscoin - Toss a or n coin(s)
*/
const HELP = 'Below is a list of my commands:\n' +
'/about - About this bot\n' +
'/calc <expr> - Do simple math calculation\n' +
'/help - Display command list\n' +
'/nameplease - Give random name\n' +
'/rolldice - Roll a dice\n' +
'/rolldice <n> - Roll n dice\n' +
'/tosscoin - Toss a coin\n' +
'/tosscoin <n> - Toss n coins'
var botStart = (msg) => {
// console.log('start', msg.from)
app.sendMessage(msg.chat.id, 'Welcome!')
app.sendMessage(msg.chat.id, HELP)
}
var botAbout = (msg) => {
app.sendMessage(msg.chat.id, ABOUT, {parse_mode: 'Markdown'})
}
var botHelp = (msg) => {
app.sendMessage(msg.chat.id, HELP)
}
var botCalc = (msg) => {
if (new RegExp('/calc(?:@' + BOT_NAME + ')?\\s+(\\S.*)', 'i').test(msg.text)) {
var result = ''
try {
result = math.eval(new RegExp('/calc(?:@' + BOT_NAME + ')?\\s+(\\S.*)', 'i').exec(msg.text)[1])
} catch (e) {
result = 'ERROR when processing formula.'
}
app.sendMessage(msg.chat.id, result, {reply_to_message_id: msg.message_id})
} else {
app.sendMessage(msg.chat.id, '[CA] What to calculate? Reply this message to answer.',
{reply_to_message_id: msg.message_id})
}
}
var botRollDice = (msg) => {
var amount = 1
if (new RegExp('/rolldice(?:@' + BOT_NAME + ')?\\s+(.+)', 'i').test(msg.text)) {
amount = Number(new RegExp('/rolldice(?:@' + BOT_NAME + ')?\\s+(.+)', 'i').exec(msg.text)[1])
}
if (isNaN(amount))
amount = 1
if (amount > 100) {
app.sendMessage(msg.chat.id, 'Amount of dice is too large. Maximum amount is 100.')
return
}
var result = ''
for (var i = 0; i < amount; i++) {
result += (i < 1 ? '' : ' ') + Math.ceil(Math.random() * 6)
}
app.sendMessage(msg.chat.id, result, {reply_to_message_id: msg.message_id})
}
var botTossCoin = (msg) => {
var amount = 1
if (new RegExp('/tosscoin(?:@' + BOT_NAME + ')?\\s+(.+)', 'i').test(msg.text)) {
amount = Number(new RegExp('/tosscoin(?:@' + BOT_NAME + ')?\\s+(.+)', 'i').exec(msg.text)[1])
}
if (isNaN(amount))
amount = 1
if (amount > 100) {
app.sendMessage(msg.chat.id, 'Amount of coin is too large. Maximum amount is 100.')
return
}
var result = ''
for (var i = 0; i < amount; i++) {
result += (i < 1 ? '' : ' ') +
['head', 'tail'][Math.ceil(Math.random() * 2) - 1]
}
app.sendMessage(msg.chat.id, result, {reply_to_message_id: msg.message_id})
}
var botRandomName = (msg) => {
fetch('https://randomuser.me/api/?inc=name&noinfo')
.then((res) => {
return res.json()
})
.then((json) => {
var name = json.results[0].name.first + " " + json.results[0].name.last
app.sendMessage(msg.chat.id, name, {reply_to_message_id: msg.message_id})
})
}
app.onText(/\/start/i, botStart)
app.onText(/\/about/i, botAbout)
app.onText(/\/help/i, botHelp)
app.onText(new RegExp('/calc(?:@' + BOT_NAME + ')?(?: (.+)?)?', 'i'), botCalc)
app.onText(new RegExp('/rolldice(?:@' + BOT_NAME + ')?(?: (.+)?)?', 'i'), botRollDice)
app.onText(new RegExp('/tosscoin(?:@' + BOT_NAME + ')?(?: (.+)?)?', 'i'), botTossCoin)
app.onText(/\/nameplease/i, botRandomName)
app.onText(/\/nameplz/i, botRandomName) // This one is synonym as above.
app.onText(new RegExp('@' + BOT_NAME + '\\b', 'i'), (msg) => app.sendMessage(msg.chat.id, 'Hey!'))
// logging | botCalc
app.onText(/.*/i, (msg) => {
console.log(msg.from.username || '', ':', msg.text)
if (msg.hasOwnProperty('reply_to_message')) {
if (msg.reply_to_message.from.username === BOT_NAME &&
msg.reply_to_message.hasOwnProperty('text')) {
if (msg.reply_to_message.text.substr(0, 4) === '[CA]') {
msg.text = '/calc@' + BOT_NAME + ' ' + msg.text
botCalc(msg)
}
}
}
})
app.on('sticker', (msg) => app.sendMessage(msg.chat.id, '👍'))
console.log('Bot started.')
// setInterval(() => console.log(Date.now()), 1e4)
|
JavaScript
| 0 |
@@ -622,16 +622,17 @@
Markdown
+.
%0Aconst A
@@ -1380,44 +1380,8 @@
%3E %7B%0A
- // console.log('start', msg.from)%0A
ap
@@ -4184,108 +4184,8 @@
e.%0A%0A
-app.onText(new RegExp('@' + BOT_NAME + '%5C%5Cb', 'i'), (msg) =%3E app.sendMessage(msg.chat.id, 'Hey!'))%0A%0A
// l
@@ -4283,16 +4283,40 @@
sg.text)
+ // Chat log in console.
%0A if (m
@@ -4727,56 +4727,4 @@
.')%0A
-%0A// setInterval(() =%3E console.log(Date.now()), 1e4)%0A
|
6624856bee454446857af16605222dcc4dc9d2bc
|
Add Apache-2.0 copyright notice
|
bub.js
|
bub.js
|
var fs = require('fs');
var path = require('path');
var request = require('hopjs-request');
var util = require('util');
// Constructor for the whole darn thing
var Bub = function (config) {
var BASE_URL = 'https://api.telegram.org/bot' + config.token;
var TIMEOUT = config.timeout ? config.timeout : 864000;
var offset = null;
// A reference to `this`, required for emitting events
var self = this;
// Start checking for updates
self.init = function (update_id) {
// Allow a custom update_id
if (update_id) offset = update_id;
// If there are updates, handle them
self.getUpdates(offset, null, TIMEOUT, handleUpdates);
};
function handleUpdates(body) {
body.result.forEach(function (result, index, results) {
// Handle text messages
if (result.message.text) {
var command = result.message.text.split(' ')[0];
var listeners = util.inspect(self.listeners(command));
if (listeners !== '[]') self.emit(command, result);
else self.emit('_default', result);
}
// TODO: Handle _joinGroup and similar messages
// Update offset
offset = result.update_id + 1;
});
// Check again after handling updates
self.init();
}
// Generic method to send HTTPS requests
function sendRequest(params, callback) {
request.post(params, function (err, res, body) {
if (err) console.error(err);
if (callback) callback(JSON.parse(body));
});
}
// API methods implemented in JavaScript
self.getMe = function (callback) {
sendRequest({
url: BASE_URL + '/getMe',
}, callback);
};
self.sendMessage = function (chat_id, text, disable_web_page_preview, reply_to_message_id, reply_markup, callback) {
sendRequest({
url: BASE_URL + '/sendMessage',
form: {
chat_id: chat_id,
text: text,
disable_web_page_preview: disable_web_page_preview,
reply_to_message_id: reply_to_message_id,
reply_markup: reply_markup
}
}, callback);
};
self.forwardMessage = function (chat_id, from_chat_id, message_id, callback) {
sendRequest({
url: BASE_URL + '/forwardMessage',
form: {
chat_id: chat_id,
from_chat_id: from_chat_id,
message_id: message_id
}
}, callback);
};
self.sendPhoto = function (chat_id, photo, caption, reply_to_message_id, reply_markup, callback) {
sendRequest({
url: BASE_URL + '/sendPhoto',
formData: {
chat_id: chat_id,
photo: photo,
caption: caption,
reply_to_message_id: reply_to_message_id,
reply_markup: reply_markup
}
}, callback);
};
self.sendAudio = function (chat_id, audio, reply_to_message_id, reply_markup, callback) {
sendRequest({
url: BASE_URL + '/sendAudio',
formData: {
chat_id: chat_id,
audio: audio,
reply_to_message_id: reply_to_message_id,
reply_markup: reply_markup
}
}, callback);
};
self.sendDocument = function (chat_id, document, reply_to_message_id, reply_markup, callback) {
sendRequest({
url: BASE_URL + '/sendDocument',
formData: {
chat_id: chat_id,
document: document,
reply_to_message_id: reply_to_message_id,
reply_markup: reply_markup
}
}, callback);
};
self.sendSticker = function (chat_id, sticker, reply_to_message_id, reply_markup, callback) {
sendRequest({
url: BASE_URL + '/sendSticker',
formData: {
chat_id: chat_id,
sticker: sticker,
reply_to_message_id: reply_to_message_id,
reply_markup: reply_markup
}
}, callback);
};
self.sendVideo = function (chat_id, video, reply_to_message_id, reply_markup, callback) {
sendRequest({
url: BASE_URL + '/sendVideo',
formData: {
chat_id: chat_id,
video: video,
reply_to_message_id: reply_to_message_id,
reply_markup: reply_markup
}
}, callback);
};
self.sendLocation = function (chat_id, latitude, longitude, reply_to_message_id, reply_markup) {
sendRequest({
url: BASE_URL + '/sendLocation',
form: {
chat_id: chat_id,
latitude: latitude,
longitude: longitude,
reply_to_message_id: reply_to_message_id,
reply_markup: reply_markup
}
}, callback);
};
self.sendChatAction = function (chat_id, action) {
sendRequest({
url: BASE_URL + '/sendChatAction',
form: {
chat_id: chat_id,
action: action
}
}, callback);
};
self.getUserProfilePhotos = function (user_id, offset, limit, callback) {
sendRequest({
url: BASE_URL + '/getUserProfilePhotos',
form: {
user_id: user_id,
offset: offset,
limit: limit
}
}, callback);
};
self.getUpdates = function (offset, limit, timeout, callback) {
sendRequest({
url: BASE_URL + '/getUpdates',
form: {
offset: offset,
limit: limit,
timeout: timeout
}
}, callback);
};
// this.setWebhook = function () {};
return this;
};
util.inherits(Bub, require('events').EventEmitter);
module.exports = Bub;
|
JavaScript
| 0 |
@@ -1,12 +1,611 @@
+/**%0A * Copyright 2015 Darshak Parikh%0A * %0A * Licensed under the Apache License, Version 2.0 (the %22License%22);%0A * you may not use this file except in compliance with the License.%0A * You may obtain a copy of the License at%0A * %0A * http://www.apache.org/licenses/LICENSE-2.0%0A * %0A * Unless required by applicable law or agreed to in writing, software%0A * distributed under the License is distributed on an %22AS IS%22 BASIS,%0A * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A * See the License for the specific language governing permissions and%0A * limitations under the License.%0A */%0A%0A
var fs = req
@@ -5815,8 +5815,9 @@
s = Bub;
+%0A
|
bcf7b565a19f9a515990bcf4d34ad4e03915a256
|
Revert "Added distinguish errors and warnings as text ERR and WARN"
|
cli.js
|
cli.js
|
/*eslint no-console: ["error", {allow: ["log"]}] */
var validate = require('./index.js');
var colors = require('colors/safe');
var cliff = require('cliff');
var pluralize = require('pluralize');
var bytes = require('bytes');
var fs = require('fs');
module.exports = function (dir, options) {
if (fs.existsSync(dir)) {
validate.BIDS(dir, options, function (issues, summary) {
var errors = issues.errors;
var warnings = issues.warnings;
if (issues.errors.length === 1 && issues.errors[0].code === '61') {
console.log(colors.red("(ERR) The directory " + dir + " failed an initial Quick Test. This means the basic names and structure of the files and directories do not comply with BIDS specification. For more info go to http://bids.neuroimaging.io/"));
} else if (issues.config && issues.config.length >= 1) {
console.log(colors.red('(ERR) Invalid Config File'));
for (var i = 0; i < issues.config.length; i++) {
var issue = issues.config[i];
issue.file.file = {relativePath: issue.file.path};
issue.files = [issue.file];
}
logIssues(issues.config, 'red', options);
} else if (errors.length >= 1 || warnings.length >= 1) {
logIssues(errors, 'red', options);
logIssues(warnings, 'yellow', options);
}
else {
console.log(colors.green("This dataset appears to be BIDS compatible."));
}
logSummary(summary);
if (issues === 'Invalid' || errors && errors.length >= 1 || issues.config && issues.config.length >= 1) {process.exit(1);}
});
} else {
console.log(colors.red(dir + " does not exist"));
process.exit(2);
}
};
function logIssues (issues, color, options) {
for (var i = 0; i < issues.length; i++) {
var issue = issues[i];
var type = (color==red ? 'ERR': 'WARN');
console.log('\t' + colors[color]((i + 1) + ': (' + type + ') ' issue.reason + ' (code: ' + issue.code + ' - ' + issue.key + ')'));
for (var j = 0; j < issue.files.length; j++) {
var file = issues[i].files[j];
if (!file || !file.file) {continue;}
console.log('\t\t.' + file.file.relativePath);
if (options.verbose) {console.log('\t\t\t' + file.reason);}
if (file.line) {
var msg = '\t\t\t@ line: ' + file.line;
if (file.character) {
msg += ' character: ' + file.character;
}
console.log(msg);
}
if (file.evidence) {
console.log('\t\t\tEvidence: ' + file.evidence);
}
}
if (issue.additionalFileCount > 0) {
console.log('\t\t'+colors[color]('... and '+issue.additionalFileCount+' more files having this issue (Use --verbose to see them all).'));
}
console.log();
}
}
function logSummary (summary) {
if (summary) {
var numSessions = summary.sessions.length > 0 ? summary.sessions.length : 1;
// data
var column1 = [
summary.totalFiles + ' ' + pluralize('File', summary.totalFiles) + ', ' + bytes(summary.size),
summary.subjects.length + ' - ' + pluralize('Subject', summary.subjects.length),
numSessions + ' - ' + pluralize('Session', numSessions)
],
column2 = summary.tasks,
column3 = summary.modalities;
var longestColumn = Math.max(column1.length, column2.length, column3.length);
var pad = ' ';
// headers
var headers = [pad, colors.blue.underline('Summary:') + pad, colors.blue.underline('Available Tasks:') + pad, colors.blue.underline('Available Modalities:')]
// rows
var rows = [headers];
for (var i = 0; i < longestColumn; i++) {
var val1, val2, val3;
val1 = column1[i] ? column1[i] + pad : '';
val2 = column2[i] ? column2[i] + pad : '';
val3 = column3[i] ? column3[i] : '';
rows.push([' ', val1, val2, val3]);
}
console.log(cliff.stringifyRows(rows));
console.log();
}
}
|
JavaScript
| 0 |
@@ -605,23 +605,16 @@
rs.red(%22
-(ERR)
The dire
@@ -936,15 +936,8 @@
ed('
-(ERR)
Inva
@@ -1992,57 +1992,8 @@
i%5D;%0A
- var type = (color==red ? 'ERR': 'WARN');%0A
@@ -2046,24 +2046,11 @@
':
-(
' +
- type + ') '
iss
|
a0a02c62ed406ee06c15b35a0ae388b1d697bd1f
|
Add info about quotes to output of help
|
cli.js
|
cli.js
|
var tester = require('./main');
var fs = require('fs');
if (process.argv.length < 4 || process.argv[2] === 'help') {
console.log('== help');
console.log('Prints this message.');
console.log('== password <password>');
console.log('Check <password> against all app ids listed in app-list.txt');
} else if (process.argv[2] === 'password') {
var appIDs = fs.readFileSync('app-list.txt').toString().split('\n');
var currentAppID = 0;
var password = process.argv.slice(3, process.argv.length).join(' ');
var queries = 0;
var elapsed = 0;
var rateLimited = false;
var done = 0;
console.log();
setInterval(function() {
elapsed++;
process.stdout.write('\x1b[1000D\x1b[K\x1b[A');
console.log((done + '/' + appIDs.length + ' ').substr(0,10) + ' ' + (queries + 'q/s ').substr(0,8) + ' ' + (elapsed + 's ').substr(0,5) + ' ' + (rateLimited ? '! RATE LIMITED (waiting) !' : ''));
queries = 0;
if (done === appIDs.length) {
console.log('Done!');
return process.exit();
}
}, 1000);
process.on('SIGINT', function() {
process.stdout.write('\n\r');
process.exit();
});
function nextAppID() {
if (currentAppID === appIDs.length) return;
if (rateLimited) {
return setTimeout(function() {
nextAppID();
}, 15000);
}
var appID = appIDs[currentAppID++];
queries++;
tester.tryPassword(password, appID, function(err, result) {
done++;
if (err) {
rateLimited = true;
currentAppID--;
} else {
rateLimited = false;
if (!result) {
} else if (result.url) {
console.log('[found url] app=' + appID + ', password=' + password + ', url=' + result.url + '\n');
} else if (result.response) {
console.log('[found response] app=' + appID + ', password=' + password + ', response=' + result.response + '\n');
} else {
console.log('[found weird] app=' + appID + ', password=' + password + ', result=' + JSON.stringify(result) + '\n');
}
nextAppID();
}
});
}
for (var w = 0; w < 50; w++) nextAppID();
}
|
JavaScript
| 0 |
@@ -287,16 +287,36 @@
list.txt
+. Don%5C't use quotes!
');%0A%7D el
|
926c0396389778a5376e7c0248215a054851dd7f
|
fix exit code
|
cli.js
|
cli.js
|
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const { changelog, release, init } = require('./');
const args = [].slice.call(process.argv, 2);
const cmd = args[0];
const dryRun = args.indexOf('-d') !== -1 || args.indexOf('--dry-run') !== -1;
const ignoreStaged = args.indexOf('-i') !== -1 || args.indexOf('--ignore-not-staged') !== -1;
const help = args.indexOf('-h') !== -1 || args.indexOf('--help') !== -1;
const mode = cmd === 'add' ? args[1] : null;
const exit = (err) => {
if (err) console.error(err.message);
process.exit(1);
};
const version = JSON.parse(fs.readFileSync(path.resolve(__dirname, './package.json')).toString()).version;
function cli() {
if (help) {
displayHelp();
return exit();
}
if (cmd === 'init') return init({ mode, dryRun, ignoreStaged }, exit);
if (cmd === 'add') return release({ mode, dryRun, ignoreStaged }, exit);
if (cmd === 'changelog') return changelog({ mode }, exit);
if (cmd !== 'help') console.info('Unknown command !!');
displayHelp();
return exit();
}
function displayHelp() {
console.log(`
Usage: js-release <command>
Version: ${version}
Command:
* js-release help display help (current view)
* js-release changelog display changelog, merge commits since last release
* js-release add <patch|minor|major> create a new (patch|minor|major) release
* js-release init create the first release extracted from the package.json version
Options:
* -d --dry-run
* -i --ignore-not-staged
* -h --help
`);
}
cli();
|
JavaScript
| 0.000697 |
@@ -559,17 +559,27 @@
ss.exit(
-1
+err ? 1 : 0
);%0A%7D;%0A%0Ac
|
bea737e6ae9456347257292fe5c56a5e357f0a5d
|
Fix bug in CLI with exit code when provided with invalid file path
|
cli.js
|
cli.js
|
#!/usr/bin/env node
'use strict';
/*
* Dependencies.
*/
var mdast,
fs,
pack;
mdast = require('./');
fs = require('fs');
pack = require('./package.json');
/*
* Detect if a value is expected to be piped in.
*/
var expextPipeIn;
expextPipeIn = !process.stdin.isTTY;
/*
* Arguments.
*/
var argv;
argv = process.argv.slice(2);
/*
* Command.
*/
var command;
command = Object.keys(pack.bin)[0];
/**
* Help.
*/
function help() {
return [
'',
'Usage: ' + command + ' [options] file',
'',
pack.description,
'',
'Options:',
'',
' -h, --help output usage information',
' -v, --version output version number',
' -a, --ast output AST information',
' --options output available settings',
' -o, --option <option> specify settings',
'',
'Usage:',
'',
'# Note that bash does not allow reading/writing to the ' +
'same through pipes',
'',
'# Pass `Readme.md` through mdast',
'$ ' + command + ' Readme.md > Readme-new.md',
'',
'# Pass stdin through mdast, with options',
'$ cat Readme.md | ' + command + ' -o ' +
'"setex-headings, bullet: *" > Readme-new.md'
].join('\n ') + '\n';
}
/**
* Fail w/ help message.
*/
function fail() {
process.stderr.write(help());
process.exit(1);
}
/**
* Log available options.
*
* @return {string}
*/
function getOptions() {
return [
'',
'# Options',
'',
'Both camel- and dash-cased options are allowed. Some options start',
'with `prefer`, this can be ignored in the CLI.',
'',
'## [Parse](https://github.com/wooorm/mdast#mdastparsevalue-options)',
'',
'- `gfm` (boolean, default: true)',
'- `tables` (boolean, default: true)',
'- `pedantic` (boolean, default: false)',
'- `breaks` (boolean, default: false)',
'- `footnotes` (boolean, default: false)',
'',
'## [Stringify](https://github.com/wooorm/mdast#' +
'mdaststringifyast-options)',
'',
'- `setex-headings` (boolean, default: false)',
'- `reference-links` (boolean, default: false)',
'- `reference-footnotes` (boolean, default: true)',
'- `fences` (boolean, default: false)',
'- `bullet` ("-", "*", or "+", default: "-")',
'- `horizontal-rule` ("-", "*", or "_", default: "*")',
'- `horizontal-rule-repetition` (number, default: 3)',
'- `horizontal-rule-spaces` (boolean, default: false)',
'- `strong` ("_", or "*", default: "*")',
'- `emphasis` ("_", or "*", default: "_")',
'',
'Settings are specified as follows:',
'',
'```',
'$ ' + command + ' --option "some-option:some-value"',
'# Multiple options:',
'$ ' + command + ' --option "emphasis:*,strong:_"',
'```'
].join('\n ') + '\n';
}
/**
* Transform a dash-cased string to camel-cased.
*
* @param {string} value
* @return {string}
*/
function camelCase(value) {
return value.toLowerCase().replace(/-([a-z])/gi, function ($0, $1) {
return $1.toUpperCase();
});
}
/*
* Program.
*/
var index,
expectOption,
expectAST,
options,
files;
/**
* Run the program.
*
* @param {string} value
*/
function program(value) {
var ast;
if (!value.length) {
fail();
} else {
ast = mdast.parse(value, options);
if (expectAST) {
console.log(ast);
} else {
console.log(mdast.stringify(ast, options));
}
}
}
if (
argv.indexOf('--help') !== -1 ||
argv.indexOf('-h') !== -1
) {
console.log(help());
} else if (
argv.indexOf('--version') !== -1 ||
argv.indexOf('-v') !== -1
) {
console.log(pack.version);
} else if (
argv.indexOf('--options') !== -1
) {
console.log(getOptions());
} else {
index = argv.indexOf('--ast');
if (index === -1) {
index = argv.indexOf('-a');
}
if (index !== -1) {
expectAST = true;
argv.splice(index, 1);
}
files = [];
options = {};
argv.forEach(function (argument) {
if (argument === '--option' || argument === '-o') {
expectOption = true;
} else if (!expectOption) {
files.push(argument);
} else {
argument
.split(',')
.map(function (value) {
var values;
values = value.split(':');
return [
camelCase(values.shift().trim()),
values.join(':').trim()
];
})
.map(function (values) {
var key,
value;
key = values[0];
value = values[1];
if (
key === 'setexHeadings' ||
key === 'referenceLinks' ||
key === 'referenceFootnotes' ||
key === 'fences'
) {
key = 'prefer' + key.charAt(0).toUpperCase() +
key.slice(1);
}
if (value === 'true') {
value = true;
} else if (value === 'false') {
value = false;
} else if (value === '') {
value = true;
} else if (Number(value) === Number(value)) {
value = Number(value);
}
return [key, value];
})
.forEach(function (values) {
options[values[0]] = values[1];
});
expectOption = false;
}
});
if (expectOption) {
fail();
} else if (!expextPipeIn && !files.length) {
fail();
} else if (
(expextPipeIn && files.length) ||
(!expextPipeIn && files.length !== 1)
) {
process.stderr.write('mdast currently expects one file.\n');
process.exit(1);
}
if (files[0]) {
fs.readFile(files[0], function (exception, content) {
if (exception) {
throw exception;
}
program(content.toString());
});
} else {
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', program);
}
}
|
JavaScript
| 0 |
@@ -6488,23 +6488,87 @@
-throw exception
+process.stderr.write(exception.message + '%5Cn');%0A process.exit(1)
;%0A
|
d479ff47834eaf4dcb4b6b1b71065824a9acfa66
|
add --output-unreleased
|
cli.js
|
cli.js
|
#!/usr/bin/env node
'use strict';
var addStream = require('add-stream');
var conventionalChangelog = require('conventional-changelog');
var fs = require('fs');
var meow = require('meow');
var tempfile = require('tempfile');
var _ = require('lodash');
var resolve = require('path').resolve;
var cli = meow({
help: [
'Usage',
' conventional-changelog',
'',
'Example',
' conventional-changelog -i CHANGELOG.md --same-file',
'',
'Options',
' -i, --infile Read the CHANGELOG from this file',
'',
' -o, --outfile Write the CHANGELOG to this file',
' If unspecified, it prints to stdout',
'',
' -s, --same-file Ouputting to the infile so you don\'t need to specify the same file as outfile',
'',
' -p, --preset Name of the preset you want to use. Must be one of the following:',
' angular, atom, codemirror, ember, eslint, express, jquery, jscs or jshint',
'',
' -k, --pkg A filepath of where your package.json is located',
' Default is the closest package.json from cwd',
'',
' -a, --append Should the newer release be appended to the older release',
' Default: false',
'',
' -r, --release-count How many releases to be generated from the latest',
' If 0, the whole changelog will be regenerated and the outfile will be overwritten',
' Default: 1',
'',
' -v, --verbose Verbose output',
' Default: false',
'',
' -n, --config A filepath of your config script',
' This value is ignored if preset is specified',
'',
' -c, --context A filepath of a json that is used to define template variables'
]
}, {
alias: {
i: 'infile',
o: 'outfile',
s: 'sameFile',
p: 'preset',
k: 'pkg',
a: 'append',
r: 'releaseCount',
v: 'verbose',
n: 'config',
c: 'context'
}
});
var flags = cli.flags;
var infile = flags.infile;
var outfile = flags.outfile;
var sameFile = flags.sameFile;
var append = flags.append;
var releaseCount = flags.releaseCount;
if (infile && infile === outfile) {
sameFile = true;
} else if (sameFile) {
if (infile) {
outfile = infile;
} else {
console.error('infile must be provided if same-file flag presents.');
process.exit(1);
}
}
var options = _.omit({
preset: flags.preset,
pkg: {
path: flags.pkg
},
append: append,
releaseCount: releaseCount
}, _.isUndefined);
if (flags.verbose) {
options.warn = console.warn.bind(console);
}
var templateContext;
var outStream;
try {
if (flags.context) {
templateContext = require(resolve(process.cwd(), flags.context));
}
if (flags.config) {
options.config = require(resolve(process.cwd(), flags.config));
}
} catch (err) {
console.error('Failed to get file. ' + err);
process.exit(1);
}
var changelogStream = conventionalChangelog (options, templateContext)
.on('error', function (err) {
if (flags.verbose) {
console.error(err.stack);
} else {
console.error(err.toString());
}
process.exit(1);
});
function noInputFile() {
if (outfile) {
outStream = fs.createWriteStream(outfile);
} else {
outStream = process.stdout;
}
changelogStream
.pipe(outStream);
}
if (infile && releaseCount !== 0) {
var readStream = fs.createReadStream(infile)
.on('error', function () {
if (flags.verbose) {
console.warn('infile does not exist.');
}
if (sameFile) {
noInputFile();
}
});
if (sameFile) {
if (options.append) {
changelogStream
.pipe(fs.createWriteStream(outfile, {
flags: 'a'
}));
} else {
var tmp = tempfile();
changelogStream
.pipe(addStream(readStream))
.pipe(fs.createWriteStream(tmp))
.on('finish', function () {
fs.createReadStream(tmp)
.pipe(fs.createWriteStream(outfile));
});
}
} else {
if (outfile) {
outStream = fs.createWriteStream(outfile);
} else {
outStream = process.stdout;
}
var stream;
if (options.append) {
stream = readStream
.pipe(addStream(changelogStream));
} else {
stream = changelogStream
.pipe(addStream(readStream));
}
stream
.pipe(outStream);
}
} else {
noInputFile();
}
|
JavaScript
| 0.000012 |
@@ -1597,32 +1597,103 @@
lt: 1',%0A '',%0A
+ ' -u, --output-unreleased Output unreleased changelog',%0A '',%0A
' -v, --ver
@@ -1722,24 +1722,24 @@
se output',%0A
-
'
@@ -2178,24 +2178,51 @@
easeCount',%0A
+ u: 'outputUnreleased',%0A
v: 'verb
@@ -2803,16 +2803,60 @@
aseCount
+,%0A outputUnreleased: flags.outputUnreleased
%0A%7D, _.is
@@ -3254,24 +3254,24 @@
exit(1);%0A%7D%0A%0A
+
var changelo
@@ -3301,17 +3301,16 @@
hangelog
-
(options
|
dfcc29dc2850cf97686d5a036fc3ec619094b2ea
|
fix clone and always listen+clone when running commands
|
cli.js
|
cli.js
|
#!/usr/bin/env node
var path = require('path')
var Dat = require('./')
var minimist = require('minimist')
var EOL = require('os').EOL
var url = require('url')
var stdout = require('stdout-stream')
var fs = require('fs')
var path = require('path')
var debug = require('debug')('dat.cli')
var defaultMessage = "Usage: dat <command> [<args>]" + EOL + EOL + "Enter 'dat help' for help"
var argv = minimist(process.argv.slice(2), {boolean: true})
var onerror = function(err) {
console.error('Error: '+err.message)
process.exit(2)
}
var first = argv._[0] || ''
var bin = {
cat: './bin/cat',
export: './bin/cat',
import: './bin/import',
init: './bin/init',
help: './bin/help',
version: './bin/version',
pull: './bin/pull',
push: './bin/push',
clone: './bin/clone',
listen: './bin/listen'
}
if (!bin.hasOwnProperty(first)) {
console.error(defaultMessage)
process.exit(1)
}
var dat = Dat(argv.path || '.', {init:false}, function(err) {
if (err) return onerror(err)
require(bin[first])(dat, argv, function(err) {
if (err) return onerror(err)
})
})
|
JavaScript
| 0 |
@@ -282,16 +282,105 @@
.cli')%0A%0A
+var argv = minimist(process.argv.slice(2), %7Bboolean: true%7D)%0Avar first = argv._%5B0%5D %7C%7C ''%0A%0A
var defa
@@ -474,62 +474,81 @@
var
-argv = minimist(process.argv.slice(2), %7Bboolean: true%7D
+badMessage = %5B'Command not found: ' + first, '', defaultMessage%5D.join(EOL
)%0A%0Av
@@ -640,36 +640,8 @@
%0A%7D%0A%0A
-var first = argv._%5B0%5D %7C%7C ''%0A
%0Avar
@@ -936,23 +936,19 @@
e.error(
-default
+bad
Message)
@@ -978,96 +978,228 @@
ar d
-at = Dat(argv.path %7C%7C '.', %7Binit:false%7D, function(err) %7B%0A if (err) return onerror(err)%0A
+ir = (first === 'clone' && argv._%5B2%5D) %7C%7C argv.path %7C%7C '.' // leaky%0A%0Avar dat = Dat(dir, %7Binit:false%7D, function(err) %7B%0A if (err) return onerror(err)%0A%0A var execCommand = function(err) %7B%0A if (err) return onerror(err)%0A
re
@@ -1239,32 +1239,34 @@
tion(err) %7B%0A
+
if (err) return
@@ -1284,9 +1284,661 @@
)%0A
-%7D)%0A%7D)
+ close()%0A %7D)%0A %7D%0A%0A if (first !== 'listen' && !dat.rpcClient) return dat.listen(argv.port, argv, execCommand)%0A execCommand()%0A%7D)%0A%0Afunction close() %7B%0A // if _server exists it means dat is the rpc server%0A if (dat._server) %7B%0A // since the server process can't exit yet we must manually close stdout%0A stdout.end()%0A%0A // if there aren't any active connections then we can close the server%0A if (dat.connections.sockets.length === 0) dat.close()%0A%0A // otherwise wait for the current connections to close%0A dat.connections.on('idle', function() %7B%0A debug('dat close due to idle')%0A dat.close()%0A %7D)%0A%0A %7D else %7B%0A dat.close()%0A %7D%0A%7D
|
214551ee380908718c49ef64bf7b3705dff5b246
|
Print brightness when not TTY
|
cli.js
|
cli.js
|
#!/usr/bin/env node
'use strict';
var brightness = require('brightness');
var meow = require('meow');
var progressControl = require('progress-control');
var chalk = require('chalk');
var cliCursor = require('cli-cursor');
var cli = meow({
help: [
'Example',
' $ brightness',
' $ brightness 0.8'
]
});
try {
if (!cli.input.length) {
brightness.get(function (err, val) {
if (err) {
console.error(err.message);
process.exit(1);
}
brightness.set(val, function (err) {
if (err) {
console.error(err.message);
process.exit(1);
}
function updateBar(val) {
brightness.set(val, function (err) {
if (err) {
console.error(err.message);
process.exit(1);
}
});
bar.update(val, {val: val * 100 + '%'});
}
cliCursor.hide();
var text = '[:bar] :val ' + chalk.dim('Use up/down arrows');
var bar = progressControl(text, {total: 10}, {
up: function () {
val = Math.min(Math.round((val + 0.1) * 10) / 10, 1);
updateBar(val);
},
down: function () {
val = Math.max(Math.round((val - 0.1) * 10) / 10, 0);
updateBar(val);
}
});
updateBar(val);
});
});
return;
}
brightness.set(parseFloat(cli.input[0], 10), function (err) {
if (err) {
console.error(err.message);
process.exit(1);
}
});
} catch (err) {
console.error(err.message);
process.exit(1);
}
|
JavaScript
| 0.000048 |
@@ -450,16 +450,87 @@
;%0A%09%09%09%7D%0A%0A
+%09%09%09if (!process.stdin.isTTY) %7B%0A%09%09%09%09console.log(val);%0A%09%09%09%09return;%0A%09%09%09%7D%0A%0A
%09%09%09brigh
|
fc4b8c0bf4f01436929f69978fd99dcb7be32225
|
extend instead of concat default shortcuts ✨
|
cli.js
|
cli.js
|
#! /usr/bin/env node
var fs = require('fs');
var output = require('./');
var pkg = require('./package.json');
var shortcuts = require('./shortcuts.json');
fs.readFile(process.env.HOME + '/.' + pkg.name + '/shortcuts.json', { encoding: 'utf8' }, function (err, data) {
if (!err) {
shortcuts = shortcuts.concat(JSON.parse(data));
}
output(shortcuts).forEach(function (line) {
console.log(line);
});
});
|
JavaScript
| 0 |
@@ -15,16 +15,137 @@
v node%0A%0A
+// TODO's:%0A// - write test for add/overwrite shortcuts%0A// - %60assignShortcuts()%60 add error handling check argument types%0A%0A
var fs =
@@ -376,20 +376,19 @@
n (err,
-data
+res
) %7B%0A if
@@ -413,25 +413,31 @@
tcuts =
-s
+assignS
hortcuts
.concat(
@@ -432,16 +432,20 @@
cuts
-.concat(
+(shortcuts,
JSON
@@ -455,12 +455,11 @@
rse(
-data
+res
));%0A
@@ -538,12 +538,590 @@
;%0A %7D);%0A%7D);%0A
+%0A/**%0A * Add/overwrite shortcuts%0A *%0A * @param %7BArray%7D ref Default shortcuts%0A * @param %7BArray%7D array New shortcuts to add/overwrite%0A * @return %7BArray%7D Extended shortcuts%0A */%0Afunction assignShortcuts(ref, shortcuts) %7B%0A var refKeys = ref.map(function(obj) %7B return Object.keys(obj)%5B0%5D; %7D);%0A var key, index;%0A%0A shortcuts.map(function(obj) %7B%0A key = Object.keys(obj)%5B0%5D;%0A index = refKeys.indexOf(key);%0A%0A if (index === -1) %7B%0A // Add new shortcut%0A ref.push(obj);%0A %7D else %7B%0A // Overwrite existing shortcut%0A ref%5Bindex%5D = obj;%0A %7D%0A %7D);%0A%0A return ref;%0A%7D%0A
|
6afd2fd27735c6adfecca1cb6c99fa0613a1dbc4
|
fix mockReadStream
|
test/encryption.js
|
test/encryption.js
|
const expect = require('chai').expect
const encryption = require('../lib/encryption')
const Readable = require('stream').Readable
describe('encryption', () => {
it('should encrypt and decrypt', () => {
const data = 'some-unencrypted-data'
// create mock read stream (to mimic a pg_dump output stream)
const mockedReadStream = new Readable()
mockedReadStream.push(data)
// pipe the readable stream through encrypt
const encrypted = encryption.encrypt(mockedReadStream, 'password123')
// pipe the encrypted stream through decrypt
const decrypted = encryption.decrypt(encrypted, 'password123')
mockedReadStream.emit('data', data)
// verify the decrypted string matches the original data
const output = decrypted.read().toString('utf8')
expect(output).to.equal(data)
})
})
|
JavaScript
| 0.000001 |
@@ -364,16 +364,59 @@
dable()%0A
+ mockedReadStream._read = () =%3E %7B %7D%0A
|
95438ed35b83a1b1aa98714c6ab0f1a8021520f3
|
Remove unused import
|
test/files.spec.js
|
test/files.spec.js
|
var assert = require('assert');
var should = require('should');
var fs = require('fs');
describe('sendgrid-nodejs repo', function() {
/*
it('should have ./Docker or docker/Docker file', function() {
assert(fileExists('Docker') || fileExists('docker/Docker'));
});
it('should have ./docker-compose.yml or ./docker/docker-compose.yml file', function() {
assert(fileExists('docker-compose.yml') || fileExists('docker/docker-compose.yml'));
});
*/
it('should have ./.env_sample file', function() {
assert(fileExists('.env_sample'));
});
it('should have ./.gitignore file', function() {
assert(fileExists('.gitignore'));
});
it('should have ./.travis.yml file', function() {
assert(fileExists('.travis.yml'));
});
it('should have ./.codeclimate.yml file', function() {
assert(fileExists('.codeclimate.yml'));
});
it('should have ./CHANGELOG.md file', function() {
assert(fileExists('CHANGELOG.md'));
});
it('should have ./CODE_OF_CONDUCT.md file', function() {
assert(fileExists('CODE_OF_CONDUCT.md'));
});
it('should have ./CONTRIBUTING.md file', function() {
assert(fileExists('CONTRIBUTING.md'));
});
it('should have ./.github/ISSUE_TEMPLATE file', function() {
assert(fileExists('.github/ISSUE_TEMPLATE'));
});
it('should have ./LICENSE.md file', function() {
assert(fileExists('LICENSE.md'));
});
it('should have ./.github/PULL_REQUEST_TEMPLATE file', function() {
assert(fileExists('.github/PULL_REQUEST_TEMPLATE'));
});
it('should have ./README.md file', function() {
assert(fileExists('README.md'));
});
it('should have ./TROUBLESHOOTING.md file', function() {
assert(fileExists('TROUBLESHOOTING.md'));
});
it('should have ./USAGE.md file', function() {
assert(fileExists('USAGE.md'));
});
/*
it('should have ./USE_CASES.md file', function() {
assert(fileExists('USE_CASES.md'));
});
*/
function fileExists(filepath) {
try {
return fs.statSync(filepath).isFile();
} catch(e) {
if (e.code === 'ENOENT') {
console.log('' + filepath + ' doesn\'t exist.');
return false;
}
throw e;
}
}
});
|
JavaScript
| 0.000001 |
@@ -34,45 +34,8 @@
');%0A
-var should = require('should');%0A
var
|
30a86e05374f705533b522d8819914b275da9d43
|
add time-out test
|
test/index-test.js
|
test/index-test.js
|
var expect = require('expect.js');
var ShortTermMemory = require('../');
var myStore;
describe('test basic functionality', function () {
it('create store', function () {
myStore = new ShortTermMemory({
duration: 60000
});
expect(myStore).to.be.an('object');
expect(myStore.get).to.be.an('function');
expect(myStore.add).to.be.an('function');
});
it('save token', function (done) {
myStore.add('unique key', {
example: 'data'
});
done();
});
it('get token', function () {
var token = myStore.get('unique key');
expect(token).to.eql({
example: 'data'
});
});
it('don\'t get token a second time', function () {
var token = myStore.get('unique key');
expect(token).to.be(false);
});
});
|
JavaScript
| 0.000005 |
@@ -716,12 +716,342 @@
);%0A%09%7D);%0A
+%09it('time out token', function (done) %7B%0A%09%09var shortStore = new ShortTermMemory(%7B%0A%09%09%09duration: 50%0A%09%09%7D);%0A%09%09shortStore.add('unique key', 'test-data');%0A%09%09setTimeout(function access () %7B%0A%09%09%09var token = shortStore.get('unique key');%0A%09%09%09if (token === false) %7B%0A%09%09%09%09done();%0A%09%09%09%7D else %7B%0A%09%09%09%09expect().fail();%0A%09%09%09%09done();%0A%09%09%09%7D%0A%09%09%7D, 60);%0A%09%7D);%0A
%7D);%0A
|
fab2ea269b05e8c49f1a9e6441e0d2abed61613a
|
set first route to login.
|
ui/app/navigation.js
|
ui/app/navigation.js
|
/**
* UI Navigation links
*/
var navigation = [
{
// 'checkPermission': {
// 'service': 'dashboard',
// 'route': '/environment/list'
// },
'id': 'home',
'label': translation.home[LANG],
'url': '#/dashboard',
'tplPath': 'modules/DASHBOARD/home/directives/dashboard.tmpl',
'scripts': ['modules/DASHBOARD/home/config.js', 'modules/DASHBOARD/home/controller.js'],
'icon': 'home',
//'userMenu': true,
//'mainMenu': true,
'tracker': true
},
{
'id': 'home',
'label': translation.home[LANG],
'url': '#/login',
'tplPath': 'modules/DASHBOARD/myAccount/directives/login.tmpl',
'scripts': ['modules/DASHBOARD/myAccount/config.js', 'modules/DASHBOARD/myAccount/controller.js'],
'footerMenu': true
},
//{
// 'id': 'help',
// 'label': 'Help',
// 'url': '#/help',
// 'guestMenu': true,
// 'userMenu': true,
// 'private': true,
// 'icon': 'question',
// 'scripts': ['modules/dashboard/config.js', 'modules/dashboard/controller.js'],
// 'tplPath': 'modules/dashboard/directives/help.tmpl'
//},
{
'id': 'help2',
'label': translation.help[LANG],
'url': '#/help',
'scripts': ['modules/DASHBOARD/home/config.js', 'modules/DASHBOARD/home/controller.js'],
'tplPath': 'modules/DASHBOARD/home/directives/help.tmpl',
'footerMenu': true
}
];
(function () {
var link = document.createElement("script");
link.type = "text/javascript";
link.src = "themes/" + themeToUse + "/bootstrap.js";
document.getElementsByTagName("head")[0].appendChild(link);
if (modules) {
var allFiles = [];
for (var pillar in modules) {
if (modules.hasOwnProperty(pillar)) {
for (var env in modules[pillar]) {
if (modules[pillar].hasOwnProperty(env)) {
for (var install in modules[pillar][env]) {
if (typeof modules[pillar][env][install] === 'string') {
allFiles.push(modules[pillar][env][install]);
}
else if (typeof modules[pillar][env][install] === 'object') {
if (modules[pillar][env][install].latest) {
allFiles.push(modules[pillar][env][install][modules[pillar][env][install].latest]);
}
else {
var latest = parseInt(Object.keys(modules[pillar][env][install])[0]);
for (var i = 1; i < Object.keys(modules[pillar][env][install]).length; i++) {
if (parseInt(Object.keys(modules[pillar][env][install])[i]) > latest) {
latest = parseInt(Object.keys(modules[pillar][env][install])[i]);
}
}
allFiles.push(modules[pillar][env][install][latest.toString()]);
}
}
}
}
}
}
}
for (var j = 0; j < allFiles.length; j++) {
var x = document.createElement("script");
x.type = "text/javascript";
x.src = allFiles[j];
document.getElementsByTagName("head")[0].appendChild(x);
}
}
})();
|
JavaScript
| 0 |
@@ -45,19 +45,25 @@
on = %5B%0A%09
-%7B%0A%09
+// %7B%0A%09//
%09// 'che
@@ -80,16 +80,19 @@
on': %7B%0A%09
+//
%09// %09'se
@@ -113,16 +113,19 @@
oard',%0A%09
+//
%09// %09'ro
@@ -155,16 +155,19 @@
t'%0A%09
+//
%09// %7D,%0A%09
%09'id
@@ -162,16 +162,19 @@
%09// %7D,%0A%09
+//
%09'id': '
@@ -173,32 +173,35 @@
%09'id': 'home',%0A%09
+//
%09'label': transl
@@ -211,32 +211,35 @@
on.home%5BLANG%5D,%0A%09
+//
%09'url': '#/dashb
@@ -242,24 +242,27 @@
ashboard',%0A%09
+//
%09'tplPath':
@@ -306,32 +306,35 @@
shboard.tmpl',%0A%09
+//
%09'scripts': %5B'mo
@@ -408,16 +408,19 @@
.js'%5D,%0A%09
+//
%09'icon':
@@ -429,16 +429,19 @@
home',%0A%09
+//
%09//'user
@@ -454,16 +454,19 @@
true,%0A%09
+//
%09//'main
@@ -479,16 +479,19 @@
true,%0A%09
+//
%09'tracke
@@ -496,24 +496,27 @@
ker': true%0A%09
+//
%7D,%0A%09%7B%0A%09%09'id'
|
923582d12acc4c8eb5e8dd5347f60b44b0772ab8
|
remove only
|
test/index.spec.js
|
test/index.spec.js
|
import { expect } from 'chai'
import { createEvent, createEvents } from '../src'
const invalidAttributes = { start: [] }
const validAttributes = { start: [2000, 10, 5, 5, 0], duration: { hours: 1 } }
const validAttributes2 = { start: [2001, 10, 5, 5, 0], duration: { hours: 1 } }
const validAttributes3 = { start: [2002, 10, 5, 5, 0], duration: { hours: 1 } }
describe('ics', () => {
describe('.createEvent', () => {
it('returns an error or value when not passed a callback', () => {
const event1 = createEvent(validAttributes)
const event2 = createEvent(invalidAttributes)
expect(event1.error).to.be.null
expect(event1.value).to.be.a('string')
expect(event2.error).to.exist
})
it('returns an error when passed an empty object', (done) => {
createEvent({}, (error, success) => {
done()
expect(error.name).to.equal('ValidationError')
expect(success).not.to.exist
})
})
it('returns a node-style callback', (done) => {
createEvent(validAttributes, (error, success) => {
expect(error).not.to.exist
expect(success).to.contain('DTSTART:200010')
done()
})
})
})
describe.only('.createEvents', () => {
it('returns an error when no arguments are passed', () => {
const events = createEvents()
expect(events.error).to.exist
})
it('returns a list of events', () => {
const { error, value } = createEvents([validAttributes, validAttributes2, validAttributes3])
expect(error).to.be.null
expect(value).to.contain('BEGIN:VCALENDAR')
})
})
})
|
JavaScript
| 0.000001 |
@@ -1195,13 +1195,8 @@
ribe
-.only
('.c
|
371d7a1fcafb91a814e70762db53b6c0a3f51227
|
fix test
|
test/index.test.js
|
test/index.test.js
|
const fs = require('fs')
const rm = require('rimraf')
const generatePlay = require('../lib/generate-play')
const updateScripts = require('../lib/update-scripts')
beforeAll(() => {
process.chdir(__dirname)
})
afterAll(cleanup)
function cleanup() {
rm.sync('play*')
const data = JSON.stringify({
scripts: { test: 'echo lol' }
}, null, 2)
fs.writeFileSync('./fixture/package.json', data, 'utf8')
}
test('generate play', () => {
return generatePlay({ dest: 'play1' })
.then(() => {
const files = fs.readdirSync('./play1')
expect(files).toEqual(['app.js', 'index.js', 'preview.js'])
})
})
test('updateScripts', () => {
return updateScripts('./fixture')
.then(() => {
const pkg = require('./fixture/package')
expect(pkg.scripts.test).toBe('echo lol')
expect(pkg.scripts.play).toBe('vbuild dev --config play.config.js')
expect(pkg.scripts['build:play']).toBe('vbuild --config play.config.js')
})
})
|
JavaScript
| 0.000002 |
@@ -840,18 +840,11 @@
Be('
-vbuild dev
+poi
--c
@@ -912,17 +912,20 @@
).toBe('
-v
+poi
build --
|
0a192430a7c43107bdacd1ff2d827ffa3c4c4aaa
|
fix test
|
test/index.test.js
|
test/index.test.js
|
var should = require('chai').should()
, promise = require('laissez-faire')
, series = require('../series')
, async = require('../async')
, map = require('..')
function delay(err, val){
var args = arguments
return promise(function(fulfill, reject){
setTimeout(function () {
if (args.length < 2) reject(err)
else fulfill(val)
}, Math.random() * 10)
})
}
describe('map', function () {
it('should work on arrays', function () {
map([1,2,3], function(v,k){
k.should.be.a('number')
return v + 1
}).should.eql([2,3,4])
})
it('should work on objects', function () {
map({a:1, b:2, c:3}, function(v,k){
k.should.be.a('string')
return v + 1
}).should.eql({a:2,b:3,c:4})
})
it('should call `fn` with `ctx` as `this`', function () {
map([1,2,3], function(v, k){
this.should.equal(Math)
return Math.pow(v, 2)
}, Math).should.eql([1,4,9])
})
})
describe('series', function () {
it('should work on arrays', function (done) {
var calls = []
series([1,2,3], function(v, k){
return delay(null, v + 1).then(function(inc){
calls.push([k, v])
return inc
})
}).then(function(res){
res.should.eql([2,3,4])
calls.should.eql([
[0,1],
[1,2],
[2,3]
])
}).node(done)
})
it('should work on objects', function (done) {
var calls = []
series({a:1,b:2,c:3}, function(v, k){
k.should.be.a('string')
return delay(null, v + 1).then(function(inc){
calls.push([k, v])
return inc
})
}).then(function(res){
res.should.eql({a:2,b:3,c:4})
calls.sort(function(a,b){
return a[0] > b[0]
}).should.eql([
['a',1],
['b',2],
['c',3]
])
}).node(done)
})
it('should call `fn` with `ctx` as `this`', function (done) {
series([1,2,3], function(v, k){
this.should.equal(Math)
return delay(null, null)
}, Math).node(done)
})
it('should handle empty arrays', function (done) {
series([], function(v, k){
throw new Error('fail')
}).then(function(res){
res.should.eql([])
}).node(done)
})
it('should handle empty objects', function (done) {
series({}, function(v, k){
throw new Error('fail')
}).then(function(res){
res.should.eql({})
}).node(done)
})
errorHandling(series)
})
describe('async', function(){
it('should work on arrays', function(done){
async([1,2,3], function(v, i){
return delay(null, v + 1)
}).then(function(arr){
arr.should.eql([2,3,4])
}).node(done)
})
it('should work on objects', function(done){
async({a:1,b:2,c:3}, function(v, i){
return delay(null, v + 1)
}).then(function(obj){
obj.should.eql({a:2,b:3,c:4})
}).node(done)
})
errorHandling(async)
})
function errorHandling(map){
describe('error handling', function () {
it('should catch sync errors', function (done) {
map([1,2,3], function(v, k){
if (v == 2) throw new Error('fail')
return delay(null, v + 1)
}).then(null, function(e){
e.message.should.equal('fail')
}).node(done)
})
it('should catch async errors', function (done) {
map([1,2,3], function(v, k){
if (v == 2) return delay(new Error('fail'))
return delay(null, null)
}).then(null, function(e){
e.message.should.equal('fail')
done()
})
})
})
}
|
JavaScript
| 0.000002 |
@@ -1018,16 +1018,43 @@
(v, k)%7B%0A
+%09%09%09k.should.be.a('number')%0A
%09%09%09retur
@@ -1066,36 +1066,36 @@
ay(null, v + 1).
-then
+read
(function(inc)%7B%0A
@@ -1080,35 +1080,32 @@
).read(function(
-inc
)%7B%0A%09%09%09%09calls.pus
@@ -1110,39 +1110,24 @@
ush(%5Bk, v%5D)%0A
-%09%09%09%09return inc%0A
%09%09%09%7D)%0A%09%09%7D).t
@@ -1310,32 +1310,51 @@
%09var calls = %5B%5D%0A
+%09%09var delayed = %5B%5D%0A
%09%09series(%7Ba:1,b:
@@ -1396,32 +1396,55 @@
.be.a('string')%0A
+%09%09%09calls.push(%5Bk, v%5D)%09%0A
%09%09%09return delay(
@@ -1456,20 +1456,20 @@
v + 1).
-then
+read
(functio
@@ -1474,23 +1474,22 @@
ion(
-inc
)%7B%0A%09%09%09%09
-calls
+delayed
.pus
@@ -1502,23 +1502,8 @@
v%5D)%0A
-%09%09%09%09return inc%0A
%09%09%09%7D
@@ -1576,111 +1576,25 @@
ls.s
-ort(function(a,b)%7B%0A%09%09%09%09return a%5B0%5D %3E b%5B0%5D%0A%09%09%09%7D).should.eql(%5B%0A%09%09%09%09%5B'a',1%5D,%0A%09%09%09%09%5B'b',2%5D,%0A%09%09%09%09%5B'c',3%5D%0A%09%09%09%5D
+hould.eql(delayed
)%0A%09%09
|
63d1b28282f2169c88cb18cf76f1779c7027f258
|
add test that starts/stops replicaset
|
test/index.test.js
|
test/index.test.js
|
var run = require('../');
describe('run', function() {
it('should start a standalone', function(done) {
var opts = {
action: 'start',
name: 'mongodb-runner-test-standalone',
port: 27001
};
run(opts, function(err) {
if (err) return done(err);
opts.action = 'stop';
run(opts, function(err) {
if (err) return done(err);
done();
});
});
});
});
|
JavaScript
| 0 |
@@ -276,16 +276,409 @@
(err);%0A%0A
+ opts.action = 'stop';%0A run(opts, function(err) %7B%0A if (err) return done(err);%0A done();%0A %7D);%0A %7D);%0A %7D);%0A%0A it('should start a replicaset', function(done) %7B%0A var opts = %7B%0A action: 'start',%0A name: 'mongodb-runner-test-replicaset',%0A topology: 'replicaset',%0A port: 27002%0A %7D;%0A%0A run(opts, function(err) %7B%0A if (err) return done(err);%0A%0A
op
|
39e080ccdfafea7d592c64c590f12107789cb9c7
|
allow overriding the stylesheet
|
static/js/widget.js
|
static/js/widget.js
|
if (typeof MiroCommunity === 'undefined') {
MiroCommunity = {
Widget: function(args) {
this.init(args);
},
jsonP: function(path) {
script = document.createElement('script');
script.type = 'text/javascript';
script.src = path;
document.getElementsByTagName('head')[0].appendChild(script);
return script;
},
createElement: function(name, attrs) {
elm = document.createElement(name);
for (attr in attrs) {
elm[attr] = attrs[attr];
}
return elm;
},
createSpan: function(content, className) {
span = document.createElement('span');
span.className = className;
span.innerHTML = content;
return span;
}
};
MiroCommunity.Widget._counter = 0;
MiroCommunity.Widget._addedStyles = false;
MiroCommunity.Widget.prototype = function() {
return {
init: function(options) {
this.opts = options;
this.counter = ++MiroCommunity.Widget._counter;
this.id = 'mc-widget-' + this.counter;
this.scriptTag = null;
},
render: function () {
this.addStyle();
document.write('<div id="' + this.id + '" class="mc-widget">');
document.write('<h2>Watch Videos from Miro Community</h2><ul class="mc-loading"><li><span/></li></ul>');
document.write('<a class="mc-from" href="http://' + this.opts.domain + '/">' + this.opts.domain + '</a></div>');
this.load();
},
addStyle: function() {
head = document.getElementsByTagName('head')[0];
if (!MiroCommunity.Widget._addedStyles) {
link = document.createElement('link');
link.rel = 'stylesheet';
link.href = 'http://' + this.opts.domain + '/css/widget.css';
head.appendChild(link);
MiroCommunity.Widget._addedStyles = true;
}
style = document.createElement('style');
style.type = 'text/css';
width = this.opts.width ? this.opts.width : 300;
style.innerText = '#' + this.id + ', #' + this.id + ' ul {width: ' + width + 'px;}';
head.appendChild(style);
},
load: function() {
var t = this;
ajax_path = 'http://' + t.opts.domain + '/feeds/json/' + t.opts.source;
MiroCommunity['callback_' + t.counter] = function(json) {
t.scriptTag.parentNode.removeChild(t.scriptTag);
t.scriptTag = null;
var div = document.getElementById(t.id);
t.update(div, json);
};
t.scriptTag = MiroCommunity.jsonP(ajax_path + '?jsoncallback=MiroCommunity.callback_' + t.counter);
},
update: function(div, json) {
var ul = div.getElementsByTagName('ul')[0];
ul.innerHTML = ul.className = '';
var count = this.opts.count ? this.opts.count : 4;
var li = null;
for (var i=0; i < json.items.length && i < count; i++) {
item = json.items[i];
li = MiroCommunity.createElement('li', {className: 'mc-video'});
link = MiroCommunity.createElement('a', {href: item.link});
thumb = MiroCommunity.createElement('span', {className: 'mc-thumbnail'});
thumb.appendChild(MiroCommunity.createElement('img', {
width: 120,
height: 90,
src: item.thumbnail}));
thumb.appendChild(MiroCommunity.createSpan('', 'mc-play'));
link.appendChild(thumb);
link.appendChild(MiroCommunity.createSpan(item.title, 'mc-title'));
link.appendChild(MiroCommunity.createSpan(item.when, 'mc-when'));
li.appendChild(link);
ul.appendChild(li);
}
if (li !== null) {
li.className += ' mc-last';
}
}
};
}();
}
|
JavaScript
| 0.000001 |
@@ -1840,20 +1840,51 @@
edStyles
+ && this.opts.stylesheet !== ''
) %7B%0A
-
@@ -1975,24 +1975,163 @@
tylesheet';%0A
+ if (this.opts.stylesheet) %7B%0A link.href = this.opts.stylesheet;%0A %7D else %7B%0A
@@ -2196,24 +2196,46 @@
idget.css';%0A
+ %7D%0A
|
36d3f719b2be634dca30475063c6500dc622a15e
|
make tests pass
|
test/index.test.js
|
test/index.test.js
|
'use strict';
var Analytics = require('@segment/analytics.js-core').constructor;
var integration = require('@segment/analytics.js-integration');
var tester = require('@segment/analytics.js-integration-tester');
var Boomtrain = require('../lib/');
describe('Boomtrain', function() {
var analytics;
var boomtrain;
var options = {
apiKey: '324fa582528ea3dbc96bd7e94a2d5b61'
};
beforeEach(function() {
analytics = new Analytics();
boomtrain = new Boomtrain(options);
analytics.use(Boomtrain);
analytics.use(tester);
analytics.add(boomtrain);
});
afterEach(function() {
analytics.restore();
analytics.reset();
boomtrain.reset();
// sandbox();
});
it('should have the right settings', function() {
analytics.compare(Boomtrain, integration('Boomtrain')
.global('_bt')
.option('apiKey', ''));
});
describe('before loading', function() {
beforeEach(function() {
analytics.stub(boomtrain, 'load');
});
describe('#initialize', function() {
it('should create the window._bt object', function() {
analytics.assert(!window._bt);
analytics.initialize();
analytics.assert(window._bt);
});
it('should call #load', function() {
analytics.initialize();
analytics.called(boomtrain.load);
});
});
});
describe('loading', function() {
it('should load', function(done) {
analytics.load(boomtrain, done);
});
});
describe('after loading', function() {
beforeEach(function(done) {
analytics.once('ready', done);
analytics.initialize();
});
describe('#identify', function() {
beforeEach(function() {
analytics.stub(window._bt.person, 'set');
});
it('should send an id', function() {
analytics.identify('[email protected]');
analytics.called(window._bt.person.set, { id: '[email protected]' , email:'[email protected]' });
});
it('should not send only traits', function() {
analytics.identify({ trait: true });
analytics.didNotCall(window._bt.person.set);
});
it('should send an id, traits, and email (from object)', function() {
analytics.identify('id', { trait: true, email: '[email protected]' });
analytics.called(window._bt.person.set, { id: 'id', trait: true, email: '[email protected]' });
});
it('should send a specified email', function() {
var user_id = 'fake_app_member_id';
analytics.identify(user_id, { trait: true, email: '[email protected]' });
analytics.called(window._bt.person.set, { trait: true, email: '[email protected]', id: user_id });
});
it('should not send id as email (if id is an invalid email)', function() {
var user_id = 'invalid_email';
analytics.identify( user_id, { trait: true });
analytics.called(window._bt.person.set, { trait: true, id: user_id });
});
it('should convert dates to unix timestamps', function() {
var date = new Date();
analytics.identify('id', { date: date });
analytics.called(window._bt.person.set, {
id: 'id',
date: Math.floor(date / 1000)
});
});
it('should alias created to created_at', function() {
var date = new Date();
analytics.identify('id', { createdAt: date });
analytics.called(window._bt.person.set, {
id: 'id',
created_at: Math.floor(date / 1000)
});
});
});
describe('#page', function() {
beforeEach(function() {
analytics.stub(window._bt, 'track');
});
it('should get page URL and call _bt.track with correct model and ID', function() {
analytics.page('Home Page', { url: 'https://marketingreads.com/deloitte-digital-buys-creative-agency-heat/', model: 'blog' });
analytics.called(window._bt.track, 'viewed', { id: '602265785760ac3ae5c2bb6909172b2c', model: 'blog' });
});
it('should use specified model and ids without Name parameter', function() {
analytics.page({ id:'test_id', model: 'blog' });
analytics.called(window._bt.track, 'viewed', { id: 'test_id', model: 'blog' });
});
});
describe('#track', function() {
beforeEach(function() {
analytics.stub(window._bt, 'track');
});
it('should send an event and properties', function() {
analytics.track('viewed', { id: '602265785760ac3ae5c2bb6909172b2c', model: 'article' });
analytics.called(window._bt.track, 'viewed', { id: '602265785760ac3ae5c2bb6909172b2c', model: 'article' });
});
});
});
});
|
JavaScript
| 0.000003 |
@@ -2860,17 +2860,16 @@
dentify(
-
user_id,
@@ -2953,32 +2953,50 @@
rue, id: user_id
+, email: undefined
%7D);%0A %7D);%0A%0A
@@ -3242,32 +3242,60 @@
oor(date / 1000)
+,%0A email: undefined
%0A %7D);%0A
@@ -3563,16 +3563,44 @@
/ 1000)
+,%0A email: undefined
%0A
@@ -4088,24 +4088,24 @@
;%0A %7D);%0A
+
it('sh
@@ -4140,31 +4140,8 @@
ids
- without Name parameter
', f
|
85815fd6cc8f673a2e1b31108c89288a5f34c787
|
Streamline karma conf
|
test/karma.conf.js
|
test/karma.conf.js
|
module.exports = function(config) {
config.set({
basePath: '../',
frameworks: ['mocha', 'chai'],
customLaunchers: {
headlessChrome: {
base: 'Chrome',
flags: ['--disable-web-security', '--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream']
}
},
files: [
{pattern: 'test/integration/*.json', watched: true, served: true, included: false},
'node_modules/jquery/dist/jquery.min.js',
'dist/vendor.js',
'dist/janus.js',
'test/integration/*.js'
],
exclude: [],
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_DEBUG,
autoWatch: false,
browsers: ['headlessChrome'],
singleRun: true,
browserNoActivityTimeout: 60000,
concurrency: Infinity
})
};
|
JavaScript
| 0 |
@@ -132,24 +132,19 @@
%7B%0A
-headless
+dev
Chrome:
@@ -648,13 +648,12 @@
LOG_
-DEBUG
+WARN
,%0A%0A
@@ -694,16 +694,11 @@
: %5B'
-headless
+dev
Chro
|
da42ecc4d319c55dd1f4c7dbbdd9350d26a9c42d
|
Update reversestr.js
|
test/reversestr.js
|
test/reversestr.js
|
//using chained methods
function reverseStr(s) {
return s.split('').reverse().join('');
}
//fast method using for loop
function reverseStr(s) {
for (var i = s.length - 1, o = ''; i >= 0; o += s[i--]) { }
return o;
}
//fast method using while loop (faster with long strings in some browsers when compared with for loop)
function reverseStr(s) {
var i = s.length, o = '';
while (i--) o += s[i];
return o;
}
|
JavaScript
| 0.000001 |
@@ -116,16 +116,41 @@
or loop%0A
+// dene 1.0 da de%C4%9Fi%C5%9Fklik%0A
function
|
583d3a88ac0f36c04839c9ea0d71b79abc5ee10d
|
Include map-area-compare in scene tests.
|
test/scene-test.js
|
test/scene-test.js
|
var GENERATE_SCENES = false, // flag to generate test scenes
specdir = process.cwd() + '/spec/',
testdir = process.cwd() + '/test/scenegraphs/',
fs = require('fs'),
tape = require('tape'),
vega = require('../'),
loader = vega.loader({baseURL: './web/'}),
specs = require('./specs-valid.json').filter(function(name) {
// remove wordcloud due to random layout
// remove map-area-compare due to cross-version node.js issue
return name !== 'wordcloud' && name !== 'map-area-compare';
});
// Standardize font metrics to suppress cross-platform variance.
vega.textMetrics.width = vega.textMetrics.estimateWidth;
tape('Vega generates scenegraphs for specifications', function(test) {
var count = specs.length;
specs.forEach(function(name) {
var path = testdir + name + '.json',
spec = JSON.parse(fs.readFileSync(specdir + name + '.vg.json')),
runtime = vega.parse(spec),
view = new vega.View(runtime, {loader: loader, renderer: 'none'});
view.initialize().runAsync().then(function() {
var actual = view.scenegraph().toJSON();
if (GENERATE_SCENES) {
// eslint-disable-next-line no-console
console.log('WRITING TEST SCENE', name, path);
fs.writeFileSync(path, actual);
} else {
var expect = fs.readFileSync(path) + '';
test.ok(vega.sceneEqual(JSON.parse(actual), JSON.parse(expect)), 'scene: ' + name);
}
}).catch(function(err) {
// eslint-disable-next-line no-console
console.error('ERROR', err);
test.fail(name);
}).then(function() {
if (--count === 0) test.end();
});
});
});
|
JavaScript
| 0 |
@@ -395,133 +395,34 @@
-// remove map-area-compare due to cross-version node.js issue%0A return name !== 'wordcloud' && name !== 'map-area-compare
+return name !== 'wordcloud
';%0A
|
b22c196ede35073c31084bd10bb445e6e9c9c2b7
|
add $watch And $digest test case
|
test/scope_spec.js
|
test/scope_spec.js
|
/* jshint globalstrict: true */
/* global Scope: false */
'use strict';
describe("[Angular-Scope]", function() {
it("can be constructed and used as an object", function() {
var scope = new Scope();
scope.aProperty = 1;
expect(scope.aProperty).toBe(1);
});
});
|
JavaScript
| 0.000004 |
@@ -269,12 +269,426 @@
%0A %7D);%0A%0A
+ describe(%22digest%22, function()%7B%0A var scope;%0A%0A beforeEach(function()%7B%0A scope = new Scope();%0A %7D);%0A%0A it(%22calls the listener function of a watch on first $digest%22, function() %7B%0A var watchFn = function() %7B return 'wat'; %7D;%0A var listenerFn = jasmine.createSpy();%0A scope.$watch(watchFn, listenerFn);%0A%0A scope.$digest();%0A%0A expect(listenerFn).toHaveBeenCalled();%0A %7D);%0A %7D);%0A%0A
%7D);%0A
|
82d8888b6c0085037f42accb72de0e0efe9bded6
|
Update tests
|
test/test-utils.js
|
test/test-utils.js
|
import test from 'tape';
import getUrlParameter from '../js/utils/get-url-parameter';
import exportXML from '../js/utils/export-xml';
test('get url paramter test', function(t) {
t.throws(
function() {
getUrlParameter('http://example.com', 'id');
},
Error,
'should throw an error when the required parameter is missing'
);
t.throws(
function() {
getUrlParameter('http://example.com?id=no', 'id', 'int');
},
Error,
'should throw an error when the required parameter is the wrong type'
);
t.equal(
getUrlParameter('http://example.com?id=1', 'id', 'int'),
1,
'should return the parameter as an int'
);
t.equal(
getUrlParameter('http://example.com?msg=hello', 'msg'),
'hello',
'should return the parameter as a string'
);
t.end();
});
test('export xml test', function(t) {
t.doesNotThrow(
function() {
exportXML([]);
},
Error,
'should throw an error when the required parameter is missing'
);
t.end();
});
|
JavaScript
| 0.000001 |
@@ -42,32 +42,33 @@
ameter from '../
+_
js/utils/get-url
@@ -83,56 +83,8 @@
er';
-%0Aimport exportXML from '../js/utils/export-xml';
%0A%0Ate
@@ -121,24 +121,25 @@
nction(t) %7B%0A
+%0A
t.throws
@@ -212,211 +212,20 @@
.com
-', 'id');%0A %7D,%0A Error,%0A 'should throw an error when the required parameter is missing'%0A );%0A%0A t.throws(%0A function() %7B%0A getUrlParameter('http://example.com?id=no
+?id=sometext
', '
@@ -667,232 +667,4 @@
%7D);%0A
-%0Atest('export xml test', function(t) %7B%0A t.doesNotThrow(%0A function() %7B%0A exportXML(%5B%5D);%0A %7D,%0A Error,%0A 'should throw an error when the required parameter is missing'%0A );%0A%0A t.end();%0A%7D);
|
136bbe9b5006068ee4141ba8313165759f3385c8
|
Remove hapi-ioredis from testServer
|
test/testServer.js
|
test/testServer.js
|
/**
* Created by Omnius on 18/07/2016.
*/
'use strict';
const Hapi = require('hapi');
const HapiAuthBasic = require('hapi-auth-basic');
const HapiAuthHawk = require('hapi-auth-hawk');
const Inert = require('inert');
// const Redis = require('hapi-ioredis');
module.exports = function () {
const server = new Hapi.Server();
server.connection({
host: '127.0.0.1',
port: '9001'
});
server.register([
Inert,
HapiAuthBasic,
HapiAuthHawk
// ,
// {
// register: Redis,
// options: {
// url: 'redis://127.0.0.1:6379'
// }
// }
], (err) => {
if (err) {
throw err;
}
});
return server;
};
|
JavaScript
| 0 |
@@ -216,49 +216,8 @@
');%0A
-// const Redis = require('hapi-ioredis');
%0A%0Amo
@@ -365,16 +365,17 @@
%7D);%0A
+%0A
serv
@@ -381,240 +381,291 @@
ver.
-register(%5B%0A Inert,%0A HapiAuthBasic,%0A HapiAuthHawk%0A // ,%0A // %7B%0A // register: Redis,%0A // options: %7B%0A // url: 'redis://127.0.0.1:6379'%0A
+state('Hawk-Session-Token', %7B%0A ttl: 24 * 60 * 60 * 1000,%0A path: '/',%0A isSecure: false,%0A isHttpOnly: false,%0A encoding: 'base64json',%0A clearInvalid: true%0A %7D);%0A%0A server.register(%5B%0A Inert,%0A
-//
-%7D%0A // %7D
+HapiAuthBasic,%0A HapiAuthHawk
%0A
|
3763e6a95aa1b07db394f0e6f39b575e1641a640
|
fix failing test
|
abi.js
|
abi.js
|
var nodeGypInstall = require('node-gyp-install')
var util = require('./util')
function getAbi (opts, version, cb) {
var log = opts.log
var install = opts.install || nodeGypInstall
version = version.replace('v', '')
util.readGypFile(version, 'src/node_version.h', function (err, a) {
if (err && err.code === 'ENOENT') return retry()
if (err) return cb(err)
util.readGypFile(version, 'src/node.h', function (err, b) {
if (err && err.code === 'ENOENT') return retry()
if (err) return cb(err)
var abi = parse(a) || parse(b)
if (!abi) return cb(new Error('Could not detect abi for ' + version))
cb(null, abi)
})
})
function retry () {
install({log: log, version: version, force: true}, function (err) {
if (err) return cb(err)
getAbi(version, cb)
})
}
function parse (file) {
var res = file.match(/#define\s+NODE_MODULE_VERSION\s+\(?(\d+)/)
return res && res[1]
}
}
module.exports = getAbi
|
JavaScript
| 0.000006 |
@@ -215,17 +215,16 @@
v', '')%0A
-%0A
util.r
@@ -798,16 +798,22 @@
getAbi(
+opts,
version,
|
ed5d4a17992b0c9f3ac987756fca0d308a6c967c
|
fix translations run block not working
|
components/core/core.module.js
|
components/core/core.module.js
|
import '../drag/drag.module';
import '../layout/layout.module';
import '../map/map.module';
//import '../translations/js/translations';
import '../utils/utils.module';
import 'angular-gettext';
import coreService from './core.service';
/**
* @namespace hs
* @ngdoc module
* @module hs.core
* @name hs.core
* @description HsCore module for whole HSLayers-NG. HsCore module consists of HsCore service which keeps some app-level settings and mantain app size and panel statuses. TODO
*/
angular
.module('hs.core', ['hs.map', 'gettext', 'hs.drag', 'hs.layout', 'hs.utils'])
/**
* @module hs.core
* @name HsCore
* @ngdoc service
* @description HsCore service of HSL. TODO expand the description
*/
.factory('HsCore', coreService);
|
JavaScript
| 0.000002 |
@@ -89,52 +89,8 @@
e';%0A
-//import '../translations/js/translations';%0A
impo
@@ -143,16 +143,58 @@
ttext';%0A
+import '../translations/js/translations';%0A
import c
|
63826647e004a18316bc3a3df246cd8a334ee49f
|
rollback added
|
test/unit/index.js
|
test/unit/index.js
|
import fs from 'fs-promise';
import path from 'path';
import TimedFile from '../../src/lib/index';
// import {
// console.log
// } from 'mocha-console.logger';
const PATH_DELIMITER = '/';
const gitTestFolder = [__dirname, '..', 'testcases', 'git'].join(PATH_DELIMITER);
const contentTestFolder = [__dirname, '..', 'testcases', 'content'].join(PATH_DELIMITER);
const fileFullPath = [contentTestFolder, 'saveTest.js'].join(PATH_DELIMITER);
describe('TimedFile', function() {
before(async () => {
await fs.createFile(fileFullPath);
});
// afterEach((done) => {
// console.log(this.ctx.currentTest.title);
// done();
// });
describe('Functionalities Present', function() {
it('Functionalities Present', function(done) {
const timedFile = new TimedFile({ fileFullPath: `${__dirname}/LICENSE`, versionsPath: `${gitTestFolder}` });
expect(timedFile).to.have.property('save');
expect(timedFile).to.have.property('diff');
expect(timedFile).to.have.property('fastforward');
expect(timedFile).to.have.property('rollback');
done();
});
});
describe('Able to Save', function() {
it('Able to Save', async function() {
const author = { name: 'Raymond Ho', email: '[email protected]' };
const timedFile = new TimedFile({ fileFullPath, versionsPath: `${gitTestFolder}` });
await fs.writeFile(fileFullPath, 'Line 1\n');
try {
await timedFile.save(author);
const jsDiffs = await timedFile.diff();
expect(jsDiffs).to.eql([{ value: 'Line 1\n', count: 7 }]);
} catch (e) {
console.log(e);
}
});
});
describe('Able to Diff When Loaded with Versions', function() {
it('Able to Diff When Loaded with Versions', async function() {
const author = { name: 'Raymond Ho', email: '[email protected]' };
await fs.appendFile(fileFullPath, 'Line 2\n');
const timedFile = new TimedFile({ fileFullPath, versionsPath: `${gitTestFolder}` });
try {
const jsDiffs = await timedFile.diff();
expect(jsDiffs).to.eql([{ count: 7, value: 'Line 1\n' },
{ count: 7, added: true, removed: undefined, value: 'Line 2\n' }]);
} catch (e) {
console.log(e);
}
});
});
describe('Able to Save When Loaded with Versions', function() {
it('Able to Save When Loaded with Versions', async function() {
const author = { name: 'Raymond Ho', email: '[email protected]' };
const timedFile = new TimedFile({ fileFullPath, versionsPath: `${gitTestFolder}` });
try {
await timedFile.save(author);
const jsDiffs = await timedFile.diff();
expect(jsDiffs).to.eql([{
count: 14,
value: 'Line 1\nLine 2\n'
}]);
} catch (e) {
console.log(e);
}
});
});
describe('Able to Preview a Rollback', function() {
it('Able to Preview a Rollback', async function() {
const author = { name: 'Raymond Ho', email: '[email protected]' };
const timedFile = new TimedFile({ fileFullPath, versionsPath: `${gitTestFolder}` });
try {
const first = await fs.readFile(fileFullPath);
// console.console.log(first.toString());
const jsDiffs = await timedFile.diff();
await timedFile.rollback();
const second = await fs.readFile(fileFullPath);
// console.console.log(second.toString());
} catch (e) {
console.log(e);
}
});
});
after('Tear Down', async () => {
await fs.remove(contentTestFolder);
await fs.remove(gitTestFolder);
});
});
|
JavaScript
| 0.000001 |
@@ -92,19 +92,16 @@
index';%0A
-//
import %7B
@@ -105,30 +105,16 @@
t %7B%0A
-//
- console.
log%0A
-//
%7D fr
@@ -123,24 +123,16 @@
'mocha-
-console.
logger';
@@ -528,120 +528,8 @@
);%0A%0A
- // afterEach((done) =%3E %7B%0A // console.log(this.ctx.currentTest.title);%0A // done();%0A // %7D);%0A%0A
@@ -1587,32 +1587,24 @@
-console.
log(e);%0A
@@ -2281,32 +2281,24 @@
-console.
log(e);%0A
@@ -2945,32 +2945,24 @@
-console.
log(e);%0A
@@ -3327,21 +3327,30 @@
const
-first
+beforeRollback
= await
@@ -3397,47 +3397,69 @@
-// console.console.log(first.toString()
+expect(beforeRollback.toString()).to.equal('Line 1%5CnLine 2%5Cn'
);%0A
@@ -3579,22 +3579,29 @@
const
-second
+afterRollback
= await
@@ -3648,48 +3648,60 @@
-// console.console.log(second.toString()
+expect(afterRollback.toString()).to.equal('Line 1%5Cn'
);%0A
@@ -3745,16 +3745,8 @@
-console.
log(
|
0525437c1e7c52215b74cbde9acda594153b2ee6
|
Fix unused component test
|
test/utils/link.js
|
test/utils/link.js
|
'use strict'
const assert = require('chai').assert
const uuid = require('uuid/v4')
const link = require('../../src/utils/link')
const filename = require('../../src/utils/filename')
describe('link()', function() {
it('should work with an empty data string', function() {
const html = ''
const components = []
const render = () => ''
const result = link(html, components, render)
assert.strictEqual(result, html)
})
it('should replace names with links', function() {
const srcs = [
`${ uuid() }/${ uuid() }/_${ uuid() }.njk`,
`${ uuid() }/${ uuid() }.njk`,
`${ uuid() }.njk`
]
// A name that includes a name of another component
srcs.push(uuid() + srcs[2])
// Unknown component that should not be replaced
srcs.push(`${ uuid() }.njk`)
const html = `
<span>${ srcs[0] }</span>
{% inject "${ srcs[1] }" %}
${ srcs[2] }
${ srcs[3] }
${ srcs[4] }
`
const components = [
{
id: uuid(),
src: srcs[0]
},
{
id: uuid(),
src: srcs[1]
},
{
id: uuid(),
src: srcs[2]
},
{
id: uuid(),
src: srcs[3]
},
{
// Component that is not used in the HTML
id: uuid(),
src: srcs[3]
}
]
const render = ({ id }) => id
const expected = `
<span>${ srcs[0].replace(filename(srcs[0]), '') + render(components[0]) }</span>
{% inject "${ srcs[1].replace(filename(srcs[1]), '') + render(components[1]) }" %}
${ render(components[2]) }
${ render(components[3]) }
${ srcs[4] }
`
const result = link(html, components, render)
assert.strictEqual(result, expected)
})
})
|
JavaScript
| 0.000002 |
@@ -1173,31 +1173,41 @@
),%0A%09%09%09%09src:
-srcs%5B3%5D
+%60$%7B uuid() %7D.njk%60
%0A%09%09%09%7D%0A%09%09%5D%0A%0A%09
|
248d9d17c832d9197012f3f54fba2dc3b9ecb2a9
|
Accept bad certs
|
test/hostmeta-https-only-test.js
|
test/hostmeta-https-only-test.js
|
// hostmeta-json-test.js
//
// Test flag to refuse falling back to http for hostmeta
//
// Copyright 2012, StatusNet Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var assert = require("assert"),
vows = require("vows"),
express = require("express"),
wf = require("../lib/webfinger");
var suite = vows.describe("Flag to prevent falling back to http");
suite.addBatch({
"When we run an HTTP app that just supports host-meta with JRD": {
topic: function() {
var app = express(),
callback = this.callback;
app.get("/.well-known/host-meta.json", function(req, res) {
res.json({
links: [
{
rel: "lrdd",
type: "application/json",
template: "http://localhost/lrdd.json?uri={uri}"
}
]
});
});
app.on("error", function(err) {
callback(err, null);
});
app.listen(80, function() {
callback(null, app);
});
},
"it works": function(err, app) {
assert.ifError(err);
},
teardown: function(app) {
if (app && app.close) {
app.close();
}
},
"and we get its host-meta data with the HTTPS-only flag": {
topic: function() {
var callback = this.callback;
wf.hostmeta("localhost", {httpsOnly: true}, function(err, jrd) {
if (err) {
callback(null);
} else {
callback(new Error("Unexpected success!"));
}
});
},
"it fails correctly": function(err) {
assert.ifError(err);
}
}
}
});
suite["export"](module);
|
JavaScript
| 0.999023 |
@@ -807,16 +807,65 @@
ger%22);%0A%0A
+process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';%0A%0A
var suit
|
38f0235edabb3ff5a54367262caf7b7dfb0fd24c
|
add test case
|
test/hubot-pivotal-slack-test.js
|
test/hubot-pivotal-slack-test.js
|
"use strict";
var chai = require('chai');
var sinon = require('sinon');
chai.use(require('sinon-chai'));
chai.use(require('chai-string'));
var DummyRobot = require('./dummy-robot');
var targetScript = require("../src/scripts/hubot-pivotal");
describe("Test for hubot-pivotal.js", function() {
let backupProjectIds;
// initial setup
before(function(done) {
backupProjectIds = process.env.PROJECT_IDS;
done();
});
// teardown for each test
afterEach(function(done) {
if (!backupProjectIds) {
// revert to undefined.
delete process.env.PROJECT_IDS;
} else {
process.env.PROJECT_IDS = backupProjectIds;
}
done();
});
// test
it("Check response for 'hello'", function() {
let dummyRobot = new DummyRobot();
let spyRespond = sinon.spy(dummyRobot, "captureSend");
// test
let reply = dummyRobot.testRun(targetScript, "hello");
// check
// chai.expect(dummyRobot.respond).to.have.been.called();
chai.expect(spyRespond.called).to.be.ok;
chai.expect(reply).to.equal("world!");
});
// test
it("Check response for 'Nice to meet you'", function() {
let dummyRobot = new DummyRobot();
let spyRespond = sinon.spy(dummyRobot, "captureSend");
// test
let reply = dummyRobot.testRun(targetScript, "Nice to meet you");
// check
chai.expect(spyRespond.called).to.not.be.ok;
chai.expect(reply).to.be.undefined;
});
// test
it("Check for 'show pivotal projects' w/ multiple project ids.", function() {
let dummyRobot = new DummyRobot();
let spyRespond = sinon.spy(dummyRobot, "captureSend");
process.env.PROJECT_IDS = "1111,2222,3333";
// test
let TEST_PROJECT_IDS = process.env.PROJECT_IDS.split(',');
let reply = dummyRobot.testRun(targetScript, "show pivotal projects");
// check
chai.expect(spyRespond.called).to.be.ok;
let urls = reply.split('\n');
// empty line will be added at last.
chai.expect(urls).to.have.length(TEST_PROJECT_IDS.length + 1);
for (let index in urls) {
if (urls[index].length == 0) {
continue; // skip empty line
}
chai.expect(urls[index]).to.endsWith(TEST_PROJECT_IDS[index])
}
});
// test
it("Check for 'show pivotal projects' w/ sigle project id.", function() {
let dummyRobot = new DummyRobot();
let spyRespond = sinon.spy(dummyRobot, "captureSend");
process.env.PROJECT_IDS = "1111";
// test
let TEST_PROJECT_IDS = process.env.PROJECT_IDS.split(',');
let reply = dummyRobot.testRun(targetScript, "show pivotal projects");
// check
chai.expect(spyRespond.called).to.be.ok;
let urls = reply.split('\n');
// empty line will be added at last.
chai.expect(urls).to.have.length(TEST_PROJECT_IDS.length + 1);
for (let index in urls) {
if (urls[index].length == 0) {
continue; // skip empty line
}
chai.expect(urls[index]).to.endsWith(TEST_PROJECT_IDS[index])
}
});
// test
it("Check for 'show pivotal projects' w/ no project ids.", function() {
let dummyRobot = new DummyRobot();
let spyRespond = sinon.spy(dummyRobot, "captureSend");
delete process.env.PROJECT_IDS;
// test
let reply = dummyRobot.testRun(targetScript, "show pivotal projects");
// check
chai.expect(spyRespond.called).to.be.ok;
chai.expect(reply).to.be.singleLine;
chai.expect(reply).to.not.contain("http");
});
});
|
JavaScript
| 0.000059 |
@@ -3799,12 +3799,502 @@
%7D);%0A%0A
+ // test getProjectName%0A it(%22Check for getProjectName%22, function() %7B%0A let dummyRobot = new DummyRobot();%0A let spyRespond = sinon.spy(dummyRobot, %22captureSend%22);%0A%0A delete process.env.PROJECT_IDS;%0A%0A // test%0A let reply = dummyRobot.testRun(targetScript, %22show pivotal projects%22);%0A%0A // check%0A chai.expect(spyRespond.called).to.be.ok;%0A chai.expect(reply).to.be.singleLine;%0A chai.expect(reply).to.not.contain(%22http%22);%0A %7D);%0A
%7D);%0A
|
6fb8db4f9c3e5bed240184406d13b5ca9b582a00
|
FIX remove comment
|
test/node/LeaderElection.test.js
|
test/node/LeaderElection.test.js
|
import assert from 'assert';
import {
default as randomToken
} from 'random-token';
import {
default as memdown
} from 'memdown';
import * as _ from 'lodash';
import * as schemas from '../helper/schemas';
import * as schemaObjects from '../helper/schema-objects';
import * as humansCollection from '../helper/humans-collection';
import * as RxDatabase from '../../dist/lib/RxDatabase';
import * as RxSchema from '../../dist/lib/RxSchema';
import * as RxCollection from '../../dist/lib/RxCollection';
import * as util from '../../dist/lib/util';
process.on('unhandledRejection', function(err) {
throw err;
});
describe('LeaderElection.test.js', () => {
describe('messaging', () => {
it('should recieve a Leader-message over the socket', async() => {
const name = randomToken(10);
const c1 = await humansCollection.createMultiInstance(name);
const c2 = await humansCollection.createMultiInstance(name);
const db1 = c1.database;
const db2 = c2.database;
const pW = util.promiseWaitResolveable(1000);
const recieved = [];
const sub = db1.leaderElector.socketMessages$
.subscribe(message => {
recieved.push(message);
pW.resolve();
});
const sub2 = db2.leaderElector.socketMessages$
.subscribe(message => recieved.push(message));
db2.leaderElector.socketMessage('tell');
await pW.promise;
assert.equal(recieved.length, 1);
assert.equal(recieved[0].type, 'tell');
assert.equal(recieved[0].token, db2.token);
assert.ok(recieved[0].time > 100);
assert.ok(recieved[0].time < new Date().getTime());
sub.unsubscribe();
sub2.unsubscribe();
});
it('leader should reply with tell when apply comes in', async() => {
const name = randomToken(10);
const c1 = await humansCollection.createMultiInstance(name);
const c2 = await humansCollection.createMultiInstance(name);
const db1 = c1.database;
const db2 = c2.database;
db1.leaderElector.beLeader();
const pW = util.promiseWaitResolveable(1000);
const recieved = [];
const sub = db2.leaderElector.socketMessages$
.subscribe(message => {
recieved.push(message);
pW.resolve();
sub.unsubscribe();
});
db2.leaderElector.socketMessage('apply');
await pW.promise;
assert.equal(recieved.length, 1);
assert.equal(recieved[0].type, 'tell');
assert.equal(recieved[0].token, db1.token);
});
});
describe('election', () => {
it('a single instance should always elect itself as leader', async() => {
const name = randomToken(10);
const c1 = await humansCollection.createMultiInstance(name);
const db1 = c1.database;
await db1.leaderElector.applyOnce();
assert.equal(db1.leaderElector.isLeader, true);
});
it('should not elect as leader if other instance is leader', async() => {
const name = randomToken(10);
const c1 = await humansCollection.createMultiInstance(name);
const c2 = await humansCollection.createMultiInstance(name);
const db1 = c1.database;
const db2 = c2.database;
await db1.leaderElector.beLeader();
await db2.leaderElector.applyOnce();
assert.equal(db2.leaderElector.isLeader, false);
});
it('when 2 instances apply at the same time, one should win', async() => {
// run often
let tries = 0;
while (tries < 3) {
tries++;
const name = randomToken(10);
const c1 = await humansCollection.createMultiInstance(name);
const c2 = await humansCollection.createMultiInstance(name);
const db1 = c1.database;
const db2 = c2.database;
await db1.leaderElector.applyOnce();
await db2.leaderElector.applyOnce();
assert.ok(db1.leaderElector.isLeader != db2.leaderElector.isLeader);
}
});
it('when many instances apply, one should win', async() => {
const name = randomToken(10);
const dbs = [];
while (dbs.length < 10) {
const c = await humansCollection.createMultiInstance(name);
dbs.push(c.database);
}
await Promise.all(
dbs.map(db => db.leaderElector.applyOnce())
);
const leaderCount = dbs
.map(db => db.leaderElector.isLeader)
.filter(is => is == true)
.length;
assert.equal(leaderCount, 1);
});
it('when the leader dies, a new one should be elected', async() => {
const name = randomToken(10);
const dbs = [];
while (dbs.length < 6) {
const c = await humansCollection.createMultiInstance(name);
dbs.push(c.database);
}
await Promise.all(
dbs.map(db => db.leaderElector.applyOnce())
);
let leaderCount = dbs
.filter(db => db.leaderElector.isLeader == true)
.length;
assert.equal(leaderCount, 1);
// let leader die
let leader = dbs
.filter(db => db.leaderElector.isLeader == true)[0];
let leaderToken = leader.token;
await leader.destroy();
// noone should be leader
leaderCount = dbs
.filter(db => db.leaderElector.isLeader == true)
.length;
assert.equal(leaderCount, 0);
// restart election
await Promise.all(
dbs.map(db => db.leaderElector.applyOnce())
);
leaderCount = dbs
.filter(db => db.leaderElector.isLeader == true)
.length;
assert.equal(leaderCount, 1);
let leader2 = dbs
.filter(db => db.leaderElector.isLeader == true)[0];
let leaderToken2 = leader2.token;
assert.notEqual(leaderToken, leaderToken2);
});
});
describe('integration', () => {
it('non-multiInstance should always be leader', async() => {
const c = await humansCollection.create(0);
const db = c.database;
assert.equal(db.isLeader, true);
});
it('non-multiInstance: waitForLeadership should instant', async() => {
const c = await humansCollection.create(0);
const db = c.database;
await db.waitForLeadership();
});
it('waitForLeadership: run once when instance becomes leader', async() => {
const name = randomToken(10);
const cols = await Promise.all(
util.filledArray(5)
.map(i => humansCollection.createMultiInstance(name))
);
const dbs = cols.map(col => col.database);
let count = 0;
dbs.forEach(db => db.waitForLeadership().then(is => count++));
await util.promiseWait(400);
assert.equal(count, 1);
// let leader die
await dbs
.filter(db => db.isLeader)[0]
.leaderElector.die();
await util.promiseWait(400);
assert.equal(count, 2);
});
/* it('exit', () => {
console.log('exit');
process.exit();
});
*/ });
});
|
JavaScript
| 0 |
@@ -7809,115 +7809,10 @@
%7D);%0A
-%0A/* it('exit', () =%3E %7B%0A console.log('exit');%0A process.exit();%0A %7D);%0A */
+
%7D)
|
cd9a482b5531099102c06faef4b82b4c655d3396
|
Split test statements
|
test/spec/controllers/session.js
|
test/spec/controllers/session.js
|
'use strict';
describe('SessionCtrl', function() {
// load the controller's module
// We need to override the async translateProvider
// http://angular-translate.github.io/docs/#/guide/22_unit-testing-with-angular-translate
beforeEach(module('Teem', function ($provide, $translateProvider) {
$provide.factory('customLoader', function ($q) {
return function () {
var deferred = $q.defer();
deferred.resolve({});
return deferred.promise;
};
});
$translateProvider.useLoader('customLoader');
}));
var SessionCtrl,
SessionSvc,
$controller,
$route,
$rootScope,
scope,
$timeout,
swellRT,
nick = 'testingnick',
password = 'testingpassword',
email = '[email protected]';
// Initialize the controller and a mock scope
beforeEach(inject(function (_$controller_, _$route_, _$rootScope_, _$timeout_, _swellRT_, _SessionSvc_) {
$controller = _$controller_;
$route = _$route_;
$rootScope = _$rootScope_;
$timeout = _$timeout_;
swellRT = _swellRT_;
SessionSvc = _SessionSvc_;
}));
describe('when loggin in', function() {
beforeEach(function() {
$route.current = {
params: {
form: 'login'
}
};
});
describe('and SwellRT will send the ok', function() {
var calledNick, calledPassword;
beforeEach(function() {
spyOn(SwellRT, 'startSession').
and.callFake(function(domain, nick, password, success) {
calledNick = nick;
calledPassword = password;
__session.address = nick + '@' + __session.domain;
success();
});
});
it('should login', function() {
scope = $rootScope.$new();
SessionCtrl = $controller('SessionCtrl', {
$route: $route,
$scope: scope
});
scope.form.login.values = {
nick: nick,
password: password
};
scope.form.login.submit();
$timeout.flush();
expect(SwellRT.startSession).
toHaveBeenCalled();
expect(calledNick).toBe(nick);
expect(calledPassword).toBe(password);
expect(SessionSvc.users.current()).toBe(nick + '@' + __session.domain);
});
});
describe('and SwellRT will send an error', function() {
beforeEach(function() {
spyOn(SwellRT, 'startSession').
and.callFake(function(domain, nick, password, success, error) {
error();
});
});
it('should show the error', function() {
// TODO
});
});
});
describe('when registering', function() {
beforeEach(function() {
$route.current = {
params: {
form: 'register'
}
};
});
});
describe('when forgot password', function() {
beforeEach(function() {
$route.current = {
params: {
form: 'forgotten_password'
}
};
});
});
describe('when recovering password', function() {
beforeEach(function() {
$route.current = {
params: {
form: 'recover_password'
}
};
});
});
});
|
JavaScript
| 0.000543 |
@@ -1678,56 +1678,8 @@
%7D);%0A
- %7D);%0A%0A it('should login', function() %7B
%0A
@@ -1982,24 +1982,79 @@
ut.flush();%0A
+ %7D);%0A%0A it('should call SwellRT', function() %7B
%0A exp
@@ -2104,24 +2104,93 @@
enCalled();%0A
+ %7D);%0A%0A it('should pass the right credentials', function() %7B
%0A exp
@@ -2264,16 +2264,76 @@
sword);%0A
+ %7D);%0A%0A it('should set current user', function() %7B%0A
|
55cefa78781b6ca974d245ae149882523e7e2268
|
Fix broken DummyOutboundResource test
|
test/test_outbound/test_dummy.js
|
test/test_outbound/test_dummy.js
|
var assert = require('assert');
var vumigo = require("../../lib");
var test_utils = vumigo.test_utils;
var DummyApi = vumigo.dummy.api.DummyApi;
describe("outbound.dummy", function() {
var api;
var request;
beforeEach(function() {
api = new DummyApi();
request = test_utils.requester(api);
});
describe("DummyOutboundResource", function() {
describe(".handlers", function() {
describe(".reply_to", function() {
it("should record the sent reply message", function() {
return request('outbound.reply_to', {
content: 'foo',
in_reply_to: '123',
continue_session: false
}).then(function(result) {
assert(result.success);
assert.equal(api.outbound.store.length, 1);
var message = api.outbound.store[0];
assert.deepEqual(message, {
content: 'foo',
in_reply_to: '123',
continue_session: false
});
});
});
it("should fail if 'content' isn't given", function() {
return request('outbound.reply_to', {
in_reply_to: '123',
}).then(function(result) {
assert(!result.success);
assert.equal(
result.reason,
"'content' must be given in replies");
});
});
it("should fail if 'content' isn't a string or null",
function() {
return request('outbound.reply_to', {
content: 3,
in_reply_to: '123',
}).then(function(result) {
assert(!result.success);
assert.equal(
result.reason,
"'content' must be a string or null");
});
});
it("should fail if 'in_reply_to' isn't given", function() {
return request('outbound.reply_to', {
content: 'foo'
}).then(function(result) {
assert(!result.success);
assert.equal(
result.reason,
"'in_reply_to' must be given in replies");
});
});
it("should fail if 'continue_session' isn't boolean",
function() {
return request('outbound.reply_to', {
content: 'foo',
in_reply_to: '123',
continue_session: 3
}).then(function(result) {
assert(!result.success);
assert.equal(
result.reason,
["'continue_session' must be either true or false",
"if given"].join(' '));
});
});
});
describe(".reply_to_group", function() {
it("should record the sent reply message", function() {
return request('outbound.reply_to_group', {
content: 'foo',
in_reply_to: '123',
continue_session: false
}).then(function(result) {
assert(result.success);
assert.equal(api.outbound.store.length, 1);
var message = api.outbound.store[0];
assert.deepEqual(message, {
content: 'foo',
in_reply_to: '123',
continue_session: false
});
});
});
it("should fail if 'content' isn't given", function() {
return request('outbound.reply_to_group', {
in_reply_to: '123',
}).then(function(result) {
assert(!result.success);
assert.equal(
result.reason,
"'content' must be given in replies");
});
});
it("should fail if 'content' isn't a string or null",
function() {
return request('outbound.reply_to_group', {
content: 3,
in_reply_to: '123',
}).then(function(result) {
assert(!result.success);
assert.equal(
result.reason,
"'content' must be a string or null");
});
});
it("should fail if 'in_reply_to' isn't given", function() {
return request('outbound.reply_to_group', {
content: 'foo'
}).then(function(result) {
assert(!result.success);
assert.equal(
result.reason,
"'in_reply_to' must be given in replies");
});
});
it("should fail if 'continue_session' isn't boolean",
function() {
return request('outbound.reply_to_group', {
content: 'foo',
in_reply_to: '123',
continue_session: 3
}).then(function(result) {
assert(!result.success);
assert.equal(
result.reason,
["'continue_session' must be either true or false",
"if given"].join(' '));
});
});
});
describe(".send_to_tag", function() {
it("should fail with a deprecation error", function() {
return request('outbound.send_to_tag', {
content: 'foo',
to_addr: '+27123',
endpoint: 'sms'
}).then(function(result) {
assert(!result.success);
assert.equal(
result.reason,
"send_to_tag is no longer supported");
});
});
});
describe(".send_to_endpoint", function() {
it("should record the sent message", function() {
return request('outbound.send_to_endpoint', {
content: 'foo',
to_addr: '+27123',
endpoint: 'sms'
}).then(function(result) {
assert(result.success);
assert.equal(api.outbound.store.length, 1);
var message = api.outbound.store[0];
assert.deepEqual(message, {
content: 'foo',
to_addr: '+27123',
endpoint: 'sms'
});
});
});
it("should fail if 'to_addr' isn't a string", function() {
return request('outbound.send_to_endpoint', {
content: 'foo',
to_addr: null,
endpoint: 'sms'
}).then(function(result) {
assert(!result.success);
assert.equal(
result.reason,
"'to_addr' needs to be a string");
});
});
it("should fail if 'content' isn't a string or null",
function() {
return request('outbound.send_to_endpoint', {
content: null,
to_addr: '+27123',
endpoint: 'sms'
}).then(function(result) {
assert(!result.success);
assert.equal(
result.reason,
"'content' needs to be a string");
});
});
it("should fail if 'endpoint' isn't a string", function() {
return request('outbound.send_to_endpoint', {
content: 'foo',
to_addr: '+27123',
endpoint: null,
}).then(function(result) {
assert(!result.success);
assert.equal(
result.reason,
"'endpoint' needs to be a string");
});
});
});
});
});
});
|
JavaScript
| 0.000002 |
@@ -8428,28 +8428,25 @@
content:
-null
+3
,%0A
@@ -8746,32 +8746,40 @@
s to be a string
+ or null
%22);%0A
|
cefb914e2fe4ba2e1cf139c197366f5c028fadf4
|
fix zoom: show people at the bottom
|
src/interaction_controller.js
|
src/interaction_controller.js
|
app.InteractionController = class {
constructor(engine, renderer, loop, overlay) {
this._overlay = overlay;
this._viewport = overlay.querySelector('.viewport');
this._engine = engine;
this._renderer = renderer;
this._loop = loop;
this._minScale = 1;
this._maxScale = 1.5;
this._center = g.zeroVec;
this._canvas = renderer.canvasElement();
this._canvas.addEventListener('mousedown', this._onMouseDown.bind(this));
this._canvas.addEventListener('mouseup', this._onMouseUp.bind(this));
this._canvas.addEventListener('mousemove', this._onMouseMove.bind(this));
this._canvas.addEventListener('mouseout', this._onMouseUp.bind(this));
// IE9, Chrome, Safari, Opera
this._canvas.addEventListener("mousewheel", this._onMouseWheel.bind(this), false);
// Firefox
this._canvas.addEventListener("DOMMouseScroll", this._onMouseWheel.bind(this), false);
window.addEventListener('resize', this._onResize.bind(this));
this._engine.addListener(app.LayoutEngine.Events.LayoutRecalculated, this._centerGraph.bind(this));
this._onResize();
}
_onResize() {
this._renderer.setSize(document.body.clientWidth, document.body.clientHeight);
this._centerGraph();
}
_computeGraphCenter(boundingBox) {
var boundingBox = this._engine.layout().boundingBox();
var centerX = boundingBox.x + boundingBox.width / 2;
var centerY = boundingBox.y + boundingBox.height / 2;
return new g.Vec(-centerX, -centerY).scale(this._minScale/app.CanvasRenderer.canvasRatio());
}
_centerGraph() {
var boundingBox = this._engine.layout().boundingBox();
var viewportBox = this._viewport.getBoundingClientRect();
var rendererSize = this._renderer.size();
var viewportWidth = viewportBox.width * app.CanvasRenderer.canvasRatio();
var viewportHeight = viewportBox.height * app.CanvasRenderer.canvasRatio();
this._minScale = 1;
if (boundingBox.width !== 0 && boundingBox.height !== 0) {
var hw = viewportWidth / 2;
var hh = viewportHeight / 2;
this._minScale = Math.min(hw / Math.abs(boundingBox.x), this._minScale);
this._minScale = Math.min(hw / Math.abs(boundingBox.x + boundingBox.width), this._minScale);
this._minScale = Math.min(hh / Math.abs(boundingBox.y), this._minScale);
this._minScale = Math.min(hh / Math.abs(boundingBox.y + boundingBox.height), this._minScale);
this._minScale *= 0.9;
}
this._renderer.setScale(this._minScale);
var viewportCenter = new g.Vec((viewportBox.left + viewportBox.width / 2), (viewportBox.top + viewportBox.height / 2));
var canvasCenter = new g.Vec(rendererSize.width / 2, rendererSize.height / 2);
this._center = viewportCenter.subtract(canvasCenter.scale(1/app.CanvasRenderer.canvasRatio()));
this._renderer.setOffset(this._center);
this._loop.invalidate();
}
/**
* @param {!Event} event
* @return {!g.Vec}
*/
_toCoordinates(event) {
var rect = this._canvas.getBoundingClientRect();
var center = new g.Vec(rect.left + rect.width / 2, rect.top + rect.height / 2);
var point = new g.Vec(event.clientX, event.clientY);
return point.subtract(center);
}
_onMouseWheel(event) {
var delta = Math.max(-1, Math.min(1, (event.wheelDelta || -event.detail)));
var fixedPoint = this._toCoordinates(event);
var zoomStep = 0.06;
var newZoom = this._renderer.scale() + zoomStep * delta;
newZoom = Math.max(newZoom, this._minScale);
newZoom = Math.min(newZoom, this._maxScale);
this._overlay.classList.toggle('hidden-overlay', !g.eq(newZoom, this._minScale));
this._renderer.setScale(newZoom, fixedPoint);
this._constrainOffset();
this._loop.invalidate();
event.preventDefault();
event.stopPropagation();
}
_onMouseDown(event) {
this._mouseDownCoordinate = this._toCoordinates(event);
this._mouseDownOffset = this._renderer.offset();
event.preventDefault(true);
event.stopPropagation();
}
_onMouseMove(event) {
if (!this._mouseDownCoordinate)
return;
var moveOffset = this._toCoordinates(event).subtract(this._mouseDownCoordinate);
var newOffset = this._mouseDownOffset.add(moveOffset);
this._renderer.setOffset(newOffset);
this._constrainOffset();
this._loop.invalidate();
}
_constrainOffset() {
var offset = this._renderer.offset();
var boundingBox = this._engine.layout().boundingBox();
var maxDimension = -Infinity;
maxDimension = Math.max(maxDimension, Math.abs(boundingBox.x));
maxDimension = Math.max(maxDimension, Math.abs(boundingBox.y));
maxDimension = Math.max(maxDimension, Math.abs(boundingBox.x + boundingBox.width));
maxDimension = Math.max(maxDimension, Math.abs(boundingBox.y + boundingBox.height));
maxDimension = maxDimension * this._renderer.scale() / app.CanvasRenderer.canvasRatio();
var minRendererSize = Math.min(this._renderer.size().width, this._renderer.size().height) / app.CanvasRenderer.canvasRatio() / 2;
var maxOffset = Math.max(maxDimension - minRendererSize, 0);
var center = g.eq(this._renderer.scale(), this._minScale) ? this._center : g.zeroVec;
var radiusVector = offset.subtract(center);
var len = radiusVector.len();
if (len > maxOffset) {
radiusVector = radiusVector.scale(maxOffset / len);
this._renderer.setOffset(center.add(radiusVector));
this._loop.invalidate();
}
}
_onMouseUp(event) {
this._mouseDownCoordinate = null;
this._mouseDownOffset = null;
}
}
|
JavaScript
| 0 |
@@ -4678,24 +4678,203 @@
nOffset() %7B%0A
+ if (g.eq(this._renderer.scale(), this._minScale)) %7B%0A this._renderer.setOffset(this._center);%0A this._loop.invalidate();%0A return;%0A %7D%0A
var
@@ -5639,108 +5639,16 @@
Size
+/2
, 0);%0A
- var center = g.eq(this._renderer.scale(), this._minScale) ? this._center : g.zeroVec;%0A
@@ -5678,32 +5678,38 @@
offset.subtract(
+this._
center);%0A
@@ -5871,16 +5871,22 @@
tOffset(
+this._
center.a
|
49d079ce979ffd775e48b69cc18adc420fdf8d68
|
add carrage return
|
Sprinkle.js
|
Sprinkle.js
|
// Main Program for Sprinkle
// by Frank Hsiung
// Loading modules {
// var http = require('http');
// var path = require('path');
var fs = require('fs');
var request = require('/usr/local/lib/node_modules/request');
var gpio = require('/usr/local/lib/node_modules/onoff').Gpio;
// }----------------------------------------------------------------------------
// set Pins {
var RelayPin = new gpio(18, 'out'); // default Relay Pin
RelayPin.writeSync(1); // turn off motor: active low
// }----------------------------------------------------------------------------
// Global Variables and Constants {
const hours = 60*60*1000;
var downCounter = 0; // Main Counter of Motor ON
var accRain = 0.0; // Raining accumulation <= 14
var rainAverage; // average of 4 rain station
var sunriseHour = 6; // for comparison of sunrise time
var sunriseMinute = 0; //
var sunsetHour = 18; // for comparison of sunset time
var sunsetMinute = 0; //
var highTemp = 250; // Highest Temperature of the day *10
// }----------------------------------------------------------------------------
// Initialization {
setTimeout(checkSchedule, 1); // Initialization for Main State
setTimeout(crawlKimono, 1); // Initialization for Kimono network spider
// }----------------------------------------------------------------------------
// }----------------------------------------------------------------------------
// State Machine and Function Call {
function crawlKimono() {
request("https://www.kimonolabs.com/api/6ucbaoiy?apikey=lcE98jpR1ZSfMv1hY8eB9cTgEUAnhoTn",
function(err, response, body) { // average rain of pass 24 hours
if (!err && response.statusCode == 200) {
var hsinchu = JSON.parse(body);
var tt = 0;
rainAverage = 0;
for (var i=0; i<4; i++) {
tt = parseFloat(hsinchu.results.Rain[i].mm);
if (isNaN(tt)) tt = 0;
rainAverage += tt;
}
rainAverage = Math.round(rainAverage*30) / 100; // 20% higher than average
if (rainAverage > 14) rainAverage = 14; // maximum setting for rainAverage = 1 week
if (rainAverage > accRain) accRain = rainAverage;
}
});
request("https://www.kimonolabs.com/api/78dba3cq?apikey=lcE98jpR1ZSfMv1hY8eB9cTgEUAnhoTn",
function(err, response, body) { // Highest Temperature
var record;
if (!err && response.statusCode == 200) {
var hsinchu = JSON.parse(body);
var str = hsinchu.results.Sun[0].temp;
for (var i=2; i < str.length; i++) {
if (str[i] == "~") {
highTemp = parseInt(str.substring(i+2, str.length), 10)*10; // for down counting second
}
}
if (highTemp > 360) highTemp = 360; // 120~360 Second
if (highTemp < 120) highTemp = 120;
str = hsinchu.results.Sun[0].sunrise;
sunriseHour = parseInt(str.substring(0,2), 10)+1; // Sprinkle one hour later
sunriseMinute = parseInt(str.substring(3,5), 10);
str = hsinchu.results.Sun[0].sunset;
sunsetHour = parseInt(str.substring(0,2), 10)-1; // Sprinkle before sunset
sunsetMinute = parseInt(str.substring(3,5), 10);
record = new Date()+': '+highTemp+' C, '+rainAverage+' mm, '+sunriseHour+':'+sunriseMinute+', '+sunsetHour+':'+sunsetMinute+'\n';
logIt(record);
} else {
record = new Date()+': network error, bypass this hour';
logIt(record);
}
});
setTimeout(crawlKimono, 1*hours); // 1 hour period; no other state
}
// .............................................................................
function checkSchedule() {
var d = new Date(); // get present time
var hour = d.getHours();
var minute = d.getMinutes();
if (((sunriseHour == hour) && (sunriseMinute == minute)) ||
((sunsetHour == hour) && (sunsetMinute == minute))) {
setTimeout(setCounter_Log, 1);
} else setTimeout(checkSchedule, 20000); // 20 seconds cycle
}
function setCounter_Log() { // one-time state; only enter once
if (accRain >= 1) { // check raining status
if (rainAverage < 1) { // no more raining
accRain -= 1; // reduce 1mm each time
}
downCounter = 0; // by pass Sprinkle
setTimeout(checkSchedule, 1*hours); // avoid state loop
} else {
downCounter = Math.floor((highTemp * (1-accRain))); // set downCounter
accRain = 0;
RelayPin.writeSync(0); // turn on motor
setTimeout(downCounting, 1); // state change
}
var d = new Date(); // writer Log file
var record = d.toLocaleTimeString()+': sprinkle '+downCounter+' second(accRain='+accRain+')\n';
logIt(record);
}
function downCounting() {
if (downCounter-- > 0) {
setTimeout(downCounting, 1000);
} else {
RelayPin.writeSync(1); // turn off motor
setTimeout(checkSchedule, 1*hours); // state change; sprinkle finished
}
}
// .............................................................................
function logIt(data) { // writer Log file out
fs.open('daily.txt', 'a+', function(err, fd) {
if (err) {
return console.error(err);
}
fs.appendFile('daily.txt', data, function(err) {
if (err) {
return console.error(err);
}
});
fs.close(fd, function(err){
if (err) {
console.log(err);
}
});
});
}
// .............................................................................
|
JavaScript
| 0.999989 |
@@ -3747,16 +3747,18 @@
his hour
+%5Cn
';%0A
|
23b5f7c8526e43d02a2bc90994767b83d5d7dbd2
|
Fix first selected message not loading
|
src/js/DependentStateMixin.js
|
src/js/DependentStateMixin.js
|
/**
* @flow
*/
var RSVP = require('rsvp');
var React = require('react/addons');
var _ = require('lodash');
var asap = require('asap');
var classToMixinFunction = require('./classToMixinFunction');
class DependentStateMixin {
_subscriptions: Array<{remove: () => void;}>;
constructor(component, config) {
this._component = component;
this._config = _.mapValues(config, stateConfig => {
return {getOptions: defaultGetOptions, ...stateConfig};
});
this._optionsByStateFieldName = {};
this._onStoreChange = this._onStoreChange.bind(this);
}
_createSubscriptions(props, state) {
var stores = _.chain(this._config).map(
(stateConfig, stateFieldName) => stateConfig.method.store
).compact().uniq().value();
this._update(props, state);
this._subscriptions = stores.map(
store => store.subscribe(this._onStoreChange)
);
}
_onStoreChange(data) {
this._update(
this._component.props,
this._component.state,
data.store
);
}
_update(props, state, store?) {
var newState = {};
var isFirstRound = true;
var didOptionsChange = true;
while (didOptionsChange) {
didOptionsChange = false;
_.forEach(this._config, (stateConfig, stateFieldName) => {
var newOptions = stateConfig.getOptions(props, {...state, ...newState});
var oldOptions = this._optionsByStateFieldName[stateFieldName];
if (
!_.isEqual(newOptions, oldOptions) ||
(isFirstRound && store && stateConfig.method.store === store)
) {
didOptionsChange = true;
var result = this._callMethod(stateConfig, stateFieldName, newOptions);
newState[stateFieldName] = result;
}
});
isFirstRound = false;
}
if (this._component.isMounted() && !_.isEmpty(newState)) {
this._component.setState(newState);
}
}
_callMethod(stateConfig, stateFieldName, options): any {
this._optionsByStateFieldName[stateFieldName] = options;
if (stateConfig.shouldFetch && !stateConfig.shouldFetch(options)) {
return null;
}
var result = stateConfig.method(options);
if (result instanceof Promise || result instanceof RSVP.Promise) {
console.assert(false, 'Stores should not return promises anymore.');
}
return result;
}
componentWillMount() {
this._createSubscriptions(
this._component.props,
this._component.state
);
}
componentWillUnmount() {
this._subscriptions.forEach(subscription => subscription.remove());
}
componentWillUpdate(nextProps, nextState) {
asap(() => {
this._update(nextProps, nextState);
});
}
getInitialState() {
return _.mapValues(this._config, (stateConfig, stateFieldName) => null);
}
}
function defaultGetOptions() {
return {};
}
module.exports = classToMixinFunction(DependentStateMixin);
|
JavaScript
| 0 |
@@ -222,16 +222,43 @@
Mixin %7B%0A
+ _isSafeToSetState: bool;%0A
_subsc
@@ -1822,29 +1822,24 @@
is._
-component.isMounted()
+isSafeToSetState
&&
@@ -2374,32 +2374,67 @@
ntWillMount() %7B%0A
+ this._isSafeToSetState = true;%0A
this._create
@@ -2536,32 +2536,68 @@
WillUnmount() %7B%0A
+ this._isSafeToSetState = false;%0A
this._subscr
|
5b9ffb67ffb9ddac2cfc4f24f00301ef356b219a
|
Fix toShortString
|
ipv6-address.js
|
ipv6-address.js
|
function toString(arr) {
return Array.prototype.map.call(arr, function(ele) {
return ele.toString(16);
}).join(":");
}
class Ipv6Address extends Uint16Array {
constructor(iterable) {
let arr = new Uint16Array(this.length);
for(let i = 0; i < this.length; ++i) {
Object.defineProperty(this, i, {
get: function() {
return arr[i];
},
set: function(val) {
arr[i] = val;
},
enumerable: true,
configurable: true
});
}
if(iterable) {
let i = 0;
for(let val of iterable) {
if(i >= this.length) {
throw new RangeError("Ipv6Address: iterable is too long");
}
this[i++] = val >>> 0;
}
}
}
toString() {
return toString(this);
}
toShortString() {
let longestLength = 0,
length = 0,
i = 0,
longestStart,
start;
for(let ele of this) {
if(ele === 0) {
if(!length) {
start = i;
}
++length;
} else {
if(length > longestLength) {
longestStart = start;
longestLength = length;
}
length = 0;
}
++i;
}
if(typeof(longestStart) === "undefined") {
return this.toString();
}
return toString(this.slice(0, longestStart)) + "::" + toString(this.slice(longestStart + longestLength));
}
get length() {
return 8;
}
* keys() {
for(let i = 0; i < this.length; ++i) {
yield i;
}
}
* values() {
for(let key of this.keys()) {
yield this[key];
}
}
* entires() {
for(let key of this.keys()) {
yield [key, this[key]];
}
}
* [Symbol.iterator]() {
return this.values();
}
}
function parseParts(parts) {
return parts.map(function(part) {
if(!/^[a-f0-9]{1,4}$/.test(part)) {
throw new Error(`Ipv6Address.parse: invalid part: '${part}'`);
}
return parseInt(part, 16);
});
}
function collapse(...arrs) {
return [].concat(...arrs);
}
Ipv6Address.parse = function(str) {
let parts = String(str).split("::");
if(parts.length > 2) {
throw new Error("Ipv6Address.parse: expected '::' to occur at most once");
}
if(parts.length === 2) {
parts = parts.map(function(part) {
return parseParts(part.split(":"));
});
if(parts[0].length + parts[1].length > 8) {
throw new Error("Ipv6Address.parse: expects ':' to occur at most 9 times if '::' occurs");
}
parts.splice(1, 1, new Array(8 - parts[0].length - parts[1].length).fill(0));
return new this(collapse(parts));
}
parts = parts[0].split(":");
if(parts.length !== 8) {
throw new Error("Ipv6Address.parse: expects ':' to occur exactly 7 times");
}
return new this(parseParts(parts));
};
export default Ipv6Address;
|
JavaScript
| 0.999989 |
@@ -1040,27 +1040,8 @@
0,%0A
- i = 0,%0A
@@ -1102,19 +1102,36 @@
let
-ele of this
+%5Bkey, val%5D of this.entries()
) %7B%0A
@@ -1145,19 +1145,19 @@
if(
-ele
+val
=== 0)
@@ -1216,17 +1216,19 @@
start =
-i
+key
;%0A
@@ -1282,20 +1282,9 @@
%7D
- else %7B%0A
+%0A
@@ -1328,36 +1328,32 @@
-
-
longestStart = s
@@ -1358,20 +1358,16 @@
start;%0A
-
@@ -1402,38 +1402,61 @@
th;%0A
+%7D%0A
-%7D%0A
+ if(val !== 0) %7B
%0A
@@ -1485,26 +1485,8 @@
%7D
-%0A%0A ++i;
%0A
@@ -1614,27 +1614,49 @@
oString(
-this.slice(
+Array.prototype.slice.call(this,
0, longe
@@ -1687,19 +1687,41 @@
ing(
-this.slice(
+Array.prototype.slice.call(this,
long
|
9fb30288f68432f6215d75c0da0659ed8f36c5be
|
tweak welcome message
|
src/js/utils/WelcomeStages.js
|
src/js/utils/WelcomeStages.js
|
var WelcomeStages = [
{
primary: 'Hello there you!',
secondary: "First off, let's see how your day is lining up...",
button: 'Skip for now'
},
{
primary: 'Nice one!',
secondary: "We're locating your calendar...",
button: ''
},
{
primary: 'Sweet!',
secondary: 'Now click on the Tupiq to shuffle your background.',
button: 'Skip for now'
},
{
primary: 'Hang tight!',
secondary: "We're loading all those pretty pixels just for you...",
button: ''
},
{
primary: "That's it!",
secondary: "Have a go at dragging the panel around and right click for some other handy actions.",
button: ''
}
];
module.exports = WelcomeStages;
|
JavaScript
| 0 |
@@ -619,18 +619,12 @@
for
-some other
+more
han
@@ -633,16 +633,29 @@
actions
+ and settings
.%22,%0A%09%09bu
|
66ed2dc5d4ef13947ca91a3d92ca6088d039db77
|
Add progress bar animation
|
src/js/views/slideshowView.js
|
src/js/views/slideshowView.js
|
'use strict';
import * as Backbone from 'backbone';
import SlideView from './slideView.js';
import SlideshowModel from '../models/slideshowModel.js';
const RIGHT_KEY_CODE = 39;
const LEFT_KEY_CODE = 37;
const UP_KEY_CODE = 38;
const DOWN_KEY_CODE = 40;
const SPACE_KEY_CODE = 32;
var SlideshowView = Backbone.View.extend({
initialize: function() {
var view = this;
this.initSlides();
this.model.listenTo(this.model, 'change:slideIndex', function(event, slideIndex) {
view.handleCurrentSlideChange(slideIndex);
});
window.model = this.model;
},
goToSlide: function(slideIndex) {
this.slideViews.forEach(slideView => {
slideView.hide();
});
this.slideViews[slideIndex].show();
},
handleCurrentSlideChange: function(slideIndex) {
this.goToSlide(slideIndex);
},
handleKeydown: function(e) {
if(e.which === RIGHT_KEY_CODE || e.which === DOWN_KEY_CODE || e.which === SPACE_KEY_CODE) {
this.model.set({'slideIndex': parseInt(this.model.get('slideIndex'), 10) + 1}, {validate:true});
} else if(e.which === LEFT_KEY_CODE || e.which === UP_KEY_CODE) {
this.model.set({'slideIndex': parseInt(this.model.get('slideIndex'), 10) - 1}, {validate:true});
}
},
events: {
'keydown': 'handleKeydown'
},
slideViews: [],
initSlides: function() {
var slideElements = this.el.querySelectorAll('slide-content');
for(let i = 0; i < slideElements.length; i++) {
this.slideViews.push(new SlideView({
el: slideElements[i]
}));
}
this.model.set('numberOfSlides', this.slideViews.length);
}
});
export default SlideshowView;
|
JavaScript
| 0.000001 |
@@ -548,32 +548,99 @@
x);%0A %7D);%0A
+ this.progressBar = this.el.querySelector('.progress-bar');%0A
window.m
@@ -832,24 +832,193 @@
ex%5D.show();%0A
+ if(this.progressBar) %7B%0A this.progressBar.style.width = (this.model.get('slideIndex') / (this.model.get('numberOfSlides') - 1)) * 100 + '%25';%0A %7D%0A
%7D,%0A h
|
c3e12e3d2e1b2b4d1170fb875c1bf4046f7e0a0d
|
decompress api response automatically
|
src/kancolle/server/server.js
|
src/kancolle/server/server.js
|
'use strict';
const KANCOLLE_BASE_DIR = process.env.KANCOLLE_BASE_DIR;
const request = require('request');
const rp = require('request-promise');
const path = require('path');
const urljoin = require('url-join');
const urlparse = require('url-parse');
const agentLog = require('winston').loggers.get('agent');
const osapi = require('../../dmm/osapi');
const sprintf = require('sprintf-js').sprintf;
const kancolleExternal = require('../external');
class KancolleServer {
constructor(worldId, host) {
this.worldId = worldId;
this.host = host;
}
download(url) {
agentLog.info('Download: ' + url);
agentLog.verbose('Remove sensitive data in URL parameters');
var parsedUrl = removeUrlParameterSensitiveData(url);
agentLog.debug('Parsed URL: ' + parsedUrl);
return request.get({
url: parsedUrl,
headers: {'x-requested-with': 'ShockwaveFlash/22.0.0.192'}
});
}
apiRequest(_url, req, onResponse) {
agentLog.info('POST URL: ' + _url);
var returnResponseAsBuffer = null;
request.post({
url: _url,
form: req.body,
headers: forgeKancolleHttpRequestHeader(this, req.headers),
encoding: returnResponseAsBuffer
}, onResponse);
}
generateApiToken(gadgetInfo) {
const url = sprintf('%s/kcsapi/api_auth_member/dmmlogin/%s/1/%d', this.host, gadgetInfo.VIEWER_ID, Date.now());
return osapi.proxyRequest(url, gadgetInfo).then(response => {
var body = response.body;
body = body.replace('svdata=', '');
body = body.replace(/\\/g, '');
var apiResponse = JSON.parse(body);
var isBan = apiResponse.api_result == 301;
var data = {
isBan: isBan,
api_token: apiResponse.api_token,
api_start_time: apiResponse.api_starttime
}
return Promise.resolve(data);
})
}
}
function forgeKancolleHttpRequestHeader(self, httpHeader) {
agentLog.verbose('Forge HTTP header to match with HTTP request from browser');
agentLog.debug(self.host)
var headers = httpHeader || {};
modifyHeader(self.host, kancolleExternal.host());
avoidSocketHangup();
return headers;
function avoidSocketHangup() {
delete headers['connection'];
delete headers['content-length'];
delete headers['content-type'];
}
function cloneHeader(header) {
return JSON.parse(JSON.stringify(header));
}
function modifyHeader(serverIp, hostRoot) {
headers.host = serverIp;
headers.origin = hostRoot;
if(headers.hasOwnProperty('referer'))
headers.referer = headers.referer.replace(headers.host, serverIp);
headers['user-agent'] = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36';
agentLog.debug(headers);
}
}
function removeUrlParameterSensitiveData(url) {
url = urlparse(url, true);
delete url.query.api_token;
delete url.query.api_starttime;
return url.toString();
}
module.exports = exports = KancolleServer;
|
JavaScript
| 0 |
@@ -961,45 +961,8 @@
l);%0A
-%09%09var returnResponseAsBuffer = null;%0A
%09%09re
@@ -1078,40 +1078,18 @@
%0A%09%09%09
-encoding: returnResponseAsBuffer
+gzip: true
%0A%09%09%7D
|
92978b5a56c58d4ff658c2a75574d29b78c6e7bd
|
Update mysql.js
|
providers/mysql.js
|
providers/mysql.js
|
const mysql = require("mysql2/promise");
let db;
const throwError = (err) => { throw err; };
exports.init = async () => {
db = await mysql.createConnection(conn: {
host: "localhost",
port: "3306",
user: "root",
password: "",
database: "Komada",
});
};
/* Table methods */
/**
* Checks if a table exists.
* @param {string} table The name of the table you want to check.
* @returns {Promise<boolean>}
*/
exports.hasTable = table => this.exec(`SELECT 1 FROM ${table} LIMIT 1`)
.then(() => true)
.catch(() => false);
/**
* Creates a new table.
* @param {string} table The name for the new table.
* @param {string} rows The rows for the table.
* @returns {Promise<Object>}
*/
exports.createTable = (table, rows) => this.exec(`CREATE TABLE '${table}' (${rows.join(", ")})`);
/**
* Drops a table.
* @param {string} table The name of the table to drop.
* @returns {Promise<Object>}
*/
exports.deleteTable = table => this.exec(`DROP TABLE '${table}'`);
/* Document methods */
/**
* Get all documents from a table.
* @param {string} table The name of the table to fetch from.
* @returns {Promise<Object[]>}
*/
exports.getAll = async (table, options = {}) => this.runAll(options.key && options.value ?
`SELECT * FROM \`${table}\` WHERE \`${options.key}\` = ${this.sanitize(options.value)}` :
`SELECT * FROM \`${table}\``).then(([rows]) => rows);
/**
* Get a row from a table.
* @param {string} table The name of the table.
* @param {string} key The row id or the key to find by. If value is undefined, it'll search by 'id'.
* @param {string} [value=null] The desired value to find.
* @returns {Promise<?Object>}
*/
exports.get = (table, key, value = null) => this.run(!value ?
`SELECT * FROM \`${table}\` WHERE \`id\` = ${this.sanitize(key)} LIMIT 1` :
`SELECT * FROM \`${table}\` WHERE \`${key}\` = ${this.sanitize(value)} LIMIT 1`)
.then(([rows]) => rows[0]).catch(() => null);
/**
* Check if a row exists.
* @param {string} table The name of the table
* @param {string} value The value to search by 'id'.
* @returns {Promise<boolean>}
*/
exports.has = (table, value) => this.runAll(`SELECT \`id\` FROM \`${table}\` WHERE \`id\` = ${this.sanitize(value)} LIMIT 1`)
.then(([rows]) => rows.length > 0);
/**
* Get a random row from a table.
* @param {string} table The name of the table.
* @returns {Promise<Object>}
*/
exports.getRandom = table => this.run(`SELECT * FROM \`${table}\` ORDER BY RAND() LIMIT 1`);
/**
* Insert a new document into a table.
* @param {string} table The name of the table.
* @param {string} row The row id.
* @param {Object} data The object with all properties you want to insert into the document.
* @returns {Promise<Object>}
*/
exports.create = (table, row, data) => {
const { keys, values } = this.serialize(Object.assign(data, { id: row }));
return this.exec(`INSERT INTO \`${table}\` (\`${keys.join("`, `")}\`) VALUES (${values.map(this.sanitize).join(", ")})`);
};
exports.set = (...args) => this.create(...args);
exports.insert = (...args) => this.create(...args);
/**
* Update a row from a table.
* @param {string} table The name of the table.
* @param {string} row The row id.
* @param {Object} data The object with all the properties you want to update.
* @returns {Promise<Object>}
*/
exports.update = (table, row, data) => {
const inserts = Object.entries(data).map(value => `\`${value[0]}\` = ${this.sanitize(value[1])}`).join(", ");
return this.exec(`UPDATE \`${table}\` SET ${inserts} WHERE id = '${row}'`);
};
exports.replace = (...args) => this.update(...args);
/**
* Delete a document from the table.
* @param {string} table The name of the directory.
* @param {string} row The row id.
* @returns {Promise<Object>}
*/
exports.delete = (table, row) => this.exec(`DELETE FROM \`${table}\` WHERE id = ${this.sanitize(row)}`);
/**
* Update the columns from a table.
* @param {string} table The name of the table.
* @param {string[]} columns Array of columns.
* @param {array[]} schema Tuples of keys/values from the schema.
* @returns {boolean}
*/
exports.updateColumns = async (table, columns, schema) => {
await this.exec(`CREATE TABLE \`temp_table\` (\n${schema.map(s => `\`${s[0]}\` ${s[1]}`).join(",\n")}\n);`);
await this.exec(`INSERT INTO \`temp_table\` (\`${columns.join("`, `")}\`) SELECT \`${columns.join("`, `")}\` FROM \`${table}\`;`);
await this.exec(`DROP TABLE \`${table}\`;`);
await this.exec(`ALTER TABLE \`temp_table\` RENAME TO \`${table}\`;`);
return true;
};
/**
* Get a row from an arbitrary SQL query.
* @param {string} sql The query to execute.
* @returns {Promise<Object>}
*/
exports.run = sql => db.query(sql).then(([rows]) => rows[0]).catch(throwError);
/**
* Get all rows from an arbitrary SQL query.
* @param {string} sql The query to execute.
* @returns {Promise<Object>}
*/
exports.runAll = sql => db.query(sql).catch(throwError);
exports.exec = (...args) => this.runAll(...args);
/**
* Transform NoSQL queries into SQL.
* @param {Object} data The object.
* @returns {Object}
*/
exports.serialize = (data) => {
const keys = [];
const values = [];
const entries = Object.entries(data);
for (let i = 0; i < entries.length; i++) {
keys[i] = entries[i][0];
values[i] = entries[i][1];
}
return { keys, values };
};
exports.sanitize = (string) => {
if (typeof string === "string") return `'${string.replace(/'/g, "''")}'`;
else if (string instanceof Object) return `'${JSON.stringify(string).replace(/'/g, "''")}'`;
return JSON.stringify(string);
};
exports.CONSTANTS = {
String: "TEXT",
Integer: "INT",
Float: "INT",
AutoID: "INT PRIMARY KEY AUTOINCREMENT UNIQUE",
Timestamp: "DATETIME",
AutoTS: "DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL",
};
exports.conf = {
moduleName: "mysql",
enabled: true,
requiredModules: ["mysql2"],
sql: true,
};
exports.help = {
name: "mysql",
type: "providers",
description: "Allows you use MySQL functionality throughout Komada.",
};
|
JavaScript
| 0.000002 |
@@ -158,14 +158,8 @@
ion(
-conn:
%7B%0A
|
b06012db6d9edc23875660dc9310986e5b322b76
|
Remove unused requires
|
app.js
|
app.js
|
#!/usr/bin/env node
'use strict';
// FIXME should not be there. This is currently needed to work on a dev Cloudron
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
require('supererror')({ splatchError: true });
var async = require('async'),
express = require('express'),
json = require('body-parser').json,
config = require('./src/config.js'),
cors = require('cors'),
multer = require('multer'),
routes = require('./src/routes.js'),
settings = require('./src/database/settings.js'),
shares = require('./src/database/shares.js'),
tags = require('./src/database/tags.js'),
things = require('./src/database/things.js'),
tokens = require('./src/database/tokens.js'),
morgan = require('morgan'),
MongoClient = require('mongodb').MongoClient,
lastmile = require('connect-lastmile'),
serveStatic = require('serve-static');
var app = express();
var router = new express.Router();
var storage = multer.diskStorage({});
var diskUpload = multer({ storage: storage }).any();
var memoryUpload = multer({ storage: multer.memoryStorage({}) }).any();
router.del = router.delete;
router.post('/api/things', routes.auth, routes.add);
router.get ('/api/things', routes.auth, routes.getAll);
router.get ('/api/things/:id', routes.auth, routes.get);
router.put ('/api/things/:id', routes.auth, routes.put);
router.del ('/api/things/:id', routes.auth, routes.del);
router.post('/api/things/:id/public', routes.auth, routes.makePublic);
router.post('/api/files', routes.auth, memoryUpload, routes.fileAdd);
// FIXME should not be public!!! but is required for thing sharing at the moment
router.get ('/api/files/:identifier', routes.fileGet);
router.get ('/api/share/:userId/:shareId', routes.getPublic);
router.get ('/api/tags', routes.auth, routes.getTags);
router.post('/api/settings', routes.auth, routes.settingsSave);
router.get ('/api/settings', routes.auth, routes.settingsGet);
router.get ('/api/export', routes.auth, routes.exportThings);
router.post('/api/import', routes.auth, diskUpload, routes.importThings);
router.post('/api/login', routes.login);
router.get ('/api/logout', routes.auth, routes.logout);
router.get ('/api/profile', routes.auth, routes.profile);
router.get ('/api/healthcheck', routes.healthcheck);
app.use(morgan('dev', { immediate: false, stream: { write: function (str) { console.log(str.slice(0, -1)); } } }));
app.use(serveStatic(__dirname + '/public', { etag: false }));
app.use(cors());
app.use(json({ strict: true, limit: '5mb' }));
app.use(router);
app.use(lastmile());
function exit(error) {
if (error) console.error(error);
process.exit(error ? 1 : 0);
}
// function welcomeIfNeeded(callback) {
// things.getAll({}, 0, 1, function (error, result) {
// if (error) return callback(error);
// if (result.length > 0) return callback(null);
// things.imp(require(__dirname + '/things.json'), callback);
// });
// }
MongoClient.connect(config.databaseUrl, function (error, db) {
if (error) exit(error);
// stash for database code to be used
config.db = db;
// welcomeIfNeeded(function (error) {
// if (error) exit(error);
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('App listening at http://%s:%s', host, port);
// must be done per user
// tags.cleanup();
// setInterval(tags.cleanup, 1000 * 60);
if (process.env.MAIL_IMAP_SERVER) {
require('./src/mail.js');
}
});
// });
});
|
JavaScript
| 0.000001 |
@@ -215,38 +215,8 @@
var
-async = require('async'),%0A
expr
@@ -428,258 +428,8 @@
'),%0A
- settings = require('./src/database/settings.js'),%0A shares = require('./src/database/shares.js'),%0A tags = require('./src/database/tags.js'),%0A things = require('./src/database/things.js'),%0A tokens = require('./src/database/tokens.js'),%0A
|
0bd75e93b437d8c080e889dad6840d03af34809f
|
Fix typos in app.js
|
app.js
|
app.js
|
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var users = require('./routes/users');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser())
app.use(express.static('public')) /// mix added this
app.use('/api/v1/posts', posts);
module.exports = app;
|
JavaScript
| 0.999978 |
@@ -146,20 +146,20 @@
);%0A%0Avar
-user
+post
s = requ
@@ -176,12 +176,12 @@
tes/
-user
+post
s');
|
dd4c85443a9c2dee57a84f0e89350d8c414b6369
|
Update to make result cleaner,
|
app.js
|
app.js
|
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var request = require('request');
var cheerio = require('cheerio');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
app.get('/trending', function(req, res){
//Scrape the github trending site
var url = 'https://github.com/trending';
var repos = [];
request(url, function(error, response, html){
if(!error) {
var $ = cheerio.load(html);
$('li.repo-list-item').each(function onEach () {
var repository = {};
var $elem = $(this);
var language = $elem.find('.repo-list-meta').text().split('•');
var starsTodayUncut = $elem.find('.repo-list-meta').text().split('•');
var starsToday = starsTodayUncut.length === 3? starsTodayUncut[1].trim(): '';
repository.title = $elem.find('.repo-list-name a').attr('href');
// Remove the first slash
repository.title = repository.title.substring(1, repository.title.length);
repository.owner = $elem.find('span.prefix').text();
repository.description = $elem.find('p.repo-list-description').text().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
repository.url = 'https://github.com/' + repository.owner + '/' + repository.title.split('/')[1];
repository.language = language.length === 3 ? language[0].trim() : '';
repository.starsToday = starsToday.split(/\s+/)[0];
repository.totalStars = getStars(repository.url);
console.log('received total stars '+repository.totalStars);
repos.push(repository);
});
}
})
})
function getStars(url)
{
console.log('url being sent '+url);
var totalStars;
request(url, function(error, response, html)
{
console.log('response error '+response, +error);
if(!error)
{
var $ = cheerio.load(html);
var $repo = $(this);
totalStars = $repo.find('social-count js-social-count a').text();
console.log('total stars '+totalStars);
}
});
return totalStars;
}
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// 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: {}
});
});
var port = Number(process.env.PORT || 5000);
app.listen(port, function () {
console.log('Listening on ' + port);
});
module.exports = app;
|
JavaScript
| 0 |
@@ -1687,130 +1687,64 @@
-repository.totalStars = getStars(repository.url);%0A console.log('received total stars '+repository.totalStars);%0A
+var metadata = %7B%0A name: repository.title,
%0A
@@ -1756,19 +1756,19 @@
-repos.push(
+ owner:
repo
@@ -1773,18 +1773,23 @@
pository
-);
+.owner,
%0A
@@ -1793,20 +1793,16 @@
-%7D);%0A
%7D%0A
@@ -1801,170 +1801,95 @@
-%7D%0A %7D)%0A%7D)%0A%0Afunction getStars(url)%0A%7B%0A console.log('url being sent '+url);%0A var totalStars;%0A request(url, function(error,
+description: repository.description,%0A url:
re
-s
po
-nse, html)
+sitory.url,
%0A
-%7B%0A
cons
@@ -1888,333 +1888,209 @@
-console.log('response error '+
+ language:
re
-s
po
-nse, +error);%0A if(!error)%0A %7B%0A var $ = cheerio.load(html);%0A var $repo = $(this);%0A totalStars = $repo.find('social-count js-social-count a').text();%0A console.log('total stars '+totalStars);%0A %7D%0A %7D);%0A%0A return totalStars;%0A%7D
+sitory.language,%0A starsToday: repository.starsToday%0A %7D;%0A%0A repos.push(metadata);%0A %7D);%0A console.log(repos%5B0%5D);%0A %7D%0A %7D);%0A%7D)
%0A%0A//
|
54fbe0290981d1b0c49053568ae240bbb6eac740
|
Add animation function
|
app.js
|
app.js
|
var DefinitionCreate = FormView.extend({
model: Definition,
initialize: function () {
FormView.prototype.initialize.call(this);
this.modelname = this.options.modelname;
this.title = 'Create ' + this.modelname;
this.instance.set({id: this.modelname,
title: this.modelname,
description: this.modelname});
return this;
},
cancel: function () {
app.navigate('', {trigger:true});
},
submit: function() {
FormView.prototype.submit.apply(this, arguments);
this.instance.save({wait: true});
},
success: function () {
app.navigate(this.modelname, {trigger:true});
},
});
var AddView = FormView.extend({
model: Item,
initialize: function () {
FormView.prototype.initialize.call(this);
this.map = this.options.map;
this.collection = this.options.collection;
this.marker = null;
},
render: function () {
FormView.prototype.render.apply(this, arguments);
this.map.on('click', this.onMapClick.bind(this));
return this;
},
close: function (e) {
if (this.marker) this.map.removeLayer(this.marker);
this.map.off('click');
this.remove();
return false;
},
cancel: function () {
this.close();
},
success: function () {
this.close();
},
submit: function(e) {
FormView.prototype.submit.apply(this, arguments);
this.collection.create(this.instance);
},
onMapClick: function (e) {
this.marker = L.marker(e.latlng).addTo(this.map);
this.$el.find('#map-help').remove();
this.instance.setLayer(this.marker);
},
});
var ListView = Backbone.View.extend({
template: Mustache.compile('<h1>{{ definition.title }}</h1><p>{{ definition.description }}</p><div id="toolbar"><a id="add" class="btn">Add</a></div>' +
'<div id="list"></div><div id="footer">{{ count }} items.</div>'),
events: {
"click a#add": "addForm",
},
initialize: function (map, definition) {
this.map = map;
this.definition = definition;
this.collection = new ItemList(definition);
this.collection.bind('add', this.addOne, this);
this.collection.bind('reset', this.addAll, this);
this.collection.fetch();
this.addView = new AddView({map:map,
definition:this.definition,
collection:this.collection});
},
render: function () {
var count = this.collection.length;
this.$el.html(this.template({definition: this.definition.attributes, count:count}));
this.$el.find("#list").html(this.definition.tableContent());
return this;
},
addForm: function (e) {
e.preventDefault();
this.$el.find("#list").prepend(this.addView.render().el);
},
addOne: function (item) {
var tpl = this.definition.templateRow();
this.$('table tbody').append(tpl(item.toJSON()));
var geom = item.layer();
if (geom) {
geom.addTo(this.map);
this.bounds.extend(geom.getLatLng());
}
},
addAll: function () {
this.render();
this.bounds = new L.LatLngBounds();
this.collection.each(this.addOne.bind(this));
if (this.bounds.isValid()) this.map.fitBounds(this.bounds);
},
});
var HomeView = Backbone.View.extend({
template: Mustache.compile('<h1>Daybed Map</h1><input id="modelname" placeholder="Name"/><a href="#" class="btn">Go</a>'),
events: {
"keyup input#modelname": "setLink",
},
render: function () {
this.$el.html(this.template({}));
return this;
},
setLink: function (e) {
this.$el.find("a").attr("href", '#' + $(e.target).val());
}
});
var DaybedMapApp = Backbone.Router.extend({
routes: {
"": "home",
":modelname/create": "create",
":modelname": "list",
},
initialize: function () {
this.definition = null;
this.map = L.map('map').setView([0, 0], 3);
this.map.attributionControl.setPrefix('');
L.tileLayer('http://{s}.tiles.mapbox.com//v3/leplatrem.map-3jyuq4he/{z}/{x}/{y}.png').addTo(this.map);
},
home: function() {
$("#content").html(new HomeView().render().el);
},
create: function(modelname) {
$("#content").html(new DefinitionCreate({modelname: modelname}).render().el);
},
list: function(modelname) {
if (!this.definition || this.definition.modelname != modelname) {
this.definition = new Definition({id: modelname});
var createIfMissing = function (model, xhr) {
if (xhr.status == 404) {
app.navigate(modelname + '/create', {trigger:true});
}
};
this.definition.fetch({error: createIfMissing});
}
var self = this;
this.definition.whenReady(function () {
$("#content").html(new ListView(self.map, self.definition).render().el);
});
},
});
|
JavaScript
| 0.000002 |
@@ -3130,17 +3130,96 @@
JSON()))
-;
+%0A .css(%22opacity%22, %220.1%22)%0A .animate(%7Bopacity: 1.0%7D, 1000);%0A
%0A
|
edf59a300cf98687b41af57fbf6675c0d0dff953
|
Move favicon.ico higher up the chain
|
app.js
|
app.js
|
// server.js
//
// main function for activity pump application
//
// Copyright 2011-2012, StatusNet Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var connect = require('connect'),
auth = require('connect-auth'),
bcrypt = require('bcrypt'),
databank = require('databank'),
express = require('express'),
_ = require('underscore'),
api = require('./routes/api'),
web = require('./routes/web'),
schema = require('./lib/schema'),
HTTPError = require('./lib/httperror').HTTPError,
Provider = require('./lib/provider').Provider,
config = require('./config'),
params,
Databank = databank.Databank,
DatabankObject = databank.DatabankObject,
db,
app,
port,
hostname;
port = config.port || process.env.PORT || 8001;
hostname = config.hostname || process.env.HOSTNAME || 'localhost';
// Initiate the DB
if (_(config).has('params')) {
params = config.params;
} else {
params = {};
}
if (_(params).has('schema')) {
_.extend(params.schema, schema);
} else {
params.schema = schema;
}
db = Databank.get(config.driver, params);
// Connect...
db.connect({}, function(err) {
var server;
var app = module.exports = express.createServer();
if (err) {
console.log("Couldn't connect to JSON store: " + err.message);
process.exit(1);
}
// Configuration
app.configure(function() {
// Templates are in public
app.set('views', __dirname + '/public/template');
app.set('view engine', 'utml');
app.use(express.logger());
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.query());
app.use(express.methodOverride());
app.use(express.session({secret: (config.secret || "activitypump")}));
var provider = new Provider();
app.use(auth([auth.Oauth({name: "client",
oauth_provider: provider,
oauth_protocol: 'http',
authenticate_provider: null,
authorize_provider: null,
authorization_finished_provider: null
}),
auth.Oauth({name: "user",
oauth_provider: provider,
oauth_protocol: 'http',
authenticate_provider: web.authenticate,
authorize_provider: web.authorize,
authorization_finished_provider: web.authorizationFinished
})
]));
app.use(function(req, res, next) {
res.local('site', (config.site) ? config.site : "ActivityPump");
res.local('owner', (config.owner) ? config.owner : "Anonymous");
res.local('ownerurl', (config.ownerURL) ? config.ownerURL : false);
next();
});
app.use(app.router);
app.use(express.favicon());
app.use(express['static'](__dirname + '/public'));
});
app.error(function(err, req, res, next) {
if (err instanceof HTTPError) {
if (req.xhr) {
res.json({error: err.message}, err.code);
} else if (req.accepts('html')) {
res.render('error', {status: err.code, error: err, title: "Error"});
} else {
res.writeHead(err.code, {'Content-Type': 'text/plain'});
res.end(err.message);
}
} else {
next(err);
}
});
// Routes
api.addRoutes(app);
// Use "noweb" to disable Web site (API engine only)
if (!_(config).has('noweb') || !config.noweb) {
web.addRoutes(app);
}
api.setBank(db);
DatabankObject.bank = db;
app.listen(port);
});
|
JavaScript
| 0.000002 |
@@ -2311,16 +2311,52 @@
mp%22)%7D));
+%0A app.use(express.favicon());
%0A%0A
@@ -3600,44 +3600,8 @@
);%0A%0A
- app.use(express.favicon());%0A
|
eedb488f07f9ffab731cdbc9d79376f1bb88ff22
|
add morgan log
|
app.js
|
app.js
|
var express = require('express');
var path = require('path');
var mount_routes = require('mount-routes');
var mount_plugins = require('mount_plugin');
var app = express();
var lifecycle = require('./lifecycle');
app.set_absolute_path = function (key, path) {
this.set(key, app.cfg.root + "/" + path);
};
app.set_key_with_setting_key = function (key, setting_key) {
var __path = path.join(app.cfg.root, app.cfg[setting_key]);
if (app.debug) {
console.log(key + " = " + __path);
}
this.set(key, __path);
};
/**
* mount routes
*/
app.mount_routes = function (path) {
mount_routes(this, path, this.debug);
}
/**
* mount plugins
*/
app.mount_plugins = function (plugin_dir) {
mount_plugins(this, plugin_dir, this.debug);
}
module.exports = function (config) {
var deepExtend = require('deep-extend');
deepExtend(app, {
express: express
});
var cfg = {
debug: false,
log_enable:true,
log_level:"dev",
// "views": "views",
// "routes": "routes",
// "public": "public",
pre: function (app) {
if (app.debug) {
console.log('pre hook');
}
},
post: function (app) {
if (app.debug) {
console.log('post hook');
}
}
}
deepExtend(cfg, config);
app.debug = cfg.debug;
if(app.debug){
app.set('root', path.join(__dirname, '../..'));
}else{
// xx/node_modules/base2/.
app.set('root', path.join(__dirname, '../..'));
}
app.cfg = cfg;
// init lifecycle
var life = app.life = lifecycle(app);
// deepExtend(app, cfg);
// hook_pre
hook_pre(app);
// settings
life.settings();
//
// global middlewares
life.global_middlewares();
//
// routes
life.routes();
// hook_post
hook_post(app);
return app;
};
function __set(app, k, v, default_v){
app.set('port', v ? v : default_v);
}
function __call (config, key, app) {
if (config[key]) {
config[key](app);
}
}
function hook_post (app) {
__call(app.cfg, 'post', app);
}
function hook_pre (app) {
__call(app.cfg, 'pre', app);
}
|
JavaScript
| 0.000025 |
@@ -962,11 +962,13 @@
ble:
-tru
+ fals
e,%0A
@@ -980,16 +980,17 @@
g_level:
+
%22dev%22,%0A
|
c0110918f8922c9634b3c74facf8207b415172a7
|
change well_known to well-known
|
app.js
|
app.js
|
const express = require('express');
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const database = require( './db' );
const fs = require( 'fs' );
const rotator = require('file-stream-rotator')
const secrets = require('./config/secrets')
// --------------------------------------------------------------------------------------
// call express
var app = express();
// disable express header
app.disable('x-powered-by')
// connect to the database
database.connect();
// init session
app.set('trust proxy', 1) // app is behind a proxy
app.use(session({ secret : secrets.session,
secure : true,
cookie: { secure: true },
proxy: true,
resave : false,
saveUninitialized : false,
store : new MongoStore({ db : 'SessionStore', url : 'mongodb://localhost:27017/etlog', ttl: 30 * 24 * 60 * 60 }),
}));
// --------------------------------------------------------------------------------------
// view engine setup
app.set('views', __dirname + '/views');
app.set('view engine', 'pug');
// --------------------------------------------------------------------------------------
// set up webserver log files
var log_dir = '/home/etlog/logs/access/';
// ensure log directory exists
fs.existsSync(log_dir) || fs.mkdirSync(log_dir);
// create a rotating write stream
var access_log = rotator.getStream({
date_format: 'YYYY-MM-DD',
filename: path.join(log_dir, 'access-%DATE%.log'),
frequency: 'daily',
verbose: false
})
// --------------------------------------------------------------------------------------
// uncomment after placing your favicon in /public
app.use(favicon(__dirname + '/public/favicon.ico'));
// custom logging
logger.token('user_role', function (req, res) {
if(req.session && req.session.user && req.session.user.role)
return req.session.user.role;
else
return "";
});
// Standard Apache combined log output with added response time and status
// output to access log
app.use(logger(':remote-addr - :req[remote_user] ":user_role" [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent" :response-time[3] ms :status', { stream : access_log }));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/.well_known', express.static('public/.well_known'));
// --------------------------------------------------------------------------------------
// Make our db accessible to our router
app.use(function(req, res, next){
req.db = database;
next();
});
// --------------------------------------------------------------------------------------
// set up routes
require('./routes')(app, database);
// --------------------------------------------------------------------------------------
// set up cron tasks
require('./cron')(database);
// --------------------------------------------------------------------------------------
// set up middleware error handling
require('./error_handling')(app);
// --------------------------------------------------------------------------------------
module.exports = app;
|
JavaScript
| 0.998208 |
@@ -2670,25 +2670,25 @@
.use('/.well
-_
+-
known', expr
@@ -2711,17 +2711,17 @@
ic/.well
-_
+-
known'))
|
a038de0ac273d3fb45c7bb63923c405ec8514675
|
remove large intro text
|
app.js
|
app.js
|
var https = require("https");
var cities = require("cities");
var zip = process.argv.slice(2);
// allow multiple inputs
// throw error when no argv
function printer(data) {
console.log("________________________________________________");
console.log("");
console.log(" 0 0 0000 0000 00000 0 0 0000 0000 ");
console.log(" 0 0 0 0 0 0 0 0 0 0 0 ");
console.log(" 0 0 0 0000 0000 0 0000 0000 0000 ");
console.log(" 0 0 0 0 0 0 0 0 0 0 0 0 ");
console.log(" 00000 0000 0 0 0 0 0 0000 0 0 ");
console.log("________________________________________________");
console.log("");
console.log(cities.zip_lookup(zip).city + ", " + cities.zip_lookup(zip).state_abbr + " " + zip);
console.log("");
console.log("Currently:");
console.log("----------------");
console.log(data.currently.summary + " and " + data.currently.temperature + "\u00b0F");
console.log("Feels like " + data.currently.apparentTemperature + "\u00b0F");
console.log("Humidity: " + data.currently.humidity);
console.log("Wind: " + data.currently.windSpeed + " bearing \u00b0" + data.currently.windBearing);
// change bearing to cardinal directions
console.log("");
console.log(data.daily.summary);
console.log("");
console.log("Tomorrow:");
console.log("----------------");
console.log("High: " + data.daily.data[0].temperatureMax + "\u00b0F");
console.log("Low: " + data.daily.data[0].temperatureMin + "\u00b0F");
console.log("Precipitation: " + (data.daily.data[0].precipProbability * 100) + "%");
}
function weather(zip) {
var latitude = cities.zip_lookup(zip).latitude;
var longitude = cities.zip_lookup(zip).longitude;
var request = https.get('https://api.forecast.io/forecast/2a65c574d33b0f4ea0c5dda6b777c91c/' + latitude + ',' + longitude, function(response) {
var body = "";
response.on('data', function(chunk) {
body += chunk;
});
response.on('end', function() {
if (response.statusCode === 200) {
try {
var data = JSON.parse(body);
printer(data);
} catch(error) {
console.error(error.message);
}
} else {
console.error("Oh no! Error.");
// custom messages for common statusCodes
}
});
});
request.on("error", function(error) {
console.error(error.message);
});
}
weather(zip);
|
JavaScript
| 0.999891 |
@@ -188,470 +188,8 @@
og(%22
-________________________________________________%22);%0A%09console.log(%22%22);%0A%09console.log(%22 0 0 0000 0000 00000 0 0 0000 0000 %22);%0A%09console.log(%22 0 0 0 0 0 0 0 0 0 0 0 %22);%0A%09console.log(%22 0 0 0 0000 0000 0 0000 0000 0000 %22);%0A%09console.log(%22 0 0 0 0 0 0 0 0 0 0 0 0 %22);%0A%09console.log(%22 00000 0000 0 0 0 0 0 0000 0 0 %22);%0A%09console.log(%22________________________________________________
%22);%0A
|
86cca371875cc36fd8658a079e1d07d91c2d9c84
|
Use client folder
|
app.js
|
app.js
|
var express = require('express');
var app = express();
app.use(express.static('public/'));
var port = process.env.PORT || 3000;
app.listen(port, function() {
console.log('Listening on port ' + port);
});
|
JavaScript
| 0.000001 |
@@ -77,14 +77,14 @@
ic('
-public
+client
/'))
|
c54ce98dd6e0f5d06020a3b5960023526589b63f
|
reset timer when clicking on 'prev'/'next'
|
app.js
|
app.js
|
/* jshint globalstrict: true, eqnull: true */
/* globals $, _, noUiSlider, Tsv, document, window, moment, d3 */
'use strict';
$(function() {
$.get('assets/data.tsv', function(rawData) {
var data = _.filter(d3.tsv.parse(rawData, function(d) {
return {
rawDate : d.Date,
date : moment(d.Date, 'DD/MM/YYYY'),
text : d.Texte
};
}), function(d) {
return d.rawDate != null && d.text != null;// && d.rawDate !== '01/01/1993'; // TMP
});
data = _.chain(data).groupBy('rawDate').values().map(function(d) {
return {
rawDate : d[0].rawDate,
date : d[0].date,
texts : _.pluck(d, 'text')
};
}).value();
var current = data[0];
var minDate = _.min(_.pluck(data, 'date'), function(d) { return d.unix(); }),
maxDate = _.max(_.pluck(data, 'date'), function(d) { return d.unix(); }),
totalDays = maxDate.diff(minDate, 'days');
var range = { },
scale = d3.scale.linear().domain([minDate.unix(), maxDate.unix()]).range([0, 100]);
_.each(data, function(d, i) {
d.percent = _.round(scale(d.date.unix()), 2);
// Slider
var name = i === 0 ? 'min'
: ((i === data.length - 1) ? 'max' : (String(d.percent) + '%'));
range[name] = d.percent;
// Steps
$('.steps').append($('<span>').addClass('steps__step')
.css('left', String(d.percent) + '%'));
});
var slider = document.getElementById('slider');
noUiSlider.create(slider, {
start : 0,
snap : true,
range : range
});
slider.noUiSlider.on('update', function(values) {
var currentIndex = _.findIndex(data, { percent : parseFloat(values[0]) });
current = data[currentIndex];
$('.text').html(current.texts.join('<br><br>'));
$('.steps__step').removeClass('current');
$($('.steps__step').get(currentIndex)).addClass('current');
});
/*
** Controls
*/
var timer,
playPause = function(play) {
if (play) {
window.clearTimeout(timer);
timer = window.setInterval(function() {
$('.next').click();
}, 1000);
$('.playpause').find('i.fa').removeClass('fa-play').addClass('fa-pause');
} else {
window.clearTimeout(timer);
timer = null;
$('.playpause').find('i.fa').removeClass('fa-pause').addClass('fa-play');
}
};
$('.prev').click(function() {
var currentIndex = _.findIndex(data, current);
if (currentIndex > 0) {
slider.noUiSlider.set(data[currentIndex - 1].percent);
}
});
$('.next').click(function() {
var currentIndex = _.findIndex(data, current);
if (currentIndex < data.length - 1) {
slider.noUiSlider.set(data[currentIndex + 1].percent);
} else {
playPause(false);
}
});
$('.playpause').click(function() {
playPause(timer == null);
});
});
});
|
JavaScript
| 0 |
@@ -3046,32 +3046,65 @@
- 1%5D.percent);%0A
+ playPause(true);%0A
%7D%0A
@@ -3325,32 +3325,65 @@
+ 1%5D.percent);%0A
+ playPause(true);%0A
%7D el
|
cbdba822eddecb9f7c73d3755e7c33bb891fc69b
|
add comments on failing test
|
app.js
|
app.js
|
cordova('asyncSeverStarted').registerAsync(function(message, callback){
function poll(){
setTimeout(function() {
if(typeof exports.app != 'undefined') {
callback("Pong:" + message);
} else {
poll();
}
}, 250);
}
poll();
});
//// Hello World HTTP server
//// Load the http module to create an http server.
//var http = require('http');
//
//// Configure our HTTP server to respond with Hello World to all requests.
//var server = http.createServer(function (request, response) {
// response.writeHead(200, {"Content-Type": "text/plain"});
// response.end("Hello World\n");
//});
//
//// Listen on port 3030, IP defaults to 127.0.0.1
//server.listen(3030);
//
//// Put a friendly message on the terminal
//console.log("Server running at http://127.0.0.1:3030/");
//// Hello World Express Server
//var express = require('express');
//var app = express();
//
//app.get('/', function (req, res) {
// res.send('Hello World!');
//});
//
//var server = app.listen(3030, function () {
//
// var host = server.address().address;
// var port = server.address().port;
//
// console.log('Example app listening at http://%s:%s', host, port);
//
//});
//// Hello World Static File Express Server
//var express = require('express');
//var app = express();
//
//app.use(express.static('public'));
//
//var server = app.listen(3030, function () {
//
// var host = server.address().address;
// var port = server.address().port;
//
// console.log('Example app listening at http://%s:%s', host, port);
//
//});
// Hello World Static File Express Server with etag false
var express = require('express');
var app = express();
var serveStatic = require('serve-static');
app.use(serveStatic('public',{ etag: false }));
var server = app.listen(3030, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
exports.app = app;
|
JavaScript
| 0 |
@@ -1606,24 +1606,1111 @@
t);%0A//%0A//%7D);
+%0A//%0A// Fails with Error:%0A//%0A//E/jxcore-log%EF%B9%95 etag@/data/data/com.openmoney.p2p/files/jxcore/node_modules/express/node_modules/etag/index.js:55:1%0A//setHeader@/data/data/com.openmoney.p2p/files/jxcore/node_modules/express/node_modules/send/index.js:739:15%0A//SendStream.prototype.send@/data/data/com.openmoney.p2p/files/jxcore/node_modules/express/node_modules/send/index.js:507:3%0A//sendIndex/next/%3C@/data/data/com.openmoney.p2p/files/jxcore/node_modules/express/node_modules/send/index.js:645:7%0A//makeCallback/%[email protected]:84:12%0A//[email protected]:780:7%0A//next@/data/data/com.openmoney.p2p/files/jxcore/node_modules/express/node_modules/send/index.js:641:5%0A//sendIndex@/data/data/com.openmoney.p2p/files/jxcore/node_modules/express/node_modules/send/index.js:649:3%0A//SendStream.prototype.pipe@/data/data/com.openmoney.p2p/files/jxcore/node_modules/express/node_modules/send/index.js:475:5%0A//serveStatic@/data/data/com.openmoney.p2p/files/jxcore/node_modules/express/node_modules/serve-static/index.js:111:5%0A//handle@/data/data/com.openmoney.p2p/files/jxcore/node_modules/express/lib/router/layer.js
%0A%0A// Hello W
|
a5b6f4184ed9e49d8692fec338bdc6c795df1848
|
mark mentions
|
app.js
|
app.js
|
var vorpal = require('vorpal')(),
DataStore = require('nedb'),
cache = new DataStore(),
fs = require('fs'),
nconf = require('nconf'),
Twit = require('twit'),
ShortIdGenerator = require('./ShortIdGenerator'),
colors = require('colors');
var T = null;
var ME;
var twitterPinAuth = null;
nconf.argv()
.env()
.file({ file: 'config.json' });
vorpal.commands = [];
vorpal
.command('/exit', 'Exit ntwt')
.action(function(args) {
args.options = args.options || {};
args.options.sessionId = this.session.id;
this.parent.exit(args.options);
});
vorpal
.command('/show <id>', 'Show cached tweet by id')
.action(function(args, callback) {
var id = args.id || -1;
var self = this;
cache.findOne({ id: id }, function(err, doc) {
if (err) return;
displayStatus(doc.status);
});
callback();
});
vorpal
.mode('/login')
.description('Authenticate your Twitter account')
.delimiter('PIN:')
.init(function(args, callback) {
var self = this;
var TwitterPinAuth = require('twitter-pin-auth');
twitterPinAuth = new TwitterPinAuth(
nconf.get('auth:consumer_key'),
nconf.get('auth:consumer_secret'));
twitterPinAuth.requestAuthUrl()
.then(function(url) {
self.log("Login and copy the PIN number: " + url);
})
.catch(function(err) {
self.log(err);
});
callback();
})
.action(function(arg, callback) {
var self = this;
twitterPinAuth.authorize(arg)
.then(function(data) {
self.log(data.accessTokenKey);
self.log(data.accessTokenSecret);
nconf.set('auth:access_token', data.accessTokenKey);
nconf.set('auth:access_token_secret', data.accessTokenSecret);
nconf.save(function (err) {
fs.readFile('config.json', function (err, data) {
console.dir(JSON.parse(data.toString()))
});
});
self.log("Authentication successfull.\n\nPlease restart ntwt!");
var options = {};
options.sessionId = self.session.id;
self.parent.exit(options);
})
.catch(function(err) {
self.log('Authentication failed!');
self.log(err);
});
callback();
});
vorpal
.catch('[words...]', 'Tweet')
.action(function(args, callback) {
if (!T || !args.words) return;
var self = this;
var status = args.words.join(' ');
T.post('statuses/update', { status: status })
.catch(function(err) {
if (err) self.log(err);
});
callback();
});
vorpal.log('Welcome to ntwt!');
if (!nconf.get('auth:access_token') || !nconf.get('auth:access_token_secret')) {
vorpal.log('Type /login to authenticate with Twitter.');
} else {
vorpal.log('Logging in...');
T = new Twit({
consumer_key: nconf.get('auth:consumer_key'),
consumer_secret: nconf.get('auth:consumer_secret'),
access_token: nconf.get('auth:access_token'),
access_token_secret: nconf.get('auth:access_token_secret')
});
T.get('account/verify_credentials', { skip_status: true })
.catch(function(err) {
vorpal.log('Error GET account/verify_credentials: ' + err);
})
.then(function(result) {
vorpal.log("Logged in as " + result.data.screen_name);
ME = result.data;
});
T.get('statuses/home_timeline', { count: 20 })
.catch(function(err) {
vorpal.log('Error GET statuses/home_timeline: ' + err);
})
.then(function(result) {
vorpal.log(result);
result.data.forEach(function(tweet) {
displayStatus(tweet);
});
});
var stream = T.stream('user');
stream.on('tweet', function(tweet) {
displayStatus(tweet);
})
}
var displayStatus = function(status) {
var id = ShortIdGenerator.generate();
var doc = {
id: id,
status: status
};
cache.insert(doc);
var line = id + "> ";
line += "<@";
line += status.user.screen_name == ME.screen_name
? status.user.screen_name.underline.yellow
: status.user.screen_name.underline.blue;
line += ">: ";
line += status.text;
line += '\n';
vorpal.log(line);
};
vorpal
.delimiter('ntwt>')
.show();
|
JavaScript
| 0.000022 |
@@ -3930,40 +3930,8 @@
) %7B%0A
- vorpal.log(result);%0A
@@ -3968,32 +3968,32 @@
nction(tweet) %7B%0A
+
@@ -4160,16 +4160,237 @@
%7D)%0A%7D%0A%0A
+var isMention = function(status) %7B%0A var mention = false;%0A status.entities.user_mentions.forEach(function(mention) %7B%0A if (mention.screen_name == ME.screen_name) mention = true;%0A %7D);%0A return mention;%0A%7D;%0A%0A
var disp
@@ -4763,24 +4763,24 @@
e += %22%3E: %22;%0A
-
line +=
@@ -4770,32 +4770,70 @@
: %22;%0A line +=
+ isMention(status) ? status.text.red :
status.text;%0A
|
b01dbb7e0b21fc1a92ec4b4fe42c1c42eeb7235e
|
Stop using deprecated bodyParser constructor
|
app.js
|
app.js
|
'use strict';
var path = require('path');
var hook = require('./hook');
var config = require('./config');
var logger = require('./logger');
// Set up Express
var express = require('express');
var bodyParser = require('body-parser');
var port = process.env.PORT || config.port;
var app = express();
app.use(bodyParser());
app.use(express.static(path.join(__dirname, 'build/www')));
app.post('/hook', hook.handle);
exports.listener = app.listen(port);
logger.info('Listening at port:', port);
|
JavaScript
| 0.000534 |
@@ -37,16 +37,92 @@
ath');%0A%0A
+var express = require('express');%0Avar bodyParser = require('body-parser');%0A%0A
var hook
@@ -216,101 +216,8 @@
);%0A%0A
-// Set up Express%0Avar express = require('express');%0Avar bodyParser = require('body-parser');%0A
var
@@ -257,16 +257,34 @@
.port;%0A%0A
+// Set up Express%0A
var app
@@ -318,12 +318,96 @@
rser
-());
+.urlencoded(%7B%0A extended: true%0A%7D));%0Aapp.use(bodyParser.json());%0A%0A// Serve the homepage
%0Aapp
@@ -462,16 +462,41 @@
www')));
+%0A%0A// Handle webhook POSTs
%0Aapp.pos
@@ -558,17 +558,16 @@
(port);%0A
-%0A
logger.i
|
d62b47e03b9b4665dd571f9889d0311dd4c5c07e
|
add routing to send craigslist model via json to be used to build view
|
app.js
|
app.js
|
var express = require('express');
var app = express();
var http = require('http');
var bodyParser = require('body-parser');
var ajaxSearchHandler = require('./models/request_to_url');
app.use(express.static('public_html'));
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
var responseOptions = {
root: __dirname,
dotfiles: 'deny',
headers: {
'x-timestamp': Date.now(),
'x-sent': true
}
};
app.get('/', function (req, res) {
res.sendFile('views/homepage.html', responseOptions);
});
app.post('/data', function (req, res) {
console.log(req.body);
var reqUrl = ajaxSearchHandler.urlFromRequest(req.body);
if(reqUrl.match(/^http:/)){
http.get(reqUrl, function(searchResponse) {
searchResponse.pipe(res);
});
}
else{
res.status(400).send('400 Bad request');
}
});
//The 404 Route (ALWAYS Keep this as the last route)
app.get('*', function(req, res){
res.status(404).send('404 not found');
});
var server = app.listen(3000, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Wordpop-node app listening at http://%s:%s', host, port);
});
|
JavaScript
| 0 |
@@ -121,33 +121,23 @@
');%0Avar
-ajaxSearchHandler
+CLModel
= requi
@@ -153,21 +153,15 @@
els/
-request_to_ur
+cl_mode
l');
@@ -700,25 +700,15 @@
l =
-ajaxSearchHandler
+CLModel
.url
@@ -941,16 +941,97 @@
%7D%0A%7D);%0A%0A
+app.get('/data/cl.json', function (req, res) %7B%0A res.send(CLModel.model);%0A%7D);%0A%0A
//The 40
|
bcef5027efee4a1ddff4d11dbbe7b93f2d590aa5
|
Add highestGrandchildren and noChildren functions and update Person prototype attributes
|
app.js
|
app.js
|
//Hold family members
var familyTree = [];
function Person(name)
{
this.name = name;
this.parent = null;
this.children = [];
this.siblings = [];
this.grandparent = null;
this.addChild = function(name) {
var child = new Person(name);
child.parent = this;
if (child.parent.parent != null) {
child.grandparent = child.parent.parent;
}
this.children.push(child);
};
this.init();
};
//Add new people to family tree
Person.prototype.init = function(){
familyTree.push(this)
};
var findPerson = function(name){
for (var i = 0; i < familyTree.length; i++) {
if (familyTree[i].name === name){
// console.log(familyTree[i]);
return familyTree[i];
}
}
console.log("Person not found");
}
//Add family members
var nancy = new Person("Nancy");
nancy.addChild("Adam")
nancy.addChild("Jill")
nancy.addChild("Carl")
findPerson("Carl").addChild("Joseph")
findPerson("Carl").addChild("Catherine")
findPerson("Jill").addChild("Kevin")
findPerson("Kevin").addChild("Samuel")
findPerson("Kevin").addChild("George")
findPerson("Kevin").addChild("James")
findPerson("Kevin").addChild("Aaron")
findPerson("James").addChild("Mary")
findPerson("George").addChild("Patrick")
findPerson("George").addChild("Robert")
console.log(findPerson("James").grandparent)
|
JavaScript
| 0.000001 |
@@ -173,10 +173,35 @@
ll;%0A
+%09this.grandchildren = 0;%0A
%09%0A
-
%09thi
@@ -331,47 +331,107 @@
%09%09%09%09
-child.grand
+var granny = child.parent.
parent
- =
+%0A%09%09%09%09
child.
+grand
parent
-.parent
+ = granny.name;%0A%09%09%09%09granny.grandchildren += 1
;%0A%09%09
@@ -466,16 +466,43 @@
d);%0A%09%7D;%0A
+%09//Auto add to family tree%0A
%09this.in
@@ -726,41 +726,8 @@
e)%7B%0A
-//%09%09%09console.log(familyTree%5Bi%5D);%0A
%09%09%09r
@@ -791,16 +791,425 @@
d%22);%0A%7D%0A%0A
+var noChildren = function()%7B%0A%09for (var i = 0; i %3C familyTree.length; i++) %7B%0A%09%09if (familyTree%5Bi%5D.children.length === 0)%7B%0A%09%09%09console.log(familyTree%5Bi%5D.name);%0A%09%09%7D%0A%09%7D%0A%7D%0A%0Avar highestGrandchildren = function()%7B%0A%09var highest = familyTree%5B0%5D;%0A%09for (var i = 0; i %3C familyTree.length-1; i++) %7B%0A%09%09if (familyTree%5Bi%5D.grandchildren %3E highest.grandchildren)%7B%0A%09%09%09highest = familyTree%5Bi%5D%0A%09%09%7D%0A%09%7D%0A%09console.log(highest.name);%0A%7D%0A%0A
//Add fa
@@ -1741,21 +1741,21 @@
on(%22
-James
+Kevin
%22).grand
pare
@@ -1754,11 +1754,51 @@
rand
-parent)
+children)%0AnoChildren();%0AhighestGrandchildren();
|
166a231106af7574c99811306698fd2284591c2a
|
Send response for debug ocr
|
app.js
|
app.js
|
var fs = require('fs');
var path = require('path');
var superagent = require('superagent');
var restify = require('restify');
var builder = require('botbuilder');
var server = restify.createServer();
var oxford = require('project-oxford');
var telegramDebug = require('./telegram-debug');
var jsonPrettify = require('json-pretty');
/**
* START BOOTSTRAP
*/
var applicationPassword = null;
var config = {
environment: (process.env.NODE_ENV || 'development'),
botCredentials: {},
luisCredentials: {},
visionApiCredentials: {}
};
config.botCredentials.appId = process.env.MICROSOFT_APP_ID;
config.botCredentials.appPassword = process.env.MICROSOFT_APP_PASSWORD;
config.luisCredentials.id = process.env.MICROSOFT_LUIS_ID;
config.luisCredentials.key = process.env.MICROSOFT_LUIS_KEY;
config.visionApiCredentials.key = process.env.MICROSOFT_VISIONAPI_KEY;
var model = `https://api.projectoxford.ai/luis/v1/application?id=${config.luisCredentials.id}&subscription-key=${config.luisCredentials.key}`;
var recognizer = new builder.LuisRecognizer(model);
var dialog = new builder.IntentDialog({ recognizers: [
recognizer
] });
dialog.begin = function(session, reply) {
this.replyReceived(session);
}
/**
* START CONTROLLER
*/
var connector = (config.environment === 'development') ?
new builder.ConsoleConnector().listen() :
new builder.ChatConnector(config.botCredentials);
var bot = new builder.UniversalBot(connector);
bot.dialog('/', dialog);
const pathToIntents = path.join(__dirname, '/intents');
const intentListing = fs.readdirSync(pathToIntents);
intentListing.forEach(intent => {
const currentIntent = require(path.join(pathToIntents, `/${intent}`));
console.info(`Registered intent ${currentIntent.label}`);
dialog.matches(currentIntent.label, currentIntent.callbackProvider(builder, bot));
});
// builder.DialogAction.send('We\'ve just launched the Building Information Model Fund from Building and Construction Authority (BCA).'));
//
dialog.onDefault([
function(session, args, next) {
console.log('|----------------------session-----------------------|');
console.log(session);
console.log('|---------------------/session-----------------------|');
console.log('|------------------------args------------------------|');
console.log(args);
console.log('|-----------------------/args------------------------|');
},
builder.DialogAction.send("It went through")
]);
dialog.matches('Upload', function (session, results) {
session.beginDialog('/uploadImage');
});
var visionClient = new oxford.Client(config.visionApiCredentials.key);
bot.dialog('/uploadImage', [
(session) => {
builder.Prompts.attachment(session, "Upload the document and I will keep track of the claim.");
},
(session, results) => {
results.response.forEach(function (attachment) {
visionClient.vision.ocr({
url: attachment.contentUrl,
language: 'en'
}).then(function (response) {
if ((typeof response.regions !== 'undefined') && (response.regions.length > 0) && (typeof response.regions[0].lines !== 'undefined')) {
var ocrText = '';
response.regions.forEach(data => {
data.lines.forEach(line => {
line.words.forEach(word => {
ocrText += word.text +" ";
});
});
});
var currencyAmount = ocrText.match(/(((SGD|USD|TOTAL|Total|total|^)(:|\s)*)|(\$\s*))(\d,?.?)+.?\d*/g);
var others = ocrText;
if (currencyAmount !== null) {
session.endDialog("I have added your invoice of " + currencyAmount+ " .");
} else {
session.send("I couldn't read your document, please send a clearer image.\n\nDebug info:\n\n`"+jsonPrettify(response.regions)+"`");
}
} else {
session.send("I couldn't read your document. Please send it in JPG or PNG format again.");
}
}, function(err) {
console.log(arguments);
session.endDialog("We're sorry, an unknown error has occured.");
});
});
}
]);
if(config.environment === 'production') {
server.post('/api/messages', connector.listen());
server.listen(process.env.port || process.env.PORT || 3978, function () {
console.log('%s listening to %s', server.name, server.url);
});
}
/**
* ENDOF CONTROLLER
*/
|
JavaScript
| 0 |
@@ -3822,24 +3822,16 @@
response
-.regions
)+%22%60%22);%0A
|
319e288fdd16ff1fb491269478f431c6c4c40dd5
|
create tables if they dont exist
|
app.js
|
app.js
|
var express = require('express');
var fs = require('fs');
var bodyParser = require('body-parser');
var lzString = require('lz-string');
var app = express();
var pg = require('pg');
var username = process.env.POSTGRES_ENV_POSTGRES_USER;
var password = process.env.POSTGRES_ENV_POSTGRES_PASSWORD;
var addr = process.env.POSTGRES_PORT_5432_TCP_ADDR;
var port = process.env.POSTGRES_PORT_5432_TCP_PORT;
var db = process.env.POSTGRES_ENV_POSTGRES_DB;
var conString = "postgres://" + username + ":" + password + "@" + addr + ":" + port + "/" + db;
var client = new pg.Client(conString);
client.connect();
var file_path = '/var/bikemoves/trips.json';
app.enable('trust proxy');
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept');
next();
});
app.use(bodyParser.json());
app.post('/v0.1/trip', function(req, res) {
var body = req.body;
if (body.tripData) {
var tripdata = JSON.parse(lzString.decompressFromBase64(body.tripData));
pg.connect(conString, function(err, client, done) {
if(err){
fs.appendFile(file_path, JSON.stringify(tripdata, null, 2));
done();
console.log(err);
return console.error('error connecting');
}
client.query('SELECT * FROM User WHERE device_uuid = ' + tripdata.deviceID, function(err, qry){
if(qry.rowCount===0){
client.query('INSERT INTO User(device_uuid, gender, age, cycling_experience) values($1, $2, $3, $4)', [tripdata.deviceID, '0', 0, 0], function(err, qry){
client.query('SELECT * FROM User WHERE device_uuid = ' + tripdata.deviceID, function(err, qry){
var userid = qry[0].id;
client.query('INSERT INTO Trip(user_id, origin_type, destination_type, start_datetime, end_datetime) values($1, $2, $3, $4, $5)', [userid, tripdata.from, tripdata.to, tripdata.startTime, tripdata.endTime], function(err, qry){
client.query('SELECT * FROM Trip WHERE user_id = ' + userid + ' AND start_datetime = ' + tripdata.startTime, function(err, qry){
var tripid = qry[0].id;
for(var i = 0; i < tripdata.points.length; i++){
client.query('INSERT INTO Point(trip_id, lat, lat) values($1, $2, $3)', [tripid, tripdata.points[i].lat, tripdata.points[i].lng], function(err, qry){});
}
});
});
});
});
}
else{
var userid = qry[0].id;
client.query('INSERT INTO Trip(user_id, origin_type, destination_type, start_datetime, end_datetime) values($1, $2, $3, $4, $5)', [userid, tripdata.from, tripdata.to, tripdata.startTime, tripdata.endTime], function(err, qry){
client.query('SELECT * FROM Trip WHERE user_id = ' + userid + ' AND start_datetime = ' + tripdata.startTime, function(err, qry){
var tripid = qry[0].id;
for(var i = 0; i < tripdata.points.length; i++){
client.query('INSERT INTO Point(trip_id, lat, long, datetime, gps_accuracy) values($1, $2, $3, $4, $5)', [tripid, tripdata.points[i].lat, tripdata.points[i].lng, tripdata.timestamps[i], tripdata.accuracys[i]], function(err, qry){});
}
});
});
}
});
});
}
});
app.post('/v0.1/user', function(req, res) {
var body = req.body;
if (body.userData) {
var userdata = JSON.parse(lzString.decompressFromBase64(body.userData));
pg.connect(conString, function(err, client, done) {
if(err){
done();
console.log(err);
return console.error('error connecting');
}
client.query('SELECT * FROM User WHERE device_uuid = ' + userdata.deviceID, function(err, qry){
if(qry.rowCount===0){
client.query('INSERT INTO User(device_uuid, gender, age, cycling_experience) values($1, $2, $3, $4)', [userdata.deviceID, userdata.gender, userdata.age, userdata.cycling_experience], function(err, qry){});
}
else{
var userid = qry[0].id;
client.query('UPDATE User SET gender=($1), age=($2), cycling_experience=($3) WHERE id=($4)', [userdata.gender, userdata.age, userdata.cycling_experience, userid], function(err, qry){});
}
});
});
}
});
app.get('/v0.1/trip', function(req, res){
res.sendFile(file_path, {
headers: {
'Content-Type': 'application/json'
}
});
});
app.listen(8888);
|
JavaScript
| 0 |
@@ -541,66 +541,8 @@
db;%0A
-var client = new pg.Client(conString);%0Aclient.connect();%0A%0A
%0Avar
@@ -797,16 +797,16 @@
cept');%0A
-
next()
@@ -808,24 +808,817 @@
ext();%0A%7D);%0A%0A
+pg.connect(conString, function(err, client, done) %7B%0A if(err)%7B%0A done();%0A console.log(err);%0A return console.error('error connecting');%0A %7D%0A%0A client.query('CREATE TABLE IF NOT EXISTS User(id integer primary key autoincrement, device_uuid varchar(255), gender character, age integer, cycling_experience integer)', function(err, qry)%7B%7D);%0A client.query('CREATE TABLE IF NOT EXISTS Trip(id integer primary key autoincrement, user_id integer, origin_type varchar(255), destination_type varchar(255), start_datetime timestamp, end_datetime timestamp)', function(err, qry)%7B%7D);%0A client.query('CREATE TABLE IF NOT EXISTS Point(id integer primary key autoincrement, trip_id integer, datetime timestamp, lat float, long float, gps_accuracy float)', function(err, qry)%7B%7D);%0A%0A%7D);%0A%0A
app.use(body
|
76aff5dedc769a8e3b2e30ec5228952b1bd6b414
|
Reset default compileCommand to pdflatex.
|
app.js
|
app.js
|
var
rimraf = require("rimraf"),
path = require("path"),
spawn = require("child_process").spawn,
fs = require("fs");
module.exports.parse = function(texString, callback){
var outputDirectory = path.join(__dirname, "temp-" + generateGuid());
var texFilePath = path.join(outputDirectory, "output.tex");
fs.mkdir(outputDirectory, function(err){
if(err) return callback(err);
fs.writeFile(texFilePath, texString, function(err){
if(err) return callback(err);
if(preParseHook){
preParseHook({
outputDirectory: outputDirectory,
texFilePath: texFilePath,
texString: texString
}, function(err){
if(err){
rimraf(outputDirectory, function(err){
if(err) throw err;
return callback(postParseHookError);
});
}
spawnLatexProcess(0, outputDirectory, [], callback);
});
}
else
spawnLatexProcess(0, outputDirectory, [], callback);
});
});
};
function spawnLatexProcess(attempt, outputDirectory, outputLogs, callback){
var outputFilePath = path.join(outputDirectory, "output.pdf");
var pdflatex = spawn(compileCommand.command, ["output.tex"].concat(compileCommand.options), {
cwd: outputDirectory
});
var outputLog = "";
pdflatex.stdout.on("data", function(data){
outputLog += data.toString("utf8");
});
pdflatex.on("close", function(code){
if(code !== 0){
process.stderr.write(outputLog);
process.stderr.write("--------------------------------------------");
return callback(new Error("Latex Error! Check your latex string"));
}
outputLogs.push(outputLog);
if(shouldRerun(outputLog) && attempt < 10)
spawnLatexProcess(++attempt, outputDirectory, outputLogs, callback);
else{
fs.exists(outputFilePath, function(exists){
if(exists){
if(postParseHook){
postParseHook({
outputDirectory: outputDirectory,
outputFilePath: outputFilePath,
outputLog: outputLog
}, function(postParseHookError){
if(postParseHookError){
rimraf(outputDirectory, function(err){
if(err) throw err;
return callback(postParseHookError);
});
}
else
sendPdfStream();
});
}
else sendPdfStream();
function sendPdfStream(){
var readStream = fs.createReadStream(outputFilePath);
callback(null, readStream, outputLogs);
readStream.on("close", function(){
rimraf(outputDirectory, function(err){
if(err) throw err;
});
});
}
}
else{
process.stderr.write(outputLog);
process.stderr.write("--------------------------------------------");
return callback(new Error("Output file was not found - Attempts: " + attempt));
}
});
}
});
}
var postParseHook = null;
module.exports.setPostParseHook = function(fn){
postParseHook = fn;
};
var preParseHook = null;
module.exports.setPreParseHook = function(fn){
preParseHook = fn;
};
var compileCommand = {
command: "latexmk",
options: ["--pdf"]
};
//var compileCommand = {
// command: "pdflatex",
// options: ["-interaction=nonstopmode"]
//};
module.exports.setCompileCommand = function(command){
compileCommand = command;
};
var rerunIndicators = ["Rerun to get cross-references right", "Rerun to get outlines right"];
module.exports.getRerunIndicators = function(){
return rerunIndicators;
};
module.exports.addRerunIndicator = function(text){
rerunIndicators.push(text);
};
function shouldRerun(outputLog){
if(compileCommand.command === "latexmk") return false;
for(var i = 0; i < rerunIndicators.length; i++){
if(outputLog.indexOf(rerunIndicators[i]) !== -1)
return true;
}
return false;
}
function generateGuid(){
var S4 = function (){
return Math.floor(Math.random() * 0x10000).toString(16);
};
return S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4();
};
|
JavaScript
| 0 |
@@ -2961,38 +2961,31 @@
fn;%0A%7D;%0A%0Avar
-compileCommand
+LATEXMK
= %7B%0A%09comman
@@ -3026,35 +3026,106 @@
%7D;%0A%0A
-//
var
-compileCommand
+PDFLATEX = %7B%0A%09command: %22pdflatex%22,%0A%09options: %5B%22-interaction=nonstopmode%22%5D%0A%7D;%0A%0Avar XELATEX
= %7B%0A
-//
%09com
@@ -3131,27 +3131,26 @@
mmand: %22
-pdf
+xe
latex%22,%0A
//%09optio
@@ -3141,18 +3141,16 @@
latex%22,%0A
-//
%09options
@@ -3184,11 +3184,41 @@
e%22%5D%0A
-//%7D
+%7D;%0A%0Avar compileCommand = PDFLATEX
;%0A%0Am
@@ -3976,12 +3976,13 @@
) + S4();%0A%7D;
+%0A
|
c2bf7d2f11465ec9dbd542db88657f22d9972500
|
Send the items to the view
|
app.js
|
app.js
|
var bogart = require('bogart')
,path = require('path');
require('dotenv').load();
var viewEngine = bogart.viewEngine('mustache', path.join(bogart.maindir(), 'views'));
var root = require("path").join(__dirname, "public");
var router = bogart.router();
var mp = require('mongodb-promise');
router.get('/', function(req) {
console.log('GET / - Find the saved webhooks.');
var url = 'mongodb://';
if (process.env.DB_USER) {
url = url + process.env.DB_USER+':'+process.env.DB_PASS+'@';
}
url = url + process.env.DB_HOST+':'+process.env.DB_PORT+'/'+process.env.DB_NAME
// Read all documents
return mp.MongoClient.connect(url)
.then(function(db){
return db.collection('webhooks')
.then(function(col) {
return col.find({}).toArray()
.then(function(items) {
console.log('Found ' + items.length + ' items.');
return viewEngine.respond('index.html', items);
db.close().then(console.log('success'));
})
})
})
.fail(function(err) {console.log(err)});
});
router.post('/payload', function(req) {
console.log('POST /payload - Save the incoming webhook.');
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://';
if (process.env.DB_USER) {
url = url + process.env.DB_USER+':'+process.env.DB_PASS+'@';
}
url = url + process.env.DB_HOST+':'+process.env.DB_PORT+'/'+process.env.DB_NAME
MongoClient.connect(url, function(err, db) {
var collection = db.collection('webhooks');
collection.insert(req.body, function(err, result) {
if(err)
throw err;
console.log("entry saved");
});
});
return bogart.json({ webhook: 'thanks' });
});
var app = bogart.app();
app.use(bogart.batteries({ secret: 'xGljGo7f4g/a1QveU8VRxhZP5Hwi2YWelejBq5h4ynM'})); // A batteries included JSGI stack including streaming request body parsing, session, flash, and much more.
app.use(bogart.middleware.directory(root));
app.use(router); // Our router
console.log('Loading ... ');
app.start(4567);
console.log('done.\n');
|
JavaScript
| 0 |
@@ -964,17 +964,17 @@
respond(
-'
+%22
index.ht
@@ -979,16 +979,55 @@
html
-', items
+%22, %7B locals: %7B items: items, errors: errors %7D %7D
);%0A
|
799365c0dd0fae08bda70d2ff3ccbfbf22213c83
|
load dotenv
|
app.js
|
app.js
|
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var bodyParser = require('body-parser');
app.use(express.static(__dirname + '/tmp'));
app.use(bodyParser.urlencoded({
extended: true
}));
var request = require('superagent');
var twilio = require('twilio');
require('shelljs/global');
var client = new twilio.RestClient(process.env.TWILIO_AUTH_SID, process.env.TWILIO_AUTH_TOKEN);
var port = process.env.PORT || 3000;
server.listen(port);
console.log('Listening at port: ' + port);
app.post('/incoming', function(req, res) {
searchMusic(req.body.Body, function(url) {
startCall(url, req.body.From);
});
});
app.post('/xml/:id', function(req, res) {
res.set('Content-Type', 'text/xml');
res.send('<Response><Play>' + process.env.BASE_URL + '/' + req.params.id + '.mp3' + '</Play><Redirect/></Response>');
});
function startCall(url, recipient) {
if (exec('youtube-dl --extract-audio --prefer-ffmpeg --audio-format mp3 --audio-quality 0 -o "tmp/%(id)s.%(ext)s" ' + url).code === 0) {
var call = client.calls.create({
to: recipient,
from: process.env.PHONE_NUMBER,
url: process.env.BASE_URL + '/xml/' + url.substring(url.length - 11)
});
}
}
function searchMusic(query, cb) {
request
.get('http://partysyncwith.me:3005/search/'+ query +'/1')
.end(function(err, res) {
if(err) {
console.log(err);
} else {
if (typeof JSON.parse(res.text).data !== 'undefined') {
if (JSON.parse(res.text).data[0].duration < 600) {
var url = JSON.parse(res.text).data[0].video_url;
cb(url);
} else {
cb(null);
}
}
}
})
}
|
JavaScript
| 0.000001 |
@@ -1,12 +1,60 @@
+var dotenv = require('dotenv');%0Adotenv.load();%0A%0A
var express
|
2c55030127aefb72bf42d0ab66820c0fe29304bd
|
Define size to be digits only
|
app.js
|
app.js
|
var express = require('express');
var gm = require('gm');
var hashblot = require('hashblot');
var crypto = require('crypto');
// Raster types we support for retrieval.
var rasterTypes = ['png','jpg','jpeg','gif','bmp','tga'];
module.exports = function appctor(opts) {
var gmopts = opts.gm || {};
function magickPd(size, pd, type, cb) {
return gm(size, size, '#fff').options(gmopts)
.draw([
'scale', size/255, size/255,
'fill-rule nonzero',
'path "' + pd + '"', ].join(' '))
.toBuffer(type, cb);
}
function svgPd(size, pd) {
return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 255 255" '
+ 'width="' + size + '" height="'+ size + '">'
+ '<path d="'+ pd + '" /></svg>';
}
function hashpathImage(req, res, next) {
// 404 for extensions we don't support
var extension = req.params.extension.toLowerCase();
if (extension != 'svg' && ~rasterTypes.indexOf(extension))
return next();
var hashType = req.params.hash;
var hash;
var pathType = req.params.path;
var str = req.params.input;
var pd;
// If there's a hashblot function for the path type,
// define a path from the byte-array-ified buffer for the given hash,
// and 404 otherwise
if (hashblot.pd[pathType]) {
try {
hash = crypto.createHash(hashType);
} catch (err) {
// 404 when the hash type is not supported
return next();
}
pd = hashblot.pd[pathType](Array.apply([],
hash.update(str, 'utf8').digest()));
} else return next();
var size;
try {
size = parseInt(req.params.size, 10);
} catch(err) {
return res.status(400).send('Invalid image size');
}
if (size < 15) {
res.redirect('/' + encodeURIComponent(hashType)
+ '/' + encodeURIComponent(pathType)
+ '/15/' + encodeURIComponent(str)
+ '.' + encodeURIComponent(extension));
} if (size > 2048) {
res.redirect('/' + encodeURIComponent(hashType)
+ '/' + encodeURIComponent(pathType)
+ '/2048/' + encodeURIComponent(str)
+ '.' + encodeURIComponent(extension));
}
if (extension == 'svg') {
res.type('svg');
res.send(svgPd(size, pd));
} else { // image is a raster type we support
magickPd(size, pd, extension, function(err, buffer) {
if (err) return next(err);
res.type(extension);
res.send(buffer);
});
}
}
var app = express();
app.get('/:hash/:path/:size/:input(|[^/]+?).:extension', hashpathImage);
return app;
};
|
JavaScript
| 0.000044 |
@@ -1665,49 +1665,13 @@
urn
-res.status(400).send('Invalid image size'
+next(
);%0A
@@ -2471,16 +2471,22 @@
th/:size
+(%5C%5Cd+)
/:input(
@@ -2506,16 +2506,20 @@
ension',
+%0A
hashpat
|
ec220386c8960c0abdca1bb89adf3ffbea63435e
|
Convert + to space.
|
app.js
|
app.js
|
'use strict';
var child_process = require('child_process');
var Color = require('color');
var async = require('async');
var streamBuffers = require('stream-buffers');
var memjs = require('memjs');
var client = memjs.Client.create();
var generating = {}; // pub/sub exposing pub existence
var express = require('express');
var app = express();
// set up config
var config = {};
try {
config = require('./config.json');
} catch (err) {
// do nothing
}
config['rgb2gif'] = config['rgb2gif'] === undefined ? 'rgb2gif' : config['rgb2gif'];
config['gifsicle'] = config['gifsicle'] === undefined ? 'gifsicle' : config['gifsicle'];
var numCPUs = require('os').cpus().length;
var workerPool = [];
// server routes
app.get('/', function (req, res) {
res.redirect('/giftext.gif');
});
app.get('/:text.gif', function (req, res) {
gif(res, req.params.text);
});
app.get('/:text', function (req, res) {
res.redirect('/' + req.params.text + '.gif');
});
var server = app.listen(process.env.PORT || 8080);
function gif(res, text) {
client.get(text, function(err, val) {
if (val) {
res.setHeader('content-type', 'image/gif');
res.end(val);
} else if (generating[text]) {
generating[text].push(function(result) {
res.setHeader('content-type', 'image/gif');
res.end(result);
});
} else {
render(res, text, 400, 150);
}
});
}
function render(res, text, width, height) {
generating[text] = [];
var buffer = new streamBuffers.WritableStreamBuffer({
initialSize: 200 * 1024
});
// hue
var hue = Math.random() * 360;
// colors
var front = Color().hsv(hue, 100, 95);
var side = Color().hsv((hue + 30 * Math.random() + 165) % 360, 80, 80);
// stream the results as they are available
res.setHeader('content-type', 'image/gif');
res.setHeader('transfer-encoding', 'chunked');
var gifsicle = child_process.spawn(config.gifsicle,
['--multifile', '-d', 8, '--loopcount', '--colors', 256], {
stdio: ['pipe', 'pipe', process.stderr]});
gifsicle.stdout.pipe(res);
gifsicle.stdout.pipe(buffer);
gifsicle.stdout.on('end', function() {
var contents;
if (buffer && buffer.size() > 0) {
contents = buffer.getContents();
// cache the result
client.set(text, contents, null, 600);
}
// notify subscribers
if (generating[text] && generating[text].length > 0) {
for (var listener in generating[text]) {
generating[text][listener](contents);
}
}
// remove publisher
generating[text] = null;
});
var options = {
color: {
front: front.rgbNumber(),
side: side.rgbNumber(),
background: 0xffffff,
opaque: true
},
text: text,
axis: Math.random() > 0.5 ? 'y' : 'wave',
width: width,
height: height
};
var frames = [];
for (var frame = 0; frame <= 23; frame++) {
frames.push(frame);
}
async.mapLimit(frames, numCPUs, function(frame, callback) {
var worker = workerPool.shift();
var buffer = new streamBuffers.WritableStreamBuffer({
initialSize: 200 * 1024
});
if (!worker) {
worker = child_process.spawn(
'node',
['./worker.js', config['rgb2gif']],
{
stdio: ['ipc', 'pipe', process.stderr]
}
);
}
worker.stdout.pipe(buffer);
var listener = function(response) {
worker.removeListener('message', listener);
workerPool.push(worker);
callback(null, buffer.getContents());
}
worker.on('message', listener);
worker.send({
options: options,
frame: frame
});
}, function(err, results) {
for (var r = 0; r < results.length; r++) {
gifsicle.stdin.write(results[r]);
}
gifsicle.stdin.end();
});
}
|
JavaScript
| 0.999858 |
@@ -850,16 +850,34 @@
ams.text
+.replace('+', ' ')
);%0A%7D);%0A%0A
|
1b3136a6cf456b40fa7bc6102b1e8cb86531f0ac
|
Convert application for valid checkstyle
|
app.js
|
app.js
|
/*jslint node: true */
var fs = require('fs');
var express = require('express');
var session = require('express-session');
var path = require('path');
var csrf = require('csurf');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var config = require(path.join(__dirname, 'config'));
var app = express();
/* Initialize mailer */
var mailer = require(path.join(__dirname, 'lib/mailer'));
config.mail.templatesDir = path.join(__dirname, 'mails');
mailer.extend(app, config.mail);
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
/* Init session */
app.use(session({
secret: config.session.token,
resave: false,
saveUninitialized: false
}));
/* Init csrf security */
app.use(csrf());
app.use(function (err, req, res, next) {
'use strict';
if (err.code !== 'EBADCSRFTOKEN') {
next(err);
}
res.status(403).send('Session token expired');
});
app.use(express.static(path.join(__dirname, 'public')));
app.use(function (req, res, next) {
'use strict';
res.cookie('XSRF-TOKEN', req.csrfToken());
next();
});
/* Api router */
var routerApi = express.Router();
var user = require(path.join(__dirname, 'routes/user'));
routerApi.use('/user', user);
var show = require(path.join(__dirname, 'routes/show'));
routerApi.use('/show', show);
var genre = require(path.join(__dirname, 'routes/genre'));
routerApi.use('/genre', genre);
routerApi.use('*', function (req, res, next) {
'use strict';
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use('/api', routerApi);
app.use('*', function (req, res, next) {
'use static';
res.sendFile(__dirname + '/public/index.html');
});
// catch 404 and forward to error handler
app.use(function (req, res, next) {
'use strict';
var err = new Error('Not Found');
err.status = 404;
next(err);
});
module.exports = app;
|
JavaScript
| 0.997367 |
@@ -1,52 +1,4 @@
-/*jslint node: true */%0A%0Avar fs = require('fs');%0A
var
@@ -130,48 +130,8 @@
');%0A
-var favicon = require('serve-favicon');%0A
var
@@ -501,114 +501,8 @@
);%0A%0A
-// uncomment after placing your favicon in /public%0A//app.use(favicon(__dirname + '/public/favicon.ico'));%0A
app.
@@ -580,17 +580,16 @@
ncoded(%7B
-
extended
@@ -595,17 +595,16 @@
d: false
-
%7D));%0Aapp
@@ -902,18 +902,16 @@
r);%0A %7D%0A
-
%0A res.s
@@ -1634,38 +1634,32 @@
nction (req, res
-, next
) %7B%0A 'use stati
@@ -1677,16 +1677,26 @@
endFile(
+path.join(
__dirnam
@@ -1700,10 +1700,9 @@
name
- +
+,
'/p
@@ -1719,16 +1719,17 @@
x.html')
+)
;%0A%7D);%0A%0A/
@@ -1916,8 +1916,9 @@
s = app;
+%0A
|
a0b5ce932e3bba650f8f6aa168f3a5acc2cfaaea
|
add space search
|
app.js
|
app.js
|
var _ = require('lodash');
var async = require('async');
var MongoClient = require('mongodb').MongoClient;
var request = require('request');
var express = require('express');
var app = express();
var resultsCollection;
var alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
function getSuggestions(text, callback) {
request({
url: 'http://google.com/complete/search',
gzip: true,
qs: { client: 'chrome', q: text },
}, function (error, response, body) {
var results = [];
if (!error && response.statusCode == 200) {
var result = JSON.parse(body);
var suggestions = result[1];
var suggesttypes = result[4]['google:suggesttype'];
for(var i = 0; i < suggestions.length; i++) {
if(suggesttypes[i] == 'QUERY') {
results.push(suggestions[i]);
}
}
} else {
console.log('Error requesting Google suggestions: ' + error);
}
callback(null, results);
})
}
app.use('/', express.static('public'));
app.get('/queries', function (req, res) {
resultsCollection.find({}, {_id:0, query:1}).toArray(
function(err, docs) {
if(docs) {
docs = docs.map(function(doc) {
return doc.query;
});
res.json({
count: docs.length,
queries: docs
})
} else {
res.sendStatus(500);
}
});
})
app.get('/search', function (req, res) {
var query = req.query.q;
console.log('/search?q=' + query);
if(!query) {
res.sendStatus(500);
return;
}
query = query.trim().toLowerCase();
console.log('searching results for ' + query);
resultsCollection.findOne( { query: query }, { _id: 0, results: 1 },
function(err, doc) {
if(err) {
console.log('Database error: ' + err);
res.sendStatus(500);
return;
}
if (doc) {
console.log('Cached: ' + query);
res.json(doc.results);
} else {
console.log('Lookup: ' + query);
async.map(alphabet.map(function(letter) {
return query + ' ' + letter;
}), getSuggestions, function(err, results) {
var unique = _.uniq(_.flatten(results, true));
resultsCollection.insert({ query: query, results: unique });
res.json(unique);
});
}
});
});
MongoClient.connect(process.env.MONGOLAB_URI, function(err, db) {
if(err) { return console.dir(err); }
console.log('Connected to database.');
resultsCollection = db.collection('results');
var server = app.listen(process.env.PORT || 3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Listening at http://%s:%s', host, port);
});
});
|
JavaScript
| 0.000002 |
@@ -228,16 +228,17 @@
abet = '
+
abcdefgh
|
ac9a8e794ac47f0db5abccc9490352a39f57e74e
|
fix favicon
|
app.js
|
app.js
|
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var fs = require("fs");
var app = express();
routes.init(app);
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon(path.join(__dirname, "public/images/favicon.png")));
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get("/", routes.index);
app.get("/create-trail", routes.createTrail);
app.post("/create-trail", routes.postTrail);
app.get("/trail", routes.trail);
app.get("/api/trails/:id", routes.apiTrail);
//app.get("/users", user.list);
http.createServer(app).listen(app.get('port'), function(){
console.log("On-the-Cent server listening on port " + app.get('port'));
});
|
JavaScript
| 0.014927 |
@@ -460,23 +460,21 @@
/images/
-favicon
+penny
.png%22)))
|
ae526efcd72e7fea4368711219e1723db1c2af1f
|
remove debug stuff
|
app.js
|
app.js
|
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var settings = require("./config").settings;
var auth = require("./routes/auth");
var routes = require('./routes/index');
var downloads = require("./routes/download");
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('node-sass-middleware')({
src: path.join(__dirname, 'sass'),
dest: path.join(__dirname, 'public'),
indentedSyntax: true,
sourceMap: false,
debug: true
}));
// configure the routes
app.use(express.static(path.join(__dirname, 'public')));
app.use("/", auth.basicAuth(settings.auth));
app.use("/", downloads);
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.000017 |
@@ -923,26 +923,8 @@
Map:
- false,%0A debug:
tru
|
ededb33847fbd7fb393467ffbec1ec3c200ba782
|
Improve performance by enabling cache
|
app.js
|
app.js
|
var path = require('path');
var koa = require('koa');
var Router = require('koa-router');
var bodyParser = require('koa-bodyparser');
var views = require('koa-views');
var serve = require('koa-static');
var session = require('koa-session');
var passport = require('koa-passport');
var locale = require('koa-locale');
var co = require('co');
// Loading settings
var settings = require('./lib/config.js');
if (!settings) {
console.error('Failed to load settings');
process.exit(1);
}
// Libraries
var Utils = require('./lib/utils');
var Mailer = require('./lib/mailer');
var Database = require('./lib/database');
var Passport = require('./lib/passport');
var Member = require('./lib/member');
var Middleware = require('./lib/middleware');
var Localization = require('./lib/localization');
var app = koa();
// Static file path
app.use(serve(path.join(__dirname, 'public')));
// Enabling BODY
app.use(bodyParser());
// Setup default locale
locale(app, 'en');
// Initializing authenication
Passport.init(passport);
Passport.local(passport);
// Setup 3rd-party authorization
if (settings.general.authorization.github.enabled)
Passport.github(passport);
if (settings.general.authorization.facebook.enabled)
Passport.facebook(passport);
if (settings.general.authorization.google.enabled)
Passport.google(passport);
if (settings.general.authorization.linkedin.enabled)
Passport.linkedin(passport);
app.use(passport.initialize());
app.use(passport.session());
// Create render
app.use(views(__dirname + '/views', {
ext: 'jade',
map: {
html: 'jade'
}
}));
// Initializing session and setting it expires in one month
app.keys = settings.general.session.keys || [];
app.use(session(app, {
maxAge: 30 * 24 * 60 * 60 * 1000
}));
// Initializing locals to make template be able to get
app.use(function *(next) {
this.state.user = this.req.user || {};
yield next;
});
app.use(function *(next) {
// Getting permission if user signed in already
if (this.isAuthenticated()) {
// Getting permission informations for such user
var perms = yield Member.getPermissions(this.state.user.id);
if (perms) {
this.state.user.permissions = perms;
}
}
if (!this.state.user.permissions) {
this.state.user.permissions = {};
}
yield next;
});
// Routes
app.use(require('./routes/auth').middleware());
app.use(require('./routes/user').middleware());
app.use(require('./routes/admin/dashboard').middleware());
app.use(require('./routes/admin/users').middleware());
app.use(require('./routes/admin/user').middleware());
app.use(require('./routes/admin/permission').middleware());
app.use(require('./routes/admin/roles').middleware());
app.use(require('./routes/admin/role').middleware());
co(function *() {
// Initializing react app
var ReactApp = require('./build/server.js');
ReactApp.init({
externalUrl: Utils.getExternalUrl()
});
// Initializing APIs
yield Mailer.init();
yield Database.init();
// Initializing routes for front-end rendering
var router = new Router();
for (var index in ReactApp.routes) {
var route = ReactApp.routes[index];
// NotFound Page
if (!route.path) {
app.use(function *pageNotFound(next) {
// Be the last handler
yield next;
if (this.status != 404)
return;
if (this.json || this.body || !this.idempotent)
return;
// Rendering
var page = yield ReactApp.render('/404');
yield this.render('index', {
title: settings.general.service.name,
content: page.content,
state: page.state
});
// Do not trigger koa's 404 handling
this.message = null;
});
continue;
}
// Redirect
if (route.redirect) {
(function(route) {
router.get(route.path, function *() {
this.redirect(route.redirect);
});
})(route);
continue;
}
// Register path for pages
router.get(route.path, Middleware.allow(route.allow || null), function *() {
var id = '[' + Date.now() + '] ' + this.req.url;
console.time(id);
// Locale
var localization = {
currentLocale: this.getLocaleFromHeader()
};
localization.messages = yield Localization.getTranslations([ localization.currentLocale ]);
localization.currentMessage = localization.messages[localization.currentLocale] || {};
// Reset initial state with session for new page
var curState = {
User: this.state.user || {},
Localization: localization,
Service: {
name: Utils.getServiceName()
}
};
curState.User.logined = this.isAuthenticated();
// Rendering page with current state and cookie to client-side
var page = yield ReactApp.render(this.request.path, curState, {
cookie: this.req.headers.cookie
});
yield this.render('index', {
title: settings.general.service.name,
content: page.content,
state: JSON.stringify(page.state)
});
console.timeEnd(id);
});
}
app.use(router.middleware());
// Localization
var localization = new Router();
localization.get('/lang/:locale', function *() {
this.body = yield Localization.getRawTranslation(this.params.locale);
this.type = 'application/json';
});
app.use(localization.middleware());
// Start the server
app.listen(settings.general.server.port, function() {
console.log('server is running at port', settings.general.server.port);
});
});
|
JavaScript
| 0.000006 |
@@ -1531,16 +1531,30 @@
'jade',%0A
+%09cache: true,%0A
%09map: %7B%0A
|
befe00cdd9659c4424de004d53f281501e03d6a9
|
disable request logging
|
app.js
|
app.js
|
const conditional = require('koa-conditional-get');
const etag = require('koa-etag');
const cors = require('koa2-cors');
const helmet = require('koa-helmet');
const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const mongoose = require('mongoose');
const { requestLogger, logger } = require('./middleware/logger');
const { responseTime, errors } = require('./middleware');
const { v4 } = require('./routes');
const app = new Koa();
mongoose.connect(process.env.SPACEX_MONGO, {
useFindAndModify: false,
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
poolSize: 200,
});
mongoose.set('bufferCommands', false);
const db = mongoose.connection;
db.on('error', (err) => {
logger.error(err);
});
db.once('connected', () => {
logger.info('Mongo connected');
app.emit('ready');
});
db.on('reconnected', () => {
logger.info('Mongo re-connected');
});
db.on('disconnected', () => {
logger.info('Mongo disconnected');
});
// disable console.errors for pino
app.silent = true;
// Error handler
app.use(errors);
app.use(conditional());
app.use(etag());
app.use(bodyParser());
// HTTP header security
app.use(helmet());
// Enable CORS for all routes
app.use(cors({
origin: '*',
allowMethods: ['GET', 'POST', 'PATCH', 'DELETE'],
allowHeaders: ['Content-Type', 'Accept'],
exposeHeaders: ['spacex-api-cache', 'spacex-api-response-time'],
}));
// Set header with API response time
app.use(responseTime);
// Request logging
app.use(requestLogger);
// V4 routes
app.use(v4.routes());
module.exports = app;
|
JavaScript
| 0.000001 |
@@ -1484,16 +1484,19 @@
logging%0A
+//
app.use(
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.