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
|
---|---|---|---|---|---|---|---|
46c4a15eae7c1453f725e22472f5051666e3843d | Add inbox to i18n translations | simul/index.ios.js | simul/index.ios.js | import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
NavigatorIOS,
} from 'react-native';
import I18n from 'react-native-i18n'
I18n.fallbacks = true;
I18n.translations = {
en: {
login: 'Login',
enter: 'Enter',
register: 'Register',
home: 'Home',
search: 'Search',
username: 'Username',
password: 'Password',
name: 'Name',
location: 'Location',
bio: 'Bio',
skills: 'Skills/Expertise',
contactInformation: 'Contact Information',
resourceRequest: 'Resource Request',
seeking: 'Opportunities Seeking',
story: 'Story',
stories: 'Stories',
message: 'Message',
messages: 'Messages',
profile: 'Profile',
createAccount: 'Create a Simul Account',
from: 'From:',
date: 'Date:',
subject: 'Subject:',
content: 'Content:',
senderContact: "Sender's contact info:",
},
ar: {
login: 'دخول',
username: 'اسم المستخدم',
password: 'كلمه السر',
name: 'اسم',
enter: 'أدخل',
register: 'تسجيل',
home: 'منزل',
search: 'بحث',
bio: 'سيرة',
location: 'موقع',
contactInformation: 'معلومات الاتصال',
skills: 'مهارات',
seeking: 'فرص تسعى',
resourceRequest: 'الموارد أريد',
story: 'قصة',
stories: 'قصص',
message: 'الرسالة',
messages: 'رسائل',
profile: 'الملف الشخصي',
createAccount: 'إصنع حساب',
from: 'من',
date: 'كان',
subject: 'موضوع',
content: 'محتوى',
senderContact: '',
}
}
import Enter from './app/components/enter.js';
class simul extends Component {
render() {
return (
<NavigatorIOS
initialRoute={{
component: Enter,
title: 'Simul',
}}
style={{flex: 1}}
/>
);
}
}
AppRegistry.registerComponent('simul', () => simul);
| JavaScript | 0 | @@ -756,24 +756,44 @@
l Account',%0A
+ inbox: 'Inbox',%0A
from: 'F
@@ -1410,16 +1410,43 @@
%D8%AD%D8%B3%D8%A7%D8%A8',%0A
+ inbox: '%D8%B5%D9%86%D8%AF%D9%88%D9%82 %D8%A7%D9%84%D9%88%D8%A7%D8%B1%D8%AF',%0A
from
|
081220f071c413988a562eec34e08e828b8a23d4 | fix trailing newlines in Changelog | version.js | version.js | const readFileSync = require('fs').readFileSync;
const execSync = require('child_process').execSync;
const validateSemver = require('semver').valid;
const isSemverValid = version => validateSemver(version) !== null;
/* VERSION */
const pkg = JSON.parse(readFileSync('./package.json'));
const version = pkg.version;
if (!isSemverValid(version)) {
throw new Error(`Unexpected version: ${version}`);
}
/* AUTHORS */
execSync('git --no-pager log --reverse --format="%aN <%aE>" | sort -fub > AUTHORS'
+ ' && git add AUTHORS && git commit -m "update AUTHORS" AUTHORS || true', { stdio: 'inherit' });
/* CHANGELOG */
execSync(`echo "### v${version}\\n" > \\#temp_changelog`, { stdio: 'inherit' });
let repository = pkg.repository;
if (repository) {
repository = repository.replace(/^git@github.com:(.*)\.git$/, '$1');
}
// Initial commit: diff against an empty tree object
execSync('git log `git describe --abbrev=0 &> /dev/null && git rev-list --tags --max-count=1 || echo "4b825dc642cb6eb9a060e54bf8d69288fbee4904"`..HEAD --reverse'
+ ` --pretty=format:"- [\\\`%h\\\`](https://github.com/${repository}/commit/%H) %s (%an)"`
+ '>> \\#temp_changelog', { stdio: 'inherit' });
execSync('$EDITOR \\#temp_changelog', { stdio: 'inherit' });
execSync('echo "\\n" >> \\#temp_changelog', { stdio: 'inherit' });
execSync('cat CHANGELOG.md || echo >> \\#temp_changelog || true', { stdio: 'inherit' });
execSync('mv -f \\#temp_changelog CHANGELOG.md', { stdio: 'inherit' });
execSync('git add CHANGELOG.md');
| JavaScript | 0.000003 | @@ -1434,13 +1434,11 @@
nc('
-mv -f
+cat
%5C%5C#
@@ -1452,28 +1452,130 @@
angelog
-CHANGELOG.md
+%7C sed -e :a -e %5C'/%5E%5C%5Cn*$/%7B$d;N;%7D;/%5C%5Cn$/ba%5C' %3E CHANGELOG.md', %7B stdio: 'inherit' %7D);%0AexecSync('rm %5C%5C#temp_changelog
', %7B std
|
c2a965a540aeff22172ea94d5a0826e9cb11812c | Update version string to 2.5.1-pre.1 | version.js | version.js | if (enyo && enyo.version) {
enyo.version.onyx = "2.5.0";
}
| JavaScript | 0.000001 | @@ -51,9 +51,15 @@
2.5.
-0
+1-pre.1
%22;%0A%7D
|
32bdf71038e41e54aa6552666d5c6bd3413a9f88 | Add quest trigger op check. | client/js/helpers/questscriptmanager.js | client/js/helpers/questscriptmanager.js | 'use strict';
var knownServerOnlyQsds = [
'3DDATA/QUESTDATA/SERVER/SOLDIER.QSD',
'3DDATA/QUESTDATA/SERVER/MUSE.QSD',
'3DDATA/QUESTDATA/SERVER/COMBAT.QSD',
'3DDATA/QUESTDATA/SERVER/HAWKER.QSD',
'3DDATA/QUESTDATA/SERVER/DEALER.QSD',
'3DDATA/QUESTDATA/NPC/QN-350.QSD',
'3DDATA/QUESTDATA/NPC/QN-070.QSD',
'3DDATA/QUESTDATA/NPC/QN-380.QSD',
'3DDATA/QUESTDATA/NPC/QN-2247.QSD',
'3DDATA/QUESTDATA/NPC/QN-2254.QSD'
];
function QuestScriptManager() {
this.triggers = {};
}
QuestScriptManager.prototype._registerTrigger = function(trigger) {
if (this.triggers[trigger.name]) {
console.error('Encountered trigger twice:', trigger.name);
return;
}
this.triggers[trigger.name] = trigger;
};
function _checkCond(ins) {
switch (ins.type) {
case 0:
console.log('set quest', ins.questNo);
break;
case 3:
console.group('check abilitys');
for (var i = 0; i < ins.abils.length; ++i) {
console.log(ins.abils[i]);
}
console.groupEnd();
break;
case 4:
console.group('check items');
for (var i = 0; i < ins.items.length; ++i) {
console.log(ins.items[i]);
}
console.groupEnd();
break;
case 9:
console.log('skill check', ins.skillNo1, ins.skillNo2, ins.op);
break;
case 13:
console.log('set npc', ins.npcNo);
break;
case 31:
console.log('quest log activity', ins.questNo, ins.op);
break;
default:
console.warn('Encountered unhandled condition type:', ins.type);
break;
}
return true;
}
function _checkTrigger(trigger) {
console.log('checkTrigger', trigger.name);
for (var i = 0; i < trigger.conditions.length; ++i) {
if (!_checkCond(trigger.conditions[i])) {
return false;
}
}
return true;
}
QuestScriptManager.prototype.checkOnly = function(triggerName) {
while (true) {
var trigger = this.triggers[triggerName];
if (!_checkTrigger(trigger)) {
return false;
}
if (trigger.checkNext) {
triggerName = trigger.nextTriggerName;
} else {
break;
}
}
return true;
}
/**
* Load helper so the QuestScriptManager can be controlled by the GDM.
*
* @param path Path to STB listing the quest scripts
* @param callback
*/
QuestScriptManager.load = function(path, callback) {
var data = new QuestScriptManager();
var waitAll = new MultiWait();
var dataTableWait = waitAll.one();
DataTable.load(path, function(qdata) {
for (var i = 0; i < qdata.rows.length; ++i) {
(function(entryIdx, dataRow) {
var filePath = normalizePath(dataRow[0]).toUpperCase();
if (knownServerOnlyQsds.indexOf(filePath) !== -1) {
// Skip It!
return;
}
if (dataRow[0] && !dataRow[1]) {
var questListWait = waitAll.one();
QuestScriptList.load(dataRow[0], function (qsdData) {
for (var j = 0; j < qsdData.scripts.length; ++j) {
var qsdScript = qsdData.scripts[j];
for (var k = 0; k < qsdScript.triggers.length; ++k) {
var trigger = qsdScript.triggers[k];
data._registerTrigger(trigger);
}
}
questListWait();
});
}
})(i, qdata.rows[i]);
}
dataTableWait();
});
waitAll.wait(function() {
callback(data);
});
};
| JavaScript | 0 | @@ -711,16 +711,357 @@
er;%0A%7D;%0A%0A
+function _checkOp(op, left, right) %7B%0A switch (op) %7B%0A case 0: return left === right;%0A case 1: return left %3E right;%0A case 2: return left %3E= right;%0A case 3: return left %3C right;%0A case 4: return left %3C= right;%0A case 10: return left !== right;%0A %7D%0A%0A console.warn('Encountered unknown trigger opcode:', op);%0A return false;%0A%7D%0A%0A
function
|
0e005ab562621cf95f7962366291b3197b655558 | remove params from Api get | client/src/services/HistoriesService.js | client/src/services/HistoriesService.js | import Api from '@/services/Api'
export default {
index (params) {
return Api().get('histories', {
params: params
})
},
post (history) {
return Api().post('histories', history)
}
}
| JavaScript | 0 | @@ -99,38 +99,8 @@
ies'
-, %7B%0A params: params%0A %7D
)%0A
|
58a9c7bdc2cb2959d43300a5d963650e362fc89b | Update hostList.js | client/views/hosts/hostList/hostList.js | client/views/hosts/hostList/hostList.js | Template.HostList.events({
});
Template.HostList.helpers({
// Get list of Hosts sorted by the sort field.
hosts: function () {
return Hosts.find({}, {sort: {sort: 1}});
}
});
Template.HostList.rendered = function () {
// Make rows sortable/draggable using Jquery-UI.
this.$('#sortable').sortable({
stop: function (event, ui) {
// Define target row items.
target = ui.item.get(0);
before = ui.item.prev().get(0);
after = ui.item.next().get(0);
// Change the sort value dependnig on target location.
// If target is now first, subtract 1 from sort value.
if (!before) {
newSort = Blaze.getData(after).sort - 1;
// If target is now last, add 1 to sort value.
} else if (!after) {
newSort = Blaze.getData(before).sort + 1;
// Get value of prev and next elements
// to determine new target sort value.
} else {
newSort = (Blaze.getData(after).sort +
Blaze.getData(before).sort) / 2;
}
// Update the database with new sort value.
Hosts.update({_id: Blaze.getData(target)._id}, {
$set: {
sort: newSort
}
});
}
});
};
// Returns a list of host types.
Template.registerHelper('hostTypes', function () {
var _default = '-- Select one --';
var a = this.type || _default;
return [_default,"Drupal", "Wordpress"].map(
function(s){
var selected = (s == a) ? 'selected="1"' : '';
var disable = (s == _default) ? ' disabled="1"' : '';
return '<option value="' + s + '" ' + selected + disable + '>' + s + '</option>';
}).join('\n');
}); | JavaScript | 0.000001 | @@ -1202,430 +1202,4 @@
%7D;%0A%0A
-// Returns a list of host types.%0ATemplate.registerHelper('hostTypes', function () %7B%0A %09var _default = '-- Select one --';%0A%09var a = this.type %7C%7C _default;%0A%09return %5B_default,%22Drupal%22, %22Wordpress%22%5D.map(%0A%09%09function(s)%7B%0A%09%09%09var selected = (s == a) ? 'selected=%221%22' : '';%0A%09%09%09var disable = (s == _default) ? ' disabled=%221%22' : '';%0A%09%09%09return '%3Coption value=%22' + s + '%22 ' + selected + disable + '%3E' + s + '%3C/option%3E';%0A%09%7D).join('%5Cn');%0A%7D);
|
6b9e7a40224281247213aaf3c9cfe47bbd1d7ed6 | Rename contrib_total_commits to calculate_total_commits. | static/js/portico/team.js | static/js/portico/team.js | const contributors_list = page_params.contributors;
const repo_name_to_tab_name = {
zulip: "server",
"zulip-desktop": "desktop",
"zulip-mobile": "mobile",
"python-zulip-api": "python-zulip-api",
"zulip-js": "zulip-js",
zulipbot: "zulipbot",
"zulip-terminal": "terminal",
"zulip-ios-legacy": "",
"zulip-android": "",
};
// Remember the loaded repositories so that HTML is not redundantly edited
// if a user leaves and then revisits the same tab.
const loaded_repos = [];
function contrib_total_commits(contributor) {
let commits = 0;
Object.keys(repo_name_to_tab_name).forEach((repo_name) => {
commits += contributor[repo_name] || 0;
});
return commits;
}
// TODO (for v2 of /team contributors):
// - Make tab header responsive.
// - Display full name instead of github username.
export default function render_tabs() {
const template = _.template($("#contributors-template").html());
// The GitHub API limits the number of contributors per repo to somwhere in the 300s.
// Since zulip/zulip repo has the highest number of contributors by far, we only show
// contributors who have atleast the same number of contributions than the last contributor
// returned by the API for zulip/zulip repo.
const least_server_commits = _.chain(contributors_list)
.filter("zulip")
.sortBy("zulip")
.value()[0].zulip;
const total_tab_html = _.chain(contributors_list)
.map((c) => ({
name: c.name,
avatar: c.avatar,
commits: contrib_total_commits(c),
}))
.sortBy("commits")
.reverse()
.filter((c) => c.commits >= least_server_commits)
.map((c) => template(c))
.value()
.join("");
$("#tab-total").html(total_tab_html);
for (const repo_name of Object.keys(repo_name_to_tab_name)) {
const tab_name = repo_name_to_tab_name[repo_name];
if (!tab_name) {
continue;
}
// Set as the loading template for now, and load when clicked.
$("#tab-" + tab_name).html($("#loading-template").html());
$("#" + tab_name).on("click", () => {
if (!loaded_repos.includes(repo_name)) {
const html = _.chain(contributors_list)
.filter(repo_name)
.sortBy(repo_name)
.reverse()
.map((c) =>
template({
name: c.name,
avatar: c.avatar,
commits: c[repo_name],
}),
)
.value()
.join("");
$("#tab-" + tab_name).html(html);
loaded_repos.push(repo_name);
}
});
}
}
| JavaScript | 0 | @@ -513,22 +513,24 @@
nction c
-ontrib
+alculate
_total_c
@@ -1570,22 +1570,24 @@
mmits: c
-ontrib
+alculate
_total_c
|
5b27ced6036bf0801628c0147b86deae5f19216d | remove console.log command | static/js/super-search.js | static/js/super-search.js | /* Super Search
Author: Kushagra Gour (http://kushagragour.in)
MIT Licensed
*/
(function () {
var isSearchOpen = false,
searchEl = document.querySelector('#js-search'),
searchInputEl = document.querySelector('#js-search__input'),
searchResultsEl = document.querySelector('#js-search__results'),
currentInputValue = '',
lastSearchResultHash,
posts = [];
// Changes XML to JSON
// Modified version from here: http://davidwalsh.name/convert-xml-json
function xmlToJson(xml) {
// Create the return object
var obj = {};
if (xml.nodeType == 1) { // element
// do attributes
if (xml.attributes.length > 0) {
obj["@attributes"] = {};
for (var j = 0; j < xml.attributes.length; j++) {
var attribute = xml.attributes.item(j);
obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
}
}
} else if (xml.nodeType == 3) { // text
obj = xml.nodeValue;
}
// do children
// If all text nodes inside, get concatenated text from them.
var textNodes = [].slice.call(xml.childNodes).filter(function (node) { return node.nodeType === 3; });
if (xml.hasChildNodes() && xml.childNodes.length === textNodes.length) {
obj = [].slice.call(xml.childNodes).reduce(function (text, node) { return text + node.nodeValue; }, '');
}
else if (xml.hasChildNodes()) {
for(var i = 0; i < xml.childNodes.length; i++) {
var item = xml.childNodes.item(i);
var nodeName = item.nodeName;
if (typeof(obj[nodeName]) == "undefined") {
obj[nodeName] = xmlToJson(item);
} else {
if (typeof(obj[nodeName].push) == "undefined") {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(xmlToJson(item));
}
}
}
return obj;
}
function getPostsFromXml(xml) {
var json = xmlToJson(xml);
return json.channel.item;
}
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","/sitemap.xml");
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState != 4) return;
if (xmlhttp.status != 200 && xmlhttp.status != 304) { return; }
var node = (new DOMParser).parseFromString(xmlhttp.responseText, 'text/xml');
node = node.children[0];
posts = getPostsFromXml(node);
}
xmlhttp.send();
window.toggleSearch = function toggleSearch() {
_gaq.push(['_trackEvent', 'supersearch', searchEl.classList.contains('is-active')]);
searchEl.classList.toggle('is-active');
if (searchEl.classList.contains('is-active')) {
// while opening
searchInputEl.value = '';
} else {
// while closing
searchResultsEl.classList.add('is-hidden');
}
setTimeout(function () {
searchInputEl.focus();
}, 210);
}
window.addEventListener('keyup', function onKeyPress(e) {
if (e.which === 27) {
toggleSearch();
}
});
window.addEventListener('keypress', function onKeyPress(e) {
if (e.which === 47 && !searchEl.classList.contains('is-active')) {
toggleSearch();
}
});
searchInputEl.addEventListener('input', function onInputChange() {
var currentResultHash, d;
currentInputValue = (searchInputEl.value + '').toLowerCase();
if (!currentInputValue || currentInputValue.length < 3) {
lastSearchResultHash = '';
searchResultsEl.classList.add('is-hidden');
return;
}
searchResultsEl.style.offsetWidth;
console.log(posts)
var matchingPosts = posts.filter(function (post) {
if ((post.title + '').toLowerCase().indexOf(currentInputValue) !== -1 || (post.description + '').toLowerCase().indexOf(currentInputValue) !== -1) {
return true;
}
});
if (!matchingPosts.length) {
searchResultsEl.classList.add('is-hidden');
}
currentResultHash = matchingPosts.reduce(function(hash, post) { return post.title + hash; }, '');
if (matchingPosts.length && currentResultHash !== lastSearchResultHash) {
searchResultsEl.classList.remove('is-hidden');
searchResultsEl.innerHTML = matchingPosts.map(function (post) {
d = new Date(post.pubDate);
return '<li><a href="' + post.link + '">' + post.title + '<span class="search__result-date">' + d.toUTCString().replace(/.*(\d{2})\s+(\w{3})\s+(\d{4}).*/,'$2 $1, $3') + '</span></a></li>';
}).join('');
}
lastSearchResultHash = currentResultHash;
});
})(); | JavaScript | 0.000019 | @@ -3992,35 +3992,8 @@
dth;
-%0A console.log(posts)
%0A%0A
|
dc6b8d7aa7a040ebb8cc2ead6ccb93fbd96fb5e0 | Update wallaby conf | wallaby.js | wallaby.js | var wallabify = require('wallabify');
var wallabyPostprocessor = wallabify({
// browserify options, such as
// insertGlobals: false
}
// you may also pass an initializer function to chain other
// browserify options, such as transformers
// , b => b.exclude('mkdirp').transform(require('babelify'))
);
module.exports = () => {
return {
files: [
{pattern: 'src/fluxlet.js', load: false}
// 'src/utils.js',
// 'src/testlet-utils.js',
// 'src/testlet.js'
],
tests: [
{pattern: 'test/fluxlet.js', load: false}
],
preprocessors: {
'**/*.js': file => require('babel')
.transform(file.content, {sourceMap: true}),
},
postprocessor: wallabyPostprocessor,
bootstrap: function () {
// required to trigger tests loading
window.__moduleBundler.loadTests();
},
env: {
type: 'browser'
},
debug: true
};
};
| JavaScript | 0 | @@ -73,247 +73,9 @@
fy(%7B
-%0A // browserify options, such as%0A // insertGlobals: false%0A %7D%0A // you may also pass an initializer function to chain other%0A // browserify options, such as transformers%0A // , b =%3E b.exclude('mkdirp').transform(require('babelify'))%0A
+%7D
);%0A%0A
|
98c11d9666c0496aa4d12ad311c111de39093e75 | add time | weather.js | weather.js | var Tinkerforge = require('tinkerforge');
var LIGHT;
var BARO;
var HUMI;
var al;
var h;
var b;
var ipcon;
var Humidity;
var AirPressure;
var Temperature;
var Illuminance;
/* istanbul ignore next */
function ipcon_connect(HOST, PORT) {
ipcon.connect(HOST, PORT,
function(error) {
switch (error) {
case 11:
console.log('Error: ALREADY CONNECTED');
break;
case 12:
console.log('Error: NOT CONNECTED');
break;
case 13:
console.log('Error: CONNECT FAILED');
break;
case 21:
console.log('Error: INVALID FUNCTION ID');
break;
case 31:
console.log('Error: TIMEOUT');
break;
case 41:
console.log('Error: INVALID PARAMETER');
break;
case 42:
console.log('Error: FUNCTION NOT SUPPORTED');
break;
default:
console.log('Error: UNKNOWN ERROR');
break;
}
process.exit();
}
);
}
/* istanbul ignore next */
function get_uid(HOST, PORT) {
ipcon = new Tinkerforge.IPConnection();
ipcon_connect(HOST, PORT);
ipcon.on(Tinkerforge.IPConnection.CALLBACK_CONNECTED,
function(connectReason) {
ipcon.enumerate();
}
);
ipcon.on(Tinkerforge.IPConnection.CALLBACK_ENUMERATE,
function(uid, connectedUid, position, hardwareVersion, firmwareVersion, deviceIdentifier) {
if (deviceIdentifier === Tinkerforge.BrickletAmbientLight.DEVICE_IDENTIFIER) {
LIGHT = uid;
} else if (deviceIdentifier === Tinkerforge.BrickletBarometer.DEVICE_IDENTIFIER) {
BARO = uid;
} else if (deviceIdentifier === Tinkerforge.BrickletHumidity.DEVICE_IDENTIFIER) {
HUMI = uid;
}
}
);
setTimeout(function() {
ipcon.disconnect();
}, 250);
}
/* istanbul ignore next */
function tfinit(HOST, PORT) {
ipcon = new Tinkerforge.IPConnection();
al = new Tinkerforge.BrickletAmbientLight(LIGHT, ipcon);
b = new Tinkerforge.BrickletBarometer(BARO, ipcon);
h = new Tinkerforge.BrickletHumidity(HUMI, ipcon);
ipcon_connect(HOST, PORT);
}
/* istanbul ignore next */
function tfdata_get() {
h.getHumidity(
function(humidity) {
Humidity = humidity / 10 + ' %RH';
},
function(error) {
Humidity = 'Error ' + error;
}
);
b.getAirPressure(
function(air_pressure) {
AirPressure = air_pressure / 1000 + ' mbar';
},
function(error) {
AirPressure = 'Error ' + error;
}
);
b.getChipTemperature(
function(temperature) {
Temperature = temperature / 100 + ' \u00B0C';
},
function(error) {
Temperature = 'Error ' + error;
}
);
al.getIlluminance(
function(illuminance) {
Illuminance = illuminance / 10 + ' Lux';
},
function(error) {
Illuminance = 'Error ' + error;
}
);
}
/* istanbul ignore next */
exports.get = function tfget(HOST, PORT, WAIT, live) {
get_uid(HOST, PORT);
setTimeout(function() {
tfinit(HOST, PORT);
if (live === true) {
process.stdin.on('data',
function(data) {
ipcon.disconnect();
process.exit();
}
);
tfdata_get();
setInterval(function() {
console.log('\033[2J');
console.log('Relative Humidity: ' + Humidity);
console.log('Air pressure: ' + AirPressure);
console.log('Temperature: ' + Temperature);
console.log('Illuminance: ' + Illuminance);
tfdata_get();
}, WAIT);
} else {
ipcon.on(Tinkerforge.IPConnection.CALLBACK_CONNECTED,
function(connectReason) {
tfdata_get();
}
);
setTimeout(function() {
console.log('');
console.log('Relative Humidity: ' + Humidity);
console.log('Air pressure: ' + AirPressure);
console.log('Temperature: ' + Temperature);
console.log('Illuminance: ' + Illuminance);
console.log('');
ipcon.disconnect();
process.exit(0);
}, 50);
}
}, 300);
};
| JavaScript | 0.00065 | @@ -2887,16 +2887,287 @@
next */%0A
+function getTime() %7B%0A var date = new Date();%0A return ((date.getHours() %3C 10 ? %220%22 : %22%22) + date.getHours()) + %22:%22 + ((date.getMinutes() %3C 10 ? %220%22 : %22%22) + date.getMinutes()) + %22:%22 + ((date.getSeconds() %3C 10 ? %220%22 : %22%22) + date.getSeconds());%0A%7D%0A/* istanbul ignore next */%0A
exports.
@@ -3746,32 +3746,90 @@
+ Illuminance);%0A
+ console.log('%5CnTime: ' + getTime());%0A
tfdata_g
@@ -4218,32 +4218,32 @@
+ Temperature);%0A
-
console.
@@ -4276,32 +4276,90 @@
+ Illuminance);%0A
+ console.log('%5CnTime: ' + getTime());%0A
console.
|
2938bdc4f281829163e1c8f804921cfa66cb96ad | Use mventory spreadsheet | lambda/app.js | lambda/app.js | var https = require("https");
var GoogleSpreadsheet = require("google-spreadsheet");
var config = {
credentialPath: "./creds.json",
siteUrl: "https://api.trademe.co.nz/v1/SiteStats.json",
sheetId: "1PvLp6O5NLeXZW00l79PXL0Zqcy3ysAocmBmX7tKTPPU",
sheetTitle: "Main"
};
exports.handler = function (event, context) {
var req = https.get(config.siteUrl, function (res) {
if (res.statusCode == 200) {
var body = '';
res.on('data', function (chunk) {
body += chunk;
});
res.on('end', function () {
console.log("Site Stats: " + body);
var stats = JSON.parse(body);
console.log("Connecting to Spreadsheet ID: " + config.sheetId);
var spreadsheet = new GoogleSpreadsheet(config.sheetId);
var creds = require(config.credentialPath);
spreadsheet.useServiceAccountAuth(creds, function (error) {
if (error) context.fail(error);
spreadsheet.getInfo(function (error, sheetInfo) {
if (error) context.fail(error);
//Use the worksheet with the same title as config.sheetTitle, when no match is found use the first worksheet
var worksheetIndex = 0;
sheetInfo.worksheets.some(function (value, index) {
if (value.title == config.sheetTitle) {
worksheetIndex = index;
return true;
}
});
var worksheet = sheetInfo.worksheets[worksheetIndex];
//Format updatedOn datetime
var dt = new Date();
var updatedOn = dt.getUTCFullYear() + "-" + (dt.getUTCMonth() + 1) + "-" + dt.getUTCDate() + " " + dt.getUTCHours() + ":" + dt.getUTCMinutes() + ":" + dt.getUTCSeconds();
worksheet.addRow({
"Active Members": stats.ActiveMembers,
"Active Listings": stats.ActiveListings,
"Members Online": stats.MembersOnline,
"Updated On": updatedOn
}, function (error) {
if (error) context.fail(error);
context.succeed();
});
});
});
});
}
else context.fail(config.siteUrl + " - " + res.statusCode);
});
req.on("error", context.fail);
req.end();
} | JavaScript | 0.000001 | @@ -200,51 +200,51 @@
: %221
-PvLp6O5NLeXZW00l79PXL0Zqcy3ysAocmBmX7tKTPPU
+RMcibAPjuPim7N_MUFdVeYqiN_ngroNrQzsHy6VDwB4
%22,%0A%09
|
60e23be34539bbd5a7da6c3aa68220a0f5166799 | level name to uppercase | lib/Logger.js | lib/Logger.js |
function Logger(manager, parent, name, level) {
level = level || Logger.NOTSET;
if (Logger.getLevelName(level) === '') {
throw new Error('[Invalid argument] Unknown level: \'' + level + '\'.');
}
/**
* Instance of manager, which holds the hierarchy of loggers.
* @type {Object}
*/
this._manager = manager;
/**
* Parent logger.
* @type {Object}
*/
this._parent = parent;
/**
* Name of this logger.
* @type {string}
*/
this._name = name;
/**
* The threshold for this logger.
* @type {number}
*/
this._level = level;
/**
* Array of set handlers.
* @type {Array}
*/
this._handlers = [];
/**
* @type {boolean}
*/
this._disabled = false;
/**
* @type {boolean}
*/
this._propagate = true;
}
Logger.NOTSET = 0;
Logger.DEBUG = 10;
Logger.INFO = 20;
Logger.WARNING = 30;
Logger.ERROR = 40;
Logger.CRITICAL = 50;
Logger.getLevelName = function(level) {
var levelName = '';
if (level === Logger.DEBUG) {
levelName = 'debug';
} else if (level === Logger.INFO) {
levelName = 'info';
} else if (level === Logger.WARNING) {
levelName = 'warning';
} else if (level === Logger.ERROR) {
levelName = 'error';
} else if (level === Logger.CRITICAL) {
levelName = 'critical';
} else if (level === Logger.NOTSET) {
levelName = 'notset';
}
return levelName;
};
Logger.prototype.getName = function() {
return this._name;
};
Logger.prototype.getEffectiveLevel = function() {
var logger = this;
while (logger) {
if (logger._level) {
return logger._level;
}
logger = logger._parent;
}
return Logger.NOTSET;
};
Logger.prototype.getChild = function(suffix) {
if (!suffix) {
throw new Error('[Invalid argument] Argument suffix must be specified.');
}
var base = this._name === 'root' ? '' : this._name + '.';
return this._manager.getLogger(base + suffix);
};
Logger.prototype.setLevel = function(level) {
if (Logger.getLevelName(level) === '') {
throw new Error('[Invalid argument] Unknown level: \'' + level + '\'.');
}
this._level = level;
};
Logger.prototype.addHandler = function(handler) {
if (typeof handler !== 'object') {
throw new Error('[Invalid argument] Argument handler must be an object.');
}
this._handlers.push(handler);
};
Logger.prototype.removeHandler = function(handler) {
var index = this._handlers.indexOf(handler);
if (index > -1) {
this._handlers.splice(index, 1);
}
};
Logger.prototype.debug = function(msg) {
this._log(Logger.DEBUG, msg);
};
Logger.prototype.info = function(msg) {
this._log(Logger.INFO, msg);
};
Logger.prototype.warning = function(msg) {
this._log(Logger.WARNING, msg);
};
Logger.prototype.error = function(msg) {
this._log(Logger.ERROR, msg);
};
Logger.prototype.critical = function(msg) {
this._log(Logger.CRITICAL, msg);
};
Logger.prototype.toString = function() {
return '[object logging.Logger]';
};
Logger.prototype.makeRecord = function(level, msg) {
return {
name: this._name,
level: level,
msg: msg
};
};
Logger.prototype._log = function(level, msg) {
if (this._disabled || level < this._level) {
return;
}
this._callHandlers(this.makeRecord(level, msg));
};
Logger.prototype._callHandlers = function(record) {
var logger = this;
while (logger) {
logger._handlers.forEach(function(handler) {
handler.handle(record);
});
if (this._propagate) {
logger = logger._parent;
} else {
logger = null;
}
}
};
Logger.prototype._callParent = function(level, msg) {
this._parent[Logger.getLevelName(level)](msg);
};
if (typeof module !== 'undefined' && module.exports) {
module.exports = Logger;
}
| JavaScript | 0.999999 | @@ -983,21 +983,21 @@
Name = '
-debug
+DEBUG
';%0A%09%7D el
@@ -1043,20 +1043,20 @@
Name = '
-info
+INFO
';%0A%09%7D el
@@ -1105,23 +1105,23 @@
Name = '
-warning
+WARNING
';%0A%09%7D el
@@ -1168,21 +1168,21 @@
Name = '
-error
+ERROR
';%0A%09%7D el
@@ -1232,24 +1232,24 @@
Name = '
-critical
+CRITICAL
';%0A%09%7D el
@@ -1301,14 +1301,14 @@
= '
-notset
+NOTSET
';%0A%09
|
d8862e6c2039db62a09f5bf365b943abe8e3c851 | update lib before publishing | lib/Select.js | lib/Select.js | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require("react");
var _react2 = _interopRequireDefault(_react);
var _MenuItem = require("@material-ui/core/MenuItem");
var _MenuItem2 = _interopRequireDefault(_MenuItem);
var _Select = require("@material-ui/core/Select");
var _Select2 = _interopRequireDefault(_Select);
var _InputLabel = require("@material-ui/core/InputLabel");
var _InputLabel2 = _interopRequireDefault(_InputLabel);
var _FormControl = require("@material-ui/core/FormControl");
var _FormControl2 = _interopRequireDefault(_FormControl);
var _ComposedComponent = require("./ComposedComponent");
var _ComposedComponent2 = _interopRequireDefault(_ComposedComponent);
var _utils = require("./utils");
var _utils2 = _interopRequireDefault(_utils);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Select = function (_Component) {
_inherits(Select, _Component);
function Select(props) {
_classCallCheck(this, Select);
var _this = _possibleConstructorReturn(this, (Select.__proto__ || Object.getPrototypeOf(Select)).call(this, props));
_this.onSelected = function (event) {
var _this$props = _this.props,
onChangeValidate = _this$props.onChangeValidate,
onChange = _this$props.onChange,
_this$props$form = _this$props.form,
key = _this$props$form.key,
_this$props$form$sche = _this$props$form.schema,
isObject = _this$props$form$sche.isObject,
values = _this$props$form$sche.enum,
findFn = _this$props$form$sche.findFn;
var currentValue = event.target.value;
_this.setState({ currentValue: currentValue });
if (isObject) {
var item = values.find(function (each) {
return findFn ? findFn(each, currentValue) : each === currentValue;
});
onChange(key, item);
} else {
onChangeValidate(event);
}
};
_this.getLabel = function (each) {
var _this$props2 = _this.props,
_this$props2$form$sch = _this$props2.form.schema,
displayFn = _this$props2$form$sch.displayFn,
noLocalization = _this$props2$form$sch.noLocalization,
getLocalizedString = _this$props2.localization.getLocalizedString;
if (displayFn) {
return displayFn(each);
}
if (noLocalization) return each.name;
return getLocalizedString(each.name);
};
var _this$props3 = _this.props,
model = _this$props3.model,
form = _this$props3.form;
_this.state = {
currentValue: _utils2.default.getValueFromModel(model, form.key) || ""
};
return _this;
}
_createClass(Select, [{
key: "render",
value: function render() {
var _this2 = this;
var _props = this.props,
form = _props.form,
getLocalizedString = _props.localization.getLocalizedString;
var currentValue = this.state.currentValue;
var menuItems = [];
if (form.schema.isObject) {
menuItems = form.schema.enum.map(function (item, idx) {
return (
// eslint-disable-next-line react/no-array-index-key
_react2.default.createElement(
_MenuItem2.default,
{ key: idx, value: item },
_this2.getLabel(item)
)
);
});
} else {
menuItems = form.titleMap.map(function (item, idx) {
return (
// eslint-disable-next-line react/no-array-index-key
_react2.default.createElement(
_MenuItem2.default,
{ key: idx, value: item.value },
_this2.getLabel(item)
)
);
});
}
return _react2.default.createElement(
_FormControl2.default,
{ fullWidth: true },
_react2.default.createElement(
_InputLabel2.default,
{ required: form.required },
form.title && getLocalizedString(form.title)
),
_react2.default.createElement(
_Select2.default,
{
value: currentValue || "",
placeholder: form.placeholder && getLocalizedString(form.placeholder),
disabled: form.readonly,
onChange: this.onSelected
},
menuItems
)
);
}
}], [{
key: "getDerivedStateFromProps",
value: function getDerivedStateFromProps(props) {
var form = props.form,
model = props.model;
if (model && form.key) {
return {
currentValue: _utils2.default.getValueFromModel(model, form.key)
};
}
return null;
}
}]);
return Select;
}(_react.Component);
exports.default = (0, _ComposedComponent2.default)(Select); | JavaScript | 0 | @@ -1165,24 +1165,157 @@
mControl);%0A%0A
+var _FormHelperText = require(%22@material-ui/core/FormHelperText%22);%0A%0Avar _FormHelperText2 = _interopRequireDefault(_FormHelperText);%0A%0A
var _Compose
@@ -4745,32 +4745,70 @@
= _props.form,%0A
+ error = _props.error,%0A
@@ -5937,32 +5937,33 @@
;%0A %7D%0A
+%0A
retu
@@ -6068,16 +6068,32 @@
th: true
+, error: !!error
%7D,%0A
@@ -6715,16 +6715,251 @@
nuItems%0A
+ ),%0A _react2.default.createElement(%0A _FormHelperText2.default,%0A null,%0A (error %7C%7C form.description) && getLocalizedString(error %7C%7C form.description)%0A
|
50e6b3dd64a2f2a04055db63818f021b73b1d570 | Add some semi colons | lib/Server.js | lib/Server.js | var express = require('express');
var bodyParser = require("body-parser");
var hb = require('handlebars');
var fs = require('fs');
var forever = require('forever-monitor');
var WifiManager = require('./WifiManager');
const path = require('path');
var hbCache = {};
hb.registerHelper('toJSON', function(object){
return new hb.SafeString(JSON.stringify(object));
});
hb.registerPartial('master', fs.readFileSync('templates/master.html', 'utf8'));
hb.registerPartial('admin', fs.readFileSync('templates/admin.html', 'utf8'));
var hbTemplate = function(path, cb){
//if(typeof hbCache[path] !== 'undefined'){
// cb(hbCache[path]);
//}else{
fs.readFile(path, 'utf-8', function(error, source){
var template = hb.compile(source);
//hbCache[path] = template;
cb(template)
});
//}
}
var Server = function(conf){
var self = this;
this.children = [];
this.setupStaticApps = function(){
for(app in this.allApps){
if(this.allApps[app].type == 'static'){
this.httpd.use("/a/" + this.allApps[app].path , express.static(this.allApps[app].appLoc));
}
}
}
this.setupJSApps = function(){
for(app in this.allApps){
if(this.allApps[app].type == 'js'){
var router = express.Router();
var subApp = require('../' + this.allApps[app].appLoc + '/' + this.allApps[app].entry);
subApp.setup(router, express);
if(subApp.staticFolder){
this.httpd.use("/a/" + this.allApps[app].path, express.static(this.allApps[app].appLoc + '/' + subApp.staticFolder));
}
this.httpd.use("/a/" + this.allApps[app].path, router);
}
}
}
this.setupStandaloneApps = function(){
for(app in this.allApps){
if(this.allApps[app].type == 'standalone'){
var appCwd = path.join(__dirname, '..', this.allApps[app].appLoc);
var child = new (forever.Monitor)(this.allApps[app].runcmd.split(' '), {cwd: appCwd, silent: false});
this.children.push(child);
child.on('error', function(err){
console.log(err);
});
child.start()
}
}
}
this.setupIframes = function(){
for(app in this.allApps){
this.httpd.get('/' + this.allApps[app].path, function(){
var appPath = self.allApps[app].path
return function(req, res){
hbTemplate('templates/app.html', function(template){
res.send(template({appPath: appPath, apps: self.apps}))
})
}
}());
}
}
this.setupRoot = function(){
this.httpd.get('/', function (req, res) {
hbTemplate('templates/home.html', function(template){
WifiManager.getStatus((err, status) => {
res.send(template({apps: self.apps, connected:!!status.ifstatus.ipv4_address}));
});
})
})
}
this.setupIcons = function(){
this.httpd.get('/icons/:app.jpg', (req, res) => {
for(var i=0; i<self.allApps.length; i++){
if(self.allApps[i].path === req.params.app){
return res.sendFile(path.join(__dirname, '../' + self.allApps[i].appLoc + '/icon.jpg'));
}
}
res.sendStatus(404);
});
}
this.updateApps = function(apps){
this.Server.close();
this.children.forEach((c) => {
c.stop();
});
this.children = [];
this.start(apps);
}
this.printRoutes = function(){
require('express-print-routes')(this.httpd, 'routes.txt');
}
this.start = function(apps){
this.httpd = express();
this.httpd.use(bodyParser.json());
this.httpd.use(express.static('assets'))
this.apps = apps;
this.allApps = this.apps.adminApps.concat(this.apps.apps);
this.setupRoot();
this.setupStaticApps();
this.setupJSApps();
this.setupStandaloneApps();
this.setupIframes();
this.setupIcons();
//this.printRoutes();
this.Server = this.httpd.listen(80, function () {
console.log('Listening on port 80!')
})
}
}
module.exports = Server;
| JavaScript | 0.999969 | @@ -2086,16 +2086,17 @@
.start()
+;
%0A %7D
@@ -2444,16 +2444,17 @@
.apps%7D))
+;
%0A
|
f72280e7f59f882b8e6f7335225e6e17397417fd | Fix callback in server | lib/Server.js | lib/Server.js | 'use strict';
const EventEmitter = require('events');
const net = require('net');
const Connection = require('./Connection');
const packet = require('./packet');
class Server extends EventEmitter {
constructor(options, cb) {
super();
this._server = net.createServer((socket) => {
this.emit('session', new Session(socket));
});
this._server.listen(options, () => {
this.emit('listening');
if (cb)
cb();
});
}
address() {
return this._server.address();
}
close(cb) {
this._server.close(() => {
this.emit('close');
if (cb)
cb();
});
}
};
class Session extends EventEmitter {
constructor(socket) {
super();
this._connection = new Connection(socket, {
heartbeatPacketType: packet.SERVER_HEARTBEAT,
});
this._connection.on('packet', (packetType, payload) => {
switch (packetType) {
case packet.DEBUG:
break;
case packet.LOGIN_REQUEST:
this.emit('login', packet.parseLoginRequest(payload));
break;
case packet.LOGOUT_REQUEST:
this.emit('logout');
break;
case packet.UNSEQUENCED_DATA:
this.emit('message', payload);
break;
case packet.CLIENT_HEARTBEAT:
break;
default:
this.emit('error', new Error('Unknown packet type: ' + packetType));
}
});
this._connection.on('error', (err) => {
this.emit('error', err);
});
this._connection.on('end', () => {
this.emit('end');
});
}
accept(payload, cb) {
this._connection.send(packet.LOGIN_ACCEPTED, packet.formatLoginAccepted(payload), cb);
}
reject(payload, cb) {
this._connection.send(packet.LOGIN_REJECTED, packet.formatLoginRejected(payload), cb);
}
send(payload, cb) {
this._connection.send(packet.SEQUENCED_DATA, payload, cb);
}
ending(cb) {
this._connection.send(packet.END_OF_SESSION);
}
end() {
this._connection.end();
}
}
module.exports = Server;
| JavaScript | 0.000001 | @@ -1965,16 +1965,20 @@
_SESSION
+, cb
);%0A %7D%0A%0A
|
d8f6ca6e479bd3e94690dde4863619c36e9b1380 | Update Update.js | lib/Update.js | lib/Update.js | "use strict";
var chalk = require('chalk');
var readline = require('readline');
var rl = readline.createInterface(process.stdin, process.stdout);
var sys = require('sys');
var exec = require('child_process').exec;
var fs = require('fs');
var request = require('request');
var tempWrite = require('temp-write');
function checkForUpdate() {
console.log(chalk.magenta("[UPDATER] Checking for updates..."));
fs.readFile('./version.txt', 'utf-8', function(err, data) {
if (err) {
console.error(err);
process.exit();
}
request('https://raw.githubusercontent.com/LifeMushroom/Modular-Node.js-IRC-Bot/master/package.json', function(error, response, body) {
if (!error && response.statusCode == 200) {
if (body > JSON.parse(data).version) {
console.log(chalk.magenta("[UPDATER]" + " Update Found!"));
rl.question(chalk.magenta("Update? [yes]/no: "), function(answer) {
if (answer == 'yes') {
fs.readFile('./config.js', 'utf-8', function (err, data) {
if (err) {
console.error(err);
process.exit();
}
var tempconfig = tempWrite.sync(data);
exec("git pull");
fs.writeFile('./old_config.js', fs.readFileSync(tempconfig, 'utf-8'), function (err) {
if (err) {
console.error(err);
process.exit();
}
console.log(chalk.magenta("[UPDATER] Successfully updated! Your new configuration's name is \"config_old.js\"."));
console.log(chalk.magenta("[UPDATER] Please check your \"config.js\" to add the new features to your \"config_old.js\" and then rename your \"config_old.js\" to \"config.js\""));
console.log(chalk.magenta("[UPDATER] Please re-run your bot when you are ready!"));
process.exit();
});
});
} else {
console.log(chalk.magenta("[UPDATER] Update Aborted"));
}
});
} else {
console.log(chalk.magenta("[UPDATER] No updates found... Booted up!"));
}
} else {
console.error(err);
}
});
});
}
checkForUpdate();
| JavaScript | 0.000002 | @@ -433,19 +433,20 @@
('./
-version.txt
+package.json
', '
@@ -732,20 +732,40 @@
%0A%09%09%09if (
-body
+JSON.parse(body).version
%3E JSON.
|
89e5621a9d3021fbfb69cb98d8ef519620ac001d | Fix typo | lib/bundle.js | lib/bundle.js | /*
* Copyright 2014-2015 Guy Bedford (http://guybedford.com)
*
* 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 ui = require('./ui');
var path = require('path');
var config = require('./config');
var Builder = require('systemjs-builder');
var fs = require('fs');
var asp = require('rsvp').denodeify;
var extend = require('./common').extend;
var alphabetize = require('./common').alphabetize;
exports.depCache = function(expression) {
var systemBuilder = new Builder();
return config.load()
.then(function() {
expression = expression || config.loader.main;
})
.then(function() {
ui.log('info', 'Injecting the traced dependency tree for `' + expression + '`...');
// trace the starting module
var cfg = config.loader.getConfig();
cfg.baseURL = path.relative(process.cwd(), config.pjson.baseURL);
systemBuilder.config(cfg);
return systemBuilder.trace(expression);
})
.then(function(tree) {
logTree(tree);
var depCache = config.loader.depCache || {};
extend(depCache, systemBuilder.getDepCache(tree));
config.loader.depCache = depCache;
})
.then(config.save)
.then(function() {
ui.log('ok', 'Depenency tree injected');
})
.catch(function(e) {
ui.log('err', e.stack || e);
});
};
// options.inject, options.sourceMaps, options.minify
exports.bundle = function(moduleExpression, fileName, opts) {
var systemBuilder = new Builder();
return config.load()
.then(function() {
fileName = fileName || path.resolve(config.pjson.baseURL, 'build.js');
if (!opts.sourceMaps)
return removeExistingSourceMap(fileName);
})
.then(function() {
ui.log('info', 'Building the bundle tree for `' + moduleExpression + '`...');
// trace the starting module
var cfg = config.loader.getConfig();
cfg.baseURL = path.relative(process.cwd(), config.pjson.baseURL);
systemBuilder.config(cfg);
return systemBuilder.trace(moduleExpression);
})
.then(function(buildTree) {
logTree(buildTree);
if (!('lowResSourceMaps' in opts))
opts.lowResSourceMaps = true;
return systemBuilder.buildTree(buildTree, fileName, opts);
})
.then(function(output) {
delete config.loader.depCache;
if (opts.inject) {
// Add the bundle to config if the inject flag was given.
var bundleName = extractBundleName(fileName);
if (!config.loader.bundles)
config.loader.bundles = {};
config.loader.bundles[bundleName] = output.modules;
ui.log('ok', '`' + bundleName + '` added to config bundles.');
}
})
.then(config.save)
.then(function() {
logBuild(path.relative(process.cwd(), fileName), opts);
})
.catch(function(e) {
ui.log('err', e.stack || e);
throw e;
});
};
exports.unbundle = function() {
return config.load()
.then(function() {
config.loader.bundles = {};
config.loader.depCache = {};
return config.save();
})
.then(function() {
ui.log('ok', 'Bundle configuration removed.');
});
};
function logBuild(outFile, opts) {
var resolution = opts.lowResSourceMaps ? '' : 'high-res ';
ui.log('ok', 'Built into `' + outFile + '`' +
(opts.sourceMaps ? ' with ' + resolution + 'source maps' : '') + ', ' +
(opts.minify ? '' : 'un') + 'minified' +
(opts.minify ? (opts.mangle ? ', ' : ', un') + 'mangled.' : '.'));
}
// options.minify, options.sourceMaps
exports.bundleSFX = function(expression, fileName, opts) {
var systemBuilder = new Builder();
return config.load()
.then(function() {
fileName = fileName || path.resolve(config.pjson.baseURL, 'build.js');
if (!opts.sourceMaps)
return removeExistingSourceMap(fileName);
})
.then(function() {
ui.log('info', 'Building the single-file sfx bundle for `' + expression + '`...');
// trace the starting module
var cfg = config.loader.getConfig();
cfg.baseURL = path.relative(process.cwd(), config.pjson.baseURL);
opts.config = cfg;
if (!('lowResSourceMaps' in opts))
opts.lowResSourceMaps = true;
return systemBuilder.buildSFX(expression, fileName, opts);
})
.then(function() {
logBuild(path.relative(process.cwd(), fileName), opts);
})
.catch(function(e) {
ui.log('err', e.stack || e);
throw e;
});
};
function logTree(tree) {
ui.log('info', '');
tree = alphabetize(tree);
for (var name in tree)
ui.log('info', ' `' + name + '`');
ui.log('info', '');
}
function extractBundleName(fileName) {
return path.relative(config.pjson.baseURL, fileName.replace(/\.js$/, '')).replace(/\\/g, '/');
}
function removeExistingSourceMap(fileName) {
return asp(fs.unlink)(fileName + '.map')
.catch(function(e) {
if (e.code === 'ENOENT')
return;
throw e;
});
}
| JavaScript | 0.999999 | @@ -1694,16 +1694,17 @@
, 'Depen
+d
ency tre
|
6f5a12fb532fdbd174ca654465a53c2509dc74f0 | create entrypoint query | lib/cayley.js | lib/cayley.js | // Dependencies
const cayley = require('cayley')
// RDF constants
const RDF_SYNTAX = '<http://www.w3.org/1999/02/22-rdf-syntax-ns#';
const FLOW_VOCAB = '<http://schema.jillix.net/vocab/';
const SCHEMA = '<http://schema.org/';
// export the cayley client for custom use
exports.connect = (scope, state, args, data, next) => {
state.client = cayley(scope.env.db);
state.g = state.client.graph;
return next ? next(null, data) : data;
};
/* FIXED CAYLEY QUERIES */
// fixed cayley query
// reads sequence informations for flow
exports.flow = (g, sequence_id, role) => {
// base graph
//const sequence = g.V(sequence_id)
//.Tag('subject')
//.Has(FLOW_VOCAB + 'role>', role);
//const sequence_handlers = sequence.Out(FLOW_VOCAB + 'handler>', 'predicate');
return [
// sequence details
g.V(sequence_id)
.Tag('subject')
.Has(FLOW_VOCAB + 'role>', role)
.Out([
FLOW_VOCAB + 'role>',
FLOW_VOCAB + 'onError>',
FLOW_VOCAB + 'onEnd>',
FLOW_VOCAB + 'next>',
], 'predicate').All(),
// sequence handler details
g.V(sequence_id)
.Has(FLOW_VOCAB + 'role>', role)
.Out(FLOW_VOCAB + 'handler>')
.Tag('subject')
.Out([
FLOW_VOCAB + 'state>',
FLOW_VOCAB + 'data>',
FLOW_VOCAB + 'once>',
FLOW_VOCAB + 'stream>',
FLOW_VOCAB + 'emit>',
FLOW_VOCAB + 'next>'
], 'predicate').All(),
// sequence handler args
g.V(sequence_id)
.Has(FLOW_VOCAB + 'role>', role)
.Out(FLOW_VOCAB + 'handler>')
.Tag('subject')
.Out(FLOW_VOCAB + 'args>', 'predicate')
.Out(RDF_SYNTAX + 'string>').All()
];
};
// fixed cayley query
// returns all modules
exports.sequences = (g) => {
return g.V()
.Tag('subject')
.Has(RDF_SYNTAX + 'type>', FLOW_VOCAB + 'Sequence>')
.Save(SCHEMA + 'name>', 'subject')
.Save(RDF_SYNTAX + 'type>', 'predicate')
.All();
};
// fixed cayley query
// returns all instances of a module
exports.instances = (g, moduleIRI) => {
return g.V()
.Has(FLOW_VOCAB + 'module>', '<' + moduleIRI + '>')
.Save(FLOW_VOCAB + 'module>', 'subject')
.Save(RDF_SYNTAX + 'type>', 'predicate')
.All();
};
// fixed cayley query
// returns an instance and its events
exports.instance = (g, instanceIRI) => {
return g.V('<' + instanceIRI + '>')
.Tag('subject')
.Out(FLOW_VOCAB + 'event>', 'predicate')
.All();
};
// fixed cayley query
// returns an event and all its sequences
exports.event = (g, eventIRI) => {
const streams = [];
streams[0] = g.V('<' + eventIRI + '>')
.Tag('subject')
.Out(FLOW_VOCAB + 'sequence>', 'predicate').All();
streams[1] = g.V().Has(
FLOW_VOCAB + 'event>',
'<' + eventIRI + '>'
).Has(
RDF_SYNTAX + 'type>',
FLOW_VOCAB + 'Sequence>'
).Tag('subject').Out([
FLOW_VOCAB + 'dataHandler>',
FLOW_VOCAB + 'onceHandler>',
FLOW_VOCAB + 'streamHandler>',
FLOW_VOCAB + 'emit>',
FLOW_VOCAB + 'sequence>',
], 'predicate')
.All();
return streams;
};
// fixed cayley query
// returns a sequence
exports.handler = (g, handlerID) => {
return g.V(handlerID)
.Tag('subject')
.Out([
FLOW_VOCAB + 'instance>',
FLOW_VOCAB + 'dataHandler>',
FLOW_VOCAB + 'onceHandler>',
FLOW_VOCAB + 'streamHandler>',
FLOW_VOCAB + 'emit>',
], 'predicate')
.All();
};
| JavaScript | 0.000002 | @@ -470,37 +470,420 @@
IES */%0A%0A
-// fixed cayley query
+exports.entrypoint = (g, entrypoint_name) =%3E %7B%0A return %5B%0A g.V(entrypoint_name).In().In().Tag('subject')%0A .Out('%3Chttp://schema.jillix.net/vocab/environment%3E', 'predicate')%0A .Out('%3Chttp://www.w3.org/1999/02/22-rdf-syntax-ns#string%3E').All(),%0A g.V(entrypoint_name).In().In().Tag('subject')%0A .Out('%3Chttp://schema.jillix.net/vocab/sequence%3E', 'predicate').All()%0A %5D;%0A%7D;%0A
%0A// read
@@ -2217,24 +2217,26 @@
exports.
-sequence
+entrypoint
s = (g)
|
aebfe5eae145d4ba472aed6625016efe89db02df | remove dead code | lib/client.js | lib/client.js |
/**
* Module dependencies.
*/
var net = require('net');
var url = require('url');
var http = require('http');
var Reader = require('./reader');
var preprocess = require('./preprocessor');
var debug = require('debug')('icecast:client');
/**
* Module exports.
*/
exports = module.exports = Client;
/**
* The `Client` class is a subclass of the `http.ClientRequest` object.
*
* It adds a stream preprocessor to make "ICY" responses work. This is only needed
* because of the strictness of node's HTTP parser. I'll volley for ICY to be
* supported (or at least configurable) in the http header for the JavaScript
* HTTP rewrite (v0.12 of node?).
*
* The other big difference is that it passes an `icecast.Reader` instance
* instead of a `http.ClientResponse` instance to the "response" event callback,
* so that the "metadata" events are automatically parsed and the raw audio stream
* it output without the Icecast bytes.
*
* Also see the [`request()`](#request) and [`get()`](#get) convenience functions.
*
* @param {Object} options connection info and options object
* @param {Function} cb optional callback function for the "response" event
* @api public
*/
function Client (options, cb) {
if ('string' == typeof options) {
options = url.parse(options);
}
var req = http.request(options);
// add the "Icy-MetaData" header
req.setHeader('Icy-MetaData', '1');
if ('function' == typeof cb) {
req.once('icecastResponse', cb);
}
req.once('response', icecastOnResponse);
req.once('socket', icecastOnSocket);
return req;
};
/**
* "response" event listener.
*
* @api private
*/
function icecastOnResponse (res) {
debug('request "response" event');
var s = res;
var metaint = res.headers['icy-metaint'];
if (metaint) {
debug('got metaint: %d', metaint);
s = new Reader(metaint);
res.pipe(s);
s.res = res;
Object.keys(res).forEach(function (k) {
if ('_' === k[0]) return;
debug('proxying %j', k);
proxy(s, k);
});
}
if (res.connection._wasIcy) {
s.httpVersion = 'ICY';
}
this.emit('icecastResponse', s);
}
/**
* "socket" event listener.
*
* @api private
*/
function icecastOnSocket (socket) {
debug('request "socket" event');
// we have to preprocess the stream (that is, intercept "data" events and
// emit our own) to make the invalid "ICY" HTTP version get translated into
// "HTTP/1.0"
preprocess(socket);
}
/**
* Proxies "key" from `stream` to `stream.res`.
*
* @api private
*/
function proxy (stream, key) {
if (key in stream) {
debug('not proxying prop "%s" because it already exists on target stream', key);
return;
}
function get () {
return stream.res[key];
}
function set (v) {
return stream.res[key] = v;
}
Object.defineProperty(stream, key, {
configurable: true,
enumerable: true,
get: get,
set: set
});
}
| JavaScript | 0.000002 | @@ -31,60 +31,8 @@
*/%0A%0A
-var net = require('net');%0Avar url = require('url');%0A
var
@@ -1163,83 +1163,8 @@
) %7B%0A
- if ('string' == typeof options) %7B%0A options = url.parse(options);%0A %7D%0A%0A
va
|
31290eaff01f202a0b52cd35d48aa1a6531c5d9d | Add function parseResponse | lib/client.js | lib/client.js | /*
** Module dependencies
*/
var request = require('request');
var Parser = require('inspire-parser').Parser;
var _ = require('lodash');
var Harvester = require('./harvest');
var stringstream = require('stringstream');
/*
** Constructor
*/
function Client(url, options) {
if (!url) throw new Error('URL is required!');
options = options || {};
this.baseRequest = request.defaults({
url: url,
qs: _.extend({ service: 'CSW', version: '2.0.2' }, options.queryStringToAppend || {}),
qsStringifyOptions: { encode: !options.noEncodeQs },
headers: {
'User-Agent': options.userAgent || 'CSWBot',
},
agentOptions: options.agentOptions,
timeout: options.timeout * 1000,
gzip: options.gzip !== false,
});
}
/*
** Private methods
*/
Client.prototype.request = function(query) {
const req = this.baseRequest({ qs: query });
req.on('response', response => {
if (! response.headers['content-type'] || response.headers['content-type'].indexOf('xml') === -1) {
req.emit('error', new Error('Not an XML response'));
return response.destroy();
}
if (response.statusCode >= 400) {
req.emit('error', new Error('Responded with an error status code: ' + response.statusCode));
return response.destroy();
}
});
return req;
};
Client.prototype.mapOptions = function(options) {
var query = {};
// Mapping original params
_.assign(query, _.pick(options, 'maxRecords', 'startPosition', 'typeNames', 'outputSchema', 'elementSetName', 'resultType', 'namespace', 'constraintLanguage'));
if (options.limit) query.maxRecords = options.limit;
if (options.offset) query.startPosition = options.offset + 1;
return query;
};
/*
** Public methods
*/
Client.prototype.getRecordById = function(id, options, cb) {
if (!cb) {
cb = options;
options = {};
}
if (_.isArray(id)) {
id = id.join(',');
}
options = this.mapOptions(options);
options.request = 'GetRecordById';
options.id = id;
this.request(options, cb);
};
Client.prototype.getRecords = function(options, cb) {
if (!cb) {
cb = options;
options = {};
}
options = this.mapOptions(options);
_.defaults(options, {
resultType: 'results',
maxRecords: 10,
typeNames: 'csw:Record',
});
options.request = 'GetRecords';
this.request(options, cb);
};
Client.prototype.getCapabilities = function() {
return this.request({ request: 'GetCapabilities' });
};
Client.prototype.capabilities = function (done) {
const doneOnce = _.once(done);
const parser = new Parser();
this.getCapabilities()
.on('error', err => doneOnce(err))
.pipe(stringstream('utf8'))
.pipe(parser)
.on('error', err => doneOnce(err))
.on('end', () => doneOnce(new Error('No parsed content')))
.on('result', result => doneOnce(null, result));
};
Client.prototype.numRecords = function(options, cb) {
if (!cb) {
cb = options;
options = {};
}
options = this.mapOptions(options);
options.resultType = 'hits';
this.getRecords(options, function(err, result) {
if (err) return cb(err);
if (result.searchResults && result.searchResults.numberOfRecordsMatched) {
cb(null, parseInt(result.searchResults.numberOfRecordsMatched));
} else {
cb(new Error('Unable to find numberOfRecordsMatched attribute'));
}
});
};
Client.prototype.harvest = function(options) {
return new Harvester(this, options);
};
/*
** Exports
*/
module.exports = Client;
| JavaScript | 0.000007 | @@ -210,24 +210,435 @@
stream');%0A%0A%0A
+function parseResponse(reqResponse, done) %7B%0A const doneOnce = _.once(done);%0A const parser = new Parser();%0A reqResponse%0A .on('error', err =%3E doneOnce(err))%0A .pipe(stringstream('utf8'))%0A .pipe(parser)%0A .on('error', err =%3E doneOnce(err))%0A .on('end', () =%3E doneOnce(new Error('No parsed content')))%0A .on('result', result =%3E doneOnce(null, result));%0A%7D%0A%0A
/*%0A** Constr
@@ -3080,246 +3080,105 @@
-const doneOnce = _.once(done);%0A const parser = new Parser();%0A this.getCapabilities()%0A .on('error', err =%3E doneOnce(err))%0A .pipe(stringstream('utf8'))%0A .pipe(parser)%0A .on('error', err =%3E
+parseResponse(this.getCapabilities(), function (err, result) %7B%0A if (err) return
done
-Once
(err)
-)
+;
%0A
@@ -3186,114 +3186,127 @@
- .on('end', () =%3E doneOnce(new Error('No parsed content')))%0A .on('result', result =%3E doneOnc
+if (result.type !== 'Capabilities') return done(new Error('Not acceptable response type: ' + result.type));%0A don
e(nu
@@ -3311,25 +3311,37 @@
null, result
-)
+.body);%0A %7D
);%0A%7D;%0A%0AClien
|
0a6e03e42cc494b713b543e9a5b0002f575b3616 | Update gulp recipe (#90) | recipes/gulp/gulpfile.js | recipes/gulp/gulpfile.js | // Copyright 2016 Google Inc. All Rights Reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE
'use strict';
const gulp = require('gulp');
const connect = require('gulp-connect');
const PWMetrics = require('../../lib/');
const port = 8080;
const connectServer = function() {
return connect.server({
root: '../public',
livereload: true,
port: port
});
};
function handleError() {
process.exit(1);
}
gulp.task('pwmetrics', function() {
connectServer();
const url = `http://localhost:${port}/index.html`;
const pwMetrics = new PWMetrics(url, {
flags: {
expectations: true
},
expectations: {
ttfmp: {
warn: '>=1000',
error: '>=2000'
},
tti: {
warn: '>=2000',
error: '>=3000'
},
ttfcp: {
warn: '>=1500',
error: '>=2000'
}
}
});
return pwMetrics.start()
.then(_ => {
connect.serverClose();
})
.catch(_ => handleError);
});
gulp.task('default', ['pwmetrics']);
| JavaScript | 0 | @@ -240,20 +240,20 @@
;%0Aconst
-port
+PORT
= 8080;
@@ -254,28 +254,50 @@
8080;%0A%0A
-const connec
+/**%0A * Start server%0A */%0Aconst star
tServer
@@ -392,20 +392,20 @@
port:
-port
+PORT
%0A %7D);%0A%7D
@@ -411,75 +411,135 @@
%7D;%0A%0A
-function handleError() %7B%0A process.exit(1
+/**%0A * Stop server%0A */%0Aconst stopServer = function() %7B%0A connect.serverClose(
);%0A%7D
+;
%0A%0A
-gulp.task('p
+/**%0A * Run pwmetrics%0A */%0Aconst runP
wmetrics
', f
@@ -534,18 +534,18 @@
wmetrics
-',
+ =
functio
@@ -554,28 +554,8 @@
) %7B%0A
- connectServer();%0A%0A
co
@@ -584,20 +584,20 @@
lhost:$%7B
-port
+PORT
%7D/index.
@@ -609,25 +609,14 @@
;%0A
-const pwMetrics =
+return
new
@@ -925,88 +925,478 @@
%7D)
-;%0A return pwMetrics.start()%0A .then(_ =%3E %7B%0A connect.serverClose();%0A %7D
+.start();%0A%7D;%0A%0A/**%0A * Handle ok result%0A * @param %7BObject%7D results - Pwmetrics results obtained through Lighthouse%0A */%0Aconst handleOk = function(results) %7B%0A stopServer();%0A return results;%0A%7D;%0A%0A/**%0A * Handle error%0A */%0Aconst handleError = function(e) %7B%0A stopServer();%0A console.error(e); // eslint-disable-line no-console%0A throw e; // Throw to exit process with status 1.%0A%7D;%0A%0Agulp.task('pwmetrics', function() %7B%0A startServer();%0A return runPwmetrics()%0A .then(handleOk
)%0A
@@ -1408,13 +1408,8 @@
tch(
-_ =%3E
hand
|
d982ff9e495f18c9aa2eea7d626aaf746380b8d5 | Fix key encoding for Map dictionaries | lib/encode.js | lib/encode.js | var Buffer = require('safe-buffer').Buffer
/**
* Encodes data in bencode.
*
* @param {Buffer|Array|String|Object|Number|Boolean} data
* @return {Buffer}
*/
function encode (data, buffer, offset) {
var buffers = []
var result = null
encode._encode(buffers, data)
result = Buffer.concat(buffers)
encode.bytes = result.length
if (Buffer.isBuffer(buffer)) {
result.copy(buffer, offset)
return buffer
}
return result
}
encode.bytes = -1
encode._floatConversionDetected = false
encode.getType = function (value) {
if (Buffer.isBuffer(value)) return 'buffer'
if (Array.isArray(value)) return 'array'
if (ArrayBuffer.isView(value)) return 'arraybufferview'
if (value instanceof Number) return 'number'
if (value instanceof Boolean) return 'boolean'
if (value instanceof Set) return 'set'
if (value instanceof Map) return 'map'
if (value instanceof ArrayBuffer) return 'arraybuffer'
return typeof value
}
encode._encode = function (buffers, data) {
if (data == null) { return }
switch (encode.getType(data)) {
case 'buffer': encode.buffer(buffers, data); break
case 'object': encode.dict(buffers, data); break
case 'map': encode.dictMap(buffers, data); break
case 'array': encode.list(buffers, data); break
case 'set': encode.listSet(buffers, data); break
case 'string': encode.string(buffers, data); break
case 'number': encode.number(buffers, data); break
case 'boolean': encode.number(buffers, data); break
case 'arraybufferview': encode.buffer(buffers, Buffer.from(data.buffer, data.byteOffset, data.byteLength)); break
case 'arraybuffer': encode.buffer(buffers, Buffer.from(data)); break
}
}
var buffE = Buffer.from('e')
var buffD = Buffer.from('d')
var buffL = Buffer.from('l')
encode.buffer = function (buffers, data) {
buffers.push(Buffer.from(data.length + ':'), data)
}
encode.string = function (buffers, data) {
buffers.push(Buffer.from(Buffer.byteLength(data) + ':' + data))
}
encode.number = function (buffers, data) {
var maxLo = 0x80000000
var hi = (data / maxLo) << 0
var lo = (data % maxLo) << 0
var val = hi * maxLo + lo
buffers.push(Buffer.from('i' + val + 'e'))
if (val !== data && !encode._floatConversionDetected) {
encode._floatConversionDetected = true
console.warn(
'WARNING: Possible data corruption detected with value "' + data + '":',
'Bencoding only defines support for integers, value was converted to "' + val + '"'
)
console.trace()
}
}
encode.dict = function (buffers, data) {
buffers.push(buffD)
var j = 0
var k
// fix for issue #13 - sorted dicts
var keys = Object.keys(data).sort()
var kl = keys.length
for (; j < kl; j++) {
k = keys[j]
if (data[k] == null) continue
encode.string(buffers, k)
encode._encode(buffers, data[k])
}
buffers.push(buffE)
}
encode.dictMap = function (buffers, data) {
buffers.push(buffD)
var keys = Array.from(data.keys()).sort()
// Sort keys to retain
for (var key of keys) {
if (data.get(key) == null) continue
encode._encode(buffers, key)
encode._encode(buffers, data.get(key))
}
buffers.push(buffE)
}
encode.list = function (buffers, data) {
var i = 0
var c = data.length
buffers.push(buffL)
for (; i < c; i++) {
if (data[i] == null) continue
encode._encode(buffers, data[i])
}
buffers.push(buffE)
}
encode.listSet = function (buffers, data) {
buffers.push(buffL)
for (var item of data) {
if (item == null) continue
encode._encode(buffers, item)
}
buffers.push(buffE)
}
module.exports = encode
| JavaScript | 0.020403 | @@ -3075,35 +3075,108 @@
-encode._encode(buffers, key
+Buffer.isBuffer(key)%0A ? encode._encode(buffers, key)%0A : encode.string(buffers, String(key)
)%0A
|
37dc0d6dee90fc1c4fc4a50eb4046b9dde293912 | Fix limit reached | lib/follow.js | lib/follow.js | var async = require('async');
var db = require('./db');
var users = db.get('users');
var newGithub = require('./new_github');
/**
* Check if a user is following another user.
*
* @param user a GH API instance
* @param other The other user
*/
function isFollowing(user, other, cb) {
user.user.getFollowUser({
user: other
}, function(err, res) {
if (err) return cb(err, null);
var ret = res.meta.status.indexOf('204') === 0; // Weird API
cb(err, ret);
});
}
/**
* Make the first user follow the second.
*
* @param user GH API instance
* @param other String login username
*/
function follow(user, other, cb) {
isFollowing(user, other, function(err, following) {
// If following, return false
if (following) {
return cb(null, false);
}
// Follow the user
user.user.followUser({
user: other
}, function(followErr, followRes) {
if (followErr) return cb(followErr, false);
return cb(null, true);
});
});
}
/**
* Follow with database updates
*
* @param user GH API instance
* @param other String login username
*/
function followWithDb(user, other, cb) {
follow(user, other, function(err, res) {
if (res) {
return users.update({
login: user.login
}, {
$addToSet: {
following: other
}
}, function(error) {
cb(error, true);
});
}
cb(err, false);
});
}
/**
* Make a user unfollow someone. Both params must be GH API instances.
*
* @param user GH API instance
* @param other String login username
*/
function unfollow(user, other, cb) {
isFollowing(user, other, function(err, following) {
// If following, return false
if (!following) {
return cb(null, false);
}
// Unfollow the user
user.user.unfollowUser({
user: other
}, function(unfollowErr, unfollowRes) {
if (unfollowErr) return cb(unfollowErr, false);
return cb(null, true);
});
});
}
/**
* Unfollow with database updates
*
* @param user GH API instance
* @param other String login username
*/
function unfollowWithDb(user, other, cb) {
unfollow(user, other, function(err, res) {
if (res) {
return users.update({
login: user.login
}, {
$pull: {
following: other
}
}, function(error) {
cb(error, true);
});
}
cb(err, false);
});
}
/**
* Adds an amount of followers to a user.
*
* @param amount - Use '-1' to add as many as possible. It will add as many followers as possible.
*/
function addFollowers(login, amount, cb) {
users.findOne({
login: login
}, function(err, user) {
// CB null if user wasn't found
if (!user) {
return cb(null, null);
}
var gh = newGithub(user.token);
gh.login = user.login;
var sum = 0;
users.find({}, function(err, docs) {
async.eachSeries(docs, function(other, fin) {
if (amount !== -1 && sum >= amount) {
return fin();
}
var ugh = newGithub(other.token);
ugh.login = other.login;
// Ignore if same as user
if (other.login === user.login) return fin();
// Follow each other
async.waterfall([
function(done) {
followWithDb(gh, other.login, done);
},
function(res, done) {
// Terminate if they didn't follow
if (!res) return done();
followWithDb(ugh, user.login, function(err, didFollow) {
if (!didFollow) {
return unfollowWithDb(gh, other.login, done);
}
sum++;
done();
});
}
], function(err) {
fin();
});
}, function() {
cb(null, {
follows: sum,
limitReached: sum < amount && amount !== -1
});
});
});
});
};
module.exports = addFollowers;
| JavaScript | 0.000002 | @@ -3834,37 +3834,46 @@
ed:
-sum %3C
+(
amount
-&& amount !== -1
+=== -1) ? false : sum %3C amount
%0A
|
b3f0c426858ab22e4abbeb987567fad0d60721a2 | Format with v7 reference | lib/format.js | lib/format.js | 'use strict';
var beautify = require('js-beautify').js_beautify,
reference = require('mapbox-gl-style-spec/reference/v6'),
sortObject = require('sort-object');
function sameOrderAs(reference) {
var keyOrder = {};
Object.keys(reference).forEach(function(k, i) {
keyOrder[k] = i + 1;
});
return {
sort: function (a, b) {
return (keyOrder[a] || Infinity) -
(keyOrder[b] || Infinity);
}
};
}
module.exports = function format(style) {
style = sortObject(style, sameOrderAs(reference.$root));
style.layers = style.layers.map(function(layer) {
return sortObject(layer, sameOrderAs(reference.layer));
});
var str = beautify(JSON.stringify(style), {
indent_size: 2,
keep_array_indentation: true
}).replace(/"filter": {[^}]+}/g, function (str) {
var str2 = str.replace(/([{}])\s+/g, '$1 ').replace(/,\s+/g, ', ').replace(/\s+}/g, ' }');
return str2.length < 100 ? str2 : str;
});
return str;
};
| JavaScript | 0 | @@ -120,9 +120,9 @@
ce/v
-6
+7
'),%0A
|
fd2a64415b903c474376865890dce7cc5451a24f | Increase timeout for defer return | lib/handle.js | lib/handle.js | const fs = require('fs'),
crypto = require('crypto'),
{ serialize } = require('./serializers'),
{ getFuncArgs } = require('./parser'),
{ logger } = require('smappi-cl');
const FORMATS = {
'json': 'application/json',
'xml': 'application/xml'
}
function STD (res) {
function output (msg, code, fmt) {
res.writeHead(code, {'Content-Type': FORMATS[fmt] || 'text/plain'});
res.end(msg);
}
res.stdout = function (msg, fmt) {
return output(msg, 200, fmt);
}
res.stderr = function (msg, fmt) {
msg += '. Please check Log tab for this API.';
msg = serialize({'error': {'code': '1501', 'message': msg}}, fmt);
return output(msg, 404, fmt);
}
return res;
}
function handleRequest (request, response, api, funcName, args, fmt, caches) {
if (!FORMATS[fmt])
return response.stderr(`Format "${fmt}" is not supported`);
response = STD(response);
switch (funcName) {
case 'favicon.ico':
return response.stderr('Not found', fmt);
case 'caches.txt':
let out = 'The caches.txt does not exist';
if (fs.existsSync(caches.rulesfile))
out = fs.readFileSync(caches.rulesfile, 'utf8')
return response.stdout(out);
case '':
return response.stderr('You did not specify a function name', fmt);
}
let chunks = funcName.split('.');
let func = api[chunks[0]];
for (let i in chunks) {
if (['function', 'undefined'].indexOf(typeof(func)) > -1) break;
func = func[chunks[++i]];
}
console.log('----------------------------------------------------------------------------------------------------')
if (typeof(func) == 'function') {
let md5sum = crypto.createHash('md5'),
cacheKey = md5sum.update(JSON.stringify(args)).digest('hex'),
cachedOut = caches.resolve(funcName, cacheKey, fmt);
console.log(`Function "${funcName}" with [${JSON.stringify(args)}]`);
if (cachedOut) {
console.log('Cached out.');
response.writeHead(200, {'Content-Type': FORMATS[fmt]});
response.end(cachedOut);
} else {
// Get arguments for function
let seqArgs = getFuncArgs(func);
let funcArgs = [];
let isSpread;
for (let i in seqArgs) {
if (seqArgs[i].indexOf('...') != -1)
isSpread = true;
let attr = seqArgs[i].replace(/\./g, '');
if (args[attr] === undefined)
return response.stderr(`No specified argument "${attr}" for "${funcName}"`, fmt);
funcArgs[i] = args[attr];
}
var returnTimeout = setTimeout(function () {
console.warn('********************************************');
console.warn('* Wait of return... You did not forget it? *');
console.warn('********************************************');
}, 20000);
// Call function
let context = {
'return': function (out) {
clearTimeout(returnTimeout);
if (this._returned) return;
out = serialize(out, fmt);
// console.log('Format:', fmt)
caches.save(funcName, cacheKey, fmt, out);
response.writeHead(200, {'Content-Type': FORMATS[fmt]});
response.end(out);
this._returned = true;
}
}
if (isSpread) {
let spread = funcArgs[0];
try {
spread = JSON.parse(spread);
if (!Array.isArray(spread))
return response.stderr('Spread only apply for iterables (such as arrays)', fmt);
} catch (err) {
console.log('JSON parse spread error: ', err);
console.log('Try to split by semicolon...')
spread = spread.split(',');
}
funcArgs = spread;
}
let out;
try {
out = func.apply(context, funcArgs);
} catch (err) {
logger.error(err.stack || err);
return response.stderr(err, fmt);
}
if (out !== undefined) {
context.return(out);
} else {
if (func.toString().indexOf('.return') == -1) {
// context.return('');
let msg = `The "${funcName}" function did not return anything, ` +
`it is necessary to call return or deferred self.return (https://smappi.org/documentation/the-deferred-return/)`;
logger.warn(msg);
return response.stderr(msg, fmt);
}
}
}
} else {
return response.stderr(`Function "${funcName}" not found`, fmt);
}
}
module.exports = { STD, handleRequest }
| JavaScript | 0.000001 | @@ -3019,17 +3019,17 @@
%7D,
-2
+3
0000);%0A
|
4e572e318494cef8cefe45a64d5420be65abd3e6 | Make Heroku.configure a named function | lib/heroku.js | lib/heroku.js | var Request = require('./request'),
_ = require('lodash');
module.exports = Heroku;
function Heroku (options) {
this.options = options;
}
Heroku.configure = function (config) {
if (config.cache) {
Request.connectCacheClient();
}
return this;
}
Heroku.request = Request.request;
Heroku.prototype.request = function (options, callback) {
if (typeof options === 'function') {
callback = options;
options = this.options;
} else {
options = _.defaults(options, this.options);
}
return Request.request(options, function (err, body) {
if (callback) callback(err, body);
});
};
require('./resourceBuilder').build();
| JavaScript | 0.999252 | @@ -174,16 +174,26 @@
unction
+configure
(config)
|
251ec33fad592ad68d43c7351deeef55ceb0855d | add deprecation warning | lib/indico.js | lib/indico.js | var Promise = require('bluebird'),
services = require('./services.js'),
settings = require('./settings.js'),
image = require('./image.js'),
request = Promise.promisify(require('request')),
indico = module.exports;
Promise.promisifyAll(request);
var public_api = 'http://apiv2.indico.io/'
indico.apiKey = false;
indico.cloud = false;
function service(name, privateCloud, apiKey, apis) {
/* given a set of parameters, returns the proper url for the REST api*/
if (privateCloud) {
var prefix = 'http://' + privateCloud + '.indico.domains/';
var url = prefix + name;
} else {
var url = public_api + name;
}
url = url + "?key=" + apiKey;
if (apis) {
url = url + "&apis=" + apis.join();
}
return url
}
function formatResults(results, nameMap) {
var formatted_results = {};
for (result in results) {
if ('results' in results[result]) {
formatted_results[nameMap[result]] = results[result]['results'];
} else {
formatted_results[nameMap[result]] = results[result];
}
}
return formatted_results;
}
function addKeywordArguments(body, config) {
// pass along additional keyword args in JSON body
for (var key in config) {
if (key !== 'apiKey' && key !== 'privateCloud') {
body[key] = config[key];
}
}
return body;
}
function standardizeApiNames(config, nameMap) {
// standardization for multi-api support
for (var key in config) {
if (key === 'apis') {
var apis = config['apis'];
for (apiName in apis) {
standardized = apis[apiName].toLowerCase();
nameMap[standardized] = apis[apiName]
apis[apiName] = standardized;
}
return apis
}
}
return false;
}
function formatName(name, batch) {
if (['predictText', 'predictImage'].indexOf(name) !== -1) {
name = 'apis';
}
if (batch) {
name += '/batch'
}
name = name.toLowerCase();
return name;
}
function postprocess(results, name, nameMap) {
if (name.indexOf('apis') === 0) {
results = formatResults(results, nameMap);
}
return results;
}
var make_request = function (name, data, batch, config) {
var apiKey = settings.resolveApiKey(config, indico.apiKey);
var privateCloud = settings.resolvePrivateCloud(config, indico.cloud);
var body = {};
var nameMap = {};
body['data'] = data;
body = addKeywordArguments(body, config);
apis = standardizeApiNames(config, nameMap);
name = formatName(name, batch);
var options = {
method: 'POST',
url: service(name, privateCloud, apiKey, apis),
body: JSON.stringify(body),
headers: {
'Content-type': 'application/json',
'Accept': 'text/plain',
'client-lib': 'node',
'version-number': '0.3.1'
}
};
return request(options).then(function (results) {
var res = results[0];
var body = results[1];
/*
TODO: Make sure this matches the API headers
*/
var warning = res.headers['X-Deprecation-Warning'];
if (warning) {
console.warn(warning);
}
if (res.statusCode !== 200) {
return body;
}
results = JSON.parse(body).results;
results = postprocess(results, name, nameMap);
return results
});
}
var api_request = function (name, api) {
return function (data, config) {
var batch = Object.prototype.toString.call(data).indexOf("Array") > -1;
if (api.type === "image") {
var size = (api == "fer" && config["detect"]) ? false : api.size;
return image.preprocess(data, size, api.min_axis, batch).then(function (packaged) {
return make_request(name, packaged, batch, config);
});
} else {
return make_request(name, data, batch, config);
}
};
}
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
function snakeCase(str) {
return str.replace(/([A-Z])/g, function (char) {
return '_' + char.toLowerCase();
});
}
services.forEach(function (api) {
var name = api.name;
indico[name] = api_request(name, api);
});
// camelCase + snake_case + lowercase supported
for (name in indico) {
indico[snakeCase(name)] = indico[name];
indico[name.toLowerCase()] = indico[name];
}
indico.posneg = indico.sentiment;
| JavaScript | 0.000001 | @@ -3222,16 +3222,23 @@
ame, api
+, batch
) %7B%0A re
@@ -3264,24 +3264,287 @@
, config) %7B%0A
+ if (batch) %7B%0A console.warn(%0A %22The %60batch%22 + capitalize(api.name) + %22%60 function will be deprecated in the next major upgrade. %22 + %0A %22Please call %60%22 + api.name.replace(%22batch%22, %22%22) + %0A %22%60 instead with the same arguments%22%0A )%0A %7D%0A
var batc
@@ -4253,16 +4253,92 @@
ame, api
+, false);%0A indico%5B%22batch%22 + capitalize(name)%5D = api_request(name, api, true
);%0A%7D);%0A%0A
|
2e19e0acc12a3af203f81d53ab0a9c6999f4a0cd | Add Sports specific Layout attributes. | lib/layout.js | lib/layout.js | 'use strict';
/**
* Layout
*
* @constructor
* @param {Object} [opts]
*/
var Layout = module.exports = function (opts) {
this._layout = new _Layout();
if (opts && opts.type) {
if (typeof opts.type !== 'string') {
throw new Error('Expected type to be a string.');
}
this._layout.type = opts.type;
}
if (opts && opts.title) {
if (typeof opts.title !== 'string') {
throw new Error('Expected title to be a string.');
}
this._layout.title = opts.title;
}
if (opts && opts.shortTitle) {
if (typeof opts.shortTitle !== 'string') {
throw new Error('Expected shortTitle to be a string.');
}
this._layout.shortTitle = opts.shortTitle;
}
if (opts && opts.subtitle) {
if (typeof opts.subtitle !== 'string') {
throw new Error('Expected subtitle to be a string.');
}
this._layout.subtitle = opts.subtitle;
}
if (opts && opts.body) {
if (typeof opts.body !== 'string') {
throw new Error('Expected body to be a string.');
}
this._layout.body = opts.body;
}
if (opts && opts.tinyIcon) {
if (typeof opts.tinyIcon !== 'string') {
throw new Error('Expected tinyIcon to be a string.');
}
this._layout.tinyIcon = opts.tinyIcon;
}
if (opts && opts.smallIcon) {
if (typeof opts.smallIcon !== 'string') {
throw new Error('Expected smallIcon to be a string.');
}
this._layout.smallIcon = opts.smallIcon;
}
if (opts && opts.largeIcon) {
if (typeof opts.largeIcon !== 'string') {
throw new Error('Expected largeIcon to be a string.');
}
this._layout.largeIcon = opts.largeIcon;
}
if (opts && opts.locationName) {
if (typeof opts.locationName !== 'string') {
throw new Error('Expected locationName to be a string.');
}
this._layout.locationName = opts.locationName;
}
};
/**
* Get the Layout JSON Object
*
* @return {Object} Layout
*/
Layout.prototype.inspect =
Layout.prototype.toJSON = function () {
return this._layout;
};
function _Layout (opts) {
// add required params here
}
| JavaScript | 0 | @@ -1846,16 +1846,1983 @@
ame;%0A %7D
+%0A%0A if (opts && opts.broadcaster) %7B%0A if (typeof opts.broadcaster !== 'string') %7B%0A throw new Error('Expected broadcaster to be a string.');%0A %7D%0A this._layout.broadcaster = opts.broadcaster;%0A %7D%0A%0A if (opts && opts.rankAway) %7B%0A if (typeof opts.rankAway !== 'string') %7B%0A throw new Error('Expected rankAway to be a string.');%0A %7D%0A this._layout.rankAway = opts.rankAway;%0A %7D%0A%0A if (opts && opts.rankHome) %7B%0A if (typeof opts.rankHome !== 'string') %7B%0A throw new Error('Expected rankHome to be a string.');%0A %7D%0A this._layout.rankHome = opts.rankHome;%0A %7D%0A%0A if (opts && opts.nameAway) %7B%0A if (typeof opts.nameAway !== 'string') %7B%0A throw new Error('Expected nameAway to be a string.');%0A %7D%0A this._layout.nameAway = opts.nameAway;%0A %7D%0A%0A if (opts && opts.nameHome) %7B%0A if (typeof opts.nameHome !== 'string') %7B%0A throw new Error('Expected nameHome to be a string.');%0A %7D%0A this._layout.nameHome = opts.nameHome;%0A %7D%0A%0A if (opts && opts.recordAway) %7B%0A if (typeof opts.recordAway !== 'string') %7B%0A throw new Error('Expected recordAway to be a string.');%0A %7D%0A this._layout.recordAway = opts.recordAway;%0A %7D%0A%0A if (opts && opts.recordHome) %7B%0A if (typeof opts.recordHome !== 'string') %7B%0A throw new Error('Expected recordHome to be a string.');%0A %7D%0A this._layout.recordHome = opts.recordHome;%0A %7D%0A%0A if (opts && opts.scoreAway) %7B%0A if (typeof opts.scoreAway !== 'string') %7B%0A throw new Error('Expected scoreAway to be a string.');%0A %7D%0A this._layout.scoreAway = opts.scoreAway;%0A %7D%0A%0A if (opts && opts.scoreHome) %7B%0A if (typeof opts.scoreHome !== 'string') %7B%0A throw new Error('Expected scoreHome to be a string.');%0A %7D%0A this._layout.scoreHome = opts.scoreHome;%0A %7D%0A%0A if (opts && opts.sportsInGame) %7B%0A if (typeof opts.sportsInGame !== 'boolean') %7B%0A throw new Error('Expected sportsInGame to be a boolean.');%0A %7D%0A this._layout.sportsInGame = opts.sportsInGame;%0A %7D
%0A%7D;%0A%0A/**
|
dbc21e6e540c1870d6f402bae5e534f0b04fb52b | Handle no-extension case | lib/loader.js | lib/loader.js | /*
* Jake JavaScript build tool
* Copyright 2112 Matthew Eernisse (mde@fleegix.org)
*
* 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.
*
*/
let path = require('path');
let fs = require('fs');
let existsSync = fs.existsSync;
let utils = require('utilities');
// Files like jakelib/foobar.jake.js
const JAKELIB_FILE_PAT = /\.jake$|\.js$/;
const SUPPORTED_EXTENSIONS = {
'js': null,
'coffee': function () {
try {
let cs = require('coffee-script');
if (typeof cs.register == 'function') {
cs.register();
}
}
catch(e) {
throw new Error('You have a CoffeeScript Jakefile, but have not installed CoffeeScript');
}
},
'ls': function () {
try {
return require('livescript');
} catch (e) {}
try {
return require('LiveScript');
} catch (e) {}
throw new Error('You have a LiveScript Jakefile, but have not installed LiveScript');
}
};
const IMPLICIT_JAKEFILE_NAMES = [
'Jakefile',
'Gulpfile'
];
let Loader = function () {
// Load a Jakefile, running the code inside -- this may result in
// tasks getting defined using the old Jake API, e.g.,
// `task('foo' ['bar', 'baz']);`, or can also auto-create tasks
// from any functions exported from the file
function loadFile(filePath) {
let exported = require(filePath);
for (let [key, value] of Object.entries(exported)) {
let t;
if (typeof value == 'function') {
t = jake.task(key, value);
t.description = '(Exported function)';
}
}
}
function fileExists(name) {
let nameWithExt = null;
// Support no file extension as well
let exts = Object.keys(SUPPORTED_EXTENSIONS).concat(['']);
exts.some((ext) => {
let fname = `${name}.${ext}`;
if (existsSync(fname)) {
nameWithExt = fname;
return true;
}
});
return nameWithExt;
}
// Recursive
function findImplicitJakefile() {
let cwd = process.cwd();
let names = IMPLICIT_JAKEFILE_NAMES;
let found = null;
names.some((name) => {
let n;
// Prefer all-lowercase
n = name.toLowerCase();
if ((found = fileExists(n))) {
return found;
}
// Check mixed-case as well
n = name;
if ((found = fileExists(n))) {
return found;
}
});
if (found) {
return found;
}
else {
process.chdir("..");
// If we've walked all the way up the directory tree,
// bail out with no result
if (cwd === process.cwd()) {
return null;
}
return findImplicitJakefile();
}
}
this.loadFile = function (fileSpecified) {
let jakefile;
let origCwd = process.cwd();
if (fileSpecified) {
if (existsSync(fileSpecified)) {
jakefile = fileSpecified;
}
}
else {
jakefile = findImplicitJakefile();
}
if (jakefile) {
let ext = jakefile.split('.')[1];
let loaderFunc = SUPPORTED_EXTENSIONS[ext];
loaderFunc && loaderFunc();
loadFile(utils.file.absolutize(jakefile));
return true;
}
else {
if (!fileSpecified) {
// Restore the working directory on failure
process.chdir(origCwd);
}
return false;
}
};
this.loadDirectory = function (d) {
let dirname = d || 'jakelib';
let dirlist;
dirname = utils.file.absolutize(dirname);
if (existsSync(dirname)) {
dirlist = fs.readdirSync(dirname);
dirlist.forEach(function (filePath) {
if (JAKELIB_FILE_PAT.test(filePath)) {
loadFile(path.join(dirname, filePath));
}
});
return true;
}
return false;
};
};
module.exports.Loader = Loader;
| JavaScript | 0.000034 | @@ -2237,16 +2237,29 @@
fname =
+ ext ? name :
%60$%7Bname
|
25bc54d59f209fe024ce37ac5ae969aa4db1de90 | fix style warnings in lib/logger.js | lib/logger.js | lib/logger.js | var util = require('util');
module.exports = Logger;
function Logger(sink) {
if (!(this instanceof Logger)) return new Logger(sink);
this.sink = sink;
}
Logger.prototype.info = partial(LevelLog, 'INFO');
Logger.prototype.log = Logger.prototype.info;
Logger.prototype.warn = partial(LevelLog, 'WARN');
Logger.prototype.error = partial(LevelLog, 'ERROR');
function LevelLog(level /*, items... */) {
var items = [].slice.call(arguments, 1);
this.sink.write(level + ' ' +
util.format.apply(util, items) +
'\n');
}
function partial(fn /*, firstArgs... */) {
var firstArgs = [].slice.call(arguments, 1);
return function() {
var args = firstArgs.concat([].slice.call(arguments));
return fn.apply(this, args);
};
}
| JavaScript | 0.999931 | @@ -379,17 +379,16 @@
og(level
-
/*, item
@@ -571,17 +571,16 @@
rtial(fn
-
/*, firs
|
aa2e8ff532a1e57d696f30ea8fa857e39f6e2a42 | Add log.wrap | lib/logger.js | lib/logger.js | var util = require('util');
var levels = [
'silly',
'input',
'verbose',
'prompt',
'debug',
'http',
'info',
'data',
'help',
'warn',
'error'
];
levels.forEach(function(level) {
exports[level] = function(msg) {
console.log(
level + ':',
util.format.apply(
this,
[msg].concat([].slice.call(arguments, 1))));
};
});
| JavaScript | 0 | @@ -422,8 +422,744 @@
%7D;%0A%7D);%0A
+%0Aexports.wrap = function(getPrefix, func) %7B%0A if (typeof getPrefix != 'function') %7B%0A var msg = getPrefix;%0A getPrefix = function() %7B%0A return msg;%0A %7D;%0A %7D%0A%0A return function() %7B%0A var args = arguments,%0A that = this,%0A prefix = getPrefix.apply(that, args);%0A wrapper = %7B%7D;%0A%0A levels.forEach(function(level) %7B%0A wrapper%5Blevel%5D = function(msg) %7B%0A msg = (prefix ? prefix + ': ' : '') + msg;%0A exports%5Blevel%5D.apply(%0A this,%0A %5Bmsg%5D.concat(%5B%5D.slice.call(arguments, 1)));%0A %7D;%0A %7D);%0A%0A return func.apply(that, %5Bwrapper%5D.concat(%5B%5D.slice.call(args)));%0A %7D;%0A%7D;%0A
|
adc2035d7e8f47e49d9d0ab1da414adff88e139c | Update master.js | lib/master.js | lib/master.js | /* vim: set expandtab tabstop=2 shiftwidth=2 foldmethod=marker: */
"use strict";
var fs = require('fs');
var path = require('path');
var util = require('util');
var Emitter = require('events').EventEmitter;
var PROCESS = process;
var child = require(__dirname + '/child.js');
/* {{{ private function _normalize() */
var _normalize = function (name) {
return name.toString().trim().toLowerCase();
};
/* }}} */
/* {{{ private function mkdir() */
var mkdir = function (dir, mode) {
if ((fs.existsSync || path.existsSync)(dir)) {
return;
}
var p = path.dirname(dir);
if (p && p != dir) {
mkdir(p, mode);
}
fs.mkdirSync(dir, mode || 493/**< 0755*/);
};
/* }}} */
/* {{{ private function _writePidFile() */
var _writePidFile = function (fn) {
mkdir(path.dirname(fn));
fs.writeFileSync(fn, PROCESS.pid);
PROCESS.on('exit', function () {
try {
var pid = fs.readFileSync(fn, 'utf8');
if (Number(pid) === PROCESS.pid) {
fs.unlinkSync(fn);
}
} catch (e) {
}
});
};
/* }}} */
exports.create = function (options) {
var _options = {
'terminate_timeout' : 1000,
'statusflush_interval' : 1000,
'addr': '0.0.0.0'
};
for (var i in options) {
_options[i] = options[i];
}
/**
* @ worker对象列表
*/
var _workers = {};
if (_options.pidfile) {
_writePidFile(_options.pidfile);
}
if (_options.statusfile) {
mkdir(path.dirname(_options.statusfile));
(function statusfile() {
var _stream = fs.createWriteStream(_options.statusfile, {
'flags': 'a+', 'encoding': 'utf8', 'mode': 420 // 0644
});
Object.keys(_workers).forEach(function (i) {
Object.keys(_workers[i].pstatus).forEach(function (p) {
_stream.write(util.format('%d:\t%s\t%s\t%j\n',
process.pid, i, p, _workers[i].pstatus[p]));
});
});
_stream.end();
setTimeout(statusfile, _options.statusflush_interval);
})();
}
var Master = function () {
Emitter.call(this);
var _self = this;
PROCESS.on('SIGHUB', function () {
_self.emit('signal', 1, 'SIGHUB');
});
PROCESS.on('exit', function () {
_self.shutdown('SIGKILL');
});
PROCESS.on('SIGTERM', function (signal, code) {
_self.emit('signal', code || 15, signal || 'SIGTERM');
_self.shutdown('SIGTERM');
setTimeout(function () {
PROCESS.exit(0);
}, _options.terminate_timeout);
});
PROCESS.on('SIGINT', function () {
PROCESS.emit('SIGTERM', 'SIGINT', 2);
});
PROCESS.on('SIGUSR1', function () {
_self.emit('signal', 30, 'SIGUSR1');
_self.reload();
});
};
util.inherits(Master, Emitter);
/* {{{ public prototype register() */
Master.prototype.register = function (name, file, options, argv) {
name = _normalize(name);
if (_workers[name]) {
_workers[name].removeAllListeners();
_workers[name].stop('SIGKILL');
}
argv = Array.isArray(argv) ? argv : [];
argv.unshift(file);
if (options && options.trace_gc) {
argv.unshift('--trace_gc');
delete options.trace_gc;
}
var _self = this;
var _pair = child.create(argv, options);
_pair.on('fork', function (pid) {
_self.emit('fork', name, pid);
});
_pair.on('exit', function (pid, code, signal) {
_self.emit('quit', name, pid, code, signal);
});
_pair.on('giveup', function (n, p) {
_self.emit('giveup', name, n, p);
});
_pair.on('broadcast', function (to, msg, pid, xxx) {
to = _normalize(to);
if (_workers[to]) {
_workers[to].broadcast(msg, name, pid, xxx);
}
});
_pair.on('disconnect', function (pid, worker) {
_self.emit('disconnect', name, pid, worker);
});
_workers[name] = _pair;
return _pair;
};
/* }}} */
Master.prototype.dispatch = function () {
Object.keys(_workers).forEach(function (i) {
_workers[i].start();
});
};
Master.prototype.reload = function () {
Object.keys(_workers).forEach(function (i) {
_workers[i].reload();
});
};
Master.prototype.shutdown = function (signal) {
Object.keys(_workers).forEach(function (i) {
_workers[i].stop(signal || 'SIGTERM');
});
};
Master.prototype.fork = function (name) {
var _pair = _workers[name];
return _pair.fork();
};
return new Master();
};
if (process.env.NODE_ENV === 'test') {
exports.mock = function (p) {
PROCESS = p;
};
}
| JavaScript | 0.000001 | @@ -1164,18 +1164,16 @@
00,%0A
-
'addr':
|
74417176676690b677895a7fef5adc722e753139 | Fix module require context issue. | lib/mockit.js | lib/mockit.js | var mod = require('module');
module.exports = function (path, mocks) {
// Reference to the original require function
var require = mod.prototype.require;
// Overwrite the require function
mod.prototype.require = function (path) {
// Return a mock object, if present. Otherwise, call the original require
// function in the current file's module context
return mocks[path] || require.call(this, path);
};
// Require the module. Our overwritten require function will be used for its
// module dependencies
var file = require(path);
// Restore the original require function
mod.prototype.require = require;
// Return the module
return file;
};
| JavaScript | 0 | @@ -445,16 +445,45 @@
e module
+ in the parent module context
. Our ov
@@ -491,32 +491,37 @@
rwritten require
+%0A //
function will b
@@ -534,21 +534,16 @@
for its
-%0A //
module
@@ -575,17 +575,37 @@
require
-(
+.call(module.parent,
path);%0A%0A
|
e599d29787d4bb70b24b1b219482eff49f36d9cd | Write the post_body to OAuth2 PUT requests | lib/oauth2.js | lib/oauth2.js | var querystring= require('querystring'),
crypto= require('crypto'),
https= require('https'),
http= require('http'),
URL= require('url'),
OAuthUtils= require('./_utils');
exports.OAuth2= function(clientId, clientSecret, baseSite, authorizePath, accessTokenPath, customHeaders) {
this._clientId= clientId;
this._clientSecret= clientSecret;
this._baseSite= baseSite;
this._authorizeUrl= authorizePath || "/oauth/authorize";
this._accessTokenUrl= accessTokenPath || "/oauth/access_token";
this._accessTokenName= "access_token";
this._authMethod= "Bearer";
this._customHeaders = customHeaders || {};
this._useAuthorizationHeaderForGET= false;
}
// This 'hack' method is required for sites that don't use
// 'access_token' as the name of the access token (for requests).
// ( http://tools.ietf.org/html/draft-ietf-oauth-v2-16#section-7 )
// it isn't clear what the correct value should be atm, so allowing
// for specific (temporary?) override for now.
exports.OAuth2.prototype.setAccessTokenName= function ( name ) {
this._accessTokenName= name;
}
// Sets the authorization method for Authorization header.
// e.g. Authorization: Bearer <token> # "Bearer" is the authorization method.
exports.OAuth2.prototype.setAuthMethod = function ( authMethod ) {
this._authMethod = authMethod;
};
// If you use the OAuth2 exposed 'get' method (and don't construct your own _request call )
// this will specify whether to use an 'Authorize' header instead of passing the access_token as a query parameter
exports.OAuth2.prototype.useAuthorizationHeaderforGET = function(useIt) {
this._useAuthorizationHeaderForGET= useIt;
}
exports.OAuth2.prototype._getAccessTokenUrl= function() {
return this._baseSite + this._accessTokenUrl; /* + "?" + querystring.stringify(params); */
}
// Build the authorization header. In particular, build the part after the colon.
// e.g. Authorization: Bearer <token> # Build "Bearer <token>"
exports.OAuth2.prototype.buildAuthHeader= function(token) {
return this._authMethod + ' ' + token;
};
exports.OAuth2.prototype._request= function(method, url, headers, post_body, access_token, callback) {
var http_library= https;
var creds = crypto.createCredentials({ });
var parsedUrl= URL.parse( url, true );
if( parsedUrl.protocol == "https:" && !parsedUrl.port ) {
parsedUrl.port= 443;
}
// As this is OAUth2, we *assume* https unless told explicitly otherwise.
if( parsedUrl.protocol != "https:" ) {
http_library= http;
}
var realHeaders= {};
for( var key in this._customHeaders ) {
realHeaders[key]= this._customHeaders[key];
}
if( headers ) {
for(var key in headers) {
realHeaders[key] = headers[key];
}
}
realHeaders['Host']= parsedUrl.host;
realHeaders['Content-Length']= post_body ? Buffer.byteLength(post_body) : 0;
if( access_token && !('Authorization' in realHeaders)) {
if( ! parsedUrl.query ) parsedUrl.query= {};
parsedUrl.query[this._accessTokenName]= access_token;
}
var queryStr= querystring.stringify(parsedUrl.query);
if( queryStr ) queryStr= "?" + queryStr;
var options = {
host:parsedUrl.hostname,
port: parsedUrl.port,
path: parsedUrl.pathname + queryStr,
method: method,
headers: realHeaders
};
this._executeRequest( http_library, options, post_body, callback );
}
exports.OAuth2.prototype._executeRequest= function( http_library, options, post_body, callback ) {
// Some hosts *cough* google appear to close the connection early / send no content-length header
// allow this behaviour.
var allowEarlyClose= OAuthUtils.isAnEarlyCloseHost(options.host);
var callbackCalled= false;
function passBackControl( response, result ) {
if(!callbackCalled) {
callbackCalled=true;
if( response.statusCode != 200 && (response.statusCode != 301) && (response.statusCode != 302) ) {
callback({ statusCode: response.statusCode, data: result });
} else {
callback(null, result, response);
}
}
}
var result= "";
var request = http_library.request(options, function (response) {
response.on("data", function (chunk) {
result+= chunk
});
response.on("close", function (err) {
if( allowEarlyClose ) {
passBackControl( response, result );
}
});
response.addListener("end", function () {
passBackControl( response, result );
});
});
request.on('error', function(e) {
callbackCalled= true;
callback(e);
});
if( options.method == 'POST' && post_body ) {
request.write(post_body);
}
request.end();
}
exports.OAuth2.prototype.getAuthorizeUrl= function( params ) {
var params= params || {};
params['client_id'] = this._clientId;
params['type'] = 'web_server';
return this._baseSite + this._authorizeUrl + "?" + querystring.stringify(params);
}
exports.OAuth2.prototype.getOAuthAccessToken= function(code, params, callback) {
var params= params || {};
params['client_id'] = this._clientId;
params['client_secret'] = this._clientSecret;
params['type']= 'web_server';
var codeParam = (params.grant_type === 'refresh_token') ? 'refresh_token' : 'code';
params[codeParam]= code;
var post_data= querystring.stringify( params );
var post_headers= {
'Content-Type': 'application/x-www-form-urlencoded'
};
this._request("POST", this._getAccessTokenUrl(), post_headers, post_data, null, function(error, data, response) {
if( error ) callback(error);
else {
var results;
try {
// As of http://tools.ietf.org/html/draft-ietf-oauth-v2-07
// responses should be in JSON
results= JSON.parse( data );
}
catch(e) {
// .... However both Facebook + Github currently use rev05 of the spec
// and neither seem to specify a content-type correctly in their response headers :(
// clients of these services will suffer a *minor* performance cost of the exception
// being thrown
results= querystring.parse( data );
}
var access_token= results["access_token"];
var refresh_token= results["refresh_token"];
delete results["refresh_token"];
callback(null, access_token, refresh_token, results); // callback results =-=
}
});
}
// Deprecated
exports.OAuth2.prototype.getProtectedResource= function(url, access_token, callback) {
this._request("GET", url, {}, "", access_token, callback );
}
exports.OAuth2.prototype.get= function(url, access_token, callback) {
if( this._useAuthorizationHeaderForGET ) {
var headers= {'Authorization': this.buildAuthHeader(access_token) }
access_token= null;
}
else {
headers= {};
}
this._request("GET", url, headers, "", access_token, callback );
}
| JavaScript | 0.000177 | @@ -4513,17 +4513,17 @@
%0A%0A if(
-
+(
options.
@@ -4538,16 +4538,44 @@
= 'POST'
+ %7C%7C options.method == 'PUT')
&& post
|
0b46167331d52e666b777cb7a31b6b5d3231da83 | allow $loadUsers to still run if not root, ignoring /etc/shadow. | lib/passwd.js | lib/passwd.js | /*jshint node: true*/
'use strict';
var fs = require('fs'),
Q = require('q'),
u = require('util'),
assert = require('assert'),
_ = require('lodash'),
tmp = require('tmp'),
exec = require('child_process').exec,
PUser = require('./p_user'),
IsAdmin = require('./is_admin');
/**
* Represents the whole of /etc/passwd. Passwd entries are represent within this
* object as this.username = PUser object.
* @constructor
*/
function Passwd () {
}
_.mixin(Passwd.prototype, IsAdmin.prototype);
/**
* loads passwd & shadow files
* @param {string} pfile path to passwd file, defaults to /etc/passwd
* @param {string} pfile path to passwd file, defaults to /etc/passwd
* @returns {promise} resolve of error
*/
Passwd.prototype.$loadUsers = function (pfile, sfile) {
var self = this;
self.file = (pfile ? pfile : (self.file ? self.file : '/etc/passwd'));
self.shadowfile = (sfile ? sfile : (self.sfile ? self.sfile : '/etc/shadow'));
// Clear any existing entries before reloading
_.forEach(self, function (value, key) {
if (value instanceof PUser) {
delete self[key];
}
});
return Q.nfcall(fs.readFile, self.file)
.then(function (data) {
data
.toString()
.trim()
.split(/\r?\n/)
.map(function (uline) {
var col = uline.split(':');
var puser = new PUser({
name: col[0],
pw: col[1],
uid: Number(col[2]),
gid: Number(col[3]),
gecos: col[4],
dir: col[5],
shell: col[6]
}, self);
self[puser.name] = puser;
});
})
.then(function () {
return Q.nfcall(fs.readFile, self.shadowfile)
.then(function (data) {
data
.toString()
.trim()
.split(/\r?\n/)
.map(function (sline) {
var scol = sline.split(':'),
sname = scol[0];
if (!self[sname]) {
console.error('Shadow entry encountered without corresponding passwd entry, ignored:', sname);
return;
}
var suser = self[sname]; //Add to existing user
// handle password field
var spw = scol[1];
suser.spasswd_state = null;
if (spw === '') {
suser.spasswd_state = 'NO PASSWORD';
} else if (spw.charAt(0) === '!') {
suser.spasswd_state = 'LOCKED';
} else if (spw === '*') {
suser.spasswd_state = 'DISABLED';
} else {
suser.spasswd_state = 'SET';
}
suser.slstchg = Number(scol[2]);
suser.smin = Number(scol[3]);
suser.smax = Number(scol[4]);
suser.swarn = Number(scol[5]);
suser.sinact = Number(scol[6]);
suser.sexpire = Number(scol[7]);
suser.sflag = scol[8];
});
});
});
};
/**
* add a new user
* @throws {Error} Error
* @param {object} puser PUser object
* @returns {promise}
*
* var foo = new PUser({
* name: 'foo',
* uid: 32000,
* gid: 8,
* gecos: 'Foo User',
* dir: '/home/foo',
* shell: '/bin/bash'
* });
* passwd.addUser(foo)
* .then(function () { ...
*/
Passwd.prototype.$addUser = function (puser) {
assert(puser !== undefined);
var self = this;
if (!this.isAdmin()) {
throw new Error('Superuser privileges are needed for this function');
}
if (!(puser instanceof PUser)) {
throw new Error('puser parameter is not an instance of PUser');
}
var cmd = u.format(
'useradd %s %s %s %s %s %s',
// (puser.pw ? '-p "' + puser.pw + '"' : ''),
(puser.uid ? '-u ' + puser.uid : ''),
(puser.gid ? '-g ' + puser.gid : ''),
(puser.gecos ? '-c "' + puser.gecos + '"' : ''),
(puser.dir ? '-d "' + puser.dir + '"' : ''),
(puser.shell ? '-s "' + puser.shell + '"' : ''),
puser.name
);
return Q.nfcall(exec, cmd)
.then(function (res) {
var stdout = res[0],
stderr = res[1];
return self.$loadUsers()
.then(function () {
if (puser.spw) { // encrypted pw?
return self[puser.name].$chgEncPw(puser.spw);
} else {
return Q.resolve();
}
});
});
};
/**
* delete a user
* @throws {Error} Error
* @param {object|string} puser PUser object or username
* @returns {promise} [stdout, stderr]
*/
Passwd.prototype.$deleteUser = function (puser) {
assert(puser !== undefined);
var self = this,
deferred = Q.defer();
if (!this.isAdmin()) {
throw new Error('Superuser privileges are needed for this function');
}
if (!(puser instanceof PUser) && typeof puser !== 'string') {
throw new Error('puser parameter is not an instance of PUser or a string');
}
var cmd = u.format(
'userdel %s',
(typeof puser === 'string' ? puser : puser.name)
);
exec(cmd, function (err, stdout, stderr) {
if (err) {
return deferred.reject(err);
}
deferred.resolve(self.$loadUsers());
});
return deferred.promise;
};
/**
* return a cleansed hash of values from the PUser objects in Passwd
* @returns {object} hash of passwd entries, cleansed of PUser methods etc
*/
Passwd.prototype.$cleansed = function () {
var puser = new PUser();
var hash = {};
_.each(this, function (v, k) {
_.each(v, function (v2, k2) {
if (puser.fields[k2] || puser.sfields[k2]) {
if (!hash[k]) {
hash[k] = {};
}
hash[k][k2] = v2;
}
});
});
return hash;
};
module.exports = Passwd;
| JavaScript | 0 | @@ -894,16 +894,42 @@
swd'));%0A
+ if (self.isAdmin()) %7B%0A
self.s
@@ -1000,16 +1000,20 @@
adow'));
+%0A %7D
%0A%0A // C
@@ -1632,24 +1632,72 @@
nction () %7B%0A
+ if (!self.shadowfile) %7B%0A return;%0A %7D%0A
return Q
|
0be426c3ef8e80a2c4466ec48e445e8859cc9b8f | Initialize returned an out of scope reference via the callback at times. | lib/plugin.js | lib/plugin.js | /**
* Copyright 2015, Marnus Weststrate
* Copyrights licensed under the MIT License. See the accompanying LICENSE file for terms.
*/
var _ = require('lodash');
var Waterline = require('waterline');
var Promise = require('es6-promise').Promise;
var buildOrm = require('./buildOrm');
/**
* Creates a new `WaterlineModelsPlugin` instance. Configuration options and/or client adapters modules
* can optionally be provided. It is important that these adapters be required statically and included
* in the JS bundle sent to the client.
*
* @param {{modelDefaults: Object, models: Object|Array, connections: Object}} options ORM configuration options.
* @param {Object|Array} clientAdapters An object/array of adapter modules for use on the client.
* @returns {Object} The plugin instance.
*/
module.exports = function waterlineModelsPlugin(options, clientAdapters) {
/**
* The current final configuration to use when initializing the ORM.
* @type {{modelDefaults: Object, models: Object|Array, connections: Object}}
*/
var config = {};
var common = {};
var server = {};
var client = {};
// ORM
var waterlineModels = {};
var waterline;
// Handle constructor options
if (options) {
if (!clientAdapters && !options.common && !options.server && !options.client) {
clientAdapters = options;
} else {
processOptions(options);
}
}
/**
* A handler for processing a combined options object.
*
* @param {Object} options
*/
function processOptions(options) {
_.merge(common, options.common);
_.merge(server, options.server);
_.merge(client, options.client);
config = _.merge({}, common, server);
}
/**
* @class WaterlineModelsPlugin
*/
var WaterlineModelsPlugin = {
name: 'WaterlineModelsPlugin',
/**
* Called to plug the FluxContext.
* @method plugContext
* @returns {Object}
*/
plugContext: function() {
return {
/**
* Provides the `models` dictionary on the action context. This can be used to initiate async
* queries or updates on models via the connections/adapters with the various Waterline methods.
*
* @param {Object} actionContext
*/
plugActionContext: function(actionContext) {
actionContext.models = waterlineModels;
},
/**
* Adds the `getModelConstructor(identity)` method to the store context which can be used
* to create a record instance with instance methods from a simple record data object.
*
* @param {Object} storeContext
*/
plugStoreContext: function(storeContext) {
storeContext.getModelConstructor = function(identity) {
if (process.env.NODE_ENV !== "production") {
if (!waterlineModels[identity]) {
throw new Error('Attempting to retrieve a constructor for unknown identity: ' + identity);
}
}
return waterlineModels[identity]._model;
};
}
};
},
/**
* Pass ORM configuration options. See the main README.md file for full detail on the possible
* configuration options, and review the
* [Waterline ORM documentation](https://github.com/balderdashy/waterline-docs) for info on model
* definitions.
*
* Options passed will be merged with any previous configuration, include that done via the
* plugin constructor parameters.
*
* @param {Object} options
* @returns {WaterlineModelsPlugin} this
*/
configure: function(options) {
if (process.env.NODE_ENV !== "production") {
if (!_.isEmpty(waterlineModels)) {
throw new Error('Attempted to configure an initialized ORM.');
}
}
processOptions(options);
return this;
},
/**
* Initializing the ORM creates a Waterline instance and Waterline Collection instances for the various
* model definitions which are exposed on `actionContext.models`. The Collection/Model instances are
* also returned via the Node style callback or returned promise.
*
* Before the `rehydrate()` method of the plugin is called the ORM will be initialized using the `server`
* configuration. After rehydration the `client` configuration will be used; this means all configuration
* must be completed before rehydrating the application state on the client. If `clientAdapters` were
* passed to the plugin constructor the ORM is initialized automatically and the method needn't be called,
* otherwise it should be called in the Fluxible `app.rehydrate()` function callback.
*
* All adapters used by the configured connections should be provided.
*
* @param {Object} adapters Adapters used to initialize the ORM.
* @param {Function} [cb] Optional Node style callback receiving initialized models: `function(err, ormModels) {}`
* @returns {Promise} Resolving to the initialized models.
*/
initialize: function(adapters, cb) {
var promise = new Promise(function(resolve, reject) {
waterline = new Waterline();
buildOrm(waterline, config, adapters, function(err, ormModels) {
if (err) {
return reject(err);
}
WaterlineModelsPlugin.setExternalModels(ormModels);
resolve(ormModels);
});
});
if (cb) {
promise.then(function(ormModels) {
cb(null, ormModels);
}, function(err) {
cb(err);
});
}
return promise;
},
/**
* Closes all open connections/adapters.
*
* @param {Function} cb A Node style cb for the async operation, possibly returning an error.
*/
tearDown: function(cb) {
waterline ? waterline.teardown(cb) : cb();
},
/**
* If the Waterline ORM is initialized externally the initialized Waterline Collections can be set on the
* context without building a new ORM instance. Models are indexed by `identity` and `globalId`, which is
* the camel cased version, if the `globalId` property is set. This method may be called multiple times,
* models are merged with any previous models and will overwrite duplicates.
*
* @param {Array|Object} models An array or object containing initialized Waterline Collections.
*/
setExternalModels: function(models) {
_.each(models, function(model) {
if (process.env.NODE_ENV !== "production") {
if (!model.identity) {
throw new Error('Attempting to set a model without an \'identity\' attribute.');
}
}
waterlineModels[model.identity] = model;
if (model.globalId) {
waterlineModels[model.globalId] = model;
}
});
},
/**
* Dehydrate the common and client configuration options.
*/
dehydrate: function() {
return {
common: common,
client: client
};
},
/**
* The local `common` config is merged with the config from the dehydrated state. The local `client`
* config is handled similarly. Finally all these options are merged together to obtain the final
* client config.
*
* If client adapters were provided to the constructor the ORM is initialized, otherwise a call
* to `initialize()` with the client adapters is necessary.
*
* @param {Object} state
* @param {Function} cb A callback, marking the rehydrate operation as async.
*/
rehydrate: function(state, cb) {
config = _.merge(state.common, common, state.client, client);
clientAdapters ? this.initialize(clientAdapters, cb) : cb();
}
};
return WaterlineModelsPlugin;
};
| JavaScript | 0 | @@ -5381,19 +5381,25 @@
resolve(
-orm
+waterline
Models);
@@ -5468,19 +5468,25 @@
unction(
-orm
+waterline
Models)
@@ -5506,19 +5506,25 @@
b(null,
-orm
+waterline
Models);
|
a22b9c0661ba5a5316743945ae01c44625ceb1d4 | make Pubkey idiomatic | lib/pubkey.js | lib/pubkey.js | /**
* Public Key
* ==========
*
* A public key corresponds to a private key. If you have a private key, you
* can find the corresponding public key with Pubkey().fromPrivkey(privkey).
*/
"use strict";
let Point = require('./point');
let bn = require('./bn');
let privkey = require('./privkey');
let Struct = require('./struct');
let Pubkey = function Pubkey(point) {
if (!(this instanceof Pubkey))
return new Pubkey(point);
if (point instanceof Point)
this.point = point;
else if (point) {
let obj = point;
this.fromObject(obj);
}
};
Pubkey.prototype = Object.create(Struct.prototype);
Pubkey.prototype.constructor = Pubkey;
Pubkey.prototype.fromJSON = function(json) {
this.fromBuffer(new Buffer(json, 'hex'));
return this;
};
Pubkey.prototype.toJSON = function() {
return this.toBuffer().toString('hex');
};
Pubkey.prototype.fromPrivkey = function(privkey) {
this.fromObject({
point: Point.getG().mul(privkey.bn),
compressed: privkey.compressed}
);
return this;
};
Pubkey.prototype.fromBuffer = function(buf, strict) {
return this.fromDER(buf, strict);
};
/**
* In order to mimic the non-strict style of OpenSSL, set strict = false. For
* information and what prefixes 0x06 and 0x07 mean, in addition to the normal
* compressed and uncompressed public keys, see the message by Peter Wuille
* where he discovered these "hybrid pubkeys" on the mailing list:
* http://sourceforge.net/p/bitcoin/mailman/message/29416133/
*/
Pubkey.prototype.fromDER = function(buf, strict) {
if (typeof strict === 'undefined')
strict = true;
else
strict = false;
if (buf[0] === 0x04 || (!strict && (buf[0] === 0x06 || buf[0] === 0x07))) {
let xbuf = buf.slice(1, 33);
let ybuf = buf.slice(33, 65);
if (xbuf.length !== 32 || ybuf.length !== 32 || buf.length !== 65)
throw new Error('Length of x and y must be 32 bytes');
let x = bn(xbuf);
let y = bn(ybuf);
this.point = Point(x, y);
this.compressed = false;
} else if (buf[0] === 0x03) {
let xbuf = buf.slice(1);
let x = bn(xbuf);
this.fromX(true, x);
this.compressed = true;
} else if (buf[0] === 0x02) {
let xbuf = buf.slice(1);
let x = bn(xbuf);
this.fromX(false, x);
this.compressed = true;
} else {
throw new Error('Invalid DER format pubkey');
}
return this;
};
Pubkey.prototype.fromString = function(str) {
this.fromDER(new Buffer(str, 'hex'));
return this;
};
Pubkey.prototype.fromX = function(odd, x) {
if (typeof odd !== 'boolean')
throw new Error('Must specify whether y is odd or not (true or false)');
this.point = Point.fromX(odd, x);
return this;
};
Pubkey.prototype.toBuffer = function() {
let compressed = typeof this.compressed === 'undefined' ? true : this.compressed;
return this.toDER(compressed);
};
Pubkey.prototype.toDER = function(compressed) {
compressed = typeof this.compressed === 'undefined' ? compressed : this.compressed;
if (typeof compressed !== 'boolean')
throw new Error('Must specify whether the public key is compressed or not (true or false)');
let x = this.point.getX();
let y = this.point.getY();
let xbuf = x.toBuffer({size: 32});
let ybuf = y.toBuffer({size: 32});
let prefix = undefined;
if (!compressed) {
prefix = new Buffer([0x04]);
return Buffer.concat([prefix, xbuf, ybuf]);
} else {
let odd = ybuf[ybuf.length - 1] % 2;
if (odd)
prefix = new Buffer([0x03]);
else
prefix = new Buffer([0x02]);
return Buffer.concat([prefix, xbuf]);
}
};
Pubkey.prototype.toString = function() {
let compressed = typeof this.compressed === 'undefined' ? true : this.compressed;
return this.toDER(compressed).toString('hex');
};
/**
* Translated from bitcoind's IsCompressedOrUncompressedPubKey
*/
Pubkey.isCompressedOrUncompressed = function(buf) {
if (buf.length < 33) {
// Non-canonical public key: too short
return false;
}
if (buf[0] === 0x04) {
if (buf.length !== 65)
// Non-canonical public key: invalid length for uncompressed key
return false;
} else if (buf[0] === 0x02 || buf[0] === 0x03) {
if (buf.length !== 33)
// Non-canonical public key: invalid length for compressed key
return false;
} else {
// Non-canonical public key: neither compressed nor uncompressed
return false;
}
return true;
}
//https://www.iacr.org/archive/pkc2003/25670211/25670211.pdf
Pubkey.prototype.validate = function() {
if (this.point.isInfinity())
throw new Error('point: Point cannot be equal to Infinity');
if (this.point.eq(Point(bn(0), bn(0))))
throw new Error('point: Point cannot be equal to 0, 0');
this.point.validate();
return this;
};
module.exports = Pubkey;
| JavaScript | 0.004528 | @@ -236,18 +236,18 @@
');%0Alet
-bn
+BN
= requi
@@ -262,44 +262,8 @@
');%0A
-let privkey = require('./privkey');%0A
let
@@ -1859,34 +1859,34 @@
');%0A let x =
-bn
+BN
(xbuf);%0A let
@@ -1889,18 +1889,18 @@
let y =
-bn
+BN
(ybuf);%0A
@@ -2023,34 +2023,34 @@
1);%0A let x =
-bn
+BN
(xbuf);%0A this
@@ -2167,18 +2167,18 @@
let x =
-bn
+BN
(xbuf);%0A
@@ -4574,17 +4574,17 @@
int(
-bn
+BN
(0),
-bn
+BN
(0))
|
509798dc57197337010116431fb1b0a742eded9b | remove TODO comment | lib/reader.js | lib/reader.js |
/**
* Module dependencies.
*/
var util = require('util');
var assert = require('assert');
var Parser = require('stream-parser');
var Transform = require('readable-stream/transform');
var debug = require('debug')('wave:reader');
var inherits = util.inherits;
var f = util.format;
var formats = {
WAVE_FORMAT_PCM: 0x0001, // PCM
WAVE_FORMAT_IEEE_FLOAT: 0x0003, // IEEE float
WAVE_FORMAT_ALAW: 0x0006, // 8-bit ITU-T G.711 A-law
WAVE_FORMAT_MULAW: 0x0007, // 8-bit ITU-T G.711 µ-law
WAVE_FORMAT_EXTENSIBLE: 0xFFFE // Determined by SubFormat
};
/**
* Module exports.
*/
module.exports = Reader;
/**
* The `Reader` class accepts a WAV audio file written to it and outputs the raw
* audio data with the WAV header stripped (most of the time, PCM audio data will
* be output, depending on the `audioFormat` property).
*
* A `"format"` event gets emitted after the WAV header has been parsed.
*
* @param {Object} opts optional options object
* @api public
*/
function Reader (opts) {
if (!(this instanceof Reader)) {
return new Reader(opts);
}
Transform.call(this, opts);
this._bytes(4, this._onRiffID);
}
inherits(Reader, Transform);
/**
* Mixin `Parser`.
*/
Parser(Reader.prototype);
// the beginning of the WAV file
Reader.prototype._onRiffID = function (chunk) {
debug('onRiffID: %o', chunk);
var id = this.riffId = chunk.toString('ascii');
if ('RIFF' === id) {
debug('detected little-endian WAVE file');
this.endianness = 'LE';
this._bytes(4, this._onChunkSize);
} else if ('RIFX' === id) {
debug('detected big-endian WAVE file');
this.endianness = 'BE';
this._bytes(4, this._onChunkSize);
} else {
this.emit('error', new Error(f('bad "chunk id": expected "RIFF" or "RIFX", got %j', id)));
}
};
// size of the WAV
Reader.prototype._onChunkSize = function (chunk) {
debug('onChunkSize: %o', chunk);
this.chunkSize = chunk['readUInt32' + this.endianness](0);
this._bytes(4, this._onFormat);
};
// the RIFF "format", should always be "WAVE"
Reader.prototype._onFormat = function (chunk) {
debug('onFormat: %o', chunk);
this.waveId = chunk.toString('ascii');
if ('WAVE' === this.waveId) {
this._bytes(4, this._onSubchunk1ID);
} else {
this.emit('error', new Error(f('bad "format": expected "WAVE", got %j', this.waveId)));
}
};
// size of the "subchunk1" (the header)
Reader.prototype._onSubchunk1ID = function (chunk) {
debug('onSubchunk1ID: %o', chunk);
var subchunk1ID = chunk.toString('ascii');
this.chunkId = subchunk1ID;
if ('fmt ' === subchunk1ID) {
this._bytes(4, this._onSubchunk1Size);
} else {
this.emit('error', new Error(f('bad "fmt id": expected "fmt ", got %j', subchunk1ID)));
}
};
Reader.prototype._onSubchunk1Size = function (chunk) {
debug('onSubchunk1Size: %o', chunk);
this.subchunk1Size = chunk['readUInt32' + this.endianness](0);
// TODO: assert should be 16 for PCM
this._bytes(this.subchunk1Size, this._onSubchunk1);
};
Reader.prototype._onSubchunk1 = function (chunk) {
debug('onSubchunk1: %o', chunk);
// TODO: support formats other than PCM?
this.audioFormat = chunk['readUInt16' + this.endianness](0);
this.channels = chunk['readUInt16' + this.endianness](2);
this.sampleRate = chunk['readUInt32' + this.endianness](4);
this.byteRate = chunk['readUInt32' + this.endianness](8); // useless...
this.blockAlign = chunk['readUInt16' + this.endianness](12); // useless...
this.bitDepth = chunk['readUInt16' + this.endianness](14);
this.signed = this.bitDepth != 8;
var format = {
audioFormat: this.audioFormat,
endianness: this.endianness,
channels: this.channels,
sampleRate: this.sampleRate,
byteRate: this.byteRate,
blockAlign: this.blockAlign,
bitDepth: this.bitDepth,
signed: this.signed
};
switch (format.audioFormat) {
case formats.WAVE_FORMAT_PCM:
// default, common case. don't need to do anything.
break;
case formats.WAVE_FORMAT_IEEE_FLOAT:
format.float = true;
break;
case formats.WAVE_FORMAT_ALAW:
format.alaw = true;
break;
case formats.WAVE_FORMAT_MULAW:
format.ulaw = true;
break;
}
this.emit('format', format);
this._bytes(4, this._onSubchunk2ID);
};
Reader.prototype._onSubchunk2ID = function (chunk) {
debug('onSubchunk2ID: %o', chunk);
var subchunk2ID = chunk.toString('ascii');
if ('data' === subchunk2ID) {
this._bytes(4, this._onSubchunk2Size);
} else {
this.emit('error', new Error(f('bad "data" chunk: expected "data", got %j', subchunk2ID)));
}
};
// size of the remaining data in this WAV file
Reader.prototype._onSubchunk2Size = function (chunk) {
debug('onSubchunk2Size: %o', chunk);
this.subchunk2Size = chunk['readUInt32' + this.endianness](0);
// even though the WAV file reports a remaining byte length, in practice it
// can't really be trusted since in streaming situations where the WAV file is
// being generated on-the-fly, the number of remaining bytes would be impossible
// to know beforehand. For this reason, some encoders write `0` for the byte
// length here... In any case, we are just gonna pass through the rest of the
// stream until EOF.
this._passthrough(Infinity, this._onEnd);
};
| JavaScript | 0 | @@ -3066,51 +3066,8 @@
k);%0A
- // TODO: support formats other than PCM?%0A
th
|
b155f48fcbcba8df5de3a96a373cbf4f5dcd2013 | Add URL Routes for Blog & Projects | lib/router.js | lib/router.js | Router.configure({
layoutTemplate: 'layout'
});
Router.map(function(){
this.route('home', {
path: '/',
template: 'home'
});
// Other routes
this.route('about');
this.route('work');
this.route('contact');
this.route('blog', {
path: '/blog',
template: 'blog'
});
});
| JavaScript | 0 | @@ -170,24 +170,25 @@
e('about');%0A
+%0A
this.route
@@ -193,24 +193,25 @@
te('work');%0A
+%0A
this.route
@@ -222,16 +222,27 @@
ntact');
+%0A%0A // BLOG
%0A this.
@@ -276,16 +276,16 @@
/blog',%0A
-
temp
@@ -302,13 +302,601 @@
g'%0A %7D);
+%0A%0A this.route('list_posts', %7B%0A path: '/admin/posts',%0A template: 'list_posts'%0A %7D);%0A%0A this.route('add_post', %7B%0A path: '/admin/posts/add',%0A template: 'add_post'%0A %7D);%0A%0A this.route('edit_post', %7B%0A path: '/admin/posts/:id/edit',%0A template: 'edit_post'%0A %7D);%0A%0A // PROJECTS%0A this.route('list_projects', %7B%0A path: '/admin/projects',%0A template: 'list_projects'%0A %7D);%0A%0A this.route('add_project', %7B%0A path: '/admin/projects/add',%0A template: 'add_project'%0A %7D);%0A this.route('edit_project', %7B%0A path: '/admin/projects/:id/edit',%0A template: 'edit_project'%0A %7D);
%0A%7D);%0A
|
b92ed91b33a4f7574973e34e8cf8a0d0d03ae3e7 | Fix userProfile route | lib/router.js | lib/router.js | Router.configure({
layoutTemplate: 'layout',
loadingTemplate: 'loading',
notFoundTemplate: 'notFound'
});
Router.route('/', {
name: 'projectsList',
waitOn: function() {
return Meteor.subscribe('Projects');
}
});
Router.route('projects/new', {
name: 'projectCreate'
});
Router.route('user/:_id', {
name: 'userProfile',
data: function() {
Meteor.users.findOne({_id: this.params._id});
}
});
| JavaScript | 0.000242 | @@ -303,18 +303,21 @@
('user/:
-_i
+userI
d', %7B%0A
@@ -362,17 +362,22 @@
) %7B%0A
-
+return
Meteor.
@@ -408,18 +408,21 @@
.params.
-_i
+userI
d%7D);%0A %7D
|
06667620514ef981ab9538ddd187ef8e8925321e | Add a comment about `rateRec` and its friend | lib/routes.js | lib/routes.js | 'use strict';
var _trader;
// Make sure these are higher than polling interval
// or there will be a lot of errors
var STALE_TICKER = 180000;
var STALE_BALANCE = 180000;
Error.prototype.toJSON = function () {
var self = this;
var ret = {};
Object.getOwnPropertyNames(self).forEach(function (key) {
ret[key] = self[key];
});
return ret;
};
var poll = function(req, res) {
if (req.device.unpair) {
return res.json({
unpair: true
});
}
var rateRec = _trader.rate(req.params.currency);
var satoshiBalanceRec = _trader.balance;
if (!rateRec || !satoshiBalanceRec)
return res.json({err: 'Server initializing'});
if (Date.now() - rateRec.timestamp > STALE_TICKER)
return res.json({err: 'Stale ticker'});
if (Date.now() - rateRec.timestamp > STALE_BALANCE)
return res.json({err: 'Stale balance'});
var rate = rateRec.rate;
res.json({
err: null,
rate: rate * _trader.config.exchanges.settings.commission,
fiat: _trader.fiatBalance(0, 0),
currency: req.params.currency,
txLimit: parseInt(_trader.config.exchanges.settings.compliance.maximum.limit, 10)
});
};
// TODO need to add in a UID for this trade
var trade = function(req, res) {
api.trade.trade(req.body.fiat, req.body.satoshis, req.body.currency, function(err) {
res.json({err: err});
});
};
var send = function(req, res) {
var fingerprint = req.connection.getPeerCertificate().fingerprint;
api.send.sendBitcoins(fingerprint, req.body, function(err, txHash) {
res.json({err: err, txHash: txHash});
});
};
var pair = function(req, res) {
var token = req.body.token;
var name = req.body.name;
_lamassuConfig.pair(
token,
req.connection.getPeerCertificate().fingerprint,
name,
function(err) {
if (err) res.json(500, { err: err.message });
else res.json(200);
}
);
};
exports.init = function(app, trader, authMiddleware) {
_trader = trader;
app.get('/poll/:currency', authMiddleware, poll);
app.post('/trade', authMiddleware, trade);
app.post('/send', authMiddleware, send);
app.post('/pair', pair);
return app;
};
| JavaScript | 0 | @@ -559,16 +559,166 @@
lance;%0A%0A
+ // %60rateRec%60 and %60satoshiBalanceRec%60 are both objects, so there's no danger%0A // of misinterpreting rate or balance === 0 as 'Server initializing'.%0A
if (!r
|
51176ee76b23fcbebe88f8337bbc4d2f23f684b8 | send notifs to users without subscription keys | lib/routes.js | lib/routes.js | const express = require('express');
const jsonwebtoken = require('jsonwebtoken');
const firebase = require('firebase');
const webpush = require('web-push');
const middlewares = require('./middlewares');
const config = require('../config');
firebase.initializeApp({
databaseURL: config.get('FIREBASE_DATABASE_URL')
});
webpush.setGCMAPIKey(config.get('GCM_API_KEY'));
const database = firebase.database();
const router = new express.Router();
router.use('/static', express.static(`${__dirname}/../static`));
router.use('/manifest.json', express.static(`${__dirname}/../static/manifest.json`));
router.use('/service-worker.js', express.static(`${__dirname}/../static/javascripts/service-worker.js`));
router.get('/', (req, res) => res.render('index.html'));
router.get('/messages', (req, res) => res.render('messages.html'));
router.post('/login', (req, res) => {
const refkey = req.body.email.replace(/[@.]/g, '-');
database.ref(`users/${refkey}/name`).set(req.body.name);
database.ref(`users/${refkey}/email`).set(req.body.email);
database.ref(`users/${refkey}/avatar`).set(req.body.avatar);
const jwtoken = jsonwebtoken.sign(req.body, config.get('JWT_SECRET'));
res.json({ jwtoken: jwtoken });
});
router.post('/message',
middlewares.verifyAuthToken,
(req, res) => {
const message = {
content: req.body.message,
author: req.user.email.replace(/[@.]/g, '-'),
when: (new Date()).valueOf()
};
const reference = database.ref('messages').push(message);
database.ref('users').once('value', data => {
const users = data.val();
for (let key in users) {
const user = users[key];
if (user.subscription) {
const payload = JSON.stringify({ user: req.user, message: message });
webpush.sendNotification(user.subscription, payload);
}
}
res.json({ key: reference.key });
});
}
);
router.post('/subscribe',
middlewares.verifyAuthToken,
(req, res) => {
const subscription = req.body;
const refkey = req.user.email.replace(/[@.]/g, '-');
database.ref(`users/${refkey}/subscription`).set(subscription).then(_ => {
res.json({ success: true });
});
}
);
router.post('/unsubscribe',
middlewares.verifyAuthToken,
(req, res) => {
const refkey = req.user.email.replace(/[@.]/g, '-');
database.ref(`users/${refkey}/subscription`).remove().then(_ => {
res.json({ success: true });
});
}
);
module.exports = router;
| JavaScript | 0 | @@ -1742,16 +1742,17 @@
if (
+!
user.sub
@@ -1760,32 +1760,77 @@
cription) %7B%0A
+ continue;%0A %7D%0A%0A
@@ -1895,24 +1895,70 @@
message %7D);%0A
+ if (user.subscription.keys) %7B%0A
@@ -2019,16 +2019,691 @@
yload);%0A
+ %7D else %7B%0A const url = 'https://android.googleapis.com/gcm/send/';%0A const subscriptionId = user.subscription.endpoint.replace(url, '');%0A const options = %7B%0A url: url,%0A headers: %7B%0A 'Authorization': %60key=$%7Bconfig.get('GCM_API_KEY')%7D%60%0A %7D,%0A body: %7B%0A registration_ids: subscriptionId,%0A notification: payload%0A %7D,%0A json: true%0A %7D;%0A request.post(options);%0A
|
f3350515065d2a7f5c869980aaa0f1947ff450d1 | fix call to process jobs | lib/runner.js | lib/runner.js | 'use strict';
import Agenda from 'agenda';
import config from 'config';
import logger from '@hoist/logger';
import {
Publisher
}
from '@hoist/broker';
import {
Event,
EventMetric,
_mongoose
}
from '@hoist/model';
import Moment from 'moment';
import uuid from 'uuid';
import Bluebird from 'bluebird';
Bluebird.promisifyAll(_mongoose);
class Runner {
constructor() {
this._publisher = new Publisher();
this._logger = logger.child({
cls: this.constructor.name
});
}
processEvents(job, done) {
this._logger.info({
job: job
}, 'processing schedule job');
var data = job.attrs.data;
if (process.env.NODE_ENV === 'production') {
if (data.application !== 'demo-connect-app') {
return Promise.resolve();
}
}
return Promise.resolve()
.then(() => {
Promise.all(data.events.map((eventName) => {
return this.createEvent(data, eventName);
}));
}).then(() => {
done();
}).catch((err) => {
this._logger.error(err);
done(err);
});
}
createEvent(data, eventName) {
var ev = new Event({
eventId: uuid.v4().split('-').join(''),
applicationId: data.application,
eventName: eventName,
environment: data.environment,
correlationId: require('uuid').v4()
});
this._logger.info({
eventId: ev.messageId,
applicationId: ev.applicationId,
correlationId: ev.correlationId,
eventName: eventName
}, 'raising scheduled event');
return this._publisher.publish(ev)
.then(() => {
var raisedDate = new Moment();
var update = {
$inc: {}
};
update.$inc.totalRaised = 1;
update.$inc['raised.' + raisedDate.utc().minutes()] = 1;
EventMetric.updateAsync({
application: ev.applicationId,
environment: 'live',
eventName: ev.eventName,
timestampHour: raisedDate.utc().startOf('hour').toDate()
}, update, {
upsert: true
}).catch((err) => {
this._logger.alert(err);
this._logger.error(err);
});
return ev;
})
.catch((err) => {
err.eventName = eventName;
this._logger.error(err, 'unable to publish event');
this._logger.alert(err, data.application, {
source: 'Runner#createEvent',
eventName: eventName
});
});
}
start() {
return _mongoose.connectAsync(config.get('Hoist.mongo.core.connectionString')).
then(() => {
this._agenda = new Agenda({
db: {
address: config.get('Hoist.mongo.core.connectionString')
}
});
Bluebird.promisifyAll(this._agenda);
this._agenda.define('create:event', this.processEvents);
this._agenda.start();
logger.info('waiting on schedule');
});
}
stop() {
return this._agenda.stopAsync().then(() => {
delete this._agenda;
return _mongoose.disconnectAsync();
});
}
}
export default Runner;
| JavaScript | 0 | @@ -2770,26 +2770,78 @@
t',
-this.processEvents
+(job, done) =%3E %7B%0A return this.processEvents(job, done);%0A %7D
);%0A
|
f074c2e2ec4e389e594c508c9f387eb8f67b38ff | Fix up comments and formatting | lib/runner.js | lib/runner.js | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//
// Run a pre-validated and pre-prepared test script across a number of (local) workers
//
'use strict';
const os = require('os');
const path = require('path');
const EventEmitter = require('events');
const fork = require('child_process').fork;
const debug = require('debug')('artillery:runner');
const L = require('lodash');
const stats = require('../../artillery-core').stats;
const distribute = require('./dist');
module.exports = createRunner;
function createRunner(script, payload, opts) {
const runner = new Runner(script, payload, opts);
return runner;
}
function Runner(script, payload, opts) {
this._script = script;
this._payload = payload;
this._opts = opts;
this._workers = {};
this.events = new EventEmitter();
this._intermediates = [];
this._allIntermediates = [];
this._currentPhase = -1;
return this;
}
Runner.prototype.run = function run() {
//
// Create worker scripts (distribute the work):
//
let numWorkers = process.env.ARTILLERY_WORKERS || os.cpus().length;
let workerScripts = divideWork(this._script, numWorkers);
// Overwrite statsInterval for workers:
L.each(workerScripts, function(s) {
s.config.statsInterval = 1;
});
debug(JSON.stringify(workerScripts, null, 4));
//
// Create workers:
//
L.each(workerScripts, (script) => {
let workerProcess = fork(path.join(__dirname, 'worker.js'));
this._workers[workerProcess.pid] = {
proc: workerProcess,
isDone: false
};
workerProcess.on('message', this._onWorkerMessage.bind(this));
workerProcess.send({
command: 'run',
opts: {
script: script,
payload: this._payload, // This is going to be inefficient with large payload files
options: this._opts
}
});
});
setInterval(this._sendStats.bind(this), this._script.config.statsInterval * 1000).unref();
return this;
};
Runner.prototype._sendStats = function() {
this.events.emit('stats', stats.combine(this._intermediates).report());
this._intermediates = [];
};
Runner.prototype._onWorkerMessage = function _onWorkerMessage(message) {
if (message.event === 'phaseStarted') {
if (message.phase.index > this._currentPhase) {
this.events.emit('phaseStarted', message.phase);
this._currentPhase = message.phase.index;
}
}
if (message.event === 'phaseCompleted') {
}
if (message.event === 'stats') {
this._intermediates.push(message.stats);
this._allIntermediates.push(message.stats);
}
if (message.event === 'done') {
let worker = this._workers[message.pid];
worker.isDone = true;
worker.proc.kill();
if (this._activeWorkerCount() === 0) {
this._sendStats();
let report = stats.combine(this._allIntermediates).report();
delete report.concurrency;
this.events.emit('done', report);
}
}
};
Runner.prototype._activeWorkerCount = function _activeWorkerCount() {
var pids = Object.keys(this._workers);
var count = pids.length;
pids.forEach((pid) => {
if (this._workers[pid].isDone) {
count--;
}
});
return count;
};
/**
* Create a number of scripts for workers from the script given to use by user.
*/
// TODO: This should be its own module in future
function divideWork(script, numWorkers) {
let newPhases = [];
for (let i = 0; i < numWorkers; i++) {
newPhases.push(L.cloneDeep(script.config.phases));
}
//
// Adjust phase definitions:
//
L.each(script.config.phases, function(phase, phaseSpecIndex) {
if (phase.arrivalRate && phase.rampTo) {
let rates = distribute(phase.arrivalRate, numWorkers);
let ramps = distribute(phase.rampTo, numWorkers);
L.each(rates, function(Lr, i) {
newPhases[i][phaseSpecIndex].arrivalRate = rates[i];
newPhases[i][phaseSpecIndex].rampTo = ramps[i];
});
return;
}
if (phase.arrivalRate && !phase.rampTo) {
let rates = distribute(phase.arrivalRate, numWorkers);
L.each(rates, function(Lr, i) {
newPhases[i][phaseSpecIndex].arrivalRate = rates[i];
});
return;
}
if (phase.arrivalCount) {
let counts = distribute(phase.arrivalCount, numWorkers);
L.each(counts, function(Lc, i) {
newPhases[i][phaseSpecIndex].arrivalCount = counts[i];
});
return;
}
if (phase.pause) {
// nothing to adjust here
return;
}
console.log('Unknown phase spec definition, skipping.\n%j\nThis should not happen', phase);
});
//
// Create new scripts:
//
let newScripts = L.map(L.range(0, numWorkers), function(i) {
let newScript = L.cloneDeep(script);
newScript.config.phases = newPhases[i];
return newScript;
});
//
// TODO: config.http.pool
//
if (!L.isUndefined(L.get(script, 'config.http.pool'))) {
let pools = distribute(script.config.http.pool, numWorkers);
L.each(newScripts, function(s, i) {
s.config.http.pool = pools[i];
});
}
return newScripts;
}
| JavaScript | 0.000009 | @@ -272,16 +272,19 @@
umber of
+%0A//
(local)
@@ -291,16 +291,17 @@
workers
+.
%0A//%0A%0A'us
@@ -1877,29 +1877,16 @@
//
-This is going to be i
+FIXME: I
neff
@@ -1910,21 +1910,16 @@
payload
- file
s%0A
@@ -1977,16 +1977,21 @@
nterval(
+%0A
this._se
@@ -2009,16 +2009,20 @@
d(this),
+%0A
this._s
@@ -4654,16 +4654,37 @@
g.%5Cn%25j%5Cn
+' +%0A '
This sho
@@ -4941,30 +4941,48 @@
//
-TODO: config.http.pool
+Adjust pool settings for HTTP if needed:
%0A /
|
2a2135a22d739597bcbb09a933d334732f315d95 | Handle HTTP auth | lib/runner.js | lib/runner.js | /**
* Fetches remote asset / local CSS file and returns analyzer results
*
* Used internally by analyze-css "binary" to communicate with CommonJS module
*/
'use strict';
var cli = require('cli'),
debug = require('debug')('analyze-css:runner'),
fs = require('fs'),
resolve = require('path').resolve,
analyzer = require('./index'),
preprocessors = new(require('./preprocessors'))(),
url = require('url');
/**
* Return user agent to be used by analyze-css when making HTTP requests (issue #75)
*/
function getUserAgent() {
var format = require('util').format,
version = require('../package').version;
return format(
'analyze-css/%s (%s %s, %s %s)',
version,
process.title,
process.version,
process.platform,
process.arch
);
}
/**
* Simplified implementation of "request" npm module
*
* @see https://www.npmjs.com/package/node-fetch
*/
function request(requestOptions, callback) {
var debug = require('debug')('analyze-css:http'),
fetch = require('node-fetch');
debug('GET %s', requestOptions.url);
debug('Options: %j', requestOptions);
fetch(requestOptions.url, requestOptions).
then(function(resp) {
debug('HTTP %d %s', resp.status, resp.statusText);
debug('Headers: %j', resp.headers._headers);
if (!resp.ok) {
var err = new Error('HTTP request failed: ' + (err ? err.toString() : 'received HTTP ' + resp.status + ' ' + resp.statusText));
callback(err);
} else {
return resp.text(); // a promise
}
}).
then(function(body) {
debug('Received %d bytes of CSS', body.length);
callback(null, body);
}).
catch(function(err) {
debug(err);
callback(err);
});
}
/**
* Module's main function
*/
function runner(options, callback) {
// call CommonJS module
var analyzerOpts = {
'noOffenders': options.noOffenders,
'preprocessor': false,
};
function analyze(css) {
new analyzer(css, analyzerOpts, callback);
}
if (options.url) {
debug('Fetching remote CSS file: %s', options.url);
// @see https://www.npmjs.com/package/node-fetch#options
var requestOptions = {
url: options.url,
// rejectUnauthorized: !options.ignoreSslErrors, // TODO
headers: {
'User-Agent': getUserAgent()
}
};
// TODO
if (options.authUser && options.authPass) {
requestOptions.auth = options.authUser + ':' + options.authPass;
}
request(requestOptions, function(err, css) {
if (err) {
err.code = analyzer.EXIT_URL_LOADING_FAILED;
debug(err);
callback(err);
} else {
analyze(css);
}
});
} else if (options.file) {
// resolve to the full path
options.file = resolve(process.cwd(), options.file);
debug('Loading local CSS file: %s', options.file);
fs.readFile(options.file, {
encoding: 'utf-8'
}, function(err, css) {
if (err) {
err = new Error('Loading CSS file failed: ' + err.toString());
err.code = analyzer.EXIT_FILE_LOADING_FAILED;
debug(err);
callback(err);
} else {
// find the matching preprocessor and use it
if (analyzerOpts.preprocessor === false) {
analyzerOpts.preprocessor = preprocessors.findMatchingByFileName(options.file);
}
// pass the name of the file being analyzed
analyzerOpts.file = options.file;
analyze(css);
}
});
} else if (options.stdin) {
debug('Reading from stdin');
cli.withStdin(analyze);
}
}
module.exports = runner;
| JavaScript | 0.00003 | @@ -2189,20 +2189,59 @@
;%0A%0A%09%09//
-TODO
+@see https://gist.github.com/cojohn/1772154
%0A%09%09if (o
@@ -2301,15 +2301,54 @@
ons.
-auth =
+headers.Authorization = %22Basic %22 + new Buffer(
opti
@@ -2366,11 +2366,11 @@
r +
-':'
+%22:%22
+ o
@@ -2384,16 +2384,44 @@
authPass
+, %22utf8%22).toString(%22base64%22)
;%0A%09%09%7D%0A%0A%09
|
e63537833ee89b8df6573688e8c6258c15580da3 | Exit from runTask method if task not found | lib/runner.js | lib/runner.js | 'use strict';
const argv = require('yargs').argv;
const fs = require('co-fs-extra');
const path = require('path');
const co = require('co');
const VError = require('verror');
const sprintf = require('extsprintf').sprintf;
const Logger = require('shark-logger');
const Storage = require('./storage');
const expand = require('expand');
process.on('uncaughtException', function(error) {
console.error(sprintf('%r', new VError(error, 'global uncaughtException')));
process.exit(1);
});
function SharkRunner(options) {
this.tasks = {};
this.storage = new Storage();
this.setStorageValues(options.storageValues);
this.logger = Logger({
name: 'SharkRunner',
level: Logger.TRACE,
deepLevel: 1
});
var time = this.logger.time().start();
this.logger.trace({ opType: this.logger.OP_TYPE.STARTED }, 'SharkRunner');
process.on('exit', function() {
this.logger.trace({
duration: time.delta(),
opType: this.logger.OP_TYPE.FINISHED
}, 'SharkRunner')
}.bind(this));
}
SharkRunner.prototype = {
constructor: SharkRunner,
getStorageValue: function() {
return this.storage.getValue.apply(this.storage, arguments);
},
setStorageValue: function() {
return this.storage.setValue.apply(this.storage, arguments);
},
setStorageValues: function() {
return this.storage.setValues.apply(this.storage, arguments);
},
collectTasks: function *(tasksPath) {
var time = this.logger.time().start();
this.logger.trace({ opType: this.logger.OP_TYPE.STARTED }, 'collectTasks', tasksPath);
try {
var files = yield expand([
'./*/*.js',
'./*/*/*.js'
], {
cwd: this.getStorageValue('tasksPath')
});
files.filter(function(filePath) {
var fileName = path.basename(filePath, '.js');
var dirName = path.basename(path.dirname(filePath));
var parentDirName = path.basename(path.dirname(path.dirname(filePath)));
var isTask = fileName === dirName;
if (isTask) {
var fullFilePath = path.join(this.getStorageValue('tasksPath'), filePath);
var taskName;
if (parentDirName === '.') {
taskName = fileName;
}
else {
taskName = path.join(parentDirName, fileName);
}
this.tasks[taskName] = fullFilePath;
}
}.bind(this));
}
catch (error) {
throw new VError(error, 'collectTasks error');
}
this.logger.trace({ duration: time.delta(), opType: this.logger.OP_TYPE.FINISHED }, 'collectTasks');
},
runRequestedTasks: function* () {
var taskName = argv._[0];
return yield this.runTask(taskName, this.logger.fields.deepLevel, {});
},
runTask: function *(taskName, deepLevel, options) {
var taskPath = this.tasks[taskName];
if (!taskPath) {
this.logger.warn({
opType: Logger.OP_TYPE.ERROR,
opName: taskName
}, 'task "%s" not found', taskName);
}
var time = this.logger.time().start();
this.logger.info({
opType: Logger.OP_TYPE.STARTED,
opName: taskName,
deepLevel: deepLevel
});
try {
var taskRunner = require(taskPath);
var taskRunnerResult = yield taskRunner.call(
this.getTaskInternalMethods.apply(this, arguments)
);
}
catch (error) {
throw new VError(error, 'runTask error');
}
this.logger.info({
opType: Logger.OP_TYPE.FINISHED,
opName: taskName,
duration: time.delta(),
deepLevel: deepLevel
});
return taskRunnerResult;
},
getTaskInternalMethods: function(taskName, deepLevel, options) {
return {
taskDeepLevel: deepLevel,
options: options || {},
logger: deepLevel === 1 ? this.logger : this.logger.child({
subName: taskName,
deepLevel: deepLevel + 1
}),
runTask: function *(taskName, options) {
try {
return yield this.runTask(taskName, deepLevel, options);
}
catch (error) {
throw new VError(error, 'runner#getTaskInternalMethods runTask error');
}
}.bind(this),
runChildTask: function *(taskName, options) {
try {
return yield this.runTask(taskName, deepLevel + 1, options);
}
catch (error) {
throw new VError(error, 'runner#getTaskInternalMethods runChildTask error');
}
}.bind(this)
};
}
};
module.exports = function(config) {
if (!config || !config.tasksPath) {
throw new VError('config.tasksPath not defined');
}
var shark = new SharkRunner({
storageValues: config
});
co(function *sharkfileSharkRunner() {
yield shark.collectTasks(shark.getStorageValue('tasksPath'));
yield shark.runRequestedTasks();
}).catch(function(error) {
console.error(sprintf('%r', new VError(error, 'sharkfileSharkRunner error')));
process.exit(1);
});
return {
setStorageValue: shark.setStorageValue.bind(shark),
getStorageValue: shark.getStorageValue.bind(shark),
setStorageValues: shark.setStorageValues.bind(shark),
runTask: shark.runTask.bind(shark)
};
};
| JavaScript | 0.000001 | @@ -2845,16 +2845,27 @@
kName);%0A
+%09%09%09return;%0A
%09%09%7D%0A%0A%09%09v
|
45784f1a7c5cacbf1aa769249b52af0a34d479f0 | allow all search sort strings | lib/search.js | lib/search.js | // Copyright 2013 Bowery Software, LLC
/**
* @fileoverview Search builder.
*/
// Module Dependencies.
var assert = require('assert')
var Builder = require('./builder')
/**
* @constructor
*/
function SearchBuilder () {}
require('util').inherits(SearchBuilder, Builder)
/**
* Set collection.
* @param {string} collection
* @return {SearchBuilder}
*/
SearchBuilder.prototype.collection = function (collection) {
assert(collection, 'Collection required.')
this._collection = collection
return this
}
/**
* Set limit.
* @param {number} limit
* @return {SearchBuilder}
*/
SearchBuilder.prototype.limit = function (limit) {
assert(limit, 'Limit required.')
this._limit = limit
return this
}
/**
* Set offset.
* @param {number} offset
* @return {SearchBuilder}
*/
SearchBuilder.prototype.offset = function (offset) {
assert.equal(typeof offset, 'number', 'Offset required.')
this._offset = offset
return this
}
/**
* Set sort.
* @param {string} field
* @param {string} order
* @return {SearchBuilder}
*/
SearchBuilder.prototype.sort = function (field, order) {
assert(field, 'field required')
assert(!!~['asc','desc'].indexOf(order), 'valid order required')
var _sort = 'value.' + field + ':' + order
if (this._sort) this._sort = [this._sort, _sort].join(',')
else this._sort = _sort
return this
}
/**
* Set query.
* @param {string} query
* @return {SearchBuilder}
*/
SearchBuilder.prototype.query = function (query) {
assert(query, 'Query required.')
this._query = query
return this._execute('get')
}
/**
* Execute search.
* @return {Object}
* @protected
*/
SearchBuilder.prototype._execute = function (method) {
assert(this._collection && this._query, 'Collection and query required.')
var pathArgs = [this._collection]
var url = this.getDelegate() && this.getDelegate().generateApiUrl(pathArgs, {
query: this._query,
limit: this._limit,
offset: this._offset,
sort: this._sort
})
return this.getDelegate()['_' + method](url)
}
// Module Exports.
module.exports = SearchBuilder
| JavaScript | 0.000013 | @@ -1157,16 +1157,23 @@
','desc'
+, 'dsc'
%5D.indexO
|
c30044e22b58877872c40d481a9d0b20ad6f2fb4 | make use of the real driver for adding and deleting migration records | lib/seeder.js | lib/seeder.js | var Seed = require('./seed');
var log = require('./log');
var dbmUtil = require('./util');
var Promise = require('bluebird');
var SeederInterface = require( './interface/seederInterface.js');
var internals = {};
Seeder = function (driver, seedsDir, versionControlled, intern) {
this.driver = dbmUtil.reduceToInterface( driver, SeederInterface );
this.seedDir = seedsDir;
this.isVC = versionControlled;
internals = intern;
};
Seeder.prototype = {
seed: function (argv, callback) {
if (this.isVC)
this.up(argv, callback);
else
this._staticSeed(argv.destination, callback);
},
up: function(funcOrOpts, callback) {
if (dbmUtil.isFunction(funcOrOpts)) {
funcOrOpts(this.driver, false, callback);
} else {
this.upToBy(funcOrOpts.destination, funcOrOpts.count, callback);
}
},
down: function(funcOrOpts, callback) {
if (dbmUtil.isFunction(funcOrOpts)) {
funcOrOpts(this.driver, callback);
} else {
this.downToBy(funcOrOpts.count, callback);
}
},
/**
* Statically call two methods from a static seeder.
*
* First: cleanSeeds
* Second: seed
*
* It's highly recommended to not use version controlled seeders at the same
* time as statics. While the cleanSeeds most of the time, the user executes
* truncates or deletes on his database. A VC-Seeder can't detect this
* and thus the state keeps the same, even if all changes of the VC-Seeder
* are gone.
*
* Nevertheless, there is a possiblity to use static seeders together with
* VC-Seeder, if you keep everything organized well at least.
*
* If a single seed is linked with it's tables and databases which it got
* applied to, the state table of the seeds will automatically cleaned up.
*
*/
_staticSeed: function (partialName, callback) {
var self = this;
return Seed.loadFromFilesystem(self.seedDir, function(err, allSeeds) {
if (err) {
callback(err);
return;
}
var toRun = dbmUtil.filterUp(allSeeds, [], partialName);
if (toRun.length === 0) {
log.info('No seeds to run');
callback(null);
return;
}
return Promise.resolve(toRun).each(function(seeder) {
log.verbose('preparing to run up seeder:', seeder.name);
return self.driver.startMigration()
.catch(callback)
.then(function() {
return (Promise.promisify(seeder.up.bind(seeder)))(self.driver, true);
});
})
.catch(callback)
.then(self.driver.endMigration.bind(self.driver))
.catch(callback)
.nodeify(callback);
});
},
upToBy: function(partialName, count, callback) {
var self = this;
return Seed.loadFromFilesystem(self.seedDir, function(err, allMigrations) {
if (err) { callback(err); return; }
return Migration.loadFromDatabase(self.seedDir, self.driver, function(err, completedMigrations) {
if (err) { callback(err); return; }
var toRun = dbmUtil.filterUp(allMigrations, completedMigrations, partialName, count);
if (toRun.length === 0) {
log.info('No seeds to run');
callback(null);
return;
}
return Promise.resolve(toRun).each(function(seeder) {
log.verbose('preparing to run up seeder:', seeder.name);
return self.driver.startMigration()
.then(function() {
var setup = seeder.setup();
if(typeof(setup) === 'function')
setup(internals.seederOptions);
return (Promise.promisify(self.up.bind(self)))(seeder.up.bind(seeder));
})
.then(self.driver.endMigration.bind(self.driver));
})
.catch(function(e) {
throw e;
})
.nodeify(callback);
});
});
},
downToBy: function(count, callback) {
var self = this;
Seed.loadFromDatabase(self.seedDir, self.driver, function(err, completedMigrations) {
if (err) { return callback(err); }
var toRun = dbmUtil.filterDown(completedMigrations, count);
if (toRun.length === 0) {
log.info('No migrations to run');
callback(null);
return;
}
return Promise.resolve(toRun).each(function(seeder) {
log.verbose('preparing to run down seeder:', seeder.name);
return self.driver.startMigration()
.then(function() {
var setup = seeder.setup();
if(typeof(setup) === 'function')
setup(internals.seederOptions);
return (Promise.promisify(self.down.bind(self)))(seeder.down.bind(seeder));
})
.then(self.driver.endMigration.bind(self.driver));
})
.catch(function(e) {
throw e;
})
.nodeify(callback);
});
}
};
module.exports = Seeder;
| JavaScript | 0 | @@ -343,16 +343,41 @@
face );%0A
+ this._driver = driver;%0A
this.s
@@ -2942,32 +2942,33 @@
f.seedDir, self.
+_
driver, function
@@ -3987,24 +3987,25 @@
edDir, self.
+_
driver, func
|
8142db3be22d3fd0971efe7dfc406325b87fd48d | allow config port | lib/server.js | lib/server.js | function start(config) {
var restify = require('restify');
var logger = require('./logger.js');
var os = require('os');
var path = require('path');
var errors = require('./errors.js');
var util = require('util');
// Statics
const APPLICATION_ROOT = path.resolve(__dirname + '/..');
const API_VERSION = require('../api_version');
// Exports
module.exports.APPLICATION_ROOT = APPLICATION_ROOT;
module.exports.hostname = os.hostname();
// Read config
config = config ? require(config) : require('../conf/server.json');
module.exports.config = config;
module.exports.port = config.port;
// Set the process' name
process.title = config.name;
module.exports.title = config.name;
// Set up errors
errors.createErrors();
// Set up logger
var log = logger.createLogger(config.log, process.title);
module.exports.log = log;
// Create Restify Server
var server = restify.createServer({
name: process.title,
version: API_VERSION,
log: log
});
// Set up mdws
var serverMdws = [
// Restify mdws
restify.requestLogger(),
restify.fullResponse(),
restify.acceptParser(server.acceptable),
restify.dateParser(config.allowedClockSkewSeconds),
restify.queryParser(),
restify.bodyParser({ mapParams: false }),
// Custom mdws
function (req, res, next) {
var message = util.format('[%s] [%s] [%s]', req.method, req.href(), req.version());
req.log.info({req: req}, message);
next();
}
];
serverMdws.forEach(function (mdw) {
server.use(mdw);
});
// Log outgoing requests
server.on('after', function (req, res) {
var message = util.format('[%s] [%s] [%s] [%s]',
req.method, req.href(), res.statusCode, req.version());
if (res.statusCode >= 200 && res.statusCode < 500)
req.log.info({res: res, req: req}, message);
else
req.log.error({res: res, req: req}, message);
});
// Log any client or server errors
server.on('error', function (err) {
log.error(err.stack, '[server error] ~ ' + err.name + ' ~ ' + err.message);
});
server.on('clientError', function (err) {
log.error(err.stack, '[client error] ~ ' + err.name + ' ~ ' + err.message);
});
// Handle uncaught exceptions
server.on('uncaughtException', function (req, res, route, err) {
req.log.fatal(err.stack, '[uncaught exception] ~ ' + route.name + ' ~ ' + err.message);
if (!res.finished) {
var e = new errors.UncaughtExceptionError(err.message);
res.json(500, e.body);
res.end();
}
err.handled = true;
});
process.on('uncaughtException', function (err) {
if (err.handled) return;
log.fatal(err.stack, '[uncaught exception] ~ ' + err.name + ' ~ ' + err.message);
});
// Load routes. Config must be loaded first.
var routes = require('./routes');
routes.loadRoutes(server, log);
// Start listening on port
server.listen(config.port, function () {
log.info(server.name + ' listening on ' + server.url);
server.emit('listening', true);
});
return server;
}
module.exports.start = start;
/**
* console.dir is just a wrapper around util.inspect using defaults
* for colourisation and depth.
*
* Replace it with our own wrapper with much deeper inspection and
* colors on the console.
*
* It's just for development since no console.dir calls should be
* left in production code anyway.
*/
(function () {
var util = require('util');
console.dir = function dbg(obj, depth) {
console.log(util.inspect(obj, false, depth || 10, true));
};
})(); | JavaScript | 0.000001 | @@ -597,16 +597,36 @@
s.port =
+ process.env.PORT %7C%7C
config.
|
a7a46070582352acaa44246c3be25ac492af30de | Fix crash due to location of log object | lib/server.js | lib/server.js | var restify = require('restify');
var endpoints = require('./endpoints');
function createServer(options) {
var cnapi = restify.createServer({
name: 'Compute Node API',
log: options.log
});
cnapi.use(restify.acceptParser(cnapi.acceptable));
cnapi.use(restify.authorizationParser());
cnapi.use(restify.dateParser());
cnapi.use(restify.queryParser());
cnapi.use(restify.bodyParser());
cnapi.on('after', restify.auditLogger({log: log}));
var model = options.model;
endpoints.attachTo(cnapi, model);
return cnapi;
}
exports.createServer = createServer;
| JavaScript | 0 | @@ -469,16 +469,22 @@
r(%7Blog:
+cnapi.
log%7D));%0A
|
b8ffea8f16daebc285171cf916cd611de92e656a | rename signing app | lib/signer.js | lib/signer.js | var Q = require('q');
var SIGNING_APP_ID = require('../conf/signing-app').id;
var blacklistedIds = [];
function sign(msg) {
var deferred = Q.defer();
msg = clone(msg);
msg.type = 'sign';
msg.forApp = {
name: 'paranoid'
};
msg.fromApp = {
name: msg.appName || 'Tradle'
};
chrome.runtime.sendMessage(
SIGNING_APP_ID, // signing app
msg,
function(response) {
if (response.error) deferred.reject(response.error);
else deferred.resolve(response);
}
)
return deferred.promise;
}
function clone(obj) {
var copy = {};
for (var p in obj) {
if (obj.hasOwnProperty(p)) copy[p] = obj[p];
}
return copy;
}
module.exports = {
sign: sign
}
| JavaScript | 0.000001 | @@ -219,16 +219,13 @@
e: '
-paranoid
+Signy
'%0A
|
b6063af639c5e8e824f7da2406cfeb63e8af8ab0 | Remove onerror callback from the raw socket | lib/socket.js | lib/socket.js | import EventEmitter from "wolfy87-eventemitter";
import EJSON from "ejson";
export default class Socket extends EventEmitter {
constructor (SocketConstructor, endpoint) {
super();
this.SocketConstructor = SocketConstructor;
this.endpoint = endpoint;
this.rawSocket = null;
}
send (object) {
if (!this.closing) {
const message = EJSON.stringify(object);
this.rawSocket.send(message);
// Emit a copy of the object, as the listener might mutate it.
this.emit("message:out", EJSON.parse(message));
}
}
open () {
/*
* Makes `open` a no-op if there's already a `rawSocket`. This avoids
* memory / socket leaks if `open` is called twice (e.g. by a user
* calling `ddp.connect` twice) without properly disposing of the
* socket connection. `rawSocket` gets automatically set to `null` only
* when it goes into a closed or error state. This way `rawSocket` is
* disposed of correctly: the socket connection is closed, and the
* object can be garbage collected.
*/
if (this.rawSocket) {
return;
}
this.closing = false;
this.rawSocket = new this.SocketConstructor(this.endpoint);
/*
* Calls to `onopen` and `onclose` directly trigger the `open` and
* `close` events on the `Socket` instance.
*/
this.rawSocket.onopen = () => this.emit("open");
this.rawSocket.onclose = () => {
this.rawSocket = null;
this.emit("close");
this.closing = false;
};
/*
* Calls to `onerror` trigger the `close` event on the `Socket`
* instance, and cause the `rawSocket` object to be disposed of.
* Since it's not clear what conditions could cause the error and if
* it's possible to recover from it, we prefer to always close the
* connection (if it isn't already) and dispose of the socket object.
*/
this.rawSocket.onerror = () => {
// It's not clear what the socket lifecycle is when errors occurr.
// Hence, to avoid the `close` event to be emitted twice, before
// manually closing the socket we de-register the `onclose`
// callback.
delete this.rawSocket.onclose;
// Safe to perform even if the socket is already closed
this.rawSocket.close();
this.rawSocket = null;
this.emit("close");
};
/*
* Calls to `onmessage` trigger a `message:in` event on the `Socket`
* instance only once the message (first parameter to `onmessage`) has
* been successfully parsed into a javascript object.
*/
this.rawSocket.onmessage = message => {
var object;
try {
object = EJSON.parse(message.data);
} catch (ignore) {
// Simply ignore the malformed message and return
return;
}
// Outside the try-catch block as it must only catch JSON parsing
// errors, not errors that may occur inside a "message:in" event
// handler
this.emit("message:in", object);
};
}
close () {
/*
* Avoid throwing an error if `rawSocket === null`
*/
if (this.rawSocket) {
this.closing = true;
this.rawSocket.close();
}
}
} | JavaScript | 0 | @@ -1690,929 +1690,8 @@
/*%0A
- * Calls to %60onerror%60 trigger the %60close%60 event on the %60Socket%60%0A * instance, and cause the %60rawSocket%60 object to be disposed of.%0A * Since it's not clear what conditions could cause the error and if%0A * it's possible to recover from it, we prefer to always close the%0A * connection (if it isn't already) and dispose of the socket object.%0A */%0A this.rawSocket.onerror = () =%3E %7B%0A // It's not clear what the socket lifecycle is when errors occurr.%0A // Hence, to avoid the %60close%60 event to be emitted twice, before%0A // manually closing the socket we de-register the %60onclose%60%0A // callback.%0A delete this.rawSocket.onclose;%0A // Safe to perform even if the socket is already closed%0A this.rawSocket.close();%0A this.rawSocket = null;%0A this.emit(%22close%22);%0A %7D;%0A /*%0A
|
1a13eebe3209407a887267762a733fb9e78a497f | copy data handler flow options and extend with session | lib/stream.js | lib/stream.js | var Stream = require('stream');
exports.Pass = function () {
return Stream.PassThrough({objectMode: true});
};
// writable
exports.Event = function (options) {
options = options || {};
if (typeof options.objectMode === 'undefined') {
options.objectMode = true;
}
var sequence = Stream.Transform({
objectMode: options.objectMode ? true : false,
transform: function (chunk, enc, next) {
var push;
var pos = -1;
var handler;
var runSeq = function (err, data) {
if (err && data) {
data = err;
err = null;
push = true;
} else {
push = false;
}
// emit error
if (err) {
return next(err);
};
// just push data to readable if data and error is true
if (push) {
return sequence.push(data);
}
// get handler
if (!(handler = sequence.seq[++pos])) {
return next(null, data);
}
// call next data handler
if (!handler[4]) {
// once handler
if (handler[3]) {
handler[4] = true;
}
handler[0].call(handler[2], handler[1], data, runSeq);
} else {
runSeq(null, data);
}
};
if (!sequence.seq) {
sequence.once('sequence', runSeq.bind(this, null, chunk));
return;
}
runSeq(null, chunk);
}
});
return sequence;
};
| JavaScript | 0 | @@ -1406,32 +1406,202 @@
%7D%0A%0A
+ var dhOptions = Object.assign(%7B%7D, handler%5B1%5D);%0A dhOptions.arg = options;%0A dhOptions.session = options.session; %0A
@@ -1632,26 +1632,25 @@
ler%5B2%5D,
-handler%5B1%5D
+dhOptions
, data,
|
f314996bbd3791084d22b3366060ffbf4206c39e | make object look less like json | lib/styled.js | lib/styled.js | 'use strict';
let cli = require('..');
let util = require('util');
let inflection = require('inflection');
/**
* styledHeader logs in a consistent header style
*
* @example
* styledHeader('MyApp') # Outputs === MyApp
*
* @param {header} header text
* @returns {null}
*/
function styledHeader(header) {
cli.log(`=== ${header}`);
}
/**
* styledObject logs an object in a consistent columnar style
*
* @example
* styledObject({name: "myapp", collaborators: ["user1@example.com", "user2@example.com"]})
* Collaborators: user1@example.com
* user2@example.com
* Name: myapp
*
* @param {obj} object data to print
* @param {keys} optional array of keys to sort/filter output
* @returns {null}
*/
function styledObject(obj, keys) {
let keyLengths = Object.keys(obj).map(function(key) { return key.toString().length; });
let maxKeyLength = Math.max.apply(Math, keyLengths) + 2;
function pp(obj) {
if (typeof obj === 'string' || typeof obj === 'number') {
return obj;
} else {
return util.inspect(obj);
}
}
function logKeyValue(key, value) {
cli.log(inflection.titleize(key)+':'+' '.repeat(maxKeyLength - key.length-1)+pp(value));
}
for (var key of (keys || Object.keys(obj).sort())) {
let value = obj[key];
if (Array.isArray(value)) {
if (value.length > 0) {
logKeyValue(key, value[0]);
for (var e of value.slice(1)) {
cli.log(" ".repeat(maxKeyLength) + pp(e));
}
}
} else if (value !== null && value !== undefined) {
logKeyValue(key, value);
}
}
}
module.exports.styledHeader = styledHeader;
module.exports.styledObject = styledObject;
| JavaScript | 0.001828 | @@ -1028,16 +1028,142 @@
rn obj;%0A
+ %7D else if (typeof obj === 'object') %7B%0A return Object.keys(obj).map(k =%3E k + ': ' + util.inspect(obj%5Bk%5D)).join(', ');%0A
%7D el
|
aba7f783d3a07cb05cfbe54c729db6792491bff9 | disable tunneling message | lib/worker.js | lib/worker.js | var _ = require('underscore')
, Promise = require('bluebird')
, config = require('config')
, url = require('url')
;
function Worker() { }
function promise_time(p$, msg) {
var s_hrtime = process.hrtime();
return p$.tap(function(){
var diff = process.hrtime(s_hrtime)
, span = ((diff[0] * 1e9 + diff[1]) / 1e6).toFixed(2) + 'ms'
;
console.log(msg, span);
});
}
Worker.prototype.listen = function(options, cb) {
options = options || {};
options.port = options.port || config.port || 80;
var tunnel_url = url.format({
protocol : config.get('tunnel.protocol')
, hostname : config.get('tunnel.hostname')
, port : config.get('tunnel.port')
});
var tunnel_opts = {
host : tunnel_url
, subdomain : config.get('req.id')
};
var p$tunnel = Promise.method(() => {
var localtunnel = require('localtunnel');
return Promise.promisify(localtunnel)(options.port, tunnel_opts);
})
, p$http = Promise.method(() => {
var express = require('express')
, responseTime = require('response-time')
, bodyParser = require('body-parser')
, request = require('./request')
, onFinished = require('on-finished')
, http = express()
, me = this
;
http.use(responseTime({ header : 'x-tm-response-time-worker' }));
http.use(request.middleware(config.get('req').manual));
http.use(bodyParser.json());
http.use(bodyParser.text({ type : ['text/*', 'application/javascript', 'application/xml'] }));
http.use(bodyParser.urlencoded({ extended: false }));
http.use(function(req, res, next){
clearTimeout(me.timeout_for_req_start_token);
onFinished(res, function (err, res) {
me.exit(err, res);
});
me.run(config.get('req'), req, res, _.once((err) => {
res.status(500).send(me.errorify(err));
}));
});
return Promise.promisify(http.listen, { context : http })(options.port);
})
;
// p$tunnel = promise_time(p$tunnel(), 'tunnel-connection-time');
// p$http = promise_time(p$http(), 'express-server-listen-time');
Promise
.all([ p$tunnel(), p$http() ])
.then(() => {
console.log('>> tunneling to:', tunnel_url);
this.timeout_for_req_start_token = setTimeout(() => {
this.exit(new Error('no requests received after connection to relay'));
}, 10 * 1000);
})
.nodeify(cb)
;
};
Worker.prototype.exit = function(err) {
if (err) {
var msg = _.isError(err)? err.message : err.toString();
console.error(msg);
}
// todo [akamel] using timeout otherwise relay crashes with socket error
setTimeout(() => {
process.exit();
}, 4 * 1000);
};
Worker.prototype.run = function(data, req, res, next) {
// todo [akamel] maybe move this to after listen? no need to wait for req to come in
var Code = require(config.get('code-module'));
var code = new Code(data);
// todo [akamel] should this be on req.manual or req.app.manual
req.details = data;
req.manual = data.manual;
req.metadata = data.metadata;
if (_.has(req.manual, 'output')) {
if (_.has(req.manual.output, 'content-type')) {
res.set('Content-Type', req.manual.output['content-type']);
}
}
var App = require('./app');
try {
req.app = new App(req, res);
code.run(req, res, next);
} catch (err) {
err.source = code.source;
next(err);
}
};
Worker.prototype.errorify = function(err) {
var ret = {
type : 'notification'
, target : 'taskmill-core-worker'
};
if (_.isError(err)) {
ret.type = err.name;
ret.error = err.message;
ret.message = err.toString();
ret.stack = err.stack;
};
if (_.has(err, 'help_url')) {
ret.details = err.help_url;
}
return ret;
};
module.exports = Worker; | JavaScript | 0.000001 | @@ -2702,16 +2702,19 @@
%7B%0A
+ //
console
|
a85caa94d225a00a607c17de7eff44d3863447e5 | fix 变量判断错误 | libs/stage.js | libs/stage.js | // class Stage
// express中叫 layer, 这里则称为 stage(阶段),代表某个处理阶段
const concat = Array.prototype.concat;
function Stage(stages) {
const befores = {};
const afters = {};
this.stages = stages;
this.stageNames = stages.map(stage => {
const name = stage.name;
befores[name] = [];
afters[name] = [];
return name;
});
this.befores = befores;
this.afters = afters;
}
['before', 'after'].map(filterName => {
Stage.prototype[filterName] = function filter(stageName, action) {
const propname = `${filterName}s`;
const filters = this[propname][stageName]; // this.befores[stagesName];
if (! filters) {
throw new Error(`Stage ${name} does not exist`);
}
filters.push(action);
this.merge();
return this;
};
return filterName;
});
Stage.prototype.merge = function merge() {
// 合并所有的filter、stage
this.actions = [];
this.stages.map((stage, i) => {
const name = this.stageNames[i];
const befores = this.befores[name];
const afters = this.afters[name];
this.actions = concat.call(this.actions, befores, [stage], afters);
return null;
});
};
Stage.prototype.set = function set(prop, value) {
this[prop] = value;
return this;
};
Stage.prototype.get = function get(prop) {
return this[prop];
};
Stage.prototype.handle = function handle(req, res, next) {
const actions = this.actions;
const originNext = next;
const startIndex = 0;
// 特别注意,nextStage不应改变全局变量
const nextStage = () => {
// 已响应了客户端,则不再继续任何处理
if (res.hasSent || res.headersSent) {
return;
}
const prevIndex = req.stageIndex;
const stageIndex = prevIndex + 1;
const isLast = stageIndex === actions.length;
if (isLast) {
originNext();
return;
}
req.stageIndex = stageIndex;
// TODO nextOnce can't be used;
// const nextOnce = () => {
// if (nextOnce.invoked) {
// return;
// }
// nextOnce.invoked = true;
// nextStage();
// };
actions[stageIndex](req, res, nextStage);
};
// 提供跳过stage处理流程的功能
nextStage.stageOver = originNext;
// 添加扩展属性
// 增加一个pathname自定义属性,用于取代req.path
// pathname可实现forward功能
req.pathname = req.path;
req.stageIndex = startIndex;
res.apiData = {};
res.apiInfo = {};
res.forward = pathname => {
if (pathname === req.path) {
throw new Error('foward path cannot be the same as req.path!');
}
res.forwardSent = true;
req.pathname = pathname;
req.stageIndex = 0;
actions[req.stageIndex](req, res, nextStage);
};
actions[startIndex](req, res, nextStage);
};
module.exports = Stage;
| JavaScript | 0.000674 | @@ -1514,11 +1514,15 @@
res.
-has
+forward
Sent
|
5c58f91232a9929e39c7b73478c5b09be999015e | Add numberWithCommas | web/js/coge/utils.js | web/js/coge/utils.js | /* global window, document, coge*/
var coge = window.coge = (function(ns) {
var waitToSearchTimer;
ns.utils = {
ascending: function(a, b) {
return a < b ? -1 : a > b ? 1 : 0;
},
descending: function(a, b) {
return a > b ? -1 : a < b ? 1 : 0;
},
open: function(link) {
window.open(link, "_self");
},
shuffle: function(array) {
var copy = array.slice(0), n = array.length, tmp, i;
while (n) {
i = Math.floor(Math.random() * n--);
tmp = copy[n];
copy[n] = copy[i];
copy[i] = tmp;
};
return copy;
},
post: function(action, params) {
var key,
input,
form = document.createElement("form");
form.method = "post";
form.action = action;
form.setAttribute("target", "_blank");
form.setAttribute("enctype", "multipart/form-data");
for(key in params) {
if (params.hasOwnProperty(key)) {
input = document.createElement("textarea");
input.name = key;
input.value = params[key];
form.appendChild(input);
}
}
form.submit("action");
},
toPrettyDuration: function(seconds) {
var fields = [
[parseInt((seconds / 86400).toFixed(1), 10), " day"],
[parseInt((seconds / 3600).toFixed(1), 10) % 24, " hour"],
[parseInt(((seconds / 60) % 60).toFixed(1), 10), " minute"],
[(seconds % 60).toFixed(2), " second"]
];
return fields.filter(function(item) { return item[0] !== 0; })
.map(function(item) {
var word = (item[0] > 1) ? item[1] + "s" : item[1];
return item[0] + word;
})
.join(", ");
},
log10: function(value) {
return Math.log(value) / Math.log(10);
},
ucfirst: function(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
},
getURLParameters: function () { // returns object of query params
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
var urlParams = {};
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
return urlParams;
},
toQueryString: function(obj, prefix) { // accepts an object of query params
var str = [];
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
str.push(typeof v == "object" ?
serialize(v, k) :
encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
}
return str.join("&");
},
objToString: function(obj, indent) {
if (typeof indent === 'undefined') indent = '';
indent += ' ';
var str = '<br>';
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
var val = obj[p];
if (typeof val === 'object')
str += indent + p + ': ' + this.objToString(val, indent) + '<br>';
else
str += indent + p + ': ' + obj[p] + '<br>';
}
}
return str;
},
wait_to_search: function(search_func, search_obj, wait_time) {
if (!wait_time)
wait_time = 250;
if (waitToSearchTimer)
clearTimeout(waitToSearchTimer);
waitToSearchTimer = setTimeout(
function() {
search_func(search_obj.value);
},
wait_time
);
},
removeSpecialChars: function(s) {
if (s) {
var s2 = s.replace(/[^\w\s\'\"\`\.\,\!\:\;\-\~\&\%\@\#\*\=\+\?\^\$\<\>\{\}\(\)\|\[\]\\]/gi, '');
return s2;
}
else {
return s;
}
},
numberWithCommas: function(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
};
return ns;
})(coge || {});
| JavaScript | 0.998824 | @@ -4437,16 +4437,25 @@
%09%7D,%0A%0A%09
+function
numberWi
@@ -4462,26 +4462,16 @@
thCommas
-: function
(x) %7B%0A%09%09
|
0d6a451a684d46f38a44d6f14747bd2abd8d317d | support initValue in textFieldValue. Add radioGroupValue | Bacon.UI.js | Bacon.UI.js | (function() {
var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
function nonEmpty(x) { return x && x.length > 0 }
Bacon.UI = {}
Bacon.UI.textFieldValue = function(textfield) {
function getValue() { return textfield.val() }
function autofillPoller() {
if (textfield.attr("type") == "password")
return Bacon.interval(100)
else if (isChrome)
return Bacon.interval(100).take(20).map(getValue).filter(nonEmpty).take(1)
else
return Bacon.never()
}
return $(textfield).asEventStream("keyup input").
merge($(textfield).asEventStream("cut paste").delay(1)).
merge(autofillPoller()).
map(getValue).skipDuplicates().toProperty(getValue())
}
Bacon.UI.optionValue = function(option) {
function getValue() { return option.val() }
return option.asEventStream("change").map(getValue).toProperty(getValue())
}
Bacon.UI.checkBoxGroupValue = function(checkboxes, initValue) {
function selectedValues() {
return checkboxes.filter(":checked").map(function(i, elem) { return $(elem).val()}).toArray()
}
if (initValue) {
checkboxes.each(function(i, elem) {
$(elem).attr("checked", initValue.indexOf($(elem).val()) >= 0)
})
}
return checkboxes.asEventStream("click").map(selectedValues).toProperty(selectedValues())
}
Bacon.Observable.prototype.pending = function(src) {
return src.map(true).merge(this.map(false)).toProperty(false)
}
Bacon.EventStream.prototype.ajax = function() {
return this["switch"](function(params) { return Bacon.fromPromise($.ajax(params)) })
}
})();
| JavaScript | 0.000001 | @@ -197,16 +197,27 @@
extfield
+, initValue
) %7B%0A
@@ -524,32 +524,99 @@
n.never()%0A %7D%0A
+ if (initValue !== null) %7B%0A textfield.val(initValue)%0A %7D%0A
return $(tex
@@ -610,18 +610,16 @@
return
-$(
textfiel
@@ -611,33 +611,32 @@
return textfield
-)
.asEventStream(%22
@@ -662,18 +662,16 @@
merge(
-$(
textfiel
@@ -671,17 +671,16 @@
extfield
-)
.asEvent
@@ -765,25 +765,8 @@
ue).
-skipDuplicates().
toPr
@@ -775,32 +775,49 @@
erty(getValue())
+.skipDuplicates()
%0A %7D%0A Bacon.UI.
@@ -1703,10 +1703,209 @@
%7D%0A
+ Bacon.UI.radioGroupValue = function(options) %7B%0A var initialValue = options.filter(':checked').val()%0A return options.asEventStream(%22change%22).map('.target.value').toProperty(initialValue)%0A %7D%0A
%7D)();%0A
+%0A
|
799228d133e602261b70011c744cb0b5624ac457 | Update copyright year to 2017 in footer on website (#1019) | website/core/Site.js | website/core/Site.js | /**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Site
* @jsx React.DOM
*/
var React = require('React');
var HeaderLinks = require('HeaderLinks');
var Site = React.createClass({
render: function() {
const titlePrefix = this.props.pageTitle ? this.props.pageTitle.concat(' | ') : '';
const title = `${titlePrefix}Draft.js | Rich Text Editor Framework for React`;
return (
<html>
<head>
<meta charSet="utf-8" />
<meta httpEquiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title>{title}</title>
<meta name="viewport" content="width=device-width" />
<meta property="og:title" content={title} />
<meta property="og:type" content="website" />
<meta property="og:url" content="http://facebook.github.io/draft-js/index.html" />
<meta property="og:description" content="Rich Text Editor Framework for React" />
<link rel="stylesheet" href="/draft-js/css/draft.css" />
<script type="text/javascript" src="//use.typekit.net/vqa1hcx.js"></script>
<script type="text/javascript">{'try{Typekit.load();}catch(e){}'}</script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.34.4/es6-shim.min.js"></script>
</head>
<body>
<div className="container">
<div className="nav-main">
<div className="wrap">
<a className="nav-home" href="/draft-js/">
Draft.js
</a>
<HeaderLinks section={this.props.section} />
</div>
</div>
{this.props.children}
<footer className="wrap">
<div className="right">© 2016 Facebook Inc.</div>
</footer>
</div>
<div id="fb-root" />
<script dangerouslySetInnerHTML={{__html: `
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-44373548-19', 'auto');
ga('send', 'pageview');
!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)
){js=d.createElement(s);js.id=id;js.src="https://platform.twitter.com/widgets.js";
fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");
`}} />
</body>
</html>
);
},
});
module.exports = Site;
| JavaScript | 0 | @@ -2032,17 +2032,17 @@
opy; 201
-6
+7
Faceboo
|
e930cae2fe9873d3e6e3cd09ce5e34b8d9066826 | Add tx types translations | www/js/lang/en-US.js | www/js/lang/en-US.js | angular.module("omniConfig")
.constant("EnglishTranslation",{
COMMON_ACTIONS: 'Actions',
COMMON_ADDRESS: 'Address',
COMMON_AVAILABLE: 'available',
COMMON_BALANCE: 'Balance',
COMMON_BITCOIN: 'Bitcoin',
COMMON_BROADCAST: 'Broadcast Transaction',
COMMON_OVERVIEW: 'Overview',
COMMON_REMOVEADDRESS: 'Remove from Wallet',
COMMON_ADDRESSES: 'Addresses',
COMMON_ASSETS: 'Assets',
COMMON_ASSET: 'Asset',
COMMON_OVERVIEW: 'Overview',
COMMON_SEND: 'Send',
COMMON_VALUE: 'Value',
COMMON_CREATEWALLET: 'Create Wallet',
COMMON_LOGIN: 'Login',
HOMEPAGE_ADDRESSEXAMPLE: '(e.g. 1EXoDusjGwvnjZUyKkxZ4UHEf77z6A5S4P)',
HOMEPAGE_BALANCECHECK:'Balance Check',
HOMEPAGE_CHECKBALANCE: 'Check Balance',
HOMEPAGE_ENTERVALIDADDRESS:'Enter a valid Bitcoin Address ',
HOMEPAGE_WELCOME: 'Welcome to Omniwallet',
NAVIGATION_ABOUT:'About',
NAVIGATION_ABOUTOMNI:'About Omniwallet',
NAVIGATION_ABOUTMSC:'About Mastercoin',
NAVIGATION_ACCOUNT:'My Account',
NAVIGATION_ADDRESSES: 'My Addresses',
NAVIGATION_ASSETS: 'My Assets',
NAVIGATION_BOOKMARKS:'Bookmarks',
NAVIGATION_CREATE: 'Create Wallet',
NAVIGATION_CONTACT:'Contact Us',
NAVIGATION_EXCHANGE: 'Exchange',
NAVIGATION_EXPLORER:'Explorer',
NAVIGATION_EXPLOREASSETS:'Assets',
NAVIGATION_FAQ:'FAQ',
NAVIGATION_FOLLOWING:'Following',
NAVIGATION_HISTORY: 'History',
NAVIGATION_LOGIN: 'Login',
NAVIGATION_LOGOUT:'Logout',
NAVIGATION_OFFERS:'My Offers',
NAVIGATION_SETTINGS:'Account Settings',
NAVIGATION_TRADE:'Trade',
NAVIGATION_TRANSACTIONS:'Transactions',
NAVIGATION_WALLET: 'My Wallet',
COMMON_LOADING:'Loading',
WALLET_OVERVIEW_BACKUP:'Backup',
WALLET_OVERVIEW_ESTIMATED:'Estimated Total value',
WALLET_OVERVIEW_IMPORT:'Import',
WALLET_OVERVIEW_TITLE:'Overview',
WALLET_OVERVIEW_OPTIONS:'Wallet Options',
WALLET_OVERVIEW_OPTIONSTOGGLE:'Toggle Options',
WALLET_OVERVIEW_PORTFOLIO:'Portfolio Composition by value',
WALLET_OVERVIEW_WALLETID:'Wallet ID',
WALLET_ADDRESSES_CREATE:'Create New Address',
WALLET_ADDRESSES_IMPORT:'Import Address With Private Key',
WALLET_ADDRESSES_TITLE:'My Addresses',
WALLET_ADDRESSES_VIEW:'View by',
WALLET_ADDRESSES_OPTIONS:'Add Address',
WALLET_ADDRESSES_WATCH:'Add Watch Only Address',
WALLET_ADDRESSES_OFFLINE:'Add Armory Offline Address',
WALLET_SEND_TITLE:'Send',
WALLET_SEND_CHOOSECOIN:'Choose coin',
WALLET_SEND_FROM:'From address',
WALLET_SEND_AMOUNT:'amount',
WALLET_SEND_TO:'To address',
WALLET_SEND_COST:'Total transaction cost',
WALLET_SEND_SUBMIT:'Next',
WALLET_SEND_FUNDS:'Send Funds',
WALLET_SEND_TOKEN:'Token',
WALLET_SEND_MODAL_AMOUNT:'Amount',
WALLET_SEND_MODAL_FROM:'From',
WALLET_SEND_MODAL_TO:'To',
WALLET_ASSETS_ASSETS: 'Assets',
WALLET_ASSETS_CREATE: 'Create',
WALLET_ASSETS_CROWDSALE: 'Crowdsale',
WALLET_ASSETS_MYASSETS: 'My Assets',
WALLET_ASSETS_SMARTPROPERTY: 'Smart Property'
}) | JavaScript | 0 | @@ -1595,16 +1595,481 @@
ading',%0A
+%09TX_TYPE_0: 'Simple Send',%0A%09TX_TYPE_3: 'Send To Owners',%0A%09TX_TYPE_20: 'Sell Offer',%0A%09TX_TYPE_21: 'Accept Offer',%0A%09TX_TYPE_22: 'Purchase Offer',%0A%09TX_TYPE_50: 'Create a Fixed Property',%0A%09TX_TYPE_51: 'Create a Crowdsale',%0A%09TX_TYPE_52: 'Promote a Property',%0A%09TX_TYPE_53: 'Close a Crowdsale Manually',%0A%09TX_TYPE_54: 'Create a Managed Property',%0A%09TX_TYPE_55: 'Grant Property Tokens',%0A%09TX_TYPE_56: 'Revoke Property Tokens',%0A%09TX_TYPE_70: 'Change Property Issuer on Record',%0A
%09WALLET_
|
8a13ae3d2fc6e56488c865f57e12a6c162affc32 | clean up index.js | demo/index.js | demo/index.js | import React from 'react';
import ReactDOM from 'react-dom';
import ons from '../OnsenUI/build/js/onsenui.js';
import {
Page,
Navigator,
Toolbar,
List,
ListItem,
Ripple,
Carousel,
CarouselItem,
BottomToolbar,
ToolbarButton,
} from 'react-onsenui';
import PageExample from './examples/Page';
import ListExample from './examples/List';
import LazyListExample from './examples/LazyList';
import TabbarExample from './examples/Tabbar';
import AlertDialogExample from './examples/AlertDialog';
import SplitterExample from './examples/Splitter';
import InputExample from './examples/Input';
import IconExample from './examples/Icon';
import RippleExample from './examples/Ripple';
import SpeedDialExample from './examples/SpeedDial';
import PullHookExample from './examples/PullHook';
import CarouselExample from './examples/Carousel';
class Examples extends React.Component {
constructor(props) {
super(props);
this.state = {class: 'test'};
this.examples = [
{
title: 'Tabbar',
component: TabbarExample
},
{
title: 'Splitter',
component: SplitterExample
},
{
title: 'SpeedDial',
component: SpeedDialExample
},
{
title: 'Carousel',
component: CarouselExample
},
{
title: 'PullHook',
component: PullHookExample
},
{
title: 'Page',
component: PageExample
},
{
title: 'Ripple',
component: RippleExample
},
{
title: 'Icon',
component: IconExample
},
{
title: 'List',
component: ListExample
},
{
title: 'Lazy List',
component: LazyListExample
},
{
title: 'Alert dialog',
component: AlertDialogExample
},
{
title: 'Input',
component: InputExample
}];
// setTimeout(() => {
// this.goto(this.examples[0]);
// }, 0);
}
goto(example) {
this.props.navigator.pushPage({
component: example.component,
props: {
key: example.title
}
});
}
render() {
return (
<Page style={{background: 'green'}}
renderToolbar={() => <Toolbar> <div className='center'> Up Toolbar </div> </Toolbar>} >
<List
dataSource={this.examples}
renderHeader={ () =>
<ListItem lockOnDrag style={{background: 'green'}} tappable tap-background-color='red'> HEADER </ListItem>
}
renderRow={(example) => (
<ListItem key={example.title} onClick={this.goto.bind(this, example)}>{example.title}</ListItem>
)}
/>
</Page>
);
}
}
class App extends React.Component {
renderPage(route, navigator) {
const props = route.props || {};
props.navigator = navigator;
return React.createElement(route.component, route.props);
}
render() {
return (
<Navigator
renderPage={this.renderPage}
initialRoute={{
component: Examples,
props: {
key: 'examples'
}
}}
/>
);
}
}
ReactDOM.render(<App />, document.getElementById('app'));
| JavaScript | 0.000007 | @@ -66,17 +66,8 @@
ort
-ons from
'../
@@ -160,81 +160,8 @@
Item
-,%0A Ripple,%0A Carousel,%0A CarouselItem,%0A BottomToolbar,%0A ToolbarButton,
%0A%7D f
|
6650aaa6e195e23554df2c3ef23624e1d1c7206b | scrub it | devServer2.js | devServer2.js | import express from 'express';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import webpackConfig from './webpack.config.dev';
import cli from 'better-console';
import _ from 'lodash';
import Wreck from 'wreck';
import {camelizeKeys} from 'humps';
import {titleize} from 'inflection';
import sanitizeHtml from 'sanitize-html';
// import { App } from './src/App';
const app = express();
const port = 3000;
const compiler = webpack(webpackConfig);
app.use(webpackDevMiddleware(compiler, {
noInfo: true,
publicPath: webpackConfig.output.publicPath,
}));
app.use(webpackHotMiddleware(compiler));
app.use(express.static('public'));
let apiData = null;
const authorIndex = {};
function doTitleize(str) {
if (str === str.toUpperCase() || str.toLowerCase()) {
return titleize(str);
}
return str;
}
function addAuthor(sessionCode) {
return ({firstname, lastname}) => {
const id = firstname + lastname;
if (authorIndex[id]) {
authorIndex[id].sessionCodes.push(sessionCode);
} else {
authorIndex[id] = {firstname, lastname, sessionCodes: [sessionCode]};
}
};
}
function fixAuthor({firstname, lastname, company, presenter}) {
let companyStr = company;
if (company.split(' ').length > 1) {
companyStr = doTitleize(company);
}
const auth = {
company: companyStr,
firstname: doTitleize(firstname),
lastname: doTitleize(lastname),
presenter,
// ...rest
};
return auth;
}
function fixPresentation({orderof, description, authors}, i, {sessionType, sessionCode}) {
const presentation = {};
// Poster authors.
if (sessionType === 'Poster presentations') {
presentation.sessionCode = sessionCode.toString() + '.' + orderof.toString();
_.each(authors, author => addAuthor(presentation.sessionCode)(author));
} else {
_.each(authors, author => addAuthor(sessionCode)(author));
}
if (description && description.title) {
presentation.description = {title: doTitleize(description.title)};
}
// _.each(presentation.description, desc =>
// description[desc.fieldLabel.toLowerCase()] = desc.fieldValue
// );
// presentation.description = camelizeKeys(description);
// if (presentation.description.title) {
// presentation.description.title = doTitleize(presentation.description.title);
// }
// presentation.description = _.pick(presentation.description, 'title');
presentation.authors = authors.map(fixAuthor);
if (presentation.authors.length > 1 && presentation.authors[0].presenter !== 1) {
const presenter = _.remove(presentation.authors, {presenter: 1});
presentation.authors = presenter.concat(presentation.authors);
}
return presentation;
}
function fixDescription(sessionDescription) {
if (!sessionDescription) {
return sessionDescription;
}
return sanitizeHtml(sessionDescription, {
allowedTags: [ 'b', 'i', 'em', 'strong', 'p', 'ul', 'li'],
});
}
function fixDataItem({presentations, sessionDescription, sessionChairs, ...rest}) {
const newItem = {
presentations: presentations.map((presentation, i) => fixPresentation(presentation, i, rest)),
sessionChairs: sessionChairs.map(fixAuthor),
sessionDescription: fixDescription(sessionDescription),
...rest,
};
// Add authors to index.
if (newItem.sessionChairs.length) {
_.each(newItem.sessionChairs, addAuthor(`<strong>${newItem.sessionCode}</strong>`));
}
return newItem;
}
function fetchData(callback) {
var fullUrl = 'http://www.xcdsystem.com/icfp/admin/program.json';
if (apiData) {
cli.log('return cached data');
callback(apiData);
} else {
cli.log('fetch new data');
Wreck.get(fullUrl, {json: true}, (err, response, payload) => {
cli.log('transform new data');
const items = _.map(camelizeKeys(payload), fixDataItem);
apiData = {
posters: _.remove(items, {sessionType: 'Poster presentations'}),
sessions: items,
// sessions: _.filter(items, (item) => {
// return (item.sessionType === 'Oral Presentations' || item.sessionType === 'Preformed Panel')
// })
};
apiData.sessions = _.groupBy(apiData.sessions, 'sessionDate');
const days = [];
_.each(_.keys(apiData.sessions), (sessionDate) => {
days.push({
sessionDate,
timeSlots: _.map(_.groupBy(apiData.sessions[sessionDate], 'sessionStartTime'), (sessions) => {
return {
sessionStartTime: sessions[0].sessionStartTime,
sessionEndTime: sessions[0].sessionEndTime,
sessions: _.map(sessions, (session) => {
if (session.sessionDescription) {
session.sessionDescription = sanitizeHtml(session.sessionDescription, {
allowedTags: [ 'b', 'i', 'em', 'strong', 'p', 'ul', 'li'],
});
}
return session;
}),
};
}),
});
});
apiData.sessions = days;
apiData.authorList = _.sortByAll(_.values(authorIndex), ['lastname', 'firstname']);
cli.log('return new data');
callback(apiData);
});
}
}
fetchData(() => {return;});
app.get('/api', (req, res) => {
if (apiData) {
cli.log('return cached data');
res.send(apiData);
} else {
res.send({error: true, msg: 'data not ready yet'});
}
});
// app.get('/render', function(req, res) {
// fetchData( items => {
// const html = React.renderToString(<App items={items} />);
// res.send(html);
// })
// });
app.listen(port, 'localhost', (err) => {
if (err) {
cli.log(err);
return;
}
cli.log('Listening at http://localhost:' + port);
});
| JavaScript | 0.000001 | @@ -1597,16 +1597,25 @@
authors
+, ...rest
%7D, i, %7Bs
@@ -1666,16 +1666,23 @@
tion = %7B
+...rest
%7D;%0A //
@@ -1867,16 +1867,28 @@
dAuthor(
+'Poster ' +
presenta
|
ab279a8ff870274d43a344469b487268aaca3a76 | Enable React strict mode | web/js/index.js | web/js/index.js | // Copyright © 2015-2019 Esko Luontola
// This software is released under the Apache License 2.0.
// The license text is at http://www.apache.org/licenses/LICENSE-2.0
/* @flow */
import React from "react";
import ReactDOM from "react-dom";
import {Provider} from "react-redux";
import {applyMiddleware, createStore} from "redux";
import {createLogger} from "redux-logger";
import reducers from "./reducers";
import history from "./history";
import router from "./router";
import routes from "./routes";
import {IntlProvider} from "react-intl";
import {language, messages} from "./intl";
import {mapRastersLoaded} from "./configActions";
import {mapRasters} from "./maps/mapOptions";
const logger = createLogger();
const store = createStore(reducers, applyMiddleware(logger));
const root = document.getElementById('root');
if (root === null) {
throw new Error('root element not found');
}
function renderComponent(component) {
ReactDOM.render(
<IntlProvider locale={language} messages={messages}>
<Provider store={store}>
{component}
</Provider>
</IntlProvider>, root);
}
async function renderNormalPage(location) {
const route = await router.resolve(routes, {...location, store});
renderComponent(route);
}
async function renderErrorPage(location, error) {
console.error("Error in rendering " + location.pathname + "\n", error);
const route = await router.resolve(routes, {...location, store, error});
renderComponent(route);
}
function handleRedirect(location, {redirect, replace}) {
console.info('Redirecting from', location, 'to', redirect);
if (replace) {
history.replace(redirect);
} else {
history.push(redirect);
}
}
async function render(location) {
try {
await renderNormalPage(location);
} catch (error) {
if (error.redirect) {
handleRedirect(location, error);
} else {
await renderErrorPage(location, error);
}
}
}
store.dispatch(mapRastersLoaded(mapRasters));
render(history.location);
history.listen((location, action) => {
console.log(`Current URL is now ${location.pathname}${location.search}${location.hash} (${action})`);
render(location);
});
| JavaScript | 0.000001 | @@ -944,16 +944,41 @@
render(%0A
+ %3CReact.StrictMode%3E%0A
%3CInt
@@ -1032,16 +1032,18 @@
%3E%0A
+
%3CProvide
@@ -1059,16 +1059,18 @@
store%7D%3E%0A
+
@@ -1087,16 +1087,18 @@
%7D%0A
+
%3C/Provid
@@ -1101,16 +1101,18 @@
ovider%3E%0A
+
%3C/In
@@ -1122,16 +1122,40 @@
rovider%3E
+%0A %3C/React.StrictMode%3E
, root);
|
f91cc2900ac40b86f0ad635601219d752851c194 | fix "if test fail, not exit when run test in local" bug | build/gulp_task/e2e/test.js | build/gulp_task/e2e/test.js | var gulp = require("gulp");
var git = require("gulp-git");
var path = require("path");
var fs = require("fs");
function _getErrorMessage(e) {
if (e[0] === undefined) {
return e;
}
else {
return e[0];
}
}
function _fail(message, done) {
console.log("fail");
console.error(message);
process.exit(1);
}
function _runTestInCI(runTestFunc, browserArr, done) {
console.log("run test...");
runTestFunc(browserArr).then(function (failList) {
console.log("pass test");
console.log("done");
done()
}, function (e) {
var failMessage = _getErrorMessage(e);
_fail(failMessage, done);
})
}
function _runTestInLocal(reportFilePath, runTestFunc, generateReportFunc, browserArr, done) {
console.log("run test...");
runTestFunc(browserArr).then(function (compareResultData) {
console.log("pass test");
console.log("done");
done()
}, function (e) {
var failMessage = _getErrorMessage(e);
var compareResultData = e[1];
console.log("fail");
console.error(failMessage);
console.log("generate report...");
generateReportFunc(reportFilePath, compareResultData).then(function () {
console.log("done");
done()
}, function (e) {
_fail(e, done);
})
})
}
function _runBuild(cb) {
var exec = require("child_process").exec;
console.log("build...");
exec("npm run buildAll", { maxBuffer: 8192 * 4000 }, function (err, stdout, stderr) {
if (err) {
throw err;
}
cb()
});
}
function _deepCopyJson(json) {
return JSON.parse(JSON.stringify(json));
}
function _writeGenerateBasedCommitIdToConfig(commitId, config, type, configFilePath) {
console.log("_write generate based commitId...");
var copiedConfig = _deepCopyJson(config);
copiedConfig[type].last_generate_based_commit_id = commitId;
fs.writeFileSync(configFilePath, JSON.stringify(copiedConfig));
}
function _restoreToCurrentCommid(e, currentCommitId, done) {
git.reset(currentCommitId, { args: '--hard' }, function (err) {
if (!!err) {
_fail(err, done);
return;
}
_runBuild(function () {
_fail(e, done);
});
});
}
module.exports = {
fail: function (message, done) {
_fail(message, done);
},
deepCopyJson: function (json) {
return _deepCopyJson(json);
},
getE2eConfigFilePath: function () {
return path.join(process.cwd(), "test/e2e/config/e2eConfig.json");
},
testInCI: function (generateDataInfo, type, generateCorrectDataFunc, runTestFunc, done) {
var configFilePath = this.getE2eConfigFilePath();
git.revParse({ args: "HEAD" }, function (err, commitId) {
var currentCommitId = commitId;
var config = JSON.parse(fs.readFileSync(configFilePath));
var basedCommitId = config[type].base_commit_id;
if (!!err) {
_fail(err, done);
return;
}
// if (basedCommitId === config[type].last_generate_based_commit_id) {
// _runBuild(function () {
// _runTestInCI(runTestFunc, [], done);
// });
// return
// }
console.log("reset hard to basedCommitId:", basedCommitId, "...");
git.reset(basedCommitId, { args: '--hard' }, function (err) {
if (!!err) {
_fail(err, done);
return;
}
_runBuild(function () {
console.log(generateDataInfo);
generateCorrectDataFunc().then(function (browser) {
console.log("reset hard to currentCommitId:", currentCommitId, "...");
git.reset(currentCommitId, { args: '--hard' }, function (err) {
if (!!err) {
_fail(err, done);
return;
}
// _writeGenerateBasedCommitIdToConfig(basedCommitId, config, type, configFilePath);
_runBuild(function () {
_runTestInCI(runTestFunc, [browser], done);
});
});
}, function (e) {
console.log("restore to origin commitId...");
_restoreToCurrentCommid(e, currentCommitId, done);
})
});
});
});
},
testInLocal: function (generateDataInfo, reportFilePath, type, generateCorrectDataFunc, generateReportFunc, runTestFunc, done) {
var configFilePath = this.getE2eConfigFilePath();
git.revParse({ args: "HEAD" }, function (err, commitId) {
var currentCommitId = commitId;
var config = JSON.parse(fs.readFileSync(configFilePath));
var basedCommitId = config[type].base_commit_id;
if (!!err) {
_fail(err, done);
return;
}
if (basedCommitId === config[type].last_generate_based_commit_id) {
console.log("already generate data based on the same commit id, not generate again...");
_runBuild(function () {
_runTestInLocal(reportFilePath, runTestFunc, generateReportFunc, [], done);
});
return
}
console.log("reset hard to basedCommitId:", basedCommitId, "...");
git.reset(basedCommitId, { args: '--hard' }, function (err) {
if (!!err) {
_fail(err, done);
return;
}
_runBuild(function () {
console.log(generateDataInfo);
generateCorrectDataFunc().then(function (browser) {
console.log("reset hard to currentCommitId:", currentCommitId, "...");
git.reset(currentCommitId, { args: '--hard' }, function (err) {
if (!!err) {
_fail(err, done);
return;
}
_writeGenerateBasedCommitIdToConfig(basedCommitId, config, type, configFilePath);
_runBuild(function () {
_runTestInLocal(reportFilePath, runTestFunc, generateReportFunc, [browser], done);
});
});
}, function (e) {
console.log("restore to origin commitId...");
_restoreToCurrentCommid(e, currentCommitId, done);
})
});
});
});
}
}
| JavaScript | 0.000002 | @@ -227,24 +227,67 @@
%5D;%0A %7D%0A%7D%0A%0A
+function _exit() %7B%0A process.exit(1);%0A%7D%0A%0A
function _fa
@@ -361,38 +361,30 @@
sage);%0A%0A
-process.
+_
exit(
-1
);%0A%7D%0A%0Afuncti
@@ -1302,48 +1302,16 @@
-console.log(%22done%22);%0A%0A done()
+_exit();
%0A
@@ -5600,32 +5600,33 @@
%7D);%0A
+%0A
|
8bcd9f9a00a5d680d59f4b6e7bebfb6c31e8432c | switch config epic to use action$ | applications/desktop/src/notebook/epics/config.js | applications/desktop/src/notebook/epics/config.js | // @flow
import { remote } from "electron";
import { selectors, actions, actionTypes } from "@nteract/core";
import { readFileObservable, writeFileObservable } from "fs-observable";
import { mapTo, mergeMap, map, switchMap } from "rxjs/operators";
import { ofType } from "redux-observable";
import type { ActionsObservable } from "redux-observable";
const path = require("path");
const HOME = remote.app.getPath("home");
export const CONFIG_FILE_PATH = path.join(HOME, ".jupyter", "nteract.json");
/**
* An epic that loads the configuration.
*
* @param {ActionObservable} actions ActionObservable for LOAD_CONFIG action
* @return {ActionObservable} ActionObservable for MERGE_CONFIG action
*/
export const loadConfigEpic = (actions: ActionsObservable<*>) =>
actions.pipe(
ofType(actionTypes.LOAD_CONFIG),
switchMap(() =>
readFileObservable(CONFIG_FILE_PATH).pipe(
map(JSON.parse),
map(actions.configLoaded)
)
)
);
/**
* An epic that saves the configuration if it has been changed.
*
* @param {ActionObservable} actions ActionObservable for SET_CONFIG_AT_KEY action
* @return {ActionObservable} ActionObservable with SAVE_CONFIG type
*/
export const saveConfigOnChangeEpic = (actions: ActionsObservable<*>) =>
actions.pipe(
ofType(actionTypes.SET_CONFIG_AT_KEY),
mapTo({ type: actionTypes.SAVE_CONFIG })
);
/**
* An epic that saves the configuration.
*
* @param {ActionObservable} actions ActionObservable containing SAVE_CONFIG action
* @return {ActionObservable} ActionObservable for DONE_SAVING action
*/
export const saveConfigEpic = (actions: ActionsObservable<*>, store: any) =>
actions.pipe(
ofType(actionTypes.SAVE_CONFIG),
mergeMap(() =>
writeFileObservable(
CONFIG_FILE_PATH,
JSON.stringify(selectors.userPreferences(store.getState()))
).pipe(map(actions.doneSavingConfig))
)
);
| JavaScript | 0 | @@ -216,16 +216,24 @@
witchMap
+, filter
%7D from
@@ -554,162 +554,8 @@
on.%0A
- *%0A * @param %7BActionObservable%7D actions ActionObservable for LOAD_CONFIG action%0A * @return %7BActionObservable%7D ActionObservable for MERGE_CONFIG action%0A
*/%0A
@@ -583,33 +583,33 @@
igEpic = (action
-s
+$
: ActionsObserva
@@ -619,33 +619,33 @@
%3C*%3E) =%3E%0A action
-s
+$
.pipe(%0A ofTyp
@@ -757,33 +757,16 @@
map(
-JSON.parse),%0A map(
+data =%3E
acti
@@ -781,16 +781,34 @@
igLoaded
+(JSON.parse(data))
)%0A
@@ -893,166 +893,8 @@
ed.%0A
- *%0A * @param %7BActionObservable%7D actions ActionObservable for SET_CONFIG_AT_KEY action%0A * @return %7BActionObservable%7D ActionObservable with SAVE_CONFIG type%0A
*/%0A
@@ -930,33 +930,33 @@
geEpic = (action
-s
+$
: ActionsObserva
@@ -966,33 +966,33 @@
%3C*%3E) =%3E%0A action
-s
+$
.pipe(%0A ofTyp
@@ -1125,168 +1125,8 @@
on.%0A
- *%0A * @param %7BActionObservable%7D actions ActionObservable containing SAVE_CONFIG action%0A * @return %7BActionObservable%7D ActionObservable for DONE_SAVING action%0A
*/%0A
@@ -1162,17 +1162,17 @@
(action
-s
+$
: Action
@@ -1210,17 +1210,17 @@
action
-s
+$
.pipe(%0A
|
6aaad4cd1f2da678b66d34dffbb6435efed9f36c | add version & license banner to dist files | gruntFile.js | gruntFile.js | /* jshint node:true */
'use strict';
module.exports = function(grunt) {
require('load-grunt-tasks')(grunt);
// Default task.
grunt.registerTask('default', ['jshint', 'karma:unit']);
grunt.registerTask('serve', ['karma:continuous', 'dist', 'build:gh-pages', 'connect:continuous', 'watch']);
grunt.registerTask('dist', ['ngmin', 'surround', 'uglify' ]);
grunt.registerTask('coverage', ['jshint', 'karma:coverage']);
grunt.registerTask('junit', ['jshint', 'karma:junit']);
// HACK TO ACCESS TO THE COMPONENT PUBLISHER
function fakeTargetTask(prefix){
return function(){
if (this.args.length !== 1) {
return grunt.log.fail('Just give the name of the ' + prefix + ' you want like :\ngrunt ' + prefix + ':bower');
}
var done = this.async();
var spawn = require('child_process').spawn;
spawn('./node_modules/.bin/gulp', [ prefix, '--branch='+this.args[0] ].concat(grunt.option.flags()), {
cwd : './node_modules/angular-ui-publisher',
stdio: 'inherit'
}).on('close', done);
};
}
grunt.registerTask('build', fakeTargetTask('build'));
grunt.registerTask('publish', fakeTargetTask('publish'));
//
// HACK TO MAKE TRAVIS WORK
var testConfig = function(configFile, customOptions) {
var options = { configFile: configFile, singleRun: true };
var travisOptions = process.env.TRAVIS && {
browsers: ['Firefox', 'PhantomJS'],
reporters: ['dots', 'coverage', 'coveralls'],
preprocessors: { 'src/*.js': ['coverage'] },
coverageReporter: {
reporters: [{
type: 'text'
}, {
type: 'lcov',
dir: 'coverage/'
}]
},
};
return grunt.util._.extend(options, customOptions, travisOptions);
};
//
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
meta: {
banner: ['/**',
' * <%= pkg.name %> - <%= pkg.description %>',
' * @version v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %>',
' * @link <%= pkg.homepage %>',
' * @license <%= pkg.license %>',
' */',
''].join('\n')
},
connect: {
options: {
base : 'out/built/gh-pages',
open: true,
livereload: true
},
server: { options: { keepalive: true } },
continuous: { options: { keepalive: false } }
},
coveralls: {
options: {
coverage_dir: 'coverage/',
// debug: true
// dryRun: true,
// force: true,
// recursive: true
}
},
karma: {
unit: testConfig('test/karma.conf.js'),
server: {configFile: 'test/karma.conf.js'},
continuous: {configFile: 'test/karma.conf.js', background: true },
coverage: {
configFile: 'test/karma.conf.js',
reporters: ['progress', 'coverage'],
preprocessors: { 'src/*.js': ['coverage'] },
coverageReporter: {
reporters: [{
type: 'text'
}, {
type: 'lcov',
dir: 'coverage/'
}]
},
singleRun: true
},
junit: {
configFile: 'test/karma.conf.js',
reporters: ['progress', 'junit'],
junitReporter: {
outputFile: 'junit/unit.xml',
suite: 'unit'
},
singleRun: true
}
},
jshint: {
src: {
files:{ src : ['src/**/*.js', 'demo/**/*.js'] },
options: { jshintrc: '.jshintrc' }
},
test: {
files:{ src : [ 'test/*.js', 'gruntFile.js'] },
options: grunt.util._.extend({}, grunt.file.readJSON('.jshintrc'), grunt.file.readJSON('test/.jshintrc'))
}
},
uglify: {
build: {
expand: true,
cwd: 'dist',
src: ['*.js', '!*.min.js'],
ext: '.min.js',
dest: 'dist'
}
},
surround: {
options: {
prepend: ['(function(window, angular, undefined) {',
'\'use strict\';'].join('\n'),
append: '})(window, window.angular);'
},
main: {
expand: true,
cwd: 'src',
src: ['*.js'],
dest: 'dist'
}
},
ngmin: {
main: {
expand: true,
cwd: 'src',
src: ['*.js'],
dest: 'dist'
}
},
changelog: {
options: {
dest: 'CHANGELOG.md'
}
},
watch: {
src: {
files: ['src/*'],
tasks: ['jshint:src', 'karma:unit:run', 'dist', 'build:gh-pages']
},
test: {
files: ['test/*.js'],
tasks: ['jshint:test', 'karma:unit:run']
},
demo: {
files: ['demo/*', 'publish.js'],
tasks: ['jshint', 'build:gh-pages']
},
livereload: {
files: ['out/built/gh-pages/**/*'],
options: { livereload: true }
}
}
});
};
| JavaScript | 0 | @@ -343,16 +343,21 @@
surround
+:main
', 'ugli
@@ -359,16 +359,35 @@
'uglify'
+, 'surround:banner'
%5D);%0A g
@@ -3911,24 +3911,127 @@
surround: %7B%0A
+ main: %7B%0A expand: true,%0A cwd: 'src',%0A src: %5B'*.js'%5D,%0A dest: 'dist',%0A
option
@@ -4027,32 +4027,34 @@
options: %7B%0A
+
prepend:
@@ -4116,16 +4116,18 @@
+
+
'%5C'use s
@@ -4145,24 +4145,26 @@
join('%5Cn'),%0A
+
appe
@@ -4197,16 +4197,26 @@
ular);'%0A
+ %7D%0A
%7D,
@@ -4218,28 +4218,30 @@
%7D,%0A
-main
+banner
: %7B%0A
@@ -4260,35 +4260,36 @@
,%0A cwd: '
-src
+dist
',%0A src:
@@ -4310,32 +4310,102 @@
dest: 'dist'
+,%0A options: %7B%0A prepend: '%3C%25= meta.banner %25%3E'%0A %7D
%0A %7D%0A %7D,%0A
|
2f179014aae3bfafab33a1af24c459dc4a353882 | remove old map | app/boot.js | app/boot.js | window.name = 'NG_DEFER_BOOTSTRAP!';
require.config({
waitSeconds: 120,
baseUrl : '/app',
paths: {
'authentication' : 'services/authentication',
'angular' : 'libs/angular-flex/angular-flex',
'ngRoute' : 'libs/angular-route/angular-route.min',
'ngSanitize' : 'libs/angular-sanitize/angular-sanitize.min',
'domReady' : 'libs/requirejs-domready/domReady',
'text' : 'libs/requirejs-text/text',
'bootstrap' : 'libs/bootstrap/dist/js/bootstrap.min',
'lodash' : 'libs/lodash/lodash.min',
'URIjs' : 'libs/uri.js/src',
'linqjs' : 'libs/linqjs/linq.min',
'leaflet' : 'libs/leaflet/dist/leaflet',
'jquery' : 'libs/jquery/dist/jquery.min',
'moment' : 'libs/moment/moment',
'leaflet-directive' : 'js/libs/leaflet/angular-leaflet-directive',
'ng-breadcrumbs' : 'js/libs/ng-breadcrumbs/dist/ng-breadcrumbs.min',
'bootstrap-datepicker': 'libs/bootstrap-datepicker/js/bootstrap-datepicker',
'ionsound' : 'libs/ionsound/js/ion.sound.min',
'jqvmap' : 'js/libs/jqvmap/jqvmap/jquery.vmap',
'jqvmapworld' : 'js/libs/jqvmap/jqvmap/maps/jquery.vmap.world',
'ngAnimate' : 'libs/angular-animate/angular-animate.min',
'ngAria' : 'libs/angular-aria/angular-aria.min',
'ngMaterial' : 'libs/angular-material/angular-material.min',
'ngSmoothScroll' : 'libs/ngSmoothScroll/angular-smooth-scroll.min',
'ammapEU' : 'directives/reporting-display/eu',
'ammap3WorldHigh' : 'directives/reporting-display/worldEUHigh',
'ammap3' : 'libs/ammap3/ammap/ammap',
'ammap-theme' : 'libs/ammap3/ammap/themes/light',
'ammap-resp' : 'libs/ammap3/ammap/plugins/responsive/responsive',
'ammap-export' : 'libs/ammap3/ammap/plugins/export/export.min',
'ammap-ex-fabric' : 'libs/ammap3/ammap/plugins/export/libs/fabric.js/fabric.min',
'ammap-ex-filesaver' : 'libs/ammap3/ammap/plugins/export/libs/FileSaver.js/FileSaver.min',
'ammap-ex-pdfmake' : 'libs/ammap3/ammap/plugins/export/libs/pdfmake/pdfmake.min',
'ammap-ex-vfs-fonts' : 'libs/ammap3/ammap/plugins/export/libs/pdfmake/vfs_fonts',
'ammap-ex-jszip' : 'libs/ammap3/ammap/plugins/export/libs/jszip/jszip.min',
'ammap-ex-xlsx' : 'libs/ammap3/ammap/plugins/export/libs/xlsx/xlsx.min',
},
shim: {
'libs/angular/angular' : { deps: ['jquery'] },
'angular' : { deps: ['libs/angular/angular'] },
'ngRoute' : { deps: ['angular'] },
'ngSanitize' : { deps: ['angular'] },
'leaflet-directive' : { deps: ['angular', 'leaflet'], exports : 'L' },
'ng-breadcrumbs' : { deps: ['angular'] },
'bootstrap' : { deps: ['jquery'] },
'linqjs' : { deps: [], exports : 'Enumerable' },
'leaflet' : { deps: [], exports : 'L' },
'bootstrap-datepicker' : { deps: ['bootstrap'] },
'jqvmap' : { deps: ['jquery'] },
'jqvmapworld' : { deps: ['jqvmap'] },
'ionsound' : { deps: ['jquery'] },
'ngAnimate' : { deps: ['angular'] },
'ngAria' : { deps: ['angular'] },
'ngMaterial' : { deps: ['angular', 'ngAnimate', 'ngAria'] },
'ngSmoothScroll' : { deps: ['angular'] },
'ammapEU' : { deps: ['ammap3'] },
'ammap3WorldHigh' : { deps: ['ammap3'] },
'ammap-theme' : { deps: ['ammap3']},
'ammap-resp' : { deps: ['ammap3']},
'ammap-export' : { deps: ['ammap3']}
},
});
// BOOT
require(['angular', 'domReady!', 'bootstrap', 'app', 'routes', 'index'], function(ng, doc){
ng.bootstrap(doc, ['kmApp']);
ng.resumeBootstrap();
});
| JavaScript | 0.000041 | @@ -1645,73 +1645,8 @@
n',%0A
- 'ammapEU' : 'directives/reporting-display/eu',%0A
|
4ac6b6ee8d880b1fd81bfb0697bf33e4777367c4 | add fail error status | src/utils/helpers.js | src/utils/helpers.js | const { Types } = require('mongoose');
const HTTPStatus = require('http-status');
const { ObjectId } = Types;
/**
* Check an parameter is a string or throw an error.
*/
function checkString(chars, { method, message } = {}) {
if (typeof chars !== 'string') {
throw new Error(message || `String parameter must be given to the ${method || 'unknown'} method.`);
}
}
module.exports.checkString = checkString;
/**
* Check that the resource is compiled before proceeding.
*/
function checkCompile(compile) {
if (compile) {
throw new Error('Resource can not be change once it has been compiled.');
}
}
module.exports.checkCompile = checkCompile;
/**
* Check if the id of an item is a valid.
*/
function checkObjectId(id, { message } = {}) {
if (!id || !ObjectId.isValid(id)) {
const error = new Error(message || 'Request did not contain a valid id.');
error.code = HTTPStatus.BAD_REQUEST;
throw error;
}
}
module.exports.checkObjectId = checkObjectId;
/**
* Check that an item exists.
*/
function checkExists(value, { message } = {}) {
if (!value) {
const error = new Error(message || 'No items were found for the given request.');
error.code = HTTPStatus.NOT_FOUND;
throw error;
}
}
module.exports.checkExists = checkExists;
/**
* Format response.
*/
function formatResponse(data) {
if (data instanceof Error) {
const error = {
status: 'error',
code: data.code || 500,
message: data.message || 'There was an error on the server.',
};
if (data.data) {
error.data = data.data;
}
return error;
}
return {
status: 'success',
code: 200,
data,
};
}
module.exports.formatResponse = formatResponse;
/**
* Format middleware to match express infrastructure.
*/
function middlify(middleware, resources, end = false) {
return (req, res, next) => (async () => middleware({
req,
res,
next,
params: req.params,
body: req.body,
query: req.query,
...resources,
}))()
.then(data => end ? res.status(200).json(formatResponse(data)) : next())
.catch(error => res.status(error.code || 500).json(formatResponse(error)));
}
module.exports.middlify = middlify;
/**
* Format hooks and execute work.
*/
function hookify(key, handler, preHooks, postHooks) {
return async (...args) => {
if (preHooks.has(key)) {
const tasks = preHooks.get(key).map(hook => hook(...args));
await Promise.all(tasks);
}
let data;
try {
data = await handler(...args);
} catch (e) {
if (e && e.name === 'ValidationError') {
const error = new Error(e._message || 'Request validation failed');
error.code = HTTPStatus.BAD_REQUEST;
error.data = e.errors;
throw error;
}
throw e;
}
if (postHooks.has(key)) {
const tasks = postHooks.get(key).map(hook => hook({ ...args[0], data }, ...args.slice(1)));
await Promise.all(tasks);
}
return data;
};
}
module.exports.hookify = hookify;
/**
* Check permissions.
*/
function permissionify(key, permissions) {
return async (...args) => {
let checks = [];
if (permissions.has(key)) {
checks = permissions.get(key).map(check => check(...args));
}
const status = await Promise.all(checks);
if (!status.find(outcome => !!outcome)) {
const error = new Error('Permission denied to access route.');
error.code = HTTPStatus.UNAUTHORIZED;
throw error;
}
};
}
module.exports.permissionify = permissionify;
/**
* Order express routes correctly so they execute correctly
*/
function orderRoutes(a, b) {
const aSegments = a[1].path.split('/').filter(segment => segment.length);
const bSegments = b[1].path.split('/').filter(segment => segment.length);
if (aSegments.length && aSegments.length === bSegments.length) {
let index = 0;
while (index < aSegments.length) {
if (aSegments[index].charAt(0) === ':' && bSegments[index].charAt(0) !== ':') {
return 1;
}
if (bSegments[index].charAt(0) === ':' && aSegments[index].charAt(0) !== ':') {
return -1;
}
index += 1;
}
}
return bSegments.length - aSegments.length;
}
module.exports.orderRoutes = orderRoutes;
| JavaScript | 0.000001 | @@ -1397,16 +1397,31 @@
status:
+ data.status %7C%7C
'error'
@@ -1447,19 +1447,48 @@
code %7C%7C
-500
+HTTPStatus.INTERNAL_SERVER_ERROR
,%0A
@@ -2776,16 +2776,47 @@
errors;%0A
+ error.status = 'fail';%0A
|
c5046367ab151ddb012041c584f26bcf034edd19 | Move index creation to startup | apps/admin/imports/startup/server/mongo-config.js | apps/admin/imports/startup/server/mongo-config.js | import { ProductsCollection } from 'meteor/moreplease:common';
const productIndexes = [
{ productId: 1 },
{ variationId: 1 },
{ storeId: 1 },
];
productIndexes.forEach((index) => {
ProductsCollection.rawCollection().createIndex(index);
});
| JavaScript | 0.000001 | @@ -1,8 +1,48 @@
+import %7B Meteor %7D from 'meteor/meteor';%0A
import %7B
@@ -186,16 +186,41 @@
%7D,%0A%5D;%0A%0A
+Meteor.startup(() =%3E %7B%0A
productI
@@ -247,16 +247,18 @@
x) =%3E %7B%0A
+
Produc
@@ -306,12 +306,18 @@
index);%0A
+ %7D);%0A
%7D);%0A
|
e23adde143972b1ccc9ad962ba1041496eda2337 | remove duplicate mention of sql query files | wallaby-config.js | wallaby-config.js | module.exports = function (wallaby) {
return {
files: [
'src/**/*.js',
'src/queries/**/*.sql',
'test/testUtilities.js'
],
tests: [
'src/queries/**/*.sql',
'test/**/*spec.js'
],
compilers: {
'**/*.js': wallaby.compilers.babel()
},
env: {
type: 'node'
},
delays: {
run: 3000
}
};
}; | JavaScript | 0.000014 | @@ -192,44 +192,8 @@
: %5B%0A
- 'src/queries/**/*.sql',%0A
|
eed809e818a2c595a826799e017e7b6d48ce6272 | Update production to use heroku. | gruntfile.js | gruntfile.js | 'use strict';
// Module dependencies.
var _ = require('lodash');
var defaultAssets = require('./config/assets/default');
var testAssets = require('./config/assets/test');
module.exports = function(grunt) {
// Project Configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
env: {
test: {
NODE_ENV: 'test',
src: 'codeaux.env.json'
},
dev: {
NODE_ENV: 'development',
src: 'codeaux.env.json'
},
prod: {
NODE_ENV: 'production',
src: 'codeaux.env.json'
}
},
watch: {
serverViews: {
files: defaultAssets.server.views,
options: {
livereload: true
}
},
serverJS: {
files: defaultAssets.server.allJS,
tasks: ['jshint', 'jscs'],
options: {
livereload: true
}
},
clientViews: {
files: defaultAssets.client.views,
options: {
livereload: true,
}
},
clientJS: {
files: defaultAssets.client.js,
tasks: ['jshint', 'jscs'],
options: {
livereload: true
}
},
clientCSS: {
files: defaultAssets.client.css,
tasks: ['csslint'],
options: {
livereload: true
}
},
clientSCSS: {
files: defaultAssets.client.sass,
tasks: ['sass', 'csslint'],
options: {
livereload: true
}
},
clientLESS: {
files: defaultAssets.client.less,
tasks: ['less', 'csslint'],
options: {
livereload: true
}
}
},
concurrent: {
default: ['nodemon', 'watch'],
debug: ['nodemon', 'watch', 'node-inspector'],
options: {
logConcurrentOutput: true,
}
},
csslint: {
options: {
csslintrc: '.csslintrc',
},
all: {
src: defaultAssets.client.css
}
},
cssmin: {
combine: {
files: {
'public/dist/application.min.css': defaultAssets.client.css
}
}
},
jscs: {
all: {
src: _.union(defaultAssets.server.allJS, defaultAssets.client.js,
testAssets.tests.server, testAssets.tests.client, testAssets.tests.e2e),
options: {
config: '.jscsrc',
verbose: true
}
}
},
jshint: {
all: {
src: _.union(defaultAssets.server.allJS, defaultAssets.client.js,
testAssets.tests.server, testAssets.tests.client, testAssets.tests.e2e),
options: {
jshintrc: true,
node: true,
mocha: true,
jasmine: true
}
}
},
karma: {
unit: {
configFile: 'karma.conf.js'
}
},
less: {
dist: {
files: [{
expand: true,
src: defaultAssets.client.less,
ext: '.css',
rename: function(base, src) {
return src.replace('/less/', '/css/');
}
}]
}
},
mochaTest: {
src: testAssets.tests.server,
options: {
reporter: 'spec',
require: 'server.js'
}
},
ngAnnotate: {
production: {
files: {
'public/dist/application.js': defaultAssets.client.js
}
}
},
nodemon: {
dev: {
script: 'server.js',
options: {
nodeArgs: ['--debug'],
ext: 'js,html',
watch: _.union(defaultAssets.server.views, defaultAssets.server.allJS, defaultAssets.server.config)
}
}
},
'node-inspector': {
custom: {
options: {
'web-port': 1337,
'web-host': 'localhost',
'debug-port': 5858,
'save-live-edit': true,
'no-preload': true,
'stack-trace-limit': 50,
'hidden': []
}
}
},
protractor: {
options: {
configFile: 'protractor.conf.js',
keepAlive: true,
noColor: false
},
e2e: {
options: {
// Target specific arguments.
args: {}
}
}
},
sass: {
dist: {
files: [{
expand: true,
src: defaultAssets.client.sass,
ext: '.css',
rename: function(base, src) {
return src.replace('/scss/', '/css/');
}
}]
}
},
uglify: {
production: {
options: {
mangle: false
},
files: {
'public/dist/application.min.js': 'public/dist/application.js'
}
}
}
});
// Load NPM tasks
require('load-grunt-tasks')(grunt);
// Making grunt default to force in order not to break the project.
grunt.option('force', true);
// A Task for loading the configuration object
grunt.task.registerTask('loadConfig', 'Connects to MongoDB instance and loads the application models.', function() {
// Get callback.
var callback = this.async();
// Use mongoose configuration to connect to mongo database.
var mongoose = require('./config/lib/mongoose.js');
mongoose.connect(function() {
callback();
});
});
// Lint CSS and JavaScript files.
grunt.registerTask('lint', ['sass', 'less', 'jshint', 'csslint', 'jscs']);
// Build application files and minify them into two production files.
grunt.registerTask('build', ['env:dev', 'lint', 'ngAnnotate', 'uglify', 'cssmin']);
// Run application in testing stage.
grunt.registerTask('test', ['env:test', 'mongoose', 'mochaTest', 'karma:unit']);
grunt.registerTask('test:server', ['env:test', 'mongoose', 'mochaTest']);
grunt.registerTask('test:client', ['env:test', 'mongoose', 'karma:unit']);
// Run application in development stage.
grunt.registerTask('default', ['env:dev', 'lint', 'concurrent:default']);
// Run application in debug stage.
grunt.registerTask('debug', ['env:dev', 'lint', 'concurrent:debug']);
// Run application in production stage.
grunt.registerTask('prod', ['build', 'env:prod', 'concurrent:default']);
};
| JavaScript | 0 | @@ -6053,20 +6053,22 @@
erTask('
-prod
+heroku
', %5B'bui
|
45246a1477a107a4e028afea0821af6bccd8f942 | fix wrong address in invoice | src/server/api/orderApi.js | src/server/api/orderApi.js | const fs = require('fs');
const { authorization, isAdmin } = require('./auth');
const bodyParser = require('body-parser');
const asyncHandler = require('express-async-handler');
const envConfig = require('../../config/envConfig');
const stripe = require('stripe')(envConfig.getSecretKey('PAYMENT_SECRET'));
const esrGenerator = require('../esr/esrGenerator');
const mail = require('../email/mail');
const { saveOrUpdate } = require('../db/mongoHelper');
const esrCodeHelpers = require('../esr/esrCodeHelpers');
const orderConfig = envConfig.getEnvironmentSpecificConfig().ORDER;
const priceCalculation = require('../../common/priceCalculation')
.create(orderConfig.MIN_PRICE_SHIPPING, orderConfig.SHIPPING_COST);
const OrderState = require('../../common/orderState');
const {
Coupon,
Invoice,
Order,
Product,
UserAddress,
} = require('../db/models');
function updateProductStocks(items) {
return Promise.all(items.map(({ amount, product }) =>
Product.update({ _id: product._id }, { $inc: { stock: amount * -1 } }).exec()
));
}
function updateCoupons(itemTotal, coupons) {
const updatedCoupons = priceCalculation.getRemainingCouponsAmount(itemTotal, coupons);
return Promise.all(updatedCoupons.map(coupon => Coupon
.findOneAndUpdate({ _id: coupon._id }, { $set: { amount: coupon.amount } })
.exec()
));
}
async function createAndSendEsr(order, email) {
const { address, total } = order;
const invoice = Invoice.findOneAndUpdate(
{ _id: order.invoice },
{ $set: { value: total, address } },
{ new: true });
const esr = esrCodeHelpers.generateInvoiceNumberCode(invoice.invoiceNumber);
const pdfPath = await esrGenerator.generate(esr, order._id, invoice.value, invoice.address);
await mail.sendESR(order, email, pdfPath);
fs.unlink(pdfPath);
await Invoice.findOneAndUpdate({ _id: invoice._id }, { $set: { esr } });
}
async function mapDbProductsToClientItems(clientItems) {
const products = await Product.find({
_id: { $in: clientItems.map(item => item.product._id) },
});
return clientItems.map((item) => {
item.product = products.find(product => product.id === item.product._id);
return item;
});
}
async function mapDbCouponsToClientCoupons(clientCoupons) {
return Coupon.find({
_id: { $in: clientCoupons.map(coupon => coupon._id) },
});
}
async function chargeCreditCard(order, userId) {
await stripe.charges
.create({
amount: order.total * 100,
description: order._id,
currency: 'chf',
source: userId,
})
.catch(({ message, detail }) => Promise.reject(new Error(`${message} ${detail || ''}`)));
}
module.exports = {
registerEndpoints(app) {
app.get('/api/orders', authorization, isAdmin, asyncHandler(async (req, res) => {
const orders = await Order.find().sort({ date: -1 });
const updatedOrders = await Promise.all(orders.map(async (order) => {
if (order.invoice) {
const invoice = Invoice.findOne({ _id: order.invoice });
return Object.assign({}, order.toObject(), {
esr: invoice.esr,
});
}
return order;
}));
res.send(updatedOrders);
}));
app.put('/api/orders', authorization, bodyParser.json(), asyncHandler(async (req, res) => {
const items = await mapDbProductsToClientItems(req.body.items);
const coupons = await mapDbCouponsToClientCoupons(req.body.coupons);
const itemTotal = priceCalculation.calculateItemTotal(items);
await saveOrUpdate(Order, Object.assign(
req.body,
{
_id: req.body.id,
user: req.user.sub,
state: OrderState.STARTED,
date: Date.now(),
items,
coupons,
itemTotal,
total: priceCalculation.calculateGrandTotal(itemTotal, coupons),
}
));
res.sendStatus(200);
}));
app.post('/api/order/sent', authorization, isAdmin, bodyParser.json(),
asyncHandler(async (req, res) =>
Order
.findOneAndUpdate({ _id: req.body.orderId }, { $set: { state: OrderState.SENT } })
.then(() => res.sendStatus(200))));
app.put('/api/userAddress', authorization, bodyParser.json(), asyncHandler(async (req, res) =>
saveOrUpdate(UserAddress, Object.assign(req.body, { user: req.user.sub }))
.then(address => res.status(200).send(address._id))));
app.get('/api/userAddresses', authorization, asyncHandler(async (req, res) =>
UserAddress
.find({ user: req.user.sub }, { user: 0 })
.then(addresses => res.status(200).send(JSON.stringify(addresses)))));
app.post('/api/payment/cleared', bodyParser.json(), authorization,
asyncHandler(async (req, res) => {
const order = await Order.findOne({ _id: req.body.shoppingCartId, user: req.user.sub });
await chargeCreditCard(order, req.body.token.id);
await updateCoupons(order.itemTotal, order.coupons);
await updateProductStocks(order.items);
await Order.findOneAndUpdate(
{ _id: req.body.shoppingCartId, user: req.user.sub },
{ $set: { state: OrderState.FINISHED } },
{ new: true }
);
res.sendStatus(200);
await mail.sendConfirmation(order, req.user.email);
})
);
app.post('/api/payment/prepayment', bodyParser.json(), authorization,
asyncHandler(async (req, res) => {
const invoice = await new Invoice({ user: req.user.sub }).save();
const updatedOrder = await Order.findOneAndUpdate(
{ _id: req.body.shoppingCartId, user: req.user.sub },
{ $set: { state: OrderState.WAITING, invoice: invoice._id } },
{ new: true });
await updateCoupons(updatedOrder.itemTotal, updatedOrder.coupons);
await updateProductStocks(updatedOrder.items);
res.sendStatus(200);
await createAndSendEsr(updatedOrder, req.user.email);
}));
app.post('/api/payment/prepayment/cleared', bodyParser.json(), authorization, isAdmin,
asyncHandler(async (req, res) => Order
.findOneAndUpdate(
{ _id: req.body.orderId },
{ $set: { state: OrderState.FINISHED } })
.then(() => res.sendStatus(200))
));
app.post('/api/payment/none', bodyParser.json(), authorization,
asyncHandler(async (req, res) => {
const order = await Order.findOneAndUpdate(
{ _id: req.body.shoppingCartId, user: req.user.sub, total: 0 },
{ $set: { state: OrderState.FINISHED } },
{ new: true }
);
await updateCoupons(order.itemTotal, order.coupons);
await updateProductStocks(order.items);
res.sendStatus(200);
await mail.sendConfirmation(order, req.user.email);
}));
},
};
| JavaScript | 0.000013 | @@ -1711,24 +1711,16 @@
.value,
-invoice.
address)
|
ced3dc7dcc2973d69a3f466bc0c4ea1ec95c560c | check to see if we should spot the first spottable element in the list when it is ready | source/DataList.js | source/DataList.js | /**
_moon.DataList_ is an [enyo.DataList](#enyo.DataList) with Moonstone styling
applied. It uses [moon.Scroller](#moon.Scroller) as its default scroller.
*/
enyo.kind({
name: "moon.DataList",
kind: "enyo.DataList",
//* @protected
noDefer: true,
allowTransitions: false,
scrollerOptions: { kind: "moon.Scroller", horizontal: "hidden" }
});
//* @protected
/**
Overload the delegate strategy to incorporate measurements for our scrollers
when they are visible.
*/
(function (enyo, moon) {
moon.DataList.delegates.vertical = enyo.clone(moon.DataList.delegates.vertical);
moon.DataList.delegates.horizontal = enyo.clone(moon.DataList.delegates.horizontal);
var exts = {
refresh: enyo.inherit(function (sup) {
return function (list) {
sup.apply(this, arguments);
list.$.scroller.resized();
};
}),
scrollToIndex: function (list, i) {
// first see if the child is already available to scroll to
var c = this.childForIndex(list, i),
// but we also need the page so we can find its position
p = this.pageForIndex(list, i),
d = this;
// if there is no page then the index is bad
if (p < 0 || p > this.pageCount(list)) { return; }
// if there isn't one, then we know we need to go ahead and
// update, otherwise we should be able to use the scroller's
// own methods to find it
if (c) {
list.$.scroller.scrollToControl(c, true);
} else {
// list.$.scroller.resizing = true;
var x, y, fn;
fn = function (sender, event, props) {
if (i >= props.start && i <= props.end) {
var c = d.childForIndex(list, i);
if (c) {
list.removeListener("paging", fn);
list.$.scroller.scrollToControl(c, true);
}
}
};
list.addListener("paging", fn);
if (list.orientation == "vertical") {
x = 0;
y = this.pagePosition(list, p);
} else {
x = this.pagePosition(list, p);
y = 0;
}
list.$.scroller.scrollTo(x, y);
}
}
};
enyo.kind.extendMethods(moon.DataList.delegates.vertical, exts, true);
enyo.kind.extendMethods(moon.DataList.delegates.vertical, {
reset: enyo.inherit(function (sup) {
return function (list) {
sup.apply(this, arguments);
if (list.$.scroller.getVertical() != "scroll") {
this.updateBounds(list);
list.refresh();
}
};
}),
updateBounds: enyo.inherit(function (sup) {
return function (list) {
sup.apply(this, arguments);
var w = list.boundsCache.width,
b = list.$.scroller.getScrollBounds(),
n = list.$.scroller.$.strategy.$.vColumn.hasNode();
if (list.$.scroller.getVertical() == "scroll" || (b.height > b.clientHeight)) {
list.boundsCache.width = w-n.offsetWidth;
}
};
})
}, true);
enyo.kind.extendMethods(moon.DataList.delegates.horizontal, exts, true);
enyo.kind.extendMethods(moon.DataList.delegates.horizontal, {
reset: enyo.inherit(function (sup) {
return function (list) {
sup.apply(this, arguments);
if (list.$.scroller.getHorizontal() != "scroll") {
this.updateBounds(list);
list.refresh();
}
list.$.scroller.scrollTo(0, 0);
};
}),
updateBounds: enyo.inherit(function (sup) {
return function (list) {
sup.apply(this, arguments);
var w = list.boundsCache.height,
b = list.$.scroller.getScrollBounds(),
n = list.$.scroller.$.strategy.$.hColumn.hasNode();
if (list.$.scroller.getVertical() == "scroll" || (b.width > b.clientWidth)) {
list.boundsCache.height = w-n.offsetHeight;
}
};
})
}, true);
})(enyo, moon);
| JavaScript | 0 | @@ -272,16 +272,34 @@
false,%0A
+%09spotlight: true,%0A
%09scrolle
@@ -355,16 +355,199 @@
idden%22 %7D
+,%0A%09didReset: function () %7B%0A%09%09var spot = enyo.Spotlight.getCurrent();%0A%09%09if (spot === this %7C%7C spo.isDescendentOf(this)) %7B%0A%09%09%09this.spotlight = false;%0A%09%09%09enyo.Spotlight.spot(this);%0A%09%09%7D%0A%09%7D
%0A%7D);%0A//*
|
a20bd5f6cc2d3d1a1d4d0b9d47f2f854072b7e84 | bump version | track-slide.js | track-slide.js | /* track-slide
* version: 1.3.0
* https://stash.c2mpg.com:8443/projects/C2/repos/track-slide
* @preserve
*/
/*exported TrackSlide */
var TrackSlide = (function ($, Dragger) {
'use strict';
var defaults = {
pageLock: false,
trackSelector: 'ul',
cellSelector: 'li',
autoResize: 'true',
animationDuration: 400,
useTransform: false
};
var previous = function () {
var num = this.current - 1;
if (num < 0) return;
moveTo.call(this, num);
};
var next = function () {
var num = this.current + 1;
if (num > this.len - this.m.fit) return;
moveTo.call(this, num);
};
var previousPage = function () {
if (this.opts.pageLock) {
previous.call(this);
return;
}
if (this.current === 0) return;
var num = this.current - this.m.fit;
if (num < 0) num = 0;
moveTo.call(this, num);
};
var nextPage = function () {
if (this.opts.pageLock) {
next.call(this);
return;
}
var max = this.len - this.m.fit;
if (this.current === max) return;
var num = this.current + this.m.fit;
if (num > max) num = max;
moveTo.call(this, num);
};
var moveTo = function (index) {
var distance;
index = Math.max(0, index);
if (this.opts.pageLock) {
index = Math.min(index, Math.ceil(this.len / this.m.fit) - 1);
distance = index * this.m.fit * this.m.item + index * this.m.fit * this.m.gap;
} else {
index = Math.min(index, this.len - this.m.fit);
// How far from the left is the item
distance = index * this.m.item + index * this.m.gap;
// If the track is longer than the bounds
// And the distance to the item is greater than the difference between the bounds and the length of the track
// Set the distance to the difference
if (this.m.track > this.m.bounds && distance > this.m.track - this.m.bounds) {
distance = this.m.track - this.m.bounds;
}
}
if (this.opts.useTransform) {
this.$track.css('transform', 'translate(' + -distance + 'px, 0px)');
} else {
this.$track.stop(true).animate({'left': -distance}, this.opts.animationDuration, 'swing');
}
this.dragger.setPosition({
x: -distance,
y: 0
});
this.current = index;
// trigger moved event
};
var onStart = function (handle) {
if (this.opts.useTransform) {
this.$el.addClass('isDragging');
}
};
var onDrag = function (handle) {
if (this.opts.useTransform) {
this.$track.css('transform', 'translate(' + handle.x + 'px, 0px)');
} else {
this.$track.css('left', handle.x);
}
};
var onStop = function (handle, hasDragged) {
if (this.opts.useTransform) {
this.$el.removeClass('isDragging');
}
if (!hasDragged) return;
// hard to know what to set the offset value to
var offset = 0; //(this.m.item / 3);
var closest;
if (this.opts.pageLock) {
closest = Math.round(handle.x / ((this.m.item + this.m.gap) * this.m.fit));
} else {
closest = Math.round((handle.x - offset) / (this.m.item + this.m.gap));
}
moveTo.call(this, -closest);
};
var getMeasurement = function () {
var bounds = this.$el.width();
var track = this.$track.outerWidth();
var trackPadding = track - this.$track.width();
var item = this.$items.eq(0).outerWidth();
var gap = 0;
if (this.len > 1) {
gap = this.$items.get(1).getBoundingClientRect().left - this.$items.get(0).getBoundingClientRect().left - item;
}
var fit = (bounds - trackPadding + gap) / (item + gap);
fit = Math.min(Math.floor(fit), this.len);
return {
'bounds': bounds,
'track': track,
'item': item,
'gap': gap,
'fit': fit
};
};
var resize = function () {
this.m = getMeasurement.call(this);
moveTo.call(this, this.current);
};
var setFocus = function (e) {
if (this.dragger.isDragging) return;
var index = this.$items.index(e.delegateTarget);
// move the track if the focused element is out of view
if (index < this.current) {
moveTo.call(this, index);
}
if (index >= this.current + this.m.fit) {
moveTo.call(this, index - this.m.fit + 1);
}
};
var bindEvents = function () {
if (this.opts.autoResize) {
$(window).on('resize', debounce(resize.bind(this)));
}
this.$items.on('focus', setFocus.bind(this));
};
var getDraggerOptions = function () {
return {
'drag': onDrag.bind(this),
'stop': onStop.bind(this),
'allowVerticalScrolling': true
};
};
var init = function () {
if (!this.$el.length) return false;
this.$track = this.$el.find(this.opts.trackSelector);
if (!this.$track.length) return false;
this.$items = this.$track.find(this.opts.cellSelector);
this.len = this.$items.length;
this.m = getMeasurement.call(this);
this.current = 0;
this.dragger = new Dragger(this.$el, getDraggerOptions.call(this));
bindEvents.call(this);
return true;
};
TrackSlide = function (el, options) {
this.$el = $(el);
this.opts = $.extend({}, defaults, options);
this.result = init.call(this);
};
TrackSlide.prototype.moveTo = moveTo;
TrackSlide.prototype.resize = resize;
TrackSlide.prototype.previous = previous;
TrackSlide.prototype.next = next;
TrackSlide.prototype.previousPage = previousPage;
TrackSlide.prototype.nextPage = nextPage;
TrackSlide.prototype.resize = resize;
function debounce(fn) {
if (typeof requestAnimationFrame === 'undefined') {
return fn;
}
var id = null;
return function () {
var args = arguments;
if (id !== null) {
cancelAnimationFrame(id);
}
id = requestAnimationFrame(function () {
fn.apply(null, args);
id = null;
});
};
}
return TrackSlide;
}(jQuery, Dragger));
| JavaScript | 0 | @@ -24,17 +24,17 @@
on: 1.3.
-0
+1
%0A * http
|
db99aa64320324291b69ae94d44c725d08f0d3a6 | Use uuid strings as key. | src/server/models/index.js | src/server/models/index.js | import mongoose from 'mongoose';
import marked from 'marked';
import crypto from 'crypto';
import uuid from 'node-uuid';
const PasswordCode = new mongoose.Schema({
_id: { type: String, unique: true, required: true, default: uuid.v4 }, // uuid
user: { type: String, required: true },
created: { type: Date, required: true, default: Date.now },
});
const RememberMeToken = new mongoose.Schema({
_id: { type: String, unique: true, required: true }, // uuid
user: { type: String, required: true },
created: { type: Date, required: true, default: Date.now },
});
const GroupSchema = new mongoose.Schema({
_id: { type: String, unique: true, required: true },
name: { type: String, trim: true, required: true },
organization: { type: String, ref: 'Organization' },
members: [{
user: { type: String, ref: 'User' },
role: {
title: { type: String, trim: true },
email: { type: String, trim: true },
},
}],
group_email: { type: String, lowercase: true, trim: true },
group_leader_email: { type: String, lowercase: true, trim: true },
externally_hidden: { type: Boolean, default: false },
old_id: { type: Number },
});
GroupSchema.set('toObject', {
virtuals: true,
});
GroupSchema.set('toJSON', {
virtuals: true,
});
const UserSchema = new mongoose.Schema({
_id: { type: String, lowercase: true, trim: true, required: true, unique: true },
username: { type: String, lowercase: true, trim: true, required: true, unique: true },
name: { type: String, required: true },
email: { type: String },
password: { type: String, select: false },
algorithm: { type: String, select: false },
salt: { type: String, select: false },
groups: [{ type: String, ref: 'Group' }],
friends: [{ type: String, ref: 'User' }],
is_active: { type: Boolean, default: true }, // just for blocking users
is_admin: { type: Boolean, default: false },
created: { type: Date, required: true, default: Date.now },
nmf_id: { type: String, select: false },
facebook_id: { type: String, unique: true, sparse: true, select: false },
google_id: { type: String, unique: true, sparse: true, select: false },
twitter_id: { type: String, unique: true, sparse: true, select: false },
phone: { type: String },
address: { type: String },
postcode: { type: String },
city: { type: String },
country: { type: String },
born: { type: Date },
joined: { type: Date },
instrument: { type: String },
instrument_insurance: { type: Boolean, select: false },
reskontro: { type: String, select: false },
membership_history: { type: String, select: false },
profile_picture: { type: String, ref: 'File' },
profile_picture_path: { type: String },
membership_status: { type: Number },
// from membership_status
in_list: { type: Boolean, required: true, default: true },
on_leave: { type: Boolean, required: true, default: false },
no_email: { type: Boolean, required: true, default: false },
social_media: {
website: { type: String },
blog: { type: String },
google: { type: String },
twitter: { type: String },
facebook: { type: String },
instagram: { type: String },
},
});
UserSchema.methods.authenticate = function authenticateUser(candidate, callback) {
const hashedPassword = crypto.createHash(this.algorithm);
hashedPassword.update(this.salt);
hashedPassword.update(candidate);
if (this.password === hashedPassword.digest('hex')) {
return callback(null, this);
}
return callback('Bad password', null);
};
UserSchema.set('toJSON', {
versionKey: false,
transform: (document, ret) => {
ret.id = ret._id;
delete ret._id;
},
});
UserSchema.set('toObject', {
versionKey: false,
transform: (document, ret) => {
ret.id = ret._id;
delete ret._id;
},
});
const OrganizationSchema = new mongoose.Schema({
_id: { type: String, lowercase: true, trim: true, required: true, unique: true },
name: { type: String },
webdomain: { type: String, trim: true },
instrument_groups: [{ type: String, ref: 'Group' }],
contact_groups: [{ type: String, ref: 'Group' }], // contacts page
administration_group: { type: String, ref: 'Group' }, // temp
musicscoreadmin_group: { type: String, ref: 'Group' },
member_group: { type: String, ref: 'Group' },
contact_text: { type: String, trim: true },
visitor_address: { type: String, trim: true },
mail_address: { type: String, trim: true },
postcode: { type: String, trim: true },
city: { type: String, trim: true },
email: { type: String, trim: true },
organization_number: { type: String, trim: true },
public_bank_account: { type: String, trim: true },
map_url: { type: String, trim: true },
social_media: {
website: { type: String },
blog: { type: String },
google: { type: String },
twitter: { type: String },
facebook: { type: String },
instagram: { type: String },
},
description: {}, // mixed hash of locale keys and values
description_nb: { type: String },
tracking_code: { type: String },
summaries: [{ type: String, ref: 'Page' }],
});
OrganizationSchema.virtual('encoded_email').get(function email() {
return marked(`<${this.email}>`);
});
OrganizationSchema.virtual('website').get(function website() {
return this.social_media.website;
});
OrganizationSchema.virtual('twitter').get(function twitter() {
return this.social_media.twitter;
});
OrganizationSchema.virtual('facebook').get(function facebook() {
return this.social_media.facebook;
});
OrganizationSchema.set('toObject', {
virtuals: true,
});
OrganizationSchema.set('toJSON', {
virtuals: true,
});
const ActivitySchema = new mongoose.Schema({
content_type: { type: String, required: true },
content_ids: [{ type: String }],
title: { type: String, required: true },
project: { type: String, ref: 'Project' },
tags: [{ type: String }],
content: {}, // mixed
changes: [{
changed: { type: Date },
user: { type: String, ref: 'User' },
}],
permissions: {
groups: [{ type: String, ref: 'Group' }],
users: [{ type: String, ref: 'User' }],
public: { type: Boolean, default: false },
},
modified: { type: Date, default: Date.now },
});
module.exports = {
schema: {
user: UserSchema,
group: GroupSchema,
},
PasswordCode: mongoose.model('PasswordCode', PasswordCode),
RememberMeToken: mongoose.model('RememberMeToken', RememberMeToken),
User: mongoose.model('User', UserSchema),
Group: mongoose.model('Group', GroupSchema),
Organization: mongoose.model('Organization', OrganizationSchema),
Activity: mongoose.model('Activity', ActivitySchema),
};
| JavaScript | 0.000001 | @@ -232,24 +232,16 @@
id.v4 %7D,
- // uuid
%0A use
@@ -449,19 +449,29 @@
true
- %7D, // uuid
+, default: uuid.v4 %7D,
%0A
|
2d38d5c757394899bb71dc305b8827c17f93706b | Fix grunt files src not parsing correctly | gruntfile.js | gruntfile.js | 'use strict';
module.exports = function (grunt) {
if (grunt.option('help')) {
require('load-grunt-tasks')(grunt);
} else {
require('jit-grunt')(grunt, {
force: 'grunt-force-task',
});
}
require('time-grunt')(grunt);
var concatConfig = {
dist: {
src: [
'<%= config.files.src $>',
],
dest: 'dist/angular-token-auth.js',
},
};
var uglifyConfig = {
dist: {
options: {
screwIE8: false,
},
files: {
'dist/angular-token-auth.min.js': 'dist/angular-token-auth.js',
},
},
};
var watchConfig = {
lint: {
files: ['<%= config.files.lint %>'],
tasks: ['lint'],
},
build: {
files: ['<%= config.files.src $>'],
tasks: ['build'],
},
};
grunt.initConfig({
config: {
lib: 'bower_components',
modules: 'src',
files: {
src: 'src/**/*.js',
lint: [
'<%= config.files.src $>',
'<%= config.files.karmaMocks %>',
'<%= config.files.karmaTests %>',
'./grunt/**/*.js',
'Gruntfile.js',
],
karmaMocks: 'tests/mocks/**/*.js',
karmaTests: 'tests/unit/**/*.js',
},
},
eslint: {
all: {
options: {
config: '.eslintrc',
},
src: '<%= config.files.lint %>',
},
},
concat: concatConfig,
uglify: uglifyConfig,
watch: watchConfig,
});
// Load external grunt task config.
grunt.loadTasks('./grunt');
grunt.registerTask('default', [
'test',
]);
grunt.registerTask('build', 'Concat and uglify', [
'concat',
'uglify',
]);
grunt.registerTask('lint', 'Run the JS linters.', [
'eslint',
]);
grunt.registerTask('test', 'Run the tests.', function (env) {
var karmaTarget = 'dev';
if (grunt.option('debug')) {
karmaTarget = 'debug';
}
if (env === 'ci' || env === 'travis') {
karmaTarget = 'ci';
}
grunt.task.run([
'force:lint',
'force:karma:' + karmaTarget,
'errorcodes',
]);
});
grunt.registerTask('travis', 'Run the tests in Travis', [
'test:travis',
]);
// This is used in combination with grunt-force-task to make the most of a
// Travis build, so all tasks can run but the build will fail if any of the
// tasks failed/errored.
grunt.registerTask('errorcodes', 'Fatally error if any errors or warnings have occurred but Grunt has been forced to continue', function () {
grunt.log.writeln('errorcount: ' + grunt.fail.errorcount);
grunt.log.writeln('warncount: ' + grunt.fail.warncount);
if (grunt.fail.warncount > 0 || grunt.fail.errorcount > 0) {
grunt.fatal('Errors have occurred.');
}
});
};
| JavaScript | 0 | @@ -298,32 +298,58 @@
dist: %7B%0A
+ files: %5B%7B%0A
src:
@@ -359,32 +359,36 @@
+
+
'%3C%25= config.file
@@ -385,33 +385,33 @@
onfig.files.src
-$
+%25
%3E',%0A
@@ -402,35 +402,43 @@
%3E',%0A
+
+
%5D,%0A
+
dest
@@ -461,32 +461,48 @@
token-auth.js',%0A
+ %7D%5D,%0A
%7D,%0A %7D
@@ -939,17 +939,17 @@
les.src
-$
+%25
%3E'%5D,%0A
@@ -1227,9 +1227,9 @@
src
-$
+%25
%3E',%0A
|
23e331af8f00f2d1cd8134639378d058d5e656b5 | add interface in repo dao | src/servers/dao/RepoDAO.js | src/servers/dao/RepoDAO.js | /**
* Created by raychen on 16/8/16.
*/
import {userSchema} from '../../models/userSchema'
import {github_repoSchema} from '../../models/github_repoSchema'
import {github_userSchema} from '../../models/github_userSchema'
import {connect} from '../config'
import {getPublicRepos, getUserStarred} from '../api/github_user'
async function getStarRepoByUser(login) {
let t = await new Promise(function (resolve, reject) {
github_userSchema.findOne({login: login}, async (err, user) => {
if (err) reject(err);
let ans = [];
for (let repo of user.star_repos){
let repo_det = await new Promise(function(resolve2, reject2) {
github_repoSchema.findOne({full_name: repo}, (err, repo_one) => {
if (err) reject2(err);
resolve2(repo_one.stars_count);
});
});
ans.push({
fullname: repo,
stars: repo_det
})
}
resolve(ans);
});
});
return t;
}
async function getPublicRepoByUser(login) {
let t = await new Promise(function (resolve, reject) {
github_userSchema.findOne({login: login}, async (err, user) => {
if (err) reject(err);
resolve(user.repos);
});
});
return t;
}
export {getStarRepoByUser, getPublicRepoByUser}
async function test() {
connect();
let t = await getPublicRepoByUser("RickChem");
console.log(t);
}
//test();
| JavaScript | 0 | @@ -319,16 +319,275 @@
_user'%0A%0A
+async function getRepoInfo(fullname)%7B%0A let t = await new Promise(function(resolve, reject) =%3E %7B%0A github_repoSchema.findOne(%7Bfull_name: fullname%7D, (err, repo_single) =%3E %7B%0A if (err) reject(err);%0A resolve(repo_single);%0A %7D);%0A %7D);%0A return t;%0A%7D%0A%0A
async fu
@@ -1526,16 +1526,29 @@
poByUser
+, getRepoInfo
%7D%0A%0Aasync
|
7fea8795c4412be69b6ad4ce94468d8b61e3c4de | allow immediate (synchronous) call to debounced function | src/shared/lib/debounce.js | src/shared/lib/debounce.js | /** Created by hhj on 1/14/16. */
/* eslint-disable func-names */
/**
* Usage:
* debounce.call(this, fn, delay)
* or
* debounce(fn, delay, this)
* or
* debounce(fn, delay).bind(this)
*
* @param fn Function to be debounced
* @param delay
* @param __context
* @returns {debounced} Debounced function as promise
*/
export default function debounce(fn, delay, __context) {
let timeout
const _context = __context || this
const debounced = function(...args) {
const context = _context || this
clearTimeout(timeout)
return new Promise(resolve => {
timeout = setTimeout(() => {
resolve(fn.apply(context, args))
}, delay)
})
}
debounced.cancel = function() {
clearTimeout(timeout)
timeout = null
}
return debounced
}
| JavaScript | 0 | @@ -461,16 +461,17 @@
function
+
(...args
@@ -470,24 +470,24 @@
(...args) %7B%0A
-
const co
@@ -533,24 +533,130 @@
ut(timeout)%0A
+%0A // immediate call (bounded to desired context):%0A if (delay === 0) return fn.apply(context, args)%0A%0A
return n
@@ -783,16 +783,16 @@
%7D)%0A %7D%0A%0A
-
deboun
@@ -812,16 +812,17 @@
function
+
() %7B%0A
|
16701c581bb986ccfae2870d4553090448703b56 | Remove unnecessary defer call | temple.js | temple.js | var Temple = {};
Temple.instanceCount = new ReactiveDict();
Template.onRendered(function () {
var self = this;
Meteor.defer(function () {
// We're going to get the element that surrounds that template
var node = $(self.firstNode).parent();
if (node.closest('#Mongol').length) {
return;
}
if (node && node.nodeType !== 3) { // get rid of text nodes
var template = self.view.name;
var currentCount = Temple.instanceCount.get('Temple_render_count_' + template) || 1;
$node = node;
var fix = ($node.css('position') === 'fixed') ? true : false;
$node.addClass('is-template').attr('data-template', (($node.attr('data-template')) ? $node.attr('data-template') + ' ' : '') + template + ' (' + currentCount + ')');
// avoid giving position:relative to fixed elements
if (fix) {
$node.css('position', 'fixed');
}
Temple.instanceCount.set('Temple_render_count_' + template, currentCount + 1);
}
});
});
Meteor.startup(function () {
$(document).keydown(function (e) {
if (e.keyCode == 84 && e.ctrlKey) {
Session.set('Temple_activated', !Session.get('Temple_activated'));
}
});
Tracker.autorun(function () {
if (Session.get('Temple_activated')) {
$('body').addClass('temple-activated');
}
else {
$('body').removeClass('temple-activated');
}
});
});
if (!!Package["msavin:mongol"]) {
// Replace default Mongol header
Template.Mongol_temple_header.replaces("Mongol_header");
Template.Mongol_header.helpers({
templeActivated : function () {
return (Session.get('Temple_activated')) ? 'Temple_activated' : '';
}
});
Template.Mongol_temple_header.inheritsHelpersFrom("Mongol_header");
Template.Mongol_header.events({
'click .Temple_activate' : function (evt) {
evt.stopPropagation();
Session.set('Temple_activated', !Session.get('Temple_activated'));
}
});
Template.Mongol_temple_header.inheritsEventsFrom("Mongol_header");
} | JavaScript | 0.000001 | @@ -118,45 +118,8 @@
%0A %0A
- Meteor.defer(function () %7B %0A
//
@@ -179,18 +179,16 @@
emplate%0A
-
var no
@@ -222,23 +222,19 @@
nt();%0A
- %0A
+%0A
-
if (node
@@ -263,26 +263,24 @@
ngth) %7B%0A
-
return; %0A
@@ -277,29 +277,23 @@
turn; %0A
-
%7D%0A
- %0A
+%0A
if (no
@@ -350,25 +350,21 @@
des%0A
-
%0A
-
var temp
@@ -386,18 +386,16 @@
w.name;%0A
-
var
@@ -475,18 +475,16 @@
) %7C%7C 1;%0A
-
$nod
@@ -493,21 +493,17 @@
= node;%0A
- %0A
+%0A
var
@@ -560,29 +560,25 @@
false;%0A
- %0A
+%0A
$node.ad
@@ -735,29 +735,25 @@
+ ')');%0A
- %0A
+%0A
// avoid
@@ -800,18 +800,16 @@
nts%0A
-
if (fix)
@@ -807,26 +807,24 @@
if (fix) %7B%0A
-
$node.
@@ -861,21 +861,15 @@
-
%7D%0A
-
- %0A
+%0A
@@ -955,25 +955,12 @@
-
%0A
- %7D%0A %0A %7D);
+%7D
%0A %0A
|
44d49f0d15aac1fccd423a368b7deef3ef2668f7 | Fix typo for aadhaarNo functions | custom/aaa/static/aaa/js/models/person.js | custom/aaa/static/aaa/js/models/person.js | hqDefine("aaa/js/models/person", [
'jquery',
'knockout',
'underscore',
'moment/moment',
'hqwebapp/js/initial_page_data',
], function (
$,
ko,
_,
moment,
initialPageData
) {
var personModel = function (data, postData) {
var self = {};
self.id = data.id;
self.name = data.name;
self.gender = data.sex;
self.status = data.migration_status;
self.dob = data.dob;
self.marriedAt = data.age_marriage || 'N/A';
self.aadhaarNo = data.has_aadhar_number;
self.address = data.hh_address;
self.subcentre = data.sc;
self.village = data.village;
self.anganwadiCentre = data.awc;
self.phone = data.contact_phone_number;
self.religion = data.hh_religion;
self.caste = data.hh_caste;
self.bplOrApl = data.hh_bpl_apl;
self.age = ko.computed(function () {
if (self.dob === 'N/A') {
return self.dob;
}
var age = Math.floor(moment(new Date()).diff(moment(self.dob, "YYYY-MM-DD"),'months',true));
if (age < 12) {
return age + " Mon";
} else if (age % 12 === 0) {
return Math.floor(age / 12) + " Yr";
} else {
return Math.floor(age / 12) + " Yr " + age % 12 + " Mon";
}
});
self.gender = ko.computed(function () {
if (self.gender === 'N/A') {
return self.gender;
}
return self.gender === 'M' ? 'Male' : 'Female';
});
self.aadhaarNo = ko.computed(function () {
if (self.gender === 'N/A') {
return self.aadhaarNo;
}
return self.aadhaarNo ? 'Yes' : 'No';
});
self.nameLink = ko.computed(function () {
var url = initialPageData.reverse('unified_beneficiary_details');
url = url.replace('details_type', 'eligible_couple');
url = url.replace('beneficiary_id', 1);
url = url + '?month=' + postData.selectedMonth() + '&year=' + postData.selectedYear();
return '<a href="' + url + '">' + self.name + '</a>';
});
return self;
};
return {
personModel: personModel,
};
});
| JavaScript | 0.999984 | @@ -1658,38 +1658,41 @@
if (self.
-gender
+aadhaarNo
=== 'N/A') %7B%0A
|
73b04cbc64f5175948dfd83cb81bf1845f153538 | Fix tests for safari | test/ext/promise.test.js | test/ext/promise.test.js | var should = require('../../');
var Promise = require('bluebird');
function promised(value) {
return new Promise(function(resolve) {
resolve(value);
});
}
function promiseFail() {
return new Promise(function(resolve, reject) {
reject(new Error('boom'));
});
}
function promiseFailTimeout() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
reject(new Error('boom'));
}, 1000);
});
}
it('should return new assertion to hold promise', function() {
var a = promised('abc').should.finally;
return a.then.should.be.a.Function();
});
it('should determine if it is Promise', function() {
promised('a').should.be.a.Promise();
});
it('should allow to chain calls like with usual assertion', function() {
return promised('abc').should.finally.be.exactly('abc')
.and.be.a.String();
});
it('should allow to use .not and .any', function() {
return promised({a: 10, b: 'abc'}).should.finally.not.have.any.of.properties('c', 'd')
.and.have.property('a', 10);
});
it('should treat assertion like promise', function() {
return Promise.all([
promised(10).should.finally.be.a.Number(),
promised('abc').should.finally.be.a.String()
]);
});
it('should propagate .not before .finally', function() {
return promised(10).should.not.finally.be.a.String();
});
it('should be possible to use .eventually as an alias for .finally', function() {
return promised(10).should.eventually.be.a.Number();
});
it('should allow to check if promise fulfilled', function() {
return Promise.all([
promised(10).should.be.fulfilled(), //positive
promiseFail().should.be.fulfilled().then(function() {//negative
should.fail();
}, function(err) {
err.should.be.Error().and.match({message: 'expected [Promise] to be fulfilled, but it was rejected with Error { message: \'boom\' }'});
}),
promised(10).should.not.be.fulfilled().then(function() {//positive fail
should.fail();
}, function(err) {
err.should.be.Error().and.match({message: 'expected [Promise] not to be fulfilled'});
}),
promiseFail().should.not.be.fulfilled()//negative fail
]);
});
it('should be allow to check if promise is fulfilledWith a value', function() {
return Promise.all([
promised(10).should.be.fulfilledWith(10), //positive
promiseFail().should.be.fulfilledWith(10).then(function() {//negative
should.fail();
}, function(err) {
err.should.be.Error().and.match({message: 'expected [Promise] to be fulfilled with 10, but it was rejected with Error { message: \'boom\' }'});
}),
promised(10).should.not.be.fulfilledWith(10).then(function() {//positive fail
should.fail();
}, function(err) {
err.should.be.Error().and.match({message: 'expected [Promise] not to be fulfilled with 10'});
}),
promiseFail().should.not.be.fulfilledWith(10)//negative fail
]);
});
it('should be allow to check if promise rejected', function() {
return Promise.all([
promiseFail().should.be.rejected(), //positive
promised(10).should.be.rejected().then(function() {//negative
should.fail();
}, function(err) {
err.should.be.Error().and.match({message: 'expected [Promise] to be rejected, but it was fulfilled with 10'});
}),
promiseFail().should.not.be.rejected().then(function() {//positive fail
should.fail();
}, function(err) {
err.should.be.Error().and.match({message: 'expected [Promise] not to be rejected'});
}),
promised(10).should.not.be.rejected()//negative fail
]);
});
it('should allow to match rejected error', function() {
return Promise.all([
promiseFail().should.be.rejectedWith(Error),
promiseFail().should.be.rejectedWith('boom'),
promiseFail().should.be.rejectedWith('boom1').then(function() {
return should.fail();
}, function(err) {
return err.should.be.Error().and.match({ message: 'expected [Promise] to be rejected with a message matching \'boom1\', but got \'boom\''});
}),
promiseFail().should.be.rejectedWith(/boom/),
promiseFail().should.be.rejectedWith(Error, { message: 'boom' }),
promiseFail().should.be.rejectedWith({ message: 'boom' }),
promiseFail().should.not.be.rejectedWith().then(function() {//positive fail
return should.fail();
}, function(err) {
return err.should.be.Error().and.match({message: 'expected [Promise] not to be rejected'});
}),
promised(10).should.be.rejectedWith().then(function() {//negative fail
return should.fail();
}, function(err) {
return err.should.be.Error().and.match({message: 'expected [Promise] to be rejected'});
}),
promiseFail().should.not.be.rejectedWith(Error).then(function() {//negative fail
return should.fail();
}, function(err) {
return err.should.be.Error().and.match({message: 'expected [Promise] not to be rejected'});
})
]);
});
it('should properly check async promise', function() {
return promiseFailTimeout().should.be.rejectedWith(Error, { message: 'boom' });
});
| JavaScript | 0.000003 | @@ -1759,33 +1759,33 @@
match(%7Bmessage:
-'
+/
expected %5BPromis
@@ -1773,32 +1773,33 @@
: /expected
+%5C
%5BPromise
%5D to be fulf
@@ -1778,32 +1778,33 @@
pected %5C%5BPromise
+%5C
%5D to be fulfille
@@ -1829,34 +1829,41 @@
cted with Error
-%7B
+%5C%7B%5B%5Cs%5CS%5D*
message: %5C'boom%5C
@@ -1851,35 +1851,40 @@
S%5D*message:
-%5C
'boom
-%5C' %7D'
+'%5B%5Cs%5CS%5D*%5C%7D/
%7D);%0A %7D),%0A
@@ -2491,33 +2491,33 @@
match(%7Bmessage:
-'
+/
expected %5BPromis
@@ -2505,32 +2505,33 @@
: /expected
+%5C
%5BPromise
%5D to be fulf
@@ -2510,32 +2510,33 @@
pected %5C%5BPromise
+%5C
%5D to be fulfille
@@ -2577,18 +2577,25 @@
h Error
-%7B
+%5C%7B%5B%5Cs%5CS%5D*
message:
@@ -2599,19 +2599,25 @@
ge:
-%5C
'boom%5C'
- %7D'
+%5B%5Cs%5CS%5D*%5C%7D/
%7D);%0A
|
ec51e549f0183da723562a252fcb73ef83b4844b | Remove console.log | test/git-diff-archive.js | test/git-diff-archive.js | "use strict";
const fs = require("fs");
const path = require("path");
const assert = require("power-assert");
const glob = require("glob");
const rimraf = require("rimraf");
const unzip = require("unzip");
const gitDiffArchive = require("../");
const ID1 = "b148b54";
const ID2 = "acd6e6d";
const EMPTY_ID1 = "f74c8e2";
const EMPTY_ID2 = "574443a";
const OUTPUT_DIR = `${__dirname}/tmp`;
const OUTPUT_PATH = `${OUTPUT_DIR}/output.zip`;
describe("git-diff-archive", () => {
after(() => {
rimraf.sync(OUTPUT_DIR);
});
it("should be chained promise", (done) => {
gitDiffArchive(ID1, ID2, {output: OUTPUT_PATH})
.then((res) => {
assert(true);
done();
});
});
describe("should be cathing errors", () => {
it("format", (done) => {
gitDiffArchive(ID1, ID2, {output: OUTPUT_PATH, format: "hoge"})
.catch((err) => {
assert(err === "specified format type is not supported");
done();
});
});
it("revision", (done) => {
gitDiffArchive(EMPTY_ID1, EMPTY_ID2, {output: OUTPUT_PATH})
.catch((err) => {
assert(err === "diff file does not exist");
done();
});
});
});
it("should be created diff zip", (done) => {
gitDiffArchive(ID1, ID2, {output: OUTPUT_PATH})
.then((res) => {
const stat = fs.statSync(OUTPUT_PATH);
assert(stat.isFile() === true);
fs.createReadStream(OUTPUT_PATH)
.pipe(unzip.Extract(({path: OUTPUT_DIR})))
.on("close", () => {
const files = glob.sync(`${OUTPUT_DIR}/**/*`, {nodir: true, dot: true});
assert(files.length === 6);
assert(files.indexOf(OUTPUT_PATH) > -1);
assert(files.indexOf(`${OUTPUT_DIR}/git-diff-archive/.eslintrc`) > -1);
assert(files.indexOf(`${OUTPUT_DIR}/git-diff-archive/LICENSE`) > -1);
assert(files.indexOf(`${OUTPUT_DIR}/git-diff-archive/README.md`) > -1);
assert(files.indexOf(`${OUTPUT_DIR}/git-diff-archive/bin/usage.txt`) > -1);
assert(files.indexOf(`${OUTPUT_DIR}/git-diff-archive/package.json`) > -1);
done();
});
});
});
describe("should arguments are passed", () => {
it("two id", (done) => {
gitDiffArchive(ID1, ID2, {
prefix: "files",
output: OUTPUT_PATH,
diffFilter: "AMCRD"
})
.then((res) => {
assert(res.cmd === `git diff --name-only --diff-filter=AMCRD ${ID1} ${ID2}`);
assert(res.output === OUTPUT_PATH);
assert(res.prefix === "files");
done();
});
});
it("one id", (done) => {
gitDiffArchive(ID1, {
prefix: "hoge",
output: OUTPUT_PATH,
diffFilter: "AMCRDB"
})
.then((res) => {
console.log(res);
assert(res.cmd === `git diff --name-only --diff-filter=AMCRDB ${ID1}`);
assert(res.output === OUTPUT_PATH);
assert(res.prefix === "hoge");
done();
});
});
});
});
| JavaScript | 0.000004 | @@ -2793,34 +2793,8 @@
%3E %7B%0A
- console.log(res);%0A
|
baa24d992e5d3c5bdbeb6e2ebfd56cb948e153bd | add checks for function type | test/inheritance.spec.js | test/inheritance.spec.js | var test = require('tape')
var constructors = require('../src/inheritance.js')
var Rectangle = constructors.Rectangle
var Square = constructors.Square
test('Rectangle and Square constructors should set width and height', function (t) {
t.plan(4)
var rec = new Rectangle(5, 10)
t.equal(rec.width, 5, 'should set rectangle width')
t.equal(rec.height, 10, 'should set rectangle height')
var squ = new Square(7)
t.equal(squ.width, 7, 'should set square width')
t.equal(squ.height, 7, 'should set square height')
})
test('Rectangle and Square area can be calculated', function (t) {
t.plan(5)
var rec = new Rectangle(5, 10)
t.equal(rec.area(), 50, 'rectangle area')
var squ = new Square(7)
t.equal(squ.area(), 49, 'square area')
t.equal(squ.area, rec.area, 'Square inherits area method from Rectangle')
t.ok(Rectangle.prototype.hasOwnProperty('area'), 'area method in Rectangle prototype')
t.notOk(Square.prototype.hasOwnProperty('area'), 'area method not in Square prototype')
})
test('Rectangle and Square description', function (t) {
t.plan(2)
var rec = new Rectangle(5, 10)
t.equal(rec.description(), 'Rectangle of width 5, height 10 and area 50.', 'should describe rectangle')
var squ = new Square(7)
t.equal(squ.description(), 'Square of side 7 and area 49.', 'should describe square')
})
| JavaScript | 0.000001 | @@ -599,17 +599,17 @@
t.plan(
-5
+7
)%0A%0A var
@@ -628,32 +628,71 @@
ectangle(5, 10)%0A
+ t.equal(typeof rec.area, 'function')%0A
t.equal(rec.ar
@@ -738,32 +738,71 @@
= new Square(7)%0A
+ t.equal(typeof squ.area, 'function')%0A
t.equal(squ.ar
@@ -1155,9 +1155,9 @@
lan(
-2
+4
)%0A%0A
@@ -1180,32 +1180,78 @@
ectangle(5, 10)%0A
+ t.equal(typeof rec.description, 'function')%0A
t.equal(rec.de
@@ -1337,24 +1337,24 @@
ectangle')%0A%0A
-
var squ =
@@ -1359,32 +1359,78 @@
= new Square(7)%0A
+ t.equal(typeof squ.description, 'function')%0A
t.equal(squ.de
|
abd567072705ac54b6e68664c6b05e9c01ccb539 | Add unit test for negation ignore rules in fsAsync (#755) | test/lib/fsAsync.spec.js | test/lib/fsAsync.spec.js | "use strict";
var crypto = require("crypto");
var fs = require("fs");
var os = require("os");
var path = require("path");
var fsAsync = require("../../lib/fsAsync");
var chai = require("chai");
var chaiAsPromised = require("chai-as-promised");
var _ = require("lodash");
var expect = chai.expect;
chai.use(chaiAsPromised);
// These tests work on the following directory structure:
// <basedir>
// .hidden
// visible
// subdir/
// subfile
// nesteddir/
// nestedfile
// node_modules/
// nestednodemodules
// node_modules
// subfile
describe("fsAsync", function() {
var baseDir;
var files = [
".hidden",
"visible",
"subdir/subfile",
"subdir/nesteddir/nestedfile",
"subdir/node_modules/nestednodemodules",
"node_modules/subfile",
];
before(function() {
baseDir = path.join(os.tmpdir(), crypto.randomBytes(10).toString("hex"));
fs.mkdirSync(baseDir);
fs.mkdirSync(path.join(baseDir, "subdir"));
fs.mkdirSync(path.join(baseDir, "subdir", "nesteddir"));
fs.mkdirSync(path.join(baseDir, "subdir", "node_modules"));
fs.mkdirSync(path.join(baseDir, "node_modules"));
_.each(files, function(file) {
fs.writeFileSync(path.join(baseDir, file), file);
});
});
after(function() {
return fsAsync.rmdirRecursive(baseDir).then(function() {
return expect(fsAsync.stat(baseDir)).to.reject;
});
});
it("can recurse directories", function() {
var foundFiles = fsAsync.readdirRecursive({ path: baseDir }).then(function(results) {
return _.map(results, function(result) {
return result.name;
}).sort();
});
var expectFiles = _.map(files, function(file) {
return path.join(baseDir, file);
}).sort();
return expect(foundFiles).to.eventually.deep.equal(expectFiles);
});
it("can ignore directories", function() {
var expected = _.chain(files)
.reject(function(file) {
return file.indexOf("node_modules") !== -1;
})
.map(function(file) {
return path.join(baseDir, file);
})
.value()
.sort();
var promise = fsAsync
.readdirRecursive({
path: baseDir,
ignore: ["node_modules"],
})
.then(function(results) {
return _.map(results, function(result) {
return result.name;
}).sort();
});
return expect(promise).to.eventually.deep.equal(expected);
});
it("supports blob rules", function() {
var expected = _.chain(files)
.reject(function(file) {
return file.indexOf("node_modules") !== -1;
})
.map(function(file) {
return path.join(baseDir, file);
})
.value()
.sort();
var promise = fsAsync
.readdirRecursive({
path: baseDir,
ignore: ["**/node_modules/**"],
})
.then(function(results) {
return _.map(results, function(result) {
return result.name;
}).sort();
});
return expect(promise).to.eventually.deep.equal(expected);
});
});
| JavaScript | 0 | @@ -2972,32 +2972,626 @@
t();%0A %7D);%0A%0A
+ return expect(promise).to.eventually.deep.equal(expected);%0A %7D);%0A%0A it(%22should support negation rules%22, function() %7B%0A var expected = _.chain(files)%0A .filter(function(file) %7B%0A return file === %22visible%22;%0A %7D)%0A .map(function(file) %7B%0A return path.join(baseDir, file);%0A %7D)%0A .value()%0A .sort();%0A%0A var promise = fsAsync%0A .readdirRecursive(%7B%0A path: baseDir,%0A ignore: %5B%22!visible%22%5D,%0A %7D)%0A .then(function(results) %7B%0A return _.map(results, function(result) %7B%0A return result.name;%0A %7D).sort();%0A %7D);%0A%0A
return expec
|
6c11bed847a40c19c648bd0a199d745f0be957f5 | Fix table row coloring | client-js/views.js | client-js/views.js | var $ = require('jquery');
var _ = require('underscore');
var Backbone = require('backbone');
var models = require('./models.js');
var InventoryItemView = Backbone.View.extend({
tagName: 'tr',
className: 'inv-list-item',
tmpl: _.template($('#inv-row-template').html()),
initialize: function() {},
render: function() {
data = {
name: this.model.get('name'),
status: "",
context_class: "",
count: this.model.get('count'),
reserved: this.model.get('reserved'),
available: this.model.get('available')
};
tr_ctxt_class = "info";
if(parseInt(this.model.reserved) == parseInt(this.model.count)) {
data['status'] = "Unavailable";
tr_ctxt_class = 'warning';
} else {
data['status'] = "Available";
}
var html = this.tmpl(data);
this.$el.html(html).addClass(tr_ctxt_class);
return this;
}
});
var InventoryListView = Backbone.View.extend({
el: '#inv-table',
initialize: function () {
this.listenTo(this.collection, 'sync', this.render);
},
render: function () {
$('.inv-list-item').remove();
var inv_table = $('#inv-table');
this.collection.each(
(model) => {
var view = new InventoryItemView({model: model});
inv_table.append(view.render().$el);
},
this
);
return this;
},
});
module.exports = {
InventoryItemView: InventoryItemView,
InventoryListView: InventoryListView
}
| JavaScript | 0.000001 | @@ -649,25 +649,16 @@
if(
-parseInt(
this.mod
@@ -664,47 +664,29 @@
del.
-reserved) == parseInt(this.model.count)
+get('available') == 0
) %7B%0A
|
24b51b5d574076626b0c466216babc93af406c2d | Add CustomEvent to polyfills | .eslintrc.js | .eslintrc.js | module.exports = {
extends: ["ash-nazg/sauron-node"],
parserOptions: {
sourceType: "module"
},
env: {
browser: true
},
settings: {
polyfills: [
"Array.isArray",
"Blob",
"console",
"Date.now",
"document.body",
"document.evaluate",
"document.head",
"document.importNode",
"document.querySelector", "document.querySelectorAll",
"DOMParser",
"Error",
"fetch",
"FileReader",
"history.pushState",
"history.replaceState",
"JSON",
"location.href",
"location.origin",
"MutationObserver",
"Object.assign", "Object.defineProperty", "Object.defineProperties",
"Object.getOwnPropertyDescriptor",
"Object.entries", "Object.keys", "Object.values",
"Promise",
"Set",
"Uint8Array",
"URL",
"window.getComputedStyle",
"window.postMessage",
"window.scrollX", "window.scrollY",
"XMLHttpRequest",
"XMLSerializer"
],
jsdoc: {
additionalTagNames: {
// In case we need to extend
customTags: []
},
augmentsExtendsReplacesDocs: true,
// Todo: Figure out why this is not working and why seem to have to
// disable for all Markdown:
/*
baseConfig: {
rules: {
"no-multi-spaces": "off"
}
}
*/
}
},
overrides: [
// Locales have no need for importing outside of SVG-Edit
{
files: [
"editor/locale/lang.*.js", "editor/extensions/ext-locale/**",
"docs/tutorials/ExtensionDocs.md"
],
rules: {
"import/no-anonymous-default-export": ["off"]
}
},
// For extensions, `this` is generally assigned to be the more
// descriptive `svgEditor`; they also have no need for importing outside
// of SVG-Edit
{
files: ["editor/extensions/**/ext-*.js"],
rules: {
"consistent-this": ["error", "svgEditor"],
"import/no-anonymous-default-export": ["off"]
}
},
// These browser files don't do importing or requiring
{
files: [
"editor/svgpathseg.js", "editor/touch.js", "editor/typedefs.js",
"editor/redirect-on-no-module-support.js",
"editor/extensions/imagelib/index.js",
"editor/external/dom-polyfill/dom-polyfill.js",
"screencasts/svgopen2010/script.js",
"opera-widget/handlers.js",
"firefox-extension/handlers.js",
"firefox-extension/content/svg-edit-overlay.js"
],
rules: {
"import/unambiguous": ["off"]
}
},
{
files: ['**/*.html'],
rules: {
'import/unambiguous': 'off'
}
},
// Our Markdown rules (and used for JSDoc examples as well, by way of
// our use of `matchingFileName` in conjunction with
// `jsdoc/check-examples` within `ash-nazg`)
{
files: ["**/*.md"],
rules: {
"eol-last": ["off"],
"no-console": ["off"],
"no-undef": ["off"],
"no-unused-vars": ["warn"],
"padded-blocks": ["off"],
"import/unambiguous": ["off"],
"import/no-unresolved": ["off"],
"node/no-missing-import": ["off"],
"no-multi-spaces": "off",
"sonarjs/no-all-duplicated-branches": "off",
'node/no-unpublished-import': ['error', {allowModules: ['@cypress/fiddle']}],
"no-alert": "off",
// Disable until may fix https://github.com/gajus/eslint-plugin-jsdoc/issues/211
"indent": "off"
}
},
// Dis-apply Node rules mistakenly giving errors with browser files,
// and treating Node global `root` as being present for shadowing
{
files: ["editor/**", "screencasts/**"],
globals: {
root: "off"
},
rules: {
"node/no-unsupported-features/node-builtins": "off"
}
},
{
// Node files
files: [
"docs/jsdoc-config.js",
"build-html.js",
"rollup.config.js", "rollup-config.config.js"
],
env: {
node: true,
},
globals: {
require: true
},
rules: {
// We can't put Rollup in npmignore or user can't get access,
// and we have too many modules to add to `peerDependencies`
// so this rule can know them to be available, so we instead
// disable
"node/no-unpublished-import": "off"
}
},
{
// As consumed by jsdoc, cannot be expressed as ESM
files: ["docs/jsdoc-config.js"],
parserOptions: {
sourceType: "script"
},
globals: {
"module": false
},
rules: {
"import/no-commonjs": "off",
"strict": "off"
}
},
{
extends: ['plugin:node/recommended-script'],
files: ['cypress/support/build-coverage-badge.js']
},
{
files: ["cypress/**"],
extends: ["plugin:cypress/recommended"],
env: {
node: true
},
rules: {
'no-console': 0,
'import/unambiguous': 0,
}
}
],
rules: {
// https://github.com/sindresorhus/eslint-plugin-unicorn/issues/453
"unicorn/regex-shorthand": 0,
// The Babel transform seems to have a problem converting these
"prefer-named-capture-group": "off",
// Override these `ash-nazg/sauron` rules which are difficult for us
// to apply at this time
"unicorn/prefer-string-slice": "off",
"default-case": "off",
"require-unicode-regexp": "off",
"max-len": ["off", {
ignoreUrls: true,
ignoreRegExpLiterals: true
}],
"unicorn/prefer-query-selector": "off",
"unicorn/prefer-node-append": "off",
"unicorn/no-zero-fractions": "off"
}
};
| JavaScript | 0 | @@ -584,16 +584,37 @@
rigin%22,%0A
+ %22CustomEvent%22,%0A
%22M
|
3509681f643f26b6941462a3b945eea71806faec | replace code style from airbnb to standard | .eslintrc.js | .eslintrc.js | module.exports = {
parser: 'babel-eslint',
parserOptions: {
ecmaVersion: 6,
sourceType: 'module'
},
rules: {
semi: 2
},
extends: 'airbnb-base',
}
| JavaScript | 0.000018 | @@ -151,20 +151,18 @@
s: '
-airbnb-base
+standard
',%0A%7D
+;
%0A
|
d242ac2952f575fb846f6677aa9cdba6b0b061fa | Whitelist beforeEach and afterEach as globals for eslint | .eslintrc.js | .eslintrc.js | module.exports = {
"env": {
"browser": true,
"es6": true,
"node": true
},
"globals": {
"describe": false,
"it": false
},
"extends": ["eslint:recommended", "plugin:react/recommended"],
"parserOptions": {
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
"jsx": true
},
"sourceType": "module"
},
"plugins": [
"react"
],
"rules": {
"indent": [
"error",
2
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"double"
],
"semi": [
"error",
"never"
]
}
}
| JavaScript | 0 | @@ -136,16 +136,66 @@
%22: false
+,%0A %22beforeEach%22: false,%0A %22afterEach%22: false,
%0A %7D,%0A
|
d1222757b74ec8df6710cd717d9d7597b77a0e7b | change publish path for win-ia32 (#496) | builder.config.js | builder.config.js | /* eslint-disable no-template-curly-in-string */
const { externals } = require('./webpack.common')
const fs = require('fs')
const path = require('path')
const { nodeFileTrace } = require('@vercel/nft')
const config = {
afterSign: 'bin/notarize.js',
detectUpdateChannel: true,
generateUpdatesFilesForAllChannels: true,
appId: 'org.digital-democracy.mapeo-desktop',
productName: 'Mapeo',
artifactName: 'Installar_Mapeo_v${version}_${os}.${ext}',
mac: {
category: 'public.app-category.utilities',
gatekeeperAssess: false,
hardenedRuntime: true,
entitlements: 'build/entitlements.mac.plist',
entitlementsInherit: 'build/entitlements.mac.plist'
},
directories: {
buildResources: 'build',
output: 'dist/main'
},
win: {
target: 'NSIS',
artifactName: 'Installar_Mapeo_v${version}_${os}-${env.ARCH}.${ext}',
rfc3161TimeStampServer: 'http://timestamp.digicert.com',
timeStampServer: 'http://timestamp.digicert.com'
},
linux: {
target: ['AppImage', 'deb'],
category: 'Utility'
},
dmg: {
icon: 'build/mapeo_installer.icns',
title: '${productName} v${version}',
sign: false,
contents: [
{
x: 410,
y: 220,
type: 'link',
path: '/Applications'
},
{
x: 130,
y: 220,
type: 'file'
}
]
},
publish: [
{
provider: 's3',
bucket: 'downloads.mapeo.app',
path: process.env.ARCH === 'ia32' ? '/desktop-win-ia32' : '/desktop'
},
{
provider: 'github',
releaseType: 'release'
}
],
extraResources: [
{
from: 'build/app-update.yml',
to: 'app-update.yml'
},
{
from: path.dirname(require.resolve('mapeo-default-settings')),
to: 'presets/default'
}
]
}
const files = [
'index.js',
'config.js',
// include everything under static
'static/**/*',
// include all translations
'messages/**/*',
// Don't ship built sourcemaps, because they are 25Mb
'!static/*.map',
// Include everything in src/ apart from src/renderer
'src/**/*',
'!src/renderer/**/*',
// but also include src/renderer/index-preload.js since this is not included
// in the renderer bundle
'src/renderer/index-preload.js',
// Ignore a bunch of noise that is in node_modules that is not needed in the
// packaged app (identified these by scanning app.asar for the largest files)
'!**/node_modules/osm-p2p-db/benchmark${/*}',
'!**/node_modules/osm-p2p-syncfile/chaos',
'!**/node_modules/osm2obj/*.osc',
'!**/node_modules/pannellum/*.{jpg,png}',
'!**/node_modules/sodium-native/prebuilds/linux-arm',
'!**/node_modules/*/{CHANGELOG.md,README.md,README,readme.md,readme}',
'!**/node_modules/**/{test,__tests__,tests,powered-test,example,examples}',
'!**/node_modules/*.d.ts',
'!**/node_modules/.bin',
'!**/*.{iml,o,hprof,orig,pyc,pyo,rbc,swp,csproj,sln,xproj}',
'!.editorconfig',
'!**/._*',
'!**/{.DS_Store,.git,.hg,.svn,CVS,RCS,SCCS,.gitignore,.gitattributes}',
'!**/{__pycache__,thumbs.db,.flowconfig,.idea,.vs,.nyc_output}',
'!**/{appveyor.yml,.travis.yml,circle.yml}',
'!**/{npm-debug.log,yarn.lock,.yarn-integrity,.yarn-metadata.json}',
'!test${/*}'
]
// Append last, these modules are excluded, but we need these files included
// since they are required at runtime (css files and iD assets)
const extraIncludeFiles = [
'node_modules/id-mapeo/dist/iD.css',
'node_modules/id-mapeo/dist/*/**/*',
'node_modules/mapbox-gl/dist/mapbox-gl.css'
]
// The results of nodeFileTrace on Windows are \ separated.
const sep = path.sep
module.exports = async () => {
// Get required files for main and background process
const { fileList } = await nodeFileTrace([
'./index.js',
'./src/background/mapeo-core/index.js',
'./src/background/map-printer/index.js'
])
// List of all modules we definitely want to include
const includeModules = fileList.reduce((acc, cur) => {
const path = cur.split(`node_modules${sep}`).pop()
let moduleName = path.split(sep)[0]
// Ensure we included namespaced modules e.g. @digidem/mapeo Note we don't
// use path.sep here, but a `/` because this is used for electron-builder
// config, which uses glob which expects `/` on all platforms
if (moduleName.startsWith('@')) moduleName += '/' + path.split(sep)[1]
acc.add(moduleName)
return acc
// Also include the webpack externals, plus electron-is-dev which is not
// picked up by static analysis
}, new Set([...externals, 'electron-is-dev']))
// List all modules in node_modules (this is only recursive to read namespaced
// modules, but it does not bother with nested node_modules, since it would
// not really change the output)
const allModules = await (async function readDirs (dir) {
let moduleNames = []
const dirList = (
await fs.promises.readdir(dir, {
withFileTypes: true
})
)
.filter(dirent => dirent.isDirectory())
.map(dirent => dirent.name)
for (const item of dirList) {
if (item.startsWith('@')) {
moduleNames = moduleNames.concat(
(await readDirs(path.join(dir, item))).map(s => item + '/' + s)
)
} else if (item.startsWith('.')) {
// ignore
} else {
moduleNames.push(item)
}
}
return moduleNames
})(path.join(__dirname, 'node_modules'))
const excludeModules = []
// Add explicit exclude paths for any modules that are not explicitly required
// by the main and background process. It would be better to do this the other
// way around (explicitly include files) but electron-builder always tries to
// add **/node_modules/**/* to the files list, and doing this as an include
// list as opposed to an exclude list was resulting in some modules missing
// from the packaged app, even though they were listed here
for (const moduleName of allModules) {
if (!includeModules.has(moduleName)) {
excludeModules.push(`!**/node_modules/${moduleName}/**/*`)
}
}
config.files = [...files, ...excludeModules, ...extraIncludeFiles]
let variantConfigTransform = config => config
const variant = process.env.MAPEO_VARIANT
if (variant && variant !== 'main') {
try {
variantConfigTransform = require(path.join(
__dirname,
'variants',
variant,
'builder.config.js'
))
} catch (e) {
console.warn('No configuration for variant ' + variant)
}
}
return variantConfigTransform(config)
}
| JavaScript | 0.000001 | @@ -1480,13 +1480,9 @@
ktop
--win-
+/
ia32
|
4edd3d02fd396c29b05ebe7be4b579139a72aa3c | update ecmascript eslint parser target | .eslintrc.js | .eslintrc.js | 'use strict';
module.exports = {
root: true,
parserOptions: {
ecmaVersion: 2018,
},
plugins: ['node', 'prettier'],
extends: ['eslint:recommended', 'plugin:node/recommended', 'plugin:prettier/recommended'],
env: {
browser: false,
node: true,
es6: true,
},
globals: {},
rules: {
/*** Possible Errors ***/
'no-console': 'off',
'no-template-curly-in-string': 'error',
'no-unsafe-negation': 'error',
/*** Best Practices ***/
curly: 'error',
eqeqeq: 'error',
'guard-for-in': 'off',
'no-caller': 'error',
'no-eq-null': 'error',
'no-eval': 'error',
'no-new': 'off',
'no-unused-expressions': [
'error',
{
allowShortCircuit: true,
allowTernary: true,
},
],
'wrap-iife': 'off',
yoda: 'error',
/*** Strict Mode ***/
strict: ['error', 'global'],
/*** Variables ***/
'no-undef': 'error',
'no-unused-vars': 'error',
'no-use-before-define': ['error', 'nofunc'],
/*** Stylistic Issues ***/
camelcase: 'error',
'new-cap': ['error', { properties: false }],
'no-array-constructor': 'error',
'no-bitwise': 'error',
'no-lonely-if': 'error',
'no-plusplus': 'off',
'no-unneeded-ternary': 'error',
/*** ECMAScript 6 ***/
'no-useless-computed-key': 'error',
'no-var': 'error',
'object-shorthand': 'error',
'prefer-template': 'error',
'symbol-description': 'error',
},
};
| JavaScript | 0 | @@ -83,10 +83,10 @@
: 20
-18
+20
,%0A
|
d692e9ae84df2ece38ba7a1ecb81624114417907 | Add valid-typeof rule | .eslintrc.js | .eslintrc.js | module.exports = {
'env': {
'browser': true,
'commonjs': true,
'es6': true,
'jasmine': true
},
'extends': [
'eslint:recommended',
'plugin:flowtype/recommended'
],
'globals': {
// The globals that (1) are accessed but not defined within many of our
// files, (2) are certainly defined, and (3) we would like to use
// without explicitly specifying them (using a comment) inside of our
// files.
'__filename': false
},
'parser': 'babel-eslint',
'parserOptions': {
'ecmaFeatures': {
'experimentalObjectRestSpread': true
},
'sourceType': 'module'
},
'plugins': [
'flowtype',
// ESLint's rule no-duplicate-imports does not understand Flow's import
// type. Fortunately, eslint-plugin-import understands Flow's import
// type.
'import'
],
'rules': {
'new-cap': 2,
'no-console': 0,
'semi': [ 'error', 'always' ],
// Possible Errors group
'no-cond-assign': 2,
'no-constant-condition': 2,
'no-control-regex': 2,
'no-debugger': 2,
'no-dupe-args': 2,
'no-duplicate-case': 2,
'no-empty': 2,
'no-empty-character-class': 2,
'no-ex-assign': 2,
'no-extra-boolean-cast': 2,
'no-extra-parens': [
'error',
'all',
{ 'nestedBinaryExpressions': false }
],
'no-extra-semi': 2,
'no-func-assign': 2,
'no-inner-declarations': 2,
'no-invalid-regexp': 2,
'no-irregular-whitespace': 2,
'no-negated-in-lhs': 2,
'no-obj-calls': 2,
'no-prototype-builtins': 0,
'no-regex-spaces': 2,
'no-sparse-arrays': 2,
'no-unexpected-multiline': 2,
'no-unreachable': 2,
'no-unsafe-finally': 2,
'use-isnan': 2,
'prefer-spread': 2,
'require-yield': 2,
'rest-spread-spacing': 2,
'sort-imports': 0,
'template-curly-spacing': 2,
'yield-star-spacing': 2,
'import/no-duplicates': 2
}
};
| JavaScript | 0.000032 | @@ -1944,24 +1944,52 @@
isnan': 2,%0A%0A
+ 'valid-typeof': 2,%0A%0A
'pre
|
35ec2e20f3ac93239360f7cb0f9fc43e860f9845 | Reducing indent to 2 spaces | .eslintrc.js | .eslintrc.js | module.exports = {
"env": {
"node": true
},
"extends": "eslint:recommended",
"rules": {
"indent": [
"error",
2
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
]
}
};
| JavaScript | 0.998368 | @@ -18,23 +18,21 @@
%7B%0A
- %22env%22
+'env'
: %7B%0A
@@ -31,18 +31,14 @@
- %22
+'
node
-%22
+'
: tr
@@ -46,29 +46,25 @@
e%0A
-
%7D,%0A
- %22
+'
extends
-%22: %22
+': '
esli
@@ -81,30 +81,28 @@
nded
-%22
+'
,%0A
- %22
+'
rules
-%22
+'
: %7B%0A
@@ -101,20 +101,16 @@
- %22
+'
indent
-%22
+'
: %5B%0A
@@ -115,37 +115,31 @@
%5B%0A
- %22
+'
error
-%22
+'
,%0A
2%0A
@@ -134,20 +134,10 @@
- 2%0A
+2%0A
@@ -143,21 +143,17 @@
%5D,%0A
- %22
+'
linebrea
@@ -159,17 +159,17 @@
ak-style
-%22
+'
: %5B%0A
@@ -170,37 +170,31 @@
%5B%0A
- %22
+'
error
-%22
+'
,%0A
%22u
@@ -189,48 +189,34 @@
- %22
+'
unix
-%22%0A
+'%0A
-
%5D,%0A
- %22
+'
quotes
-%22
+'
: %5B%0A
@@ -221,37 +221,31 @@
%5B%0A
- %22
+'
error
-%22
+'
,%0A
%22s
@@ -240,27 +240,17 @@
- %22
+'
single
-%22%0A
+'%0A
@@ -260,18 +260,14 @@
- %22
+'
semi
-%22
+'
: %5B%0A
@@ -276,29 +276,23 @@
- %22
+'
error
-%22
+'
,%0A
@@ -291,35 +291,23 @@
- %22
+'
always
-%22%0A %5D%0A
+'%0A %5D%0A
%7D%0A
|
f159e79f3ea3a0388f6461ccf5cb03d81012af32 | Allow for-of statement. | .eslintrc.js | .eslintrc.js | module.exports = {
"parser": "babel-eslint",
"parserOptions": {
"ecmaVersion": 2018,
"sourceType": "module"
},
"env": {
"node": true,
"es6": true
},
"extends": [
"airbnb-base",
"plugin:promise/recommended"
],
"plugins": [
"import",
"promise",
"typescript"
],
"rules": {
"func-names": "off",
"import/prefer-default-export": "off",
"no-await-in-loop": "off",
"no-console": "off",
"no-plusplus": "off",
"no-underscore-dangle": ["error", { "allowAfterThis": true, "allowAfterSuper": true }],
},
"overrides": [{
"files": ["**/*.ts"],
"parser": "typescript-eslint-parser",
"rules": {
"import/no-unresolved": "off",
"no-undef": "off",
"typescript/no-array-constructor": ["error"],
"typescript/no-triple-slash-reference": ["error"],
"typescript/no-unused-vars": ["error"]
}
}, {
"files": ["scripts/**/*"],
"rules": {
"import/no-extraneous-dependencies": "off"
}
}]
};
| JavaScript | 0.000075 | @@ -561,16 +561,643 @@
rue %7D%5D,%0A
+ %22no-restricted-syntax%22: %5B%0A %22error%22,%0A %7B%0A selector: 'ForInStatement',%0A message: 'for..in loops iterate over the entire prototype chain, which is virtually never what you want. Use Object.%7Bkeys,values,entries%7D, and iterate over the resulting array.',%0A %7D,%0A %7B%0A selector: 'LabeledStatement',%0A message: 'Labels are a form of GOTO; using them makes code confusing and hard to maintain and understand.',%0A %7D,%0A %7B%0A selector: 'WithStatement',%0A message: '%60with%60 is disallowed in strict mode because it makes code impossible to predict and optimize.',%0A %7D%0A %5D%0A
%7D,%0A %22
@@ -1352,24 +1352,55 @@
ef%22: %22off%22,%0A
+ %22no-unused-vars%22: %22off%22,%0A
%22types
|
2ac83ddbc144b52f0edfd52704d6e97b18782147 | Remove tmp ignore | .eslintrc.js | .eslintrc.js | const error = 2;
const warn = 1;
const ignore = 0;
module.exports = {
root: true,
extends: [
'airbnb',
'plugin:jest/recommended',
'plugin:import/react-native',
'prettier',
'prettier/react',
],
plugins: ['prettier', 'jest', 'import', 'react', 'jsx-a11y', 'json'],
parser: 'babel-eslint',
parserOptions: {
ecmaVersion: 8,
sourceType: 'module',
},
env: {
es6: true,
node: true,
'jest/globals': true,
},
settings: {
'import/core-modules': ['enzyme'],
'import/ignore': ['node_modules\\/(?!@storybook)'],
'import/resolver': {
node: {
extensions: ['.js', '.ts'],
},
},
},
rules: {
'prettier/prettier': [
warn,
{
printWidth: 100,
tabWidth: 2,
bracketSpacing: true,
trailingComma: 'es5',
singleQuote: true,
},
],
'no-debugger': process.env.NODE_ENV === 'production' ? error : ignore,
'class-methods-use-this': ignore,
'import/extensions': [
error,
'always',
{
js: 'never',
ts: 'never',
},
],
'import/no-extraneous-dependencies': [
error,
{
devDependencies: [
'examples/**',
'examples-native/**',
'**/example/**',
'*.js',
'**/*.test.js',
'**/*.stories.js',
'**/scripts/*.js',
'**/stories/**/*.js',
'**/__tests__/**/*.js',
'**/.storybook/**/*.js',
],
peerDependencies: true,
},
],
'import/prefer-default-export': ignore,
'import/default': error,
'import/named': error,
'import/namespace': error,
'react/jsx-filename-extension': [
warn,
{
extensions: ['.js', '.jsx'],
},
],
'react/jsx-no-bind': [
error,
{
ignoreDOMComponents: true,
ignoreRefs: true,
allowArrowFunctions: true,
allowFunctions: true,
allowBind: true,
},
],
'jsx-a11y/label-has-associated-control': [
warn,
{
labelComponents: ['CustomInputLabel'],
labelAttributes: ['label'],
controlComponents: ['CustomInput'],
depth: 3,
},
],
'react/no-unescaped-entities': ignore,
'jsx-a11y/label-has-for': [
error,
{
required: {
some: ['nesting', 'id'],
},
},
],
'linebreak-style': ignore,
'jsx-a11y/anchor-is-valid': [
error,
{
components: ['RoutedLink', 'MenuLink', 'LinkTo', 'Link'],
specialLink: ['overrideParams', 'kind', 'story', 'to'],
},
],
'no-underscore-dangle': [
error,
{
allow: ['__STORYBOOK_CLIENT_API__', '__STORYBOOK_ADDONS_CHANNEL__'],
},
],
},
overrides: [
{
files: ['**/react-native*/**', '**/REACT_NATIVE*/**', '**/crna*/**'],
rules: {
'jsx-a11y/accessible-emoji': ignore,
},
},
{
files: '**/.storybook/config.js',
rules: {
'global-require': ignore,
},
},
],
};
| JavaScript | 0.000001 | @@ -2403,39 +2403,8 @@
%5D,%0A
- 'linebreak-style': ignore,%0A
|
4ea79ff4ab18474c4a692e1be9262950343f528a | Remove requirement for babel-eslint | .eslintrc.js | .eslintrc.js | (function() {
let error = 2;
module.exports = {
parser: "babel-eslint",
parserOptions: {
"ecmaVersion": 6,
"sourceType": "module"
},
root: true,
extends: "ftgp",
rules: {
"quotes": [error, "double"],
"ftgp/require-class-comment": 0
}
};
})();
| JavaScript | 0 | @@ -48,34 +48,8 @@
= %7B%0A
-%09%09parser: %22babel-eslint%22,%0A
%09%09pa
|
24da14197350c079a902f21297667a0348db4291 | remove unsued variables | embark-ui/src/components/Console.js | embark-ui/src/components/Console.js | import PropTypes from "prop-types";
import React, {Component} from 'react';
import Convert from 'ansi-to-html';
import { Form, Col, Row, Card, CardBody, Input, CardFooter, TabContent, TabPane, Nav, NavItem, NavLink } from 'reactstrap';
import classnames from 'classnames';
import {AsyncTypeahead} from 'react-bootstrap-typeahead'
import Logs from "./Logs";
import "./Console.css";
import {EMBARK_PROCESS_NAME} from '../constants';
const convert = new Convert();
class Console extends Component {
constructor(props) {
super(props);
this.state = {value: '', isLoading: true, options: [], activeTab: EMBARK_PROCESS_NAME};
}
handleSubmit(event) {
event.preventDefault();
this.props.postCommand(this.state.value);
this.setState({value: ''});
this.typeahead.getInstance().clear()
}
handleChange(value, cb) {
this.setState({value: value}, cb);
}
toggle(tab) {
if (this.state.activeTab !== tab) {
this.setState({
activeTab: tab
});
this.props.updateTab(tab);
}
}
renderNav() {
return (
<Nav tabs>
{this.props.processes.map((process) => (
<NavItem key={process.name}>
<NavLink
className={classnames({ active: this.state.activeTab === process.name })}
onClick={() => { this.toggle(process.name); }}
>
{process.name}
</NavLink>
</NavItem>
))}
</Nav>
)
}
renderTabs() {
const {processLogs, processes} = this.props;
return (
<TabContent activeTab={this.state.activeTab}>
{processes.map(process => (
<TabPane key={process.name} tabId={process.name}>
<Logs>
{processLogs
.filter((item) => item.name === process.name)
.reverse()
.map((item, i) => <p key={i} className={item.logLevel}
dangerouslySetInnerHTML={{__html: convert.toHtml(item.msg)}}></p>)}
</Logs>
</TabPane>
))}
</TabContent>
);
}
render() {
return (
<Row>
<Col>
<Card>
<Card.Body className="console-container">
{this.renderNav()}
{this.renderTabs()}
</Card.Body>
{this.props.isEmbark() && <Card.Footer>
<AsyncTypeahead
autoFocus={true}
emptyLabel={false}
labelKey="value"
multiple={false}
maxResults={10}
isLoading={this.state.isLoading}
onInputChange={(text) => this.handleChange(text)}
onChange={(text) => {
if (text && text[0]) {
this.handleChange(text[0].value)
}
}}
ref={(typeahead) => this.typeahead = typeahead}
searchText={false}
onKeyDown={(e) => {
if (e.keyCode === 13) {
this.handleChange(e.target.value, () => {
this.handleSubmit(e)
})
}
}}
onSearch={(value) => {
this.props.postCommandSuggestions(value)
}}
filterBy={['value', 'description']}
maxHeight="200px"
placeholder="Type a command (e.g help)"
options={this.props.command_suggestions}
renderMenuItemChildren={(option) => (
<div>
{option.value}
<div>
<small>{option.command_type} - {option.description}</small>
</div>
</div>
)}
/>
</Card.Footer>}
</Card>
</Col>
</Row>
);
}
}
Console.propTypes = {
postCommand: PropTypes.func,
postCommandSuggestions: PropTypes.func,
isEmbark: PropTypes.func,
processes: PropTypes.arrayOf(PropTypes.object).isRequired,
command_suggestions: PropTypes.arrayOf(PropTypes.object),
processLogs: PropTypes.arrayOf(PropTypes.object).isRequired,
updateTab: PropTypes.func
};
export default Console;
| JavaScript | 0.000436 | @@ -118,14 +118,8 @@
rt %7B
- Form,
Col
@@ -134,37 +134,8 @@
ard,
- CardBody, Input, CardFooter,
Tab
|
4bd4c6cc453da42df4c4fc16005e4be647c2c7ad | extend js tests timeout | spec/javascripts/member-ui/fundraiser_spec.js | spec/javascripts/member-ui/fundraiser_spec.js | //= require sumofus
describe("fundraiser", function() {
var suite = this;
before(function() {
suite.validatePath = /\/api\/pages\/[0-9]+\/actions\/validate/;
window.onbeforeunload = function(){
return 'Are you sure you want to leave?';
};
});
afterEach(function() {
suite.server.restore();
});
beforeEach(function() {
MagicLamp.wish("pages/fundraiser");
suite.server = sinon.fakeServer.create();
suite.server.respondWith("GET", '/api/braintree/token',
[200, { "Content-Type": "application/json" },
'{ "token": "'+helpers.btClientToken+'" }' ]);
suite.follow_up_url = "/pages/636/follow-up";
suite.fundraiserBar = new window.FundraiserBar(suite.follow_up_url);
suite.fundraiserBar.redirectTo = sinon.stub().returns(null);
suite.server.respond(); // respond to request for token
});
describe('loading and first panel', function(){
it("shows only the first two panels of the donate panel", function() {
expect(helpers.currentStepOf(3)).to.eq(1);
});
it('does not display the "next" button', function(){
expect($('.fundraiser-bar__first-continue')).to.have.css('display', 'none');
});
it('autofills the custom amount with a dollar sign', function(){
var $el = $('.fundraiser-bar__custom-field');
expect($el).to.have.value('');
$el.focus();
expect($el).to.have.value('$');
});
it('reveals the "next" button when a custom amount is entered', function(){
var $next = $('.fundraiser-bar__first-continue');
var $input = $('.fundraiser-bar__custom-field');
expect($next).to.have.css('display','none');
$input.focus();
expect($next).not.to.have.css('display','none');
$input.blur();
expect($next).have.css('display','none');
$input.focus();
$input.val('$25');
$input.blur();
expect($next).not.to.have.css('display','none');
});
it('moves to step 2 when amount button clicked', function(){
$('.fundraiser-bar__amount-button').click();
expect(helpers.currentStepOf(3)).to.eq(2);
});
it('moves to step 2 when next clicked with custom amount', function(){
$('.fundraiser-bar__custom-field').val('$22');
$('.fundraiser-bar__first-continue').click();
expect(helpers.currentStepOf(3)).to.eq(2);
});
it('does not move to step 2 if custom amount has only dollar sign', function(){
$('.fundraiser-bar__custom-field').val('$');
$('.fundraiser-bar__first-continue').click();
expect(helpers.currentStepOf(3)).to.eq(1);
});
it('displays the amount over step 1 after moving ahead', function(){
$('.fundraiser-bar__custom-field').val('$22');
$('.fundraiser-bar__first-continue').click();
expect($('.fundraiser-bar__display-amount').text()).to.eq('$22');
});
});
describe('second panel', function(){
// most of the interaction on the form are on the form js, which is beyond the scope
// of this test suite
beforeEach(function(){
$('.fundraiser-bar__custom-field').val('$22');
$('.fundraiser-bar__first-continue').click();
});
it('returns to panel 1 if number 1 is clicked', function(){
$('.fundraiser-bar__step-label[data-step="1"] .fundraiser-bar__step-number').click();
expect(helpers.currentStepOf(3)).to.eq(1);
});
it('makes a request to validate the form', function(){
$('.action-bar__submit-button').click();
var request = helpers.last(suite.server.requests);
expect(request.method).to.eq("POST");
expect(request.url).to.match(suite.validatePath);
});
it('moves to panel 3 if validation passes', function(){
$('.action-bar__submit-button').click();
helpers.last(suite.server.requests).respond(200, { "Content-Type": "application/json" }, '{}');
expect(helpers.currentStepOf(3)).to.eq(3);
});
it('stays on panel 2 if validation fails', function(){
$('.action-bar__submit-button').click();
helpers.last(suite.server.requests).respond(422, { "Content-Type": "application/json" }, '{ "errors": {} }');
expect(helpers.currentStepOf(3)).to.eq(2);
});
});
describe('third panel', function() {
beforeEach(function(){
suite.server.respondWith("POST", this.validatePath, ["200", {}, ""]);
$('.fundraiser-bar__custom-field').val('$22');
$('.fundraiser-bar__first-continue').click();
$('.action-bar__submit-button').click();
suite.server.respond();
expect(helpers.currentStepOf(3)).to.eq(3);
});
it('disables the button when the form submits', function(){
var $button = $('.fundraiser-bar__submit-button');
expect($button).not.to.have.class('button--disabled');
$button.click();
expect($button).to.have.class('button--disabled');
});
xit('first makes a request to braintree', function(){
// I don't think we can test this without some serious iframe hackery
});
it('sends the nonce to the server after receiving it from braintree', function(){
suite.fundraiserBar.fakeNonceSuccess({nonce: helpers.btNonce});
request = helpers.last(suite.server.requests);
expect(request.method).to.eq("POST");
expect(request.url).to.eq("/api/braintree/transaction");
bodyPairs = decodeURI(request.requestBody).split('&');
expect(bodyPairs).to.include.members(["payment_method_nonce="+helpers.btNonce, "amount=22"]);
});
it('loads the follow-up url after success from the server', function(){
suite.server.respondWith('POST', "/api/braintree/transaction", [200, { "Content-Type": "application/json" }, '{ "success": "true" }' ]);
suite.fundraiserBar.fakeNonceSuccess({nonce: helpers.btNonce});
suite.server.respond();
expect(suite.fundraiserBar.redirectTo).to.have.been.calledWith(suite.follow_up_url);
});
xit('displays validation errors passed back from the server', function(){
// it doesn't actually do this yet, spec is here as a reminder
});
});
});
| JavaScript | 0.000001 | @@ -69,16 +69,40 @@
= this;
+%0A suite.timeout(10000);
%0A%0A befo
|
03511e6b250873c5fe6c99cafca41850120f5ca1 | fix build display | apps/app/src/pages/Build/ScreenshotsDiffCard.js | apps/app/src/pages/Build/ScreenshotsDiffCard.js | import * as React from "react";
import { x } from "@xstyled/styled-components";
import { gql } from "graphql-tag";
import {
Card,
CardHeader,
CardTitle,
CardBody,
BaseLink,
LinkBlock,
useDisclosureState,
DisclosureContent,
Disclosure,
Icon,
} from "@argos-ci/app/src/components";
import { ChevronRightIcon } from "@primer/octicons-react";
import { getStatusPrimaryColor } from "../../containers/Status";
import { ScreenshotDiffStatusIcon } from "./ScreenshotDiffStatusIcons";
export const ScreenshotsDiffCardFragment = gql`
fragment ScreenshotsDiffCardFragment on ScreenshotDiff {
url
status
compareScreenshot {
id
name
url
}
baseScreenshot {
id
name
url
}
}
`;
export function EmptyScreenshotCard() {
return (
<Card>
<CardHeader border={0}>
<CardTitle>No screenshot found</CardTitle>
</CardHeader>
</Card>
);
}
function EmptyScreenshot() {
return <x.div flex={1 / 3} />;
}
function Screenshot({ screenshot, title }) {
if (!screenshot?.url) return <EmptyScreenshot />;
return (
<BaseLink href={screenshot.url} target="_blank" title={title} flex={1 / 3}>
<img alt={screenshot.name} src={screenshot.url} />
</BaseLink>
);
}
export function ScreenshotsDiffCard({
screenshotDiff,
opened = true,
...props
}) {
const { compareScreenshot, baseScreenshot, url } = screenshotDiff;
const disclosure = useDisclosureState({ defaultOpen: opened });
return (
<Card {...props}>
<CardHeader
position="sticky"
top={40}
alignSelf="flex-start"
borderBottom={disclosure.open ? 1 : 0}
>
<CardTitle display="flex" alignItems="center" gap={1} fontSize="sm">
<LinkBlock
as={Disclosure}
state={disclosure}
px={1}
color="secondary-text"
>
<x.div
as={ChevronRightIcon}
transform
rotate={disclosure.open ? 90 : 0}
transitionDuration={300}
w={4}
h={4}
/>
</LinkBlock>
<Icon
as={ScreenshotDiffStatusIcon(screenshotDiff.status)}
color={getStatusPrimaryColor(screenshotDiff.status)}
/>
{baseScreenshot.name}
</CardTitle>
</CardHeader>
<DisclosureContent state={disclosure}>
<CardBody display="flex" gap={1} p={1}>
<Screenshot screenshot={baseScreenshot} title="Base screenshot" />
{compareScreenshot ? (
<Screenshot
screenshot={compareScreenshot}
title="Current screenshot"
/>
) : (
<EmptyScreenshot />
)}
{url ? (
<Screenshot screenshot={{ url, name: "diff" }} title="Diff" />
) : (
<EmptyScreenshot />
)}
</CardBody>
</DisclosureContent>
</Card>
);
}
| JavaScript | 0.000033 | @@ -2301,16 +2301,42 @@
%7B
+compareScreenshot.name %7C%7C
baseScre
|
ae86b237deee88c55c43fa79a40a32d0cc695703 | fixing up the email | app/util.js | app/util.js | var nodemailer = require('nodemailer');
var twilio = require('twilio')(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);
var _ = require('lodash');
// Nodejs encryption with CTR
var crypto = require('crypto'),
algorithm = 'aes-256-ctr',
password = 'CORSICA'; //This should be secret
var util = exports;
util.encrypt = function encrypt(text){
var cipher = crypto.createCipher(algorithm,password);
var crypted = cipher.update(text,'utf8','hex');
crypted += cipher.final('hex');
return crypted;
};
util.decrypt = function decrypt(text){
var decipher = crypto.createDecipher(algorithm,password);
var dec = decipher.update(text,'hex','utf8');
dec += decipher.final('utf8');
return dec;
};
util.notify = function notify(waitlist){
// setup e-mail data with unicode symbols
_.each(waitlist.subscribers, function (person, key) {
console.log(person.firstName, "your position is " + (key+1) + " on the waitlist");
var text = 'A spot has opened up in ' + waitlist.listing.code + ": " + waitlist.listing.title ; // plaintext body
var subject = 'A spot has opened up in ' + waitlist.listing.code;
var html = '<b>A spot has opened up in ' + waitlist.listing.code + ": " + waitlist.listing.title + 'Your position is ' + (key+1) + '</b>';
console.log(person.textPreference===true);
if (key === 0){
console.log(person.email);
var link = "http://red411.herokuapp.com/confirm/"+ waitlist._id + "?u="+ util.encrypt(person.email);
console.log("link");
html = html + " To claim, head to <a href='"+ link +"'></a>";
if (person.textPreference === true || person.textPreference === "true" ){
console.log("sent a text");
message(person.phoneNumber, waitlist.listing.code);
}
}
//perform actions
util.mail(person.email, text, html );
});
};
/** CLAIM A WAITLIST SPOT **/
util.claim = function notify(waitlist){
// setup e-mail data with unicode symbols
// _.each(waitlist.subscribers, function (person, key) {
var person = waitlist.subscribers[0];
var text = "TEST" ; // plaintext body
var subject = "TEST";
var html = "TEST";
//perform actions
util.mail(person.email, subject, text, html );
// });
};
util.mail = function mail(to,subject,text,html) {
// create reusable transporter object using SMTP transport
var transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: 'xtupledev@gmail.com',
pass: 'xTuple!23510'
}
});
// body...
var mailOptions = {
from: 'Corsica (oratt001@gmail.com)', // sender address
to: to, // list of receivers
subject: subject,
text: text,
html: html// html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
if(error){
console.log(error);
return error;
}else{
console.log('Message sent: ' + info.response);
return info.reponse;
}
});
};
/* Text the User
* @param wailist
* @param people on the list
*/
util.message = function message(number, course) {
// body...
twilio.sendMessage({
to: number, // Any number Twilio can deliver to
from: '+17579135000', // A number you bought from Twilio and can use for outbound communication
body: "Hi, This is CORSICA, a spot in " + course + " has opened up",
}, function( err, responseData) {
console.log(err);
if (!err) {
console.log(responseData);
return responseData;
//res.end();
}
});
};
//module.exports(list);
| JavaScript | 0.999999 | @@ -1530,34 +1530,16 @@
to
-%3Ca href='%22+ link +%22'%3E%3C/a%3E%22
+'%22+ link
;%0A
|
c4e753d1c81bc584f5ddd92bde3c986b3c181613 | Allow setting highlanderDeactivate in activate | source/ui/Group.js | source/ui/Group.js | /**
_enyo.Group_ provides a wrapper around multiple elements. It enables the
creation of radio groups from arbitrary components supporting the
[GroupItem](#enyo.GroupItem) API.
*/
enyo.kind({
name: "enyo.Group",
published: {
/**
If true, only one GroupItem in the component list may be active at
a given time.
*/
highlander: true,
//* If true, an active highlander item may be deactivated
allowHighlanderDeactivate: false,
//* The control that was last selected
active: null,
/**
The `groupName` property is used to scope this group to a certain
set of controls. When used, the group only controls activation of controls who
have the same `groupName` property set on them.
*/
groupName: null
},
//* @protected
handlers: {
onActivate: "activate"
},
activate: function(inSender, inEvent) {
if ((this.groupName || inEvent.originator.groupName) && (inEvent.originator.groupName != this.groupName)) {
return;
}
if (this.highlander) {
// deactivation messages are ignored unless it's an attempt
// to deactivate the highlander
if (!inEvent.originator.active) {
// this clause prevents deactivating a grouped item once it's been active,
// as long as `allowHighlanderDeactivate` is false. Otherwise, the only
// proper way to deactivate a grouped item is to choose a new highlander.
if (inEvent.originator == this.active && !this.allowHighlanderDeactivate) {
this.active.setActive(true);
}
} else {
this.setActive(inEvent.originator);
}
}
},
activeChanged: function(inOld) {
if (inOld) {
inOld.setActive(false);
inOld.removeClass("active");
}
if (this.active) {
this.active.addClass("active");
}
}
});
| JavaScript | 0 | @@ -980,16 +980,429 @@
nder) %7B%0A
+%09%09%09// we can optionally accept an %60allowHighlanderDeactivate%60 property in inEvent without directly %0A%09%09%09// specifying it when instatiating the group - used mainly for custom kinds requiring deactivation %0A%09%09%09if (inEvent.allowHighlanderDeactivate !== undefined && inEvent.allowHighlanderDeactivate !== this.allowHighlanderDeactivate) %7B%0A%09%09%09%09this.setAllowHighlanderDeactivate(inEvent.allowHighlanderDeactivate);%0A%09%09%09%7D%0A
%09%09%09// de
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.