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
|
---|---|---|---|---|---|---|---|
43b7930247c46cfa454f4ceed1f1e777235ea895 | clear action | src/astroprint/static/js/app/views/terminal.js | src/astroprint/static/js/app/views/terminal.js | var TerminalView = Backbone.View.extend({
el: '#terminal-view',
outputView: null,
sourceId: null,
events: {
'submit form': 'onSend',
'show': 'onShow',
'hide': 'onHide',
'click button.clear': 'onClear'
},
initialize: function()
{
this.outputView = new OutputView();
this.sourceId = Math.floor((Math.random() * 100000)); //Generate a random sourceId
app.eventManager.on("astrobox:PrinterResponse", _.bind(function(data) {
if (data.sourceId == this.sourceId) {
this.outputView.add('received', data.response);
}
}, this));
},
onClear: function(e)
{
e.preventDefault();
this.outputView.clear();
},
onSend: function(e)
{
e.preventDefault();
var sendField = this.$('input');
var command = sendField.val();
if (this.sourceId && command) {
var loadingBtn = this.$('button.send').closest('.loading-button');
loadingBtn.addClass('loading');
$.ajax({
url: API_BASEURL + 'printer/comm/send',
method: 'POST',
data: {
sourceId: this.sourceId,
command: command
}
})
.done(_.bind(function(){
this.outputView.add('sent', command);
}, this))
.fail(function(){
loadingBtn.addClass('error');
setTimeout(function(){
loadingBtn.removeClass('error');
}, 3000);
})
.always(function(){
loadingBtn.removeClass('loading');
sendField.val('');
});
}
return false;
},
onShow: function()
{
this.$('input').focus();
$.ajax({
url: API_BASEURL + 'printer/comm/listen',
method: 'POST'
})
},
onHide: function()
{
$.ajax({
url: API_BASEURL + 'printer/comm/listen',
method: 'DELETE'
});
}
});
var OutputView = Backbone.View.extend({
el: '#terminal-view .output-container',
add: function(type, text)
{
switch(type) {
case 'sent':
text = '<div class="sent bold"><i class="icon-angle-right"></i>'+text+'</div>';
break;
case 'received':
text = '<div class="received"><i class="icon-angle-left"></i>'+text+'</div>';
break;
}
this.$el.append(text);
this.$el.scrollTop(this.$el[0].scrollHeight);
},
clear: function()
{
this.$el.html('');
}
});
| var TerminalView = Backbone.View.extend({
el: '#terminal-view',
outputView: null,
sourceId: null,
events: {
'submit form': 'onSend',
'show': 'onShow',
'hide': 'onHide'
},
initialize: function()
{
this.outputView = new OutputView();
this.sourceId = Math.floor((Math.random() * 100000)); //Generate a random sourceId
app.eventManager.on("astrobox:PrinterResponse", _.bind(function(data) {
if (data.sourceId == this.sourceId) {
this.outputView.add('received', data.response);
}
}, this));
},
onClear: function(e)
{
e.preventDefault();
this.outputView.clear();
},
onSend: function(e)
{
e.preventDefault();
var sendField = this.$('input');
var command = sendField.val();
if (this.sourceId && command) {
var loadingBtn = this.$('button.send').closest('.loading-button');
loadingBtn.addClass('loading');
$.ajax({
url: API_BASEURL + 'printer/comm/send',
method: 'POST',
data: {
sourceId: this.sourceId,
command: command
}
})
.done(_.bind(function(){
this.outputView.add('sent', command);
}, this))
.fail(function(){
loadingBtn.addClass('error');
setTimeout(function(){
loadingBtn.removeClass('error');
}, 3000);
})
.always(function(){
loadingBtn.removeClass('loading');
sendField.val('');
});
}
return false;
},
onShow: function()
{
this.$('input').focus();
$.ajax({
url: API_BASEURL + 'printer/comm/listen',
method: 'POST'
})
},
onHide: function()
{
$.ajax({
url: API_BASEURL + 'printer/comm/listen',
method: 'DELETE'
});
}
});
var OutputView = Backbone.View.extend({
el: '#terminal-view .output-container',
add: function(type, text)
{
switch(type) {
case 'sent':
text = '<div class="sent bold"><i class="icon-angle-right"></i>'+text+'</div>';
break;
case 'received':
text = '<div class="received"><i class="icon-angle-left"></i>'+text+'</div>';
break;
}
this.$el.append(text);
this.$el.scrollTop(this.$el[0].scrollHeight);
},
clear: function()
{
this.$el.empty();
}
});
| JavaScript | 0.000001 |
615a2718f0d62205869b72e347cf909c8c43c4de | Add docstrings to the popover view | web_client/views/popover/AnnotationPopover.js | web_client/views/popover/AnnotationPopover.js | import _ from 'underscore';
import View from '../View';
import { restRequest } from 'girder/rest';
import ElementCollection from 'girder_plugins/large_image/collections/ElementCollection';
import annotationPopover from '../../templates/popover/annotationPopover.pug';
import '../../stylesheets/popover/annotationPopover.styl';
/**
* This view behaves like a bootstrap "popover" that follows the mouse pointer
* over the image canvas and dynamically updates according to the features
* under the pointer.
*
* @param {object} [settings]
* @param {number} [settings.debounce]
* Debounce time in ms for rerendering due to mouse movements
*/
var AnnotationPopover = View.extend({
initialize(settings) {
if (settings.debounce) {
this._position = _.debounce(this._position, settings.debounce);
}
$('body').on('mousemove', '.h-image-view-body', (evt) => this._position(evt));
$('body').on('mouseout', '.h-image-view-body', () => this._hide());
$('body').on('mouseover', '.h-image-view-body', () => this._show());
this._hidden = !settings.visible;
this._users = {};
this.collection = new ElementCollection();
this.listenTo(this.collection, 'add', this._getUser);
this.listenTo(this.collection, 'all', this.render);
},
render() {
this.$el.html(
annotationPopover({
annotations: _.uniq(
this.collection.pluck('annotation'),
_.property('id')),
formatDate: this._formatDate,
users: this._users
})
);
this._show();
if (!this._visible()) {
this._hide();
}
this._height = this.$('.h-annotation-popover').height();
},
/**
* Set the popover visibility state.
*
* @param {boolean} [show]
* if true: show the popover
* if false: hide the popover
* if undefined: toggle the popover state
*/
toggle(show) {
if (show === undefined) {
show = this._hidden;
}
this._hidden = !show;
this.render();
return this;
},
/**
* Check the local cache for the given creator. If it has not already been
* fetched, then send a rest request to get the user information and
* rerender the popover.
*
* As a consequence to avoid always rendering asyncronously, the user name
* will not be shown on the first render. In practice, this isn't usually
* noticeable.
*/
_getUser(model) {
var id = model.get('annotation').get('creatorId');
if (!_.has(this._users, id)) {
restRequest({
path: 'user/' + id
}).then((user) => {
this._users[id] = user;
this.render();
});
}
},
/**
* Format a Date object as a localized string.
*/
_formatDate(s) {
var d = new Date(s);
return d.toLocaleString();
},
/**
* Remove the hidden class on the popover element if this._visible()
* returns true.
*/
_show() {
if (this._visible()) {
this.$el.removeClass('hidden');
}
},
/**
* Unconditionally hide popover.
*/
_hide() {
this.$el.addClass('hidden');
},
/**
* Determine if the popover should be visible. Returns true
* if there are active annotations under the mouse pointer and
* the label option is enabled.
*/
_visible() {
return !this._hidden && this.collection.length > 0;
},
/**
* Reset the position of the popover to the position of the
* mouse pointer.
*/
_position(evt) {
if (this._visible()) {
this.$el.css({
left: evt.pageX + 5,
top: evt.pageY - this._height / 2
});
}
}
});
export default AnnotationPopover;
| import _ from 'underscore';
import View from '../View';
import { restRequest } from 'girder/rest';
import ElementCollection from 'girder_plugins/large_image/collections/ElementCollection';
import annotationPopover from '../../templates/popover/annotationPopover.pug';
import '../../stylesheets/popover/annotationPopover.styl';
var AnnotationPopover = View.extend({
initialize(settings) {
if (settings.debounce) {
this.position = _.debounce(this.position, settings.debounce);
}
$('body').on('mousemove', '.h-image-view-body', (evt) => this.position(evt));
$('body').on('mouseout', '.h-image-view-body', () => this._hide());
$('body').on('mouseover', '.h-image-view-body', () => this._show());
this._hidden = !settings.visible;
this._users = {};
this.collection = new ElementCollection();
this.listenTo(this.collection, 'add', this._getUser);
this.listenTo(this.collection, 'all', this.render);
},
render() {
this.$el.html(
annotationPopover({
annotations: _.uniq(
this.collection.pluck('annotation'),
_.property('id')),
formatDate: this._formatDate,
users: this._users
})
);
this._show();
if (!this._visible()) {
this._hide();
}
this._height = this.$('.h-annotation-popover').height();
},
_getUser(model) {
var id = model.get('annotation').get('creatorId');
if (!_.has(this._users, id)) {
restRequest({
path: 'user/' + id
}).then((user) => {
this._users[id] = user;
this.render();
});
}
},
_formatDate(s) {
var d = new Date(s);
return d.toLocaleString();
},
_show() {
if (this._visible()) {
this.$el.removeClass('hidden');
}
},
_hide() {
this.$el.addClass('hidden');
},
_visible() {
return !this._hidden && this.collection.length > 0;
},
position(evt) {
if (this._visible()) {
this.$el.css({
left: evt.pageX + 5,
top: evt.pageY - this._height / 2
});
}
},
toggle(show) {
this._hidden = !show;
this.render();
}
});
export default AnnotationPopover;
| JavaScript | 0 |
828032d625d4246a1d4a86333e962d00e04bcfb6 | test åäö | src/main/resources/client/components/SiteWrapper/SiteWrapper.js | src/main/resources/client/components/SiteWrapper/SiteWrapper.js | 'use strict';
// Vendor
var _assign = require('lodash/object/assign');
var Vue = require('vue');
var $ = require('jquery');
// Components
var TechInfoWindow = require('components/TechInfoWindow/TechInfoWindow.js');
// Utils
var AuthenticationUtil = require('utils/AuthenticationUtil/AuthenticationUtil.js');
var TechnicalInfoUtil = require('utils/TechnicalInfoUtil/TechnicalInfoUtil.js');
// CSS modules
var styles = _assign(
require('./SiteWrapper.css'),
require('css/modules/Colors.less')
);
/**
* Site Wrapper Component
*/
var SiteWrapperMixin = {
props: ['activity'],
template: require('./SiteWrapper.html'),
data: function() {
return {
authenticated: false,
userModel: {},
_styles: styles,
}
},
components: {
'tech-info-window': TechInfoWindow
},
events: {
/*
'authenticate': function() {
if(this.authenticated) {
this.$broadcast('logged-in', this.userModel);
}
},
*/
'setTextTitle': function() {
}
},
ready: function() {
/*
// Authenticate
Authenticationutil.authenticate(function(authenticated, userModel) {
if(authenticated) {
this.$set('authenticated', true);
this.$set('userModel', userModel);
this.$broadcast('logged-in', userModel);
}
}.bind(this));
*/
AuthenticationUtil.authenticate(function(authenticated) {
if (authenticated.isLoggedIn) {
this.$set('authenticated', true);
this.$set('userModel', authenticated);
console.log(authenticated);
}
}.bind(this));
// Set GitHub-image
this.$els.githubImage1.src = this.$els.githubImage2.src = require('octicons/svg/mark-github.svg');
},
methods: {
init: function() {
},
checkLoggedInStatus: function() {
AuthenticationUtil.authenticate(function(authenticated) {
if (!authenticated.isLoggedIn) {
var url = '/secure?return=';
$(location).attr('href', url + window.location.href);
}
});
}
}
};
module.exports = SiteWrapperMixin;
| 'use strict';
// Vendor
var _assign = require('lodash/object/assign');
var Vue = require('vue');
var $ = require('jquery');
// Components
var TechInfoWindow = require('components/TechInfoWindow/TechInfoWindow.js');
// Utils
var AuthenticationUtil = require('utils/AuthenticationUtil/AuthenticationUtil.js');
var TechnicalInfoUtil = require('utils/TechnicalInfoUtil/TechnicalInfoUtil.js');
// CSS modules
var styles = _assign(
require('./SiteWrapper.css'),
require('css/modules/Colors.less')
);
/**
* Site Wrapper Component
*/
var SiteWrapperMixin = {
props: ['activity'],
template: require('./SiteWrapper.html'),
data: function() {
return {
authenticated: false,
userModel: {},
_styles: styles,
}
},
components: {
'tech-info-window': TechInfoWindow
},
events: {
/*
'authenticate': function() {
if(this.authenticated) {
this.$broadcast('logged-in', this.userModel);
}
},
*/
'setTextTitle': function() {
}
},
ready: function() {
/*
// Authenticate
Authenticationutil.authenticate(function(authenticated, userModel) {
if(authenticated) {
this.$set('authenticated', true);
this.$set('userModel', userModel);
this.$broadcast('logged-in', userModel);
}
}.bind(this));
*/
AuthenticationUtil.authenticate(function(authenticated) {
if (authenticated.isLoggedIn) {
this.$set('authenticated', true);
this.$set('userModel', authenticated);
}
}.bind(this));
// Set GitHub-image
this.$els.githubImage1.src = this.$els.githubImage2.src = require('octicons/svg/mark-github.svg');
},
methods: {
init: function() {
},
checkLoggedInStatus: function() {
AuthenticationUtil.authenticate(function(authenticated) {
if (!authenticated.isLoggedIn) {
var url = '/secure?return=';
$(location).attr('href', url + window.location.href);
}
});
}
}
};
module.exports = SiteWrapperMixin;
| JavaScript | 0.000001 |
ae543be4b0ce6807cbb6b70b09d28bd390290fad | add default export (#48) | leveldown.js | leveldown.js | const util = require('util')
, AbstractLevelDOWN = require('abstract-leveldown').AbstractLevelDOWN
, binding = require('bindings')('leveldown').leveldown
, ChainedBatch = require('./chained-batch')
, Iterator = require('./iterator')
, fs = require('fs')
function LevelDOWN (location) {
if (!(this instanceof LevelDOWN))
return new LevelDOWN(location)
AbstractLevelDOWN.call(this, location)
this.binding = binding(location)
}
util.inherits(LevelDOWN, AbstractLevelDOWN)
LevelDOWN.prototype._open = function (options, callback) {
this.binding.open(options, callback)
}
LevelDOWN.prototype._close = function (callback) {
this.binding.close(callback)
}
LevelDOWN.prototype._put = function (key, value, options, callback) {
this.binding.put(key, value, options, callback)
}
LevelDOWN.prototype._get = function (key, options, callback) {
this.binding.get(key, options, callback)
}
LevelDOWN.prototype._del = function (key, options, callback) {
this.binding.del(key, options, callback)
}
LevelDOWN.prototype._chainedBatch = function () {
return new ChainedBatch(this)
}
LevelDOWN.prototype._batch = function (operations, options, callback) {
return this.binding.batch(operations, options, callback)
}
LevelDOWN.prototype.approximateSize = function (start, end, callback) {
if (start == null ||
end == null ||
typeof start === 'function' ||
typeof end === 'function') {
throw new Error('approximateSize() requires valid `start`, `end` and `callback` arguments')
}
if (typeof callback !== 'function') {
throw new Error('approximateSize() requires a callback argument')
}
start = this._serializeKey(start)
end = this._serializeKey(end)
this.binding.approximateSize(start, end, callback)
}
LevelDOWN.prototype.compactRange = function (start, end, callback) {
this.binding.compactRange(start, end, callback)
}
LevelDOWN.prototype.getProperty = function (property) {
if (typeof property != 'string')
throw new Error('getProperty() requires a valid `property` argument')
return this.binding.getProperty(property)
}
LevelDOWN.prototype._iterator = function (options) {
return new Iterator(this, options)
}
LevelDOWN.destroy = function (location, callback) {
if (arguments.length < 2)
throw new Error('destroy() requires `location` and `callback` arguments')
if (typeof location != 'string')
throw new Error('destroy() requires a location string argument')
if (typeof callback != 'function')
throw new Error('destroy() requires a callback function argument')
binding.destroy(location, function (err) {
if (err) return callback(err)
// On Windows, RocksDB silently fails to remove the directory because its
// Logger, which is instantiated on destroy(), has an open file handle on a
// LOG file. Destroy() removes this file but Windows won't actually delete
// it until the handle is released. This happens when destroy() goes out of
// scope, which disposes the Logger. So back in JS-land, we can again
// attempt to remove the directory. This is merely a workaround because
// arguably RocksDB should not instantiate a Logger or open a file at all.
fs.rmdir(location, function (err) {
if (err) {
// Ignore this error in case there are non-RocksDB files left.
if (err.code === 'ENOTEMPTY') return callback()
if (err.code === 'ENOENT') return callback()
return callback(err)
}
callback()
})
})
}
LevelDOWN.repair = function (location, callback) {
if (arguments.length < 2)
throw new Error('repair() requires `location` and `callback` arguments')
if (typeof location != 'string')
throw new Error('repair() requires a location string argument')
if (typeof callback != 'function')
throw new Error('repair() requires a callback function argument')
binding.repair(location, callback)
}
module.exports = LevelDOWN.default = LevelDOWN
| const util = require('util')
, AbstractLevelDOWN = require('abstract-leveldown').AbstractLevelDOWN
, binding = require('bindings')('leveldown').leveldown
, ChainedBatch = require('./chained-batch')
, Iterator = require('./iterator')
, fs = require('fs')
function LevelDOWN (location) {
if (!(this instanceof LevelDOWN))
return new LevelDOWN(location)
AbstractLevelDOWN.call(this, location)
this.binding = binding(location)
}
util.inherits(LevelDOWN, AbstractLevelDOWN)
LevelDOWN.prototype._open = function (options, callback) {
this.binding.open(options, callback)
}
LevelDOWN.prototype._close = function (callback) {
this.binding.close(callback)
}
LevelDOWN.prototype._put = function (key, value, options, callback) {
this.binding.put(key, value, options, callback)
}
LevelDOWN.prototype._get = function (key, options, callback) {
this.binding.get(key, options, callback)
}
LevelDOWN.prototype._del = function (key, options, callback) {
this.binding.del(key, options, callback)
}
LevelDOWN.prototype._chainedBatch = function () {
return new ChainedBatch(this)
}
LevelDOWN.prototype._batch = function (operations, options, callback) {
return this.binding.batch(operations, options, callback)
}
LevelDOWN.prototype.approximateSize = function (start, end, callback) {
if (start == null ||
end == null ||
typeof start === 'function' ||
typeof end === 'function') {
throw new Error('approximateSize() requires valid `start`, `end` and `callback` arguments')
}
if (typeof callback !== 'function') {
throw new Error('approximateSize() requires a callback argument')
}
start = this._serializeKey(start)
end = this._serializeKey(end)
this.binding.approximateSize(start, end, callback)
}
LevelDOWN.prototype.compactRange = function (start, end, callback) {
this.binding.compactRange(start, end, callback)
}
LevelDOWN.prototype.getProperty = function (property) {
if (typeof property != 'string')
throw new Error('getProperty() requires a valid `property` argument')
return this.binding.getProperty(property)
}
LevelDOWN.prototype._iterator = function (options) {
return new Iterator(this, options)
}
LevelDOWN.destroy = function (location, callback) {
if (arguments.length < 2)
throw new Error('destroy() requires `location` and `callback` arguments')
if (typeof location != 'string')
throw new Error('destroy() requires a location string argument')
if (typeof callback != 'function')
throw new Error('destroy() requires a callback function argument')
binding.destroy(location, function (err) {
if (err) return callback(err)
// On Windows, RocksDB silently fails to remove the directory because its
// Logger, which is instantiated on destroy(), has an open file handle on a
// LOG file. Destroy() removes this file but Windows won't actually delete
// it until the handle is released. This happens when destroy() goes out of
// scope, which disposes the Logger. So back in JS-land, we can again
// attempt to remove the directory. This is merely a workaround because
// arguably RocksDB should not instantiate a Logger or open a file at all.
fs.rmdir(location, function (err) {
if (err) {
// Ignore this error in case there are non-RocksDB files left.
if (err.code === 'ENOTEMPTY') return callback()
if (err.code === 'ENOENT') return callback()
return callback(err)
}
callback()
})
})
}
LevelDOWN.repair = function (location, callback) {
if (arguments.length < 2)
throw new Error('repair() requires `location` and `callback` arguments')
if (typeof location != 'string')
throw new Error('repair() requires a location string argument')
if (typeof callback != 'function')
throw new Error('repair() requires a callback function argument')
binding.repair(location, callback)
}
module.exports = LevelDOWN
| JavaScript | 0 |
5b3a17e24efcf7603f0fd73d8eabd8fb516ee536 | fix wrong this context (#4352) | lib/workers/repository/process/lookup/rollback.js | lib/workers/repository/process/lookup/rollback.js | const { logger } = require('../../../../logger');
const versioning = require('../../../../versioning');
module.exports = {
getRollbackUpdate,
};
function getRollbackUpdate(config, versions) {
const { packageFile, versionScheme, depName, currentValue } = config;
const version = versioning.get(versionScheme);
// istanbul ignore if
if (!version.isLessThanRange) {
logger.info(
{ versionScheme },
'Current version scheme does not support isLessThanRange()'
);
return null;
}
const lessThanVersions = versions.filter(v =>
version.isLessThanRange(v, currentValue)
);
// istanbul ignore if
if (!lessThanVersions.length) {
logger.info(
{ packageFile, depName, currentValue },
'Missing version has nothing to roll back to'
);
return null;
}
logger.info(
{ packageFile, depName, currentValue },
`Current version not found - rolling back`
);
logger.debug(
{ dependency: depName, versions },
'Versions found before rolling back'
);
lessThanVersions.sort((a, b) => version.sortVersions(a, b));
const toVersion = lessThanVersions.pop();
// istanbul ignore if
if (!toVersion) {
logger.info('No toVersion to roll back to');
return null;
}
let fromVersion;
const newValue = version.getNewValue(
currentValue,
'replace',
fromVersion,
toVersion
);
return {
updateType: 'rollback',
branchName:
'{{{branchPrefix}}}rollback-{{{depNameSanitized}}}-{{{newMajor}}}.x',
commitMessageAction: 'Roll back',
isRollback: true,
newValue,
newMajor: version.getMajor(toVersion),
semanticCommitType: 'fix',
};
}
| const { logger } = require('../../../../logger');
const versioning = require('../../../../versioning');
module.exports = {
getRollbackUpdate,
};
function getRollbackUpdate(config, versions) {
const { packageFile, versionScheme, depName, currentValue } = config;
const version = versioning.get(versionScheme);
// istanbul ignore if
if (!version.isLessThanRange) {
logger.info(
{ versionScheme },
'Current version scheme does not support isLessThanRange()'
);
return null;
}
const lessThanVersions = versions.filter(v =>
version.isLessThanRange(v, currentValue)
);
// istanbul ignore if
if (!lessThanVersions.length) {
logger.info(
{ packageFile, depName, currentValue },
'Missing version has nothing to roll back to'
);
return null;
}
logger.info(
{ packageFile, depName, currentValue },
`Current version not found - rolling back`
);
logger.debug(
{ dependency: depName, versions },
'Versions found before rolling back'
);
lessThanVersions.sort(version.sortVersions);
const toVersion = lessThanVersions.pop();
// istanbul ignore if
if (!toVersion) {
logger.info('No toVersion to roll back to');
return null;
}
let fromVersion;
const newValue = version.getNewValue(
currentValue,
'replace',
fromVersion,
toVersion
);
return {
updateType: 'rollback',
branchName:
'{{{branchPrefix}}}rollback-{{{depNameSanitized}}}-{{{newMajor}}}.x',
commitMessageAction: 'Roll back',
isRollback: true,
newValue,
newMajor: version.getMajor(toVersion),
semanticCommitType: 'fix',
};
}
| JavaScript | 0.000011 |
c2e3d2b8ca5ebe76fc12a08038bf9251c43bdbac | Fix time differences (add 1 second) | src/client/rest/RequestHandlers/Sequential.js | src/client/rest/RequestHandlers/Sequential.js | const RequestHandler = require('./RequestHandler');
/**
* Handles API Requests sequentially, i.e. we wait until the current request is finished before moving onto
* the next. This plays a _lot_ nicer in terms of avoiding 429's when there is more than one session of the account,
* but it can be slower.
* @extends {RequestHandler}
*/
module.exports = class SequentialRequestHandler extends RequestHandler {
constructor(restManager) {
super(restManager);
/**
* Whether this rate limiter is waiting for a response from a request
* @type {Boolean}
*/
this.waiting = false;
/**
* The time difference between Discord's Dates and the local computer's Dates. A positive number means the local
* computer's time is ahead of Discord's.
* @type {Number}
*/
this.timeDifference = 0;
}
push(request) {
super.push(request);
this.handle();
}
/**
* Performs a request then resolves a promise to indicate its readiness for a new request
* @param {APIRequest} item the item to execute
* @returns {Promise<Object, Error>}
*/
execute(item) {
return new Promise((resolve, reject) => {
item.request.gen().end((err, res) => {
if (res && res.headers) {
this.requestLimit = res.headers['x-ratelimit-limit'];
this.requestResetTime = Number(res.headers['x-ratelimit-reset']) * 1000;
this.requestRemaining = Number(res.headers['x-ratelimit-remaining']);
this.timeDifference = Date.now() - new Date(res.headers.date).getTime();
}
if (err) {
if (err.status === 429) {
setTimeout(() => {
this.waiting = false;
resolve();
}, res.headers['retry-after']);
} else {
this.queue.shift();
this.waiting = false;
item.reject(err);
resolve(err);
}
} else {
this.queue.shift();
const data = res && res.body ? res.body : {};
item.resolve(data);
if (this.requestRemaining === 0) {
setTimeout(() => {
this.waiting = false;
resolve(data);
}, (this.requestResetTime - Date.now()) + this.timeDifference + 1000);
} else {
this.waiting = false;
resolve(data);
}
}
});
});
}
handle() {
super.handle();
if (this.waiting || this.queue.length === 0) {
return;
}
this.waiting = true;
const item = this.queue[0];
this.execute(item).then(() => this.handle());
}
};
| const RequestHandler = require('./RequestHandler');
/**
* Handles API Requests sequentially, i.e. we wait until the current request is finished before moving onto
* the next. This plays a _lot_ nicer in terms of avoiding 429's when there is more than one session of the account,
* but it can be slower.
* @extends {RequestHandler}
*/
module.exports = class SequentialRequestHandler extends RequestHandler {
constructor(restManager) {
super(restManager);
/**
* Whether this rate limiter is waiting for a response from a request
* @type {Boolean}
*/
this.waiting = false;
/**
* The time difference between Discord's Dates and the local computer's Dates. A positive number means the local
* computer's time is ahead of Discord's.
* @type {Number}
*/
this.timeDifference = 0;
}
push(request) {
super.push(request);
this.handle();
}
/**
* Performs a request then resolves a promise to indicate its readiness for a new request
* @param {APIRequest} item the item to execute
* @returns {Promise<Object, Error>}
*/
execute(item) {
return new Promise((resolve, reject) => {
item.request.gen().end((err, res) => {
if (res && res.headers) {
this.requestLimit = res.headers['x-ratelimit-limit'];
this.requestResetTime = Number(res.headers['x-ratelimit-reset']) * 1000;
this.requestRemaining = Number(res.headers['x-ratelimit-remaining']);
this.timeDifference = Date.now() - new Date(res.headers.date).getTime();
}
if (err) {
if (err.status === 429) {
setTimeout(() => {
this.waiting = false;
resolve();
}, res.headers['retry-after']);
} else {
this.queue.shift();
this.waiting = false;
item.reject(err);
resolve(err);
}
} else {
this.queue.shift();
const data = res && res.body ? res.body : {};
item.resolve(data);
if (this.requestRemaining === 0) {
setTimeout(() => {
this.waiting = false;
resolve(data);
}, (this.requestResetTime - Date.now()) + this.timeDifference - 1000);
} else {
this.waiting = false;
resolve(data);
}
}
});
});
}
handle() {
super.handle();
if (this.waiting || this.queue.length === 0) {
return;
}
this.waiting = true;
const item = this.queue[0];
this.execute(item).then(() => this.handle());
}
};
| JavaScript | 0.000059 |
1eeee314affb486acc249d670452063b78e42e49 | refactor the Index module for readability and testability | lib/Index.js | lib/Index.js | 'use strict';
const {noop, defaults} = require('lodash');
const path = require('path');
const Sequelize = require('sequelize');
class Index {
/**
* @param options
*/
constructor(options) {
options = defaults(options, {
filename: path.join(process.cwd(), '.index'),
log: noop,
});
const {db, Result} = Index.prepareDb(options);
this.db = db;
this.Result = Result;
}
/**
* Prepare the "Result" collection for mutations
*
* @returns {Promise}
*/
sync() {
if (!this.ready) this.ready = this.Result.sync();
return this.ready;
}
/**
* Prepare the database
*
* @param {String} options.filename
* @param {Function} options.log
*
* @returns {{db: Sequelize, result: Model}}
*/
static prepareDb(options) {
const db = new Sequelize('cachething', 'carrier', null, {
'dialect': 'sqlite',
'storage': options.filename,
'logging': options.log,
});
const Result = Index.defineResultModel(db);
return {db, Result};
}
/**
* Define the "Result" model on the given database instance
* @param db
* @returns {*|void|Model|{}}
*/
static defineResultModel(db) {
return db.define('Result', {
action: Sequelize.STRING,
fileHash: Sequelize.STRING,
outputHash: Sequelize.STRING,
created: Sequelize.BIGINT,
expires: Sequelize.BIGINT,
fileName: Sequelize.STRING,
compressed: Sequelize.BOOLEAN,
fileSize: Sequelize.BIGINT,
runtime: Sequelize.BIGINT
});
}
}
module.exports = Index; | 'use strict';
const path = require('path');
const defaults = require('defa');
const Sequelize = require('sequelize');
class Index {
constructor(options) {
defaults(options, {
'filename': () => path.join(process.cwd(), '.index')
});
this.prepareDb(options.filename);
}
sync() {
if (!this.ready)
this.ready = this.Result.sync();
return this.ready;
}
log() {
// do nothing
// TODO log it somewhere
}
/**
* Prepare the database and insert models and stuff
* @param {String} filename
* @returns {Promise}
*/
prepareDb(filename) {
const sequelize = new Sequelize('cachething', 'carrier', null, {
'dialect': 'sqlite',
'storage': filename,
'logging': msg => this.log(msg)
});
this.db = sequelize;
this.Result = sequelize.define('Result', {
action: Sequelize.STRING,
fileHash: Sequelize.STRING,
outputHash: Sequelize.STRING,
created: Sequelize.BIGINT,
expires: Sequelize.BIGINT,
fileName: Sequelize.STRING,
compressed: Sequelize.BOOLEAN,
fileSize: Sequelize.BIGINT,
runtime: Sequelize.BIGINT
});
}
}
module.exports = Index; | JavaScript | 0.000004 |
be75c469b7d90952e89a9ee7c87ea7ad017cd104 | Allow alias exploding | plugins/aliases.js | plugins/aliases.js | // This is the aliases plugin
// One must not run this plugin with the queue/smtp_proxy plugin.
var Address = require('address-rfc2821').Address;
exports.register = function () {
this.inherits('queue/discard');
this.register_hook('rcpt','aliases');
};
exports.aliases = function (next, connection, params) {
var plugin = this;
var config = this.config.get('aliases', 'json') || {};
var rcpt = params[0].address();
var user = params[0].user;
var host = params[0].host;
var match = user.split("-", 1);
var action = "<missing>";
if (config[rcpt]) {
action = config[rcpt].action || action;
match = rcpt;
switch (action.toLowerCase()) {
case 'drop':
_drop(plugin, connection, rcpt);
break;
case 'alias':
_alias(plugin, connection, match, config[match], host);
break;
default:
connection.loginfo(plugin, "unknown action: " + action);
}
}
if (config['@'+host]) {
action = config['@'+host].action || action;
match = '@'+host;
switch (action.toLowerCase()) {
case 'drop':
_drop(plugin, connection, '@'+host);
break;
case 'alias':
_alias(plugin, connection, match, config[match], host);
break;
default:
connection.loginfo(plugin, "unknown action: " + action);
}
}
if (config[user] || config[match[0]]) {
if (config[user]) {
action = config[user].action || action;
match = user;
}
else {
action = config[match[0]].action || action;
match = match[0];
}
switch (action.toLowerCase()) {
case 'drop':
_drop(plugin, connection, rcpt);
break;
case 'alias':
_alias(plugin, connection, match, config[match], host);
break;
default:
connection.loginfo(plugin, "unknown action: " + action);
}
}
next();
};
function _drop(plugin, connection, rcpt) {
connection.logdebug(plugin, "marking " + rcpt + " for drop");
connection.transaction.notes.discard = true;
}
function _alias(plugin, connection, key, config, host) {
var to;
var toAddress;
if (config.to) {
if (Array.isArray(config.to)) {
connection.logdebug(plugin, "aliasing " + connection.transaction.rcpt_to + " to " + config.to);
connection.transaction.rcpt_to.pop();
for (var i = 0, len = config.to.length; i < len; i++) {
toAddress = new Address('<' + config.to[i] + '>');
connection.transaction.rcpt_to.push(toAddress);
}
} else {
if (config.to.search("@") !== -1) {
to = config.to;
} else {
to = config.to + '@' + host;
}
connection.logdebug(plugin, "aliasing " +
connection.transaction.rcpt_to + " to " + to);
toAddress = new Address('<' + to + '>');
connection.transaction.rcpt_to.pop();
connection.transaction.rcpt_to.push(toAddress);
}
} else {
connection.loginfo(plugin, 'alias failed for ' + key +
', no "to" field in alias config');
}
}
| // This is the aliases plugin
// One must not run this plugin with the queue/smtp_proxy plugin.
var Address = require('address-rfc2821').Address;
exports.register = function () {
this.inherits('queue/discard');
this.register_hook('rcpt','aliases');
};
exports.aliases = function (next, connection, params) {
var plugin = this;
var config = this.config.get('aliases', 'json') || {};
var rcpt = params[0].address();
var user = params[0].user;
var host = params[0].host;
var match = user.split("-", 1);
var action = "<missing>";
if (config[rcpt]) {
action = config[rcpt].action || action;
match = rcpt;
switch (action.toLowerCase()) {
case 'drop':
_drop(plugin, connection, rcpt);
break;
case 'alias':
_alias(plugin, connection, match, config[match], host);
break;
default:
connection.loginfo(plugin, "unknown action: " + action);
}
}
if (config['@'+host]) {
action = config['@'+host].action || action;
match = '@'+host;
switch (action.toLowerCase()) {
case 'drop':
_drop(plugin, connection, '@'+host);
break;
case 'alias':
_alias(plugin, connection, match, config[match], host);
break;
default:
connection.loginfo(plugin, "unknown action: " + action);
}
}
if (config[user] || config[match[0]]) {
if (config[user]) {
action = config[user].action || action;
match = user;
}
else {
action = config[match[0]].action || action;
match = match[0];
}
switch (action.toLowerCase()) {
case 'drop':
_drop(plugin, connection, rcpt);
break;
case 'alias':
_alias(plugin, connection, match, config[match], host);
break;
default:
connection.loginfo(plugin, "unknown action: " + action);
}
}
next();
};
function _drop(plugin, connection, rcpt) {
connection.logdebug(plugin, "marking " + rcpt + " for drop");
connection.transaction.notes.discard = true;
}
function _alias(plugin, connection, key, config, host) {
var to;
var toAddress;
if (config.to) {
if (config.to.search("@") !== -1) {
to = config.to;
}
else {
to = config.to + '@' + host;
}
connection.logdebug(plugin, "aliasing " +
connection.transaction.rcpt_to + " to " + to);
toAddress = new Address('<' + to + '>');
connection.transaction.rcpt_to.pop();
connection.transaction.rcpt_to.push(toAddress);
}
else {
connection.loginfo(plugin, 'alias failed for ' + key +
', no "to" field in alias config');
}
}
| JavaScript | 0.000005 |
70fc4295de4e9123f90bbf9e18749d990e2da403 | Fix indentation | simplePagination.spec.js | simplePagination.spec.js | 'use strict';
describe('Simple Pagination', function() {
var pagination;
// load the app
beforeEach(module('SimplePagination'));
// get service
beforeEach(inject(function(Pagination) {
pagination = Pagination.getNew();
}));
it('should paginate', function() {
pagination.numPages = 2;
expect(pagination.page).toBe(0);
pagination.nextPage();
expect(pagination.page).toBe(1);
pagination.prevPage();
expect(pagination.page).toBe(0);
});
it('should not paginate outside min and max page', function() {
pagination.numPages = 2;
pagination.page = 0;
pagination.prevPage();
expect(pagination.page).toBe(0);
pagination.page = 1;
pagination.nextPage();
expect(pagination.page).toBe(1);
});
it('should jump to a given page id', function() {
pagination.numPages = 3;
expect(pagination.page).toBe(0);
pagination.toPageId(2);
expect(pagination.page).toBe(2);
});
});
| 'use strict';
describe('Simple Pagination', function() {
var pagination;
// load the app
beforeEach(module('SimplePagination'));
// get service
beforeEach(inject(function(Pagination) {
pagination = Pagination.getNew();
}));
it('should paginate', function() {
pagination.numPages = 2;
expect(pagination.page).toBe(0);
pagination.nextPage();
expect(pagination.page).toBe(1);
pagination.prevPage();
expect(pagination.page).toBe(0);
});
it('should not paginate outside min and max page', function() {
pagination.numPages = 2;
pagination.page = 0;
pagination.prevPage();
expect(pagination.page).toBe(0);
pagination.page = 1;
pagination.nextPage();
expect(pagination.page).toBe(1);
});
it('should jump to a given page id', function() {
pagination.numPages = 3;
expect(pagination.page).toBe(0);
pagination.toPageId(2);
expect(pagination.page).toBe(2);
});
});
| JavaScript | 0.017244 |
f6faa3bc938bb92cbe7497b228eeeba0ca256020 | Edit comment | core/tests/protractor/cacheSlugs.js | core/tests/protractor/cacheSlugs.js | // Copyright 2016 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview End-to-end tests for cache slugs.
*/
var general = require('../protractor_utils/general.js');
var ERROR_PAGE_URL_SUFFIX = '/console_errors';
var getUniqueLogMessages = function(logs) {
// Returns unique log messages.
var logsDict = {};
for (var i = 0; i < logs.length; i++) {
if (!logsDict.hasOwnProperty(logs[i].message)) {
logsDict[logs[i].message] = true;
}
}
return Object.keys(logsDict);
};
var checkConsoleErrorsExist = function(expectedErrors) {
// Checks that browser logs match entries in expectedErrors array.
browser.manage().logs().get('browser').then(function(browserLogs) {
// Some browsers such as chrome raise two errors for a missing resource.
// To keep consistent behaviour across browsers, we keep only the logs
// that have a unique value for their message attribute.
var uniqueLogMessages = getUniqueLogMessages(browserLogs);
expect(uniqueLogMessages.length).toBe(expectedErrors.length);
for (var i = 0; i < expectedErrors.length; i++) {
var errorPresent = false;
for (var j = 0; j < uniqueLogMessages.length; j++) {
if (uniqueLogMessages[j].match(expectedErrors[i])) {
errorPresent = true;
}
}
expect(errorPresent).toBe(true);
}
});
};
describe('Cache Slugs', function() {
it('should check that errors get logged for missing resources', function() {
browser.get(ERROR_PAGE_URL_SUFFIX);
var expectedErrors = [
'http://localhost:9001/build/fail/logo/288x128_logo_white.png',
// Warning fired by synchronous AJAX request in
// core/templates/dev/head/pages/header_js_libs.html.
// This warning is expected and it's needed for constants loading.
'Synchronous XMLHttpRequest on the main thread'
];
checkConsoleErrorsExist(expectedErrors);
});
});
| // Copyright 2016 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview End-to-end tests for cache slugs.
*/
var general = require('../protractor_utils/general.js');
var ERROR_PAGE_URL_SUFFIX = '/console_errors';
var getUniqueLogMessages = function(logs) {
// Returns unique log messages.
var logsDict = {};
for (var i = 0; i < logs.length; i++) {
if (!logsDict.hasOwnProperty(logs[i].message)) {
logsDict[logs[i].message] = true;
}
}
return Object.keys(logsDict);
};
var checkConsoleErrorsExist = function(expectedErrors) {
// Checks that browser logs match entries in expectedErrors array.
browser.manage().logs().get('browser').then(function(browserLogs) {
// Some browsers such as chrome raise two errors for a missing resource.
// To keep consistent behaviour across browsers, we keep only the logs
// that have a unique value for their message attribute.
var uniqueLogMessages = getUniqueLogMessages(browserLogs);
expect(uniqueLogMessages.length).toBe(expectedErrors.length);
for (var i = 0; i < expectedErrors.length; i++) {
var errorPresent = false;
for (var j = 0; j < uniqueLogMessages.length; j++) {
if (uniqueLogMessages[j].match(expectedErrors[i])) {
errorPresent = true;
}
}
expect(errorPresent).toBe(true);
}
});
};
describe('Cache Slugs', function() {
it('should check that errors get logged for missing resources', function() {
browser.get(ERROR_PAGE_URL_SUFFIX);
var expectedErrors = [
'http://localhost:9001/build/fail/logo/288x128_logo_white.png',
// Warning fired by synchronous AJAX request in
// core/templates/dev/head/pages/header_js_libs.html this warning is
// expected and it's needed for constants loading.
'Synchronous XMLHttpRequest on the main thread'
];
checkConsoleErrorsExist(expectedErrors);
});
});
| JavaScript | 0 |
7a8f39067376f44c30b688e960d980b1cafe2337 | Add 'add' to projectDeploy provided interface | core/cb.project.deploy/main.js | core/cb.project.deploy/main.js | // Requires
var _ = require('underscore');
var DeploymentSolution = require("./solution").DeploymentSolution;
// List of all deployment solution
var SUPPORTED = [];
function setup(options, imports, register) {
// Import
var logger = imports.logger.namespace("deployment");
var events = imports.events;
var workspace = imports.workspace;
// Return a specific solution
var getSolution = function(solutionId) {
return _.find(SOLUTIONS, function(solution) {
return solution.id == solutionId;
});
};
// Add a solution
var addSolution = function(solution) {
if (!_.isArray(solution)) solution = [solution];
_.each(solution, function(_sol) {
SUPPORTED.push(new DeploymentSolution(workspace, events, logger, _sol));
});
};
// Add basic solutions
addSolution([
require("./ghpages")
])
// Register
register(null, {
'projectDeploy': {
'SUPPORTED': SUPPORTED,
'get': getSolution,
'add': addSolution
}
});
}
// Exports
module.exports = setup;
| // Requires
var _ = require('underscore');
var DeploymentSolution = require("./solution").DeploymentSolution;
// List of all deployment solution
var SUPPORTED = [];
function setup(options, imports, register) {
// Import
var logger = imports.logger.namespace("deployment");
var events = imports.events;
var workspace = imports.workspace;
// Return a specific solution
var getSolution = function(solutionId) {
return _.find(SOLUTIONS, function(solution) {
return solution.id == solutionId;
});
};
// Add a solution
var addSolution = function(solution) {
if (!_.isArray(solution)) solution = [solution];
_.each(solution, function(_sol) {
SUPPORTED.push(new DeploymentSolution(workspace, events, logger, _sol));
});
}
// Add basic solutions
addSolution([
require("./ghpages")
])
// Register
register(null, {
'projectDeploy': {
'SUPPORTED': SUPPORTED,
'get': getSolution
}
});
}
// Exports
module.exports = setup;
| JavaScript | 0.000001 |
66d067a35ed2fcaf9decaad683ebeb2f563b2117 | Add styling clases to fix buttons appearing white on iOS | src/main/web/js/app/mobile-table.js | src/main/web/js/app/mobile-table.js | $(function() {
var markdownTable = $('.markdown-table-wrap');
if (markdownTable.length) {
$('<button class="btn btn--secondary btn--mobile-table-show">View table</button>').insertAfter(markdownTable);
$('<button class="btn btn--secondary btn--mobile-table-hide">Close table</button>').insertAfter(markdownTable.find('table'));
$('.btn--mobile-table-show').click(function () {
$(this).closest('.markdown-table-container').find('.markdown-table-wrap').show();
});
$('.btn--mobile-table-hide').click(function () {
$(this).closest('.markdown-table-wrap').css('display', '');
});
}
});
| $(function() {
var markdownTable = $('.markdown-table-wrap');
if (markdownTable.length) {
$('<button class="btn btn--mobile-table-show">View table</button>').insertAfter(markdownTable);
$('<button class="btn btn--mobile-table-hide">Close table</button>').insertAfter(markdownTable.find('table'));
$('.btn--mobile-table-show').click(function () {
$(this).closest('.markdown-table-container').find('.markdown-table-wrap').show();
});
$('.btn--mobile-table-hide').click(function () {
$(this).closest('.markdown-table-wrap').css('display', '');
});
}
});
| JavaScript | 0 |
285bdf6c56f70fb2fd0a8fc7e881d244bf8a6cd0 | Remove odd html tags | src/components/NavigationBar/NavigationBar.js | src/components/NavigationBar/NavigationBar.js | import React from 'react'
import {
Link
} from 'react-router-dom';
import './navigation-bar.css';
import { isAuthenticated } from '../../helper/auth';
import * as firebase from 'firebase';
class NavigationBar extends React.Component {
signout() {
firebase.auth().signOut();
}
authenticated() {
return (
<nav className="navigation-bar glow">
<div className="navigation-bar__item--flex">
<Link className="navigation-bar__link" to="/">Biografia</Link>
</div>
<div className="navigation-bar__item">
<Link className="navigation-bar__link" to="/admin">Admin</Link>
<a className="navigation-bar__link" onClick={this.signout} >Sign Out</a>
</div>
</nav>
)
}
unauthenticated() {
return (
<nav className="navigation-bar">
<div className="navigation-bar__item--flex">
<Link className="navigation-bar__link" to="/">Biografia</Link>
</div>
<div className="navigation-bar__item">
<Link className="navigation-bar__link" to="/signin">Sign In</Link>
</div>
</nav>
)
}
render() {
if (isAuthenticated()) {
return this.authenticated();
} else {
return this.unauthenticated();
}
}
}
export { NavigationBar }
| import React from 'react'
import {
Link
} from 'react-router-dom';
import './navigation-bar.css';
import { isAuthenticated } from '../../helper/auth';
import * as firebase from 'firebase';
class NavigationBar extends React.Component {
signout() {
firebase.auth().signOut();
}
authenticated() {
return (
<div className="navigation-bar__wrapper">
<div className="navigation-bar__placeholder"></div>
<nav className="navigation-bar">
<div className="navigation-bar__item--flex">
<Link className="navigation-bar__link" to="/">Home</Link>
</div>
<div className="navigation-bar__item">
<Link className="navigation-bar__link" to="/admin">Admin</Link>
<a className="navigation-bar__link" onClick={this.signout} >Sign Out</a>
</div>
</nav>
</div>
)
}
unauthenticated() {
return (
<div className="navigation-bar__wrapper">
<div className="navigation-bar__placeholder"></div>
<nav className="navigation-bar">
<div className="navigation-bar__item--flex">
<Link className="navigation-bar__link" to="/">Home</Link>
</div>
<div className="navigation-bar__item">
<Link className="navigation-bar__link" to="/signin">Sign In</Link>
</div>
</nav>
</div>
)
}
render() {
if (isAuthenticated()) {
return this.authenticated();
} else {
return this.unauthenticated();
}
}
}
export { NavigationBar }
| JavaScript | 0.999801 |
207f9e63434b1c191b8d3296e17e1bb881c580c0 | reset board on start | lib/board/index.js | lib/board/index.js | import bus from 'component/bus'
import Board from 'kvnneff/bloxparty-board@1.0.3-alpha'
export default function plugin () {
return function (app) {
var board = new Board()
app.set('board', board.json())
board.on('change', function () {
app.set('board', board.json())
})
bus.on('player:move', function (direction) {
board.move(direction)
})
bus.on('game:begin', function () {
board.reset()
board.start()
})
bus.on('client', function (data) {
board.sync(data.board)
})
bus.on('game:stop', function () {
board.stop()
})
}
}
| import bus from 'component/bus'
import Board from 'kvnneff/bloxparty-board@1.0.3-alpha'
export default function plugin () {
return function (app) {
var board = new Board()
app.set('board', board.json())
board.on('change', function () {
app.set('board', board.json())
})
bus.on('player:move', function (direction) {
board.move(direction)
})
bus.on('game:begin', function () {
board.start()
})
bus.on('client', function (data) {
board.sync(data.board)
})
bus.on('game:stop', function () {
board.stop()
})
}
}
| JavaScript | 0.000001 |
95fb0e2af62acc4b3ea4d88e1832325807467143 | Put initialization in a separate callable function. | www/googleplayservices.js | www/googleplayservices.js | var argscheck = require ('cordova/argscheck')
var exec = require ('cordova/exec')
module.exports = function () {
var exports = {}
exports.getPlayerId = function (init) {
var success = (typeof init.success != "undefined") ? init.success : function () {}
var error = (typeof init.error != "undefined") ? init.error : function () {}
cordova.exec (success, error, "GooglePlayServices", "getPlayerId", [])
}
exports.initialize = function (init) {
var success = (typeof init.success != "undefined") ? init.success : function () {}
var error = (typeof init.error != "undefined") ? init.error : function () {}
cordova.exec (success, error, "GooglePlayServices", "initialize", [])
}
return exports
} ()
| var argscheck = require ('cordova/argscheck')
var exec = require ('cordova/exec')
module.exports = function () {
var exports = {}
exports.getPlayerId = function (init) {
var success = (typeof init.success != "undefined") ? init.success : function () {}
var error = (typeof init.error != "undefined") ? init.error : function () {}
cordova.exec (success, error, "GooglePlayServices", "getPlayerId", [])
}
return exports
} () | JavaScript | 0 |
ded1e02da7a42aaa5ea0a4414d9ebac7d986995f | move buildHelpers require down a slot | packages/build-runtime.js | packages/build-runtime.js | "use strict";
var transform = require("../lib/babel/transformation");
var buildHelpers = require("../lib/babel/build-helpers");
var util = require("../lib/babel/util");
var fs = require("fs");
var t = require("../lib/babel/types");
var _ = require("lodash");
var relative = function (filename) {
return __dirname + "/babel-runtime/" + filename;
};
var writeFile = function (filename, content) {
filename = relative(filename);
console.log(filename);
fs.writeFileSync(filename, content);
};
var readFile = function (filename, defaultify) {
var file = fs.readFileSync(require.resolve(filename), "utf8");
if (defaultify) {
file += '\nmodule.exports = { "default": module.exports, __esModule: true };\n';
}
return file;
};
var updatePackage = function () {
var pkgLoc = relative("package.json");
var pkg = require(pkgLoc);
var mainPkg = require("../package.json");
pkg.version = mainPkg.version;
writeFile("package.json", JSON.stringify(pkg, null, 2));
};
var selfContainify = function (code) {
return transform(code, {
optional: ["selfContained"]
}).code;
};
var buildHelpers2 = function () {
var body = util.template("self-contained-helpers-head");
var tree = t.program(body);
buildHelpers(body, t.identifier("helpers"));
return transform.fromAst(tree, null, {
optional: ["selfContained"]
}).code;
};
writeFile("helpers.js", buildHelpers2());
writeFile("core-js.js", readFile("core-js/library", true));
writeFile("regenerator/index.js", readFile("regenerator-babel/runtime-module", true));
writeFile("regenerator/runtime.js", selfContainify(readFile("regenerator-babel/runtime")));
updatePackage();
| "use strict";
var buildHelpers = require("../lib/babel/build-helpers");
var transform = require("../lib/babel/transformation");
var util = require("../lib/babel/util");
var fs = require("fs");
var t = require("../lib/babel/types");
var _ = require("lodash");
var relative = function (filename) {
return __dirname + "/babel-runtime/" + filename;
};
var writeFile = function (filename, content) {
filename = relative(filename);
console.log(filename);
fs.writeFileSync(filename, content);
};
var readFile = function (filename, defaultify) {
var file = fs.readFileSync(require.resolve(filename), "utf8");
if (defaultify) {
file += '\nmodule.exports = { "default": module.exports, __esModule: true };\n';
}
return file;
};
var updatePackage = function () {
var pkgLoc = relative("package.json");
var pkg = require(pkgLoc);
var mainPkg = require("../package.json");
pkg.version = mainPkg.version;
writeFile("package.json", JSON.stringify(pkg, null, 2));
};
var selfContainify = function (code) {
return transform(code, {
optional: ["selfContained"]
}).code;
};
var buildHelpers2 = function () {
var body = util.template("self-contained-helpers-head");
var tree = t.program(body);
buildHelpers(body, t.identifier("helpers"));
return transform.fromAst(tree, null, {
optional: ["selfContained"]
}).code;
};
writeFile("helpers.js", buildHelpers2());
writeFile("core-js.js", readFile("core-js/library", true));
writeFile("regenerator/index.js", readFile("regenerator-babel/runtime-module", true));
writeFile("regenerator/runtime.js", selfContainify(readFile("regenerator-babel/runtime")));
updatePackage();
| JavaScript | 0 |
cb9bc30842fdededbb25f7e627e8f3f84eb151a4 | Fix failing test | tests/pages/jobs/JobsOverview-cy.js | tests/pages/jobs/JobsOverview-cy.js | describe('Jobs Overview', function () {
context('Jobs page loads correctly', function () {
beforeEach(function () {
cy.configureCluster({
mesos: '1-for-each-health',
nodeHealth: true
});
cy.visitUrl({url: '/jobs'});
});
it('has the right active navigation entry', function () {
cy.get('.page-header-navigation .tab-item.active')
.should('to.have.text', 'Jobs');
});
it('displays empty jobs overview page', function () {
cy.get('.page-content .panel-content h3')
.should('to.have.text', 'No Jobs Created');
});
});
});
| describe('Jobs Overview', function () {
context('Jobs page loads correctly', function () {
beforeEach(function () {
cy.configureCluster({
mesos: '1-for-each-health',
nodeHealth: true
});
cy.visitUrl({url: '/jobs'});
});
it('has the right active navigation entry', function () {
cy.get('.page-header-navigation .tab-item.active')
.should('to.have.text', 'Jobs');
});
it('displays empty jobs overview page', function () {
cy.get('.page-content .panel-content h3')
.should('to.have.text', 'No Jobs Found');
});
});
});
| JavaScript | 0.000209 |
8bf416778ad35f9c96c76de2db451fc3924de8f9 | Fix little typo | plugins/weather.js | plugins/weather.js | /** Created on May 6, 2014
* author: MrPoxipol
*/
var http = require('http');
var util = require('util');
// Templates module
var Mustache = require('mustache');
var debug = require('../nibo/debug');
const COMMAND_NAME = 'weather';
// pattern for util.format()
const API_URL_PATTERN = 'http://api.openweathermap.org/data/2.5/weather?q=%s&lang=eng';
exports.meta = {
name: 'weather',
commandName: COMMAND_NAME,
description: 'Fetches actual weather conditions from openweathermap.org at specific place on the Earth'
};
function kelvinsToCelcius(temperature) {
return Math.round(temperature - 273.15);
}
function calcWindChill(temperature, windSpeed) {
if (temperature < 10 && (windSpeed / 3.6) >= 1.8) {
var windChill = (13.12 + 0.6215 * temperature - 11.37 * Math.pow(windSpeed, 0.16) + 0.3965 * temperature * Math.pow(windSpeed, 0.16));
windChill = Math.round(windChill);
}
return null;
}
function getWeatherFromJson(data) {
var parsedJson;
try {
parsedJson = JSON.parse(data);
} catch (e) {
debug.debug('JSON parsing error');
return;
}
var weather = {
city: parsedJson.name
};
if (!weather.city) {
return;
}
weather.country = parsedJson.sys.country;
weather.temp = kelvinsToCelcius(parsedJson.main.temp);
weather.description = parsedJson.weather[0].description;
weather.windSpeed = parsedJson.wind.speed;
weather.pressure = Math.round(parsedJson.main.pressure);
weather.windChill = calcWindChill(weather.temp, weather.windSpeed);
var pattern;
if (weather.windChill !== null)
pattern = '[{{&city}}, {{&country}}]: {{&temp}}°C (felt as {{&windChill}}°C) - {{&description}}, {{&pressure}} hPa';
else
pattern = '[{{&city}}, {{&country}}]: {{&temp}}°C - {{&description}}, {{&pressure}} hPa';
var output = Mustache.render(pattern, weather);
return output;
}
function sendResponse(bot, args, message) {
bot.sayToUser(args.channel, args.user.nick, message);
}
function fetchWeather(bot, args) {
args.place = encodeURIComponent(args.place);
var url = util.format(API_URL_PATTERN, args.place);
http.get(url, function (response) {
var responseParts = [];
response.setEncoding('utf8');
response.on('data', function (chunk) {
responseParts.push(chunk);
});
response.on('end', function () {
var data = responseParts.join('');
var message = getWeatherFromJson(data);
if (message) {
sendResponse(bot, args, message);
} else {
sendResponse(bot,
args,
util.format('[%s] Could not find weather information.', decodeURIComponent(args.place))
);
}
});
}).on('error', function (e) {
debug.error('HTTP ' + e.message);
sendResponse(bot, args, '[] Weather is not available at the moment.');
});
}
exports.onCommand = function (bot, user, channel, command) {
if (command.name !== COMMAND_NAME)
return;
if (command.args.length < 1)
return;
var args = {
user: user,
channel: channel,
place: command.args.join(' '),
};
fetchWeather(bot, args);
}; | /** Created on May 6, 2014
* author: MrPoxipol
*/
var http = require('http');
var util = require('util');
// Templates module
var Mustache = require('mustache');
var debug = require('../nibo/debug');
const COMMAND_NAME = 'weather';
// pattern for util.format()
const API_URL_PATTERN = 'http://api.openweathermap.org/data/2.5/weather?q=%s&lang=eng';
exports.meta = {
name: 'weather',
commandName: COMMAND_NAME,
description: 'Fetches actual weather conditions from openweathermap.org at specific place on the Earth'
};
function kelvinsToCelcius(temperature) {
return Math.round(temperature - 273.15);
}
function calcWindChill(temperature, windSpeed) {
if (temperature < 10 && (windSpeed / 3.6) >= 1.8) {
var windChill = (13.12 + 0.6215 * temperature - 11.37 * Math.pow(windSpeed, 0.16) + 0.3965 * temperature * Math.pow(windSpeed, 0.16));
windChill = Math.round(windChill);
}
return null;
}
function getWeatherFromJson(data) {
var parsedJson;
try {
parsedJson = JSON.parse(data);
} catch (e) {
debug.debug('JSON parsing error');
return;
}
var weather = {
city: parsedJson.name
};
if (!weather.city) {
return;
}
weather.country = parsedJson.sys.country;
weather.temp = kelvinsToCelcius(parsedJson.main.temp);
weather.description = parsedJson.weather[0].description;
weather.windSpeed = parsedJson.wind.speed;
weather.pressure = Math.round(parsedJson.main.pressure);
weather.windChill = calcWindChill(weather.temp, weather.windSpeed);
var pattern;
if (weather.windChill !== null)
pattern = '[{{&city}}, {{&country}}]: {{&temp}}°C (felt as {{&windChill}}°C) - {{&description}}, {{&pressure}} hPa';
else
pattern = '[{{&city}}, {{&country}}]: {{&temp}}°C - {{&description}}, {{&pressure}} hPa';
var output = Mustache.render(pattern, weather);
return output;
}
function sendResponse(bot, args, message) {
bot.sayToUser(args.channel, args.user.nick, message);
}
function fetchWeather(bot, args) {
args.place = encodeURIComponent(args.place);
var url = util.format(API_URL_PATTERN, args.place);
http.get(url, function (response) {
var responseParts = [];
response.setEncoding('utf8');
response.on('data', function (chunk) {
responseParts.push(chunk);
});
response.on('end', function () {
var data = responseParts.join('');
var message = getWeatherFromJson(data);
if (message) {
sendResponse(bot, args, message);
} else {
sendResponse(bot,
args,
util.format('[%s] Could not find weather information.', decodeURIComponent(args.place))
);
}
});
}).on('error', function (e) {
debug.error('HTTP ' + e.message);
sendResponse(bot, args, '[] Weather is not avaiable at the moment.');
});
}
exports.onCommand = function (bot, user, channel, command) {
if (command.name !== COMMAND_NAME)
return;
if (command.args.length < 1)
return;
var args = {
user: user,
channel: channel,
place: command.args.join(' '),
};
fetchWeather(bot, args);
}; | JavaScript | 0.999968 |
93a63d4371249b1d3d8f0c934153804261d6e072 | add promise rejection error reporting | client/scripts/arcademode/actions/test.js | client/scripts/arcademode/actions/test.js |
'use strict';
export const OUTPUT_CHANGED = 'OUTPUT_CHANGED';
export const TESTS_STARTED = 'TESTS_STARTED';
export const TESTS_FINISHED = 'TESTS_FINISHED';
export function onOutputChange(newOutput) {
return {
type: OUTPUT_CHANGED,
userOutput: newOutput
};
}
/* Thunk action which runs the test cases against user code. */
export function runTests(userCode, currChallenge) {
return dispatch => {
dispatch(actionTestsStarted());
// Eval user code inside worker
// http://stackoverflow.com/questions/9020116/is-it-possible-to-restrict-the-scope-of-a-javascript-function/36255766#36255766
function createWorker () {
return new Promise((resolve, reject) => {
const wk = new Worker('../../public/js/worker.bundle.js');
wk.postMessage([userCode, currChallenge.toJS()]); // postMessage mangles the Immutable object, so it needs to be transformed into regular JS before sending over to worker.
wk.onmessage = e => {
// console.log(`worker onmessage result: ${e.data}`);
resolve(e.data);
};
});
}
return createWorker()
.then(workerData => {
dispatch(onOutputChange(workerData[0].output));
if (workerData.length > 1) {
dispatch(actionTestsFinished(workerData.slice(1)));
}
})
.catch(err => { console.log(`Promise rejected: ${err}.`); });
};
}
/* Dispatched when a user starts running the tests.*/
export function actionTestsStarted () {
return {
type: TESTS_STARTED
};
}
/* Dispatched when the tests finish. */
export function actionTestsFinished (testResults) {
return {
type: TESTS_FINISHED,
testResults
};
}
|
'use strict';
export const OUTPUT_CHANGED = 'OUTPUT_CHANGED';
export const TESTS_STARTED = 'TESTS_STARTED';
export const TESTS_FINISHED = 'TESTS_FINISHED';
export function onOutputChange(newOutput) {
return {
type: OUTPUT_CHANGED,
userOutput: newOutput
};
}
/* Thunk action which runs the test cases against user code. */
export function runTests(userCode, currChallenge) {
return dispatch => {
dispatch(actionTestsStarted());
// Eval user code inside worker
// http://stackoverflow.com/questions/9020116/is-it-possible-to-restrict-the-scope-of-a-javascript-function/36255766#36255766
function createWorker () {
return new Promise((resolve, reject) => {
const wk = new Worker('../../public/js/worker.bundle.js');
wk.postMessage([userCode, currChallenge.toJS()]); // postMessage mangles the Immutable object, so it needs to be transformed into regular JS before sending over to worker.
wk.onmessage = e => {
// console.log(`worker onmessage result: ${e.data}`);
resolve(e.data);
};
});
}
return createWorker()
.then(workerData => {
dispatch(onOutputChange(workerData[0].output));
if (workerData.length > 1) {
dispatch(actionTestsFinished(workerData.slice(1)));
}
});
};
}
/* Dispatched when a user starts running the tests.*/
export function actionTestsStarted () {
return {
type: TESTS_STARTED
};
}
/* Dispatched when the tests finish. */
export function actionTestsFinished (testResults) {
return {
type: TESTS_FINISHED,
testResults
};
}
| JavaScript | 0 |
2fd85899d20ad2d15555c6975f16e095dfc348f3 | add exception handling for cloudflare error. | lib/courier/jnt.js | lib/courier/jnt.js | 'use strict'
var request = require('request')
var moment = require('moment')
var tracker = require('../')
var trackingInfo = function (number) {
return {
method: 'POST',
url: 'https://www.jtexpress.ph/index/router/index.html',
json: true,
body: {
method: 'app.findTrack',
data: {
billcode: number,
lang: 'en',
source: 3
}
}
}
}
var parser = {
trace: function (data) {
var courier = {
code: tracker.COURIER.JNT.CODE,
name: tracker.COURIER.JNT.NAME
}
var result = {
courier: courier,
number: data.billcode,
status: tracker.STATUS.PENDING
}
var checkpoints = []
for (var i = 0; i < data.details.length; i++) {
var item = data.details[i]
var message = [
item.desc
].join(' - ')
var checkpoint = {
courier: courier,
location: item.city || item.siteName,
message: message,
status: tracker.STATUS.IN_TRANSIT,
time: moment(item.scantime + 'T+0800', 'YYYY-MM-DD HH:mm:ssZ').utc().format('YYYY-MM-DDTHH:mmZ')
}
if (item.scantype === 'Delivered') {
checkpoint.status = tracker.STATUS.DELIVERED
}
checkpoints.push(checkpoint)
}
result.checkpoints = checkpoints
result.status = tracker.normalizeStatus(result.checkpoints)
return result
}
}
module.exports = function () {
return {
trackingInfo: trackingInfo,
trace: function (number, cb) {
var tracking = trackingInfo(number)
request(tracking, function (err, res, body) {
if (err) {
return cb(err)
}
try {
if (res.statusCode !== 200) {
return cb(tracker.error(res.statusMessage))
}
var result = parser.trace(JSON.parse(body.data))
cb(result ? null : tracker.error(tracker.ERROR.INVALID_NUMBER), result)
} catch (e) {
cb(tracker.error(e.message))
}
})
}
}
}
| 'use strict'
var request = require('request')
var moment = require('moment')
var tracker = require('../')
var trackingInfo = function (number) {
return {
method: 'POST',
url: 'https://www.jtexpress.ph/index/router/index.html',
json: true,
body: {
method: 'app.findTrack',
data: {
billcode: number,
lang: 'en',
source: 3
}
}
}
}
var parser = {
trace: function (data) {
var courier = {
code: tracker.COURIER.JNT.CODE,
name: tracker.COURIER.JNT.NAME
}
var result = {
courier: courier,
number: data.billcode,
status: tracker.STATUS.PENDING
}
var checkpoints = []
for (var i = 0; i < data.details.length; i++) {
var item = data.details[i]
var message = [
item.desc
].join(' - ')
var checkpoint = {
courier: courier,
location: item.city || item.siteName,
message: message,
status: tracker.STATUS.IN_TRANSIT,
time: moment(item.scantime + 'T+0800', 'YYYY-MM-DD HH:mm:ssZ').utc().format('YYYY-MM-DDTHH:mmZ')
}
if (item.scantype === 'Delivered') {
checkpoint.status = tracker.STATUS.DELIVERED
}
checkpoints.push(checkpoint)
}
result.checkpoints = checkpoints
result.status = tracker.normalizeStatus(result.checkpoints)
return result
}
}
module.exports = function () {
return {
trackingInfo: trackingInfo,
trace: function (number, cb) {
var tracking = trackingInfo(number)
request(tracking, function (err, res, body) {
if (err) {
return cb(err)
}
try {
var result = parser.trace(JSON.parse(body.data))
cb(result ? null : tracker.error(tracker.ERROR.INVALID_NUMBER), result)
} catch (e) {
cb(tracker.error(e.message))
}
})
}
}
}
| JavaScript | 0 |
138ad3b71603f2f1ce7a05954c2e065b41d339cb | Update to ES6 syntax | client/webpack.production.config.babel.js | client/webpack.production.config.babel.js | /* global __dirname */
import path from "path";
import webpack from "webpack";
import HTMLPlugin from "html-webpack-plugin";
import CleanPlugin from "clean-webpack-plugin";
import ExtractTextPlugin from "extract-text-webpack-plugin";
import UglifyJSPlugin from "uglifyjs-webpack-plugin";
export default {
entry: ["babel-polyfill", "./src/js/index.js"],
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
use: [
"babel-loader",
{
loader: "eslint-loader",
options: {
configFile: path.resolve(__dirname, "./.eslintrc")
}
}
]
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
},
{
test: /\.less$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: [
{loader: "css-loader"},
{loader: "less-loader"}
]
})
},
{
test: /\.woff$/,
use: {
loader: "url-loader?limit=100000"
}
}
]
},
node: {
fs: "empty"
},
mode: "production",
output: {
path: path.resolve(__dirname, "./dist"),
filename: "app.[hash:8].js",
sourceMapFilename: "[name].js.map",
publicPath: "/static/"
},
plugins: [
new webpack.DefinePlugin({
"process.env.NODE_ENV": JSON.stringify("production")
}),
new ExtractTextPlugin("style.[hash:8].css"),
new HTMLPlugin({
filename: "index.html",
title: "Virtool",
favicon: "./src/images/favicon.ico",
template: "./src/index.html",
inject: "body"
}),
new CleanPlugin(["dist"], {
verbose: true
}),
new UglifyJSPlugin({
sourceMap: true
})
]
};
| /* global module, __dirname */
import path from "path";
import webpack from "webpack";
import HTMLPlugin from "html-webpack-plugin";
import CleanPlugin from "clean-webpack-plugin";
import ExtractTextPlugin from "extract-text-webpack-plugin";
import UglifyJSPlugin from "uglifyjs-webpack-plugin";
module.exports = {
entry: ["babel-polyfill", "./src/js/index.js"],
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
use: [
"babel-loader",
{
loader: "eslint-loader",
options: {
configFile: path.resolve(__dirname, "./.eslintrc")
}
}
]
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
},
{
test: /\.less$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: [
{loader: "css-loader"},
{loader: "less-loader"}
]
})
},
{
test: /\.woff$/,
use: {
loader: "url-loader?limit=100000"
}
}
]
},
node: {
fs: "empty"
},
mode: "production",
output: {
path: path.resolve(__dirname, "./dist"),
filename: "app.[hash:8].js",
sourceMapFilename: "[name].js.map",
publicPath: "/static/"
},
plugins: [
new webpack.DefinePlugin({
"process.env.NODE_ENV": JSON.stringify("production")
}),
new ExtractTextPlugin("style.[hash:8].css"),
new HTMLPlugin({
filename: "index.html",
title: "Virtool",
favicon: "./src/images/favicon.ico",
template: "./src/index.html",
inject: "body"
}),
new CleanPlugin(["dist"], {
verbose: true
}),
new UglifyJSPlugin({
sourceMap: true
})
]
};
| JavaScript | 0 |
7b2b3e9dfbf805da61b1e957e71bdd3bad0352dc | Fix typo | server/lib/client-info.js | server/lib/client-info.js | /**
* Client info keyed on client id. Mainly used for logging.
* Getting full details about a client is a multi-part process
* since we get partial info when they request a token, and more
* when they finally connect/authenticate over the web socket.
*/
var useragent = require('useragent');
var log = require('./logger.js');
function ClientInfo(id, userAgentString) {
this.id = id;
// User isn't yet known, we'll update this in update() later
this.username = 'unauthenticated';
// Try to extract useful browser/device info
try {
var agent = useragent.parse(userAgentString);
this.agent = agent.toString();
this.device = agent.device.toString();
} catch(err) {
log.error({err: err}, 'Error parsing user agent string: `%s`', userAgentString);
this.agent = "Unknown";
this.device = "Unknown";
}
this.born = Date.now();
// How many times this client has sync'ed during this connection.
this.downstreamSyncs = 0;
this.upstreamSyncs = 0;
// Web Socket data usage for this client
this.bytesSent = 0;
this.bytesReceived = 0;
}
// How long this client has been connected in MS
ClientInfo.prototype.connectedInMS = function() {
return Date.now() - this.born;
};
/**
* Keep track of client info objects while they are still connected.
*/
var clients = {};
function remove(id) {
delete clients[id];
}
function find(client) {
return clients[client.id];
}
/**
* Step 1: create a partial ClientInfo object when the client requests a token
*/
function init(id, userAgentString) {
clients[id] = new ClientInfo(id, userAgentString);
}
/**
* Step 2: update the ClientInfo object with all the client info when
* web socket connection is completed.
*/
function update(client) {
var id = client.id;
// Auto-remove when this client is closed.
client.once('closed', function() {
remove(id);
});
var info = find(client);
if(!info) {
log.warn('No ClientInfo object found for client.id=%s', id);
return;
}
info.username = client.username;
}
module.exports = {
init: init,
update: update,
remove: remove,
find: find
};
| /**
* Client info keyed on client id. Mainly used for logging.
* Getting full details about a client is a multi-part process
* since we get partial info when they request a token, and more
* when they finally connect/authenticate over the web socket.
*/
var useragent = require('useragent');
var log = require('./logger.js');
function ClientInfo(id, userAgentString) {
this.id = id;
// User isn't yet known, we'll update this in update() later
this.username = 'unauthenticated';
// Try to extract useful browser/device info
try {
var agent = useragent.parse(userAgentString);
this.agent = agent.toString();
this.device = agent.device.toString();
} catch(err) {
log.error({err: err}, 'Error parsing user agent string: `%s`', userAgentString);
this.agent = "Unknown";
this.device = "Unknown";
}
this.born = Date.now();
// How many times this client has sync'ed during this connection.
this.downstreamSyncs = 0;
this.upstreamSyncs = 0;
// Web Socket data usage for this client
this.bytesSent = 0;
this.bytesRecevied = 0;
}
// How long this client has been connected in MS
ClientInfo.prototype.connectedInMS = function() {
return Date.now() - this.born;
};
/**
* Keep track of client info objects while they are still connected.
*/
var clients = {};
function remove(id) {
delete clients[id];
}
function find(client) {
return clients[client.id];
}
/**
* Step 1: create a partial ClientInfo object when the client requests a token
*/
function init(id, userAgentString) {
clients[id] = new ClientInfo(id, userAgentString);
}
/**
* Step 2: update the ClientInfo object with all the client info when
* web socket connection is completed.
*/
function update(client) {
var id = client.id;
// Auto-remove when this client is closed.
client.once('closed', function() {
remove(id);
});
var info = find(client);
if(!info) {
log.warn('No ClientInfo object found for client.id=%s', id);
return;
}
info.username = client.username;
}
module.exports = {
init: init,
update: update,
remove: remove,
find: find
};
| JavaScript | 0.999999 |
205dba7e0e4a828ae27a4b08af3c67186e162a7a | Improve variable names | server/lib/userSession.js | server/lib/userSession.js | //
// Copyright 2014 Ilkka Oksanen <iao@iki.fi>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS
// IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language
// governing permissions and limitations under the License.
//
'use strict';
const User = require('../models/user');
exports.auth = function *auth(next) {
const cookie = this.cookies.get('auth') || '';
const ts = new Date();
this.mas = this.mas || {};
this.mas.user = null;
const [ userId, secret ] = cookie.split('-');
if (userId && secret) {
const user = yield User.fetch(parseInt(userId));
if (user && user.get('secretExpires') > ts && user.get('secret') === secret) {
this.mas.user = user;
}
}
yield next;
};
| //
// Copyright 2014 Ilkka Oksanen <iao@iki.fi>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS
// IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language
// governing permissions and limitations under the License.
//
'use strict';
const user = require('../models/user');
exports.auth = function *auth(next) {
const cookie = this.cookies.get('auth') || '';
const ts = new Date();
this.mas = this.mas || {};
this.mas.user = null;
const [ userId, secret ] = cookie.split('-');
if (userId && secret) {
const userRecord = yield user.fetch(parseInt(userId));
if (userRecord && userRecord.get('secretExpires') > ts &&
userRecord.get('secret') === secret) {
this.mas.user = userRecord;
}
}
yield next;
};
| JavaScript | 0.998747 |
55be56e6a4d27d717954a93e4043a04705ad06af | use https for transifex download | tools/downloadLanguages.js | tools/downloadLanguages.js | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
Environment Variables
USERNAME - valid Transifex user name with read privileges
PASSWORD - password for above username
LANG [optional] - single language code to retrieve in xx-XX format (I.e. en-US)
*/
'use strict'
const path = require('path')
const fs = require('fs')
const request = require('request')
// The names of the directories in the locales folder are used as a list of languages to retrieve
var languages = fs.readdirSync(path.join(__dirname, '..', 'app', 'extensions', 'brave', 'locales')).filter(function (language) {
return language !== 'en-US'
}).map(function (language) {
return language.replace('-', '_')
})
// Support retrieving a single language
if (process.env.LANG_CODE) {
languages = [process.env.LANG_CODE]
}
if (process.env.META) {
var localLanguages = fs.readdirSync(path.join(__dirname, '..', 'app', 'extensions', 'brave', 'locales'))
console.log(` <meta name="availableLanguages" content="${localLanguages.join(', ')}">`)
console.log(localLanguages.map(function (l) {
return `'${l}'`
}).join(',\n '))
process.exit(0)
}
// Setup the credentials
const username = process.env.USERNAME
const password = process.env.PASSWORD
if (!(username && password)) {
throw new Error('The USERNAME and PASSWORD environment variables must be set to the Transifex credentials')
}
// URI and resource list
const TEMPLATE = 'https://www.transifex.com/api/2/project/brave-laptop/resource/RESOURCE_SLUG/translation/LANG_CODE/?file'
// Retrieve resource names dynamically
var resources = fs.readdirSync(path.join(__dirname, '..', 'app', 'extensions', 'brave', 'locales', 'en-US')).map(function (language) {
return language.split(/\./)[0]
})
// For each language / resource combination
languages.forEach(function (languageCode) {
resources.forEach(function (resource) {
// Build the URI
var URI = TEMPLATE.replace('RESOURCE_SLUG', resource + 'properties')
URI = URI.replace('LANG_CODE', languageCode)
// Authorize and request the translation file
request.get(URI, {
'auth': {
'user': username,
'pass': password,
'sendImmediately': true
}
}, function (error, response, body) {
if (error) {
// Report errors (often timeouts)
console.log(error.toString())
} else {
if (response.statusCode === 401) {
throw new Error('Unauthorized - Are the USERNAME and PASSWORD env vars set correctly?')
}
// Check to see if the directory exists, if not create it
var directory = path.join(__dirname, '..', 'app', 'extensions', 'brave', 'locales', languageCode.replace('_', '-'))
if (!fs.existsSync(directory)) {
console.log(`${languageCode} does not exist - creating directory`)
if (!process.env.TEST) {
fs.mkdirSync(directory)
} else {
console.log(`${languageCode} would have been created`)
}
} else {
// Directory exists - continue
}
// Build the filename and store the translation file
var filename = path.join(__dirname, '..', 'app', 'extensions', 'brave', 'locales', languageCode.replace('_', '-'), resource + '.properties')
console.log('[*] ' + filename)
if (process.env.TEST) {
console.log(body)
} else {
fs.writeFileSync(filename, body)
}
}
})
})
})
| /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
Environment Variables
USERNAME - valid Transifex user name with read privileges
PASSWORD - password for above username
LANG [optional] - single language code to retrieve in xx-XX format (I.e. en-US)
*/
'use strict'
const path = require('path')
const fs = require('fs')
const request = require('request')
// The names of the directories in the locales folder are used as a list of languages to retrieve
var languages = fs.readdirSync(path.join(__dirname, '..', 'app', 'extensions', 'brave', 'locales')).filter(function (language) {
return language !== 'en-US'
}).map(function (language) {
return language.replace('-', '_')
})
// Support retrieving a single language
if (process.env.LANG_CODE) {
languages = [process.env.LANG_CODE]
}
if (process.env.META) {
var localLanguages = fs.readdirSync(path.join(__dirname, '..', 'app', 'extensions', 'brave', 'locales'))
console.log(` <meta name="availableLanguages" content="${localLanguages.join(', ')}">`)
console.log(localLanguages.map(function (l) {
return `'${l}'`
}).join(',\n '))
process.exit(0)
}
// Setup the credentials
const username = process.env.USERNAME
const password = process.env.PASSWORD
if (!(username && password)) {
throw new Error('The USERNAME and PASSWORD environment variables must be set to the Transifex credentials')
}
// URI and resource list
const TEMPLATE = 'http://www.transifex.com/api/2/project/brave-laptop/resource/RESOURCE_SLUG/translation/LANG_CODE/?file'
// Retrieve resource names dynamically
var resources = fs.readdirSync(path.join(__dirname, '..', 'app', 'extensions', 'brave', 'locales', 'en-US')).map(function (language) {
return language.split(/\./)[0]
})
// For each language / resource combination
languages.forEach(function (languageCode) {
resources.forEach(function (resource) {
// Build the URI
var URI = TEMPLATE.replace('RESOURCE_SLUG', resource + 'properties')
URI = URI.replace('LANG_CODE', languageCode)
// Authorize and request the translation file
request.get(URI, {
'auth': {
'user': username,
'pass': password,
'sendImmediately': true
}
}, function (error, response, body) {
if (error) {
// Report errors (often timeouts)
console.log(error.toString())
} else {
if (response.statusCode === 401) {
throw new Error('Unauthorized - Are the USERNAME and PASSWORD env vars set correctly?')
}
// Check to see if the directory exists, if not create it
var directory = path.join(__dirname, '..', 'app', 'extensions', 'brave', 'locales', languageCode.replace('_', '-'))
if (!fs.existsSync(directory)) {
console.log(`${languageCode} does not exist - creating directory`)
if (!process.env.TEST) {
fs.mkdirSync(directory)
} else {
console.log(`${languageCode} would have been created`)
}
} else {
// Directory exists - continue
}
// Build the filename and store the translation file
var filename = path.join(__dirname, '..', 'app', 'extensions', 'brave', 'locales', languageCode.replace('_', '-'), resource + '.properties')
console.log('[*] ' + filename)
if (process.env.TEST) {
console.log(body)
} else {
fs.writeFileSync(filename, body)
}
}
})
})
})
| JavaScript | 0 |
d6ae29f4d18462b2b150fba0e12d3b42960fca20 | Test cases for default code version | tests/unit/services/rollbar-test.js | tests/unit/services/rollbar-test.js | import { moduleFor, test } from 'ember-qunit';
import Ember from 'ember';
import Rollbar from 'rollbar';
moduleFor('service:rollbar', 'Unit | Service | rollbar', {
needs: ['config:environment']
});
test('it exists', function(assert) {
let service = this.subject();
assert.ok(service);
});
test('notifier', function(assert) {
let service = this.subject();
assert.ok(service.get('notifier') instanceof Rollbar);
});
test('critical', function(assert) {
let service = this.subject();
let uuid = service.critical('My error message').uuid;
assert.ok(uuid);
});
test('error', function(assert) {
let service = this.subject();
let uuid = service.error('My error message').uuid;
assert.ok(uuid);
});
test('warning', function(assert) {
let service = this.subject();
let uuid = service.warning('My error message').uuid;
assert.ok(uuid);
});
test('info', function(assert) {
let service = this.subject();
let uuid = service.info('My error message').uuid;
assert.ok(uuid);
});
test('debug', function(assert) {
let service = this.subject();
let uuid = service.debug('My error message').uuid;
assert.ok(uuid);
});
test('config with default value for code version', function(assert) {
let service = this.subject();
let currentVersion = Ember.getOwner(this).resolveRegistration('config:environment').APP.version
assert.equal(service.get('config').code_version, currentVersion);
});
test('config custom value for code version', function(assert) {
let service = this.subject({
config: {
code_version: '1.2.3'
}
});
assert.equal(service.get('config').code_version, '1.2.3');
});
test('registerLogger: register error handler for Ember errors if enabled', function(assert) {
assert.expect(2);
let service = this.subject({
config: {
enabled: true
},
error(message) {
assert.ok(true, 'error handler is called');
assert.equal(message, 'foo', 'error is passed to error handler as argument');
}
});
service.registerLogger();
Ember.onerror('foo');
});
test('registerLogger: does not override previous hook', function(assert) {
assert.expect(4);
let service = this.subject({
config: {
enabled: true
},
error(message) {
assert.ok(true, 'rollbar error handler is called');
assert.equal(message, 'foo', 'error is passed to rollbar error handler as argument');
}
});
Ember.onerror = function(message) {
assert.ok(true, 'previous hook is called');
assert.equal(message, 'foo', 'error is passed to previous hook as argument');
};
service.registerLogger();
Ember.onerror('foo');
});
test('registerLogger: does not register logger if disabled', function(assert) {
assert.expect(1);
let service = this.subject({
config: {
enabled: false
},
error() {
assert.notOk(true);
}
});
Ember.onerror = function() {
assert.ok(true);
};
service.registerLogger();
Ember.onerror();
})
| import { moduleFor, test } from 'ember-qunit';
import Ember from 'ember';
import Rollbar from 'rollbar';
moduleFor('service:rollbar', 'Unit | Service | rollbar', {
needs: ['config:environment']
});
test('it exists', function(assert) {
let service = this.subject();
assert.ok(service);
});
test('notifier', function(assert) {
let service = this.subject();
assert.ok(service.get('notifier') instanceof Rollbar);
});
test('critical', function(assert) {
let service = this.subject();
let uuid = service.critical('My error message').uuid;
assert.ok(uuid);
});
test('error', function(assert) {
let service = this.subject();
let uuid = service.error('My error message').uuid;
assert.ok(uuid);
});
test('warning', function(assert) {
let service = this.subject();
let uuid = service.warning('My error message').uuid;
assert.ok(uuid);
});
test('info', function(assert) {
let service = this.subject();
let uuid = service.info('My error message').uuid;
assert.ok(uuid);
});
test('debug', function(assert) {
let service = this.subject();
let uuid = service.debug('My error message').uuid;
assert.ok(uuid);
});
test('registerLogger: register error handler for Ember errors if enabled', function(assert) {
assert.expect(2);
let service = this.subject({
config: {
enabled: true
},
error(message) {
assert.ok(true, 'error handler is called');
assert.equal(message, 'foo', 'error is passed to error handler as argument');
}
});
service.registerLogger();
Ember.onerror('foo');
});
test('registerLogger: does not override previous hook', function(assert) {
assert.expect(4);
let service = this.subject({
config: {
enabled: true
},
error(message) {
assert.ok(true, 'rollbar error handler is called');
assert.equal(message, 'foo', 'error is passed to rollbar error handler as argument');
}
});
Ember.onerror = function(message) {
assert.ok(true, 'previous hook is called');
assert.equal(message, 'foo', 'error is passed to previous hook as argument');
};
service.registerLogger();
Ember.onerror('foo');
});
test('registerLogger: does not register logger if disabled', function(assert) {
assert.expect(1);
let service = this.subject({
config: {
enabled: false
},
error() {
assert.notOk(true);
}
});
Ember.onerror = function() {
assert.ok(true);
};
service.registerLogger();
Ember.onerror();
})
| JavaScript | 0 |
8ceb8c074327ecd4be630018c7643f84e26f1b08 | Include the extra secrets.js. | server/config/secrets.js | server/config/secrets.js | /** Important **/
/** You should not be committing this file to GitHub **/
module.exports = {
// Find the appropriate database to connect to, default to localhost if not found.
db: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://localhost/ReactWebpackNode',
sessionSecret: process.env.SESSION_SECRET || 'Your Session Secret goes here'
}; | JavaScript | 0 |
|
ede80b3f5a07d3cc11ba94f9ea40e52e0bb3a8a1 | add endGame method in game menu | src/common/directives/diGameMenu/diGameMenu.js | src/common/directives/diGameMenu/diGameMenu.js | /**
* directive.diGameMenu Module
*
* Description
*/
angular.module('directive.diGameMenu', [
'service.GameManager'
])
.controller('GameMenuCtrl', [
'$scope',
'GameManager',
function (
$scope,
GameManager
){
$scope.continueGame = function continueGame() {
GameManager.setPause();
$scope.closeModal();
};
$scope.restartGame = function restartGame() {
GameManager.newGame();
$scope.closeModal();
GameManager.setGameStart();
};
$scope.endGame = function endGame() {
GameManager.gameOver();
$scope.closeModal();
};
this.isPause = function isPause() {
return GameManager.isPause();
};
this.isGameStart = function isGameStart() {
return GameManager.isGameStart();
};
}])
.directive('diGameMenu', [
function(
){
var GameMenu = {};
GameMenu.controller = 'GameMenuCtrl';
GameMenu.templateUrl = 'directives/diGameMenu/diGameMenu.tpl.html';
GameMenu.restrict = 'A';
GameMenu.replace = true;
GameMenu.scope = true;
GameMenu.link = function link(scope, element, attrs, controller) {
scope.$on('app.pause', function() {
if (!controller.isPause() && controller.isGameStart()) {
$(element).modal({
backdrop: 'static'
});
} else {
scope.closeModal();
}
});
scope.closeModal = function closeModal() {
$(element).modal('hide');
};
};
return GameMenu;
}]); | /**
* directive.diGameMenu Module
*
* Description
*/
angular.module('directive.diGameMenu', [
'service.GameManager'
])
.controller('GameMenuCtrl', [
'$scope',
'GameManager',
function (
$scope,
GameManager
){
$scope.continueGame = function continueGame() {
GameManager.setPause();
$scope.closeModal();
return this;
};
$scope.restartGame = function restartGame() {
GameManager.newGame();
$scope.closeModal();
GameManager.setGameStart();
return this;
};
this.isPause = function isPause() {
return GameManager.isPause();
};
this.isGameStart = function isGameStart() {
return GameManager.isGameStart();
};
}])
.directive('diGameMenu', [
function(
){
var GameMenu = {};
GameMenu.controller = 'GameMenuCtrl';
GameMenu.templateUrl = 'directives/diGameMenu/diGameMenu.tpl.html';
GameMenu.restrict = 'A';
GameMenu.replace = true;
GameMenu.scope = true;
GameMenu.link = function link(scope, element, attrs, controller) {
scope.$on('app.pause', function() {
if (!controller.isPause() && controller.isGameStart()) {
$(element).modal({
backdrop: 'static'
});
} else {
scope.closeModal();
}
});
scope.closeModal = function closeModal() {
$(element).modal('hide');
};
};
return GameMenu;
}]); | JavaScript | 0 |
0313147b8cc69c0eb8fe76642922be9b121eadcd | Fix closure loader path in legacy example | examples/legacy-closure-lib/webpack.config.js | examples/legacy-closure-lib/webpack.config.js | var HtmlWebpackPlugin = require('html-webpack-plugin'),
webpack = require('webpack'),
pathUtil = require('path');
module.exports = {
entry: {
app: './src/app.js',
},
output: {
path: './build',
filename: '[name].js',
},
resolve: {
modulesDirectories: ['node_modules'],
root: [
__dirname,
],
alias: {
'npm': __dirname + '/node_modules',
}
},
resolveLoader: {
root: pathUtil.join(__dirname, 'node_modules'),
},
module: {
loaders: [
{
test: /google-closure-library\/closure\/goog\/base/,
loaders: [
'imports?this=>{goog:{}}&goog=>this.goog',
'exports?goog',
],
},
// Loader for closure library
{
test: /google-closure-library\/closure\/goog\/.*\.js/,
loaders: [
require.resolve('../../index'),
],
exclude: [/base\.js$/],
},
// Loader for project js files
{
test: /\/src\/.*\.js/,
loaders: [
require.resolve('../../index'),
],
exclude: [/node_modules/, /test/],
},
],
},
plugins: [
// This will copy the index.html to the build directory and insert script tags
new HtmlWebpackPlugin({
template: 'src/index.html',
}),
new webpack.ProvidePlugin({
goog: 'google-closure-library/closure/goog/base',
}),
],
closureLoader: {
paths: [
__dirname + '/node_modules/google-closure-library/closure/goog',
],
es6mode: false,
watch: false,
},
devServer: {
contentBase: './build',
noInfo: true,
inline: true,
historyApiFallback: true,
},
devtool: 'source-map',
};
| var HtmlWebpackPlugin = require('html-webpack-plugin'),
webpack = require('webpack'),
pathUtil = require('path');
module.exports = {
entry: {
app: './src/app.js',
},
output: {
path: './build',
filename: '[name].js',
},
resolve: {
modulesDirectories: ['node_modules'],
root: [
__dirname,
],
alias: {
'npm': __dirname + '/node_modules',
}
},
resolveLoader: {
root: pathUtil.join(__dirname, 'node_modules'),
},
module: {
loaders: [
{
test: /google-closure-library\/closure\/goog\/base/,
loaders: [
'imports?this=>{goog:{}}&goog=>this.goog',
'exports?goog',
],
},
// Loader for closure library
{
test: /google-closure-library\/closure\/goog\/.*\.js/,
loaders: [
require.resolve('../../index'),
],
exclude: [/base\.js$/],
},
// Loader for project js files
{
test: /\/src\/.*\.js/,
loaders: [
'closure',
],
exclude: [/node_modules/, /test/],
},
],
},
plugins: [
// This will copy the index.html to the build directory and insert script tags
new HtmlWebpackPlugin({
template: 'src/index.html',
}),
new webpack.ProvidePlugin({
goog: 'google-closure-library/closure/goog/base',
}),
],
closureLoader: {
paths: [
__dirname + '/node_modules/google-closure-library/closure/goog',
],
es6mode: false,
watch: false,
},
devServer: {
contentBase: './build',
noInfo: true,
inline: true,
historyApiFallback: true,
},
devtool: 'source-map',
};
| JavaScript | 0 |
70f855f1a8accf94641c71e48e8544676085fa20 | Rewrite LogoutButton to hooks | src/components/SettingsManager/LogoutButton.js | src/components/SettingsManager/LogoutButton.js | import React from 'react';
import PropTypes from 'prop-types';
import { useTranslator } from '@u-wave/react-translate';
import Button from '@mui/material/Button';
import LogoutIcon from '@mui/icons-material/PowerSettingsNew';
import ConfirmDialog from '../Dialogs/ConfirmDialog';
import FormGroup from '../Form/Group';
const { useState } = React;
function LogoutButton({ onLogout }) {
const { t } = useTranslator();
const [showDialog, setShowDialog] = useState(false);
const handleOpen = () => {
setShowDialog(true);
};
const handleClose = () => {
setShowDialog(false);
};
const handleConfirm = () => {
onLogout();
setShowDialog(false);
};
return (
<>
<Button color="inherit" className="LogoutButton" onClick={handleOpen}>
<LogoutIcon className="LogoutButton-icon" />
{t('settings.logout')}
</Button>
{showDialog && (
<ConfirmDialog
title=""
confirmLabel={t('dialogs.logout.action')}
onConfirm={handleConfirm}
onCancel={handleClose}
>
<FormGroup>{t('dialogs.logout.confirm')}</FormGroup>
</ConfirmDialog>
)}
</>
);
}
LogoutButton.propTypes = {
onLogout: PropTypes.func.isRequired,
};
export default LogoutButton;
| import React from 'react';
import PropTypes from 'prop-types';
import { translate } from '@u-wave/react-translate';
import Button from '@mui/material/Button';
import LogoutIcon from '@mui/icons-material/PowerSettingsNew';
import ConfirmDialog from '../Dialogs/ConfirmDialog';
import FormGroup from '../Form/Group';
const enhance = translate();
class LogoutButton extends React.Component {
static propTypes = {
t: PropTypes.func.isRequired,
onLogout: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = {
showDialog: false,
};
}
handleOpen = () => {
this.setState({ showDialog: true });
};
handleClose = () => {
this.closeDialog();
};
handleConfirm = () => {
const { onLogout } = this.props;
onLogout();
this.closeDialog();
};
closeDialog() {
this.setState({ showDialog: false });
}
render() {
const { t } = this.props;
const { showDialog } = this.state;
return (
<>
<Button color="inherit" className="LogoutButton" onClick={this.handleOpen}>
<LogoutIcon className="LogoutButton-icon" />
{t('settings.logout')}
</Button>
{showDialog && (
<ConfirmDialog
title=""
confirmLabel={t('dialogs.logout.action')}
onConfirm={this.handleConfirm}
onCancel={this.handleClose}
>
<FormGroup>{t('dialogs.logout.confirm')}</FormGroup>
</ConfirmDialog>
)}
</>
);
}
}
export default enhance(LogoutButton);
| JavaScript | 0 |
89ab12e6324f4d6fc32280f244bb91cea81482dd | Use correct path in examples when using handlers nested in subdirs | examples/serverless-offline/webpack.config.js | examples/serverless-offline/webpack.config.js | const path = require('path');
const nodeExternals = require('webpack-node-externals');
module.exports = {
entry: './src/handler.js',
target: 'node',
externals: [nodeExternals()],
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel-loader'],
include: __dirname,
exclude: /node_modules/,
}],
},
output: {
libraryTarget: 'commonjs',
path: path.join(__dirname, '.webpack'),
filename: 'src/handler.js'
},
};
| const path = require('path');
const nodeExternals = require('webpack-node-externals');
module.exports = {
entry: './src/handler.js',
target: 'node',
externals: [nodeExternals()],
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel-loader'],
include: __dirname,
exclude: /node_modules/,
}],
},
output: {
libraryTarget: 'commonjs',
path: path.join(__dirname, '.webpack'),
filename: 'handler.js'
},
};
| JavaScript | 0 |
4453bf5e68f1fd41cebe9e3dc2833d2df7fdfd0f | Update moonpay api | server/lib/v1/moonpay.js | server/lib/v1/moonpay.js | 'use strict';
var axios = require('axios');
var db = require('./db');
var API_KEY = process.env.MOONPAY_API_KEY;
var PRIORITY_SYMBOLS = ['BTC', 'BCH', 'ETH', 'USDT', 'LTC', 'XRP', 'XLM', 'EOS', 'DOGE', 'DASH'];
var fiatSigns = {
usd: '$',
eur: '€',
gbp: '£'
};
function save(_id, data) {
var collection = db().collection('moonpay');
return collection.updateOne({_id: _id}, {$set: {data: data}}, {upsert: true});
}
function getCurrenciesFromAPI() {
return axios.get('https://api.moonpay.io/v3/currencies', {
params: {
apiKey: API_KEY
}
}).then(function(response) {
var data = response.data;
if (!data || !data.length) throw new Error('Bad moonpay response');
var coins = {};
var coinsUSA = {};
PRIORITY_SYMBOLS.forEach(function(symbol) {
var coin = data.find(function(item) {
return item.code === symbol.toLowerCase();
});
if (coin) {
coins[coin.id] = {
symbol: symbol,
isSupported: !coin.isSuspended
}
coinsUSA[coin.id] = {
symbol: symbol,
isSupported: !coin.isSuspended && coin.isSupportedInUS
}
}
});
var fiat = {};
data.forEach(function(item) {
if (item.type === 'fiat') {
fiat[item.id] = {
symbol: item.code.toUpperCase(),
sign: fiatSigns[item.code] || '',
precision: item.precision
};
}
});
return {
coins: coins,
coins_usa: coinsUSA,
fiat: fiat
};
});
}
function getCountriesFromAPI() {
return axios.get('https://api.moonpay.io/v3/countries').then(function(response) {
var data = response.data;
if (!data || !data.length) throw new Error('Bad moonpay response');
var document = data.filter(function(country) {
return country.supportedDocuments && country.supportedDocuments.length > 0;
}).map(function(country) {
return {
code: country.alpha3,
name: country.name,
supportedDocuments: country.supportedDocuments
}
});
var allowed = data.filter(function(country) {
return country.isAllowed;
}).map(function(country) {
var item = {};
item.code = country.alpha3;
item.name = country.name;
if (country.states) {
item.states = country.states.filter(function(state) {
return state.isAllowed;
}).map(function(state) {
return {
code: state.code,
name: state.name
};
});
}
return item;
});
return {
document: document,
allowed: allowed
};
});
}
function getFromCache(id) {
var collection = db().collection('moonpay');
return collection
.find({_id: id})
.limit(1)
.next().then(function(item) {
if (!item) return {};
delete item.id;
return item.data;
});
}
module.exports = {
save: save,
getCurrenciesFromAPI: getCurrenciesFromAPI,
getCountriesFromAPI: getCountriesFromAPI,
getFromCache: getFromCache
};
| 'use strict';
var axios = require('axios');
var db = require('./db');
var PRIORITY_SYMBOLS = ['BTC', 'BCH', 'ETH', 'USDT', 'LTC', 'XRP', 'XLM', 'EOS', 'DOGE', 'DASH'];
var fiatSigns = {
usd: '$',
eur: '€',
gbp: '£'
};
function save(_id, data) {
var collection = db().collection('moonpay');
return collection.updateOne({_id: _id}, {$set: {data: data}}, {upsert: true});
}
function getCurrenciesFromAPI() {
return axios.get('https://api.moonpay.io/v3/currencies').then(function(response) {
var data = response.data;
if (!data || !data.length) throw new Error('Bad moonpay response');
var coins = {};
var coinsUSA = {};
PRIORITY_SYMBOLS.forEach(function(symbol) {
var coin = data.find(function(item) {
return item.code === symbol.toLowerCase();
});
if (coin) {
coins[coin.id] = {
symbol: symbol,
isSupported: !coin.isSuspended
}
coinsUSA[coin.id] = {
symbol: symbol,
isSupported: !coin.isSuspended && coin.isSupportedInUS
}
}
});
var fiat = {};
data.forEach(function(item) {
if (item.type === 'fiat') {
fiat[item.id] = {
symbol: item.code.toUpperCase(),
sign: fiatSigns[item.code] || '',
precision: item.precision
};
}
});
return {
coins: coins,
coins_usa: coinsUSA,
fiat: fiat
};
});
}
function getCountriesFromAPI() {
return axios.get('https://api.moonpay.io/v3/countries').then(function(response) {
var data = response.data;
if (!data || !data.length) throw new Error('Bad moonpay response');
var document = data.filter(function(country) {
return country.supportedDocuments && country.supportedDocuments.length > 0;
}).map(function(country) {
return {
code: country.alpha3,
name: country.name,
supportedDocuments: country.supportedDocuments
}
});
var allowed = data.filter(function(country) {
return country.isAllowed;
}).map(function(country) {
var item = {};
item.code = country.alpha3;
item.name = country.name;
if (country.states) {
item.states = country.states.filter(function(state) {
return state.isAllowed;
}).map(function(state) {
return {
code: state.code,
name: state.name
};
});
}
return item;
});
return {
document: document,
allowed: allowed
};
});
}
function getFromCache(id) {
var collection = db().collection('moonpay');
return collection
.find({_id: id})
.limit(1)
.next().then(function(item) {
if (!item) return {};
delete item.id;
return item.data;
});
}
module.exports = {
save: save,
getCurrenciesFromAPI: getCurrenciesFromAPI,
getCountriesFromAPI: getCountriesFromAPI,
getFromCache: getFromCache
};
| JavaScript | 0 |
94f350b9b01a1048f03c9c93bad0fda1f0b9041e | refactor serial writes | lib/board.js | lib/board.js |
var events = require('events'),
child = require('child_process'),
util = require('util'),
serial = require('serialport').SerialPort;
/*
* The main Arduino constructor
* Connect to the serial port and bind
*/
var Board = function (options) {
this.messageBuffer = '';
var self = this;
this.detect(function (err, serial) {
if (err) throw err;
self.serial = serial;
self.serial.write('0');
self.serial.on('data', function(data){
self.emit('data', data);
self.messageBuffer += data;
self.attemptParse();
});
self.emit('connected');
});
}
/*
* EventEmitter, I choose you!
*/
util.inherits(Board, events.EventEmitter);
/*
* Detect an Arduino board
* Loop through all USB devices and try to connect
* This should really message the device and wait for a correct response
*/
Board.prototype.detect = function (cb) {
child.exec('ls /dev | grep usb', function(err, stdout, stderr){
var possible = stdout.slice(0, -1).split('\n'),
found = false;
for (var i in possible) {
var tempSerial, err;
try {
tempSerial = new serial('/dev/' + possible[i]);
} catch (e) {
err = e;
}
if (!err) {
found = tempSerial;
break;
}
}
if (found) cb(null, found);
else cb(new Error('Could not find Arduino'));
});
}
/*
* Attempt to parse the message buffer via delimiter
* Called every time data bytes are received
*/
Board.prototype.attemptParse = function (data) {
var b = this.messageBuffer.split('\r\n');
while (b.length > 1) {
this.emit('message', b.shift());
}
this.messageBuffer = b[0];
}
/*
* Low-level serial write
*/
Board.prototype.write = function (m) {
this.serial.write('!' + m + '.');
}
/*
* Set a pin's mode
* val == out = 01
* val == in = 00
*/
Board.prototype.pinMode = function (pin, val) {
val = (
val == 'out' ?
'01' :
'00'
);
// console.log('pm 00' + pin + val);
this.write('00' + pin + val);
}
/*
* Tell the board to write to a digital pin
*/
Board.prototype.digitalWrite = function (pin, val) {
//console.log('dw 01' + pin + val);
this.write('01' + pin + val);
}
Board.prototype.digitalRead = function (pin, val) {}
Board.prototype.analogWrite = function (pin, val) {}
Board.prototype.analogWrite = function (pin, val) {}
module.exports = Board;
|
var events = require('events'),
child = require('child_process'),
util = require('util'),
serial = require('serialport').SerialPort;
/*
* The main Arduino constructor
* Connect to the serial port and bind
*/
var Board = function (options) {
this.messageBuffer = '';
var self = this;
this.detect(function (err, serial) {
if (err) throw err;
self.serial = serial;
self.serial.on('data', function(data){
self.emit('data', data);
self.messageBuffer += data;
self.attemptParse();
});
self.emit('connected');
});
}
/*
* EventEmitter, I choose you!
*/
util.inherits(Board, events.EventEmitter);
/*
* Detect an Arduino board
* Loop through all USB devices and try to connect
* This should really message the device and wait for a correct response
*/
Board.prototype.detect = function (cb) {
child.exec('ls /dev | grep usb', function(err, stdout, stderr){
var possible = stdout.slice(0, -1).split('\n'),
found = false;
for (var i in possible) {
var tempSerial, err;
try {
tempSerial = new serial('/dev/' + possible[i]);
} catch (e) {
err = e;
}
if (!err) {
found = tempSerial;
break;
}
}
if (found) cb(null, found);
else cb(new Error('Could not find Arduino'));
});
}
/*
* Attempt to parse the message buffer via delimiter
* Called every time data bytes are received
*/
Board.prototype.attemptParse = function (data) {
var b = this.messageBuffer.split('\r\n');
while (b.length > 1) {
this.emit('message', b.shift());
}
this.messageBuffer = b[0];
}
/*
* Low-level serial write
*/
Board.prototype.write = function (m) {
this.serial.write(m);
}
/*
* Set a pin's mode
* val == out = 01
* val == in = 00
*/
Board.prototype.pinMode = function (pin, val) {
this.serial.write(
'00' +
pin +
(val == 'out' ? '01' : '00')
);
}
/*
* Tell the board to write to a digital pin
*/
Board.prototype.digitalWrite = function (pin, val) {
this.serial.write('01' + pin + val + '\r');
}
Board.prototype.digitalRead = function (pin, val) {}
Board.prototype.analogWrite = function (pin, val) {}
Board.prototype.analogWrite = function (pin, val) {}
module.exports = Board;
| JavaScript | 0.000001 |
09214e30538194174194130ccc2e85c70648915d | Change text view init | www/views/backup/text.js | www/views/backup/text.js | define([
'jquery',
'underscore',
'backbone',
'shCore',
'shBrushAppleScript',
'shBrushAS3',
'shBrushBash',
'shBrushColdFusion',
'shBrushCpp',
'shBrushCSharp',
'shBrushCss',
'shBrushDelphi',
'shBrushDiff',
'shBrushErlang',
'shBrushGroovy',
'shBrushHaxe',
'shBrushJava',
'shBrushJavaFX',
'shBrushJScript',
'shBrushPerl',
'shBrushPhp',
'shBrushPlain',
'shBrushPowerShell',
'shBrushPython',
'shBrushRuby',
'shBrushSass',
'shBrushScala',
'shBrushSql',
'shBrushTypeScript',
'shBrushVb',
'shBrushXml',
'models/backup/text',
'text!templates/backup/text.html'
], function($, _, Backbone, SyntaxHighlighter, BrushAppleScript, BrushAS3,
BrushBash, BrushColdFusion, BrushCpp, BrushCSharp, BrushCss, BrushDelphi,
BrushDiff, BrushErlang, BrushGroovy, BrushHaxe, BrushJava, BrushJavaFX,
BrushJScript, BrushPerl, BrushPhp, BrushPlain, BrushPowerShell,
BrushPython, BrushRuby, BrushSass, BrushScala, BrushSql, BrushTypeScript,
BrushVb, BrushXml, TextModel, textTemplate) {
'use strict';
var TextView = Backbone.View.extend({
className: 'text-viewer-box',
events: {
'mouseover .close-viewer': 'addIconWhite',
'mouseout .close-viewer': 'removeIconWhite',
'click .close-viewer': 'onClickClose'
},
template: _.template(textTemplate),
initialize: function(options) {
this.model = new TextModel(options);
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
SyntaxHighlighter.highlight(null, this.$('pre')[0]);
this.$el.fadeIn(400);
return this;
},
addIconWhite: function(evt) {
this.$(evt.target).addClass('icon-white');
},
removeIconWhite: function(evt) {
this.$(evt.target).removeClass('icon-white');
},
onClickClose: function() {
this.$('.close-viewer').roll(400);
this.$el.fadeOut(400, function() {
this.remove();
}.bind(this));
}
});
return TextView;
});
| define([
'jquery',
'underscore',
'backbone',
'shCore',
'shBrushAppleScript',
'shBrushAS3',
'shBrushBash',
'shBrushColdFusion',
'shBrushCpp',
'shBrushCSharp',
'shBrushCss',
'shBrushDelphi',
'shBrushDiff',
'shBrushErlang',
'shBrushGroovy',
'shBrushHaxe',
'shBrushJava',
'shBrushJavaFX',
'shBrushJScript',
'shBrushPerl',
'shBrushPhp',
'shBrushPlain',
'shBrushPowerShell',
'shBrushPython',
'shBrushRuby',
'shBrushSass',
'shBrushScala',
'shBrushSql',
'shBrushTypeScript',
'shBrushVb',
'shBrushXml',
'models/backup/text',
'text!templates/backup/text.html'
], function($, _, Backbone, SyntaxHighlighter, BrushAppleScript, BrushAS3,
BrushBash, BrushColdFusion, BrushCpp, BrushCSharp, BrushCss, BrushDelphi,
BrushDiff, BrushErlang, BrushGroovy, BrushHaxe, BrushJava, BrushJavaFX,
BrushJScript, BrushPerl, BrushPhp, BrushPlain, BrushPowerShell,
BrushPython, BrushRuby, BrushSass, BrushScala, BrushSql, BrushTypeScript,
BrushVb, BrushXml, TextModel, textTemplate) {
'use strict';
var TextView = Backbone.View.extend({
className: 'text-viewer-box',
events: {
'mouseover .close-viewer': 'addIconWhite',
'mouseout .close-viewer': 'removeIconWhite',
'click .close-viewer': 'onClickClose'
},
template: _.template(textTemplate),
initialize: function(options) {
this.model = new TextModel({
id: options.id,
volume: options.volume,
snapshot: options.snapshot
});
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
SyntaxHighlighter.highlight(null, this.$('pre')[0]);
this.$el.fadeIn(400);
return this;
},
addIconWhite: function(evt) {
this.$(evt.target).addClass('icon-white');
},
removeIconWhite: function(evt) {
this.$(evt.target).removeClass('icon-white');
},
onClickClose: function() {
this.$('.close-viewer').roll(400);
this.$el.fadeOut(400, function() {
this.remove();
}.bind(this));
}
});
return TextView;
});
| JavaScript | 0.000001 |
0d63f0442e795ec0371e73050076ea3dd60c0725 | Fix for undefined req.onErrorCallback | lib/express_validator.js | lib/express_validator.js | /*
* This binds the node-validator library to the req object so that
* the validation / sanitization methods can be called on parameter
* names rather than the actual strings.
*
* 1. Be sure to include `req.mixinParams()` as middleware to merge
* query string, body and named parameters into `req.params`
*
* 2. To validate parameters, use `req.check(param_name, [err_message])`
* e.g. req.check('param1').len(1, 6).isInt();
* e.g. req.checkHeader('referer').contains('mydomain.com');
*
* Each call to `check()` will throw an exception by default. To
* specify a custom err handler, use `req.onValidationError(errback)`
* where errback receives a parameter containing the error message
*
* 3. To sanitize parameters, use `req.sanitize(param_name)`
* e.g. req.sanitize('large_text').xss();
* e.g. req.sanitize('param2').toInt();
*
* 4. Done! Access your validated and sanitized paramaters through the
* `req.params` object
*/
var Validator = require('validator').Validator,
Filter = require('validator').Filter;
var validator = new Validator();
var expressValidator = function(req, res, next) {
req.updateParam = function(name, value) {
// route params like /user/:id
if (this.params && this.params.hasOwnProperty(name) && undefined !== this.params[name]) {
return this.params[name] = value;
}
// query string params
if (undefined !== this.query[name]) {
return this.query[name] = value;
}
// request body params via connect.bodyParser
if (this.body && undefined !== this.body[name]) {
return this.body[name] = value;
}
return false;
};
req.check = function(param, fail_msg) {
validator.error = function(msg) {
var error = {
param: param,
msg: msg
}
if (req._validationErrors === undefined) {
req._validationErrors = [];
}
req._validationErrors.push(error);
if(req.onErrorCallback) {
req.onErrorCallback(msg);
}
}
return validator.check(this.param(param), fail_msg);
};
req.checkHeader = function(param, fail_msg) {
var to_check;
if (header === 'referrer' || header === 'referer') {
to_check = this.headers.referer;
} else {
to_check = this.headers[header];
}
return validator.check(to_check || '', fail_msg);
};
req.onValidationError = function(errback) {
req.onErrorCallback = errback;
};
req.validationErrors = function(mapped) {
if (req._validationErrors === undefined) {
return false;
}
if (mapped) {
var errors = {};
req._validationErrors.map(function(err) {
errors[err.param] = err.msg;
});
return errors;
} else {
return req._validationErrors;
}
}
req.filter = function(param) {
var self = this;
var filter = new Filter();
filter.modify = function(str) {
this.str = str;
self.updateParam(param, str); // Replace the param with the filtered version
};
return filter.sanitize(this.param(param));
};
// Create some aliases - might help with code readability
req.sanitize = req.filter;
req.assert = req.check;
return next();
};
module.exports = expressValidator;
module.exports.Validator = Validator;
module.exports.Filter = Filter;
| /*
* This binds the node-validator library to the req object so that
* the validation / sanitization methods can be called on parameter
* names rather than the actual strings.
*
* 1. Be sure to include `req.mixinParams()` as middleware to merge
* query string, body and named parameters into `req.params`
*
* 2. To validate parameters, use `req.check(param_name, [err_message])`
* e.g. req.check('param1').len(1, 6).isInt();
* e.g. req.checkHeader('referer').contains('mydomain.com');
*
* Each call to `check()` will throw an exception by default. To
* specify a custom err handler, use `req.onValidationError(errback)`
* where errback receives a parameter containing the error message
*
* 3. To sanitize parameters, use `req.sanitize(param_name)`
* e.g. req.sanitize('large_text').xss();
* e.g. req.sanitize('param2').toInt();
*
* 4. Done! Access your validated and sanitized paramaters through the
* `req.params` object
*/
var Validator = require('validator').Validator,
Filter = require('validator').Filter;
var validator = new Validator();
var expressValidator = function(req, res, next) {
req.updateParam = function(name, value) {
// route params like /user/:id
if (this.params && this.params.hasOwnProperty(name) && undefined !== this.params[name]) {
return this.params[name] = value;
}
// query string params
if (undefined !== this.query[name]) {
return this.query[name] = value;
}
// request body params via connect.bodyParser
if (this.body && undefined !== this.body[name]) {
return this.body[name] = value;
}
return false;
};
req.check = function(param, fail_msg) {
validator.error = function(msg) {
var error = {
param: param,
msg: msg
}
if (req._validationErrors === undefined) {
req._validationErrors = [];
}
req._validationErrors.push(error);
req.onErrorCallback(msg);
}
return validator.check(this.param(param), fail_msg);
};
req.checkHeader = function(param, fail_msg) {
var to_check;
if (header === 'referrer' || header === 'referer') {
to_check = this.headers.referer;
} else {
to_check = this.headers[header];
}
return validator.check(to_check || '', fail_msg);
};
req.onValidationError = function(errback) {
req.onErrorCallback = errback;
};
req.validationErrors = function(mapped) {
if (req._validationErrors === undefined) {
return false;
}
if (mapped) {
var errors = {};
req._validationErrors.map(function(err) {
errors[err.param] = err.msg;
});
return errors;
} else {
return req._validationErrors;
}
}
req.filter = function(param) {
var self = this;
var filter = new Filter();
filter.modify = function(str) {
this.str = str;
self.updateParam(param, str); // Replace the param with the filtered version
};
return filter.sanitize(this.param(param));
};
// Create some aliases - might help with code readability
req.sanitize = req.filter;
req.assert = req.check;
return next();
};
module.exports = expressValidator;
module.exports.Validator = Validator;
module.exports.Filter = Filter;
| JavaScript | 0.00001 |
698f35d4196afb6838eb892d79e491f180fe4d8e | format code | messages/handleCourseMessage.js | messages/handleCourseMessage.js | 'use strict'
const {type} = require('message-type')
const canvasApi = require('../canvasApi')
const config = require('../server/init/configuration')
const log = require('../server/init/logging')
const ugParser = require('./ugParser')
const calcSisForOmregistrerade = require('./calcSisForOmregistrerade')
const createCsvFile = require('./createCsvFile')
const csvVol = config.full.azure.csvBlobName
const csvDir = config.full.localFile.csvDir
function parseKey ({ug1Name, _desc}) {
const {userType} = _desc
if (userType === type.students) {
return ugParser.parseKeyStudent(ug1Name)
}
if (userType === type.teachers || userType === type.assistants || userType === type.courseresponsibles) {
return ugParser.parseKeyTeacher(ug1Name)
}
log.error('Course code not parsable from Key. type, ', userType + ' ug1Name, ' + ug1Name)
throw new Error('Key parse error, type, ' + userType + ' ug1Name, ' + ug1Name)
}
function handleCourseMessage (msg) {
let sisCourseCodeFunction
if (msg._desc.userType === type.omregistrerade) {
log.info('using calcSisForOmregistrerade')
sisCourseCodeFunction = calcSisForOmregistrerade
} else {
log.info('using parseKey')
sisCourseCodeFunction = parseKey
}
return Promise.resolve()
.then(() => sisCourseCodeFunction(msg))
.then(sisCourseCode => createCsvFile(msg, sisCourseCode, csvDir, csvVol))
.then(({name}) => canvasApi.sendCsvFile(name, true))
.then(canvasReturnValue => {
return {msg, resp: canvasReturnValue}
})
}
module.exports = {handleCourseMessage, parseKey}
| 'use strict'
const {type} = require('message-type')
const canvasApi = require('../canvasApi')
const config = require('../server/init/configuration')
const log = require('../server/init/logging')
const ugParser = require('./ugParser')
const calcSisForOmregistrerade = require('./calcSisForOmregistrerade')
const createCsvFile = require('./createCsvFile')
const csvVol = config.full.azure.csvBlobName
const csvDir = config.full.localFile.csvDir
function parseKey ({ug1Name, _desc}) {
const {userType} = _desc
if (userType === type.students) {
return ugParser.parseKeyStudent(ug1Name)
}
if (userType === type.teachers || userType === type.assistants || userType === type.courseresponsibles) {
return ugParser.parseKeyTeacher(ug1Name)
}
log.error('Course code not parsable from Key. type, ', userType + ' ug1Name, ' + ug1Name)
throw new Error('Key parse error, type, ' + userType + ' ug1Name, ' + ug1Name)
}
function handleCourseMessage (msg) {
let sisCourseCodeFunction
if (msg._desc.userType === type.omregistrerade) {
log.info('using calcSisForOmregistrerade')
sisCourseCodeFunction = calcSisForOmregistrerade
} else {
log.info('using parseKey')
sisCourseCodeFunction = parseKey
}
return Promise.resolve()
.then(() => sisCourseCodeFunction(msg))
.then(sisCourseCode => createCsvFile(msg, sisCourseCode, csvDir, csvVol))
.then(({name}) => canvasApi.sendCsvFile(name, true))
.then(canvasReturnValue => {
return {msg, resp: canvasReturnValue}
})
}
module.exports = {handleCourseMessage, parseKey}
| JavaScript | 0.000061 |
5fc2d1337e5a3e90c1a884949c4af49afc7ef7fa | use .txt() for the "date" value | lib/build.js | lib/build.js |
/**
* Module dependencies.
*/
var xmlbuilder = require('xmlbuilder');
/**
* Module exports.
*/
exports.build = build;
function ISODateString(d){
function pad(n){
return n < 10 ? '0' + n : n;
}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z';
}
// instanceof is horribly unreliable so we use these hackish but safer checks
// http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray
function isArray(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
function isDate(obj) {
return Object.prototype.toString.call(obj) === '[object Date]';
}
function isBoolean(obj) {
return (obj === true || obj === false || toString.call(obj) == '[object Boolean]');
}
function isNumber(obj) {
return Object.prototype.toString.call(obj) === '[object Number]';
}
function isObject(obj) {
return Object.prototype.toString.call(obj) === '[object Object]';
}
function isString(obj) {
return Object.prototype.toString.call(obj) === '[object String]';
}
/**
* generate an XML plist string from the input object
*
* @param {Object} obj - the object to convert
* @returns {String} converted plist
* @api public
*/
function build (obj) {
var XMLHDR = { 'version': '1.0','encoding': 'UTF-8' }
, XMLDTD = { 'ext': 'PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\"' }
, doc = xmlbuilder.create()
, child = doc.begin('plist', XMLHDR, XMLDTD).att('version', '1.0');
walk_obj(obj, child);
return child.end({
pretty: true
});
}
/**
* depth first, recursive traversal of a javascript object. when complete,
* next_child contains a reference to the build XML object.
*
* @api private
*/
function walk_obj(next, next_child) {
var tag_type, i, prop;
if (isArray(next)) {
next_child = next_child.ele('array');
for(i=0 ;i < next.length;i++) {
walk_obj(next[i], next_child);
}
} else if (isObject(next)) {
if (Buffer.isBuffer(next)) {
next_child.ele('data').raw(next.toString('base64'));
} else {
next_child = next_child.ele('dict');
for(prop in next) {
if (next.hasOwnProperty(prop)) {
next_child.ele('key').txt(prop);
walk_obj(next[prop], next_child);
}
}
}
} else if (isNumber(next)) {
// detect if this is an integer or real
tag_type =(next % 1 === 0) ? 'integer' : 'real';
next_child.ele(tag_type).txt(next.toString());
} else if (isDate(next)) {
next_child.ele('date').txt(ISODateString(new Date(next)));
} else if (isBoolean(next)) {
val = next ? 'true' : 'false';
next_child.ele(val);
} else if (isString(next)) {
next_child.ele('string').txt(next);
}
}
|
/**
* Module dependencies.
*/
var xmlbuilder = require('xmlbuilder');
/**
* Module exports.
*/
exports.build = build;
function ISODateString(d){
function pad(n){
return n < 10 ? '0' + n : n;
}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z';
}
// instanceof is horribly unreliable so we use these hackish but safer checks
// http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray
function isArray(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
function isDate(obj) {
return Object.prototype.toString.call(obj) === '[object Date]';
}
function isBoolean(obj) {
return (obj === true || obj === false || toString.call(obj) == '[object Boolean]');
}
function isNumber(obj) {
return Object.prototype.toString.call(obj) === '[object Number]';
}
function isObject(obj) {
return Object.prototype.toString.call(obj) === '[object Object]';
}
function isString(obj) {
return Object.prototype.toString.call(obj) === '[object String]';
}
/**
* generate an XML plist string from the input object
*
* @param {Object} obj - the object to convert
* @returns {String} converted plist
* @api public
*/
function build (obj) {
var XMLHDR = { 'version': '1.0','encoding': 'UTF-8' }
, XMLDTD = { 'ext': 'PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\"' }
, doc = xmlbuilder.create()
, child = doc.begin('plist', XMLHDR, XMLDTD).att('version', '1.0');
walk_obj(obj, child);
return child.end({
pretty: true
});
}
/**
* depth first, recursive traversal of a javascript object. when complete,
* next_child contains a reference to the build XML object.
*
* @api private
*/
function walk_obj(next, next_child) {
var tag_type, i, prop;
if (isArray(next)) {
next_child = next_child.ele('array');
for(i=0 ;i < next.length;i++) {
walk_obj(next[i], next_child);
}
} else if (isObject(next)) {
if (Buffer.isBuffer(next)) {
next_child.ele('data').raw(next.toString('base64'));
} else {
next_child = next_child.ele('dict');
for(prop in next) {
if (next.hasOwnProperty(prop)) {
next_child.ele('key').txt(prop);
walk_obj(next[prop], next_child);
}
}
}
} else if (isNumber(next)) {
// detect if this is an integer or real
tag_type =(next % 1 === 0) ? 'integer' : 'real';
next_child.ele(tag_type).txt(next.toString());
} else if (isDate(next)) {
next_child.ele('date').raw(ISODateString(new Date(next)));
} else if (isBoolean(next)) {
val = next ? 'true' : 'false';
next_child.ele(val);
} else if (isString(next)) {
next_child.ele('string').text(next);
}
}
| JavaScript | 0 |
29f263950a3ea5dc70a5aec6066fe2c7391c2887 | Fix a bug in cache callback. | lib/cache.js | lib/cache.js | var http = require("http"),
url = require("url"),
util = require("util");
var map = {},
head = null,
tail = null,
size = 512,
n = 0;
var headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_7) AppleWebKit/534.36 (KHTML, like Gecko) Chrome/13.0.767.1 Safari/534.36"
};
module.exports = function(key, callback) {
var value = map[key];
// If this value is in the cache…
if (value) {
// Move it to the front of the least-recently used list.
if (value.previous) {
value.previous.next = value.next;
if (value.next) value.next.previous = value.previous;
else tail = value.previous;
value.previous = null;
value.next = head;
head.previous = value;
head = value;
}
// If the value is loaded, callback.
// Otherwise, add the callback to the list.
return value.callbacks
? value.callbacks.push(callback)
: callback(value.value);
}
// Otherwise, add the value to the cache.
value = map[key] = {
key: key,
next: head,
previous: null,
callbacks: [callback]
};
// Add the value to the front of the least-recently used list.
if (head) head.previous = value;
else tail = value;
head = value;
n++;
util.log(key);
// Load the requested resource!
var u = url.parse(key);
http.get({
host: u.host,
port: u.port,
path: u.pathname + (u.search ? "?" + u.search : ""),
headers: headers
}, function(response) {
var body = new Buffer(+response.headers['content-length'] || 2048), // TODO realloc
offset = 0;
response
.on("data", function(chunk) {
offset += chunk.copy(body, offset);
})
.on("end", function() {
var callbacks = value.callbacks;
delete value.callbacks; // must be deleted before callback!
value.value = body.slice(0, offset);
callbacks.forEach(function(callback) { callback(value.value); });
});
}).on("error", function(error) {
callback(null);
});
flush();
};
// Flush any extra values.
function flush() {
for (var value = tail; n > size && value; value = value.previous) {
n--;
delete map[value.key];
if (value.next) value.next.previous = value.previous;
else if (tail = value.previous) tail.next = null;
if (value.previous) value.previous.next = value.next;
else if (head = value.next) head.previous = null;
}
}
| var http = require("http"),
url = require("url"),
util = require("util");
var map = {},
head = null,
tail = null,
size = 512,
n = 0;
var headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_7) AppleWebKit/534.36 (KHTML, like Gecko) Chrome/13.0.767.1 Safari/534.36"
};
module.exports = function(key, callback) {
var value = map[key];
// If this value is in the cache…
if (value) {
// Move it to the front of the least-recently used list.
if (value.previous) {
value.previous.next = value.next;
if (value.next) value.next.previous = value.previous;
else tail = value.previous;
value.previous = null;
value.next = head;
head.previous = value;
head = value;
}
// If the value is loaded, callback.
// Otherwise, add the callback to the list.
return value.callbacks
? value.callbacks.push(callback)
: callback(value.value);
}
// Otherwise, add the value to the cache.
value = map[key] = {
key: key,
next: head,
previous: null,
callbacks: [callback]
};
// Add the value to the front of the least-recently used list.
if (head) head.previous = value;
else tail = value;
head = value;
n++;
util.log(key);
// Load the requested resource!
var u = url.parse(key);
http.get({
host: u.host,
port: u.port,
path: u.pathname + (u.search ? "?" + u.search : ""),
headers: headers
}, function(response) {
var body = new Buffer(+response.headers['content-length'] || 2048), // TODO realloc
offset = 0;
response
.on("data", function(chunk) {
offset += chunk.copy(body, offset);
})
.on("end", function() {
value.value = body.slice(0, offset);
value.callbacks.forEach(function(callback) { callback(value.value); });
delete value.callbacks;
});
}).on("error", function(error) {
callback(null);
});
flush();
};
// Flush any extra values.
function flush() {
for (var value = tail; n > size && value; value = value.previous) {
n--;
delete map[value.key];
if (value.next) value.next.previous = value.previous;
else if (tail = value.previous) tail.next = null;
if (value.previous) value.previous.next = value.next;
else if (head = value.next) head.previous = null;
}
}
| JavaScript | 0 |
3a58de3460047f8151e31ed8b506abe0f8a29bf9 | Update cache.js | lib/cache.js | lib/cache.js | var catchallDir = '.catchall',
cacheDir = catchallDir + "/cache";
var cfg = require('yaconfig').file(catchallDir + "/cached.json"),
fs = require('fs'),
crypto = require('crypto'),
path = require('path');
//yaconfig makes our directories - this is fine.
try {
fs.mkdirSync(cacheDir, 0777);
} catch(e) {
}
function _cacheKey(source) {
return crypto.createHash('md5').update(source).digest("hex");
}
function _cachePath(key) {
return cacheDir + "/" + key + ".cache";
}
function exists(path) {
try {
fs.lstatSync(path);
return true;
} catch(e) {
return false;
}
}
exports.get = function(source, lastModified, callback) {
var key = _cacheKey(source);
//no cache?
if(!cfg.get(key)) return callback(true);
//old cache?
if(cfg.get(key) < lastModified.getTime()) return callback(true);
var cachePath = _cachePath(key);
//exists? necessary to beat race condition with http requests
if(!exists(cachePath)) return callback(true);
callback(null, cachePath);
}
exports.set = function(source, lastModified, content, callback) {
var key = _cacheKey(source);
cfg.set(key, lastModified.getTime());
fs.writeFile(_cachePath(key), content);
}
| var catchallDir = '/usr/local/etc/catchall',
cacheDir = catchallDir + "/cache";
var cfg = require('yaconfig').file(catchallDir + "/cached.json"),
fs = require('fs'),
crypto = require('crypto'),
path = require('path');
//yaconfig makes our directories - this is fine.
try {
fs.mkdirSync(cacheDir, 0777);
} catch(e) {
}
function _cacheKey(source) {
return crypto.createHash('md5').update(source).digest("hex");
}
function _cachePath(key) {
return cacheDir + "/" + key + ".cache";
}
function exists(path) {
try {
fs.lstatSync(path);
return true;
} catch(e) {
return false;
}
}
exports.get = function(source, lastModified, callback) {
var key = _cacheKey(source);
//no cache?
if(!cfg.get(key)) return callback(true);
//old cache?
if(cfg.get(key) < lastModified.getTime()) return callback(true);
var cachePath = _cachePath(key);
//exists? necessary to beat race condition with http requests
if(!exists(cachePath)) return callback(true);
callback(null, cachePath);
}
exports.set = function(source, lastModified, content, callback) {
var key = _cacheKey(source);
cfg.set(key, lastModified.getTime());
fs.writeFile(_cachePath(key), content);
} | JavaScript | 0.00036 |
788bbb94da9be5d8f0a8b0b5b173d1a6e463a50e | use native isArray method | lib/check.js | lib/check.js |
/**
* Module dependencies.
*/
var fs = require('fs')
, path = require('path');
/**
* Initialize a `check` instance with the given filename.
*
* @param {String} filename
* @api public
*/
module.exports = function(filename) {
return new check(filename);
};
/**
* Initialize a new `check` with the given filename.
*
* @param {String} filename
* @api private
*/
function check(filename) {
this.filename = filename || '';
this.types = [];
this.valid = null;
};
/**
* Set valid file types.
*
* @param {Array|String} types
* @api public
*/
check.prototype.accept = function(types) {
this.types = types;
return this;
};
/**
* Catch if the filename has passed the validation.
*
* @param {Function} fn
* @api public
*/
check.prototype.pass = function(fn) {
var filename = this.filename;
fn && this._validate(function(result, type) {
result && fn(filename, type);
});
return this;
};
/**
* Catch if the filename failed to validate.
*
* @param {Function} fn
* @api public
*/
check.prototype.fail = function(fn) {
var filename = this.filename;
fn && this._validate(function(result, type) {
result || fn(filename, type);
});
return this;
};
/**
* Check if a file exists and matches the specified file types.
*
* @param {Function} fn
* @api private
*/
check.prototype._validate = function(fn) {
var type = path.extname(this.filename).substr(1)
, hasType = !!this.types.length
, isTypeAccepted = Array.isArray(this.types)
? (!!~this.types.indexOf(type))
: (this.types === type);
if (this.valid !== null) {
fn(this.valid, type);
} else {
fs.stat(this.filename, function(err, stats) {
var result
= this.valid
= hasType
? (stats && stats.isFile() && isTypeAccepted && true || false)
: (stats && stats.isFile() && true || false);
fn(result, type);
});
}
return this;
};
|
/**
* Module dependencies.
*/
var fs = require('fs')
, path = require('path');
/**
* Initialize a `check` instance with the given filename.
*
* @param {String} filename
* @api public
*/
module.exports = function(filename) {
return new check(filename);
};
/**
* Initialize a new `check` with the given filename.
*
* @param {String} filename
* @api private
*/
function check(filename) {
this.filename = filename || '';
this.types = [];
this.valid = null;
};
/**
* Set valid file types.
*
* @param {Array|String} types
* @api public
*/
check.prototype.accept = function(types) {
this.types = types;
return this;
};
/**
* Catch if the filename has passed the validation.
*
* @param {Function} fn
* @api public
*/
check.prototype.pass = function(fn) {
var filename = this.filename;
fn && this._validate(function(result, type) {
result && fn(filename, type);
});
return this;
};
/**
* Catch if the filename failed to validate.
*
* @param {Function} fn
* @api public
*/
check.prototype.fail = function(fn) {
var filename = this.filename;
fn && this._validate(function(result, type) {
result || fn(filename, type);
});
return this;
};
/**
* Check if a file exists and matches the specified file types.
*
* @param {Function} fn
* @api private
*/
check.prototype._validate = function(fn) {
var type = path.extname(this.filename).substr(1)
, hasType = !!this.types.length
, isTypeAccepted = isArray(this.types)
? (!!~this.types.indexOf(type))
: (this.types === type);
if (this.valid !== null) {
fn(this.valid, type);
} else {
fs.stat(this.filename, function(err, stats) {
var result
= this.valid
= hasType
? (stats && stats.isFile() && isTypeAccepted && true || false)
: (stats && stats.isFile() && true || false);
fn(result, type);
});
}
return this;
};
function isArray(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
};
| JavaScript | 0.00007 |
816203edee083d829f93072da5bcf320e7305e08 | fix pypo | lib/handlers/hydrater.js | lib/handlers/hydrater.js | 'use strict';
/**
* @file Define the hydrater endpoint
*
* Will queue requests onto the system file
*
*/
var restify = require('restify');
/**
* This handler receives a document on a POST request and process the document.
*
* @param {Object} req Request object from the client
* @param {Object} res Response we want to return
* @param {Object} server Current server. See implementation in index.js
* @param {Function} next Callback to call once res has been populated.
*/
module.exports = function(req, res, server, logger, next) {
if(!req.params.file_path) {
return next(new restify.BadMethodError('No file to process'));
} else if(!req.params.callback && !req.params.long_poll) {
return next(new restify.BadMethodError('No specified callback'));
}
// Push the new task to the queue
var task = {};
task.file_path = req.params.file_path;
task.callback = req.params.callback;
if(req.params.long_poll) {
task.res = res;
task.next = next;
delete req.params.long_poll;
}
else {
res.send(202);
next();
}
task.document = req.params.document;
task.document.metadatas = task.document.metadatas || {};
task.document.datas = task.document.datas || {};
// Add this new task to queue
server.queue.push(task);
logger("Queuing: " + task.file_path);
};
| 'use strict';
/**
* @file Define the hydrater endpoint
*
* Will queue requests onto the system file
*
*/
var restify = require('restify');
/**
* This handler receives a document on a POST request and process the document.
*
* @param {Object} req Request object from the client
* @param {Object} res Response we want to return
* @param {Object} server Current server. See implementation in index.js
* @param {Function} next Callback to call once res has been populated.
*/
module.exports = function(req, res, server, logger, next) {
if(!req.params.file_path) {
return next(new restify.BadMethodError('No file to process'));
} else if(!req.params.callback && !req.params.long_poll) {
return next(new restify.BadMethodError('No specified callback'));
}
// Push the new task to the queue
var task = {};
task.file_path = req.params.file_path;
task.callback = req.params.callback;
if(req.params.long_poll) {
task.res = res;
task.next = next;
delete req.params.long_poll;
}
else {
res.send(202);
next();
}
task.document = req.params.document;
task.document.metadatas = task.document.metadatas || {};
task.document.datas = task.document.datas || {};
// Add this new task to queue
server.queue.push(task);
logger("Queuing: " + task.file_path);
};
| JavaScript | 0.000003 |
ab2e7b39c16d371cb4127313e827476ee703bd86 | clean up | lib/import-cable-type.js | lib/import-cable-type.js | /**
* @fileOverview read a csv file with cable type details and insert the cable types in mongo.
* @author Dong Liu
*/
var csv = require('csv'),
fs = require('fs'),
path = require('path'),
mongoose = require('mongoose'),
CableType = require('../model/meta.js').CableType;
var inputPath, realPath, db, line = 0,
types = [],
parser, processed = 0,
success = 0;
if (process.argv.length === 3) {
inputPath = process.argv[2];
} else {
console.warn('needs exact one argument for the input csv file path');
process.exit(1);
}
realPath = path.resolve(process.cwd(), inputPath);
if (!fs.existsSync(realPath)) {
console.warn(realPath + ' does not exist.');
console.warn('Please input a valid csv file path.');
process.exit(1);
}
mongoose.connect('mongodb://localhost/cable_frib');
db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
console.log('db connected');
});
function createType(types, i) {
CableType.create({
name: types[i][4] + 'C_' + types[i][5] + '_' + types[i][6] + '_' + types[i][1],
service: types[i][3],
conductorNumber: types[i][4],
conductorSize: types[i][5],
fribType: types[i][6],
typeNumber: types[i][1],
pairing: types[i][7],
shielding: types[i][8],
outerDiameter: types[i][9],
voltageRating: types[i][10],
raceway: types[i][11],
tunnelHotcell: (types[i][12] === 'yes'),
otherRequirements: types[i][13],
createdBy: 'system',
createdOn: Date.now()
}, function (err, doc) {
processed += 1;
if (err) {
console.log(err);
} else {
success += 1;
console.log('New type created with id: ' + doc.id);
}
if (processed === types.length) {
console.log(processed + 'types were processed, and ' + success + ' types were inserted. Bye.');
mongoose.connection.close();
process.exit();
}
});
}
parser = csv.parse();
parser.on('readable', function () {
var record;
do {
record = parser.read();
if (!!record) {
line += 1;
console.log('read ' + line + ' lines ...');
if (record.length > 2 && record[1].length === 3) {
types.push(record);
}
}
} while (!!record);
});
parser.on('error', function (err) {
console.log(err.message);
});
parser.on('finish', function () {
var i;
for (i = 0; i < types.length; i += 1) {
createType(types, i);
}
});
fs.createReadStream(realPath).pipe(parser);
| /**
* @fileOverview read a csv file with cable type details and insert the cable types in mongo.
* @author Dong Liu
*/
var csv = require('csv'),
fs = require('fs'),
path = require('path'),
mongoose = require('mongoose'),
CableType = require('../model/meta.js').CableType;
var inputPath, realPath, db, line = 0,
types = [],
parser, processed = 0,
success = 0;
if (process.argv.length === 3) {
inputPath = process.argv[2];
} else {
console.warn('needs exact one argument for the input csv file path');
process.exit(1);
}
realPath = path.resolve(process.cwd(), inputPath);
if (!fs.existsSync(realPath)) {
console.warn(realPath + ' does not exist.');
console.warn('Please input a valid csv file path.');
process.exit(1);
}
mongoose.connect('mongodb://localhost/cable_frib');
db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
console.log('db connected');
});
// stream = fs.createReadStream(__dirname + '/' + fileName);
function createType(types, i) {
CableType.create({
name: types[i][4] + 'C_' + types[i][5] + '_' + types[i][6] + '_' + types[i][1],
service: types[i][3],
conductorNumber: types[i][4],
conductorSize: types[i][5],
fribType: types[i][6],
typeNumber: types[i][1],
pairing: types[i][7],
shielding: types[i][8],
outerDiameter: types[i][9],
voltageRating: types[i][10],
raceway: types[i][11],
tunnelHotcell: (types[i][12] === 'yes'),
otherRequirements: types[i][13],
createdBy: 'system',
createdOn: Date.now()
}, function (err, doc) {
processed += 1;
if (err) {
console.log(err);
} else {
success += 1;
console.log('New type created with id: ' + doc.id);
}
if (processed === types.length) {
console.log(processed + 'types were processed, and ' + success + ' types were inserted. Bye.');
mongoose.connection.close();
process.exit();
}
});
}
parser = csv.parse();
parser.on('readable', function () {
var record;
do {
record = parser.read();
if (!!record) {
line += 1;
console.log('read ' + line + ' lines ...');
if (record.length > 2 && record[1].length === 3) {
types.push(record);
}
}
} while (!!record);
});
parser.on('error', function (err) {
console.log(err.message);
});
parser.on('finish', function () {
var i;
for (i = 0; i < types.length; i += 1) {
createType(types, i);
}
});
fs.createReadStream(realPath).pipe(parser);
| JavaScript | 0.000001 |
a931624215682a5608bd496ad5145d1dbc5875d3 | Move init to #run | lib/impulse-bin/index.js | lib/impulse-bin/index.js | /**
* Modules for commander.js and others
*
* Licensed under MIT.
* Copyright (c) 2013 David Smith <https://github.com/codeactual/>
*/
/*jshint node:true*/
'use strict';
module.exports = {
ImpulseBin: ImpulseBin,
create: function() { return new ImpulseBin(); },
extend: function(ext) { extend(ImpulseBin.prototype, ext); }
};
var util = require('util');
var sprintf = util.format;
var requireComponent = require('../component/require');
var configurable = requireComponent('configurable.js');
var extend = requireComponent('extend');
function ImpulseBin() {
this.settings = {
adapter: 'commander',
quietOption: 'quiet',
requiredOptionTmpl: '--%s is required',
verboseOption: 'verbose',
verboseLogName: '[verbose]',
stdoutLogName: '[stdout]',
stderrLogName: '[stderr]'
};
// Assigned in run():
this.adapter = null; // Ex. require('./lib/adapter/commander.js')
this.options = {}; // Ex, commander options object from adapter
this.provider = null; // Ex. commander module after parse()
this.console = require('long-con').create();
}
configurable(ImpulseBin.prototype);
/**
* Wrap adapter require() for stubbing.
*
* @param {string} name Ex. 'commander'
*/
ImpulseBin.prototype.loadAdapter = function(name) {
return require('../adapter/' + this.get('adapter'));
};
/**
* Run the module (function) with a prepared context.
*
* @param {object} provider Ex. commander.js parse() output
* @param {function} handler Handles CLI options/args from provider
*/
ImpulseBin.prototype.run = function(provider, handler) {
var self = this;
var bind = requireComponent('bind');
var each = requireComponent('each');
var extend = requireComponent('extend');
this.adapter = this.loadAdapter();
this.options = this.adapter.options(provider);
this.provider = provider;
this.stderr = this.console.create(this.get('stderrLogName'), console.error, 'red');
this.stdout = this.console.create(this.get('stdoutLogName'), console.log);
this.verbose = this.createVerbose();
this.console.set('quiet', this.options[this.get('quietOption')]);
var context = {
args: this.adapter.args(provider),
child_process: require('child_process'),
clc: this.clc,
fs: require('fs'),
options: this.options,
provider: provider,
shelljs: require('outer-shelljs').create(),
util: util
};
handler.call(extend(context, this));
};
ImpulseBin.prototype.createVerbose = function(name) {
if (!this.options[this.get('verboseOption')]) { return impulseBinNoOp; }
return this.console.create(this.get('verboseLogName'), console.log);
};
ImpulseBin.prototype.exit = function(msg, code) {
this.stderr(msg);
process.exit(typeof code === 'undefined' ? 1 : code);
};
/**
* Exit if the given CLI options are undefined.
*
* @param {string|array} key
* @param {number} exitCode
*/
ImpulseBin.prototype.exitOnMissingOption = function(key, exitCode) {
var self = this;
[].concat(key).forEach(function(key) {
if (typeof self.options[key] === 'undefined') {
self.exit(sprintf(self.get('requiredOptionTmpl'), key), exitCode);
}
});
};
ImpulseBin.prototype.exitOnShelljsErr = function(res) {
if (res.code !== 0) { this.exit(res.output, res.code); }
};
function defClrFn(str) { return str; }
function impulseBinNoOp() {}
| /**
* Modules for commander.js and others
*
* Licensed under MIT.
* Copyright (c) 2013 David Smith <https://github.com/codeactual/>
*/
/*jshint node:true*/
'use strict';
module.exports = {
ImpulseBin: ImpulseBin,
create: function() { return new ImpulseBin(); },
extend: function(ext) { extend(ImpulseBin.prototype, ext); }
};
var util = require('util');
var sprintf = util.format;
var requireComponent = require('../component/require');
var configurable = requireComponent('configurable.js');
var extend = requireComponent('extend');
function ImpulseBin() {
this.settings = {
adapter: 'commander',
quietOption: 'quiet',
requiredOptionTmpl: '--%s is required',
verboseOption: 'verbose',
verboseLogName: '[verbose]',
stdoutLogName: '[stdout]',
stderrLogName: '[stderr]'
};
// Assigned in run():
this.adapter = null; // Ex. require('./lib/adapter/commander.js')
this.options = {}; // Ex, commander options object from adapter
this.provider = null; // Ex. commander module after parse()
this.console = require('long-con').create();
this.verbose = this.createVerbose();
}
configurable(ImpulseBin.prototype);
/**
* Wrap adapter require() for stubbing.
*
* @param {string} name Ex. 'commander'
*/
ImpulseBin.prototype.loadAdapter = function(name) {
return require('../adapter/' + this.get('adapter'));
};
/**
* Run the module (function) with a prepared context.
*
* @param {object} provider Ex. commander.js parse() output
* @param {function} handler Handles CLI options/args from provider
*/
ImpulseBin.prototype.run = function(provider, handler) {
var self = this;
var bind = requireComponent('bind');
var each = requireComponent('each');
var extend = requireComponent('extend');
this.adapter = this.loadAdapter();
this.options = this.adapter.options(provider);
this.provider = provider;
this.stderr = this.console.create(this.get('stderrLogName'), console.error, 'red');
this.stdout = this.console.create(this.get('stdoutLogName'), console.log);
this.console.set('quiet', this.options[this.get('quietOption')]);
var context = {
args: this.adapter.args(provider),
child_process: require('child_process'),
clc: this.clc,
fs: require('fs'),
options: this.options,
provider: provider,
shelljs: require('outer-shelljs').create(),
util: util
};
handler.call(extend(context, this));
};
ImpulseBin.prototype.createVerbose = function(name) {
if (!this.options[this.get('verboseOption')]) { return impulseBinNoOp; }
return this.console.create(this.get('verboseLogName'), console.log);
};
ImpulseBin.prototype.exit = function(msg, code) {
this.stderr(msg);
process.exit(typeof code === 'undefined' ? 1 : code);
};
/**
* Exit if the given CLI options are undefined.
*
* @param {string|array} key
* @param {number} exitCode
*/
ImpulseBin.prototype.exitOnMissingOption = function(key, exitCode) {
var self = this;
[].concat(key).forEach(function(key) {
if (typeof self.options[key] === 'undefined') {
self.exit(sprintf(self.get('requiredOptionTmpl'), key), exitCode);
}
});
};
ImpulseBin.prototype.exitOnShelljsErr = function(res) {
if (res.code !== 0) { this.exit(res.output, res.code); }
};
function defClrFn(str) { return str; }
function impulseBinNoOp() {}
| JavaScript | 0.00001 |
604e28533ce36dbf7c3e5ddd299cbec5a717b82e | Fix and improve test | test/acceptance/batch/leader-multiple-users-query-order.test.js | test/acceptance/batch/leader-multiple-users-query-order.test.js | require('../../helper');
var assert = require('../../support/assert');
var TestClient = require('../../support/test-client');
var BatchTestClient = require('../../support/batch-test-client');
var JobStatus = require('../../../batch/job_status');
describe('multiple batch clients and users, job query order', function() {
before(function(done) {
this.batchTestClientA = new BatchTestClient({ name: 'consumerA' });
this.batchTestClientB = new BatchTestClient({ name: 'consumerB' });
this.testClient = new TestClient();
this.testClient.getResult(
[
'drop table if exists ordered_inserts_a',
'drop table if exists ordered_inserts_bbbbb',
'create table ordered_inserts_a (status numeric)',
'create table ordered_inserts_bbbbb (status numeric)'
].join(';'),
done
);
});
after(function (done) {
this.batchTestClientA.drain(function(err) {
if (err) {
return done(err);
}
this.batchTestClientB.drain(done);
}.bind(this));
});
function createJob(queries) {
return {
query: queries
};
}
it('should run job queries in order (multiple consumers)', function (done) {
var jobRequestA1 = createJob([
"insert into ordered_inserts_a values(1)",
"select pg_sleep(0.25)",
"insert into ordered_inserts_a values(2)"
]);
var jobRequestA2 = createJob([
"insert into ordered_inserts_a values(3)"
]);
var jobRequestB1 = createJob([
"insert into ordered_inserts_bbbbb values(1)"
]);
var self = this;
this.batchTestClientA.createJob(jobRequestA1, function(err, jobResultA1) {
if (err) {
return done(err);
}
var override = { host: 'cartodb250user.cartodb.com' };
self.batchTestClientB.createJob(jobRequestB1, override, function(err, jobResultB1) {
if (err) {
return done(err);
}
// we don't care about the producer
self.batchTestClientB.createJob(jobRequestA2, function(err, jobResultA2) {
if (err) {
return done(err);
}
jobResultA1.getStatus(function (err, jobA1) {
if (err) {
return done(err);
}
jobResultA2.getStatus(function(err, jobA2) {
if (err) {
return done(err);
}
jobResultB1.getStatus(function(err, jobB1) {
assert.equal(jobA1.status, JobStatus.DONE);
assert.equal(jobA2.status, JobStatus.DONE);
assert.equal(jobB1.status, JobStatus.DONE);
assert.ok(
new Date(jobA1.updated_at).getTime() < new Date(jobA2.updated_at).getTime(),
'A1 (' + jobA1.updated_at + ') ' +
'should finish before A2 (' + jobA2.updated_at + ')'
);
assert.ok(
new Date(jobB1.updated_at).getTime() < new Date(jobA1.updated_at).getTime(),
'B1 (' + jobA1.updated_at + ') ' +
'should finish before A1 (' + jobA1.updated_at + ')'
);
function statusMapper (status) { return { status: status }; }
self.testClient.getResult('select * from ordered_inserts_a', function(err, rows) {
assert.ok(!err);
// cartodb250user and vizzuality test users share database
var expectedRows = [1, 2, 3].map(statusMapper);
assert.deepEqual(rows, expectedRows);
var query = 'select * from ordered_inserts_bbbbb';
self.testClient.getResult(query, override, function(err, rows) {
assert.ok(!err);
var expectedRows = [1].map(statusMapper);
assert.deepEqual(rows, expectedRows);
done();
});
});
});
});
});
});
});
});
});
});
| require('../../helper');
var assert = require('../../support/assert');
var TestClient = require('../../support/test-client');
var BatchTestClient = require('../../support/batch-test-client');
var JobStatus = require('../../../batch/job_status');
describe('multiple batch clients and users, job query order', function() {
before(function(done) {
this.batchTestClientA = new BatchTestClient({ name: 'consumerA' });
this.batchTestClientB = new BatchTestClient({ name: 'consumerB' });
this.testClientA = new TestClient();
this.testClientA.getResult(
'drop table if exists ordered_inserts; create table ordered_inserts (status numeric)',
done
);
});
after(function (done) {
this.batchTestClientA.drain(function(err) {
if (err) {
return done(err);
}
this.batchTestClientB.drain(done);
}.bind(this));
});
function createJob(queries) {
return {
query: queries
};
}
it('should run job queries in order (multiple consumers)', function (done) {
var jobRequestA1 = createJob([
"insert into ordered_inserts values(1)",
"select pg_sleep(0.25)",
"insert into ordered_inserts values(2)"
]);
var jobRequestA2 = createJob([
"insert into ordered_inserts values(3)"
]);
var jobRequestB1 = createJob([
"insert into ordered_inserts values(4)"
]);
var self = this;
this.batchTestClientA.createJob(jobRequestA1, function(err, jobResultA1) {
if (err) {
return done(err);
}
// we don't care about the producer
self.batchTestClientB.createJob(jobRequestA2, function(err, jobResultA2) {
if (err) {
return done(err);
}
var override = { host: 'cartodb250user.cartodb.com' };
self.batchTestClientB.createJob(jobRequestB1, override, function(err, jobResultB1) {
if (err) {
return done(err);
}
jobResultA1.getStatus(function (err, jobA1) {
if (err) {
return done(err);
}
jobResultA2.getStatus(function(err, jobA2) {
if (err) {
return done(err);
}
jobResultB1.getStatus(function(err, jobB1) {
assert.equal(jobA1.status, JobStatus.DONE);
assert.equal(jobA2.status, JobStatus.DONE);
assert.equal(jobB1.status, JobStatus.DONE);
self.testClientA.getResult('select * from ordered_inserts', function(err, rows) {
assert.ok(!err);
// cartodb250user and vizzuality test users share database
var expectedRows = [1, 4, 2, 3].map(function(status) { return {status: status}; });
assert.deepEqual(rows, expectedRows);
assert.ok(
new Date(jobA1.updated_at).getTime() < new Date(jobA2.updated_at).getTime(),
'A1 (' + jobA1.updated_at + ') ' +
'should finish before A2 (' + jobA2.updated_at + ')'
);
assert.ok(
new Date(jobB1.updated_at).getTime() < new Date(jobA1.updated_at).getTime(),
'B1 (' + jobA1.updated_at + ') ' +
'should finish before A1 (' + jobA1.updated_at + ')'
);
done();
});
});
});
});
});
});
});
});
});
| JavaScript | 0.000001 |
30b8c22189d25378d3db1e986b30d6766776da34 | fix js message when no collection | Resources/public/arkounay_image_bundle.js | Resources/public/arkounay_image_bundle.js | // Refresh thumbnails :
function readURL(input, $img) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$img.show();
$img.attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
function refreshThumbnail(){
$(".form-with-image .form-image input[type=file]").change(function(){
readURL(this, $(this).closest('.row').find('.js-img'));
});
}
refreshThumbnail();
$(function(){
function updateImageFromPath($pacImage) {
var val = $pacImage.find('.arkounay-image-path').val();
if (val !== '') {
$pacImage.find('img').attr('src', val);
}
}
function submitFile(file, $image) {
var formData = new FormData();
formData.append('file', file);
var $progress = $image.find('progress');
$.ajax({
url: url,
type: 'POST',
xhr: function () {
var xhr = $.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function (e) {
if (e.lengthComputable) {
$progress.show();
$progress.attr({value: e.loaded, max: e.total});
} else {
$progress.hide();
}
}, false);
}
return xhr;
},
success: function (res) {
if (res[0] !== false) {
$image.find('.arkounay-image-path').val(res[0]);
updateImageFromPath($image);
} else {
alert("Le fichier spécifié (" + file.name + ") n'a pas pu être envoyé sur le serveur.\n\nSeules les images sont autorisés.");
}
$progress.hide();
},
error: function() {
alert("Une erreur est survenue lors de l'envoi du fichier " + file.name + ".");
$progress.hide();
},
data: formData,
cache: false,
contentType: false,
processData: false
});
}
var arkounayImageSel = '.arkounay-image';
$(document).on('click', '.arkounay-image-button-upload', function (e) {
e.preventDefault();
e.stopPropagation();
$(this).parent().find('.arkounay-image-file-input').click();
});
$(document).on('change', '.arkounay-image-file-input', function () {
var file = this.files[0];
submitFile(file, $(this).closest('.arkounay-image'));
});
$(document).on('drag dragstart dragend dragover dragenter dragleave drop', arkounayImageSel, function(e) {
e.preventDefault();
e.stopPropagation();
})
.on('dragover dragenter', arkounayImageSel, function() {
$(this).addClass('is-dragover');
})
.on('dragleave dragend drop', arkounayImageSel, function() {
$(this).removeClass('is-dragover');
})
.on('drop', arkounayImageSel, function(e) {
submitFile(e.originalEvent.dataTransfer.files[0], $(this))
});
$(document).on('change', '.arkounay-image-path', function () {
updateImageFromPath($(this).closest('.arkounay-image'));
});
$.each($(arkounayImageSel), function(i, el) {
updateImageFromPath($(el));
});
$collection = $('.arkounay-image-collection');
if ($collection.length) {
$collection.collection({
up: '<a href="#">▲</a>',
down: '<a href="#">▼</a>',
add: '<a href="#" class="btn btn-default"><span class="glyphicon glyphicon-plus"></span> ' + addStr + '</a>',
remove: '<a href="#" class="btn btn-default"><span class="glyphicon glyphicon-trash"></span> Supprimer</a>',
duplicate: '<a href="#">[ # ]</a>',
add_at_the_end: true
});
}
}); | // Refresh thumbnails :
function readURL(input, $img) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$img.show();
$img.attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
function refreshThumbnail(){
$(".form-with-image .form-image input[type=file]").change(function(){
readURL(this, $(this).closest('.row').find('.js-img'));
});
}
refreshThumbnail();
$(function(){
function updateImageFromPath($pacImage) {
var val = $pacImage.find('.arkounay-image-path').val();
if (val !== '') {
$pacImage.find('img').attr('src', val);
}
}
function submitFile(file, $image) {
var formData = new FormData();
formData.append('file', file);
var $progress = $image.find('progress');
$.ajax({
url: url,
type: 'POST',
xhr: function () {
var xhr = $.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function (e) {
if (e.lengthComputable) {
$progress.show();
$progress.attr({value: e.loaded, max: e.total});
} else {
$progress.hide();
}
}, false);
}
return xhr;
},
success: function (res) {
if (res[0] !== false) {
$image.find('.arkounay-image-path').val(res[0]);
updateImageFromPath($image);
} else {
alert("Le fichier spécifié (" + file.name + ") n'a pas pu être envoyé sur le serveur.\n\nSeules les images sont autorisés.");
}
$progress.hide();
},
error: function() {
alert("Une erreur est survenue lors de l'envoi du fichier " + file.name + ".");
$progress.hide();
},
data: formData,
cache: false,
contentType: false,
processData: false
});
}
var arkounayImageSel = '.arkounay-image';
$(document).on('click', '.arkounay-image-button-upload', function (e) {
e.preventDefault();
e.stopPropagation();
$(this).parent().find('.arkounay-image-file-input').click();
});
$(document).on('change', '.arkounay-image-file-input', function () {
var file = this.files[0];
submitFile(file, $(this).closest('.arkounay-image'));
});
$(document).on('drag dragstart dragend dragover dragenter dragleave drop', arkounayImageSel, function(e) {
e.preventDefault();
e.stopPropagation();
})
.on('dragover dragenter', arkounayImageSel, function() {
$(this).addClass('is-dragover');
})
.on('dragleave dragend drop', arkounayImageSel, function() {
$(this).removeClass('is-dragover');
})
.on('drop', arkounayImageSel, function(e) {
submitFile(e.originalEvent.dataTransfer.files[0], $(this))
});
$(document).on('change', '.arkounay-image-path', function () {
updateImageFromPath($(this).closest('.arkounay-image'));
});
$.each($(arkounayImageSel), function(i, el) {
updateImageFromPath($(el));
});
$('.arkounay-image-collection').collection({
up: '<a href="#">▲</a>',
down: '<a href="#">▼</a>',
add: '<a href="#" class="btn btn-default"><span class="glyphicon glyphicon-plus"></span> ' + addStr + '</a>',
remove: '<a href="#" class="btn btn-default"><span class="glyphicon glyphicon-trash"></span> Supprimer</a>',
duplicate: '<a href="#">[ # ]</a>',
add_at_the_end: true
});
}); | JavaScript | 0.000001 |
a805017c4690ef9ccaf512269d1c250dcc8b52ff | Add support for --log-file. | lib/entry.js | lib/entry.js | var child_process = require('child_process');
var fs = require('fs');
var path = require('path');
var optimist = require('optimist');
var app = require('./web/app');
var settings = require('./settings');
var crawler = require('./crawler/app');
var utils = require('./utils');
var _ = require('underscore');
exports.run = function() {
var argv;
var child_args;
var log_file;
optimist = optimist.usage('Usage: $0 [-l 0.0.0.0] -p [port] -d [devops.json] [-D] [-c] [-h]');
optimist = optimist['default']('l', '0.0.0.0');
optimist = optimist.describe('l', 'Listening address');
optimist = optimist['default']('p', 3000);
optimist = optimist['default']('d', settings.saved_crawls_path);
optimist = optimist['default']('c', false);
optimist = optimist['default']('h', false);
optimist = optimist['default']('D', false);
optimist = optimist.alias('c', 'crawler');
optimist = optimist.describe('c', 'Run the crawler to update devops.json');
optimist = optimist.describe('D', 'Detach and run as a service');
optimist = optimist.describe('log-file', 'File to log output to');
optimist = optimist.alias('h', 'help');
optimist = optimist.describe('h', 'Print usage help');
argv = optimist.argv;
if (argv.h) {
optimist.showHelp(console.log);
process.exit();
}
if (argv.c) {
crawler.run(argv);
process.exit();
}
if (argv['log-file']) {
log_file = fs.createWriteStream(argv['log-file'], { flags: 'a' });
// process.stderr.pipe(log_file) doesn't work in node 0.6 and later
process.__defineGetter__('stdout', function() { return log_file; });
process.__defineGetter__('stderr', function() { return log_file; });
}
if (argv.D) {
child_args = process.argv.slice(2);
child_args = child_args.filter(function (element) {
return (element != '-D');
});
child_process.fork('./lib/entry.js', child_args);
process.exit();
}
app.run(argv);
console.log("Gutsy now listening on", argv.l + ":" + argv.p);
};
exports.run();
| var child_process = require('child_process');
var fs = require('fs');
var path = require('path');
var optimist = require('optimist');
var app = require('./web/app');
var settings = require('./settings');
var crawler = require('./crawler/app');
var utils = require('./utils');
var _ = require('underscore');
exports.run = function() {
var argv;
var child_args;
optimist = optimist.usage('Usage: $0 [-l 0.0.0.0] -p [port] -d [devops.json] [-D] [-c] [-h]');
optimist = optimist['default']('l', '0.0.0.0');
optimist = optimist.describe('l', 'Listening address');
optimist = optimist['default']('p', 3000);
optimist = optimist['default']('d', settings.saved_crawls_path);
optimist = optimist['default']('c', false);
optimist = optimist['default']('h', false);
optimist = optimist['default']('D', false);
optimist = optimist.alias('c', 'crawler');
optimist = optimist.describe('c', 'Run the crawler to update devops.json');
optimist = optimist.describe('D', 'Detach and run as a service');
optimist = optimist.alias('h', 'help');
optimist = optimist.describe('h', 'Print usage help');
argv = optimist.argv;
if (argv.h) {
optimist.showHelp(console.log);
} else if (argv.c) {
crawler.run(argv);
} else if (argv.D) {
child_args = process.argv.slice(2);
child_args = child_args.filter(function (element) {
return (element != '-D');
});
child_process.fork('./lib/entry.js', child_args);
process.exit();
} else {
app.run(argv);
console.log("Gutsy now listening on", argv.l + ":" + argv.p);
}
};
exports.run();
| JavaScript | 0 |
539b3dd598b6e97ca80e7dd342e3d4713eba973b | Update copied and pasted test description | components/norg-app/test/norg-app.test.js | components/norg-app/test/norg-app.test.js | import { html, fixture, expect } from '@open-wc/testing';
import '../norg-app.js';
describe('NorgApp', () => {
it('renders the nodes table', async () => {
const el = await fixture(html`
<norg-app></norg-app>
`);
expect(el.shadowRoot.querySelector('main')).lightDom.to.contain(
'norg-nodes-table');
});
it('controls the drawer menu', async () => {
const el = await fixture(html`
<norg-app></norg-app>
`);
const drawer = el.shadowRoot.querySelector('mwc-drawer');
const button = drawer.querySelector('mwc-icon-button');
expect(drawer.open).to.be.false;
button.click();
expect(drawer.open).to.be.true;
});
it('matches the snapshot', async () => {
const el = await fixture(html`
<norg-app></norg-app>
`);
expect(el).shadowDom.to.equalSnapshot();
});
it('passes the a11y audit', async () => {
const el = await fixture(html`
<norg-app></norg-app>
`);
await expect(el).shadowDom.to.be.accessible({ignoredRules: ['aria-allowed-role']});
});
});
| import { html, fixture, expect } from '@open-wc/testing';
import '../norg-app.js';
describe('NorgApp', () => {
it('renders the nodes table', async () => {
const el = await fixture(html`
<norg-app></norg-app>
`);
expect(el.shadowRoot.querySelector('main')).lightDom.to.contain(
'norg-nodes-table');
});
it('changes the page if a menu link gets clicked', async () => {
const el = await fixture(html`
<norg-app></norg-app>
`);
const drawer = el.shadowRoot.querySelector('mwc-drawer');
const button = drawer.querySelector('mwc-icon-button');
expect(drawer.open).to.be.false;
button.click();
expect(drawer.open).to.be.true;
});
it('matches the snapshot', async () => {
const el = await fixture(html`
<norg-app></norg-app>
`);
expect(el).shadowDom.to.equalSnapshot();
});
it('passes the a11y audit', async () => {
const el = await fixture(html`
<norg-app></norg-app>
`);
await expect(el).shadowDom.to.be.accessible({ignoredRules: ['aria-allowed-role']});
});
});
| JavaScript | 0 |
b73a2af61ea5655fdbf3b53ff42a2a20f9817b92 | change resolving of cascades files | lib/faced.js | lib/faced.js | /*jslint node: true, nomen:true*/
"use strict";
var _ = require("underscore");
var OpenCV = require("opencv");
var Detector = require("./detector");
var path = require('path');
var hc_path = path.join( path.dirname(require.resolve("opencv")), '..', 'data');
var cascades = {
"face": path.join(hc_path, "haarcascade_frontalface_alt2.xml") ,
"mouth": path.join(hc_path, "haarcascade_mcs_mouth.xml") ,
"nose": path.join(hc_path, "haarcascade_mcs_nose.xml") ,
"eyeLeft": path.join(hc_path, "haarcascade_mcs_lefteye.xml") ,
"eyeRight": path.join(hc_path, "haarcascade_mcs_righteye.xml")
};
var Faced = function () {
var element;
this.cascades = {};
_.each(cascades, function (path, element) {
this.cascades[element] = new OpenCV.CascadeClassifier(path);
}, this);
};
Faced.prototype.detect = function (path, fn, context) {
if (!this.cascades) {
throw new Error("Faced has been destroyed");
}
OpenCV.readImage(path, _.bind(function (err, img) {
var detector, size;
if (err || typeof img !== "object") {
return fn.call(context, undefined, undefined, path);
}
size = img.size();
if (size[0] === 0 || size[1] === 0) {
return fn.call(context, undefined, undefined, path);
}
detector = new Detector(this.cascades);
detector.run(img, function (faces) {
fn.call(context, faces, img, path);
});
}, this));
};
Faced.prototype.destroy = function () {
delete this.cascades;
}
module.exports = Faced; | /*jslint node: true, nomen:true*/
"use strict";
var _ = require("underscore");
var OpenCV = require("opencv");
var Detector = require("./detector");
var cascades = {
"face": "../node_modules/opencv/data/haarcascade_frontalface_alt2.xml",
"mouth": "../node_modules/opencv/data/haarcascade_mcs_mouth.xml",
"nose": "../node_modules/opencv/data/haarcascade_mcs_nose.xml",
"eyeLeft": "../node_modules/opencv/data/haarcascade_mcs_lefteye.xml",
"eyeRight": "../node_modules/opencv/data/haarcascade_mcs_righteye.xml"
};
var Faced = function () {
var element;
this.cascades = {};
_.each(cascades, function (path, element) {
this.cascades[element] = new OpenCV.CascadeClassifier(__dirname + "/" + path);
}, this);
};
Faced.prototype.detect = function (path, fn, context) {
if (!this.cascades) {
throw new Error("Faced has been destroyed");
}
OpenCV.readImage(path, _.bind(function (err, img) {
var detector, size;
if (err || typeof img !== "object") {
return fn.call(context, undefined, undefined, path);
}
size = img.size();
if (size[0] === 0 || size[1] === 0) {
return fn.call(context, undefined, undefined, path);
}
detector = new Detector(this.cascades);
detector.run(img, function (faces) {
fn.call(context, faces, img, path);
});
}, this));
};
Faced.prototype.destroy = function () {
delete this.cascades;
}
module.exports = Faced; | JavaScript | 0 |
21e0366b6e16160d38cc14eec7d8fc0e0803350c | Fix lint | src/overridable.js | src/overridable.js | import React, { PureComponent } from 'react'
import { withPropsFromContext } from 'react-context-props'
export default (styles = {}, designName) => Target => {
class OverridableComponent extends PureComponent {
constructor(props) {
super(props)
this.designName = designName || Target.displayName || Target.name
this.Component = Target
}
getOverride() {
if (!this.props.design.getOverrideFor) {
return { ...styles, ...this.props.styles }
}
const override = this.props.design.getOverrideFor(
Object.assign(Target, { designName: this.designName })
)
this.Component = override.Component
return { ...styles, ...this.props.styles, ...override.css }
}
render() {
const { design, ...otherProps } = this.props // eslint-disable-line
const props = { ...otherProps, styles: this.getOverride() }
return <this.Component {...props} />
}
}
OverridableComponent.displayName = Target.displayName || Target.name
OverridableComponent.defaultProps = {
design: {},
styles: {},
}
return withPropsFromContext(['design'])(OverridableComponent)
}
| import React, {PureComponent} from 'react'
import {withPropsFromContext} from 'react-context-props'
export default (styles = {}, designName) => Target => {
class OverridableComponent extends PureComponent {
constructor(props) {
super(props)
this.designName = designName || Target.displayName || Target.name
this.Component = Target
}
getOverride() {
if (!this.props.design.getOverrideFor) {
return {...styles, ...this.props.styles}
}
const override = this.props.design.getOverrideFor(
Object.assign(Target, {designName: this.designName})
)
this.Component = override.Component
return {...styles, ...this.props.styles, ...override.css}
}
render() {
const {design, ...otherProps} = this.props // eslint-disable-line
const props = {...otherProps, styles: this.getOverride()}
return <this.Component {...props} />
}
}
OverridableComponent.displayName = Target.displayName || Target.name
OverridableComponent.defaultProps = {
design: {},
styles: {},
}
return withPropsFromContext(['design'])(OverridableComponent)
}
| JavaScript | 0.000032 |
f1d2871905f49a3c2597d124e3edfe1bbd67518d | _parent._parent in event | lib/event/index.js | lib/event/index.js | 'use strict'
const delegateEvent = require('./delegate')
const addListener = require('./listener')
exports.properties = {
hasEvents: true
}
exports.on = {
Child: {
define: {
eventCache: {
value: {}
},
key: {
set (val) {
// dangerous for context!
this._parent._parent.setKey('hasEvents', true, false)
const cache = this.eventCache
if (!cache[val]) {
cache[val] = true
addListener(val, (e) => delegateEvent(val, e))
}
this._key = val
},
get (val) {
return this._key
}
}
}
}
}
| 'use strict'
const delegateEvent = require('./delegate')
const addListener = require('./listener')
exports.properties = {
hasEvents: true
}
exports.on = {
Child: {
define: {
eventCache: {
value: {}
},
key: {
set (val) {
this.parent.parent.setKey('hasEvents', true, false)
const cache = this.eventCache
if (!cache[val]) {
cache[val] = true
addListener(val, (e) => delegateEvent(val, e))
}
this._key = val
},
get (val) {
return this._key
}
}
}
}
}
| JavaScript | 1 |
ef3c9923f653fbec4e4164b252efb06605c385ee | Fix linting errors | src/pat/masonry.js | src/pat/masonry.js | /**
* Patternslib pattern for Masonry
* Copyright 2015 Syslab.com GmBH
*/
(function (root, factory) {
if (typeof define === "function" && define.amd) {
define([
"jquery",
"pat-registry",
"pat-parser",
"masonry",
"imagesloaded"
], function() {
return factory.apply(this, arguments);
});
} else {
factory(root.$, root.patterns, root.patterns.Parser, root.Masonry, root.imagesLoaded);
}
}(this, function($, registry, Parser, Masonry, imagesLoaded) {
"use strict";
var parser = new Parser("masonry");
parser.add_argument("column-width");
parser.add_argument("container-style", "{ position: 'relative' }");
parser.add_argument("gutter");
parser.add_argument("hidden-style", "{ opacity: 0, transform: 'scale(0.001)' }");
parser.add_argument("is-fit-width", false);
parser.add_argument("is-origin-left", true);
parser.add_argument("is-origin-top", true);
parser.add_argument("item-selector", ".item");
parser.add_argument("stamp", "");
parser.add_argument("transition-duration", "0.4s");
parser.add_argument("visible-style", "{ opacity: 1, transform: 'scale(1)' }");
var masonry = {
name: "masonry",
trigger: ".pat-masonry",
init: function mypattern_init($el, opts) {
var options = parser.parse($el, opts);
imagesLoaded(this, $.proxy(function() {
new Masonry($el[0], {
columnWidth: this.getTypeCastedValue(options.columnWidth),
containerStyle: options.containerStyle,
gutter: this.getTypeCastedValue(options.gutter),
hiddenStyle: options.hiddenStyle,
isFitWidth: options.is["fit-width"],
isOriginTOp: options.is["origin-top"],
isOriginLeft: options.is["origin-left"],
itemSelector: options.itemSelector,
stamp: options.stamp,
transitionDuration: options.transitionDuration,
visibleStyle: options.visibleStyle
});
}, this));
},
getTypeCastedValue: function (original) {
var val = Number(original);
if (isNaN(val)) {
val = original || 0;
}
return val;
}
};
registry.register(masonry);
}));
| /**
* Patternslib pattern for Masonry
* Copyright 2015 Syslab.com GmBH
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define([
"pat-registry",
"pat-parser",
"masonry",
"imagesloaded"
], function() {
return factory.apply(this, arguments);
});
} else {
factory(root.patterns, root.patterns.Parser, root.Masonry, root.imagesLoaded);
}
}(this, function(registry, Parser, Masonry, imagesLoaded) {
"use strict";
var parser = new Parser("masonry");
parser.add_argument("column-width");
parser.add_argument("container-style", "{ position: 'relative' }");
parser.add_argument("gutter");
parser.add_argument("hidden-style", "{ opacity: 0, transform: 'scale(0.001)' }");
parser.add_argument("is-fit-width", false);
parser.add_argument("is-origin-left", true);
parser.add_argument("is-origin-top", true);
parser.add_argument("item-selector", ".item");
parser.add_argument("stamp", "");
parser.add_argument("transition-duration", "0.4s");
parser.add_argument("visible-style", "{ opacity: 1, transform: 'scale(1)' }");
var masonry = {
name: "masonry",
trigger: ".pat-masonry",
init: function mypattern_init($el, opts) {
var options = parser.parse($el, opts);
imagesLoaded(this, $.proxy(function() {
new Masonry($el[0], {
columnWidth: this.getTypeCastedValue(options.columnWidth),
containerStyle: options.containerStyle,
gutter: this.getTypeCastedValue(options.gutter),
hiddenStyle: options.hiddenStyle,
isFitWidth: options.is['fit-width'],
isOriginTOp: options.is['origin-top'],
isOriginLeft: options.is['origin-left'],
itemSelector: options.itemSelector,
stamp: options.stamp,
transitionDuration: options.transitionDuration,
visibleStyle: options.visibleStyle,
});
}, this));
},
getTypeCastedValue: function (original) {
var val = Number(original);
if (isNaN(val)) {
val = original || 0;
}
return val;
}
};
registry.register(masonry);
}));
| JavaScript | 0.000075 |
9c48a19e7db09ae624a5249a17fa7cc50c3f062f | create require name for custom modules | lib/flow.client.js | lib/flow.client.js | var Flow = require('flow');
var server = require('./socket');
// init flow with core module
var CoreInst = Flow({
// load module bundles and return the entry-point exports
module: function (name, callback) {
// crate script dom element
var node = document.createElement('script');
node.onload = function () {
node.remove();
name = name[0] === '/' ? name + '/bundle.js' : name;
callback(null, require(name));
};
// set url and append dom script elm to the document head
node.src = name[0] === '/' ? '/app_module' : '/module/';
node.src += name + '/bundle.js';
document.head.appendChild(node);
},
// load composition
composition: function (name, callback) {
this.flow('C/' + name, {
net: '/',
to: '@'
}, function (err, composition) {
composition = JSON.parse(composition);
composition._roles = {'*': true};
callback(err, composition);
});
},
request: server.request,
// Load html snippets.
markup: function (urls, callback) {
var self = this;
var count = 0;
var snippets = {};
var errorHappend;
var next = function (url, index) {
self.flow(url, {net: '/'}, function (err, snippet) {
if (errorHappend) {
return;
}
if (err) {
errorHappend = true;
return callback(err);
}
snippets[url] = snippet;
if (++count === urls.length) {
callback(null, snippets, true);
}
});
};
urls.forEach(next);
},
// Load css files.
styles: function (urls) {
urls.forEach(function (url) {
var link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.setAttribute('href', url);
global.document.head.appendChild(link);
});
},
reset: function () {
// reset module instances
CoreInst.reset();
// reset DOM body
document.body.innerHTML = '';
// remove styles
var styles = document.head.querySelectorAll('link[rel=stylesheet]');
if (styles) {
styles.forEach(function (stylesheet) {
stylesheet.remove();
});
}
// reset server
server.reset();
// load entrypoint
CoreInst.load('*');
}
});
CoreInst.load('*');
| var Flow = require('flow');
var server = require('./socket');
// init flow with core module
var CoreInst = Flow({
// load module bundles and return the entry-point exports
module: function (name, callback) {
// crate script dom element
var node = document.createElement('script');
node.onload = function () {
node.remove();
callback(null, require(name));
};
// set url and append dom script elm to the document head
node.src = name[0] === '/' ? '/app_module' : '/module/';
node.src += name + '/bundle.js';
document.head.appendChild(node);
},
// load composition
composition: function (name, callback) {
this.flow('C/' + name, {
net: '/',
to: '@'
}, function (err, composition) {
composition = JSON.parse(composition);
composition._roles = {'*': true};
callback(err, composition);
});
},
request: server.request,
// Load html snippets.
markup: function (urls, callback) {
var self = this;
var count = 0;
var snippets = {};
var errorHappend;
var next = function (url, index) {
self.flow(url, {net: '/'}, function (err, snippet) {
if (errorHappend) {
return;
}
if (err) {
errorHappend = true;
return callback(err);
}
snippets[url] = snippet;
if (++count === urls.length) {
callback(null, snippets, true);
}
});
};
urls.forEach(next);
},
// Load css files.
styles: function (urls) {
urls.forEach(function (url) {
var link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.setAttribute('href', url);
global.document.head.appendChild(link);
});
},
reset: function () {
// reset module instances
CoreInst.reset();
// reset DOM body
document.body.innerHTML = '';
// remove styles
var styles = document.head.querySelectorAll('link[rel=stylesheet]');
if (styles) {
styles.forEach(function (stylesheet) {
stylesheet.remove();
});
}
// reset server
server.reset();
// load entrypoint
CoreInst.load('*');
}
});
CoreInst.load('*');
| JavaScript | 0 |
8c649e6f89d391e7075315cab6ef9144b3554bd4 | Fix "Source Maps are off" | lib/global-eval.js | lib/global-eval.js | // we define a __exec for globally-scoped execution
// used by module format implementations
var __exec;
(function() {
var hasBtoa = typeof btoa != 'undefined';
function getSource(load) {
var lastLineIndex = load.source.lastIndexOf('\n');
// wrap ES formats with a System closure for System global encapsulation
var wrap = load.metadata.format != 'global';
var sourceMap = load.metadata.sourceMap;
if (sourceMap) {
if (typeof sourceMap != 'object')
throw new TypeError('load.metadata.sourceMap must be set to an object.');
sourceMap = JSON.stringify(sourceMap);
}
return (wrap ? '(function(System, SystemJS, require) {' : '') + load.source + (wrap ? '\n})(System, System);' : '')
// adds the sourceURL comment if not already present
+ (load.source.substr(lastLineIndex, 15) != '\n//# sourceURL='
? '\n//# sourceURL=' + load.address + (sourceMap ? '!transpiled' : '') : '')
// add sourceMappingURL if load.metadata.sourceMap is set
+ (sourceMap && hasBtoa && '\n//# sourceMappingURL=data:application/json;base64,' + btoa(unescape(encodeURIComponent(sourceMap))) || '');
}
var curLoad;
// System.register, System.registerDynamic, AMD define pipeline
// if currently evalling code here, immediately reduce the registered entry against the load record
hook('pushRegister_', function() {
return function(register) {
if (!curLoad)
return false;
this.reduceRegister_(curLoad, register);
return true;
};
});
// System clobbering protection (mostly for Traceur)
var curSystem;
var callCounter = 0;
function preExec(loader, load) {
curLoad = load;
if (callCounter++ == 0)
curSystem = __global.System;
__global.System = __global.SystemJS = loader;
}
function postExec() {
if (--callCounter == 0)
__global.System = __global.SystemJS = curSystem;
curLoad = undefined;
}
__exec = function(load) {
if ((load.metadata.integrity || load.metadata.nonce) && supportsScriptExec)
return scriptExec.call(this, load);
try {
preExec(this, load);
curLoad = load;
(0, eval)(getSource(load));
postExec();
}
catch(e) {
postExec();
throw addToError(e, 'Evaluating ' + load.address);
}
};
var supportsScriptExec = false;
if (isBrowser && typeof document != 'undefined' && document.getElementsByTagName) {
var scripts = document.getElementsByTagName('script');
$__curScript = scripts[scripts.length - 1];
if (!(window.chrome && window.chrome.extension || navigator.userAgent.match(/^Node\.js/)))
supportsScriptExec = true;
}
// script execution via injecting a script tag into the page
// this allows CSP integrity and nonce to be set for CSP environments
var head;
function scriptExec(load) {
if (!head)
head = document.head || document.body || document.documentElement;
var script = document.createElement('script');
script.text = getSource(load, false);
var onerror = window.onerror;
var e;
window.onerror = function(_e) {
e = addToError(_e, 'Evaluating ' + load.address);
}
preExec(this, load);
if (load.metadata.integrity)
script.setAttribute('integrity', load.metadata.integrity);
if (load.metadata.nonce)
script.setAttribute('nonce', load.metadata.nonce);
head.appendChild(script);
head.removeChild(script);
postExec();
window.onerror = onerror;
if (e)
throw e;
}
})();
| // we define a __exec for globally-scoped execution
// used by module format implementations
var __exec;
(function() {
var hasBtoa = typeof btoa != 'undefined';
function getSource(load) {
var lastLineIndex = load.source.lastIndexOf('\n');
// wrap ES formats with a System closure for System global encapsulation
var wrap = load.metadata.format != 'global';
var sourceMap = load.metadata.sourceMap;
if (sourceMap) {
if (typeof sourceMap != 'object')
throw new TypeError('load.metadata.sourceMap must be set to an object.');
if (sourceMap.mappings)
sourceMap.mappings = ';' + sourceMap.mappings;
sourceMap = JSON.stringify(sourceMap);
}
return (wrap ? '(function(System, SystemJS, require) {' : '') + load.source + (wrap ? '\n})(System, System);' : '')
// adds the sourceURL comment if not already present
+ (load.source.substr(lastLineIndex, 15) != '\n//# sourceURL='
? '\n//# sourceURL=' + load.address + (sourceMap ? '!transpiled' : '') : '')
// add sourceMappingURL if load.metadata.sourceMap is set
+ (sourceMap && hasBtoa && '\n//# sourceMappingURL=data:application/json;base64,' + btoa(unescape(encodeURIComponent(sourceMap))) || '');
}
var curLoad;
// System.register, System.registerDynamic, AMD define pipeline
// if currently evalling code here, immediately reduce the registered entry against the load record
hook('pushRegister_', function() {
return function(register) {
if (!curLoad)
return false;
this.reduceRegister_(curLoad, register);
return true;
};
});
// System clobbering protection (mostly for Traceur)
var curSystem;
var callCounter = 0;
function preExec(loader, load) {
curLoad = load;
if (callCounter++ == 0)
curSystem = __global.System;
__global.System = __global.SystemJS = loader;
}
function postExec() {
if (--callCounter == 0)
__global.System = __global.SystemJS = curSystem;
curLoad = undefined;
}
__exec = function(load) {
if ((load.metadata.integrity || load.metadata.nonce) && supportsScriptExec)
return scriptExec.call(this, load);
try {
preExec(this, load);
curLoad = load;
(0, eval)(getSource(load));
postExec();
}
catch(e) {
postExec();
throw addToError(e, 'Evaluating ' + load.address);
}
};
var supportsScriptExec = false;
if (isBrowser && typeof document != 'undefined' && document.getElementsByTagName) {
var scripts = document.getElementsByTagName('script');
$__curScript = scripts[scripts.length - 1];
if (!(window.chrome && window.chrome.extension || navigator.userAgent.match(/^Node\.js/)))
supportsScriptExec = true;
}
// script execution via injecting a script tag into the page
// this allows CSP integrity and nonce to be set for CSP environments
var head;
function scriptExec(load) {
if (!head)
head = document.head || document.body || document.documentElement;
var script = document.createElement('script');
script.text = getSource(load, false);
var onerror = window.onerror;
var e;
window.onerror = function(_e) {
e = addToError(_e, 'Evaluating ' + load.address);
}
preExec(this, load);
if (load.metadata.integrity)
script.setAttribute('integrity', load.metadata.integrity);
if (load.metadata.nonce)
script.setAttribute('nonce', load.metadata.nonce);
head.appendChild(script);
head.removeChild(script);
postExec();
window.onerror = onerror;
if (e)
throw e;
}
})(); | JavaScript | 0 |
739dac61b706563a04eee791635094e1182ae4ea | remove commented out imports | troposphere/static/js/components/common/InstanceDetail.react.js | troposphere/static/js/components/common/InstanceDetail.react.js | import React from 'react';
import Router from 'react-router';
import Backbone from 'backbone';
import stores from 'stores';
import InstanceDetailsSection from 'components/projects/resources/instance/details/sections/InstanceDetailsSection.react';
import PastInstanceDetailsSection from 'components/projects/resources/instance/details/sections/PastInstanceDetailsSection.react';
import InstanceActionsAndLinks from 'components/projects/resources/instance/details/actions/InstanceActionsAndLinks.react';
import InstanceMetricsSection from 'components/projects/resources/instance/details/sections/InstanceMetricsSection.react';
import Instance from 'models/Instance';
import InstanceState from 'models/InstanceState';
import InstanceInfoSection from 'components/projects/resources/instance/details/sections/InstanceInfoSection.react';
var InstanceDetail = React.createClass({
displayName: "InstanceDetail",
mixins: [Router.State],
getInitialState: function(){
return{
instance: stores.InstanceStore.get(this.getParams().id),
instanceHistory: stores.InstanceHistoryStore.fetchWhere({"instance": this.getParams().id})
}
},
onNewData: function(){
this.setState({instance: stores.InstanceStore.get(this.getParams().id), instanceHistory: stores.InstanceHistoryStore.fetchWhere({"instance": this.getParams().id})});
},
componentDidMount: function(){
stores.InstanceStore.addChangeListener(this.onNewData);
stores.InstanceHistoryStore.addChangeListener(this.onNewData);
stores.ProviderStore.addChangeListener(this.onNewData);
},
renderInactiveInstance: function(){
var instanceObj = new Instance(this.state.instanceHistory.models[0].get('instance')),
instanceStateObj = new InstanceState({"status_raw": "deleted"}),
image = this.state.instanceHistory.models[0].get('image'),
size = this.state.instanceHistory.models[0].get('size');
instanceObj.set('image', image);
instanceObj.set('size', size);
instanceObj.set('state', instanceStateObj);
return (
<div className="container">
<div className="row resource-details-content">
<div className="col-md-6">
<InstanceInfoSection instance={instanceObj}/>
</div>
<div className="col-md-6">
<PastInstanceDetailsSection instance={instanceObj} />
</div>
</div>
<hr/>
</div>
);
},
renderActiveInstance: function(){
var instance = this.state.instance;
var metrics = typeof show_instance_metrics != "undefined" ? <InstanceMetricsSection instance={instance}/> : "";
return (
<div className="container">
<div className="row resource-details-content">
<div className="col-md-9">
<InstanceInfoSection instance={instance}/>
<hr/>
<InstanceDetailsSection instance={instance} />
<hr/>
{metrics}
</div>
<div className="col-md-3">
<InstanceActionsAndLinks
project={null}
instance={instance}
/>
</div>
</div>
</div>
);
},
render: function(){
if(!this.state.instanceHistory){
return <div className="loading" />
}
return this.state.instance ? this.renderActiveInstance() : this.renderInactiveInstance();
},
});
export default InstanceDetail;
| import React from 'react';
import Router from 'react-router';
import Backbone from 'backbone';
import stores from 'stores';
import InstanceDetailsSection from 'components/projects/resources/instance/details/sections/InstanceDetailsSection.react';
import PastInstanceDetailsSection from 'components/projects/resources/instance/details/sections/PastInstanceDetailsSection.react';
import InstanceActionsAndLinks from 'components/projects/resources/instance/details/actions/InstanceActionsAndLinks.react';
import InstanceMetricsSection from 'components/projects/resources/instance/details/sections/InstanceMetricsSection.react';
import Instance from 'models/Instance';
import InstanceState from 'models/InstanceState';
import InstanceInfoSection from 'components/projects/resources/instance/details/sections/InstanceInfoSection.react';
// var React = require('react/addons'),
// Router = require('react-router'),
// Backbone = require('backbone'),
// BreadcrumbBar = require('components/projects/common/BreadcrumbBar.react'),
//
// InstanceDetailsSection = require('components/projects/resources/instance/details/sections/InstanceDetailsSection.react'),
//
//
// stores = require('stores'),
// Time = require('components/common/Time.react'),
// ResourceTags = require('components/projects/resources/instance/details/sections/ResourceTags.react'),
// actions = require('actions'),
// moment = require('moment'),
// CryptoJS = require('crypto-js'),
// Gravatar = require('components/common/Gravatar.react');
var InstanceDetail = React.createClass({
displayName: "InstanceDetail",
mixins: [Router.State],
getInitialState: function(){
return{
instance: stores.InstanceStore.get(this.getParams().id),
instanceHistory: stores.InstanceHistoryStore.fetchWhere({"instance": this.getParams().id})
}
},
onNewData: function(){
this.setState({instance: stores.InstanceStore.get(this.getParams().id), instanceHistory: stores.InstanceHistoryStore.fetchWhere({"instance": this.getParams().id})});
},
componentDidMount: function(){
stores.InstanceStore.addChangeListener(this.onNewData);
stores.InstanceHistoryStore.addChangeListener(this.onNewData);
stores.ProviderStore.addChangeListener(this.onNewData);
},
renderInactiveInstance: function(){
var instanceObj = new Instance(this.state.instanceHistory.models[0].get('instance')),
instanceStateObj = new InstanceState({"status_raw": "deleted"}),
image = this.state.instanceHistory.models[0].get('image'),
size = this.state.instanceHistory.models[0].get('size');
instanceObj.set('image', image);
instanceObj.set('size', size);
instanceObj.set('state', instanceStateObj);
return (
<div className="container">
<div className="row resource-details-content">
<div className="col-md-6">
<InstanceInfoSection instance={instanceObj}/>
</div>
<div className="col-md-6">
<PastInstanceDetailsSection instance={instanceObj} />
</div>
</div>
<hr/>
</div>
);
},
renderActiveInstance: function(){
var instance = this.state.instance;
var metrics = typeof show_instance_metrics != "undefined" ? <InstanceMetricsSection instance={instance}/> : "";
return (
<div className="container">
<div className="row resource-details-content">
<div className="col-md-9">
<InstanceInfoSection instance={instance}/>
<hr/>
<InstanceDetailsSection instance={instance} />
<hr/>
{metrics}
</div>
<div className="col-md-3">
<InstanceActionsAndLinks
project={null}
instance={instance}
/>
</div>
</div>
</div>
);
},
render: function(){
if(!this.state.instanceHistory){
return <div className="loading" />
}
return this.state.instance ? this.renderActiveInstance() : this.renderInactiveInstance();
},
});
export default InstanceDetail;
| JavaScript | 0 |
d96c20cd158d9dc46e7138fffc42d724fe09d3df | make output resizable only when plugin present | present/js/play.js | present/js/play.js | // Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
function initPlayground(transport) {
"use strict";
function text(node) {
var s = "";
for (var i = 0; i < node.childNodes.length; i++) {
var n = node.childNodes[i];
if (n.nodeType === 1 && n.tagName === "SPAN" && n.className != "number") {
var innerText = n.innerText === undefined ? "textContent" : "innerText";
s += n[innerText] + "\n";
continue;
}
if (n.nodeType === 1 && n.tagName !== "BUTTON") {
s += text(n);
}
}
return s;
}
function init(code) {
var output = document.createElement('div');
var outpre = document.createElement('pre');
var running;
if ($ && $(output).resizable) {
$(output).resizable({
handles: "n,w,nw",
minHeight: 27,
minWidth: 135,
maxHeight: 608,
maxWidth: 990
});
}
function onKill() {
if (running) running.Kill();
}
function onRun(e) {
onKill();
output.style.display = "block";
outpre.innerHTML = "";
run1.style.display = "none";
var options = {Race: e.shiftKey};
running = transport.Run(text(code), PlaygroundOutput(outpre), options);
}
function onClose() {
onKill();
output.style.display = "none";
run1.style.display = "inline-block";
}
var run1 = document.createElement('button');
run1.innerHTML = 'Run';
run1.className = 'run';
run1.addEventListener("click", onRun, false);
var run2 = document.createElement('button');
run2.className = 'run';
run2.innerHTML = 'Run';
run2.addEventListener("click", onRun, false);
var kill = document.createElement('button');
kill.className = 'kill';
kill.innerHTML = 'Kill';
kill.addEventListener("click", onKill, false);
var close = document.createElement('button');
close.className = 'close';
close.innerHTML = 'Close';
close.addEventListener("click", onClose, false);
var button = document.createElement('div');
button.classList.add('buttons');
button.appendChild(run1);
// Hack to simulate insertAfter
code.parentNode.insertBefore(button, code.nextSibling);
var buttons = document.createElement('div');
buttons.classList.add('buttons');
buttons.appendChild(run2);
buttons.appendChild(kill);
buttons.appendChild(close);
output.classList.add('output');
output.appendChild(buttons);
output.appendChild(outpre);
output.style.display = "none";
code.parentNode.insertBefore(output, button.nextSibling);
}
var play = document.querySelectorAll('div.playground');
for (var i = 0; i < play.length; i++) {
init(play[i]);
}
}
| // Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
function initPlayground(transport) {
"use strict";
function text(node) {
var s = "";
for (var i = 0; i < node.childNodes.length; i++) {
var n = node.childNodes[i];
if (n.nodeType === 1 && n.tagName === "SPAN" && n.className != "number") {
var innerText = n.innerText === undefined ? "textContent" : "innerText";
s += n[innerText] + "\n";
continue;
}
if (n.nodeType === 1 && n.tagName !== "BUTTON") {
s += text(n);
}
}
return s;
}
function init(code) {
var output = document.createElement('div');
var outpre = document.createElement('pre');
var running;
// TODO(adg): check that jquery etc is loaded.
$(output).resizable({
handles: "n,w,nw",
minHeight: 27,
minWidth: 135,
maxHeight: 608,
maxWidth: 990
});
function onKill() {
if (running) running.Kill();
}
function onRun(e) {
onKill();
output.style.display = "block";
outpre.innerHTML = "";
run1.style.display = "none";
var options = {Race: e.shiftKey};
running = transport.Run(text(code), PlaygroundOutput(outpre), options);
}
function onClose() {
onKill();
output.style.display = "none";
run1.style.display = "inline-block";
}
var run1 = document.createElement('button');
run1.innerHTML = 'Run';
run1.className = 'run';
run1.addEventListener("click", onRun, false);
var run2 = document.createElement('button');
run2.className = 'run';
run2.innerHTML = 'Run';
run2.addEventListener("click", onRun, false);
var kill = document.createElement('button');
kill.className = 'kill';
kill.innerHTML = 'Kill';
kill.addEventListener("click", onKill, false);
var close = document.createElement('button');
close.className = 'close';
close.innerHTML = 'Close';
close.addEventListener("click", onClose, false);
var button = document.createElement('div');
button.classList.add('buttons');
button.appendChild(run1);
// Hack to simulate insertAfter
code.parentNode.insertBefore(button, code.nextSibling);
var buttons = document.createElement('div');
buttons.classList.add('buttons');
buttons.appendChild(run2);
buttons.appendChild(kill);
buttons.appendChild(close);
output.classList.add('output');
output.appendChild(buttons);
output.appendChild(outpre);
output.style.display = "none";
code.parentNode.insertBefore(output, button.nextSibling);
}
var play = document.querySelectorAll('div.playground');
for (var i = 0; i < play.length; i++) {
init(play[i]);
}
}
| JavaScript | 0.00001 |
828103f6d3ffc139dce1badf6d420cc990b0d77b | Use 'protocol' and 'host' from config.server | src/modules/socket/socket-client.js | src/modules/socket/socket-client.js | /* @flow */
import eio from 'engine.io-client/engine.io';
import { bus, config } from '../../core-client.js';
import * as models from '../../models/models.js';
import stringpack from 'stringpack';
const {
protocol,
host,
} = config.server;
let backOff = 1, client;
const packer = stringpack(Object.keys(models).sort().map(key => models[key]));
function disconnected() {
/* eslint-disable no-use-before-define */
if (backOff < 256) {
backOff *= 2;
} else {
backOff = 256;
}
bus.emit('change', {
state: { connectionStatus: 'offline', backOff }
});
setTimeout(connect, backOff * 1000);
}
function onMessage(message) {
const changes = packer.decode(message);
changes.source = 'server';
bus.emit('change', changes);
}
function connect() {
client = new eio.Socket((protocol === 'https:' ? 'wss:' : 'ws:') + '//' + host, {
jsonp: 'document' in window && 'createElement' in window.document // Disable JSONP in non-web environments, e.g.- react-native
});
client.on('close', disconnected);
client.on('open', () => {
backOff = 1;
bus.emit('change', {
state: { connectionStatus: 'online', backOff }
});
});
client.on('message', onMessage);
}
bus.on('change', (changes) => {
if (changes.source === 'server') return;
const { state, ...filtered } = changes;
if (Object.keys(filtered).length) {
client.send(packer.encode(filtered));
}
}, 1);
connect();
| /* @flow */
import eio from 'engine.io-client/engine.io';
import { bus, config } from '../../core-client.js';
import * as models from '../../models/models.js';
import stringpack from 'stringpack';
const protocol = config.server.protocol, host = config.server.apiHost;
let backOff = 1, client;
const packer = stringpack(Object.keys(models).sort().map(key => models[key]));
function disconnected() {
/* eslint-disable no-use-before-define */
if (backOff < 256) {
backOff *= 2;
} else {
backOff = 256;
}
bus.emit('change', {
state: { connectionStatus: 'offline', backOff }
});
setTimeout(connect, backOff * 1000);
}
function onMessage(message) {
const changes = packer.decode(message);
changes.source = 'server';
bus.emit('change', changes);
}
function connect() {
client = new eio.Socket((protocol === 'https:' ? 'wss:' : 'ws:') + '//' + host, {
jsonp: 'document' in window && 'createElement' in window.document // Disable JSONP in non-web environments, e.g.- react-native
});
client.on('close', disconnected);
client.on('open', () => {
backOff = 1;
bus.emit('change', {
state: { connectionStatus: 'online', backOff }
});
});
client.on('message', onMessage);
}
bus.on('change', (changes) => {
if (changes.source === 'server') return;
const { state, ...filtered } = changes;
if (Object.keys(filtered).length) {
client.send(packer.encode(filtered));
}
}, 1);
connect();
| JavaScript | 0.000072 |
574c1c9dc1311238d216418855fa3b90dd219f72 | Add lib code | lib/index.js | lib/index.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.mockRes = exports.mockReq = undefined;
var _sinon = require('sinon');
var _sinon2 = _interopRequireDefault(_sinon);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Returns a new mock request for use in testing.
var mockReq = exports.mockReq = function mockReq() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var ret = {};
return Object.assign(ret, {
accepts: _sinon2.default.stub().returns(ret),
acceptsCharsets: _sinon2.default.stub().returns(ret),
acceptsEncodings: _sinon2.default.stub().returns(ret),
acceptsLanguages: _sinon2.default.stub().returns(ret),
body: {},
flash: _sinon2.default.stub().returns(ret),
get: _sinon2.default.stub().returns(ret),
is: _sinon2.default.stub().returns(ret),
params: {},
query: {},
session: {}
}, options);
};
// Returns a new mock response for use in testing.
var mockRes = exports.mockRes = function mockRes() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var ret = {};
return Object.assign(ret, {
append: _sinon2.default.stub().returns(ret),
attachement: _sinon2.default.stub().returns(ret),
clearCookie: _sinon2.default.stub().returns(ret),
cookie: _sinon2.default.stub().returns(ret),
download: _sinon2.default.stub().returns(ret),
end: _sinon2.default.stub().returns(ret),
format: {},
get: _sinon2.default.stub().returns(ret),
headersSent: _sinon2.default.stub().returns(ret),
json: _sinon2.default.stub().returns(ret),
jsonp: _sinon2.default.stub().returns(ret),
links: _sinon2.default.stub().returns(ret),
locals: {},
location: _sinon2.default.stub().returns(ret),
redirect: _sinon2.default.stub().returns(ret),
render: _sinon2.default.stub().returns(ret),
send: _sinon2.default.stub().returns(ret),
sendFile: _sinon2.default.stub().returns(ret),
sendStatus: _sinon2.default.stub().returns(ret),
set: _sinon2.default.stub().returns(ret),
status: _sinon2.default.stub().returns(ret),
type: _sinon2.default.stub().returns(ret),
vary: _sinon2.default.stub().returns(ret)
}, options);
}; | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.mockRes = exports.mockReq = undefined;
var _sinon = require('sinon');
var _sinon2 = _interopRequireDefault(_sinon);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Returns a new mock request for use in testing.
var mockReq = exports.mockReq = function mockReq() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var ret = {};
return Object.assign(ret, {
accepts: _sinon2.default.stub().returns(ret),
acceptsCharsets: _sinon2.default.stub().returns(ret),
acceptsEncodings: _sinon2.default.stub().returns(ret),
acceptsLanguages: _sinon2.default.stub().returns(ret),
body: {},
flash: _sinon2.default.stub().returns(ret),
get: _sinon2.default.stub().returns(ret),
is: _sinon2.default.stub().returns(ret),
params: {},
query: {},
session: {}
}, options);
};
// Returns a new mock response for use in testing.
var mockRes = exports.mockRes = function mockRes() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var ret = {};
return Object.assign(ret, {
append: _sinon2.default.stub().returns(ret),
attachement: _sinon2.default.stub().returns(ret),
clearCookie: _sinon2.default.stub().returns(ret),
cookie: _sinon2.default.stub().returns(ret),
download: _sinon2.default.stub().returns(ret),
end: _sinon2.default.stub().returns(ret),
format: {},
get: _sinon2.default.stub().returns(ret),
headersSent: _sinon2.default.stub().returns(ret),
json: _sinon2.default.stub().returns(ret),
jsonp: _sinon2.default.stub().returns(ret),
links: _sinon2.default.stub().returns(ret),
locals: {},
location: _sinon2.default.stub().returns(ret),
redirect: _sinon2.default.stub().returns(ret),
render: _sinon2.default.stub().returns(ret),
send: _sinon2.default.stub().returns(ret),
sendFile: _sinon2.default.stub().returns(ret),
sendStatus: _sinon2.default.stub().returns(ret),
set: _sinon2.default.stub().returns(ret),
status: _sinon2.default.stub().returns(ret),
type: _sinon2.default.stub().returns(ret),
vary: _sinon2.default.stub().returns(ret)
}, options);
}; | JavaScript | 0.000007 |
fed83241144ccd26079890088371170793d4796d | Add the translate module to the main index | lib/index.js | lib/index.js | this.interaction_machine = require("./interaction_machine");
this.InteractionMachine = this.interaction_machine.InteractionMachine;
this.app = require("./app");
this.App = this.app.App;
this.dummy = require("./dummy");
this.DummyApi = this.dummy.DummyApi;
this.tester = require("./tester");
this.AppTester = this.tester.AppTester;
this.config = require("./config");
this.user = require("./user");
this.promise = require("./promise");
this.states = require("./states/index");
this.metrics = require("./metrics");
this.http = require("./http");
this.utils = require("./utils");
this.translate = require("./translate");
this.test_utils = require("./test_utils");
this.fixtures = require("./fixtures");
| this.interaction_machine = require("./interaction_machine");
this.InteractionMachine = this.interaction_machine.InteractionMachine;
this.app = require("./app");
this.App = this.app.App;
this.dummy = require("./dummy");
this.DummyApi = this.dummy.DummyApi;
this.tester = require("./tester");
this.AppTester = this.tester.AppTester;
this.config = require("./config");
this.user = require("./user");
this.promise = require("./promise");
this.states = require("./states/index");
this.metrics = require("./metrics");
this.http = require("./http");
this.utils = require("./utils");
this.test_utils = require("./test_utils");
this.fixtures = require("./fixtures");
| JavaScript | 0.000001 |
058514cacfa222b39c02d26df1648e47d86a7e93 | Remove unnecessary content from index.js | lib/index.js | lib/index.js | /*
* biojs-io-biom
* https://github.com/iimog/biojs-io-biom
*
* Copyright (c) 2016 Markus J. Ankenbrand
* Licensed under the MIT license.
*/
module.exports = require("./biojs-io-biom");
| /*
* biojs-io-biom
* https://github.com/iimog/biojs-io-biom
*
* Copyright (c) 2016 Markus J. Ankenbrand
* Licensed under the MIT license.
*/
/**
@class biojsiobiom
*/
/**
* Private Methods
*/
/*
* Public Methods
*/
/**
* Method responsible to say Hello
*
* @example
*
* biojsiobiom.hello('biojs');
*
* @method hello
* @param {String} name Name of a person
* @return {String} Returns hello name
*/
module.exports.hello = function (name) {
return 'hello ' + name;
};
//module.exports.Biom = require("./biojs-io-biom");
| JavaScript | 0.000006 |
e7b9ebc894ef7d58fd7405ff2c2c82dfcd4bace2 | Resolve lint issues in lib/index | lib/index.js | lib/index.js | /**
* An app that makes apps.
*
* @package appmaker
* @author Andrew Sliwinski <a@mozillafoundation.org>
*/
var Vue = require('vue');
var model = require('./model');
var router = require('./router');
// Restore user state
model.restore(function (err) {
if (err) throw new Error('Could not restore user state.');
// Register views
Vue.component('templates', require('../views/templates'));
Vue.component('apps', require('../views/apps'));
Vue.component('profile', require('../views/profile'));
Vue.component('detail', require('../views/detail'));
// Vue.component('play', require('../views/play'));
// Vue.component('edit', require('../views/edit'));
// Vue.component('block', require('../views/brick'));
// Create "app"
var app = new Vue({
el: '#app',
data: {
currentView: 'templates',
title: 'Templates'
}
});
// Route
router(app);
});
| /**
* An app that makes apps.
*
* @package appmaker
* @author Andrew Sliwinski <a@mozillafoundation.org>
*/
var Vue = require('vue');
var model = require('./model');
var router = require('./router');
// Restore user state
model.restore(function (err) {
if (err) throw new Error('Could not restore user state.');
// Register views
Vue.component('templates', require('../views/templates'));
Vue.component('apps', require('../views/apps'));
Vue.component('profile', require('../views/profile'));
Vue.component('detail', require('../views/detail'));
// Vue.component('play', require('../views/play'));
// Vue.component('edit', require('../views/edit'));
// Vue.component('block', require('../views/brick'));
// Create "app"
var app = new Vue({
el: '#app',
data: {
currentView: 'templates',
title: 'Templates'
}
});
// Route
router(app);
}); | JavaScript | 0 |
40701a683eb8a49625124fcc0c7aa80dc3f3104c | Group the differences | lib/index.js | lib/index.js | // Dependencies
var LevDist = require("levdist");
function Change(removed, added, sensitivity) {
this._ = [removed, added];
this.changes = LevDist(removed, added);
this.modified = this.changes > sensitivity;
}
function Diff(oldLines, newLines, sensitivity) {
var self = this;
self.old_lines = oldLines;
self.new_lines = newLines;
self.sensitivity = sensitivity || 0;
self.changes = [];
// Convert to array
oldLines = typeof oldLines === "string" ? oldLines.split("\n") : oldLines;
newLines = typeof newLines === "string" ? newLines.split("\n") : newLines;
// Iterate the new lines
var cOldLine = null;
newLines.forEach(function (cNewLine, i) {
cOldLine = oldLines[i] || "";
self.changes.push(new Change(cOldLine, cNewLine, self.sensitivity));
});
}
Diff.prototype.toString = function () {
var self = this
, str = ""
, cDiff = { added: "", removed: "" }
;
self.changes.forEach(function (cChange) {
if (!cChange.modified) {
str += cDiff.removed;
str += cDiff.added;
cDiff.removed = "";
cDiff.added = "";
str += " " + cChange._[1] + "\n"
} else {
cDiff.removed += " - " + cChange._[0] + "\n"
if (cChange._[1]) {
cDiff.added += " + " + cChange._[1] + "\n"
}
}
});
str += cDiff.removed;
str += cDiff.added;
return str;
};
function LineDiff (oldLines, newLines, sensitivity) {
return new Diff(oldLines, newLines, sensitivity);
}
module.exports = LineDiff;
| // Dependencies
var LevDist = require("levdist");
//function Change(removed, added, notModified,) {
// this._ = [removed, added];
// this.
//}
function Diff(oldLines, newLines, sensitivity) {
var self = this;
self.old_lines = oldLines;
self.new_lines = newLines;
self.sensitivity = sensitivity || 0;
self.changes = [];
// Convert to array
oldLines = typeof oldLines === "string" ? oldLines.split("\n") : oldLines;
newLines = typeof newLines === "string" ? newLines.split("\n") : newLines;
// Iterate the new lines
var cOldLine = null
, oldLineI = 0
;
debugger
newLines.forEach(function (cNewLine, i) {
cOldLine = oldLines[oldLineI];
if (cOldLine) {
++oldLineI;
}
self.changes.push({
_: [cOldLine, cNewLine]
, changes: LevDist(cOldLine, cNewLine)
});
});
}
Diff.prototype.toString = function () {
var self = this
, str = ""
, cDiff = { added: "", removed: "" }
;
self.changes.forEach(function (cChange) {
if (cChange.changes <= self.sensitivity) {
str += cDiff.removed;
str += cDiff.added;
str += " " + cChange._[1] + "\n"
} else {
cDiff.removed += " - " + cChange._[0] + "\n"
if (cChange._[1]) {
cDiff.added += " + " + cChange._[1] + "\n"
}
}
});
return str;
};
function LineDiff (oldLines, newLines, sensitivity) {
return new Diff(oldLines, newLines, sensitivity);
}
module.exports = LineDiff;
| JavaScript | 0.999991 |
939d6089384c817429b719e7a6925b48e48ee65c | Call prototype.initialize to prevent overwriting other plugins | lib/index.js | lib/index.js | var extend = require('xtend')
var Joi = require('joi')
var difference = require('lodash.difference')
module.exports = function modelBase (bookshelf, params) {
if (!bookshelf) {
throw new Error('Must pass an initialized bookshelf instance')
}
var model = bookshelf.Model.extend({
initialize: function (attrs, options) {
bookshelf.Model.prototype.initialize.call(this)
if (this.validate) {
var baseValidation = {
// id might be number or string, for optimization
id: Joi.any().optional(),
created_at: Joi.date().optional(),
updated_at: Joi.date().optional()
}
this.validate = this.validate.isJoi ?
this.validate.keys(baseValidation) :
Joi.object(this.validate).keys(baseValidation)
} else {
this.validate = Joi.any()
}
this.on('saving', this.validateSave)
},
hasTimestamps: ['created_at', 'updated_at'],
validateSave: function (model, attrs, options) {
var validation
// model is not new or update method explicitly set
if ((model && !model.isNew()) || (options && options.method === 'update')) {
var schemaKeys = this.validate._inner.children.map(function (child) {
return child.key
})
var presentKeys = Object.keys(attrs)
var optionalKeys = difference(schemaKeys, presentKeys)
// only validate the keys that are being updated
validation = Joi.validate(attrs, this.validate.optionalKeys(optionalKeys))
} else {
validation = Joi.validate(this.attributes, this.validate)
}
if (validation.error) {
throw new Error(validation.error)
} else {
return validation.value
}
}
}, {
/* Model CRUD */
/**
* Naive findAll - fetches all data for `this`
* @param {Object} filter (optional)
* @param {Object} options (optional)
* @return {Promise(bookshelf.Collection)} Bookshelf Collection of Models
*/
findAll: function (filter, options) {
filter = extend({}, filter)
return this.forge().query({ where: filter }).fetchAll(options)
},
/**
* Naive findOne - fetch data for `this` matching data
* @param {Object} data
* @param {Object} options (optional)
* @return {Promise(bookshelf.Model)} single Model
*/
findOne: function (data, options) {
options = extend({ require: true }, options)
return this.forge(data).fetch(options)
},
/**
* Naive add - create and save a model based on data
* @param {Object} data
* @param {Object} options (optional)
* @return {Promise(bookshelf.Model)} single Model
*/
create: function (data, options) {
return this.forge(data)
.save(null, options)
},
/**
* Naive update - update a model based on data
* @param {Object} data
* @param {Object} options
* @return {Promise(bookshelf.Model)} edited Model
*/
update: function (data, options) {
options = extend({ patch: true, require: true }, options)
return this.forge({ id: options.id }).fetch(options)
.then(function (model) {
return model ? model.save(data, options) : undefined
})
},
/**
* Naive destroy
* @param {Object} options
* @return {Promise(bookshelf.Model)} empty Model
*/
destroy: function (options) {
options = extend({ require: true }, options)
return this.forge({ id: options.id })
.destroy(options)
},
/**
* Find or create - try and find the model, create one if not found
* @param {Object} data
* @param {Object} options
* @return {Promise(bookshelf.Model)} single Model
*/
findOrCreate: function (data, options) {
options = extend({ require: false }, options)
return this.findOne(data, options)
.bind(this)
.then(function (model) {
return model ? model : this.create(data, options)
})
}
})
return model
}
| var extend = require('xtend')
var Joi = require('joi')
var difference = require('lodash.difference')
module.exports = function modelBase (bookshelf, params) {
if (!bookshelf) {
throw new Error('Must pass an initialized bookshelf instance')
}
var model = bookshelf.Model.extend({
initialize: function (attrs, options) {
if (this.validate) {
var baseValidation = {
// id might be number or string, for optimization
id: Joi.any().optional(),
created_at: Joi.date().optional(),
updated_at: Joi.date().optional()
}
this.validate = this.validate.isJoi ?
this.validate.keys(baseValidation) :
Joi.object(this.validate).keys(baseValidation)
} else {
this.validate = Joi.any()
}
this.on('saving', this.validateSave)
},
hasTimestamps: ['created_at', 'updated_at'],
validateSave: function (model, attrs, options) {
var validation
// model is not new or update method explicitly set
if ((model && !model.isNew()) || (options && options.method === 'update')) {
var schemaKeys = this.validate._inner.children.map(function (child) {
return child.key
})
var presentKeys = Object.keys(attrs)
var optionalKeys = difference(schemaKeys, presentKeys)
// only validate the keys that are being updated
validation = Joi.validate(attrs, this.validate.optionalKeys(optionalKeys))
} else {
validation = Joi.validate(this.attributes, this.validate)
}
if (validation.error) {
throw new Error(validation.error)
} else {
return validation.value
}
}
}, {
/* Model CRUD */
/**
* Naive findAll - fetches all data for `this`
* @param {Object} filter (optional)
* @param {Object} options (optional)
* @return {Promise(bookshelf.Collection)} Bookshelf Collection of Models
*/
findAll: function (filter, options) {
filter = extend({}, filter)
return this.forge().query({ where: filter }).fetchAll(options)
},
/**
* Naive findOne - fetch data for `this` matching data
* @param {Object} data
* @param {Object} options (optional)
* @return {Promise(bookshelf.Model)} single Model
*/
findOne: function (data, options) {
options = extend({ require: true }, options)
return this.forge(data).fetch(options)
},
/**
* Naive add - create and save a model based on data
* @param {Object} data
* @param {Object} options (optional)
* @return {Promise(bookshelf.Model)} single Model
*/
create: function (data, options) {
return this.forge(data)
.save(null, options)
},
/**
* Naive update - update a model based on data
* @param {Object} data
* @param {Object} options
* @return {Promise(bookshelf.Model)} edited Model
*/
update: function (data, options) {
options = extend({ patch: true, require: true }, options)
return this.forge({ id: options.id }).fetch(options)
.then(function (model) {
return model ? model.save(data, options) : undefined
})
},
/**
* Naive destroy
* @param {Object} options
* @return {Promise(bookshelf.Model)} empty Model
*/
destroy: function (options) {
options = extend({ require: true }, options)
return this.forge({ id: options.id })
.destroy(options)
},
/**
* Find or create - try and find the model, create one if not found
* @param {Object} data
* @param {Object} options
* @return {Promise(bookshelf.Model)} single Model
*/
findOrCreate: function (data, options) {
options = extend({ require: false }, options)
return this.findOne(data, options)
.bind(this)
.then(function (model) {
return model ? model : this.create(data, options)
})
}
})
return model
}
| JavaScript | 0 |
176f9e1c9a9661790cedfcde6120078a5eb82a03 | Allow passing in a default set of exchanges. | lib/index.js | lib/index.js | var uri = require('url')
, dns = require('dns')
, NoDataError = require('./errors/nodataerror');
var DEFAULT_PROVIDERS = [ 'google' ];
exports = module.exports = function(exchanges) {
if (!exchanges) {
exchanges = {};
DEFAULT_PROVIDERS.forEach(function(provider) {
var conf = require('./providers/' + provider);
var i, len;
for (i = 0, len = conf.exchanges.length; i < len; ++i) {
exchanges[conf.exchanges[i].toLowerCase()] = conf.services;
}
});
}
var plugin = {};
plugin.resolveServices = function(identifier, type, cb) {
if (typeof type == 'function') {
cb = type;
type = undefined;
}
var url = uri.parse(identifier);
if (url.protocol != 'acct:') {
// This plugin only supports resolving of `acct:`-type identifiers. If
// the identifier is unsupported, return without an error and without
// resolving services. The expectation is that other discovery mechanisms
// are registered with `fingro` that will be used as alternatives.
return cb(null);
}
dns.resolve(url.hostname, 'MX', function (err, records) {
if (err) { return cb(err); }
records.sort(function(lhs, rhs) { return rhs.priority < lhs.priority; });
var result = {}
, record
, services
, i, len;
for (i = 0, len = records.length; i < len; ++i) {
record = records[i];
services = exchanges[record.exchange.toLowerCase()]
if (services) {
Object.keys(services).forEach(function(type) {
var val = services[type];
if (typeof val == 'string') {
result[type] = { location: val };
} else {
result[type] = val;
}
});
if (type) {
result = result[type];
if (!result) { return cb(new NoDataError('Service not found: ' + type)); }
return cb(null, result);
}
return cb(null, result);
}
}
// Unable to find a service mapping from the configured set of mail
// exchanges. Return without an error and without resolving services.
// The expectation is that other discovery mechanisms are registered
// with `fingro` that will be used as alternatives.
return cb(null);
});
}
return plugin;
}
| var uri = require('url')
, dns = require('dns')
, NoDataError = require('./errors/nodataerror');
var DEFAULT_PROVIDERS = [ 'google' ];
exports = module.exports = function() {
var map = {};
DEFAULT_PROVIDERS.forEach(function(provider) {
var conf = require('./providers/' + provider);
var i, len;
for (i = 0, len = conf.exchanges.length; i < len; ++i) {
map[conf.exchanges[i].toLowerCase()] = conf.services;
}
});
var plugin = {};
plugin.resolveServices = function(identifier, type, cb) {
if (typeof type == 'function') {
cb = type;
type = undefined;
}
var url = uri.parse(identifier);
if (url.protocol != 'acct:') {
// This plugin only supports resolving of `acct:`-type identifiers. If
// the identifier is unsupported, return without an error and without
// resolving services. The expectation is that other discovery mechanisms
// are registered with `fingro` that will be used as alternatives.
return cb(null);
}
dns.resolve(url.hostname, 'MX', function (err, records) {
if (err) { return cb(err); }
records.sort(function(lhs, rhs) { return rhs.priority < lhs.priority; });
var result = {}
, record
, services
, i, len;
for (i = 0, len = records.length; i < len; ++i) {
record = records[i];
services = map[record.exchange.toLowerCase()]
if (services) {
Object.keys(services).forEach(function(type) {
var val = services[type];
if (typeof val == 'string') {
result[type] = { location: val };
} else {
result[type] = val;
}
});
if (type) {
result = result[type];
if (!result) { return cb(new NoDataError('Service not found: ' + type)); }
return cb(null, result);
}
return cb(null, result);
}
}
// Unable to find a service mapping from the configured set of mail
// exchanges. Return without an error and without resolving services.
// The expectation is that other discovery mechanisms are registered
// with `fingro` that will be used as alternatives.
return cb(null);
});
}
return plugin;
}
| JavaScript | 0 |
e01d0dc03228801f895584be587dcf7afc801ace | Correct output debug statement | lib/index.js | lib/index.js | var p2list = require('properties-parser');
var p2tree = require('java.properties.js').default;
var path = require('path');
var createProperties2JsonPreprocessor = function(file, config) {
config = typeof config === 'object' ? config : {};
var distPath = config.dist || 'spec/javascripts/fixtures/json/';
var fileName = path.basename(file.path).replace(/\.[^/.]+$/, '');
console.log('Writing output: ', path.normalize(distPath + '/' + fileName + '.json'));
file.rename(path.normalize(distPath + '/' + fileName + '.json'));
var content = config.tree ? p2tree(file.content) : p2list.parse(file.content);
return JSON.stringify(content);
};
module.exports = {
transform: createProperties2JsonPreprocessor
};
| var p2list = require('properties-parser');
var p2tree = require('java.properties.js').default;
var path = require('path');
var createProperties2JsonPreprocessor = function(file, config) {
config = typeof config === 'object' ? config : {};
var distPath = config.dist || 'spec/javascripts/fixtures/json/';
var fileName = path.basename(file.path).replace(/\.[^/.]+$/, '');
console.log('Move output: ', distPath + '/' + fileName + '.json');
file.rename(path.normalize(distPath + '/' + fileName + '.json'));
var content = config.tree ? p2tree(file.content) : p2list.parse(file.content);
return JSON.stringify(content);
};
module.exports = {
transform: createProperties2JsonPreprocessor
};
| JavaScript | 0.001266 |
906ef441890ad31529db727b06d133318e0c4dec | Switch to keyup to repaint any time the block is changed. | wagtailcodeblock/static/wagtailcodeblock/js/wagtailcodeblock.js | wagtailcodeblock/static/wagtailcodeblock/js/wagtailcodeblock.js | function CodeBlockDefinition() {
window.wagtailStreamField.blocks.StructBlockDefinition.apply(this, arguments);
}
CodeBlockDefinition.prototype.render = function(placeholder, prefix, initialState, initialError) {
var block = window.wagtailStreamField.blocks.StructBlockDefinition.prototype.render.apply(
this, arguments
);
var languageField = $(document).find('#' + prefix + '-language');
var codeField = $(document).find('#' + prefix + '-code');
var targetField = $(document).find('#' + prefix + '-target');
function updateLanguage() {
var languageCode = languageField.val();
targetField.removeClass().addClass('language-' + languageCode);
prismRepaint();
}
function prismRepaint() {
Prism.highlightElement(targetField[0]);
}
function populateTargetCode() {
var codeText = codeField.val();
targetField.text(codeText);
prismRepaint(targetField);
}
updateLanguage();
populateTargetCode();
languageField.on('change', updateLanguage);
codeField.on('keyup', populateTargetCode);
return block;
}
window.telepath.register('wagtailcodeblock.blocks.CodeBlock', CodeBlockDefinition);
| function CodeBlockDefinition() {
window.wagtailStreamField.blocks.StructBlockDefinition.apply(this, arguments);
}
CodeBlockDefinition.prototype.render = function(placeholder, prefix, initialState, initialError) {
var block = window.wagtailStreamField.blocks.StructBlockDefinition.prototype.render.apply(
this, arguments
);
var languageField = $(document).find('#' + prefix + '-language');
var codeField = $(document).find('#' + prefix + '-code');
var targetField = $(document).find('#' + prefix + '-target');
function updateLanguage() {
var languageCode = languageField.val();
targetField.removeClass().addClass('language-' + languageCode);
prismRepaint();
}
function prismRepaint() {
Prism.highlightElement(targetField[0]);
}
function populateTargetCode() {
var codeText = codeField.val();
targetField.text(codeText);
prismRepaint(targetField);
}
updateLanguage();
populateTargetCode();
languageField.on('change', updateLanguage);
codeField.on('change', populateTargetCode);
codeField.keypress(function() {
prismRepaint();
});
return block;
}
window.telepath.register('wagtailcodeblock.blocks.CodeBlock', CodeBlockDefinition);
| JavaScript | 0 |
708118c6822c56b650de66d390376da58a1e35ed | clear interval | lib/index.js | lib/index.js | 'use strict';
const restify = require('restify');
const ws281x = require('rpi-ws281x-native');
var NUM_LEDS = parseInt(process.argv[2], 10) || 10;
var pixelData = new Uint32Array(NUM_LEDS);
var itv;
function init () {
var server = restify.createServer();
server.get('/rainbow', (req, res, next) => {
res.send('rainbow');
// ---- animation-loop
clearInterval(itv);
ws281x.reset();
ws281x.init(NUM_LEDS);
var offset = 0;
itv = setInterval(function () {
for (var i = 0; i < NUM_LEDS; i++) {
pixelData[i] = colorwheel((offset + i) % 256);
}
offset = (offset + 1) % 256;
ws281x.render(pixelData);
}, 1000 / 30);
});
server.get('/stop', (req, res, next) => {
res.send('stop');
clearInterval(itv);
ws281x.reset();
});
server.listen(8080);
}
// rainbow-colors, taken from http://goo.gl/Cs3H0v
function colorwheel(pos) {
pos = 255 - pos;
if (pos < 85) { return rgb2Int(255 - pos * 3, 0, pos * 3); }
else if (pos < 170) { pos -= 85; return rgb2Int(0, pos * 3, 255 - pos * 3); }
else { pos -= 170; return rgb2Int(pos * 3, 255 - pos * 3, 0); }
}
function rgb2Int(r, g, b) {
return ((r & 0xff) << 16) + ((g & 0xff) << 8) + (b & 0xff);
}
module.exports = {
init: init
};
| 'use strict';
const restify = require('restify');
const ws281x = require('rpi-ws281x-native');
var NUM_LEDS = parseInt(process.argv[2], 10) || 10;
var pixelData = new Uint32Array(NUM_LEDS);
var itv;
ws281x.init(NUM_LEDS);
function init () {
var server = restify.createServer();
server.get('/rainbow', (req, res, next) => {
res.send('rainbow');
// ---- animation-loop
clearInterval(itv);
var offset = 0;
itv = setInterval(function () {
for (var i = 0; i < NUM_LEDS; i++) {
pixelData[i] = colorwheel((offset + i) % 256);
}
offset = (offset + 1) % 256;
ws281x.render(pixelData);
}, 1000 / 30);
});
server.get('/stop', (req, res, next) => {
res.send('stop');
clearInterval(itv);
ws281x.reset();
});
server.listen(8080);
}
// rainbow-colors, taken from http://goo.gl/Cs3H0v
function colorwheel(pos) {
pos = 255 - pos;
if (pos < 85) { return rgb2Int(255 - pos * 3, 0, pos * 3); }
else if (pos < 170) { pos -= 85; return rgb2Int(0, pos * 3, 255 - pos * 3); }
else { pos -= 170; return rgb2Int(pos * 3, 255 - pos * 3, 0); }
}
function rgb2Int(r, g, b) {
return ((r & 0xff) << 16) + ((g & 0xff) << 8) + (b & 0xff);
}
module.exports = {
init: init
};
| JavaScript | 0.000003 |
bd01810ba846c1dfe7a438f3cb97fd6f147f3735 | remove express powered by header. added uncaught error handler | lib/index.js | lib/index.js | var express = require('express');
var bodyParser = require('body-parser');
var buildLog = require('./log.js');
var buildConfig = require('./config.js');
var buildRedis = require('./redis.js');
var buildCache = require('./cache.js');
var buildCron = require('./cron.js');
var buildRouter = require('./router.js');
module.exports = function (config, options) {
var conf = buildConfig(config);
var log = (options && options.log) ? options.log(conf) : buildLog(conf);
log.info('server: building redis connection');
var redis = buildRedis(conf, log);
log.info('server: building cache');
var cache = buildCache(conf, log, redis);
log.info('server: building cron');
var cron = buildCron(conf, log, redis, cache);
return {
config : conf,
log : log,
redis : redis,
cache : cache,
cron : cron,
start : function () {
cron.startCron();
cron.listenForMessages();
if (!config.port) {
throw new Error('missing "port" key in config');
}
var router = buildRouter(conf, log, cache, cron);
var app = express();
app.disable('x-powered-by');
app.use(accessLogger);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(router);
app.use(function (e, req, res, next) {
var status = e.status || 500;
res.send(status);
log.error('uncaught error: ' + (e.message || '?'), { error: e });
});
function accessLogger(req, res, next) {
log.debug('access: ' + req.method + ' ' + req.url);
next();
}
app.listen(config.port);
log.info('server: running on port ' + config.port);
}
};
}; | var express = require('express');
var bodyParser = require('body-parser');
var buildLog = require('./log.js');
var buildConfig = require('./config.js');
var buildRedis = require('./redis.js');
var buildCache = require('./cache.js');
var buildCron = require('./cron.js');
var buildRouter = require('./router.js');
module.exports = function (config, options) {
var conf = buildConfig(config);
var log = (options && options.log) ? options.log(conf) : buildLog(conf);
log.info('server: building redis connection');
var redis = buildRedis(conf, log);
log.info('server: building cache');
var cache = buildCache(conf, log, redis);
log.info('server: building cron');
var cron = buildCron(conf, log, redis, cache);
return {
config : conf,
log : log,
redis : redis,
cache : cache,
cron : cron,
start : function () {
cron.startCron();
cron.listenForMessages();
if (!config.port) {
throw new Error('missing "port" key in config');
}
var router = buildRouter(conf, log, cache, cron);
var app = express();
app.use(accessLogger);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(router);
function accessLogger(req, res, next) {
log.debug('access: ' + req.method + ' ' + req.url);
next();
}
app.listen(config.port);
log.info('server: running on port ' + config.port);
}
};
}; | JavaScript | 0.000005 |
3803a80298692ca5a7b38ccf635a79accee26fb5 | Copy user_access | lib/index.js | lib/index.js | 'use strict';
var fs = require('fs');
var MailParser = require("mailparser").MailParser;
var Encoder = require('node-html-encoder').Encoder;
var AnyfetchClient = require('cluestr');
var async = require('async');
/**
* HYDRATING FUNCTION
*
* @param {string} path Path of the specified file
* @param {string} document to hydrate
* @param {function} cb Callback, first parameter, is the error if any, then the processed data
*/
var reg = new RegExp("(<([^>]+)>)", "g");
function exists(item){
return item ? item : '';
}
module.exports = function(path, document, cb) {
if(!document.metadatas) {
document.metadatas = {};
}
if(!document.datas) {
document.datas = {};
}
var anyfetchClient = new AnyfetchClient();
anyfetchClient.setAccessToken(document.access_token);
var mailparser = new MailParser();
var encoder = new Encoder('entity');
mailparser.on("end", function(mail_object){
document.document_type = "email";
document.metadatas.to = [];
(mail_object.to || []).forEach(function(item){
document.metadatas.to.push(item);
});
document.metadatas.cc = [];
(mail_object.cc || []).forEach(function(item){
document.metadatas.cc.push(item);
});
document.metadatas.bcc = [];
(mail_object.bcc || []).forEach(function(item){
document.metadatas.bcc.push(item);
});
document.metadatas.from = exists(mail_object.from);
document.metadatas.subject = exists(mail_object.subject);
if (mail_object.html) {
document.datas.html = encoder.htmlDecode(mail_object.html).trim();
}
if (mail_object.headers && mail_object.headers.date) {
document.creation_date = new Date(mail_object.headers.date);
}
if (mail_object.text) {
document.metadatas.text = mail_object.text;
}
else if (document.datas.html) {
document.metadatas.text = document.datas.html.replace(reg, " ");
document.metadatas.text = document.metadatas.text.replace(" ", " ");
}
document.metadatas.text = document.metadatas.text.trim();
async.each((mail_object.attachments || []), function(attachment, cb){
var docAttachment = {};
docAttachment.identifier = document.identifier + "/" + attachment.fileName;
docAttachment.document_type = "file";
docAttachment.metadatas = {};
docAttachment.metadatas.path = "/" + attachment.fileName;
docAttachment.user_access = document.user_access;
// File to send
var fileConfigAttachment = function(){
return {
file: attachment.content,
filename: attachment.fileName,
knownLength: attachment.length
};
};
anyfetchClient.sendDocumentAndFile(docAttachment, fileConfigAttachment, function(err) {
cb(err);
});
}, function(err){
cb(err, document);
});
});
fs.createReadStream(path).pipe(mailparser);
};
| 'use strict';
var fs = require('fs');
var MailParser = require("mailparser").MailParser;
var Encoder = require('node-html-encoder').Encoder;
var AnyfetchClient = require('cluestr');
var async = require('async');
/**
* HYDRATING FUNCTION
*
* @param {string} path Path of the specified file
* @param {string} document to hydrate
* @param {function} cb Callback, first parameter, is the error if any, then the processed data
*/
var reg = new RegExp("(<([^>]+)>)", "g");
function exists(item){
return item ? item : '';
}
module.exports = function(path, document, cb) {
if(!document.metadatas) {
document.metadatas = {};
}
if(!document.datas) {
document.datas = {};
}
var anyfetchClient = new AnyfetchClient();
anyfetchClient.setAccessToken(document.access_token);
var mailparser = new MailParser();
var encoder = new Encoder('entity');
mailparser.on("end", function(mail_object){
document.document_type = "email";
document.metadatas.to = [];
(mail_object.to || []).forEach(function(item){
document.metadatas.to.push(item);
});
document.metadatas.cc = [];
(mail_object.cc || []).forEach(function(item){
document.metadatas.cc.push(item);
});
document.metadatas.bcc = [];
(mail_object.bcc || []).forEach(function(item){
document.metadatas.bcc.push(item);
});
document.metadatas.from = exists(mail_object.from);
document.metadatas.subject = exists(mail_object.subject);
if (mail_object.html) {
document.datas.html = encoder.htmlDecode(mail_object.html).trim();
}
if (mail_object.headers && mail_object.headers.date) {
document.creation_date = new Date(mail_object.headers.date);
}
if (mail_object.text) {
document.metadatas.text = mail_object.text;
}
else if (document.datas.html) {
document.metadatas.text = document.datas.html.replace(reg, " ");
document.metadatas.text = document.metadatas.text.replace(" ", " ");
}
document.metadatas.text = document.metadatas.text.trim();
async.each((mail_object.attachments || []), function(attachment, cb){
var docAttachment = {};
docAttachment.identifier = document.identifier + "/" + attachment.fileName;
docAttachment.document_type = "file";
docAttachment.metadatas = {};
docAttachment.metadatas.path = "/" + attachment.fileName;
// File to send
var fileConfigAttachment = function(){
return {
file: attachment.content,
filename: attachment.fileName,
knownLength: attachment.length
};
};
anyfetchClient.sendDocumentAndFile(docAttachment, fileConfigAttachment, function(err) {
cb(err);
});
}, function(err){
cb(err, document);
});
});
fs.createReadStream(path).pipe(mailparser);
}; | JavaScript | 0.000001 |
c9a2f9b16a40449f060a50c92654fc21eb043587 | Update index.js | lib/index.js | lib/index.js | var tokenize = require('./tokenize');
var languageProcessor = require('./language-processor');
/**
* Constructor
* @param {Object} options - Instance options
*/
var Sentiment = function (options) {
this.options = options;
};
/**
* Registers the specified language
*
* @param {String} languageCode
* - Two-digit code for the language to register
* @param {Object} language
* - The language module to register
*/
Sentiment.prototype.registerLanguage = function (languageCode, language) {
languageProcessor.addLanguage(languageCode, language);
};
/**
* Performs sentiment analysis on the provided input 'phrase'.
*
* @param {String} phrase
* - Input phrase
* @param {Object} opts
* - Options
* @param {Object} opts.language
* - Input language code (2 digit code), defaults to 'en'
* @param {Object} opts.extras
* - Optional sentiment additions to AFINN (hash k/v pairs)
* @param {function} callback
* - Optional callback
* @return {Object}
*/
Sentiment.prototype.analyze = function (phrase, opts, callback) {
// Parse arguments
if (typeof phrase === 'undefined') phrase = '';
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
opts = opts || {};
var languageCode = opts.language || 'en';
var labels = languageProcessor.getLabels(languageCode);
// Merge extra labels
if (typeof opts.extras === 'object') {
labels = Object.assign(labels, opts.extras);
}
// Storage objects
var tokens = tokenize(phrase),
score = 0,
words = [],
positive = [],
negative = [],
calculation = [];
// Iterate over tokens
var i = tokens.length;
while (i--) {
var obj = tokens[i];
if (!labels.hasOwnProperty(obj)) continue;
words.push(obj);
// Apply scoring strategy
var tokenScore = labels[obj];
// eslint-disable-next-line max-len
tokenScore = languageProcessor.applyScoringStrategy(languageCode, tokens, i, tokenScore);
if (tokenScore > 0) positive.push(obj);
if (tokenScore < 0) negative.push(obj);
score += tokenScore;
var zipObj = {};
// Calculations breakdown
zipObj[obj] = tokenScore;
calculation.push(zipObj);
}
var result = {
score: score,
comparative: tokens.length > 0 ? score / tokens.length : 0,
calculation: calculation,
tokens: tokens,
words: words,
positive: positive,
negative: negative
};
// Handle optional async interface
if (typeof callback === 'function') {
process.nextTick(function () {
callback(null, result);
});
} else {
return result;
}
};
module.exports = Sentiment;
| var tokenize = require('./tokenize');
var languageProcessor = require('./language-processor');
/**
* Constructor
* @param {Object} options - Instance options
*/
var Sentiment = function (options) {
this.options = options;
};
/**
* Registers the specified language
*
* @param {String} languageCode
* - Two-digit code for the language to register
* @param {Object} language
* - The language module to register
*/
Sentiment.prototype.registerLanguage = function (languageCode, language) {
languageProcessor.addLanguage(languageCode, language);
};
/**
* Performs sentiment analysis on the provided input 'phrase'.
*
* @param {String} phrase
* - Input phrase
* @param {Object} opts
* - Options
* @param {Object} opts.language
* - Input language code (2 digit code), defaults to 'en'
* @param {Object} opts.extras
* - Optional sentiment additions to AFINN (hash k/v pairs)
* @param {function} callback
* - Optional callback
* @return {Object}
*/
Sentiment.prototype.analyze = function (phrase, opts, callback) {
// Parse arguments
if (typeof phrase === 'undefined') phrase = '';
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
opts = opts || {};
var languageCode = opts.language || 'en';
var labels = languageProcessor.getLabels(languageCode);
// Merge extra labels
if (typeof opts.extras === 'object') {
labels = Object.assign(labels, opts.extras);
}
// Storage objects
var tokens = tokenize(phrase),
score = 0,
words = [],
positive = [],
negative = [],
calculation = [];
// Iterate over tokens
var i = tokens.length;
while (i--) {
var obj = tokens[i];
if (!labels.hasOwnProperty(obj)) continue;
words.push(obj);
// Apply scoring strategy
var tokenScore = labels[obj];
// eslint-disable-next-line max-len
tokenScore = languageProcessor.applyScoringStrategy(languageCode, tokens, i, tokenScore);
if (tokenScore > 0) positive.push(obj);
if (tokenScore < 0) negative.push(obj);
score += tokenScore;
var zipObj = {};
// Calculations breakdown
zipObj[obj] = tokenScore;
calculation.push(zipObj);
}
var result = {
score: score,
calculation: calculation,
comparative: tokens.length > 0 ? score / tokens.length : 0,
tokens: tokens,
words: words,
positive: positive,
negative: negative
};
// Handle optional async interface
if (typeof callback === 'function') {
process.nextTick(function () {
callback(null, result);
});
} else {
return result;
}
};
module.exports = Sentiment;
| JavaScript | 0.000002 |
c867172e874a73de564c6900c8fbf04b25970f26 | Allow the init function to be async | packages/express/index.js | packages/express/index.js | const express = require('express');
module.exports = async init => {
const app = express();
app.disable('x-powered-by');
await init(app, express);
const port = process.env.PORT;
if (!port) {
throw new Error('missing port');
}
app.listen(port, () => {
console.log(`app listen on port ${port}`);
});
};
| const express = require('express');
module.exports = init => {
const app = express();
app.disable('x-powered-by');
init(app, express);
const port = process.env.PORT;
if (!port) {
throw new Error('missing port');
}
app.listen(port, () => {
console.log(`app listen on port ${port}`);
});
};
| JavaScript | 0.000142 |
315b7c3c60261f0dd4d3a6aed06871473f3340d9 | returning the data | lib/index.js | lib/index.js | /**
* Fixture loader
*/
'use strict';
/**
* Module dependencies.
*/
var path = require('path');
var fs = require('fs');
/**
* Types.
*/
/**
* Load fixtures.
*/
function load(basePath, data, opts) {
fs.readdirSync(basePath).forEach(function(fileName) {
var filePath = path.join(basePath, fileName);
var ext = path.extname(fileName);
var name = path.basename(fileName, ext);
var stat = fs.statSync(filePath);
if (stat.isDirectory()) {
data[name] = {};
return load(filePath, data[name], opts);
}
if (!stat.isFile()) return;
if (data.hasOwnProperty(name)) {
throw new Error('conflict: ' + filePath);
}
var fileData = fs.readFileSync(filePath);
var fixture = function(type) {
switch (type || ext.slice(1)) {
case 'buffer':
return fileData.slice();
case 'json':
return JSON.parse(fileData.toString());
default:
return opts.trim ? fileData.toString().trim() : fileData.toString();
}
};
if (opts.type === 'function') {
data[name] = fixture;
return;
}
Object.defineProperty(data, name, {
configurable: true,
enumerable: true,
get: fixture,
});
});
}
/**
* Reload fixtures.
*/
exports.reload = function(opts) {
opts = opts || {};
if (!opts.path) {
opts.path = path.join(process.cwd(), 'test', 'fixtures');
}
if (!opts.scope) {
Object.keys(exports).forEach(function(key) {
if (key === 'reload') return;
delete exports[key];
});
opts.scope = exports;
}
if (!opts.hasOwnProperty('trim')) {
opts.trim = true;
}
if (!fs.existsSync(opts.path)) return;
var stat = fs.statSync(opts.path);
if (!stat.isDirectory()) return;
load(opts.path, opts.scope, opts);
return opts.scope;
};
/**
* Initial load.
*/
exports.reload();
| /**
* Fixture loader
*/
'use strict';
/**
* Module dependencies.
*/
var path = require('path');
var fs = require('fs');
/**
* Types.
*/
/**
* Load fixtures.
*/
function load(basePath, data, opts) {
fs.readdirSync(basePath).forEach(function(fileName) {
var filePath = path.join(basePath, fileName);
var ext = path.extname(fileName);
var name = path.basename(fileName, ext);
var stat = fs.statSync(filePath);
if (stat.isDirectory()) {
data[name] = {};
return load(filePath, data[name], opts);
}
if (!stat.isFile()) return;
if (data.hasOwnProperty(name)) {
throw new Error('conflict: ' + filePath);
}
var fileData = fs.readFileSync(filePath);
var fixture = function(type) {
switch (type || ext.slice(1)) {
case 'buffer':
return fileData.slice();
case 'json':
return JSON.parse(fileData.toString());
default:
return opts.trim ? fileData.toString().trim() : fileData.toString();
}
};
if (opts.type === 'function') {
data[name] = fixture;
return;
}
Object.defineProperty(data, name, {
configurable: true,
enumerable: true,
get: fixture,
});
});
}
/**
* Reload fixtures.
*/
exports.reload = function(opts) {
opts = opts || {};
if (!opts.path) {
opts.path = path.join(process.cwd(), 'test', 'fixtures');
}
if (!opts.scope) {
Object.keys(exports).forEach(function(key) {
if (key === 'reload') return;
delete exports[key];
});
opts.scope = exports;
}
if (!opts.hasOwnProperty('trim')) {
opts.trim = true;
}
if (!fs.existsSync(opts.path)) return;
var stat = fs.statSync(opts.path);
if (!stat.isDirectory()) return;
load(opts.path, opts.scope, opts);
};
/**
* Initial load.
*/
exports.reload();
| JavaScript | 0.999951 |
4b45eb37d1b8537979930a964892be6c267e019d | Fix reducer function name | site/reducers/playback.js | site/reducers/playback.js | import {
START_PLAYBACK,
PAUSE_PLAYBACK,
} from '../constants/ActionTypes'
const initialState = {
startTime: null,
pauseTime: null,
}
export default function playback(state = initialState, action) {
switch (action.type) {
case START_PLAYBACK:
return Object.assign({}, state, {
startTime: performance.now(),
})
case PAUSE_PLAYBACK:
return Object.assign({}, state, {
pauseTime: performance.now(),
})
default:
return state
}
}
| import {
START_PLAYBACK,
PAUSE_PLAYBACK,
} from '../constants/ActionTypes'
const initialState = {
startTime: null,
pauseTime: null,
}
export default function song(state = initialState, action) {
switch (action.type) {
case START_PLAYBACK:
return Object.assign({}, state, {
startTime: performance.now(),
})
case PAUSE_PLAYBACK:
return Object.assign({}, state, {
pauseTime: performance.now(),
})
default:
return state
}
}
| JavaScript | 0.999551 |
215d8166bbf11aec7b9cc56c18364f092b88d849 | Remove underscore.js dependency. | formErrors.js | formErrors.js | angular.module('FormErrors', [])
// just put <form-errors><form-errors> wherever you want form errors to be displayed!
.directive('formErrors', [function () {
return {
// only works if embedded in a form or an ngForm (that's in a form).
// It does use its closest parent that is a form OR ngForm
require: '^form',
template:
'<div class="form-errors" ng-transclude>' +
'<div class="form-error" ng-repeat="error in errors">' +
'{{error}}' +
'</div>' +
'</div>',
replace: true,
transclude: true,
restrict: 'AE',
scope: { isValid: '=' },
link: function postLink(scope, elem, attrs, ctrl) {
// list of some default error reasons
var defaultErrorReasons = {
required: 'is required.',
minlength: 'is too short.',
maxlength: 'is too long.',
email: 'is not a valid email address.',
pattern: 'does not expect the matched pattern.',
fallback: 'is invalid.'
},
// uppercase words helper
ucwords = function(text) {
return text.replace(/^([a-z])|\s+([a-z])/g, function ($1) {
return $1.toUpperCase();
});
},
// breakup camelCase
breakup = function(text, separator) {
return text.replace(/[A-Z]/g, function (match) {
return separator + match;
});
},
// humanize words
humanize = function (value) {
return ucwords(breakup(value, ' ').replace(/[-_+]/g, ' '));
},
// this is where we form our message
formMessage = function formMessage(elem, error, props) {
// get the nice name if used the niceName directive
// or humanize the elem name and call it good
var niceName = props.$niceName || humanize(elem);
// get a reason from our default set
var reason = defaultErrorReasons[error] || defaultErrorReasons.fallback;
// if they used the errorMessages directive, grab that message
if(typeof props.$errorMessages === 'object')
reason = props.$errorMessages[error];
else if(typeof props.$errorMessages === 'string')
reason = props.$errorMessages;
// return our nicely formatted message
return niceName + ' ' + reason;
};
// only update the list of errors if there was actually a change
scope.$watch(function() { return ctrl.$error; }, function() {
// we can pass in a variable to keep track of form validity in page's ctrl
scope.isValid = ctrl.$valid;
scope.errors = [];
angular.forEach(ctrl, function(props, elem) {
// elem has some internal properties we don't want to iterate over
if(elem[0] === '$') return;
angular.forEach(props.$error, function(isInvalid, error) {
// don't need to even try and get a a message unless it's invalid
if(isInvalid) {
scope.errors.push(formMessage(elem, error, props));
}
});
});
}, true);
}
};
}])
// set a nice name to $niceName on the ngModel ctrl for later use
.directive('niceName', [function () {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ctrl) {
ctrl.$niceName = attrs.niceName;
}
};
}])
// set an errorMessage(s) to $errorMessages on the ngModel ctrl for later use
.directive('errorMessages', [function () {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ctrl) {
// attrs.errorMessages can be:
// 1) "must be filled out."
// 2) "'must be filled out.'"
// 3) "{ required: 'must be filled out.' }"
try {
ctrl.$errorMessages = scope.$eval(attrs.errorMessages);
} catch(e) {
ctrl.$errorMessages = attrs.errorMessages;
}
}
};
}]); | angular.module('FormErrors', [])
// just put <form-errors><form-errors> wherever you want form errors to be displayed!
.directive('formErrors', [function () {
return {
// only works if embedded in a form or an ngForm (that's in a form).
// It does use its closest parent that is a form OR ngForm
require: '^form',
template:
'<div class="form-errors" ng-transclude>' +
'<div class="form-error" ng-repeat="error in errors">' +
'{{error}}' +
'</div>' +
'</div>',
replace: true,
transclude: true,
restrict: 'AE',
scope: { isValid: '=' },
link: function postLink(scope, elem, attrs, ctrl) {
// list of some default error reasons
var defaultErrorReasons = {
required: 'is required.',
minlength: 'is too short.',
maxlength: 'is too long.',
email: 'is not a valid email address.',
pattern: 'does not expect the matched pattern.',
fallback: 'is invalid.'
},
// uppercase words helper
ucwords = function(text) {
return text.replace(/^([a-z])|\s+([a-z])/g, function ($1) {
return $1.toUpperCase();
});
},
// breakup camelCase
breakup = function(text, separator) {
return text.replace(/[A-Z]/g, function (match) {
return separator + match;
});
},
// humanize words
humanize = function (value) {
return ucwords(breakup(value, ' ').replace(/[-_+]/g, ' '));
},
// this is where we form our message
formMessage = function formMessage(elem, error, props) {
// get the nice name if used the niceName directive
// or humanize the elem name and call it good
var niceName = props.$niceName || humanize(elem);
// get a reason from our default set
var reason = defaultErrorReasons[error] || defaultErrorReasons.fallback;
// if they used the errorMessages directive, grab that message
if(typeof props.$errorMessages === 'object')
reason = props.$errorMessages[error];
else if(typeof props.$errorMessages === 'string')
reason = props.$errorMessages;
// return our nicely formatted message
return niceName + ' ' + reason;
};
// only update the list of errors if there was actually a change
scope.$watch(function() { return ctrl.$error; }, function() {
// we can pass in a variable to keep track of form validity in page's ctrl
scope.isValid = ctrl.$valid;
scope.errors = [];
_.each(ctrl, function(props, elem) {
// elem has some internal properties we don't want to iterate over
if(elem[0] === '$') return;
_.each(props.$error, function(isInvalid, error) {
// don't need to even try and get a a message unless it's invalid
if(isInvalid) {
scope.errors.push(formMessage(elem, error, props));
}
});
});
}, true);
}
};
}])
// set a nice name to $niceName on the ngModel ctrl for later use
.directive('niceName', [function () {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ctrl) {
ctrl.$niceName = attrs.niceName;
}
};
}])
// set an errorMessage(s) to $errorMessages on the ngModel ctrl for later use
.directive('errorMessages', [function () {
return {
require: 'ngModel',
link: function(scope, elem, attrs, ctrl) {
// attrs.errorMessages can be:
// 1) "must be filled out."
// 2) "'must be filled out.'"
// 3) "{ required: 'must be filled out.' }"
try {
ctrl.$errorMessages = scope.$eval(attrs.errorMessages);
} catch(e) {
ctrl.$errorMessages = attrs.errorMessages;
}
}
};
}]); | JavaScript | 0 |
2c5b10044921635da6e3f7b9cfa33180b7f55138 | rewrite for sensors | lib/index.js | lib/index.js | /**
* Imports
*/
var fs = require('fs')
/**
* Vars
*/
var motor = {
path: '/sys/class/tacho-motor/',
available: getPaths('/sys/class/tacho-motor/'),
prefix: 'out'
}
var sensor = {
path: '/sys/class/lego-sensor/',
available: getPaths('/sys/class/lego-sensor/'),
prefix: 'in'
}
/**
* Expose devices
*/
module.exports = devices
/**
* Get a device
* @param {String} port
* @return {String} path
*/
function devices (port) {
var device = isNaN(port) ? motor : sensor
if (device === motor) {
port = port.toUpperCase()
}
return device.path + device.available[device.prefix + port]
}
function getPaths (path) {
return fs.readdirSync(path).reduce(function (obj, file) {
var portName = fs.readFileSync(path + file + '/port_name', 'utf-8').trim()
obj[portName] = file.trim()
return obj
}, {})
}
| /**
* Imports
*/
var fs = require('fs')
/**
* Vars
*/
var motorPath = '/sys/class/tacho-motor/'
var paths = fs.readdirSync(motorPath).reduce(function (obj, file) {
var portName = fs.readFileSync(motorPath + file + '/port_name', 'utf-8').trim()
obj[portName] = file.trim()
return obj
}, {})
/**
* Expose devices
*/
module.exports = devices
/**
* Get a device
* @param {String} port
* @return {String} path
*/
function devices (port) {
const portName = 'out' + port.toUpperCase()
return portToPath(portName)
}
/**
* Convert port to path
* @return {Object}
*/
function portToPath (port) {
return motorPath + paths[port]
}
| JavaScript | 0.000311 |
42b44fabcb141b429cb024bd173a385666d60595 | fix validate import (commonJS / ES6 compatibility issue) | lib/index.js | lib/index.js | const modDelim = '_';
const elemDelim = '__';
export function buildClassName(bemjson) {
if (!bemjson) {
return '';
}
// validation
// istanbul ignore next
if (process.env.NODE_ENV !== 'production') {
require('./validate.js').default(bemjson);
}
let out = '';
// block
if (typeof bemjson.block !== 'undefined') {
out += (out ? ' ' : '') + bemjson.block;
// elem
if (typeof bemjson.elem !== 'undefined') {
out += elemDelim + bemjson.elem;
}
const entity = out;
if (typeof bemjson.mods !== 'undefined') {
Object.keys(bemjson.mods).forEach(modName => {
const modValue = bemjson.mods[modName];
let modValueString = '';
if (modValue !== false) {
// 'short' boolean mods
if (modValue !== true) {
modValueString += modDelim + modValue;
}
out += ' ' + entity + modDelim + modName + modValueString;
}
});
}
}
if (typeof bemjson.mix !== 'undefined') {
// convert object or array into array
const mixes = [].concat(bemjson.mix);
mixes
// filter holes in array
.filter(mix => mix)
.forEach(mix => {
out += (out ? ' ' : '') + buildClassName(mix);
});
}
if (typeof bemjson.className !== 'undefined') {
out += (out ? ' ' : '') + bemjson.className;
}
return out;
}
| const modDelim = '_';
const elemDelim = '__';
export function buildClassName(bemjson) {
if (!bemjson) {
return '';
}
// validation
// istanbul ignore next
if (process.env.NODE_ENV !== 'production') {
require('./validate.js')(bemjson);
}
let out = '';
// block
if (typeof bemjson.block !== 'undefined') {
out += (out ? ' ' : '') + bemjson.block;
// elem
if (typeof bemjson.elem !== 'undefined') {
out += elemDelim + bemjson.elem;
}
const entity = out;
if (typeof bemjson.mods !== 'undefined') {
Object.keys(bemjson.mods).forEach(modName => {
const modValue = bemjson.mods[modName];
let modValueString = '';
if (modValue !== false) {
// 'short' boolean mods
if (modValue !== true) {
modValueString += modDelim + modValue;
}
out += ' ' + entity + modDelim + modName + modValueString;
}
});
}
}
if (typeof bemjson.mix !== 'undefined') {
// convert object or array into array
const mixes = [].concat(bemjson.mix);
mixes
// filter holes in array
.filter(mix => mix)
.forEach(mix => {
out += (out ? ' ' : '') + buildClassName(mix);
});
}
if (typeof bemjson.className !== 'undefined') {
out += (out ? ' ' : '') + bemjson.className;
}
return out;
}
| JavaScript | 0 |
49e4ea4ea04539ce473da175b48d95277700e33b | Add missing use strict statement to lib/index.js | lib/index.js | lib/index.js | 'use strict';
var Client = require('./client'),
Sandbox = require('./sandbox'),
accounts = require('./accounts'),
calendars = require('./calendars'),
contacts = require('./contacts'),
model = require('./model'),
request = require('./request'),
transport = require('./transport');
/**
* model
*/
for (var key in model) {
exports[key] = model[key];
}
/**
* accounts
*/
exports.createAccount = accounts.create;
/**
* calendars
*/
exports.createCalendarObject = calendars.createCalendarObject;
exports.updateCalendarObject = calendars.updateCalendarObject;
exports.deleteCalendarObject = calendars.deleteCalendarObject;
exports.syncCalendar = calendars.sync;
/**
* contacts
*/
exports.createCard = contacts.createCard;
exports.updateCard = contacts.updateCard;
exports.deleteCard = contacts.deleteCard;
exports.syncAddressBook = contacts.sync;
/**
* client
*/
exports.Client = Client;
/**
* request
*/
exports.request = request;
exports.Request = request.Request;
/**
* sandbox
*/
exports.createSandbox = function() {
return new Sandbox();
};
exports.Sandbox = Sandbox;
/**
* transport
*/
exports.transport = transport;
exports.Transport = transport.Transport;
| var Client = require('./client'),
Sandbox = require('./sandbox'),
accounts = require('./accounts'),
calendars = require('./calendars'),
contacts = require('./contacts'),
model = require('./model'),
request = require('./request'),
transport = require('./transport');
/**
* model
*/
for (var key in model) {
exports[key] = model[key];
}
/**
* accounts
*/
exports.createAccount = accounts.create;
/**
* calendars
*/
exports.createCalendarObject = calendars.createCalendarObject;
exports.updateCalendarObject = calendars.updateCalendarObject;
exports.deleteCalendarObject = calendars.deleteCalendarObject;
exports.syncCalendar = calendars.sync;
/**
* contacts
*/
exports.createCard = contacts.createCard;
exports.updateCard = contacts.updateCard;
exports.deleteCard = contacts.deleteCard;
exports.syncAddressBook = contacts.sync;
/**
* client
*/
exports.Client = Client;
/**
* request
*/
exports.request = request;
exports.Request = request.Request;
/**
* sandbox
*/
exports.createSandbox = function() {
return new Sandbox();
};
exports.Sandbox = Sandbox;
/**
* transport
*/
exports.transport = transport;
exports.Transport = transport.Transport;
| JavaScript | 0.000003 |
ab77a4b0726e7e6ee7ee9c0ee8093a314b773175 | refactor add commands from array | lib/index.js | lib/index.js | const api = require('../api')
const getLastMessage = require('./modules/getlastmessage')
class Botact {
constructor(options) {
if (!options.confirmation || !options.token) {
throw 'Bot\'s options isn\'t full.'
}
this.msg = []
this.action = {}
this.settings = options
this.messages = { commands: [], hears: [] }
}
confirm(req, res) {
if (req.body.type === 'confirmation') {
this.settings.group_id = req.body.group_id
return res.end(this.settings.confirmation)
}
return false
}
execute() {
setInterval(() => {
const method = this.msg.map(obj => `API.messages.send(${JSON.stringify(obj)})`)
this.msg = []
if (method.length) {
api('execute', {
code: `return [ ${method.join(',')} ];`,
access_token: this.settings.token
}).then(console.log).catch(console.log)
}
}, 350)
}
command(command, callback) {
if (typeof command === 'object') {
command.forEach(cmd => this.messages.commands[cmd.toLowerCase()] = callback)
} else {
this.messages.commands[command.toLowerCase()] = callback
}
}
hears(command, callback) {
if (typeof command === 'object') {
command.forEach(cmd => this.messages.hears[cmd.toLowerCase()] = callback)
} else {
this.messages.hears[command.toLowerCase()] = callback
}
}
on(callback) {
this.messages.on = callback
}
reply(user_id, message, attachments) {
this.msg.push({
user_id: user_id,
message: message,
attachment: attachments
})
}
event(event, callback) {
this.action[event] = callback
}
listen(req, res) {
res.end('ok')
const data = req.body.object
data.body = getLastMessage(data).body
if (req.body.type === 'message_new') {
let methods = {}
Object.keys(this.messages.hears).map(method => methods[method] = this.messages.hears[method])
if (this.messages.commands[data.body.toLowerCase()]) {
this.messages.commands[data.body.toLowerCase()](data)
} else {
if (!Object.keys(methods).length) {
if (typeof this.messages.on === 'function') {
return this.messages.on(data)
}
return console.log('Bot can\'t found reserved reply.')
}
Object.keys(methods).some((key, i) => {
if (new RegExp(key, 'i').test(data.body.toLowerCase())) {
return methods[key](data) || true
}
if (i === --Object.keys(methods).length) {
return this.messages.on(data)
}
})
}
}
if (typeof this.action[req.body.type] === 'function') {
this.action[req.body.type](data)
}
}
}
module.exports = Botact
| const api = require('../api')
const getLastMessage = require('./modules/getlastmessage')
class Botact {
constructor(options) {
if (!options.confirmation || !options.token) {
throw 'Bot\'s options isn\'t full.'
}
this.msg = []
this.action = {}
this.settings = options
this.messages = { commands: [], hears: [] }
}
confirm(req, res) {
if (req.body.type === 'confirmation') {
this.settings.group_id = req.body.group_id
return res.end(this.settings.confirmation)
}
return false
}
execute() {
setInterval(() => {
const method = this.msg.map(obj => `API.messages.send(${JSON.stringify(obj)})`)
this.msg = []
if (method.length) {
api('execute', {
code: `return [ ${method.join(',')} ];`,
access_token: this.settings.token
}).then(console.log).catch(console.log)
}
}, 350)
}
command(command, callback) {
if (typeof command === 'object') {
return command.some(cmd => this.messages.commands[cmd.toLowerCase()] = callback)
}
this.messages.commands[command.toLowerCase()] = callback
}
hears(command, callback) {
if (typeof command === 'object') {
return command.some(cmd => this.messages.hears[cmd.toLowerCase()] = callback)
}
this.messages.hears[command.toLowerCase()] = callback
}
on(callback) {
this.messages.on = callback
}
reply(user_id, message, attachments) {
this.msg.push({
user_id: user_id,
message: message,
attachment: attachments
})
}
event(event, callback) {
this.action[event] = callback
}
listen(req, res) {
res.end('ok')
const data = req.body.object
data.body = getLastMessage(data).body
if (req.body.type === 'message_new') {
let methods = {}
Object.keys(this.messages.hears).map(method => methods[method] = this.messages.hears[method])
if (this.messages.commands[data.body.toLowerCase()]) {
this.messages.commands[data.body.toLowerCase()](data)
} else {
if (!Object.keys(methods).length) {
if (typeof this.messages.on === 'function') {
return this.messages.on(data)
}
return console.log('Bot can\'t found reserved reply.')
}
Object.keys(methods).some((key, i) => {
if (new RegExp(key, 'i').test(data.body.toLowerCase())) {
return methods[key](data) || true
}
if (i === --Object.keys(methods).length) {
return this.messages.on(data)
}
})
}
}
if (typeof this.action[req.body.type] === 'function') {
this.action[req.body.type](data)
}
}
}
module.exports = Botact
| JavaScript | 0.000052 |
f49f0c7bb89f086cf0050ef3baf02ec84237c156 | Remove eventual onEmpty DOM | lib/html5/_list.js | lib/html5/_list.js | 'use strict';
var isFunction = require('es5-ext/lib/Function/is-function')
, d = require('es5-ext/lib/Object/descriptor')
, isList = require('es5-ext/lib/Object/is-list')
, isPlainObject = require('es5-ext/lib/Object/is-plain-object')
, makeElement = require('dom-ext/lib/Document/prototype/make-element')
, castAttributes = require('dom-ext/lib/Element/prototype/cast-attributes')
, elExtend = require('dom-ext/lib/Element/prototype/extend')
, remove = require('dom-ext/lib/Element/prototype/remove')
, replaceContent = require('dom-ext/lib/Element/prototype/replace-content')
, isNode = require('dom-ext/lib/Node/is-node')
, isText = require('dom-ext/lib/Text/is-text')
, memoize = require('memoizee/lib/regular')
, map = Array.prototype.map;
module.exports = function (name, childName, isChildNode) {
require('../base/element').extProperties[name] = {
_construct: d(function (list/*, renderItem, thisArg*/) {
var attrs, renderItem, render, thisArg, cb, onEmpty;
if (isPlainObject(list) && !isFunction(arguments[1])) {
attrs = list;
list = arguments[1];
renderItem = arguments[2];
thisArg = arguments[3];
} else {
renderItem = arguments[1];
thisArg = arguments[2];
}
if (isNode(list) || !isList(list) || !isFunction(renderItem)) {
return elExtend.apply(this, arguments);
}
if (attrs) {
if (attrs.onEmpty) {
onEmpty = attrs.onEmpty;
delete attrs.onEmpty;
if (isNode(onEmpty)) remove.call(onEmpty);
}
castAttributes.call(this, attrs);
}
cb = function (item, index, list) {
var result;
result = this.safeCollect(renderItem.bind(thisArg, item, index, list));
if (result == null) return null;
if (isText(result) && !result.data && result._isDomExtLocation_) {
return result;
}
if (!isChildNode(result)) {
result = makeElement.call(this.document, childName, result);
}
return result;
};
render = function () {
var content = map.call(list, cb, this._domjs);
if (!content.length && onEmpty) content = onEmpty;
replaceContent.call(this, content);
}.bind(this);
if (typeof list.on === 'function') {
cb = memoize(cb, { length: 1 });
list.on('change', render);
}
render();
return this;
})
};
};
| 'use strict';
var isFunction = require('es5-ext/lib/Function/is-function')
, d = require('es5-ext/lib/Object/descriptor')
, isList = require('es5-ext/lib/Object/is-list')
, isPlainObject = require('es5-ext/lib/Object/is-plain-object')
, makeElement = require('dom-ext/lib/Document/prototype/make-element')
, castAttributes = require('dom-ext/lib/Element/prototype/cast-attributes')
, elExtend = require('dom-ext/lib/Element/prototype/extend')
, replaceContent = require('dom-ext/lib/Element/prototype/replace-content')
, isNode = require('dom-ext/lib/Node/is-node')
, isText = require('dom-ext/lib/Text/is-text')
, memoize = require('memoizee/lib/regular')
, map = Array.prototype.map;
module.exports = function (name, childName, isChildNode) {
require('../base/element').extProperties[name] = {
_construct: d(function (list/*, renderItem, thisArg*/) {
var attrs, renderItem, render, thisArg, cb, onEmpty;
if (isPlainObject(list) && !isFunction(arguments[1])) {
attrs = list;
list = arguments[1];
renderItem = arguments[2];
thisArg = arguments[3];
} else {
renderItem = arguments[1];
thisArg = arguments[2];
}
if (isNode(list) || !isList(list) || !isFunction(renderItem)) {
return elExtend.apply(this, arguments);
}
if (attrs) {
if (attrs.onEmpty) {
onEmpty = attrs.onEmpty;
delete attrs.onEmpty;
}
castAttributes.call(this, attrs);
}
cb = function (item, index, list) {
var result;
result = this.safeCollect(renderItem.bind(thisArg, item, index, list));
if (result == null) return null;
if (isText(result) && !result.data && result._isDomExtLocation_) {
return result;
}
if (!isChildNode(result)) {
result = makeElement.call(this.document, childName, result);
}
return result;
};
render = function () {
var content = map.call(list, cb, this._domjs);
if (!content.length && onEmpty) content = onEmpty;
replaceContent.call(this, content);
}.bind(this);
if (typeof list.on === 'function') {
cb = memoize(cb, { length: 1 });
list.on('change', render);
}
render();
return this;
})
};
};
| JavaScript | 0.000005 |
e7ad1992ab12a19774c4be3c30724f5677314f45 | Fix a typo | lib/index.js | lib/index.js | 'use babel'
import {Motion} from './main'
import {ensureUninstalled} from './helpers'
module.exports = {
config: {
liveReload: {
description: 'Automatically reload motion page in editor',
type: 'boolean',
default: true
},
lintingDelay: {
description: 'Delay for updating lint messages in editor in ms',
type: 'integer',
minimum: 0,
default: 300
}
},
activate() {
require('atom-package-deps').install().then(function() {
atom.config.set('color-picker.automaticReplace', true)
atom.config.set('autocomplete-plus.enableBuiltinProvider', false)
atom.packages.disablePackage('autocomplete-snippets')
})
this.motion = new Motion()
this.motion.activate()
ensureUninstalled('steel-motion')
ensureUninstalled('intelli-colorpicker')
ensureUninstalled('number-range')
ensureUninstalled('flint')
ensureUninstalled('language-flint')
},
consumeLinter(indieRegistry) {
const linter = indieRegistry.register({name: 'Motion'})
this.motion.consumeLinter(linter)
},
consumeStatusbar(statusBar) {
this.motion.consumeStatusbar(statusBar)
},
provideAutocomplete() {
return this.motion.provideAutocomplete()
},
provideDeclarations() {
return this.motion.provideDeclarations()
},
dispose() {
this.motion.dispose()
}
}
| 'use babel'
import {Motion} from './main'
import {ensureUninstalled} from './helpers'
module.exports = {
config: {
liveReload: {
description: 'Automatically reload motion page in editor',
type: 'boolean',
default: true
},
lintingDelay: {
description: 'Delay for updating lint messages in editor in ms',
type: 'integer',
minimum: 0,
default: 300
}
},
activate() {
require('atom-package-deps').install().then(function() {
atom.config.set('color-picker.automaticReplace', true)
atom.config.set('autocomplete-plus.enableBuiltinProvider', false)
atom.packages.disablePackage('autocomplete-snippets')
})
this.motion = new Motion()
this.motion.activate()
ensureUninstalled('steel-motion')
ensureUninstalled('intelli-colorpicker')
ensureUninstalled('number-range')
ensureUninstalled('flint')
ensureUninstalled('language-flint')
},
consumeLinter(indieRegistry) {
const linter = indieRegistry.register({name: 'Motion'})
this.motion.consumeLinter(linter)
},
consumeStatusbar(statusBar) {
this.motion.consumeStatusbar(statusBar)
},
provideAutocomplete() {
return this.motion.provideAutocomplete()
},
provideDeclarations() {
return this.flint.provideDeclarations()
},
dispose() {
this.motion.dispose()
}
}
| JavaScript | 0.003765 |
62ca306b5e396e826f5da94bbd7f3b60f3f3d15e | Add more tests | web/src/js/components/Search/__tests__/SearchTextResult.test.js | web/src/js/components/Search/__tests__/SearchTextResult.test.js | /* eslint-env jest */
import React from 'react'
import {
shallow
} from 'enzyme'
const getMockProps = () => ({
result: {
title: 'Some search result',
linkURL: 'http://www.example.com',
snippet: 'This is the search result description.'
}
})
afterEach(() => {
jest.clearAllMocks()
})
describe('SearchTextResult page component', () => {
it('renders without error', () => {
const SearchTextResult = require('js/components/Search/SearchTextResult').default
const mockProps = getMockProps()
shallow(
<SearchTextResult {...mockProps} />
)
})
it('displays the title as a clickable link', () => {
const SearchTextResult = require('js/components/Search/SearchTextResult').default
const mockProps = getMockProps()
mockProps.result.title = 'Hey, click to our site!'
const wrapper = shallow(
<SearchTextResult {...mockProps} />
)
const anchor = wrapper.find(`a[href="${mockProps.result.linkURL}"]`).first()
expect(anchor.find('h3').first().text()).toEqual('Hey, click to our site!')
})
it('displays the link URL', () => {
const SearchTextResult = require('js/components/Search/SearchTextResult').default
const mockProps = getMockProps()
mockProps.result.linkURL = 'https://example.io'
const wrapper = shallow(
<SearchTextResult {...mockProps} />
)
const linkURL = wrapper
.find('div')
.filterWhere(n => n.text() === 'https://example.io')
expect(linkURL.length).toBe(1)
})
it('displays the snippet text', () => {
const SearchTextResult = require('js/components/Search/SearchTextResult').default
const mockProps = getMockProps()
mockProps.result.snippet = 'Hi there!'
const wrapper = shallow(
<SearchTextResult {...mockProps} />
)
const snippetElem = wrapper
.find('div')
.filterWhere(n => n.text() === 'Hi there!')
expect(snippetElem.length).toBe(1)
})
})
| /* eslint-env jest */
import React from 'react'
import {
shallow
} from 'enzyme'
const getMockProps = () => ({
result: {
title: 'Some search result',
linkURL: 'http://www.example.com',
snippet: 'This is the search result description.'
}
})
afterEach(() => {
jest.clearAllMocks()
})
describe('SearchTextResult page component', () => {
it('renders without error', () => {
const SearchTextResult = require('js/components/Search/SearchTextResult').default
const mockProps = getMockProps()
shallow(
<SearchTextResult {...mockProps} />
)
})
})
| JavaScript | 0 |
70fe2dab0f4105f88105a3583348c16db5ac9763 | add lowr function | lib/index.js | lib/index.js | var async = require('async')
, etcd = new (require('node-etcd'))();
// Accepts an array of strings as configuration keys.
// Each {key1} corresponds to /config/{key1} entry in etcd.
// Returns an object with properties corresponding to input keys.
// Each property is an EventEmitter. It emits the `modified` event
// when the value of the configuration key. In addition, each EventEmitter
// has a `current` property which returns the current string value stored in etcd.
exports.etcd_config = function (keys, callback) {
var config = {};
async.each(
keys,
function (key, callback) {
etcd.get('/config/' + key, function (error, result) {
if (error)
return callback(error);
var watch = etcd.watcher('/config/' + key, result.node.modifiedIndex + 1);
watch.current = result.node.value;
watch.on('change', function (result) {
if (watch.current !== result.node.value)
this.emit('modified', result.node.value);
watch.current = result.node.value;
});
watch.on('error', function (error) {
throw error; // TODO (tjanczuk): consider surfacing etcd errors differently?
});
config[key] = watch;
callback();
});
},
function (error) {
callback && (error ? callback(error) : callback(null, config));
}
);
return config; // for convenience of REPL
};
// Converts response from etcd into a JS object representing only
// the data and its hierarchy. Etcd directories are represented as JS objects.
function etcd2js(node) {
if (node.value !== undefined)
return node.value;
var result = {};
if (Array.isArray(node.nodes)) {
node.nodes.forEach(function (child) {
result[child.key.substring(node.key.length === 1 ? 1 : node.key.length + 1)]
= etcd2js(child);
});
}
return result;
}
exports.etcd2js = etcd2js;
// Gets the key from etcd (recursively) and returns a JS representation of
// the hierarchy.
exports.etcd_get = function (key, callback) {
etcd.get(key, { recursive: true }, function (error, result) {
error ? callback(error): callback(null, etcd2js(result.node));
});
};
// The .lowr async function completes in either of two situations:
//
// 1. If the sync_root is not locked, it obtains an exclusive, distributed lock of the sync_root
// via etcd and returns a function that can be used to release the lock as a callback parameter.
//
// 2. If the sync_root is locked, it waits for that lock to be released, and returns without any results.
//
// This logic allows several homogenic, distributed processes to ensure that a certain workload is
// completed by only one of them.
//
// The lock TTL in etcd is configured with the `/config/lock.ttl` confguration entry.
// While the lock is held, it is reset to that TTL every `/config/lock.renew` period.
var lock_id = process.pid + '.' + Date.now();
exports.lowr = function (sync_root, etcdconfig, callback) {
// Attempt to take the lock
etcd.set(
'/lock/' + sync_root,
lock_id,
{ prevExist: false, ttl: +etcdconfig.lock_ttl.current },
function (error, result) {
if (error) {
if (error.errorCode === 105) {
// Lock is currently held, wait for its release
var watch = etcd.watcher('/lock/' + sync_root, error.error.index + 1);
watch.on('change', function (result) {
if (result.node.value === undefined)
done();
});
watch.on('error', done);
function done(error, result) {
watch.stop();
callback(error, result);
}
return;
}
return callback(error);
}
// Lock was taken, renew it periodically until released
var renew = setInterval(function () {
etcd.set('/lock/' + sync_root, lock_id, { ttl: +etcdconfig.lock_ttl.current });
}, +etcdconfig.lock_renew.current * 1000);
// Return a function that must be used to release the lock
callback(null, function (callback) {
clearInterval(renew);
etcd.compareAndDelete('/lock/' + sync_root, lock_id, function (error) {
return callback && callback(error);
});
});
});
};
| var async = require('async')
, etcd = new (require('node-etcd'))();
// Accepts an array of strings as configuration keys.
// Each {key1} corresponds to /config/{key1} entry in etcd.
// Returns an object with properties corresponding to input keys.
// Each property is an EventEmitter. It emits the `modified` event
// when the value of the configuration key. In addition, each EventEmitter
// has a `current` property which returns the current string value stored in etcd.
exports.etcd_config = function (keys, callback) {
var config = {};
async.each(
keys,
function (key, callback) {
etcd.get('/config/' + key, function (error, result) {
if (error)
return callback(error);
var watch = etcd.watcher('/config/' + key, result.node.modifiedIndex + 1);
watch.current = result.node.value;
watch.on('change', function (result) {
if (watch.current !== result.node.value)
this.emit('modified', result.node.value);
watch.current = result.node.value;
});
watch.on('error', function (error) {
throw error; // TODO (tjanczuk): consider surfacing etcd errors differently?
});
config[key] = watch;
callback();
});
},
function (error) {
callback && (error ? callback(error) : callback(null, config));
}
);
return config; // for convenience of REPL
};
// Converts response from etcd into a JS object representing only
// the data and its hierarchy. Etcd directories are represented as JS objects.
function etcd2js(node) {
if (node.value !== undefined)
return node.value;
var result = {};
if (Array.isArray(node.nodes)) {
node.nodes.forEach(function (child) {
result[child.key.substring(node.key.length === 1 ? 1 : node.key.length + 1)]
= etcd2js(child);
});
}
return result;
}
exports.etcd2js = etcd2js;
// Gets the key from etcd (recursively) and returns a JS representation of
// the hierarchy.
exports.etcd_get = function (key, callback) {
etcd.get(key, { recursive: true }, function (error, result) {
error ? callback(error): callback(null, etcd2js(result.node));
});
};
| JavaScript | 0.001708 |
6f5f47c0149938ed92d7e64c3e2d4200d0e6625a | Fix for returning only single device | src/plugins/ble.js | src/plugins/ble.js | // install : cordova plugin add https://github.com/don/cordova-plugin-ble-central#:/plugin
// link : https://github.com/don/cordova-plugin-ble-central
angular.module('ngCordova.plugins.ble', [])
.factory('$cordovaBLE', ['$q', '$timeout', function ($q, $timeout) {
return {
scan: function (services, seconds) {
var q = $q.defer();
var devices = [];
ble.scan(services, seconds, function (result) {
devices.push(result);
}, function (error) {
q.reject(error);
});
$timeout(function() {
q.resolve(devices);
}, seconds*1000);
return q.promise;
},
connect: function (deviceID) {
var q = $q.defer();
ble.connect(deviceID, function (result) {
q.resolve(result);
}, function (error) {
q.reject(error);
});
return q.promise;
},
disconnect: function (deviceID) {
var q = $q.defer();
ble.disconnect(deviceID, function (result) {
q.resolve(result);
}, function (error) {
q.reject(error);
});
return q.promise;
},
read: function (deviceID, serviceUUID, characteristicUUID) {
var q = $q.defer();
ble.read(deviceID, serviceUUID, characteristicUUID, function (result) {
q.resolve(result);
}, function (error) {
q.reject(error);
});
return q.promise;
},
write: function (deviceID, serviceUUID, characteristicUUID, data) {
var q = $q.defer();
ble.write(deviceID, serviceUUID, characteristicUUID, data, function (result) {
q.resolve(result);
}, function (error) {
q.reject(error);
});
return q.promise;
},
writeCommand: function (deviceID, serviceUUID, characteristicUUID, data) {
var q = $q.defer();
ble.writeCommand(deviceID, serviceUUID, characteristicUUID, data, function (result) {
q.resolve(result);
}, function (error) {
q.reject(error);
});
return q.promise;
},
notify: function (deviceID, serviceUUID, characteristicUUID) {
var q = $q.defer();
ble.notify(deviceID, serviceUUID, characteristicUUID, function (result) {
q.resolve(result);
}, function (error) {
q.reject(error);
});
return q.promise;
},
indicate: function (deviceID, serviceUUID, characteristicUUID) {
var q = $q.defer();
ble.indicate(deviceID, serviceUUID, characteristicUUID, function (result) {
q.resolve(result);
}, function (error) {
q.reject(error);
});
return q.promise;
},
isConnected: function (deviceID) {
var q = $q.defer();
ble.isConnected(deviceID, function (result) {
q.resolve(result);
}, function (error) {
q.reject(error);
});
return q.promise;
},
isEnabled: function () {
var q = $q.defer();
ble.isEnabled(function (result) {
q.resolve(result);
}, function (error) {
q.reject(error);
});
return q.promise;
}
};
}]);
| // install : cordova plugin add https://github.com/don/cordova-plugin-ble-central#:/plugin
// link : https://github.com/don/cordova-plugin-ble-central
angular.module('ngCordova.plugins.ble', [])
.factory('$cordovaBLE', ['$q', function ($q) {
return {
scan: function (services, seconds) {
var q = $q.defer();
ble.scan(services, seconds, function (result) {
q.resolve(result);
}, function (error) {
q.reject(error);
});
return q.promise;
},
connect: function (deviceID) {
var q = $q.defer();
ble.connect(deviceID, function (result) {
q.resolve(result);
}, function (error) {
q.reject(error);
});
return q.promise;
},
disconnect: function (deviceID) {
var q = $q.defer();
ble.disconnect(deviceID, function (result) {
q.resolve(result);
}, function (error) {
q.reject(error);
});
return q.promise;
},
read: function (deviceID, serviceUUID, characteristicUUID) {
var q = $q.defer();
ble.read(deviceID, serviceUUID, characteristicUUID, function (result) {
q.resolve(result);
}, function (error) {
q.reject(error);
});
return q.promise;
},
write: function (deviceID, serviceUUID, characteristicUUID, data) {
var q = $q.defer();
ble.write(deviceID, serviceUUID, characteristicUUID, data, function (result) {
q.resolve(result);
}, function (error) {
q.reject(error);
});
return q.promise;
},
writeCommand: function (deviceID, serviceUUID, characteristicUUID, data) {
var q = $q.defer();
ble.writeCommand(deviceID, serviceUUID, characteristicUUID, data, function (result) {
q.resolve(result);
}, function (error) {
q.reject(error);
});
return q.promise;
},
notify: function (deviceID, serviceUUID, characteristicUUID) {
var q = $q.defer();
ble.notify(deviceID, serviceUUID, characteristicUUID, function (result) {
q.resolve(result);
}, function (error) {
q.reject(error);
});
return q.promise;
},
indicate: function (deviceID, serviceUUID, characteristicUUID) {
var q = $q.defer();
ble.indicate(deviceID, serviceUUID, characteristicUUID, function (result) {
q.resolve(result);
}, function (error) {
q.reject(error);
});
return q.promise;
},
isConnected: function (deviceID) {
var q = $q.defer();
ble.isConnected(deviceID, function (result) {
q.resolve(result);
}, function (error) {
q.reject(error);
});
return q.promise;
},
isEnabled: function () {
var q = $q.defer();
ble.isEnabled(function (result) {
q.resolve(result);
}, function (error) {
q.reject(error);
});
return q.promise;
}
};
}]);
| JavaScript | 0 |
462fa68d7ea0c6eb1bf5e4230c519a1e0be3cf95 | Add a function to ease page creation. | page/index.js | page/index.js | //Dependency
var React = require('react');
var detailMixin = require('./detail').mixin;
//Function to help page creation.
module.exports = {
detail: detailMixin,
search: require('./search'),
/**
* Helper to creates a detail page.
* @param {object} config - The page configtration.
* @returns {object} - The react component associated to the page.
*/
createDetail: function createDetail(config){
config = config || {};
if(config.mixins !== undefined){
config.mixins.push(detailMixin);
} else {
config.mixins = [detailMixin];
}
return React.createClass(config);
}
};
| module.exports = {
detail: require('./detail'),
search: require('./search')
};
| JavaScript | 0 |
ef9ccdded16892d965871416a615c1c2506cae2b | Set the public directory. | lib/index.js | lib/index.js | "use strict";
const BloggifyCore = require("bloggify-core")
, ul = require("ul")
, defaults = require("./defaults")
, Lien = require("lien")
;
/**
* bloggifyServer
* The Bloggify server.
*
* @name bloggifyServer
* @function
* @param {Number} a Param descrpition.
* @param {Number} b Param descrpition.
* @return {Number} Return description.
*/
module.exports = class BloggifyServer extends BloggifyCore {
constructor (options) {
if (typeof options === "string") {
options = { root: options };
}
options = ul.deepMerge(options, defaults);
super(options.root, options);
options.server.public = `${this.paths.root}/${options.server.public}`;
this.server = new Lien(options.server);
this._serverLoaded = false;
this._serverPort = options.server.port;
this.server.on("load", (err, data) => {
this._serverLoaded = [err, data];
});
if (options.loadPlugins !== false) {
this.loadPlugins();
}
let firstRequests = this._firstRequests = [];
this.on("plugins-loaded", () => {
firstRequests._called = true;
firstRequests.forEach(c => c[2]());
});
this.server.router.use(function (req, res, next) {
if (firstRequests._called) {
return next();
}
firstRequests.push([req, res, next]);
});
}
onLoad (cb) {
if (this._serverLoaded) {
return cb(this._serverLoaded[0], this._serverLoaded[1]);
}
this.server.on("load", cb);
}
};
| "use strict";
const BloggifyCore = require("bloggify-core")
, ul = require("ul")
, defaults = require("./defaults")
, Lien = require("lien")
;
/**
* bloggifyServer
* The Bloggify server.
*
* @name bloggifyServer
* @function
* @param {Number} a Param descrpition.
* @param {Number} b Param descrpition.
* @return {Number} Return description.
*/
module.exports = class BloggifyServer extends BloggifyCore {
constructor (options) {
if (typeof options === "string") {
options = { root: options };
}
options = ul.deepMerge(options, defaults);
super(options.root, options);
this.server = new Lien(options.server);
this._serverLoaded = false;
this._serverPort = options.server.port;
this.server.on("load", (err, data) => {
this._serverLoaded = [err, data];
});
if (options.loadPlugins !== false) {
this.loadPlugins();
}
let firstRequests = this._firstRequests = [];
this.on("plugins-loaded", () => {
firstRequests._called = true;
firstRequests.forEach(c => c[2]());
});
this.server.router.use(function (req, res, next) {
if (firstRequests._called) {
return next();
}
firstRequests.push([req, res, next]);
});
}
onLoad (cb) {
if (this._serverLoaded) {
return cb(this._serverLoaded[0], this._serverLoaded[1]);
}
this.server.on("load", cb);
}
};
| JavaScript | 0 |
18f39e6beb8a5461c1689d23bb649e6afee49acc | increase nodejs memory limits | lib/index.js | lib/index.js | #!/bin/sh
':' // ; export MAX_MEM="--max-old-space-size=120"; exec "$(command -v node || command -v nodejs)" "${NODE_OPTIONS:-$MAX_MEM}" "$0" "$@"
/*
* @copyright Copyright (c) Sematext Group, Inc. - All Rights Reserved
*
* @licence SPM Agent for MongoDB is free-to-use, proprietary software.
* THIS IS PROPRIETARY SOURCE CODE OF Sematext Group, Inc. (Sematext)
* This source code may not be copied, reverse engineered, or altered for any purpose.
* This source code is to be used exclusively by users and customers of Sematext.
* Please see the full license (found in LICENSE in this distribution) for details on its license and the licenses of its dependencies.
*/
var SpmAgent = require('spm-agent')
var osAgent = require('spm-agent-os')
var mongoDbAgent = require('./mongodb-agent')
// this requires are here to compile with enclose.js
// var packageJson = require('../package.json')
// var packageJson2 = require('spm-agent/package.json')
var url = require('url')
function MongoDbMonitor () {
var mongoDbUrl = [{url: 'mongodb://localhost:27017/admin'}]
if (SpmAgent.Config.mongodb && SpmAgent.Config.mongodb.url) {
mongoDbUrl = SpmAgent.Config.mongodb.url
} else if (process.env.SPM_MONGODB_URL) {
mongoDbUrl = [{url: process.env.SPM_MONGODB_URL}]
}
if (process.argv.length > 3) {
var parsedUrl = url.parse(process.argv[3])
if (/mongodb/.test(parsedUrl.protocol) && parsedUrl.port !== null) {
mongoDbUrl = [{url: process.argv[3]}]
} else {
console.error('Invalid MongoDB-URL: ' + process.argv[3] + ' using ' + mongoDbUrl)
}
}
var njsAgent = new SpmAgent()
var agentsToLoad = [
mongoDbAgent,
osAgent
]
agentsToLoad.forEach(function (a) {
try {
var Monitor = a
if (a === mongoDbAgent) {
mongoDbUrl.forEach(function (connection) {
var secureUrl = null
if (connection) {
secureUrl = connection.url.replace(/:.*@/i, ' ')
}
SpmAgent.Logger.info('Start Monitor for: ' + secureUrl)
njsAgent.createAgent(new Monitor(connection))
})
} else {
njsAgent.createAgent(new Monitor())
}
} catch (err) {
console.log(err)
SpmAgent.Logger.error('Error loading agent ' + a + ' ' + err)
}
})
return njsAgent
}
var tokens = 0
console.log('SPM Token: ' + SpmAgent.Config.get('tokens.spm'))
if (SpmAgent.Config.get('tokens.spm') || process.env.SPM_TOKEN || process.argv[2] && process.argv[2].length > 30) {
if (process.argv[2] && process.argv[2].length > 30) {
process.env.SPM_TOKEN = process.argv[2]
}
tokens++
MongoDbMonitor()
} else {
console.log('Missing SPM_TOKEN')
}
if (tokens === 0) {
console.log('Please specify the required environment variables: SPM_TOKEN or edit /etc/spmagent/config file')
process.exit(-1)
}
process.on('uncaughtException', function (err) {
console.error((new Date()).toUTCString() + ' uncaughtException:', err.message)
console.error(err.stack)
process.exit(1)
})
| #!/bin/sh
':' // ; export MAX_MEM="--max-old-space-size=60"; exec "$(command -v node || command -v nodejs)" "${NODE_OPTIONS:-$MAX_MEM}" "$0" "$@"
/*
* @copyright Copyright (c) Sematext Group, Inc. - All Rights Reserved
*
* @licence SPM Agent for MongoDB is free-to-use, proprietary software.
* THIS IS PROPRIETARY SOURCE CODE OF Sematext Group, Inc. (Sematext)
* This source code may not be copied, reverse engineered, or altered for any purpose.
* This source code is to be used exclusively by users and customers of Sematext.
* Please see the full license (found in LICENSE in this distribution) for details on its license and the licenses of its dependencies.
*/
var SpmAgent = require('spm-agent')
var osAgent = require('spm-agent-os')
var mongoDbAgent = require('./mongodb-agent')
// this requires are here to compile with enclose.js
// var packageJson = require('../package.json')
// var packageJson2 = require('spm-agent/package.json')
var url = require('url')
function MongoDbMonitor () {
var mongoDbUrl = [{url: 'mongodb://localhost:27017/admin'}]
if (SpmAgent.Config.mongodb && SpmAgent.Config.mongodb.url) {
mongoDbUrl = SpmAgent.Config.mongodb.url
} else if (process.env.SPM_MONGODB_URL) {
mongoDbUrl = [{url: process.env.SPM_MONGODB_URL}]
}
if (process.argv.length > 3) {
var parsedUrl = url.parse(process.argv[3])
if (/mongodb/.test(parsedUrl.protocol) && parsedUrl.port !== null) {
mongoDbUrl = [{url: process.argv[3]}]
} else {
console.error('Invalid MongoDB-URL: ' + process.argv[3] + ' using ' + mongoDbUrl)
}
}
var njsAgent = new SpmAgent()
var agentsToLoad = [
mongoDbAgent,
osAgent
]
agentsToLoad.forEach(function (a) {
try {
var Monitor = a
if (a === mongoDbAgent) {
mongoDbUrl.forEach(function (connection) {
var secureUrl = null
if (connection) {
secureUrl = connection.url.replace(/:.*@/i, ' ')
}
SpmAgent.Logger.info('Start Monitor for: ' + secureUrl)
njsAgent.createAgent(new Monitor(connection))
})
} else {
njsAgent.createAgent(new Monitor())
}
} catch (err) {
console.log(err)
SpmAgent.Logger.error('Error loading agent ' + a + ' ' + err)
}
})
return njsAgent
}
var tokens = 0
console.log('SPM Token: ' + SpmAgent.Config.get('tokens.spm'))
if (SpmAgent.Config.get('tokens.spm') || process.env.SPM_TOKEN || process.argv[2] && process.argv[2].length > 30) {
if (process.argv[2] && process.argv[2].length > 30) {
process.env.SPM_TOKEN = process.argv[2]
}
tokens++
MongoDbMonitor()
} else {
console.log('Missing SPM_TOKEN')
}
if (tokens === 0) {
console.log('Please specify the required environment variables: SPM_TOKEN or edit /etc/spmagent/config file')
process.exit(-1)
}
process.on('uncaughtException', function (err) {
console.error((new Date()).toUTCString() + ' uncaughtException:', err.message)
console.error(err.stack)
process.exit(1)
})
| JavaScript | 0.000001 |
d3c5aa99800a362f0af86e709913beb7015112bd | customize enhancements #2 | module/Customize/public/scripts/zork/customize.js | module/Customize/public/scripts/zork/customize.js | /**
* User interface functionalities
* @package zork
* @subpackage user
* @author David Pozsar <david.pozsar@megaweb.hu>
*/
( function ( global, $, js )
{
"use strict";
if ( typeof js.customize !== "undefined" )
{
return;
}
var customCssSelector = "head link.customize-stylesheet[data-customize]";
/**
* @class Customize module
* @constructor
* @memberOf Zork
*/
global.Zork.Customize = function ()
{
this.version = "1.0";
this.modulePrefix = [ "zork", "customize" ];
};
global.Zork.prototype.customize = new global.Zork.Customize();
global.Zork.Customize.prototype.reload = function ()
{
$( customCssSelector ).each( function () {
var css = $( this ),
id = css.data( "customize" ),
href = js.core.uploadsUrl
+ "/customize/custom." + id + "."
+ Number( new Date() ).toString(36)
+ ".css",
link = $( "<link />" )
.one( "ready load", function () {
css.remove();
} )
.attr( {
"href" : href,
"type" : "text/css",
"rel" : "stylesheet",
"class" : "customize-stylesheet",
"data-customize" : id
} )
.data( "customize", id );
css.removeClass( "customize-stylesheet" );
$( "head" ).append( link );
} );
};
global.Zork.Customize.prototype.properties = function ( element )
{
js.require( "js.ui.dialog" );
element = $( element );
var addButton = $( "<button type='button' />" ).text(
element.data( "jsPropertiesAddLabel" ) ||
js.core.translate( "customize.form.addProperty" )
);
addButton.click( function () {
js.ui.dialog.prompt( {
"message": js.core.translate( "customize.form.addMessage" ),
"input": function ( prop ) {
if ( prop && ( prop = String( prop ).replace( /[^a-zA-Z0-9\-]/, "" ) ) ) {
element
.prepend(
$( "<dd />" )
.append(
$( "<input type='text'>" )
.attr( {
"name": "properties[" + prop + "][value]"
} )
)
.append(
$( "<label />" )
.append(
$( "<input type='checkbox' value='important'>" )
.attr( {
"name": "properties[" + prop + "][priority]"
} )
)
.append( js.core.translate( "customize.form.important" ) )
)
)
.prepend(
$( "<dt />" )
.append(
$( "<label />" )
.attr( "for", "properties[" + prop + "][value]" )
.text( prop )
)
);
}
}
} );
} );
element.before( addButton );
};
global.Zork.Customize.prototype.properties.isElementConstructor = true;
} ( window, jQuery, zork ) );
| /**
* User interface functionalities
* @package zork
* @subpackage user
* @author David Pozsar <david.pozsar@megaweb.hu>
*/
( function ( global, $, js )
{
"use strict";
if ( typeof js.customize !== "undefined" )
{
return;
}
var customCssSelector = "head link.customize-stylesheet[data-customize]";
/**
* @class Customize module
* @constructor
* @memberOf Zork
*/
global.Zork.Customize = function ()
{
this.version = "1.0";
this.modulePrefix = [ "zork", "customize" ];
};
global.Zork.prototype.customize = new global.Zork.Customize();
global.Zork.Customize.prototype.reload = function ()
{
$( customCssSelector ).each( function () {
var css = $( this ),
id = css.data( "customize" ),
href = js.core.uploadsUrl
+ "/customize/custom." + id + "."
+ Number( new Date() ).toString(36)
+ ".css",
link = $( "<link />" )
.one( "ready load", function () {
css.remove();
} )
.attr( {
"href" : href,
"type" : "text/css",
"rel" : "stylesheet"
} );
css.removeClass( "customize-stylesheet" );
$( "head" ).append( link );
} );
};
global.Zork.Customize.prototype.properties = function ( element )
{
js.require( "js.ui.dialog" );
element = $( element );
var addButton = $( "<button type='button' />" ).text(
element.data( "jsPropertiesAddLabel" ) ||
js.core.translate( "customize.form.addProperty" )
);
addButton.click( function () {
js.ui.dialog.prompt( {
"message": js.core.translate( "customize.form.addMessage" ),
"input": function ( prop ) {
if ( prop && ( prop = String( prop ).replace( /[^a-zA-Z0-9\-]/, "" ) ) ) {
element
.prepend(
$( "<dd />" )
.append(
$( "<input type='text'>" )
.attr( {
"name": "properties[" + prop + "][value]"
} )
)
.append(
$( "<label />" )
.append(
$( "<input type='checkbox' value='important'>" )
.attr( {
"name": "properties[" + prop + "][priority]"
} )
)
.append( js.core.translate( "customize.form.important" ) )
)
)
.prepend(
$( "<dt />" )
.append(
$( "<label />" )
.attr( "for", "properties[" + prop + "][value]" )
.text( prop )
)
);
}
}
} );
} );
element.before( addButton );
};
global.Zork.Customize.prototype.properties.isElementConstructor = true;
} ( window, jQuery, zork ) );
| JavaScript | 0 |
809ddd475e59b6bc08dc60342d482e8a78b86290 | Add comment | lib/index.js | lib/index.js | 'use strict';
var transform = require('babel-core').transform;
var MagicString = require('magic-string');
var traverse = require('babel-traverse')['default'];
var PersistentFilter = require('broccoli-persistent-filter');
function LazyCode(node, options) {
PersistentFilter.call(this, node, options);
}
LazyCode.prototype = Object.create(PersistentFilter.prototype);
LazyCode.prototype.constructor = LazyCode;
LazyCode.prototype.extensions = ['js'];
LazyCode.prototype.targetExtension = 'js';
LazyCode.prototype.processString = function (content) {
var ast = transform(content).ast;
var positions = [];
var s = new MagicString(content);
traverse(ast, {
enter: function(path) {
if (path.node.type === 'CallExpression') {
if (path.node.callee.name === 'define') {
var start = path.node.arguments[2].body.body[0].start;
var end = path.node.arguments[2].body.body[path.node.arguments[2].body.body.length - 1].end;
// TODO make this generic
// Ember CLI is making assumptions on evaluation being in the
// module body. The environment has a try/catch return which
// requires an outer scope
if (path.node.arguments[0].value === 'dummy/config/environment') {
positions.push([start, end, true]);
} else {
positions.push([start, end]);
}
}
}
}
});
positions.forEach(function(cords) {
var content = s.snip(cords[0], cords[1]).toString();
content = content.split('\n').map(function(piece) {
return piece.trim();
}).join('').replace(/"/g, '\\"');
s.overwrite(cords[0], cords[1], content);
if (cords.length > 2) {
s.insert(cords[0], 'eval("(function() {');
s.insert(cords[0], '})()");');
} else {
s.insert(cords[0], 'eval("');
s.insert(cords[1], '");');
}
});
return s.toString();
};
module.exports = LazyCode;
| 'use strict';
var transform = require('babel-core').transform;
var MagicString = require('magic-string');
var traverse = require('babel-traverse')['default'];
var PersistentFilter = require('broccoli-persistent-filter');
function LazyCode(node, options) {
PersistentFilter.call(this, node, options);
}
LazyCode.prototype = Object.create(PersistentFilter.prototype);
LazyCode.prototype.constructor = LazyCode;
LazyCode.prototype.extensions = ['js'];
LazyCode.prototype.targetExtension = 'js';
LazyCode.prototype.processString = function (content) {
var ast = transform(content).ast;
var positions = [];
var s = new MagicString(content);
traverse(ast, {
enter: function(path) {
if (path.node.type === 'CallExpression') {
if (path.node.callee.name === 'define') {
var start = path.node.arguments[2].body.body[0].start;
var end = path.node.arguments[2].body.body[path.node.arguments[2].body.body.length - 1].end;
if (path.node.arguments[0].value === 'dummy/config/environment') {
positions.push([start, end, true]);
} else {
positions.push([start, end]);
}
}
}
}
});
positions.forEach(function(cords) {
var content = s.snip(cords[0], cords[1]).toString();
content = content.split('\n').map(function(piece) {
return piece.trim();
}).join('').replace(/"/g, '\\"');
s.overwrite(cords[0], cords[1], content);
if (cords.length > 2) {
s.insert(cords[0], 'eval("(function() {');
s.insert(cords[0], '})()");');
} else {
s.insert(cords[0], 'eval("');
s.insert(cords[1], '");');
}
});
return s.toString();
};
module.exports = LazyCode;
| JavaScript | 0 |
aed045646fa7f33f4ac1e657c2e0b04326b11b3f | Fix non camelCase identifiers | lib/node/column-namer.js | lib/node/column-namer.js | 'use strict';
function stripTtableName(name) {
return name.split('.').pop();
}
// This class is used to help generate the names of node query columns
module.exports = class ColumnNamer {
constructor (columns) {
this.columns = columns.map(name => stripTtableName(name));
}
uniqueName(baseName) {
var name = baseName;
var ok = this.isUnique(name);
if (!ok) {
// try adding a numeric suffix
var count = 1;
while (!ok) {
name = baseName + '_' + (++count);
ok = this.isUnique(name);
}
}
this.columns.push(name); // ?
return name;
}
isUnique(name) {
// TODO: should this be case-insensitive?
return !this.columns.includes(name);
}
};
| 'use strict';
function strip_table_name(name) {
return name.split('.').pop();
}
// This class is used to help generate the names of node query columns
module.exports = class ColumnNamer {
constructor (columns) {
this.columns = columns.map(name => strip_table_name(name));
}
uniqueName(baseName) {
var name = baseName;
var ok = this.isUnique(name);
if (!ok) {
// try adding a numeric suffix
var count = 1;
while (!ok) {
name = baseName + '_' + (++count);
ok = this.isUnique(name);
}
}
this.columns.push(name); // ?
return name;
}
isUnique(name) {
// TODO: should this be case-insensitive?
return !this.columns.includes(name);
}
};
| JavaScript | 0.999999 |
5fe32b5cb0ff7d66db112171af86583a4f6cd7aa | Replace double backslash in file paths on Windows with single forward slash, fixes #5 | lib/index.js | lib/index.js | var through = require("through");
var path = require("path");
console.warn("Injecting Rewireify into modules");
module.exports = function rewireify(file, options) {
options = {
ignore: options.ignore || ""
};
var ignore = ["__get__", "__set__", "rewire"].concat(options.ignore.split(","));
if (/\.json$/.test(file) || ignore.indexOf(path.basename(file, ".js")) > -1) {
return through();
}
var data = "";
var post = "";
function write(buffer) {
data += buffer;
}
function pathTo(file) {
var relpath = __dirname;
if (path.sep == "\\") {
relpath = relpath.replace(/\\/g, "/");
}
return path.join(relpath, file);
}
function end() {
post += "/* This code was injected by Rewireify */\n";
post += "var __getter = require(\"" + pathTo("__get__") + "\").toString();\n";
post += "var __setter = require(\"" + pathTo("__set__") + "\").toString();\n";
post += "\n";
post += "eval(__getter);\n"
post += "eval(__setter);\n"
post += "module.exports.__get__ = __get__;\n";
post += "module.exports.__set__ = __set__;\n";
this.queue(data);
this.queue(post);
this.queue(null);
}
return through(write, end);
};
| var through = require("through");
var path = require("path");
console.warn("Injecting Rewireify into modules");
module.exports = function rewireify(file, options) {
options = {
ignore: options.ignore || ""
};
var ignore = ["__get__", "__set__", "rewire"].concat(options.ignore.split(","));
if (/\.json$/.test(file) || ignore.indexOf(path.basename(file, ".js")) > -1) {
return through();
}
var data = "";
var post = "";
function write(buffer) {
data += buffer;
}
function end() {
post += "/* This code was injected by Rewireify */\n";
post += "var __getter = require(\"" + path.join(__dirname, "__get__") + "\").toString();\n";
post += "var __setter = require(\"" + path.join(__dirname, "__set__") + "\").toString();\n";
post += "\n";
post += "eval(__getter);\n"
post += "eval(__setter);\n"
post += "module.exports.__get__ = __get__;\n";
post += "module.exports.__set__ = __set__;\n";
this.queue(data);
this.queue(post);
this.queue(null);
}
return through(write, end);
};
| JavaScript | 0 |
482904105748551fa859fcda702baae33d33fe80 | Fix typo | lib/passport-yj/index.js | lib/passport-yj/index.js | /*
* Module dependencies
*/
var Strategy = require('./strategy');
/*
* Framework version
*/
require('pkginfo')(module, 'version');
/*
* Expose constructors
*/
exports.YJStrategy = Strategy;
| /*
* Module dependencies
*/
var Strategy = require('./strategy');
/*
* Framework version
*/
require('pgkinfo')(module, 'version');
/*
* Expose constructors
*/
exports.YJStrategy = Strategy;
| JavaScript | 0.999999 |
7e7261f0ef2e1044775eec2824a863b3b77966c2 | change public api | lib/index.js | lib/index.js | var esprima = require('esprima');
var fs = require('fs');
var skip = /^\s+\*/gm;
var mapName = function(elm){
return elm.name;
};
var findReturns = function(expr){
var returns = []
expr.body.forEach(function(expr){
if(expr.type === 'ReturnStatement'){
if(expr.argument.type === 'Literal'){
returns.push(expr.argument.value);
} else if(expr.argument.type === 'ObjectExpression'){
returns.push('Object');
} else if(expr.argument.type === 'ArrayExpression'){
returns.push('Array');
} else if(expr.argument.type === 'FunctionExpression'){
returns.push('Function');
}
}
});
return returns;
};
var findRaises = function(expr){
var raises = []
expr.body.forEach(function(expr){
if(expr.type === 'ThrowStatement'){
if(expr.argument.type === 'NewExpression'){
raises.push(expr.argument.callee.name);
}
}
});
return raises;
};
var parseExpressions = function(expr){
var expressions = {};
var _parse = function(expr){
if(!expr){
return;
} else if(expr.length && typeof expr.forEach === 'function'){
return expr.forEach(_parse);
}
if(expr.type === 'FunctionExpression'){
expressions[expr.loc.start.line] = {
name: expr.id,
params: expr.params.map(mapName),
returns: findReturns(expr.body),
raises: findRaises(expr.body),
};
_parse(expr.body);
} else if(expr.type === 'FunctionDeclaration'){
expressions[expr.loc.start.line] = {
name: expr.id.name,
params: expr.params.map(mapName),
returns: findReturns(expr.body),
raises: findRaises(expr.body),
};
_parse(expr.body);
} else if(expr.type === 'AssignmentExpression' && expr.right.type === 'FunctionExpression'){
var data = {};
if(expr.left.type === 'MemberExpression'){
data.name = expr.left.property.name;
if(expr.left.object.type === 'MemberExpression'){
if(expr.left.object.property.name === 'prototype'){
data.class = expr.left.object.object.name;
}
}
}
if(expr.right.type === 'FunctionExpression'){
data.params = expr.right.params.map(mapName);
data.returns = findReturns(expr.right.body);
data.raises = findRaises(expr.right.body);
}
expressions[expr.loc.start.line] = data;
} else if(expr.type === 'VariableDeclarator' && expr.init.type === 'FunctionExpression'){
expressions[expr.loc.start.line] = {
name: expr.id.name,
params: expr.init.params.map(mapName),
returns: findReturns(expr.init.body),
raises: findRaises(expr.init.body),
};
} else {
_parse(expr.expression || expr.callee || expr.body || expr.declarations);
}
};
_parse(expr);
return expressions;
};
module.exports.parseFile = function(filename, options){
return module.exports.parseContents(fs.readFileSync(filename, 'utf-8'), options);
};
module.exports.parseContents = function(contents, options){
options = options || {};
var tolerant = (options.tolerant === undefined)? true: options.tolerant;
var parsed = esprima.parse(contents, {comment: true, loc: true, tolerant: tolerant});
var expressions = parseExpressions(parsed);
var results = [];
parsed.comments.forEach(function(comment){
if(comment.type === 'Block'){
var body = comment.value;
body = body.replace(skip, '');
results.push({
doc: body,
data: expressions[comment.loc.end.line + 1],
});
}
});
return results;
};
module.exports.parse = module.exports.parseFile;
| var esprima = require('esprima');
var fs = require('fs');
var skip = /^\s+\*/gm;
var mapName = function(elm){
return elm.name;
};
var findReturns = function(expr){
var returns = []
expr.body.forEach(function(expr){
if(expr.type === 'ReturnStatement'){
if(expr.argument.type === 'Literal'){
returns.push(expr.argument.value);
} else if(expr.argument.type === 'ObjectExpression'){
returns.push('Object');
} else if(expr.argument.type === 'ArrayExpression'){
returns.push('Array');
} else if(expr.argument.type === 'FunctionExpression'){
returns.push('Function');
}
}
});
return returns;
};
var findRaises = function(expr){
var raises = []
expr.body.forEach(function(expr){
if(expr.type === 'ThrowStatement'){
if(expr.argument.type === 'NewExpression'){
raises.push(expr.argument.callee.name);
}
}
});
return raises;
};
var parseExpressions = function(expr){
var expressions = {};
var _parse = function(expr){
if(!expr){
return;
} else if(expr.length && typeof expr.forEach === 'function'){
return expr.forEach(_parse);
}
if(expr.type === 'FunctionExpression'){
expressions[expr.loc.start.line] = {
name: expr.id,
params: expr.params.map(mapName),
returns: findReturns(expr.body),
raises: findRaises(expr.body),
};
_parse(expr.body);
} else if(expr.type === 'FunctionDeclaration'){
expressions[expr.loc.start.line] = {
name: expr.id.name,
params: expr.params.map(mapName),
returns: findReturns(expr.body),
raises: findRaises(expr.body),
};
_parse(expr.body);
} else if(expr.type === 'AssignmentExpression' && expr.right.type === 'FunctionExpression'){
var data = {};
if(expr.left.type === 'MemberExpression'){
data.name = expr.left.property.name;
if(expr.left.object.type === 'MemberExpression'){
if(expr.left.object.property.name === 'prototype'){
data.class = expr.left.object.object.name;
}
}
}
if(expr.right.type === 'FunctionExpression'){
data.params = expr.right.params.map(mapName);
data.returns = findReturns(expr.right.body);
data.raises = findRaises(expr.right.body);
}
expressions[expr.loc.start.line] = data;
} else if(expr.type === 'VariableDeclarator' && expr.init.type === 'FunctionExpression'){
expressions[expr.loc.start.line] = {
name: expr.id.name,
params: expr.init.params.map(mapName),
returns: findReturns(expr.init.body),
raises: findRaises(expr.init.body),
};
} else {
_parse(expr.expression || expr.callee || expr.body || expr.declarations);
}
};
_parse(expr);
return expressions;
};
module.exports.parseDataFile = function(filename, options){
return module.exports.parseData(fs.readFileSync(filename, 'utf-8'), options);
};
module.exports.parseData = function(contents, options){
options = options || {};
var tolerant = (options.tolerant === undefined)? true: options.tolerant;
var parsed = esprima.parse(contents, {comment: true, loc: true, tolerant: tolerant});
var expressions = parseExpressions(parsed);
var results = [];
parsed.comments.forEach(function(comment){
if(comment.type === 'Block'){
var body = comment.value;
body = body.replace(skip, '');
results.push({
doc: body,
data: expressions[comment.loc.end.line + 1],
});
}
});
return results;
};
| JavaScript | 0 |
b593b0434d39420196ab742beb7137eb336ccced | Fix casing | source/static/scripts.js | source/static/scripts.js | // Piwik/Matomo
var _paq = _paq || [];
_paq.push(["setDocumentTitle", document.domain + "/" + document.title]);
_paq.push(["setCookieDomain", "*.openfisca.org"]);
_paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);
(function() {
var u="//stats.data.gouv.fr/";
_paq.push(['setTrackerUrl', u+'piwik.php']);
_paq.push(['setSiteId', '4']);
var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
})();
function getPathName() {
if (location.pathname.startsWith('/doc/')) { // Very ugly. Triggered when the doc is hosted under the /doc/ subdomain. A proper configuration system would be preferable.
return '/doc';
}
return '';
}
$(document).ready(function() {
$('a[href^="https://"], a[href^="http://"]').attr("target", "_blank"); // Make all external links open in a new window
// Activate action button tooltip
$('.actionbutton').tooltip()
});
| // Piwik/Matomo
var _paq = _paq || [];
_paq.push(["setDocumentTitle", document.domain + "/" + document.title]);
_paq.push(["setCookieDomain", "*.openfisca.org"]);
_paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);
(function() {
var u="//stats.data.gouv.fr/";
_paq.push(['setTrackerUrl', u+'piwik.php']);
_paq.push(['setSiteId', '4']);
var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
})();
function getPathName() {
if (location.pathname.startsWith('/doc/')) { // Very ugly. Triggered when the doc is hosted under the /doc/ subdomain. A proper configuration system would be preferable.
return '/doc';
}
return '';
}
$(document).ready(function() {
$('a[href^="https://"], a[href^="http://"]').attr("target", "_blank"); // Make all external links open in a new Window
// Activate action button tooltip
$('.actionbutton').tooltip()
});
| JavaScript | 0.000002 |
ae8b3a33c1cb288ba476c1155f94184c9f108f23 | Add suit selection | public/js/index.js | public/js/index.js | var suits = ['clubs', 'spades', 'diamonds', 'hearts'];
$('#simulate').click(function () {
boardData = {
table: { flop: ['ah', 'td', 'jh'] },
hands: [['ac', 'jd'], ['90%']]
};
submitData(boardData, function(data){
$('#output').append($('<pre>').text(JSON.stringify(data, null, ' ')));
});
});
$('#cardPicker').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget); // Button that triggered the modal
var playerId = button.attr('data-playerId');
var numCards = button.attr('data-numCards');
console.log(playerId);
console.log(numCards);
var $modal = $(this);
$('#selection-title #currCard', this).text(numCards);
$('#selection-title #numCards', this).text(numCards);
$modal.data("playerId",playerId);
<!-- TODO: implement num cards functionality -->
});
$("#saveCards").click(function() {
console.log("Saving changes for player id: " + $("#cardPicker").data("playerId"));
});
$(window).load(function() {
$('#liteAccordion').liteAccordion({
containerWidth: 700,
containerHeight: 500
});
});
/*
* Modal suit pickers:
*/
/*
* When you click on a suit image, it will display the cards associated with the suit and hide the old display.
*/
(function () {
var suitDisplayed = suits[0]; // init
function getCardDisplay(suit) {
return $('#card-selection-' + suit.toLowerCase());
}
suits.forEach(function (suit) {
$('.suit-select #suit-' + suit).click(function () {
getCardDisplay(suitDisplayed).hide();
getCardDisplay(suit).show();
suitDisplayed = suit;
});
});
$('.suit-select #suit-' + suitDisplayed).click();
})();
| $('#simulate').click(function () {
boardData = {
table: { flop: ['ah', 'td', 'jh'] },
hands: [['ac', 'jd'], ['90%']]
};
submitData(boardData, function(data){
$('#output').append($('<pre>').text(JSON.stringify(data, null, ' ')));
});
});
$('#cardPicker').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget); // Button that triggered the modal
var playerId = button.attr('data-playerId');
var numCards = button.attr('data-numCards');
console.log(playerId);
console.log(numCards);
var $modal = $(this);
$('#selection-title #currCard', this).text(numCards);
$('#selection-title #numCards', this).text(numCards);
$modal.data("playerId",playerId);
<!-- TODO: implement num cards functionality -->
});
$("#saveCards").click(function() {
console.log("Saving changes for player id: " + $("#cardPicker").data("playerId"));
});
$(window).load(function() {
$('#liteAccordion').liteAccordion({
containerWidth: 700,
containerHeight: 500
});
});
| JavaScript | 0 |
55fc827b45bcee19b29bd1f732d6978632f43030 | Add alert command | lib/index.js | lib/index.js | define(['require', 'exports', './terminal', './env', './fs/index'], function(require, exports, terminal, env, fs) {
var Terminal = exports.Terminal = terminal.Terminal;
var Environment = exports.Environment = env.Environment;
var Filesystem = exports.Filesystem = fs.Filesystem;
exports.Machine = (function() {
function Machine(name) {
this.name = name;
var fsData;
// try {
// fsData = JSON.parse(localStorage.machines)[name];
// } catch(e) {
fsData = {
root: {
files: {
bin: {
files: {
echo: {
executable: true,
command: {
exec: function(args, context) {
context.view.stream.write(args.join(' '));
context.data.write(args.join(' '));
}
}
},
pwd: {
executable: true,
command: {
exec: function(args, context) {
context.view.stream.write(context.fs.pathTo(context.currentDir));
context.data.write(context.fs.pathTo(context.currentDir));
}
}
},
ls: {
executable: true,
command: {
exec: function(args, context) {
var files = context.fs.listFiles(context.fs.getFile(args[0], context.currentDir));
files.forEach(function(file) {
context.view.stream.write(file.name);
});
}
}
},
cd: {
executable: true,
command: {
exec: function(args, context) {
context.currentDir = context.fs.getFile(args[0], context.currentDir) || context.currentDir;
}
}
},
alert: {
executable: true,
command: {
exec: function(args, context) {
if(args.length > 0 && args[0]) alert(args.join(' '));
context.data.on('data', function(d) {
alert(d);
});
}
}
},
test: {
executable: true,
command: {
exec: function(args, context) {
console.log(arguments);
context.data.on('data', function(d) {
alert('someone sent me: ' + d);
});
}
}
}
}
}
}
}
};
// }
this.fs = new Filesystem(fsData);
this.env = new Environment({
vars: {
PATH: "/bin"
}
}, this.fs);
/*try {
var machines = JSON.parse(localStorage.machines);
} catch(e) {
var machines = {};
}
machines[this.name] = this.fs.data;
localStorage.machines = JSON.stringify(machines);*/
}
Machine.prototype.createTerminal = function createTerminal(view) {
return new Terminal(this, view);
};
return Machine;
})();
});
| define(['require', 'exports', './terminal', './env', './fs/index'], function(require, exports, terminal, env, fs) {
var Terminal = exports.Terminal = terminal.Terminal;
var Environment = exports.Environment = env.Environment;
var Filesystem = exports.Filesystem = fs.Filesystem;
exports.Machine = (function() {
function Machine(name) {
this.name = name;
var fsData;
// try {
// fsData = JSON.parse(localStorage.machines)[name];
// } catch(e) {
fsData = {
root: {
files: {
bin: {
files: {
echo: {
executable: true,
command: {
exec: function(args, context) {
context.view.stream.write(args.join(' '));
context.data.write(args.join(' '));
}
}
},
pwd: {
executable: true,
command: {
exec: function(args, context) {
context.view.stream.write(context.fs.pathTo(context.currentDir));
context.data.write(context.fs.pathTo(context.currentDir));
}
}
},
ls: {
executable: true,
command: {
exec: function(args, context) {
var files = context.fs.listFiles(context.fs.getFile(args[0], context.currentDir));
files.forEach(function(file) {
context.view.stream.write(file.name);
});
}
}
},
cd: {
executable: true,
command: {
exec: function(args, context) {
context.currentDir = context.fs.getFile(args[0], context.currentDir) || context.currentDir;
}
}
},
test: {
executable: true,
command: {
exec: function(args, context) {
console.log(arguments);
context.data.on('data', function(d) {
alert('someone sent me: ' + d);
});
}
}
}
}
}
}
}
};
// }
this.fs = new Filesystem(fsData);
this.env = new Environment({
vars: {
PATH: "/bin"
}
}, this.fs);
/*try {
var machines = JSON.parse(localStorage.machines);
} catch(e) {
var machines = {};
}
machines[this.name] = this.fs.data;
localStorage.machines = JSON.stringify(machines);*/
}
Machine.prototype.createTerminal = function createTerminal(view) {
return new Terminal(this, view);
};
return Machine;
})();
});
| JavaScript | 0.000026 |
d81ddccf6f38c9e8e7545d8fd892faa37bc6eeb5 | Update Invitation Service's updateInvitation method to return the result | lib/invitations.js | lib/invitations.js | var async = require('async'),
crypto = require('crypto'),
pg = require('pg'),
config = require('../config'),
INVITATIONS = 'SELECT * FROM invitations ORDER BY id',
INVITATION_BY_ID = 'SELECT * FROM invitations WHERE id=$1 LIMIT 1',
INVITATION_GUESTS = 'SELECT * FROM guests WHERE invitation_id=$1',
UPDATE_INVITATION = 'UPDATE invitations SET rsvp=true WHERE id=$1';
exports.encipherId = function (id) {
var cipher = crypto.createCipher('bf', config.secrets.invitation);
cipher.update(String(id), 'utf8', 'hex');
return cipher.final('hex');
};
exports.decipherId = function (encipheredId) {
var decipher = crypto.createDecipher('bf', config.secrets.invitation);
decipher.update(encipheredId, 'hex', 'utf8');
return decipher.final('utf8');
};
exports.loadInvitation = function (id, callback) {
function processResults(results, callback) {
var invitation = results.invitation.rows[0];
if (invitation) {
invitation.guests = results.guests.rows;
}
callback(null, invitation);
}
pg.connect(config.database, function (err, db, done) {
if (err) { return callback(err); }
async.waterfall([
async.parallel.bind(null, {
invitation: db.query.bind(db, INVITATION_BY_ID, [id]),
guests : db.query.bind(db, INVITATION_GUESTS, [id])
}),
processResults
], function () {
done();
callback.apply(null, arguments);
});
});
};
exports.loadInvitations = function (callback) {
function processInvitation(db, invitation, callback) {
db.query(INVITATION_GUESTS, [invitation.id], function (err, results) {
if (err) { return callback(err); }
invitation.guests = results.rows;
callback(null, invitation);
});
}
function processInvitations(db, results, callback) {
async.map(results.rows, processInvitation.bind(null, db), callback);
}
pg.connect(config.database, function (err, db, done) {
if (err) { return callback(err); }
async.waterfall([
db.query.bind(db, INVITATIONS),
processInvitations.bind(null, db)
], function () {
done();
callback.apply(null, arguments);
});
});
};
exports.updateInvitation = function (id, changes, callback) {
pg.connect(config.database, function (err, db, done) {
if (err) { return callback(err); }
db.query(UPDATE_INVITATION, [id], function (err, results) {
done();
callback(err, results && results.rows[0]);
});
});
};
| var async = require('async'),
crypto = require('crypto'),
pg = require('pg'),
config = require('../config'),
INVITATIONS = 'SELECT * FROM invitations ORDER BY id',
INVITATION_BY_ID = 'SELECT * FROM invitations WHERE id=$1 LIMIT 1',
INVITATION_GUESTS = 'SELECT * FROM guests WHERE invitation_id=$1',
UPDATE_INVITATION = 'UPDATE invitations SET rsvp=true WHERE id=$1';
exports.encipherId = function (id) {
var cipher = crypto.createCipher('bf', config.secrets.invitation);
cipher.update(String(id), 'utf8', 'hex');
return cipher.final('hex');
};
exports.decipherId = function (encipheredId) {
var decipher = crypto.createDecipher('bf', config.secrets.invitation);
decipher.update(encipheredId, 'hex', 'utf8');
return decipher.final('utf8');
};
exports.loadInvitation = function (id, callback) {
function processResults(results, callback) {
var invitation = results.invitation.rows[0];
if (invitation) {
invitation.guests = results.guests.rows;
}
callback(null, invitation);
}
pg.connect(config.database, function (err, db, done) {
if (err) { return callback(err); }
async.waterfall([
async.parallel.bind(null, {
invitation: db.query.bind(db, INVITATION_BY_ID, [id]),
guests : db.query.bind(db, INVITATION_GUESTS, [id])
}),
processResults
], function () {
done();
callback.apply(null, arguments);
});
});
};
exports.loadInvitations = function (callback) {
function processInvitation(db, invitation, callback) {
db.query(INVITATION_GUESTS, [invitation.id], function (err, results) {
if (err) { return callback(err); }
invitation.guests = results.rows;
callback(null, invitation);
});
}
function processInvitations(db, results, callback) {
async.map(results.rows, processInvitation.bind(null, db), callback);
}
pg.connect(config.database, function (err, db, done) {
if (err) { return callback(err); }
async.waterfall([
db.query.bind(db, INVITATIONS),
processInvitations.bind(null, db)
], function () {
done();
callback.apply(null, arguments);
});
});
};
exports.updateInvitation = function (id, changes, callback) {
pg.connect(config.database, function (err, db, done) {
if (err) { return callback(err); }
db.query(UPDATE_INVITATION, [id], function () {
done();
callback.apply(null, arguments);
});
});
};
| JavaScript | 0 |
61484366a210e78d3e4fe0fa81ebea628d8c4054 | Fix export to work with imcomplete data | server/program-export.js | server/program-export.js | const _ = require('lodash')
const moment = require('moment')
const excelWriter = require('./excel-writer')
const fs = require('fs')
const enums = require('../shared/enums')
const utils = require('../shared/utils')
var dateFormat = 'DD.MM.YYYY'
exports.constructProgramExportData = function constructProgramExportData(docs, showClassificationAuthor) {
return createData(docs, showClassificationAuthor)
}
function createData(docs, showClassificationAuthor) {
var tmpXlsxFile = "kavi_luokittelut.xlsx"
var columns = ["Alkuperäinen nimi", "Suomenkielinen nimi", "Jakso", "Jakson nimi", "Rekisteröintipäivä", "Kesto", "Luokittelun tilaaja", "Luokittelija", "Uudelleenluokittelija", "Ikäraja", "Kriteerit", "Perustelu", "Varoitukset", "Ohjelman tyyppi", "Maa", "Valmistumisvuosi", "Ohjaaja", "Tuotantoyhtiö", "Synopsis"]
columnWidths = [{"wch":40},{"wch":40},{"wch":10},{"wch":40},{"wch":15},{"wch":10},{"wch":40},{"wch":25},{"wch":25},{"wch":10},{"wch":40},{"wch":20},{"wch":20},{"wch":20},{"wch":10},{"wch":15},{"wch":20},{"wch":20},{"wch":40}]
var xlsData = []
xlsData.push(columns)
_.forEach(docs, function (doc) {
var name = listToString(doc.name)
var classification = doc.classification && doc.classification[0] ? doc.classification[0] : {}
doc.originalName = enums.util.isTvEpisode(doc) ? (doc.series || {}).name : name
doc.format = classification.format
doc.duration = enums.util.isGameType(doc) ? "" :classification.duration
doc.classificationBuyer = classification.buyer ? doc.classifications[0].buyer.name : ""
doc.classificationAuthor = classification.author && showClassificationAuthor ? doc.classifications[0].author.name : ""
doc.agelimit = classification.agelimit
doc.warnings = classification.warnings ? doc.classifications[0].warnings.join(', ') : ""
doc.criteriaComments = classification.isReclassification ? _.values(classification.criteriaComments).listToString(', ') : ""
doc.criteria = classification.criteria
doc.episodeCode = enums.util.isTvEpisode(doc) ? utils.seasonEpisodeCode(doc) : ""
doc.episodeName = enums.util.isTvEpisode(doc) ? name : ""
doc.reclassifier = classification.isReclassification && classification.authorOrganization ? enums.authorOrganization[classification.authorOrganization] : ""
doc.registrationDate = classification.registrationDate ? moment(classification.registrationDate).format(dateFormat) : ""
xlsData.push([doc.originalName, listToString(doc.nameFi), doc.episodeCode, doc.episodeName, doc.registrationDate, doc.duration, doc.classificationBuyer, doc.classificationAuthor, doc.reclassifier, doc.agelimit, doc.criteria, doc.criteriaComments, doc.warnings, enums.programType[doc.programType].fi, listToString(doc.country), doc.year, listToString(doc.directors), listToString(doc.productionCompanies), doc.synopsis])
function listToString(list) {
return (list || []).join(', ')
}
})
excelWriter.write(tmpXlsxFile, xlsData, columnWidths)
var fileData = fs.readFileSync(tmpXlsxFile)
fs.unlinkSync(tmpXlsxFile)
return fileData
} | const _ = require('lodash')
const moment = require('moment')
const excelWriter = require('./excel-writer')
const fs = require('fs')
const enums = require('../shared/enums')
const utils = require('../shared/utils')
var dateFormat = 'DD.MM.YYYY'
exports.constructProgramExportData = function constructProgramExportData(docs, showClassificationAuthor) {
return createData(docs, showClassificationAuthor)
}
function createData(docs, showClassificationAuthor) {
var tmpXlsxFile = "kavi_luokittelut.xlsx"
var columns = ["Alkuperäinen nimi", "Suomenkielinen nimi", "Jakso", "Jakson nimi", "Rekisteröintipäivä", "Kesto", "Luokittelun tilaaja", "Luokittelija", "Uudelleenluokittelija", "Ikäraja", "Kriteerit", "Perustelu", "Varoitukset", "Ohjelman tyyppi", "Maa", "Valmistumisvuosi", "Ohjaaja", "Tuotantoyhtiö", "Synopsis"]
columnWidths = [{"wch":40},{"wch":40},{"wch":10},{"wch":40},{"wch":15},{"wch":10},{"wch":40},{"wch":25},{"wch":25},{"wch":10},{"wch":40},{"wch":20},{"wch":20},{"wch":20},{"wch":10},{"wch":15},{"wch":20},{"wch":20},{"wch":40}]
var xlsData = []
xlsData.push(columns)
_.forEach(docs, function(doc){
doc.originalName = doc.programType === 3 ? doc.series.name : doc.name.join(', ')
doc.format = doc.classifications[0] === undefined ? "" : doc.classifications[0].format
doc.duration = doc.classifications[0] === undefined || enums.util.isGameType(doc) ? "" : doc.classifications[0].duration
doc.classificationBuyer = doc.classifications[0] === undefined ? "" : doc.classifications[0].buyer === undefined ? "" : doc.classifications[0].buyer.name
doc.classificationAuthor = doc.classifications[0] === undefined ? "" : doc.classifications[0].author === undefined ? "" : showClassificationAuthor ? doc.classifications[0].author.name : ""
doc.agelimit = doc.classifications[0] === undefined ? "" : doc.classifications[0].agelimit === undefined ? "" : doc.classifications[0].agelimit
doc.warnings = doc.classifications[0] === undefined ? "" : doc.classifications[0].warnings === undefined ? "" : doc.classifications[0].warnings.join(', ')
doc.criteriaComments = doc.classifications[0] === undefined ? "" : doc.classifications[0].isReclassification ? _.values(doc.classifications[0].criteriaComments).join(', ') : ""
doc.criteria = doc.classifications[0] === undefined ? "" : doc.classifications[0].criteria === undefined ? "" : doc.classifications[0].criteria
doc.episodeCode = doc.programType === 3 ? utils.seasonEpisodeCode(doc) : ""
doc.episodeName = doc.programType === 3 ? doc.name.join(', ') : ""
doc.reclassifier = doc.classifications[0] === undefined ? "" : doc.classifications[0].isReclassification ? doc.classifications[0].authorOrganization === undefined ? "" : enums.authorOrganization[doc.classifications[0].authorOrganization] : ""
xlsData.push([doc.originalName, doc.nameFi.join(', '), doc.episodeCode, doc.episodeName, moment(doc.classifications[0].registrationDate).format(dateFormat), doc.duration, doc.classificationBuyer, doc.classificationAuthor, doc.reclassifier, doc.agelimit, doc.criteria, doc.criteriaComments, doc.warnings, enums.programType[doc.programType].fi, doc.country.join(', '), doc.year, doc.directors.join(', '), doc.productionCompanies.join(', '), doc.synopsis])
})
excelWriter.write(tmpXlsxFile, xlsData, columnWidths)
var fileData = fs.readFileSync(tmpXlsxFile)
fs.unlinkSync(tmpXlsxFile)
return fileData
} | JavaScript | 0 |
b3d4d5ff368783e0c4e74d639c04b60019fa672d | Clean this up a bit. | a-minimalist-critique/a-minimalist-critique.js | a-minimalist-critique/a-minimalist-critique.js | function launch(prefix, containerId, config) {
var config = config || {};
var deps = [
"element-factory.js",
"sprite-manager.js",
"animation.js"
];
var loaded = 0;
for (var i = 0; i < deps.length; i++) {
var elem = document.createElement('script');
elem.src = prefix + deps[i];
elem.onload = function() {
if (++loaded < deps.length) return;
var container = document.getElementById(containerId);
var canvas = yoob.makeCanvas(container, 600, 400);
var g = (new MinimalistCritique()).init({ canvas: canvas });
g.start();
};
document.body.appendChild(elem);
}
}
MinimalistCritique = function() {
this.init = function(cfg) {
this.canvas = cfg.canvas;
this.ctx = this.canvas.getContext('2d');
this.manager = (new yoob.SpriteManager()).init({ canvas: this.canvas });
this.animation = (new yoob.Animation()).init({'object': this});
this.reset();
return this;
};
this.reset = function() {
this.manager.clearSprites();
this.current = null;
this.floorLevel = this.canvas.height;
this.sizes = [10, 40, 200, this.canvas.width];
this.stage = 0;
this.addNextBlock();
};
this.start = function() {
this.animation.start();
};
this.addBlock = function(cfg) {
var d = new yoob.Sprite();
cfg.dy = 1;
d.init(cfg);
d.draw = function(ctx) {
ctx.fillStyle = this.fillStyle || "green";
ctx.fillRect(this.getLeftX(), this.getTopY(), this.getWidth(), this.getHeight());
};
d.fillStyle = "green";
this.manager.addSprite(d);
this.current = d;
};
this.addNextBlock = function() {
if (this.stage >= this.sizes.length) {
this.animation.stop();
var $this = this;
setTimeout(function() {
// draw the big red X
var angles = [0.125, 0.375];
for (var i = 0; i <= 1; i++) {
$this.ctx.save();
$this.ctx.translate($this.canvas.width / 2, $this.canvas.height / 2);
$this.ctx.rotate(angles[i] * 2 * Math.PI);
$this.ctx.fillStyle = 'red';
$this.ctx.fillRect(
$this.canvas.width * -0.40,
$this.canvas.height * -0.05,
$this.canvas.width * 0.80,
$this.canvas.height * 0.10
);
$this.ctx.restore();
}
setTimeout(function() {
$this.reset();
$this.start();
}, 1000);
}, 100);
}
this.addBlock({
x: this.canvas.width / 2,
y: 0 - this.sizes[this.stage] / 2,
width: this.sizes[this.stage],
height: this.sizes[this.stage]
});
};
this.draw = function() {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.manager.draw(this.ctx);
};
this.update = function() {
this.manager.move();
if (this.current.getBottomY() >= this.floorLevel) {
this.current.setPosition(this.current.getX(), this.floorLevel - this.current.getHeight() / 2);
this.floorLevel = this.floorLevel - this.current.getHeight();
this.current.setVelocity(0, 0);
this.stage += 1;
this.draw();
this.addNextBlock();
}
};
}
| function launch(prefix, containerId, config) {
var config = config || {};
var deps = [
"element-factory.js",
"sprite-manager.js",
"animation.js"
];
var loaded = 0;
for (var i = 0; i < deps.length; i++) {
var elem = document.createElement('script');
elem.src = prefix + deps[i];
elem.onload = function() {
if (++loaded < deps.length) return;
var container = document.getElementById(containerId);
var canvas = yoob.makeCanvas(container, 600, 400);
var g = (new MinimalistCritique()).init({ canvas: canvas });
g.start();
};
document.body.appendChild(elem);
}
}
MinimalistCritique = function() {
this.init = function(cfg) {
this.canvas = cfg.canvas;
this.ctx = this.canvas.getContext('2d');
this.reset();
return this;
};
this.reset = function() {
this.manager = (new yoob.SpriteManager()).init({ canvas: this.canvas });
this.current = null;
this.floorLevel = this.canvas.height;
this.sizes = [10, 40, 200, this.canvas.width];
this.stage = 0;
this.addNextBlock();
this.animation = (new yoob.Animation()).init({'object': this});
};
this.start = function() {
this.animation.start();
};
this.addBlock = function(cfg) {
var d = new yoob.Sprite();
cfg.dy = 1;
d.init(cfg);
d.draw = function(ctx) {
ctx.fillStyle = this.fillStyle || "green";
ctx.fillRect(this.getLeftX(), this.getTopY(), this.getWidth(), this.getHeight());
};
d.fillStyle = "green";
this.manager.addSprite(d);
this.current = d;
};
this.addNextBlock = function() {
if (this.stage >= this.sizes.length) {
// start blinking the X
//alert('done');
this.animation.stop();
this.ctx.save();
this.ctx.translate(this.canvas.width / 2, this.canvas.height / 2);
this.ctx.rotate(0.125 * 2 * Math.PI);
this.ctx.fillStyle = 'red';
this.ctx.fillRect(
this.canvas.width * -0.40,
this.canvas.height * -0.05,
this.canvas.width * 0.80,
this.canvas.height * 0.10
);
this.ctx.restore();
this.ctx.save();
this.ctx.translate(this.canvas.width / 2, this.canvas.height / 2);
this.ctx.rotate(0.375 * 2 * Math.PI);
this.ctx.fillStyle = 'red';
this.ctx.fillRect(
this.canvas.width * -0.40,
this.canvas.height * -0.05,
this.canvas.width * 0.80,
this.canvas.height * 0.10
);
this.ctx.restore();
var $this = this;
setTimeout(function() {
$this.reset();
$this.start();
}, 1000);
return;
}
this.addBlock({
x: this.canvas.width / 2,
y: 0 - this.sizes[this.stage] / 2,
width: this.sizes[this.stage],
height: this.sizes[this.stage]
});
};
this.draw = function() {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.manager.draw(this.ctx);
};
this.update = function() {
this.manager.move();
if (this.current.getBottomY() >= this.floorLevel) {
this.current.setPosition(this.current.getX(), this.floorLevel - this.current.getHeight() / 2);
this.floorLevel = this.floorLevel - this.current.getHeight();
this.current.setVelocity(0, 0);
this.stage += 1;
this.draw();
this.addNextBlock();
}
};
}
| JavaScript | 0.000004 |
2e075f5cc86f883f179003d543a321787f1c9971 | Update prefs.js | public/js/prefs.js | public/js/prefs.js | window.prefs = {};
$(document).ready(function() {
window.api.get("prefs/get/name-subj", function(data) {
var btnTrue = data.val;
if(btnTrue == "1") {
$("prefs-hwView-swap").prop("checked", true);
}
$("#prefs-hwView-swap").change(function() {
if(btnTrue == "1") {
btnTrue = "0";
} else {
btnTrue = "1";
};
window.api.post("prefs/set", { name: "name-subj", value: btnTrue}, function() {});
});
alert("buttonstuff!");
});
$("#usr-btn").click(function() {
var usrname = $("#usr-name").val();
window.api.post("prefs/setName", { name: "#{usrname}" }, function() {
alert("maybe this worked!");
});
});
});
| window.prefs = {};
$(document).ready(function() {
window.api.get("prefs/get/name-subj", function(data) {
var btnTrue = data.val;
if(btnTrue == "1") {
$("prefs-hwView-swap").prop("checked", true);
}
$("#prefs-hwView-swap").change(function() {
if(btnTrue == "1") {
btnTrue = "0";
} else {
btnTrue = "1";
};
window.api.post("prefs/set", { name: "name-subj", value: btnTrue}, function() {});
});
});
});
| JavaScript | 0.000001 |
71f24279ef1a2f852735cbc9522cdfcce17eb725 | remove duplicate | lib/index.js | lib/index.js | 'use strict';
var _ = require('lodash');
// Tasks
//
// require('./tasks/docs/browserSync.js');
// require('./tasks/docs/clean.js');
// require('./tasks/docs/copy.js');
// require('./tasks/docs/deploy.js');
// require('./tasks/docs/ngdocs.js');
// require('./tasks/docs/readme.js');
// require('./tasks/docs/resolveDocsDependencies.js');
// require('./tasks/docs/scripts.js');
// require('./tasks/docs/styles.js');
// require('./tasks/docs/views.js');
// require('./tasks/src/bump.js');
// require('./tasks/src/changelog.js');
// require('./tasks/src/clean.js');
// require('./tasks/src/deploy.js');
// require('./tasks/src/jshint.js');
// require('./tasks/src/scripts.js');
// require('./tasks/src/styles.js');
// require('./tasks/src/templates.js');
// require('./tasks/src/karma.js');
// require('./tasks/test/jshint.js');
require('./debug');
module.exports = function(gulp, options) {
if(!options.type) throw new Error('Required option: \'type\'');
if(!options.pkg) throw new Error('Required option: \'pkg\'');
var config = require('./config')(options);
config.channels = require('gulp-channels')(gulp, config);
require('./tasks/src/bump.js')(gulp, config);
require('./tasks/src/changelog.js')(gulp, config);
require('./tasks/src/clean.js')(gulp, config);
require('./tasks/src/copy.js')(gulp, config);
require('./tasks/src/deploy.js')(gulp, config);
require('./tasks/src/views.js')(gulp, config);
require('./tasks/src/serve.js')(gulp, config);
require('./tasks/src/watch.js')(gulp, config);
require('./tasks/src/jshint.js')(gulp, config);
require('./tasks/src/scripts.js')(gulp, config);
require('./tasks/src/styles.js')(gulp, config);
require('./tasks/src/templates.js')(gulp, config);
require('./tasks/test/clean.js')(gulp, config);
require('./tasks/test/jshint.js')(gulp, config);
require('./tasks/test/karma.js')(gulp, config);
require('./tasks/docs/browserSync.js')(gulp, config);
require('./tasks/docs/clean.js')(gulp, config);
require('./tasks/docs/copy.js')(gulp, config);
require('./tasks/docs/deploy.js')(gulp, config);
require('./tasks/docs/ngdocs.js')(gulp, config);
require('./tasks/docs/readme.js')(gulp, config);
require('./tasks/docs/resolveDocsDependencies.js')(gulp, config);
require('./tasks/docs/scripts.js')(gulp, config);
require('./tasks/docs/styles.js')(gulp, config);
require('./tasks/docs/views.js')(gulp, config);
};
module.exports.component = function(gulp, options) {
options.type = 'component';
module.exports(gulp, options);
};
module.exports.application = function(gulp, options) {
options.type = 'application';
module.exports(gulp, options);
};
| 'use strict';
var _ = require('lodash');
// Tasks
//
// require('./tasks/docs/browserSync.js');
// require('./tasks/docs/clean.js');
// require('./tasks/docs/copy.js');
// require('./tasks/docs/deploy.js');
// require('./tasks/docs/ngdocs.js');
// require('./tasks/docs/readme.js');
// require('./tasks/docs/resolveDocsDependencies.js');
// require('./tasks/docs/scripts.js');
// require('./tasks/docs/styles.js');
// require('./tasks/docs/views.js');
// require('./tasks/src/bump.js');
// require('./tasks/src/changelog.js');
// require('./tasks/src/clean.js');
// require('./tasks/src/deploy.js');
// require('./tasks/src/jshint.js');
// require('./tasks/src/scripts.js');
// require('./tasks/src/styles.js');
// require('./tasks/src/templates.js');
// require('./tasks/src/karma.js');
// require('./tasks/test/jshint.js');
require('./debug');
module.exports = function(gulp, options) {
if(!options.type) throw new Error('Required option: \'type\'');
if(!options.pkg) throw new Error('Required option: \'pkg\'');
var config = require('./config')(options);
config.channels = require('gulp-channels')(gulp, config);
require('./tasks/src/bump.js')(gulp, config);
require('./tasks/src/changelog.js')(gulp, config);
require('./tasks/src/clean.js')(gulp, config);
require('./tasks/src/copy.js')(gulp, config);
require('./tasks/src/deploy.js')(gulp, config);
require('./tasks/src/views.js')(gulp, config);
require('./tasks/src/serve.js')(gulp, config);
require('./tasks/src/watch.js')(gulp, config);
require('./tasks/src/jshint.js')(gulp, config);
require('./tasks/src/scripts.js')(gulp, config);
require('./tasks/src/styles.js')(gulp, config);
require('./tasks/src/templates.js')(gulp, config);
require('./tasks/test/clean.js')(gulp, config);
require('./tasks/test/jshint.js')(gulp, config);
require('./tasks/test/karma.js')(gulp, config);
require('./tasks/docs/clean.js')(gulp, config);
require('./tasks/docs/browserSync.js')(gulp, config);
require('./tasks/docs/clean.js')(gulp, config);
require('./tasks/docs/copy.js')(gulp, config);
require('./tasks/docs/deploy.js')(gulp, config);
require('./tasks/docs/ngdocs.js')(gulp, config);
require('./tasks/docs/readme.js')(gulp, config);
require('./tasks/docs/resolveDocsDependencies.js')(gulp, config);
require('./tasks/docs/scripts.js')(gulp, config);
require('./tasks/docs/styles.js')(gulp, config);
require('./tasks/docs/views.js')(gulp, config);
};
module.exports.component = function(gulp, options) {
options.type = 'component';
module.exports(gulp, options);
};
module.exports.application = function(gulp, options) {
options.type = 'application';
module.exports(gulp, options);
};
| JavaScript | 0.004769 |
7f61b5dca20864208fbcaad669423446a6164137 | Add year-parser test case | db/test/unit/tdsystem/year-parser.spec.js | db/test/unit/tdsystem/year-parser.spec.js | 'use strict';
var client = require('cheerio-httpcli');
var parser = require('../../../js/tdsystem/year-parser');
var util = require('../../../js/swimtrack-util');
var testUrl = 'http://www.tdsystem.co.jp/i2015.htm';
describe('Test 2015 top page', function() {
it('should find a right meet and venue from a given meet name', function(done) {
client.fetch(testUrl, function(err, $, res) {
let parseResult = parser.parsePage(2015, $);
let meets = parseResult.meets;
expect(meets.length).toEqual(198);
let meetFound = false;
for (let i = 0; i < meets.length; i++) {
let meet = meets[i];
if (meet.name === '中部学生選手権水泳競技大会') {
meetFound = true;
expect(meet.days).toContain('2015-07-04');
expect(meet.days).toContain('2015-07-05');
expect(meet.venue.city).toEqual('愛知');
expect(meet.venue.name).toEqual('日本ガイシアリーナ');
expect(meet.venue.course).toEqual('長水路');
break;
}
}
expect(meetFound).toEqual(true);
done();
});
});
});
| 'use strict';
var client = require('cheerio-httpcli');
var parser = require('../../../js/tdsystem/year-parser');
var util = require('../../../js/swimtrack-util');
var testUrl = 'http://www.tdsystem.co.jp/i2015.htm';
describe('Test 2015 top page', function() {
it('should find a right meet and venue from a given meet name', function(done) {
client.fetch(testUrl, 'Shift_JIS', function(err, $, res) {
let parseResult = parser.parsePage(2015, $);
let meets = parseResult.meets;
let meetFound = false;
for (let i = 0; i < meets.length; i++) {
let meet = meets[i];
if (meet.name === '中部学生選手権水泳競技大会') {
meetFound = true;
expect(meet.days).toContain('2015-07-04');
expect(meet.days).toContain('2015-07-05');
expect(meet.venue.city).toEqual('愛知');
expect(meet.venue.name).toEqual('日本ガイシアリーナ');
expect(meet.venue.course).toEqual('長水路');
break;
}
}
expect(meetFound).toEqual(true);
done();
});
});
});
| JavaScript | 0.000041 |
5da7fca1ad5ac8541c282d0c2cc7c3b288bbf933 | fix registration logic | AdapterResolver.js | AdapterResolver.js | (function (define) {
define(function () {
"use strict";
var adapters;
adapters = {};
/**
* Finds an adapter for the given object and the role.
* This is overly simplistic for now. We can replace this
* resolver later.
* @param object {Object}
* @param type {String}
* @description Loops through all Adapters registered with
* AdapterResolver.register, calling each Adapter's canHandle
* method. Adapters added later are found first.
*/
function AdapterResolver (object, type) {
var adaptersOfType, i, Adapter;
adaptersOfType = adapters[type];
if (adaptersOfType) {
i = adaptersOfType.length;
while ((Adapter = adaptersOfType[--i])) {
if (Adapter.canHandle(object)) {
return Adapter;
}
}
}
}
AdapterResolver.register = function registerAdapter (Adapter, type) {
if (!(type in adapters)) adapters[type] = [];
adapters[type].push(Adapter);
};
return AdapterResolver;
});
}(
typeof define == 'function'
? define
: function (factory) { module.exports = factory(); }
)); | (function (define) {
define(function () {
"use strict";
var adapters;
adapters = {};
/**
* Finds an adapter for the given object and the role.
* This is overly simplistic for now. We can replace this
* resolver later.
* @param object {Object}
* @param type {String}
* @description Loops through all Adapters registered with
* AdapterResolver.register, calling each Adapter's canHandle
* method. Adapters added later are found first.
*/
function AdapterResolver (object, type) {
var adaptersOfType, i, Adapter;
adaptersOfType = adapters[type];
if (adaptersOfType) {
i = adaptersOfType.length;
while ((Adapter = adaptersOfType[--i])) {
if (Adapter.canHandle(object)) {
return Adapter;
}
}
}
}
AdapterResolver.register = function registerAdapter (Adapter, type) {
if (!type in adapters) adapters[type] = [];
adapters[type].push(Adapter);
};
return AdapterResolver;
});
}(
typeof define == 'function'
? define
: function (factory) { module.exports = factory(); }
)); | JavaScript | 0.000001 |