commit
stringlengths 40
40
| subject
stringlengths 1
1.49k
| old_file
stringlengths 4
311
| new_file
stringlengths 4
311
| new_contents
stringlengths 1
29.8k
| old_contents
stringlengths 0
9.9k
| lang
stringclasses 3
values | proba
float64 0
1
|
---|---|---|---|---|---|---|---|
10edeb80155d0bcdff3207497a63e0e3275fdc9d | test on Mobile Safari 13.0 | karma.conf.js | karma.conf.js | /* eslint-disable no-console */
/* eslint-env node */
const { createDefaultConfig } = require('@open-wc/testing-karma'),
merge = require('deepmerge'),
baseCustomLaunchers = {
FirefoxHeadless: {
base: 'Firefox',
flags: ['-headless']
}
},
sauceCustomLaunchers = {
slChrome: {
base: 'SauceLabs',
browserName: 'chrome',
browserVersion: 'beta',
platformName: 'Windows 10'
},
slIphoneSimulator: {
base: 'SauceLabs',
browserName: 'Safari',
appiumVersion: '1.15.0',
deviceName: 'iPhone Simulator',
deviceOrientation: 'portrait',
platformVersion: '13.0',
platformName: 'iOS'
}
},
allCustomLaunchers = {
...baseCustomLaunchers,
...sauceCustomLaunchers
};
module.exports = config => {
const useSauce = process.env.SAUCE_USERNAME && process.env.SAUCE_ACCESS_KEY,
customLaunchers = useSauce ? allCustomLaunchers : baseCustomLaunchers;
if (!useSauce) {
console.warn('Missing SAUCE_USERNAME/SAUCE_ACCESS_KEY, skipping sauce.');
}
config.set(
merge(createDefaultConfig(config), {
coverageIstanbulReporter: {
thresholds: {
global: {
statements: 90,
branches: 85,
functions: 100,
lines: 90
}
}
},
customLaunchers,
browsers: Object.keys(customLaunchers),
files: [{
// runs all files ending with .test in the test folder,
// can be overwritten by passing a --grep flag. examples:
//
// npm run test -- --grep test/foo/bar.test.js
// npm run test -- --grep test/bar/*
pattern: config.grep ? config.grep : 'test/**/*.test.js',
type: 'module'
}],
esm: {
nodeResolve: true
},
client: {
mocha: {
ui: 'tdd'
}
},
sauceLabs: {
testName: 'cosmoz-utils karma tests'
},
reporters: ['dots', 'saucelabs'],
singleRun: true
// you can overwrite/extend the config further
})
);
return config;
};
| /* eslint-disable no-console */
/* eslint-env node */
const { createDefaultConfig } = require('@open-wc/testing-karma'),
merge = require('deepmerge'),
baseCustomLaunchers = {
FirefoxHeadless: {
base: 'Firefox',
flags: ['-headless']
}
},
sauceCustomLaunchers = {
slChrome: {
base: 'SauceLabs',
browserName: 'chrome',
browserVersion: 'beta',
platformName: 'Windows 10'
}
},
allCustomLaunchers = {
...baseCustomLaunchers,
...sauceCustomLaunchers
};
module.exports = config => {
const useSauce = process.env.SAUCE_USERNAME && process.env.SAUCE_ACCESS_KEY,
customLaunchers = useSauce ? allCustomLaunchers : baseCustomLaunchers;
if (!useSauce) {
console.warn('Missing SAUCE_USERNAME/SAUCE_ACCESS_KEY, skipping sauce.');
}
config.set(
merge(createDefaultConfig(config), {
coverageIstanbulReporter: {
thresholds: {
global: {
statements: 90,
branches: 85,
functions: 100,
lines: 90
}
}
},
customLaunchers,
browsers: Object.keys(customLaunchers),
files: [{
// runs all files ending with .test in the test folder,
// can be overwritten by passing a --grep flag. examples:
//
// npm run test -- --grep test/foo/bar.test.js
// npm run test -- --grep test/bar/*
pattern: config.grep ? config.grep : 'test/**/*.test.js',
type: 'module'
}],
esm: {
nodeResolve: true
},
client: {
mocha: {
ui: 'tdd'
}
},
sauceLabs: {
testName: 'cosmoz-utils karma tests'
},
reporters: ['dots', 'saucelabs'],
singleRun: true
// you can overwrite/extend the config further
})
);
return config;
};
| JavaScript | 0 |
02aa972ed92949505ce629f5b3608cb649ebbfe9 | Fix an error when running gulp test | gulp/test.js | gulp/test.js | var gulp = require('gulp'),
gulpLoadPlugins = require('gulp-load-plugins'),
karma = require('karma').server;
var plugins = gulpLoadPlugins();
var defaultTasks = ['env:test', 'karma:unit', 'mochaTest'];
gulp.task('env:test', function () {
process.env.NODE_ENV = 'test';
});
gulp.task('karma:unit', function (done) {
karma.start({
configFile: __dirname + '/../karma.conf.js',
singleRun: true
}, function () {
done();
});
});
gulp.task('loadTestSchema', function () {
require('../server.js');
require('../node_modules/meanio/lib/core_modules/module/util').preload('../packages/**/server', 'model');
});
gulp.task('mochaTest', ['loadTestSchema'], function () {
return gulp.src('../packages/**/server/tests/**/*.js', {read: false})
.pipe(plugins.mocha({
reporter: 'spec'
}));
});
gulp.task('test', defaultTasks);
| var gulp = require('gulp'),
gulpLoadPlugins = require('gulp-load-plugins'),
karma = require('karma').server;
var plugins = gulpLoadPlugins();
var defaultTasks = ['env:test', 'karma:unit', 'mochaTest'];
gulp.task('env:test', function () {
process.env.NODE_ENV = 'test';
});
gulp.task('karma:unit', function (done) {
karma.start({
configFile: __dirname + '/../karma.conf.js',
singleRun: true
}, done);
});
gulp.task('loadTestSchema', function () {
require('../server.js');
require('../node_modules/meanio/lib/core_modules/module/util').preload('../packages/**/server', 'model');
});
gulp.task('mochaTest', ['loadTestSchema'], function () {
return gulp.src('../packages/**/server/tests/**/*.js', {read: false})
.pipe(plugins.mocha({
reporter: 'spec'
}));
});
gulp.task('test', defaultTasks);
| JavaScript | 0.000044 |
13c83991a7007c59658e801ddbcf972786fbd4b5 | Add a basic settings object to state.js | src/tracker/state.js | src/tracker/state.js | var STATE = (function(){
var stateChangedEvents = [];
var triggerStateChanged = function(changeType, changeDetail){
for(var callback of stateChangedEvents){
callback(changeType, changeDetail);
}
};
var defineTriggeringProperty = function(obj, type, property){
var name = "_"+property;
Object.defineProperty(obj, property, {
get: (() => obj[name]),
set: (value => {
obj[name] = value;
triggerStateChanged(type, property);
})
});
};
/*
* Internal settings class constructor.
*/
var SETTINGS = function(){
};
/*
* Resets settings without triggering state changed event.
*/
SETTINGS.prototype._reset = function(){
this._autoscroll = true;
};
/*
* Internal class constructor.
*/
var CLS = function(){
this.settings = new SETTINGS();
this.resetState();
};
/*
* Resets the state to default values.
*/
CLS.prototype.resetState = function(){
this._savefile = null;
this._isTracking = false;
this.settings._reset();
triggerStateChanged("data", "reset");
};
/*
* Returns the savefile object, creates a new one if needed.
*/
CLS.prototype.getSavefile = function(){
if (!this._savefile){
this._savefile = new SAVEFILE();
}
return this._savefile;
};
/*
* Returns true if the database file contains any data.
*/
CLS.prototype.hasSavedData = function(){
return this._savefile != null;
};
/*
* Returns true if currently tracking message.
*/
CLS.prototype.isTracking = function(){
return this._isTracking;
};
/*
* Toggles the tracking state.
*/
CLS.prototype.toggleTracking = function(){
this._isTracking = !this._isTracking;
triggerStateChanged("tracking", this._isTracking);
};
/*
* Combines current savefile with the provided one.
*/
CLS.prototype.uploadSavefile = function(readFile){
this.getSavefile().combineWith(readFile);
triggerStateChanged("data", "upload");
};
/*
* Triggers a savefile download, if available.
*/
CLS.prototype.downloadSavefile = function(){
if (this.hasSavedData()){
DOM.downloadTextFile("dht.txt", this._savefile.toJson());
}
};
/*
* Registers a Discord server and channel.
*/
CLS.prototype.addDiscordChannel = function(serverName, serverType, channelId, channelName){
var serverIndex = this.getSavefile().findOrRegisterServer(serverName, serverType);
if (this.getSavefile().tryRegisterChannel(serverIndex, channelId, channelName) === true){
triggerStateChanged("data", "channel");
}
};
/*
* Adds all messages from the array to the specified channel.
*/
CLS.prototype.addDiscordMessages = function(channelId, discordMessageArray){
if (this.getSavefile().addMessagesFromDiscord(channelId, discordMessageArray)){
triggerStateChanged("data", "messages");
}
};
/*
* Adds a listener that is called whenever the state changes. If trigger is true, the callback is ran after adding it to the listener list.
* The callback is a function that takes subject (generic type) and detail (specific type or data).
*/
CLS.prototype.onStateChanged = function(callback, trigger){
stateChangedEvents.push(callback);
trigger && callback();
};
return new CLS();
})();
| var STATE = (function(){
var stateChangedEvents = [];
var triggerStateChanged = function(changeType, changeDetail){
for(var callback of stateChangedEvents){
callback(changeType, changeDetail);
}
};
/*
* Internal class constructor.
*/
var CLS = function(){
this.resetState();
};
/*
* Resets the state to default values.
*/
CLS.prototype.resetState = function(){
this._savefile = null;
this._isTracking = false;
triggerStateChanged("data", "reset");
};
/*
* Returns the savefile object, creates a new one if needed.
*/
CLS.prototype.getSavefile = function(){
if (!this._savefile){
this._savefile = new SAVEFILE();
}
return this._savefile;
};
/*
* Returns true if the database file contains any data.
*/
CLS.prototype.hasSavedData = function(){
return this._savefile != null;
};
/*
* Returns true if currently tracking message.
*/
CLS.prototype.isTracking = function(){
return this._isTracking;
};
/*
* Toggles the tracking state.
*/
CLS.prototype.toggleTracking = function(){
this._isTracking = !this._isTracking;
triggerStateChanged("tracking", this._isTracking);
};
/*
* Combines current savefile with the provided one.
*/
CLS.prototype.uploadSavefile = function(readFile){
this.getSavefile().combineWith(readFile);
triggerStateChanged("data", "upload");
};
/*
* Triggers a savefile download, if available.
*/
CLS.prototype.downloadSavefile = function(){
if (this.hasSavedData()){
DOM.downloadTextFile("dht.txt", this._savefile.toJson());
}
};
/*
* Registers a Discord server and channel.
*/
CLS.prototype.addDiscordChannel = function(serverName, serverType, channelId, channelName){
var serverIndex = this.getSavefile().findOrRegisterServer(serverName, serverType);
if (this.getSavefile().tryRegisterChannel(serverIndex, channelId, channelName) === true){
triggerStateChanged("data", "channel");
}
};
/*
* Adds all messages from the array to the specified channel.
*/
CLS.prototype.addDiscordMessages = function(channelId, discordMessageArray){
if (this.getSavefile().addMessagesFromDiscord(channelId, discordMessageArray)){
triggerStateChanged("data", "messages");
}
};
/*
* Adds a listener that is called whenever the state changes. If trigger is true, the callback is ran after adding it to the listener list.
* The callback is a function that takes subject (generic type) and detail (specific type or data).
*/
CLS.prototype.onStateChanged = function(callback, trigger){
stateChangedEvents.push(callback);
trigger && callback();
};
return new CLS();
})();
| JavaScript | 0.000002 |
e4b929506588b5707d2947c4f5b629e8ab540135 | Remove Aside | lib/components/pickers/LocationPicker.react.js | lib/components/pickers/LocationPicker.react.js | 'use strict';
var React = require('react');
var SingleSelect2 = require('./SingleSelect2.react');
var classNames = require('classnames');
var LocationPicker = React.createClass({
getInitialState() {
return{
value: this.props.value || [''],
selecting: true
};
},
_toggleState(item) {
this.setState({selecting: !this.state.selecting});
},
_onResults(value, collection) {
this.setState({
value: value
});
},
_onClick() {
this.props.onSelect(this.state.value);
},
render() {
return(
<div>
{this.props.editable ? this.renderSelect() : this.renderLabel()}
</div>
);
},
renderSelect() {
return(
<div className='inline-block'>
<SingleSelect2
collection={this.props.data}
ref='select'
value={this.props.value}
editable={this.props.editable}
onSelect={this._toggleState}
onRemove={this._toggleState}
onResults={this._onResults}
/>
{this.state.selecting ? this.renderButton() : null}
</div>
);
},
renderButton() {
return (
<button
className='no-style-btn mock-bttn padding'
onClick={this._onClick}>
<i className='fa fa-plus'/>
</button>
);
},
renderLabel() {
return(<label>{this.props.value}</label>);
}
});
module.exports = LocationPicker;
| 'use strict';
var React = require('react');
var SingleSelect2 = require('./SingleSelect2.react');
var classNames = require('classnames');
var LocationPicker = React.createClass({
getInitialState() {
return{
value: this.props.value || [''],
selecting: true
};
},
_toggleState(item) {
this.setState({selecting: !this.state.selecting});
},
_onResults(value, collection) {
this.setState({
value: value
});
},
_onClick() {
this.props.onSelect(this.state.value);
},
render() {
return(
<div>
{this.props.editable ? this.renderSelect() : this.renderLabel()}
</div>
);
},
renderSelect() {
return(
<div className='inline-block'>
<SingleSelect2
collection={this.props.data}
ref='select'
value={this.props.value}
editable={this.props.editable}
onSelect={this._toggleState}
onRemove={this._toggleState}
onResults={this._onResults}
/>
{this.state.selecting ? this.renderButton() : null}
</div>
);
},
renderButton() {
return (
<aside>
<button
className='no-style-btn mock-bttn padding'
onClick={this._onClick}>
<i className='fa fa-plus'/>
</button>
</aside>
);
},
renderLabel() {
return(<label>{this.props.value}</label>);
}
});
module.exports = LocationPicker;
| JavaScript | 0.000001 |
5cfee4759bdb391f6ecc2b9c6d79147d8ae018c2 | Make Icebox really not reorderable. | public/javascript/tracklight.js | public/javascript/tracklight.js | $(document).ready(function() {
// Fetches all tickets, page by page. Updates tickets already
// in the DOM and adds new tickets to the Icebox.
function fetchTickets(page) {
function fetchTicketsFromPage(page) {
$.getJSON("/tickets?page="+page, function(data) {
// Add the tickets to the Icebox.
$.each(data, function(i, ticket_details) {
$("#icebox").append("<li class='ticket-marker' id='ticket_"+ticket_details.id+"_marker' />");
$("#ticket_"+ticket_details.id).oror(function() {
return createTicket(ticket_details.id).appendTo($("#icebox"));
}).fn('update', ticket_details);
});
// Fetch more.
if (data.length > 0) fetchTicketsFromPage(page+1);
});
}
fetchTicketsFromPage(1);
}
// Creates and returns a new, unloaded ticket. Call #update to load.
function createTicket(id) {
return $("#ticket_template").clone(true)
.attr({id: "ticket_"+id, ticket_id: id})
.fn({
// If ticket_details is not given, details will be fetched.
update: function(ticket_details) {
var self = $(this);
function updateWithDetails(ticket_details) {
self.removeClass('loading');
self.find(".title").text(ticket_details.title);
self.find(".link").attr({href: ticket_details.url}).text('#'+ticket_details.id);
self.find(".requester").text(ticket_details.requester);
self.find(".responsible").text(ticket_details.responsible);
self.find(".state").text(ticket_details.state);
self.find(".description").text(ticket_details.description);
self.find(".tags").text(ticket_details.tags);
}
if (ticket_details != undefined)
updateWithDetails(ticket_details);
else
$.getJSON("/tickets/"+self.attr("ticket_id"), updateWithDetails);
return self;
}
});
}
$(".list").sortable({
connectWith: [".list"],
cancel: ".disclosure",
change: function(e, ui) {
if (ui.placeholder.parent().is("#icebox")) {
var id = ui.item.attr("id");
ui.placeholder.insertAfter("#"+id+"_marker");
}
},
update: function(e, ui) {
$(this).not("#icebox").fn('save');
}
}).not("#icebox").fn({
// Moves and creates tickets to match the given list of ticket ids.
// After update, the list has exactly those tickets whose ids are given,
// and in the given order.
update: function(ticket_ids) {
var self = $(this);
$.each(ticket_ids, function(i, id) {
// Find or create ticket by id.
var ticket = $("#ticket_"+id).oror(function() {
return createTicket(id);
});
// Insert in the correct place.
if (i == 0) { ticket.prependTo(self); }
else { ticket.insertAfter(self.find(".ticket:eq("+(i-1)+")")[0]); }
});
// Remove any extra tickets.
self.find(".ticket:gt("+(ticket_ids.length-1)+")").remove();
},
save: function() {
var ticket_ids = $(this).sortable("serialize")
$.post('/lists/'+$(this).attr('id'), ticket_ids);
}
});
$(".disclosure").click(function() {
var shouldClose = $(this).hasClass("open");
$(this).parent().find(".details").toggle(!shouldClose).end().end().toggleClass("open", !shouldClose);
});
// Fetch lists
$.getJSON("/lists", function(lists) {
// Fetch tickets for lists
$.each(lists, function(list, ticket_ids) {
$("#"+list).fn('update', ticket_ids);
})
})
// Fetch all tickets and add extras to Icebox
fetchTickets();
});
| $(document).ready(function() {
// Fetches all tickets, page by page. Updates tickets already
// in the DOM and adds new tickets to the Icebox.
function fetchTickets(page) {
function fetchTicketsFromPage(page) {
$.getJSON("/tickets?page="+page, function(data) {
// Add the tickets to the Icebox.
$.each(data, function(i, ticket_details) {
$("#icebox").append("<li class='ticket-marker' id='ticket_"+ticket_details.id+"_marker' />");
$("#ticket_"+ticket_details.id).oror(function() {
return createTicket(ticket_details.id).appendTo($("#icebox"));
}).fn('update', ticket_details);
});
// Fetch more.
if (data.length > 0) fetchTicketsFromPage(page+1);
});
}
fetchTicketsFromPage(1);
}
// Creates and returns a new, unloaded ticket. Call #update to load.
function createTicket(id) {
return $("#ticket_template").clone(true)
.attr({id: "ticket_"+id, ticket_id: id})
.fn({
// If ticket_details is not given, details will be fetched.
update: function(ticket_details) {
var self = $(this);
function updateWithDetails(ticket_details) {
self.removeClass('loading');
self.find(".title").text(ticket_details.title);
self.find(".link").attr({href: ticket_details.url}).text('#'+ticket_details.id);
self.find(".requester").text(ticket_details.requester);
self.find(".responsible").text(ticket_details.responsible);
self.find(".state").text(ticket_details.state);
self.find(".description").text(ticket_details.description);
self.find(".tags").text(ticket_details.tags);
}
if (ticket_details != undefined)
updateWithDetails(ticket_details);
else
$.getJSON("/tickets/"+self.attr("ticket_id"), updateWithDetails);
return self;
}
});
}
$(".list").fn({
// Moves and creates tickets to match the given list of ticket ids.
// After update, the list has exactly those tickets whose ids are given,
// and in the given order.
update: function(ticket_ids) {
var self = $(this);
$.each(ticket_ids, function(i, id) {
// Find or create ticket by id.
var ticket = $("#ticket_"+id).oror(function() {
return createTicket(id);
});
// Insert in the correct place.
if (i == 0) { ticket.prependTo(self); }
else { ticket.insertAfter(self.find(".ticket:eq("+(i-1)+")")[0]); }
});
// Remove any extra tickets.
self.find(".ticket:gt("+(ticket_ids.length-1)+")").remove();
},
save: function() {
var ticket_ids = $(this).sortable("serialize")
$.post('/lists/'+$(this).attr('id'), ticket_ids);
}
}).sortable({
connectWith: [".list"],
cancel: ".disclosure",
change: function(e, ui) {
if (ui.placeholder.parent().is("#icebox")) {
var id = ui.item.attr("id");
ui.placeholder.insertAfter("#"+id+"_marker");
}
},
update: function(e, ui) {
$(this).not("#icebox").fn('save');
}
});
$(".disclosure").click(function() {
var shouldClose = $(this).hasClass("open");
$(this).parent().find(".details").toggle(!shouldClose).end().end().toggleClass("open", !shouldClose);
});
// Fetch lists
$.getJSON("/lists", function(lists) {
// Fetch tickets for lists
$.each(lists, function(list, ticket_ids) {
$("#"+list).fn('update', ticket_ids);
})
})
// Fetch all tickets and add extras to Icebox
fetchTickets();
});
| JavaScript | 0 |
567afe992d3e4a6e1a57530d366a853814a77282 | change all the parameter name that in relation to unlogin redirect | public/js/admin/login.js | public/js/admin/login.js | /**
* 登录脚本
*/
var page = {
loginFormDom: $("#login-form"),
usernameDom: $('#username'),
passwordDom: $('#password'),
rememberMeDom: $('#remember-me'),
toolBarDom: $('.tool-bar'),
init: function(){
//初始化公共方法
Public.init(),
//初始化 UI 组件
Widgets.init(),
this.initDom(),
this.initValidator(),
this.addEvent();
},
initDom: function(){
var self = this;
//添加操作按钮
var historyUri = 'admin';
var reg = new RegExp("(^|&)" + 'historyUri' + "=([^&]*)(&|$)");
var uriResult = window.location.search.substr(1).match(reg);
if (uriResult != null) {
historyUri = unescape(uriResult[2]);
}
self.toolBarDom.html(
Widgets.OperateButtons._button(self, 'login', 'login', 'LOGIN', function(){
window.location = historyUri;
}, 'btn-success col-xs-12')
);
},
initValidator: function(){
var self = this;
self.loginFormDom.validate({
rules: {
username: {
required: ["用户名"],
},
password: {
required: ["密码"],
rangelength: [6, 30]
}
},
errorPlacement : function(error, element) {
element.parent().addClass('has-error');
$('#'+element.attr('id')+'-error').html(error.text());
},success: function( error, element){
$(element).parent().removeClass('has-error');
$('#'+$(element).attr('id')+'-error').html('');
}
});
},
addEvent: function(){
var self = this;
document.onkeydown = function(e){
var ev = document.all ? window.event : e;
if(ev.keyCode==13) {
ev.keyCode=0;
self.toolBarDom.find('#login').click();
return false;
}
}
},
getPostData: function(){
var self = this;
var isRememberMe = $('#remember-me').is(':checked');
return {
username: self.usernameDom.val(),
password: self.passwordDom.val(),
remember_me: isRememberMe,
};
}
};
$(function() {
page.init();
}); | /**
* 登录脚本
*/
var page = {
loginFormDom: $("#login-form"),
usernameDom: $('#username'),
passwordDom: $('#password'),
rememberMeDom: $('#remember-me'),
toolBarDom: $('.tool-bar'),
init: function(){
//初始化公共方法
Public.init(),
//初始化 UI 组件
Widgets.init(),
this.initDom(),
this.initValidator(),
this.addEvent();
},
initDom: function(){
var self = this;
//添加操作按钮
var jumpUri = 'admin';
var reg = new RegExp("(^|&)" + 'historyUri' + "=([^&]*)(&|$)");
var uriResult = window.location.search.substr(1).match(reg);
if (uriResult != null) {
jumpUri = unescape(uriResult[2]);
}
self.toolBarDom.html(
Widgets.OperateButtons._button(self, 'login', 'login', 'LOGIN', function(){
window.location = jumpUri;
}, 'btn-success col-xs-12')
);
},
initValidator: function(){
var self = this;
self.loginFormDom.validate({
rules: {
username: {
required: ["用户名"],
},
password: {
required: ["密码"],
rangelength: [6, 30]
}
},
errorPlacement : function(error, element) {
element.parent().addClass('has-error');
$('#'+element.attr('id')+'-error').html(error.text());
},success: function( error, element){
$(element).parent().removeClass('has-error');
$('#'+$(element).attr('id')+'-error').html('');
}
});
},
addEvent: function(){
var self = this;
document.onkeydown = function(e){
var ev = document.all ? window.event : e;
if(ev.keyCode==13) {
ev.keyCode=0;
self.toolBarDom.find('#login').click();
return false;
}
}
},
getPostData: function(){
var self = this;
var isRememberMe = $('#remember-me').is(':checked');
return {
username: self.usernameDom.val(),
password: self.passwordDom.val(),
remember_me: isRememberMe,
};
}
};
$(function() {
page.init();
}); | JavaScript | 0.000001 |
01b1ebf71012623351ed79cebac615a684885857 | add theme_color to manifest | server/manifest.js | server/manifest.js | "use strict";
// Manifest for web application - https://w3c.github.io/manifest/
var pkg = require("./../package.json");
module.exports = function manifest(req) {
var data = {
name: pkg.name,
lang: "en-US",
background_color: "#181818",
theme_color: "#181818",
display: "fullscreen",
orientation: "any",
icons: [
{src: "logo32.png", sizes: "32x32", type: "image/png"},
{src: "logo120.png", sizes: "120x120", type: "image/png"},
{src: "logo128.png", sizes: "128x128", type: "image/png"},
{src: "logo152.png", sizes: "152x152", type: "image/png"},
{src: "logo180.png", sizes: "180x180", type: "image/png"},
{src: "logo192.png", sizes: "192x192", type: "image/png"}
]
};
var proto = (req.connection && req.connection.encrypted) ? "https://" : "http://";
var path = (req.url.match(/(.+)\?!\/manifest\.json/) || [null, "/"])[1];
data.start_url = proto + req.headers["host"] + path;
return JSON.stringify(data);
};
| "use strict";
// Manifest for web application - https://w3c.github.io/manifest/
var pkg = require("./../package.json");
module.exports = function manifest(req) {
var data = {
name: pkg.name,
lang: "en-US",
background_color: "#181818",
display: "fullscreen",
orientation: "any",
icons: [
{src: "logo32.png", sizes: "32x32", type: "image/png"},
{src: "logo120.png", sizes: "120x120", type: "image/png"},
{src: "logo128.png", sizes: "128x128", type: "image/png"},
{src: "logo152.png", sizes: "152x152", type: "image/png"},
{src: "logo180.png", sizes: "180x180", type: "image/png"},
{src: "logo192.png", sizes: "192x192", type: "image/png"}
]
};
var proto = (req.connection && req.connection.encrypted) ? "https://" : "http://";
var path = (req.url.match(/(.+)\?!\/manifest\.json/) || [null, "/"])[1];
data.start_url = proto + req.headers["host"] + path;
return JSON.stringify(data);
};
| JavaScript | 0 |
401c335ec3d4b9a3f094d92fb05ecc93e31164c8 | Add emoji RegExp | src/renderer/MyCompiler.js | src/renderer/MyCompiler.js | import React from 'react'
// import Compiler from 'imports?React=react!md2react'
import Compiler from 'imports?React=react!../../node_modules/md2react/src/index'
import path from 'path'
import Highlight from 'react-highlight'
let $ = React.createElement;
function highlight(code, lang, key) {
return <Highlight className={lang}>{code}</Highlight>;
}
export default class MyCompiler extends Compiler {
static rEmoji = /:[0-9a-z_+-]+:/g;
constructor(opts) {
opts.highlight = highlight;
super(opts);
}
compile({md, dirname, search, indication}) {
this.dirname = dirname;
if (search === '') {
this.search = null;
} else {
this.search = {
text: search,
regExp: new RegExp(`(${search})`, 'ig')
};
}
this.indication = indication;
this.ids = {};
this.marksCount = 0;
return super.compile(md);
}
root(node, defs, key, tableAlign) {
return $('div', {
key,
className: 'markdown-body'
}, this.toChildren(node, defs, key));
}
text(node, defs, key, tableAlign) {
if (!this.search || node.value.indexOf(this.search.text) === -1) {
return node.value;
}
let children = [];
let words = node.value.split(this.search.regExp);
words = words.map((word, i) => {
if (i % 2 === 0) {
return word
}
return $('mark', {
className: this.marksCount === this.indication ? 'indicated' : '',
ref: `mark${this.marksCount++}`
}, word);
});
return $('span', {}, words);
}
image({src, title, alt}, defs, key, tableAlign) {
if(!(/^https?:\/\//.test(src))) {
src = path.resolve(this.dirname, src);
}
return $('img', {
key,
src: src,
title: title,
alt: alt
});
}
link(node, defs, key, tableAlign) {
if(!(/^https?:\/\//.test(node.href))) {
node.href = path.resolve(this.dirname, node.href);
}
return $('a', {
key,
href: node.href,
title: node.title
}, this.toChildren(node, defs, key));
}
heading(node, defs, key, tableAlign) {
let text = node.children
.filter((child) => { return child.type == 'text' })
.map((child) => { return child.value })
.join('');
let id = text
.toLowerCase()
.replace(/\s/g, '-')
.replace(/[!<>#%@&='"`:;,\.\*\+\(\)\{\}\[\]\\\/\|\?\^\$]+/g, '')
if (this.ids[id] == null) {
this.ids[id] = 0;
} else {
this.ids[id]++;
id = `${id}-${this.ids[id]}`
}
return $(('h'+node.depth.toString()), {key}, [
$('a', {key: key+'-a', id: id, className: 'anchor', href: '#'+id}, [
$('span', {key: key+'-a-span', className: 'icon icon-link'})
]),
this.toChildren(node, defs, key)
]);
}
}
| import React from 'react'
// import Compiler from 'imports?React=react!md2react'
import Compiler from 'imports?React=react!../../node_modules/md2react/src/index'
import path from 'path'
import Highlight from 'react-highlight'
let $ = React.createElement;
function highlight(code, lang, key) {
return <Highlight className={lang}>{code}</Highlight>;
}
export default class MyCompiler extends Compiler {
constructor(opts) {
opts.highlight = highlight;
super(opts);
}
compile({md, dirname, search, indication}) {
this.dirname = dirname;
if (search === '') {
this.search = null;
} else {
this.search = new RegExp(`(${search})`, 'ig');
}
this.indication = indication;
this.ids = {};
this.marksCount = 0;
return super.compile(md);
}
root(node, defs, key, tableAlign) {
return $('div', {
key,
className: 'markdown-body'
}, this.toChildren(node, defs, key));
}
text(node, defs, key, tableAlign) {
if (!this.search) {
return node.value;
}
let children = [];
let words = node.value.split(this.search);
words = words.map((word, i) => {
if (i % 2 === 0) {
return word
}
return $('mark', {
className: this.marksCount === this.indication ? 'indicated' : '',
ref: `mark${this.marksCount++}`
}, word);
});
return $('span', {}, words);
}
image({src, title, alt}, defs, key, tableAlign) {
if(!(/^https?:\/\//.test(src))) {
src = path.resolve(this.dirname, src);
}
return $('img', {
key,
src: src,
title: title,
alt: alt
});
}
link(node, defs, key, tableAlign) {
if(!(/^https?:\/\//.test(node.href))) {
node.href = path.resolve(this.dirname, node.href);
}
return $('a', {
key,
href: node.href,
title: node.title
}, this.toChildren(node, defs, key));
}
heading(node, defs, key, tableAlign) {
let text = node.children
.filter((child) => { return child.type == 'text' })
.map((child) => { return child.value })
.join('');
let id = text
.toLowerCase()
.replace(/\s/g, '-')
.replace(/[!<>#%@&='"`:;,\.\*\+\(\)\{\}\[\]\\\/\|\?\^\$]+/g, '')
if (this.ids[id] == null) {
this.ids[id] = 0;
} else {
this.ids[id]++;
id = `${id}-${this.ids[id]}`
}
return $(('h'+node.depth.toString()), {key}, [
$('a', {key: key+'-a', id: id, className: 'anchor', href: '#'+id}, [
$('span', {key: key+'-a-span', className: 'icon icon-link'})
]),
this.toChildren(node, defs, key)
]);
}
}
| JavaScript | 0.999999 |
09c4808e52aafffe7c4601e655307241d589250f | include css | karma.conf.js | karma.conf.js | // karma.conf.js
module.exports = function(config) {
config.set({
frameworks: ['jasmine', 'requirejs'],
files: [
{pattern: 'tests/common.js', included: true},
{pattern: 'tests/fixtures/*.html', included: false},
{pattern: 'tests/fixtures/test.css', included: true},
{pattern: 'tests/spec/*.js', included: false},
{pattern: 'tests/vendor/**/*.js', included: false},
{pattern: 'tests/utils/*.js', included: false},
{pattern: 'rich/**/*.js', included: false},
{pattern: 'demos/src/static/js/**/*.js', included: false},
{pattern: 'demos/src/static/js/**/*.html', included: false},
{pattern: 'demos/src/static/css/styles.css', included: true},
'tests/karma-main.js'
],
preprocessors: {
'rich/**/*.js': 'coverage'
},
exclude: [
'**/karma.conf.js'
],
reporters: ['dots'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});
};
| // karma.conf.js
module.exports = function(config) {
config.set({
frameworks: ['jasmine', 'requirejs'],
files: [
{pattern: 'tests/common.js', included: true},
{pattern: 'tests/fixtures/*.html', included: false},
{pattern: 'tests/spec/*.js', included: false},
{pattern: 'tests/vendor/**/*.js', included: false},
{pattern: 'tests/utils/*.js', included: false},
{pattern: 'rich/**/*.js', included: false},
{pattern: 'demos/src/static/js/**/*.js', included: false},
{pattern: 'demos/src/static/js/**/*.html', included: false},
{pattern: 'demos/src/static/css/styles.css', included: true},
'tests/karma-main.js'
],
preprocessors: {
'rich/**/*.js': 'coverage'
},
exclude: [
'**/karma.conf.js'
],
reporters: ['dots'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});
};
| JavaScript | 0.000054 |
f1b173558ffa7a3c5475abd010bcaad9d7d237d8 | fix schedule rules to local server time | server/schedule.js | server/schedule.js | const schedule = require('node-schedule')
const axios = require('axios')
const cheerio = require('cheerio')
const Account = require('APP/db').Accounts
const transformData = require('./utils').transformData
const clearWhiteSpace = require('./utils').clearWhiteSpace
const clearFlairWhiteSpace = require('./utils').clearFlairWhiteSpace
const clearUsernameLines = require('./utils').clearUsernameLines
const weeklyTimelineUpdateRule = new schedule.RecurrenceRule()
weeklyTimelineUpdateRule.minute = 55
weeklyTimelineUpdateRule.hour = 19
weeklyTimelineUpdateRule.dayOfWeek = 0
const hourlyStatsUpdateRule = new schedule.RecurrenceRule()
hourlyStatsUpdateRule.minute = 0
const fetchLeaderboardsAccountsRule = new schedule.RecurrenceRule()
fetchLeaderboardsAccountsRule.minute = 55
fetchLeaderboardsAccountsRule.hour = 19
const weeklyTimelineUpdate = schedule.scheduleJob(weeklyTimelineUpdateRule, function() {
Account.findAll()
.then(allAccounts => allAccounts.map(account => account.update({
timeline: account.timeline.concat(account.getWeeklyStats())
})))
.catch(console.error)
})
const hourlyStatsUpdate = schedule.scheduleJob(hourlyStatsUpdateRule, function() {
Account.findAll()
.then(allAccounts => allAccounts.map(account => {
axios.get(account.url)
.then(response => response.data)
.then(data => {
const newStats = fetchStats(data)
account.update({
allTime: newStats[0],
rolling300: newStats[1],
flairs: newStats[2],
name: newStats[3]
})
})
}))
})
const fetchLeaderboardsAccounts = schedule.scheduleJob(fetchLeaderboardsAccountsRule, function() {
axios.get('http://tagpro-radius.koalabeast.com/boards')
.then(response => response.data)
.then(data => {
const $ = cheerio.load(data)
fetchLeaderboards($)
})
})
function fetchStats(data) {
const $ = cheerio.load(data)
return [fetchAllTime($), fetchRolling300($), fetchFlairs($), fetchName($), fetchDegrees($)]
}
function fetchAllTime($) {
let dataArr = []
$('#all-stats').find('td').each(function(index, elem) {
dataArr.push(elem.firstChild.data)
})
dataArr = transformData(dataArr, 'all')
return dataArr
}
function fetchRolling300($) {
let dataArr = []
$('#rolling').find('td').each(function(index, elem) {
dataArr.push(elem.firstChild.data)
})
dataArr = transformData(dataArr, 'rolling')
return dataArr
}
function fetchName($) {
return clearWhiteSpace($('.profile-name').text())
}
function fetchDegrees($) {
return clearWhiteSpace($('.profile-detail').find('td')[5].children[0].data.slice(0, -1))
}
function fetchFlairs($) {
const dataArr = []
$('#owned-flair').find('.flair-header').each(function(index, elem) {
const flairName = clearFlairWhiteSpace(elem.firstChild.data)
if (flairName !== 'Remove Flair') dataArr.push({flairName})
})
$('#owned-flair').find('.flair-footer').each(function(index, elem) {
let flairCount = clearWhiteSpace(elem.firstChild.next.firstChild.data)
flairCount = +flairCount.split(':')[1] || 0
if (index !== dataArr.length) dataArr[index].flairCount = flairCount
})
return dataArr
}
function fetchLeaderboards($) {
const accountArr = []
$('#daily').find('a').each(function(index, elem) {
accountArr.push({
name: clearUsernameLines(elem.lastChild.data),
url: `http://tagpro-radius.koalabeast.com${elem.attribs.href}`
})
})
accountArr.forEach(account => Account.findOrCreate({
where: {
url: account.url
},
defaults: {
name: account.name
}
}))
}
module.exports = fetchStats
| const schedule = require('node-schedule')
const axios = require('axios')
const cheerio = require('cheerio')
const Account = require('APP/db').Accounts
const transformData = require('./utils').transformData
const clearWhiteSpace = require('./utils').clearWhiteSpace
const clearFlairWhiteSpace = require('./utils').clearFlairWhiteSpace
const clearUsernameLines = require('./utils').clearUsernameLines
const weeklyTimelineUpdateRule = new schedule.RecurrenceRule()
weeklyTimelineUpdateRule.minute = 55
weeklyTimelineUpdateRule.hour = 15
weeklyTimelineUpdateRule.dayOfWeek = 0
const hourlyStatsUpdateRule = new schedule.RecurrenceRule()
hourlyStatsUpdateRule.minute = 0
const fetchLeaderboardsAccountsRule = new schedule.RecurrenceRule()
fetchLeaderboardsAccountsRule.minute = 55
fetchLeaderboardsAccountsRule.hour = 15
const weeklyTimelineUpdate = schedule.scheduleJob(weeklyTimelineUpdateRule, function() {
Account.findAll()
.then(allAccounts => allAccounts.map(account => account.update({
timeline: account.timeline.concat(account.getWeeklyStats())
})))
.catch(console.error)
})
const hourlyStatsUpdate = schedule.scheduleJob(hourlyStatsUpdateRule, function() {
Account.findAll()
.then(allAccounts => allAccounts.map(account => {
axios.get(account.url)
.then(response => response.data)
.then(data => {
const newStats = fetchStats(data)
account.update({
allTime: newStats[0],
rolling300: newStats[1],
flairs: newStats[2],
name: newStats[3]
})
})
}))
})
const fetchLeaderboardsAccounts = schedule.scheduleJob(fetchLeaderboardsAccountsRule, function() {
axios.get('http://tagpro-radius.koalabeast.com/boards')
.then(response => response.data)
.then(data => {
const $ = cheerio.load(data)
fetchLeaderboards($)
})
})
function fetchStats(data) {
const $ = cheerio.load(data)
return [fetchAllTime($), fetchRolling300($), fetchFlairs($), fetchName($), fetchDegrees($)]
}
function fetchAllTime($) {
let dataArr = []
$('#all-stats').find('td').each(function(index, elem) {
dataArr.push(elem.firstChild.data)
})
dataArr = transformData(dataArr, 'all')
return dataArr
}
function fetchRolling300($) {
let dataArr = []
$('#rolling').find('td').each(function(index, elem) {
dataArr.push(elem.firstChild.data)
})
dataArr = transformData(dataArr, 'rolling')
return dataArr
}
function fetchName($) {
return clearWhiteSpace($('.profile-name').text())
}
function fetchDegrees($) {
return clearWhiteSpace($('.profile-detail').find('td')[5].children[0].data.slice(0, -1))
}
function fetchFlairs($) {
const dataArr = []
$('#owned-flair').find('.flair-header').each(function(index, elem) {
const flairName = clearFlairWhiteSpace(elem.firstChild.data)
if (flairName !== 'Remove Flair') dataArr.push({flairName})
})
$('#owned-flair').find('.flair-footer').each(function(index, elem) {
let flairCount = clearWhiteSpace(elem.firstChild.next.firstChild.data)
flairCount = +flairCount.split(':')[1] || 0
if (index !== dataArr.length) dataArr[index].flairCount = flairCount
})
return dataArr
}
function fetchLeaderboards($) {
const accountArr = []
$('#daily').find('a').each(function(index, elem) {
accountArr.push({
name: clearUsernameLines(elem.lastChild.data),
url: `http://tagpro-radius.koalabeast.com${elem.attribs.href}`
})
})
accountArr.forEach(account => Account.findOrCreate({
where: {
url: account.url
},
defaults: {
name: account.name
}
}))
}
module.exports = fetchStats
| JavaScript | 0 |
da7ed22007d80514bce44163732525d230e63e60 | Update the karma.conf.js to run once | karma.conf.js | karma.conf.js | module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['mocha', 'chai', 'sinon'],
files: [
'./test/**/*.spec.js'
],
exclude: [
'./test/PolicyEngine.spec.js'
],
preprocessors: {
'./test/**/*.spec.js': ['webpack', 'sourcemap']
},
// webpack configuration
webpack: {
devtool: 'inline-source-map'
},
reporters: ['spec', 'html'],
specReporter: {
maxLogLines: 5, // limit number of lines logged per test
suppressErrorSummary: false, // do not print error summary
suppressFailed: false, // do not print information about failed tests
suppressPassed: false, // do not print information about passed tests
suppressSkipped: false, // do not print information about skipped tests
showSpecTiming: true, // print the time elapsed for each spec
failFast: false // test would finish with error when a first fail occurs.
},
// the default configuration
htmlReporter: {
outputFile: 'test/units.html',
// Optional
pageTitle: 'Unit Tests',
subPageTitle: 'reThink Project performance tests',
groupSuites: true,
useCompactStyle: true,
useLegacyStyle: true
},
plugins: ['karma-spec-reporter',
'karma-webpack',
'karma-sourcemap-loader',
'karma-mocha', 'karma-chai',
'karma-sinon',
'karma-htmlfile-reporter',
'karma-mocha-reporter',
'karma-chrome-launcher'],
// customDebugFile: './test/units.html',
// customContextFile: './test/units.html',
client: {
mocha: {
reporter: 'html'
},
captureConsole: true
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['ChromeTravis'],
customLaunchers: {
ChromeTravis: {
base: 'Chrome',
flags: [
'--disable-web-security',
'--ignore-certificate-errors'
]
}
},
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true
});
};
| module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['mocha', 'chai', 'sinon'],
files: [
'./test/**/*.spec.js'
],
exclude: [
'./test/PolicyEngine.spec.js'
],
preprocessors: {
'./test/**/*.spec.js': ['webpack', 'sourcemap']
},
// webpack configuration
webpack: {
devtool: 'inline-source-map'
},
reporters: ['spec', 'html'],
specReporter: {
maxLogLines: 5, // limit number of lines logged per test
suppressErrorSummary: false, // do not print error summary
suppressFailed: false, // do not print information about failed tests
suppressPassed: false, // do not print information about passed tests
suppressSkipped: false, // do not print information about skipped tests
showSpecTiming: true, // print the time elapsed for each spec
failFast: false // test would finish with error when a first fail occurs.
},
// the default configuration
htmlReporter: {
outputFile: 'test/units.html',
// Optional
pageTitle: 'Unit Tests',
subPageTitle: 'reThink Project performance tests',
groupSuites: true,
useCompactStyle: true,
useLegacyStyle: true
},
plugins: ['karma-spec-reporter',
'karma-webpack',
'karma-sourcemap-loader',
'karma-mocha', 'karma-chai',
'karma-sinon',
'karma-htmlfile-reporter',
'karma-mocha-reporter',
'karma-chrome-launcher'],
// customDebugFile: './test/units.html',
// customContextFile: './test/units.html',
client: {
mocha: {
reporter: 'html'
},
captureConsole: true
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['ChromeTravis'],
customLaunchers: {
ChromeTravis: {
base: 'Chrome',
flags: [
'--disable-web-security',
'--ignore-certificate-errors'
]
}
},
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
| JavaScript | 0 |
45fee2355f56f24c092ed1969b0e52f243d98e9e | Make comment deletion play nice with editing | public/js/application.js | public/js/application.js | $(document).ready(function() {
// This is called after the document has loaded in its entirety
// This guarantees that any elements we bind to will exist on the page
// when we try to bind to them
// See: http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
$('.comment-form').on('submit', function(event){
event.preventDefault();
var url = $(this).attr('action');
var data = $(this).serialize();
var request = $.ajax({
url: url,
method: 'POST',
data: data
});
request.done(function(response){
$('.comments ul').append(
$('<li id='+response.id+'>' + response.content + '<a class="comment-edit" href="#edit">Edit</a><form class="comment-delete" action="/comments/'+response.id+'/delete" method="post"><input type="hidden" name="_method" value="delete"><input type="submit" value="Delete"></form>')
)
});
});
$('.comments').on('click', '.comment-edit', function(event){
event.preventDefault();
if ($('.comments').find('#dynaform').attr('action')){
formText = $('#dynaform input[type=text]').val();
id = $('#dynaform').parent().attr('id')
$('#dynaform').replaceWith(formText + ' <a class="comment-edit" href="#edit">Edit</a><form class="comment-delete" action="/comments/'+id+'/delete" method="post"><input type="hidden" name="_method" value="delete"><input type="submit" value="Delete"></form>');
};
$listItem = $(this).parent();
commentId = $listItem.attr('id')
commentText = $listItem
.clone()
.children()
.remove()
.end()
.text()
.trim();
$listItem.html('<form id="dynaform" action="/comments/'+commentId+'/edit" method="post"><input type="hidden" name="_method" value="put" ><input name="content" type="text" value="'+commentText+'"><input type="submit"></form>');
$listItem.on('submit', '#dynaform', function(event){
event.preventDefault();
id = $(this).parent().attr('id')
url = $(this).attr('action');
data = $(this).serialize();
request = $.ajax({
url: url,
method: 'put',
data: data
});
request.done(function(text){
console.log(text);
$listItem.html(text + ' <a class="comment-edit" href="#edit">Edit</a><form class="comment-delete" action="/comments/'+id+'/delete" method="post"><input type="hidden" name="_method" value="delete"><input type="submit" value="Delete"></form>');
});
});
});
$('.comments').on('click', '.comment-delete', function(event){
event.preventDefault();
url = $(this).attr('action')
request = $.ajax({
url: url,
method: 'delete'
});
request.done(function(id){
$('.comments #'+id).remove();
});
});
});
| $(document).ready(function() {
// This is called after the document has loaded in its entirety
// This guarantees that any elements we bind to will exist on the page
// when we try to bind to them
// See: http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
$('.comment-form').on('submit', function(event){
event.preventDefault();
var url = $(this).attr('action');
var data = $(this).serialize();
var request = $.ajax({
url: url,
method: 'POST',
data: data
});
request.done(function(response){
$('.comments ul').append(
$('<li id='+response.id+'>' + response.content + " <a class='comment-edit' href='#edit'>Edit</a> <a class='comment-delete' href='#delete'>Delete</a>" + '</li>')
)
});
});
$('.comments').on('click', '.comment-edit', function(event){
event.preventDefault();
if ($('.comments').find('#dynaform').attr('action')){
formText = $('#dynaform input[type=text]').val();
$('#dynaform').replaceWith(formText + " <a class='comment-edit' href='#edit'>Edit</a> <a class='comment-delete' href='#delete'>Delete</a>");
};
$listItem = $(this).parent();
commentId = $listItem.attr('id')
commentText = $listItem
.clone()
.children()
.remove()
.end()
.text()
.trim();
$listItem.html('<form id="dynaform" action="/comments/'+commentId+'/edit" method="post"><input type="hidden" name="_method" value="put" ><input name="content" type="text" value="'+commentText+'"><input type="submit"></form>');
$listItem.on('submit', '#dynaform', function(event){
event.preventDefault();
url = $(this).attr('action');
data = $(this).serialize();
request = $.ajax({
url: url,
method: 'put',
data: data
});
request.done(function(text){
console.log(text);
$listItem.html(text + " <a class='comment-edit' href='#edit'>Edit</a> <a class='comment-delete' href='#delete'>Delete</a>");
});
});
});
$('.comments').on('click', '.comment-delete', function(event){
event.preventDefault();
url = $(this).attr('action')
request = $.ajax({
url: url,
method: 'delete'
});
request.done(function(id){
$('.comments #'+id).remove();
});
});
});
| JavaScript | 0 |
b452560bcaf90ea6e6b01e10797b4991980081e5 | Allow specifying AngularJS version for testing using env variable | karma.conf.js | karma.conf.js | module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js',
'https://code.angularjs.org/1.2.17/angular-mocks.js',
'src/*.js',
'test/**/*.spec.js'
],
exclude: [],
preprocessors: {},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['PhantomJS'],
singleRun: false
})
if(process.env.ANGULARJS_VERSION) {
config.files[0] = 'https://ajax.googleapis.com/ajax/libs/angularjs/' +
process.env.ANGULARJS_VERSION + '/angular.min.js'
config.files[1] = 'https://code.angularjs.org/' +
process.env.ANGULARJS_VERSION + '/angular-mocks.js'
}
}
| module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js',
'https://code.angularjs.org/1.2.17/angular-mocks.js',
'src/*.js',
'test/**/*.spec.js'
],
exclude: [],
preprocessors: {},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['PhantomJS'],
singleRun: false
})
}
| JavaScript | 0 |
4b1367114829feef9400bea8e9f64b90813bbf88 | Update dropin.js | client/dropin.js | client/dropin.js | var app = angular.module('WifiGoApp', []);
app.controller('DropinController', ['$scope', '$http', function ($scope, $http) {
$scope.message = 'Please use the form below to pay:';
$scope.showDropinContainer = true;
$scope.isError = false;
$scope.isPaid = false;
$scope.getToken = function () {
$http({
method: 'POST',
url:'/clientoken'
}).success(function (data) {
console.log(data.client_token);
braintree.setup(data.client_token, 'dropin', {
container: 'checkout',
// Form is not submitted by default when paymentMethodNonceReceived is implemented
paymentMethodNonceReceived: function (event, nonce) {
$scope.message = 'Processing your payment...';
$scope.showDropinContainer = false;
$http({
method: 'POST',
url: 'http://localhost:3000/api/v1/process',
data: {
amount: $scope.amount,
payment_method_nonce: nonce
}
}).success(function (data) {
console.log(data.success);
if (data.success) {
$scope.message = 'Payment authorized, thanks.';
$scope.showDropinContainer = false;
$scope.isError = false;
$scope.isPaid = true;
} else {
// implement your solution to handle payment failures
$scope.message = 'Payment failed: ' + data.message + ' Please refresh the page and try again.';
$scope.isError = true;
}
}).error(function (error) {
$scope.message = 'Error: cannot connect to server. Please make sure your server is running.';
$scope.showDropinContainer = false;
$scope.isError = true;
});
}
});
}).error(function (error) {
$scope.message = 'Error: cannot connect to server. Please make sure your server is running.';
$scope.showDropinContainer = false;
$scope.isError = true;
});
};
$scope.getToken();
}]);
app.controller("UserInfoController", ['$scope', '$http', function ($scope, $http){
$scope.userInfo = {}
$scope.userInfo.submitUserInfo=function(item,event){
console.log("form submit");
var dataObject = {
"firstName":$scope.userInfo.firstName,
"lastName":$scope.userInfo.lastName,
"address1":$scope.userInfo.address1,
"address2":$scope.userInfo.address2,
"city":$scope.userInfo.city,
"state":$scope.userInfo.state,
"postalcode":$scope.userInfo.postalcode,
"country":$scope.userInfo.country
}
console.log(dataObject);
}
}]);
| var app = angular.module('WifiGoApp', []);
app.controller('DropinController', ['$scope', '$http', function ($scope, $http) {
$scope.message = 'Please use the form below to pay:';
$scope.showDropinContainer = true;
$scope.isError = false;
$scope.isPaid = false;
$scope.getToken = function () {
$http({
method: 'POST',
url: process.env.WIFI_APP_URL+'/clientoken'
}).success(function (data) {
console.log(data.client_token);
braintree.setup(data.client_token, 'dropin', {
container: 'checkout',
// Form is not submitted by default when paymentMethodNonceReceived is implemented
paymentMethodNonceReceived: function (event, nonce) {
$scope.message = 'Processing your payment...';
$scope.showDropinContainer = false;
$http({
method: 'POST',
url: 'http://localhost:3000/api/v1/process',
data: {
amount: $scope.amount,
payment_method_nonce: nonce
}
}).success(function (data) {
console.log(data.success);
if (data.success) {
$scope.message = 'Payment authorized, thanks.';
$scope.showDropinContainer = false;
$scope.isError = false;
$scope.isPaid = true;
} else {
// implement your solution to handle payment failures
$scope.message = 'Payment failed: ' + data.message + ' Please refresh the page and try again.';
$scope.isError = true;
}
}).error(function (error) {
$scope.message = 'Error: cannot connect to server. Please make sure your server is running.';
$scope.showDropinContainer = false;
$scope.isError = true;
});
}
});
}).error(function (error) {
$scope.message = 'Error: cannot connect to server. Please make sure your server is running.';
$scope.showDropinContainer = false;
$scope.isError = true;
});
};
$scope.getToken();
}]);
app.controller("UserInfoController", ['$scope', '$http', function ($scope, $http){
$scope.userInfo = {}
$scope.userInfo.submitUserInfo=function(item,event){
console.log("form submit");
var dataObject = {
"firstName":$scope.userInfo.firstName,
"lastName":$scope.userInfo.lastName,
"address1":$scope.userInfo.address1,
"address2":$scope.userInfo.address2,
"city":$scope.userInfo.city,
"state":$scope.userInfo.state,
"postalcode":$scope.userInfo.postalcode,
"country":$scope.userInfo.country
}
console.log(dataObject);
}
}]);
| JavaScript | 0.000001 |
128d446f39de93ce63bda3b8ef261446ad6efb0b | fix timestamps when viewing logs | settings/js/log.js | settings/js/log.js | /**
* Copyright (c) 2012, Robin Appelman <icewind1991@gmail.com>
* This file is licensed under the Affero General Public License version 3 or later.
* See the COPYING-README file.
*/
OC.Log={
levels:['Debug','Info','Warning','Error','Fatal'],
loaded:50,//are initially loaded
getMore:function(){
$.get(OC.filePath('settings','ajax','getlog.php'),{offset:OC.Log.loaded},function(result){
if(result.status=='success'){
OC.Log.addEntries(result.data);
}
});
OC.Log.loaded+=50;
},
addEntries:function(entries){
for(var i=0;i<entries.length;i++){
var entry=entries[i];
var row=$('<tr/>');
var levelTd=$('<td/>');
levelTd.text(OC.Log.levels[entry.level]);
row.append(levelTd);
var appTd=$('<td/>');
appTd.text(entry.app);
row.append(appTd);
var messageTd=$('<td/>');
messageTd.text(entry.message);
row.append(messageTd);
var timeTd=$('<td/>');
timeTd.text(formatDate(entry.time*1000));
row.append(timeTd);
$('#log').append(row);
}
}
}
$(document).ready(function(){
$('#moreLog').click(function(){
OC.Log.getMore();
})
});
| /**
* Copyright (c) 2012, Robin Appelman <icewind1991@gmail.com>
* This file is licensed under the Affero General Public License version 3 or later.
* See the COPYING-README file.
*/
OC.Log={
levels:['Debug','Info','Warning','Error','Fatal'],
loaded:50,//are initially loaded
getMore:function(){
$.get(OC.filePath('settings','ajax','getlog.php'),{offset:OC.Log.loaded},function(result){
if(result.status=='success'){
OC.Log.addEntries(result.data);
}
});
OC.Log.loaded+=50;
},
addEntries:function(entries){
for(var i=0;i<entries.length;i++){
var entry=entries[i];
var row=$('<tr/>');
var levelTd=$('<td/>');
levelTd.text(OC.Log.levels[entry.level]);
row.append(levelTd);
var appTd=$('<td/>');
appTd.text(entry.app);
row.append(appTd);
var messageTd=$('<td/>');
messageTd.text(entry.message);
row.append(messageTd);
var timeTd=$('<td/>');
timeTd.text(formatDate(entry.time));
row.append(timeTd);
$('#log').append(row);
}
}
}
$(document).ready(function(){
$('#moreLog').click(function(){
OC.Log.getMore();
})
});
| JavaScript | 0.000007 |
02140ea64d130788532638040bbbefc6e59967d7 | fix the karma refernce to the old define.debug file | karma.conf.js | karma.conf.js | // Karma configuration file
//
// For all available config options and default values, see:
// https://github.com/karma-runner/karma/blob/stable/lib/config.js#L54
module.exports = function (config) {
'use strict';
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
frameworks: [
'mocha'
],
// list of files / patterns to load in the browser
files: [
'bower_components/chai/chai.js',
'define.js',
'test/define.js'
],
// use dots reporter, as travis terminal does not support escaping sequences
// possible values: 'dots', 'progress', 'junit', 'teamcity'
// CLI --reporters progress
reporters: ['dots'],
// enable / disable watching file and executing tests whenever any file changes
// CLI --auto-watch --no-auto-watch
autoWatch: true,
// start these browsers
// CLI --browsers Chrome,Firefox,Safari
browsers: [
'Chrome',
'Firefox',
'PhantomJS'
],
// if browser does not capture in given timeout [ms], kill it
// CLI --capture-timeout 5000
captureTimeout: 20000,
// auto run tests on start (when browsers are captured) and exit
// CLI --single-run --no-single-run
singleRun: false,
plugins: [
'karma-mocha',
'karma-requirejs',
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-ie-launcher',
'karma-safari-launcher',
'karma-phantomjs-launcher'
]
});
};
| // Karma configuration file
//
// For all available config options and default values, see:
// https://github.com/karma-runner/karma/blob/stable/lib/config.js#L54
module.exports = function (config) {
'use strict';
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
frameworks: [
'mocha'
],
// list of files / patterns to load in the browser
files: [
'bower_components/chai/chai.js',
'define.debug.js',
'test/define.js'
],
// use dots reporter, as travis terminal does not support escaping sequences
// possible values: 'dots', 'progress', 'junit', 'teamcity'
// CLI --reporters progress
reporters: ['dots'],
// enable / disable watching file and executing tests whenever any file changes
// CLI --auto-watch --no-auto-watch
autoWatch: true,
// start these browsers
// CLI --browsers Chrome,Firefox,Safari
browsers: [
'Chrome',
'Firefox',
'PhantomJS'
],
// if browser does not capture in given timeout [ms], kill it
// CLI --capture-timeout 5000
captureTimeout: 20000,
// auto run tests on start (when browsers are captured) and exit
// CLI --single-run --no-single-run
singleRun: false,
plugins: [
'karma-mocha',
'karma-requirejs',
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-ie-launcher',
'karma-safari-launcher',
'karma-phantomjs-launcher'
]
});
};
| JavaScript | 0.000202 |
77b5ea44bba135d23e62c5db9c2c31fca9d23755 | Remove debug output | visualizer/app.js | visualizer/app.js | #!/usr/bin/env node
"use strict"
var q = require('q')
var fs = require('fs')
var fsp = require('fs-promise')
var path = require('path')
var Flow = require('./../lib/flow/flow')
var Mustache = require('mustache')
var express = require('express')
var app = express()
app.get('/', function (req, res) {
const FLOW_DIRECTORY = path.join(process.cwd(), 'flows');
// Read files from query
let selectedFiles = req.query['files'] || []
// Make absolute file names
let absoluteFileNames = selectedFiles.map(file => path.join(FLOW_DIRECTORY, file) )
let allFiles = fs.readdirSync(FLOW_DIRECTORY)
.filter(filename => fs.statSync(path.join(FLOW_DIRECTORY, filename)).isFile() && path.extname(filename) == '.json')
console.log('files:', selectedFiles)
// Load templates
let template = fs.readFileSync(path.join(__dirname, 'views/layout.mustache'), 'utf-8')
let partials = {
'flow_selection': fs.readFileSync(path.join(__dirname, 'views/selection.mustache'), 'utf-8'),
'checkpoint_selection': fs.readFileSync(path.join(__dirname, 'views/checkpoint_selection.mustache'), 'utf-8')
}
let view = {
'file': selectedFiles[0],
'allFiles': allFiles,
'flowDirectory': FLOW_DIRECTORY,
'messages': [],
'flows': [],
'checkpoints': [],
'json': function() {
return function(json, render) {
return "JSON: " + render(json)
}
},
'img': function() {
return function(value, render) {
let rendered = render(value) + ""
let length = rendered.length
return length > 0 ? ('<img src="data:image/png;base64,' + rendered + '">') : ''
}
},
'device-icon': function() {
let iconType = {
'phone': 'mobile',
'tablet': 'tablet',
'desktop': 'desktop'
}
let faType = iconType[this.type]
let screenSize = null
if (this.width && this.height) {
screenSize = this.width + "x" + this.height
}
if (faType) {
let capitalizeFirstLetter = string => string[0].toUpperCase() + string.slice(1)
let title = Mustache.render("{{type}}{{#screenSize}}, {{.}}{{/screenSize}}", {
'type': capitalizeFirstLetter(faType),
'screenSize': screenSize
})
return '<i class="fa fa-' + faType + '" aria-hidden="true" title="' + title + '"></i>'
} else {
return ''
}
}
}
q.all(absoluteFileNames.map(fileName => fsp.access(fileName, fs.F_OK)
.catch(err => {
let message = "Error loading file. " + (err.path || "")
console.log(message)
view.messages.push(message)
res.status(404)
})
.then(() => {
let flow = Flow.load(fileName)
view.flows.push({
devices: flow.deviceArray(),
grid: flow.grid()
})
view.checkpoints = view.checkpoints.concat(flow.checkpoints().map(c => c.name))
})
)).then(() => {
// Filter duplicates
view.checkpoints = view.checkpoints.filter((value, index, self) => {
// Is the first value in the array
return self.indexOf(value) === index
})
// Render template
let html = Mustache.render(template, view, partials)
res.send(html)
}).catch(err => {
let message = "An error occured. " + err.message
console.log(message)
view.messages.push(message)
res.status(500)
})
});
app.use('/public', express.static(path.join(__dirname, '/public')))
app.use('/bower_components', express.static(path.join(__dirname, '/bower_components')))
app.listen(3000, function () {
console.log('Listening on port 3000.')
})
| #!/usr/bin/env node
"use strict"
var q = require('q')
var fs = require('fs')
var fsp = require('fs-promise')
var path = require('path')
var Flow = require('./../lib/flow/flow')
var Mustache = require('mustache')
var express = require('express')
var app = express()
app.get('/', function (req, res) {
const FLOW_DIRECTORY = path.join(process.cwd(), 'flows');
// Read files from query
let selectedFiles = req.query['files'] || []
// Make absolute file names
let absoluteFileNames = selectedFiles.map(file => path.join(FLOW_DIRECTORY, file) )
let allFiles = fs.readdirSync(FLOW_DIRECTORY)
.filter(filename => fs.statSync(path.join(FLOW_DIRECTORY, filename)).isFile() && path.extname(filename) == '.json')
console.log('files:', selectedFiles)
// Load templates
let template = fs.readFileSync(path.join(__dirname, 'views/layout.mustache'), 'utf-8')
let partials = {
'flow_selection': fs.readFileSync(path.join(__dirname, 'views/selection.mustache'), 'utf-8'),
'checkpoint_selection': fs.readFileSync(path.join(__dirname, 'views/checkpoint_selection.mustache'), 'utf-8')
}
let view = {
'file': selectedFiles[0],
'allFiles': allFiles,
'flowDirectory': FLOW_DIRECTORY,
'messages': [],
'flows': [],
'checkpoints': [],
'json': function() {
return function(json, render) {
return "JSON: " + render(json)
}
},
'img': function() {
return function(value, render) {
let rendered = render(value) + ""
let length = rendered.length
return length > 0 ? ('<img src="data:image/png;base64,' + rendered + '">') : ''
}
},
'device-icon': function() {
let iconType = {
'phone': 'mobile',
'tablet': 'tablet',
'desktop': 'desktop'
}
let faType = iconType[this.type]
let screenSize = null
if (this.width && this.height) {
screenSize = this.width + "x" + this.height
}
if (faType) {
let capitalizeFirstLetter = string => string[0].toUpperCase() + string.slice(1)
let title = Mustache.render("{{type}}{{#screenSize}}, {{.}}{{/screenSize}}", {
'type': capitalizeFirstLetter(faType),
'screenSize': screenSize
})
return '<i class="fa fa-' + faType + '" aria-hidden="true" title="' + title + '"></i>'
} else {
return ''
}
}
}
q.all(absoluteFileNames.map(fileName => fsp.access(fileName, fs.F_OK)
.catch(err => {
let message = "Error loading file. " + (err.path || "")
console.log(message)
view.messages.push(message)
res.status(404)
})
.then(() => {
let flow = Flow.load(fileName)
view.flows.push({
devices: flow.deviceArray(),
grid: flow.grid()
})
view.checkpoints = view.checkpoints.concat(flow.checkpoints().map(c => c.name))
})
)).then(() => {
view.checkpoints = view.checkpoints.filter((value, index, self) => {
// Is the first value in the array
return self.indexOf(value) === index
})
console.log('view.checkpoints', view.checkpoints)
// Render template
let html = Mustache.render(template, view, partials)
res.send(html)
}).catch(err => {
let message = "An error occured. " + err.message
console.log(message)
view.messages.push(message)
res.status(500)
})
});
app.use('/public', express.static(path.join(__dirname, '/public')))
app.use('/bower_components', express.static(path.join(__dirname, '/bower_components')))
app.listen(3000, function () {
console.log('Listening on port 3000.')
})
| JavaScript | 0.000037 |
729f3b090efdefbeed7166b167f96547a700892e | add missing flow annotation | src/types/RouterConfig.js | src/types/RouterConfig.js | // @flow
export type RouterConfig = {
history?: Object
};
| export type RouterConfig = {
history?: Object
};
| JavaScript | 0.000002 |
6fe59001ef8eb6b932e05db93323476b6b6ddecd | Create app.js | client/js/app.js | client/js/app.js | // angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'ngResource'])
.run(function($window, $location, $ionicPlatform, $rootScope, AuthenticationService) {
$rootScope.user = {
name: $window.sessionStorage.name,
is_admin: $window.sessionStorage.is_admin
};
if ($rootScope.user.is_admin) {
AuthenticationService.isAdmin = true;
}
$rootScope.$on("$stateChangeStart", function(event, toState) {
//redirect only if both isAuthenticated is false and no token is set
if (['home', 'login', 'logout', 'register', 'one', 'two', 'three', 'all'].indexOf(toState.name) === -1) {
if (!AuthenticationService.isAuthenticated && !$window.localStorage.token) {
event.preventDefault();
$location.path("/home");
}
}
});
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
.config(function($stateProvider, $urlRouterProvider, $httpProvider) {
// Ionic uses AngularUI Router which uses the concept of states
// Learn more here: https://github.com/angular-ui/ui-router
// Set up the various states which the app can be in.
// Each state's controller can be found in controllers.js
$stateProvider.state('home', {
url: "/",
templateUrl: "templates/home.html",
controller: 'HomeCtrl'
})
.state('register', {
url: "/register",
templateUrl: "templates/two.html",
controller: 'RegisterCtrl'
})
.state('login', {
url: "/login",
templateUrl: "templates/one.html",
controller: 'LoginCtrl'
})
.state('one', {
url: "/one",
templateURL: "templates/one.html",
controller: 'OneCtrl'
})
.state('two', {
url: "/two",
templateURL: "templates/two.html",
controller: 'TwoCtrl'
})
.state('three', {
url: "/three",
templateURL: "templates/three.html",
controller: 'ThreeCtrl'
})
.state('all', {
url: "/all",
templateURL: "templates/all.html",
controller: 'AllCtrl'
})
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/');
// Register middleware to ensure our auth token is passed to the server
$httpProvider.interceptors.push('TokenInterceptor');
})
| // angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'ngResource'])
.run(function($window, $location, $ionicPlatform, $rootScope, AuthenticationService) {
$rootScope.user = {
name: $window.sessionStorage.name,
is_admin: $window.sessionStorage.is_admin
};
if ($rootScope.user.is_admin) {
AuthenticationService.isAdmin = true;
}
$rootScope.$on("$stateChangeStart", function(event, toState) {
//redirect only if both isAuthenticated is false and no token is set
if (['home', 'login', 'logout', 'register', 'one', 'two', 'three', 'all'].indexOf(toState.name) === -1) {
if (!AuthenticationService.isAuthenticated && !$window.localStorage.token) {
event.preventDefault();
$location.path("/home");
}
}
});
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
.config(function($stateProvider, $urlRouterProvider, $httpProvider) {
// Ionic uses AngularUI Router which uses the concept of states
// Learn more here: https://github.com/angular-ui/ui-router
// Set up the various states which the app can be in.
// Each state's controller can be found in controllers.js
$stateProvider.state('home', {
url: "/",
templateUrl: "templates/home.html",
controller: 'HomeCtrl'
})
.state('register', {
url: "/register",
templateUrl: "templates/two.html",
controller: 'RegisterCtrl'
})
.state('login', {
url: "/one",
templateUrl: "templates/one.html",
controller: 'LoginCtrl'
})
.state('one', {
url: "/one",
templateURL: "templates/one.html",
controller: 'OneCtrl'
})
.state('two', {
url: "/two",
templateURL: "templates/two.html",
controller: 'TwoCtrl'
})
.state('three', {
url: "/three",
templateURL: "templates/three.html",
controller: 'ThreeCtrl'
})
.state('all', {
url: "/all",
templateURL: "templates/all.html",
controller: 'AllCtrl'
})
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/');
// Register middleware to ensure our auth token is passed to the server
$httpProvider.interceptors.push('TokenInterceptor');
})
| JavaScript | 0.000003 |
7372d0a63496d55a64c3ee0cc68e576362964f25 | extend custom id generation function test | test/id.js | test/id.js | /**
* Created by schwarzkopfb on 14/06/16.
*/
'use strict'
const test = require('tap'),
Database = require('..'),
{ url } = require('./credentials'),
db = new Database,
user = {
id: Number, // not necessary
name: String,
timestamp: Date.now
}
test.tearDown(() => db.unref())
// custom id generator fn
db.id = (db, schema, model) => {
test.type(db, Database)
test.type(schema, Database.Schema)
test.type(model, Database.Model)
return new Promise((ok, error) => {
db.client.incr(`id:${schema.name}`, (err, id) => {
if (err)
error(err)
else
ok(id)
})
})
}
db.define({ user })
.connect(url)
// WARNING: this drops all the data in the selected database!
db.client.flushdb()
test.test('custom id generator function #1', test => {
db.create('user', { name: 'test' })
.save()
.then(user => {
test.equal(user.id, 1, 'model should have a numeric id')
test.end()
next()
})
.catch(test.threw)
})
function next() {
test.test('custom id generator function #2', test => {
db.create('user', { name: 'test2' })
.save()
.then(user => {
test.equal(user.id, 2, 'model should have a numeric id')
test.end()
})
.catch(test.threw)
})
}
| /**
* Created by schwarzkopfb on 14/06/16.
*/
'use strict'
const test = require('tap'),
Database = require('..'),
{ url } = require('./credentials'),
db = new Database,
user = {
id: Number, // not necessary
name: String,
timestamp: Date.now
}
test.tearDown(() => db.unref())
// custom id generator fn
db.id = (db, schema, model) => {
test.type(db, Database)
test.type(schema, Database.Schema)
test.type(model, Database.Model)
return new Promise((ok, error) => {
db.client.incr(`id:${schema.name}`, (err, id) => {
if (err)
error(err)
else
ok(id)
})
})
}
db.define({ user })
.connect(url)
// WARNING: this drops all the data in the selected database!
db.client.flushdb()
test.test('custom id generator function', test => {
db.create('user', { name: 'test' })
.save()
.then(user => {
test.equal(user.id, 1, 'model should have a numeric id')
test.end()
})
.catch(test.threw)
})
| JavaScript | 0 |
f511803a3d2dc360c3795e1a5c80931bf7759d68 | Support running licensee on Windows | rules/license-detectable-by-licensee.js | rules/license-detectable-by-licensee.js | // Copyright 2017 TODO Group. All rights reserved.
// Licensed under the Apache License, Version 2.0.
const isWindows = require('is-windows')
const spawnSync = require('child_process').spawnSync
module.exports = function (targetDir, options) {
const expected = '\nLicense: ([^\n]*)'
const licenseeOutput = spawnSync(isWindows ? 'licensee.bat' : 'licensee', [targetDir]).stdout
if (licenseeOutput == null) {
return {
failures: [`Licensee is not installed`]
}
}
const results = licenseeOutput.toString().match(expected)
if (results != null) {
// License: Apache License 2.0
const identified = results[1]
return {
passes: [`Licensee identified the license for project: ${identified}`]
}
} else {
return {
failures: ['Licensee did not identify a license for project']
}
}
}
| // Copyright 2017 TODO Group. All rights reserved.
// Licensed under the Apache License, Version 2.0.
const spawnSync = require('child_process').spawnSync
module.exports = function (targetDir, options) {
const expected = '\nLicense: ([^\n]*)'
const licenseeOutput = spawnSync('licensee', [targetDir]).stdout
if (licenseeOutput == null) {
return {
failures: [`Licensee is not installed`]
}
}
const results = licenseeOutput.toString().match(expected)
if (results != null) {
// License: Apache License 2.0
const identified = results[1]
return {
passes: [`Licensee identified the license for project: ${identified}`]
}
} else {
return {
failures: ['Licensee did not identify a license for project']
}
}
}
| JavaScript | 0 |
60462bfb941b2793393a0a7ca96ef067602afe58 | Add version to menu | main.js | main.js | import electron from 'electron';
import { app, BrowserWindow, Menu, dialog, shell } from 'electron';
import moment from 'moment';
import path from 'path';
import setupEvents from './installers/setupEvents';
let mainWindow = { show: () => { console.log('show'); } }; // temp object while app loads
let willQuit = false;
function createWindow() {
mainWindow = new BrowserWindow({
width: 800,
minWidth: 800,
height: 600,
fullscreenable: true,
backgroundColor: '#403F4D',
icon: path.join(__dirname, 'assets/png/128x128.png')
});
mainWindow.loadURL('file://' + __dirname + '/index.html');
}
function manageRefresh() {
const time = moment('24:00:00', 'hh:mm:ss').diff(moment(), 'seconds');
setTimeout(
midnightTask,
time*1000
);
function midnightTask() {
mainWindow.reload();
}
}
function menuSetup() {
const menuTemplate = [
{
label: 'todometer',
submenu: [
{
label: 'About',
click: () => {
dialog.showMessageBox(mainWindow, {
type: 'info',
title: 'About',
message: 'todometer is built by Cassidy Williams',
detail: 'You can find her on GitHub and Twitter as @cassidoo, or on her website cassidoo.co.',
icon: path.join(__dirname, 'assets/png/64x64.png')
});
}
},
{
label: 'Contribute (v1.0.4)',
click: () => {
shell.openExternal('http://github.com/cassidoo/todometer');
}
},
{
type: 'separator'
/* For debugging
}, {
label: 'Dev tools',
click: () => {
mainWindow.webContents.openDevTools();
}
*/
}, {
label: 'Quit',
accelerator: 'CommandOrControl+Q',
click: () => {
app.quit();
}
}
]
},
{
label: 'Edit',
submenu: [
{role: 'undo'},
{role: 'redo'},
{role: 'cut'},
{role: 'copy'},
{role: 'paste'},
{role: 'delete'},
{role: 'selectall'}
]
},
{
label: 'View',
submenu: [
{role: 'reload'},
{role: 'togglefullscreen'},
{role: 'minimize'},
{role: 'hide'},
{role: 'close'}
]
}
];
const menu = Menu.buildFromTemplate(menuTemplate);
Menu.setApplicationMenu(menu);
}
app.on('ready', () => {
// Squirrel events have to be handled before anything else
if (setupEvents.handleSquirrelEvent()) {
// squirrel event handled and app will exit in 1000ms, so don't do anything else
return;
}
createWindow();
menuSetup();
electron.powerMonitor.on('resume', () => {
mainWindow.reload();
console.log('reloaded');
});
mainWindow.on('close', (e) => {
if (willQuit) {
mainWindow = null;
} else {
e.preventDefault();
mainWindow.hide();
}
});
manageRefresh();
});
app.on('activate', () => mainWindow.show());
app.on('before-quit', () => willQuit = true);
| import electron from 'electron';
import { app, BrowserWindow, Menu, dialog, shell } from 'electron';
import moment from 'moment';
import path from 'path';
import setupEvents from './installers/setupEvents';
let mainWindow = { show: () => { console.log('show'); } }; // temp object while app loads
let willQuit = false;
function createWindow() {
mainWindow = new BrowserWindow({
width: 800,
minWidth: 800,
height: 600,
fullscreenable: true,
backgroundColor: '#403F4D',
icon: path.join(__dirname, 'assets/png/128x128.png')
});
mainWindow.loadURL('file://' + __dirname + '/index.html');
}
function manageRefresh() {
const time = moment('24:00:00', 'hh:mm:ss').diff(moment(), 'seconds');
setTimeout(
midnightTask,
time*1000
);
function midnightTask() {
mainWindow.reload();
}
}
function menuSetup() {
const menuTemplate = [
{
label: 'todometer',
submenu: [
{
label: 'About',
click: () => {
dialog.showMessageBox(mainWindow, {
type: 'info',
title: 'About',
message: 'todometer is built by Cassidy Williams',
detail: 'You can find her on GitHub and Twitter as @cassidoo, or on her website cassidoo.co.',
icon: path.join(__dirname, 'assets/png/64x64.png')
});
}
},
{
label: 'Contribute',
click: () => {
shell.openExternal('http://github.com/cassidoo/todometer');
}
},
{
type: 'separator'
/* For debugging
}, {
label: 'Dev tools',
click: () => {
mainWindow.webContents.openDevTools();
}
*/
}, {
label: 'Quit',
accelerator: 'CommandOrControl+Q',
click: () => {
app.quit();
}
}
]
},
{
label: 'Edit',
submenu: [
{role: 'undo'},
{role: 'redo'},
{role: 'cut'},
{role: 'copy'},
{role: 'paste'},
{role: 'delete'},
{role: 'selectall'}
]
},
{
label: 'View',
submenu: [
{role: 'reload'},
{role: 'togglefullscreen'},
{role: 'minimize'},
{role: 'hide'},
{role: 'close'}
]
}
];
const menu = Menu.buildFromTemplate(menuTemplate);
Menu.setApplicationMenu(menu);
}
app.on('ready', () => {
// Squirrel events have to be handled before anything else
if (setupEvents.handleSquirrelEvent()) {
// squirrel event handled and app will exit in 1000ms, so don't do anything else
return;
}
createWindow();
menuSetup();
electron.powerMonitor.on('resume', () => {
mainWindow.reload();
console.log('reloaded');
});
mainWindow.on('close', (e) => {
if (willQuit) {
mainWindow = null;
} else {
e.preventDefault();
mainWindow.hide();
}
});
manageRefresh();
});
app.on('activate', () => mainWindow.show());
app.on('before-quit', () => willQuit = true);
| JavaScript | 0.000001 |
2795d431059557d84cd0898b2eb6ab806a895fbf | Fix minute format of downloaded filename | chrome-get-urls-from-tabs-in-windows.js | chrome-get-urls-from-tabs-in-windows.js | var textarea = document.getElementById('copy-area');
var create_download_link;
var generate_filename;
chrome.windows.getAll({populate:true}, function(windows){
var w_index = 0;
chrome.storage.sync.get(function(items) {
var format = items.file_format;
if (format === 'yaml') {
var chrome_tabs = [];
windows.forEach(function(window){
textarea.value += "- Window " + w_index + ":\n";
window.tabs.forEach(function(tab){
textarea.value += " - page_title: '" + tab.title.replace('\'', '\'\'') + "'\n";
textarea.value += " url: '" + tab.url + "'\n";
});
textarea.value += "\n";
w_index++;
});
}
else if (format === 'html') {
windows.forEach(function(window){
textarea.value += "Window " + w_index + ":";
window.tabs.forEach(function(tab){
textarea.value += "\n";
textarea.value += "\t* " + tab.title + "\n";
textarea.value += "\t " + tab.url + "\n";
});
textarea.value += "\n\n";
w_index++;
});
}
else { // format === 'text'
windows.forEach(function(window){
textarea.value += "Window " + w_index + ":";
window.tabs.forEach(function(tab){
textarea.value += "\n";
textarea.value += "\t* " + tab.title + "\n";
textarea.value += "\t " + tab.url + "\n";
});
textarea.value += "\n\n";
w_index++;
});
}
create_download_link(textarea.value);
});
});
// Adapted from:
// http://stackoverflow.com/a/18197511
create_download_link = function(text) {
generate_filename(function(filename) {
var download_link = document.createElement('a');
download_link.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
download_link.setAttribute('download', filename);
download_link.innerHTML = 'Download file';
document.querySelector('body').appendChild(download_link);
});
};
generate_filename = function(callback) {
chrome.storage.sync.get(function(items) {
var format = items.file_format;
var d = new Date();
var date_string =
d.getFullYear()
+ ''
+ ('0' + (d.getMonth() + 1)).slice(-2)
+ ''
+ ('0' + d.getDate()).slice(-2)
+ '-'
+ ('0' + d.getHours()).slice(-2)
+ 'h'
+ ('0' + d.getMinutes()).slice(-2);
var file_extension = '';
if (format === 'yaml') {
file_extension = 'yml';
}
else if (format === 'html') {
file_extension = 'html';
}
else {
file_extension = 'txt';
}
callback('chrome-tabs-' + date_string + '.' + file_extension);
});
}; | var textarea = document.getElementById('copy-area');
var create_download_link;
var generate_filename;
chrome.windows.getAll({populate:true}, function(windows){
var w_index = 0;
chrome.storage.sync.get(function(items) {
var format = items.file_format;
if (format === 'yaml') {
var chrome_tabs = [];
windows.forEach(function(window){
textarea.value += "- Window " + w_index + ":\n";
window.tabs.forEach(function(tab){
textarea.value += " - page_title: '" + tab.title.replace('\'', '\'\'') + "'\n";
textarea.value += " url: '" + tab.url + "'\n";
});
textarea.value += "\n";
w_index++;
});
}
else if (format === 'html') {
windows.forEach(function(window){
textarea.value += "Window " + w_index + ":";
window.tabs.forEach(function(tab){
textarea.value += "\n";
textarea.value += "\t* " + tab.title + "\n";
textarea.value += "\t " + tab.url + "\n";
});
textarea.value += "\n\n";
w_index++;
});
}
else { // format === 'text'
windows.forEach(function(window){
textarea.value += "Window " + w_index + ":";
window.tabs.forEach(function(tab){
textarea.value += "\n";
textarea.value += "\t* " + tab.title + "\n";
textarea.value += "\t " + tab.url + "\n";
});
textarea.value += "\n\n";
w_index++;
});
}
create_download_link(textarea.value);
});
});
// Adapted from:
// http://stackoverflow.com/a/18197511
create_download_link = function(text) {
generate_filename(function(filename) {
var download_link = document.createElement('a');
download_link.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
download_link.setAttribute('download', filename);
download_link.innerHTML = 'Download file';
document.querySelector('body').appendChild(download_link);
});
};
generate_filename = function(callback) {
chrome.storage.sync.get(function(items) {
var format = items.file_format;
var d = new Date();
var date_string =
d.getFullYear()
+ ''
+ ('0' + (d.getMonth() + 1)).slice(-2)
+ ''
+ ('0' + d.getDate()).slice(-2)
+ '-'
+ ('0' + d.getHours()).slice(-2)
+ 'h'
+ d.getMinutes();
var file_extension = '';
if (format === 'yaml') {
file_extension = 'yml';
}
else if (format === 'html') {
file_extension = 'html';
}
else {
file_extension = 'txt';
}
callback('chrome-tabs-' + date_string + '.' + file_extension);
});
}; | JavaScript | 0 |
151ca1a929fe3ee86b18c9137b45aadfb045606e | remove transports key | karma.conf.js | karma.conf.js | module.exports = (config) => {
const configuration = {
frameworks: [
'browserify',
'jasmine',
],
files: [
'packages/**/*.spec.js',
],
browsers: [
'ChromeHeadless',
],
customLaunchers: {
ChromeTravisCi: {
base: 'ChromeHeadless',
flags: ['--headless --disable-gpu'],
},
},
reporters: [
'progress',
'coverage',
],
coverageReporter: {
check: {
each: {
statements: 100,
branches: 100,
functions: 100,
lines: 100,
},
global: {
statements: 100,
branches: 100,
functions: 100,
lines: 100,
},
},
reporters: [
{
type: 'html',
dir: 'coverage/',
subdir: 'report-html',
},
{
type: 'text',
},
{
type: 'json',
},
],
instrumenterOptions: {
istanbul: {
noCompact: true,
},
},
},
preprocessors: {
'packages/**/*.spec.js': ['browserify'],
},
browserify: {
debug: true,
transform: [
[
'babelify',
{
presets: [
'@babel/preset-env',
],
},
],
],
},
};
if (process.env.TRAVIS) {
configuration.browsers = [
'ChromeTravisCi',
];
}
config.set(configuration);
};
| module.exports = (config) => {
const configuration = {
frameworks: [
'browserify',
'jasmine',
],
files: [
'packages/**/*.spec.js',
],
browsers: [
'ChromeHeadless',
],
transports: ['polling'],
customLaunchers: {
ChromeTravisCi: {
base: 'ChromeHeadless',
flags: ['--headless --disable-gpu'],
},
},
reporters: [
'progress',
'coverage',
],
coverageReporter: {
check: {
each: {
statements: 100,
branches: 100,
functions: 100,
lines: 100,
},
global: {
statements: 100,
branches: 100,
functions: 100,
lines: 100,
},
},
reporters: [
{
type: 'html',
dir: 'coverage/',
subdir: 'report-html',
},
{
type: 'text',
},
{
type: 'json',
},
],
instrumenterOptions: {
istanbul: {
noCompact: true,
},
},
},
preprocessors: {
'packages/**/*.spec.js': ['browserify'],
},
browserify: {
debug: true,
transform: [
[
'babelify',
{
presets: [
'@babel/preset-env',
],
},
],
],
},
};
if (process.env.TRAVIS) {
configuration.browsers = [
'ChromeTravisCi',
];
}
config.set(configuration);
};
| JavaScript | 0 |
042aa373b77f40b6b49e60b96eb36fdb6034e257 | Fix the regex to match the license reported by licensee | rules/license-detectable-by-licensee.js | rules/license-detectable-by-licensee.js | // Copyright 2017 TODO Group. All rights reserved.
// Licensed under the Apache License, Version 2.0.
const isWindows = require('is-windows')
const spawnSync = require('child_process').spawnSync
module.exports = function (targetDir, options) {
const expected = /License: ([^\n]+)/
const licenseeOutput = spawnSync(isWindows() ? 'licensee.bat' : 'licensee', [targetDir]).stdout
if (licenseeOutput == null) {
return {
failures: [`Licensee is not installed`]
}
}
const results = licenseeOutput.toString().match(expected)
if (results != null) {
// License: Apache License 2.0
const identified = results[1]
return {
passes: [`Licensee identified the license for project: ${identified}`]
}
} else {
return {
failures: ['Licensee did not identify a license for project']
}
}
}
| // Copyright 2017 TODO Group. All rights reserved.
// Licensed under the Apache License, Version 2.0.
const isWindows = require('is-windows')
const spawnSync = require('child_process').spawnSync
module.exports = function (targetDir, options) {
const expected = '\nLicense: ([^\n]*)'
const licenseeOutput = spawnSync(isWindows() ? 'licensee.bat' : 'licensee', [targetDir]).stdout
if (licenseeOutput == null) {
return {
failures: [`Licensee is not installed`]
}
}
const results = licenseeOutput.toString().match(expected)
if (results != null) {
// License: Apache License 2.0
const identified = results[1]
return {
passes: [`Licensee identified the license for project: ${identified}`]
}
} else {
return {
failures: ['Licensee did not identify a license for project']
}
}
}
| JavaScript | 0 |
264d55a67f3ed05826e2734d1c9ec2ae1bda72fa | add karma-ie-launcher | karma.conf.js | karma.conf.js | module.exports = function(karma) {
karma.configure({
// base path, that will be used to resolve files and exclude
basePath: '../',
// frameworks to use
frameworks: ['mocha'],
// list of files / patterns to load in the browser
files: [
'PointerGestures/node_modules/chai/chai.js',
'PointerGestures/node_modules/chai-spies/chai-spies.js',
'PointerEvents/src/boot.js',
'PointerEvents/src/PointerEvent.js',
'PointerEvents/src/pointermap.js',
'PointerEvents/src/sidetable.js',
'PointerEvents/src/dispatcher.js',
'PointerEvents/src/installer.js',
'PointerEvents/src/mouse.js',
'PointerEvents/src/touch.js',
'PointerEvents/src/ms.js',
'PointerEvents/src/platform-events.js',
'PointerEvents/src/capture.js',
'PointerGestures/src/PointerGestureEvent.js',
'PointerGestures/src/initialize.js',
'PointerGestures/src/sidetable.js',
'PointerGestures/src/pointermap.js',
'PointerGestures/src/dispatcher.js',
'PointerGestures/src/hold.js',
'PointerGestures/src/track.js',
'PointerGestures/src/flick.js',
'PointerGestures/src/tap.js',
'PointerGestures/tests/setup.js',
'PointerGestures/tests/!(setup).js'
],
// list of files to exclude
exclude: [],
// test results reporter to use
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters: ['progress'],
// web server port
port: 9876,
// cli runner port
runnerPort: 9100,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: karma.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: ['Chrome'],
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 60000,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: true,
// plugins to load
plugins: [
'karma-mocha',
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-ie-launcher',
'karma-script-launcher',
'karma-crbot-reporter'
]
});
};
| module.exports = function(karma) {
karma.configure({
// base path, that will be used to resolve files and exclude
basePath: '../',
// frameworks to use
frameworks: ['mocha'],
// list of files / patterns to load in the browser
files: [
'PointerGestures/node_modules/chai/chai.js',
'PointerGestures/node_modules/chai-spies/chai-spies.js',
'PointerEvents/src/boot.js',
'PointerEvents/src/PointerEvent.js',
'PointerEvents/src/pointermap.js',
'PointerEvents/src/sidetable.js',
'PointerEvents/src/dispatcher.js',
'PointerEvents/src/installer.js',
'PointerEvents/src/mouse.js',
'PointerEvents/src/touch.js',
'PointerEvents/src/ms.js',
'PointerEvents/src/platform-events.js',
'PointerEvents/src/capture.js',
'PointerGestures/src/PointerGestureEvent.js',
'PointerGestures/src/initialize.js',
'PointerGestures/src/sidetable.js',
'PointerGestures/src/pointermap.js',
'PointerGestures/src/dispatcher.js',
'PointerGestures/src/hold.js',
'PointerGestures/src/track.js',
'PointerGestures/src/flick.js',
'PointerGestures/src/tap.js',
'PointerGestures/tests/setup.js',
'PointerGestures/tests/!(setup).js'
],
// list of files to exclude
exclude: [],
// test results reporter to use
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters: ['progress'],
// web server port
port: 9876,
// cli runner port
runnerPort: 9100,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: karma.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: ['Chrome'],
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 60000,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: true,
// plugins to load
plugins: [
'karma-mocha',
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-script-launcher',
'karma-crbot-reporter'
]
});
};
| JavaScript | 0.007187 |
57bd5958c8431494744dac23265d420dbd876fc4 | remove electron deprectated api | main.js | main.js | 'use strict';
const Electron = require('electron');
module.exports = {
load () {
Editor.Menu.register( 'open-log-file', () => {
return [
{
label: Editor.T('CONSOLE.editor_log'),
params: [],
click () {
Editor.Ipc.sendToMain('console:open-log-file');
}
},
{
label: Editor.T('CONSOLE.cocos_console_log'),
params: [],
click () {
Editor.Ipc.sendToMain('app:open-cocos-console-log');
}
},
];
}, true );
},
unload () {
Editor.Menu.unregister( 'open-log-file' );
},
messages: {
'open' () {
Editor.Panel.open('console');
},
'open-log-file': function () {
Electron.shell.openItem(Editor.logfile);
},
'console:clear' () {
Editor.clearLog();
},
'popup-open-log-menu': function (event, x, y) {
let menuTmpl = Editor.Menu.getMenu('open-log-file');
let editorMenu = new Editor.Menu(menuTmpl, event.sender);
x = Math.floor(x);
y = Math.floor(y);
editorMenu.nativeMenu.popup(Electron.BrowserWindow.fromWebContents(event.sender), x, y);
editorMenu.dispose();
}
}
};
| 'use strict';
const Electron = require('electron');
const BrowserWindow = require('browser-window');
module.exports = {
load () {
Editor.Menu.register( 'open-log-file', () => {
return [
{
label: Editor.T('CONSOLE.editor_log'),
params: [],
click () {
Editor.Ipc.sendToMain('console:open-log-file');
}
},
{
label: Editor.T('CONSOLE.cocos_console_log'),
params: [],
click () {
Editor.Ipc.sendToMain('app:open-cocos-console-log');
}
},
];
}, true );
},
unload () {
Editor.Menu.unregister( 'open-log-file' );
},
messages: {
'open' () {
Editor.Panel.open('console');
},
'open-log-file': function () {
Electron.shell.openItem(Editor.logfile);
},
'console:clear' () {
Editor.clearLog();
},
'popup-open-log-menu': function (event, x, y) {
let menuTmpl = Editor.Menu.getMenu('open-log-file');
let editorMenu = new Editor.Menu(menuTmpl, event.sender);
x = Math.floor(x);
y = Math.floor(y);
editorMenu.nativeMenu.popup(BrowserWindow.fromWebContents(event.sender), x, y);
editorMenu.dispose();
}
}
};
| JavaScript | 0.998059 |
f3c5b5302be6583b474ae157993664b9c764c8dd | add browserify.bundleDelay to karma config | karma.conf.js | karma.conf.js | module.exports = function (karma) {
karma.set({
frameworks: ['browserify', 'mocha', 'sinon-chai'],
files: [
'src/**/*.js',
'test/**/*.spec.js',
],
preprocessors: {
'src/**/*.js': ['browserify'],
'test/**/*.spec.js': ['browserify'],
},
browserify: {
bundleDelay: 800,
debug: true,
transform: [
['babelify', {
presets: ['es2015'],
sourceMapsAbsolute: true,
}],
['browserify-istanbul', {
ignore: ['test/**', '**/node_modules/**'],
instrumenterConfig: {
embedSource: true,
},
}],
],
},
colors: true,
concurrency: 5,
logLevel: karma.LOG_DISABLE,
singleRun: true,
browserDisconnectTimeout: 60 * 1000,
browserDisconnectTolerance: 1,
browserNoActivityTimeout: 60 * 1000,
captureTimeout: 4 * 60 * 1000,
});
if (process.env.TRAVIS) {
const customLaunchers = require('./saucelabs-browsers');
karma.set({
autoWatch: false,
browsers: Object.keys(customLaunchers),
coverageReporter: {
type: 'lcovonly',
dir: 'coverage/',
},
customLaunchers,
reporters: ['dots', 'saucelabs', 'coverage'],
sauceLabs: {
testName: 'ScrollReveal',
build: process.env.TRAVIS_BUILD_NUMBER || 'manual',
tunnelIdentifier: process.env.TRAVIS_BUILD_NUMBER || 'autoGeneratedTunnelID',
recordVideo: true,
},
});
} else {
process.env.PHANTOMJS_BIN = './node_modules/phantomjs-prebuilt/bin/phantomjs';
karma.set({
browsers: ['PhantomJS'],
coverageReporter: {
type: 'lcov',
dir: 'coverage/',
},
reporters: ['mocha', 'coverage'],
});
}
};
| module.exports = function (karma) {
karma.set({
frameworks: ['browserify', 'mocha', 'sinon-chai'],
files: [
'src/**/*.js',
'test/**/*.spec.js',
],
preprocessors: {
'src/**/*.js': ['browserify'],
'test/**/*.spec.js': ['browserify'],
},
browserify: {
debug: true,
transform: [
['babelify', {
presets: ['es2015'],
sourceMapsAbsolute: true,
}],
['browserify-istanbul', {
ignore: ['test/**', '**/node_modules/**'],
instrumenterConfig: {
embedSource: true,
},
}],
],
},
colors: true,
concurrency: 5,
logLevel: karma.LOG_DISABLE,
singleRun: true,
browserDisconnectTimeout: 60 * 1000,
browserDisconnectTolerance: 1,
browserNoActivityTimeout: 60 * 1000,
captureTimeout: 4 * 60 * 1000,
});
if (process.env.TRAVIS) {
const customLaunchers = require('./saucelabs-browsers');
karma.set({
autoWatch: false,
browsers: Object.keys(customLaunchers),
coverageReporter: {
type: 'lcovonly',
dir: 'coverage/',
},
customLaunchers,
reporters: ['dots', 'saucelabs', 'coverage'],
sauceLabs: {
testName: 'ScrollReveal',
build: process.env.TRAVIS_BUILD_NUMBER || 'manual',
tunnelIdentifier: process.env.TRAVIS_BUILD_NUMBER || 'autoGeneratedTunnelID',
recordVideo: true,
},
});
} else {
process.env.PHANTOMJS_BIN = './node_modules/phantomjs-prebuilt/bin/phantomjs';
karma.set({
browsers: ['PhantomJS'],
coverageReporter: {
type: 'lcov',
dir: 'coverage/',
},
reporters: ['mocha', 'coverage'],
});
}
};
| JavaScript | 0 |
b2b3662e2478a166019962bfb0fda9679b8f328e | update import page | src/views/Import.react.js | src/views/Import.react.js | import React, { Component, PropTypes } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as PreviewActions from 'actions/previewPage/PreviewActions';
class ImportView extends Component {
constructor(props) {
super(props);
const { mappingsection, homesection, dispatch } = this.props;
this.jsonpreview = mappingsection.mappingData;
this.stringJSon=JSON.stringify(this.jsonpreview,null,4);
this.actions = bindActionCreators(PreviewActions, dispatch);
console.log("json",this.stringJSon.length);
}
importJson() {
}
isBackToThirdStep(e){
this.actions.redirectMapping();
}
parseJson(json){
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
return '<span>' + match + '</span>';
});
}
componentWillReceiveProps(nextProps){
this.props = nextProps;
let mappingsection = this.props.mappingsection;
if(mappingsection && mappingsection.mappingData){
this.jsonpreview = mappingsection.mappingData;
}
}
render() {
return (
<div className="container">
<div className="row">
<div className="upload-container">
<legend>Json Preview</legend>
</div>
<div className="col-lg-6">
<div className="row">
<div ng-hide="mappedJson">
<i className="fa fa-spinner fa-pulse"></i>
Processing Json</div>
<div className="panel panel-default">
<div className="panel-body">
{this.stringJSon}
</div>
</div>
</div>
</div>
<div className="col-lg-3 col-lg-offset-9 btn-set button-container">
<button className="btn btn-primary pull-right" onClick={this.actions.redirectMapping}>Back</button>
<span> </span>
<div className="btn btn-primary pull-right" onClick={this.importJson.bind(this)}>Download</div>
</div>
</div>
</div>
)
}
}
function mapStateToProps(state) {
const { mappingsection, attributesectionsearch, homesection } = state;
return {
mappingsection, attributesectionsearch, homesection
};
}
ImportView.propTypes = {
mappingsection: React.PropTypes.object,
dispatch: React.PropTypes.func.isRequired
};
export default connect(mapStateToProps)(ImportView); | import React, { Component, PropTypes } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as PreviewActions from 'actions/previewPage/PreviewActions';
class ImportView extends Component {
constructor(props) {
super(props);
const { mappingsection, homesection, dispatch } = this.props;
console.log(this.state);
this.mappedJson;
this.jsonpreview = [
{
"product":"pen",
"ProductId":100,
"price":100
},
{
"product":"pencile",
"ProductId":101,
"price":101
},
{
"product":"ink",
"ProductId":102,
"price":102
}
];
this.stringJSon=JSON.stringify(this.jsonpreview,null,4);
this.actions = bindActionCreators(PreviewActions, dispatch);
console.log("json",this.stringJSon.length);
}
importJson() {
}
isBackToThirdStep(e){
this.actions.redirectMapping();
}
parseJson(json){
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
return '<span>' + match + '</span>';
});
}
componentWillReceiveProps(nextProps){
this.props = nextProps;
let mappingsection = this.props.mappingsection;
if(mappingsection && mappingsection.mappingData){
this.jsonpreview = mappingsection.mappingData;
}
}
render() {
return (
<div className="container">
<div className="row">dir
<div className="upload-container">
<legend>Json Preview</legend>
</div>
<div className="col-lg-6">
<div className="row">
<div ng-hide="mappedJson">
<i className="fa fa-spinner fa-pulse"></i>
Processing Json</div>
<div className="panel panel-default">
<div className="panel-body">
{this.stringJSon}
</div>
</div>
</div>
</div>
<div className="col-lg-3 col-lg-offset-9 btn-set button-container">
<button className="btn btn-primary pull-right" onClick={this.actions.redirectMapping}>Back</button>
<span> </span>
<div className="btn btn-primary pull-right" onClick={this.importJson.bind(this)}>Download</div>
</div>
</div>
</div>
)
}
}
function mapStateToProps(state) {
const { mappingsection, attributesectionsearch, homesection } = state;
return {
mappingsection, attributesectionsearch, homesection
};
}
ImportView.propTypes = {
mappingsection: React.PropTypes.object,
dispatch: React.PropTypes.func.isRequired
};
export default connect(mapStateToProps)(ImportView); | JavaScript | 0 |
f0e7c9a87da54065447577999124b02510314006 | second question answered | main.js | main.js | var _ = require('underscore');
var data = require('./items.json');
//Getting prices from the data.
// var prices = _.pluck (data, 'price');
// console.log(prices)
//Reducing the prices to a single number
//Dividing that by the number of items in the array
// var avgPrice = _.reduce(prices, function(a, b);
//
// console.log(prices)
//Second question!
//get prices between $14 and $18, not using other list of prices
var priceRange = _.filter(data,
function(priceList){
return Number (priceList.price) > 14 && Number (priceList.price) < 18;
}
);
//get names of said items
var rangeNames = _.pluck(priceRange, 'title');
console.log("Items that cost between $14.00 USD and $18.00 USD:" + " " + rangeNames + ".");
//Question three
// var pounds = _.pluck (data, 'currency_code');
// console.log(pounds)
| var _ = require('underscore');
var data = require('./items.json');
//Getting prices from the data.
// var prices = _.pluck (data, 'price');
//Reducing the prices to a single number
//Dividing that by the number of items in the array
// var avgPrice = _.reduce(prices, function(a, b);
//
// console.log(prices)
//Second question!
//get prices between $14 and $18
//list of prices is already plucked
// var priceRange = _.filter(prices,
// function(priceList){
// if _.each (prices) >= 14 && <=18;
// return true;
// }
// else {
// return false;
// }
// );
// console.log(priceRange)
//get names of said items
| JavaScript | 0.999955 |
7bb60f26909d0b415f02684e33115e52a3aa4134 | remove repo stats | public/views/repoView.js | public/views/repoView.js | 'use strict';
(function(module) {
const repoView = {};
// REVIEW: Private methods declared here live only within the scope of the wrapping IIFE.
const ui = function() {
let $about = $('#about'); // Best practice: Cache the DOM query if it's used more than once.
$about.find('ul').empty();
// $about.show().siblings().hide();
};
var render = Handlebars.compile($('#repo-template').text());
repoView.index = function() {
ui();
// The jQuery `append` method lets us append an entire array of HTML elements at once:
$('#about li').append(
// repos.with('name').map(render) // Want to filter by a different property other than name?
repos.with('watchers_count').map(render)
);
};
module.repoView = repoView;
})(window);
| 'use strict';
(function(module) {
const repoView = {};
// REVIEW: Private methods declared here live only within the scope of the wrapping IIFE.
const ui = function() {
let $about = $('#about'); // Best practice: Cache the DOM query if it's used more than once.
$about.find('ul').empty();
// $about.show().siblings().hide();
};
var render = Handlebars.compile($('#repo-template').text());
repoView.index = function() {
ui();
// The jQuery `append` method lets us append an entire array of HTML elements at once:
$('#about ul').append(
// repos.with('name').map(render) // Want to filter by a different property other than name?
repos.with('watchers_count').map(render)
);
};
module.repoView = repoView;
})(window);
| JavaScript | 0.000001 |
b45b2875a025feaaa9de6939c567c3fd67bcf66e | Update webpack.config.js | public/webpack.config.js | public/webpack.config.js | const path = require('path');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
module.exports = [
{
mode: 'production',
entry: {
front: path.join(__dirname, 'resources', 'javascript', 'index.js'),
},
watch: true,
output: {
path: __dirname + '/dist/',
publicPath: '/dist/',
filename: "[name].js",
},
module: {
rules: [
{
test: /.jsx?$/,
include: [
path.resolve(__dirname, 'resources', 'javascript'),
],
exclude: [
path.resolve(__dirname, 'node_modules'),
],
loader: 'babel-loader',
query: {
presets: [
["@babel/env", {
"targets": {
"browsers": "last 2 chrome versions"
}
}],
],
},
},
],
},
resolve: {
extensions: ['.json', '.js', '.jsx']
},
devtool: 'source-map',
optimization: {
minimizer: [
new UglifyJsPlugin({
extractComments: true,
}),
],
},
},
{
mode: 'development',
entry: [
path.join(__dirname, 'resources', 'scss', 'screen.scss'),
],
output: {
path: __dirname + '/dist/',
publicPath: '/dist/',
filename: "[name].css",
},
module: {
rules: [
{
test: /\.s?css$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].css',
}
},
{
loader: 'extract-loader'
},
{
loader: 'css-loader?-url'
},
{
loader: 'postcss-loader',
},
{
loader: 'sass-loader'
},
],
},
],
},
},
];
| const path = require('path');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
module.exports = [
{
mode: 'production',
entry: {
front: path.join(__dirname, 'resources', 'javascript', 'index.js'),
},
watch: true,
output: {
path: __dirname + '/dist/',
publicPath: '/dist/',
filename: "[name].js",
},
module: {
rules: [
{
test: /.jsx?$/,
include: [
path.resolve(__dirname, 'resources', 'javascript'),
],
exclude: [
path.resolve(__dirname, 'node_modules'),
],
loader: 'babel-loader',
query: {
presets: [
["@babel/env", {
"targets": {
"browsers": "last 2 chrome versions"
}
}],
],
},
},
],
},
resolve: {
extensions: ['.json', '.js', '.jsx']
},
devtool: 'source-map',
optimization: {
minimizer: [
new UglifyJsPlugin({
extractComments: true,
}),
],
},
},
{
mode: 'development',
entry: [
path.join(__dirname, 'resources', 'scss', 'screen.scss'),
],
output: {
path: __dirname + '/dist/',
publicPath: '/dist/',
filename: "[name].css",
},
module: {
rules: [
{
test: /\.s?css$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].css',
}
},
{
loader: 'extract-loader'
},
{
loader: 'css-loader?-url'
},
{
loader: 'postcss-loader',
options: {
plugins: function () {
return [
require('precss'),
require('autoprefixer'),
require('cssnano'),
];
},
},
},
{
loader: 'sass-loader'
},
],
},
],
},
},
];
| JavaScript | 0.000003 |
92b505ae8dc9d0e94c961248f53e72604aaf54d8 | Change default milestonesExpanded setting to `current` | client/app/bundles/course/lesson-plan/reducers/flags.js | client/app/bundles/course/lesson-plan/reducers/flags.js | import actionTypes from '../constants';
export const initialState = {
canManageLessonPlan: false,
milestonesExpanded: 'current',
};
export default function (state = initialState, action) {
const { type } = action;
switch (type) {
case actionTypes.LOAD_LESSON_PLAN_SUCCESS: {
const nextState = { ...state, ...action.flags };
if (!nextState.milestonesExpanded) {
nextState.milestonesExpanded = initialState.milestonesExpanded;
}
return nextState;
}
default:
return state;
}
}
| import actionTypes from '../constants';
const initialState = {
canManageLessonPlan: false,
milestonesExpanded: 'all',
};
export default function (state = initialState, action) {
const { type } = action;
switch (type) {
case actionTypes.LOAD_LESSON_PLAN_SUCCESS: {
return { ...state, ...action.flags };
}
default:
return state;
}
}
| JavaScript | 0 |
c387c73a7aea97b8d95d20ab7ed44504ec351ee2 | trim vestigial functionality | main.js | main.js | /*jslint browser: true*/
/*global Tangram, gui */
map = (function () {
'use strict';
var map_start_location = [40.70531887544228, -74.00976419448853, 15]; // NYC
/*** URL parsing ***/
// leaflet-style URL hash pattern:
// #[zoom],[lat],[lng]
var url_hash = window.location.hash.slice(1, window.location.hash.length).split('/');
if (url_hash.length == 3) {
map_start_location = [url_hash[1],url_hash[2], url_hash[0]];
// convert from strings
map_start_location = map_start_location.map(Number);
}
/*** Map ***/
var map = L.map('map',
{"keyboardZoomOffset" : .05}
);
var layer = Tangram.leafletLayer({
scene: 'scene.yaml',
attribution: '<a href="https://mapzen.com/tangram" target="_blank">Tangram</a> | © OSM contributors | <a href="https://mapzen.com/" target="_blank">Mapzen</a>'
});
window.layer = layer;
var scene = layer.scene;
window.scene = scene;
// setView expects format ([lat, long], zoom)
map.setView(map_start_location.slice(0, 3), map_start_location[2]);
var hash = new L.Hash(map);
/***** Render loop *****/
window.addEventListener('load', function () {
// Scene initialized
layer.on('init', function() {
});
layer.addTo(map);
});
return map;
}());
| /*jslint browser: true*/
/*global Tangram, gui */
map = (function () {
'use strict';
var locations = {
'Oakland': [37.8044, -122.2708, 15],
'New York': [40.70531887544228, -74.00976419448853, 15],
'Seattle': [47.5937, -122.3215, 15]
};
var map_start_location = locations['New York'];
/*** URL parsing ***/
// leaflet-style URL hash pattern:
// #[zoom],[lat],[lng]
var url_hash = window.location.hash.slice(1, window.location.hash.length).split('/');
if (url_hash.length == 3) {
map_start_location = [url_hash[1],url_hash[2], url_hash[0]];
// convert from strings
map_start_location = map_start_location.map(Number);
}
/*** Map ***/
var map = L.map('map',
{"keyboardZoomOffset" : .05}
);
var layer = Tangram.leafletLayer({
scene: 'scene.yaml',
numWorkers: 2,
attribution: '<a href="https://mapzen.com/tangram" target="_blank">Tangram</a> | © OSM contributors | <a href="https://mapzen.com/" target="_blank">Mapzen</a>',
unloadInvisibleTiles: false,
updateWhenIdle: false
});
window.layer = layer;
var scene = layer.scene;
window.scene = scene;
// setView expects format ([lat, long], zoom)
map.setView(map_start_location.slice(0, 3), map_start_location[2]);
var hash = new L.Hash(map);
/***** Render loop *****/
window.addEventListener('load', function () {
// Scene initialized
layer.on('init', function() {
});
layer.addTo(map);
});
return map;
}());
| JavaScript | 0 |
2dd36e05760a6beb875af57ecb72b786fa8f88b3 | Disable devtools on start | main.js | main.js | 'use strict';
const electron = require('electron');
// Module to control application life.
const app = electron.app;
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow;
const Menu = electron.Menu;
const MenuItem = electron.MenuItem;
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;
function createWindow() {
// Create the browser window.
mainWindow = new BrowserWindow({ width: 1080, height: 760 });
// Disable default menu at start.
const menu = new Menu();
mainWindow.setMenu(menu);
// and load the index.html of the app.
mainWindow.loadURL('file://' + __dirname + '/index.html');
// mainWindow.webContents.openDevTools();
// Emitted when the window is closed.
mainWindow.on('closed', function() {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
});
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', createWindow);
// Quit when all windows are closed.
app.on('window-all-closed', function() {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', function() {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
createWindow();
}
});
| 'use strict';
const electron = require('electron');
// Module to control application life.
const app = electron.app;
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow;
const Menu = electron.Menu;
const MenuItem = electron.MenuItem;
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;
function createWindow() {
// Create the browser window.
mainWindow = new BrowserWindow({ width: 1080, height: 760 });
// Disable default menu at start.
const menu = new Menu();
mainWindow.setMenu(menu);
// and load the index.html of the app.
mainWindow.loadURL('file://' + __dirname + '/index.html');
mainWindow.webContents.openDevTools();
// Emitted when the window is closed.
mainWindow.on('closed', function() {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
});
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', createWindow);
// Quit when all windows are closed.
app.on('window-all-closed', function() {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', function() {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
createWindow();
}
});
| JavaScript | 0.000001 |
e799f21a35e71739fd2e809609b886b0630d8c6d | Refactor code | main.js | main.js | // Init the app after page loaded.
window.onload = initPage;
var debug = true;
var config = {
text: {
"message": "Guest The Letter From a (lowser) to z (higher)",
"guess": "Guesses:",
"hint": "Higher Or Lower:",
"guessed": "Letters Guessed:",
"export": "Export Canvas Image"
}
};
// The entry function.
function initPage() {
if (!canvasSupport()) { // If Canvas is not supported on the browser, do nothing but tell the user.
alert("Sorry, your browser does not support HTML5 Canvas");
return false;
}
canvasApp();
}
function canvasApp() {
var canvas = document.getElementById("theCanvas"),
ctx = canvas.getContext("2d"),
guessedCount = 0,
guessedChars = [],
allowedChars = range("a", "z"),
userInputChar,
correctChar = getRandomChar();
addEventListeners();
initGame();
function initGame() {
// Background color
ctx.fillStyle = "rgb(255, 255, 170)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// box border
ctx.strokeStyle = "#000000";
ctx.strokeRect(5, 5, canvas.width - 10, canvas.height - 10);
// Message
ctx.fillStyle = "red";
ctx.font = "14px Sans-Serif";
ctx.fillText(t("message"), 100, 50);
// Guesses
ctx.fillStyle = "green";
ctx.font = "16px Sans-Serif";
ctx.fillText(t("guess") + guessedCount, 210, 70);
// Higher Or Lower
ctx.fillStyle = "black";
ctx.font = "16px Sans-Serif";
ctx.fillText(t("hint"), 170, 170);
// Letters Guessed
ctx.fillStyle = "red";
ctx.font = "16px Sans-Serif";
ctx.fillText(t("guessed"), 10, 370);
}
function addEventListeners() {
}
function getRandomChar() {
var random = rand(0, allowedChars.length - 1);
return allowedChars[random];
}
function t(text) {
return typeof config["text"][text] !== "undefined" ? config["text"][text] : "";
}
}
// Does the browser support HTML5 Canvas ?
function canvasSupport() {
var canvas = document.createElement("canvas");
return !!(canvas.getContext && canvas.getContext("2d"));
}
// A simple debugging tool.
function log() {
if (!debug) return ;
var args = Array.prototype.slice.call(arguments);
if (window.console && window.console.log) {
console.log.apply(console, args);
} else {
alert(args.join("\n"));
}
}
//http://phpjs.org/functions/range/
function range(low, high, step) {
var matrix = [];
var inival, endval, plus;
var walker = step || 1;
var chars = false;
if (!isNaN(low) && !isNaN(high)) {
inival = low;
endval = high;
} else if (isNaN(low) && isNaN(high)) {
chars = true;
inival = low.charCodeAt(0);
endval = high.charCodeAt(0);
} else {
inival = (isNaN(low) ? 0 : low);
endval = (isNaN(high) ? 0 : high);
}
plus = ((inival > endval) ? false : true);
if (plus) {
while (inival <= endval) {
matrix.push(((chars) ? String.fromCharCode(inival) : inival));
inival += walker;
}
} else {
while (inival >= endval) {
matrix.push(((chars) ? String.fromCharCode(inival) : inival));
inival -= walker;
}
}
return matrix;
}
//http://phpjs.org/functions/rand/
function rand(min, max) {
var argc = arguments.length;
if (argc === 0) {
min = 0;
max = 2147483647;
} else if (argc === 1) {
throw new Error('Warning: rand() expects exactly 2 parameters, 1 given');
}
return Math.floor(Math.random() * (max - min + 1)) + min;
} | // Init the app after page loaded.
window.onload = initPage;
var debug = true;
var config = {
text: {
"message": "Guest The Letter From a (lowser) to z (higher)",
"guess": "Guesses:",
"hint": "Higher Or Lower:",
"guessed": "Letters Guessed:",
"export": "Export Canvas Image"
}
};
// The entry function.
function initPage() {
if (!canvasSupport()) { // If Canvas is not supported on the browser, do nothing but tell the user.
alert("Sorry, your browser does not support HTML5 Canvas");
return false;
}
drawScreen();
}
function drawScreen() {
var canvas = document.getElementById("theCanvas");
if (!canvas) {
throw new Error("The canvas element does not exists!");
}
var ctx = canvas.getContext("2d");
// Background color
ctx.fillStyle = "rgb(255, 255, 170)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// box border
ctx.strokeStyle = "#000000";
ctx.strokeRect(5, 5, canvas.width - 10, canvas.height - 10);
// Message
ctx.fillStyle = "red";
ctx.font = "14px Sans-Serif";
ctx.fillText(t("message"), 100, 50);
// Guesses
ctx.fillStyle = "green";
ctx.font = "16px Sans-Serif";
ctx.fillText(t("guess"), 210, 70);
// Higher Or Lower
ctx.fillStyle = "black";
ctx.font = "16px Sans-Serif";
ctx.fillText(t("hint"), 170, 170);
// Letters Guessed
ctx.fillStyle = "red";
ctx.font = "16px Sans-Serif";
ctx.fillText(t("guessed"), 10, 370);
}
function t(text) {
return typeof config["text"][text] !== "undefined" ? config["text"][text] : "";
}
// Does the browser support HTML5 Canvas ?
function canvasSupport() {
var canvas = document.createElement("canvas");
return !!(canvas.getContext && canvas.getContext("2d"));
}
// A simple debugging tool.
function log() {
if (!debug) return ;
var args = Array.prototype.slice.call(arguments);
if (window.console && window.console.log) {
console.log.apply(console, args);
} else {
alert(args.join("\n"));
}
}
| JavaScript | 0.000002 |
e9b0c6cab2f41fe26369a6d3105cfce7280cea47 | use tasklistData.newChild | client/scripts/task/modals/cam-tasklist-comment-form.js | client/scripts/task/modals/cam-tasklist-comment-form.js | define([
'angular',
'camunda-bpm-sdk',
'text!./cam-tasklist-comment-form.html'
], function(
angular,
camSDK,
template
) {
'use strict';
var commentCreateModalCtrl = [
'$scope',
'$translate',
'Notifications',
'camAPI',
'task',
function(
$scope,
$translate,
Notifications,
camAPI,
task
) {
var Task = camAPI.resource('task');
$scope.comment = { message: '' };
$scope.$on('$locationChangeSuccess', function() {
$scope.$dismiss();
});
function errorNotification(src, err) {
$translate(src).then(function(translated) {
Notifications.addError({
status: translated,
message: (err ? err.message : ''),
exclusive: true
});
});
}
function successNotification(src) {
$translate(src).then(function(translated) {
Notifications.addMessage({
duration: 3000,
status: translated
});
});
}
$scope.submit = function() {
Task.createComment(task.id, $scope.comment.message, function(err) {
if (err) {
return errorNotification('COMMENT_SAVE_ERROR', err);
}
successNotification('COMMENT_SAVE_SUCCESS');
$scope.$close();
});
};
}];
return [
'$modal',
'$scope',
function(
$modal,
$scope
) {
var commentData = $scope.tasklistData.newChild($scope);
function open(task) {
$modal.open({
// creates a child scope of a provided scope
scope: $scope,
//TODO: extract filter edit modal class to super style sheet
windowClass: 'filter-edit-modal',
size: 'lg',
template: template,
controller: commentCreateModalCtrl,
resolve: {
task: function() { return task; }
}
}).result.then(function() {
commentData.changed('task');
});
}
$scope.createComment = function(task) {
open(task);
};
}];
});
| define([
'angular',
'camunda-bpm-sdk',
'text!./cam-tasklist-comment-form.html'
], function(
angular,
camSDK,
template
) {
'use strict';
var commentCreateModalCtrl = [
'$scope',
'$translate',
'Notifications',
'camAPI',
'task',
function(
$scope,
$translate,
Notifications,
camAPI,
task
) {
var Task = camAPI.resource('task');
$scope.comment = { message: '' };
$scope.$on('$locationChangeSuccess', function() {
$scope.$dismiss();
});
function errorNotification(src, err) {
$translate(src).then(function(translated) {
Notifications.addError({
status: translated,
message: (err ? err.message : ''),
exclusive: true
});
});
}
function successNotification(src) {
$translate(src).then(function(translated) {
Notifications.addMessage({
duration: 3000,
status: translated
});
});
}
$scope.submit = function() {
Task.createComment(task.id, $scope.comment.message, function(err) {
if (err) {
return errorNotification('COMMENT_SAVE_ERROR', err);
}
successNotification('COMMENT_SAVE_SUCCESS');
$scope.$close();
});
};
}];
return [
'$modal',
'$scope',
function(
$modal,
$scope
) {
var commentData = $scope.taskData.newChild($scope);
function open(task) {
$modal.open({
// creates a child scope of a provided scope
scope: $scope,
//TODO: extract filter edit modal class to super style sheet
windowClass: 'filter-edit-modal',
size: 'lg',
template: template,
controller: commentCreateModalCtrl,
resolve: {
task: function() { return task; }
}
}).result.then(function() {
commentData.changed('task');
});
}
$scope.createComment = function(task) {
open(task);
};
}];
});
| JavaScript | 0.000002 |
08cb9c97c18d8491ce018fb02dd7b1ff05e160c7 | Fix wrong subtraction name in pathoscope mapping overview | client/src/js/analyses/components/Pathoscope/Mapping.js | client/src/js/analyses/components/Pathoscope/Mapping.js | import numbro from "numbro";
import React from "react";
import { connect } from "react-redux";
import { ProgressBar } from "react-bootstrap";
import { Link } from "react-router-dom";
import styled from "styled-components";
import { Box, Flex, FlexItem, Icon, Label } from "../../../base";
import { getColor } from "../../../base/utils";
import { toThousand } from "../../../utils/utils";
const StyledAnalysisMappingReference = styled.div`
align-items: center;
display: flex;
flex: 0 0 auto;
margin-left: 10px;
${Label} {
margin-left: 5px;
}
`;
export const AnalysisMappingReference = ({ index, reference }) => (
<StyledAnalysisMappingReference>
<Link to={`/refs/${reference.id}`}>{reference.name}</Link>
<Label>{index.version}</Label>
</StyledAnalysisMappingReference>
);
const StyledAnalysisMappingSubtraction = styled(Link)`
flex: 0 0 auto;
margin-left: 10px;
`;
export const AnalysisMappingSubtraction = ({ subtraction }) => (
<StyledAnalysisMappingSubtraction to={`/subtractions/${subtraction.id}`}>
{subtraction.id}
</StyledAnalysisMappingSubtraction>
);
const AnalysisMappingLegendIcon = styled(Icon)`
color: ${props => getColor(props.color)};
margin-right: 3px;
`;
const AnalysisMappingLegendLabel = styled.div`
align-items: center;
display: flex;
margin-bottom: 5px;
justify-content: space-between;
width: 500px;
`;
const AnalysisMappingLegendCount = styled.div`
padding-left: 50px;
text-align: right;
`;
const StyledAnalysisMapping = styled(Box)`
margin-bottom: 30px;
h3 {
align-items: flex-end;
display: flex;
justify-content: space-between;
}
`;
const AnalysisMappingLegendIconReference = styled.div`
display: flex;
align-items: center;
`;
export const AnalysisMapping = ({ index, reference, subtraction, toReference, total, toSubtraction = 0 }) => {
const referencePercent = toReference / total;
const subtractionPercent = toSubtraction / total;
const totalMapped = toReference + toSubtraction;
const sumPercent = totalMapped / total;
return (
<StyledAnalysisMapping>
<h3>
{numbro(sumPercent).format({ output: "percent", mantissa: 2 })} mapped
<small>
{toThousand(totalMapped)} / {toThousand(total)}
</small>
</h3>
<ProgressBar>
<ProgressBar now={referencePercent * 100} />
<ProgressBar bsStyle="warning" now={subtractionPercent * 100} />
</ProgressBar>
<Flex>
<FlexItem>
<AnalysisMappingLegendLabel>
<AnalysisMappingLegendIconReference>
<AnalysisMappingLegendIcon name="circle" color="blue" />
<AnalysisMappingReference reference={reference} index={index} />
</AnalysisMappingLegendIconReference>
<AnalysisMappingLegendCount>{toThousand(toReference)}</AnalysisMappingLegendCount>
</AnalysisMappingLegendLabel>
<AnalysisMappingLegendLabel>
<AnalysisMappingLegendIconReference>
<AnalysisMappingLegendIcon name="circle" color="yellow" />
<AnalysisMappingSubtraction subtraction={subtraction} />
</AnalysisMappingLegendIconReference>
<AnalysisMappingLegendCount>{toThousand(toSubtraction)}</AnalysisMappingLegendCount>
</AnalysisMappingLegendLabel>
</FlexItem>
</Flex>
</StyledAnalysisMapping>
);
};
const mapStateToProps = state => {
const { index, read_count, reference, subtracted_count, subtraction } = state.analyses.detail;
return {
index,
reference,
subtraction,
toReference: read_count,
toSubtraction: subtracted_count,
total: state.samples.detail.quality.count
};
};
export default connect(mapStateToProps)(AnalysisMapping);
| import numbro from "numbro";
import React from "react";
import { connect } from "react-redux";
import { ProgressBar } from "react-bootstrap";
import { Link } from "react-router-dom";
import styled from "styled-components";
import { Box, Flex, FlexItem, Icon, Label } from "../../../base";
import { getColor } from "../../../base/utils";
import { toThousand } from "../../../utils/utils";
const StyledAnalysisMappingReference = styled.div`
align-items: center;
display: flex;
flex: 0 0 auto;
margin-left: 10px;
${Label} {
margin-left: 5px;
}
`;
export const AnalysisMappingReference = ({ index, reference }) => (
<StyledAnalysisMappingReference>
<Link to={`/refs/${reference.id}`}>{reference.name}</Link>
<Label>{index.version}</Label>
</StyledAnalysisMappingReference>
);
const StyledAnalysisMappingSubtraction = styled(Link)`
flex: 0 0 auto;
margin-left: 10px;
`;
export const AnalysisMappingSubtraction = ({ subtraction }) => (
<StyledAnalysisMappingSubtraction to={`/subtractions/${subtraction.id}`}>
{subtraction.id}
</StyledAnalysisMappingSubtraction>
);
const AnalysisMappingLegendIcon = styled(Icon)`
color: ${props => getColor(props.color)};
margin-right: 3px;
`;
const AnalysisMappingLegendLabel = styled.div`
align-items: center;
display: flex;
margin-bottom: 5px;
justify-content: space-between;
width: 500px;
`;
const AnalysisMappingLegendCount = styled.div`
padding-left: 50px;
text-align: right;
`;
const StyledAnalysisMapping = styled(Box)`
margin-bottom: 30px;
h3 {
align-items: flex-end;
display: flex;
justify-content: space-between;
}
`;
const AnalysisMappingLegendIconReference = styled.div`
display: flex;
align-items: center;
`;
export const AnalysisMapping = ({ index, reference, subtraction, toReference, total, toSubtraction = 0 }) => {
const referencePercent = toReference / total;
const subtractionPercent = toSubtraction / total;
const totalMapped = toReference + toSubtraction;
const sumPercent = totalMapped / total;
return (
<StyledAnalysisMapping>
<h3>
{numbro(sumPercent).format({ output: "percent", mantissa: 2 })} mapped
<small>
{toThousand(totalMapped)} / {toThousand(total)}
</small>
</h3>
<ProgressBar>
<ProgressBar now={referencePercent * 100} />
<ProgressBar bsStyle="warning" now={subtractionPercent * 100} />
</ProgressBar>
<Flex>
<FlexItem>
<AnalysisMappingLegendLabel>
<AnalysisMappingLegendIconReference>
<AnalysisMappingLegendIcon name="circle" color="blue" />
<AnalysisMappingReference reference={reference} index={index} />
</AnalysisMappingLegendIconReference>
<AnalysisMappingLegendCount>{toThousand(toReference)}</AnalysisMappingLegendCount>
</AnalysisMappingLegendLabel>
<AnalysisMappingLegendLabel>
<AnalysisMappingLegendIconReference>
<AnalysisMappingLegendIcon name="circle" color="yellow" />
<AnalysisMappingSubtraction subtraction={subtraction} />
</AnalysisMappingLegendIconReference>
<AnalysisMappingLegendCount>{toThousand(toSubtraction)}</AnalysisMappingLegendCount>
</AnalysisMappingLegendLabel>
</FlexItem>
</Flex>
</StyledAnalysisMapping>
);
};
const mapStateToProps = state => {
const { index, read_count, reference, subtracted_count } = state.analyses.detail;
return {
index,
reference,
subtraction: state.samples.detail.subtraction,
toReference: read_count,
toSubtraction: subtracted_count,
total: state.samples.detail.quality.count
};
};
export default connect(mapStateToProps)(AnalysisMapping);
| JavaScript | 0 |
65152c3d81201e3f2c5673e09d4df5c0c27c5662 | Throw error instead of logging to console. (fixes #35) | main.js | main.js | const { app } = require('electron')
const chokidar = require('chokidar')
const fs = require('fs')
const { spawn } = require('child_process')
const appPath = app.getAppPath()
const ignoredPaths = /node_modules|[/\\]\./
// Main file poses a special case, as its changes are
// only effective when the process is restarted (hard reset)
// We assume that electron-reload is required by the main
// file of the electron application
const mainFile = module.parent.filename
/**
* Creates a callback for hard resets.
*
* @param {String} eXecutable path to electron executable
* @param {String} hardResetMethod method to restart electron
* @returns {Function} handler to pass to chokidar
*/
const createHardresetHandler = (eXecutable, hardResetMethod, argv) =>
() => {
// Detaching child is useful when in Windows to let child
// live after the parent is killed
const args = (argv || []).concat([appPath])
const child = spawn(eXecutable, args, {
detached: true,
stdio: 'inherit'
})
child.unref()
// Kamikaze!
// In cases where an app overrides the default closing or quiting actions
// firing an `app.quit()` may not actually quit the app. In these cases
// you can use `app.exit()` to gracefully close the app.
if (hardResetMethod === 'exit') {
app.exit()
} else {
app.quit()
}
}
module.exports = function elecronReload (glob, options = {}) {
const browserWindows = []
const watcher = chokidar.watch(glob, Object.assign({ ignored: [ignoredPaths, mainFile] }, options))
// Callback function to be executed:
// I) soft reset: reload browser windows
const softResetHandler = () => browserWindows.forEach(bw => bw.webContents.reloadIgnoringCache())
// II) hard reset: restart the whole electron process
const eXecutable = options.electron
const hardResetHandler = createHardresetHandler(eXecutable, options.hardResetMethod, options.argv)
// Add each created BrowserWindow to list of maintained items
app.on('browser-window-created', (e, bw) => {
browserWindows.push(bw)
// Remove closed windows from list of maintained items
bw.on('closed', function () {
const i = browserWindows.indexOf(bw) // Must use current index
browserWindows.splice(i, 1)
})
})
// Enable default soft reset
watcher.on('change', softResetHandler)
// Preparing hard reset if electron executable is given in options
// A hard reset is only done when the main file has changed
if (eXecutable) {
if (!fs.existsSync(eXecutable)) {
throw new Error('Provided electron executable cannot be found or is not exeecutable!')
}
const hardWatcher = chokidar.watch(mainFile, Object.assign({ ignored: [ignoredPaths] }, options))
if (options.forceHardReset === true) {
// Watch every file for hard reset and not only the main file
hardWatcher.add(glob)
// Stop our default soft reset
watcher.close()
}
hardWatcher.once('change', hardResetHandler)
}
}
| const { app } = require('electron')
const chokidar = require('chokidar')
const fs = require('fs')
const { spawn } = require('child_process')
const appPath = app.getAppPath()
const ignoredPaths = /node_modules|[/\\]\./
// Main file poses a special case, as its changes are
// only effective when the process is restarted (hard reset)
// We assume that electron-reload is required by the main
// file of the electron application
const mainFile = module.parent.filename
/**
* Creates a callback for hard resets.
*
* @param {String} eXecutable path to electron executable
* @param {String} hardResetMethod method to restart electron
* @returns {Function} handler to pass to chokidar
*/
const createHardresetHandler = (eXecutable, hardResetMethod, argv) =>
() => {
// Detaching child is useful when in Windows to let child
// live after the parent is killed
const args = (argv || []).concat([appPath])
const child = spawn(eXecutable, args, {
detached: true,
stdio: 'inherit'
})
child.unref()
// Kamikaze!
// In cases where an app overrides the default closing or quiting actions
// firing an `app.quit()` may not actually quit the app. In these cases
// you can use `app.exit()` to gracefully close the app.
if (hardResetMethod === 'exit') {
app.exit()
} else {
app.quit()
}
}
module.exports = function elecronReload (glob, options = {}) {
const browserWindows = []
const watcher = chokidar.watch(glob, Object.assign({ ignored: [ignoredPaths, mainFile] }, options))
// Callback function to be executed:
// I) soft reset: reload browser windows
const softResetHandler = () => browserWindows.forEach(bw => bw.webContents.reloadIgnoringCache())
// II) hard reset: restart the whole electron process
const eXecutable = options.electron
const hardResetHandler = createHardresetHandler(eXecutable, options.hardResetMethod, options.argv)
// Add each created BrowserWindow to list of maintained items
app.on('browser-window-created', (e, bw) => {
browserWindows.push(bw)
// Remove closed windows from list of maintained items
bw.on('closed', function () {
const i = browserWindows.indexOf(bw) // Must use current index
browserWindows.splice(i, 1)
})
})
// Enable default soft reset
watcher.on('change', softResetHandler)
// Preparing hard reset if electron executable is given in options
// A hard reset is only done when the main file has changed
if (eXecutable && fs.existsSync(eXecutable)) {
const hardWatcher = chokidar.watch(mainFile, Object.assign({ ignored: [ignoredPaths] }, options))
if (options.forceHardReset === true) {
// Watch every file for hard reset and not only the main file
hardWatcher.add(glob)
// Stop our default soft reset
watcher.close()
}
hardWatcher.once('change', hardResetHandler)
} else {
console.log('Electron could not be found. No hard resets for you!')
}
}
| JavaScript | 0 |
8fbfe5f28641a15674904238cc10be81e96607b4 | add more test cases | src/websocket_url.spec.js | src/websocket_url.spec.js | /// <reference path="websocket_url.js">
describe("WebsocketUrl", function() {
'use strict';
it("should understand absolute http urls", function() {
expect(websocketUrl("http://example.com/sub/")).toEqual("ws://example.com/sub/");
});
it("should understand absolute https urls", function() {
expect(websocketUrl("https://example.com/sub/")).toEqual("wss://example.com/sub/");
});
it("should understand absolute urls", function() {
expect(websocketUrl("/funny")).toMatch(/^wss?:\/\/[^\/]*\/funny$/);
});
it("should understand relative urls", function() {
// NOTE: relative url derived from test suite named: "test/SpecRunner.html"
expect(websocketUrl("funny")).toMatch(/^wss?:\/\/[^\/]*\.*\/test\/funny$/);
});
it("should understand root urls", function() {
expect(websocketUrl("/")).toMatch(/^wss?:\/\/[^\/]*\.*\/$/);
});
it("should understand blank urls", function() {
expect(websocketUrl("")).toMatch(/^wss?:\/\/[^\/]*\.*\/test\/SpecRunner.html$/);
});
});
| /// <reference path="websocket_url.js">
describe("WebsocketUrl", function() {
'use strict';
it("should understand absolute http urls", function() {
expect(websocketUrl("http://example.com/sub/")).toEqual("ws://example.com/sub/");
});
it("should understand absolute https urls", function() {
expect(websocketUrl("https://example.com/sub/")).toEqual("wss://example.com/sub/");
});
it("should understand absolute urls", function() {
expect(websocketUrl("/funny")).toMatch(/^wss?:\/\/[^\/]*\/funny/);
});
it("should understand relative urls", function() {
// NOTE: relative url derived from test suite named: "test/SpecRunner.html"
expect(websocketUrl("funny")).toMatch(/^wss?:\/\/[^\/]*\.*\/test\/funny/);
});
});
| JavaScript | 0 |
fa7a3f22444b784052b71d6649bb435421803d0d | Add description and example | src/widgets/IconWidget.js | src/widgets/IconWidget.js | /**
* IconWidget is a generic widget for {@link OO.ui.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget,
* which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1]
* for a list of icons included in the library.
*
* @example
* // An icon widget with a label
* var myIcon = new OO.ui.IconWidget({
* icon: 'help',
* iconTitle: 'Help'
* });
* // Create a label.
* var iconLabel = new OO.ui.LabelWidget({
* label: 'Help'
* });
* $('body').append(myIcon.$element, iconLabel.$element);
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons
*
* @class
* @extends OO.ui.Widget
* @mixins OO.ui.IconElement
* @mixins OO.ui.TitledElement
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.IconWidget = function OoUiIconWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.IconWidget.super.call( this, config );
// Mixin constructors
OO.ui.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
// Initialization
this.$element.addClass( 'oo-ui-iconWidget' );
};
/* Setup */
OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
OO.mixinClass( OO.ui.IconWidget, OO.ui.IconElement );
OO.mixinClass( OO.ui.IconWidget, OO.ui.TitledElement );
/* Static Properties */
OO.ui.IconWidget.static.tagName = 'span';
| /**
* Icon widget.
*
* See OO.ui.IconElement for more information.
*
* @class
* @extends OO.ui.Widget
* @mixins OO.ui.IconElement
* @mixins OO.ui.TitledElement
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.IconWidget = function OoUiIconWidget( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.IconWidget.super.call( this, config );
// Mixin constructors
OO.ui.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) );
OO.ui.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) );
// Initialization
this.$element.addClass( 'oo-ui-iconWidget' );
};
/* Setup */
OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget );
OO.mixinClass( OO.ui.IconWidget, OO.ui.IconElement );
OO.mixinClass( OO.ui.IconWidget, OO.ui.TitledElement );
/* Static Properties */
OO.ui.IconWidget.static.tagName = 'span';
| JavaScript | 0.000001 |
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',
inbox: 'Inbox',
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: 'إصنع حساب',
inbox: 'صندوق الوارد',
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);
| 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 |
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('cat \\#temp_changelog | sed -e :a -e \'/^\\n*$/{$d;N;};/\\n$/ba\' > CHANGELOG.md', { stdio: 'inherit' });
execSync('rm \\#temp_changelog', { stdio: 'inherit' });
execSync('git add CHANGELOG.md');
| 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 |
c2a965a540aeff22172ea94d5a0826e9cb11812c | Update version string to 2.5.1-pre.1 | version.js | version.js | if (enyo && enyo.version) {
enyo.version.onyx = "2.5.1-pre.1";
}
| if (enyo && enyo.version) {
enyo.version.onyx = "2.5.0";
}
| JavaScript | 0.000001 |
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')
},
post (history) {
return Api().post('histories', history)
}
}
| import Api from '@/services/Api'
export default {
index (params) {
return Api().get('histories', {
params: params
})
},
post (history) {
return Api().post('histories', history)
}
}
| JavaScript | 0 |
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
}
});
}
});
};
| 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 |
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 calculate_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: calculate_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);
}
});
}
}
| 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 |
dc6b8d7aa7a040ebb8cc2ead6ccb93fbd96fb5e0 | Update wallaby conf | wallaby.js | wallaby.js | var wallabify = require('wallabify');
var wallabyPostprocessor = wallabify({});
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
};
};
| 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 |
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: "1RMcibAPjuPim7N_MUFdVeYqiN_ngroNrQzsHy6VDwB4",
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();
} | 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 |
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, cb);
}
end() {
this._connection.end();
}
}
module.exports = Server;
| '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 |
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('./package.json', '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 (JSON.parse(body).version > 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();
| "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 |
aebfe5eae145d4ba472aed6625016efe89db02df | remove dead code | lib/client.js | lib/client.js |
/**
* Module dependencies.
*/
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) {
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
});
}
|
/**
* 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 |
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');
function parseResponse(reqResponse, done) {
const doneOnce = _.once(done);
const parser = new Parser();
reqResponse
.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));
}
/*
** 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) {
parseResponse(this.getCapabilities(), function (err, result) {
if (err) return done(err);
if (result.type !== 'Capabilities') return done(new Error('Not acceptable response type: ' + result.type));
done(null, result.body);
});
};
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;
| /*
** 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 |
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;
/**
* Start server
*/
const startServer = function() {
return connect.server({
root: '../public',
livereload: true,
port: PORT
});
};
/**
* Stop server
*/
const stopServer = function() {
connect.serverClose();
};
/**
* Run pwmetrics
*/
const runPwmetrics = function() {
const url = `http://localhost:${PORT}/index.html`;
return new PWMetrics(url, {
flags: {
expectations: true
},
expectations: {
ttfmp: {
warn: '>=1000',
error: '>=2000'
},
tti: {
warn: '>=2000',
error: '>=3000'
},
ttfcp: {
warn: '>=1500',
error: '>=2000'
}
}
}).start();
};
/**
* Handle ok result
* @param {Object} results - Pwmetrics results obtained through Lighthouse
*/
const handleOk = function(results) {
stopServer();
return results;
};
/**
* Handle error
*/
const handleError = function(e) {
stopServer();
console.error(e); // eslint-disable-line no-console
throw e; // Throw to exit process with status 1.
};
gulp.task('pwmetrics', function() {
startServer();
return runPwmetrics()
.then(handleOk)
.catch(handleError);
});
gulp.task('default', ['pwmetrics']);
| // 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 |
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/v7'),
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;
};
| '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 |
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 configure (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();
| 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 |
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;
}
if (opts && opts.broadcaster) {
if (typeof opts.broadcaster !== 'string') {
throw new Error('Expected broadcaster to be a string.');
}
this._layout.broadcaster = opts.broadcaster;
}
if (opts && opts.rankAway) {
if (typeof opts.rankAway !== 'string') {
throw new Error('Expected rankAway to be a string.');
}
this._layout.rankAway = opts.rankAway;
}
if (opts && opts.rankHome) {
if (typeof opts.rankHome !== 'string') {
throw new Error('Expected rankHome to be a string.');
}
this._layout.rankHome = opts.rankHome;
}
if (opts && opts.nameAway) {
if (typeof opts.nameAway !== 'string') {
throw new Error('Expected nameAway to be a string.');
}
this._layout.nameAway = opts.nameAway;
}
if (opts && opts.nameHome) {
if (typeof opts.nameHome !== 'string') {
throw new Error('Expected nameHome to be a string.');
}
this._layout.nameHome = opts.nameHome;
}
if (opts && opts.recordAway) {
if (typeof opts.recordAway !== 'string') {
throw new Error('Expected recordAway to be a string.');
}
this._layout.recordAway = opts.recordAway;
}
if (opts && opts.recordHome) {
if (typeof opts.recordHome !== 'string') {
throw new Error('Expected recordHome to be a string.');
}
this._layout.recordHome = opts.recordHome;
}
if (opts && opts.scoreAway) {
if (typeof opts.scoreAway !== 'string') {
throw new Error('Expected scoreAway to be a string.');
}
this._layout.scoreAway = opts.scoreAway;
}
if (opts && opts.scoreHome) {
if (typeof opts.scoreHome !== 'string') {
throw new Error('Expected scoreHome to be a string.');
}
this._layout.scoreHome = opts.scoreHome;
}
if (opts && opts.sportsInGame) {
if (typeof opts.sportsInGame !== 'boolean') {
throw new Error('Expected sportsInGame to be a boolean.');
}
this._layout.sportsInGame = opts.sportsInGame;
}
};
/**
* 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
}
| '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 |
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);
};
}
| 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 |
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))));
};
});
exports.wrap = function(getPrefix, func) {
if (typeof getPrefix != 'function') {
var msg = getPrefix;
getPrefix = function() {
return msg;
};
}
return function() {
var args = arguments,
that = this,
prefix = getPrefix.apply(that, args);
wrapper = {};
levels.forEach(function(level) {
wrapper[level] = function(msg) {
msg = (prefix ? prefix + ': ' : '') + msg;
exports[level].apply(
this,
[msg].concat([].slice.call(arguments, 1)));
};
});
return func.apply(that, [wrapper].concat([].slice.call(args)));
};
};
| 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 |
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 in the parent module context. Our overwritten require
// function will be used for its module dependencies
var file = require.call(module.parent, path);
// Restore the original require function
mod.prototype.require = require;
// Return the module
return file;
};
| 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 |
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');
// BLOG
this.route('blog', {
path: '/blog',
template: 'blog'
});
this.route('list_posts', {
path: '/admin/posts',
template: 'list_posts'
});
this.route('add_post', {
path: '/admin/posts/add',
template: 'add_post'
});
this.route('edit_post', {
path: '/admin/posts/:id/edit',
template: 'edit_post'
});
// PROJECTS
this.route('list_projects', {
path: '/admin/projects',
template: 'list_projects'
});
this.route('add_project', {
path: '/admin/projects/add',
template: 'add_project'
});
this.route('edit_project', {
path: '/admin/projects/:id/edit',
template: 'edit_project'
});
});
| 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 |
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/:userId', {
name: 'userProfile',
data: function() {
return Meteor.users.findOne({_id: this.params.userId});
}
});
| 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 |
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;
// `rateRec` and `satoshiBalanceRec` are both objects, so there's no danger
// of misinterpreting rate or balance === 0 as 'Server initializing'.
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;
};
| '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 |
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) {
continue;
}
const payload = JSON.stringify({ user: req.user, message: message });
if (user.subscription.keys) {
webpush.sendNotification(user.subscription, payload);
} else {
const url = 'https://android.googleapis.com/gcm/send/';
const subscriptionId = user.subscription.endpoint.replace(url, '');
const options = {
url: url,
headers: {
'Authorization': `key=${config.get('GCM_API_KEY')}`
},
body: {
registration_ids: subscriptionId,
notification: payload
},
json: true
};
request.post(options);
}
}
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;
| 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 |
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', (job, done) => {
return this.processEvents(job, done);
});
this._agenda.start();
logger.info('waiting on schedule');
});
}
stop() {
return this._agenda.stopAsync().then(() => {
delete this._agenda;
return _mongoose.disconnectAsync();
});
}
}
export default Runner;
| '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 |
998a5b756c6b3c98a0ad3644d388eafc1ec31c82 | refactor property definitons | lib/sample.js | lib/sample.js | var bisect = require('./bisect');
var EE = require('events').EventEmitter;
var inherits = require('inherits');
function quantile() {
var self = this;
function getQuantile(q) {
if (!self.length) return NaN;
var p = (self.length - 1) * q;
var i = Math.floor(p);
var j = Math.ceil(p);
return (self[i] + self[j])/2;
}
switch (arguments.length) {
case 0:
return;
case 1:
return getQuantile(arguments[0]);
default:
return Array.prototype.map.call(arguments, getQuantile);
}
}
function Sample() {
this.order = [];
this.values = [];
this.quantile = quantile.bind(this.values);
}
Object.defineProperty(Sample.prototype, 'median', {
enumerable: true,
get: function getMedian() {
return this.quantile(0.5);
}
});
Object.defineProperty(Sample.prototype, 'iqr', {
enumerable: true,
get: function getIQR() {
if (this.values.length < 3) return NaN;
var qs = this.quantile(0.25, 0.75);
return qs[1] - qs[0];
}
});
Object.defineProperty(Sample.prototype, 'lo', {
enumerable: true,
get: function getLo() {
if (this.values.length < 3) return NaN;
var qs = this.quantile(0.25, 0.50, 0.75);
var iqr = qs[2] - qs[0];
var tol = 3 * iqr / 2;
return qs[0] - tol;
}
});
Object.defineProperty(Sample.prototype, 'hi', {
enumerable: true,
get: function getHi() {
if (this.values.length < 3) return NaN;
var qs = this.quantile(0.25, 0.50, 0.75);
var iqr = qs[2] - qs[0];
var tol = 3 * iqr / 2;
return qs[2] + tol;
}
});
Object.defineProperty(Sample.prototype, 'range', {
enumerable: true,
get: function getRange() {
if (this.values.length < 3) return [NaN, NaN, NaN];
var qs = this.quantile(0.25, 0.50, 0.75);
var iqr = qs[2] - qs[0];
var tol = 3 * iqr / 2;
return [qs[0] - tol, qs[1], qs[2] + tol];
}
});
inherits(Sample, EE);
Sample.prototype.add = function addValue(value) {
var i = bisect.right(this.values, value);
this.values.splice(i, 0, value);
for (var o=this.order, n=o.length, j=0; j<n; j++)
if (o[j] >= i) o[j]++;
this.order.push(i);
this.emit('change');
};
Sample.prototype.inOrder = function inOrder() {
var ar = new Array(this.order.length);
for (var o=this.order, n=o.length, i=0; i<n; i++)
ar[i] = this.values[o[i]];
return ar;
};
module.exports = Sample;
| var bisect = require('./bisect');
var EE = require('events').EventEmitter;
var inherits = require('inherits');
function quantile() {
var self = this;
function getQuantile(q) {
if (!self.length) return NaN;
var p = (self.length - 1) * q;
var i = Math.floor(p);
var j = Math.ceil(p);
return (self[i] + self[j])/2;
}
switch (arguments.length) {
case 0:
return;
case 1:
return getQuantile(arguments[0]);
default:
return Array.prototype.map.call(arguments, getQuantile);
}
}
function Sample() {
this.order = [];
this.values = [];
this.quantile = quantile.bind(this.values);
Object.defineProperty(this, 'median', {
enumerable: true,
get: this.getMedian
});
Object.defineProperty(this, 'iqr', {
enumerable: true,
get: this.getIQR
});
Object.defineProperty(this, 'lo', {
enumerable: true,
get: this.getLo
});
Object.defineProperty(this, 'hi', {
enumerable: true,
get: this.getHi
});
Object.defineProperty(this, 'range', {
enumerable: true,
get: this.getRange
});
}
inherits(Sample, EE);
Sample.prototype.getMedian = function getMedian() {
return this.quantile(0.5);
};
Sample.prototype.getIQR = function getIQR() {
if (this.values.length < 3) return NaN;
var qs = this.quantile(0.25, 0.75);
return qs[1] - qs[0];
};
Sample.prototype.getLo = function getLo() {
if (this.values.length < 3) return NaN;
var qs = this.quantile(0.25, 0.50, 0.75);
var iqr = qs[2] - qs[0];
var tol = 3 * iqr / 2;
return qs[0] - tol;
};
Sample.prototype.getHi = function getHi() {
if (this.values.length < 3) return NaN;
var qs = this.quantile(0.25, 0.50, 0.75);
var iqr = qs[2] - qs[0];
var tol = 3 * iqr / 2;
return qs[2] + tol;
};
Sample.prototype.getRange = function getRange() {
if (this.values.length < 3) return [NaN, NaN, NaN];
var qs = this.quantile(0.25, 0.50, 0.75);
var iqr = qs[2] - qs[0];
var tol = 3 * iqr / 2;
return [qs[0] - tol, qs[1], qs[2] + tol];
};
Sample.prototype.add = function addValue(value) {
var i = bisect.right(this.values, value);
this.values.splice(i, 0, value);
for (var o=this.order, n=o.length, j=0; j<n; j++)
if (o[j] >= i) o[j]++;
this.order.push(i);
this.emit('change');
};
Sample.prototype.inOrder = function inOrder() {
var ar = new Array(this.order.length);
for (var o=this.order, n=o.length, i=0; i<n; i++)
ar[i] = this.values[o[i]];
return ar;
};
module.exports = Sample;
| JavaScript | 0.000001 |
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', 'dsc'].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
| // 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 |
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 = process.env.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));
};
})(); | 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 |
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: cnapi.log}));
var model = options.model;
endpoints.attachTo(cnapi, model);
return cnapi;
}
exports.createServer = createServer;
| 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 |
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: 'Signy'
};
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
}
| 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 |
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 `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();
}
}
} | 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 |
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;
}
var dhOptions = Object.assign({}, handler[1]);
dhOptions.arg = options;
dhOptions.session = options.session;
handler[0].call(handler[2], dhOptions, data, runSeq);
} else {
runSeq(null, data);
}
};
if (!sequence.seq) {
sequence.once('sequence', runSeq.bind(this, null, chunk));
return;
}
runSeq(null, chunk);
}
});
return sequence;
};
| 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 |
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 if (typeof obj === 'object') {
return Object.keys(obj).map(k => k + ': ' + util.inspect(obj[k])).join(', ');
} 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;
| '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 |
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.forwardSent || 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;
| // 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 |
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, initValue) {
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()
}
if (initValue !== null) {
textfield.val(initValue)
}
return textfield.asEventStream("keyup input").
merge(textfield.asEventStream("cut paste").delay(1)).
merge(autofillPoller()).
map(getValue).toProperty(getValue()).skipDuplicates()
}
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)) })
}
Bacon.UI.radioGroupValue = function(options) {
var initialValue = options.filter(':checked').val()
return options.asEventStream("change").map('.target.value').toProperty(initialValue)
}
})();
| (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 |
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">© 2017 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;
| /**
* 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 |
8a13ae3d2fc6e56488c865f57e12a6c162affc32 | clean up index.js | demo/index.js | demo/index.js | import React from 'react';
import ReactDOM from 'react-dom';
import '../OnsenUI/build/js/onsenui.js';
import {
Page,
Navigator,
Toolbar,
List,
ListItem
} 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'));
| 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 |
76a779b0016b9ab3016d7fe4f65169351c8346bf | Add skill. Add command line args to give dump dir and match_id to end at. | dev/export.js | dev/export.js | var db = require("../db"),
fs = require("fs"),
zlib = require("zlib"),
moment = require("moment"),
path = require("path"),
JSONStream = require("JSONStream");
console.log(process.argv.length);
if (process.argv.length != 4) {
console.log("Not enough arguments");
process.exit();
}
var filePath = process.argv[2];
var startingMatchId = process.argv[3];
try {
var stat = fs.statSync(filePath);
if (!stat.isDirectory) {
console.log("Not a valid directory");
process.exit(1);
}
} catch (e) {
console.log(e);
process.exit(1);
}
var fileName = path.join(filePath, "yasp-dump-" + moment().format("YYYY-MM-DD") + ".json.gz");
try {
var stat = fs.statSync(fileName);
if (stat.isFile()) {
console.log("Export file already exists");
process.exit(1);
}
} catch (e) {
if (e.code !== 'ENOENT') {
process.exit(1);
}
}
var count = 0,
max = 500000,
jsstream = JSONStream.stringify(),
gzip = zlib.createGzip(),
write = fs.createWriteStream(fileName);
jsstream.pipe(gzip).pipe(write);
console.log("Exporting parsed matches since match_id " + startingMatchId);
var stream = db.select("*")
.from("matches")
.leftJoin('match_skill', 'matches.match_id', 'match_skill.match_id')
.where("version", ">", 0)
.where("matches.match_id", ">", startingMatchId)
.orderBy("matches.match_id", "desc")
.stream();
stream.on("data", function(match){
stream.pause();
db.select()
.from('player_matches')
.where({
"player_matches.match_id": Number(match.match_id)
})
.orderBy("player_slot", "asc")
.asCallback(function(err, players) {
if (err) {
console.log(err);
stream.resume();
return;
}
count++;
delete match.pgroup;
delete match.url;
players.forEach(function(p) {
delete p.match_id;
});
match.players = players;
jsstream.write(match);
stream.resume();
if (count % 10000 === 0) {
console.log("Exported %s, matchID %s", count, match.match_id);
}
if (count > max) {
stream.end();
}
});
});
stream.on("end", function() {
jsstream.end();
});
jsstream.on("end", function() {
gzip.end();
});
gzip.on("end", function() {
write.end();
console.log("Done. Exported %s", count);
process.exit();
}); | var db = require("../db"),
fs = require("fs"),
zlib = require("zlib"),
moment = require("moment"),
JSONStream = require("JSONStream");
var fileName = "./export/yasp-dump-" + moment().format("YYYY-MM-DD") + ".json.gz";
try {
var stat = fs.statSync(fileName);
if (stat.isFile()) {
console.log("Export file already exists");
process.exit(1);
}
} catch (e) {
console.log(e);
}
var count = 0,
max = 500000,
jsstream = JSONStream.stringify(),
gzip = zlib.createGzip(),
write = fs.createWriteStream(fileName);
jsstream.pipe(gzip).pipe(write);
var stream = db.select("*").from("matches").where("version", ">", 0).orderBy("match_id", "desc").stream();
stream.on("data", function(match){
stream.pause()
db.select().from('player_matches').where({
"player_matches.match_id": Number(match.match_id)
}).orderBy("player_slot", "asc").asCallback(function(err, players) {
if (err) {
console.log(err);
stream.resume();
return;
}
count++;
delete match.pgroup;
delete match.url;
players.forEach(function(p) {
delete p.match_id;
})
match.players = players;
jsstream.write(match);
stream.resume();
if (count % 10000 === 0) {
console.log("Exported %s, matchID %s", count, match.match_id);
}
if (count > max) {
stream.end();
}
});
})
stream.on("end", function() {
jsstream.end();
})
jsstream.on("end", function() {
gzip.end();
});
gzip.on("end", function() {
write.end();
console.log("Done. Exported %s", count);
}) | JavaScript | 0 |
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(
<React.StrictMode>
<IntlProvider locale={language} messages={messages}>
<Provider store={store}>
{component}
</Provider>
</IntlProvider>
</React.StrictMode>, 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);
});
| // 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 |
4ae59071996f260ff2faa181a09a22f4335110fe | update Table schema | src/schemas/Table/index.js | src/schemas/Table/index.js | import React, { Children, cloneElement } from 'react';
import PropTypes from 'utils/PropTypes';
import { observable } from 'mobx';
import { returnsArgument } from 'empty-functions';
import parseAPIPath from 'utils/parseAPIPath';
import { isFunction, isObject, isBoolean } from 'lodash';
export default function TableSchema() {
return <noscript />;
}
TableSchema.propTypes = {
name: PropTypes.string.isRequired,
api: PropTypes.stringOrObject,
mapOnFetchResponse: PropTypes.func,
mapOnFetchOneResponse: PropTypes.func,
mapOnSave: PropTypes.func,
uniqueKey: PropTypes.string,
maxSelections: PropTypes.number,
extend: PropTypes.object,
};
TableSchema.defaultProps = {
mapOnFetchResponse: returnsArgument,
mapOnFetchOneResponse: returnsArgument,
mapOnSave: returnsArgument,
maxSelections: -1,
extend: {},
};
TableSchema.setConfig = ({ name, api, children, ...other }, tables) => {
children = Children.toArray(children);
const firstChild = children[0];
if (firstChild && children.length === 1 && firstChild.type === 'noscript') {
children = Children.toArray(firstChild.props.children);
}
let uniqueKey;
const formRenderers = [];
const queryRenderers = [];
const tableRenderers = [];
children.forEach((child, index) => {
const { inForm, inQuery, inTable, unique, ...otherProps } = child.props;
const props = observable(otherProps);
const push = (nodes, inIssuer, renderKey, defaultRender) => {
if (!inIssuer) {
return;
}
const key = child.key || index;
const Component = child.type;
const component = Component;
const render = (function () {
if (isFunction(inIssuer)) {
return inIssuer;
}
if (isObject(inIssuer)) {
return function render(props) {
return <Component {...props} {...inIssuer} />;
};
}
if (!isBoolean(inIssuer)) {
return function render() {
return <span>{inIssuer}</span>;
};
}
if (isFunction(Component[renderKey])) {
return Component[renderKey];
}
if (defaultRender) {
return defaultRender;
}
return function render(props) {
return <Component {...props} />;
};
})();
const options = {
key,
component,
Component,
};
const renderNode = () => {
const node = render(props, options);
if (!node) {
return null;
}
return node.key ? node : cloneElement(node, { key });
};
nodes.push({ render, renderNode, props, options });
};
if (!uniqueKey && unique) {
uniqueKey = props.name;
}
push(formRenderers, inForm, 'renderForm');
push(queryRenderers, inQuery, 'renderQuery');
push(tableRenderers, inTable, 'renderTable', (props, { text }) => text);
});
const table = {
uniqueKey,
...other,
api: parseAPIPath(api || name),
formRenderers,
queryRenderers,
tableRenderers,
};
tables[name] = table;
if (tableRenderers.length && !table.uniqueKey) {
console.error(`Table "${name}" is missing uniqueKey!`);
}
};
TableSchema.schemaName = 'tables';
TableSchema.DataType = Object;
|
import React, { Children, cloneElement } from 'react';
import PropTypes from 'utils/PropTypes';
import { returnsArgument } from 'empty-functions';
import parseAPIPath from 'utils/parseAPIPath';
import { isFunction, isObject, isBoolean } from 'lodash';
export default function TableSchema() {
return (<noscript />);
}
TableSchema.propTypes = {
name: PropTypes.string.isRequired,
api: PropTypes.stringOrObject,
mapOnFetchResponse: PropTypes.func,
mapOnFetchOneResponse: PropTypes.func,
mapOnSave: PropTypes.func,
uniqueKey: PropTypes.string,
maxSelections: PropTypes.number,
extend: PropTypes.object,
};
TableSchema.defaultProps = {
mapOnFetchResponse: returnsArgument,
mapOnFetchOneResponse: returnsArgument,
mapOnSave: returnsArgument,
maxSelections: -1,
extend: {},
};
TableSchema.setConfig = ({ name, api, children, ...other }, tables) => {
children = Children.toArray(children);
const firstChild = children[0];
if (firstChild && children.length === 1 && firstChild.type === 'noscript') {
children = Children.toArray(firstChild.props.children);
}
const formRenderers = [];
const queryRenderers = [];
const tableRenderers = [];
const createPusher = (child, props, index) => {
return (nodes, inIssuer, renderKey, defaultRender) => {
if (inIssuer) {
const key = child.key || index;
const Component = child.type;
const component = Component;
const render = (function () {
if (isFunction(inIssuer)) { return inIssuer; }
if (isObject(inIssuer)) {
return function render(props) {
return (<Component {...props} {...inIssuer} />);
};
}
if (!isBoolean(inIssuer)) {
return function render() {
return (<span>{inIssuer}</span>);
};
}
if (isFunction(Component[renderKey])) { return Component[renderKey]; }
if (defaultRender) { return defaultRender; }
return function render(props) { return (<Component {...props} />); };
}());
const options = {
key,
component,
Component,
};
const renderNode = () => {
const node = render(props, options);
if (!node) { return null; }
return node.key ? node : cloneElement(node, { key });
};
nodes.push({ render, renderNode, props, options });
}
};
};
let uniqueKey;
children.forEach((child, index) => {
const { inForm, inQuery, inTable, unique, ...props } = child.props;
const push = createPusher(child, props, index);
if (!uniqueKey && unique) { uniqueKey = props.name; }
push(formRenderers, inForm, 'renderForm');
push(queryRenderers, inQuery, 'renderQuery');
push(tableRenderers, inTable, 'renderTable', (props, { text }) => text);
});
const table = {
uniqueKey,
...other,
api: parseAPIPath(api || name),
formRenderers,
queryRenderers,
tableRenderers,
};
tables[name] = table;
if (tableRenderers.length && !table.uniqueKey) {
console.error(`Table "${name}" is missing uniqueKey!`);
}
};
TableSchema.schemaName = 'tables';
TableSchema.DataType = Object;
| JavaScript | 0 |
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, filter } 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.
*/
export const loadConfigEpic = (action$: ActionsObservable<*>) =>
action$.pipe(
ofType(actionTypes.LOAD_CONFIG),
switchMap(() =>
readFileObservable(CONFIG_FILE_PATH).pipe(
map(data => actions.configLoaded(JSON.parse(data)))
)
)
);
/**
* An epic that saves the configuration if it has been changed.
*/
export const saveConfigOnChangeEpic = (action$: ActionsObservable<*>) =>
action$.pipe(
ofType(actionTypes.SET_CONFIG_AT_KEY),
mapTo({ type: actionTypes.SAVE_CONFIG })
);
/**
* An epic that saves the configuration.
*/
export const saveConfigEpic = (action$: ActionsObservable<*>, store: any) =>
action$.pipe(
ofType(actionTypes.SAVE_CONFIG),
mergeMap(() =>
writeFileObservable(
CONFIG_FILE_PATH,
JSON.stringify(selectors.userPreferences(store.getState()))
).pipe(map(actions.doneSavingConfig))
)
);
| // @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 |
c5046367ab151ddb012041c584f26bcf034edd19 | Move index creation to startup | apps/admin/imports/startup/server/mongo-config.js | apps/admin/imports/startup/server/mongo-config.js | import { Meteor } from 'meteor/meteor';
import { ProductsCollection } from 'meteor/moreplease:common';
const productIndexes = [
{ productId: 1 },
{ variationId: 1 },
{ storeId: 1 },
];
Meteor.startup(() => {
productIndexes.forEach((index) => {
ProductsCollection.rawCollection().createIndex(index);
});
});
| import { ProductsCollection } from 'meteor/moreplease:common';
const productIndexes = [
{ productId: 1 },
{ variationId: 1 },
{ storeId: 1 },
];
productIndexes.forEach((index) => {
ProductsCollection.rawCollection().createIndex(index);
});
| JavaScript | 0.000001 |
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: [
'test/**/*spec.js'
],
compilers: {
'**/*.js': wallaby.compilers.babel()
},
env: {
type: 'node'
},
delays: {
run: 3000
}
};
}; | 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 |
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: {
files: [{
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.');
}
});
};
| '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 |
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 getRepoInfo(fullname){
let t = await new Promise(function(resolve, reject) => {
github_repoSchema.findOne({full_name: fullname}, (err, repo_single) => {
if (err) reject(err);
resolve(repo_single);
});
});
return t;
}
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, getRepoInfo}
async function test() {
connect();
let t = await getPublicRepoByUser("RickChem");
console.log(t);
}
//test();
| /**
* 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 |
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)
// immediate call (bounded to desired context):
if (delay === 0) return fn.apply(context, args)
return new Promise(resolve => {
timeout = setTimeout(() => {
resolve(fn.apply(context, args))
}, delay)
})
}
debounced.cancel = function () {
clearTimeout(timeout)
timeout = null
}
return debounced
}
| /** 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 |
16701c581bb986ccfae2870d4553090448703b56 | Remove unnecessary defer call | temple.js | temple.js | var Temple = {};
Temple.instanceCount = new ReactiveDict();
Template.onRendered(function () {
var self = this;
// 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");
} | 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 |
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.aadhaarNo === '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,
};
});
| 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 |
27f9a21b88f37fb4f865affa3011cda428c44def | Repair annotation tests. | test/Annotations.test.js | test/Annotations.test.js | import { test } from 'substance-test'
import { setCursor, setSelection, openManuscriptEditor, loadBodyFixture } from './shared/integrationTestHelpers'
import setupTestApp from './shared/setupTestApp'
const annotations = [
{
name: 'Strong',
type: 'bold',
menu: 'format',
tool: 'toggle-bold'
},
{
name: 'Emphasize',
type: 'italic',
menu: 'format',
tool: 'toggle-italic'
},
{
name: 'Link',
type: 'ext-link',
menu: 'insert',
tool: 'create-ext-link'
},
{
name: 'Subscript',
type: 'sub',
menu: 'format',
tool: 'toggle-subscript'
},
{
name: 'Superscript',
type: 'sup',
menu: 'format',
tool: 'toggle-superscript'
},
{
name: 'Monospace',
type: 'monospace',
menu: 'format',
tool: 'toggle-monospace'
}
]
const ANNO_SELECTOR = {
'external-link': '.sc-external-link'
}
const fixture = `<p id="p1">
Lorem <bold>ipsum</bold> dolor <italic>sit</italic> amet, ea <ext-link href="foo">ludus</ext-link>
intellegat his, <sub>graece</sub> fastidii <sup>phaedrum</sup> ea mea, ne duo esse <monospace>omnium</monospace>.
</p>`
annotations.forEach(anno => {
test(`Annotations: toggle ${anno.name} annotation`, t => {
testAnnotationToggle(t, anno)
})
})
function testAnnotationToggle (t, anno) {
let { editor } = _setup(t)
toggleTool(t, editor, anno)
// Set the cursor and check if tool is active
setCursor(editor, 'p1.content', 3)
t.equal(isToolActive(editor, anno), false, 'Tool must be disabled')
// Set the selection and check if tool is active
setSelection(editor, 'p1.content', 2, 4)
t.equal(isToolActive(editor, anno), true, 'Tool must be active')
// Toggle the tool and check if an annotation appeared
toggleTool(t, editor, anno)
let annoEl = editor.find('[data-path="p1.content"] .sc-' + anno.type)
let annoId = annoEl.getAttribute('data-id')
t.notNil(annoEl, 'There should be an annotation')
let offset = annoEl.getAttribute('data-offset')
t.equal(offset, '2', 'The data-offset property must be equal to begining of the selection')
let length = annoEl.getAttribute('data-length')
t.equal(length, '2', 'The data-length property must be equal to the length of the selection')
let text = annoEl.text()
t.equal(text.length, parseInt(length), 'The number of annotated symbols must be equal to length of the selection')
// Set the cursor, toggle the tool and check if an annotation disappeared
setCursor(editor, 'p1.content', 3)
t.equal(isToolActive(editor, anno), true, 'Tool must be active')
toggleTool(t, editor, anno)
let removedAnno = editor.find('[data-path="p1.content"] [data-id="' + annoId + '"]')
t.isNil(removedAnno, 'There should be no annotation')
t.end()
}
function _setup (t) {
let { app } = setupTestApp(t, { archiveId: 'blank' })
let editor = openManuscriptEditor(app)
loadBodyFixture(editor, fixture)
return { editor }
}
function isToolActive (el, anno) {
let menu = openMenu(el, anno.menu)
let toolEl = menu.find(`.sc-menu-item.sm-${anno.tool}`)
return !toolEl.getAttribute('disabled')
}
function toggleTool (t, editor, anno) {
t.doesNotThrow(() => {
let menu = openMenu(editor, anno.menu)
menu.find(`.sc-menu-item.sm-${anno.tool}`).el.click()
})
}
function openMenu (el, menuName) {
const menu = el.find(`.sc-tool-dropdown.sm-${menuName}`)
const isActive = menu.find('button').hasClass('sm-active')
if (!isActive) {
menu.find('button').el.click()
}
return menu
}
| import { test } from 'substance-test'
import { setCursor, setSelection, openManuscriptEditor, loadBodyFixture } from './shared/integrationTestHelpers'
import setupTestApp from './shared/setupTestApp'
const ANNO_TYPES = {
'bold': 'Strong',
'italic': 'Emphasize',
'external-link': 'Link',
'subscript': 'Subscript',
'superscript': 'Superscript',
'monospace': 'Monospace'
}
const ANNO_SELECTOR = {
'external-link': '.sc-external-link'
}
const fixture = `<p id="p1">
Lorem <bold>ipsum</bold> dolor <italic>sit</italic> amet, ea <ext-link href="foo">ludus</ext-link>
intellegat his, <sub>graece</sub> fastidii <sup>phaedrum</sup> ea mea, ne duo esse <monospace>omnium</monospace>.
</p>`
Object.keys(ANNO_TYPES).forEach(annoType => {
test(`Annotations: toggle ${ANNO_TYPES[annoType]} annotation`, t => {
testAnnotationToggle(t, annoType)
})
})
function testAnnotationToggle (t, annoType) {
let annoSelector = ANNO_SELECTOR[annoType] || `.sc-annotation.sm-${annoType}`
let toolSelector = '.sc-toggle-tool.sm-' + annoType
let { editor } = _setup(t)
let annoTool = editor.find(toolSelector)
// Set the cursor and check if tool is active
setCursor(editor, 'p1.content', 3)
t.equal(_isToolActive(editor, annoType), false, 'Tool must be disabled')
// Set the selection and check if tool is active
setSelection(editor, 'p1.content', 2, 4)
t.equal(_isToolActive(editor, annoType), true, 'Tool must be active')
// Toggle the tool and check if an annotation appeared
annoTool.find('button').click()
let anno = editor.find('[data-path="p1.content"] ' + annoSelector)
let annoId = anno.getAttribute('data-id')
t.notNil(anno, 'There should be an annotation')
let offset = anno.el.getAttribute('data-offset')
t.equal(offset, '2', 'The data-offset property must be equal to begining of the selection')
let length = anno.el.getAttribute('data-length')
t.equal(length, '2', 'The data-length property must be equal to the length of the selection')
let text = anno.text()
t.equal(text.length, parseInt(length), 'The number of annotated symbols must be equal to length of the selection')
// Set the cursor, toggle the tool and check if an annotation disappeared
setCursor(editor, 'p1.content', 3)
t.equal(_isToolActive(editor, annoType), true, 'Tool must be active')
annoTool.find('button').click()
let removedAnno = editor.find('[data-path="p1.content"] [data-id="' + annoId + '"]')
t.isNil(removedAnno, 'There should be no annotation')
t.end()
}
function _setup (t) {
let { app } = setupTestApp(t, { archiveId: 'blank' })
let editor = openManuscriptEditor(app)
loadBodyFixture(editor, fixture)
return { editor }
}
function _isToolActive (el, annoType) {
let toolSelector = '.sc-toggle-tool.sm-' + annoType
let tool = el.find(toolSelector)
let btn = tool.find('button')
return !btn.getAttribute('disabled')
}
| JavaScript | 0 |
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) => {
assert(res.cmd === `git diff --name-only --diff-filter=AMCRDB ${ID1}`);
assert(res.output === OUTPUT_PATH);
assert(res.prefix === "hoge");
done();
});
});
});
});
| "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 |
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(7)
var rec = new Rectangle(5, 10)
t.equal(typeof rec.area, 'function')
t.equal(rec.area(), 50, 'rectangle area')
var squ = new Square(7)
t.equal(typeof squ.area, 'function')
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(4)
var rec = new Rectangle(5, 10)
t.equal(typeof rec.description, 'function')
t.equal(rec.description(), 'Rectangle of width 5, height 10 and area 50.', 'should describe rectangle')
var squ = new Square(7)
t.equal(typeof squ.description, 'function')
t.equal(squ.description(), 'Square of side 7 and area 49.', 'should describe square')
})
| 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 |
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);
});
it("should support negation rules", function() {
var expected = _.chain(files)
.filter(function(file) {
return file === "visible";
})
.map(function(file) {
return path.join(baseDir, file);
})
.value()
.sort();
var promise = fsAsync
.readdirRecursive({
path: baseDir,
ignore: ["!visible"],
})
.then(function(results) {
return _.map(results, function(result) {
return result.name;
}).sort();
});
return expect(promise).to.eventually.deep.equal(expected);
});
});
| "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 |
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(this.model.get('available') == 0) {
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
}
| 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 |
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: 'standard',
};
| module.exports = {
parser: 'babel-eslint',
parserOptions: {
ecmaVersion: 6,
sourceType: 'module'
},
rules: {
semi: 2
},
extends: 'airbnb-base',
}
| JavaScript | 0.000018 |
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,
"beforeEach": false,
"afterEach": 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"
]
}
}
| 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 |
4edd3d02fd396c29b05ebe7be4b579139a72aa3c | update ecmascript eslint parser target | .eslintrc.js | .eslintrc.js | 'use strict';
module.exports = {
root: true,
parserOptions: {
ecmaVersion: 2020,
},
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',
},
};
| '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 |
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,
'valid-typeof': 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
}
};
| 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 |
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'
]
}
};
| 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 |
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 }],
"no-restricted-syntax": [
"error",
{
selector: 'ForInStatement',
message: 'for..in loops iterate over the entire prototype chain, which is virtually never what you want. Use Object.{keys,values,entries}, and iterate over the resulting array.',
},
{
selector: 'LabeledStatement',
message: 'Labels are a form of GOTO; using them makes code confusing and hard to maintain and understand.',
},
{
selector: 'WithStatement',
message: '`with` is disallowed in strict mode because it makes code impossible to predict and optimize.',
}
]
},
"overrides": [{
"files": ["**/*.ts"],
"parser": "typescript-eslint-parser",
"rules": {
"import/no-unresolved": "off",
"no-undef": "off",
"no-unused-vars": "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"
}
}]
};
| 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 |
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'],
},
},
],
'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,
},
},
],
};
| 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 |