commit
stringlengths 40
40
| subject
stringlengths 1
3.25k
| old_file
stringlengths 4
311
| new_file
stringlengths 4
311
| old_contents
stringlengths 0
26.3k
| lang
stringclasses 3
values | proba
float64 0
1
| diff
stringlengths 0
7.82k
|
---|---|---|---|---|---|---|---|
ec4d32a446072ccef80381821a98ba8f3459233c
|
Update image.js
|
lib/image.js
|
lib/image.js
|
var util = require('./util');
/**
* Represents an mage
* @param {Object} modem docker-modem
* @param {String} name Image's name
*/
var Image = function(modem, name) {
this.modem = modem;
this.name = name;
};
/**
* Inspect
* @param {Function} callback Callback, if specified Docker will be queried.
* @return {Object} Name only if callback isn't specified.
*/
Image.prototype.inspect = function(callback) {
if (typeof callback === 'function') {
var opts = {
path: '/images/' + this.name + '/json',
method: 'GET',
statusCodes: {
200: true,
404: 'no such image',
500: 'server error'
}
};
this.modem.dial(opts, function(err, data) {
callback(err, data);
});
} else {
return JSON.stringify({name: this.name});
}
};
/**
* History
* @param {Function} callback Callback
*/
Image.prototype.history = function(callback) {
var opts = {
path: '/images/' + this.name + '/history',
method: 'GET',
statusCodes: {
200: true,
404: 'no such image',
500: 'server error'
}
};
this.modem.dial(opts, function(err, data) {
callback(err, data);
});
};
/**
* Get
* @param {Function} callback Callback with data stream.
*/
Image.prototype.get = function(callback) {
var opts = {
path: '/images/' + this.name + '/get',
method: 'GET',
isStream: true,
statusCodes: {
200: true,
500: 'server error'
}
};
this.modem.dial(opts, function(err, data) {
callback(err, data);
});
};
/**
* Push
* @param {Object} opts Push options, like 'registry' (optional)
* @param {Function} callback Callback with stream.
* @param {Object} auth Registry authentication
*/
Image.prototype.push = function(opts, callback, auth) {
var self = this;
var optsf = {
path: '/images/' + this.name + '/push?',
method: 'POST',
options: opts,
authconfig: opts.authconfig || auth,
isStream: true,
statusCodes: {
200: true,
404: 'no such image',
500: 'server error'
}
};
delete optsf.options.authconfig;
this.modem.dial(optsf, function(err, data) {
callback(err, data);
});
};
/**
* Tag
* @param {Object} opts Tag options, like 'repo' (optional)
* @param {Function} callback Callback
*/
Image.prototype.tag = function(opts, callback) {
var self = this;
var optsf = {
path: '/images/' + this.name + '/tag?',
method: 'POST',
options: opts,
statusCodes: {
200: true, // unofficial, but proxies may return it
201: true,
400: 'bad parameter',
404: 'no such image',
409: 'conflict',
500: 'server error'
}
};
this.modem.dial(optsf, function(err, data) {
callback(err, data);
});
};
/**
* Removes the image
* @param {[Object]} opts Remove options (optional)
* @param {Function} callback Callback
*/
Image.prototype.remove = function(opts, callback) {
var args = util.processArgs(opts, callback);
var optsf = {
path: '/images/' + this.name + '?',
method: 'DELETE',
statusCodes: {
200: true,
404: 'no such image',
409: 'conflict',
500: 'server error'
},
options: args.opts
};
this.modem.dial(optsf, function(err, data) {
args.callback(err, data);
});
};
module.exports = Image;
|
JavaScript
| 0.000001 |
@@ -45,16 +45,17 @@
ents an
+i
mage%0A *
|
9a9d8ec029367ed2963104db3ecd8ce3a3d8bb33
|
update Dialog
|
src/Dialog/Dialog.js
|
src/Dialog/Dialog.js
|
/**
* @file Dialog component
* @author liangxiaojun([email protected])
*/
import React, {Children, cloneElement, Component} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import PositionPop from '../_PositionPop';
import Paper from '../Paper';
import FlatButton from '../FlatButton';
import RaisedButton from '../RaisedButton';
import IconButton from '../IconButton';
import Theme from '../Theme';
import Position from '../_statics/Position';
import Util from '../_vendors/Util';
import PopManagement from '../_vendors/PopManagement';
class Dialog extends Component {
static ButtonTheme = Theme;
static Position = Position;
constructor(props, ...restArgs) {
super(props, ...restArgs);
}
okButtonClickHandler = () => {
const {visible, onOKButtonClick} = this.props;
visible && onOKButtonClick && onOKButtonClick(() => {
this.setState({
visible: false
}, () => {
const {onRequestClose} = this.props;
onRequestClose && onRequestClose();
});
});
};
cancelButtonClickHandler = () => {
const {onCancelButtonClick, onRequestClose} = this.props;
onCancelButtonClick && onCancelButtonClick();
this.setState({
visible: false
}, () => {
onRequestClose && onRequestClose();
});
};
closeButtonClickHandler = () => {
const {onCloseButtonClick, onRequestClose} = this.props;
onCloseButtonClick && onCloseButtonClick();
this.setState({
visible: false
}, () => {
onRequestClose && onRequestClose();
});
};
renderHandler = (...args) => {
PopManagement.push(this, {
shouldLockBody: this.props.showModal
});
const {onRender} = this.props;
onRender && onRender(...args);
};
destroyHandler = (...args) => {
PopManagement.pop(this);
const {onDestroy} = this.props;
onDestroy && onDestroy(...args);
};
componentWillUnmount() {
PopManagement.pop(this);
}
render() {
const {
children,
className, modalClassName, position, disabled, showModal,
title, buttons, isLoading, visible,
okButtonVisible, okButtonText, okButtonIconCls, okButtonTheme, okButtonDisabled, okButtonIsLoading,
cancelButtonVisible, cancelButtonText, cancelButtonIconCls, cancelButtonDisabled, cancelButtonIsLoading,
cancelButtonTheme, closeButtonVisible, closeIconCls,
// not passing down these props
isBlurClose, isEscClose,
onRequestClose, onOKButtonClick, onCloseButtonClick, onCancelButtonClick,
...restProps
} = this.props,
dialogClassName = classNames('dialog', {
[className]: className
});
return (
<PositionPop {...restProps}
className={dialogClassName}
position={position}
visible={visible}
container={<Paper depth={6}></Paper>}
showModal={showModal}
modalClassName={modalClassName}
onRender={this.renderHandler}
onDestroy={this.destroyHandler}>
<div className="dialog-title">
{title}
{
closeButtonVisible ?
<IconButton className="dialog-title-close-button"
iconCls={closeIconCls}
disabled={disabled}
onClick={this.closeButtonClickHandler}/>
:
null
}
</div>
<div className="dialog-content">
{children}
</div>
<div className="dialog-buttons">
{
buttons ?
Children.map(buttons, button => cloneElement(button, {
isLoading,
disabled
}))
:
null
}
{
!buttons && okButtonVisible ?
<RaisedButton className="ok-button"
value={okButtonText}
iconCls={okButtonIconCls}
theme={okButtonTheme}
disabled={okButtonDisabled}
isLoading={isLoading || okButtonIsLoading}
disableTouchRipple={true}
onClick={this.okButtonClickHandler}/>
:
null
}
{
!buttons && cancelButtonVisible ?
<FlatButton className="cancel-button"
value={cancelButtonText}
iconCls={cancelButtonIconCls}
theme={cancelButtonTheme}
disabled={cancelButtonDisabled}
isLoading={isLoading || cancelButtonIsLoading}
disableTouchRipple={true}
onClick={this.cancelButtonClickHandler}/>
:
null
}
</div>
</PositionPop>
);
}
}
Dialog.propTypes = {
/**
* The css class name of the root element.
*/
className: PropTypes.string,
/**
* The css class name of the modal.
*/
modalClassName: PropTypes.string,
/**
* The styles of the root element.
*/
style: PropTypes.object,
parentEl: PropTypes.object,
/**
* The dialog alignment.
*/
position: PropTypes.oneOf(Util.enumerateValue(Position)),
/**
* If true,the element will disabled.
*/
disabled: PropTypes.bool,
/**
* If true,dialog box will display.
*/
visible: PropTypes.bool,
/**
* If true,the pop-up box will be displayed in the mask layer, or the pop-up box will appear below the element.
*/
showModal: PropTypes.bool,
/**
* Set the title of dialog.
*/
title: PropTypes.any,
/**
* If true,when press down mouse the pop-up box will closed.
*/
isBlurClose: PropTypes.bool,
isLoading: PropTypes.bool,
/**
* If true, the OK button will display.
*/
okButtonVisible: PropTypes.bool,
/**
* Set the text value of the OK button.
*/
okButtonText: PropTypes.string,
/**
* Set the icon class of the OK button.
*/
okButtonIconCls: PropTypes.string,
/**
* If true, the OK button will disabled.
*/
okButtonDisabled: PropTypes.bool,
/**
* If true, the ok button will have loading effect.
*/
okButtonIsLoading: PropTypes.bool,
/**
* Set theme of OK button.
*/
okButtonTheme: PropTypes.oneOf(Util.enumerateValue(Theme)),
/**
* If true, the cancel button will display.
*/
cancelButtonVisible: PropTypes.bool,
/**
* Set the text value of the cancel button.
*/
cancelButtonText: PropTypes.string,
/**
* Set the icon class of the cancel button.
*/
cancelButtonIconCls: PropTypes.string,
/**
* If true, the cancel button will disabled.
*/
cancelButtonDisabled: PropTypes.bool,
/**
* If true, the cancel button will have loading effect.
*/
cancelButtonIsLoading: PropTypes.bool,
/**
* Set theme of cancel button.
*/
cancelButtonTheme: PropTypes.oneOf(Util.enumerateValue(Theme)),
/**
* If true, the close button in title will display.
*/
closeButtonVisible: PropTypes.bool,
closeIconCls: PropTypes.string,
isEscClose: PropTypes.bool,
/**
* The buttons of Dialog.
*/
buttons: PropTypes.any,
/**
* The function of dialog render.
*/
onRender: PropTypes.func,
/**
* The function that trigger when click submit.
*/
onRequestClose: PropTypes.func,
/**
* Callback function fired when click the ok button.
*/
onOKButtonClick: PropTypes.func,
/**
* Callback function fired when click the cancel button.
*/
onCancelButtonClick: PropTypes.func,
/**
* Callback function fired when click the close button.
*/
onCloseButtonClick: PropTypes.func
};
Dialog.defaultProps = {
parentEl: document.body,
position: Position.CENTER,
disabled: false,
visible: false,
showModal: true,
isBlurClose: false,
isLoading: false,
okButtonVisible: true,
okButtonText: 'OK',
okButtonDisabled: false,
okButtonIsLoading: false,
okButtonTheme: Theme.SUCCESS,
cancelButtonVisible: true,
cancelButtonText: 'Cancel',
cancelButtonDisabled: false,
cancelButtonIsLoading: false,
cancelButtonTheme: Theme.DEFAULT,
closeButtonVisible: true,
closeIconCls: 'fas fa-times',
isEscClose: true
};
export default Dialog;
|
JavaScript
| 0.000001 |
@@ -760,24 +760,137 @@
gs);%0A %7D%0A%0A
+ /**%0A * public%0A */%0A getEl = () =%3E %7B%0A return this.refs.pop && this.refs.pop.getEl();%0A %7D;%0A%0A
okButton
@@ -3203,16 +3203,51 @@
tProps%7D%0A
+ ref=%22pop%22%0A
|
f7742677396466e101590c8a5875df7ec2153fc3
|
Move line
|
js/script.js
|
js/script.js
|
define(['angular', 'jquery', 'jss', 'farbtastic', 'defaults'], function(angular, jquery, jss, farbtastic, defaults) {
return {
init: function(scope) {
var that = this;
jquery.each(defaults.defaultTheme.colors, function(key, value) {
var inputFarbtastic = jquery('#' + key).farbtastic('#input-' + key);
// Add a listener to update farbtastic and style when a color is changed.
scope.$watch('theme.colors["' + key + '"]', function(newVal, oldVal) {
jquery.farbtastic('#' + key).setColor(newVal);
that.updateStyle(false);
});
});
// Add a listener to update the page item count when the window is resized.
jquery(window).resize(function() {
scope.$apply(function() {
scope.setPageItemCount(that.getPageItemCount());
});
});
scope.setPageItemCount(that.getPageItemCount());
jquery('body').show();
},
/**
Compares window height to element height to fine the number of elements per page.
returns: The number of items to fit on a page.
*/
getPageItemCount: function() {
var pageHeight = jquery('body').height();
var headerHeight = jquery('h1').outerHeight(true);
var navBarHeight = jquery('.page-chooser').outerHeight(true);
var footerHeight = jquery('.footer').outerHeight(true);
var height = pageHeight - (headerHeight + navBarHeight + footerHeight);
jss.set('.external', {
'height': '' + height
});
jss.set('.bookmark_page', {
'height': '' + height
});
return Math.floor((height) / 60) - 1;
},
/**
Changes the style to whatever is in the scope.
transition: A bool indicating whether to slowly transition or immediately change.
*/
updateStyle: function(transition) {
var scope = angular.element(document.body).scope();
var options_color = defaults.defaultTheme['options-color'];
var background_color = defaults.defaultTheme['background-color'];
var main_color = defaults.defaultTheme['main-color'];
var title_color = defaults.defaultTheme['title-color'];
jquery.each(defaults.defaultTheme.colors, function(key, value) {
jquery('#' + key).farbtastic('.color-picker .' + key);
//
// // Add a listener to update farbtastic when a color is changed.
// scope.$watch('theme.colors["' + key + '"]', function(newVal, oldVal) {
// jquery.farbtastic('#' + key).setColor(newVal);
// });
});
if (scope.theme) {
background_color = scope.theme.colors['background-color'];
options_color = scope.theme.colors['options-color'];
main_color = scope.theme.colors['main-color'];
title_color = scope.theme.colors['title-color'];
}
if(scope.font === 0) {
jss.set('body', {
'font-family': '"Segoe UI", Helvetica, Arial, sans-serif',
});
} else {
jss.set('body', {
'font-family': 'Raleway, "Segoe UI", Helvetica, Arial, sans-serif',
});
}
jss.set('*', {
'border-color': options_color
});
jss.set('::-webkit-scrollbar', {
'background': background_color
});
jss.set('::-webkit-scrollbar-thumb', {
'background': options_color
});
jss.set('::-webkit-input-placeholder', {
'background': main_color
});
// Transition the colors
if (transition) {
jquery('.background-color').animate({'backgroundColor': background_color}, {duration: 800, queue: false});
jquery('.title-color').animate({'color': title_color}, {duration: 400, queue: false});
jquery('body').animate({'color': main_color}, {duration: 400, queue: false});
jquery('input').animate({'color': main_color}, {duration: 400, queue: false});
jquery('.options-color').animate({'color': options_color}, {duration: 400, queue: false});
}
//but then we still need to add it to the DOM.
jss.set('.background-color', {
'background-color': background_color
});
jss.set('.title-color', {
'color': title_color
});
jss.set('body', {
'color': main_color
});
jss.set('input', {
'color': main_color
});
jss.set('.options-color', {
'color': options_color
});
jss.set('.bookmark-active', {
'color': options_color
//'border-bottom': '2px solid ' + options_color
});
}
};
});
|
JavaScript
| 0.000014 |
@@ -949,32 +949,67 @@
%7D);%0A%0A
+ jquery('body').show();%0A
scop
@@ -1056,44 +1056,8 @@
());
-%0A%0A jquery('body').show();
%0A
|
68a096de4e645e74f877f3436fb0b4c3b983de85
|
Change from SIGHUP to SIGUSR2.
|
lib/index.js
|
lib/index.js
|
var _ = require('lodash');
var fs = require('fs');
var cluster = require('cluster');
var logger = require('log4js').getLogger('SATAN');
var Satan = function(defaultConfig, configFilePath) {
this.workers = {};
this.workerCount = 0;
this.loadingCount = 0;
this.targetWorkerCount = 0;
this.defaultConfig = defaultConfig;
this.configFile = {};
this.configFilePath = configFilePath;
};
Satan.prototype.refreshConfiguration = function() {
if (this.configFilePath) {
try {
this.configFile = JSON.parse(fs.readFileSync(this.configFilePath));
} catch (e) {
logger.error('Failed to read config file! Continuing anyway with previous configuration...');
logger.error(e);
}
}
this.config = _.defaults({
arguments: (this.defaultConfig.arguments || []).concat(this.configFile.arguments || [])
}, this.defaultConfig, this.configFile, {
instances: 1,
schedulingPolicy: 'rr',
nodeArguments: process.execArgs
});
this.targetWorkerCount = this.config.instances;
};
Satan.prototype.prepare = function() {
var self = this;
switch (this.config.schedulingPolicy) {
case 'rr':
cluster.schedulingPolicy = cluster.SCHED_RR;
break;
case 'none':
cluster.schedulingPolicy = cluster.SCHED_NODE;
break;
default:
throw new Error("Invalid scheduling policy " + this.config.schedulingPolicy);
break;
}
cluster.setupMaster({
execArgs: this.config.nodeArguments,
exec: this.config.script,
args: this.config.arguments
});
process.on('SIGHUP', function() {
logger.debug('Caught SIGHUP!');
self.reload();
});
};
Satan.prototype.ensureWorkerCount = function() {
var instanceDelta = function() {
return this.targetWorkerCount - this.workerCount - this.loadingCount;
}.bind(this);
if (instanceDelta() > 0) {
logger.info('Upscaling to %s worker(s).', this.targetWorkerCount);
while (instanceDelta() > 0) {
this.spawnWorker();
}
} else if (instanceDelta() < 0) {
logger.info('Downscaling to %s worker(s).', this.targetWorkerCount);
while (instanceDelta() < 0) {
this.removeWorker(Object.keys[this.workers][0]);
}
} else {
return;
}
// Ensures that the config is correct
this.ensureWorkerCount();
};
Satan.prototype.start = function() {
this.refreshConfiguration();
this.prepare();
this.ensureWorkerCount();
};
Satan.prototype.reload = function() {
var oldWorkers = Object.keys(this.workers);
logger.info('Reloading configuration...');
this.refreshConfiguration();
this.ensureWorkerCount();
logger.info('Reloading all remaining workers...');
for (var i = 0; i < oldWorkers.length; i++) {
var worker = this.workers[oldWorkers[i]];
// Check if worker still exists
if (!worker || worker.satanState != 'online') {
continue;
}
this.reloadWorker(oldWorkers[i]);
}
};
Satan.prototype.spawnWorker = function(notify) {
var self = this;
var worker = cluster.fork();
if (notify === undefined) {
notify = true;
}
worker.once('disconnect', function() {
delete self.workers[worker.id];
if (!this.ignoreDisconnect) {
logger.warn('Worker %s disconnected!', worker.id);
self.workerCount--;
}
self.ensureWorkerCount();
});
if (notify) {
this.loadingCount++;
}
worker.satanState = 'loading';
this.workers[worker.id] = worker;
worker.once('online', function() {
worker.satanState = 'online';
if (notify) {
self.workerCount++;
self.loadingCount--;
}
});
logger.info('Spawned worker #%s...', worker.id);
return worker;
};
Satan.prototype.reloadWorker = function(id) {
var worker = this.workers[id];
if (!worker) {
return;
}
logger.info('Reloading worker #%s...', id);
worker.satanState = 'reloading';
var newWorker = this.spawnWorker(false);
newWorker.once('listening', function() {
worker.ignoreDisconnect = true;
worker.send('shutdown');
});
return newWorker;
};
Satan.prototype.removeWorker = function(id) {
var worker = this.workers[id];
if (!worker) {
return;
}
logger.info('Removing worker #%s...', id);
this.workerCount--;
worker.ignoreDisconnect = true;
worker.satanState = 'unloading';
worker.send('shutdown');
};
module.exports = Satan;
|
JavaScript
| 0 |
@@ -1472,19 +1472,20 @@
.on('SIG
-HUP
+USR2
', funct
@@ -1522,11 +1522,12 @@
SIG
-HUP
+USR2
!');
|
24a3c50e478ace1e69ec48af4fa0a379b3cc3608
|
reset to time
|
static/scripts/autologout.js
|
static/scripts/autologout.js
|
$(document).ready(() => {
const $autoLoggoutAlertModal = $('.auto-logout-alert-modal');
const showModalOnRemainingSeconds = $autoLoggoutAlertModal.find('.form-group').data('showOnRemainingSec') || 3600;
// default remaining session time in sec, will be overwritten by server
const rstDefault = showModalOnRemainingSeconds * 2;
const maxTotalRetrys = 1;
let rst = rstDefault; // remaining session time in sec
let processing = false;
populateModalForm($autoLoggoutAlertModal, {});
const showAutoLogoutModal = ((status) => {
// switching between to texts inlcuded in the modal
if (status === 'error') {
$autoLoggoutAlertModal.find('.sloth-default').hide();
$autoLoggoutAlertModal.find('.sloth-error').show();
} else {
$autoLoggoutAlertModal.find('.sloth-default').show();
$autoLoggoutAlertModal.find('.sloth-error').hide();
}
$autoLoggoutAlertModal.find('.modal-header').remove();
$autoLoggoutAlertModal.modal('show');
});
const decRst = (() => {
setTimeout(() => {
if (rst >= 60) {
rst -= 60;
$('.js-time').text(Math.floor(rst / 60));
// show auto loggout alert modal
// don't show modal while processing
if (!processing && rst <= showModalOnRemainingSeconds) {
showAutoLogoutModal('default');
}
decRst();
}
}, 1000 * 60);
});
// Sync rst with Server every 5 mins
const syncRst = (() => {
setInterval(() => {
$.post('/account/ttl', ((result) => {
const { ttl } = result; // in sec
if (typeof ttl === 'number') {
rst = ttl;
}
}));
}, 1000 * 60 * 5);
});
let retry = 0;
let totalRetry = 0;
// extend session
const IStillLoveYou = (async () => {
$.post('/account/ttl', { resetTimer: true }, () => {
// on success
processing = false;
totalRetry = 0;
retry = 0;
rst = rstDefault;
$.showNotification('Sitzung erfolgreich verlängert.', 'success', true);
}).fail(() => {
// retry 4 times before showing error
if (retry < 4) {
retry += 1;
setTimeout(() => {
IStillLoveYou();
}, (2 ** retry) * 1000);
} else {
retry = 0;
if (totalRetry === maxTotalRetrys) {
/* eslint-disable-next-line max-len */
$.showNotification('Deine Sitzung konnte nicht verlängert werden! Bitte speichere deine Arbeit und lade die Seite neu.', 'danger', false);
} else {
showAutoLogoutModal('error');
}
totalRetry += 1;
}
});
});
decRst(); // dec. rst
syncRst(); // Sync rst with Server
$autoLoggoutAlertModal.find('.btn-incRst').on('click', (e) => {
e.stopPropagation();
e.preventDefault();
processing = true;
$autoLoggoutAlertModal.modal('hide');
});
// on modal close (button or backdrop)
$autoLoggoutAlertModal.on('hidden.bs.modal', () => {
processing = true;
IStillLoveYou();
});
});
|
JavaScript
| 0.000008 |
@@ -295,39 +295,12 @@
t =
-showModalOnRemainingSeconds * 2
+7200
;%0A%09c
|
a465651bc5704886abe6b24711b514a448affa17
|
Fix regression tests
|
test/regressions/index.js
|
test/regressions/index.js
|
import React from 'react';
import ReactDOM from 'react-dom';
import vrtest from 'vrtest/client';
import webfontloader from 'webfontloader';
import TestViewer from './TestViewer';
// Get all the tests specifically written for preventing regressions.
const requireRegression = require.context('./tests', true, /js$/);
const regressions = requireRegression.keys().reduce((res, path) => {
const [suite, name] = path
.replace('./', '')
.replace('.js', '')
.split('/');
res.push({
path,
suite: `regression-${suite}`,
name,
case: requireRegression(path).default,
});
return res;
}, []);
const blacklistSuite = [
// Flaky
'docs-demos-progress',
'docs-discover-more', // GitHub images
// Needs interaction
'docs-demos-dialogs',
'docs-demos-menus',
'docs-demos-tooltips',
// Useless
'docs-', // Home
'docs-guides',
];
const blacklistName = [
'docs-getting-started-usage/Usage', // codesandbox inside
];
// Also use some of the demos to avoid code duplication.
const requireDemos = require.context('docs/src/pages', true, /js$/);
const demos = requireDemos.keys().reduce((res, path) => {
const [name, ...suiteArray] = path
.replace('./', '')
.replace('.js', '')
.split('/')
.reverse();
const suite = `docs-${suiteArray.reverse().join('-')}`;
if (!blacklistSuite.includes(suite) && !blacklistName.includes(`${suite}/${name}`)) {
res.push({
path,
suite,
name,
case: requireDemos(path).default,
});
}
return res;
}, []);
const rootEl = document.createElement('div');
rootEl.style.display = 'inline-block';
vrtest.before(() => {
if (document && document.body) {
document.body.appendChild(rootEl);
}
return new Promise(resolve => {
webfontloader.load({
google: {
families: ['Roboto:300,400,500', 'Material+Icons'],
},
timeout: 20000,
active: () => {
resolve('active');
},
inactive: () => {
resolve('inactive');
},
});
});
});
let suite;
const tests = regressions.concat(demos);
tests.forEach(test => {
if (!suite || suite.name !== test.suite) {
suite = vrtest.createSuite(test.suite);
}
suite.createTest(test.name, () => {
const TestCase = test.case;
ReactDOM.render(
<TestViewer>
<TestCase />
</TestViewer>,
rootEl,
);
});
});
|
JavaScript
| 0.000005 |
@@ -946,16 +946,108 @@
inside%0A
+ 'docs-demos-drawers/tileData', // raw data%0A 'docs-demos-grid-list/tileData', // raw data%0A
%5D;%0A%0A// A
|
7a70da681bcce7523e521a3db2dd8999e5c3519a
|
fix formatting
|
gulpfile.js
|
gulpfile.js
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2016 Mickael Jeanroy
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
const fs = require('fs');
const path = require('path');
const gulp = require('gulp');
const babel = require('gulp-babel');
const jasmine = require('gulp-jasmine');
const eslint = require('gulp-eslint');
const gutil = require('gulp-util');
const git = require('gulp-git');
const bump = require('gulp-bump');
const runSequence = require('run-sequence');
const del = require('del');
const ROOT = __dirname;
const SRC = path.join(ROOT, 'src');
const TEST = path.join(ROOT, 'test');
const DIST = path.join(ROOT, 'dist');
gulp.task('clean', () => {
return del(DIST);
});
gulp.task('lint', () => {
const src = [
path.join(SRC, '**', '*.js'),
path.join(TEST, '**', '*.js'),
path.join(ROOT, '*.js'),
];
return gulp.src(src)
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
});
gulp.task('test', ['build'], () => {
const specs = path.join(TEST, '**', '*-spec.js');
return gulp.src(specs).pipe(jasmine());
});
gulp.task('build', ['lint', 'clean'], () => {
return gulp.src(path.join(__dirname, 'src', '**/*.js'))
.pipe(babel())
.pipe(gulp.dest(DIST));
});
gulp.task('commit:pre', () => {
const dist = path.join(__dirname, 'dist');
const packageJson = path.join(__dirname, 'package.json');
return gulp.src([packageJson, dist])
.pipe(git.add({args: '-f'}))
.pipe(git.commit('release: release version'));
});
gulp.task('commit:post', () => {
const dist = path.join(__dirname, 'dist');
return gulp.src(dist)
.pipe(git.rm({args: '-r'}))
.pipe(git.commit('release: prepare next release'));
});
gulp.task('tag', (done) => {
const pkg = fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8');
const version = JSON.parse(pkg).version;
git.tag(`v${version}`, `release: tag version ${version}`, done);
});
['major', 'minor', 'patch'].forEach((level) => {
gulp.task(`bump:${level}`, () => {
return gulp.src(path.join(__dirname, 'package.json'))
.pipe(bump({type: level})
.on('error', gutil.log))
.pipe(gulp.dest(__dirname));
});
gulp.task('release:' + level, ['build'], () => {
runSequence(`bump:${level}`, 'commit:pre', 'tag', 'commit:post');
});
});
gulp.task('default', ['build']);
|
JavaScript
| 0.000006 |
@@ -1882,20 +1882,16 @@
rc(src)%0A
-
.pip
@@ -1898,36 +1898,32 @@
e(eslint())%0A
-
-
.pipe(eslint.for
@@ -1929,20 +1929,16 @@
rmat())%0A
-
.pip
|
145667b72b721e246d7965c7a3c925b59f2dfbec
|
Tweak gulpfile
|
gulpfile.js
|
gulpfile.js
|
var path = require('path');
var source = require('vinyl-source-stream');
var minimist = require('minimist');
var gulpif = require('gulp-if');
var gulp = require('gulp');
var gutil = require('gulp-util');
var preprocess = require('gulp-preprocess');
var watchify = require('watchify');
var browserify = require('browserify');
var babelify = require('babelify');
var tsify = require('tsify');
var stylus = require('gulp-stylus');
var minifyCss = require('gulp-minify-css');
var streamify = require('gulp-streamify');
var autoprefixer = require('gulp-autoprefixer');
var rename = require('gulp-rename');
// command line options
var minimistOptions = {
string: ['env', 'mode', 'target'],
default: {
env: 'env.json',
mode: 'dev',
target: 'browser'
}
};
var options = minimist(process.argv.slice(2), minimistOptions);
var paths = {
styles: ['src/styl/reset.styl', 'src/styl/common.styl', 'src/styl/form.styl',
'src/styl/overlay.styl', 'src/styl/overlay-popup.styl', 'src/styl/*.styl'
]
};
function buildHtml(src, dest, context) {
console.log(context);
return gulp.src(path.join(src, 'index.html'))
.pipe(preprocess({context: context}))
.pipe(gulp.dest(dest));
}
function buildStyl(src, dest, mode) {
return gulp.src(src)
.pipe(stylus())
.pipe(streamify(autoprefixer({ browsers: ['and_chr >= 50', 'ios_saf >= 9']})))
.pipe(gulpif(mode === 'prod', minifyCss()))
.pipe(rename('app.css'))
.pipe(gulp.dest(dest + '/css/compiled/'));
}
function buildScripts(src, dest, mode) {
var opts = (mode === 'dev') ? { debug: true } : {};
return browserify(src + '/js/main.ts', opts)
.plugin(tsify)
.transform(babelify, {
extensions: ['.tsx', '.ts', '.js', '.jsx'],
presets: ['es2015']
})
.bundle()
.on('error', function(error) { gutil.log(gutil.colors.red(error.message)); })
.pipe(source('app.js'))
.pipe(gulp.dest(dest));
}
gulp.task('html', function() {
var context = require('./' + options.env);
context.MODE = options.mode;
context.TARGET = options.target;
return buildHtml('src', 'www', context);
});
gulp.task('styl', function() {
return buildStyl('src/styl/index.styl', 'www', options.mode);
});
gulp.task('scripts', function() {
return buildScripts('./src', 'www', options.mode);
});
gulp.task('watch-scripts', function() {
var opts = watchify.args;
opts.debug = true;
var bundleStream = watchify(
browserify('./src/js/main.ts', opts)
.plugin(tsify)
.transform(babelify, {
extensions: ['.tsx', '.ts', '.js', '.jsx'],
presets: ['es2015']
})
);
function rebundle() {
return bundleStream
.bundle()
.on('error', function(error) { gutil.log(gutil.colors.red(error.message)); })
.pipe(source('app.js'))
.pipe(gulp.dest('./www'));
}
bundleStream.on('update', rebundle);
bundleStream.on('log', gutil.log);
return rebundle();
});
// Watch Files For Changes
gulp.task('launch-watch', function() {
gulp.watch(paths.styles, ['styl']);
gulp.watch(['src/index.html', 'env.json'], ['html']);
});
gulp.task('default', ['html', 'styl', 'scripts']);
gulp.task('watch', ['html', 'styl', 'watch-scripts', 'launch-watch']);
module.exports = {
buildHtml: buildHtml,
buildStyl: buildStyl,
buildScripts: buildScripts
};
|
JavaScript
| 0.000001 |
@@ -1386,12 +1386,15 @@
== '
-prod
+release
', m
@@ -1992,39 +1992,8 @@
v);%0A
- context.MODE = options.mode;%0A
co
|
2336a3d6ba8804ad85e84afe59218d0c4314927d
|
Set version based on server ping version name
|
auto.js
|
auto.js
|
'use strict';
var mcf = require('minecraft-protocol-forge');
var mc = require('minecraft-protocol');
var ping = mc.ping;
var assert = require('assert');
function createClientAuto(options, cb) {
assert.ok(options, 'options is required');
console.log('pinging',options.host);
// TODO: refactor with DNS SRV lookup in NMP
// TODO: detect ping timeout, https://github.com/PrismarineJS/node-minecraft-protocol/issues/329
ping(options, function(err, response) {
var client;
if (err) return cb(err, null);
console.log('ping response',response);
// TODO: could also use ping pre-connect to save description, type, negotiate protocol etc.
// ^ see https://github.com/PrismarineJS/node-minecraft-protocol/issues/327
if (response.modinfo && response.modinfo.type === 'FML') {
// Use the list of Forge mods from the server ping, so client will match server
var forgeMods = response.modinfo.modList;
console.log('Using forgeMods:',forgeMods);
client = mcf.createClient(options); // we know we can use Forge
client.forgeMods = forgeMods; // for fmlHandshakeStep TODO: refactor, constructor?
} else {
client = mc.createClient(options); // vanilla
}
cb(null, client);
});
}
module.exports = {
createClientAsync: createClientAuto
};
|
JavaScript
| 0 |
@@ -733,16 +733,705 @@
sues/327
+%0A var motd = response.description;%0A console.log('Server description:',motd); // TODO: save%0A%0A // Pass server-reported version to protocol handler%0A // The version string is interpereted by https://github.com/PrismarineJS/node-minecraft-data%0A var versionName = response.version.name; // 1.8.9, 1.7.10%0A var versionProtocol = response.version.protocol;// 47, 5%0A%0A console.log(%60Server version: $%7BversionName%7D, protocol: $%7BversionProtocol%7D%60);%0A // TODO: test or report unsupported versions?%0A // TODO: fix non-vanilla/FML server support! Spigot 1.8.8, Glowstone++ 1.8.9 is 'versionName'; should use versionProtocol%0A //%0A%0A options.version = versionName;
%0A%0A if
|
2b8b5f02850750c00457df51ee087a80f5c0c852
|
Remove _padOperation from OperationsLog
|
src/oplog/OperationsLog.js
|
src/oplog/OperationsLog.js
|
'use strict';
const Log = require('ipfs-log');
const Cache = require('./Cache');
class OperationsLog {
constructor(ipfs, dbname, opts) {
this.dbname = dbname;
this.options = opts || { cacheFile: null };
this._lastWrite = null;
this._ipfs = ipfs;
this._log = null;
}
get ops() {
return this._log.items;
}
addOperation(operation, key, value) {
const entry = {
op: operation,
key: key,
value: value,
meta: {
ts: new Date().getTime()
}
};
let node, logHash;
return this._log.add(entry)
.then((op) => node = op)
.then(() => Object.assign(node.payload, { hash: node.hash }))
.then(() => Log.getIpfsHash(this._ipfs, this._log))
.then((hash) => logHash = hash)
.then(() => this._lastWrite = logHash)
.then(() => Cache.set(this.dbname, logHash))
.then(() => {
return { operation: node.payload, log: logHash };
})
}
load(id) {
return Log.create(this._ipfs, id)
.then((log) => this._log = log)
.then(() => Cache.loadCache(this.options.cacheFile))
.then(() => this.merge(Cache.get(this.dbname)))
}
merge(hash) {
if(!hash || hash === this._lastWrite || !this._log)
return Promise.resolve([]);
const oldCount = this._log.items.length;
let newItems = [];
return Log.fromIpfsHash(this._ipfs, hash)
.then((other) => this._log.join(other))
.then((merged) => newItems = merged)
.then(() => Cache.set(this.dbname, hash))
.then(() => newItems.forEach((f) => Object.assign(f.payload, { hash: f.hash })))
.then(() => newItems.map((f) => f.payload))
}
delete() {
this._log.clear();
}
_padOperation(node) {
Object.assign(node.payload, { hash: node.hash });
return node;
}
}
module.exports = OperationsLog;
|
JavaScript
| 0.000003 |
@@ -1703,108 +1703,8 @@
%0A %7D
-%0A%0A _padOperation(node) %7B%0A Object.assign(node.payload, %7B hash: node.hash %7D);%0A return node;%0A %7D
%0A%7D%0A%0A
|
d3008ce9dd2f704c9d5a1b4fbc2c134e63d6021c
|
Make package.json get copied when building
|
gulpfile.js
|
gulpfile.js
|
var childProcess = require('child_process');
var path = require('path');
var clean = require('gulp-clean');
var cleanCss = require('gulp-clean-css');
var concat = require('gulp-concat');
var copy = require('gulp-copy');
var gulp = require('gulp');
var jade = require('gulp-jade');
var jshint = require('gulp-jshint');
var less = require('gulp-less');
var lesshint = require('gulp-lesshint');
var merge = require('merge-stream');
var plumber = require('gulp-plumber');
var uglify = require('gulp-uglify');
var watch = require('gulp-watch');
var bowerInstall = require('./lib/bower_install.js');
var logger = require('./lib/logger.js');
var settings = require('./lib/settings.js');
var version = require('./lib/version.js');
var frontEndDependencies = require('./lib/front_end_deps.js');
var jadeLocals = {
settings: settings,
version: version,
deps: frontEndDependencies,
};
var paths = {};
paths.lessMain = 'less/theme.less';
paths.lessAll = 'less/**/*.less';
paths.css = 'public/css/';
paths.jade = 'jade/**/*.jade';
paths.html = 'public/';
paths.serverJs = ['server.js', 'lib/**/*.js'];
paths.publicJs = ['public/js/**/*.js', '!public/js/lib/**/*.js'];
paths.server = concatenateItems(paths.serverJs, '*.json', '!package.json', '!bower.json');
paths.js = concatenateItems('gulpfile.js', paths.serverJs, paths.publicJs);
paths.misc = ['node_modules/**/*'];
paths.assets = ['public/imgs/**/*', 'public/fonts/**/*', 'public/**/*.html'];
paths.public = 'public/';
paths.build = 'dist/';
paths.buildJsHead = 'dist/public/js/bundle_head.js';
paths.buildJsFinal = 'dist/public/js/bundle_final.js';
paths.buildCss = 'dist/public/css/bundle.css';
function concatenateItems() {
var itemList = [];
for (var i = 0; i < arguments.length; i++) {
itemList = itemList.concat(arguments[i]);
}
return itemList;
}
var server = null;
var restarting = false;
function startServer() {
if (server !== null) {
throw new Error('Server is already started');
}
server = childProcess.spawn('node', ['server.js']);
server.stdout.on('data', function(data) {
process.stdout.write(data);
});
server.stderr.on('data', function(data) {
process.stdout.write(data);
});
}
function restartServer(callback) {
if (restarting) {
return;
}
restarting = true;
if (server === null) {
startServer();
callback(null);
restarting = false;
return;
}
server.on('exit', function() {
server = null;
startServer();
callback(null);
restarting = false;
});
server.kill('SIGTERM');
}
gulp.task('bower', function(callback) {
bowerInstall(callback);
});
gulp.task('server', function(callback) {
startServer();
});
gulp.task('less', function() {
return gulp.src(paths.lessMain)
.pipe(less())
.pipe(gulp.dest(paths.css));
});
gulp.task('jade', function() {
return gulp.src(paths.jade)
.pipe(jade({
locals: jadeLocals,
}))
.pipe(gulp.dest(paths.html));
});
gulp.task('watch_less', ['less'], function() {
// Watch is done like this so that if any Less file changes, the entire
// monolithic less file is rebuilt (which depends on everything).
return watch(paths.lessAll, function() {
gulp.src(paths.lessMain)
.pipe(less())
.pipe(gulp.dest(paths.css));
});
});
gulp.task('watch_jade', function() {
return gulp.src(paths.jade)
.pipe(watch(paths.jade))
.pipe(plumber())
.pipe(jade({
locals: jadeLocals,
}))
.pipe(gulp.dest(paths.html));
});
gulp.task('watch_server', function() {
startServer();
return watch(paths.server, function() {
logger.log('File changed. Restarting server...');
restartServer(function() {});
});
});
gulp.task('watch', ['watch_less', 'watch_jade', 'watch_server']);
gulp.task('lint_js', function() {
return gulp.src(paths.js)
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
gulp.task('lint_less', function() {
return gulp.src(paths.lessAll)
.pipe(lesshint())
.pipe(lesshint.reporter());
});
gulp.task('lint', ['lint_js', 'lint_less']);
gulp.task('build_server', function() {
return gulp.src(paths.server)
.pipe(copy(paths.build));
});
gulp.task('build_misc', function() {
return gulp.src(paths.misc)
.pipe(copy(paths.build));
});
gulp.task('build_assets', ['jade'], function() {
return gulp.src(paths.assets)
.pipe(copy(paths.build));
});
gulp.task('build_js', function() {
var headFiles = frontEndDependencies.headJs.map(function(fileName) {
return paths.public + fileName;
});
var finalFiles = frontEndDependencies.finalJs.map(function(fileName) {
return paths.public + fileName;
});
var head = gulp.src(headFiles)
.pipe(concat(paths.buildJsHead))
.pipe(uglify())
.pipe(gulp.dest('.'));
var final = gulp.src(finalFiles)
.pipe(concat(paths.buildJsFinal))
.pipe(uglify())
.pipe(gulp.dest('.'));
return merge(head, final);
});
gulp.task('build_css', ['less'], function() {
var files = frontEndDependencies.css.map(function(fileName) {
return paths.public + fileName;
});
return gulp.src(files)
.pipe(concat(paths.buildCss))
.pipe(cleanCss({
keepSpecialComments: 0,
}))
.pipe(gulp.dest('.'));
});
gulp.task('build', ['build_server', 'build_misc', 'build_assets', 'build_js', 'build_css']);
gulp.task('clean', function() {
return gulp.src(paths.build, { read: false })
.pipe(clean());
});
gulp.task('default', ['watch']);
|
JavaScript
| 0.000001 |
@@ -1219,25 +1219,8 @@
on',
- '!package.json',
'!b
|
7c2b094dc8de81def37730913ee62bc79d9b6a9b
|
Improve logging
|
src/rest.js
|
src/rest.js
|
import http from 'http';
import urlParser from 'url';
import debug from 'debug';
const log = debug('w3c-webdriver');
function findError({ status, value }) {
if (!status && (!value || !value.error)) {
return null;
}
const { message, error } = value;
return new Error(`WebDriverError(${error || status}): ${message}`);
}
function sendRequest(method, url, body) {
const jsonBody = JSON.stringify(body);
const urlParts = urlParser.parse(url);
const options = {
hostname: urlParts.hostname,
port: urlParts.port,
path: urlParts.path,
method,
headers: {}
};
if (body) {
options.headers['Content-Length'] = Buffer.byteLength(jsonBody);
options.headers['Content-Type'] = 'application/json';
}
return new Promise((resolve, reject) => {
const request = http.request(options, (response) => {
const chunks = [];
response.setEncoding('utf8');
response.on('data', (chunk) => {
chunks.push(chunk);
});
response.on('end', () => {
let responseBody;
try {
responseBody = JSON.parse(chunks.join(''));
} catch (err) {
reject(err);
}
log(`WebDriver response: ${chunks.join('')}`);
const error = findError(responseBody);
if (error) {
reject(error);
return;
}
resolve(responseBody);
});
});
request.on('error', error => reject(error));
if (body) {
request.write(jsonBody);
}
request.end();
});
}
export const GET = url => sendRequest('GET', url);
export const POST = (url, body) => sendRequest('POST', url, body);
export const DELETE = (url, body) => sendRequest('DELETE', url, body);
|
JavaScript
| 0.00001 |
@@ -777,24 +777,86 @@
eject) =%3E %7B%0A
+ log(%60WebDriver request: $%7Boptions.url%7D $%7Boptions.body%7D%60);%0A
const re
|
dcd585a80d60792a9846a17cea5989cb45196d48
|
add implicit grant test
|
js/token.js
|
js/token.js
|
;
(function() {
var oAuthImplicitGRant = function(){
function getParameterByName(name) {
var match = RegExp('[#&]' + name + '=([^&]*)').exec(window.location.hash);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
function getAccessToken() {
return getParameterByName('access_token');
console.log("access_token!", access_token); //the new item is returned with an ID
}
function getIdToken() {
return getParameterByName('id_token');
}
$(function () {
var access_token = getAccessToken();
// Optional: an id_token will be returned by Auth0
// if your response_type argument contained id_token
var id_token = getIdToken();
// Use the access token to make API calls
$('#get-appointments').click(function(e) {
e.preventDefault();
// $.ajax({
// cache: false,
// url: "https://danvitoriano.auth0.com/userinfo",
// headers: { "Authorization": "Bearer " + access_token }
// });
$.ajax({
type: 'GET',
cache: false,
url: 'https://danvitoriano.auth0.com/userinfo',
headers: { "Authorization": "Bearer " + access_token },
success: function(data) {
console.log("access_token!", access_token); //the new item is returned with an ID
$("#res-10").html("<p class='text-success mt-2' role=alert>" + data.email + "</p>");
},
error: function() {
console.log("Content not added!", access_token); //the new item is returned with an ID
$("#res-10").html("<p class='text-danger mt-2' role=alert>Error " + access_token + "</p>");
}
});
});
});
}();
})();
|
JavaScript
| 0.000004 |
@@ -1379,24 +1379,70 @@
ta.email + %22
+, %22 + data.name + %22, %22 + data.family_name + %22
%3C/p%3E%22);%0A%09
|
02f708cdd2b845454a5f25998df9e0f618df399a
|
Update character
|
commit.js
|
commit.js
|
var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
var inFile = process.argv[ 2
|
JavaScript
| 0 |
@@ -146,24 +146,25 @@
nFile = process.argv%5B 2
+%5D
|
feb25b5bfc12d8d797bf35a1175b5d7bc13acf9f
|
Fix error + add global list var
|
js/script.js
|
js/script.js
|
function AfficherClassement() {
var liste = [[1,"MULOT Cyrille",3],[2,"AMIOT Antoine",2],[3,"BRUNET Xavier",36],[4,"FONTENAY Karine",1],[5,"PRIVAT Nicolas",61],[6,"KAMINSKI Stephan",98],[7,"GARDENT Thierry",51],[8,"HENNENFENT Roland",17],[9,"BENOIT Philippe",39],[10,"LANGEVIN Samuel",58],[11,"REVILLER Thierry",86],[12,"SAVART Jerome",65],[13,"MOULIN Franck",68],[14,"ALENDOURO Victor",66],[15,"PECOT Stève",95],[16,"VASTESAEGER Sven",75],[17,"GARNIER Dominique",23],[18,"FLOURET Michel",46],[19,"MINARD Anne laure",76],[20,"PASQUET Frederic",79],[21,"DEVILLERT Christophe",28],[22,"LAPIERRE Michael",85],[23,"ROUX Thierry",82],[24,"ROULET David",59],[25,"DORDAIN Tony",93],[26,"MENDER Miloud",96],[27,"FONTAINE Julien",29],[28,"FOUQUET Arnaud",48],[29,"GICQUEL Fabrice",97],[30,"ARAR Didier",84],[31,"BRAJON Bertrand",57],[32,"SCIACCA Aurélia",50],[33,"LOPES LELO Maria",5],[34,"FORESTIER David",33],[35,"HUET Jérôme",53],[36,"MARSURA Philippe",42],[37,"LINVAL Philippe",69],[38,"HERNOT Laurent",89],[39,"LAKAS Patrice",67],[40,"MARCHAND Eric",40],[41,"BOURNAT Thierry",38],[42,"CAMBONI Mario",25],[43,"BARICHARD Jérôme",47],[44,"SANSELME Philippe",87],[45,"ANDRE Serge",71],[46,"CARTON Noël",24],[47,"PETITJEAN Rémy",64],[48,"TEISSEDRE Christian",37],[49,"AMY Jérôme",99],[50,"MOYNAULT Christophe",35],[51,"VéNIANT Romu",92],[52,"LEBIGUE Tristan",88],[53,"JUGE Fabrice",26],[54,"VINCENT Jérémy",90],[55,"IVART Yann",30],[56,"DESJOUR Patrick",70],[57,"GALLON Fabrice",77],[58,"GUYOT Jean-joseph",27],[59,"CHATARD Benoit",80],[60,"ROUX Claude",9],[61,"KOWALSKI Dany",63],[62,"PERRETTE Christophe",34],[63,"DUBOURDIEU Stephane",81],[64,"LAMBERT Guillaume",54],[65,"FAMBRINI Cyril",52],[66,"MOUNIER Christian",72],[67,"BROSSARD Remy",13],[68,"FOUQUET Arnaud",94],[69,"ARNAUD Christian",44]];
var liste2 = [[70,"MOSNIER Bernard",55],[71,"BERGERET Lise",8],[72,"BERGERET Christophe",7],[73,"LEFEBVRE Michel",91],[74,"FLEURY Stephanie",15],[75,"AUBARD Nicolas",74],[76,"VALLEE Nelly",45],[77,"BERNABEU Julien",73],[78,"DUPRé Alain",78],[79,"SALIGNAT Jean-claude",4],[80,"VOLAT Marc",21],[81,"BENIGAUD Sylviane",18],[82,"LEPAIN Laurent",22]];
for (i=0; i!=liste.length; i++) {
document.getElementById('liste').innerHTML += '<tr><td>'+liste[i][2]+'</td><td>'+liste[i][1]+'</td><td>'+liste[i][0]+'</td></tr>';
}
for (y=0; y!=liste2.length; y++) {
document.getElementById('liste').innerHTML += '<tr><td>'+liste2[y][2]+'</td><td>'+liste2[y][1]+'</td><td>'+liste2[y][0]+'</td></tr>';
}
}
|
JavaScript
| 0 |
@@ -1,37 +1,4 @@
-function AfficherClassement() %7B%0A%0A
%09var
@@ -2108,199 +2108,105 @@
;%0A%0A%09
-for (i=0; i!=liste.length; i++) %7B%0A%09%09document.getElementById('liste').innerHTML += '%3Ctr%3E%3Ctd%3E'+liste%5Bi%5D%5B2%5D+'%3C/td%3E%3Ctd%3E'+liste%5Bi%5D%5B1%5D+'%3C/td%3E%3Ctd%3E'+liste%5Bi%5D%5B0%5D+'%3C/td%3E%3C/tr%3E';%0A%09%7D%0A
+var listeglobal = liste.concat(liste2);%0A%0Afunction AfficherClassement() %7B
%0A%09for (
-y
+i
=0;
-y!=
+i%3C
liste
-2
+global
.len
@@ -2210,17 +2210,17 @@
length;
-y
+i
++) %7B%0A%09%09
@@ -2285,14 +2285,19 @@
iste
-2%5By%5D%5B2
+global%5Bi%5D%5B0
%5D+'%3C
@@ -2311,19 +2311,24 @@
%3E'+liste
-2%5By
+global%5Bi
%5D%5B1%5D+'%3C/
@@ -2345,14 +2345,19 @@
iste
-2%5By%5D%5B0
+global%5Bi%5D%5B2
%5D+'%3C
|
4cd9ed14cd42f9596af8e66c129926a9186abb6d
|
add keyDownListener - listener is working and moving snake node, but making large jumps and not maintaining new direction
|
lib/index.js
|
lib/index.js
|
const $ = require('jquery');
const Board = require('./board.js')
const Snake = require('./snake.js')
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext('2d');
let board = new Board(canvas, ctx);
let snake = new Snake();
function animate() {
requestAnimationFrame(function gameLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
snake.draw();
snake.moveLeft;
if (snake.wallDetection === true) {
} else {
requestAnimationFrame(gameLoop);
}
}
)};
animate();
|
JavaScript
| 0 |
@@ -304,24 +304,47 @@
ameLoop() %7B%0A
+ keyDownListener();%0A
ctx.clea
@@ -402,24 +402,27 @@
.draw();%0A
+ //
snake.moveL
@@ -424,12 +424,12 @@
move
-Left
+Down
;%0A
@@ -532,16 +532,415 @@
%7D%0A)%7D;%0A
+%0Afunction keyDownListener() %7B%0A $(document).keydown(function(e) %7B%0A if (e.keyCode === 37) %7B%0A console.log(%22Left%22)%0A snake.moveLeft;%0A %7D else if (e.keyCode == 38) %7B%0A console.log(%22Up%22)%0A snake.moveUp;%0A %7D else if (e.keyCode == 39) %7B%0A console.log(%22Right%22)%0A snake.moveRight;%0A %7D else if (e.keyCode = 40) %7B%0A console.log(%22Down%22)%0A snake.moveDown;%0A %7D%0A %7D)%0A%7D%0A%0A
animate(
|
10948eda639312dceffeb090248d6b817a6fc620
|
add Store
|
base.js
|
base.js
|
import h from 'virtual-dom/h'
import diff from 'virtual-dom/diff'
import patch from 'virtual-dom/patch'
import createElement from 'virtual-dom/create-element'
let debug = false;
class Thunk {
constructor(renderFn, state, shouldUpdate, name) {
this.type = 'Thunk';
this.renderFn = renderFn;
this.state = state;
this.shouldUpdate = shouldUpdate;
this.name = name;
}
render(previous) {
var previousState = previous ? previous.state : null;
if (this.shouldUpdate(this.state, previousState)) {
if (debug) {
console.log('call render of ', this.name);
}
return this.renderFn(this.state);
}
return previous.vnode;
}
}
export class Component {
constructor(state) {
this.thunk = this.newThunk(state);
}
newThunk(state) {
return new Thunk((state) => {
let Hook = function(){}
Hook.prototype.hook = (element) => {
this.element = element;
this.elementChanged(element);
};
let vnode = h(this.constructor.name, {
'element-changed': new Hook(),
}, [this.render(state)]);
return vnode;
}, state, this.shouldUpdate.bind(this), this.constructor.name);
}
// abstract
render(state) {
return h();
}
bind(parent) {
this.element = createElement(this.thunk);
parent.appendChild(this.element);
}
// abstract
reduce(state, type, data) {
return state;
}
emit(type, data) {
let newState = this.reduce(this.thunk.state, type, data);
let newThunk = this.newThunk(newState);
let patches = diff(this.thunk, newThunk);
this.element = patch(this.element, patches);
this.thunk = newThunk;
}
// abstract
elementChanged(element) {
if (debug) {
console.log('element changed', this.constructor.name);
}
}
boundedEqual(a, b, n) {
if (a === b) {
return true;
}
if (n == 0) {
return a === b;
}
let aType = typeof a;
let bType = typeof b;
if (aType != bType) {
return false;
}
switch (aType) {
case 'object':
let aKeys = Object.keys(a);
let bKeys = Object.keys(b);
if (aKeys.length != bKeys.length) {
return false;
}
let len = aKeys.length;
for (let i = 0; i < len; i++) {
let key = aKeys[i];
if (!this.boundedEqual(a[key], b[key], n - 1)) {
if (key.slice(0, 1) == 'on' && typeof a[key] == 'function' && typeof b[key] == 'function') {
continue; // skip event handlers
}
return false;
}
}
return true;
default:
return this.boundedEqual(a, b, n - 1);
}
}
// abstract
shouldUpdate(state, previousState) {
if (previousState === undefined && state === undefined) {
// no state
return false;
}
if (!previousState || !state) {
return true;
}
return !this.boundedEqual(state, previousState, 2);
}
}
export function e(selector, properties, children) {
switch (typeof selector) {
case 'string':
return h(selector, properties, children);
default:
return new selector(properties).thunk;
}
}
export var none = h('div', { style: { display: 'none' } });
export var clear = h('div', { style: { clear: 'both' } });
export function div(...subs) {
return h('div', {}, [...subs]);
}
export function merge(a, b) {
let aType = typeof a;
let bType = typeof b;
if (aType == 'object' && bType == 'object') {
let obj = {};
if (b['>_<']) {
for (let key in a) {
obj[key] = merge(a[key], b['>_<']);
}
} else {
for (let key in b) {
if (a[key]) {
obj[key] = merge(a[key], b[key]);
} else {
obj[key] = b[key];
}
}
for (let key in a) {
if (key in obj) {
continue
}
obj[key] = a[key];
}
}
return obj;
} else {
return b;
}
}
/*
console.log(merge({
categories: {
1: {
dishes: {
1: {
selected: 5,
},
},
weekly_dishes: {
1: {
selected: 5,
},
},
},
2: {
dishes: {
1: {
selected: 5,
},
},
weekly_dishes: {
1: {
selected: 5,
},
},
},
},
}, {
categories: {
'>_<': {
dishes: {
'>_<': {
selected: 0,
},
},
weekly_dishes: {
'>_<': {
selected: 0,
},
},
},
},
}));
*/
|
JavaScript
| 0.000002 |
@@ -1349,155 +1349,28 @@
%0A%0A
-// abstract%0A reduce(state, type, data) %7B%0A return state;%0A %7D%0A%0A emit(type, data) %7B%0A let newState = this.reduce(this.thunk.state, type, data);
+setState(newState) %7B
%0A
@@ -1533,24 +1533,79 @@
Thunk;%0A %7D%0A%0A
+ setStore(store) %7B%0A store.setComponent(this);%0A %7D%0A%0A
// abstrac
@@ -2845,24 +2845,385 @@
2);%0A %7D%0A%7D%0A%0A
+export class Store %7B%0A constructor(initState, eventHandler) %7B%0A this.state = initState;%0A this.eventHandler = eventHandler;%0A %7D%0A%0A emit(type, data) %7B%0A this.state = this.eventHandler(this.state, type, data);%0A if (this.component) %7B%0A this.component.setState(this.state);%0A %7D%0A %7D%0A%0A setComponent(component) %7B%0A this.component = component;%0A %7D%0A%7D%0A%0A
export funct
|
467d5df5fef2fdb9979302b632097892f8302fdf
|
correct indentation
|
js/script.js
|
js/script.js
|
$('form').one("submit", function(event) {
event.preventDefault();
var send = $(this).serialize()
$.ajax({
type: 'GET',
url: './download.php',
data: send,
dataType: 'json',
success: function(obj) {
var value = obj[0];
$("ul").append("<li>" + "Demand for power is " + value.demand + "GW" + "</li>");
$("ul").append("<li>" + "Wind Power supplies " + value.wind + "GW" + "</li>");
$("ul").append("<li>" + "Wind Power accounts for around " + ((value.wind / value.demand) * 100).toFixed(2) + "%" + " of the total Energy Supply" + "</li>");
var wind = ((value.wind / value.demand) * 100).toFixed(2); // need this to be the output of our JSON func, ((value.wind / value.demand) * 100).toFixed(2)
if (wind <= 3) {
$('.rotor').css('-webkit-animation', 'rotate 40s infinite linear');
}
else if (wind > 3 && wind <= 8) {
$('.rotor').css('-webkit-animation', 'rotate 20s infinite linear');
}
else {
$('.rotor').css('-webkit-animation', 'rotate 2s infinite linear');
}
},
error: function() {
alert('Error');
}
});
});
$('#datetimepicker_start').datetimepicker({
format: 'unixtime'
});
$('#datetimepicker_end').datetimepicker({
format: 'unixtime'
});
|
JavaScript
| 0.003018 |
@@ -95,18 +95,17 @@
alize()%0A
-
+%0A
$.ajax
@@ -107,18 +107,16 @@
.ajax(%7B%0A
-
type
@@ -124,18 +124,16 @@
'GET',%0A
-
url:
@@ -151,26 +151,24 @@
d.php',%0A
-
data: send,%0A
@@ -167,18 +167,16 @@
: send,%0A
-
data
@@ -189,18 +189,16 @@
'json',%0A
-
succ
@@ -220,26 +220,24 @@
bj) %7B%0A
-
var value =
@@ -245,18 +245,16 @@
bj%5B0%5D;%0A%0A
-
@@ -334,34 +334,32 @@
/li%3E%22);%0A
-
$(%22ul%22).append(%22
@@ -425,26 +425,24 @@
%22);%0A
-
-
$(%22ul%22).appe
@@ -587,18 +587,16 @@
li%3E%22);%0A%0A
-
@@ -758,18 +758,16 @@
-
if (wind
@@ -777,34 +777,32 @@
3) %7B%0A
-
-
$('.rotor').css(
@@ -853,38 +853,34 @@
near');%0A
- %7D%0A
+%7D%0A
else if
@@ -901,26 +901,24 @@
ind %3C= 8) %7B%0A
-
$(
@@ -987,30 +987,26 @@
');%0A
- %7D%0A
+%7D%0A
else
@@ -1008,18 +1008,16 @@
else %7B%0A
-
@@ -1089,30 +1089,26 @@
');%0A
- %7D%0A
+%7D%0A
%7D,%0A
@@ -1104,18 +1104,16 @@
%7D,%0A
-
erro
@@ -1134,18 +1134,16 @@
%7B%0A
-
alert('E
@@ -1154,22 +1154,18 @@
');%0A
- %7D%0A
+%7D%0A
%7D);%0A%7D)
|
e451fe415fe99879601f3615150985ae25e3d406
|
Fix Syntax error
|
js/script.js
|
js/script.js
|
/*
Theme: Flatfy Theme
Author: Andrea Galanti
Bootstrap Version
Build: 1.0
http://www.andreagalanti.it
*/
$(window).load(function() {
//Preloader
$('#status').delay(300).fadeOut();
$('#preloader').delay(300).fadeOut('slow');
$('body').delay(550).css({'overflow':'visible'});
})
$(document).ready(function() {
//animated logo
$(".navbar-brand").hover(function () {
$(this).toggleClass("animated shake");
});
//animated scroll_arrow
$(".img_scroll").hover(function () {
$(this).toggleClass("animated infinite bounce");
});
//Wow Animation DISABLE FOR ANIMATION MOBILE/TABLET
wow = new WOW(
{
mobile: false
});
wow.init();
//MagnificPopup
$('.image-link').magnificPopup({type:'image'});
// OwlCarousel N1
$("#owl-demo").owlCarousel({
autoPlay: 3000,
items : 3,
itemsDesktop : [1199,3],
itemsDesktopSmall : [979,3]
});
// OwlCarousel N2
$("#owl-demo-1").owlCarousel({
navigation : false, // Show next and prev buttons
slideSpeed : 300,
paginationSpeed : 400,
singleItem:true
});
//SmothScroll
$('a[href*=#]').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
&& location.hostname == this.hostname) {
var $target = $(this.hash);
$target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
if ($target.length) {
var targetOffset = $target.offset().top;
$('html,body').animate({scrollTop: targetOffset}, 600);
return false;
}
}
});
//Subscribe
new UIMorphingButton( document.querySelector( '.morph-button' ) );
// for demo purposes only
[].slice.call( document.querySelectorAll( 'form button' ) ).forEach( function( bttn ) {
bttn.addEventListener( 'click', function( ev ) { ev.preventDefault(); } );
} );
});
|
JavaScript
| 0.000594 |
@@ -1099,16 +1099,18 @@
a%5Bhref*=
+%5C%5C
#%5D').cli
|
fdae693182931a05e90739eaa495e260ea134f4d
|
Create Staccato with string key.
|
base.js
|
base.js
|
var stream = require('stream')
var cadence = require('cadence')
var delta = require('delta')
var Destructible = require('destructible')
var interrupt = require('interrupt').createInterrupter('staccato')
function Staccato (stream, opening) {
this.stream = stream
this._destructible = new Destructible(interrupt)
this._listeners = {
open: this._open.bind(this),
error: this.destroy.bind(this)
}
this._destructible.markDestroyed(this)
this._delta = null
this._readable = false
if (opening) {
this._destructible.addDestructor('open', this, '_open')
} else {
this._open()
}
this.stream.once('error', this._listeners.error)
this._destructible.addDestructor('error', this, '_uncatch')
this.destroyed = false
}
Staccato.prototype._open = function () {
this.stream.removeListener('open', this._listeners.open)
this._opened = true
}
Staccato.prototype._uncatch = function () {
this.stream.removeListener('error', this._listeners.error)
}
Staccato.prototype._cancel = function () {
if (this._delta != null) {
this._delta.cancel([])
this._delta = null
}
}
Staccato.prototype.destroy = function () {
this._destructible.destroy()
}
Staccato.prototype.ready = cadence(function (async) {
interrupt.assert(!this.destroyed, 'destroyed')
if (!this._opened) {
async(function () {
this._destructible.invokeDestructor('open')
this._destructible.invokeDestructor('error')
this._destructible.addDestructor('delta', this, '_cancel')
this._delta = delta(async()).ee(this.stream).on('open')
}, function () {
this._delta = null
this._destructible.invokeDestructor('delta')
this.stream.once('error', this._listeners.error)
this._destructible.addDestructor('error', this, '_uncatch')
})
}
})
module.exports = Staccato
|
JavaScript
| 0 |
@@ -302,25 +302,26 @@
uctible(
-interrupt
+'staccato'
)%0A th
|
9f2d5d298b45eb4be5993663721e83f7949a12f4
|
disable browser on default call
|
gulpfile.js
|
gulpfile.js
|
/*!
* @author: Divio AG
* @copyright: http://www.divio.ch
*/
'use strict';
// #####################################################################################################################
// #IMPORTS#
var browserSync = require('browser-sync');
var cache = require('gulp-cached');
var gulp = require('gulp');
var gutil = require('gulp-util');
var imagemin = require('gulp-imagemin');
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');
var karma = require('karma').server;
var scsslint = require('gulp-scss-lint');
var yuidoc = require('gulp-yuidoc');
// #####################################################################################################################
// #SETTINGS#
var paths = {
'css': './site/static/css/',
'html': './site/templates/',
'images': './site/static/img/',
'js': './site/static/js/',
'sass': './site/private/sass/',
'docs': './site/static/docs',
'tests': './site/tests'
};
var patterns = {
'images': [
paths.images + '*',
paths.images + '**/*',
'!' + paths.images + 'dummy/*/**'
],
'js': [
paths.js + '*.js',
paths.js + '**/*.js',
paths.tests + '*.js',
'!' + paths.js + '*.min.js',
'!' + paths.js + '**/*.min.js'
],
'sass': [
paths.sass + '*',
paths.sass + '**/*',
'!' + paths.sass + 'libs/*.scss',
'!' + paths.sass + 'settings/*.scss',
'!' + paths.sass + 'layout/_print.scss'
]
};
patterns.jshint = patterns.js.concat(['!' + paths.js + 'libs/*.js', './gulpfile.js']);
var port = parseInt(process.env.PORT, 10) || 8000;
// #####################################################################################################################
// #LINTING#
gulp.task('lint', ['jslint', 'scsslint']);
gulp.task('jslint', function () {
gulp.src(patterns.jshint)
.pipe(jshint())
.pipe(jscs())
.on('error', function (error) {
gutil.log('\n' + error.message);
})
.pipe(jshint.reporter('jshint-stylish'));
});
gulp.task('scsslint', function () {
// DOCS: https://github.com/brigade/scss-lint/
gulp.src(patterns.sass)
.pipe(cache('scsslint'))
.pipe(scsslint({
'config': './scss-lint.json'
}));
// FIXME: tests currently pass even if there is a linting error, the reporter stops all remaining issues :(
// .pipe(scsslint.failReporter());
});
// #########################################################
// #PREPROCESSING#
gulp.task('preprocess', ['images', 'docs']);
gulp.task('images', function () {
var options = {
'interlaced': true,
'optimizationLevel': 5,
'progressive': true
};
gulp.src(patterns.images)
.pipe(cache(imagemin(options)))
.pipe(gulp.dest(paths.images)).on('error', function (error) {
gutil.log('\n' + error.message);
});
});
gulp.task('docs', function () {
gulp.src(patterns.js)
.pipe(yuidoc())
.pipe(gulp.dest(paths.docs));
});
// #########################################################
// #SERVICES#
gulp.task('browser', function () {
var files = [
paths.css + '*.css',
paths.html + '**/*.html',
paths.js + '**/*.js'
];
// DOCS: http://www.browsersync.io/docs/options/
setTimeout(function () {
browserSync.init(files, {
'proxy': '0.0.0.0:' + port,
'port': port + 1,
'ui': {
'port': port + 2
}
});
}, 1000);
});
// #########################################################
// #TESTS#
gulp.task('tests', ['lint'], function () {
// run javascript tests
karma.start({
'configFile': __dirname + '/.site/tests/karma.conf.js',
'singleRun': true
});
});
gulp.task('karma', function () {
// run javascript tests
karma.start({
'configFile': __dirname + '/.site/tests/karma.conf.js'
});
});
// #####################################################################################################################
// #COMMANDS#
gulp.task('watch', function () {
gulp.watch(patterns.jshint, ['lint']);
});
gulp.task('default', ['lint', 'browser', 'watch']);
|
JavaScript
| 0.000001 |
@@ -4245,19 +4245,8 @@
nt',
- 'browser',
'wa
|
2f5c2a17f6c421bf74cbd3a1c53170eed41ae72c
|
add story of FormSubmit
|
stories/form/form.stories.js
|
stories/form/form.stories.js
|
import React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
// import { linkTo } from '@storybook/addon-links';
import { Components } from 'meteor/vulcan:core';
import 'meteor/vulcan:forms';
import { withKnobs, boolean, text } from '@storybook/addon-knobs';
const vulcan_forms = storiesOf('Core/Forms/CoreComponents', module);
vulcan_forms.addDecorator(withKnobs);
vulcan_forms
.add('FormError - message', () => (
<Components.FormError
error={{
message: 'An error message',
}}
/>
))
.add('FormError intl - no properties', () => (
<Components.FormError
error={{
id: 'intl-id',
}}
/>
))
.add('FormError intl', () => (
<Components.FormError
error={{
id: 'intl-id',
properties: {
name: 'address.street',
},
}}
/>
));
vulcan_forms
.add('FormGroupHeader', () => {
const label = text('Header label', 'myLabel');
const collapsed = boolean('collapsed', false);
const hidden = boolean('hidden', false);
const hasErrors = boolean('hasErrors', false);
const textInside = text('Text inside', 'My text inside');
const groupName = text('Group name', 'admin');
const collapsible = boolean('collapsible', true);
const group = { name: [groupName], collapsible: collapsible };
return (
<div>
<Components.FormGroupHeader label={label} group={group} />
<Components.FormGroupLayout
label="labelInner"
anchorName="anchorNameInner"
collapsed={collapsed}
hidden={hidden}
hasErrors={hasErrors}
group={group}>
{textInside}
</Components.FormGroupLayout>
</div>
);
})
.add('FormGroupLine', () => {
const label = text('Header label', 'myLabel');
const collapsed = boolean('collapsed', false);
const hidden = boolean('hidden', false);
const hasErrors = boolean('hasErrors', false);
const textInside = text('Text inside', 'My text inside');
const groupName = text('Group name', 'admin');
const collapsible = boolean('collapsible', true);
const group = { name: [groupName], collapsible: collapsible };
return (
<div>
<Components.FormGroupHeaderLine label={label} group={group} />
<Components.FormGroupLayoutLine
label="labelInner"
anchorName="anchorNameInner"
collapsed={collapsed}
hidden={hidden}
hasErrors={hasErrors}
group={group}>
{textInside}
</Components.FormGroupLayoutLine>
</div>
);
})
.add('FormGroupNone', () => {
const collapsed = boolean('collapsed', false);
const hidden = boolean('hidden', false);
const hasErrors = boolean('hasErrors', false);
const textInside = text('Text inside', 'My text inside');
const groupName = text('Group name', 'admin');
const collapsible = boolean('collapsible', true);
const group = { name: [groupName], collapsible: collapsible };
return (
<div>
<Components.FormGroupHeaderNone />
<Components.FormGroupLayoutNone
label="labelInner"
anchorName="anchorNameInner"
collapsed={collapsed}
hidden={hidden}
hasErrors={hasErrors}
group={group}>
{textInside}
</Components.FormGroupLayoutNone>
</div>
);
});
vulcan_forms.add('FormNestedArrayLayout - nested item before/after components', () => (
<Components.FormNestedArray
value={[{ name: 'Jane' }, { name: 'DELETED' }, { name: 'John' }]}
deletedValues={['peoples.1']}
path="peoples"
formComponents={{
...Components,
FormNestedItem: () => (
<div>
<input />
</div>
),
}}
errors={[]}
updateCurrentValues={action('updateCurrentValues')}
arrayField={{
beforeComponent: props => (
<div>
BEFORE {props.itemIndex} {props.visibleItemIndex}
</div>
),
afterComponent: props => <div>AFTER</div>,
}}
/>
));
|
JavaScript
| 0 |
@@ -324,26 +324,25 @@
const vulcan
-_f
+F
orms = stori
@@ -386,26 +386,25 @@
ule);%0Avulcan
-_f
+F
orms.addDeco
@@ -420,34 +420,33 @@
hKnobs);%0A%0Avulcan
-_f
+F
orms%0A .add('For
@@ -894,26 +894,25 @@
));%0A%0Avulcan
-_f
+F
orms%0A .add(
@@ -3446,10 +3446,9 @@
lcan
-_f
+F
orms
@@ -4097,12 +4097,177 @@
%7D%7D%0A /%3E%0A));%0A
+%0AvulcanForms.add('FormSubmit', () =%3E %7B%0A const submitLabel = text('Submit Label', 'Submit Label');%0A return %3CComponents.FormSubmit submitLabel=%7BsubmitLabel%7D /%3E;%0A%7D);%0A
|
a109f4ee6d90d4b244cf309dda827867af2fbd17
|
update regex
|
lib/index.js
|
lib/index.js
|
"use strict";
var Crawler = require('crawler').Crawler,
url = require('url'),
regex = "/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi",
urls = [];
exports.VERSION = "0.0.7";
exports.Extractor = function(startUrl,callback,maxConnections){
var host = url.parse(startUrl).hostname;
var crawler = new Crawler({
"maxConnections": maxConnections || 10,
"callback" : function(err,result,$){
if (!err && result && result.headers && result.headers['content-type'].toLowerCase().indexOf("text/html") >= 0){
$("a").each(function(index,a){
if (url.parse(a.href).hostname === host && urls.indexOf(a.href) === -1){
crawler.queue(a.href);
urls.push(a.href);
}
});
($("body").html().match(regex) || []).forEach(function(email){
if (callback) callback(result.options.uri,email);
});
}
}
});
crawler.queue(startUrl);
}
|
JavaScript
| 0.000003 |
@@ -94,86 +94,8 @@
l'),
-%0A regex = %22/(%5Ba-zA-Z0-9._-%5D+@%5Ba-zA-Z0-9._-%5D+%5C.%5Ba-zA-Z0-9._-%5D+)/gi%22,
@@ -995,13 +995,62 @@
tch(
-regex
+/(%5Ba-zA-Z0-9._-%5D+@%5Ba-zA-Z0-9._-%5D+%5C.%5Ba-zA-Z0-9._-%5D+)/gi
) %7C%7C
|
8682141ce26540fbf4eb9a6201f86290cc66400d
|
drop database only if exists (first time run)
|
gulpfile.js
|
gulpfile.js
|
var gulp = require('gulp');
var mocha = require('gulp-mocha');
var shell = require('gulp-shell');
var jshint = require('gulp-jshint');
gulp.task('lint', function() {
return gulp.src(['./lib/**/*.js', './test/**/*.js'])
.pipe(jshint({ loopfunc: true, expr: true }))
.pipe(jshint.reporter('default'));
});
gulp.task('test:unit', ['lint'], function() {
return gulp.src([
'./test/helpers/*.js',
'./test/unit/*.js'
])
.pipe(mocha());
});
gulp.task('reset:db', shell.task(
[
'PGUSER=testdb PGPASSWORD=password psql -h localhost -p 15432 postgres -c "drop database testdb"',
'PGUSER=testdb PGPASSWORD=password psql -h localhost -p 15432 postgres -c "create database testdb with owner testdb"'
])
);
gulp.task('test:integration', ['lint', 'reset:db'], function() {
return gulp.src([
'./test/helpers/*.js',
'./test/integration/*.js'
])
.pipe(mocha());
});
gulp.task('test', [
'lint',
'test:unit',
'test:integration'
]);
|
JavaScript
| 0 |
@@ -580,24 +580,34 @@
op database
+if exists
testdb%22',%0A
|
d4f959175dd570cb1bd909ef66533c91cf6df0fd
|
Update script.js
|
js/script.js
|
js/script.js
|
(function(window, document, undefined) {
window.onload = init;
function init() {
//get the canvas
var canvas = document.getElementById("mapcanvas");
var c = canvas.getContext("2d");
var cwidth = 960;
var cheight = 540;
var moves = {
u: [0,-1],
d: [0,1],
l: [-1,0],
r: [1,0]
};
document.getElementById("paintbtn").onclick = paint;
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex ;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function reset(){
c.clearRect ( 0 , 0 , canvas.width, canvas.height );
c.beginPath();
}
function walk(start, stop){
var distX = stop.x - start.x;
var distY = stop.y - start.y;
var walkSteps = [];
for(var i = 0; i< Math.abs(distX); i++){
if(distX < 0){
walkSteps.push(moves.l);
} else {
walkSteps.push(moves.r);
}
}
for(var i = 0; i< Math.abs(distY); i++){
if(distY < 0){
walkSteps.push(moves.u);
} else {
walkSteps.push(moves.d);
}
}
var randSteps = 12;
for(var i = 0; i< randSteps; i++){
var rand =Math.floor(Math.random() * (2 - 1 + 1)) + 1;
if(rand < 1){
walkSteps.push(moves.u);
walkSteps.push(moves.d);
} else{
walkSteps.push(moves.l);
walkSteps.push(moves.r);
}
}
return shuffle(walkSteps);
}
function createRoom(x, y, pw, ph){
var randw = Math.floor((Math.random() * ((pw/2) - 1 + 1) + 1) );
var randh = Math.floor((Math.random() * ((ph/2) - 1 + 1) + 1) );
//alert(randw + ", " + randh);
return [randw, randh];
}
function paint(){
reset();
var widthSelect = document.getElementById("width");
var pathWidth = widthSelect.options[widthSelect.selectedIndex].value;
var heightSelect = document.getElementById("height");
var pathHeight = heightSelect.options[heightSelect.selectedIndex].value;
//alert(pathWidth + ", " + pathHeight);
for(var i = 0; i< pathWidth; i++){
for(var j = 0; j< pathHeight; j++){
c.beginPath();
//c.lineWidth = 1;
c.fillStyle = "#000000";
c.fillRect(i*30+0.5, j*30+0.5, 30, 30);
c.stroke();
}
}
var startpoint = {
x: 0,
y: 9
}
var endpoint = {
x: 9,
y: 0
}
var movingpoint = {
x: 0,
y: 9
}
var movingpointold = {
x: 0,
y: 9
}
var walkArray = walk(startpoint, endpoint);
for (var i = 0; i< walkArray.length; i++){
movingpoint.x = movingpoint.x + walkArray[i][0];
movingpoint.y = movingpoint.y + walkArray[i][1];
var oppcurrMoveX = -1 * walkArray[i][0];
var oppcurrMoveY = -1 * walkArray[i][1];
var index = -1;
for(var j = i; j< walkArray.length; j++){
if(walkArray[j][0] == oppcurrMoveX && walkArray[j][1] == oppcurrMoveY){
index = j;
break;
}
}
if(movingpoint.x > pathWidth -1){
movingpoint.x = movingpoint.x - 1;
if (index > -1) {
walkArray.splice(index, 1);
}
}
if(movingpoint.x < 0){
movingpoint.x = movingpoint.x + 1;
if (index > -1) {
walkArray.splice(index, 1);
}
}
if(movingpoint.y > pathHeight -1){
movingpoint.y = movingpoint.y - 1;
if (index > -1) {
walkArray.splice(index, 1);
}
}
if( movingpoint.y < 0){
movingpoint.y = movingpoint.y + 1;
if (index > -1) {
walkArray.splice(index, 1);
}
}
c.fillStyle = "#FFFFFF";
c.fillRect(movingpoint.x*30 + 0.5, movingpoint.y*30 + 0.5, 28, 28);
for(var j = movingpointold.x; j <= movingpoint.x; j++){
for(var k = movingpointold.y; k <= movingpoint.y; k++){
c.fillStyle = "#FFFFFF";
c.fillRect(j*30 + 14.5, k*30 + 14.5, 2, 2);
}
}
movingpointold.x = movingpoint.x;
movingpointold.y = movingpoint.y;
}
/*
for(var i = 0; i< Math.floor(pathWidth/2)+1; i++){
for(var j = 0; j< Math.floor(pathHeight/2)+1; j++){
var randRoom = Math.floor((Math.random() * 9));
if(randRoom < 1){
roomDim = createRoom(i,j,pathWidth,pathHeight);
c.beginPath();
c.lineWidth = 3;
c.fillStyle = "#FFFFFF";
c.fillRect(i*30 + 0.5, j*30+ 0.5, roomDim[0]*30, roomDim[1]*30);
c.stroke();
}
}
}*/
c.fillStyle = "#33CC33";
c.fillRect(startpoint.x*30 + 0.5, startpoint.y*30 + 0.5, 30, 30);
c.fillStyle = "#CC0000";
c.fillRect(endpoint.x*30 +0.5, endpoint.y*30 +0.5, 30 ,30);
}
}
})(window, document, undefined);
|
JavaScript
| 0.000002 |
@@ -5487,115 +5487,8 @@
-c.fillStyle = %22#FFFFFF%22;%0A c.fillRect(movingpoint.x*30 + 0.5, movingpoint.y*30 + 0.5, 28, 28);
%0A
@@ -5789,36 +5789,156 @@
%0A
+%7D%0A
+ c.fillStyle = %22#FFFFFF%22;%0A c.fillRect(movingpoint.x*30 + 0.5, movingpoint.y*30 + 0.5, 28, 28);
%0A
@@ -5929,33 +5929,32 @@
%0A
-%7D
%0A
|
435934eae43f977adaa23c74067f44b939e096e2
|
handle a few more scenarios
|
test/scale-factor-test.js
|
test/scale-factor-test.js
|
var test = require('tape');
var calculateScaleFactor = require('../').calculateScaleFactor;
test('returns 0.5 for value in middle', function (t) {
t.plan(1);
var scaleFactor = calculateScaleFactor(4, 8, 6);
t.equals(scaleFactor, 0.5);
});
test('returns 0 for value on min', function (t) {
t.plan(1);
var scaleFactor = calculateScaleFactor(4, 8, 4);
t.equals(scaleFactor, 0);
});
test('returns 1 for value on max', function (t) {
t.plan(1);
var scaleFactor = calculateScaleFactor(4, 8, 8);
t.equals(scaleFactor, 1);
});
test('handles value above middle, below max', function (t) {
t.plan(1);
var scaled = calculateScaleFactor(4, 8, 7);
t.equals(scaled, 0.75);
});
test('handles value below middle, above min', function (t) {
t.plan(1);
var scaleFactor = calculateScaleFactor(4, 8, 5);
t.equals(scaleFactor, 0.25);
});
test('returns 0 for value below min', function (t) {
t.plan(1);
var scaled = calculateScaleFactor(4, 8, 3);
t.equals(scaled, 0);
});
test('returns 1 for value above max', function (t) {
t.plan(1);
var scaled = calculateScaleFactor(4, 8, 9);
t.equals(scaled, 1);
});
|
JavaScript
| 0.000002 |
@@ -1131,16 +1131,305 @@
scaled, 1);%0A%7D);%0A
+%0Atest('throws Error when max is equal to min', function (t) %7B%0A t.plan(1);%0A%0A t.throws(function () %7B%0A calculateScaleFactor(4, 4, 9);%0A %7D);%0A%7D);%0A%0Atest('throws Error when max is below min', function (t) %7B%0A t.plan(1);%0A%0A t.throws(function () %7B%0A calculateScaleFactor(4, 4, 3);%0A %7D);%0A%7D);%0A
|
11d065d9cbbbaef137033d6fdc924284daecd7d4
|
Fix up linter and flow warnings
|
src/pages/EditorialPage.js
|
src/pages/EditorialPage.js
|
// @flow
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { editorials } from '../actions/editorials'
import StreamContainer from '../containers/StreamContainer'
import { MainView } from '../components/views/MainView'
import { selectQueryPreview } from '../selectors/routing'
import { getQueryParamValue } from '../helpers/uri_helper'
import { media } from '../styles/jss'
import { maxBreak2 } from '../styles/jso'
const streamStyle = media(maxBreak2, {
paddingLeft: '0 !important',
paddingRight: '0 !important',
})
const mapStateToProps = (state) => ({
isPreview: selectQueryPreview(state) === 'true',
})
class EditorialPage extends Component {
shouldComponentUpdate() {
return false
}
render() {
return (
<MainView className="Editorial">
<StreamContainer
action={editorials(this.props.isPreview)}
className={`${streamStyle}`}
shouldInfiniteScroll={false}
/>
</MainView>
)
}
}
export default connect(mapStateToProps)(EditorialPage)
|
JavaScript
| 0.000001 |
@@ -310,67 +310,8 @@
ng'%0A
-import %7B getQueryParamValue %7D from '../helpers/uri_helper'%0A
impo
@@ -517,23 +517,21 @@
Props =
-(
state
-)
=%3E (%7B%0A
@@ -584,16 +584,56 @@
e',%0A%7D)%0A%0A
+type Props = %7B%0A isPreview: boolean,%0A%7D%0A%0A
class Ed
@@ -664,16 +664,32 @@
onent %7B%0A
+ props: Props%0A%0A
should
|
a6bd24ad0239e869c62a4ba1eabd5a3c1eabcf88
|
update documentFormatter
|
sashimi-webapp/src/logic/formatter/documentFormatter.js
|
sashimi-webapp/src/logic/formatter/documentFormatter.js
|
const documentFormatter = {
format: function format(data) {
return "Document formatted! Ready for display!";
},
};
module.exports = documentFormatter;
|
JavaScript
| 0 |
@@ -1,123 +1,320 @@
-const documentFormatter = %7B%0A format: function format(data) %7B%0A return %22D
+// Import module%0Aconst EventEmitter2 = require('eventemitter2');%0A%0Aconst documentFormatter = new EventEmitter2();%0Alet content = '';%0A%0AdocumentFormatter.set = function set(newContent) %7B%0A content = newContent;%0A d
ocument
- f
+F
ormatte
-d! Ready for display!%22;%0A %7D,
+r.emit('changed', content);%0A%7D;%0A%0AdocumentFormatter.get = function get() %7B%0A return content;
%0A%7D;%0A
|
60b63ed74b6c25498711e5da3557f09586ad8afc
|
Bump version to 2.5.0, #10
|
assets/frontend.min.js
|
assets/frontend.min.js
|
!function(o,e){"use strict";function n(){var n=Math.max(e.documentElement.clientWidth,o.innerWidth||0),i=new google.maps.LatLng(parseFloat(a.map.lat),parseFloat(a.map.lng)),r={zoomControl:!a.controls.zoomControl,zoomControlOptions:{position:google.maps.ControlPosition.RIGHT_CENTER},mapTypeControl:!a.controls.mapTypeControl,streetViewControl:!a.controls.streetViewControl,scrollwheel:!a.mobile.scrollwheel,draggable:n>480||!t(),center:i,zoom:parseInt(a.map.zoom),mapTypeId:google.maps.MapTypeId[a.map.type],mapTypeControlOptions:{style:google.maps.MapTypeControlStyle.DROPDOWN_MENU,position:google.maps.ControlPosition.TOP_LEFT},styles:a.map.styles,fullscreenControl:!a.controls.fullscreenControl,fullscreenControlOptions:{position:google.maps.ControlPosition.RIGHT_TOP},gestureHandling:a.mobile.gestureHandling||"auto"},s=new google.maps.Map(l,r);if(1===a.marker.enabled){var m=new google.maps.Marker({position:i,map:s,optimized:!1,title:a.marker.title,icon:a.marker.file||a.marker.color||""});if("NONE"!==a.marker.animation&&m.setAnimation(google.maps.Animation[a.marker.animation]),1===a.info_window.enabled){var p=new google.maps.InfoWindow({content:a.info_window.text});google.maps.event.addListener(s,"click",function(){p.close()})}}1===a.marker.enabled&&1===a.info_window.enabled&&(google.maps.event.addListener(m,"click",function(){p.open(s,m),m.setAnimation(null)}),1===a.info_window.state&&o.setTimeout(function(){p.open(s,m),m.setAnimation(null)},2e3));var g;google.maps.event.addDomListener(o,"resize",function(){g&&clearTimeout(g),g=o.setTimeout(function(){s.setCenter(i)},300)})}function t(){return"ontouchstart"in o||navigator.maxTouchPoints}var a=o._agmOpt,l=e.getElementById("agm-canvas");"undefined"!=typeof l&&l&&("object"==typeof google&&google.maps?google.maps.event.addDomListener(o,"load",n):(l.innerHTML='<p class="map-not-loaded" style="text-align: center">Failed to load Google Map.<br>Please try again.</p>',l.style.height="auto"))}(window,document);
|
JavaScript
| 0 |
@@ -96,17 +96,17 @@
dth%7C%7C0),
-i
+r
=new goo
@@ -166,17 +166,17 @@
p.lng)),
-r
+s
=%7BzoomCo
@@ -429,17 +429,17 @@
,center:
-i
+r
,zoom:pa
@@ -815,17 +815,17 @@
%22auto%22%7D,
-s
+m
=new goo
@@ -841,11 +841,11 @@
Map(
-l,r
+i,s
);if
@@ -871,17 +871,17 @@
ed)%7Bvar
-m
+p
=new goo
@@ -910,15 +910,15 @@
ion:
-i
+r
,map:
-s
+m
,opt
@@ -1021,17 +1021,17 @@
mation&&
-m
+p
.setAnim
@@ -1102,33 +1102,33 @@
ow.enabled)%7Bvar
-p
+g
=new google.maps
@@ -1199,17 +1199,17 @@
istener(
-s
+m
,%22click%22
@@ -1220,17 +1220,17 @@
ction()%7B
-p
+g
.close()
@@ -1305,33 +1305,33 @@
ent.addListener(
-m
+p
,%22click%22,functio
@@ -1330,37 +1330,37 @@
,function()%7B
-p
+g
.open(
-s,m),m
+m,p),p
.setAnimatio
@@ -1422,21 +1422,21 @@
n()%7B
-p
+g
.open(
-s,m),m
+m,p),p
.set
@@ -1462,17 +1462,17 @@
3));var
-g
+d
;google.
@@ -1519,17 +1519,17 @@
ction()%7B
-g
+d
&&clearT
@@ -1539,12 +1539,12 @@
out(
-g),g
+d),d
=o.s
@@ -1564,17 +1564,17 @@
ction()%7B
-s
+m
.setCent
@@ -1576,17 +1576,17 @@
tCenter(
-i
+r
)%7D,300)%7D
@@ -1586,16 +1586,91 @@
%7D,300)%7D)
+,l.map=m,l.marker=p,l.infoWindow=g,o.dispatchEvent(new Event(%22agm.loaded%22))
%7Dfunctio
@@ -1744,16 +1744,27 @@
gmOpt,l=
+o.AGM=%7B%7D,i=
e.getEle
@@ -1810,12 +1810,12 @@
eof
-l&&l
+i&&i
&&(%22
@@ -1896,17 +1896,17 @@
ad%22,n):(
-l
+i
.innerHT
@@ -2015,17 +2015,17 @@
n.%3C/p%3E',
-l
+i
.style.h
|
0a5e07ff167547d6a17132379bf72df292fca41d
|
Update skipBinding.js
|
bindings/skipBinding.js
|
bindings/skipBinding.js
|
ko.bindingHandlers.skipBinding = {
init: function() {
return { controlsDescendantBindings: true };
}
}
ko.virtualElements.allowedBindings.skipBinding = true;
|
JavaScript
| 0.000001 |
@@ -1,8 +1,122 @@
+/**%0A * Tell Knockout to Skip Binding.%0A * @see http://www.knockmeout.net/2012/05/quick-tip-skip-binding.html%0A **/%0A
ko.bindi
|
b1d3386a9dda7a4bfea19356014b00ac2e2c5319
|
fix jshint warnings
|
management_frontend/src/data/index.js
|
management_frontend/src/data/index.js
|
/*jshint -W097 */
'use strict';
/* globals fetch */
// TODO: caching
function check200(resp) {
if (resp.status >= 200 && resp.status < 300) {
return resp;
} else {
var err = new Error(resp.statusText);
err.response = resp;
throw err;
}
}
var changes = {
/*jshint -W119 */
get: function(id) {
if (!id || id.trim() === '') {
return new Promise((res, rej) => {
rej(new Error('No id specified'));
});
} else {
return fetch(`/api/changes/${id}`,
{ credentials: 'same-origin' })
.then(r => r.json());
}
},
/*jshint +W119 */
getWeek: function() {
return fetch('/api/changes/week',
{ credentials: 'same-origin' })
.then(check200)
/*jshint -W119 */
.then(r => r.json());
/*jshint +W119 */
},
getAll: function(cursor) {
var p;
/*jshint -W119 */
if (cursor) {
p = fetch(`/api/changes/all?cursor=${cursor}`,
{ credentials: 'same-origin' });
/*jshint +W119 */
} else {
p = fetch('/api/changes/all',
{ credentials: 'same-origin' });
}
return p
.then(check200)
/*jshint -W119 */
.then(r => r.json());
/*jshint +W119 */
},
/*jshint -W119 */
delete: function(id) {
if (!id || id.trim() === '') {
return new Promise((res, rej) => {
rej(new Error('No id specified'));
});
} else {
return fetch(`/api/changes/${id}`,
{ method: 'delete', credentials: 'same-origin' })
.then(r => r.json());
}
},
/*jshint +W119 */
input: function(data) {
return fetch('/api/changes',
{ method: 'post', credentials: 'same-origin',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data) })
/*jshint -W119 */
.then(r => r.json());
/*jshint +W119 */
}
};
var timetables = {
getForClass: function(forClass) {
if (!forClass || forClass.trim() === '') {
return new Promise((res, rej) => {
rej(new Error('No class specified'))
})
} else {
return fetch(`/api/timetables/for_class/${forClass}`,
{ credentials: 'same-origin' })
.then(check200)
.then(r => r.json());
}
},
getAll: function(cursor) {
var p;
if (cursor) {
p = fetch(`/api/timetables/all?cursor=${cursor}`,
{ credentials: 'same-origin' });
} else {
p = fetch('/api/timetables/all', { credentials: 'same-origin' });
}
return p
.then(check200)
.then(r => r.json());
},
input: function(data) {
return fetch('/api/timetables',
{ method: 'post', credentials: 'same-origin',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data) })
.then(r => r.json());
}
}
module.exports = {
changes: changes,
timetables: timetables
};
|
JavaScript
| 0.000001 |
@@ -41,16 +41,25 @@
ls fetch
+, Promise
*/%0A%0A//
@@ -2182,24 +2182,46 @@
etables = %7B%0A
+ /*jshint -W119 */%0A
getForCl
@@ -2242,24 +2242,24 @@
forClass) %7B%0A
-
if (
@@ -2396,16 +2396,17 @@
ified'))
+;
%0A
@@ -2412,16 +2412,17 @@
%7D)
+;
%0A
@@ -2624,32 +2624,54 @@
%7D%0A %7D,%0A
+ /*jshint +W119 */%0A
getAll: func
@@ -2975,32 +2975,62 @@
.then(check200)%0A
+ /*jshint -W119 */%0A
.the
@@ -3043,24 +3043,54 @@
r.json());%0A
+ /*jshint +W119 */%0A
%7D,%0A i
@@ -3305,32 +3305,58 @@
ingify(data) %7D)%0A
+ /*jshint -W119 */%0A
.the
@@ -3373,23 +3373,50 @@
son());%0A
+ /*jshint +W119 */%0A
%7D%0A
-
%7D
+;
%0A%0Amodule
|
23c1df7cf7ab242a90ab4738721e9f29ffa8e15d
|
Update quick-example.js
|
docs/examples/quick-example.js
|
docs/examples/quick-example.js
|
'use strict'
var Seneca = require('../../')
// Functionality in seneca is composed into simple
// plugins that can be loaded into seneca instances.
function rejector () {
this.add('cmd:run', (msg, done) => {
return done(null, {tag: 'rejector'})
})
}
function approver () {
this.add('cmd:run', (msg, done) => {
return done(null, {tag: 'approver'})
})
}
function local () {
this.add('cmd:run', function (msg, done) {
this.prior(msg, (err, reply) => {
return done(null, {tag: reply ? reply.tag : 'local'})
})
})
}
// Services can listen for messages using a variety of
// transports. In process and http are included by default.
Seneca()
.use(approver)
.listen({type: 'http', port: '8260', pin: 'cmd:*'})
Seneca()
.use(rejector)
.listen(8270)
// Load order is important, messages can be routed
// to other services or handled locally. Pins are
// basically filters over messages
function handler (err, reply) {
console.log(err, reply)
}
Seneca()
.use(local)
.act('cmd:run', handler)
Seneca()
.client({port: 8270, pin: 'cmd:run'})
.client({port: 8260, pin: 'cmd:run'})
.use(local)
.act('cmd:run', handler)
Seneca()
.client({port: 8260, pin: 'cmd:run'})
.client({port: 8270, pin: 'cmd:run'})
.use(local)
.act('cmd:run', handler)
// Output
// null { tag: 'none' }
// null { tag: 'approver' }
// null { tag: 'rejector' }
|
JavaScript
| 0.000001 |
@@ -1332,12 +1332,13 @@
g: '
-none
+local
' %7D%0A
|
592b25069183e8e5fa23b730897c2b9256248187
|
refactor run
|
src/run.js
|
src/run.js
|
'use strict';
const cp = require('child_process');
const denodeify = require('denodeify');
const debug = require('debug')('ember-cli-update');
module.exports = async function run(command, options) {
debug(command);
let result = (await denodeify(cp.exec)(command, options)).toString();
debug(result);
return result;
};
|
JavaScript
| 0.000003 |
@@ -14,18 +14,25 @@
%0A%0Aconst
-cp
+denodeify
= requi
@@ -39,21 +39,17 @@
re('
-child_process
+denodeify
');%0A
@@ -49,24 +49,31 @@
ify');%0Aconst
+ exec =
denodeify =
@@ -62,35 +62,33 @@
exec = denodeify
- =
+(
require('denodei
@@ -76,34 +76,44 @@
fy(require('
-denodeify'
+child_process').exec
);%0Aconst deb
@@ -256,26 +256,12 @@
ait
-denodeify(cp.
exec
-)
(com
|
f3d8d90617926acdce3633114e560c7c9c05d33f
|
Add markdown filter for Swig
|
helpers/swig.js
|
helpers/swig.js
|
'use strict';
//////////////////////////////
// Variables
//////////////////////////////
var swig = require('swig'),
path = require('path'),
fs = require('fs-extra');
var ibmColors = fs.readJSONSync(process.cwd() + '/bower_components/ibm-colors/ibm-colors.json');
//////////////////////////////
// Pattern Swig Tag
//////////////////////////////
var swigPatternTag = {
parse: function (str, line, parser, types, options) {
// Start of a parse
parser.on('start', function () {
});
// Match of any token
parser.on('*', function (token) {
if (token.type !== 0 && token.match !== 'from') {
this.out.push(token.match)
}
});
// End of parse
parser.on('end', function () {
this.out.push(options.filename || null);
});
// Parser is good to go
return true;
},
compile: function (compiler, args) {
var file = '"patterns/' + args[1] + '/' + args[0] + '/' + args[0] + '.html"',
pattern = 'pattern ' + args[0] + ' from ' + args[1];
return '_output += "\\n<!-- {% ' + pattern + ' %} -->\\n" + _swig.compileFile(' + file + ')(_ctx) + "<!-- {% end ' + pattern + ' %} -->\\n";\n';
},
ends: false
}
swig.setTag(
'pattern',
swigPatternTag.parse,
swigPatternTag.compile,
swigPatternTag.ends
);
//////////////////////////////
// Color Filters
//////////////////////////////
var getIBMColor = function getIBMColor (palette, tint) {
palette = palette.toLowerCase();
return ibmColors[palette][tint];
}
swig.setFilter('ibmTextColor', function (tint) {
if (tint === 'core' || tint >= 50) {
return getIBMColor('white', 'core');
}
else {
return getIBMColor('gray', 90);
}
});
swig.setFilter('ibmSass', function (palette, tint) {
if (typeof tint === 'string' && tint.toLowerCase() === 'core') {
tint = ''
}
else {
tint = ', ' + tint;
}
return 'color(\'' + palette.toLowerCase() + '\'' + tint + ')';
});
swig.setFilter('ibmHex', function (palette, tint) {
return getIBMColor(palette, tint);
});
swig.setFilter('ibmRGB', function (palette, tint) {
var hex = getIBMColor(palette, tint),
r, g, b;
hex = hex.substr(1);
if (hex.length === 3) {
r = parseInt(hex[0] + '' + hex[0], 16);
g = parseInt(hex[1] + '' + hex[1], 16);
b = parseInt(hex[2] + '' + hex[2], 16);
}
else if (hex.length === 6) {
r = parseInt(hex.substr(0, 2), 16);
g = parseInt(hex.substr(2, 2), 16);
b = parseInt(hex.substr(4, 2), 16);
}
else {
throw new Error('Invalid Hex color ' + hex);
}
return 'rgb(' + r + ', ' + g + ', ' + b + ')';
});
//////////////////////////////
// File Types
//////////////////////////////
var getFileExtension = function getFileExtension(file) {
return path.extname(file).replace('.', '');
}
swig.setFilter('fileExtension', function (file) {
return getFileExtension(file);
});
swig.setFilter('fileType', function (file) {
var ext = getFileExtension(file);
if (ext !== 'webm' && ext !== 'mp4') {
return 'image';
}
else {
return 'video';
}
});
//////////////////////////////
// Export Swig
//////////////////////////////
module.exports = swig;
|
JavaScript
| 0 |
@@ -135,24 +135,60 @@
re('path'),%0A
+ marked = require('./markdown'),%0A
fs = req
@@ -3078,24 +3078,178 @@
';%0A %7D%0A%7D);%0A%0A
+//////////////////////////////%0A// Markdown Filter%0A//////////////////////////////%0Aswig.setFilter('markdown', function (text) %7B%0A return marked(text);%0A%7D);%0A%0A
////////////
|
0d93d7755151d85e4f9528914aa1f77e8c0eed4d
|
set expiry on S3 objects to prevent 24 hour cache allowing quicker updates
|
lambdas/src/admin/upload_post.js
|
lambdas/src/admin/upload_post.js
|
// uploadPost
var co = require('co');
var shortid = require('shortid');
shortid.characters('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$@');
var moment = require('moment');
var getSlug = require('speakingurl');
var AWS = require('aws-sdk');
var docClient = new AWS.DynamoDB.DocumentClient();
var s3 = new AWS.S3({
signatureVersion: 'v4'
});
var auth = require('../../lib/auth.js');
exports.handler = (event, context, callback) => {
// STAGE VARIABLES FROM API GATEWAY
var stage = event.stage;
var signing_key = event.signing_key;
var cookie = event.cookie;
var token_name = event.token_name;
var stage_articles_bucket = event.articles_bucket;
var stage_articles_bucket_path = event.articles_bucket_path;
var stage_posts_table = event.posts_table;
var post_id = event.post_id;
var post_status = event.post_status;
var title = event.title;
var categories = event.categories;
var date = event.date;
var html = event.html;
var articles_bucket = new AWS.S3({params: {Bucket: stage_articles_bucket}});
co(function *(){
var user = yield auth(signing_key, cookie, token_name);
if(!date){
date = moment().valueOf();
}else{
date = moment(date).valueOf();
}
if(!post_id){ // NEW POST
post_id = yield addBlogPostToDB(title, date, categories, post_status);
}else{
var old_post = yield getBlogPostFromDB(post_id);
console.log(old_post);
yield updateBlogPostInDB(old_post.post_id, old_post.date, title, date, categories, post_status);
}
yield addBlogPostToS3(post_id, html);
callback(null, {status: 'success'});
}).catch(onerror);
function getBlogPostFromDB(post_id){
console.log("getBlogPostFromDB");
return new Promise(function(resolve, reject){
var params = {
TableName: stage_posts_table,
KeyConditionExpression: "post_id = :post_id",
ExpressionAttributeValues: {
":post_id": post_id
}
};
docClient.query(params, function(err, data) {
if (err){
reject(err);
}else{
console.log(data.Items[0]);
resolve(data.Items[0]);
}
});
})
}
function addBlogPostToDB(title, date, categories, post_status){
var post_id = shortid.generate();
return new Promise(function(resolve, reject){
var params = {
TableName : stage_posts_table,
Item: {
post_id: post_id,
title: title,
date: date,
categories: categories,
post_url: getSlug(title)+"_"+post_id,
post_status: post_status || "published"
}
};
docClient.put(params, function(err, data) {
if (err){
reject(err);
}else{
resolve(post_id);
}
});
})
}
function updateBlogPostInDB(post_id, date, title, new_date, categories, post_status){
return new Promise(function(resolve, reject){
var params = {
TableName: stage_posts_table,
Key:{
"post_id": post_id
},
UpdateExpression: "set title = :title, #date=:new_date, categories=:categories, post_status=:post_status",
ExpressionAttributeNames: {"#date": "date"},
ExpressionAttributeValues:{
":title":title,
":new_date":new_date,
":categories":categories,
":post_status":post_status
},
ReturnValues:"UPDATED_NEW"
}
docClient.update(params, function(err, data) {
if (err){
reject(err);
}else{
resolve(post_id);
}
});
})
}
function addBlogPostToS3(post_id, html){
console.log(post_id, html);
return new Promise(function(resolve, reject){
s3.putObject({
Bucket: stage_articles_bucket,
Key: stage_articles_bucket_path+"/"+post_id+"/index.html",
Body: html,
ACL: 'public-read',
ContentType: 'text/html; charset=utf-8"'
}, function(err, data) {
if(err){
reject(err);
}else{
resolve();
}
})
});
}
function onerror(err) {
console.log("ERROR!");
console.log(err);
console.log(arguments);
callback(err.message);
}
}
|
JavaScript
| 0 |
@@ -1874,17 +1874,16 @@
rams = %7B
-
%0A
@@ -2494,24 +2494,16 @@
rate();%0A
-
%0A
@@ -4166,17 +4166,16 @@
Object(%7B
-
%0A
@@ -4213,17 +4213,16 @@
_bucket,
-
%0A
@@ -4288,17 +4288,16 @@
x.html%22,
-
%0A
@@ -4409,16 +4409,60 @@
=utf-8%22'
+,%0A CacheControl: 'max-age=30'
%0A
@@ -4654,20 +4654,16 @@
;%0A %7D%0A
-
%0A%0A fu
@@ -4811,8 +4811,9 @@
%0A %7D%0A%7D
+%0A
|
db1f252bf7ad0eaf4b1afc7b26c7af89ab6c3308
|
correct nested resource comment
|
gen/base/router.js
|
gen/base/router.js
|
/*
* Geddy JavaScript Web development framework
* Copyright 2112 Matthew Eernisse ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
var router = new geddy.RegExpRouter();
router.get('/').to('Main.index');
// Basic routes
// router.match('/moving/pictures/:id', 'GET').to('Moving.pictures');
//
// router.match('/farewells/:farewelltype/kings/:kingid', 'GET').to('Farewells.kings');
//
// Can also match specific HTTP methods only
// router.get('/xandadu').to('Xanadu.specialHandler');
// router.del('/xandadu/:id').to('Xanadu.killItWithFire');
//
// Resource-based routes
// router.resource('hemispheres');
//
// Nested Resource-based routes
// router.resource('hemispheres', function(){
// this.resource('countries');
// this.get('/print(.:format)').to('Hemispheres.print');
// });
exports.router = router;
|
JavaScript
| 0 |
@@ -1209,18 +1209,23 @@
spheres'
-,
+).nest(
function
|
f7f78c94f97c7494b3429d098e38cb5c55ef1460
|
Add some error checking.
|
ears.js
|
ears.js
|
var http = require('http');
var fs = require('fs');
var cp = require('child_process');
var config = {}
var configFile = fs.readFile('config.json', function (err, data) {
if (err) throw err;
config = JSON.parse(data);
console.log(config);
});
var server = http.createServer(function (req, res) {
console.log("Got %s request to %s.", req.method, req.url);
var data = '';
req.addListener('data', function (chunk) { data += chunk; });
req.addListener('end', function () {
data = data.replace(/^payload=/, '');
data = decodeURIComponent(data);
data = JSON.parse(data);
handleHit(data, function (err) {
if (err) {
res.writeHead(500);
res.end(JSON.stringify({"status": err}));
} else {
res.writeHead(200);
res.end(JSON.stringify({"status": "ok"}));
}
});
});
});
function handleHit(data, callback) {
var repo = data.repository.name;
options = config.repositories[repo];
if (options === undefined) {
callback('no such repository "' + repo + '"');
return;
}
cp.exec('git pull', {cwd: options.path}, function (error, stdout, stderr) {
if (error) {
callback(stderr);
} else {
scriptPath = options.script;
if (options.script !== undefined) {
cp.exec(scriptPath, {cwd: options.path},
function(error, stdout, stderr) {
if (err) {
callback(stderr);
} else {
callback();
}
});
} else {
callback();
}
}
});
}
server.listen(8080);
// EOF vim:ts=2:sw=2
|
JavaScript
| 0 |
@@ -475,24 +475,163 @@
nction () %7B%0A
+ if (req.method != 'POST' %7C%7C !data) %7B%0A res.writeHead(500);%0A res.end(JSON.stringify(%7B%22status%22: %22what?%22%7D));%0A return;%0A %7D%0A
data = d
|
ecf72bd2a5eeacef7cb568b0543a7129ab30181f
|
Update index.js
|
heroku/index.js
|
heroku/index.js
|
'use strict';
const smoochBot = require('smooch-bot');
const MemoryLock = smoochBot.MemoryLock;
const SmoochApiStore = smoochBot.SmoochApiStore;
const SmoochApiBot = smoochBot.SmoochApiBot;
const StateMachine = smoochBot.StateMachine;
const app = require('../app');
const script = require('../script');
const SmoochCore = require('smooch-core');
const jwt = require('../jwt');
const fs = require('fs');
class BetterSmoochApiBot extends SmoochApiBot {
constructor(options) {
super(options);
}
sendImage(imageFileName) {
const api = this.store.getApi();
let message = Object.assign({
role: 'appMaker'
}, {
name: this.name,
avatarUrl: this.avatarUrl
});
var real = fs.realpathSync(imageFileName);
let source = fs.readFileSync(real);
return api.conversations.uploadImage(this.userId, source, message);
}
}
const name = 'SmoochBot';
const avatarUrl = 'https://s.gravatar.com/avatar/f91b04087e0125153623a3778e819c0a?s=80';
const store = new SmoochApiStore({
jwt
});
const lock = new MemoryLock();
function createWebhook(smoochCore, target) {
return smoochCore.webhooks.create({
target,
triggers: ['message:appUser']
})
.then((res) => {
console.log('Smooch webhook created at target', res.webhook.target);
return smoochCore.webhooks.create({
target,
triggers: ['postback']
})
.then((res) => {
console.log('Smooch postback webhook created at target', res.webhook.target);
})
.catch((err) => {
console.error('Error creating Smooch webhook:', err);
console.error(err.stack);
});
}
)
.catch((err) => {
console.error('Error creating Smooch webhook:', err);
console.error(err.stack);
});
}
// Create a webhook if one doesn't already exist
if (process.env.SERVICE_URL) {
const target = process.env.SERVICE_URL.replace(/\/$/, '') + '/webhook';
const smoochCore = new SmoochCore({
jwt
});
smoochCore.webhooks.list()
.then((res) => {
if (!res.webhooks.some((w) => w.target === target)) {
createWebhook(smoochCore, target);
}
});
}
app.post('/webhook', function(req, res, next) {
const messages = req.body.messages.reduce((prev, current) => {
if (current.role === 'appUser') {
prev.push(current);
}
return prev;
}, []);
if (messages.length === 0) {
return res.end();
}
const appUser = req.body.appUser;
const userId = appUser.userId || appUser._id;
const stateMachine = new StateMachine({
script,
bot: new BetterSmoochApiBot({
name,
avatarUrl,
lock,
store,
userId
})
});
stateMachine.receiveMessage(messages[0])
.then(() => res.end())
.catch((err) => {
console.error('SmoochBot error:', err);
console.error(err.stack);
res.end();
});
});
app.get('/webhook', function (req, res) {
if (req.query['hub.verify_token'] === 'e3ee919e328d689bdc2b3a66df9be93fe9a87adc') {
res.send(req.query['hub.challenge']);
}
res.send('Error, wrong validation token');
})
var server = app.listen(process.env.PORT || 8000, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Smooch Bot listening at http://%s:%s', host, port);
});
|
JavaScript
| 0.000002 |
@@ -1390,677 +1390,32 @@
-return smoochCore.webhooks.create(%7B%0A target,%0A triggers: %5B'postback'%5D%0A %7D)%0A .then((res) =%3E %7B%0A console.log('Smooch postback webhook created at target', res.webhook.target);%0A %7D)%0A .catch((err) =%3E %7B%0A console.error('Error creating Smooch webhook:', err);%0A console.error(err.stack);%0A %7D);%0A %7D %0A )%0A .catch((err) =%3E %7B%0A console.error('Error creating Smooch webhook:', err);%0A console.error(err.stack);%0A %7D);%0A%7D
+%0A %7D )%0A
%0A%0A//
|
80b516f57bd0d22e301c76225b9bfec75fcddc1d
|
Fix test fixtures
|
lib/node_modules/@stdlib/_tools/eslint/rules/require-file-extensions/test/fixtures/invalid.js
|
lib/node_modules/@stdlib/_tools/eslint/rules/require-file-extensions/test/fixtures/invalid.js
|
'use strict';
var invalid = [];
var test;
test = {
'code': [
'// VARIABLES //',
'',
'var readme = require( \'debug/README.md\' )'
].join( '\n' ),
'errors': [
{
'message': 'require statement of file does not end with one of the whitelisted file extensions (.js,.json,.node). Value: debug/README.md',
'type': 'CallExpression'
}
]
};
invalid.push( test );
test = {
'code': [
'// MODULES //',
'',
'var debug = require( \'debug/src/browser\' )'
].join( '\n' ),
'errors': [
{
'message': 'require statement of file is missing a file extension. Value: debug/src/browser',
'type': 'CallExpression'
}
]
};
invalid.push( test );
test = {
'code': [
'// MODULES //',
'',
'var debug = require( \'@stdlib/beep\' )'
].join( '\n' ),
'errors': [
{
'message': 'Cannot resolve module: "@stdlib/beep"',
'type': 'CallExpression'
}
]
};
invalid.push( test );
// EXPORTS //
module.exports = invalid;
|
JavaScript
| 0.000001 |
@@ -793,17 +793,17 @@
sage': '
-C
+c
annot re
|
47434bc2b51006d3b6cc8019e319715768c7afbb
|
Remove experimental label
|
trinity.js
|
trinity.js
|
#!/usr/bin/env node
'use strict'
const pkg = require('./package.json')
const Configstore = require('configstore')
const defaultConfig = require('./defaultConfig')
const Vorpal = require('vorpal')
const chalk = Vorpal().chalk
const winston = require('winston')
let networkConnection = true
winston
.add(winston.transports.File, {
filename: 'trinity.log',
level: 'debug'
})
.remove(winston.transports.Console)
const wallet = require('./lib/wallet')
const network = require('./lib/network')
const contacts = require('./lib/contacts')
const conf = new Configstore(pkg.name, defaultConfig)
const trinity = Vorpal()
.delimiter(chalk.dim.green('[' + network.get() + '] ') + chalk.green('trinity') + chalk.green(' >'))
.history('trinity-command-history')
.show()
trinity.log(chalk.bold.green("\n" + ' Wake up, Neo… ' + "\n"))
trinity
.command('send neo', chalk.bold.red('[EXPERIMENTAL]') + ' Send NEO from one of your addresses to one of your contacts.')
.action(function (args, cb) {
let self = this
wallet.sendNeo(self, args, cb)
})
trinity
.command('send gas', chalk.bold.red('[EXPERIMENTAL]') + ' Send GAS from one of your addresses to one of your contacts.')
.action(function (args, cb) {
let self = this
wallet.sendGas(self, args, cb)
})
trinity
.command('wallet list', 'List available wallets.')
.action(function (args, cb) {
let self = this
wallet.list(self, args, cb)
})
trinity
.command('wallet show', 'Select an address to show its balances, transactions, claimables, etc.')
.action(function (args, cb) {
let self = this
wallet.show(self, args, cb)
})
trinity
.command('wallet create', 'Creates a new wallet address.')
.action(function (args, cb) {
let self = this
wallet.create(self, args, cb)
})
trinity
.command('wallet import', 'Import an existing private key in WIF format.')
.action(function (args, cb) {
let self = this
wallet.import(self, args, cb)
})
trinity
.command('wallet remove', 'Select an address to remove from local storage.')
.action(function (args, cb) {
let self = this
wallet.remove(self, args, cb)
})
trinity
.command('wallet clear', 'Purge all wallet information from local storage.')
.action(function (args, cb) {
let self = this
wallet.clear(self, args, cb)
})
trinity
.command('contact list', 'List your contacts.')
.action(function (args, cb) {
let self = this
contacts.list(self, args, cb)
})
trinity
.command('contact add', 'Add a new contact.')
.action(function (args, cb) {
let self = this
contacts.add(self, args, cb)
})
trinity
.command('contact remove', 'Remove an existing contact.')
.action(function (args, cb) {
let self = this
contacts.remove(self, args, cb)
})
trinity
.command('contact clear', 'Purge all contact information from local storage.')
.action(function (args, cb) {
let self = this
contacts.clear(self, args, cb)
})
trinity
.command('claim gas', chalk.bold.red('[EXPERIMENTAL]') + ' Claim all available and unavailable gas.')
.action(function (args, cb) {
let self = this
wallet.claimAllGas(self, args, cb)
})
trinity
.command('network', 'Switch to a different network.')
.action(function (args, cb) {
let self = this
network.set(self, args, cb)
})
wallet.updateBalances(trinity)
var trinityLoop = setInterval(() => {
wallet.updateBalances(trinity)
wallet.updateClaimables(trinity)
}, 5000)
|
JavaScript
| 0.002438 |
@@ -876,45 +876,9 @@
o',
-chalk.bold.red('%5BEXPERIMENTAL%5D') + '
+'
Send
@@ -1064,45 +1064,9 @@
s',
-chalk.bold.red('%5BEXPERIMENTAL%5D') + '
+'
Send
@@ -2938,45 +2938,9 @@
s',
-chalk.bold.red('%5BEXPERIMENTAL%5D') + '
+'
Clai
|
a308c3f20bd3a2d0cfccf97e11c4d2f203ca6b7b
|
Fix reportCoverage script
|
package-scripts.js
|
package-scripts.js
|
module.exports = {
scripts: {
commit: {
description: 'This uses commitizen to help us generate beautifully formatted commit messages',
script: 'git-cz',
},
test: {
default: {
description: 'just pass it on to npm... Do not take this config very seriously :-)',
script: 'cross-env NODE_ENV=test ava ./src/**/*.test.js',
},
watch: {
description: 'pass the -w flag on to the npm t command so ava will watch stuff',
script: 'p-s test -w',
},
},
build: 'rimraf dist && babel --copy-files --out-dir dist --ignore *.test.js src',
lint: {
description: 'this does stuff',
script: 'eslint .',
},
checkCoverage: {
description: 'We want to keep 100% code coverage on this project because, reasons',
script: 'nyc check-coverage --statements 100 --branches 100 --functions 100 --lines 100',
},
cover: {
description: 'we use nyc to instrument our code for coverage. Some of the config happens in package.json',
script: 'nyc npm t',
},
reportCoverage: {
description: 'Report coverage stats to codecov. This should be run after the `cover` script',
script: 'cat ./coverage/lcov.info | node_modules/.bin/codecov',
},
release: {
description: 'We automate releases with semantic-release. This should only be run on travis',
script: 'semantic-release pre && npm publish && semantic-release post',
},
validate: {
description: 'This runs several scripts to make sure things look good before committing or on clean install',
script: 'p-s -p lint,build,cover && p-s check-coverage',
},
},
options: {
silent: false,
},
}
|
JavaScript
| 0 |
@@ -1203,53 +1203,8 @@
t: '
-cat ./coverage/lcov.info %7C node_modules/.bin/
code
|
0c05a92f87f37e4df17f34f9d2d7ebb9180389de
|
remove stray debug log line
|
browser/src/render/Renderer.js
|
browser/src/render/Renderer.js
|
'use strict'
import ViewState from './ViewState'
import BrowserRtcBufferFactory from '../BrowserRtcBufferFactory'
import YUVASurfaceShader from './YUVASurfaceShader'
import YUVSurfaceShader from './YUVSurfaceShader'
import Size from '../Size'
export default class Renderer {
/**
*
* @param {BrowserSession} browserSession
* @returns {Renderer}
*/
static create (browserSession) {
// create offscreen gl context
const canvas = document.createElement('canvas')
let gl = canvas.getContext('webgl2', {
antialias: false,
depth: false,
alpha: true,
preserveDrawingBuffer: false
})
if (!gl) {
throw new Error('This browser doesn\'t support WebGL2!')
}
gl.clearColor(0, 0, 0, 0)
const yuvaShader = YUVASurfaceShader.create(gl)
const yuvShader = YUVSurfaceShader.create(gl)
return new Renderer(browserSession, gl, yuvaShader, yuvShader, canvas)
}
/**
* @name RenderFrame
* @type{Promise<number>}
* @property {Function} fire
* @property {Function} then
*/
/**
* @return {RenderFrame}
*/
static createRenderFrame () {
let animationResolve = null
const animationPromise = new Promise((resolve) => {
animationResolve = resolve
})
animationPromise._animationResolve = animationResolve
animationPromise.fire = () => {
window.requestAnimationFrame((time) => {
animationPromise._animationResolve(time)
})
}
return animationPromise
}
/**
* Use Renderer.create(..) instead.
* @private
* @param {BrowserSession}browserSession
* @param {WebGLRenderingContext}gl
* @param {YUVASurfaceShader}yuvaShader
* @param {YUVSurfaceShader}yuvShader
* @param {HTMLCanvasElement}canvas
*/
constructor (browserSession, gl, yuvaShader, yuvShader, canvas) {
/**
* @type {BrowserSession}
*/
this.browserSession = browserSession
/**
* @type {WebGLRenderingContext}
*/
this.gl = gl
/**
* @type {YUVASurfaceShader}
*/
this.yuvaShader = yuvaShader
/**
* @type {YUVSurfaceShader}
*/
this.yuvShader = yuvShader
/**
* @type {HTMLCanvasElement}
*/
this.canvas = canvas
/**
* @type {HTMLImageElement}
* @private
*/
this._emptyImage = new window.Image()
this._emptyImage.src = '//:0'
}
/**
* @param {BrowserSurface}browserSurface
* @param {{bufferContents: {type: string, syncSerial: number, geo: Size, yuvContent: Uint8Array, yuvWidth: number, yuvHeight: number, alphaYuvContent: Uint8Array, alphaYuvWidth: number, alphaYuvHeight: number, pngImage: HTMLImageElement}|null, bufferDamage: Number, opaquePixmanRegion: number, inputPixmanRegion: number, dx: number, dy: number, bufferTransform: number, bufferScale: number}} newState
*/
renderBackBuffer (browserSurface, newState) {
const views = browserSurface.browserSurfaceViews
const bufferContents = newState.bufferContents
if (bufferContents) {
let viewState = browserSurface.renderState
if (!viewState) {
viewState = ViewState.create(this.gl)
browserSurface.renderState = viewState
}
this._draw(bufferContents, viewState, views)
} else {
console.trace('rendering empty surface')
views.forEach((browserSurfaceView) => {
browserSurfaceView.drawImage(this._emptyImage)
})
}
}
/**
* @param {{type: string, syncSerial: number, geo: Size, yuvContent: Uint8Array, yuvWidth: number, yuvHeight: number, alphaYuvContent: Uint8Array, alphaYuvWidth: number, alphaYuvHeight: number, pngImage: HTMLImageElement}}bufferContents
* @param {ViewState}viewState
* @param {BrowserSurfaceView[]}views
* @private
*/
_draw (bufferContents, viewState, views) {
// update textures or image
viewState.update(bufferContents)
// paint the textures
if (bufferContents.type === 'h264') {
this._drawH264(bufferContents, viewState, views)
} else { // if (browserRtcDcBuffer.type === 'png')
this._drawImage(viewState, views)
}
}
/**
* @param {{type: string, syncSerial: number, geo: Size, yuvContent: Uint8Array, yuvWidth: number, yuvHeight: number, alphaYuvContent: Uint8Array, alphaYuvWidth: number, alphaYuvHeight: number, pngImage: HTMLImageElement}}bufferContents
* @param {ViewState}viewState
* @param {BrowserSurfaceView[]}views
* @private
*/
_drawH264 (bufferContents, viewState, views) {
const bufferSize = bufferContents.geo
const viewPortUpdate = this.canvas.width !== bufferSize.w || this.canvas.height !== bufferSize.h
this.canvas.width = bufferSize.w
this.canvas.height = bufferSize.h
if (bufferContents.alphaYuvContent != null) {
this.yuvaShader.use()
this.yuvaShader.draw(viewState.yTexture, viewState.uTexture, viewState.vTexture, viewState.alphaYTexture, bufferSize, viewPortUpdate)
} else {
this.yuvShader.use()
this.yuvShader.draw(viewState.yTexture, viewState.uTexture, viewState.vTexture, bufferSize, viewPortUpdate)
}
// blit rendered texture from render canvas into view canvasses
views.forEach((view) => {
view.drawCanvas(this.canvas)
})
}
/**
* @param {ViewState}viewState
* @param {BrowserSurfaceView[]}views
* @private
*/
_drawImage (viewState, views) {
views.forEach((view) => {
view.drawImage(viewState.image)
})
}
}
/**
* @type {Promise<number>}
* @private
*/
Renderer._animationPromise = null
/**
* @type {Function}
* @private
*/
Renderer._animationResolve = null
|
JavaScript
| 0.000004 |
@@ -3237,55 +3237,8 @@
e %7B%0A
- console.trace('rendering empty surface')%0A
|
56fe255b24b1163d3a0ddb2aaebed71a5478be46
|
add option to bust cache
|
src/Layers/DynamicMapLayer.js
|
src/Layers/DynamicMapLayer.js
|
import { Util } from 'leaflet';
import { RasterLayer } from './RasterLayer';
import { cleanUrl } from '../Util';
import mapService from '../Services/MapService';
export var DynamicMapLayer = RasterLayer.extend({
options: {
updateInterval: 150,
layers: false,
layerDefs: false,
timeOptions: false,
format: 'png24',
transparent: true,
f: 'json'
},
initialize: function (options) {
options.url = cleanUrl(options.url);
this.service = mapService(options);
this.service.addEventParent(this);
if ((options.proxy || options.token) && options.f !== 'json') {
options.f = 'json';
}
Util.setOptions(this, options);
},
getDynamicLayers: function () {
return this.options.dynamicLayers;
},
setDynamicLayers: function (dynamicLayers) {
this.options.dynamicLayers = dynamicLayers;
this._update();
return this;
},
getLayers: function () {
return this.options.layers;
},
setLayers: function (layers) {
this.options.layers = layers;
this._update();
return this;
},
getLayerDefs: function () {
return this.options.layerDefs;
},
setLayerDefs: function (layerDefs) {
this.options.layerDefs = layerDefs;
this._update();
return this;
},
getTimeOptions: function () {
return this.options.timeOptions;
},
setTimeOptions: function (timeOptions) {
this.options.timeOptions = timeOptions;
this._update();
return this;
},
query: function () {
return this.service.query();
},
identify: function () {
return this.service.identify();
},
find: function () {
return this.service.find();
},
_getPopupData: function (e) {
var callback = Util.bind(function (error, featureCollection, response) {
if (error) { return; } // we really can't do anything here but authenticate or requesterror will fire
setTimeout(Util.bind(function () {
this._renderPopup(e.latlng, error, featureCollection, response);
}, this), 300);
}, this);
var identifyRequest = this.identify().on(this._map).at(e.latlng);
// remove extraneous vertices from response features
identifyRequest.simplify(this._map, 0.5);
if (this.options.layers) {
identifyRequest.layers('visible:' + this.options.layers.join(','));
} else {
identifyRequest.layers('visible');
}
identifyRequest.run(callback);
// set the flags to show the popup
this._shouldRenderPopup = true;
this._lastClick = e.latlng;
},
_buildExportParams: function () {
var bounds = this._map.getBounds();
var size = this._map.getSize();
var ne = this._map.options.crs.project(bounds.getNorthEast());
var sw = this._map.options.crs.project(bounds.getSouthWest());
var sr = parseInt(this._map.options.crs.code.split(':')[1], 10);
// ensure that we don't ask ArcGIS Server for a taller image than we have actual map displaying
var top = this._map.latLngToLayerPoint(bounds._northEast);
var bottom = this._map.latLngToLayerPoint(bounds._southWest);
if (top.y > 0 || bottom.y < size.y) {
size.y = bottom.y - top.y;
}
var params = {
bbox: [sw.x, sw.y, ne.x, ne.y].join(','),
size: size.x + ',' + size.y,
dpi: 96,
format: this.options.format,
transparent: this.options.transparent,
bboxSR: sr,
imageSR: sr
};
if (this.options.dynamicLayers) {
params.dynamicLayers = this.options.dynamicLayers;
}
if (this.options.layers) {
params.layers = 'show:' + this.options.layers.join(',');
}
if (this.options.layerDefs) {
params.layerDefs = typeof this.options.layerDefs === 'string' ? this.options.layerDefs : JSON.stringify(this.options.layerDefs);
}
if (this.options.timeOptions) {
params.timeOptions = JSON.stringify(this.options.timeOptions);
}
if (this.options.from && this.options.to) {
params.time = this.options.from.valueOf() + ',' + this.options.to.valueOf();
}
if (this.service.options.token) {
params.token = this.service.options.token;
}
if (this.options.proxy) {
params.proxy = this.options.proxy;
}
return params;
},
_requestExport: function (params, bounds) {
if (this.options.f === 'json') {
this.service.request('export', params, function (error, response) {
if (error) { return; } // we really can't do anything here but authenticate or requesterror will fire
if (this.options.token) {
response.href += ('?token=' + this.options.token);
}
if (this.options.proxy) {
response.href = this.options.proxy + '?' + response.href;
}
if (response.href) {
this._renderImage(response.href, bounds);
} else {
this._renderImage(response.imageData, bounds, response.contentType);
}
}, this);
} else {
params.f = 'image';
this._renderImage(this.options.url + 'export' + Util.getParamString(params), bounds);
}
}
});
export function dynamicMapLayer (url, options) {
return new DynamicMapLayer(url, options);
}
export default dynamicMapLayer;
|
JavaScript
| 0 |
@@ -4177,24 +4177,143 @@
oxy;%0A %7D%0A%0A
+ // use a timestamp to bust server cache%0A if (this.options.disableCache) %7B%0A params._ts = Date.now();%0A %7D%0A%0A
return p
|
a6f260357ce21866a194fe92fc024111ce608c53
|
Add missing font file in build
|
ember-cli-build.js
|
ember-cli-build.js
|
/* global require, module */
var EmberApp = require('ember-cli/lib/broccoli/ember-app');
module.exports = function(defaults) {
var app = new EmberApp(defaults, {
// Add options here
});
// Use `app.import` to add additional libraries to the generated
// output files.
//
// If you need to use different assets in different
// environments, specify an object as the first parameter. That
// object's keys should be the environment name and the values
// should be the asset to use in that environment.
//
// If the library that you are including contains AMD or ES6
// modules that you would like to import into your application
// please specify an object with the list of modules as keys
// along with the exports of each module as its value.
app.import('bower_components/bootstrap/dist/js/bootstrap.js');
app.import('bower_components/bootstrap/dist/css/bootstrap.css');
app.import('bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.woff', {
destDir: 'fonts'
});
app.import('vendor/forge.min.js');
return app.toTree();
};
|
JavaScript
| 0 |
@@ -1021,16 +1021,134 @@
'%0A %7D);%0A
+ app.import('bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.woff2', %7B%0A destDir: 'fonts'%0A %7D);%0A
app.im
@@ -1176,17 +1176,16 @@
n.js');%0A
-%0A
return
|
e702b2ccd58efc78f2b40135fb293da2cdc123fd
|
drop automatic body for delete request, allow manual override
|
src/helpers/fetch.js
|
src/helpers/fetch.js
|
import {isObject, isString, startsWith, endsWith} from './util';
import {
encodeUriQuery,
encodeUriSegment,
replaceUrlParamFromUrl,
replaceQueryStringParamFromUrl,
splitUrlByProtocolAndDomain
} from './url';
import {defaultGlobals, defaultHeaders, defaultIdKeys} from '../defaults';
export class HttpError extends Error {
constructor(statusCode = 500, {body, message = 'HttpError'}) {
super(message);
this.name = this.constructor.name;
this.message = message;
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, this.constructor);
} else {
this.stack = new Error(message).stack;
}
// Http
this.statusCode = statusCode;
this.status = statusCode;
this.body = body;
}
}
export const buildFetchUrl = (context, {url, urlParams, stripTrailingSlashes = true}) => {
const [protocolAndDomain = '', remainderUrl] = splitUrlByProtocolAndDomain(url);
// Replace urlParams with values from context
let builtUrl = Object.keys(urlParams).reduce((wipUrl, urlParam) => {
const urlParamInfo = urlParams[urlParam];
const contextAsObject = !isObject(context)
? {
[defaultIdKeys.singular]: context
}
: context;
const value = contextAsObject[urlParam] || ''; // self.defaults[urlParam];
if (value) {
const encodedValue = urlParamInfo.isQueryParamValue ? encodeUriQuery(value, true) : encodeUriSegment(value);
return replaceUrlParamFromUrl(wipUrl, urlParam, encodedValue);
}
return replaceUrlParamFromUrl(wipUrl, urlParam);
}, remainderUrl);
// Strip trailing slashes and set the url (unless this behavior is specifically disabled)
if (stripTrailingSlashes) {
builtUrl = builtUrl.replace(/\/+$/, '') || '/';
}
return protocolAndDomain + builtUrl;
};
export const buildFetchOpts = (context, {method, headers, credentials, query, body}) => {
const opts = {
headers: defaultHeaders
};
if (method) {
opts.method = method;
}
if (headers) {
opts.headers = {
...opts.headers,
...headers
};
}
if (credentials) {
opts.credentials = credentials;
}
if (query) {
opts.query = query;
}
const hasBody = /^(POST|PUT|PATCH|DELETE)$/i.test(opts.method);
if (hasBody) {
if (body) {
opts.body = isString(body) ? body : JSON.stringify(body);
} else if (context) {
opts.body = isString(context) ? context : JSON.stringify(context);
}
}
return opts;
};
export const parseResponse = res => {
const contentType = res.headers.get('Content-Type');
// @NOTE parses 'application/problem+json; charset=utf-8' for example
// see https://tools.ietf.org/html/rfc6839
const isJson =
contentType && (startsWith(contentType, 'application/json') || endsWith(contentType.split(';')[0], '+json'));
return res[isJson ? 'json' : 'text']();
};
const fetch = (url, options = {}) => {
// Support options.query
const builtUrl = Object.keys(options.query || []).reduce((wipUrl, queryParam) => {
const queryParamValue = isString(options.query[queryParam])
? options.query[queryParam]
: JSON.stringify(options.query[queryParam]);
return replaceQueryStringParamFromUrl(wipUrl, queryParam, queryParamValue);
}, url);
return (options.Promise || defaultGlobals.Promise)
.resolve((defaultGlobals.fetch || fetch)(builtUrl, options))
.then(res => {
if (!res.ok) {
return parseResponse(res).then(body => {
throw new HttpError(res.status, {
body
});
});
}
return res;
});
};
export default fetch;
|
JavaScript
| 0 |
@@ -2224,15 +2224,8 @@
ATCH
-%7CDELETE
)$/i
@@ -2248,27 +2248,8 @@
d);%0A
- if (hasBody) %7B%0A
if
@@ -2254,26 +2254,24 @@
if (body) %7B%0A
-
opts.bod
@@ -2320,18 +2320,16 @@
(body);%0A
-
%7D else
@@ -2333,16 +2333,27 @@
lse if (
+hasBody &&
context)
@@ -2359,38 +2359,49 @@
) %7B%0A
- opts.body
+const contextAsObject
=
+!
is
-String
+Object
(context
@@ -2405,20 +2405,105 @@
ext)
- ? context :
+%0A ? %7B%0A %5BdefaultIdKeys.singular%5D: context%0A %7D%0A : context;%0A opts.body =
JSO
@@ -2521,24 +2521,26 @@
(context
-);%0A %7D
+AsObject);
%0A %7D%0A r
|
f065db729416def067cd39cebd4cca2cfaee7ae0
|
Update Italian translations
|
i18n/jquery.spectrum-it.js
|
i18n/jquery.spectrum-it.js
|
// Spectrum Colorpicker
// Italian (it) localization
// https://github.com/bgrins/spectrum
(function ( $ ) {
var localization = $.spectrum.localization["it"] = {
cancelText: "annulla",
chooseText: "scegli"
};
$.extend($.fn.spectrum.defaults, localization);
})( jQuery );
|
JavaScript
| 0 |
@@ -208,16 +208,109 @@
%22scegli%22
+,%0A%09%09clearText: %22Annulla selezione colore%22,%0A%09%09noColorSelectedText: %22Nessun colore selezionato%22
%0A%09%7D;%0A%0A
|
eea51f2b100abb5f70d528df0d683fdd0bba5176
|
Change fractal to lighter version
|
main.js
|
main.js
|
(function() {
function Complex(r, i) {
this.r = r;
this.i = i;
}
Complex.prototype.add = function(other) {
return new Complex(this.r + other.r, this.i + other.i);
}
Complex.prototype.sub = function(other) {
return new Complex(this.r - other.r, this.i - other.i);
}
Complex.prototype.mul = function(other) {
return new Complex(this.r * other.r - this.i * other.i,
this.i * other.r + this.r * other.i);
}
Complex.prototype.div = function(other) {
var denominator = other.r * other.r + other.i * other.i;
return new Complex((this.r * other.r + this.i * other.i) / denominator,
(this.i * other.r - this.r * other.i) / denominator);
}
function setFillStyle(ctx, r, g, b, a) {
ctx.fillStyle = "rgba(" + r + ", " + g + ", " + b + ", " + a + ")";
}
window.onload = function() {
var planeCanvas = document.getElementById("plane");
planeCanvas.width = window.innerWidth;
planeCanvas.height = window.innerHeight;
var ctx = planeCanvas.getContext("2d");
var one = new Complex(1, 0);
var three = new Complex(3, 0);
var f = function(z) { return z.mul(z).mul(z).sub(one); };
var fPrime = function(z) { return three.mul(z).mul(z); };
var N = function(z) { return z.sub(f(z).div(fPrime(z))); };
var bottom = Math.floor(planeCanvas.height / 2);
var top = -bottom;
var right = Math.floor(planeCanvas.width / 2);
var left = -right;
setFillStyle(ctx, 255, 255, 255, 1);
ctx.fillRect(0, 0, planeCanvas.width, planeCanvas.height);
for (var x = left - 10; x < right + 10; x++) {
for (var y = top - 10; y < bottom + 10; y++) {
var yo = new Complex(x/500, y/500);
var ayy = N(yo);
var ayy2 = N(ayy);
var n = 0;
while (Math.abs(ayy2.r - ayy.r) > 0.000001) {
ayy = ayy2;
ayy2 = N(ayy2);
n++;
}
if (Math.abs(ayy.r - 1) < 0.001) {
setFillStyle(ctx, 0, 198, 255, 1-n/20);
} else if(Math.abs(ayy.r + 0.5) < 0.001) {
setFillStyle(ctx, 0, 0, 0, 1-n/20);
} else {
setFillStyle(ctx, 255, 255, 255, 1);
}
ctx.fillRect(x - left, y - top, 1, 1);
}
}
}
})();
|
JavaScript
| 0.000003 |
@@ -2224,18 +2224,16 @@
8, 255,
-1-
n/20);%0A
@@ -2341,10 +2341,8 @@
0,
-1-
n/20
|
be67db65e87113b3da2baf1a6fe8fbe5b558d86d
|
modify routing, placeholder
|
assets/js/1995.js
|
assets/js/1995.js
|
const search = instantsearch({
searchClient: algoliasearch('IA90805VYI', '9e30d633e7ae5597b0ddb7744f621017'),
indexName: 'index',
});
search.addWidget(
instantsearch.widgets.searchBox({
container: '#searchbox',
placeholder: ' ver.1995を検索…',
poweredBy: true,
cssClasses: {
form: 'search-nagisa',
},
})
);
/*
search.addWidget(
instantsearch.widgets.refinementList({
container: '#refinement-list',
attribute: 'text',
//searchable: true,
templates: {
item(item) {
var resultStr = `${item.value}`;
return `
👉 ${resultStr} (${item.count})
`;
}
}
})
);
*/
search.addWidget(
instantsearch.widgets.poweredBy({
container: '#powered-by',
cssClasses: {
root: 'powered-by-nagisa',
},
})
);
search.addWidget(
instantsearch.widgets.hits({
container: '#hits',
cssClasses: {
item: 'item-nagisa',
},
templates: {
empty: "キーワード<em>「{{query}}」</em>では探せませんでした。",
item(hit) {
var resultStr = `${hit.text.join('')}`;
return `
<dt><a href="${hit.url}" target="_blank">${hit._highlightResult.title.value}</a></dt>
<dd>${resultStr.slice(0, 120)}…</dd>
`;
}
},
})
);
// initialize pagination
search.addWidget(
instantsearch.widgets.pagination({
container: '#pagination',
maxPages: 20,
// default is to scroll to 'body', here we disable this behavior
scrollTo: false,
showFirstLast: true,
collapsible: true,
//autoHideContainer: true,
cssClasses: {
item: 'pagination-nagisa',
},
})
);
search.start();
|
JavaScript
| 0 |
@@ -131,16 +131,35 @@
index',%0A
+ routing: true,%0A
%7D);%0A%0Asea
@@ -266,17 +266,16 @@
older: '
-
ver.1995
@@ -519,36 +519,8 @@
t',%0A
- //searchable: true,%0A
|
f61487fecffbc2a7b3194553f141cf9891e7fc6e
|
Remove second call to the same function
|
src/hooks/install.js
|
src/hooks/install.js
|
import fs from 'fs';
import path from 'path';
import { getGitHooksPath, packagePath } from '../paths';
import { error, separator } from '../log';
const hooks = ['post-checkout', 'post-merge', 'post-rewrite'];
const infoString = 'this file has been automatically generated, please do not edit it';
/**
* is autoinstaller hook
*
* @desc check if an existing git hook is a previously installed
* npm-autoinstaller hook
* @param {string} hook - name of the git hook
* @return {boolean}
*/
export const isAutoinstallerHook = (hook) => {
const data = fs.readFileSync(`${getGitHooksPath()}/${hook}`, 'utf8');
const lines = data.split("\n");
return lines.length > 2 && lines[2].startsWith('# npm-autoinstaller');
};
/**
* has already other hooks
*
* @desc checks if there are already git hooks installed which are not
* from this package
* @return {boolean}
*/
export const hasAlreadyOtherHooks = () => {
for (let hook of hooks) {
if (fs.existsSync(`${getGitHooksPath()}/${hook}`)) {
if (isAutoinstallerHook(hook)) {
fs.unlinkSync(`${getGitHooksPath()}/${hook}`);
continue;
}
return true;
}
}
return false;
};
/**
* replace hook in string
*
* @desc replaces the {HOOK} placeholder in a string
* @param {string} content - string in which the hook should get replaced
* @param {string} hook - name of the git hook
* @return {string}
*/
export const replaceHookInString = (content, hook, relativePath) => {
let replacedString = content.replace(/\{HOOK\}/g, hook);
replacedString = replacedString.replace(/\{INFO\}/g, infoString);
replacedString = replacedString.replace(/\{PATH}/g, relativePath);
return replacedString;
};
/**
* copy hooks
*
* @desc copyies the hook template over to the git hooks directory
*/
export const copyHooks = () => {
for (let hook of hooks) {
try {
const relativePath = path.relative(getGitHooksPath(), __dirname);
const content = fs.readFileSync(`${packagePath}/dist/hooks/hook-template.sh`, 'utf8');
fs.writeFileSync(`${getGitHooksPath()}/${hook}`, replaceHookInString(content, hook, relativePath));
fs.chmodSync(`${getGitHooksPath()}/${hook}`, '755');
} catch (e) {
separator();
error('npm-autoinstaller could not be installed:');
error('could not copy git hooks!');
error(e);
separator();
return;
}
}
};
/**
* install hooks
*
* @desc installs all available git hooks
* @param {function} callback - optional callback function
*/
export const installHooks = (callback) => {
if (!getGitHooksPath()) {
separator();
error('npm-autoinstaller could not be installed:');
error('git hooks directory not found!');
error('this directory is most likely not a git repository.');
separator();
} else {
fs.lstat(getGitHooksPath(), (err, stats) => {
if (err || !stats.isDirectory()) {
separator();
error('npm-autoinstaller could not be installed:');
error('git hooks directory not found!');
error('this directory is most likely not a git repository.');
separator();
} else if (hasAlreadyOtherHooks()) {
separator();
error('npm-autoinstaller could not be installed:');
error('it seems like you already have some git hooks installed.');
error('if you are using (or have used) another git-hooks package, please read:');
error('https://github.com/cyrilwanner/npm-autoinstaller/blob/master/MIGRATING.md'.underline);
separator();
} else {
copyHooks();
}
if (typeof callback === 'function') {
callback();
}
});
}
};
|
JavaScript
| 0.000014 |
@@ -2598,30 +2598,68 @@
%7B%0A
-if (!getGitHooksPath()
+const gitHooksPath = getGitHooksPath();%0A%0A if (!gitHooksPath
) %7B%0A
@@ -2884,19 +2884,16 @@
.lstat(g
-etG
itHooksP
@@ -2895,18 +2895,16 @@
ooksPath
-()
, (err,
|
eb4303ce9ecc7c1e3e031ac88a981d4b5f772d9d
|
modify window dimensions
|
main.js
|
main.js
|
const {app, BrowserWindow} = require('electron')
const path = require('path')
const url = require('url')
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win
function createWindow () {
// Create the browser window.
win = new BrowserWindow({width: 800, height: 600})
// and load the index.html of the app.
win.loadURL(url.format({
pathname: path.join(__dirname, 'static/index.html'),
protocol: 'file:',
slashes: true
}))
// Open the DevTools.
// win.webContents.openDevTools()
// Emitted when the window is closed.
win.on('closed', () => {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
win = null
})
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)
// Quit when all windows are closed.
app.on('window-all-closed', () => {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (win === null) {
createWindow()
}
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
|
JavaScript
| 0 |
@@ -360,11 +360,12 @@
th:
-800
+1024
, he
@@ -374,9 +374,9 @@
ht:
-6
+8
00%7D)
|
67113377f87e986349a3bb2db2ce793708b72bfa
|
Write tests for User model
|
server/config/config.js
|
server/config/config.js
|
const dotenv = require('dotenv');
dotenv.config();
module.exports = {
development: {
username: 'Newman',
password: 'andela2017',
database: 'postit-db-dev',
host: '127.0.0.1',
port: 5432,
secret_key: process.env.SECRET_KEY,
dialect: 'postgres'
},
test: {
// username: 'Newman',
// password: 'andela2017',
// database: 'postit-db-test',
username: 'postgres',
password: '',
database: 'postit_db_test',
host: '127.0.0.1',
port: 5432,
secret_key: process.env.SECRET_KEY,
dialect: 'postgres'
},
production: {
use_env_variable: 'PROD_DB_URL',
username: '?',
password: '?',
database: '?',
host: '?',
dialect: '?'
}
};
|
JavaScript
| 0.000003 |
@@ -286,19 +286,16 @@
t: %7B%0A
- //
usernam
@@ -310,19 +310,16 @@
an',%0A
- //
passwor
@@ -342,11 +342,8 @@
%0A
- //
dat
@@ -366,24 +366,27 @@
b-test',%0A
+ //
username: '
@@ -395,24 +395,27 @@
stgres',%0A
+ //
password: '
@@ -416,24 +416,27 @@
ord: '',%0A
+ //
database: '
|
51bb37c0cd0d94c73703e01044da9371566f417d
|
remove redundant Parenthese
|
src/client/app/blockly/lib/generators/python/hedgehog.js
|
src/client/app/blockly/lib/generators/python/hedgehog.js
|
'use strict';
goog.provide('Blockly.Python.hedgehog');
goog.require('Blockly.Python');
// set indentaion to 4 spaces
Blockly.Python.INDENT = ' ';
Blockly.Python['hedgehog_scope'] = function(block) {
var statements = Blockly.Python.statementToCode(block, 'IN');
Blockly.Python.definitions_['import_hedgehog'] = 'from hedgehog.client import connect';
var code = 'with connect(emergency=15) as hedgehog:\n' + statements;
return code;
};
Blockly.Python['hedgehog_turn'] = function(block) {
var number_motor1 = block.getFieldValue('MOTOR1');
var number_motor2 = block.getFieldValue('MOTOR2');
var dropdown_dir = block.getFieldValue('DIR');
var value_num = Blockly.Python.valueToCode(block, 'NUM', Blockly.Python.ORDER_ATOMIC);
var dropdown_unit = block.getFieldValue('UNIT');
// imports
Blockly.Python.definitions_['import_sleep'] = 'from time import sleep';
Blockly.Python.definitions_['import_hedgehog'] = 'from hedgehog.client import connect';
// TODO: Assemble Python into code variable.
var code = 'blub\n';
return code;
};
Blockly.Python['hedgehog_move'] = function(block) {
var port = block.getFieldValue('PORT');
var speed = Blockly.Python.valueToCode(block, 'SPEED', Blockly.Python.ORDER_ATOMIC);
var time = Blockly.Python.valueToCode(block, 'TIME', Blockly.Python.ORDER_ATOMIC);
// imports
Blockly.Python.definitions_['import_sleep'] = 'from time import sleep';
Blockly.Python.definitions_['import_hedgehog'] = 'from hedgehog.client import connect';
var code = 'hedgehog.move(' + port + ', ' + speed + ')' + '; sleep(' + time + ')\n';
// return [code, Blockly.Python.ORDER_FUNCTION];
return code;
};
Blockly.Python['hedgehog_speed'] = function(block) {
var speed = block.getFieldValue('SPEED');
return [speed, Blockly.Python.ORDER_NONE];
};
Blockly.Python['hedgehog_servo'] = function(block) {
var port = block.getFieldValue('PORT');
var angle = Blockly.Python.valueToCode(block, 'ANGLE', Blockly.Python.ORDER_ATOMIC);
// imports
Blockly.Python.definitions_['import_hedgehog'] = 'from hedgehog.client import connect';
var code = 'hedgehog.set_servo(' + port + ', ' + angle + '*22' + ')\n';
return code;
};
Blockly.Python['hedgehog_degrees'] = function(block) {
var angle = block.getFieldValue('ANGLE');
// imports
Blockly.Python.definitions_['import_hedgehog'] = 'from hedgehog.client import connect';
return [angle, Blockly.Python.ORDER_NONE];
};
Blockly.Python['hedgehog_read_analog'] = function(block) {
var port = block.getFieldValue('PORT');
var code = 'hedgehog.get_analog(' + port + ')';
return [code, Blockly.Python.ORDER_NONE];
};
Blockly.Python['hedgehog_read_digital'] = function(block) {
var port = block.getFieldValue('PORT');
var code = 'hedgeho.get_digital(' + port + ')';
return [code, Blockly.Python.ORDER_NONE];
};
|
JavaScript
| 0.999985 |
@@ -2028,38 +2028,36 @@
ly.Python.ORDER_
-ATOMIC
+NONE
);%0A%0A // impor
|
d328177f1134f16b9684b443333274aada2a6721
|
Update db functions
|
assets/js/db-server.js
|
assets/js/db-server.js
|
/**
* Global DB server class.
*/
class DBServer {
/**
* Initialise with database options.
*/
constructor() {
this.server = null;
this.options = {
server: 'tei-viewer',
version: 3,
schema: {
tei: {
key: {keyPath: 'id', autoIncrement: true}
}
}
};
}
/**
* Connect to the database.
*/
connect() {
var _this = this;
return new Promise(function(resolve, reject) {
db.open(_this.options).then(function(server) {
_this.server = server;
resolve();
}).catch(function (err) {
if (err.type === 'blocked') {
oldConnection.close();
return err.resume;
}
reject(err);
});
});
}
/**
* Add a record, ensuring that a connection is established first.
*/
add(data) {
var _this = this;
function addRecord(id, xml) {
return new Promise(function(resolve, reject) {
_this.server.tei.add(data).then(function() {
resolve();
}).catch(function (err) {
reject(err);
});
});
}
return new Promise(function(resolve, reject) {
if (_this.server === null) {
_this.connect().then(function() {
resolve(addRecord(data));
}).catch(function (err) {
reject(err);
});
} else {
resolve(addRecord(data));
}
});
}
/**
* Return a record, ensuring that a connection is established first.
*/
get(id) {
var _this = this;
function getRecord(id) {
return new Promise(function(resolve, reject) {
_this.server.tei.get(id).then(function(record) {
if (typeof record === 'undefined') {
reject(new Error('Record not found'));
}
resolve(record);
}).catch(function (err) {
reject(err);
});
});
}
return new Promise(function(resolve, reject) {
if (_this.server === null) {
_this.connect().then(function() {
resolve(getRecord(id));
}).catch(function (err) {
reject(err);
});
} else {
resolve(getRecord(id));
}
});
}
/**
* Update a record, ensuring that a connection is established first.
*/
update(record) {
var _this = this;
function updateRecord(record) {
return new Promise(function(resolve, reject) {
_this.server.tei.update(record).then(function() {
resolve();
}).catch(function (err) {
reject(err);
});
});
}
return new Promise(function(resolve, reject) {
if (_this.server === null) {
_this.connect().then(function() {
resolve(updateRecord(record));
}).catch(function (err) {
reject(err);
});
} else {
resolve(updateRecord(record));
}
});
}
/**
* Return multiple records, ensuring that a connection is established first.
*/
getMultiple(fromRecord=0, toRecord=50) {
var _this = this;
function getMultipleRecords(fromRecord, toRecord) {
return new Promise(function(resolve, reject) {
_this.server.tei.query()
.all()
.limit(fromRecord, toRecord)
.execute()
.then(function(records) {
resolve(records);
}).catch(function (err) {
reject(err);
});
});
}
return new Promise(function(resolve, reject) {
if (_this.server === null) {
_this.connect().then(function() {
resolve(getMultipleRecords(fromRecord, toRecord));
}).catch(function (err) {
reject(err);
});
} else {
resolve(getMultipleRecords(fromRecord, toRecord));
}
});
}
/**
* Count records, ensuring that a connection is established first.
*/
count() {
var _this = this;
function countRecords() {
return new Promise(function(resolve, reject) {
_this.server.tei.count().then(function (n) {
resolve(n);
}).catch(function (err) {
reject(err);
});
});
}
return new Promise(function(resolve, reject) {
if (_this.server === null) {
_this.connect().then(function() {
resolve(countRecords());
}).catch(function (err) {
reject(err);
});
} else {
resolve(countRecords());
}
});
}
}
export default window.dbServer = new DBServer();
|
JavaScript
| 0 |
@@ -3657,42 +3657,12 @@
get
-Multiple(fromRecord=0, toRecord=50
+All(
) %7B%0A
@@ -3708,24 +3708,19 @@
tion get
-Multiple
+All
Records(
@@ -3886,69 +3886,8 @@
l()%0A
- .limit(fromRecord, toRecord)%0A
@@ -4340,44 +4340,19 @@
(get
-MultipleRecords(fromRecord, toRecord
+AllRecords(
));%0A
@@ -4498,44 +4498,19 @@
(get
-MultipleRecords(fromRecord, toRecord
+AllRecords(
));%0A
@@ -5360,16 +5360,847 @@
%0A %7D%0A%0A
+ /**%0A * Clear all records, ensuring that a connection is established first.%0A */%0A clearAll() %7B%0A var _this = this;%0A%0A function clearAllRecords() %7B%0A return new Promise(function(resolve, reject) %7B%0A _this.server.tei.clear().then(function () %7B%0A resolve();%0A %7D).catch(function (err) %7B%0A reject(err);%0A %7D);%0A %7D);%0A %7D%0A%0A return new Promise(function(resolve, reject) %7B%0A if (_this.server === null) %7B%0A _this.connect().then(function() %7B%0A resolve(clearAllRecords());%0A %7D).catch(function (err) %7B%0A reject(err);%0A %7D);%0A %7D else %7B%0A resolve(clearAllRecords());%0A %7D%0A %7D);%0A %7D%0A%0A
%7D%0A%0Aexpor
|
7c6120ba5ab495f338597816958d268a7392c041
|
Make 'change' event of select component for table of GeoNames data
|
js/components/geonames-inputs.js
|
js/components/geonames-inputs.js
|
(function(app) {
'use strict';
var dom = app.dom || require('../dom.js');
var Collection = app.Collection || require('../base/collection.js');
var GeoNamesInputs = function(el, props) {
this.el = el;
this._geonamesAttrs = props.geonamesAttrs;
this._geonamesData = props.geonamesData;
this._inputElement = this.el.querySelector('input');
this._table = new GeoNamesInputs.Table(this.el.querySelector('.preferences-table'), props);
this._tableControls = new GeoNamesInputs.TableControls(this.el.querySelector('.preferences-table-controls'), props);
};
GeoNamesInputs.prototype.init = function() {
this._table.init();
this._tableControls.init();
this._inputElement.addEventListener('change', this._changeEnabled.bind(this));
this._geonamesAttrs.on('change:enabled', this._updateEnabled.bind(this));
this._geonamesData.on('loading', this._updateState.bind(this, 'loading'));
this._geonamesData.on('loaded', this._updateState.bind(this, 'loaded'));
this._geonamesData.on('error', this._updateState.bind(this, 'error'));
};
GeoNamesInputs.prototype._changeEnabled = function(event) {
this._geonamesAttrs.set('enabled', event.target.checked);
};
GeoNamesInputs.prototype._updateEnabled = function(enabled) {
this._inputElement.checked = enabled;
};
GeoNamesInputs.prototype._updateState = function(state) {
this.el.setAttribute('data-state', state);
};
GeoNamesInputs.Table = (function() {
var Table = function(el, props) {
this.el = el;
this._geonamesAttrs = props.geonamesAttrs;
};
Table.prototype.init = function() {
this._geonamesAttrs.on('change:enabled', this._updateEnabled.bind(this));
};
Table.prototype._updateEnabled = function(enabled) {
dom.toggleClass(this.el, 'disabled', !enabled);
};
return Table;
})();
GeoNamesInputs.TableControls = (function() {
var TableControls = function(el, props) {
this.el = el;
this._geonamesAttrs = props.geonamesAttrs;
this._geonamesData = props.geonamesData;
this._countryOptions = new Collection();
this._countrySelect = new GeoNamesInputs.TableSelect(this.el.querySelector(".preferences-table-select[name='country']"), {
options: this._countryOptions,
});
this._nameSelect = new GeoNamesInputs.TableSelect(this.el.querySelector(".preferences-table-select[name='name']"), { /* TODO */ });
};
TableControls.prototype.init = function() {
this._countrySelect.init();
this._geonamesAttrs.on('change:enabled', this._updateEnabled.bind(this));
this._geonamesData.on('loaded', this._dataLoaded.bind(this));
};
TableControls.prototype._updateEnabled = function(enabled) {
dom.toggleClass(this.el, 'disabled', !enabled);
};
TableControls.prototype._dataLoaded = function() {
var options = this._geonamesData.getCountries().map(function(country) {
return { value: country, label: country, selected: false };
});
options.unshift({ value: '', label: '--Select--', selected: true });
this._countryOptions.reset(options);
};
return TableControls;
})();
GeoNamesInputs.TableSelect = (function() {
var TableSelect = function(el, props) {
this.el = el;
this._options = props.options;
};
TableSelect.prototype.init = function() {
this._options.on('reset', this._reset.bind(this));
};
TableSelect.prototype._reset = function(options) {
var fragment = document.createDocumentFragment();
options.forEach(function(option) {
var s = "<option value='" + option.value + "'" + (option.selected ? ' selected' : '') + ">" + option.label + "</option>";
fragment.appendChild(dom.render(s));
});
this.el.innerHTML = '';
this.el.appendChild(fragment);
};
return TableSelect;
})();
if (typeof module !== 'undefined' && module.exports) {
module.exports = GeoNamesInputs;
} else {
app.GeoNamesInputs = GeoNamesInputs;
}
})(this.app || (this.app = {}));
|
JavaScript
| 0.000002 |
@@ -142,16 +142,75 @@
on.js');
+%0A var Events = app.Events %7C%7C require('../base/events.js');
%0A%0A var
@@ -3385,16 +3385,51 @@
ptions;%0A
+ this._events = new Events();%0A
%7D;%0A%0A
@@ -3489,51 +3489,237 @@
his.
-_options.on('reset', this._reset.bind(this)
+el.addEventListener('change', this._onchange.bind(this));%0A this._options.on('reset', this._reset.bind(this));%0A %7D;%0A%0A TableSelect.prototype.on = function() %7B%0A return Events.prototype.on.apply(this._events, arguments
);%0A
@@ -4129,32 +4129,197 @@
gment);%0A %7D;%0A%0A
+ TableSelect.prototype._onchange = function() %7B%0A var value = this.el.options%5Bthis.el.selectedIndex%5D.value;%0A this._events.emit('change', value);%0A %7D;%0A%0A
return Table
|
6ea488d29fbee5b78c1c225356c6ecef5383c238
|
Update toggle to use cookies and query params
|
src/main/webapp/scripts/toggle.js
|
src/main/webapp/scripts/toggle.js
|
const KEYWORDS_TEMPLATE_URL = '/templates/keywords.html';
const TEMPLATES_URL = [KEYWORDS_TEMPLATE_URL];
const KEYWORDS_OBJ_URL = '/keyword';
const NEWS_OBJ_URL = '/json/news.json';
const ACTIONS_OBJ_URL = '/actions';
const OBJECTS_URLS = [KEYWORDS_OBJ_URL, NEWS_OBJ_URL, ACTIONS_OBJ_URL];
const HTML_SECTIONS_PROMISE = loadHtmlSections(TEMPLATES_URL, OBJECTS_URLS);
/**
* Loads an array of html templates, an array of json objects, and renders them using mustache.
* Returns a promise.all of all the render html sections.
*/
async function loadHtmlSections(templatesUrls, objsUrls) {
const htmlTemplatesPromises = loadUrls(templatesUrls, loadTemplate);
const objsPromises = loadUrls(objsUrls, loadObject);
const values = await Promise.all([htmlTemplatesPromises, objsPromises]);
const templates = values[0];
const objs = values[1];
return renderTemplateObj(templates, objs);
}
function renderTemplateObj(templates, objs) {
let result = objs[0];
for (let i = 0; i < result.keywords.length; i++) {
let term = result.keywords[i].term;
result.keywords[i].news = objs[1].articles[term];
result.keywords[i].actions = objs[2].results[term];
}
let htmlSections = Mustache.render(templates[0], result);
return htmlSections;
}
/**
* Activates the section that triggered the event.
*/
function activateSection(event) {
const selectedOption = event.currentTarget.value;
loadSection(selectedOption);
return;
}
/**
* Loads the content section.
*/
async function loadContentSection() {
const htmlSection = await HTML_SECTIONS_PROMISE;
$("#content").html(htmlSection);
return;
}
|
JavaScript
| 0 |
@@ -54,55 +54,8 @@
ml';
-%0Aconst TEMPLATES_URL = %5BKEYWORDS_TEMPLATE_URL%5D;
%0A%0Aco
@@ -79,23 +79,34 @@
URL = '/
+json/
keyword
+s.json
';%0Aconst
@@ -199,23 +199,19 @@
URLS = %5B
-KEYWORD
+NEW
S_OBJ_UR
@@ -213,19 +213,22 @@
BJ_URL,
-NEW
+ACTION
S_OBJ_UR
@@ -224,32 +224,73 @@
IONS_OBJ_URL
-, ACTION
+%5D;%0A%0Aconst KEYWORDS_PROMISE = loadKeywords(KEYWORD
S_OBJ_URL%5D;%0A
@@ -278,33 +278,33 @@
KEYWORDS_OBJ_URL
-%5D
+)
;%0A%0Aconst HTML_SE
@@ -337,24 +337,33 @@
ections(
+KEYWORDS_
TEMPLATE
S_URL, O
@@ -354,17 +354,16 @@
TEMPLATE
-S
_URL, OB
@@ -372,18 +372,516 @@
CTS_URLS
-);
+, KEYWORDS_PROMISE);%0A%0A/**%0A * Loads the keywords array from a servlet or from cookies.%0A * Returns a promise of the keywords array.%0A */%0Aasync function loadKeywords(keywordsUrl) %7B%0A const cookieName = 'keywords';%0A let keywords;%0A const cookie = getCookie(cookieName);%0A if (cookie === %22%22) %7B%0A keywords = await loadObject(keywordsUrl);%0A const keywordsJson = JSON.stringify(keywords);%0A setCookie(cookieName, keywordsJson, 7);%0A %7D else %7B%0A keywords = JSON.parse(cookie);%0A %7D%0A return keywords;%0A%7D
%0A%0A/**%0A *
@@ -1076,21 +1076,19 @@
template
-s
Url
-s
, objsUr
@@ -1089,16 +1089,33 @@
objsUrls
+, keywordsPromise
) %7B%0A co
@@ -1130,36 +1130,38 @@
Template
-s
Promise
-s
= load
-Urls
+Template
(templat
@@ -1165,27 +1165,167 @@
late
-s
Url
-s, loadTemplate
+);%0A const keywords = await keywordsPromise;%0A const queryString = %60?key=$%7Bkeywords.join('&key=')%7D%60;%0A objsUrls = objsUrls.map(url =%3E %60$%7Burl%7D$%7BqueryString%7D%60
);%0A
@@ -1427,25 +1427,23 @@
Template
-s
Promise
-s
, objsPr
@@ -1468,17 +1468,16 @@
template
-s
= value
@@ -1543,23 +1543,32 @@
template
-s
, objs
+, keywords
);%0A%7D%0A%0Afu
@@ -1604,15 +1604,24 @@
late
-s
, objs
+, keywords
) %7B%0A
@@ -1639,15 +1639,68 @@
t =
-objs%5B0%5D
+new Object();%0A result.keywords = new Array(keywords.length)
;%0A
@@ -1719,23 +1719,16 @@
0; i %3C
-result.
keywords
@@ -1757,16 +1757,72 @@
t term =
+ keywords%5Bi%5D;%0A result.keywords%5Bi%5D = new Object();%0A
result.
@@ -1837,16 +1837,23 @@
%5Bi%5D.term
+ = term
;%0A re
@@ -1881,17 +1881,17 @@
= objs%5B
-1
+0
%5D.articl
@@ -1942,9 +1942,9 @@
bjs%5B
-2
+1
%5D.re
@@ -2005,20 +2005,16 @@
template
-s%5B0%5D
, result
|
8ca480a240213dd7e30f371d9342a6af0c56b165
|
make lobby scope apply when connected.
|
js/frontend/controllers/lobby.js
|
js/frontend/controllers/lobby.js
|
define(['./module', 'darkwallet', 'frontend/services', 'frontend/channel_link', 'bitcoinjs-lib', 'util/protocol'],
function (controllers, DarkWallet, Services, ChannelLink, Bitcoin, Protocol) {
'use strict';
var selectedChannel;
controllers.controller('LobbyCtrl', ['$scope', 'notify', function($scope, notify) {
var transport, currentChannel;
// Link a channel with this scope by name
var channelLinks = {};
var linkChannel = function(name) {
var channelLink;
if (channelLinks.hasOwnProperty(name)) {
// Channel is already linked
channelLink = channelLinks[name];
} else {
// Totally new channel, subscribe
channelLink = new ChannelLink(name, $scope);
channelLinks[name] = channelLink;
channelLink.addCallback('subscribed', function() {
notify.success('channel', 'subscribed successfully')
channelLink.channel.sendOpening();
if(!$scope.$$phase) {
$scope.$apply();
}
})
channelLink.addCallback('Contact', function(data) {
notify.success('contact', data.body.name)
var peer = data.peer;
$scope.newContact = data.body;
$scope.newContact.pubKeyHex = peer.pubKeyHex;
$scope.newContact.fingerprint = peer.fingerprint;
})
channelLink.addCallback('Shout', function(data) {
var peer = channelLink.channel.getPeer(data.sender)
var channel = channelLink.channel;
// add user pubKeyHex to use as identicon
if (!data.peer) {
// lets set a dummy hex code for now
data.peer = {pubKeyHex: "deadbeefdeadbeefdeadbeef"};
}
// show notification
if (data.sender == channel.fingerprint) {
notify.success('me', data.body.text)
} else {
notify.note(data.sender.slice(0,12), data.body.text)
}
if (!$scope.$$phase) {
$scope.$apply();
}
})
}
$scope.shoutboxLog = channelLink.channel.chatLog;
selectedChannel = name;
$scope.subscribed = channelLink.channel.channelHash;
currentChannel = channelLink.channel;
if (!$scope.$$phase) {
$scope.$apply();
}
return channelLink;
}
// Lobby service port
Services.connectNg('lobby', $scope, function(data) {
// onMesssage callback
console.log("[LobbyCtrl] Message", data);
if (data.type == 'initChannel') {
linkChannel(data.name);
}
}, function(port) {
// onCreate callback
transport = DarkWallet.getLobbyTransport();
$scope.lobbyChannels = transport.channels;
$scope.pairCode = '';
// Initialize a channel
var connectChannel = function(name) {
var pairCodeHash = transport.hashChannelName(name);
if (transport.getChannel(name)) {
// Channel exists, relink
linkChannel(name);
} else {
// Create if it doesn't exist
ChannelLink.start(name, port);
}
$scope.subscribed = pairCodeHash;
}
if (!selectedChannel && transport.channels && transport.channels.length) {
// should remember the last connected channel but for
// now reconnect the first
selectedChannel = transport.channels[transport.channels.length-1].name;
}
$scope.subscribed = false;
$scope.shoutbox = '';
$scope.shoutboxLog = [];
// Initialize some own data
$scope.comms = transport.comms;
$scope.myself = transport.myself;
$scope.peers = transport.peers;
$scope.peerIds = transport.peerIds;
$scope.requests = transport.requests;
// Now reconnect or initialize
if (selectedChannel) {
connectChannel(selectedChannel);
}
$scope.selectChannel = function(channel) {
// Relink
connectChannel(channel.name);
if (currentChannel) {
currentChannel.sendOpening();
}
}
$scope.newTempIdentity = function() {
currentChannel.newSession();
currentChannel.sendOpening();
}
// Action to start announcements and reception
$scope.joinChannel = function() {
connectChannel($scope.pairCode);
}
$scope.selectPeer = function(peer) {
$scope.selectedPeer = peer;
}
$scope.pairPeer = function(peer) {
$scope.selectedPeer = peer;
var identity = DarkWallet.getIdentity();
var msg = Protocol.ContactMsg(identity);
currentChannel.postDH(peer.pubKey, msg, function() {
notify.success("lobby", "pairing sent");
});
}
$scope.sendText = function() {
var toSend = $scope.shoutbox;
// don't send empty shouts
if (toSend == '')
return;
$scope.shoutbox = '';
currentChannel.postEncrypted(Protocol.ShoutMsg(toSend), function(err, data) {
if (err) {
notify.error("error sending " + err)
}
});
}
$scope.addNewContact = function(contact) {
var identity = DarkWallet.getIdentity();
var newContact = {name: contact.name, address: contact.stealth, fingerprint: contact.fingerprint};
identity.contacts.addContact(newContact)
$scope.newContact = null;
notify.success('Contact added')
}
});
}]);
});
|
JavaScript
| 0 |
@@ -3916,32 +3916,90 @@
hannel);%0A %7D%0A%0A
+ if (!$scope.$$phase) %7B%0A $scope.$apply();%0A %7D%0A
$scope.selec
|
d6ef6cd0846f8543c129d34e672fe89939f2b58a
|
Update webpack.config.js comments
|
src/main/webapp/webpack.config.js
|
src/main/webapp/webpack.config.js
|
const path = require("path");
const webpack = require("webpack");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const TerserPlugin = require("terser-webpack-plugin");
const WebpackAssetsManifest = require("webpack-assets-manifest");
const i18nThymeleafWebpackPlugin = require("./webpack/i18nThymeleafWebpackPlugin");
const entries = require("./entries");
const formatAntStyles = require("./styles");
const antColours = formatAntStyles();
module.exports = (env, argv) => {
const isProduction = argv.mode === "production";
return {
/*
This option controls if and how source maps are generated.
1. Development: "eval-source-map" - Recommended choice for development builds with high quality SourceMaps.
2. Production: "source-map" - Recommended choice for production builds with high quality SourceMaps.
*/
devtool: isProduction ? "source-map" : "eval-source-map",
/*
Cache the generated webpack modules and chunks to improve build speed.
*/
cache: {
type: "filesystem",
},
entry: entries,
resolve: {
extensions: [".js", ".jsx"],
symlinks: false,
},
output: {
path: path.resolve(__dirname, "dist"),
pathinfo: false,
publicPath: `/dist/`,
filename: path.join("js", "[name]-[contenthash].js"),
chunkFilename: path.join("js", "[name]-[contenthash].chunk.js"),
},
/*
Prevent bundling of jQuery, it will be added (and exposed) through the vendor bundle.
*/
externals: {
jquery: "jQuery",
},
module: {
rules: [
{
test: /\.(js|jsx)$/i,
include: path.resolve(__dirname, "resources/js"),
loader: "babel-loader",
options: {
cacheCompression: false,
cacheDirectory: true,
},
},
{
test: /\.less$/i,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
{
loader: "less-loader",
options: {
lessOptions: {
modifyVars: antColours,
javascriptEnabled: true,
},
},
},
],
},
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
{ loader: "css-loader", options: { importLoaders: 1 } },
"postcss-loader",
],
},
{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: "asset/resource",
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/i,
type: "asset/resource",
},
],
},
optimization: {
/*
Only minimize assets for production builds
*/
...(isProduction
? {
minimize: true,
minimizer: [
new CssMinimizerPlugin({ parallel: true }),
new TerserPlugin({ parallel: true, include: /\/resources/ }),
],
runtimeChunk: "single",
splitChunks: {
name: false,
chunks(chunk) {
// exclude modals in projects-samples-*
return (
typeof chunk.name === "string" &&
!chunk.name.includes("project-samples-")
);
},
},
}
: { minimize: false }),
},
plugins: [
/*
Extract CSS into its own bundle.
*/
new MiniCssExtractPlugin({
ignoreOrder: true,
filename: "css/[name].bundle.css",
}),
/*
Custom IRIDA internationalization plugin. See Docs for more information
*/
new i18nThymeleafWebpackPlugin({
functionName: "i18n",
templatePath: path.join("..", "pages", "templates"),
}),
new webpack.ProvidePlugin({
// Provide the custom internationalization function.
i18n: path.resolve(
path.join(__dirname, path.join("resources", "js", "i18n"))
),
process: "process/browser",
}),
new WebpackAssetsManifest({
integrity: false,
entrypoints: true,
writeToDisk: true,
}),
],
};
};
|
JavaScript
| 0.000001 |
@@ -481,16 +481,358 @@
les%22);%0A%0A
+/**%0A * @file Webpack Build configuration file.%0A * Directs webpack how to compile CSS and JavaScript assets.%0A * Run in development: %60yarn start%60%0A * - Better source maps%0A * - No minification%0A * Run for production: %60yarn build%60%0A * - Assets will be chunked into proper sizes%0A * - Hashes will be appended to break cache with older files.%0A */%0A%0A
const an
@@ -4463,32 +4463,168 @@
ser%22,%0A %7D),%0A
+ /*%0A Webpack Manifest is used by the Webpacker Thymeleaf plugin to find assets required%0A for each entry point.%0A */%0A
new Webpac
|
07882b223605d36a512597ea8423eccdb02f1adb
|
Update command line option doc.
|
src/command_line_options/process_command_line_options.js
|
src/command_line_options/process_command_line_options.js
|
const commandLineArgs = require('command-line-args');
const {commandLineOptionDefinitions} = require('./command_line_option_definitions');
const {exit} = require('../util.js');
const clOpts = commandLineArgs(commandLineOptionDefinitions);
function processCommandLineOptions(mailServers) {
if (clOpts.help) {
console.info(`Run this program like this: \`node src/index.js --mailserver=localTest\`, where 'localTest' is the specified mail server.
\nSubstitute your choice of mailserver. Note that the mailserver is configured in 'conf/mail_servers.conf.js'.
\nOptionally supply '--keepListening true' to keep the server listening indefinitely for new mail messages.
\nGet the list of mail servers like this: \`node index.js --list\`
\nYou can also specify username and password (overrides any config).
\nPrepend all long-form option names with '--'. To reduce typing you can use the option aliases listed below in the command line option list.
\nPrepend all aliases (the short-form option names) with '-'.
\nHere are all command line options:
\n\nCommand Line Option List
\n------------------------
`);
console.log(commandLineOptionDefinitions);
exit(0);
}
if (clOpts.list) {
console.info(`The list of configured mail servers is:
\n(Beginning of list)
\n${Object.keys(mailServers).join()}
\n(End of list)
`);
exit(0);
}
console.log('\n\u2600 Running with these options:');
console.log(clOpts);
return clOpts;
}
module.exports = processCommandLineOptions;
|
JavaScript
| 0 |
@@ -822,16 +822,106 @@
onfig).%0A
+ %5CnThe 'startAt' option counts from zero being the first message on the email server.%0A
%5CnP
|
ba1ccb905de983ac0e2aaf2f1d83911b12db5b45
|
test form again
|
server/database/demo.js
|
server/database/demo.js
|
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit: 10,
host: process.env.MYSQL_HOST,
user: process.env.MYSQL_USER,
password: process.env.MYSQL_PASSWORD,
database: process.env.MYSQL_DB,
port: process.env.MYSQL_PORT
});
exports.createDemo = function(req, res) {
var data = req.body;
pool.getConnection(function(err, connection) {
connection.query(`INSERT INTO demos VALUES (null, ?, ?, ?, ?, ?, ?, ?, ?)`, [data.firstname, data.lastname, data.email, data.phone, data.jobtitle, data.company, data.country, data.page],function(err, rows, fields) {
if(err) throw err;
console.log(rows);
connection.release();
})
})
// if successful
res.render('demo', {message: "You're the best! We'll be in touch soon!", countries: ['US', 'Canada']});
}
|
JavaScript
| 0 |
@@ -688,20 +688,24 @@
render('
-demo
+home-dev
', %7Bmess
|
2b252f77d893ad8778656e9fe3bfda3aefa25290
|
change numer of sentences before loading external
|
assets/js/quiz.js
|
assets/js/quiz.js
|
var quiz = {
backend : "http://spraakbanken.gu.se/ws/korp?",
familjeliv : [
"FAMILJELIV-ADOPTION",
"FAMILJELIV-ALLMANNA-EKONOMI",
"FAMILJELIV-ALLMANNA-FAMILJELIV",
"FAMILJELIV-ALLMANNA-FRITID",
"FAMILJELIV-ALLMANNA-HUSHEM",
"FAMILJELIV-ALLMANNA-HUSDJUR",
"FAMILJELIV-ALLMANNA-KROPP",
"FAMILJELIV-ALLMANNA-NOJE",
"FAMILJELIV-ALLMANNA-SAMHALLE",
"FAMILJELIV-ALLMANNA-SANDLADAN",
"FAMILJELIV-EXPERT",
"FAMILJELIV-FORALDER",
"FAMILJELIV-GRAVID",
"FAMILJELIV-KANSLIGA",
"FAMILJELIV-MEDLEM-ALLMANNA",
"FAMILJELIV-MEDLEM-FORALDRAR",
"FAMILJELIV-MEDLEM-PLANERARBARN",
"FAMILJELIV-MEDLEM-VANTARBARN",
"FAMILJELIV-PAPPAGRUPP",
"FAMILJELIV-PLANERARBARN",
"FAMILJELIV-SEXSAMLEVNAD",
"FAMILJELIV-SVARTATTFABARN",
"FAMILJELIV-ANGLARUM"],
flashback: [
"FLASHBACK-DATOR",
"FLASHBACK-DROGER",
"FLASHBACK-FORDON",
"FLASHBACK-HEM",
"FLASHBACK-KULTUR",
"FLASHBACK-LIVSSTIL",
"FLASHBACK-MAT",
"FLASHBACK-POLITIK",
"FLASHBACK-RESOR",
"FLASHBACK-SAMHALLE",
"FLASHBACK-SEX",
"FLASHBACK-SPORT",
"FLASHBACK-VETENSKAP",
"FLASHBACK-OVRIGT",
"FLASHBACK-FLASHBACK"
],
punct : ['.', ',', '!', '?', ';', '-', '"', '\'', '(', ')'],
current : {},
getNewSentence : function(){
if(window.localStorage['quiz-sentences'] == undefined){
window.localStorage['quiz-sentences'] = JSON.stringify(preloaded);
}
var sentences = JSON.parse(window.localStorage['quiz-sentences']);
if(sentences.length == 0){
sentences = preloaded;
window.localStorage['quiz-sentences'] = JSON.stringify(preloaded);
this.loadNewSentences();
}
var random = Math.floor(Math.random()*sentences.length);
quiz.current = sentences[random];
sentences.splice(random, 1);
window.localStorage['quiz-sentences'] = JSON.stringify(sentences);
if(sentences.length == (preloaded.length - 15)){
this.loadNewSentences();
}
return quiz.current;
},
loadNewSentences : function(callback){
jQuery.ajaxSettings.traditional = true;
var corpora = this.getRandomCorpora();
$.each(corpora, function(index, corpus){
console.log('load from: '+corpus);
jQuery.ajax({
url:quiz.backend,
dataType:'jsonp', data: {
'command':'query_sample',
'corpus': corpus,
'start': 0,
'end': 5,
'cqp': '[]',
'defaultcontext':'1 sentence',
'show_struct':['text_username', 'text_date', 'thread_title']
}
}).done(function(data){
console.log(data);
if(data.hasOwnProperty('ERROR') == false){
jQuery.each(data.kwic, function(i, kwic) {
var sentence = "";
jQuery.each(kwic.tokens, function(key, val) {
if (jQuery.inArray(val.word, quiz.punct) > -1){
sentence = sentence.trim() + val.word;
}
else{
sentence += ' ' + val.word;
}
});
var sentences = JSON.parse(window.localStorage['quiz-sentences']);
sentences.push({f : kwic.corpus, s : sentence.trim()});
window.localStorage['quiz-sentences'] = JSON.stringify(sentences);
});
}
});
});
},
getRandomCorpora: function(){
var corpuslist = new Array();
var corpus_familjeliv = this.familjeliv[Math.floor(Math.random()*this.familjeliv.length)];
corpuslist.push(corpus_familjeliv);
var corpus_flashback = this.flashback[Math.floor(Math.random()*this.flashback.length)];
corpuslist.push(corpus_flashback);
return corpuslist;
}
}
|
JavaScript
| 0.000012 |
@@ -1837,17 +1837,17 @@
ength -
-1
+2
5))%7B%0A%09%09%09
|
cb5ef5ee2df00a33d0475a1befc119301e589a42
|
Make tap coordinates accurate when canvas is scaled or element is scrolled
|
src/Input/Methods/TapInput.js
|
src/Input/Methods/TapInput.js
|
function TapInput (element, tapRegions) {
this.element = typeof element !== 'undefined' ? element : document;
this.tapRegions = Array.isArray(tapRegions) ? tapRegions : [];
this.upCount = 0;
this.listeners = {
touchStart: this.tap.bind(this),
mouseDown: this.tap.bind(this)
};
}
TapInput.prototype.add = function (tapRegion) {
this.tapRegions.push(tapRegion);
};
TapInput.prototype.listen = function () {
this.element.addEventListener('touchstart', this.listeners.touchStart);
this.element.addEventListener('mousedown', this.listeners.mouseDown);
};
TapInput.prototype.tap = function (event) {
event.preventDefault();
// Used for both touchstart and mousedown events
var isTouchEvent = event.type === 'touchstart';
var x = isTouchEvent ? event.touches[0].clientX : event.clientX;
var y = isTouchEvent ? event.touches[0].clientY : event.clientY;
for (var i = 0; i < this.tapRegions.length; i += 1) {
var tapRegion = this.tapRegions[i];
if (tapRegion.boundingBox.isPointWithin(x, y) && typeof tapRegion.onTap === 'function') {
tapRegion.onTap(x, y);
}
}
};
TapInput.prototype.detach = function () {
this.element.removeEventListener('touchstart', this.listeners.touchStart);
this.element.removeEventListener('mousedown', this.listeners.mouseDown);
};
|
JavaScript
| 0 |
@@ -640,16 +640,17 @@
ault();%0A
+%0A
// Use
@@ -742,16 +742,342 @@
start';%0A
+%0A // Used to get position of point within element%0A var targetRect = event.target.getBoundingClientRect();%0A%0A // Scale factors for canvas%0A var scaleX = (this.element.width %7C%7C this.element.clientWidth) / this.element.clientWidth;%0A var scaleY = (this.element.height %7C%7C this.element.clientHeight) / this.element.clientWidth;%0A%0A
var x
@@ -1078,16 +1078,18 @@
var x =
+((
isTouchE
@@ -1120,16 +1120,17 @@
clientX
+
: event.
@@ -1136,16 +1136,45 @@
.clientX
+) - targetRect.left) * scaleX
;%0A var
@@ -1177,16 +1177,18 @@
var y =
+((
isTouchE
@@ -1219,16 +1219,17 @@
clientY
+
: event.
@@ -1235,16 +1235,44 @@
.clientY
+) - targetRect.top) * scaleY
;%0A for
|
ca6aed3c2ffabc91305840d40a2304b2c7bc9649
|
clean up notes schema
|
imports/api/notes/notes.js
|
imports/api/notes/notes.js
|
import SimpleSchema from 'simpl-schema';
import { Mongo } from 'meteor/mongo';
const CollectionManager = require('/imports/api/collection/CollectionManager.js');
let Notes = {};
Notes.schema = new SimpleSchema({
_id: {
type: String,
autoValue: function() {
if (!this.isSet) {
return Random.id();
}
}
},
createdAt: {
type: Date,
autoValue: function() {
if (!this.isSet) {
return new Date();
}
}
},
createdBy: {
type: String,
autoValue: function() {
if (!this.isSet) {
return Meteor.userId();
}
}
},
lastChangeBy: {
type: String,
autoValue: () => {
return Meteor.userId();
}
},
lastChangeAt: {
type: Date,
autoValue: () => {
return new Date();
}
},
title: {
type: String
},
text: {
type: String
},
authorId: {
type: String,
autoValue: function() {
if (!this.isSet) {
return Meteor.userId();
}
}
},
date: {
type: String,
autoValue: function() {
if (!this.isSet) {
return new Date();
}
}
},
time: {
type: String,
autoValue: function() {
if (!this.isSet) {
return new Date(); // TODO: get time
}
}
}
});
Notes.name = 'notes';
Notes.uniqueKeys = ['_id'];
Notes.attachSchema = Notes.schema;
Notes.persistence = new CollectionManager(Notes, Projects);
export default Notes;
|
JavaScript
| 0.000022 |
@@ -1032,180 +1032,8 @@
%7D,%0A
- authorId: %7B%0A type: String,%0A autoValue: function() %7B%0A if (!this.isSet) %7B%0A return Meteor.userId();%0A %7D%0A %7D%0A %7D,%0A
@@ -1110,75 +1110,24 @@
-if (!this.isSet) %7B%0A return new Date();%0A %7D
+return 'legacy';
%0A
@@ -1222,93 +1222,24 @@
-if (!this.isSet) %7B%0A return new Date(); // TODO: get time%0A %7D
+return 'legacy';
%0A
|
af39c7982062cdd7b067569a717a1d7accd960c3
|
Improve help text on matching context detail picker
|
webofneeds/won-owner-webapp/src/main/webapp/app/components/details/matching-context-picker.js
|
webofneeds/won-owner-webapp/src/main/webapp/app/components/details/matching-context-picker.js
|
import angular from "angular";
import { attach, delay } from "../../utils.js";
import { DomCache } from "../../cstm-ng-utils.js";
const serviceDependencies = ["$scope", "$element"];
function genComponentConf() {
let template = `
<div class="mcp__checkboxes">
<label ng-repeat="context in self.defaultBoxes">
<input type="checkbox" ng-model="context.selected" ng-change="self.updateMatchingContext()"/> {{context.name}}
</label>
</div>
<div class="mcp__helptext">
<span>use whitespace to separate context names</span>
</div>
<div class="mcp__input">
<input
class="mcp__input__inner"
type="text"
placeholder="e.g. 'sports fitness'"
ng-keyup="::self.updateMatchingContext()"
ng-class="{'mcp__input__inner--withreset' : self.showResetButton}"
/>
<svg class="mcp__input__icon clickable"
style="--local-primary:var(--won-primary-color);"
ng-if="self.showResetButton"
ng-click="self.resetMatchingContext()">
<use xlink:href="#ico36_close" href="#ico36_close"></use>
</svg>
</div>
<div class="mcp__contextlist">
<span class="mcp__contextlist__context" ng-repeat="context in self.addedContext">{{context}}</span>
</div>
<!-- TODO: style this -->
<button type="submit" class="won-button--outlined red mcp__restore-button"
ng-if="self.defaultMatchingContext && self.defaultMatchingContext.length > 0"
ng-click="::self.restoreDefault()">
<span>Restore Default</span>
</button>
`;
class Controller {
constructor() {
attach(this, serviceDependencies, arguments);
this.domCache = new DomCache(this.$element);
window.mcp4dbg = this;
this.addedContext = [];
// this.suggestedContext = this.suggestedMatchingContext;
this.defaultBoxes = [];
// this.suggestedBoxes = [];
this.showResetButton = false;
delay(0).then(() => this.showInitialMatchingContext());
}
showInitialMatchingContext() {
if (this.initialMatchingContext) {
let tempContext = [...this.initialMatchingContext];
this.addedContext = this.initialMatchingContext;
// deal with default contexts
if (
this.defaultMatchingContext &&
this.defaultMatchingContext.length > 0
) {
for (let context of this.defaultMatchingContext) {
let isPresent = !!this.initialMatchingContext.includes(context);
this.defaultBoxes.push({ name: context, selected: isPresent });
}
tempContext = this.initialMatchingContext.filter(
context => !this.defaultMatchingContext.includes(context)
);
}
if (tempContext.length > 0) {
this.textfield().value = tempContext.join(" ");
this.showResetButton = true;
}
}
this.$scope.$apply();
}
updateMatchingContext() {
const text = this.textfield().value;
let checkboxContext = [];
let textfieldContext = [];
// get values from checkboxes
for (let box of this.defaultBoxes) {
if (box && box.selected) checkboxContext.push(box.name);
}
// get values from text field
if (text && text.trim().length > 0) {
this.showResetButton = true;
textfieldContext = text.trim().split(/\s+/);
}
// - if textfield is empty -> hide resetbutton
else {
this.showResetButton = false;
}
// join & reduce
let combinedContext = [...checkboxContext, ...textfieldContext].reduce(
function(a, b) {
if (a.indexOf(b) < 0) a.push(b);
return a;
},
[]
);
// if empty -> reset, else callback
if (combinedContext.length > 0) {
this.addedContext = combinedContext;
this.onMatchingContextUpdated({ matchingContext: combinedContext });
} else {
this.resetMatchingContext();
}
}
resetMatchingContext() {
this.addedContext = this.showOnlyCheckedContexts();
this.textfield().value = "";
this.onMatchingContextUpdated({ matchingContext: [] });
this.showResetButton = false;
}
showOnlyCheckedContexts() {
let checkedContext = [];
for (let box of this.defaultBoxes) {
if (box.selected) {
checkedContext.push(box.name);
}
}
return checkedContext;
}
restoreDefault() {
this.addedContext = this.defaultMatchingContext || [];
this.textfield().value = "";
this.showResetButton = false;
this.onMatchingContextUpdated({
matchingContext: this.addedContext,
});
for (let box of this.defaultBoxes) {
box.selected = true;
}
}
textfieldNg() {
return this.domCache.ng(".mcp__input__inner");
}
textfield() {
return this.domCache.dom(".mcp__input__inner");
}
}
Controller.$inject = serviceDependencies;
return {
restrict: "E",
controller: Controller,
controllerAs: "self",
bindToController: true, //scope-bindings -> ctrl
scope: {
onMatchingContextUpdated: "&",
defaultMatchingContext: "=",
initialMatchingContext: "=",
},
template: template,
};
}
export default angular
.module("won.owner.components.matchingContextPicker", [])
.directive("wonMatchingContextPicker", genComponentConf).name;
|
JavaScript
| 0.000002 |
@@ -225,16 +225,167 @@
ate = %60%0A
+%09 %3Cdiv class=%22mcp__helptext%22%3E%0A %3Cspan%3ESet matching context(s): Restricts matches to posts with any of these contexts%3C/span%3E%0A %3C/div%3E%0A %0A
%3Cd
@@ -676,22 +676,37 @@
pan%3E
+C
us
-e white
+tom context(s) (Use
space
+s
to
@@ -725,14 +725,11 @@
text
- names
+s):
%3C/sp
|
f1aff81a7ef27e45a4ea82776fa078a259772dc4
|
fix linting #348
|
app/assets/javascripts/oxalis/view/right-menu/dataset_info_tab_view.js
|
app/assets/javascripts/oxalis/view/right-menu/dataset_info_tab_view.js
|
/**
* dataset_info_view.js
* @flow
*/
import _ from "lodash";
import React, { Component } from "react";
import { connect } from "react-redux";
import Maybe from "data.maybe";
import { getBaseVoxel } from "oxalis/model/scaleinfo";
import constants, { ControlModeEnum } from "oxalis/constants";
import { getPlaneScalingFactor } from "oxalis/model/accessors/flycam_accessor";
import { getSkeletonTracing } from "oxalis/model/accessors/skeletontracing_accessor";
import Store from "oxalis/store";
import TemplateHelpers from "libs/template_helpers";
import { setAnnotationNameAction } from "oxalis/model/actions/annotation_actions";
import EditableTextLabel from "oxalis/view/components/editable_text_label";
import type { OxalisState, TracingType, DatasetType, FlycamType, TaskType } from "oxalis/store";
type DatasetInfoTabStateProps = {
tracing: TracingType,
dataset: DatasetType,
flycam: FlycamType,
task: ?TaskType,
};
type DatasetInfoTabProps = DatasetInfoTabStateProps & { setAnnotationName: string => void };
class DatasetInfoTabView extends Component<DatasetInfoTabProps> {
calculateZoomLevel(): number {
let width;
let zoom;
const viewMode = Store.getState().temporaryConfiguration.viewMode;
if (constants.MODES_PLANE.includes(viewMode)) {
zoom = getPlaneScalingFactor(this.props.flycam);
width = constants.PLANE_WIDTH;
} else if (constants.MODES_ARBITRARY.includes(viewMode)) {
zoom = this.props.flycam.zoomStep;
width = constants.ARBITRARY_WIDTH;
} else {
throw Error(`Model mode not recognized: ${viewMode}`);
}
// unit is nm
const baseVoxel = getBaseVoxel(this.props.dataset.scale);
return zoom * width * baseVoxel;
}
chooseUnit(zoomLevel: number): string {
if (zoomLevel < 1000) {
return `${zoomLevel.toFixed(0)} nm`;
} else if (zoomLevel < 1000000) {
return `${(zoomLevel / 1000).toFixed(1)} μm`;
} else {
return `${(zoomLevel / 1000000).toFixed(1)} mm`;
}
}
setAnnotationName = (newName: string) => {
this.props.setAnnotationName(newName);
};
render() {
const { tracingType, name } = this.props.tracing;
const tracingName = name || "<untitled>";
const treesMaybe = getSkeletonTracing(this.props.tracing).chain(tracing =>
Maybe.fromNullable(tracing.trees),
);
const treeCount = treesMaybe.map(trees => _.size(trees)).getOrElse(null);
const nodeCount = treesMaybe
.map(trees => _.reduce(trees, (sum, tree) => (sum += _.size(tree.nodes)), 0))
.getOrElse(null);
const branchPointCount = treesMaybe
.map(trees => _.reduce(trees, (sum, tree) => (sum += _.size(tree.branchPoints)), 0))
.getOrElse(null);
let annotationTypeLabel;
if (this.props.task != null) {
// In case we have a task display its id as well
annotationTypeLabel = (
<span>
{tracingType} : {this.props.task.id}
</span>
);
} else {
// Or display an explorative tracings name
annotationTypeLabel = (
<span>
Explorational Tracing :
<EditableTextLabel value={tracingName} onChange={this.setAnnotationName} />
</span>
);
}
const zoomLevel = this.calculateZoomLevel();
const dataSetName = this.props.dataset.name;
const isPublicViewMode =
Store.getState().temporaryConfiguration.controlMode === ControlModeEnum.VIEW;
return (
<div className="flex-overflow">
<p>
{annotationTypeLabel}
</p>
<p>
Dataset: {dataSetName}
</p>
<p>
Viewport Width: {this.chooseUnit(zoomLevel)}
</p>
<p>
Dataset Resolution: {TemplateHelpers.formatScale(this.props.dataset.scale)}
</p>
{this.props.tracing.type === "skeleton"
? <div>
<p>
Number of Trees: {treeCount}
</p>
<p>
Number of Nodes: {nodeCount}
</p>
<p>
Number of Branch Points: {branchPointCount}
</p>
</div>
: null}
{isPublicViewMode
? <div>
<table className="table table-condensed table-nohead table-bordered">
<tbody>
<tr>
<th colSpan="2">Controls</th>
</tr>
<tr>
<td>I,O or Alt + Mousewheel</td>
<td>Zoom in/out</td>
</tr>
<tr>
<td>Mousewheel or D and F</td>
<td>Move Along 3rd Axis</td>
</tr>
<tr>
<td>Left Mouse Drag or Arrow Keys</td>
<td>Move</td>
</tr>
<tr>
<td>Right Click Drag in 3D View</td>
<td>Rotate 3D View</td>
</tr>
<tr>
<td>K,L</td>
<td>Scale Up/Down Viewports</td>
</tr>
</tbody>
</table>
<div>
<img
className="img-50"
src="/assets/images/Max-Planck-Gesellschaft.svg"
alt="Max Plank Geselleschaft Logo"
/>
<img
className="img-50"
src="/assets/images/MPI-brain-research.svg"
alt="Max Plank Institute of Brain Research Logo"
/>
</div>
</div>
: null}
</div>
);
}
}
const mapStateToProps = (state: OxalisState): DatasetInfoTabStateProps => ({
tracing: state.tracing,
dataset: state.dataset,
flycam: state.flycam,
task: state.task,
});
const mapDispatchToProps = (dispatch: Dispatch<*>) => ({
setAnnotationName(tracingName: string) {
dispatch(setAnnotationNameAction(tracingName));
},
});
export default connect(mapStateToProps, mapDispatchToProps)(DatasetInfoTabView);
|
JavaScript
| 0 |
@@ -2429,32 +2429,83 @@
nt = treesMaybe%0A
+ // eslint-disable-next-line no-return-assign%0A
.map(trees
@@ -2632,24 +2632,75 @@
treesMaybe%0A
+ // eslint-disable-next-line no-return-assign%0A
.map(t
|
90cb5c55e51d4785b205a4b0e79c9f9b1957a1f7
|
Update gulp setup to look in my modules directory when importing modules
|
gulp/browserify.js
|
gulp/browserify.js
|
'use strict';
import path from 'path';
import glob from 'glob';
import browserify from 'browserify';
import watchify from 'watchify';
import envify from 'envify';
import babelify from 'babelify';
import _ from 'lodash';
import vsource from 'vinyl-source-stream';
import buffer from 'vinyl-buffer';
import gulpif from 'gulp-if';
export default function(gulp, plugins, args, config, taskTarget, browserSync) {
let dirs = config.directories;
let entries = config.entries;
let browserifyTask = (files) => {
return files.map((entry) => {
let dest = path.resolve(taskTarget);
// Options
let customOpts = {
entries: [entry],
debug: true,
transform: [
babelify, // Enable ES6 features
envify // Sets NODE_ENV for better optimization of npm packages
]
};
let bundler = browserify(customOpts);
if (!args.production) {
// Setup Watchify for faster builds
let opts = _.assign({}, watchify.args, customOpts);
bundler = watchify(browserify(opts));
}
let rebundle = function() {
let startTime = new Date().getTime();
bundler.bundle()
.on('error', function(err) {
plugins.util.log(
plugins.util.colors.red('Browserify compile error:'),
'\n',
err.stack,
'\n'
);
this.emit('end');
})
.on('error', plugins.notify.onError(config.defaultNotification))
.pipe(vsource(entry))
.pipe(buffer())
.pipe(plugins.sourcemaps.init({loadMaps: true}))
.pipe(gulpif(args.production, plugins.uglify()))
.on('error', plugins.notify.onError(config.defaultNotification))
.pipe(plugins.rename(function(filepath) {
// Remove 'source' directory as well as prefixed folder underscores
// Ex: 'src/_scripts' --> '/scripts'
filepath.dirname = filepath.dirname.replace(dirs.source, '').replace('_', '');
}))
.pipe(plugins.sourcemaps.write('./'))
.pipe(gulp.dest(dest))
// Show which file was bundled and how long it took
.on('end', function() {
let time = (new Date().getTime() - startTime) / 1000;
console.log(
plugins.util.colors.cyan(entry)
+ ' was browserified: '
+ plugins.util.colors.magenta(time + 's'));
return browserSync.reload('*.js');
});
};
if (!args.production) {
bundler.on('update', rebundle); // on any dep update, runs the bundler
bundler.on('log', plugins.util.log); // output build logs to terminal
}
return rebundle();
});
};
// Browserify Task
gulp.task('browserify', (done) => {
return glob('./' + path.join(dirs.source, dirs.scripts, entries.js), function(err, files) {
if (err) {
done(err);
}
return browserifyTask(files);
});
});
}
|
JavaScript
| 0 |
@@ -819,16 +819,69 @@
%5D
+,%0A paths: %5B'./node_modules','./src/_modules/'%5D
%0A %7D
|
e8a53d7051104a35232d8f0cc2eddebfa34f137f
|
Revert jade changes
|
gulp/tasks/jade.js
|
gulp/tasks/jade.js
|
var gulp = require('gulp');
var jade = require('gulp-jade');
var plumber = require('gulp-plumber');
var changed = require('gulp-changed');
var gulpif = require('gulp-if');
var frontMatter = require('gulp-front-matter');
var prettify = require('gulp-prettify');
var config = require('../config');
function renderHtml(onlyChanged) {
return gulp
.src([config.src.templates + '/[^_]*.jade'])
.pipe(plumber({ errorHandler: config.errorHandler }))
.pipe(gulpif(onlyChanged, changed(config.dest.html, { extension: '.html' })))
.pipe(frontMatter({ property: 'data' }))
.pipe(jade())
.pipe(prettify({
indent_size: 2,
wrap_attributes: 'auto', // 'force'
preserve_newlines: true,
// unformatted: [],
end_with_newline: true
}))
.pipe(gulp.dest(config.dest.html));
}
gulp.task('jade', function() {
return renderHtml();
});
gulp.task('jade:changed', function() {
return renderHtml(true);
});
gulp.task('jade:watch', function() {
gulp.watch([config.src.templates + '/**/_*.jade'], ['jade']);
gulp.watch([config.src.templates + '/**/[^_]*.jade'], ['jade:changed']);
});
|
JavaScript
| 0.000001 |
@@ -740,17 +740,16 @@
uto', //
-
'force'%0A
|
f4120ac5c257c0269c4ac0e3d28b5cebbed2a226
|
Clean up api
|
imports/api/api.js
|
imports/api/api.js
|
import { Tasks } from './tasks/tasks.js'
import './tasks/methods.js'
if (Meteor.isServer) {
console.log("PUBLISHING TASKS!!!");
// This code only runs on the server
// Only publish tasks that are public or belong to the current user
Meteor.publish('tasks', function tasksPublication() {
return Tasks.find({ user_id: this.userId });
});
}
export { Tasks }
|
JavaScript
| 0 |
@@ -90,85 +90,8 @@
) %7B%0A
- console.log(%22PUBLISHING TASKS!!!%22);%0A // This code only runs on the server%0A
//
@@ -119,22 +119,8 @@
hat
-are public or
belo
@@ -252,16 +252,55 @@
);%0A %7D);
+%0A%0A console.log(%22PUBLISHING TASKS!!!%22);
%0A%7D%0A%0Aexpo
|
11b2bad8e9ae090d80fd8ef196e0683ad0c2e797
|
fix lint
|
fava/static/javascript/editor.js
|
fava/static/javascript/editor.js
|
/* global Mousetrap */
const URI = require('urijs');
const CodeMirror = require('codemirror/lib/codemirror');
require('codemirror/mode/sql/sql');
require('codemirror/addon/mode/simple');
// search
require('codemirror/addon/dialog/dialog');
require('codemirror/addon/search/searchcursor');
require('codemirror/addon/search/search');
// print margin
require('codemirror/addon/display/rulers');
// trailing whitespace
require('codemirror/addon/edit/trailingspace');
// folding
require('codemirror/addon/fold/foldcode');
require('codemirror/addon/fold/foldgutter');
require('./codemirror-fold-beancount.js');
// auto-complete
require('codemirror/addon/hint/show-hint');
require('./codemirror-hint-beancount.js');
require('./codemirror-mode-beancount.js');
function saveEditorContent(cm) {
const $button = $('#source-editor-submit');
const fileName = $('#source-editor-select').val();
$button
.attr('disabled', 'disabled')
.text('Saving...');
$.ajax({
type: 'PUT',
url: $button.data('url'),
data: {
file_path: fileName,
source: cm.getValue(),
}
})
.done((data) => {
if (!data.success) {
alert(`Writing to\n\n\t${fileName}\n\nwas not successful.`);
} else {
$button
.removeAttr('disabled')
.text('Save');
cm.focus();
}
});
}
function formatEditorContent(cm) {
const $button = $('#source-editor-format');
const scrollPosition = cm.getScrollInfo().top;
$button.attr('disabled', 'disabled');
const url = $button.attr('data-url');
$.post(url, {
source: cm.getValue(),
})
.done((data) => {
if (data.success) {
cm.setValue(data.payload);
cm.scrollTo(null, scrollPosition);
} else {
alert('There was an error formatting the file with bean-format.');
}
$button.removeAttr('disabled');
});
}
function centerCursor(cm) {
const top = cm.cursorCoords(true, 'local').top;
const height = cm.getScrollInfo().clientHeight;
cm.scrollTo(null, top - (height / 2));
}
function jumpToMarker(cm) {
const cursor = cm.getSearchCursor('FAVA-INSERT-MARKER');
if (cursor.findNext()) {
cm.focus();
cm.setCursor(cursor.pos.from);
cm.execCommand('goLineUp');
centerCursor(cm);
} else {
cm.setCursor(cm.lastLine(), 0);
}
}
module.exports.initEditor = function initEditor() {
const rulers = [];
if (window.editorPrintMarginColumn) {
rulers.push({
column: window.editorPrintMarginColumn,
lineStyle: 'dotted',
});
}
const defaultOptions = {
mode: 'beancount',
indentUnit: 4,
lineNumbers: true,
rulers,
foldGutter: true,
showTrailingSpace: true,
gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
extraKeys: {
'Ctrl-Space': 'autocomplete',
'Ctrl-S': (cm) => {
saveEditorContent(cm);
},
'Cmd-S': (cm) => {
saveEditorContent(cm);
},
'Ctrl-D': (cm) => {
formatEditorContent(cm);
},
'Cmd-D': (cm) => {
formatEditorContent(cm);
},
Tab: (cm) => {
if (cm.somethingSelected()) {
cm.indentSelection('add');
} else {
cm.execCommand('insertSoftTab');
}
},
},
};
const readOnlyOptions = {
mode: 'beancount',
readOnly: true,
};
const queryOptions = {
mode: 'text/x-sql',
lineNumbers: true,
extraKeys: {
'Ctrl-Enter': () => {
$('#submit-query').click();
},
'Cmd-Enter': () => {
$('#submit-query').click();
},
},
};
// Read-only editors
$('.editor-readonly').each((i, el) => {
CodeMirror.fromTextArea(el, readOnlyOptions);
});
// Query editor
if ($('#query-editor').length) {
const editor = CodeMirror.fromTextArea(document.getElementById('query-editor'), queryOptions);
// when the focus is outside the editor
Mousetrap.bind(['ctrl+enter', 'meta+enter'], (event) => {
event.preventDefault();
$('#submit-query').click();
});
$('.stored-queries select').change((event) => {
const sourceElement = $('.stored-queries a.source-link');
const query = $(event.currentTarget).val();
const sourceLink = $('option:selected', event.currentTarget).attr('data-source-link');
editor.setValue(query);
sourceElement.attr('href', sourceLink).toggle(query !== '');
});
}
// The /source/ editor
if ($('#source-editor').length) {
const el = document.getElementById('source-editor');
const editor = CodeMirror.fromTextArea(el, defaultOptions);
editor.on('keyup', (cm, event) => {
if (!cm.state.completionActive && event.keyCode !== 13) {
CodeMirror.commands.autocomplete(cm, null, { completeSingle: false });
}
});
const line = parseInt(new URI(location.search).query(true).line, 10);
if (line > 0) {
editor.setCursor(line - 1, 0);
centerCursor(editor);
} else {
jumpToMarker(editor);
}
$('#source-editor-select').change((event) => {
event.preventDefault();
event.stopImmediatePropagation();
const $select = $(event.currentTarget);
$select.attr('disabled', 'disabled');
const filePath = $select.val();
$.get($select.parents('form').attr('action'), {
file_path: filePath,
})
.done((data) => {
editor.setValue(data);
editor.setCursor(0, 0);
$select.removeAttr('disabled');
jumpToMarker(editor);
});
});
// keybindings when the focus is outside the editor
Mousetrap.bind(['ctrl+s', 'meta+s'], (event) => {
event.preventDefault();
saveEditorContent(editor);
});
Mousetrap.bind(['ctrl+d', 'meta+d'], (event) => {
event.preventDefault();
formatEditorContent(editor);
});
$('#source-editor-submit').click((event) => {
event.preventDefault();
event.stopImmediatePropagation();
saveEditorContent(editor);
});
$('#source-editor-format').click((event) => {
event.preventDefault();
event.stopImmediatePropagation();
formatEditorContent(editor);
});
}
};
|
JavaScript
| 0.000004 |
@@ -1090,16 +1090,17 @@
),%0A %7D
+,
%0A %7D)%0A
|
020537ee76339b589d098454d49ebb5c531f815d
|
Include embeds in logs
|
src/modules/commands/data/log.js
|
src/modules/commands/data/log.js
|
const { Command } = require('discord-akairo');
const moment = require('moment');
const fs = require('fs');
function exec(message, args){
try {
fs.mkdirSync('./src/data/logs/');
} catch (err) {
if (err.code !== 'EEXIST') throw err;
}
return message.channel.fetchMessages({ limit: 100, before: args.before || undefined }).then(messages => {
const object = {
location: {
channel: message.channel.name || 'DM',
channelID: message.channel.id,
guild: message.guild ? message.guild.name : undefined,
guildID: message.guild ? message.guild.id : undefined
},
messages: messages.map(m => {
return {
id: m.id,
author: m.author.username,
authorID: m.author.id,
time: m.createdTimestamp,
date: m.createdAt.toString(),
content: m.cleanContent,
attachment: m.attachments.size ? m.attachments.first().url : undefined
};
})
};
const filename = `./src/data/logs/log_${moment(message.createdTimestamp).format('YYYY-MM-DD_HH-mm-ss')}.json`;
fs.writeFileSync(filename, JSON.stringify(object, null, '\t'));
this.client.logger.log(2, `Saved messages to ${filename}.`);
return message.delete();
});
}
module.exports = new Command('log', exec, {
aliases: ['log', 'logs'],
args: [
{
id: 'before'
}
],
category: 'data'
});
|
JavaScript
| 0.000001 |
@@ -1081,16 +1081,1005 @@
().url :
+ undefined,%0A embeds: m.embeds.length ? m.embeds.map(embed =%3E %7B%0A return %7B%0A title: embed.title %7C%7C undefined,%0A url: embed.url %7C%7C undefined,%0A color: embed.color %7C%7C undefined,%0A description: embed.description %7C%7C undefined,%0A fields: embed.fields.length ? embed.fields.map(field =%3E %7B%0A return %7B%0A name: field.name,%0A value: field.value%0A %7D;%0A %7D) : undefined,%0A thumbnail: embed.thumbnail && embed.thumbnail.url %7C%7C undefined,%0A image: embed.image && embed.image.url %7C%7C undefined,%0A footer: embed.footer && embed.footer.text %7C%7C undefined,%0A %7D;%0A %7D) :
undefin
|
5c91a5b71cff1ffa087cfb2d88a0d53a836c521a
|
Fix a TODO to not use my username muscle-memoried from work :)
|
server/wsapi/lobbies.js
|
server/wsapi/lobbies.js
|
import { EventEmitter } from 'events'
import { Map } from 'immutable'
import cuid from 'cuid'
import errors from '../http/errors'
import { Mount, Api, registerApiRoutes } from '../websockets/api-decorators'
function validateBody(bodyValidators) {
return async function(data, next) {
const body = data.get('body')
if (!body) throw new errors.BadRequest('invalid body')
for (const key of Object.keys(bodyValidators)) {
if (!bodyValidators[key](body[key])) {
throw new errors.BadRequestError(`Invalid ${key}`)
}
}
return await next(data)
}
}
const nonEmptyString = str => typeof str === 'string' && str.length > 0
class Player {
constructor(name, race) {
this.name = name
this.id = cuid()
this.race = race
}
}
export class Lobby extends EventEmitter {
constructor(name, map, numSlots, hostName, hostRace = 'r') {
super()
this.name = name
this.map = map
this.numSlots = numSlots
this.players = new Map()
this.slots = new Array(numSlots)
this.hostName = hostName
const { player: hostPlayer } = this.addPlayer(hostName, hostRace)
this.hostId = hostPlayer.id
const self = this
this._serialized = {
get name() { return self.name },
get map() { return self.map },
get numSlots() { return self.numSlots },
get host() { return { name: self.hostName, id: self.hostId } },
get filledSlots() { return self.players.size }
}
}
toJSON() {
return this._serialized
}
// Adds a player in the first available slot
addPlayer(name, race = 'r') {
if (this.players.size >= this.numSlots) throw new Error('no open slots')
const player = new Player(name, race)
this.players = this.players.set(player.id, player)
let slot
for (slot = 0; slot < this.slots.length; slot++) {
if (!this.slots[slot]) {
this.slots[slot] = player
break
}
}
if (slot === this.slots.length) throw new Error('no empty slot found')
return { player, slot }
}
// Removes the player with specified `id`, returning whether or not the lobby should be closed
removePlayer(id) {
if (!this.players.has(id)) throw new Error('player not found')
this.players = this.players.delete(id)
for (let slot = 0; slot < this.slots.length; slot++) {
if (this.slots[slot] && this.slots[slot].id === id) {
delete this.slots[slot]
break
}
}
// TODO(tec27): handle computers
return this.players.size === 0
}
}
@Mount('/lobbies')
export class LobbyApi {
constructor(nydus, userSockets) {
this.nydus = nydus
this.userSockets = userSockets
this.lobbyMap = new Map()
this.userToLobby = new Map()
}
@Api('/create',
validateBody({
name: nonEmptyString,
map: nonEmptyString,
numSlots: s => s >= 2 && s <= 8,
}),
'getUser',
'ensureNotInLobby')
async create(data, next) {
const { name, map, numSlots } = data.get('body')
const user = data.get('user')
if (this.lobbyMap.has('name')) {
throw new errors.ConflictError('already another lobby with that name')
}
const lobby = new Lobby(name, map, numSlots, user.name)
this.lobbyMap = this.lobbyMap.set(name, lobby)
this.userToLobby = this.userToLobby.set(user, lobby)
// TODO(travisc): in theory these should be unnecessary (we just need to monitor user
// disconnects out here, and let Lobby tell us when it can be closed on parts (map disconnects
// through same part code). Then Lobby could have less complexity (no need for EE).
lobby.on('close', () => this.lobbyMap = this.lobbyMap.delete(name))
.on('userLeft', user => this.userToLobby = this.userToLobby.delete(user))
// TODO(tec27): subscribe user, deal with new sockets for that user
}
async getUser(data, next) {
const user = this.userSockets.get(data.client)
if (!user) throw new errors.UnauthorizedError('authorization required')
const newData = data.set('user', user)
return await next(newData)
}
async ensureNotInLobby(data, next) {
if (this.userToLobby.has(data.get('user'))) {
throw new errors.ConflictError('cannot enter multiple lobbies at once')
}
return await next(data)
}
}
export default function registerApi(nydus, userSockets) {
const api = new LobbyApi(nydus, userSockets)
registerApiRoutes(api, nydus)
return api
}
|
JavaScript
| 0 |
@@ -3331,14 +3331,12 @@
DO(t
-ravisc
+ec27
): i
|
e67d17867a4bfee23dc5f403dda23b9096a3ba73
|
fix bug
|
services/grabService.js
|
services/grabService.js
|
var co = require('co');
var request = require('co-request');
var cheerio = require('cheerio');
var CronJob = require('cron').CronJob;
var moment = require('moment');
var mongoose = require('mongoose');
var OneModel = mongoose.model('One');
var logger = require('winston');
module.exports = function() {
grab(); //启动时抓取一次
new CronJob('0 0 1 * * *', grab, null, true, 'Asia/Shanghai');
};
var grab = function() {
co(function*() {
var localVol = yield getLocalVol();
var vol = getTodayVol();
logger.info("local's vol = " + localVol);
logger.info("today's vol = " + vol);
var one = {};
var path , result, $;
for (var i = localVol + 1; i <= vol; i++) {
path = 'http://wufazhuce.com/one/vol.' + i;
result = yield request(path);
if (result.statusCode !== 200) {
throw Error('can not get ' + path);
}
//console.log(result.body);
$ = cheerio.load(result.body, {
decodeEntities: false
});
//var one = {};
one.vol = i;
one.tilte = $('h2.articulo-titulo').text().trim();
one.author = $('p.articulo-autor').text().trim().replace('作者/', '');
one.abstract = $('div.comilla-cerrar').text().trim();
one.article = $('div.articulo-contenido').html();
one.one = $('div.one-cita').text().trim();
one.date = parseDate($('p.dom').text(), $('p.may').text()).unix();
one.imgUrl = $('div.one-imagen img').attr('src');
one.imgDetail = $('div.one-imagen-leyenda').text().trim();
yield new OneModel(one).save();
logger.info("save vol." + one.vol + " success");
}
}).then(function() {
logger.info("grab done");
}).catch(function(err) {
logger.error(err.stack);
});
}
var parseDate = function(day, monthAndYear) {
var dateStr = day + " " + monthAndYear + " +0800";
return moment(dateStr, 'D MMM YYYY Z');
}
var getTodayVol = function() {
var day1 = moment("8 Oct 2012 +0800", 'D MMM YYYY Z');
// var sub = moment().subtract(day1);
return (moment().subtract(day1.unix(), "seconds").unix() / (24 * 60 * 60) | 0) + 1; // today - firstday +1
};
var getLocalVol = function*() {
var res = yield OneModel.find({}, {
vol: 1
}).sort({
vol: -1
}).limit(1);
logger.info(res[0].vol);
return res.length > 0 ? res[0].vol : 0;
};
|
JavaScript
| 0.000001 |
@@ -2123,34 +2123,8 @@
1);%0A
-%09logger.info(res%5B0%5D.vol);%0A
%09ret
|
1a21bf6093d2d9b70882f60505c24b68db17c1a9
|
add better explanation of BETA status
|
src/store.async.js
|
src/store.async.js
|
/**
* Copyright (c) 2019 ESHA Research
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Adds an 'async' duplicate on all store APIs that
* performs storage-related operations asynchronously and returns
* a promise.
*
* Status: BETA - needs testing and better docs
*/
;(function(window, _) {
var dontPromisify = ['async', 'area', 'namespace', 'isFake', 'toString'];
_.promisify = function(api) {
var async = api.async = _.Store(api._id, api._area, api._ns);
async._async = true;
Object.keys(api).forEach(function(name) {
if (name.charAt(0) !== '_' && dontPromisify.indexOf(name) < 0) {
var fn = api[name];
if (typeof fn === "function") {
async[name] = _.promiseFn(name, fn, api);
}
}
});
return async;
};
_.promiseFn = function(name, fn, self) {
return function promised() {
var args = arguments;
return new Promise(function(resolve, reject) {
setTimeout(function() {
try {
resolve(fn.apply(self, args));
} catch (e) {
reject(e);
}
}, 0);
});
};
};
// promisify existing apis
for (var apiName in _.apis) {
_.promisify(_.apis[apiName]);
}
// ensure future apis are promisified
Object.defineProperty(_.storeAPI, 'async', {
enumerable: true,
configurable: true,
get: function() {
var async = _.promisify(this);
// overwrite getter to avoid re-promisifying
Object.defineProperty(this, 'async', {
enumerable: true,
value: async
});
return async;
}
});
})(window, window.store._);
|
JavaScript
| 0 |
@@ -340,37 +340,58 @@
A -
-needs testing and better docs
+works great, but lacks justification for existence
%0A */
|
f204be5fea7dd03ca90db43204cebc9063b86981
|
Add email verification link to unwanted paths.
|
src/inject/inject.js
|
src/inject/inject.js
|
// Retriving user options
chrome.extension.sendMessage({}, function(settings) {
initOnHashChangeAction(settings['Domains'])
initShortcuts(settings['Shortcut'], settings['BackgroundShortcut'])
initListViewShortcut(settings['RegExp'])
})
function initOnHashChangeAction(domains) {
allDomains = "//github.com,"
if(domains) allDomains += domains
// Take string -> make array -> make queries -> avoid nil -> join queries to string
selectors = allDomains.replace(/\s/, '').split(',').map(function (name) {
if (name.length) return (".AO [href*='" + name + "']")
}).filter(function(name) { return name }).join(", ")
intervals = []
// Find GitHub link and append it to tool bar on hashchange
window.onhashchange = function() {
fetchAndAppendGitHubLink()
}
function fetchAndAppendGitHubLink() {
// In case previous intervals got interrupted
clearAllIntervals()
retryForActiveMailBody = setInterval(function() {
mail_body = $('.nH.hx').filter(function() { return this.clientHeight != 0 })[0]
if( mail_body ) {
github_links = mail_body.querySelectorAll(selectors)
github_links = reject_unwanted_paths(github_links)
// Avoid multple buttons
$('.github-link').remove()
if( github_links.length ) {
url = github_links[github_links.length-1].href
// Go to thread instead of .diff link (pull request notifications)
url = url.match(/\.diff/) ? url.slice(0, url.length-5) : url
link = $("<a class='github-link T-I J-J5-Ji lS T-I-ax7 ar7' target='_blank' href='"+ url +"'>Visit Thread on GitHub</a>")
$(".iH > div").append(link)
window.idled = true
document.getElementsByClassName('github-link')[0].addEventListener("DOMNodeRemovedFromDocument", function (ev) {
fetchAndAppendGitHubLink()
}, false)
}
clearInterval(retryForActiveMailBody)
} else if ( $('.nH.hx').length == 0 ) {
// Not in a mail view
clearInterval(retryForActiveMailBody)
}
}, 100)
intervals.push(retryForActiveMailBody)
}
}
function initShortcuts(shortcut, backgroundShortcut) {
$(document).on("keypress", function(event) {
// Shortcut: bind user's combination, if a button exist and event not in a textarea
if( processRightCombinationBasedOnShortcut(shortcut, event) && window.idled && $(".github-link:visible")[0] && notAnInput(event.target)) {
triggerGitHubLink(false)
}
// Bacground Shortcut: bind user's combination, if a button exist and event not in a textarea
if( processRightCombinationBasedOnShortcut(backgroundShortcut, event) && window.idled && $(".github-link:visible")[0] && notAnInput(event.target)) {
triggerGitHubLink(true)
}
})
}
function initListViewShortcut(regexp) {
$(document).on("keypress", function(event) {
// Shortcut: bind ctrl + return
selected = getVisible(document.querySelectorAll('.PE ~ [tabindex="0"]'))
if( event.ctrlKey && event.keyCode == 13 && selected ) {
generateUrlAndGoTo(selected, regexp)
}
})
}
// Trigger the appended link in mail view
function triggerGitHubLink (backgroundOrNot) {
// avoid link being appended multiple times
window.idled = false
event = backgroundOrNot ? fakeBackgroundClick() : fakeClick()
$(".github-link:visible")[0].dispatchEvent(event)
setTimeout( function(){ window.idled = true }, 100)
}
// Go to selected email GitHub thread
function generateUrlAndGoTo (selected, regexp) {
// If the title looks like a GitHub notification email.
if( (title = selected.innerText.match(/\[(.*)\]\s.*\s\(\#(\d*)\)/)) ) {
// org name coms from a label
regexp = new RegExp(regexp)
org = selected.querySelectorAll('.av')[0].innerText.toLowerCase().match(regexp)
if(org) {
org = org[1]
repo = title[1]
issue_no = title[2]
url = "https://github.com/" + org + "/" + repo + "/issues/" + issue_no
linkWithUrl(url).dispatchEvent(fakeClick())
}
}
}
//
// Helpers
//
function processRightCombinationBasedOnShortcut (shortcut, event) {
// Processing shortcut from preference
combination = shortcut.replace(/\s/g, '').split('+')
keys = ['shift', 'alt', 'meta', 'ctrl']
trueOrFalse = []
// If a key is in the combination, push the value to trueOrFalse array, and delete it from the combination
keys.map(function(key) {
index = combination.indexOf(key)
if(index >= 0) {
trueOrFalse.push( eval('event.' + key + 'Key' ) )
combination.splice(index, 1)
}
})
// If there is a keyCode left, add that to the mix.
if(combination.length) trueOrFalse.push(event.keyCode == combination[0])
// Evaluate trueOrFalse by looking for the existence of False
return trueOrFalse = (trueOrFalse.indexOf(false) < 0)
}
// .click() doesn't usually work as expected
function fakeClick () {
var click = document.createEvent("MouseEvents")
click.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
return click
}
function fakeBackgroundClick () {
var click = document.createEvent("MouseEvents")
click.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, true, 0, null)
return click
}
function linkWithUrl (url) {
var l = document.createElement('a')
l.href = url
l.target = "_blank"
return l
}
function getVisible (nodeList) {
if(nodeList.length) {
var node
$(nodeList).map(function() {
if(typeof node == 'undefined' && (this.offsetTop > 0 || this.offsetLeft > 0)) {
node = this
}
})
return node
}
}
function notAnInput (element) {
return !element.className.match(/editable/) && element.tagName != "TEXTAREA" && element.tagName != "INPUT"
}
function clearAllIntervals () {
intervals.map(function(num) {
clearInterval(num)
delete intervals[intervals.indexOf(num)]
})
}
// Reject unsubscribe and subscription management paths
// Make sure the keywords((un)subscribe) can still be repository names
function reject_unwanted_paths (links) {
paths = ['\/\/[^\/]*\/mailers\/unsubscribe\?', '\/\/[^\/]*\/.*\/.*\/unsubscribe_via_email', '\/\/[^\/]*\/.*\/.*\/subscription$']
regexp = new RegExp(paths.join('|'))
return $(links).filter(function() {
if(!this.href.match(regexp)) return this
})
}
|
JavaScript
| 0.000002 |
@@ -6132,20 +6132,17 @@
ubscribe
- and
+,
subscri
@@ -6147,16 +6147,33 @@
ription
+and verification
manageme
@@ -6344,16 +6344,28 @@
ribe%5C?',
+%0D%0A
'%5C/%5C/%5B%5E
@@ -6401,16 +6401,28 @@
_email',
+%0D%0A
'%5C/%5C/%5B%5E
@@ -6449,16 +6449,92 @@
iption$'
+,%0D%0A '%5C/%5C/%5B%5E%5C/%5D*%5C/.*%5C/.*%5C/emails%5C/.*%5C/confirm_verification%5C/.*'%0D%0A
%5D%0D%0A reg
|
16f6eaa6b048c2b2ff9a3ea0fb6b1a2e9e64cf2d
|
Fix literal error
|
src/store/index.js
|
src/store/index.js
|
import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import { componseWithDevtools } from 'redux-devtools-extension';
import thunk from 'redux-thunk';
import { uiTheme } from './uiTheme';
import { storageMiddlewareReducer } from './storage';
const rootReducer = combineReducers({
uiTheme,
});
const reducers = compose(storageMiddlewareReducer)(rootReducer);
const enhancer = componseWithDevtools(applyMiddleware(thunk));
export default createStore(
reducers,
enhancer,
);
|
JavaScript
| 0.99856 |
@@ -83,25 +83,24 @@
port %7B compo
-n
seWithDevtoo
@@ -92,25 +92,25 @@
mposeWithDev
-t
+T
ools %7D from
@@ -403,17 +403,16 @@
= compo
-n
seWithDe
@@ -412,17 +412,17 @@
eWithDev
-t
+T
ools(app
|
ae3ad24928a7105c50bbd91f351594d4545a8030
|
Reorder default controls
|
src/ol/control/controldefaults.js
|
src/ol/control/controldefaults.js
|
goog.provide('ol.control');
goog.require('ol.Collection');
goog.require('ol.control.Attribution');
goog.require('ol.control.Logo');
goog.require('ol.control.Zoom');
/**
* @param {olx.control.DefaultsOptions=} opt_options Defaults options.
* @return {ol.Collection} Controls.
* @todo stability experimental
*/
ol.control.defaults = function(opt_options) {
var options = goog.isDef(opt_options) ? opt_options : {};
var controls = new ol.Collection();
var attributionControl = goog.isDef(options.attribution) ?
options.attribution : true;
if (attributionControl) {
var attributionControlOptions = goog.isDef(options.attributionOptions) ?
options.attributionOptions : undefined;
controls.push(new ol.control.Attribution(attributionControlOptions));
}
var logoControl = goog.isDef(options.logo) ?
options.logo : true;
if (logoControl) {
var logoControlOptions = goog.isDef(options.logoOptions) ?
options.logoOptions : undefined;
controls.push(new ol.control.Logo(logoControlOptions));
}
var zoomControl = goog.isDef(options.zoom) ?
options.zoom : true;
if (zoomControl) {
var zoomControlOptions = goog.isDef(options.zoomOptions) ?
options.zoomOptions : undefined;
controls.push(new ol.control.Zoom(zoomControlOptions));
}
return controls;
};
|
JavaScript
| 0 |
@@ -456,16 +456,280 @@
ion();%0A%0A
+ var zoomControl = goog.isDef(options.zoom) ?%0A options.zoom : true;%0A if (zoomControl) %7B%0A var zoomControlOptions = goog.isDef(options.zoomOptions) ?%0A options.zoomOptions : undefined;%0A controls.push(new ol.control.Zoom(zoomControlOptions));%0A %7D%0A%0A
var at
@@ -1315,272 +1315,8 @@
%7D%0A%0A
- var zoomControl = goog.isDef(options.zoom) ?%0A options.zoom : true;%0A if (zoomControl) %7B%0A var zoomControlOptions = goog.isDef(options.zoomOptions) ?%0A options.zoomOptions : undefined;%0A controls.push(new ol.control.Zoom(zoomControlOptions));%0A %7D%0A%0A
re
|
5545de89d6076ede3184b1af9e39d6efe37befa5
|
Use an external service to deliver JS resource with ‘Content-Type: application/javascript;’
|
src/js/sdk/loader.js
|
src/js/sdk/loader.js
|
/**
* Loads specific scripts, depending on the parameters.
* @class SDK Loader
* @param {Object} options
* @param {Integer} [options.kit] Represent the serveral bookmarklet types (default: tricket-print).
* @param {Integer} [options.env] Represent the environment aka branch name (default: master).
* @param {String} [options.path] Host url path of where the actual resource to be loaded.
*/
(function (options) {
'use strict';
options = options || {};
options.kit = options.kit || 0;
options.env = options.env || 0;
options.path = options.path || '//source.xing.com/xws/jira-helpers/raw/';
var doc = document,
scriptTag = doc.createElement('script'),
environments = ['master', 'develop'],
kits = [
'ticket-print',
'add-ticket',
'ticket-print-lay-scrum',
'add-ticket-lay-scrum'
],
environment = environments[options.env],
kit = kits[options.kit],
url = options.path + environment + '/build/' + kit + '-bookmarklet.js'
;
scriptTag.setAttribute('src', url);
doc.head.appendChild(scriptTag);
})(options);
|
JavaScript
| 0 |
@@ -573,44 +573,42 @@
'//
-source.xing.com/xws/jira-helpers/raw
+rawgit.com/cange/jira-bookmarklets
/';%0A
|
38978aba71639d8178699d32b00a44467f540dd6
|
fix value convertion
|
src/app/execution/txLogger.js
|
src/app/execution/txLogger.js
|
'use strict'
var yo = require('yo-yo')
var remix = require('ethereum-remix')
var EventManager = remix.lib.EventManager
var helper = require('../../lib/helper')
var ethJSUtil = require('ethereumjs-util')
var BN = ethJSUtil.BN
/**
* This just export a function that register to `newTransaction` and forward them to the logger.
* Emit debugRequested
*
*/
class TxLogger {
constructor (opts = {}) {
this.event = new EventManager()
this.opts = opts
opts.api.editorpanel.registerLogType('knownTransaction', (data) => {
return renderKnownTransaction(this, data)
})
opts.api.editorpanel.registerLogType('unknownTransaction', (data) => {
return renderUnknownTransaction(this, data)
})
opts.events.txListener.register('newTransaction', (tx) => {
log(this, tx, opts.api)
})
}
}
function log (self, tx, api) {
var resolvedTransaction = api.resolvedTransaction(tx.hash)
if (resolvedTransaction) {
api.parseLogs(tx, resolvedTransaction.contractName, api.compiledContracts(), (error, logs) => {
if (!error) {
api.editorpanel.log({type: 'knownTransaction', value: { tx: tx, resolvedData: resolvedTransaction, logs: logs }})
}
})
} else {
// contract unknown - just displaying raw tx.
api.editorpanel.log({ type: 'unknownTransaction', value: { tx: tx } })
}
}
function renderKnownTransaction (self, data) {
var to = data.tx.to
if (to) to = helper.shortenAddress(data.tx.to)
function debug () {
self.event.trigger('debugRequested', [data.tx.hash])
}
function detail () {
// @TODO here should open a modal containing some info (e.g input params, logs, ...)
}
return yo`<span>${context(self, data.tx)}: from:${helper.shortenAddress(data.tx.from)}, to:${to}, ${data.resolvedData.contractName}.${data.resolvedData.fn}, value:${value(data.tx.value)} wei, data:${helper.shortenHexData(data.tx.input)}, ${data.logs.length} logs, hash:${helper.shortenHexData((data.tx.hash))},<button onclick=${detail}>Details</button> <button onclick=${debug}>Debug</button></span>`
}
function renderUnknownTransaction (self, data) {
var to = data.tx.to
if (to) to = helper.shortenAddress(data.tx.to)
function debug () {
self.event.trigger('debugRequested', [data.tx.hash])
}
function detail () {
// @TODO here should open a modal containing some info (e.g input params, logs, ...)
}
return yo`<span>${context(self, data.tx)}: from:${helper.shortenAddress(data.tx.from)}, to:${to}, value:${value(data.tx.value)} wei, data:${helper.shortenHexData((data.tx.input))}, hash:${helper.shortenHexData((data.tx.hash))}, <button onclick=${detail}>Details</button> <button onclick=${debug}>Debug</button></span>`
}
function context (self, tx) {
if (self.opts.api.context() === 'vm') {
return yo`<span>(vm)</span>`
} else {
return yo`<span>block:${tx.blockNumber}, txIndex:${tx.transactionIndex}`
}
}
function value (v) {
try {
if (v.indexOf && v.indexOf('0x') === 0) {
return (new BN(v.replace('0x', ''), 12)).toString(10)
} else {
return v.toString(10)
}
} catch (e) {
console.log(e)
return v
}
}
module.exports = TxLogger
|
JavaScript
| 0.000002 |
@@ -3033,9 +3033,9 @@
), 1
-2
+6
)).t
|
fb63d33acdee9110bd0e525f6b3b681a95547910
|
Fix for Portuguese whitespace errors again
|
imports/i18n/pt/_export.js
|
imports/i18n/pt/_export.js
|
import authentication from './authentication'
import dashboard from './dashboard'
import language from './language'
import mail from './mail'
import misc from './misc'
import modal from './modals'
import navigation from './navigation'
import pages from './pages'
import store from './store'
import swal from './swals'
const pt = {
...authentication,
dashboard,
language,
mail,
...misc,
modal,
navigation,
...pages,
store,
swal
}
export default pt
|
JavaScript
| 0 |
@@ -462,9 +462,8 @@
ault pt%0A
-%0A
|
9a1e1890490224e474b8fa1bef405927cd4e4b11
|
fix undefined error on depthArray
|
src/assets/js/Sounds/index.js
|
src/assets/js/Sounds/index.js
|
var Sounds = {
value: 0,
max: 11000,
create: function(listener, camera) {
this.listener = listener;
this.camera = camera;
this.initAtmosphere();
this.initHeartBeats();
return this;
},
initAtmosphere: function () {
this.atmosphere = new THREE.Audio( this.listener );
this.atmosphere.load( 'assets/sounds/atmosphere.mp3' );
this.atmosphere.autoplay = true;
this.atmosphere.setLoop(true);
this.atmosphere.setVolume(0.5);
},
initHeartBeats: function () {
this.heartBeats = new THREE.Audio( this.listener );
this.heartBeats.load( 'assets/sounds/heart_beats.mp3' );
this.heartBeats.autoplay = true;
this.heartBeats.setLoop(true);
this.heartBeats.setVolume(2);
},
initVoiceSynthesis: function() {
var request = new XMLHttpRequest();
request.open('GET', '/assets/js/Sounds/data/depth.json', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
this.depthData = JSON.parse(request.responseText);
this.depthArray = _.map(this.depthData, function(el) {
return el.depth;
});
this.speech = new SpeechSynthesisUtterance();
this.speech.lang = "en-US";
} else {
this.depthData = {};
this.depthArray = [];
}
}.bind(this);
request.onerror = function() {
console.log("Loading audio data file error");
};
request.send();
},
update: function() {
if(!window.speechSynthesis.talking) {
var depth = Math.round(this.camera.position.y) - this.max;
if (this.depthArray.indexOf(depth) != -1) {
this.speech.text = _.find(this.depthData, function (o) {
return o.depth == depth;
}).message;
if (!window.speechSynthesis.talking)
window.speechSynthesis.speak(this.speech);
}
}
}
};
module.exports = Sounds;
|
JavaScript
| 0.000012 |
@@ -1612,16 +1612,35 @@
pthArray
+ && this.depthArray
.indexOf
|
5c805c2e85591d12402365ab4dc65ddc85cb204f
|
Add more comments to the code
|
lib/authorizer/auth-interface.js
|
lib/authorizer/auth-interface.js
|
var _ = require('lodash'),
createAuthInterface;
/**
* Creates a wrapper around RequestAuth and provides getters and setters helper functions
*
* @param {RequestAuth} auth
* @constructor
*/
createAuthInterface = function (auth) {
// cached value of auth object
var authObject = auth.parameters().toObject();
/**
* @typedef AuthInterface
*/
return {
/**
* @param {String|Array<String>} key
* @return {*} Returns a value for a key or an object having all keys & values depending on the input
* @example
* get('foo') // bar
* get(['foo', 'alpha']) // {foo: 'bar', 'alpha': 'beta'}
*/
get: function (key) {
if (_.isString(key)) {
return authObject[key];
}
if (_.isArray(key)) {
return _.pick(authObject, key);
}
},
/**
* @param {String|Object} key
* @param {*} [value]
* @return {AuthInterface}
* @example set('foo', 'bar') or set({foo: 'bar', 'alpha': 'beta'})
*/
set: function (key, value) {
var modifiedParams = {};
if (_.isPlainObject(key)) {
modifiedParams = key;
}
else if (_.isString(key)) {
modifiedParams[key] = value;
}
else {
return this;
}
_.forEach(modifiedParams, (value, key) => {
var param;
if ((param = auth.parameters().one(key))) {
param.system && param.set(value);
}
else {
auth.parameters().add({key: key, value: value, system: true});
}
});
authObject = auth.parameters().toObject(); // update the cache
return this;
}
};
};
module.exports = createAuthInterface;
|
JavaScript
| 0 |
@@ -287,34 +287,200 @@
t =
-auth.parameters().toObject
+%7B%7D;%0A%0A /**%0A * Updates the cache value for auth object which is used by #get%0A */%0A function updateCache() %7B%0A authObject = auth.parameters().toObject();%0A %7D%0A%0A updateCache
();%0A
@@ -1540,33 +1540,75 @@
else %7B
+ // invalid input found, no change to auth
%0A
-
@@ -1718,16 +1718,112 @@
param;%0A
+ // if auth has the param already then update it only when it's a sytem property%0A
@@ -1938,32 +1938,210 @@
%7D%0A
+ // when param is missing then just add a new param to the variableList%0A // do not use append/insert since they don't typecast the item being added%0A
@@ -2280,70 +2280,22 @@
-authObject = auth.parameters().toObject(); // update the c
+updateC
ache
+();
%0A%0A
|
1dbda5d071eda0ea04c80d8820d844d7af37e245
|
remove dashboard styles
|
lib/build/files/webpack_files.js
|
lib/build/files/webpack_files.js
|
var files = {
dashboard: {
stylesheets: [
'/stylesheets/cartodb.css',
'/stylesheets/common.css',
'/stylesheets/dashboard.css'
],
scripts: [
'/javascripts/cdb_static.js',
'/javascripts/models_static.js',
'/javascripts/dashboard_templates_static.js',
'/javascripts/dashboard_deps_static.js',
'/javascripts/dashboard_static.js'
]
},
profile: {
stylesheets: [
'/stylesheets/cartodb.css',
'/stylesheets/common.css',
'/stylesheets/dashboard.css'
],
scripts: [
'/javascripts/cdb_static.js',
'/javascripts/models_static.js',
'/javascripts/profile_templates.js',
'/javascripts/account_deps_static.js',
'/javascripts/profile_static.js'
]
}
};
module.exports = files;
|
JavaScript
| 0 |
@@ -492,44 +492,8 @@
css'
-,%0A '/stylesheets/dashboard.css'
%0A
|
9f5702483835f1fa2d182ad46ad8af951c0a3f10
|
Add already saved sensor check
|
src/actions/VaccineActions.js
|
src/actions/VaccineActions.js
|
/* eslint-disable no-await-in-loop */
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2021
*/
import { ToastAndroid } from 'react-native';
import { PermissionSelectors } from '../selectors/permission';
import selectScannedSensors from '../selectors/vaccine';
import { PermissionActions } from './PermissionActions';
import BleService from '../bluetooth/BleService';
import { syncStrings } from '../localization/index';
export const VACCINE_ACTIONS = {
ERROR_BLUETOOTH_DISABLED: 'Vaccine/errorBluetoothDisabled',
ERROR_LOCATION_DISABLED: 'Vaccine/errorLocationDisabled',
SCAN_START: 'Vaccine/sensorScanStart',
SCAN_ERROR: 'Vaccine/sensorScanError',
SCAN_STOP: 'Vaccine/sensorScanStop',
SENSOR_FOUND: 'Vaccine/sensorFound',
};
const scanStart = () => ({ type: VACCINE_ACTIONS.SCAN_START });
const scanStop = () => ({ type: VACCINE_ACTIONS.SCAN_STOP });
const sensorFound = macAddress => ({ type: VACCINE_ACTIONS.SENSOR_FOUND, payload: { macAddress } });
const startSensorScan = () => async (dispatch, getState) => {
const bluetoothEnabled = PermissionSelectors.bluetooth(getState());
const locationPermission = PermissionSelectors.location(getState());
// Ensure the correct permissions before initiating a new sync process.
if (!bluetoothEnabled) dispatch(PermissionActions.requestBluetooth());
if (!locationPermission) await dispatch(PermissionActions.requestLocation());
if (!bluetoothEnabled) {
ToastAndroid.show(syncStrings.please_enable_bluetooth, ToastAndroid.LONG);
return null;
}
if (!locationPermission) {
ToastAndroid.show(syncStrings.grant_location_permission, ToastAndroid.LONG);
return null;
}
dispatch(scanForSensors());
// Scan will continue running until it is stopped...
return null;
};
const scanForSensors = () => async (dispatch, getState) => {
dispatch(scanStart());
const deviceCallback = device => {
const alreadyFound = selectScannedSensors(getState());
// TODO: Filter out already saved sensors?
if (!alreadyFound.includes(device?.id)) {
dispatch(sensorFound(device?.id));
}
};
BleService().scanForSensors(deviceCallback);
};
const stopSensorScan = () => async dispatch => {
dispatch(scanStop());
BleService().stopScan();
};
export const TemperatureSyncActions = {
startSensorScan,
stopSensorScan,
};
|
JavaScript
| 0 |
@@ -1,42 +1,4 @@
-/* eslint-disable no-await-in-loop */%0A
/**%0A
@@ -384,16 +384,64 @@
/index';
+%0Aimport %7B UIDatabase %7D from '../database/index';
%0A%0Aexport
@@ -1902,16 +1902,60 @@
ce =%3E %7B%0A
+ const %7B id %7D = device;%0A%0A if (id) %7B%0A
cons
@@ -2009,31 +2009,18 @@
));%0A
-%0A
-// TODO: Filter ou
+ cons
t al
@@ -2028,24 +2028,63 @@
eady
- s
+S
aved
-sensors?%0A
+= UIDatabase.get('Sensor', id, 'macAddress');%0A%0A
@@ -2110,27 +2110,36 @@
ncludes(
-device?.id)
+id) && !alreadySaved
) %7B%0A
@@ -2140,16 +2140,18 @@
%7B%0A
+
dispatch
@@ -2167,21 +2167,21 @@
und(
-device?.id));
+id));%0A %7D
%0A
|
bba8562e037496f10687480099ec4ec5e8df9e73
|
Add DateRange validation for parameters
|
src/api/handlers/timesheet.js
|
src/api/handlers/timesheet.js
|
// const User = require('../../resources/user');
const BaseJoi = require('joi')
, Extension = require('joi-date-extensions')
, Boom = require('boom')
, TimesheetResources = require('../../resources/timesheet');
const Joi = BaseJoi.extend(Extension);
const { UserId, Timesheet } = require('../schema');
module.exports.timesheetFromToById = {
tags: ['api'],
notes: 'Fetches the Timesheet',
description: 'Fetches all days with periods between the given date range',
plugins: {
'hapi-swagger': {
responses: {
'200': {
description: 'The timesheet for a user in a given date range',
schema: Timesheet
},
'404':{
description: 'Not Found',
}
,'400':{
description: 'Bad Request',
}
},
},
},
validate: {
params: {
userId: UserId.required(),
from: Joi.date()
.format('YYYY-MM-DD')
.description('startpoint of the timesheet')
.example('2017-05-01')
.required(),
to: Joi.date()
.description('endpoint of the timesheet')
.example('2017-05-01')
.format('YYYY-MM-DD')
.required(),
}
},
handler: function (request, reply){
const { userId, from ,to } = request.params;
return TimesheetResources.get(userId, from, to)
.then(
(timesheet) => {
if(timesheet) return reply(timesheet);
return reply(Boom.create(404, `Could not find timesheet for user ${userId}'`));
}
);
}
};
|
JavaScript
| 0 |
@@ -958,16 +958,27 @@
params:
+Joi.object(
%7B%0A
@@ -1282,32 +1282,70 @@
the timesheet')%0A
+ .format('YYYY-MM-DD')%0A
@@ -1384,36 +1384,128 @@
.
-format('YYYY-MM-DD')
+min(Joi.ref('from')) // It is important that .min is below example see https://github.com/hapijs/joi/issues/1186
%0A
@@ -1532,24 +1532,25 @@
, %0A %7D
+)
%0A %7D,%0A
|
7512e265924a029d9345c6127cc9909e1d56f7e4
|
Include `<` and `>` into BNF attributes
|
src/languages/bnf.js
|
src/languages/bnf.js
|
/*
Language: Backus–Naur Form
Author: Oleg Efimov <[email protected]>
*/
function(hljs){
return {
contains: [
// Attribute
{
className: 'attribute',
begin: /</,
end: />/,
excludeBegin: true,
excludeEnd: true
},
// Specific
{
begin: /::=/,
starts: {
end: /$/,
contains: [
{
begin: /</, end: />/
},
// Common
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE
]
}
}
]
};
}
|
JavaScript
| 0.00001 |
@@ -192,24 +192,16 @@
in: /%3C/,
-%0A
end: /%3E
@@ -205,62 +205,8 @@
/%3E/
-,%0A excludeBegin: true,%0A excludeEnd: true
%0A
|
723e935703924956e75dd9b0a83d539ef71bf31b
|
Clean out console.logs
|
src/transaction.js
|
src/transaction.js
|
'use strict';
var EventEmitter = require('events').EventEmitter,
http = require('http'),
https = require('https'),
stream = require('stream'),
url = require('url'),
util = require('util');
var RedirectError = require('./errors').RedirectError;
function Transaction(requestOptions, requestBody, configuration) {
EventEmitter.call(this);
this.requestOptions = requestOptions;
this.requestBody = requestBody;
this.configuration = configuration || {};
this.requests = [];
this.responses = [];
this.requestFormatter = new RequestFormatter();
this.responseFormatter = new ResponseFormatter();
// Things that could move into a state.
this.redirectCount = 0;
this.currentLocation = null;
}
util.inherits(Transaction, EventEmitter);
Transaction.prototype.send = function () {
this.sendRequest(this.requestOptions, this.requestBody);
this.emit('request');
};
Transaction.prototype.sendRequest = function (requestOptions, body) {
var _this = this;
this.currentLocation = url.format(requestOptions);
var request = http.request(requestOptions, function (response) {
_this.onResponse(response);
});
this.requests.push(this.requestFormatter.format(request, body));
if (body) {
console.log(body);
var bodyStream = stringToStream(body.trim());
bodyStream.pipe(request);
} else {
request.end();
}
};
Transaction.prototype.onResponse = function (response) {
var _this = this,
body = '';
response.setEncoding('utf8');
response.on('data', function (chunk) {
body += chunk;
});
response.on('end', function () {
_this.completeResponse(response, body);
response.removeAllListeners();
});
};
Transaction.prototype.completeResponse = function (response, body) {
this.responses.push(this.responseFormatter.format(response, body));
this.emit('response');
if (this.shouldRedirect(response)) {
this.tryToRedirect(response);
} else {
this.emit('end');
}
};
Transaction.prototype.shouldRedirect = function (response) {
var redirectCodes = this.configuration.redirectStatusCodes || [];
if (this.configuration.followRedirects) {
for (var i = 0; i < redirectCodes.length; ++i) {
if (response.statusCode === redirectCodes[i]) {
return true;
}
}
}
return false;
};
Transaction.prototype.tryToRedirect = function (response) {
var limit = this.configuration.redirectLimit,
resolved = this.getUrlFromCurrentLocation(response.headers.location),
request = url.parse(resolved);
this.redirectCount += 1;
if (this.redirectCount > limit) {
this.emit('error', new RedirectError('Reached redirect limit of ' + limit));
return;
}
this.sendRequest(request);
this.emit('redirect');
};
Transaction.prototype.getUrlFromCurrentLocation = function (uri) {
return url.resolve(this.currentLocation, uri);
};
Transaction.prototype.getRequest = function () {
return this.requests[0];
};
Transaction.prototype.getResponse = function () {
return this.responses[this.responses.length - 1];
};
// -----------------------------------------------------------------------------
function MessageFormatter() {}
MessageFormatter.prototype.format = function (message, body) {
var formatted = this.startLine(message);
formatted += this.headerLines(message);
if (body) {
formatted += '\r\n';
formatted += body;
}
return formatted;
};
function RequestFormatter() {
MessageFormatter.call(this);
}
// -----------------------------------------------------------------------------
util.inherits(RequestFormatter, MessageFormatter);
RequestFormatter.prototype.startLine = function (request) {
var method = request.method,
path = request.path,
version = 'HTTP/1.1';
return method + ' ' + path + ' ' + version + '\r\n';
};
RequestFormatter.prototype.headerLines = function (request) {
var headerLines = '',
keys = Object.keys(request._headerNames);
keys.forEach(function (key) {
var name = request._headerNames[key],
value = request._headers[key];
headerLines += name + ': ' + value + '\r\n';
});
return headerLines;
};
// -----------------------------------------------------------------------------
function ResponseFormatter() {
MessageFormatter.call(this);
}
util.inherits(ResponseFormatter, MessageFormatter);
ResponseFormatter.prototype.startLine = function (response) {
var version = 'HTTP/1.1',
statusCode = response.statusCode,
reasonPhrase = response.statusMessage;
return version + ' ' + statusCode + ' ' + reasonPhrase + '\r\n';
};
ResponseFormatter.prototype.headerLines = function (response) {
var headerLines = '';
for (var i = 0; i < response.rawHeaders.length; ++i) {
headerLines += response.rawHeaders[i];
headerLines += (i % 2 === 0 ? ': ' : '\r\n');
}
return headerLines;
};
// -----------------------------------------------------------------------------
function stringToStream(string) {
var s = new stream.Readable();
s.push(string);
s.push(null);
return s;
}
// -----------------------------------------------------------------------------
module.exports = Transaction;
|
JavaScript
| 0.000003 |
@@ -1269,35 +1269,8 @@
) %7B%0A
- console.log(body);%0A
|
e5e8938beb6068bd4ec2a74f7fb5ed1cfe3a2333
|
fix another issue related with last refactoring.
|
src/transformer.js
|
src/transformer.js
|
var Transformer = (function () {
var iv_size_ = 8;
var generateRandomUint8Array = function (len) {
var vector = new Uint8Array(len);
for (var i = 0; i < len; i++) {
vector[i] = (Math.random() + '').substr(3) & 255;
}
return vector;
}
var create_transformer = Module.cwrap('create_transformer', 'number', []);
/**
* Create a transformer instance.
* @constructor
*/
var Transformer = function () {
this.handle_ = create_transformer();
this.ciphertext_max_len_ = 0;
};
// int set_key(int handle, const unsigned char* key, uint32_t key_len)
var set_key = Module.cwrap('set_key', 'number',
['number', 'number', 'number']);
/**
* Sets the key for transformation session.
*
* @param {ArrayBuffer} key session key.
* @return {boolean} true if successful.
*/
Transformer.prototype.setKey = function (key) {
var ptr = Module._malloc(key.byteLength);
var dataHeap = new Uint8Array(Module.HEAPU8.buffer, ptr, key.byteLength);
dataHeap.set(new Uint8Array(key));
var ret = set_key(this.handle_, dataHeap.byteOffset, key.byteLength);
Module._free(dataHeap.byteOffset);
return ret == 0;
};
// int configure(int handle, const unsigned char* data,
// uint32_t data_len)
var configure = Module.cwrap('configure', 'number',
['number', 'number', 'number']);
/**
* Performs configuration to the transformer.
*
* @param {String} serialized Json string.
*/
Transformer.prototype.configure = function (jsonStr) {
var jsonStrArrayBuffer = str2ab(jsonStr);
var jsonStrObj = JSON.parse(jsonStr);
this.ciphertext_max_len_ = jsonStrObj.ciphertext_max_len;
var ptr = Module._malloc(jsonStrArrayBuffer.byteLength);
var dataHeap = new Uint8Array(Module.HEAPU8.buffer, ptr,
jsonStrArrayBuffer.byteLength);
dataHeap.set(new Uint8Array(jsonStrArrayBuffer));
var ret = configure(this.handle_, dataHeap.byteOffset, jsonStr.byteLength);
Module._free(dataHeap.byteOffset);
return ret == 0;
}
// int set_init_vector(int handle, const unsigned char* data,
// uint32_t data_len)
var set_init_vector = Module.cwrap('set_init_vector', 'number',
['number', 'number', 'number']);
var setInitVector = function (handle) {
var iv = generateRandomUint8Array(iv_size_);
var ptr = Module._malloc(iv.byteLength);
var dataHeap = new Uint8Array(Module.HEAPU8.buffer, ptr, iv.byteLength);
dataHeap.set(iv);
var ret = set_init_vector(handle, dataHeap.byteOffset, iv.byteLength);
Module._free(dataHeap.byteOffset);
return ret == 0;
}
// int transform(int handle, const uint8_t* data, uint32_t data_len,
// uint8_t* output, uint32_t* output_len) {
var transform = Module.cwrap('transform', 'number',
['number', 'number', 'number', 'number',
'number']);
/**
* Transforms a piece of data to obfuscated form.
*
* @param {ArrayBuffer} plaintext data need to be obfuscated.
* @return {?ArrayBuffer} obfuscated data, or null if failed.
*/
Transformer.prototype.transform = function (plaintext) {
if (!setInitVector(this.handle_)) {
return null;
}
var plaintextLen = plaintext.byteLength;
var ptr = Module._malloc(plaintextLen);
var dataHeap1 = new Uint8Array(Module.HEAPU8.buffer, ptr, plaintextLen);
dataHeap1.set(new Uint8Array(plaintext));
var ciphertextLen = plaintextLen + iv_size_;
if (this.ciphertext_max_len_) {
ciphertextLen = this.ciphertext_max_len_;
}
ptr = Module._malloc(ciphertextLen);
var dataHeap2 = new Uint8Array(Module.HEAPU8.buffer, ptr, ciphertextLen);
ptr = Module._malloc(4);
var dataHeap3 = new Uint8Array(Module.HEAPU8.buffer, ptr, 4);
var data = new Uint32Array([ciphertextLen]);
dataHeap3.set(new Uint8Array(data.buffer));
var ret = transform(this.handle_,
dataHeap1.byteOffset, plaintext.byteLength,
dataHeap2.byteOffset, dataHeap3.byteOffset);
if (ret != 0) {
return null;
}
var length = (new Uint32Array(dataHeap3.buffer, dataHeap3.byteOffset, 4))[0];
var result = new Uint8Array(length);
result.set(new Uint8Array(dataHeap2.buffer, dataHeap2.byteOffset, length));
Module._free(dataHeap1.byteOffset);
Module._free(dataHeap2.byteOffset);
Module._free(dataHeap3.byteOffset);
return result.buffer;
}
// int restore(int handle, const uint8_t* data, uint32_t data_len,
// uint8_t* result, uint32_t* result_len) {
var restore = Module.cwrap('restore', 'number',
['number', 'number', 'number', 'number',
'number']);
/**
* Restores data from obfuscated form to original form.
*
* @param {ArrayBuffer} ciphertext obfuscated data.
* @return {?ArrayBuffer} original data, or null if failed.
*/
Transformer.prototype.restore = function (ciphertext) {
var len = ciphertext.byteLength;
var ptr = Module._malloc(len);
var dataHeap1 = new Uint8Array(Module.HEAPU8.buffer, ptr, len);
dataHeap1.set(new Uint8Array(ciphertext, 0, len));
ptr = Module._malloc(len);
var dataHeap2 = new Uint8Array(Module.HEAPU8.buffer, ptr, len);
ptr = Module._malloc(4);
var dataHeap3 = new Uint8Array(Module.HEAPU8.buffer, ptr, 4);
var data = new Uint32Array([len]);
dataHeap3.set(new Uint8Array(data.buffer));
var ret = restore(this.handle_,
dataHeap1.byteOffset, ciphertext.byteLength,
dataHeap2.byteOffset, dataHeap3.byteOffset);
if (ret != 0) {
return null;
}
var len = (new Uint32Array(dataHeap3.buffer, dataHeap3.byteOffset, 4))[0];
var result = new Uint8Array(len);
result.set(new Uint8Array(dataHeap2.buffer, dataHeap2.byteOffset, length));
Module._free(dataHeap1.byteOffset);
Module._free(dataHeap2.byteOffset);
Module._free(dataHeap3.byteOffset);
return result.buffer;
};
var delete_transformer = Module.cwrap('delete_transformer', 'number',
['number']);
/**
* Dispose the transformer.
*
* This should be the last method to be called for a transformer
* instance.
*/
Transformer.prototype.dispose = function () {
delete_transformer(this.handle_);
this.handle_ = -1;
}
return Transformer;
}());
|
JavaScript
| 0 |
@@ -6001,27 +6001,24 @@
eOffset, len
-gth
));%0A Modu
|
1c778937b07dd325d407757f1ca2d2df4af2800b
|
Rename deprecated adapter method names
|
src/app/store/AdapterMixin.js
|
src/app/store/AdapterMixin.js
|
define( [ "Ember", "EmberData" ], function( Ember, DS ) {
var get = Ember.get;
var push = [].push;
var reURL = /^[a-z]+:\/\/([\w\.]+)\/(.+)$/i;
var AdapterError = DS.AdapterError;
/**
* Adapter mixin for using static model names
* instead of using type.modelName as name
*/
return Ember.Mixin.create( Ember.Evented, {
find: function( store, type, id, snapshot ) {
var url = this.buildURL( type, id, snapshot, "find" );
return this.ajax( url, "GET" );
},
findAll: function( store, type, sinceToken ) {
var url = this.buildURL( type, null, null, "findAll" );
var query = sinceToken ? { since: sinceToken } : undefined;
return this.ajax( url, "GET", { data: query } );
},
findQuery: function( store, type, query ) {
var url = this.buildURL( type, query, null, "findQuery" );
query = this.sortQueryParams ? this.sortQueryParams( query ) : query;
return this.ajax( url, "GET", { data: query } );
},
createRecordMethod: "POST",
createRecord: function( store, type, snapshot ) {
var self = this;
var url = self.buildURL( type, null, snapshot, "createRecord" );
var method = get( self, "createRecordMethod" );
var data = self.createRecordData( store, type, snapshot );
return self.ajax( url, method, data )
.then(function( data ) {
self.trigger( "createRecord", store, type, snapshot );
return data;
});
},
createRecordData: function( store, type, snapshot ) {
var data = {};
var serializer = store.serializerFor( type.modelName );
serializer.serializeIntoHash( data, type, snapshot, { includeId: true } );
return { data: data };
},
updateRecordMethod: "PUT",
updateRecord: function( store, type, snapshot ) {
var self = this;
var url = self.buildURL( type, snapshot.id, snapshot, "updateRecord" );
var method = get( self, "updateRecordMethod" );
var data = self.updateRecordData( store, type, snapshot );
return self.ajax( url, method, data )
.then(function( data ) {
self.trigger( "updateRecord", store, type, snapshot );
return data;
});
},
updateRecordData: function( store, type, snapshot ) {
var data = {};
var serializer = store.serializerFor( type.modelName );
serializer.serializeIntoHash( data, type, snapshot );
return { data: data };
},
deleteRecord: function( store, type, snapshot ) {
var self = this;
var url = self.buildURL( type, snapshot.id, snapshot, "deleteRecord" );
return self.ajax( url, "DELETE" )
.then(function( data ) {
self.trigger( "deleteRecord", store, type, snapshot );
return data;
});
},
urlForCreateRecord: function( modelName, snapshot ) {
// Why does Ember-Data do this?
// the id is missing on BuildURLMixin.urlForCreateRecord
return this._buildURL( modelName, snapshot.id );
},
/**
* Custom buildURL method with type instead of modelName
* @param {DS.Model} type
* @param {string?} id
* @returns {string}
*/
_buildURL: function( type, id ) {
var host = get( this, "host" );
var ns = get( this, "namespace" );
var url = [ host ];
// append the adapter specific namespace
if ( ns ) { push.call( url, ns ); }
// append the type fragments (and process the dynamic ones)
push.apply( url, this.buildURLFragments( type, id ) );
return url.join( "/" );
},
/**
* Custom method for building URL fragments
* @param {DS.Model} type
* @param {string?} id
* @returns {string[]}
*/
buildURLFragments: function( type, id ) {
var path = type.toString();
var url = path.split( "/" );
if ( !Ember.isNone( id ) ) { push.call( url, id ); }
return url;
},
ajax: function( url ) {
var adapter = this;
return this._super.apply( this, arguments )
.catch(function( err ) {
if ( err instanceof AdapterError ) {
var _url = reURL.exec( url );
err.host = _url && _url[1] || get( adapter, "host" );
err.path = _url && _url[2] || get( adapter, "namespace" );
}
return Promise.reject( err );
});
},
ajaxOptions: function() {
var hash = this._super.apply( this, arguments );
hash.timeout = 10000;
hash.cache = false;
return hash;
},
isSuccess: function( status, headers, payload ) {
return this._super.apply( this, arguments )
&& ( payload ? !payload.error : true );
},
handleResponse: function( status, headers, payload ) {
if ( this.isSuccess( status, headers, payload ) ) {
return payload;
} else if ( this.isInvalid( status, headers, payload ) ) {
return new DS.InvalidError( payload && payload.errors || [] );
}
return new AdapterError([{
name : "HTTP Error",
message: payload && payload.error || "Failed to load resource",
detail : payload && payload.message,
status : status
}]);
}
});
});
|
JavaScript
| 0.000001 |
@@ -335,16 +335,22 @@
%7B%0A%09%09find
+Record
: functi
@@ -436,16 +436,22 @@
t, %22find
+Record
%22 );%0A%09%09%09
@@ -721,21 +721,17 @@
%09%09%7D,%0A%0A%09%09
-findQ
+q
uery: fu
@@ -813,13 +813,9 @@
l, %22
-findQ
+q
uery
|
2704cf053648de858100ff640ad4243c394f0a38
|
add sorting category to searchbar
|
src/pages/CustomerInvoicePage.js
|
src/pages/CustomerInvoicePage.js
|
/* eslint-disable react/forbid-prop-types */
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2019
*/
import React, { useCallback } from 'react';
import PropTypes from 'prop-types';
import { View, ToastAndroid } from 'react-native';
import { connect } from 'react-redux';
import { MODAL_KEYS } from '../utilities';
import { useRecordListener } from '../hooks';
import { getItemLayout, getPageDispatchers } from './dataTableUtilities';
import { ROUTES } from '../navigation/constants';
import { BottomConfirmModal, DataTablePageModal } from '../widgets/modals';
import { PageButton, PageInfo, SearchBar, DataTablePageView } from '../widgets';
import { DataTable, DataTableHeaderRow, DataTableRow } from '../widgets/DataTable';
import { buttonStrings, modalStrings } from '../localization';
import globalStyles from '../globalStyles';
/**
* Renders a mSupply mobile page with customer invoice loaded for editing
*
* State:
* Uses a reducer to manage state with `backingData` being a realm results
* of items to display. `data` is a plain JS array of realm objects. data is
* hydrated from the `backingData` for displaying in the interface.
* i.e: When filtering, data is populated from filtered items of `backingData`.
*
* dataState is a simple map of objects corresponding to a row being displayed,
* holding the state of a given row. Each object has the shape :
* { isSelected, isFocused, isDisabled }
*/
export const CustomerInvoice = ({
dispatch,
data,
dataState,
pageObject,
sortKey,
isAscending,
modalKey,
hasSelection,
keyExtractor,
searchTerm,
modalValue,
columns,
getPageInfoColumns,
refreshData,
onSelectNewItem,
onEditComment,
onEditTheirRef,
onFilterData,
onDeleteItems,
onDeselectAll,
onCloseModal,
onCheck,
onUncheck,
onSortColumn,
onEditTotalQuantity,
onAddTransactionItem,
onAddMasterList,
onApplyMasterLists,
route,
}) => {
const { isFinalised, comment, theirRef } = pageObject;
// Listen for this invoice being finalised which will prune items and cause side effects
// outside of the reducer. Reconcile differences when triggered.
useRecordListener(refreshData, pageObject, 'Transaction');
const pageInfoColumns = useCallback(getPageInfoColumns(pageObject, dispatch, route), [
comment,
theirRef,
isFinalised,
]);
const getCallback = (colKey, propName) => {
switch (colKey) {
case 'totalQuantity':
return onEditTotalQuantity;
case 'remove':
if (propName === 'onCheck') return onCheck;
return onUncheck;
default:
return null;
}
};
const getModalOnSelect = () => {
switch (modalKey) {
case MODAL_KEYS.SELECT_ITEM:
return onAddTransactionItem;
case MODAL_KEYS.TRANSACTION_COMMENT_EDIT:
return onEditComment;
case MODAL_KEYS.THEIR_REF_EDIT:
return onEditTheirRef;
case MODAL_KEYS.SELECT_MASTER_LISTS:
return onApplyMasterLists;
default:
return null;
}
};
const renderRow = useCallback(
listItem => {
const { item, index } = listItem;
const rowKey = keyExtractor(item);
return (
<DataTableRow
rowData={data[index]}
rowState={dataState.get(rowKey)}
rowKey={rowKey}
columns={columns}
isFinalised={isFinalised}
getCallback={getCallback}
rowIndex={index}
/>
);
},
[data, dataState]
);
const renderHeader = useCallback(
() => (
<DataTableHeaderRow
columns={columns}
onPress={onSortColumn}
isAscending={isAscending}
sortKey={sortKey}
/>
),
[sortKey, isAscending]
);
const { verticalContainer, topButton } = globalStyles;
const {
pageTopSectionContainer,
pageTopLeftSectionContainer,
pageTopRightSectionContainer,
} = globalStyles;
return (
<DataTablePageView>
<View style={pageTopSectionContainer}>
<View style={pageTopLeftSectionContainer}>
<PageInfo columns={pageInfoColumns} isEditingDisabled={isFinalised} />
<SearchBar onChangeText={onFilterData} value={searchTerm} />
</View>
<View style={pageTopRightSectionContainer}>
<View style={verticalContainer}>
<PageButton
style={{ ...topButton, marginLeft: 0 }}
text={buttonStrings.new_item}
onPress={onSelectNewItem}
isDisabled={isFinalised}
/>
<PageButton
text={buttonStrings.add_master_list_items}
onPress={onAddMasterList}
isDisabled={isFinalised}
/>
</View>
</View>
</View>
<DataTable
data={data}
extraData={dataState}
renderRow={renderRow}
renderHeader={renderHeader}
keyExtractor={keyExtractor}
getItemLayout={getItemLayout}
columns={columns}
/>
<BottomConfirmModal
isOpen={hasSelection}
questionText={modalStrings.remove_these_items}
onCancel={onDeselectAll}
onConfirm={onDeleteItems}
confirmText={modalStrings.remove}
/>
<DataTablePageModal
fullScreen={false}
isOpen={!!modalKey}
modalKey={modalKey}
onClose={onCloseModal}
onSelect={getModalOnSelect()}
dispatch={dispatch}
currentValue={modalValue}
/>
</DataTablePageView>
);
};
const mapDispatchToProps = (dispatch, ownProps) => {
const { transaction } = ownProps || {};
const { otherParty } = transaction;
const hasMasterLists = otherParty.masterLists.length > 0;
const noMasterLists = () =>
ToastAndroid.show(modalStrings.customer_no_masterlist_available, ToastAndroid.LONG);
return {
...getPageDispatchers(dispatch, ownProps, 'Transaction', ROUTES.CUSTOMER_INVOICE),
[hasMasterLists ? null : 'onAddMasterList']: noMasterLists,
};
};
const mapStateToProps = state => {
const { pages } = state;
const { customerInvoice } = pages;
return customerInvoice;
};
export const CustomerInvoicePage = connect(mapStateToProps, mapDispatchToProps)(CustomerInvoice);
CustomerInvoice.defaultProps = {
modalValue: null,
};
CustomerInvoice.propTypes = {
dispatch: PropTypes.func.isRequired,
data: PropTypes.array.isRequired,
dataState: PropTypes.object.isRequired,
pageObject: PropTypes.object.isRequired,
sortKey: PropTypes.string.isRequired,
isAscending: PropTypes.bool.isRequired,
modalKey: PropTypes.string.isRequired,
hasSelection: PropTypes.bool.isRequired,
keyExtractor: PropTypes.func.isRequired,
searchTerm: PropTypes.string.isRequired,
modalValue: PropTypes.any,
columns: PropTypes.array.isRequired,
getPageInfoColumns: PropTypes.func.isRequired,
refreshData: PropTypes.func.isRequired,
onSelectNewItem: PropTypes.func.isRequired,
onAddMasterList: PropTypes.func.isRequired,
onEditComment: PropTypes.func.isRequired,
onEditTheirRef: PropTypes.func.isRequired,
onFilterData: PropTypes.func.isRequired,
onDeleteItems: PropTypes.func.isRequired,
onDeselectAll: PropTypes.func.isRequired,
onCloseModal: PropTypes.func.isRequired,
onCheck: PropTypes.func.isRequired,
onUncheck: PropTypes.func.isRequired,
onSortColumn: PropTypes.func.isRequired,
onEditTotalQuantity: PropTypes.func.isRequired,
onAddTransactionItem: PropTypes.func.isRequired,
onApplyMasterLists: PropTypes.func.isRequired,
route: PropTypes.string.isRequired,
};
|
JavaScript
| 0 |
@@ -768,16 +768,46 @@
lStrings
+, tableStrings, generalStrings
%7D from
@@ -4155,16 +4155,28 @@
earchBar
+%0A
onChang
@@ -4195,16 +4195,28 @@
terData%7D
+%0A
value=%7B
@@ -4226,16 +4226,108 @@
rchTerm%7D
+%0A placeholder=%7B%60$%7BgeneralStrings.searchBar%7D $%7BtableStrings.item_name%7D%60%7D%0A
/%3E%0A
|
0d3533269779b72b3e3f15e073fc8f729513d1b7
|
Remove invalid proxy function (#230)
|
src/browser/StatusBarProxy.js
|
src/browser/StatusBarProxy.js
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*
*/
function notSupported (win, fail) {
//
console.log('StatusBar is not supported');
setTimeout(function () {
if (win) {
win();
}
// note that while it is not explicitly supported, it does not fail
// this is really just here to allow developers to test their code in the browser
// and if we fail, then their app might as well. -jm
}, 0);
}
module.exports = {
isVisible: false,
styleBlackTranslucent: notSupported,
styleDefault: notSupported,
styleLightContent: notSupported,
styleBlackOpaque: notSupported,
overlaysWebView: notSupported,
styleLightContect: notSupported,
backgroundColorByName: notSupported,
backgroundColorByHexString: notSupported,
hide: notSupported,
show: notSupported,
_ready: notSupported
};
require('cordova/exec/proxy').add('StatusBar', module.exports);
|
JavaScript
| 0 |
@@ -1439,45 +1439,8 @@
ed,%0A
- styleLightContect: notSupported,%0A
|
1c9455adbdc0cfa393b54abda09f1c3898ad329f
|
Update dev.js
|
grunt/tasks/dev.js
|
grunt/tasks/dev.js
|
/**
* Project Dev Task
*/
module.exports = function(grunt) {
'use strict';
// Dev Task for Grunt
grunt.registerTask( "dev", "Task for Dev build purpose where minified versions will not run.", [
"validatealljs",
"concat",
"cssmin",
"validation",
"phantomas"
]);
};
|
JavaScript
| 0.000001 |
@@ -280,16 +280,32 @@
antomas%22
+,%0A%09%22sitespeedio%22
%0A %5D);
|
14a3bd262c65035c63735d3e89821179d0471cbd
|
Add APP_INIT
|
src/client/constants/index.js
|
src/client/constants/index.js
|
/* User settings */
// TODO - Add more
export const USER_SAVE = "USER_SAVE"
export const USER_LOAD = "USER_LOAD"
/* Conetnt */
export const BOARD_CHANGE = "BOARD_CHANGE"
export const BOARD_REQUEST = "BOARD_REQUEST"
export const BOARD_LOADED = "BOARD_LOADED"
export const BOARD_DESTROY = "BOARD_DESTROY"
export const BOARD_LIST_LOADED = "BOARD_LIST_LOADED"
export const BOARD_LIST_REQUEST = "BOARD_LIST_REQUEST"
export const THREAD_REQUEST = "THREAD_REQUEST"
export const THREAD_LOADED = "THREAD_LOADED"
export const THREAD_DESTROY = "THREAD_DESTROY"
export const THREAD_POST_LOAD = "THREAD_POST_LOAD"
/* Header */
export const PROVIDER_CHANGE = "PROVIDER_CHANGE"
export const FILTER_BOARD = "FILTER_BOARD"
export const FILTER_THREAD = "FILTER_THREAD"
export const SEARCH_THREAD = "SEARCH_THREAD"
export const SERACH_BOARD = "SERACH_BOARD"
/* Animations */
export const HEADER_SHRINKING = "HEADER_SHRINKING"
export const HEADER_EXPANDING = "HEADER_EXPANDING"
export const HEADER_ANIMATION_END = "HEADER_ANIMATION_END"
export const LOGO_SPIN_START = "LOGO_SPIN_START"
export const LOGO_SPIN_END = "LOGO_SPIN_END"
export const SCROLL_START = "SCROLL_START"
export const SCROLL_END = "SCROLL_END"
|
JavaScript
| 0.000001 |
@@ -103,24 +103,60 @@
USER_LOAD%22%0A%0A
+export const APP_INIT = %22APP_INIT%22%0A%0A
%0A/* Conetnt
|
43a7783f918388b3f7e1f483fcf70c397a342db8
|
add docs to strings
|
helpers/strings.js
|
helpers/strings.js
|
module.exports = {
mainMenuMessage: 'Welcome to @arbeit_bot! I am a completelly free of charge Telegram based freelance market. Please select whether you are looking for job or contractors.',
clientMenuMessage: 'What would you like to do?',
selectCategoryMessage: 'Please select category that your job falls into. Number of contractors available can be found between [square brackets].',
selectJobHourlyRateMessage: 'Please select how much money would you like to pay. Price is given in USD per hour to identify level of developers. Yet you can negotiate fixed price in private messages with contractor later on. Number of available contractors in selected category for rate is given in [square brackets].',
addJobDescriptionMessage: 'Please give us job description (limited to 500 characters). It will be visible to contractors. Please be brief, details can be discussed later with contractors in private dialogues.',
filledEverythingMessage: 'You did it! Your profile is now complete. Now just sit back and wait for clients of your categories to offer you work (obviously if they like your bio).',
fullFreelancerMessageAvailable: 'You are all set! Sit back and relax – clients from relevant categories will contact you if they like your bio and hourly rate.',
fullFreelancerMessageBusy: 'You are all set! However, clients will not bother you as you are in busy status.',
emptyFreelancerMessage: 'Welcome to the freelancer profile! Please fill in your bio, hourly rate and categories, so that clients can evaluate you and offer you job.',
missingFreelancerMessage: 'Welcome to the freelancer profile! Please remember that clients will not be able to find you if you don\'t have bio, categories or hourly rate.',
languageMessage: 'What language do you speak?\n\nНа каком языке вы говорите?',
helpMessage: 'In case you have any requests, suggestions, concerns or just want to chat, contact by creator by clicking the button bellow.',
becameBusyMessage: 'You just set your status to busy. You will not receive any new job offers until you switch back to available.',
becameAvailableMessage: 'You just switched to available status. You will now receive relevant job offers until you switch back to busy.',
missingBecameBusyMessage: 'You just changed your status to busy. But this doesn\'t mean much as clients will not be able to find you without properly filled bio, categories and hourly rate.',
missingBecameAvailableMessage: 'You just changed to available status. But this doesn\'t mean much as clients will not be able to find you without properly filled bio, categories and hourly rate.',
pickFreelancersMessage: 'Success! Job has been created. Please select what freelancers should receive job offer from you.',
editBioMessage: 'Please enter your bio (up to 150 characters)',
selectCandidateMessage: 'Please select a candidate that you liked the most.',
changedBioMessage: 'Congrats! Your new bio is:\n\n',
yourCurrentBio: 'Your current bio:',
editHourlyRateMessage: 'What is your hourly rate?',
pickCategoriesMessage: 'Please pick categories',
suggestCategoryMessage: 'Want to suggest a category?',
waitContractorResponseMessage: 'waitContractorResponseMessage',
waitClientResponseMessage: 'waitClientResponseMessage',
contactWithFreelancerMessage: 'contactWithFreelancerMessage',
clientHasChosenAnotherFreelancer: 'Client has chosen another freelancer.',
mainMenuOptions: {
findJobs: 'Find work',
findContractors: 'Find contractors',
help: 'Help'
},
clientMenuOptions: {
postNewJob: 'Post new job',
myJobs: 'My jobs',
back: '🔙 Back'
},
freelanceMenuOptions: {
editBio: 'Edit bio',
addBio: 'Add bio',
editCategories: 'Edit categories',
addCategories: 'Add categories',
editHourlyRate: 'Edit hourly rate',
addHourlyRate: 'Add hourly rate',
back: '🔙 Back',
busy: '⚒ Busy',
available: '✅ Available',
},
hourlyRateOptions: [
'$0 – $5', '$5 – $10', '$10 – $20',
'$20 – $30', '$30 – $40', '$40 – $50',
'$50 – $75', '$75 – $100', '$100 – $200',
'$200+'
],
selectedCategory: ' ✅',
selectedHourlyRate: '✅ ',
categoryLeft: '<',
categoryRight: '>',
inlineSeparator: '~',
categoryInline: 'cI',
hourlyRateInline: 'hRI',
freelancerInline: 'fI',
freelancerJobInline: 'fJI',
selectFreelancerInline: 'sFI',
selectAnotherFreelancerInline: 'sAFI',
completeJobInline: 'cJI',
inputBioState: 'inputBioState',
inputCategoryNameState: 'inputCategoryNameState',
inputHourlyRateState: 'inputHourlyRateState',
inputJobDescriptionState: 'inputJobDescriptionState',
jobCreateCancel: '❌ Cancel',
selectFreelancerCancel: '❌ Cancel',
jobSendAllFreelancers: 'Send to all',
jobSelectFreelancer: 'Select contractor',
jobSelectAnotherFreelancer: 'Select another contractor',
interestedOption: '✅',
notInterestedOption: '❌',
acceptOption: '✅',
refuseOption: '❌',
pendingOption: '🕒',
jobStates: {
searchingForFreelancer: 'searchingForFreelancer',
freelancerChosen: 'freelancerChosen',
finished: 'finished'
},
freelancerOptions: {
interested: 'Interested',
notInterested: 'Not interested',
//report: 'Report'
},
freelancerAcceptOptions: {
accept: 'Accept',
refuse: 'Refuse'
}
};
|
JavaScript
| 0.000001 |
@@ -1,8 +1,91 @@
+/**%0A * Storage for all the strings in project; change once, use everywhere ;)%0A */%0A%0A
module.e
|
639f64307ad5e5203d93a6fcfa784161b971ab1f
|
Fix Est Account Value
|
src/client/user/UserWallet.js
|
src/client/user/UserWallet.js
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import _ from 'lodash';
import UserWalletSummary from '../wallet/UserWalletSummary';
import { SBD, STEEM } from '../../common/constants/cryptos';
import { getUserDetailsKey } from '../helpers/stateHelpers';
import UserWalletTransactions from '../wallet/UserWalletTransactions';
import Loading from '../components/Icon/Loading';
import {
getUser,
getAuthenticatedUser,
getAuthenticatedUserName,
getTotalVestingShares,
getTotalVestingFundSteem,
getUsersTransactions,
getUsersAccountHistory,
getUsersAccountHistoryLoading,
getLoadingGlobalProperties,
getLoadingMoreUsersAccountHistory,
getUserHasMoreAccountHistory,
getCryptosPriceHistory,
} from '../reducers';
import {
getGlobalProperties,
getUserAccountHistory,
getMoreUserAccountHistory,
} from '../wallet/walletActions';
import { getAccount } from './usersActions';
@withRouter
@connect(
(state, ownProps) => ({
user:
ownProps.isCurrentUser || ownProps.match.params.name === getAuthenticatedUserName(state)
? getAuthenticatedUser(state)
: getUser(state, ownProps.match.params.name),
authenticatedUserName: getAuthenticatedUserName(state),
totalVestingShares: getTotalVestingShares(state),
totalVestingFundSteem: getTotalVestingFundSteem(state),
usersTransactions: getUsersTransactions(state),
usersAccountHistory: getUsersAccountHistory(state),
usersAccountHistoryLoading: getUsersAccountHistoryLoading(state),
loadingGlobalProperties: getLoadingGlobalProperties(state),
loadingMoreUsersAccountHistory: getLoadingMoreUsersAccountHistory(state),
userHasMoreActions: getUserHasMoreAccountHistory(
state,
ownProps.isCurrentUser
? getAuthenticatedUserName(state)
: getUser(state, ownProps.match.params.name).name,
),
cryptosPriceHistory: getCryptosPriceHistory(state),
}),
{
getGlobalProperties,
getUserAccountHistory,
getMoreUserAccountHistory,
getAccount,
},
)
class Wallet extends Component {
static propTypes = {
location: PropTypes.shape().isRequired,
totalVestingShares: PropTypes.string.isRequired,
totalVestingFundSteem: PropTypes.string.isRequired,
user: PropTypes.shape().isRequired,
getGlobalProperties: PropTypes.func.isRequired,
getUserAccountHistory: PropTypes.func.isRequired,
getMoreUserAccountHistory: PropTypes.func.isRequired,
getAccount: PropTypes.func.isRequired,
usersTransactions: PropTypes.shape().isRequired,
usersAccountHistory: PropTypes.shape().isRequired,
cryptosPriceHistory: PropTypes.shape().isRequired,
usersAccountHistoryLoading: PropTypes.bool.isRequired,
loadingGlobalProperties: PropTypes.bool.isRequired,
loadingMoreUsersAccountHistory: PropTypes.bool.isRequired,
userHasMoreActions: PropTypes.bool.isRequired,
isCurrentUser: PropTypes.bool,
authenticatedUserName: PropTypes.string,
};
static defaultProps = {
isCurrentUser: false,
authenticatedUserName: '',
};
componentDidMount() {
const {
totalVestingShares,
totalVestingFundSteem,
usersTransactions,
user,
isCurrentUser,
authenticatedUserName,
} = this.props;
const username = isCurrentUser
? authenticatedUserName
: this.props.location.pathname.match(/@(.*)(.*?)\//)[1];
if (_.isEmpty(totalVestingFundSteem) || _.isEmpty(totalVestingShares)) {
this.props.getGlobalProperties();
}
if (_.isEmpty(usersTransactions[getUserDetailsKey(username)])) {
this.props.getUserAccountHistory(username);
}
if (_.isEmpty(user)) {
this.props.getAccount(username);
}
}
render() {
const {
user,
totalVestingShares,
totalVestingFundSteem,
loadingGlobalProperties,
usersTransactions,
usersAccountHistoryLoading,
loadingMoreUsersAccountHistory,
userHasMoreActions,
usersAccountHistory,
cryptosPriceHistory,
} = this.props;
const userKey = getUserDetailsKey(user.name);
const transactions = _.get(usersTransactions, userKey, []);
const actions = _.get(usersAccountHistory, userKey, []);
const currentSteemRate = _.get(
cryptosPriceHistory,
`${STEEM.symbol}.priceDetails.currentUSDPrice`,
null,
);
const currentSBDRate = _.get(
cryptosPriceHistory,
`${SBD.symbol}.priceDetails.currentUSDPrice`,
null,
);
const steemRateLoading = _.isNull(currentSteemRate) || _.isNull(currentSBDRate);
return (
<div>
<UserWalletSummary
user={user}
loading={user.fetching}
totalVestingShares={totalVestingShares}
totalVestingFundSteem={totalVestingFundSteem}
loadingGlobalProperties={loadingGlobalProperties}
steemRate={currentSteemRate}
sbdRate={currentSBDRate}
steemRateLoading={steemRateLoading}
/>
{transactions.length === 0 && usersAccountHistoryLoading ? (
<Loading style={{ marginTop: '20px' }} />
) : (
<UserWalletTransactions
transactions={transactions}
actions={actions}
currentUsername={user.name}
totalVestingShares={totalVestingShares}
totalVestingFundSteem={totalVestingFundSteem}
getMoreUserAccountHistory={this.props.getMoreUserAccountHistory}
loadingMoreUsersAccountHistory={loadingMoreUsersAccountHistory}
userHasMoreActions={userHasMoreActions}
/>
)}
</div>
);
}
}
export default Wallet;
|
JavaScript
| 0 |
@@ -810,32 +810,43 @@
osPriceHistory,%0A
+ getRate,%0A
%7D from '../reduc
@@ -2016,16 +2016,42 @@
state),%0A
+ rate: getRate(state),%0A
%7D),%0A
@@ -3086,16 +3086,55 @@
string,%0A
+ rate: PropTypes.number.isRequired,%0A
%7D;%0A%0A
@@ -4170,24 +4170,36 @@
iceHistory,%0A
+ rate,%0A
%7D = this
@@ -4641,32 +4641,178 @@
null,%0A );%0A
+ // cryptosPriceHistory doesn't support SBD prices anymore.%0A // But just in case it may support again, try it first and then use feed rate.%0A
const steemR
@@ -4823,16 +4823,22 @@
oading =
+%0A
_.isNul
@@ -4856,24 +4856,25 @@
eemRate) %7C%7C
+(
_.isNull(cur
@@ -4885,16 +4885,79 @@
SBDRate)
+ && _.isNull(rate));%0A const sbdRate = currentSBDRate %7C%7C rate
;%0A%0A r
@@ -5283,26 +5283,19 @@
bdRate=%7B
-currentSBD
+sbd
Rate%7D%0A
|
690b4e39edee372995af6e6a75d4570696535cb4
|
Switch period and number variables in moment.subtract()
|
endpoints/currency/arion.js
|
endpoints/currency/arion.js
|
var request = require('request');
var moment = require('moment');
var h = require('apis-helpers');
var app = require('../../server');
app.get('/currency/arion', function(req, res){
var toSend = 'm=GetCurrencies&beginDate='+moment().subtract('days', 1).format('YYYY-MM-DD')+'&finalDate='+moment().format('YYYY-MM-DD')+'¤cyType=AlmenntGengi¤ciesAvailable=ISK%2CUSD%2CGBP%2CEUR%2CCAD%2CDKK%2CNOK%2CSEK%2CCHF%2CJPY%2CXDR';
request.get({
headers: {'content-type' : 'application/x-www-form-urlencoded'},
url: 'http://www.arionbanki.is/Webservice/PortalCurrency.ashx',
body: toSend
}, function(error, response, body){
if(error || response.statusCode !== 200) {
return res.status(500).json({error:'www.arionbanki.is refuses to respond or give back data'});
}
var jsonObject = JSON.parse(body),
currencies = [];
jsonObject.forEach(function(object,i){
var changePer = parseFloat(object.LastValueChange)/parseFloat(object.MidValue),
currency = {
shortName: object.Ticker,
longName: h.currency[object.Ticker].long,
value: object.MidValue,
askValue: object.AskValue,
bidValue: object.BidValue,
changeCur: object.LastValueChange,
changePer: changePer.toFixed(2),
};
if(currency.changePer == '-0.00')
currency.changePer = 0;
currencies.push(currency)
});
return res.json({ results: currencies });
});
});
|
JavaScript
| 0 |
@@ -241,17 +241,17 @@
act(
+1,
'days'
-, 1
).fo
|
28c574e0f15c94ae8fdbaa20a757190affdbaf28
|
Update evaluate tests to reintroduce hard coded attic
|
babel/test/evaluate.js
|
babel/test/evaluate.js
|
import test from 'ava';
import * as _ from 'lodash';
import {Board} from '../src/board';
import {boards} from './data/boards';
import * as attic from './data/attic';
let boardInstance = new Board(5, 5);
/*
Collects data for each `board` after evaluation and stores it in `testBoards`.
This data is then compared to the correct data in `boards` for the tests.
Passing tests could look like this:
testBoards -> {
'a simple row match': {
matchData: [
[6, 3]
],
evaluatedOrbs: [
[ 1, 7, 8, 7, 5 ],
[ 5, 2, 3, 4, 4 ],
[ 4, 1, 2, 3, 3 ],
[ 3, 5, 1, 2, 2 ],
[ 2, 3, 4, 5, 1 ]
]
},
'a simple column match': {
matchData: [
[6, 3]
],
evaluatedOrbs: [
[ 1, 2, 3, 4, 7 ],
[ 5, 1, 2, 3, 8 ],
[ 4, 5, 1, 2, 7 ],
[ 3, 4, 5, 1, 5 ],
[ 2, 3, 4, 5, 4 ]
]
},
// and so on...
}
*/
let testBoards = {};
_.each(boards, (metadata, name) => {
boardInstance.orbs = _.cloneDeep(metadata.orbs);
boardInstance.attic.types = [6, 7, 8, 9, 0];
boardInstance.attic.generateOrbs();
testBoards[name] = {};
testBoards[name].matchData = boardInstance.evaluate();
testBoards[name].evaluatedOrbs = boardInstance.orbs;
});
_.each(boards, (metadata, name) => {
test(`gathers data for ${name}`, t => {
t.true(_.isEqual(testBoards[name].matchData, metadata.evaluate.matchData));
});
test(`removes matches and replaces with valid type orbs for ${name}`, t => {
_.each(_.flattenDeep(testBoards[name].evaluatedOrbs), orb => {
t.true(_.includes(_.range(10), orb));
});
});
test(`nonmatch orbs drop down into the correct place for ${name}`, t => {
_.each(metadata.evaluate.nonMatchDropped, section => {
let [sliceData, droppedOrbs] = section;
let [row, start, end] = sliceData;
t.ok(_.isEqual(_.slice(testBoards[name].evaluatedOrbs[row], start, end), droppedOrbs));
});
});
test(`orbs from atticOrbs drop down to fill in the rest of the board for ${name}`, t => {
_.each(metadata.evaluate.atticOrbsDropped, section => {
let [sliceData, droppedAtticOrbs] = section;
let [row, start, end] = sliceData;
_.each(_.slice(testBoards[name].evaluatedOrbs[row], start, end), orb => {
t.true(_.includes([6, 7, 8, 9, 0], orb))
});
});
});
test(`unaffected orbs are unchanged for ${name}`, t => {
_.each(metadata.evaluate.unaffectedOrbs, sliceData => {
let [row, start, end] = sliceData;
let beforeSlice = _.slice(metadata.orbs[row], start, end);
let evaluatedSlice = _.slice(testBoards[name].evaluatedOrbs[row], start, end);
t.true(_.isEqual(beforeSlice, evaluatedSlice));
});
});
});
|
JavaScript
| 0.000003 |
@@ -1126,71 +1126,25 @@
tic.
-types = %5B6, 7, 8, 9, 0%5D;%0A boardInstance.attic.generateO
+orbs = attic.o
rbs
-()
;%0A
@@ -2345,22 +2345,30 @@
-_.each
+t.ok(_.isEqual
(_.slice
@@ -2422,87 +2422,25 @@
d),
-orb =%3E %7B%0A t.true(_.includes(%5B6, 7, 8, 9, 0%5D, orb))%0A %7D
+droppedAtticOrbs)
);%0A
|
7abc5ef4c5ca989abef38c7ff5541bd177735e98
|
Fix TimelineDemo for last day of the month.
|
Apps/TimelineDemo/TimelineDemo.js
|
Apps/TimelineDemo/TimelineDemo.js
|
/*global document,window,define*/
define(['dojo',
'dijit/dijit',
'Core/Clock',
'Core/Color',
'Core/JulianDate',
'Core/TimeInterval',
'Widgets/Timeline'
], function(
dojo,
dijit,
Clock,
Color,
JulianDate,
TimeInterval,
Timeline) {
"use strict";
var startDatePart, endDatePart, startTimePart, endTimePart;
var timeline, clock;
function handleSetTime(e) {
if (typeof timeline !== 'undefined') {
var scrubJulian = e.timeJulian;
clock.currentTime = scrubJulian;
var date = scrubJulian.toDate();
document.getElementById('mousePos').innerHTML = date.toUTCString();
}
}
function handleSetZoom(e) {
var span = timeline._timeBarSecondsSpan, spanUnits = 'sec';
if (span > 31536000) {
span /= 31536000;
spanUnits = 'years';
} else if (span > 2592000) {
span /= 2592000;
spanUnits = 'months';
} else if (span > 604800) {
span /= 604800;
spanUnits = 'weeks';
} else if (span > 86400) {
span /= 86400;
spanUnits = 'days';
} else if (span > 3600) {
span /= 3600;
spanUnits = 'hours';
} else if (span > 60) {
span /= 60;
spanUnits = 'minutes';
}
dojo.byId('formatted').innerHTML = '<br/>Start: ' + e.startJulian.toDate().toUTCString() + '<br/>Stop: ' + e.endJulian.toDate().toUTCString() + '<br/>Span: ' + span + ' ' + spanUnits;
document.getElementById('mousePos').innerHTML = clock.currentTime.toDate().toUTCString();
}
function makeTimeline(startJulian, scrubJulian, endJulian) {
clock = new Clock({
startTime : startJulian,
currentTime : scrubJulian,
stopTime : endJulian
});
timeline = new Timeline('time1', clock);
timeline.addEventListener('settime', handleSetTime, false);
timeline.addEventListener('setzoom', handleSetZoom, false);
timeline.addTrack(new TimeInterval(startJulian, startJulian.addSeconds(60*60)), 8, Color.RED, new Color(0.75, 0.75, 0.75, 0.5));
timeline.addTrack(new TimeInterval(endJulian.addSeconds(-60*60), endJulian), 8, Color.GREEN);
var middle = startJulian.getSecondsDifference(endJulian) / 4;
timeline.addTrack(new TimeInterval(startJulian.addSeconds(middle), startJulian.addSeconds(middle * 3)), 8, Color.BLUE, new Color(0.75, 0.75, 0.75, 0.5));
}
// Adjust start/end dates in reaction to any calendar/time clicks
//
function newDatesSelected() {
var startJulian, endJulian, startDate, endDate;
if (startDatePart && startTimePart) {
startDate = dojo.date.stamp.fromISOString(startDatePart + startTimePart + 'Z'); // + 'Z' for UTC
startJulian = new JulianDate.fromDate(startDate);
}
if (endDatePart && endTimePart) {
endDate = dojo.date.stamp.fromISOString(endDatePart + endTimePart + 'Z');
endJulian = new JulianDate.fromDate(endDate);
}
if (startJulian && endJulian) {
if (!timeline) {
makeTimeline(startJulian, startJulian, endJulian);
}
clock.startTime = startJulian;
clock.stopTime = endJulian;
timeline.zoomTo(startJulian, endJulian);
}
}
// React to calendar date clicks
//
function newStartDateSelected(newDate) {
startDatePart = dojo.date.stamp.toISOString(newDate, {
selector : 'date'
});
newDatesSelected();
}
function newEndDateSelected(newDate) {
endDatePart = dojo.date.stamp.toISOString(newDate, {
selector : 'date'
});
newDatesSelected();
}
// React to time-of-day selectors
//
function newStartTimeSelected(newTime) {
startTimePart = newTime.toString().replace(/.*1970\s(\S+).*/, 'T$1');
newDatesSelected();
}
function newEndTimeSelected(newTime) {
endTimePart = newTime.toString().replace(/.*1970\s(\S+).*/, 'T$1');
newDatesSelected();
}
dojo.ready(function() {
dojo.connect(dijit.byId('startCal'), 'onChange', newStartDateSelected);
dojo.connect(dijit.byId('endCal'), 'onChange', newEndDateSelected);
dojo.connect(dijit.byId('startTimeSel'), 'onChange', newStartTimeSelected);
dojo.connect(dijit.byId('endTimeSel'), 'onChange', newEndTimeSelected);
dijit.byId('startTimeSel').set('value', 'T00:00:00');
dijit.byId('endTimeSel').set('value', 'T24:00:00');
var now = new Date();
var today = now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate();
var tomorrow = now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + (now.getDate() + 1);
dijit.byId('startCal').set('value', today);
dijit.byId('endCal').set('value', tomorrow);
});
});
|
JavaScript
| 0 |
@@ -4761,211 +4761,71 @@
var
-now = new Date();%0A var today = now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate();%0A var tomorrow = now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + (now.getDate() +
+today = new JulianDate();%0A var tomorrow = today.addDays(
1);%0A
@@ -4873,16 +4873,25 @@
', today
+.toDate()
);%0A
@@ -4935,16 +4935,25 @@
tomorrow
+.toDate()
);%0A %7D
|
9fde566796fda861b38d7af3352e8bb2db02f7ee
|
add es7/object polyfills
|
ie-polyfills.js
|
ie-polyfills.js
|
/** IE9, IE10 and IE11 requires all of the following polyfills. **/
import "core-js/es6/symbol";
import "core-js/es6/object";
import "core-js/es6/function";
import "core-js/es6/parse-int";
import "core-js/es6/parse-float";
import "core-js/es6/number";
import "core-js/es6/math";
import "core-js/es6/string";
import "core-js/es6/date";
import "core-js/es6/array";
import "core-js/es6/regexp";
import "core-js/es6/map";
import "core-js/es6/weak-map";
import "core-js/es6/set";
import "core-js/es6/promise";
import "core-js/es7/array";
// import requestAnimationFrame polyfill for IE9 support
import "./raf.js";
/** IE10 and IE11 requires the following for NgClass support on SVG elements */
import 'classlist.js'; // Run `npm install --save classlist.js`.
/** IE10 and IE11 requires the following to support `@angular/animation`. */
import "web-animations-js"; // Run `npm install --save web-animations-js`.
|
JavaScript
| 0 |
@@ -490,17 +490,15 @@
s/es
-6/promise
+7/array
%22;%0Ai
@@ -516,21 +516,22 @@
-js/es7/
-array
+object
%22;%0A// im
|
06c9a5c1b52ae2974f9ca22a011f8a6493787b8e
|
add timeout
|
protractor-config.js
|
protractor-config.js
|
exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: [
'test/e2e/*spec.js'
],
capabilities: {
'browserName': 'chrome',
'chromeOptions': {'args': ['--disable-extensions']}
},
baseUrl: 'http://localhost:3000',
jasmineNodeOpts: {
onComplete: null,
isVerbose: false,
showColors: true,
includeStackTrace: true,
defaultTimeoutInterval: 10000
}
};
|
JavaScript
| 0.000008 |
@@ -252,16 +252,193 @@
3000',%0A%0A
+ onPrepare: function() %7B%0A // Override the timeout for webdriver.%0A var ptor = protractor.getInstance();%0A ptor.driver.manage().timeouts().setScriptTimeout(60000);%0A %7D,%0A%0A
jasmin
@@ -446,24 +446,24 @@
NodeOpts: %7B%0A
-
onComple
@@ -577,9 +577,9 @@
al:
-1
+6
0000
|
ea9a4dd6114f6885c6f0bc6bfba40a91937e4fe5
|
Add socket event listeners and refactoring for generic notify function
|
event/static/event/scripts/socket.js
|
event/static/event/scripts/socket.js
|
function Socket(url, icon_url) {
var socket = new WebSocket(url);
socket.onopen = function open() {
console.log('WebSockets connection created.');
};
socket.onmessage = function message(event) {
var data = JSON.parse(event.data);
notify(data, icon_url);
};
if (socket.readyState === WebSocket.OPEN) {
socket.onopen();
}
}
function notify(data, icon_url) {
if ('Notification' in window) {
var title = data['date'] + ' ' + data['title'],
options = {
"body": 'has been changed',
"icon": icon_url
};
switch (Notification.permission) {
case 'default':
Notification.requestPermission().then(function (permission) {
if (permission === 'granted') {
new Notification(title, options);
}
});
break;
case 'granted':
new Notification(title, options);
break;
}
}
}
|
JavaScript
| 0 |
@@ -75,16 +75,32 @@
ket.
-on
+addEventListener('
open
- =
+',
fun
@@ -105,20 +105,16 @@
unction
-open
() %7B%0A
@@ -160,24 +160,25 @@
ated.');%0A %7D
+)
;%0A%0A socket.
@@ -181,19 +181,35 @@
ket.
-on
+addEventListener('
message
- =
+',
fun
@@ -214,23 +214,16 @@
unction
-message
(event)
@@ -265,115 +265,138 @@
ata)
-;%0A
+,
%0A
-notify(data, icon_url);%0A %7D;%0A%0A if (socket.readyState === WebSocket.OPEN) %7B%0A socket.onopen(
+ title = data%5B'date'%5D + ' ' + data%5B'title'%5D,%0A body = 'has been changed';%0A%0A notify(title, body, icon_url
);%0A %7D
+);
%0A%7D%0A%0A
@@ -415,22 +415,24 @@
ify(
-data
+text, body
, icon
-_url
) %7B%0A
@@ -485,42 +485,12 @@
e =
-data%5B'date'%5D + ' ' + data%5B'title'%5D
+text
,%0A
@@ -525,34 +525,20 @@
%22body%22:
-'has been changed'
+body
,%0A
@@ -553,20 +553,16 @@
n%22: icon
-_url
%0A
|
416fb7ee4655b1baa293a5b16749ca5688d4a426
|
Update version string to 2.3.0-rc.1
|
version.js
|
version.js
|
if (enyo && enyo.version) {
enyo.version["enyo-ilib"] = "2.3.0-pre.12";
}
|
JavaScript
| 0 |
@@ -61,14 +61,12 @@
3.0-
-pre
+rc
.1
-2
%22;%0A%7D
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.