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
7c51a8f2baac9c0977d5a54551c8078f57cff09d
remove redundant functions, re #3201
arches/app/media/js/views/graph-designer.js
arches/app/media/js/views/graph-designer.js
define([ 'underscore', 'knockout', 'views/base-manager', 'models/graph', 'views/graph/graph-tree', 'graph-designer-data', 'bindings/resizable-sidepanel' ], function(_, ko, BaseManagerView, GraphModel, GraphTree, data) { var viewModel = { dataFilter: ko.observable(''), placeholder: ko.observable(''), graphid: ko.observable(data.graphid), activeTab: ko.observable('graph'), viewState: ko.observable('design'), expandAll: function(){ viewModel.graphTree.expandAll(); }, collapseAll: function(){ viewModel.graphTree.collapseAll(); }, } viewModel.graphModel = new GraphModel({ data: data.graph, datatypes: data.datatypes, ontology_namespaces: data.ontology_namespaces }); viewModel.graphTree = new GraphTree({ graphModel: viewModel.graphModel }); if (viewModel.activeTab() === 'graph') { // here we might load data/views asyncronously }else{ } if (viewModel.viewState() === 'design') { // here we might load data/views asyncronously }else{ } return new BaseManagerView({ viewModel: viewModel }); });
JavaScript
0.000003
@@ -477,187 +477,8 @@ gn') -,%0A expandAll: function()%7B%0A viewModel.graphTree.expandAll();%0A %7D,%0A collapseAll: function()%7B%0A viewModel.graphTree.collapseAll();%0A %7D, %0A
67d0ce5928a0d9d837b3d90fd647b54a72da5b09
Handle case where image doesn't have a src
sashimi-webapp/src/logic/renderer/core.js
sashimi-webapp/src/logic/renderer/core.js
import VirtualBook from './VirtualBook'; import VirtualPage from './VirtualPage'; import helper from './helper'; const CLASS_NAME_PREFIX = 'page-view'; // Setting up page-break-before mechanism // These page-break-before are hardcoded for now. // TODO: Refactor this code const checkShouldPageBreak = function checkShouldPageBreak(childHeights, index) { const BREAK_PAGE = true; const DO_NOTHING = false; const eleName = childHeights[index].ele.tagName; switch (eleName) { case 'H1': { // If this H1 is at the beginning of the page, do not break if (index === 0) { return DO_NOTHING; } else { return BREAK_PAGE; } } case 'H2': { // If a H2 was immediately preceeded by H1, // then, this H2 will not have a page-before-break if (childHeights[index - 1] && childHeights[index - 1].ele.tagName === 'H1') { return DO_NOTHING; } else { return BREAK_PAGE; } } default: return ['PAGEBREAK'].some(name => name === eleName); } }; export default { /** * Render pageRenderer's HTML content into its referenceFrame. * This function will cause the reflowing of HTML content * within the width of the referenceFrame. * @return {Promise} promise after the HTML has rendered */ updateReferenceFrame: function updateReferenceFrame(pageRenderer) { const rf = pageRenderer.referenceFrame; rf.innerHTML = pageRenderer.sourceHTML; // Additional element styling const imgElements = rf.getElementsByTagName('IMG'); for (let i = 0; i < imgElements.length; i += 1) { helper.overwriteStyle(imgElements[i].style, { maxWidth: '100%', maxHeight: `${pageRenderer.renderHeight}px` }); } // Special check for image loading // A similar checking might be needed for external plugin return new Promise((resolve, reject) => { // TODO: Need to reject promise after timeout // in case the images is taking too long to load. const imageArray = rf.getElementsByTagName('IMG'); let countLoadedImage = 0; const checkForLoadingCompletion = () => { if (countLoadedImage === imageArray.length) { resolve(rf); } }; const increateLoadedImageCount = () => { countLoadedImage += 1; checkForLoadingCompletion(); }; for (let i = 0; i < imageArray.length; i += 1) { // Increment image load count as long as the image is processed. imageArray[i].onload = increateLoadedImageCount; imageArray[i].onerror = increateLoadedImageCount; } checkForLoadingCompletion(); }); }, /** * Get the height of all elements inside a referenceFrame. * @return {array} childHeights - array containing reference to each elements and its respective height */ getChildHeights: function getChildHeights(referenceFrame) { const childNodes = referenceFrame.childNodes; const childArray = Object.keys(childNodes).map(key => childNodes[key]); const childHeights = childArray.filter(childNode => (childNode.nodeName !== '#text')) .map((childNode) => { const nodeStyle = childNode.currentStyle || getComputedStyle(childNode); // Get node's height const nodeStyleHeight = parseFloat(nodeStyle.height, 10) || 0; const nodeHeight = Math.max( childNode.clientHeight, childNode.offsetHeight, nodeStyleHeight ); // Get node's margin const nodeMargin = parseFloat(nodeStyle.marginTop, 10) + parseFloat(nodeStyle.marginBottom, 10); const totalHeight = nodeHeight + nodeMargin; if (isNaN(totalHeight)) { throw new Error('Error calculating element\'s height'); } return ({ height: totalHeight, ele: childNode }); }); return childHeights; }, /** * This function will take in an array of elements with their heights information * to organise them into an array of page according to the page size specified. * @param {PageRenderer} pageRenderer * @param {array} childHeights - array containing reference to each elements and its respective height * @return {array} virtualBookPages - array of pages containing references to element */ getPaginationVirtualDom: function getPaginationVirtualDom(pageRenderer, childHeights) { const pr = pageRenderer; const virtualBook = new VirtualBook(); let virtualPage = new VirtualPage(pr.renderHeight); // Allocate element in pages within the render height childHeights.forEach((element, index) => { try { if (checkShouldPageBreak(childHeights, index)) { // Create a new page is page should be broken here virtualBook.add(virtualPage); virtualPage = new VirtualPage(pr.renderHeight); } virtualPage.add(element); } catch (error) { // Store existing page first virtualBook.add(virtualPage); if (error.message === 'Element is larger than page') { if (virtualPage.filledHeight > 0) { // if currently not at the beginning of page, // create new page before inserting. // TODO: Consider breaking element into smaller chunk virtualPage = new VirtualPage(pr.renderHeight); } virtualPage.forceAdd(element); } else if (error.message === 'Page should break here') { virtualPage = new VirtualPage(pr.renderHeight); virtualPage.forceAdd(element); } else if (error.message === 'Page is full') { virtualPage = new VirtualPage(pr.renderHeight); virtualPage.add(element); } else { throw error; } } }); virtualBook.add(virtualPage); return virtualBook.pages; }, /** * Render DOM into the renderFrame of the given pageRenderer * @param {PageRenderer} pageRenderer - to supply page sizing and renderFrame * @param {array} virtualBookPages - array of pages containing references to element */ renderPage: function renderPage(pageRenderer, virtualBookPages) { if (!pageRenderer || !virtualBookPages) { throw new Error('parameters is null or undefined'); } const pr = pageRenderer; // Remove all existing children of renderFrame while (pr.renderFrame.firstChild) { pr.renderFrame.removeChild(pr.renderFrame.firstChild); } // Recreate pages for renderFrame virtualBookPages.forEach((page) => { // Create a new page const pageDiv = document.createElement('DIV'); pageDiv.setAttribute('class', CLASS_NAME_PREFIX); const refStyle = { // CSS to set up the page sizing width: pr.page.width, height: pr.page.height, paddingTop: pr.page.padding.top, paddingBottom: pr.page.padding.bottom, paddingLeft: pr.page.padding.left, paddingRight: pr.page.padding.right }; helper.overwriteStyle(pageDiv.style, refStyle); pr.renderFrame.appendChild(pageDiv); // Put content into the page page.elements.forEach((node) => { pageDiv.appendChild(node.ele); }); }); }, };
JavaScript
0.001132
@@ -2610,24 +2610,163 @@ dImageCount; +%0A%0A // Handle case where image does not have a src attribute%0A if (!imageArray%5Bi%5D.getAttribute.src) increateLoadedImageCount(); %0A %7D%0A
dc6c840ef7c71f615ffb37b43ff59b574fda38a0
Remove configuration options we no longer support; also send config object all the way through in certain build systems.
packages/truffle/lib/build.js
packages/truffle/lib/build.js
var async = require("async"); var mkdirp = require("mkdirp"); var del = require("del"); var fs = require("fs"); var Contracts = require("./contracts"); var BuildError = require("./errors/builderror"); var child_process = require("child_process"); var spawnargs = require("spawn-args"); var _ = require("lodash"); var expect = require("truffle-expect"); var contract = require("truffle-contract"); function CommandBuilder(command) { this.command = command; }; CommandBuilder.prototype.build = function(options, callback) { console.log("Running `" + this.command + "`...") var args = spawnargs(this.command); var ps = args.shift(); var cmd = child_process.spawn(ps, args, { detached: false, cwd: options.working_directory, env: _.merge(process.env, { WORKING_DIRECTORY: options.working_directory, BUILD_DESTINATION_DIRECTORY: options.destination_directory, BUILD_CONTRACTS_DIRECTORY: options.contracts_build_directory, WEB3_PROVIDER_LOCATION: "http://" + options.rpc.host + ":" + options.rpc.port }) }); cmd.stdout.on('data', function(data) { console.log(data.toString()); }); cmd.stderr.on('data', function(data) { console.log("build error: " + data); }); cmd.on('close', function(code) { var error = null; if (code !== 0) { error = "Command exited with code " + code; } callback(error); }); }; var Build = { clean: function(options, callback) { var destination = options.build_directory; var contracts_build_directory = options.contracts_build_directory; // Clean first. del([destination + '/*', "!" + contracts_build_directory]).then(function() { mkdirp(destination, callback); }); }, // Note: key is a legacy parameter that will eventually be removed. // It's specific to the default builder and we should phase it out. build: function(options, callback) { var self = this; expect.options(options, [ "build_directory", "working_directory", "contracts_build_directory", "network", "network_id", "provider", "resolver", "rpc" ]); var key = "build"; if (options.dist) { key = "dist"; } var logger = options.logger || console; var builder = options.builder; // No builder specified. Ignore the build then. if (typeof builder == "undefined") { if (options.quiet != true) { return callback(new BuildError("No build configuration specified. Can't build.")); } return callback(); } if (typeof builder == "string") { builder = new CommandBuilder(builder); } else if (typeof builder !== "function") { return callback(new BuildError("Build configuration can no longer be specified as an object. Please see our documentation for an updated list of supported build configurations.")); } else { // If they've only provided a build function, use that. builder = { build: builder }; } // Use our own clean method unless the builder supplies one. var clean = this.clean; if (builder.hasOwnProperty("clean")) { clean = builder.clean; } clean(options, function(err) { if (err) return callback(err); // If necessary. This prevents errors due to the .sol.js files not existing. Contracts.compile(options, function(err) { if (err) return callback(err); var resolved_options = { working_directory: options.working_directory, contracts_build_directory: options.contracts_build_directory, destination_directory: options.build_directory, rpc: options.rpc, provider: options.provider, network: options.network }; builder.build(resolved_options, function(err) { if (!err) return callback(); if (typeof err == "string") { err = new BuildError(err); } callback(err); }); }); }); }, // Deprecated: Specific to default builder. dist: function(config, callback) { this.build(config, "dist", callback); } } module.exports = Build;
JavaScript
0
@@ -956,94 +956,9 @@ tory -,%0A WEB3_PROVIDER_LOCATION: %22http://%22 + options.rpc.host + %22:%22 + options.rpc.port %0A + @@ -1949,94 +1949,8 @@ ory%22 -,%0A %22network%22,%0A %22network_id%22,%0A %22provider%22,%0A %22resolver%22,%0A %22rpc%22 %0A @@ -3240,340 +3240,8 @@ );%0A%0A - var resolved_options = %7B%0A working_directory: options.working_directory,%0A contracts_build_directory: options.contracts_build_directory,%0A destination_directory: options.build_directory,%0A rpc: options.rpc,%0A provider: options.provider,%0A network: options.network%0A %7D;%0A%0A @@ -3262,17 +3262,8 @@ ild( -resolved_ opti
d40873edace052c8de9c63c7517a3baf4693ed38
test ok
src/scripts/modules/article/ArticleCtrl.spec.js
src/scripts/modules/article/ArticleCtrl.spec.js
//The tests describe('<Unit Test>', function() { describe('Article:', function() { var $scope, ArticleCtrl; beforeEach(module('arb')); beforeEach(inject(function ($controller, _$httpBackend_, $rootScope, $state, _ArbRest_, conf) { var baseUrl = conf.getApiUrl(); $scope = $rootScope.$new(); ArticleCtrl = $controller('ArticleCtrl', { $scope: $scope, ArbRest: _ArbRest_ }); _$httpBackend_.expectPOST( baseUrl + '/article').respond(); $state.transitionTo('article.create'); })); afterEach(inject(function ($rootScope, _$httpBackend_) { $rootScope.$digest(); _$httpBackend_.flush(); })); describe('Method Save', function() { iit('test', inject(function ($rootScope, $state, conf) { $scope.title = 'title of article'; $scope.contents = 'contents of article'; ArticleCtrl.create($state, $scope); }) ); it('should be able to save without problems', inject(function(_$httpBackend_, $state, $controller, $rootScope) { var $httpBackend = _$httpBackend_; $scope = $rootScope.$new(); ArticleCtrl = $controller('ArticleCtrl', { $scope: $scope, }); $state.transitionTo('article.create'); $scope.title = 'title of article'; $scope.contents = 'contents of article'; ArticleCtrl.create($state, $scope); console.log($httpBackend) $rootScope.$digest(); $httpBackend.flush(); //asset }) ); it( 'should pass a dummy test ArticleCtrl', function() { ArticleCtrl.should.exist; }); it('should be able to show an error when try to save without title', function(done) { article.title = ''; return article.save(function(err) { should.exist(err); done(); }); }); }); // afterEach(function(done) { // Article.remove({}); // User.remove({}); // done(); // }); // after(function(done){ // Article.remove().exec(); // User.remove().exec(); // done(); // }); }); });
JavaScript
0.000003
@@ -244,28 +244,24 @@ f) %7B%0A%0A - var baseUrl @@ -282,28 +282,24 @@ rl();%0A - - $scope = $ro @@ -316,28 +316,24 @@ ew();%0A - - ArticleCtrl @@ -363,36 +363,32 @@ trl', %7B%0A - $scope: $scope,%0A @@ -395,20 +395,16 @@ - - ArbRest: @@ -416,37 +416,29 @@ Rest_%0A - - %7D);%0A%0A - _$http @@ -501,17 +501,9 @@ - %0A +%0A @@ -524,39 +524,32 @@ itionTo('article -.create ');%0A%0A %7D));%0A%0A @@ -788,24 +788,74 @@ e, conf) %7B%0A%0A + $state.transitionTo('article.create');%0A%0A $s
b73bf0f45e959b29eb75a61c9915d024a0475974
Add no-sparse-arrays rule
.eslintrc.js
.eslintrc.js
module.exports = { 'env': { 'browser': true, 'commonjs': true, 'es6': true, 'jasmine': true }, 'extends': [ 'eslint:recommended', 'plugin:flowtype/recommended' ], 'globals': { // The globals that (1) are accessed but not defined within many of our // files, (2) are certainly defined, and (3) we would like to use // without explicitly specifying them (using a comment) inside of our // files. '__filename': false }, 'parser': 'babel-eslint', 'parserOptions': { 'ecmaFeatures': { 'experimentalObjectRestSpread': true }, 'sourceType': 'module' }, 'plugins': [ 'flowtype', // ESLint's rule no-duplicate-imports does not understand Flow's import // type. Fortunately, eslint-plugin-import understands Flow's import // type. 'import' ], 'rules': { 'new-cap': 2, 'no-console': 0, 'semi': [ 'error', 'always' ], 'no-cond-assign': 2, 'no-constant-condition': 2, 'no-control-regex': 2, 'no-debugger': 2, 'no-dupe-args': 2, 'no-duplicate-case': 2, 'no-empty': 2, 'no-empty-character-class': 2, 'no-ex-assign': 2, 'no-extra-boolean-cast': 2, 'no-extra-parens': [ 'error', 'all', { 'nestedBinaryExpressions': false } ], 'no-extra-semi': 2, 'no-func-assign': 2, 'no-inner-declarations': 2, 'no-invalid-regexp': 2, 'no-irregular-whitespace': 2, 'no-negated-in-lhs': 2, 'no-obj-calls': 2, 'no-prototype-builtins': 0, 'no-regex-spaces': 2, 'prefer-spread': 2, 'require-yield': 2, 'rest-spread-spacing': 2, 'sort-imports': 0, 'template-curly-spacing': 2, 'yield-star-spacing': 2, 'import/no-duplicates': 2 } };
JavaScript
0.000052
@@ -1755,24 +1755,55 @@ -spaces': 2, +%0A 'no-sparse-arrays': 2, %0A%0A 'p
d2bab8ccb7be305db6629440b3dcb72a699fed35
Fix welcome page authentication redirect not working
api/controllers/auth.js
api/controllers/auth.js
'use strict' let passport = require('passport') let BasicStrategy = require('passport-http').BasicStrategy let BearerStrategy = require('passport-http-bearer').Strategy let crypto = require('crypto') let LocalStrategy = require('passport-local').Strategy let User = require('../db').User let Rat = require('../db').Rat let db = require('../db').db let Token = require('../db').Token let Client = require('../db').Client let bcrypt = require('bcrypt') let Permission = require('../permission') exports.LocalStrategy = new LocalStrategy({ usernameField: 'email', passwordField: 'password', session: false }, function (email, password, done) { if (!email || !password) { done(null, false, { message: 'Incorrect username/email.' }) } findUserWithRats({ email: { $iLike: email }}).then(function (user) { if (!user) { done(null, false, { message: 'Incorrect username/email.' }) return } if (user.salt) { crypto.pbkdf2(password, user.salt, 25000, 512, 'sha256', function (err, hashRaw) { let hash = new Buffer(hashRaw, 'binary').toString('hex') if (user.password === hash) { // Legacy password system migration bcrypt.hash(password, 16, function (error, convertedPassword) { if (error) { done(null, user) return } let apiUser = convertUserToAPIResult(user) User.update({ password: convertedPassword, salt: null }, { where: { id: user.id } }).then(function () { done(null, apiUser) }).catch(function () { done(null, false) }) }) } else { done(null, false, { message: 'Incorrect username or password.' }) } }) } else { bcrypt.compare(password, user.password, function (err, res) { if (err || res === false) { done(null, false) } else { done(null, convertUserToAPIResult(user)) } }) } }).catch(function () { done(null, false) }) }) passport.use(exports.LocalStrategy) passport.use('client-basic', new BasicStrategy( function (username, secret, callback) { Client.findById(username).then(function (client) { if (!client) { callback(null, false) } bcrypt.compare(secret, client.secret, function (err, res) { if (err || res === false) { callback(null, false) } else { callback(null, client) } }) }).catch(function (error) { callback(error) }) } )) passport.use(new BearerStrategy( function (accessToken, callback) { Token.findOne({ where: { value: accessToken } }).then(function (token) { if (!token) { callback(null, false) return } User.findOne({ where: { id: token.userId }, attributes: { include: [ [db.cast(db.col('nicknames'), 'text[]'), 'nicknames'] ], exclude: [ 'nicknames' ] }, include: [ { model: Rat, as: 'rats', required: false } ] }).then(function (userInstance) { let user = userInstance.toJSON() let reducedRats = user.rats.map(function (rat) { return rat.id }) user.CMDRs = reducedRats delete user.rats callback(null, user, { scope: '*' }) }).catch(function () { callback(null, false) }) }).catch(function () { callback(null, false) }) } )) exports.isClientAuthenticated = passport.authenticate('client-basic', { session : false }) exports.isBearerAuthenticated = passport.authenticate('bearer', { session: false }) exports.isAuthenticated = function (isUserFacing) { return function (req, res, next) { if (req.user) { req.session.returnTo = null return next() } else { passport.authenticate('bearer', { session : false }, function (error, user) { if (!user) { if (!isUserFacing) { let error = Permission.authenticationError() res.model.errors.push(error) res.status(error.code) return next(error) } else { req.session.returnTo = req.originalUrl || req.url if (req.session.legacy) { return res.redirect('/login') } else { res.model.data = req.user res.status(200) return } } } req.user = user next() })(req, res, next) } } } function findUserWithRats (where) { return User.findOne({ where: where, attributes: { include: [ [db.cast(db.col('nicknames'), 'text[]'), 'nicknames'] ], exclude: [ 'nicknames', 'dispatch', 'deletedAt' ] }, include: [ { model: Rat, as: 'rats', required: false } ] }) } function convertUserToAPIResult (userInstance) { let user = userInstance.toJSON() let reducedRats = user.rats.map(function (rat) { return rat.id }) user.CMDRs = reducedRats delete user.rats delete user.salt delete user.password return user }
JavaScript
0.000001
@@ -4405,16 +4405,32 @@ n.legacy + %7C%7C isUserFacing ) %7B%0A @@ -4560,16 +4560,37 @@ us(200)%0A + next()%0A
f00db50a1b27b0563bfb57e52c6fa17480893a01
Remove parameter
helpText.js
helpText.js
const helpIntro = "This help command posts a list of commands.\ This list is not necessarily complete or acurate.\ Some commands may not yet be implemented.\n\n"; blockQuote = function(str) { return ("```\n" + str + "\n```"); } exports.help = function(msg) { return blockQuote(helpIntro + "Bot Admin commands:\ !help public (not implemented):\ displays this help text in the channel the request was made from.\ \ Bot User Commands:\ !help (not implemented):\ Sends the user this help text in a direct message\ !ping:\ Bot replys \"Pong!\" and the time it took to reply.\ !on-call:\ Toggles the on-call role for the command sender.\ Only works if the server has a role called \"On-call\".")) }
JavaScript
0.000003
@@ -261,11 +261,8 @@ ion( -msg ) %7B%0A
77469e9a060d4c4b4301f8956d21faac19e760c8
remove comments
src/searching/builder/HardwaresSearchBuilder.js
src/searching/builder/HardwaresSearchBuilder.js
'use strict'; import SearchBuilder from './SearchBuilder'; import FieldFinder from '../../util/searchingFields/FieldFinder' const BASE_URL = '/catalog/hardwares'; /** * Defined a search over Devices * @example ogapi.devicesSearchBuilder() */ export default class HardwaresSearchBuilder extends SearchBuilder { /** * @param {!InternalOpenGateAPI} parent - Instance of our InternalOpenGateAPI */ constructor(parent) { super(parent, {}, new FieldFinder(parent, BASE_URL)); this._url = BASE_URL; } /** * The response will only have a summary information * @example * ogapi.HardwaresSearchBuilder().summary() * @return {HardwaresSearchBuilder} */ /** * The search request will have this group by * @example * @param {!(object)} group * @return {SearchBuilder} */ group(group) { this._builderParams.group = (group || {}); return this; } /** * The search request will have this filter * @example * ogapi.HardwaresSearchBuilder().select(...) * @param {!(SelectBuilder|object)} select * @return {SearchBuilder} */ select(select) { this._builderParams.select = (select); return this; } /** * The response will return a flattened response * @example * ogapi.HardwaresSearchBuilder().flattened() * @return {HardwaresSearchBuilder} */ flattened() { this._urlParams.flattened = true; return this; } /** * The response will return a response without sorted * @example * ogapi.HardwaresSearchBuilder().disableDefaultSorted() * @return {HardwaresSearchBuilder} */ disableDefaultSorted() { this._urlParams.defaultSorted = false; return this; } }
JavaScript
0
@@ -555,198 +555,8 @@ %0D%0A%0D%0A - /**%0D%0A * The response will only have a summary information %0D%0A * @example%0D%0A *%09ogapi.HardwaresSearchBuilder().summary() %0D%0A * @return %7BHardwaresSearchBuilder%7D %0D%0A */%0D%0A%0D%0A%0D%0A
3b86889a99c8951835380fb5baae6d92e7dbd45d
Throw proper error
lib/jor1k.js
lib/jor1k.js
"use strict"; // jor1k compatibility var VIRTIO_MAGIC_REG = 0x0; var VIRTIO_VERSION_REG = 0x4; var VIRTIO_DEVICE_REG = 0x8; var VIRTIO_VENDOR_REG = 0xc; var VIRTIO_HOSTFEATURES_REG = 0x10; var VIRTIO_HOSTFEATURESSEL_REG = 0x14; var VIRTIO_GUESTFEATURES_REG = 0x20; var VIRTIO_GUESTFEATURESSEL_REG = 0x24; var VIRTIO_GUEST_PAGE_SIZE_REG = 0x28; var VIRTIO_QUEUESEL_REG = 0x30; var VIRTIO_QUEUENUMMAX_REG = 0x34; var VIRTIO_QUEUENUM_REG = 0x38; var VIRTIO_QUEUEALIGN_REG = 0x3C; var VIRTIO_QUEUEPFN_REG = 0x40; var VIRTIO_QUEUENOTIFY_REG = 0x50; var VIRTIO_INTERRUPTSTATUS_REG = 0x60; var VIRTIO_INTERRUPTACK_REG = 0x64; var VIRTIO_STATUS_REG = 0x70; /** @const */ var VRING_DESC_F_NEXT = 1; /* This marks a buffer as continuing via the next field. */ /** @const */ var VRING_DESC_F_WRITE = 2; /* This marks a buffer as write-only (otherwise read-only). */ /** @const */ var VRING_DESC_F_INDIRECT = 4; /* This means the buffer contains a list of buffer descriptors. */ function hex8(n) { return h(n); } var message = {}; /** @param {...string} log */ message.Debug = function(log) { dbg_log([].slice.apply(arguments).join(" "), LOG_9P); }; message.Abort = function() { if(DEBUG) { throw "abort"; } }; // XXX: Should go through emulator interface var LoadBinaryResource; if(typeof XMLHttpRequest !== "undefined") { LoadBinaryResource = function(url, OnSuccess, OnError) { var req = new XMLHttpRequest(); req.open('GET', url, true); req.responseType = "arraybuffer"; req.onreadystatechange = function () { if (req.readyState != 4) { return; } if ((req.status != 200) && (req.status != 0)) { OnError("Error: Could not load file " + url); return; } var arrayBuffer = req.response; if (arrayBuffer) { OnSuccess(arrayBuffer); } else { OnError("Error: No data received from: " + url); } }; /* req.onload = function(e) { var arrayBuffer = req.response; if (arrayBuffer) { OnLoadFunction(arrayBuffer); } }; */ req.send(null); }; } else { LoadBinaryResource = function(url, OnSuccess, OnError) { //console.log(url); require("fs")["readFile"](url, function(err, data) { if(err) { OnError(err); } else { OnSuccess(data.buffer); } }); }; }
JavaScript
0.000002
@@ -1224,15 +1224,36 @@ row -%22abort%22 +new Error(%22message.Abort()%22) ;%0A
82bbb5267792b2d9220a2343ed34df10b9023fea
Update RestDAO to new sink interface.
src/foam/dao/RestDAO.js
src/foam/dao/RestDAO.js
/** * @license * Copyright 2017 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ foam.CLASS({ package: 'foam.dao', name: 'RestDAO', extends: 'foam.dao.AbstractDAO', documentation: function() {/* A client-side DAO for interacting with a REST endpoint. Sinks are managed on the client (i.e., sinks passed to select() will not serialize the sink and send it to the endpoint for server-side logic implementation). */}, requires: [ 'foam.core.Serializable', 'foam.dao.ArraySink', 'foam.net.HTTPRequest' ], properties: [ { class: 'String', name: 'baseURL', documentation: 'URL for most rest calls. Some calls add "/<some-info>".', final: true, required: true } ], methods: [ function put(o) { /** * PUT baseURL * <network-foam-jsonified FOAM object> */ return this.createRequest_({ method: 'PUT', url: this.baseURL, payload: this.jsonify_(o) }).send().then(this.onResponse.bind(this, 'put')) .then(this.onPutResponse); }, function remove(o) { /** * DELETE baseURL/<network-foam-jsonified FOAM object id> */ return this.createRequest_({ method: 'DELETE', url: this.baseURL + '/' + encodeURIComponent(this.jsonify_(o.id)) }).send().then(this.onResponse.bind(this, 'remove')) .then(this.onRemoveResponse); }, function find(id) { /** * GET baseURL/<network-foam-jsonified FOAM object id> */ return this.createRequest_({ method: 'GET', url: this.baseURL + '/' + encodeURIComponent(this.jsonify_(id)) }).send().then(this.onResponse.bind(this, 'find')) .then(this.onFindResponse); }, function select(sink, skip, limit, order, predicate) { /** * GET baseURL * { skip, limit, order, predicate } * * Each key's value is network-foam-jsonified. */ var payload = {}; var networkSink = this.Serializable.isInstance(sink) && sink; if ( networkSink ) payload.sink = networkSink; if ( typeof skip !== 'undefined' ) payload.skip = skip; if ( typeof limit !== 'undefined' ) payload.limit = limit; if ( typeof order !== 'undefined' ) payload.order = order; if ( typeof predicate !== 'undefined' ) payload.predicate = predicate; return this.createRequest_({ method: 'POST', url: this.baseURL + ':select', payload: this.jsonify_(payload) }).send().then(this.onResponse.bind(this, 'select')) .then(this.onSelectResponse.bind( this, sink || this.ArraySink.create())); }, function removeAll(skip, limit, order, predicate) { /** * POST baseURL/removeAll * { skip, limit, order, predicate } * * Each key's value is network-foam-jsonified. */ var payload = {}; if ( typeof skip !== 'undefined' ) payload.skip = skip; if ( typeof limit !== 'undefined' ) payload.limit = limit; if ( typeof order !== 'undefined' ) payload.order = order; if ( typeof predicate !== 'undefined' ) payload.predicate = predicate; return this.createRequest_({ method: 'POST', url: this.baseURL + ':removeAll', payload: this.jsonify_(payload) }).send().then(this.onResponse.bind(this, 'removeAll')) .then(this.onRemoveAllResponse); }, function createRequest_(o) { // Demand that required properties are set before using DAO. this.validate(); // Each request should default to a json responseType. return this.HTTPRequest.create(Object.assign({responseType: 'json'}, o)); }, function jsonify_(o) { // What's meant by network-foam-jsonified for HTTP/JSON/REST APIs: // Construct JSON-like object using foam's network strategy, then // construct well-formed JSON from the object. return JSON.stringify(foam.json.Network.objectify(o)); } ], listeners: [ function onResponse(name, response) { if ( response.status !== 200 ) { throw new Error( 'Unexpected ' + name + ' response code from REST DAO endpoint: ' + response.status); } return response.payload; }, function onPutResponse(payload) { var o = foam.json.parse(payload); this.pub('on', 'put', o); return o; }, function onRemoveResponse(payload) { var o = foam.json.parse(payload); if ( o !== null ) this.pub('on', 'remove', o); return o; }, function onFindResponse(payload) { return foam.json.parse(payload); }, function onSelectResponse(localSink, payload) { var wasSerializable = this.Serializable.isInstance(localSink); var remoteSink = foam.json.parse(payload); // If not proxying a local unserializable sink, just return the remote. if ( wasSerializable ) return remoteSink; var array = remoteSink.a; if ( ! array ) throw new Error('Expected ArraySink from REST endpoint when proxying local sink'); if ( localSink.put ) { for ( var i = 0; i < array.length; i++ ) { localSink.put(array[i]); } } if ( localSink.eof ) localSink.eof(); return localSink; }, function onRemoveAllResponse(payload) { return undefined; } ] });
JavaScript
0
@@ -5818,16 +5818,22 @@ ink.put( +null, array%5Bi%5D
1be84c26866c142669626455a31a2b91ce4907fb
Update shake.js
js/shake.js
js/shake.js
//Origin https://gist.github.com/leecrossley/4078996 var shake = (function () { var shake = {}, watchId = null, options = { frequency: 300 }, previousAcceleration = { x: null, y: null, z: null }, shakeCallBack = null; // Start watching the accelerometer for a shake gesture shake.startWatch = function (onShake) { alert('method called'); if (onShake) { alert('shaking!'); shakeCallBack = onShake; } watchId = navigator.accelerometer.watchAcceleration(getAccelerationSnapshot, handleError, options); }; // Stop watching the accelerometer for a shake gesture shake.stopWatch = function () { if (watchId !== null) { navigator.accelerometer.clearWatch(watchId); watchId = null; } }; // Gets the current acceleration snapshot from the last accelerometer watch function getAccelerationSnapshot() { navigator.accelerometer.getCurrentAcceleration(assessCurrentAcceleration, handleError); } // Assess the current acceleration parameters to determine a shake function assessCurrentAcceleration(acceleration) { var accelerationChange = {}; if (previousAcceleration.x !== null) { accelerationChange.x = Math.abs(previousAcceleration.x, acceleration.x); accelerationChange.y = Math.abs(previousAcceleration.y, acceleration.y); accelerationChange.z = Math.abs(previousAcceleration.z, acceleration.z); } if (accelerationChange.x + accelerationChange.y + accelerationChange.z > 30) { // Shake detected if (typeof (shakeCallBack) === "function") { shakeCallBack(); } //shake.stopWatch(); setTimeout(shake.startWatch, 1000, shakeCallBack); previousAcceleration = { x: null, y: null, z: null }; } else { previousAcceleration = { x: acceleration.x, y: acceleration.y, z: acceleration.z }; } } // Handle errors here function handleError() { } return shake; })();
JavaScript
0.000001
@@ -357,85 +357,22 @@ -alert('method called');%0A if (onShake) %7B%0A alert('shaking!'); +if (onShake) %7B %0A @@ -1577,16 +1577,48 @@ etected%0A + alert('shaking!!');%0A @@ -1725,18 +1725,16 @@ -// shake.st
f355f5f9e9dc95c5cebd594eba3e14b4526b19e2
Fix dependency typo
lib/login.js
lib/login.js
'use strict'; var delKey = require('key-del'); var get = require('lodash.get'); var tokenUtils = require('./token'); module.exports = function (options) { return function (req, res) { var getUser = options.getUser var configureToken = options.configureToken || require('./configure-token'); var validatePassword = options.validatePassword || require('./password').validate; var body = req.body; var idField = options.idField; var passwordField = options.passwordField; var passwordHashField = options.passwordHashField; var id = get(body, idField); var password = get(body, passwordField); if (id && password) { getUser.call({ req: req }, id, function (err, user) { if (err) { return res.status(401).json(err); } var hash; if (user && get(user, passwordHashField)) { hash = get(user, passwordHashField); validatePassword(password, hash).then(function (valid) { var tokenData, token; if (valid) { deleteKey(user, passwordHashField, { copy: false }); tokenData = configureToken(user) || get(user, idField); token = tokenUtils.create(tokenData, options); res.json({ token: token }); } else { res.status(401).json('Unauthorized'); } }) .catch(function (error) { res.status(400).json(error); }); } else { res.status(400).json('Invalid user data.'); } }); } else { res.status(400).json('Invalid arguments, expected `' + idField + '` and `' + passwordField + '` to be present.'); } }; };
JavaScript
0.000256
@@ -15,16 +15,19 @@ %0Avar del +ete Key = re
0e106c85948354fac279cf65fcf8572c5477ead9
fix missing files
server/src/database.js
server/src/database.js
import dotenv from 'dotenv'; import Sequelize from 'sequelize'; import User from './../models/User'; import Group from './../models/Group'; import Message from './../models/Message'; import GroupMember from './../models/GroupMember'; import Archive from './../models/archive'; dotenv.config(); let connection; if (process.env.NODE_ENV !== 'production') { connection = new Sequelize( process.env.DB_TEST_NAME, process.env.DB_TEST_USER, process.env.DB_TEST_PASS, { host: process.env.DB_TEST_HOST, port: process.env.DB_PORT, dialect: 'postgres', logging: false }); } else { connection = new Sequelize( process.env.DB_NAME, process.env.DB_USER, process.env.DB_PASS, { host: process.env.DB_HOST, port: process.env.DB_PORT, dialect: 'postgres', dialectOptions: { ssl: true, native: true, }, logging: false }); } const database = {}; // Database models database.Sequelize = Sequelize; database.connection = connection; database.User = User(connection, Sequelize); database.Group = Group(connection, Sequelize); database.Message = Message(connection, Sequelize); database.GroupMember = GroupMember(connection, Sequelize); database.Archive = Archive(connection, Sequelize); // Database 1:M relationships database.Group.belongsTo(database.User, { foreignKey: 'userId' }); database.User.hasMany(database.Group, { foreignKey: 'userId' }); database.Message.belongsTo(database.Group, { foreignKey: 'inGroup' }); database.Group.hasMany(database.Message, { foreignKey: 'inGroup' }); database.Message.belongsTo(database.User, { foreignKey: 'author' }); database.User.hasMany(database.Message, { foreignKey: 'author' }); // Database N:M relationships database.User.belongsToMany(database.Group, { through: database.GroupMember, foreignKey: 'userId' }); database.Group.belongsToMany(database.User, { through: database.GroupMember, foreignKey: 'groupId' }); database.User.belongsToMany(database.Message, { through: database.Archive, foreignKey: 'userId' }); database.Message.belongsToMany(database.User, { through: database.Archive, foreignKey: 'messageId' }); export default database;
JavaScript
0.000365
@@ -293,71 +293,13 @@ );%0A%0A -let connection;%0A%0Aif (process.env.NODE_ENV !== 'production') %7B%0A +const con @@ -315,34 +315,32 @@ new Sequelize(%0A - process.env.DB @@ -344,21 +344,14 @@ .DB_ -TEST_ NAME,%0A - pr @@ -367,21 +367,14 @@ .DB_ -TEST_ USER,%0A - pr @@ -390,21 +390,16 @@ .DB_ -TEST_ PASS, %7B%0A @@ -386,34 +386,32 @@ .env.DB_PASS, %7B%0A - host: proces @@ -423,13 +423,8 @@ .DB_ -TEST_ HOST @@ -421,34 +421,32 @@ nv.DB_HOST,%0A - port: process.en @@ -452,34 +452,32 @@ nv.DB_PORT,%0A - dialect: 'postgr @@ -485,248 +485,8 @@ s',%0A - logging: false%0A %7D);%0A%7D else %7B%0A connection = new Sequelize(%0A process.env.DB_NAME,%0A process.env.DB_USER,%0A process.env.DB_PASS, %7B%0A host: process.env.DB_HOST,%0A port: process.env.DB_PORT,%0A dialect: 'postgres',%0A @@ -503,18 +503,16 @@ ions: %7B%0A - ss @@ -526,18 +526,16 @@ ,%0A - - native: @@ -548,15 +548,11 @@ - %7D,%0A - @@ -570,19 +570,14 @@ lse%0A - %7D);%0A -%7D%0A%0A %0Acon
8b30e388fdaba3aa78169c037da7d9dd775749b1
Disable buggy jsx-indent rule
.eslintrc.js
.eslintrc.js
const path = require('path'); module.exports = { 'root': true, 'parser': 'babel-eslint', 'env': { 'browser': true }, 'extends': [ 'airbnb', 'plugin:import/errors' ], 'settings': { 'import/resolver': { 'webpack': { 'config': path.join(__dirname, 'src', 'webpack.config.babel.js') } } }, 'rules': { 'space-before-function-paren': 0, 'comma-dangle': [2, 'never'], 'one-var': 0, 'one-var-declaration-per-line': 0, 'prefer-arrow-callback': 0, 'arrow-parens': [2, 'as-needed'], 'strict': 0, 'no-use-before-define': [2, {'functions': false}], 'no-underscore-dangle': 0, // https://github.com/benmosher/eslint-plugin-import/issues/414 'import/extensions': 0, 'react/jsx-filename-extension': 0, 'react/jsx-wrap-multilines': 0, 'react/prefer-stateless-function': 0, 'react/jsx-first-prop-new-line': 0, 'react/jsx-no-bind': 0, 'react/sort-comp': [2, { order: [ 'displayName', 'propTypes', 'mixins', 'statics', 'getDefaultProps', 'defaultProps', 'getInitialState', 'constructor', 'render', '/^_render.+$/', // any auxiliary _render methods 'componentWillMount', 'componentDidMount', 'componentWillReceiveProps', 'shouldComponentUpdate', 'componentWillUpdate', 'componentDidUpdate', 'componentWillUnmount', '/^on[A-Z].+$/', // event handlers 'everything-else', '/^_.+$/' // private methods ] }] } }
JavaScript
0.000001
@@ -934,24 +934,119 @@ o-bind': 0,%0A + // https://github.com/yannickcr/eslint-plugin-react/issues/1176%0A 'react/jsx-indent': 0,%0A 'react/s
759146998f1a3f92f72f401648989b8b7705d7f2
add fee limit and route limit arguments to get routes
lightning/get_routes.js
lightning/get_routes.js
const BN = require('bn.js'); const {isFinite} = require('lodash'); const {routesFromQueryRoutes} = require('./../lnd'); const defaultFinalCltvDelta = 144; const defaultRoutesReturnCount = 10; const intBase = 10; const msatsPerToken = 1e3; const pathNotFoundErrors = [ 'noPathFound', 'noRouteFound', 'insufficientCapacity', 'maxHopsExceeded', 'targetNotInNetwork', ]; /** Get invoice payment routes { destination: <Send Destination Hex Encoded Public Key String> lnd: <LND GRPC API Object> [timeout]: <Final CLTV Timeout Blocks Delta Number> tokens: <Tokens to Send Number> } @returns via cbk { routes: [{ fee: <Route Fee Tokens Number> fee_mtokens: <Route Fee MilliTokens String> mtokens: <Total MilliTokens String> timeout: <Timeout Block Height Number> tokens: <Total Tokens Number> hops: [{ channel_capacity: <Channel Capacity Tokens Number> channel_id: <BOLT 07 Encoded Channel Id String> fee: <Fee Number> fee_mtokens: <Fee MilliTokens String> forward: <Forward Tokens Number> forward_mtokens: <Forward MilliTokens String> timeout: <Timeout Block Height Number> }] }] } */ module.exports = ({destination, lnd, timeout, tokens}, cbk) => { if (!destination) { return cbk([400, 'ExpectedDestination']); } if (!lnd) { return cbk([500, 'ExpectedLnd']); } if (!tokens) { return cbk([400, 'ExpectedTokens']); } return lnd.queryRoutes({ amt: tokens, final_cltv_delta: timeout || defaultFinalCltvDelta, num_routes: defaultRoutesReturnCount, pub_key: destination, }, (err, res) => { // Exit early when an error indicates that no routes are possible if (!!err && isFinite(err.code) && !!pathNotFoundErrors[err.code]) { return cbk(null, {routes: []}); } if (!!err) { return cbk([503, 'UnexpectedQueryRoutesError', err]); } try { return cbk(null, routesFromQueryRoutes({response: res})); } catch (e) { return cbk([503, 'InvalidGetRoutesResponse', e]); } }); };
JavaScript
0
@@ -472,24 +472,105 @@ Key String%3E%0A + %5Bfee%5D: %3CMaximum Fee Tokens Number%3E%0A %5Blimit%5D: %3CLimit Results Count Number%3E%0A lnd: %3CLN @@ -1331,16 +1331,28 @@ ination, + fee, limit, lnd, ti @@ -1614,16 +1614,68 @@ tokens,%0A + fee_limit: !fee ? undefined : %7Bfee_limit: fee%7D,%0A fina @@ -1737,16 +1737,25 @@ _routes: + limit %7C%7C default
55926c63f80c1fcc38a613510b25f6694c80d57c
Rename /s to /small
builtins/core.other.js
builtins/core.other.js
const {Feature} = require('other') const feature = new Feature({ name: 'Core', version: '0.0.4', dependencies: { otherjs: '2.x' } }) feature.listen({ to: {commands: ['blockquote', 'caption', 'h1', 'h2', 'h3', 'p', 's']}, on({command, args}) { return {stagedMessage: {format: command === 's' ? 'system' : command}} } }) module.exports = feature
JavaScript
0.000244
@@ -95,9 +95,9 @@ 0.0. -4 +5 ',%0A @@ -127,17 +127,17 @@ herjs: ' -2 +3 .x'%0A %7D%0A @@ -225,16 +225,20 @@ 'p', 's +mall '%5D%7D,%0A o @@ -258,16 +258,101 @@ rgs%7D) %7B%0A + // TODO: Remove this small -%3E system hack once the ioS client understands small.%0A retu @@ -393,16 +393,20 @@ d === 's +mall ' ? 'sys
fa67c36084076d263b1ffa57e79273623c97ec78
fix homepage
lib/dao.js
lib/dao.js
'use strict'; var dao = module.exports = {}; var parser = require('./parser'); var config = require('./config'); // a simple pool dao._queue = []; dao._pending = false; // get the whole data tree dao.tree = function (options, callback) { if ( dao._data ) { return callback(null, dao._data); } dao._queue.push(callback); if ( dao._pending ) { return; } dao._pending = true; var sys = options.sys; var user = options.user; parser.raw_tree( sys.doc, function (err, raw_tree) { if ( err ) { return dao._complete(err); } var ltree = parser.language_tree(raw_tree, user.languages); parser.create_data(ltree, function (err, data) { if ( err ) { return dao._complete(err); } dao._data = data; dao._complete(null, data); }); }); }; // get the current document dao.current = function (req_data, options, callback) { dao.tree(options, function (err, tree) { if ( err ) { return callback(err); } var lang = require('./lang'); var ltree = dao._language_tree(tree, req_data.language); var found = null; if ( ltree ) { found = dao._route(ltree, req_data.path_slices); } callback(null, { current : found, tree : ltree || // use the default tree dao._language_tree(tree, options.user.default_language) }); }); }; dao._language_tree = function (tree, language) { language = language || 'default'; tree = tree[language.toLowerCase()]; if ( !tree ) { return null; } return tree.tree; }; dao._route = function (tree, slices) { var slash = '/'; var pathname = slash + slices.join(slash); if ( pathname ) { pathname += slash; } return dao._search_into(tree, pathname); }; dao._search_into = function (node, pathname) { var pages = node.pages; var match; if ( pages ) { pages.some(function (sub_node) { var sub_uri = sub_node.url + '/'; if ( pathname.indexOf(sub_uri) === 0 ) { match = sub_node; return true; } }); } return match && dao._search_into(match, pathname) || match || null; }; dao._complete = function (err, data) { dao._pending = false; dao._queue.forEach(function (callback) { callback(err, data); }); dao._queue.length = 0; };
JavaScript
0.000007
@@ -1131,24 +1131,81 @@ './lang');%0A%0A + // our logic make sure the %60ltree%60 always exists%0A var @@ -1278,38 +1278,171 @@ ound - = null;%0A%0A if ( ltree ) +;%0A var slices = req_data.path_slices;%0A var is_homepage = slices.length === 0;%0A%0A if ( is_homepage ) %7B%0A found = ltree;%0A %7D else %7B%0A @@ -1478,30 +1478,16 @@ (ltree, -req_data.path_ slices); @@ -1543,16 +1543,20 @@ current + : found, @@ -1580,131 +1580,58 @@ -: ltree %7C%7C %0A // use the default tree%0A dao._language_tree(tree, options.user.default_langu + : ltree,%0A is_homepage : is_homep age -) %0A @@ -1965,65 +1965,17 @@ ash) -;%0A%0A if ( pathname ) %7B%0A pathname + -= slash; -%0A %7D %0A%0A
9cb52a2ace65fd16a1d1ef1e51a18cf1f8f3844d
remove .only
src/components/user/services/user.service.v2.integration.test.js
src/components/user/services/user.service.v2.integration.test.js
const chai = require('chai'); const chaiHttp = require('chai-http'); const { ObjectId } = require('mongoose').Types; const appPromise = require('../../../app'); const testObjects = require('../../../../test/services/helpers/testObjects')(appPromise); chai.use(chaiHttp); const { expect } = chai; describe.only('user service v2', function test() { let app; let server; let accountModelService; let usersModelService; before(async () => { app = await appPromise; server = await app.listen(0); accountModelService = app.service('accountModel'); usersModelService = app.service('usersModel'); }); after(async () => { await server.close(); }); const getAdminToken = async (schoolId = undefined) => { const adminUser = await testObjects.createTestUser({ roles: ['administrator'], schoolId }); const credentials = { username: adminUser.email, password: `${Date.now()}` }; await testObjects.createTestAccount(credentials, 'local', adminUser); const token = await testObjects.generateJWT(credentials); return token; }; const getPermissionToken = async (schoolId, permissions = []) => { const currentUserRole = `currentUserPermission`; await testObjects.createTestRole({ name: currentUserRole, permissions, }); const currentUser = await testObjects.createTestUser({ firstName: 'deleteUser', roles: [currentUserRole], schoolId, }); const credentials = { username: currentUser.email, password: `${Date.now()}` }; await testObjects.createTestAccount(credentials, 'local', currentUser); const token = await testObjects.generateJWT(credentials); return token; }; describe('API tests', () => { it('When an admin deletes a student, then it succeeds', async () => { const { _id: schoolId } = await testObjects.createTestSchool(); const user = await testObjects.createTestUser({ roles: ['student'], schoolId }); const token = await getAdminToken(schoolId); const request = chai .request(app) .delete(`/users/v2/admin/student/${user._id.toString()}`) .query({ userId: user._id.toString() }) .set('Accept', 'application/json') .set('Authorization', token) .set('Content-type', 'application/json'); const response = await request.send(); expect(response.status).to.equal(204); }); it('When an admin deletes a teacher, then it succeeds', async () => { const { _id: schoolId } = await testObjects.createTestSchool(); const user = await testObjects.createTestUser({ roles: ['teacher'], schoolId }); const token = await getAdminToken(schoolId); const request = chai .request(app) .delete(`/users/v2/admin/teacher/${user._id.toString()}`) .query({ userId: user._id.toString() }) .set('Accept', 'application/json') .set('Authorization', token) .set('Content-type', 'application/json'); const response = await request.send(); expect(response.status).to.equal(204); }); it('when a teacher deletes a student, then it throws Forbidden', async () => { const { _id: schoolId } = await testObjects.createTestSchool(); // const params = await testObjects.generateRequestParamsFromUser(admin); const teacher = await testObjects.createTestUser({ roles: ['teacher'], schoolId }); const user = await testObjects.createTestUser({ roles: ['student'], schoolId }); const token = await testObjects.generateJWTFromUser(teacher); const request = chai .request(app) .delete(`/users/v2/admin/student/${user._id.toString()}`) .query({ userId: user._id.toString() }) .set('Accept', 'application/json') .set('Authorization', token) .set('Content-type', 'application/json'); const response = await request.send(); expect(response.status).to.equal(403); }); it('when an admin deletes a non-existing user, then it throws Not-Found', async () => { const { _id: schoolId } = await testObjects.createTestSchool(); const notFoundId = ObjectId(); const token = await getAdminToken(schoolId); const request = chai .request(app) .delete(`/users/v2/admin/student/${notFoundId.toString()}`) .query({ userId: notFoundId.toString() }) .set('Accept', 'application/json') .set('Authorization', token) .set('Content-type', 'application/json'); const response = await request.send(); expect(response.status).to.equal(404); }); it('when an admin deletes a student from a different school, then it throws Not-Found', async () => { const { _id: schoolId } = await testObjects.createTestSchool(); const { _id: otherSchoolId } = await testObjects.createTestSchool(); const user = await testObjects.createTestUser({ roles: ['student'], schoolId }); const token = await getAdminToken(otherSchoolId); const request = chai .request(app) .delete(`/users/v2/admin/student/${user._id.toString()}`) .query({ userId: user._id.toString() }) .set('Accept', 'application/json') .set('Authorization', token) .set('Content-type', 'application/json'); const response = await request.send(); expect(response.status).to.equal(403); }); it('when a user with STUDENT_DELETE permission deletes a student, then it succeeds', async () => { const school = await testObjects.createTestSchool({ name: 'testSchool', }); const { _id: schoolId } = school; const token = await getPermissionToken(schoolId, ['STUDENT_DELETE']); const deleteUser = await testObjects.createTestUser({ roles: ['student'], schoolId }); const request = chai .request(app) .delete(`/users/v2/admin/student/${deleteUser._id.toString()}`) .set('Accept', 'application/json') .set('Authorization', token) .set('Content-type', 'application/json'); const response = await request.send(); expect(response.status).to.equal(204); const checkUser = await usersModelService.get(deleteUser._id); expect(checkUser.fullName).to.equal('DELETED USER'); const checkAccount = await accountModelService.find({ query: { userId: deleteUser._id }, paginate: false }); expect(checkAccount.length).to.equal(0); }); it('when a user with STUDENT_DELETE permission deletes a teacher, then it throws Forbidden', async () => { const school = await testObjects.createTestSchool({ name: 'testSchool', }); const { _id: schoolId } = school; const token = await getPermissionToken(schoolId, ['STUDENT_DELETE']); const deleteUser = await testObjects.createTestUser({ roles: ['teacher'], schoolId }); const request = chai .request(app) .delete(`/users/v2/admin/teacher/${deleteUser._id.toString()}`) .set('Accept', 'application/json') .set('Authorization', token) .set('Content-type', 'application/json'); const response = await request.send(); expect(response.status).to.equal(403); }); }); });
JavaScript
0.000001
@@ -303,13 +303,8 @@ ribe -.only ('us
634056ca739ca96cc6e3cad542602797a3808016
work 100% of the time
lib/match.js
lib/match.js
'use strict' const Game = require('./game') const EventEmitter = require('events') const NewEvent = new EventEmitter() const $ = require('jquery') $(document).ready( () => { resetGame(); trueKeys(); falseKeys(); startPlayers(); playGame(); logNames(); nextLevel(); updateRealScores() }) let canvas = document.getElementById('game') let context = canvas.getContext('2d') let game = new Game let currentKeys = {} let start = "no tron" let playerOneName = "" let playerOneScore = 0 let playerTwoName = "" let playerTwoScore = 0 let level = 1 let levelUp = false // let surrenderCount = 0 const drawOne = () => { context.fillStyle = "#FF0000" context.fillRect(game.bikeOne.x, game.bikeOne.y, game.bikeOne.width, game.bikeOne.height) } const drawTwo = () => { context.fillStyle = "#FFFF00" context.fillRect(game.bikeTwo.x, game.bikeTwo.y, game.bikeTwo.width, game.bikeTwo.height) } const playerOneMove = (direction) => { drawOne(); direction game.fillBikeTrailOne } const playerTwoMove = (direction) => { drawTwo(); direction game.fillBikeTrailTwo } const gameDirectionStatus = { 65: () => { playerOneMove(game.bikeOne.moveLeft) }, 87: () => { playerOneMove(game.bikeOne.moveUp) }, 68: () => { playerOneMove(game.bikeOne.moveRight) }, 83: () => { playerOneMove(game.bikeOne.moveDown) }, 74: () => { playerTwoMove(game.bikeTwo.moveLeft) }, 73: () => { playerTwoMove(game.bikeTwo.moveUp) }, 76: () => { playerTwoMove(game.bikeTwo.moveRight) }, 75: () => { playerTwoMove(game.bikeTwo.moveDown) } } const executeTrueKeyFunctions = () => { _.forEach(currentKeys, (n, key) => { if (n) { let gameDirection = gameDirectionStatus[key] if (gameDirection) { gameDirection() } } else if (n === false) { return } }) } const trueKeys = () => { $('#start, #reset').on('keydown', (event) => { if (game.gameStatus !== "alive") { levelUp = false start = "no tron" updatePlayersAndScores() $(`<p>${game.gameStatus}</p>`).appendTo('#player_status') } else if (start === "le tron") { levelUp = true currentKeys[event.keyCode] = true executeTrueKeyFunctions() } event.preventDefault() }) setTimeout(nextLevel, 10000) } const falseKeys = () => { $('#start, #reset').on('keyup', (event) => { currentKeys[event.keyCode] = false updatePlayersAndScores() event.preventDefault() }) } const updatePlayersAndScores = () => { updateRealScores() $('#playerOne').empty() $('#playerOne').append(`<div id="playerOne" style="float: left; width: 170px;">${playerOneName}</div>`) $('#playerOneScore').empty() $('#playerOneScore').append(`${playerOneScore}`) $('#playerTwo').empty() $('#playerTwo').append(`<div id="playerTwo" style="float: left; width: 170px;">${playerTwoName}</div>`) $('#playerTwoScore').empty() $('#playerTwoScore').append(`${playerTwoScore}`) } const updateRealScores = () => { if (start === "le tron") { if (game.gameStatus === "Player One Wins!") { console.log(game.gameStatus); playerOneScore += 1 } else if (game.gameStatus === "Player Two Wins!") { console.log(game.gameStatus); playerTwoScore += 1 } } } const playGame = () => { if (start === "le tron") { executeTrueKeyFunctions() } else if (start === "no tron") { return } } const logNames = () => { let rootUrl = 'http://localhost:8080/'; let fullUrl = window.location.href let p1 = '?playerone='; let p2 = '&playertwo=' $('#start').on('click', (event) => { playerOneName = fullUrl.split(p1).join("").split(p2)[0].replace(rootUrl, '') playerTwoName = fullUrl.split(p1).join("").split(p2)[1].replace(rootUrl, '') }) } const startPlayers = () => { $('#start').on('click', (event) => { start = "le tron" }) } const nextLevel = () => { if(levelUp === true) { console.log(level) level += 0.5 setTimeout(nextLevel, 10000) } else if (levelUp === false) { return } } // const surrender = () => { // surrenderCount += 1 // if(surrenderCount === 50) { // console.log(surrenderCount) // $(`<p>GAME OVER - SOMEONE SURRENDERED</p>`).appendTo('#player_status') // } // console.log(surrenderCount) // setTimeout(surrender, 500) // } const resetGame = () => { $('#reset').on('click', (event) => { game = new Game context.clearRect(0, 0, canvas.width, canvas.height) $('#player_status').children().remove() start = "le tron" updateRealScores() }) }
JavaScript
0.000103
@@ -1894,24 +1894,54 @@ %22alive%22) %7B%0A + updatePlayersAndScores()%0A levelUp @@ -1976,39 +1976,8 @@ on%22%0A - updatePlayersAndScores()%0A%0A @@ -3701,16 +3701,45 @@ rl, '')%0A + updatePlayersAndScores()%0A %7D)%0A%7D%0A%0A @@ -4502,31 +4502,8 @@ on%22%0A - updateRealScores()%0A %7D)
862748ca527e804d6303dd768a951dbb731515e5
update env vars name
bot_modules/trellotasks.js
bot_modules/trellotasks.js
// $ trelloTasks // $ Authors: Zeh // $ Created on: Mon Apr 4 22:04:38 BRT 2016 // - trello card: Me(r2d3) will create your week trello card // Tasks //------------- // Check error // Give some feedback if not find user // Random anwsers when finish the process // Add new checklist mode options var Base = require('../src/base_module'), Trello = require("node-trello"); var t = new Trello( process.env.TRELLO_KEY , process.env.TRELLO_TOKEN); var checkModel = [ "Segunda", "Terça", "Quarta", "Quinta", "Sexta"]; //Global var username; var trelloTasks = function(bot) { Base.call(this, bot); this.respond(/(.*)?trello card(.*)?/i, function(response) { username = response.user.name; response.reply("Só um segundo."); getRightList("SjRJiE2O") .then(function(idList) { return createCard(idList); }) .then(function(idCard) { return createChecklist(idCard); }) .then(function() { response.reply("Feito, amiguinho."); }); }); }; Base.setup(trelloTasks, 'trelloTasks'); module.exports = trelloTasks; //---------------------- //Helper functions //--------------------- function getRightList(boardId) { return new Promise(function(resolve, reject) { t.get(`/1/boards/${boardId}/lists`, function(err, data) { if (err) reject(Error("Network Error: "+err) ); var boardList = data.sort(function(a) { return new Date(a.name.split(" - ")); }); resolve(boardList[0].id); }); }); } function getUserID(username) { return new Promise(function(resolve, reject) { t.get("/1/search/members", { query: username }, function(err, data) { if (err) reject(Error("Network Error: "+err) ); resolve(data[0].id); }); }); } function createCard(idList) { return new Promise(function(resolve, reject) { getUserID(username).then(function(userID) { var newCard = { name: username, idList: idList, idMembers: userID } t.post("1/cards",newCard, function(err, data) { if (err) reject(Error(err) ); resolve(data.id); }); }); }); } function createChecklist(idCard) { return new Promise(function(resolve, reject) { checkModel.forEach(function (value, key) { var newChecklist = { idCard: idCard, name: value, pos: key } t.post("/1/checklists",newChecklist, function(err, data) { if (err) reject(Error(err) ); }); }); resolve(); }); }
JavaScript
0.000001
@@ -407,49 +407,58 @@ env. -TRELLO_KEY , process.env.TRELLO_TOKEN +trellotasks_key , process.env.trellotasks_token );%0A -%0A var
cb06de92c630dce65521f3eef6539fc31f5fe8a4
Add no-irregular-whitespace rule
.eslintrc.js
.eslintrc.js
module.exports = { 'env': { 'browser': true, 'commonjs': true, 'es6': true, 'jasmine': true }, 'extends': [ 'eslint:recommended', 'plugin:flowtype/recommended' ], 'globals': { // The globals that (1) are accessed but not defined within many of our // files, (2) are certainly defined, and (3) we would like to use // without explicitly specifying them (using a comment) inside of our // files. '__filename': false }, 'parser': 'babel-eslint', 'parserOptions': { 'ecmaFeatures': { 'experimentalObjectRestSpread': true }, 'sourceType': 'module' }, 'plugins': [ 'flowtype', // ESLint's rule no-duplicate-imports does not understand Flow's import // type. Fortunately, eslint-plugin-import understands Flow's import // type. 'import' ], 'rules': { 'new-cap': 2, 'no-console': 0, 'semi': [ 'error', 'always' ], 'no-cond-assign': 2, 'no-constant-condition': 2, 'no-control-regex': 2, 'no-debugger': 2, 'no-dupe-args': 2, 'no-duplicate-case': 2, 'no-empty': 2, 'no-empty-character-class': 2, 'no-ex-assign': 2, 'no-extra-boolean-cast': 2, 'no-extra-parens': [ 'error', 'all', { 'nestedBinaryExpressions': false } ], 'no-extra-semi': 2, 'no-func-assign': 2, 'no-inner-declarations': 2, 'no-invalid-regexp': 2, 'prefer-spread': 2, 'require-yield': 2, 'rest-spread-spacing': 2, 'sort-imports': 0, 'template-curly-spacing': 2, 'yield-star-spacing': 2, 'import/no-duplicates': 2 } };
JavaScript
0.000111
@@ -1592,24 +1592,62 @@ -regexp': 2, +%0A 'no-irregular-whitespace': 2, %0A%0A 'p
191abc51b60499e63cd59ff297b0159d47991c1b
Remove dead code (#1295)
lib/mixin.js
lib/mixin.js
'use strict'; var _ = require("lodash"); function mixin(a, b) { if (! a) { a = {}; } if (! b) {b = {}; } a = _.cloneDeep(a); for(var prop in b) { a[prop] = b[prop]; } return a; } module.exports = mixin;
JavaScript
0
@@ -62,51 +62,8 @@ ) %7B%0A -%09if (! a) %7B a = %7B%7D; %7D%0A%09if (! b) %7Bb = %7B%7D; %7D%0A %09a =
d6b76c5ab6d8f4340354ba9eecaccd1dfd4cad4c
fix update users from keeper
src/modules/keeper/controllers/KeeperCtrl.js
src/modules/keeper/controllers/KeeperCtrl.js
(function () { 'use strict'; /** * @param Base * @param $scope * @param {User} user * @return {KeeperCtrl} */ const controller = function (Base, $scope, user) { const signatureAdapter = require('@waves/signature-adapter'); class KeeperCtrl extends Base { /** * @type {boolean} */ isInit = false; /** * @type {boolean} */ noKeeper = false; /** * @type {boolean} */ noKeeperPermission = false; /** * @type {boolean} */ noKeeperAccounts = false; /** * @type {boolean} */ incorrectKeeperNetwork = false; /** * @type {boolean} */ lockedKeeper = false; /** * @type {WavesKeeperAdapter} */ adapter = signatureAdapter.WavesKeeperAdapter; /** * @type {boolean} */ loading = false; /** * @type {boolean} */ error = false; /** * @type {user} */ selectedUser = null; /** * @type {boolean} */ saveUserData = true; /** * @type {string} */ name = ''; constructor() { super($scope); this.getUsers(); } /** * @return {Promise<boolean>} */ isAvilableAdapter() { return this.adapter.isAvailable(); } onError(error) { const { code } = error; switch (code) { case 0: this.noKeeper = true; break; case 1: this.noKeeperPermission = true; break; case 2: this.noKeeperAccounts = true; break; case 3: this.incorrectKeeperNetwork = true; break; case 'locked': this.lockedKeeper = true; break; default: } this.error = true; } /** * @return {void} */ getUsers() { this.loading = true; this.error = false; this.noKeeper = false; this.noKeeperPermission = false; this.noKeeperAccounts = false; this.incorrectKeeperNetwork = false; this.lockedKeeper = false; this.isAvilableAdapter() .then(() => this.adapter.getUserList()) .then(([user]) => { if (!user) { return Promise.reject({ code: 'locked' }); } this.selectedUser = user; delete this.selectedUser.type; }) .catch((e) => this.onError(e)) .finally(() => { this.isInit = true; this.loading = false; $scope.$apply(); }); } /** * @return {void} */ login() { const userSettings = user.getDefaultUserSettings({ termsAccepted: false }); const newUser = { ...this.selectedUser, userType: this.adapter.type, settings: userSettings, saveToStorage: this.saveUserData }; const api = ds.signature.getDefaultSignatureApi(newUser); return user.create({ ...newUser, settings: userSettings.getSettings(), api }, true, true).catch(() => { this.error = true; $scope.$digest(); }); } } return new KeeperCtrl(); }; controller.$inject = ['Base', '$scope', 'user']; angular.module('app.keeper').controller('KeeperCtrl', controller); })();
JavaScript
0
@@ -1547,16 +1547,93 @@ scope);%0A + this.adapter.onUpdate((state) =%3E this.onUpdateState(state));%0A @@ -2607,32 +2607,255 @@ %0A %7D%0A%0A + onUpdateState(data) %7B%0A if (data && data.account && this.selectedUser && this.selectedUser.address !== data.account.address) %7B%0A this.getUsers();%0A %7D%0A %7D%0A%0A /**%0A
53a070e727b5c6b40ed6b5cd12e5a470b201d29f
Change example
example/src/index.js
example/src/index.js
import Graph from 'react-graph-vis' // import Graph from 'react-graph-vis' import React from 'react' import {render} from 'react-dom' let graph = { nodes: [ {id: 1, label: 'Node 1', color: '#e04141'}, {id: 2, label: 'Node 2', color: '#e09c41'}, {id: 3, label: 'Node 3', color: '#e0df41'}, {id: 4, label: 'Node 4', color: '#7be041'}, {id: 5, label: 'Node 5', color: '#41e0c9'} ], edges: [ {from: 1, to: 2}, {from: 1, to: 3}, {from: 2, to: 4}, {from: 2, to: 5} ] }; let options = { layout: { hierarchical: false }, edges: { color: "#000000" } }; let events = { select: function(event) { var { nodes, edges } = event; console.log("Selected nodes:"); console.log(nodes); console.log("Selected edges:"); console.log(edges); } } class ExampleGraph extends React.Component { constructor({initialGraph}) { super(); this.state = { graph: initialGraph }; } clickHandler() { const { graph } = this.state; const nodes = Array.from(graph.nodes); this.counter = this.counter || 5; this.counter++; if (Math.random() > 0.5) { nodes.pop(); this.setState({graph: {...graph, nodes }}); } else { this.setState({ graph: { ...graph, nodes: [ {id: this.counter, label: `Node ${this.counter}`, color: '#41e0c9'}, ...nodes ], edges: [ {from: graph.nodes[Math.floor(Math.random()*graph.nodes.length)].id, to: this.counter}, ...graph.edges ] } }); } } render() { return (<div onClick={this.clickHandler.bind(this)}> <h1>React graph vis</h1> <p><a href="https://github.com/crubier/react-graph-vis">Github</a> - <a href="https://www.npmjs.com/package/react-graph-vis">NPM</a></p> <p><a href="https://github.com/crubier/react-graph-vis/tree/master/example">Source of this page</a></p> <p>A React component to display beautiful network graphs using vis.js</p> <p>Make sure to visit <a href="http://visjs.org">visjs.org</a> for more info.</p> <p>This package allows to render network graphs using vis.js.</p> <p>Rendered graphs are scrollable, zoomable, retina ready, dynamic, and switch layout on double click.</p> <Graph graph={this.state.graph} options={options} events={events} /> </div>); } } render(<ExampleGraph initialGraph={graph}/> , document.getElementById("root"));
JavaScript
0.000001
@@ -872,1078 +872,24 @@ %0A%7D%0A%0A -class ExampleGraph extends React.Component %7B%0A constructor(%7BinitialGraph%7D) %7B%0A super();%0A this.state = %7B%0A graph: initialGraph%0A %7D;%0A %7D%0A clickHandler() %7B%0A const %7B graph %7D = this.state;%0A const nodes = Array.from(graph.nodes);%0A this.counter = this.counter %7C%7C 5;%0A this.counter++;%0A if (Math.random() %3E 0.5) %7B%0A nodes.pop();%0A this.setState(%7Bgraph: %7B...graph, nodes %7D%7D);%0A %7D else %7B%0A this.setState(%7B%0A graph: %7B%0A ...graph,%0A nodes: %5B%0A %7Bid: this.counter, label: %60Node $%7Bthis.counter%7D%60, color: '#41e0c9'%7D,%0A ...nodes%0A %5D,%0A edges: %5B%0A %7Bfrom: graph.nodes%5BMath.floor(Math.random()*graph.nodes.length)%5D.id, to: this.counter%7D,%0A ...graph.edges%0A %5D%0A %7D%0A %7D);%0A %7D%0A %7D%0A render() %7B%0A return (%3Cdiv onClick=%7Bthis.clickHandler.bind(this)%7D%3E%0A +render(%0A %3Cdiv%3E%0A @@ -913,24 +913,16 @@ is%3C/h1%3E%0A - %3Cp%3E%3C @@ -1050,32 +1050,24 @@ NPM%3C/a%3E%3C/p%3E%0A - %3Cp%3E%3Ca hr @@ -1158,32 +1158,24 @@ age%3C/a%3E%3C/p%3E%0A - %3Cp%3EA Rea @@ -1236,32 +1236,24 @@ vis.js%3C/p%3E%0A - %3Cp%3EMake @@ -1322,32 +1322,24 @@ e info.%3C/p%3E%0A - %3Cp%3EThis @@ -1392,32 +1392,24 @@ vis.js.%3C/p%3E%0A - %3Cp%3ERende @@ -1507,24 +1507,17 @@ ck.%3C/p%3E%0A - +%0A %3CGra @@ -1530,19 +1530,8 @@ ph=%7B -this.state. grap @@ -1574,22 +1574,17 @@ /%3E%0A - +%0A %3C/div%3E );%0A @@ -1583,65 +1583,11 @@ div%3E -); +, %0A - %7D%0A%7D%0A%0Arender(%3CExampleGraph initialGraph=%7Bgraph%7D/%3E , doc @@ -1614,11 +1614,12 @@ (%22root%22) +%0A );%0A
499aa57e8781e3c22fce5c0a745dc56785ed89d6
Fix dest vertex not updating edge labels on edge creation
web/war/src/main/webapp/js/data/withSocketHandlers.js
web/war/src/main/webapp/js/data/withSocketHandlers.js
define([], function() { 'use strict'; return withSocketHandlers; function withSocketHandlers() { this.after('initialize', function() { this.on('socketMessage', this.onSocketMessage); }); this.onSocketMessage = function(evt, message) { var self = this, updated = null; switch (message.type) { case 'propertiesChange': // TODO: create edgesUpdated events if (message.data && message.data.vertex && !message.data.vertex.sourceVertexId) { if (self.cachedVertices[message.data.vertex.id]) { updated = self.updateCacheWithVertex(message.data.vertex, { returnNullIfNotChanged: true }); if (updated) { self.trigger('verticesUpdated', { vertices: [updated], options: { originalEvent: message.type } }); } } } else if (message.data && message.data.edge) { var label = message.data.edge.label, vertices = _.compact([ self.cachedVertices[message.data.edge.sourceVertexId], self.cachedVertices[message.data.edge.destVertex] ]); vertices.forEach(function(vertex) { if (!vertex.edgeLabels) { vertex.edgeLabels = []; } if (vertex.edgeLabels.indexOf(label) === -1) { vertex.edgeLabels.push(label); } }); if (vertices.length) { self.trigger('verticesUpdated', { vertices: vertices, options: { originalEvent: message.type } }); } } break; case 'entityImageUpdated': if (message.data && message.data.graphVertexId) { updated = self.updateCacheWithVertex(message.data.vertex, { returnNullIfNotChanged: true }); if (updated) { self.trigger('verticesUpdated', { vertices: [updated] }); self.trigger('iconUpdated', { src: null }); } } else console.warn('entityImageUpdated event received with no graphVertexId', message); break; case 'textUpdated': if (message.data && message.data.graphVertexId) { self.trigger('textUpdated', { vertexId: message.data.graphVertexId }) } else console.warn('textUpdated event received with no graphVertexId', message); break; case 'edgeDeletion': if (_.findWhere(self.selectedEdges, { id: message.data.edgeId })) { self.trigger('selectObjects'); } self.trigger('edgesDeleted', { edgeId: message.data.edgeId}); break; case 'verticesDeleted': if (_.some(self.selectedVertices, function(vertex) { return ~message.data.vertexIds.indexOf(vertex.id); })) { self.trigger('selectObjects'); } self.trigger('verticesDeleted', { vertices: message.data.vertexIds.map(function(vId) { return { id: vId }; }) }); break; } }; } });
JavaScript
0.000001
@@ -1532,16 +1532,18 @@ stVertex +Id %5D%0A
916dfff21ad276d7ae40d4c71558ec3f31b64d3a
Fix test warning
src/tests/structs/unit_DeliveryPipeline.test.js
src/tests/structs/unit_DeliveryPipeline.test.js
const DeliveryPipeline = require('../../structs/DeliveryPipeline.js') const config = require('../../config.js') const DeliveryRecord = require('../../models/DeliveryRecord.js') const ArticleMessage = require('../../structs/ArticleMessage.js') const ArticleRateLimiter = require('../../structs/ArticleMessageRateLimiter.js') jest.mock('../../config.js') jest.mock('../../structs/FeedData.js') jest.mock('../../structs/db/Feed.js') jest.mock('../../structs/ArticleMessageRateLimiter.js') jest.mock('../../structs/ArticleMessage.js') // jest.mock('../../models/DeliveryRecord.js') const Bot = () => ({ shard: { ids: [] } }) const NewArticle = () => ({ feedObject: {}, article: {} }) describe('Unit::structs/DeliveryPipeline', function () { beforeAll(() => { DeliveryRecord.Model = jest.fn() }) afterEach(() => { jest.restoreAllMocks() }) describe('constructor', function () { it('sets the fields', function () { const bot = { foo: 'bar', shard: { ids: [] } } jest.spyOn(config, 'get') .mockReturnValue({ log: { unfiltered: true } }) const pipeline = new DeliveryPipeline(bot) expect(pipeline.bot).toEqual(bot) expect(pipeline.logFiltered).toEqual(true) }) }) describe('getChannel', () => { it('returns the channel', () => { const newArticle = { feedObject: {} } const pipeline = new DeliveryPipeline(Bot()) const get = jest.fn() pipeline.bot = { channels: { cache: { get } } } const channel = { bla: 'dah' } get.mockReturnValue(channel) expect(pipeline.getChannel(newArticle)) .toEqual(channel) }) }) describe('createArticleMessage', () => { it('returns the article message', async () => { const pipeline = new DeliveryPipeline(Bot()) await expect(pipeline.createArticleMessage({})) .resolves.toBeInstanceOf(ArticleMessage) }) }) describe('deliver', () => { beforeEach(() => { jest.spyOn(DeliveryPipeline.prototype, 'getChannel') .mockReturnValue({}) jest.spyOn(DeliveryPipeline.prototype, 'createArticleMessage') .mockResolvedValue() jest.spyOn(DeliveryPipeline.prototype, 'handleArticleBlocked') .mockResolvedValue() jest.spyOn(DeliveryPipeline.prototype, 'sendNewArticle') .mockResolvedValue() jest.spyOn(DeliveryPipeline.prototype, 'handleArticleFailure') .mockResolvedValue() }) it('does not send article if it does not pass filters', async () => { const pipeline = new DeliveryPipeline(Bot()) const sendNewArticle = jest.spyOn(pipeline, 'sendNewArticle') jest.spyOn(pipeline, 'createArticleMessage') .mockResolvedValue({ passedFilters: () => false }) await pipeline.deliver(NewArticle()) expect(sendNewArticle).not.toHaveBeenCalled() }) it('sends the article for delivery', async () => { const pipeline = new DeliveryPipeline(Bot()) const articleMessage = { passedFilters: () => true } const sendNewArticle = jest.spyOn(pipeline, 'sendNewArticle') jest.spyOn(pipeline, 'createArticleMessage') .mockResolvedValue(articleMessage) await pipeline.deliver(NewArticle()) expect(sendNewArticle) .toHaveBeenCalled() }) it('handles errors', async () => { const pipeline = new DeliveryPipeline(Bot()) const articleMessage = { passedFilters: () => true } const error = new Error('deadgf') jest.spyOn(pipeline, 'sendNewArticle') .mockRejectedValue(error) const handleArticleFailure = jest.spyOn(pipeline, 'handleArticleFailure') jest.spyOn(pipeline, 'createArticleMessage') .mockResolvedValue(articleMessage) await pipeline.deliver(NewArticle()) expect(handleArticleFailure) .toHaveBeenCalled() }) }) describe('handleArticleBlocked', () => { beforeEach(() => { config.get.mockReturnValue({ log: { unfiltered: false } }) }) it('records the filter block', async () => { const pipeline = new DeliveryPipeline(Bot()) const recordFilterBlock = jest.spyOn(pipeline, 'recordFilterBlock') const newArticle = NewArticle() await pipeline.handleArticleBlocked(newArticle) expect(recordFilterBlock).toHaveBeenCalledWith(newArticle) }) }) describe('handleArticleFailure', async () => { beforeEach(() => { jest.spyOn(DeliveryPipeline.prototype, 'getChannel') .mockReturnValue({}) }) it('records the failure', async () => { const pipeline = new DeliveryPipeline(Bot()) const recordFailure = jest.spyOn(pipeline, 'recordFailure') const newArticle = NewArticle() await pipeline.handleArticleFailure(newArticle, new Error('atwegq')) expect(recordFailure).toHaveBeenCalledTimes(1) }) it('sends the error if error code 50035', async () => { const pipeline = new DeliveryPipeline(Bot()) const channel = { send: jest.fn() } jest.spyOn(pipeline, 'getChannel') .mockReturnValue(channel) const newArticle = NewArticle() const error = new Error('srfx') error.code = 50035 await pipeline.handleArticleFailure(newArticle, error) expect(channel.send).toHaveBeenCalledTimes(1) }) }) describe('sendNewArticle', () => { it('enqueues the article', async () => { const pipeline = new DeliveryPipeline(Bot()) const newArticle = NewArticle() const articleMessage = { foo: 'baz' } await pipeline.sendNewArticle(newArticle, articleMessage) expect(ArticleRateLimiter.enqueue) .toHaveBeenCalledWith(articleMessage) }) it('records the success', async () => { const pipeline = new DeliveryPipeline(Bot()) const newArticle = NewArticle() const articleMessage = { foo: 'baz' } const recordSuccess = jest.spyOn(pipeline, 'recordSuccess') await pipeline.sendNewArticle(newArticle, articleMessage) expect(recordSuccess) .toHaveBeenCalledWith(newArticle) }) }) describe('record functions', () => { const original = DeliveryRecord.Model const modelSave = jest.fn() beforeEach(() => { DeliveryRecord.Model = jest.fn() .mockReturnValue({ save: modelSave }) modelSave.mockReset() }) afterEach(() => { DeliveryRecord.Model = original }) describe('recordFailure', () => { it('creates and saves the model', async () => { const pipeline = new DeliveryPipeline(Bot()) const newArticle = { article: { _id: 'abc' }, feedObject: { channel: 'abaa' } } const errorMessage = '53e47yu' await pipeline.recordFailure(newArticle, errorMessage) expect(DeliveryRecord.Model).toHaveBeenCalledWith({ articleID: newArticle.article._id, channel: newArticle.feedObject.channel, delivered: false, comment: errorMessage }) expect(modelSave).toHaveBeenCalledTimes(1) }) }) describe('recordSuccess', () => { it('works', async () => { const pipeline = new DeliveryPipeline(Bot()) const newArticle = { article: { _id: 'abc' }, feedObject: { channel: 'abaa' } } await pipeline.recordSuccess(newArticle) expect(DeliveryRecord.Model).toHaveBeenCalledWith({ articleID: newArticle.article._id, channel: newArticle.feedObject.channel, delivered: true }) expect(modelSave).toHaveBeenCalledTimes(1) }) }) describe('recordFilterBlock', () => { it('works', async () => { const pipeline = new DeliveryPipeline(Bot()) const newArticle = { article: { _id: 'abc' }, feedObject: { channel: 'abaa' } } await pipeline.recordFilterBlock(newArticle) expect(DeliveryRecord.Model).toHaveBeenCalledWith({ articleID: newArticle.article._id, channel: newArticle.feedObject.channel, delivered: false, comment: 'Blocked by filters' }) expect(modelSave).toHaveBeenCalledTimes(1) }) }) }) })
JavaScript
0.000002
@@ -4576,38 +4576,32 @@ ArticleFailure', - async () =%3E %7B%0A bef
0dbd623d0be0461c72db7ccc6f85e51695fd3e2c
Prepare for 1.1 release.
src/game/typingmania.js
src/game/typingmania.js
import Viewport from '../graphics/viewport.js' import InputHandler from './input.js' import Sound from '../media/sound.js' import Sfx from '../media/sfx.js' import SongSystem from '../song/songsystem.js' import LoadingController from './controller/1-loading.js' import MenuController from './controller/2-menu.js' import SongLoadController from './controller/3-song-load.js' import SongController from './controller/4-song.js' import ResultController from './controller/5-result.js' import VolumeController from './controller/9-volume.js' import LoadingScreen from '../screen/1-loading.js' import MenuScreen from '../screen/2-menu.js' import SongScreen from '../screen/4-song.js' import ResultScreen from '../screen/5-result.js' import SongInfoScreen from '../screen/8-songinfo.js' import BackgroundScreen from '../screen/9-background.js' export default class TypingMania { constructor (config) { this.config = Object.assign({}, { assets_url: 'assets/assets.dat', songs_url: 'data/songs.json', }, config) this.viewport = new Viewport(1920, 1080) this.input = new InputHandler() this.sound = new Sound() this.sfx = new Sfx(this.sound) this.songs = new SongSystem(this.sound) // Will be set in song-load because they're not global this.typing = null this.score = null this.media = null this.background_screen = new BackgroundScreen(this.viewport, '1.0.1') this.songinfo_screen = new SongInfoScreen(this.viewport) this.loading_screen = new LoadingScreen(this.viewport) this.menu_screen = new MenuScreen(this.viewport) this.song_screen = new SongScreen(this.viewport) this.result_screen = new ResultScreen(this.viewport) this.loading_controller = new LoadingController(this) this.menu_controller = new MenuController(this) this.song_load_controller = new SongLoadController(this) this.song_controller = new SongController(this) this.result_controller = new ResultController(this) this.volume_controller = new VolumeController(this) this.game_mode = 'normal' } reset () { // Reset all song-dependant system this.media.pause() this.media.destroy() this.typing = null this.score = null this.media = null } // Main game/input loop async run () { let runner = this.loading_controller while (true) { runner = await runner.run() if (!runner) { break } } } }
JavaScript
0
@@ -1411,11 +1411,11 @@ '1. -0.1 +1.0 ')%0A
8843d46e5aff802f92ba4003030c310d1968048d
fix gremlin bindings
lib/gds.js
lib/gds.js
// Licensed under the Apache License, Version 2.0 (the 'License'); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an 'AS IS' BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. 'use strict'; // Necessary Dependencies var assert = require('assert'); var _ = require('underscore'); var request = require('request'); var debug = require('debug')('gds-wrapper'); // Global function gds(config) { // Validate config assert.equal(typeof config, 'object', 'You must specify the endpoint url when invoking this module'); assert.ok(/^https?:/.test(config.url), 'url is not valid'); this.config = config; return this; } // Session gds.prototype.session = require('./session'); // Schema gds.prototype.schema = require('./schema'); // Vertices gds.prototype.vertices = require('./vertices'); // Edges gds.prototype.edges = require('./edges'); // IO gds.prototype.io = require('./io'); // Index gds.prototype.index = require('./index'); // Graphs gds.prototype.graphs = require('./graphs'); // Gremlin gds.prototype.gremlin = function (traversal, callback) { var opts = { url: '/gremlin', method: 'POST', json: true, body: { gremlin: '', bindings: '', }, }; // If traveral is string if (_.isObject(traversal)) { // If an Object, map the gremlin query in if (traversal.gremlin) { opts.body.gremlin = traversal.gremlin; } // Add the bindings for said gremlin if (traversal.bindings) { opts.body.bindings = traversal.bindings; } } else if (_.isArray(traversal)) { // If processing an array, stringify opts.body.gremlin = traversal.join('.'); } else { // Straigh pass opts.body.gremlin = traversal; } return this.apiCall(opts, callback); }; // API Call gds.prototype.apiCall = function (opts, callback) { if (!opts) { opts = {}; } var config = this.config; // Auth if (config.session && typeof opts.url.url === 'undefined') { opts.headers = { Authorization: 'gds-token ' + config.session, }; } else { opts.auth = { user: config.username, pass: config.password, }; } // Force the URL if (typeof opts.url === 'object') { opts.url = opts.url.baseURL + opts.url.url; } else if (opts.url.substr(0, 4) !== 'http') { opts.url = config.url + opts.url; } // Debug Opts debug(opts); var _this = this; return request(opts, function (error, response, body) { var returnObject = { error: error, response: response, body: body, }; debug(returnObject); if (!callback) { return returnObject; } // force an error for non-2XX responses if (!error && response && (response.statusCode < 200 || response.statusCode >=300)) { error = response.statusCode; } // Reload Session if (config.session && error === 403) { console.log('Bad session, reload'); _this.session(function (err, body) { _this.config.session = body; _this.apiCall(opts, callback); }); } else { return callback(error, body); } }); }; module.exports = gds;
JavaScript
0.000001
@@ -1569,18 +1569,18 @@ ndings: -'' +%7B%7D ,%0A %7D,
64cd4c5c3324a7b20b6f9cda93770eca0e95c199
support path option in get for debugging purposes
lib/get.js
lib/get.js
var hash = require('./hash') var options = require('./options') module.exports = get function get (db, heads, key, opts, cb) { if (typeof opts === 'function') return get(db, heads, key, null, opts) var req = new GetRequest(db, key, opts) req.start(heads, cb) } function GetRequest (db, key, opts) { this.key = key this.results = [] this._callback = noop this._options = opts || null this._prefixed = !!(opts && opts.prefix) this._path = hash(key, !this._prefixed) this._db = db this._error = null this._active = 0 this._workers = [] } GetRequest.prototype._push = function (node) { if (this._prefixed && isPrefix(node.key, this.key)) { this.results.push(node) } else if (node.key === this.key) { this.results.push(node) } } GetRequest.prototype.start = function (heads, cb) { if (cb) this._callback = cb if (!heads.length) return process.nextTick(finalize, this) this._update(heads, null) } GetRequest.prototype._update = function (nodes, worker) { if (worker) { var r = this._workers.indexOf(worker) if (r > -1) this._workers.splice(r, 1) } this._active += nodes.length for (var i = 0; i < nodes.length; i++) { var next = new Worker(nodes[i], worker ? worker.i + 1 : 0) this._workers.push(next) if (this._isHead(next.lock, next)) this._moveCloser(next) else this._end(next, null, true) } if (worker) { this._end(worker, null) } } GetRequest.prototype._end = function (worker, err, removeWorker) { if (removeWorker) { var i = this._workers.indexOf(worker) if (i > -1) this._workers.splice(i, 1) } if (err) this._error = err if (--this._active) return this._finalize() } GetRequest.prototype._finalize = function () { var error = this._error var cb = this._callback this._error = this._callback = null if (error) cb(error) else cb(null, this._prereturn(this.results)) } GetRequest.prototype._prereturn = function (results) { // TODO: the extra prefixed check should prob be it's own option, ie deletes: true if (allDeletes(results) && !this._prefixed) results = [] var map = options.map(this._options, this._db) var reduce = options.reduce(this._options, this._db) if (map) results = results.map(map) if (reduce) return results.length ? results.reduce(reduce) : null return results } GetRequest.prototype._updatePointers = function (ptrs, worker) { var self = this this._db._getAllPointers(ptrs, false, onnodes) function onnodes (err, nodes) { if (err) return self._end(worker, err, false) self._update(nodes, worker) } } GetRequest.prototype._getAndMoveCloser = function (ptr, worker) { var self = this // TODO: make this optimisation *everywhere* (ie isHead(ptr) vs isHead(node)) // if (!self._isHead(ptr, worker)) return self._end(worker, null) this._db._getPointer(ptr.feed, ptr.seq, false, onnode) function onnode (err, node) { if (err) return self._end(worker, err, false) if (!self._isHead(node, worker)) return self._end(worker, null, true) worker.head = node worker.i++ self._moveCloser(worker) } } GetRequest.prototype._pushPointers = function (ptrs, worker) { var self = this this._db._getAllPointers(ptrs, false, onresults) function onresults (err, nodes) { if (err) return self._end(worker, err, false) for (var i = 0; i < nodes.length; i++) { var node = nodes[i] if (self._isHead(node, worker)) self._push(node) } self._end(worker, null, false) } } GetRequest.prototype._moveCloser = function (worker) { var path = this._path var head = worker.head // If no head -> 404 if (!head) return this._end(worker, null, false) // We want to find the key closest to our path. // At max, we need to go through path.length iterations for (; worker.i < path.length; worker.i++) { var i = worker.i var val = path[i] if (head.path[i] === val) continue // We need a closer node. See if the trie has one that // matches the path value var remoteBucket = head.trie[i] || [] var remoteValues = remoteBucket[val] || [] // No closer ones -> 404 if (!remoteValues.length) return this._end(worker, null, false) // More than one reference -> We have forks. if (remoteValues.length > 1) this._updatePointers(remoteValues, worker) else this._getAndMoveCloser(remoteValues[0], worker) return } this._push(head) // TODO: not sure if this is even needed! // check if we had a collision, or similar // (our last bucket contains more stuff) var top = path.length - 1 var last = head.trie[top] var lastValues = last && last[path[top]] if (!lastValues || !lastValues.length) return this._end(worker, null, false) this._pushPointers(lastValues, worker) } GetRequest.prototype._isHead = function (head, worker) { var clock = head.seq + 1 for (var i = 0; i < this._workers.length; i++) { var otherWorker = this._workers[i] if (otherWorker === worker) continue var otherClock = otherWorker.lock.clock[head.feed] if (clock <= otherClock) return false } return true } function Worker (head, i) { this.i = i this.head = head this.lock = head } function noop () {} function allDeletes (list) { for (var i = 0; i < list.length; i++) { if (list[i].value !== null) return false } return true } function isPrefix (key, prefix) { if (prefix.length && prefix[0] === '/') prefix = prefix.slice(1) return key.slice(0, prefix.length) === prefix } function finalize (req) { req._finalize() }
JavaScript
0
@@ -452,16 +452,29 @@ ._path = + opts.path %7C%7C hash(ke
27209ebff0889c987f37c8d7bc8d2522473629b1
Stop counting png and ico
lib/mstat.js
lib/mstat.js
var fs = require('fs'); var path = require('path'); var gitignoreToGlob = require('gitignore-globs'); var micromatch = require('micromatch'); var readdir = require('recursive-readdir-sync'); var colors = require('colors'); var Analysis = require('./analysis'); function checkFileExists(path) { try { fs.lstatSync(path); } catch (e) { return false; } return true; } function getIgnorePattern(appRoot, gitignorePath) { const defaultIgnore = [ '.git/**', '.*', '**/.*', 'node_modules/**/.*', // https://github.com/sevenweb/gitignore-globs/issues/3 '**/node_modules/**', '.meteor/**', '**/.meteor/**', 'packages/npm-container/**', // For meteorhacks/npm 'packages/npm-container/**/.*', 'packages/npm-container/.**', '**/.DS_Store' ]; var gitignore = path.resolve(appRoot, gitignorePath); if (checkFileExists(gitignore)) { var globs = gitignoreToGlob(gitignore); return defaultIgnore.concat(globs); } else { console.log('Warning: Cannot find .gitignore file:'.yellow.underline); console.log(gitignore); console.log(''); return defaultIgnore; } } module.exports = function (options) { const ignorePattern = getIgnorePattern(options.appRoot, options.gitignorePath); var analysis = new Analysis(); var files = readdir(options.appRoot); files.forEach(function (file) { var stat = fs.lstatSync(file); if (stat.isFile() && ! micromatch.any(file, ignorePattern)) { analysis.addFile(file); } }); return analysis; };
JavaScript
0
@@ -1136,16 +1136,210 @@ %0A %7D%0A%7D%0A%0A +function isCode(filePath) %7B%0A const NON_CODE_PATTERNS = %5B%0A /.+%5C.png$/,%0A /.+%5C.ico$/%0A %5D;%0A%0A return ! NON_CODE_PATTERNS.some(function (pattern) %7B%0A return pattern.test(filePath);%0A %7D);%0A%7D%0A%0A module.e @@ -1656,16 +1656,32 @@ Pattern) + && isCode(file) ) %7B%0A
5a06a1e17f219920853c0562634edd988b7854e5
Remove call to done.
lib/phases/routes.js
lib/phases/routes.js
/** * Module dependencies. */ var scripts = require('scripts') , path = require('path') , fs = require('fs') , existsSync = fs.existsSync || path.existsSync // <=0.6 /** * Route drawing phase. * * This phase will `require` a routes file, allowing the application to draw its * routes. * * This phase is typically the last phase before instructing the server to * listen. Any initializers should be run prior to drawing routes, ensuring * that the application is fully prepared to handle requests. * * Examples: * * app.phase(bootable.routes('routes.js')); * * @param {String|Object} options * @return {Function} * @api public */ module.exports = function(options) { if ('string' == typeof options) { options = { filename: options } } options = options || {}; var filename = options.filename || 'routes' , extensions = options.extensions; return function routes() { var script = scripts.resolve(path.resolve(filename), extensions); if (!existsSync(script)) { return done(); } require(script).call(this); } }
JavaScript
0
@@ -1027,15 +1027,8 @@ turn - done() ; %7D%0A
f4c5a647da2787e41fbab362c1a2ac48add63d60
fix loaders wrong parameter
src/getDefaultConfig.js
src/getDefaultConfig.js
import { join } from 'path'; import webpack from 'webpack'; import ExtractTextPlugin from 'extract-text-webpack-plugin'; let getCommonConfig = { getLoders: function (args) { let name = args.hash ? '[name].[hash:8].[ext]' : '[name].[ext]'; const babelQuery = { presets: ['stage-0', 'es2015', 'react'] }; const loaders = [ { test: /\.js$/, loader: 'babel', query: babelQuery, exclude: /node_modules/ }, { test: /\.json$/, loader: 'json' }, { test: /\.(png|jpg|gif)$/, loader: 'url', query: { limit: 2048, name: `images/${name}` } }, { test: /\.woff$/, loader: 'url', query: { limit: 100, minetype: 'application/font-woff', name: `fonts/${name}` } }, { test: /\.woff2$/, loader: 'url', query: { limit: 100, minetype: 'application/font-woff2', name: `fonts/${name}` } }, { test: /\.ttf$/, loader: 'url', query: { limit: 100, minetype: 'application/octet-stream', name: `fonts/${name}` } }, { test: /\.eot$/, loader: 'url', query: { limit: 100, name: `fonts/${name}` } }, { test: /\.svg$/, loader: 'url', query: { limit: 10000, minetype: 'image/svg+xml', name: `fonts/${name}` } } ]; return loaders.concat(this.getCssLoaders(args)) }, getCssLoaders: function (args) { let cssLoaderLocal = 'css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss?pack=default'; let cssLoaderGlobal = 'css!postcss?pack=default'; let lessLoader = 'css?importLoaders=1!less!postcss?pack=default' if (args.extractCss) { cssLoaderLocal = ExtractTextPlugin.extract('style', cssLoaderLocal); cssLoaderGlobal = ExtractTextPlugin.extract('style', cssLoaderGlobal); lessLoader = ExtractTextPlugin.extract('style', lessLoader); } else { cssLoaderLocal = 'style!' + cssLoaderLocal; cssLoaderGlobal = 'style!' + cssLoaderGlobal; lessLoader = 'style!' + lessLoader; } if (args.cssModules) { return [ { test: /\.css$/, loader: cssLoaderLocal, exclude: /node_modules/ }, { test: /\.css$/, loader: cssLoaderGlobal, include: /node_modules/ }, { test: /\.less$/, loader: lessLoader, include: /node_modules/ } ]; } else { return [ { test: /\.css$/, loader: cssLoaderGlobal }, { test: /\.less$/, loader: lessLoader } ] } }, getPluigns: function (args) { const vendorJsName = args.hash ? 'vendor.[chunkhash:8].js' : 'vendor.js'; const cssName = args.hash ? '[name].[chunkhash:8].js' : '[name].js'; let plugins = [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(args.env) }), new webpack.optimize.OccurrenceOrderPlugin(), new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: vendorJsName, minChunks: Infinity }), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false }, sourceMap: false }) ] if (args.extractCss) { return plugins.concat([ new ExtractTextPlugin(cssName, { allChunks: true }) ]) } } } /** args {Object} * args = { * ... * cwd {String} process.cwd * devtool {String} choost webpack devtool, `false` recommended * publicPath {String} could be a cdn prefix, default `/static/` * hash {Boolean} determine to hash js/css or not, default `true` * extractCss {Boolean} determine to extract css file or not, default `true` * cssModules {Boolean} determine to make css(exclude /node_modules/) modular or not, default `true` * ... * } **/ export default function getDefaultConfig (args) { let pkg = require(join(args.cwd, 'package.json')); const jsName = args.hash ? '[name].[chunkhash:8].js' : '[name].js'; return { devtool: args.devtool || false, entry: pkg.entry, output: { path: join(args.cwd, 'build'), filename: jsName, publicPath: args.publicPath || '/static/' }, module: { loaders: getCommonConfig.getLoders(args) }, resolve: { extensions: ['', '.js'] }, plugins: getCommonConfig.getPluigns(args), postcss: function () { return { default: [ require('autoprefixer')({ browsers: ['last 2 versions'] }) ] } } } }
JavaScript
0.000001
@@ -622,33 +622,33 @@ %7B limit: 100, mi -n +m etype: 'applicat @@ -746,33 +746,33 @@ %7B limit: 100, mi -n +m etype: 'applicat @@ -873,25 +873,25 @@ mit: 100, mi -n +m etype: 'appl @@ -1091,17 +1091,17 @@ 0000, mi -n +m etype: '
895fc60774bd3ac258317a4f9afd2205bc627c52
Simplify PulsarStatus
lib/pulsar/status.js
lib/pulsar/status.js
module.exports = (function () { var PulsarStatus = function (status) { this.status = status || 'CREATED'; } PulsarStatus.STATUS_CREATED = 'CREATED'; PulsarStatus.STATUS_PENDING = 'PENDING'; PulsarStatus.STATUS_RUNNING = 'RUNNING'; PulsarStatus.STATUS_FINISHED = 'FINISHED'; PulsarStatus.STATUS_CANCELLED = 'CANCELLED'; PulsarStatus.STATUS_FAILED = 'FAILED'; PulsarStatus.STATUS_KILLED = 'KILLED'; PulsarStatus.prototype.get = function () { return this.status; } PulsarStatus.prototype.set = function (status) { this.status = status; } PulsarStatus.prototype.isRunning = function () { return this.status == STATUS_PENDING; } return PulsarStatus; })()
JavaScript
0.99994
@@ -99,22 +99,41 @@ %7C%7C -' +PulsarStatus.STATUS_ CREATED -' ;%0A %7D +; %0A%0A @@ -177,51 +177,8 @@ D';%0A - PulsarStatus.STATUS_PENDING = 'PENDING';%0A Pu @@ -265,55 +265,8 @@ D';%0A - PulsarStatus.STATUS_CANCELLED = 'CANCELLED';%0A Pu @@ -408,32 +408,33 @@ this.status;%0A %7D +; %0A%0A PulsarStatus @@ -495,24 +495,25 @@ status;%0A %7D +; %0A%0A PulsarSt @@ -582,28 +582,42 @@ s == - += PulsarStatus. STATUS_ -PEND +RUNN ING;%0A %7D %0A%0A @@ -612,16 +612,17 @@ ING;%0A %7D +; %0A%0A retu @@ -643,9 +643,10 @@ s;%0A%0A - %7D)() +; %0A
b9f8624e7ecaa2b709b4942f4939c7d13da189c7
Disable refresh button when already running
src/plugins/01_software/public/js/controller.js
src/plugins/01_software/public/js/controller.js
angular.module('Software.controllers', ['Software.services']). controller('softwareController', function($scope, $q, $sce, BranchesApiService, softwareApiService, SocketAccess) { var socket = SocketAccess(); $scope.showUpdatesOnly = true; $scope.showOnlyLatest = true; $scope.selectedBranch = undefined; $scope.installResult = ''; $scope.latestVersions = []; $scope.refreshingPackages = false; $scope.aptUpdateRefreshDate = 'unknown'; $scope.aptUpdateStatus = undefined; $scope.loadBranchesError = undefined; $scope.loadPackagesError = undefined; $scope.loadNewpackagesError = undefined; $scope.aptUpdateError = false; $scope.aptUpdateErrorData = undefined socket.on('Software.Update.update', function(data) { $scope.$apply(function() { $scope.aptUpdateStatus = data; }); }); socket.on('Software.Update.done', function(data) { $scope.$apply(function() { console.log( JSON.stringify(data)); $scope.refreshingPackages = data.running; $scope.aptUpdateStatus = data; if (!data.success) { $scope.aptUpdateError = true; var error = "<strong>Output:</strong> <br>" + data.data.join('<br>') + '<br><hr><br><strong>Error: </strong>' + data.error.join('<br>'); $scope.aptUpdateErrorData = $sce.trustAsHtml(error); } }); }); $scope.$watch('aptUpdateStatus', function(newStatus) { if (newStatus) { $scope.aptUpdateRefreshDate = newStatus.lastUpdate ? moment(newStatus.lastUpdate).fromNow() : 'unknown'; } }); BranchesApiService.getBranches().then( function(branches) { $scope.branches = branches; $scope.loadBranchesError = undefined; }, function(reason) { $scope.loadBranchesError = reason; }); softwareApiService.aptUpdateStatus(). then(function(result) { $scope.aptUpdateStatus = result.data; }); $scope.refreshPackages = function() { $scope.refreshingPackages = true; softwareApiService.startAptUpdate().then( function(result) { $scope.aptUpdateStatus = result.data; }, function(reason) { console.log(JSON.stringify(reason)); } ); }; $scope.loadInstalledSoftware = function() { $scope.loadingInstalled = softwareApiService.loadInstalledSoftware(); $scope.loadingInstalled.then( function(items) { $scope.loadPackagesError = undefined; $scope.installedSoftware = items.data; }, function(reason) { $scope.loadPackagesError = reason; }); }; $scope.loadVersions = function() { $scope.latestVersions = []; if ($scope.selectedBranch) { var packageName = 'openrov-*'; if ($scope.showUpdatesOnly) { $scope.loadingPackages = softwareApiService.getUpdates(packageName, $scope.selectedBranch); } else { $scope.loadingPackages = softwareApiService.getAll(packageName, $scope.selectedBranch, $scope.showOnlyLatest); } $scope.loadingPackages .then( function(result) { $scope.loadNewpackagesError = ''; $scope.latestVersions = result.data; }, function(reason) { $scope.loadNewpackagesError = reason; }) } }; $scope.install = function(item) { softwareApiService.install(item.package, item.version, item.branch) .then(function(result) { $scope.installResult = JSON.stringify(result); $scope.loadInstalledSoftware(); $scope.loadVersions(); }) }; $scope.loadInstalledSoftware(); });
JavaScript
0
@@ -1479,24 +1479,106 @@ ewStatus) %7B%0A + $scope.refreshingPackages = newStatus.running? newStatus.running : false;%0A $sco @@ -2143,24 +2143,61 @@ ges = true;%0A + $scope.aptUpdateError = false;%0A softwa
21e97dcb10a5efd5cfa62ce9a176dffd0148166a
fix matchtype.js v2
src/utils/matchesType.js
src/utils/matchesType.js
import isArray from 'lodash/lang/isArray'; import intersection from 'lodash/array/intersection'; export default function matchesType(targetType, draggedItemType) { var draggedItemTypeArr = draggedItemType.split('#'); if (isArray(targetType)) { if (intersection(targetType, draggedItemTypeArr)) { return true; } else { return false; } } else { return draggedItemTypeArr.some(t => t === targetType); } }
JavaScript
0.000004
@@ -293,16 +293,23 @@ TypeArr) + !== %5B%5D ) %7B%0A %09%09
9017a368715117dac37623f23221b1b48b811639
Add axios request to breweryDB through our API endpoint
server/api/breweries/breweryController.js
server/api/breweries/breweryController.js
'use strict'; const axios = require('axios'); // const Post = require('./postModel') const _API_KEY = require('../config/apiKeys.js').breweryDBKey; const _API_ENDPOINT = 'http://api.brewerydb.com/v2/'; exports.get = (req, res, next) => { console.log('brewery get controller'); // Post.find({}) // .then((post) => { // if (post) { // res.json(post) // } else { // console.log('No posts in database') // } // }) } exports.post = (req, res, next) => { console.log('brewery post controller'); // let newPost = new Post({ // title: req.body.title, // text: req.body.text, // author: req.body.author // }) // // newPost.save() // .then((post) => { // if (post) { // res.json(post) // } else { // console.log('Could not save post') // } // }) }
JavaScript
0
@@ -158,16 +158,15 @@ API_ -ENDPOINT +BASEURL = ' @@ -197,16 +197,18 @@ /v2/';%0A%0A +%0A +%0A exports. @@ -239,215 +239,412 @@ %3E %7B%0A +%0A -console.log('brewery get controller');%0A %0A%0A // Post.find(%7B%7D)%0A // .then((post) =%3E %7B%0A // if (post +// breweryDB endpoint%0A var endPoint = 'locations/';%0A%0A // endpoint query options%0A var queryOptions = %7B%0A //locality: 'San Francisco'%0A locality: req.params.location,%0A p: '1'%0A %7D;%0A%0A // axios RESTful API call%0A axios.get(createUrl(endPoint, queryOptions))%0A .then(function (response ) %7B%0A - // - res. -json(post)%0A // %7D else %7B%0A // console.log('No posts in database')%0A // %7D%0A // %7D) +end(JSON.stringify(response.data));%0A %7D)%0A .catch(function (error) %7B%0A console.log(error);%0A %7D);%0A %0A%7D%0A%0A @@ -681,16 +681,19 @@ ) =%3E %7B%0A + // console @@ -729,230 +729,452 @@ ');%0A - // let newPost = new Post(%7B%0A // title: req.body.title,%0A // text: req.body.text,%0A // author: req.body.author%0A // %7D)%0A //%0A // newPost.save()%0A // .then((post) =%3E %7B%0A // if (post) %7B +%0A%7D%0A%0A// Helper formatting function for connecting to breweryDB %0Avar createUrl = function(endPoint, queryOptions) %7B%0A var key = '?key=' + _API_KEY;%0A%0A var queryStrings = %5B%5D;%0A%0A // Create query string from all query options%0A for (let query in queryOptions) %7B%0A if (typeof queryOptions%5Bquery%5D === 'string') %7B%0A // encode spaces for url if query option is string %0A -// - res.json(post)%0A // +queryStrings.push(query + '=' + queryOptions%5Bquery%5D.replace(' ', '+'));%0A %7D @@ -1187,65 +1187,146 @@ %7B%0A -// - console.log('Could not save post')%0A // +queryStrings.push(query + '=' + queryOptions%5Bquery%5D);%0A %7D%0A %7D%0A +%0A -// %7D) +return _API_BASEURL + endPoint + key + '&' + queryStrings.join('&'); %0A%7D%0A
58e81ef2a15cb23f45e15ba141b763760230f2b3
increase plane distance
src/gltf/user_camera.js
src/gltf/user_camera.js
import { vec3 } from 'gl-matrix'; import { gltfCamera } from './camera.js'; import { jsToGl, clamp } from './utils.js'; import { getSceneExtents } from './gltf_utils.js'; const VecZero = vec3.create(); const PanSpeedDenominator = 1200; const MaxNearFarRatio = 10000; class UserCamera extends gltfCamera { constructor( position = [0, 0, 0], target = [0, 0,0], up = [0, 1, 0], xRot = 0, yRot = 0, zoom = 1) { super(); this.position = jsToGl(position); this.target = jsToGl(target); this.up = jsToGl(up); this.xRot = xRot; this.yRot = yRot; this.zoom = zoom; this.zoomFactor = 1.04; this.rotateSpeed = 1 / 180; this.panSpeed = 1; this.sceneExtents = { min: vec3.create(), max: vec3.create() }; } updatePosition() { // calculate direction from focus to camera (assuming camera is at positive z) // yRot rotates *around* x-axis, xRot rotates *around* y-axis const direction = vec3.fromValues(0, 0, 1); this.toLocalRotation(direction); const position = vec3.create(); vec3.scale(position, direction, this.zoom); vec3.add(position, position, this.target); this.position = position; this.fitCameraPlanesToExtents(this.sceneExtents.min, this.sceneExtents.max); } reset(gltf, sceneIndex) { this.xRot = 0; this.yRot = 0; this.fitViewToScene(gltf, sceneIndex, true); } zoomIn(value) { if (value > 0) { this.zoom *= this.zoomFactor; } else { this.zoom /= this.zoomFactor; } } rotate(x, y) { const yMax = Math.PI / 2 - 0.01; this.xRot += (x * this.rotateSpeed); this.yRot += (y * this.rotateSpeed); this.yRot = clamp(this.yRot, -yMax, yMax); } pan(x, y) { const left = vec3.fromValues(-1, 0, 0); this.toLocalRotation(left); vec3.scale(left, left, x * this.panSpeed); const up = vec3.fromValues(0, 1, 0); this.toLocalRotation(up); vec3.scale(up, up, y * this.panSpeed); vec3.add(this.target, this.target, up); vec3.add(this.target, this.target, left); } fitPanSpeedToScene(min, max) { const longestDistance = vec3.distance(min, max); this.panSpeed = longestDistance / PanSpeedDenominator; } fitViewToScene(gltf, sceneIndex) { getSceneExtents(gltf, sceneIndex, this.sceneExtents.min, this.sceneExtents.max); this.fitCameraTargetToExtents(this.sceneExtents.min, this.sceneExtents.max); this.fitZoomToExtents(this.sceneExtents.min, this.sceneExtents.max); this.fitPanSpeedToScene(this.sceneExtents.min, this.sceneExtents.max); this.fitCameraPlanesToExtents(this.sceneExtents.min, this.sceneExtents.max); } toLocalRotation(vector) { vec3.rotateX(vector, vector, VecZero, -this.yRot); vec3.rotateY(vector, vector, VecZero, -this.xRot); } getLookAtTarget() { return this.target; } getPosition() { return this.position; } fitZoomToExtents(min, max) { const maxAxisLength = Math.max(max[0] - min[0], max[1] - min[1]); this.zoom = this.getFittingZoom(maxAxisLength); } fitCameraTargetToExtents(min, max) { for (const i of [0, 1, 2]) { this.target[i] = (max[i] + min[i]) / 2; } } fitCameraPlanesToExtents(min, max) { const longestDistance = vec3.distance(min, max); let zNear = this.zoom - (longestDistance * 0.6); let zFar = this.zoom + (longestDistance * 0.6); // minimum near plane value needs to depend on far plane value to avoid z fighting or too large near planes zNear = Math.max(zNear, zFar / MaxNearFarRatio); this.znear = zNear; this.zfar = zFar; } getFittingZoom(axisLength) { const yfov = this.yfov; const xfov = this.yfov * this.aspectRatio; const yZoom = axisLength / 2 / Math.tan(yfov / 2); const xZoom = axisLength / 2 / Math.tan(xfov / 2); return Math.max(xZoom, yZoom); } } export { UserCamera };
JavaScript
0.000055
@@ -3634,32 +3634,146 @@ min, max)%0A %7B%0A + // Manually increase scene extent just for the camera planes to avoid camera clipping in most situations.%0A const lo @@ -3779,32 +3779,37 @@ ongestDistance = + 10 * vec3.distance(m
dbabdeb5f7f29bafd2dc84a63478c568d37d93a0
Add support for converting arrays
lib/parse.js
lib/parse.js
'use strict'; /** * Attempts to convert object properties recursively to numbers. * @param {Object} obj - Object to iterate over. * @param {Object} options - Options. * @param {Function} options.parser - Parser to process string with. Should return NaN if not a valid number. Defaults to parseInt. * @return {Object} Returns new object with same properties (shallow copy). */ function parseNums(obj, options) { var result = {}, key, value, parsedValue; for (key in obj) { if (obj.hasOwnProperty(key)) { value = obj[key]; parsedValue = options.parser.call(null, value, 10, key); if (typeof value === 'string' && !isNaN(parsedValue)) { result[key] = parsedValue; } else if (value.constructor === Object) { result[key] = parseNums(value, options); } else { result[key] = value; } } } return result; } module.exports = parseNums;
JavaScript
0.000001
@@ -458,16 +458,42 @@ result = + Array.isArray(obj) ? %5B%5D : %7B%7D,%0A @@ -825,16 +825,40 @@ = Object + %7C%7C Array.isArray(value) ) %7B%0A
cb5a32d45ad68df534690024811c46065546bb68
remove unnecessary state
packages/admin/src/components/table/LooTable.js
packages/admin/src/components/table/LooTable.js
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableHead from '@material-ui/core/TableHead'; import { TableFooter } from '@material-ui/core'; const styles = theme => ({ root: { width: '100%', overflowX: 'auto', marginTop: theme.spacing.unit * 3, }, table: { minWidth: 500, }, actionStyles: { flexShrink: 0, color: theme.palette.text.secondary, marginLeft: theme.spacing.unit * 2.5, }, }); class LooTable extends Component { constructor(props) { super(props); this.state = { page: this.props.page, rowsPerPage: this.props.rowsPerPage, }; } componentDidUpdate(prevProps) { const { page: prevPage, rowsPerPage: prevRowsPerPage } = prevProps; const { page, rowsPerPage } = this.props; if (prevPage !== page) { this.setState({ page: page }); } else if (prevRowsPerPage !== rowsPerPage) { this.setState({ rowsPerPage }); } } render() { const { classes, data, colRender, rowRender, footerRender, handleChangePage, handleChangeRowsPerPage, } = this.props; const { page, rowsPerPage } = this.state; return ( <div className={classes.root}> <Table className={classes.table}> <TableHead>{colRender()}</TableHead> <TableBody> {rowRender({ data, })} </TableBody> <TableFooter> {footerRender({ data, rowsPerPage, page, handleChangePage: handleChangePage.bind(this), handleChangeRowsPerPage: handleChangeRowsPerPage.bind(this), })} </TableFooter> </Table> </div> ); } } LooTable.propTypes = { classes: PropTypes.object.isRequired, data: PropTypes.shape({ docs: PropTypes.array.isRequired, }), rowRender: PropTypes.func.isRequired, colRender: PropTypes.func.isRequired, rowsPerPage: PropTypes.number.isRequired, }; LooTable.defaultProps = { footerRender() { return null; }, handleChangePage(event, page) { this.setState({ page }); }, handleChangeRowsPerPage(event) { this.setState({ rowsPerPage: event.target.value }); }, rowsPerPage: 10, page: 0, }; export default withStyles(styles, { withTheme: true })(LooTable);
JavaScript
0.000997
@@ -654,470 +654,8 @@ t %7B%0A - constructor(props) %7B%0A super(props);%0A%0A this.state = %7B%0A page: this.props.page,%0A rowsPerPage: this.props.rowsPerPage,%0A %7D;%0A %7D%0A%0A componentDidUpdate(prevProps) %7B%0A const %7B page: prevPage, rowsPerPage: prevRowsPerPage %7D = prevProps;%0A const %7B page, rowsPerPage %7D = this.props;%0A if (prevPage !== page) %7B%0A this.setState(%7B page: page %7D);%0A %7D else if (prevRowsPerPage !== rowsPerPage) %7B%0A this.setState(%7B rowsPerPage %7D);%0A %7D%0A %7D%0A%0A re @@ -659,24 +659,24 @@ render() %7B%0A + const %7B%0A @@ -752,24 +752,55 @@ oterRender,%0A + rowsPerPage,%0A page,%0A handle @@ -865,54 +865,8 @@ ops; -%0A const %7B page, rowsPerPage %7D = this.state; %0A%0A @@ -1271,35 +1271,24 @@ leChangePage -.bind(this) ,%0A @@ -1343,19 +1343,8 @@ Page -.bind(this) ,%0A @@ -1728,24 +1728,24 @@ rRender() %7B%0A + return n @@ -1758,172 +1758,8 @@ %7D,%0A - handleChangePage(event, page) %7B%0A this.setState(%7B page %7D);%0A %7D,%0A handleChangeRowsPerPage(event) %7B%0A this.setState(%7B rowsPerPage: event.target.value %7D);%0A %7D,%0A ro
fd47fed4ba176eefc1aaeeb7c6834575c4153187
Simplify Button
packages/components/components/button/Button.js
packages/components/components/button/Button.js
import React from 'react'; import PropTypes from 'prop-types'; import keycode from 'keycode'; import Icon from '../icon/Icon'; const Button = ({ type = 'button', role = 'button', loading = false, tabIndex, buttonRef, className = '', children, title, disabled = false, onClick, onKeyDown, onKeyUp, onFocus, onBlur, icon, ...rest }) => { const handleClick = (event) => { if (!disabled && onClick) { onClick(event); } }; const handleKeyDown = (event) => { const key = keycode(event); if (onKeyDown) { onKeyDown(event); } if (event.target === event.currentTarget && (key === 'space' || key === 'enter')) { event.preventDefault(); if (onClick) { onClick(event); } } }; const handleKeyUp = (event) => { if (onKeyUp) { onKeyUp(event); } }; const handleFocus = (event) => { if (disabled) { return; } if (onFocus) { onFocus(event); } }; const handleBlur = (event) => { if (onBlur) { onBlur(event); } }; const iconComponent = typeof icon === 'string' ? <Icon className="flex-item-noshrink" name={icon} /> : icon; const iconButtonClass = !children ? 'pm-button--for-icon' : ''; return ( <button role={role} disabled={loading ? true : disabled} className={`pm-button ${iconButtonClass} ${className}`} type={type} tabIndex={disabled ? '-1' : tabIndex} title={title} ref={buttonRef} onClick={handleClick} onBlur={handleBlur} onFocus={handleFocus} onKeyDown={handleKeyDown} onKeyUp={handleKeyUp} aria-busy={loading} {...rest} > {iconComponent} {children} </button> ); }; Button.propTypes = { loading: PropTypes.bool, role: PropTypes.string, tabIndex: PropTypes.string, title: PropTypes.string, disabled: PropTypes.bool, buttonRef: PropTypes.oneOfType([PropTypes.func, PropTypes.object]), onClick: PropTypes.func, onKeyDown: PropTypes.func, onKeyUp: PropTypes.func, onBlur: PropTypes.func, onFocus: PropTypes.func, type: PropTypes.string, className: PropTypes.string, icon: PropTypes.oneOfType([PropTypes.string, PropTypes.node]), children: PropTypes.node }; export default Button;
JavaScript
0.000004
@@ -60,39 +60,8 @@ s';%0A -import keycode from 'keycode';%0A impo @@ -275,950 +275,33 @@ -onClick,%0A onKeyDown,%0A onKeyUp,%0A onFocus,%0A onBlur,%0A icon,%0A ...rest%0A%7D) =%3E %7B%0A const handleClick = (event) =%3E %7B%0A if (!disabled && onClick) %7B%0A onClick(event);%0A %7D%0A %7D;%0A%0A const handleKeyDown = (event) =%3E %7B%0A const key = keycode(event);%0A%0A if (onKeyDown) %7B%0A onKeyDown(event);%0A %7D%0A%0A if (event.target === event.currentTarget && (key === 'space' %7C%7C key === 'enter')) %7B%0A event.preventDefault();%0A%0A if (onClick) %7B%0A onClick(event);%0A %7D%0A %7D%0A %7D;%0A%0A const handleKeyUp = (event) =%3E %7B%0A if (onKeyUp) %7B%0A onKeyUp(event);%0A %7D%0A %7D;%0A%0A const handleFocus = (event) =%3E %7B%0A if (disabled) %7B%0A return;%0A %7D%0A%0A if (onFocus) %7B%0A onFocus(event);%0A %7D%0A %7D;%0A%0A const handleBlur = (event) =%3E %7B%0A if (onBlur) %7B%0A onBlur(event);%0A %7D%0A %7D;%0A +icon,%0A ...rest%0A%7D) =%3E %7B %0A @@ -781,180 +781,8 @@ ef%7D%0A - onClick=%7BhandleClick%7D%0A onBlur=%7BhandleBlur%7D%0A onFocus=%7BhandleFocus%7D%0A onKeyDown=%7BhandleKeyDown%7D%0A onKeyUp=%7BhandleKeyUp%7D%0A
a69a2973b71a27e0fcc400714e73abebc214dbb5
Update loop module
src/visual-novel.loop.js
src/visual-novel.loop.js
( function( VN ) { /** * Variable: timers * * Hold timers for loop */ VN.prototype.timers = {}; /** * Function: loop * * Repeat the action passed a number of times or infinitely * * @param id = reference to loop so it can cleared later * @param repeat = no of times to repeat or repeat infinitely * @param action = action to perform * @param delay = delay before repeating the action */ VN.prototype.loop = function loop( id, repeat, action, delay ) { // repeat = true : repeat infinitely // repeat = number : repeat number of times // repeat = null/undefined : no repeat, perform action once if ( action ) { var self = this; var timerDelay = delay ? delay : 100; var eventToAdd = function eventToAdd() { // check if loop exists, and clear if it does if ( self.timers[ id ] ) { self.clearLoop( id ); self.timers[ id ] = null; } if ( repeat === true ) { // repeat infinitely self.timers[ id ] = { type : "interval", timer : setInterval( function() { action(); }, timerDelay ) }; } else if ( repeat > 0 ) { // repeat a number of times var repeatTimes = repeat; var repeatTimeout = function() { action(); repeatTimes--; checkRepeat(); }; var checkRepeat = function() { if ( repeatTimes ) { self.timers[ id ].timer = setTimeout( repeatTimeout, timerDelay ); } else { self.timers[ id ].timer = null; } }; self.timers[ id ] = { type : "timeout", timer : null }; checkRepeat(); } else { action(); } }; this.eventTracker.addEvent( "nowait", eventToAdd ); } }; /** * Function: clearLoop * * Clear the loop stored in timers * * @param id = reference to loop timer */ VN.prototype.clearLoop = function clearLoop( id ) { var self = this; function eventToAdd() { self.clearTimer( id ); } this.eventTracker.addEvent( "nowait", eventToAdd ); }; /** * Function: clearTimer * * Clear a timer by checking it in timers * * @param id = reference to the timer */ VN.prototype.clearTimer = function clearTimer( id ) { var timerInfo = this.timers[ id ]; if ( timerInfo ) { if ( timerInfo.type === "timeout" ) { clearTimeout( timerInfo.timer ); } else if ( timerInfo.type === "interval" ) { clearInterval( timerInfo.timer ); } this.timers[ id ] = null; } }; /** * Function: resetLoops * * Reset all loops that have not been cleared * Loops are stored in timers */ VN.prototype.resetLoops = function resetLoops() { var loops = this.timers; var loopType = null; for ( var loopId in loops ) { loopType = loops[ loopId ] ? loops[ loopId ].type : null; if ( loopType && ( loopType === "timeout" || loopType === "interval" ) ) { this.clearTimer( loopId ); } } }; } )( window.VisualNovel = window.VisualNovel || {} );
JavaScript
0.000001
@@ -2942,16 +2942,199 @@ %7D%0A%0A%09%7D;%0A%0A +%09/**%0A%09 * Attach module to namespace%0A%09 */%0A%09VN.prototype.modules.push(%0A%09%09%7B%0A%09%09%09%22init%22: function init( novelId ) %7B%7D,%0A%09%09%09%22reset%22: function reset() %7B%0A%0A%09%09%09%09this.resetLoops();%0A%0A%09%09%09%7D%0A%09%09%7D%0A%09);%0A%0A %7D )( win
2ecb47ba230427f03ec3dcba3f78c04fdd99d354
use Date.now() instead of new Date().getTime() for the performance improvements
lib/ntp.js
lib/ntp.js
var http = Npm.require('http'); var logger = Npm.require('debug')("kadira:ntp"); var Fiber = Npm.require('fibers'); Ntp = function (endpoint) { this.endpoint = endpoint + '/simplentp/sync'; this.diff = 0; this.reSyncCount = 0; this.reSync = new Retry({ baseTimeout: 1000*60, maxTimeout: 1000*60*10, minCount: 0 }); } Ntp.prototype.getTime = function() { return (new Date).getTime() + Math.round(this.diff); }; Ntp.prototype.sync = function() { logger('init sync'); var self = this; var retryCount = 0; var retry = new Retry({ baseTimeout: 1000*20, maxTimeout: 1000*60, minCount: 1 }); syncTime(); function syncTime () { if(retryCount<5) { logger('attempt time sync with server', retryCount); retry.retryLater(retryCount++, getStartTime); } else { logger('maximum retries reached'); self.reSync.retryLater(self.reSyncCount++, self.sync.bind(self)); } } function getStartTime () { new Fiber(function () { HTTP.get(self.endpoint, function (err, res) { if(!err) { getServerTime(); } else { syncTime(); } }); }).run(); } function getServerTime () { new Fiber(function () { var startTime = (new Date).getTime(); HTTP.get(self.endpoint, function (err, res) { var serverTime = parseInt(res.content); if(!err && serverTime) { // ((new Date).getTime() + startTime)/2 : Midpoint between req and res self.diff = serverTime - ((new Date).getTime() + startTime)/2; self.reSync.retryLater(self.reSyncCount++, self.sync.bind(self)); logger('successfully updated diff value', self.diff); } else { syncTime(); } }); }).run(); } }
JavaScript
0.000003
@@ -380,34 +380,24 @@ return -(new Date).getTime +Date.now () + Mat @@ -1241,34 +1241,24 @@ tTime = -(new Date).getTime +Date.now ();%0A @@ -1400,34 +1400,24 @@ // ( -(new Date).getTime +Date.now () + sta @@ -1497,26 +1497,16 @@ - ( -(new Date).getTime +Date.now () +
25964b41c3cf9b7c54f2ba1396d1383e7475a730
Fix new api
packages/components/containers/app/createApi.js
packages/components/containers/app/createApi.js
import { fetchJson } from 'proton-shared/lib/fetch/fetch'; import configureApi from 'proton-shared/lib/api'; export default ({ CLIENT_ID, APP_VERSION, API_VERSION, API_URL }) => (UID) => { return configureApi({ xhr: fetchJson, UID, API_URL, CLIENT_ID, API_VERSION, APP_VERSION }); };
JavaScript
0.000058
@@ -4,21 +4,11 @@ ort -%7B fetchJson %7D +xhr fro @@ -214,19 +214,8 @@ xhr -: fetchJson ,%0A
15fb6a36871a7db8552eb18e2da7aef144373c12
Define the way transitions work
json_api.js
json_api.js
/*jslint indent: 2, nomen: true, maxlen: 100 */ /*global require, applicationContext */ (function () { "use strict"; var FoxxGenerator = require('./foxx_generator').Generator, generator; generator = new FoxxGenerator('example', { mediaType: 'application/vnd.api+json', applicationContext: applicationContext, }); generator.defineTransition('asignee', { description: 'Get the person this object is assigned to', to: 'one', // to: 'many', // action: function() { // Find the person in its repository // }, }); generator.addState('todo', { type: 'entity', attributes: { // Title of the state title: { type: 'string', required: true }, // User ID of the person this is assigned to asignee: { type: 'string' } }, transitions: [ { to: 'person', via: 'asignee' } ] }); generator.addState('person', { type: 'entity', attributes: { name: { type: 'string', required: true } } }); generator.addState('todos', { type: 'repository', transitions: [ { to: 'todo', via: 'element' } ] }); generator.addState('people', { type: 'repository', transitions: [ { to: 'person', via: 'element' } ] }); }());
JavaScript
0.000649
@@ -433,17 +433,16 @@ ed to',%0A -%0A to: @@ -452,108 +452,136 @@ e',%0A - // -to: 'many',%0A%0A // action: function() %7B%0A // Find the person in its repository%0A // %7D, +%7D).inverseTranstion('assigned', %7B%0A // description: 'Get all objects that are assigned to this person',%0A // to: 'many' %0A %7D @@ -1020,16 +1020,84 @@ %7D%0A %7D +,%0A%0A transitions: %5B%0A // %7B to: 'todo', via: 'assigned' %7D%0A %5D %0A %7D);%0A%0A
4ad923e7d39c8a4efa0e61f90a7e446f69e1f5e3
Fix the piezo tone function
lib/piezo.js
lib/piezo.js
var Board = require("../lib/board.js"), events = require("events"), util = require("util"); function Piezo( opts ) { opts = Board.options( opts ); // Hardware instance properties this.board = Board.mount( opts ); this.firmata = this.board.firmata; this.mode = this.firmata.MODES.PWM; this.pin = opts.pin || 3; if ( !Board.Pin.isPWM(this.pin) ) { this.emit( "error", this.pin + "is not a valid PWM pin" ); } // Set the pin to INPUT mode this.firmata.pinMode( this.pin, this.mode ); // Piezo instance properties this.interval = null; this.playing = false; this.queue = []; // TODO: Implement a playback stack } util.inherits( Piezo, events.EventEmitter ); Piezo.prototype.tone = function( tone, duration ) { this.firmata.analogWrite( this.pin, tone ); setTimeout(function() { this.firmata.analogWrite( this.pin, 0 ); }.bind(this), duration ); return this; }; Piezo.prototype.fade = function( fromVol, toVol ) { // TODO: Add speed control toVol = toVol === 0 ? -1 : toVol; var now = fromVol, step = toVol < fromVol ? -1 : 1; this.interval = setInterval(function() { now = now + step; if ( now !== toVol ) { this.firmata.analogWrite( this.pin, now ); } else { // this.firmata.analogWrite( this.pin, 0 ); clearInterval( this.interval ); } }.bind(this), 50 ); return this; }; // Piezo.prototype.alarm = function( pattern ) { // }; // Piezo.prototype.note = function( note, duration ) { // var notes = { // "c": 1915, // "d": 1700, // "e": 1519, // "f": 1432, // "g": 1275, // "a": 1136, // "b": 1014, // "C": 956 // }; // return this; // }; module.exports = Piezo;
JavaScript
0.999829
@@ -704,67 +704,302 @@ );%0A%0A -Piezo.prototype.tone = function( tone, duration ) %7B%0A%0A this +/**%0A * Alternate between high/low pulses count number of times,%0A * changing every duration ms.%0A *%0A * This simulates different tone.%0A *%0A * From https://www.sparkfun.com/products/7950#comment-4eaad84d757b7fd351006efb%0A */%0Afunction pulse( piezo, count, duration ) %7B%0A%0A if ( count %3E 0 ) %7B%0A%0A piezo .fir @@ -1020,27 +1020,28 @@ te( -this +piezo .pin, -tone +255 );%0A -%0A + se @@ -1062,28 +1062,31 @@ ion() %7B%0A -this + piezo .firmata.ana @@ -1087,36 +1087,37 @@ ta.analogWrite( -this +piezo .pin, 0 );%0A %7D.b @@ -1117,30 +1117,332 @@ ;%0A -%7D.bind(this), duration + setTimeout(function() %7B%0A pulse( piezo, --count, duration );%0A %7D, duration);%0A %7D, duration);%0A%0A %7D%0A%0A%7D%0A%0APiezo.prototype.tone = function( tone, duration ) %7B%0A%0A var us = 500000 / tone - 11%0A rep = (duration * 500) / (us + 11),%0A firmata = this.firmata%0A pin = this.pin;%0A%0A pulse( this, rep, us / 1000 );%0A
3b4d08b80600e9203d76be813e3d6e281f69cc52
fix proptype for error
src/routes/ExchangeRates/components/ControlPanel/ControlPanel.js
src/routes/ExchangeRates/components/ControlPanel/ControlPanel.js
import React, { PropTypes } from 'react' import { reduxForm } from 'redux-form' import { connect } from 'react-redux' import './ControlPanel.scss' import { validate, warn } from '../../modules/validation' import { selectors, fetchRates } from '../../modules/exchangeRates' import CurrencyPicker from '../CurrencyPicker' import DatePicker from '../DatePicker' const ControlPanel = ({ handleSubmit, currencies, error }) => ( <form onSubmit={handleSubmit} className='exchange_rates__control_panel'> <div className='row'> <div className='col--4 exchange_rates__label'> <label htmlFor='currency'>Select Base Currency</label> </div> <div className='col--4 exchange_rates__form-field'> <CurrencyPicker name='currency' currencies={currencies} /> </div> </div> <div className='row'> <div className='col--4 exchange_rates__label'> <label htmlFor='date'>Select Date</label> </div> <div className='col--4 exchange_rates__form-field'> <DatePicker name='date' /> </div> </div> <div className='row-center'> <div className='col--4 exchange_rates__form-field'> <button className='button-wide' type='submit'>Request rates</button> </div> </div> { (error) ? ( <div className='error-box'> <span>{error}</span> </div> ) : null } </form> ) ControlPanel.propTypes = { currencies : PropTypes.object.isRequired, handleSubmit: PropTypes.func.isRequired, error : PropTypes.string.isRequired } const mapStateToProps = state => { const currencies = selectors.getCurrencies(state) const baseCurrency = selectors.getBaseCurrency(state) const currencyLabel = `${baseCurrency} - ${currencies[baseCurrency].name}` return { error : selectors.getError(state), currencies : currencies, initialValues: { date : selectors.getSelectedDate(state), currency: currencyLabel } } } const mapDispatchToProps = dispatch => ({ onSubmit: ({ date, currency }) => { const currencyCode = currency.substr(0, 3) dispatch(fetchRates(date, currencyCode)) } }) const form = reduxForm({ form: 'controlPanel', validate, warn }) export default connect(mapStateToProps, mapDispatchToProps)(form(ControlPanel))
JavaScript
0.000001
@@ -1514,25 +1514,65 @@ pes. -string.isRequired +oneOfType(%5B%0A PropTypes.string,%0A PropTypes.bool%0A %5D) %0A%7D%0A%0A
0fb57542e6de23252de745f0fd4640724b8ef995
Fix pip script when using pipenv
lib/pip.js
lib/pip.js
const fse = require('fs-extra'); const path = require('path'); const {spawnSync} = require('child_process'); const {quote} = require('shell-quote'); const values = require('lodash.values'); const {buildImage, getBindPath} = require('./docker'); /** * Install requirements described in requirementsPath to targetPath * @param {string} requirementsPath * @param {string} targetFolder * @param {Object} serverless * @param {string} servicePath * @param {Object} options * @return {undefined} */ function installRequirements(requirementsPath, targetFolder, serverless, servicePath, options) { if (!fse.existsSync(path.join(requirementsPath))) { // No requirements file found return; } // Create target folder if it does not exist const targetRequirementsFolder = path.join(targetFolder, 'requirements'); fse.ensureDirSync(targetRequirementsFolder); const dotSlsReqs = path.join(targetFolder, 'requirements.txt'); let fileName = requirementsPath; if (options.usePipenv && fse.existsSync(path.join(servicePath, 'Pipfile'))) { fileName = dotSlsReqs; } serverless.cli.log(`Installing requirements of ${requirementsPath} in ${targetFolder}...`); // In case the requirements file is a symlink, copy it to targetFolder // if using docker to avoid errors if (options.dockerizePip && fileName !== dotSlsReqs) { fse.copySync(fileName, dotSlsReqs); fileName = dotSlsReqs; } let cmd; let cmdOptions; let pipCmd = [ options.pythonBin, '-m', 'pip', '--isolated', 'install', '-t', targetRequirementsFolder, '-r', fileName, ...options.pipCmdExtraArgs, ]; if (!options.dockerizePip) { // Check if pip has Debian's --system option and set it if so const pipTestRes = spawnSync( options.pythonBin, ['-m', 'pip', 'help', 'install']); if (pipTestRes.error) { if (pipTestRes.error.code === 'ENOENT') { throw new Error( `${options.pythonBin} not found! ` + 'Try the pythonBin option.'); } throw new Error(pipTestRes.error); } if (pipTestRes.stdout.toString().indexOf('--system') >= 0) { pipCmd.push('--system'); } } if (options.dockerizePip) { cmd = 'docker'; // Build docker image if required let dockerImage; if (options.dockerFile) { serverless.cli.log(`Building custom docker image from ${options.dockerFile}...`); dockerImage = buildImage(options.dockerFile); } else { dockerImage = options.dockerImage; } serverless.cli.log(`Docker Image: ${dockerImage}`); // Prepare bind path depending on os platform const bindPath = getBindPath(servicePath); cmdOptions = [ 'run', '--rm', '-v', `${bindPath}:/var/task:z`, ]; if (options.dockerSsh) { // Mount necessary ssh files to work with private repos cmdOptions.push('-v', `${process.env.HOME}/.ssh/id_rsa:/root/.ssh/id_rsa:z`); cmdOptions.push('-v', `${process.env.HOME}/.ssh/known_hosts:/root/.ssh/known_hosts:z`); cmdOptions.push('-v', `${process.env.SSH_AUTH_SOCK}:/tmp/ssh_sock:z`); cmdOptions.push('-e', 'SSH_AUTH_SOCK=/tmp/ssh_sock'); } if (process.platform === 'linux') { // Set the ownership of the .serverless/requirements folder to current user pipCmd = quote(pipCmd); const chownCmd = quote([ 'chown', '-R', `${process.getuid()}:${process.getgid()}`, targetRequirementsFolder, ]); pipCmd = ['/bin/bash', '-c', '"' + pipCmd + ' && ' + chownCmd + '"']; // const stripCmd = quote([ // 'find', targetRequirementsFolder, // '-name', '"*.so"', // '-exec', 'strip', '{}', '\;', // ]); // pipCmd = ['/bin/bash', '-c', '"' + pipCmd + ' && ' + stripCmd + ' && ' + chownCmd + '"']; } cmdOptions.push(dockerImage); cmdOptions.push(...pipCmd); } else { cmd = pipCmd[0]; cmdOptions = pipCmd.slice(1); } const res = spawnSync(cmd, cmdOptions, {cwd: servicePath, shell: true}); if (res.error) { if (res.error.code === 'ENOENT') { if (options.dockerizePip) { throw new Error('docker not found! Please install it.'); } throw new Error(`${options.pythonBin} not found! Try the pythonBin option.`); } throw new Error(res.error); } if (res.status !== 0) { throw new Error(res.stderr); } }; /** * pip install the requirements to the .serverless/requirements directory * @return {undefined} */ function installAllRequirements() { fse.ensureDirSync(path.join(this.servicePath, '.serverless')); if (this.serverless.service.package.individually) { let doneModules = []; values(this.serverless.service.functions) .forEach((f) => { if (!doneModules.includes(f.module)) { installRequirements( `${f.module}/${this.options.fileName}`, `.serverless/${f.module}`, this.serverless, this.servicePath, this.options ); doneModules.push(f.module); } }); } else { installRequirements( this.options.fileName, '.serverless', this.serverless, this.servicePath, this.options ); } }; module.exports = {installAllRequirements};
JavaScript
0.000001
@@ -595,112 +595,8 @@ ) %7B%0A - if (!fse.existsSync(path.join(requirementsPath))) %7B%0A // No requirements file found%0A return;%0A %7D%0A //
3cd72951e241badd47ece38a8715fd31b701bc84
Update web-audio.js
web-audio/web-audio.js
web-audio/web-audio.js
var context; window.addEventListener('load', init, false); function init() { try { var dogBarkingBuffer = null; // Fix up prefixing window.AudioContext = window.AudioContext || window.webkitAudioContext; var context = new AudioContext(); url = 'https://commons.wikimedia.org/wiki/File:Sound-of-dog.ogg'; function loadDogSound(url) { var request = new XMLHttpRequest(); request.open('GET', url, true); request.responseType = 'arraybuffer'; // Decode asynchronously request.onload = function() { context.decodeAudioData( request.response, function(buffer) { dogBarkingBuffer = buffer; }, onError ); } request.send(); alert('Request sent.'); } } catch(e) { alert('Web Audio API is not supported in this browser'); } }
JavaScript
0
@@ -77,16 +77,99 @@ %0A%09try %7B%0A +%09 var dogBarkingUrl = 'https://commons.wikimedia.org/wiki/File:Sound-of-dog.ogg';%0A %09%09var do @@ -289,20 +289,16 @@ text;%0A%09%09 -var context @@ -324,80 +324,176 @@ );%0A%09 -%09 %0A%09%09 -url = 'https://commons.wikimedia.org/wiki/File:Sound-of-dog.ogg';%0A%09%09 +loadDogSound(dogBarkingUrl);%0A%09%09alert('Sound Loaded');%0A%09%09playSound(dogBarkingBuffer);%0A%09%7D%0A%09catch(e) %7B%0A%09%09alert('Web Audio API is not supported in this browser');%0A%09%7D%0A%7D%0A%0A func @@ -517,18 +517,16 @@ (url) %7B%0A -%09%09 %09var req @@ -554,18 +554,16 @@ uest();%0A -%09%09 %09request @@ -587,18 +587,16 @@ true);%0A -%09%09 %09request @@ -631,13 +631,9 @@ ';%0A%09 -%09%09%0A%09%09 +%0A %09// @@ -654,18 +654,16 @@ onously%0A -%09%09 %09request @@ -685,18 +685,16 @@ ion() %7B%0A -%09%09 %09%09contex @@ -712,18 +712,16 @@ ioData(%0A -%09%09 %09%09%09reque @@ -737,18 +737,16 @@ se, %0A%09%09%09 -%09%09 function @@ -756,18 +756,16 @@ ffer) %7B%0A -%09%09 %09%09%09%09dogB @@ -787,18 +787,16 @@ buffer;%0A -%09%09 %09%09%09%7D, %0A%09 @@ -801,18 +801,16 @@ %0A%09%09%09 -%09%09 onError%0A %09%09%09%09 @@ -809,22 +809,16 @@ ror%0A -%09%09 %09%09);%0A -%09%09 %09%7D%0A -%09%09 %09req @@ -834,114 +834,485 @@ ();%0A -%09%09%09alert('Request sent.');%0A%09%09%7D%0A%09%7D%0A%09catch(e) %7B%0A%09%09alert('Web Audio API is not supported in this browser');%0A%09%7D +%7D%0A%0Afunction playSound(buffer) %7B%0A var source = context.createBufferSource(); // creates a sound source%0A source.buffer = buffer; // tell the source which sound to play%0A source.connect(context.destination); // connect the source to the context's destination (the speakers)%0A source.start(0); // play the source now%0A // note: on older systems, may have to use deprecated noteOn(time); %0A%7D%0A
cb100dbbbd1feb5fe1931b484393886a51cee5cc
Add count + avoid to show orga as an assignee
extension/content.js
extension/content.js
let selectedAssignee = ''; function addHeaderOptionsIcon() { const headerButtons = $('div.project-header > div.d-table.mt-1.float-right.f6'); headerButtons.prepend(Handlebars.templates['header-options-icon']()); } function addProjectsOptionsPane() { const panes = $('div.project-pane'); const panesParent = panes.parent(); const isFullscreen = window.location.search.match(/fullscreen=true/); panesParent.append(Handlebars.templates['projects-options-pane']({ isFullscreen })); } function addButtonsEventListeners() { $('button.jgh-projects-options-toggle').on('click', toggleProjectOptionsPane); $('#tgh-projects-assigns-button').on('click', updateAssignsList); } function toggleProjectOptionsPane() { const pane = $('div.project-pane.jgh-projects-options-pane'); if (pane.hasClass('d-none')) { pane.removeClass('d-none'); openPane(); } else { pane.addClass('d-none'); } } function addAssignsFilter() { const headerButtons = $('div.project-header > div.d-table.mt-1.float-right.f6'); headerButtons.prepend(Handlebars.templates['assigns-filter']()); } function updateAssignsList() { const assignsList = $('#tgh-projects-assigns-list'); const assignees = getAssigneesList(); const template = Handlebars.templates['assigns-list']; assignsList.html(template({ assignees })); $('.tgh-projects-assigns-toggle').on('click', toggleAssignee); } function toggleAssignee(e) { const assignee = e ? $(e.currentTarget).find('.select-menu-item-text').text().trim() : ''; const cards = $('.issue-card'); if (selectedAssignee === assignee) { selectedAssignee = ''; } else if (selectedAssignee !== assignee) { selectedAssignee = assignee } cards.each((index, card) => { if (!selectedAssignee) { $(card).show(); } else { const cardAssignees = $(card).find('img.avatar'); if (cardAssignees.length && cardAssignees[0].alt === `@${assignee}`) { $(card).show(); } else { $(card).hide(); } } }); } function getRepositoriesList() { const repositories = new Set(); const cardsDesc = $('.issue-card').find('small'); cardsDesc.each((index, cardDesc) => { const cardText = cardDesc.innerText.trim(); const matchRepo = cardText.match(/.*\/(.*)#\d+ .*/); if (matchRepo && matchRepo.length > 1) { repositories.add(matchRepo[1]); } }); return repositories; } function getLabelsList() { const labels = {}; const labelEls = $('.issue-card-label'); labelEls.each((index, label) => { labels[label.innerText] = label.style.cssText; }); return labels; } function getAssigneesList() { const assignees = []; const assigneesEls = $('img.avatar'); assigneesEls.each((index, assignee) => { const username = assignee.alt.substring(1); const avatar = assignee.src; const isSelected = selectedAssignee === username; assignees.push({ username, avatar, isSelected }); }); return _.sortBy(_.uniqBy(assignees, x => x.username), x => x.username.toLowerCase()); } function openPane() { // Hide repositories const repositories = Array.from(getRepositoriesList()); $('#jgh-projects-options-repolist').html(Handlebars.templates['repositories-checkboxes']({ repositories })); $('.jgh-projects-options-toggle-repo').on('click', toggleRepositoryEvent); // Hide labels const labels = getLabelsList(); $('#jgh-projects-options-labelist').html(Handlebars.templates['labels-checkboxes']({ labels })); $('.jgh-projects-options-toggle-label').on('click', toggleLabelEvent); } function toggleRepositoryEvent(e) { const repo = e.target.id; const checked = e.target.checked; const repoPattern = `.*\\/${repo}#\\d+ .*`; const cards = $('.issue-card'); cards.each((index, card) => { const cardDesc = $(card).find('small')[0]; if (cardDesc.innerText.match(repoPattern)) { if (checked) { $(card).hide(); } else { $(card).show(); } } }); } function toggleLabelEvent(e) { const label = e.target.id; const checked = e.target.checked; const cards = $('.issue-card'); cards.each((index, card) => { const cardLabels = $(card).find('.issue-card-label'); if (cardLabels.length && cardLabels[0].innerText === label) { if (checked) { $(card).hide(); } else { $(card).show(); } } }); } $(document).ready(() => { addHeaderOptionsIcon(); addAssignsFilter(); addProjectsOptionsPane(); addButtonsEventListeners(); });
JavaScript
0
@@ -2659,10 +2659,10 @@ s = -%5B%5D +%7B%7D ;%0A @@ -2685,16 +2685,33 @@ ls = $(' +.project-columns img.avat @@ -2900,16 +2900,20 @@ e;%0A%0A +if ( assignee @@ -2917,24 +2917,97 @@ nees -.push(%7B +%5Busername%5D) %7B%0A assignees%5Busername%5D.count += 1;%0A %7D else %7B%0A assignees%5B username , av @@ -3002,17 +3002,21 @@ username -, +%5D = %7B avatar, @@ -3020,74 +3020,126 @@ ar, -isSelected %7D);%0A %7D);%0A%0A return _.sortBy(_.uniqBy(assignees, x +username, isSelected, count: 1 %7D;%0A %7D%0A %7D);%0A%0A return Object.keys(assignees).map(x =%3E assignees%5Bx%5D).sort((a, b) =%3E -x +a .use @@ -3147,17 +3147,26 @@ name -), x =%3E x +.toLowerCase() %3E b .use
83887be8cf61476c8ddc51870bd45adfb1ab7fb9
Update docs
docs/index.js
docs/index.js
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { Markdown } from 'markdownloader'; import { Header, Navbar, Nav, Row, Col } from 'rsuite'; import Affix from 'rsuite-affix'; import './less/index.less'; import DatePickerDefault from './example/DatePickerDefault'; import DatePickerDisabled from './example/DatePickerDisabled'; import DatePickerCustomToolbar from './example/DatePickerCustomToolbar'; import DatePickerIntl from './example/DatePickerIntl'; import DatePickerValue from './example/DatePickerValue'; class App extends Component { render() { return ( <div className="doc-page"> <Header inverse> <div className="container"> <Navbar.Header> <Navbar.Brand> <a href="#">RSUITE DatePicker</a> </Navbar.Brand> <Navbar.Toggle /> </Navbar.Header> <Navbar.Collapse> <Nav pullRight> <Nav.Item href="https://github.com/rsuite/rsuite-datepicker">GitHub</Nav.Item> </Nav> </Navbar.Collapse> </div> </Header> <div className="container"> <Row> <Col md={2} xsHidden smHidden> <Affix offsetTop={70}> <Nav className="sidebar"> <Nav.Item href="#readme">概述</Nav.Item> <Nav.Item href="#default">示例</Nav.Item> <Nav.Item href="#default">&nbsp;&nbsp;- 默认</Nav.Item> <Nav.Item href="#disabled">&nbsp;&nbsp;- 禁用与隐藏</Nav.Item> <Nav.Item href="#custom-toolbar">&nbsp;&nbsp;- 自定义快捷项</Nav.Item> <Nav.Item href="#locale">&nbsp;&nbsp;- 本地化</Nav.Item> <Nav.Item href="#controlled">&nbsp;&nbsp;- 非受控与受控</Nav.Item> <Nav.Item href="#api">API</Nav.Item> </Nav> </Affix> </Col> <Col md={10}> <hr id="readme" className="target-fix" /> <Markdown> {require('../README.md')} </Markdown> <hr id="default" className="target-fix" /> <h2>示例</h2> <h3>默认</h3> <DatePickerDefault /> <Markdown> {require('./md/DatePickerDefault.md')} </Markdown> <hr id="disabled" className="target-fix" /> <h3>禁用与隐藏</h3> <DatePickerDisabled /> <Markdown> {require('./md/DatePickerDisabled.md')} </Markdown> <hr id="custom-toolbar" className="target-fix" /> <h3>自定义快捷项</h3> <DatePickerCustomToolbar /> <Markdown> {require('./md/DatePickerCustomToolbar.md')} </Markdown> <hr id="locale" className="target-fix" /> <h3>本地化</h3> <DatePickerIntl /> <Markdown> {require('./md/DatePickerIntl.md')} </Markdown> <hr id="locale" className="target-fix" /> <h3>非受控与受控</h3> <DatePickerValue /> <Markdown> {require('./md/DatePickerValue.md')} </Markdown> <h3>属性</h3> <Markdown> {require('./md/props.md')} </Markdown> </Col> </Row> </div> </div> ); } } ReactDOM.render(<App />, document.getElementById('app') );
JavaScript
0.000001
@@ -3069,38 +3069,42 @@ %3Chr id=%22 -loca +control le +d %22 className=%22tar @@ -3276,32 +3276,85 @@ %3C/Markdown%3E%0A%0A + %3Chr id=%22api%22 className=%22target-fix%22 /%3E%0A %3Ch
8c63a529370e84a0fba6478c9f08165db97cfc3d
Load date input component (task #8668)
resources/src/components/fh/index.js
resources/src/components/fh/index.js
import blobInput from './Text' import booleanInput from './Boolean' import countryInput from './List' import currencyInput from './List' import datetimeInput from './Datetime' import decimalInput from './Decimal' import dblistInput from './List' import emailInput from './Email' import integerInput from './Integer' import listInput from './List' import phoneInput from './Phone' import relatedInput from './Related' import reminderInput from './Datetime' import stringInput from './Text' import sublistInput from './List' import textInput from './Text' import timeInput from './Time' import urlInput from './Url' export default { blobInput, booleanInput, countryInput, currencyInput, datetimeInput, decimalInput, dblistInput, emailInput, integerInput, listInput, phoneInput, relatedInput, reminderInput, stringInput, sublistInput, textInput, timeInput, urlInput }
JavaScript
0
@@ -126,24 +126,55 @@ om './List'%0A +import dateInput from './Date'%0A import datet @@ -722,24 +722,39 @@ rencyInput,%0A + dateInput,%0A datetime
290722d69aa3014862237ce7ac2739cdaaba7b50
Add Query.offset for easier app level paging.
lib/query.js
lib/query.js
"use strict"; // self.table('tableAlias') // .query('primaryKeyValue', 'optionalRangeValue') // .fetch(done); // // this.query('edit', id) // .fetch(done); // this.query('edit', id) // .remove(done); // this.put('edit', id, range) // .set({}) // this.query('edit', id) // .update() // .set() // .commit(done); // this.batch() // .add('edit'); var UpdateQuery = require('./update-query'), debug = require('plog')('mambo:query'); function Query(model, alias, hash, range){ if(!model.schema(alias).range){ throw new TypeError('Query only for hash/range tables. Should call Model.get.'); } this.model = model; this.alias = alias; this.hash = hash; this.range = range; this.fieldNames = null; this.consistentRead = false; this._limit = -1; this._count = false; this.scanForward = true; this.startKey = null; this.filter = {}; this.useIndex = null; } // @todo (lucas) Add where to implement range key conditions. Query.prototype.start = function(hash, range){ this.startKey = [hash, range]; return this; }; Query.prototype.count = function(){ this._count = true; return this; }; Query.prototype.limit = function(l){ this._limit = l; return this; }; Query.prototype.consistent = function(){ this.consistentRead = true; return this; }; Query.prototype.reverse = function(){ this.scanForward = false; return this; }; Query.prototype.fields = function(fieldNames){ this.fieldNames = fieldNames; return this; }; Query.prototype.update = function(){ return new UpdateQuery(this.model, this.alias, this.hash, this.range); }; // Use a secondary index. Query.prototype.index = function(name){ this.useIndex = name; return this; }; Query.prototype.fetch = function(done){ var opts = {}, schema = this.model.schema(this.alias); if(this._limit > -1){ opts.limit = this._limit; } if(this.consistentRead){ opts.consistentRead = this.consistentRead; } if(!this.scanForward){ opts.scanIndexForward = this.scanForward; } if(this.fieldNames){ opts.attributesToGet = this.fieldNames; } if(this.useIndex){ opts.index = this.useIndex; } if(this._count){ opts.count = true; } if(this.filter){ Object.keys(this.filter).forEach(function(key){ var f = new Filter(schema, key, this.filter[key]); opts.rangeKeyCondition = f.export(); }.bind(this)); } debug('Calling query for `' + this.alias + '`'); this.model.query(this.alias, this.hash, opts, done); }; // module.exports.query('song') // // .where('id', 'IN', [1, 2, 3]) // // .where('loves', '<', 1) // // .where('trending', '=', null) // // .where('title', '!=', null) // // .where('bio', 'NULL') // // .where('location', 'NOT_NULL') // // .where('started', 'BETWEEN', [1990, 1992]) // // .fetch(done); Query.prototype.where = function(key, operator, value){ operator = expandOperator(operator) || operator; var f = {}; f[operator] = value; this.filter[key] = f; return this; }; function expandOperator(op){ switch(op){ case '>': return 'GT'; case '>=': return 'GE'; case '<': return 'LT'; case '<=': return 'LE'; case '!=': return 'NE'; case '=' || '==' || '===': return 'EQ'; default: return undefined; } } var opToArgLength = { 'EQ': 1, 'NE': 1, 'LE': 1, 'LT': 1, 'GE': 1, 'GT': 1, 'NOT_NULL': 0, 'NULL': 0, 'CONTAINS': 1, 'NOT_CONTAINS': 1, 'BEGINS_WITH': 1, 'IN': null, 'BETWEEN': 2 }; function Filter(schema, key, data){ this.schema = schema; this.field = schema.field(key); this.operator = undefined; this.value = []; if(data === new Object(data)){ this.operator = Object.keys(data)[0]; this.value = data[this.operator]; if(!Array.isArray(this.value)){ this.value = [this.value]; } } else { this.operator = data; // @todo (lucas) Assert its actually a valueles condition. } var expectLen = opToArgLength[this.operator]; if(expectLen !== null && this.value.length !== expectLen){ throw new Error('Invalid number of args for ' + key + ' filter: ' +this.operator + ' ' + this.value); } } Filter.prototype.export = function(){ var ret = { 'AttributeValueList': [], 'ComparisonOperator': 'EQ' }; if(this.value){ ret.AttributeValueList = this.value.map(function(val){ var ret = {}; ret[this.field.shortType] = this.field.export(val); return ret; }.bind(this)); } if(this.operator){ ret.ComparisonOperator = this.operator; } return ret; }; module.exports = Query;
JavaScript
0
@@ -948,16 +948,38 @@ = null;%0A + this._offset = 0;%0A %7D%0A%0A// @t @@ -1275,16 +1275,112 @@ imit = l + + this._offset;%0A return this;%0A%7D;%0A%0AQuery.prototype.offset = function(o)%7B%0A this._offset = o ;%0A re @@ -1967,16 +1967,37 @@ s = %7B%7D,%0A + self = this,%0A @@ -2063,16 +2063,53 @@ %3E -1)%7B%0A + this._limit += this._offset;%0A @@ -2836,20 +2836,317 @@ , opts, -done +function(err, items)%7B%0A if(err) return done(err);%0A%0A // If there is a user supplied offset, pre-slice down the items%0A // to what the user actually wants.%0A if(self._offset)%7B%0A items = items.slice(self._offset, self._limit);%0A %7D%0A done(null, items);%0A %7D );%0A%7D;%0A%0A/
9472983845a17d4006eaf243681f2654e8592104
missing semicolon
lib/query.js
lib/query.js
'use strict'; var traverse = require('traverse'); var ObjectID = require('mongodb').ObjectID; var TWO_DAYS = 172800000; function default_options (opts) { opts = opts || { }; if (opts) { var keys = [null].concat(Object.keys(opts)); // if (keys.indexOf('laxDate') < 1) { opts.laxDate = false; } if (keys.indexOf('deltaAgo') < 1) { opts.deltaAgo = ( TWO_DAYS * 2 ); } if (keys.indexOf('walker') < 1) { opts.walker = { date: parseInt, sgv: parseInt }; } } return opts; } function create (params, opts) { opts = default_options(opts); var finder = walker(opts.walker)(params); var query = finder && finder.find ? finder.find : { }; if (!query.date && !query.dateString) { // if (!laxDate) { } query.date = { $gte: Date.now( ) - opts.deltaAgo }; } if (query._id && query._id.length) { query._id = ObjectID(query._id); } return query; } function walker (spec) { var fns = [ ]; var keys = Object.keys(spec); keys.forEach(function config (prop) { var typer = spec[prop]; fns.push(walk_prop(prop, typer)); }); function exec (obj) { var fn; while (fn = fns.shift( )) { obj = fn(obj); } return obj; } return exec } function walk_prop (prop, typer) { function iter (opts) { if (opts && opts.find && opts.find[prop]) { traverse(opts.find[prop]).forEach(function (x) { if (this.isLeaf) { this.update(typer(x)); } }); } return opts; } return iter; } walker.walk_prop = walk_prop; create.walker = walker; create.default_options = default_options; exports = module.exports = create;
JavaScript
0.999988
@@ -1215,16 +1215,17 @@ urn exec +; %0A%7D%0A%0Afunc
e809ee4c4d479bd96e9ca8ff14390b3b95cdb9fe
fix responsive tool docs
pages/docs/responsive-tool.js
pages/docs/responsive-tool.js
import React from 'react'; import withDocs from '../../site/withDocs'; const ResponsiveTool = ({ compile }) => { return ( <div> {compile(` # Responsive Tool Arwes has some utilities to handle responsive functionalities. You can use the \`createResponsive\` module and create your tool. \`\`\`javascript import { createTheme, createResponsive } from 'arwes'; const myTheme = createTheme(); const responsive = createResponsive({ getTheme: () => myTheme }); // To know in what breakpoint the viewport is at: const state = responsive.get(); // \`{ medium: true, status: 'medium' }\` // if device is on medium breakpoint, for example. // To listen for viewport changes: const listener = responsive.on(state => console.log(state)); // To turn it off: responsive.off(listener); \`\`\` You need to provide the [Design System](/docs/design-system) theme for it to know about the breakpoints. In a component you can use it the same way: \`\`\`javascript import React from 'react'; import ReactDOM from 'react-dom'; import { ThemeProvider, createTheme, withStyles, createResponsive } from 'arwes'; class MyComponentClass extends React.Component { constructor () { super(...arguments); this.responsive = createResponsive({ getTheme: () => this.props.theme }); } render () { const { status } = this.responsive.get(); return <div>Responsive status: {status}</div>; } } const MyComponent = withStyles()(MyComponentClass); const App = () => ( <ThemeProvider theme={createTheme()}> <MyComponent /> </ThemeProvider> ); ReactDOM.render(<App />, document.querySelector('#root')); \`\`\` So the component can render \`Responsive status: large\` when viewport is in breakpoint large when it is mounted. `).tree} </div> ); } export default withDocs(ResponsiveTool);
JavaScript
0
@@ -661,23 +661,25 @@ ten for -viewpor +breakpoin t change
f9bf1483349b03a393e5ece209b16d477da94049
move custom static middleware to top of stack
lib/tty.js
lib/tty.js
/** * tty.js * Copyright (c) 2012, Christopher Jeffrey (MIT License) */ process.title = 'tty.js'; /** * Modules */ var path = require('path') , fs = require('fs') , EventEmitter = require('events').EventEmitter; var express = require('express') , io = require('socket.io') , pty = require('pty.js'); /** * Config */ var conf = require('./config'); /** * Auth */ var auth = basicAuth(); /** * App & Middleware */ var app = conf.https && conf.https.key && !conf.https.disabled ? express.createServer(conf.https) : express.createServer(); app.use(function(req, res, next) { var setHeader = res.setHeader; res.setHeader = function(name) { switch (name) { case 'Cache-Control': case 'Last-Modified': case 'ETag': return; } return setHeader.apply(res, arguments); }; next(); }); app.use(auth); app.use(express.favicon(__dirname + '/../static/favicon.ico')); app.use(app.router); if (conf.static) { app.use(express.static(conf.static)); } app.use(express.static(__dirname + '/../static')); /** * Stylesheets */ app.get('/style.css', function(req, res, next) { res.contentType('.css'); res.sendfile(conf.stylesheet); }); app.get('/user.css', function(req, res, next) { res.contentType('.css'); return conf.userStylesheet ? res.sendfile(conf.userStylesheet) : res.send('\n'); }); /** * Expose Terminal Options */ app.get('/options.js', function(req, res, next) { res.contentType('.js'); fs.readFile(conf.json, 'utf8', function(err, data) { try { data = JSON.parse(data) || {}; } catch(e) { data = {}; } res.send('Terminal.options = ' + JSON.stringify(data.term || {}) + ';\n' + '(' + applyConfig + ')();'); }); }); function applyConfig() { for (var key in Terminal.options) { if (Object.prototype.hasOwnProperty.call(Terminal.options, key)) { Terminal[key] = Terminal.options[key]; } } delete Terminal.options; } /** * Sockets */ var io = io.listen(app) , state = {}; io.configure(function() { io.disable('log'); }); io.set('authorization', function(data, next) { data.__proto__ = EventEmitter.prototype; auth(data, null, function(err) { data.user = data.remoteUser || data.user; return !err ? next(null, true) : next(err); }); }); io.sockets.on('connection', function(socket) { var req = socket.handshake , terms = {} , uid = 0; // Kill older session. if (conf.sessions && conf.users) { if (state[req.user]) { try { state[req.user].disconnect(); } catch (e) { ; } } state[req.user] = socket; } socket.on('create', function(cols, rows, func) { var id = uid++ , len = Object.keys(terms).length , term; if (len >= conf.limitPerUser || pty.total >= conf.limitGlobal) { return func('Terminal limit.'); } term = pty.fork(conf.shell, conf.shellArgs, { name: conf.termName, cols: cols, rows: rows, cwd: conf.cwd || process.env.HOME }); terms[id] = term; term.on('data', function(data) { socket.emit('data', id, data); }); term.on('close', function() { // make sure it closes // on the clientside socket.emit('kill', id); // ensure removal if (terms[id]) delete terms[id]; console.log( 'Closed pty (%s): %d.', term.pty, term.fd); }); console.log('' + 'Created shell with pty (%s) master/slave' + ' pair (master: %d, pid: %d)', term.pty, term.fd, term.pid); return func(null, { pty: term.pty, process: sanitize(conf.shell) }); }); socket.on('data', function(id, data) { if (!terms[id]) { console.error('' + 'Warning: Client attempting to' + ' write to a non-existent terminal.' + ' (id: %s)', id); return; } terms[id].write(data); }); socket.on('kill', function(id) { if (!terms[id]) return; terms[id].destroy(); delete terms[id]; }); socket.on('resize', function(id, cols, rows) { if (!terms[id]) return; terms[id].resize(cols, rows); }); socket.on('process', function(id, func) { if (!terms[id]) return; var name = terms[id].process; return func(null, sanitize(name)); }); socket.on('disconnect', function() { var key = Object.keys(terms) , i = key.length , term; while (i--) { term = terms[key[i]]; term.destroy(); } if (state[req.user]) delete state[req.user]; console.log('Client disconnected. Killing all pty\'s...'); }); }); /** * Listen */ app.listen(conf.port || 8080, conf.hostname); /** * Basic Auth */ function basicAuth() { if (!conf.users) { return function(req, res, next) { next(); }; } if (conf.hooks.auth) { return express.basicAuth(conf.hooks.auth); } var crypto = require('crypto') , saidWarning; var sha1 = function(text) { return crypto .createHash('sha1') .update(text) .digest('hex'); }; var hashed = function(hash) { if (!hash) return; return hash.length === 40 && !/[^a-f0-9]/.test(hash); }; var verify = function(user, pass, next) { var user = sha1(user) , password; if (!Object.hasOwnProperty.call(conf.users, user)) { return next(); } password = conf.users[user]; next(null, sha1(pass) === password); }; // Hash everything for consistency. Object.keys(conf.users).forEach(function(name) { if (!saidWarning && !hashed(conf.users[name])) { console.log('Warning: You should sha1 your usernames/passwords.'); saidWarning = true; } var username = !hashed(name) ? sha1(name) : name; conf.users[username] = !hashed(conf.users[name]) ? sha1(conf.users[name]) : conf.users[name]; if (username !== name) delete conf.users[name]; }); return express.basicAuth(verify); } function sanitize(file) { if (!file) return ''; file = file.split(' ')[0] || ''; return path.basename(file) || ''; }
JavaScript
0
@@ -859,24 +859,86 @@ use(auth);%0A%0A +if (conf.static) %7B%0A app.use(express.static(conf.static));%0A%7D%0A%0A app.use(expr @@ -1016,70 +1016,8 @@ );%0A%0A -if (conf.static) %7B%0A app.use(express.static(conf.static));%0A%7D%0A%0A app.
7b58b32312075e28abcf507893b2dab489f29a39
Move setting headers to a separate method
lib/reply.js
lib/reply.js
/* eslint-disable no-useless-return */ 'use strict' const pump = require('pump') const safeStringify = require('fast-safe-stringify') const xtend = require('xtend') const validation = require('./validation') const serialize = validation.serialize const statusCodes = require('./status-codes.json') const stringify = JSON.stringify function Reply (req, res, handle) { this.res = res this.handle = handle this._req = req this.sent = false this._serializer = null // this._extendServerError = () => {} } /** * Instead of using directly res.end(), we are using setImmediate(…) * This because we have observed that with this technique we are faster at responding to the various requests, * since the setImmediate forwards the res.end at the end of the poll phase of libuv in the event loop. * So we can gather multiple requests and then handle all the replies in a different moment, * causing a general improvement of performances, ~+10%. */ Reply.prototype.send = function (payload) { if (this.sent) { throw new Error('Reply already sent') } if (!payload) { if (!this.res.statusCode) { this.res.statusCode = 204 } this.res.setHeader('Content-Length', '0') setImmediate(wrapReplyEnd, this, '') return } if (payload && payload.isBoom) { this._req.log.error(payload) this.res.statusCode = payload.output.statusCode for (var k in payload.output.headers) { this.header(k, payload.output.headers[k]) } setImmediate( wrapReplyEnd, this, safeStringify(payload.output.payload) ) return } if (payload instanceof Error) { if (!this.res.statusCode || this.res.statusCode < 400) { this.res.statusCode = 500 } this._req.log.error(payload) setImmediate( wrapReplyEnd, this, stringify(xtend({ error: statusCodes[this.res.statusCode + ''], message: payload.message, statusCode: this.res.statusCode }, this._extendServerError && this._extendServerError())) ) return } if (typeof payload.then === 'function') { return payload.then(wrapReplySend(this)).catch(wrapReplySend(this)) } if (payload._readableState) { if (!this.res.getHeader('Content-Type')) { this.res.setHeader('Content-Type', 'application/octet-stream') } return pump(payload, this.res, wrapPumpCallback(this)) } if (!this.res.getHeader('Content-Type') || this.res.getHeader('Content-Type') === 'application/json') { this.res.setHeader('Content-Type', 'application/json') // Here we are assuming that the custom serializer is a json serializer const str = this._serializer ? this._serializer(payload) : serialize(this.handle, payload) if (!this.res.getHeader('Content-Length')) { this.res.setHeader('Content-Length', Buffer.byteLength(str)) } setImmediate(wrapReplyEnd, this, str) return } // All the code below must have a 'content-type' setted if (this._serializer) { setImmediate(wrapReplyEnd, this, this._serializer(payload)) return } setImmediate(wrapReplyEnd, this, payload) return } Reply.prototype.header = function (key, value) { this.res.setHeader(key, value) return this } Reply.prototype.code = function (code) { this.res.statusCode = code return this } Reply.prototype.serializer = function (fn) { this._serializer = fn return this } function wrapPumpCallback (reply) { return function pumpCallback (err) { if (err) { reply._req.log.error(err) setImmediate(wrapReplyEnd, reply) } } } function wrapReplyEnd (reply, payload) { reply.sent = true reply.res.end(payload) } function wrapReplySend (reply, payload) { return function send (payload) { return reply.send(payload) } } function buildReply (R) { function _Reply (req, res, handle) { this.res = res this.handle = handle this._req = req this.sent = false this._serializer = null } _Reply.prototype = new R() return _Reply } module.exports = Reply module.exports.buildReply = buildReply
JavaScript
0.000001
@@ -1378,54 +1378,8 @@ de%0A%0A - for (var k in payload.output.headers) %7B%0A @@ -1393,12 +1393,10 @@ ader +s ( -k, payl @@ -1417,18 +1417,9 @@ ders -%5Bk%5D)%0A %7D +) %0A%0A @@ -3154,32 +3154,205 @@ return this%0A%7D%0A%0A +Reply.prototype.headers = function (headers) %7B%0A var keys = Object.keys(headers)%0A for (var i = 0; i %3C keys.length; i++) %7B%0A this.header(keys%5Bi%5D, headers%5Bkeys%5Bi%5D%5D)%0A %7D%0A%7D%0A%0A Reply.prototype.
50f865510c5ef9d73486e4ac63e898c39ef8c8d5
Use camel case
lib/uri.js
lib/uri.js
'use strict'; const path = require('path'); const url = require('url'); module.exports = function normalizeURI (uri) { if (typeof uri === 'string') uri = url.parse(uri, true); if (uri.hostname === '.' || uri.hostname === '..') { uri.pathname = uri.hostname + uri.pathname; delete uri.hostname; delete uri.host; } if (typeof uri.pathname !== 'undefined') uri.pathname = path.resolve(uri.pathname); uri.query = uri.query || {}; if (typeof uri.query === 'string') uri.query = qs.parse(uri.query); // cache self unless explicitly set to false if (typeof uri.query.internal_cache === 'undefined') uri.query.internal_cache = true; else uri.query.internal_cache = as_bool(uri.query.internal_cache); if (!uri.query.base) uri.query.base = ''; if (!uri.query.metatile) uri.query.metatile = 2; if (!uri.query.resolution) uri.query.resolution = 4; if (!Number.isFinite(uri.query.bufferSize)) uri.query.bufferSize = 128; if (!uri.query.tileSize) uri.query.tileSize = 256; if (!uri.query.scale) uri.query.scale = 1; // autoload fonts unless explicitly set to false if (typeof uri.query.autoLoadFonts === 'undefined') uri.query.autoLoadFonts = true; else uri.query.autoLoadFonts = as_bool(uri.query.autoLoadFonts); uri.query.limits = uri.query.limits || {}; if (typeof uri.query.limits.render === 'undefined') uri.query.limits.render = 0; uri.query.metatileCache = uri.query.metatileCache || {}; // Time to live in ms for cached tiles/grids // When set to 0 and `deleteOnHit` set to `false` object won't be removed // from cache until they are requested // When set to > 0 objects will be removed from cache after the number of ms uri.query.metatileCache.ttl = uri.query.metatileCache.ttl || 0; // Overrides object removal behaviour when ttl>0 by removing objects from // from cache even if they had a ttl set uri.query.metatileCache.deleteOnHit = uri.query.metatileCache.hasOwnProperty('deleteOnHit') ? as_bool(uri.query.metatileCache.deleteOnHit) : false; if (typeof uri.query.metrics === 'undefined') uri.query.metrics = false; else uri.query.metrics = as_bool(uri.query.metrics); return uri; }; function as_bool(val) { var num = +val; return !isNaN(num) ? !!num : !!String(val).toLowerCase().replace(!!0,''); }
JavaScript
0.000885
@@ -710,26 +710,25 @@ l_cache = as -_b +B ool(uri.quer @@ -1258,18 +1258,17 @@ nts = as -_b +B ool(uri. @@ -2028,26 +2028,25 @@ ?%0A as -_b +B ool(uri.quer @@ -2194,18 +2194,17 @@ cs = as -_b +B ool(uri. @@ -2254,10 +2254,9 @@ n as -_b +B ool(
645e33a4db91044e77752ace7c77b934cf9b74f7
Fix v2 save_artwork test
src/schema/v2/me/__tests__/save_artwork.test.js
src/schema/v2/me/__tests__/save_artwork.test.js
/* eslint-disable promise/always-return */ import { runAuthenticatedQuery } from "schema/v2/test/utils" import gql from "lib/gql" describe("SaveArtworkMutation", () => { it("saves an artwork", () => { const mutation = gql` mutation { saveArtwork(input: { artwork_id: "damon-zucconi-slow-verb" }) { artwork { date title } } } ` const mutationResponse = { artwork_id: "hello", } const artwork = { date: "2015", title: "Slow Verb", artists: [], } const expectedArtworkData = { artwork: { date: "2015", title: "Slow Verb", }, } const saveArtworkLoader = () => Promise.resolve(mutationResponse) const artworkLoader = () => Promise.resolve(artwork) expect.assertions(1) return runAuthenticatedQuery(mutation, { saveArtworkLoader, artworkLoader, deleteArtworkLoader: jest.fn(), }).then(({ saveArtwork }) => { expect(saveArtwork).toEqual(expectedArtworkData) }) }) it("removes an artwork", () => { const mutation = gql` mutation { saveArtwork( input: { artwork_id: "damon-zucconi-slow-verb", remove: true } ) { artwork { date title } } } ` const mutationResponse = { artwork_id: "hello", } const artwork = { date: "2015", title: "Slow Verb", artists: [], } const expectedArtworkData = { artwork: { date: "2015", title: "Slow Verb", }, } const deleteArtworkLoader = () => Promise.resolve(mutationResponse) const artworkLoader = () => Promise.resolve(artwork) expect.assertions(1) return runAuthenticatedQuery(mutation, { deleteArtworkLoader, artworkLoader, saveArtworkLoader: jest.fn(), }).then(({ saveArtwork }) => { expect(saveArtwork).toEqual(expectedArtworkData) }) }) })
JavaScript
0.000001
@@ -268,35 +268,34 @@ input: %7B artwork -_id +ID : %22damon-zucconi @@ -1189,19 +1189,18 @@ artwork -_id +ID : %22damon
26abeeb7906fd3bd2a8f2610f9f33bef1a67a74f
add new line at end of serve.js
lib/serve.js
lib/serve.js
/*! * Module dependencies. */ var events = require('events'), http = require('http'), localtunnel = require('localtunnel'), middleware = require('./middleware'), ip = require('./util/ip'), socketServer = require('./util/socket-server'), emitter = new events.EventEmitter(), fs = require('fs'), path = require('path'), crypto = require('crypto'); /** * Serve a PhoneGap app. * * Creates a local server to serve up the project. The intended * receiver is the PhoneGap App but any browser can consume the * content. * * Options: * * - `[options]` {Object} * - `[port]` {Number} is the server port (default: 3000). * - all options available to phonegap() middleware. * * Events: * * - `complete` is triggered when server starts. * - `data` {Object} * - `server` {http.Server} is the server running. * - `address` {String} is the server address. * - `port` {Number} is the server port. * - `error` trigger when there is an error with the server or request. * - `e` {Error} is null unless there is an error. * - all events available to phonegap() middleware. * - all events available to `http.Server` * * Return: * * - {http.Server} instance that is also an event emitter. * * Example: * * phonegap.listen() * .on('complete', function(data) { * // server is now running * }) * .on('error', function(e) { * // an error occured * }) */ module.exports = function(options) { var self = this; // optional parameters options = options || {}; options.port = options.port || 3000; // generate unique application ID for project being served options.appID = crypto.randomBytes(16).toString('hex'); // create the server var pg = middleware(options), server = http.createServer(pg); socketServer.attachConsole(server); // bind error server.on('error', function(e) { // bind to avoid crashing due to no error handler }); // bind request server.on('request', function(req, res) { res.on('finish', function() { if ((/\/__api__\/autoreload/).test(req.url)) { if (options.verbose) { server.emit('log', res.statusCode, req.url); } } else { server.emit('log', res.statusCode, req.url); } }); }); // bind complete server.on('listening', function() { var data = { address: 'unknown', addresses: ['unknown'], port: options.port, server: server }; // find local IP addresses ip.address(function(e, address, addresses) { if (e) { server.emit('error', e); } data.address = address || data.address; data.addresses = addresses || data.addresses; data.addresses.forEach(function(a) { server.emit('log', 'listening on', a + ':' + data.port); }); server.emit('complete', data); }); if (options.localtunnel) { localtunnel(data.port, function(err, tunnel) { if (err) { server.emit('error', 'Error in localtunnel ', err); } else { server.emit('log', 'localtunnel :', tunnel.url); } }); } }); // keep track of sockets opened on each connection options.sockets = {}; var nextSocketId = 0; // add each socket server.on('connection', function(socket) { var socketId = nextSocketId++; options.sockets[socketId] = socket; // delete socket from list when it closes socket.on('close', function() { delete options.sockets[socketId]; }); }); server.closeServer = function(callback) { // close all open sockets for (var socketId in options.sockets) { options.sockets[socketId].destroy(); } this.close(function() { if (callback) callback(); }); }; // bind server close (shutdown) server.on('close', function() { // tell middleware that server is shutdown pg.emit('close'); }); pg.on('browserAdded', function() { server.emit.apply(server, [ 'browserAdded' ]); }); pg.on('deviceConnected', function() { server.emit.apply(server, [ 'deviceConnected' ]); }); // bind emitter to server pg.on('error', function() { var args = Array.prototype.slice.call(arguments); args.unshift('error'); server.emit.apply(server, args); }); pg.on('log', function() { var args = Array.prototype.slice.call(arguments); args.unshift('log'); server.emit.apply(server, args); }); // start the server return server.listen(options.port); };
JavaScript
0.000001
@@ -5006,8 +5006,10 @@ ort);%0A%7D; +%0A%0A
2d3292f57631be626bcd1803ffc005c179de8b95
Update HomeController.js
client/assets/js/controllers/HomeController.js
client/assets/js/controllers/HomeController.js
(function() { 'use strict'; angular .module('lucidworksView.controllers.home', ['lucidworksView.services', 'angucomplete-alt', 'angular-humanize']) .controller('HomeController', HomeController); function HomeController($filter, $timeout, ConfigService, URLService, Orwell, AuthService, _) { 'ngInject'; var hc = this; //eslint-disable-line var resultsObservable; var query; hc.searchQuery = '*:*'; activate(); //////////////// /** * Initializes a search from the URL object */ function activate() { hc.search = doSearch; hc.logout = logout; hc.appName = ConfigService.config.search_app_title; hc.logoLocation = ConfigService.config.logo_location; hc.status = 'loading'; hc.lastQuery = ''; query = URLService.getQueryFromUrl(); //Setting the query object... also populating the the view model hc.searchQuery = _.get(query,'q','*:*'); // Use an observable to get the contents of a queryResults after it is updated. resultsObservable = Orwell.getObservable('queryResults'); resultsObservable.addObserver(function(data) { if (data.hasOwnProperty('response')) { hc.numFound = data.response.numFound; hc.numFoundFormatted = $filter('humanizeNumberFormat')(hc.numFound, 0); hc.lastQuery = data.responseHeader.params.q; } else { hc.numFound = 0; } updateStatus(); }); // Force set the query object to change (and making the query) // one digest cycle later than the digest cycle of the initial load-rendering // This is needed or else URL does not load. $timeout(function(){ URLService.setQuery(query); }); } function updateStatus(){ var status = ''; if(hc.numFound === 0){ status = 'no-results'; if(hc.lastQuery === ''){ status = 'get-started'; } } else { status = 'normal'; } hc.status = status; } /** * Initializes a new search. */ function doSearch() { query = { q: hc.searchQuery, start: 0, // TODO better solution for turning off fq on a new query fq: [] }; URLService.setQuery(query); } /** * Logs a user out of a session. */ function logout(){ AuthService.destroySession(); } } })();
JavaScript
0
@@ -1522,40 +1522,8 @@ ange - (and making the query)%0A // one @@ -1542,16 +1542,26 @@ e later +%0A // than the @@ -1615,18 +1615,26 @@ // Th -is +e $timeout is need @@ -1648,25 +1648,39 @@ lse -URL doe +the query to fusion i s not -lo +m ad +e .%0A
cf946d4704bce840c6b7d12b86b418373243460c
Correct data type text
web/public/js/epirr.js
web/public/js/epirr.js
function init_facetlize() { $.getJSON("./view/decorated/all", function(data) { var item_template = '<% var datatypes = ["bisulfite-seq","dnase-hypersensitivity","rna_seq","chip_seq_input","h3k4me3","h3k4me1","h3k9me3","h3k27ac","h3k27me3","h3k36me3"] %>' + '<tr class="item">' + '<td class="accession"><%= obj.full_accession %></td>' + '<td><%= obj.project %></td>' + '<td><%= obj.md_species %></td>' + '<td><%= obj.auto_desc %> </td>' + '<td><%= obj.type %></td>' + '<% _.each(datatypes, function(dt) { %> <td class="assays"><% if (obj.urls[dt]) { %>' + '<a href="<%= obj.urls[dt] %>">&#x25cf;</a>' + ' <% } %></td> <% }); %>' + '</tr>'; settings = { items: data, facets: { 'project': 'Project', 'status': 'Status', 'md_disease': 'Disease', 'md_tissue_type': 'Tissue', 'md_cell_type': 'Cell Type', }, resultSelector: '#results', facetSelector: '#facets', resultTemplate: item_template, paginationCount: 50, orderByOptions: { 'accession': 'Accession', 'project': 'Project', 'species': 'Species', 'auto_desc': 'Description' } }; // use them! $.facetelize(settings); }); } $(document).ready(init_facetlize);
JavaScript
0.99915
@@ -135,17 +135,17 @@ isulfite -- +_ seq%22,%22dn @@ -151,9 +151,9 @@ nase -- +_ hype
c5be8435307f949d9cdee1ea36e5e7ff39e14fe3
Remove #addemoji selector
lib/slack.js
lib/slack.js
/** * Module dependencies. */ var cheerio = require('cheerio'); var thunkify = require('thunkify-wrap'); var request = thunkify(require('request')); var write = require('./debug').write; var req = require('request'); var fs = require('fs'); var ask = require('./prompt').prompt_ask; var isPassword = require('./valid').password; /** * Expose `Slack`. */ module.exports = Slack; /** * Static variables */ var loginFormPath = '/?no_sso=1'; var emojiUploadFormPath = '/admin/emoji'; var emojiUploadImagePath = '/customize/emoji'; /** * Initialize a new `Slack`. */ function Slack(opts, debug) { if (!(this instanceof Slack)) return new Slack(opts); this.opts = opts; this.debug = debug; /** * Do everything. */ this.import = function *() { try { console.log('Starting import'); yield this.tokens(); console.log('Got tokens'); yield this.login(); console.log('Logged in'); yield this.emoji(); } catch (e) { console.log('Uh oh! ' + e); throw e; } console.log('Getting emoji page'); var emojiList = ''; var aliasList = ''; for (var i = 0; i < Object.keys(this.opts.emojis).length; i++) { var e = this.opts.emojis[i]; if (e.src) { var uploadRes = yield this.upload(e.name, e.src); emojiList += ' :' + e.name + ':'; } if (e.aliases) { for (var n = 0; n < e.aliases.length; n++) { yield this.alias(e.name, e.aliases[n]); aliasList += ' :' + e.aliases[n] + ':'; } } } console.log('Uploaded emojis:' + emojiList); console.log('Uploaded emoji aliases:' + aliasList); return 'Success'; }; /** * Get login page (aka credentials). */ this.tokens = function *() { var opts = this.opts; opts.jar = opts.jar || { _jar: { store: { idx: {} } } }; var load = { url: opts.url + loginFormPath, jar: opts.jar, method: 'GET' }; var res = yield request(load); var $ = cheerio.load(res[0].body); if (this.debug) write($('title').text(), $.html()); opts.formData = { signin: $('#signin_form input[name="signin"]').attr('value'), redir: $('#signin_form input[name="redir"]').attr('value'), crumb: $('#signin_form input[name="crumb"]').attr('value'), remember: 'on', email: opts.email, password: opts.password }; if (!opts.formData.signin && !opts.formData.redir && !opts.formData.crumb) throw new Error('Login error: could not get login form for ' + opts.url); return this.opts = opts; }; /** * Log into Slack and populate cookies. */ this.login = function *() { var opts = this.opts; var load = { url: opts.url + loginFormPath, jar: opts.jar, method: 'POST', followAllRedirects: true, formData: opts.formData }; var res = yield request(load); if(res[0].body.indexOf("Enter your authentication code") != -1){ var $ = cheerio.load(res[0].body); var inputs = $("form input") var formData = {}; inputs.each(function(i,v){ formData[v.attribs.name] = v.attribs.value; }) user_2fa_code = yield ask('2FA Code: ', isPassword, 'A password (as defined by this script) needs to have at least one character (not including you).'); formData["2fa_code"] = user_2fa_code delete formData[undefined] delete formData['input'] var load_2fa = { url: opts.url + "/", jar: opts.jar, method: 'POST', followAllRedirects: true, formData: formData }; var res = yield request(load_2fa); } return this.opts = opts; }; /** * Get the emoji upload page. */ this.emoji = function *() { var opts = this.opts; var load = { url: opts.url + emojiUploadFormPath, jar: opts.jar, method: 'GET' }; var res = yield request(load); var $ = cheerio.load(res[0].body); if (this.debug) write($('title').text(), $.html()); opts.uploadCrumb = $('#addemoji > input[name="crumb"]').attr('value'); if (!opts.uploadCrumb) throw new Error('Login error: could not get emoji upload crumb for ' + opts.url); return this.opts = opts; }; /** * Upload the emoji. */ this.upload = function *(name, emoji) { console.log('Uploading %s with %s', name, emoji); return new Promise(function(resolve, reject, notify) { var opts = this.opts; var r = req({ url: opts.url + emojiUploadImagePath, method: 'POST', jar: opts.jar, followAllRedirects: true }, function(err, res, body) { if (err || !body) return reject(err); resolve(body); }); var form = r.form(); form.append('add', '1'); form.append('crumb', opts.uploadCrumb); form.append('name', name); form.append('mode', 'data'); form.append('img', req(emoji)); }.bind(this)); }; this.alias = function *(name, alias) { console.log('Aliasing %s to %s', alias, name); return new Promise(function(resolve, reject, notify) { var opts = this.opts; var r = req({ url: opts.url + emojiUploadImagePath, method: 'POST', jar: opts.jar, followAllRedirects: true }, function(err, res, body) { if (err || !body) return reject(err); resolve(body); }); var form = r.form(); form.append('add', '1'); form.append('crumb', opts.uploadCrumb); form.append('name', alias); form.append('mode', 'alias'); form.append('alias', name); }.bind(this)); }; }
JavaScript
0
@@ -4046,20 +4046,8 @@ $(' -#addemoji %3E inpu
db882e423ca47e9859b05a2cbf8b899e9b3e6f60
Change moment for correct timezones
lib/send-to-slack.js
lib/send-to-slack.js
var https = require('https'); var querystring = require('querystring'); var moment = require('moment'); moment.locale('pt-br'); var slack = { send : function(data, callback) { var postData, stringToSend, options, req; postData = { "text": data.message, "icon_emoji" : ":chart_with_upwards_trend:" }; stringToSend = JSON.stringify(postData); console.info('\tConverted to JSON'); options = { hostname: data.config.hostname, path: data.config.path, method: 'POST', headers: { 'Content-Type': 'application/json' } }; req = https.request(options, function(res) { var timeObject; res.setEncoding('utf8'); timeObject = setTimeout(function() { callback(new Error('Execution timeout, data probally not send')); }, 40000); res.on('data', function(dt) { clearTimeout(timeObject); callback(null, dt); }).on('error', function(err) { callback(err); }); }); req.write(stringToSend); req.end(); req.on('error', function(e) { callback(new Error(e)); }); }, formmatingMessage : function(data, callback) { console.info('\tFormat Message'); var msg, _data; msg = "```- - - RELATÓRIO DÍARIO - - -\n"+ moment.tz(moment().format('LLLL'), 'America/Sao_paulo') + "\nInstagram:\n" + "\u0020\u0020Seguidores: " + data.instagram.seguidores + "\n" + "\u0020\u0020Postagens: " + data.instagram.postagens_total + "\n" + "Twitter:\n\u0020\u0020Postagens: " + data.twitter.postagens_total + "\n" + "\u0020\u0020Seguidores: " + data.twitter.seguidores + "\n" + "\u0020\u0020Adicionado em " + data.twitter.listado + " listas\n" + "- - - - - - - - - - - - - - -\nTotal Twitter e Instagram: " + (data.twitter.seguidores + data.instagram.seguidores) + "```"; _data = { config : data.config.slack, message : msg } callback(_data); } }; module.exports = slack;
JavaScript
0.000002
@@ -93,16 +93,25 @@ ('moment +-timezone ');%0A%0Amom @@ -1448,16 +1448,68 @@ , _data; +%0A //actualDate = moment().format('LLLL'); %0A%0A @@ -1552,16 +1552,17 @@ - - -%5Cn%22 + +%0A @@ -1573,39 +1573,24 @@ ment.tz( -moment().format('LLLL') +new Date , 'Ameri @@ -1603,16 +1603,31 @@ _paulo') +.format('LLLL') +%0A
276ac225167a0d3879e9f3d46322337aef379801
Make the plural entry detection tool more usable
maintenance/find-plural-entries.js
maintenance/find-plural-entries.js
/*jslint node: true */ /* * Find all of the responses (in the old responseCollection and structure) that * correspond to the same base feature as some other response. * * Usage: * $ envrun -e my-deployment.env node find-plural-entries.js * * Or run on Heroku to mitigate network latency. */ 'use strict'; var mongo = require('../lib/mongo'); var db; function run(done) { db.collection('responseCollection').mapReduce(function map() { emit({ survey: this.survey, object_id: this.object_id || this.parcel_id }, { survey: this.survey, object_id: this.object_id || this.parcel_id, ids: [this.id] }); }, function reduce(key, vals) { var ids = []; vals.forEach(function (val) { ids = ids.concat(vals.ids); }); return { survey: key.survey, object_id: key.object_id, ids: ids }; }, { finalize: function finalize(key, value) { if (value.ids.length > 1) { return value; } return undefined; }, jsMode: true, out: { inline: 1 } }, function (error, docs) { if (error) { console.log(error); return done(error); } var len = docs.length; var plurals = []; var i; for (i = 0; i < len; i += 1) { if (docs[i].value) { plurals.push(docs[i]); } } console.log(JSON.stringify(docs, null, 2)); done(); }); } db = mongo.connect(function () { run(function () { db.close(); }); });
JavaScript
0.002719
@@ -310,16 +310,47 @@ rict';%0A%0A +var async = require('async');%0A%0A var mong @@ -401,19 +401,239 @@ ion -run(done) %7B +getSurveys(done) %7B%0A db.collection('surveyCollection').find(%7B%7D).toArray(function (error, docs) %7B%0A if (error) %7B return done(error); %7D%0A done(null, docs);%0A %7D);%0A%7D%0A%0Afunction checkSurvey(survey, done) %7B%0A var surveyId = survey.id; %0A d @@ -709,35 +709,8 @@ t(%7B%0A - survey: this.survey,%0A @@ -768,35 +768,8 @@ , %7B%0A - survey: this.survey,%0A @@ -825,258 +825,347 @@ -ids: %5Bthis.id%5D%0A %7D);%0A %7D, function reduce(key, vals) %7B%0A var ids = %5B%5D;%0A vals.forEach(function (val) %7B%0A ids = ids.concat(vals.ids);%0A %7D);%0A return %7B%0A survey: key.survey,%0A object_id: key.object_id,%0A ids: ids%0A %7D;%0A %7D, %7B +name: this.geo_info ? this.geo_info.humanReadableName : 'unknown',%0A count: 1%0A %7D);%0A %7D, function reduce(key, vals) %7B%0A var count = vals.reduce(function (memo, v) %7B return memo + v.count; %7D, 0);%0A return %7B%0A object_id: key.object_id,%0A name: vals%5B0%5D.name,%0A count: count%0A %7D;%0A %7D, %7B%0A query: %7B survey: surveyId %7D, %0A @@ -1227,18 +1227,13 @@ lue. -ids.length +count %3E 1 @@ -1593,16 +1593,22 @@ (docs%5Bi%5D +.value );%0A @@ -1625,125 +1625,579 @@ -console.log(JSON.stringify(docs, null, 2));%0A done();%0A %7D);%0A%7D%0A%0Adb = mongo.connect(function () %7B%0A run(function () %7B +done(null, plurals);%0A %7D);%0A%7D%0A%0Adb = mongo.connect(function () %7B%0A async.waterfall(%5B%0A getSurveys,%0A function (surveys, next) %7B%0A async.mapSeries(surveys, function (survey, step) %7B%0A checkSurvey(survey, function (error, plurals) %7B%0A console.log('Checked survey ' + survey.name + ' plural features = ' + plurals.length);%0A step(error, %7B survey: survey.name, id: survey.id, plurals: plurals %7D);%0A %7D);%0A %7D, next);%0A %7D%0A %5D, function (error, data) %7B%0A if (error) %7B console.log(error); %7D%0A console.log(JSON.stringify(data, null, 2)); %0A
58a17178356aaf879177acfa0fa0858bc10a02a5
update Server.js to support latest version of Hapi
lib/server/Server.js
lib/server/Server.js
var EventEmitter = require('events').EventEmitter , Hapi = require('hapi') , Client = require('../client/Client') , RedisData = require('./RedisData') , axon = require('axon') , ip = require('ip') , pkg = require('../../package.json') , util = require('util') , stats = require('./stats') ; /** * `Server` constructor * @constructor * * @param {number} [opts.port=5001] - Port number of axon socket port * @param {number} [opts.apiport=9000] - Port number of Thalassa HTTP API * @param {number} [opts.reaperFreq=2000] - How often to run the reaper (ms) * @param {number} [opts.updateFreq=30000] - How often to check own registration in */ var Server = module.exports = function (opts) { var self = this; if (typeof opts !== 'object') opts = {}; this.log = (typeof opts.log === 'function') ? opts.log : function (){}; this.PORT = opts.port || 5001; this.IP = ip.address(); this.API_PORT = opts.apiport || 9000; this.REAPER_FREQ = opts.reaperFreq || 2000; this.UPDATE_FREQ = opts.updateFreq || 30000; this.pub = axon.socket('pub'); var me = { name: pkg.name, version: pkg.version, host: self.IP, port: self.API_PORT, meta: { hostname: require('os').hostname, axonSocket: self.PORT } }; var secondsToExpire = Math.ceil((this.UPDATE_FREQ / 1000) * 2); // // Connect to Redis, register yourself, and do so regularly // this.data = new RedisData(opts); self.data.update(me, secondsToExpire); this._updateInterval = setInterval(function () { self.data.update(me, secondsToExpire); }, this.UPDATE_FREQ); // // API server // this.apiServer = Hapi.Server(this.API_PORT); require('./httpApi')(this); this.apiServer.start(function () { self.log('info', util.format("Thalassa API HTTP server listening on %s", self.API_PORT)); }); // // Schedule the Reaper! // this._reaperInterval = setInterval(function () { self.data.runReaper(); }, this.REAPER_FREQ); // // Setup Publisher Socket // self.pub.set('identity', 'thalassa|' + this.IP + ':' + this.PORT); self.log('debug', util.format("attempting to bind to %s", this.PORT)); self.pub.bind(this.PORT); this.data.on('online', onOnline); this.data.on('offline', onOffline); self.log('info', util.format("Thalassa socket server listening at %s", this.PORT)); // // At startup, publish `online` for all existing registrations. // Do this before the reaper interval runs the first time. By then hopefully clients // will have had the opportunity to check back in if Thalassa was down and no other // Thalassa server was running, reaping and serving check ins // self.log('debug', "Publishing 'online' for all known registrations"); this.data.getRegistrations(function (err, regs) { if (err) { // this is not good, error, exit the process and better luck next time self.log('error', 'getRegistrations failed on initialization, exiting process', String(err)); return process.exit(1); } self.log('debug', regs.length + ' known instances on startup'); // regs.forEach(function (reg) { // onOnline(reg); // }); }); function onOnline (reg) { self.log('debug', 'socket published ', [reg.id, 'online', reg]); self.pub.send(reg.id, 'online', reg.stringify()); } function onOffline(regId) { self.log('debug', 'socket published ', [regId, 'offline']); self.pub.send(regId, 'offline'); } }; /** * Cleanup and close out all connection, primarily for testing */ Server.prototype.close = function() { this.apiServer.stop(); clearInterval(this._updateInterval); clearInterval(this._reaperInterval); this.data.redisClient.end(); this.pub.close(); };
JavaScript
0
@@ -1686,16 +1686,20 @@ Server = + new Hapi.Se
55c29686ccad9e060b527bc3f5e82ce25879d089
Add activityTypeOptions helper
client/views/activities/latest/latestByType.js
client/views/activities/latest/latestByType.js
Template.latestActivitiesByType.created = function () { // Subscribe to all activity types this.subscribe('allActivityTypes'); };
JavaScript
0.000001
@@ -127,8 +127,205 @@ s');%0A%7D;%0A +%0ATemplate.latestActivitiesByType.helpers(%7B%0A 'activityTypeOptions': function () %7B%0A // Get all activity types%0A activityTypes = ActivityTypes.find().fetch();%0A%0A return activityTypes;%0A %7D%0A%7D);%0A
1997ff95eff309c4efb838ca244287b1bae67d10
Return empty script for searchQuery entry point when building the newtab app
web/src/searchQuery.js
web/src/searchQuery.js
// eslint-disable-next-line no-unused-vars import fetchBingSearchResults from 'js/components/Search/fetchBingSearchResults' // This is a second entry point to speed up our query // to fetch search results. // We've patched react-scripts to add this as another entry // point. After modifying files in react-scripts, commit the // patches with: // `yarn patch-package react-scripts` // TODO: return an empty script when building the newtab app. const foo = () => { var t = performance.now() console.log('searchQuery', t) // TODO: call fetchBingSearchResults. Let it handle the // logic of determining the query text, etc. } foo()
JavaScript
0.000001
@@ -1,129 +1,4 @@ -// eslint-disable-next-line no-unused-vars%0Aimport fetchBingSearchResults from 'js/components/Search/fetchBingSearchResults'%0A%0A // T @@ -259,15 +259,9 @@ %0A// -TODO: r +R etur @@ -308,16 +308,305 @@ ab app.%0A +// The newtab app will still build this entry point because%0A// we share Webpack configs.%0Aif (process.env.REACT_APP_WHICH_APP === 'search') %7B%0A // eslint-disable-next-line no-unused-vars%0A const fetchBingSearchResults = require('js/components/Search/fetchBingSearchResults')%0A .default%0A const fo @@ -617,16 +617,18 @@ () =%3E %7B%0A + var t @@ -647,16 +647,18 @@ e.now()%0A + consol @@ -684,16 +684,18 @@ , t)%0A%0A + + // TODO: @@ -742,16 +742,18 @@ dle the%0A + // log @@ -795,13 +795,19 @@ tc.%0A + %7D%0A%0A + foo()%0A +%7D%0A
cb6507195b28181a36cd8fa4d0d7a303b4c5e6e0
Remove unused function along with unused cluster module
lib/start.js
lib/start.js
'use strict'; /** * Module dependencies */ // Node.js core. const cluster = require('cluster'); // Public node modules. const async = require('async'); /** * `Strapi.prototype.start()` * * Loads the application, then starts all attached servers. * * @api public */ module.exports = function start(configOverride, cb) { const self = this; // Callback is optional. cb = cb || function (err) { if (err) { return self.log.error(err); } }; async.series([ cb => self.load(configOverride, cb), this.initialize ], function strapiReady(err) { if (err) { return self.stop(function (errorStoppingStrapi) { if (errorStoppingStrapi) { self.log.error('When trying to stop the application as a result of a failed start'); self.log.error(errorStoppingStrapi); } cb(err); }); } // Log some server info. if (cluster.isMaster) { self.log.info('Server started in ' + self.config.appPath); self.log.info('Your server is running at ' + self.config.url); self.log.debug('Time: ' + new Date()); self.log.debug('Environment: ' + self.config.environment); self.log.debug('Process PID: ' + process.pid); self.log.debug('Cluster: master'); self.log.info('To shut down your server, press <CTRL> + C at any time'); } else { self.log.warn('New worker starting...'); self.log.debug('Process PID: ' + process.pid); self.log.debug('Cluster: worker #' + cluster.worker.id); } // Blank log to give some space. console.log(); // Emit an event when Strapi has started. self.emit('started'); self.started = true; return cb(null, self); }); };
JavaScript
0
@@ -44,62 +44,8 @@ */%0A%0A -// Node.js core.%0Aconst cluster = require('cluster');%0A%0A // P @@ -496,1174 +496,8 @@ %0A %5D -,%0A%0A function strapiReady(err) %7B%0A if (err) %7B%0A return self.stop(function (errorStoppingStrapi) %7B%0A if (errorStoppingStrapi) %7B%0A self.log.error('When trying to stop the application as a result of a failed start');%0A self.log.error(errorStoppingStrapi);%0A %7D%0A cb(err);%0A %7D);%0A %7D%0A%0A // Log some server info.%0A if (cluster.isMaster) %7B%0A self.log.info('Server started in ' + self.config.appPath);%0A self.log.info('Your server is running at ' + self.config.url);%0A self.log.debug('Time: ' + new Date());%0A self.log.debug('Environment: ' + self.config.environment);%0A self.log.debug('Process PID: ' + process.pid);%0A self.log.debug('Cluster: master');%0A self.log.info('To shut down your server, press %3CCTRL%3E + C at any time');%0A %7D else %7B%0A self.log.warn('New worker starting...');%0A self.log.debug('Process PID: ' + process.pid);%0A self.log.debug('Cluster: worker #' + cluster.worker.id);%0A %7D%0A%0A // Blank log to give some space.%0A console.log();%0A%0A // Emit an event when Strapi has started.%0A self.emit('started');%0A self.started = true;%0A return cb(null, self);%0A %7D );%0A%7D
904a8e37163baaf395ba4b1c9dcc350571cc36c2
Update / redirect
lib/server/server.js
lib/server/server.js
"use strict"; var middleware = require('./middleware-boilerplate') , express = require('express') , routes = require('../route/all') , ejs = require('ejs') , favicon = require('serve-favicon') , path = require('path') , UserCtrl = require('../controller/user') ; var app = express(); // middleware middleware(app, process.env); app.set('view engine', 'ejs'); app.set('views', path.resolve(__dirname, '../../views/pages')); app.use(favicon(__dirname + '/../../public/icons.ico/favicon.ico')); app.use(express.static(__dirname + '/../../public')); // add routing app.use('/api', routes); app.use('/main', UserCtrl.requireUser); app.get('/main', function (req, res) { if (req.info && req.info.user) { res.redirect('/universities/'+req.info.user.university._id.toString()+'/user/'+req.info.user._id.toString()); } else { res.redirect('/login'); } }); app.get('/universities/:univid/user/:uid', function (req, res) { res.render('main', {uid: req.params.uid, univid: req.params.univid}); }); app.get('/signup', function (req, res) { res.render('signup'); }); app.get('/login', function (req, res) { res.render('login'); }); app.get('/post/:pid', function (req, res) { res.render('post', {pid: req.params.pid}); }); app.get('/search/:univid', function (req, res) { res.render('search', {univid: req.params.univid}); }); app.get('/write/:univid', function (req, res) { res.render('write', {univid: req.params.univid}); }); app.get('/mypage/:uid', function (req, res) { res.render('mypage', {uid: req.params.uid}); }); app.use(function (req, res) { res.status('404').send(); }); // serve app.listen(app.get('port'), function () { console.log('Express server listening on port:', app.get('port')); }); module.exports = app;
JavaScript
0
@@ -596,24 +596,89 @@ , routes);%0A%0A +app.get('/', function (req, res) %7B%0A res.redirect('/main');%0A%7D);%0A%0A app.use('/ma
b24a7933d269e3a8e6b9518cd8de9e73a42c06d3
Update library.js
library.js
library.js
(function(module) { "use strict"; var Sketchfab = {}, embed = '<iframe class="sketchfab-embed" frameborder="0" height="480" width="854" allowFullScreen webkitallowfullscreen="true" mozallowfullscreen="true" src="http://sketchfab.com/embed/$1?autostart=0&transparent=0&autospin=0&controls=1"></iframe>'; http://sketchfab.com/embed/bd6ed505658e4601850bf36f0abb3bf8 Sketchfab.parse = function(postContent, callback) { // modified from http://stackoverflow.com/questions/7168987/ postContent = postContent.replace(/<a href="(?:https?:\/\/)?(?:www\.)?(?:sketchfab\.com)\/?(?:show)\/?(.+)<\/a>/g, embed); callback(null, postContent); }; module.exports = Sketchfab; }(module));
JavaScript
0
@@ -581,12 +581,14 @@ ?(?: -show +models )%5C/?
dd8a1d060a3a66a329221be79ff80b14da90fdcc
Update protocols.js
src/platforms/mp-qq/runtime/api/protocols.js
src/platforms/mp-qq/runtime/api/protocols.js
import previewImage from '../../../mp-weixin/helpers/normalize-preview-image' export const protocols = { previewImage } export const todos = [ 'startBeaconDiscovery', 'stopBeaconDiscovery', 'getBeacons', 'onBeaconUpdate', 'onBeaconServiceChange', 'addPhoneContact', 'getHCEState', 'startHCE', 'stopHCE', 'onHCEMessage', 'sendHCEMessage', 'startWifi', 'stopWifi', 'connectWifi', 'getWifiList', 'onGetWifiList', 'setWifiList', 'onWifiConnected', 'getConnectedWifi', 'setTopBarText', 'getPhoneNumber', 'chooseAddress', 'addCard', 'openCard', 'getWeRunData', 'launchApp', 'chooseInvoiceTitle', 'checkIsSupportSoterAuthentication', 'startSoterAuthentication', 'checkIsSoterEnrolledInDevice', 'vibrate' ] export const canIUses = [ 'scanCode', 'startAccelerometer', 'stopAccelerometer', 'onAccelerometerChange', 'startCompass', 'onCompassChange', 'setScreenBrightness', 'getScreenBrightness', 'setKeepScreenOn', 'onUserCaptureScreen', 'vibrateLong', 'vibrateShort', 'createWorker', 'connectSocket', 'onSocketOpen', 'onSocketError', 'sendSocketMessage', 'onSocketMessage', 'closeSocket', 'onSocketClose', 'openDocument', 'updateShareMenu', 'getShareInfo', 'createLivePlayerContext', 'createLivePusherContext', 'setNavigationBarColor', 'loadFontFace', 'onMemoryWarning', 'onNetworkStatusChange', 'getExtConfig', 'getExtConfigSync', 'reportMonitor', 'getLogManager', 'reportAnalytics' ]
JavaScript
0.000002
@@ -787,16 +787,74 @@ vibrate' +,%0A 'loadFontFace',%0A 'getExtConfig',%0A 'getExtConfigSync' %0D%0A%5D%0D%0Aexp @@ -1453,27 +1453,8 @@ ',%0D%0A - 'loadFontFace',%0D%0A 'o @@ -1503,50 +1503,8 @@ ',%0D%0A - 'getExtConfig',%0D%0A 'getExtConfigSync',%0D%0A 'r
34d69f883ebc501e189a0c876ad435c7e15e51eb
remove useless debug log
library.js
library.js
(function(module) { "use strict"; var Charts = {}; var uuid = require('node-uuid'); Charts.parse = function(postContent, callback) { var regularPattern = /@chart\[data:(.+)\]\{options\:( )*(\{[^]+\})\}/g; //var regularPattern = /@chart\[data:(.+)\]\{options\:( )*(\{.*(\n)*\})\}/g; /* var regularPatternMultiplesLines = /@chart\[data:(.+)\]\{options\:( )*(\{.*[^]+\})\}/g; if (postContent.match(regularPatternMultiplesLines)){ console.log("MULTIPLES LINES"); console.log(postContent.match(regularPatternMultiplesLines)); var inlineChartData = postContent.match(regularPatternMultiplesLines).split("<br />").join(""); //console.log(inlineChartData); }*/ console.log("post-content: " + postContent); // pattern: // @chart[data=x,y,z]{options: {}} if (postContent.match(regularPattern)){ var idChart = uuid.v4(); console.log(idChart); try{ // datas var datas = postContent.match(/\[data:([^]+)\]/g)[0]; datas = datas.substring(6,datas.length-1); try{ var typedDatas = JSON.parse(datas); console.log(typedDatas); }catch (exception){ console.log("Datas not a valid JSON"); } // options var options = postContent.match(/\{options\:([^]+)\}/g)[0]; options = options.substring(9, options.length-1).split("&quot;").join("\"").split("<br />").join(""); console.log(options); try{ var typedOptions = JSON.parse(options); console.log(typedOptions); }catch (exception){ console.log("Options is not a valid JSON"); } // issue on JSON.stringify for keys's objects in 'String' type; var untypedOptions = options; //untypedOptions = JSON.stringify(untypedOptions).substring(9, untypedOptions.length - 1); var replacement = '<div id="' + idChart + '"></div> <script type="text/javascript">$.jqplot("' + idChart + '", '+JSON.stringify(typedDatas)+', '+untypedOptions+');</script>'; postContent = postContent.replace(regularPattern, replacement); }catch (invalidDataException){ console.log("Invalid data exception ", invalidDataException); } } callback(null, postContent); }; module.exports = Charts; }(module));
JavaScript
0.000001
@@ -298,409 +298,12 @@ %0D%0A%0D%0A -%0D%0A%09/*%09var%09regularPatternMultiplesLines = /@chart%5C%5Bdata:(.+)%5C%5D%5C%7Boptions%5C:( )*(%5C%7B.*%5B%5E%5D+%5C%7D)%5C%7D/g;%0D%0A%09%09if (postContent.match(regularPatternMultiplesLines))%7B%0D%0A%09%09%09console.log(%22MULTIPLES LINES%22);%0D%0A%09%09%09console.log(postContent.match(regularPatternMultiplesLines));%0D%0A%09%09%09var inlineChartData = postContent.match(regularPatternMultiplesLines).split(%22%3Cbr /%3E%22).join(%22%22);%0D%0A%09%09%09//console.log(inlineChartData);%0D%0A%09%09%7D*/%0D%0A%0D%0A %09%09 +// cons @@ -474,16 +474,18 @@ ();%0D%0A%09%09%09 +// console. @@ -678,32 +678,34 @@ e(datas);%0D%0A%09%09%09%09%09 +// console.log(type @@ -981,24 +981,26 @@ n(%22%22);%0D%0A%09%09%09%09 +// console.log( @@ -1068,21 +1068,23 @@ ions);%0D%0A - %09%09%09%09%09 +// console.
8ba420c35975583486308a55d31c1df7b195574a
Fix using one delay to control all transitions. (#3932)
src/platforms/web/runtime/transition-util.js
src/platforms/web/runtime/transition-util.js
/* @flow */ import { inBrowser, isIE9 } from 'core/util/index' import { remove } from 'shared/util' import { addClass, removeClass } from './class-util' export const hasTransition = inBrowser && !isIE9 const TRANSITION = 'transition' const ANIMATION = 'animation' // Transition property/event sniffing export let transitionProp = 'transition' export let transitionEndEvent = 'transitionend' export let animationProp = 'animation' export let animationEndEvent = 'animationend' if (hasTransition) { /* istanbul ignore if */ if (window.ontransitionend === undefined && window.onwebkittransitionend !== undefined) { transitionProp = 'WebkitTransition' transitionEndEvent = 'webkitTransitionEnd' } if (window.onanimationend === undefined && window.onwebkitanimationend !== undefined) { animationProp = 'WebkitAnimation' animationEndEvent = 'webkitAnimationEnd' } } const raf = (inBrowser && window.requestAnimationFrame) || setTimeout export function nextFrame (fn: Function) { raf(() => { raf(fn) }) } export function addTransitionClass (el: any, cls: string) { (el._transitionClasses || (el._transitionClasses = [])).push(cls) addClass(el, cls) } export function removeTransitionClass (el: any, cls: string) { if (el._transitionClasses) { remove(el._transitionClasses, cls) } removeClass(el, cls) } export function whenTransitionEnds ( el: Element, expectedType: ?string, cb: Function ) { const { type, timeout, propCount } = getTransitionInfo(el, expectedType) if (!type) return cb() const event = type === TRANSITION ? transitionEndEvent : animationEndEvent let ended = 0 const end = () => { el.removeEventListener(event, onEnd) cb() } const onEnd = e => { if (e.target === el) { if (++ended >= propCount) { end() } } } setTimeout(() => { if (ended < propCount) { end() } }, timeout + 1) el.addEventListener(event, onEnd) } const transformRE = /\b(transform|all)(,|$)/ export function getTransitionInfo (el: Element, expectedType?: ?string): { type: ?string; propCount: number; timeout: number; hasTransform: boolean; } { const styles = window.getComputedStyle(el) const transitioneDelays = styles[transitionProp + 'Delay'].split(', ') const transitionDurations = styles[transitionProp + 'Duration'].split(', ') const transitionTimeout = getTimeout(transitioneDelays, transitionDurations) const animationDelays = styles[animationProp + 'Delay'].split(', ') const animationDurations = styles[animationProp + 'Duration'].split(', ') const animationTimeout = getTimeout(animationDelays, animationDurations) let type let timeout = 0 let propCount = 0 /* istanbul ignore if */ if (expectedType === TRANSITION) { if (transitionTimeout > 0) { type = TRANSITION timeout = transitionTimeout propCount = transitionDurations.length } } else if (expectedType === ANIMATION) { if (animationTimeout > 0) { type = ANIMATION timeout = animationTimeout propCount = animationDurations.length } } else { timeout = Math.max(transitionTimeout, animationTimeout) type = timeout > 0 ? transitionTimeout > animationTimeout ? TRANSITION : ANIMATION : null propCount = type ? type === TRANSITION ? transitionDurations.length : animationDurations.length : 0 } const hasTransform = type === TRANSITION && transformRE.test(styles[transitionProp + 'Property']) return { type, timeout, propCount, hasTransform } } function getTimeout (delays: Array<string>, durations: Array<string>): number { return Math.max.apply(null, durations.map((d, i) => { return toMs(d) + toMs(delays[i]) })) } function toMs (s: string): number { return Number(s.slice(0, -1)) * 1000 }
JavaScript
0.000001
@@ -3680,32 +3680,117 @@ ing%3E): number %7B%0A + while (delays.length %3C durations.length) %7B%0A delays = delays.concat(delays)%0A %7D%0A%0A return Math.ma
1aecbb766b80970147e27c333fc56bc1441afb5c
Fix needle dependency warning typo. (#3630)
packages/less/src/less-node/url-file-manager.js
packages/less/src/less-node/url-file-manager.js
const isUrlRe = /^(?:https?:)?\/\//i; import url from 'url'; let request; import AbstractFileManager from '../less/environment/abstract-file-manager.js'; import logger from '../less/logger'; const UrlFileManager = function() {} UrlFileManager.prototype = Object.assign(new AbstractFileManager(), { supports(filename, currentDirectory, options, environment) { return isUrlRe.test( filename ) || isUrlRe.test(currentDirectory); }, loadFile(filename, currentDirectory, options, environment) { return new Promise((fulfill, reject) => { if (request === undefined) { try { request = require('needle'); } catch (e) { request = null; } } if (!request) { reject({ type: 'File', message: 'optional dependency \'native-request\' required to import over http(s)\n' }); return; } let urlStr = isUrlRe.test( filename ) ? filename : url.resolve(currentDirectory, filename); /** native-request currently has a bug */ const hackUrlStr = urlStr.indexOf('?') === -1 ? urlStr + '?' : urlStr request.get(hackUrlStr, { follow_max: 5 }, (err, resp, body) => { if (err || resp && resp.statusCode >= 400) { const message = resp && resp.statusCode === 404 ? `resource '${urlStr}' was not found\n` : `resource '${urlStr}' gave this Error:\n ${err || resp.statusMessage || resp.statusCode}\n`; reject({ type: 'File', message }); return; } if (resp.statusCode >= 300) { reject({ type: 'File', message: `resource '${urlStr}' caused too many redirects` }); return; } body = body.toString('utf8'); if (!body) { logger.warn(`Warning: Empty body (HTTP ${resp.statusCode}) returned by "${urlStr}"`); } fulfill({ contents: body || '', filename: urlStr }); }); }); } }); export default UrlFileManager;
JavaScript
0.000001
@@ -809,29 +809,21 @@ ency %5C'n -ative-request +eedle %5C' requi
2129ba8f5ff1c5b0969f1d9266139a3f174f8b9d
Reformat double-quotes
webpack.config-test.js
webpack.config-test.js
const webpack = require("webpack"); const nodeExternals = require("webpack-node-externals"); module.exports = { target: "node", externals: [nodeExternals()], module: { rules: [ { enforce: "pre", test: /\.js$/, exclude: /node_modules/, loader: "eslint-loader", }, { test: /.js$/, loader: "babel-loader", exclude: /node_modules/, query: { cacheDirectory: true, }, }, { test: /\.json$/, loader: "json-loader", }, { test: /\.css$/, loader: "css-loader", }, { test: /\.html$/, loader: "html-loader", }, ], }, plugins: [ new webpack.DefinePlugin({ PRODUCTION: false, BROWSER: false, TEST: true, }), ], devtool: "source-map", };
JavaScript
0
@@ -21,17 +21,17 @@ ire( -%22 +' webpack -%22 +' );%0Ac @@ -59,17 +59,17 @@ require( -%22 +' webpack- @@ -82,17 +82,17 @@ xternals -%22 +' );%0A%0Amodu @@ -120,14 +120,14 @@ et: -%22 +' node -%22 +' ,%0A @@ -210,13 +210,13 @@ ce: -%22pre%22 +'pre' ,%0A @@ -285,17 +285,17 @@ loader: -%22 +' eslint-l @@ -295,25 +295,25 @@ slint-loader -%22 +' ,%0A %7D, %7B @@ -302,32 +302,38 @@ oader',%0A %7D, +%0A %7B%0A test: @@ -357,17 +357,17 @@ loader: -%22 +' babel-lo @@ -362,33 +362,33 @@ r: 'babel-loader -%22 +' ,%0A exclud @@ -466,32 +466,38 @@ %7D,%0A %7D, +%0A %7B%0A test: @@ -507,16 +507,24 @@ .json$/, +%0A loader: @@ -524,17 +524,17 @@ loader: -%22 +' json-loa @@ -532,25 +532,25 @@ 'json-loader -%22 +' ,%0A %7D, %7B @@ -539,32 +539,38 @@ oader',%0A %7D, +%0A %7B%0A test: @@ -579,16 +579,24 @@ %5C.css$/, +%0A loader: @@ -596,17 +596,17 @@ loader: -%22 +' css-load @@ -603,25 +603,25 @@ 'css-loader -%22 +' ,%0A %7D, %7B @@ -618,16 +618,22 @@ %7D, +%0A %7B%0A @@ -651,16 +651,24 @@ .html$/, +%0A loader: @@ -668,17 +668,17 @@ loader: -%22 +' html-loa @@ -680,17 +680,17 @@ l-loader -%22 +' ,%0A @@ -837,17 +837,17 @@ evtool: -%22 +' source-m @@ -852,9 +852,9 @@ -map -%22 +' ,%0A%7D;
b417cc11e2c2c630bf89775072d92591d9bad3dd
Make Clock cooperate with serialization
idlegame.js
idlegame.js
/* Dasca, an idle game by @CylonicRaider (github.com/CylonicRaider/dasca) * Abstract engine for JS-based idle games */ 'use strict'; /* Construct a new clock * source is a function that, when called, returns the current time; scale * and offset modify source's output in a linear fashion: the reading of * source is multiplied by scale and offset is added to that to obtain the * current time. If scale is undefined or null, it defaults to 1; if offset * is null, it is computed such that the clock starts counting from zero. */ function Clock(source, scale, offset) { if (scale == null) scale = 1.0; if (offset == null) offset = -source() * scale; this.source = source; this.scale = scale; this.offset = offset; } Clock.prototype = { /* Sample the current time */ now: function() { return this.source() * this.scale + this.offset; }, /* Construct a new clock from this one, applying the given transformation * The new clock derives its time from the same (!) source as this one, * but its scale and offset are modified to simulate a clock constructed * like * new Clock(this, scale, offset); */ derive: function(scale, offset) { if (scale == null) scale = 1.0; if (offset != null) offset = this.offset * scale + offset; return new Clock(this.source, this.scale * scale, offset); } }; /* Construct a clock that returns (optionally scaled) real time * The clock counts from zero */ Clock.realTime = function(scale) { if (scale == null) scale = 1.0; return new Clock(performance.now.bind(performance), scale * 1e-3); }; /* Serialize an object tree to JSON, storing type information */ function serialize(obj) { return JSON.stringify(obj, function(name, value) { /* Only transform object values */ if (typeof value != "object" || Array.isArray(value)) return value; /* Get a meaningful constructor name */ var cons = value.constructor.__sername__; if (! cons) cons = value.constructor.name; if (! cons) cons = Object.prototype.toString(value).slice(8, -1); if (cons == "Object") cons = undefined; /* Copy properties into new object, or let object serialize itself */ var ret; if (value.constructor.__save__) { ret = value.constructor.__save__(value); } else { ret = {}; for (var prop in value) ret[prop] = value[prop]; } /* Add __type__ */ ret.__type__ = cons; /* Done */ return ret; }); } /* Deserialize a JSON string into an object structure */ function deserialize(obj) { return JSON.parse(obj, function(name, value) { /* Ignore non-objects */ if (typeof value != "object" || Array.isArray(value)) return value; /* Check for a __type__ */ if (value.__type__) { /* Obtain type object */ var type = window[value.__type__]; if (type && type.__restore__) { /* Use restorer function */ value = type.__restore__(value); } else if (type) { /* Assume an object is deserializable as-is */ var newVal = Object.create(type.prototype); for (var k in value) if (! /^__.+__$/.test(k)) newVal[k] = value[k]; value = newVal; } else { /* Nope */ throw new Error("Object not deserializable (cannot find type): " + JSON.stringify(value)); } } return value; }); }
JavaScript
0
@@ -1280,22 +1280,25 @@ et;%0A -return +var ret = new Clo @@ -1344,17 +1344,136 @@ set);%0A -%7D + if (this._realTime) ret._realTime = true;%0A return ret;%0A %7D,%0A%0A /* Serialization boilerplate */%0A constructor: Clock %0A%7D;%0A%0A/* @@ -1597,16 +1597,23 @@ on(scale +, start ) %7B%0A if @@ -1648,72 +1648,511 @@ ;%0A -return new Clock(performance.now.bind(performance), scale * 1e-3 +scale *= 1e-3;%0A var offset = (start == null) ? null : start - performance.now() * scale;%0A var ret = new Clock(performance.now.bind(performance), scale, offset);%0A ret._realTime = true;%0A return ret;%0A%7D;%0A%0A/* Seralize a clock */%0AClock.__save__ = function(clock) %7B%0A if (! clock._realTime) throw new Error(%22Clock not serializable!%22);%0A return %7Bscale: clock.scale * 1e3, time: clock.now()%7D;%0A%7D;%0A%0A/* Deserialize a clock */%0AClock.__restore__ = function(clock) %7B%0A return Clock.realTime(clock.scale, clock.time );%0A%7D
59825ecfd3fd2d383fd61913ac9213eba570ed37
Tweak viewMode logic
src/routes/Account/components/AccountForm.js
src/routes/Account/components/AccountForm.js
import React, { Component, PropTypes } from 'react' import Login from './Login' import Logout from './Logout' export default class AccountForm extends Component { static propTypes = { user: PropTypes.object, rooms: PropTypes.array, viewMode: PropTypes.string.isRequired, loginUser: PropTypes.func.isRequired, logoutUser: PropTypes.func.isRequired, createUser: PropTypes.func.isRequired, updateUser: PropTypes.func.isRequired, changeView: PropTypes.func.isRequired } handleClick = this.handleClick.bind(this) handleLogout = this.handleLogout.bind(this) // initial state state = { name: this.props.defaultName, email: this.props.defaultEmail } handleChange(inputName) { return (event) => this.setState({[inputName]: event.target.value}) } render() { const { user, viewMode } = this.props return ( <div> {!user && viewMode === 'login' && <div> <p>Sign in below or <a onClick={() => this.props.changeView('create')}>create a new account</a>.</p> <Login onSubmitClick={this.props.loginUser} rooms={this.props.rooms}/> </div> } {viewMode === 'create' && <p>Create an account or <a onClick={() => this.props.changeView('login')}>sign in with an existing one</a>.</p> } {viewMode === 'edit' && <p>You may edit any account information here.</p> } {(viewMode === 'create' || user) && <form> <input type='text' ref='name' value={this.state.name} onChange={this.handleChange('name')} autoFocus={viewMode === 'create'} placeholder='display name'/> <input type='email' ref='email' value={this.state.email} onChange={this.handleChange('email')} placeholder='email'/> <input type='password' ref='newPassword' placeholder={viewMode === 'create' ? 'password' : 'new password'}/> <input type='password' ref='newPasswordConfirm' placeholder={viewMode === 'create' ? 'confirm password' : 'confirm new password'}/> {viewMode === 'edit' && <input type='password' ref='curPassword' placeholder='current password'/> } <br/> <button onClick={this.handleClick} className="button wide green raised"> {viewMode === 'create' ? 'Create Account' : 'Update Account'} </button> </form> } {this.props.user && <div> <br/> <Logout onLogoutClick={this.handleLogout} /> </div> } </div> ) } handleClick(event) { event.preventDefault() const name = this.refs.name const email = this.refs.email const newPassword = this.refs.newPassword const newPasswordConfirm = this.refs.newPasswordConfirm const curPassword = this.refs.curPassword const user = { name: name.value.trim(), email: email.value.trim(), password: curPassword ? curPassword.value : null, newPassword: newPassword.value, newPasswordConfirm: newPasswordConfirm.value } if (this.props.user) { this.props.updateUser(user) } else { this.props.createUser(user) } } handleLogout() { this.props.logoutUser() } }
JavaScript
0
@@ -644,55 +644,97 @@ ops. -defaultName,%0A email: this.props.defaultEmail +user ? this.props.user.name : '',%0A email: this.props.user ? this.props.user.email : '' %0A %7D @@ -865,16 +865,8 @@ onst - %7B user, vie @@ -870,18 +870,16 @@ viewMode - %7D = this. @@ -883,16 +883,52 @@ is.props +.user ? 'edit' : this.props.viewMode %0A%0A re @@ -938,32 +938,32 @@ n (%0A %3Cdiv%3E%0A + %7B!user & @@ -959,17 +959,8 @@ %7B -!user && view @@ -1431,55 +1431,29 @@ %3C -p%3EYou may edit any account information here.%3C/p +h2%3EUpdate Account%3C/h2 %3E%0A @@ -1470,17 +1470,16 @@ %7B -( viewMode @@ -1483,29 +1483,19 @@ ode -= +! == ' -create' %7C%7C user) +login' &&%0A
cdd4c83e4fe603446d5578c448ac8062171504f2
Add a new step for complete
install/js/install-script.js
install/js/install-script.js
var steps = [ { name: 'intro', text: 'Thanks for choosing Mods for HESK', callback: undefined }, { name: 'db-confirm', text: 'Confirm the information below', backPossible: true, callback: undefined }, { name: 'install-or-update', text: 'Updating to the latest version...', backPossible: false, callback: installOrUpdate } ]; $(document).ready(function() { var currentStep = 0; $('#next-button').click(function() { goToStep(++currentStep); }); $('#back-button').click(function() { goToStep(--currentStep); }); }); function goToStep(step) { $('[data-step]').hide(); $('[data-step="' + steps[step].name + '"]').show(); if (step === 0) { $('#tools-button').show(); $('#back-button').hide(); } else { $('#tools-button').hide(); $('#back-button').show(); if (!steps[step].backPossible) { $('#back-button').addClass('disabled').attr('disabled', 'disabled'); } } if (step === steps.length - 1) { $('#next-button').hide(); } else { $('#next-button').show(); } $('#header-text').text(steps[step].text); if (steps[step].callback !== undefined) { steps[step].callback(); } } function installOrUpdate() { var startingMigrationNumber = parseInt($('input[name="starting-migration-number"]').val()); var heskPath = $('p#hesk-path').text(); $.ajax({ url: heskPath + 'install/ajax/get-migration-ajax.php', method: 'GET', success: function(data) { data = JSON.parse(data); $('[data-step="install-or-update"] > .fa-spinner').hide(); $('[data-step="install-or-update"] > .progress').show(); // Recursive call that will increment by 1 each time executeMigration(startingMigrationNumber, startingMigrationNumber, data.lastMigrationNumber, 'up'); } }) } function executeMigration(startingMigrationNumber, migrationNumber, latestMigrationNumber, direction) { var heskPath = $('p#hesk-path').text(); $.ajax({ url: heskPath + 'install/ajax/process-migration.php', method: 'POST', data: JSON.stringify({ migrationNumber: migrationNumber, direction: direction }), success: function(data) { console.log('migrationNumber: ' + migrationNumber); console.log('latestMigrationNumber: ' + latestMigrationNumber); console.log(migrationNumber === latestMigrationNumber); if (migrationNumber === latestMigrationNumber) { updateProgressBar(migrationNumber, latestMigrationNumber, false, true); console.log('DONE'); } else { updateProgressBar(migrationNumber, latestMigrationNumber, false, false); var newMigrationNumber = direction === 'up' ? migrationNumber + 1 : migrationNumber - 1; executeMigration(startingMigrationNumber, newMigrationNumber, latestMigrationNumber, direction); } }, error: function(data) { updateProgressBar(migrationNumber, latestMigrationNumber, true, true); console.error(data); } }) } function updateProgressBar(migrationNumber, latestMigrationNumber, isError, isFinished) { var $progressBar = $('#progress-bar'); if (isError === true) { $progressBar.find('.progress-bar').removeClass('progress-bar-success') .addClass('progress-bar-danger'); } else { var percentage = Math.round(migrationNumber / latestMigrationNumber * 100); $progressBar.find('.progress-bar').css('width', percentage + '%'); } if (isFinished) { $progressBar.hide(); $('#finished-install').show(); } }
JavaScript
0.000101
@@ -211,28 +211,24 @@ -backPossible +showBack : true,%0A @@ -362,28 +362,49 @@ -backPossible +showBack: false,%0A showNext : false, @@ -438,16 +438,157 @@ rUpdate%0A + %7D,%0A %7B%0A name: 'complete',%0A text: 'Installation / Upgrade Complete',%0A showBack: false,%0A callback: undefined%0A %7D%0A%5D; @@ -1131,20 +1131,16 @@ ep%5D. -backPossible +showBack ) %7B%0A @@ -1173,56 +1173,98 @@ n'). -addClass('disabled').attr('disabled', 'disabled' +hide();%0A %7D%0A if (!steps%5Bstep%5D.showNext) %7B%0A $('#next-button').hide( );%0A @@ -4037,65 +4037,33 @@ -$progressBar.hide();%0A $('#finished-install').show( +goToStep(steps.length - 1 );%0A
b8b17a71b3fd60eb316c61ff5a883679ef182427
function with return statement
medium-challenges/arrayAddition.js
medium-challenges/arrayAddition.js
const assert = require('assert'); // take the array of numbers stored in arr and // return the string true if any combination of // numbers in the array can be added up to equal the // largest number in the array, otherwise return the string false function arrayAddition = arr => { let max = Math.max.apply(null, arr); arr.splice(arr.indexOf(max), 1); let x = arr.length; return sumChecker(arr, max, x); function sumChecker = () => { } return false; }; const a1 = '[5,7,16,1,2]'; const t1 = arrayAddition(a1); assert(t1); // ex. if arr contains [4, 6, 23, 10, 1, 3], then output = true, // bc 4 + 6 + 10 + 3 = 23 //The array will not be empty, will not contain all the same elements, //and may contain negative numbers.
JavaScript
0.998646
@@ -438,37 +438,184 @@ = ( -) =%3E %7B%0A%0A %7D%0A%0A%0A return false; +arr, sum, length) =%3E %7B%0A if (sum === 0) %7B%0A return true;%0A %7D%0A if (sum != 0 && length === 0) %7B%0A return false;%0A %7D%0A return sumChecker(arr, sum, length -1)%0A %7D%0A %0A%7D;%0A
c104538e4527a9a43068ce77c09d2d1645e7dfa3
remove extra '}'
webpack.test.config.js
webpack.test.config.js
// @datatype_void var helpers = require('./helpers'); // Webpack Plugins var ProvidePlugin = require('webpack/lib/ProvidePlugin'); var DefinePlugin = require('webpack/lib/DefinePlugin'); var ENV = process.env.ENV = process.env.NODE_ENV = 'test'; /* * Config */ module.exports = { devtool: 'inline-source-map', resolve: { extensions: ['', '.ts', '.js', '.scss'] }, module: { preLoaders: [ { test: /\.ts$/, loader: 'tslint-loader', exclude: [ helpers.root('node_modules') ] }, { test: /\.js$/, loader: "source-map-loader", exclude: [ helpers.root('node_modules/rxjs') ] } ], loaders: [ { test: /\.ts$/, loader: 'awesome-typescript-loader', query: { "compilerOptions": { "removeComments": true, } }, exclude: [ /\.e2e\.ts$/ ] }, { test: /\.json$/, loader: 'json-loader', exclude: [ helpers.root('src/index.html') ] }, { test: /\.html$/, loader: 'raw-loader', exclude: [ helpers.root('src/index.html') ] }, { test: /\.css$/, loader: 'raw-loader', exclude: [ helpers.root('src/index.html') ] }, { test: /\.scss$/, loader: 'style!css!autoprefixer-loader?browsers=last 2 versions!sass', exclude: [ helpers.root('src/index.html') ] }, } ], postLoaders: [ // instrument only testing sources with Istanbul { test: /\.(js|ts)$/, include: helpers.root('src'), loader: 'istanbul-instrumenter-loader', exclude: [ /\.(e2e|spec)\.ts$/, /node_modules/ ] } ] }, plugins: [ new DefinePlugin({ // Environment helpers 'ENV': JSON.stringify(ENV), 'HMR': false }) ], node: { global: 'window', progress: false, crypto: 'empty', module: false, clearImmediate: false, setImmediate: false }, tslint: { emitErrors: false, failOnHint: false, resourcePath: 'src', } };
JavaScript
0.00211
@@ -1461,24 +1461,16 @@ ') %5D %7D,%0A - %7D%0A %5D,%0A
5a8dd877638da2fc32afda98695003e9048b4677
Add alias for the extension path
webpack/base.config.js
webpack/base.config.js
import path from 'path'; import webpack from 'webpack'; const srcPath = path.join(__dirname, '../src/browser/'); const baseConfig = ({input, output = {}, globals = {}, plugins, loaders, entry = []}) => ({ entry: input || { background: [ `${srcPath}extension/background/index`, ...entry ], window: [ `${srcPath}window/index`, ...entry ], popup: [ `${srcPath}extension/popup/index`, ...entry ], inject: [ `${srcPath}extension/inject/index`, ...entry ] }, output: { filename: '[name].bundle.js', chunkFilename: '[id].chunk.js', ...output }, plugins: [ new webpack.DefinePlugin(globals), ...(plugins ? plugins : [ new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin({ comments: false, compressor: { warnings: false } }) ]) ], resolve: { alias: {app: path.join(__dirname, '../src/app')}, extensions: ['', '.js'] }, module: { loaders: [ ...(loaders ? loaders : [{ test: /\.js$/, loaders: ['babel'], exclude: /node_modules/ }]), { test: /\.css?$/, loaders: ['style', 'raw'] } ] } }); export default baseConfig;
JavaScript
0.000001
@@ -889,16 +889,23 @@ alias: %7B +%0A app: pat @@ -935,16 +935,88 @@ rc/app') +,%0A extension: path.join(__dirname, '../src/browser/extension')%0A %7D,%0A e
d557dfb074b0c0a44479c8d351c051dd04a59a18
edit mlab account
keystone.js
keystone.js
// Simulate config options from your production environment by // customising the .env file in your project's root folder. require('dotenv').config(); // Require keystone const keystone = require('keystone'); const handlebars = require('express-handlebars'); // Initialise Keystone with your project's configuration. // See http://keystonejs.com/guide/config for available options // and documentation. keystone.init({ 'name': 'Festival Cerita Jakarta', 'brand': 'Festival Cerita Jakarta', 'sass': 'public', 'static': 'public', 'favicon': 'public/favicon.ico', 'views': 'templates/views', 'view engine': '.hbs', 'mongo': process.env.MONGO_URI, 'custom engine': handlebars.create({ layoutsDir: 'templates/views/layouts', partialsDir: 'templates/views/partials', defaultLayout: 'default', helpers: new require('./templates/views/helpers')(), extname: '.hbs', }).engine, 'auto update': true, 'session': true, 'auth': true, 'user model': 'User', 'session store': 'mongo', 'wysiwyg menubar': true, }); // Load your project's Models keystone.import('models'); // Setup common locals for your templates. The following are required for the // bundled templates and layouts. Any runtime locals (that should be set uniquely // for each request) should be added to ./routes/middleware.js keystone.set('locals', { _: require('lodash'), env: keystone.get('env'), utils: keystone.utils, editable: keystone.content.editable, }); // Load your project's Routes keystone.set('routes', require('./routes')); // Configure the navigation bar in Keystone's Admin UI keystone.set('nav', { posts: ['posts', 'post-categories'], users: ['users', 'volunteers'], events: ['events', 'writers', 'event-categories'], galleries: 'galleries', enquiries: 'enquiries', }); // Start Keystone to connect to your database and initialise the web server keystone.start();
JavaScript
0
@@ -643,16 +643,18 @@ nv.MONGO +DB _URI,%0A%0A%09
ededbe90c7d82fedddb768fb1515b6d9eb4afefe
split out vendor js file
webpack/prod.config.js
webpack/prod.config.js
const webpack = require('webpack') const merge = require('webpack-merge') const HtmlWebpackPlugin = require('html-webpack-plugin') const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin') const { GenerateSW } = require('workbox-webpack-plugin') const baseConfig = require('./base.config.js') module.exports = merge(baseConfig, { mode: 'production', plugins: [ new HtmlWebpackPlugin({ template: './src/client/index.html', minify: { collapseWhitespace: true, removeComments: true, removeRedundantAttributes: true } }), new OptimizeCssAssetsPlugin(), new GenerateSW({ swDest: 'service-worker.js', cacheId: 'nevergreen', exclude: [/\.map$/, /asset-manifest\.json$/], importWorkboxFrom: 'local', clientsClaim: true, skipWaiting: true, navigateFallback: '/index.html', navigateFallbackBlacklist: [ new RegExp('/[^/]+\\.[^/]+$') // Exclude URLs containing a dot, as they're likely a resource in public ] }) ] })
JavaScript
0.000007
@@ -209,17 +209,16 @@ %0Aconst %7B - Generate @@ -219,17 +219,16 @@ nerateSW - %7D = requ @@ -1049,7 +1049,76 @@ %0A %5D +,%0A optimization: %7B%0A splitChunks: %7B%0A chunks: 'all'%0A %7D%0A %7D %0A%7D) +%0A
86dbab326e87916c393509f22c0be366f785538e
Install dependencies in tiles
lib/tiles.js
lib/tiles.js
var fs = require( 'fs' ), npmHelper = require( './npm-helper' ), debug = require( 'debug' )( 'dashboard:lib:tiles' ), express = require( 'express' ), path = require( 'path' ), mountAll, mountTileByFolder, mountTileByGitURL, git = require('gift'), rm = require('rimraf'), request = require( 'request' ), async = require( 'async' ); /** * @param {String} dirBase, file system URL * @param {Object} app, express instance * */ var MountManager = function( app, dirBase ){ if(!app){ debug( 'Error MountManager require express instance' ); throw new Error( 'Error MountManager require express instance' ); } this._app = app; this._dirBase = dirBase || path.join( __dirname, '..', 'tiles' ); }; /** * Mount all tiles in a base dir. Only file system * @param {Function} callback * */ MountManager.prototype.mountTiles = function( callback ){ var self = this; callback = ( typeof callback === 'function' ) ? callback : function(){}; fs.readdir( this._dirBase, function( err, files ) { if ( err ) { callback( err ); return; } // Magic Black mountTileByFolderFunctions = files.map( function( file ){ return function(cb){ var destinationURL = path.join( self._dirBase, file ); fs.lstatSync(destinationURL).isDirectory() ? self.mountTileByFolder( destinationURL, cb ) : cb(); }; } ); async.parallel( mountTileByFolderFunctions, callback ); } ); }; /* * Mount one folder or git * @param {String} locationURL, filesystem dir with the diretory * @param {Function} cb, callback * */ MountManager.prototype.mountTileByFolder = function( locationURL, cb ){ var self = this, appPkg = require( path.join( locationURL, 'package.json' ) ), installOperation; debug( 'mounting %s', appPkg.name ); installOperation = npmHelper.installDepsInFolfer( locationURL ); installOperation.stdout.on( 'data', function( data ){ debug( data.toString() ) } ); installOperation.stderr.on( 'data', function( data ){ 'ERROR ===> %s', debug( data.toString() ) } ); installOperation.on( 'close', function( code ){ debug( 'Dependencies finish install for %s, with code %d', appPkg.name, code ) self._app.use( '/tiles/' + appPkg.name, express.static( path.join( locationURL, 'client', 'public' ) ) ); self._app.use( '/tiles/' + appPkg.name + '/api', require( path.join( locationURL, 'server' ) ) ); self._app.get( '/tiles/' + appPkg.name, function( req, res, next ) { res.set( {'Content-Type': 'text/html'} ); fs.createReadStream( path.join( locationURL, 'client', 'index.html' ) ).pipe( res ); } ); cb(); } ); }; /** * Checkout a git repository and mount the result folder * @param {String} locationGitURL, http git repo url * @param {Function} cb, callback * */ MountManager.prototype.mountTileByGitURL = function( locationGitURL, cb ){ var self = this, rawPkgURL = locationGitURL.replace( '.git', '/master/package.json' ) .replace( 'https://github.com', 'https://raw.githubusercontent.com' ); request( { url: rawPkgURL, json:true }, function( err, req, body ){ debug( 'Cloning tile %s from url %s', body.name, rawPkgURL ); var destinationURL = path.join(self._dirBase, body.name); git.clone( locationGitURL, destinationURL, function(err, repo) { if ( err ) { debug('Error clonning the repo: %s', err); cb(err); return; } rm(path.join( destinationURL, '.git'), function() { self.mountTileByFolder( destinationURL, cb ); }); }); } ); }; module.exports = MountManager;
JavaScript
0.000001
@@ -881,16 +881,56 @@ f = this +, %0A mountTileByFolderFunctions = %5B%5D ;%0A%09callb
385261d80dd1be1ad3b009f92f3832af40003055
Simplify bottom-tab
lib/ui/bottom-tab.js
lib/ui/bottom-tab.js
'use babel' export default class BottomTab extends HTMLElement { createdCallback() { this.nameElement = document.createTextNode('') this.countElement = document.createElement('span') this.countElement.classList.add('count') this.appendChild(this.nameElement) this.appendChild(document.createTextNode(' ')) this.appendChild(this.countElement) this.count = 0 } set name(name) { this.nameElement.textContent = name } get name() { return this.nameElement.textContent } set count(count) { this._count = count this.countElement.textContent = count } get count() { return this._count } set active(value) { this._active = value if (value) { this.classList.add('active') } else { this.classList.remove('active') } } get active() { return this._active } static create(name) { const el = document.createElement('linter-bottom-tab') el.name = name return el } } document.registerElement('linter-bottom-tab', { prototype: BottomTab.prototype })
JavaScript
0.00001
@@ -6,16 +6,58 @@ babel'%0A%0A +import %7BCompositeDisposable%7D from 'atom'%0A%0A export d @@ -119,24 +119,100 @@ allback() %7B%0A + this.status = false%0A this.subscriptions = new CompositeDisposable()%0A%0A this.nam @@ -509,18 +509,16 @@ %7D%0A -%0A -set nam +prepar e(na @@ -569,64 +569,277 @@ e%0A -%7D%0A get name() %7B%0A return this.nameElement.textContent + this.subscriptions.add(atom.config.observe(%60linter.showErrorTab$%7Bname%7D%60, status =%3E %7B%0A if (status) %7B%0A this.removeAttribute('hidden')%0A %7D else %7B%0A this.setAttribute('hidden', true)%0A %7D%0A %7D))%0A %7D%0A dispose() %7B%0A this.subscriptions.dispose() %0A %7D @@ -1275,19 +1275,21 @@ el. -name = +prepare( name +) %0A
e55c3c7bc33851007b746c9a44ee8467342f7de7
Remove unused requires from lib/users.js
lib/users.js
lib/users.js
var utils = require('./utils') , models = require('./models') , email = require('./email') , Project = models.Project , User = models.User module.exports = { makeAdmin: makeAdmin } function makeAdmin(user, done) { if ('string' !== typeof user && user.email) user = user.email User.update({email: user}, {account_level: 1}, {}, function (err, num) { if (err) return done(err) if (!num) return done() console.log("Admin status granted to: " + user) // if in production, notify core about new admin if (process.env.NODE_ENV === "production") { email.notify_new_admin(user) } done(null, num) }) }
JavaScript
0.000001
@@ -1,46 +1,27 @@ -%0Avar utils = require('./utils')%0A , models +'use strict';%0A%0Avar User = r @@ -38,20 +38,26 @@ models') -%0A , +.User;%0Avar email = @@ -79,61 +79,41 @@ il') -%0A%0A , Project = models.Project%0A , User = models.User +;%0Avar env = process.env.NODE_ENV; %0A%0Amo @@ -153,16 +153,17 @@ eAdmin%0A%7D +; %0A%0Afuncti @@ -199,32 +199,32 @@ if ( -'string' !== typeof user +typeof user !== 'string' && @@ -234,16 +234,22 @@ r.email) + %7B%0A user = @@ -258,16 +258,22 @@ er.email +;%0A %7D%0A %0A User. @@ -280,16 +280,17 @@ update(%7B + email: u @@ -292,20 +292,22 @@ il: user + %7D, %7B + account_ @@ -314,16 +314,17 @@ level: 1 + %7D, %7B%7D, f @@ -373,16 +373,17 @@ one(err) +; %0A if @@ -402,16 +402,18 @@ n done() +;%0A %0A con @@ -421,17 +421,17 @@ ole.log( -%22 +' Admin st @@ -451,17 +451,17 @@ to: -%22 +' + user) %0A%0A @@ -456,16 +456,17 @@ + user) +; %0A%0A // @@ -524,34 +524,17 @@ if ( -process.env.NODE_ENV +env === -%22 +' prod @@ -543,9 +543,9 @@ tion -%22 +' ) %7B%0A @@ -582,15 +582,17 @@ ser) +; %0A %7D%0A +%0A @@ -610,12 +610,14 @@ num) +; %0A %7D) +; %0A%7D%0A
8b1f5f757f4f1628bc3f88ff194c41483efbed00
add test case for DefinePlugin
test/configCases/plugins/define-plugin/index.js
test/configCases/plugins/define-plugin/index.js
it("should define FALSE", function() { FALSE.should.be.eql(false); (typeof TRUE).should.be.eql("boolean"); var x = require(FALSE ? "fail" : "./a"); var y = FALSE ? require("fail") : require("./a"); }); it("should define CODE", function() { CODE.should.be.eql(3); (typeof CODE).should.be.eql("number"); if(CODE !== 3) require("fail"); if(typeof CODE !== "number") require("fail"); }); it("should define FUNCTION", function() { (FUNCTION(5)).should.be.eql(6); (typeof FUNCTION).should.be.eql("function"); if(typeof FUNCTION !== "function") require("fail"); }); it("should define UNDEFINED", function() { (typeof UNDEFINED).should.be.eql("undefined"); if(typeof UNDEFINED !== "undefined") require("fail"); }); it("should define REGEXP", function() { REGEXP.toString().should.be.eql("/abc/i"); (typeof REGEXP).should.be.eql("object"); if(typeof REGEXP !== "object") require("fail"); }); it("should define OBJECT", function() { var o = OBJECT; o.SUB.FUNCTION(10).should.be.eql(11); }); it("should define OBJECT.SUB.CODE", function() { (typeof OBJECT.SUB.CODE).should.be.eql("number"); OBJECT.SUB.CODE.should.be.eql(3); if(OBJECT.SUB.CODE !== 3) require("fail"); if(typeof OBJECT.SUB.CODE !== "number") require("fail"); (function(sub) { // should not crash sub.CODE.should.be.eql(3); }(OBJECT.SUB)); }); it("should define OBJECT.SUB.STRING", function() { (typeof OBJECT.SUB.STRING).should.be.eql("string"); OBJECT.SUB.STRING.should.be.eql("string"); if(OBJECT.SUB.STRING !== "string") require("fail"); if(typeof OBJECT.SUB.STRING !== "string") require("fail"); (function(sub) { // should not crash sub.STRING.should.be.eql("string"); }(OBJECT.SUB)); }); it("should define process.env.DEFINED_NESTED_KEY", function() { (process.env.DEFINED_NESTED_KEY).should.be.eql(5); (typeof process.env.DEFINED_NESTED_KEY).should.be.eql("number"); if(process.env.DEFINED_NESTED_KEY !== 5) require("fail"); if(typeof process.env.DEFINED_NESTED_KEY !== "number") require("fail"); var x = process.env.DEFINED_NESTED_KEY; x.should.be.eql(5); var indirect = process.env; (indirect.DEFINED_NESTED_KEY).should.be.eql(5); (function(env) { (env.DEFINED_NESTED_KEY).should.be.eql(5); (typeof env.DEFINED_NESTED_KEY).should.be.eql("number"); if(env.DEFINED_NESTED_KEY !== 5) require("fail"); if(typeof env.DEFINED_NESTED_KEY !== "number") require("fail"); var x = env.DEFINED_NESTED_KEY; x.should.be.eql(5); }(process.env)); }); it("should define process.env.DEFINED_NESTED_KEY_STRING", function() { if(process.env.DEFINED_NESTED_KEY_STRING !== "string") require("fail"); })
JavaScript
0
@@ -2604,9 +2604,131 @@ il%22);%0A%7D) +;%0Ait(%22should assign to process.env%22, function() %7B%0A%09process.env.TEST = %22test%22;%0A%09process.env.TEST.should.be.eql(%22test%22);%0A%7D); %0A
59e5600d8e267a7246bdca1a88911427bbe16869
Fix validation message in UpdateHandler Class
lib/updateHandler.js
lib/updateHandler.js
var _ = require('underscore'), async = require('async'), keystone = require('../'), utils = require('./utils'); /** * UpdateHandler Class * * @param {Object} item to update * @api public */ function UpdateHandler(list, item, req) { if (!(this instanceof UpdateHandler)) return new UpdateHandler(list, item); this.list = list; this.item = item; this.req = req; } /** * Processes data from req.body, req.query, or any data source. * * Options: * - fields (comma-delimited list or array of field paths) * - flashErrors (boolean, default false; whether to push validation errors to req.flash) * - ignoreNoedit (boolean, default false; whether to ignore noedit settings on fields) * * @param {Object} data * @param {Object} options (can be comma-delimited list of fields) (optional) * @param {Function} callback (optional) * @api public */ UpdateHandler.prototype.process = function(data, options, callback) { if ('function' == typeof options) { callback = options; options = null; } if (!options) { options = {}; } else if ('string' == typeof options) { options = { fields: options }; } if (!options.fields) { options.fields = _.keys(this.list.fields); } else if ('string' == typeof options.fields) { options.fields = options.fields.split(',').map(function(i) { return i.trim(); }); } var actionQueue = [], validationErrors = {}; var addValidationError = function(path, msg, type) { validationErrors[path] = { name: 'ValidatorError', path: path, message: msg, type: type || 'required' }; } // TODO: The whole progress queue management code could be a lot neater... var progress = (function(err) { if (err) { if (options.logErrors) { console.log('Error saving changes to ' + this.item.list.singular + ' ' + this.item.id + ':'); console.log(err); } callback(err, this); } else if (_.size(validationErrors)) { if (options.flashErrors) { this.req.flash('error', { type: 'ValidationError', title: 'There was a problem saving your changes:', list: _.pluck(validationErrors, 'message') }); } callback({ message: 'Validation failed', name: 'ValidationError', errors: validationErrors }, this); } else if (actionQueue.length) { // TODO: parallel queue handling for cloudinary uploads? actionQueue.pop()(); } else { saveItem(); } }).bind(this); var saveItem = (function() { this.item.save((function(err) { if (err) { if (err.name == 'ValidationError') { // don't log simple validation errors if (options.flashErrors) { this.req.flash('error', { type: 'ValidationError', title: 'There was a problem saving your changes:', list: _.pluck(validationErrors, 'message') }); } } else { if (options.logErrors) { console.log('Error saving changes to ' + this.item.list.singular + ' ' + this.item.id + ':'); console.log(err); } if (options.flashErrors) { this.req.flash('error', 'There was an error saving your changes: ' + err.message + ' (' + err.name + (err.type ? ': ' + err.type : '') + ')'); } } } return callback(err, this); }).bind(this)); }).bind(this); options.fields.forEach(function(path) { var field = this.list.field(path), invalidated = false; if (!field) { throw new Error('UpdateHandler.process called with invalid field path: ' + path); } // skip uneditable fields if (!options.ignoreNoedit && field.noedit) return; // Some field types have custom behaviours switch (field.type) { case 'cloudinaryimage': actionQueue.push(field.getRequestHandler(this.item, this.req, function(err) { if (err && options.flashErrors) { req.flash('error', field.label + ' upload failed - ' + err.message); } progress(err); })); break; case 'password': // passwords should only be set if a value is provided if (!data[field.path]) return; // validate matching password fields if (data[field.path] != data[field.paths.confirm]) { addValidationError(field.path, 'Passwords must match.'); invalidated = true; } break; case 'email': if (data[field.path] && !utils.isEmail(data[field.path])) { addValidationError(field.path, 'Please enter a valid email address in the ' + field.label + ' field.'); invalidated = true; } break; // TODO: Ensure valid format for more field types (dates, numbers, etc) // TODO: This sort of validation should be passed off to the Field Class } // validate required fields, unless they've already been invalidated by field-specific behaviour if (!invalidated && field.required && !field.validateInput(data)) { addValidationError(field.path, field.label + ' is required.'); } field.updateItem(this.item, data); }, this); progress(); } /*! * Export class */ exports = module.exports = UpdateHandler;
JavaScript
0.000005
@@ -2740,35 +2740,29 @@ st: _.pluck( -validationE +err.e rrors, 'mess
84575cf35b00d96ecbcba1f1d009cc5fec49ddaa
Return correct non darwin firewall setting
lib/util/firewall.js
lib/util/firewall.js
'use strict'; /** * Kalabox firewall utility module. * @module kbox.util.firewall */ // Npm modules var _ = require('lodash'); var Promise = require('bluebird'); // Kalabox modules var shell = require('./shell.js'); /** * Gets status of firewall blocking everything. * **ONLY WORKS ON OSX** */ var isBlockingAll = function() { // @todo: Need support for other OS here if (process.platform !== 'darwin') { Promise.resolve(true); } // Set up our OSX command to check this var cmd = '/usr/libexec/ApplicationFirewall/socketfilterfw --getblockall'; // Run our command to check if we are blocking all ports return Promise.fromNode(function(cb) { shell.exec(cmd, cb); }) // Return true if blocked all is disabled .then(function(response) { return (response !== 'Block all DISABLED! \n'); }); }; /** * Gets status of firewall being in an okay state. * **ONLY WORKS ON OSX** * @arg {function} callback - Callback function. * @arg {error} callback.err - Possible error object. * @arg {boolean} callback.isOkay - Boolean result set to true if firewall is * in an okay state. * @example * kbox.util.firewall.isOkay(function(err, isOkay) { * if (err) { * return throw err; * } * console.log('Firewall is in a good state -> ' + isOkay); * }); */ exports.isOkay = function() { // Check if we are blocking all ports return isBlockingAll() // If we aren't then we are good .then(function(isBlockingAll) { return !isBlockingAll; }); };
JavaScript
0.000001
@@ -417,16 +417,23 @@ ) %7B%0A +return Promise. @@ -440,19 +440,20 @@ resolve( -tru +fals e);%0A %7D%0A
bf5cbd8c9fb90bbc4afa512402d444e00c5c4ddb
Move local definitions of the SUT inside 'beforeEach' blocks in order to let the framework handle setup and teardown.
spec/regularity_spec.js
spec/regularity_spec.js
var Regularity = require('../lib/regularity.js'); describe("Regularity", function() { var regularity; beforeEach(function() { regularity = new Regularity(); }); it("is an object constructor", function() { expect(typeof regularity).toBe('object'); }); describe("return from done()", function() { it("is a RegExp instance", function() { expect(regularity.done() instanceof RegExp).toBe(true); }); it ("returns an empty regexp by default", function() { expect(regularity.done()).toEqual(new RegExp()); }); }); describe("escapes regexp special characters", function() { var charactersToBeEscaped = [ '*', '.', '?', '^', '+', '$', '|', '(', ')', '[', ']', '{', '}' ]; charactersToBeEscaped.forEach(function testEscapedChar(character) { it("escapes '" + character + "'", function() { var currentRegex = regularity.append(character).done(); expect(currentRegex.source).toBe("\\" + character); }); }); }); describe("#startWith", function(){ it("matches positive", function(){ var regex = regularity.startWith('a').done(); expect(regex.test('abcde')).toBe(true); }); it("matches negative", function(){ var regex = regularity.startWith('a').done(); expect(regex.test('edcba')).toBe(false); }); }); describe("#endWith", function(){ it("matches positive", function(){ var regex = regularity.endWith('a').done(); expect(regex.test('edcba')).toBe(true); }); it("matches negative", function(){ var regex = regularity.endWith('a').done(); expect(regex.test('abcde')).toBe(false); }); }); describe("#maybe", function(){ it("matches with pattern", function(){ var regex = regularity.maybe('a').done(); expect(regex.test('aaaa')).toBe(true); }); it("matches without pattern", function(){ var regex = regularity.maybe('a').done(); expect(regex.test('bbbb')).toBe(true); }); }); describe("#oneOf", function(){ it("matches with one", function(){ var regex = regularity.oneOf(['a','bb','ccc']).done(); expect(regex.test('addd')).toBe(true); }); it("matches with other", function(){ var regex = regularity.oneOf(['a','bb','ccc']).done(); expect(regex.test('dbb')).toBe(true); }); it("does not match", function(){ var regex = regularity.oneOf(['a','bb','ccc']).done(); expect(regex.test('bccddd')).toBe(true); }); }); describe("#between", function(){ it("doesn't match under lower bound", function(){ var regex = regularity.between([2,3], 'a').done(); expect(regex.test('addd')).toBe(false); }); }); }); // append: [Function], // between: [Function], // zeroOrMore: [Function], // oneOrMore: [Function], // atLeast: [Function], // atMost: [Function], // insensitive: [Function], // global: [Function], // multiLine: [Function], // done: [Function], // regexp: [Function] }
JavaScript
0
@@ -1144,39 +1144,46 @@ -it(%22matches positive%22, +var regex;%0A beforeEach( function @@ -1176,32 +1176,33 @@ eEach(function() + %7B%0A va @@ -1191,36 +1191,32 @@ ) %7B%0A -var regex = regulari @@ -1233,32 +1233,88 @@ th('a').done();%0A + %7D);%0A%0A it(%22matches positive%22, function()%7B%0A expe @@ -1409,66 +1409,8 @@ ()%7B%0A - var regex = regularity.startWith('a').done();%0A @@ -1524,39 +1524,46 @@ -it(%22matches positive%22, +var regex;%0A beforeEach( function @@ -1556,32 +1556,33 @@ eEach(function() + %7B%0A va @@ -1571,36 +1571,32 @@ ) %7B%0A -var regex = regulari @@ -1611,32 +1611,88 @@ th('a').done();%0A + %7D);%0A%0A it(%22matches positive%22, function()%7B%0A expe @@ -1787,64 +1787,8 @@ ()%7B%0A - var regex = regularity.endWith('a').done();%0A @@ -1904,35 +1904,38 @@ -it(%22matches with pattern%22, +var regex;%0A beforeEach( func @@ -1932,32 +1932,33 @@ eEach(function() + %7B%0A va @@ -1947,36 +1947,32 @@ ) %7B%0A -var regex = regulari @@ -1985,32 +1985,107 @@ be('a').done();%0A + %7D);%0A%0A it(%22matches when the pattern is present%22, function()%7B%0A expe @@ -2157,22 +2157,23 @@ es w -ithout +hen the pattern %22, f @@ -2168,16 +2168,30 @@ pattern + isn't present %22, funct @@ -2201,62 +2201,8 @@ ()%7B%0A - var regex = regularity.maybe('a').done();%0A @@ -2316,31 +2316,38 @@ -it(%22matches with one%22, +var regex;%0A beforeEach( func @@ -2344,32 +2344,33 @@ eEach(function() + %7B%0A va @@ -2359,36 +2359,32 @@ ) %7B%0A -var regex = regulari @@ -2410,32 +2410,88 @@ 'ccc'%5D).done();%0A + %7D);%0A%0A it(%22matches with one%22, function()%7B%0A expe @@ -2587,75 +2587,8 @@ ()%7B%0A - var regex = regularity.oneOf(%5B'a','bb','ccc'%5D).done();%0A @@ -2691,75 +2691,8 @@ ()%7B%0A - var regex = regularity.oneOf(%5B'a','bb','ccc'%5D).done();%0A
aeda2f8e5814adcd4bc2cbf1bdb6372fa36b6507
Add @private to all functions in lib/utils
lib/utils.js
lib/utils.js
/* * EJS Embedded JavaScript templates * 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. * */ /** * Private utility functions * @module utils * @private */ 'use strict'; var regExpChars = /[|\\{}()[\]^$+*?.]/g; /** * Escape characters reserved in regular expressions. * * If `string` is `undefined` or `null`, the empty string is returned. * * @param {String} string Input string * @return {String} Escaped string * @static */ exports.escapeRegExpChars = function (string) { // istanbul ignore if if (!string) { return ''; } return String(string).replace(regExpChars, '\\$&'); }; var _ENCODE_HTML_RULES = { '&': '&amp;' , '<': '&lt;' , '>': '&gt;' , '"': '&#34;' , "'": '&#39;' } , _MATCH_HTML = /[&<>\'"]/g; /** * Stringified version of constants used by {@link module:utils.escapeXML}. * * It is used in the process of generating {@link ClientFunction}s. * * @readonly * @type {String} */ exports.escapeFuncStr = 'var _ENCODE_HTML_RULES = {\n' + ' "&": "&amp;"\n' + ' , "<": "&lt;"\n' + ' , ">": "&gt;"\n' + ' , \'"\': "&#34;"\n' + ' , "\'": "&#39;"\n' + ' }\n' + ' , _MATCH_HTML = /[&<>\'"]/g;\n'; /** * Escape characters reserved in XML. * * If `markup` is `undefined` or `null`, the empty string is returned. * * @implements {EscapeCallback} * @param {String} markup Input string * @return {String} Escaped string * @static */ exports.escapeXML = function (markup) { return markup == undefined ? '' : String(markup) .replace(_MATCH_HTML, function(m) { return _ENCODE_HTML_RULES[m] || m; }); }; /** * Copy all properties from one object to another, in a shallow fashion. * * @param {Object} to Destination object * @param {Object} from Source object * @return {Object} Destination object * @static */ exports.shallowCopy = function (to, from) { from = from || {}; for (var p in from) { to[p] = from[p]; } return to; }; /** * Simple in-process cache implementation. Does not implement limits of any * sort. * * @implements Cache * @static */ exports.cache = { _data: {}, set: function (key, val) { this._data[key] = val; }, get: function (key) { return this._data[key]; }, reset: function () { this._data = {}; } };
JavaScript
0
@@ -991,32 +991,44 @@ ring%0A * @static%0A + * @private%0A */%0Aexports.esca @@ -1991,32 +1991,44 @@ ring%0A * @static%0A + * @private%0A */%0Aexports.esca @@ -2429,32 +2429,44 @@ ject%0A * @static%0A + * @private%0A */%0Aexports.shal @@ -2708,16 +2708,28 @@ @static%0A + * @private%0A */%0Aexpo
8efe0819be47ed515b557ad949e75ee15257eece
Fix issue #10
lib/widget-images.js
lib/widget-images.js
var moment = require('moment'), utils = require('./utils'), wu = require('./widget-utils'); var self; var Image = function(screen, showbox, docker) { if (!(this instanceof Image)) return new Image(screen, showbox, docker); self = this; this.showbox = showbox; this.screen = screen; this.docker = docker; this.nodeTable = wu.newListTable(showbox, 0, 0, '100%-2', '50%', ''); setData(); } function setData() { self.docker.listImages((err, images) => { var nodeInfo = [ ['Id', 'Tags', 'Size', 'Created'] ]; images.forEach(s => { var row = []; row.push(s.Id); row.push(s.RepoTags[0].toString()); row.push((s.Size / 1000 / 1000).toFixed(2) + 'MB'); row.push(moment(new Date(s.Created * 1000), 'YYYYMMDD').fromNow()); nodeInfo.push(row); }) self.nodeTable.setData(nodeInfo); self.screen.render(); }) } Image.prototype.show = function() { setData(); this.nodeTable.show(); this.screen.render(); } Image.prototype.hide = function() { this.nodeTable.hide(); this.screen.render(); } module.exports = Image;
JavaScript
0.000011
@@ -577,25 +577,32 @@ sh(s.Id);%0A%09%09 -%09 + row.push(s.R @@ -598,16 +598,82 @@ ow.push( +( +s && s.RepoTags && s.RepoTags.length && s.RepoTags.length %3E 0) ? s.RepoTa @@ -688,16 +688,21 @@ String() + : '' );%0A%09%09%09ro @@ -1124,8 +1124,9 @@ = Image; +%0A
91cf9b353a6aaff57bf23c8f23ccd68439f2ade3
use new compareVersion method
lib/utils.js
lib/utils.js
var os = require('os'), fs = require('fs'), path = require('path'), log = require('./display.js').log, idLenStandard = require('../include/default.js').idLenStandard, verLenStandard = require('../include/default.js').verLenStandard, linkLenStandard = require('../include/default.js').linkLenStandard, sizeLenStandard = require('../include/default.js').sizeLenStandard, npmVerLenStandard = require('../include/default.js').npmVerLenStandard, spareGlobalProperties = require('../include/default.js').spareGlobalProperties, spareEcosystemProperties = require('../include/default.js').spareEcosystemProperties; var message, warning, error, suggestion, example; exports.compareVersions = function(versionA, versionB) { var arrayA = versionA.split('-'), arrayB = versionB.split('-'), mainA = arrayA[0].split('.'), mainB = arrayB[0].split('.'), notSmaller, len = (mainA.length <= mainB.length) ? mainA.length : mainB.length; for (var i = 0; i < len; ++i) { if (parseInt(mainA[i], 10) < parseInt(mainB[i], 10)) { notSmaller = -1; break; } else if (parseInt(mainA[i], 10) > parseInt(mainB[i], 10)) { notSmaller = 1; break; } else if (i === len - 1) { if (mainA.length > mainB.length) { notSmaller = 1; } else if (mainA.length === mainB.length) { if (arrayA.length === arrayB.length === 1) { notSmaller = 0; } else { if (parseInt(arrayA[-1], 10) < parseInt(arrayB[-1], 10)) { notSmaller = -1; break; } else if (parseInt(arrayA[-1], 10) > parseInt(arrayB[-1], 10)) { notSmaller = 1; break; } else { notSmaller = 0; } } } else { notSmaller = -1; } } } return notSmaller; }; exports.normalizeValue = function(value) { var normalValue; if (value === 'true') { normalValue = true; } else if (value === 'false') { normalValue = false; } else if (!value.match(/[a-z][A-Z]/)) { normalValue = parseInt(value, 10); } else { normalValue = value; } return normalValue; }; exports.toMB = function(size) { return ((parseInt(size, 10)/1024/1024).toFixed(2).toString()+'MB'); }; exports.fillSpace = function(type, string, length) { var i, gap, standard; if (type === 'id') { standard = length || idLenStandard; } else if (type === 'version') { standard = length || verLenStandard; } else if (type === 'link') { standard = length || linkLenStandard; } else if (type === 'size') { standard = length || sizeLenStandard; } else if (type === 'npm') { standard = length || npmVerLenStandard; } else { standard = 18; } if (string.length < standard) { gap = standard - string.length; for (i = 0; i < gap; ++i) { string += (' '); } } return string; }; exports.cleanGloalConfig = function(config) { spareGlobalProperties.forEach(function(p) { delete config[p]; }); return config; }; exports.cleanEcosystemConfig = function(config) { spareEcosystemProperties.forEach(function(p) { delete process.config[p]; }); return config; }; exports.removeEcosystem = function(ecosystems, id) { var newEcosystems = []; ecosystems.forEach(function(e) { if (e.id !== id) { newEcosystems = newEcosystems.concat(e); } }); return newEcosystems; };
JavaScript
0
@@ -715,16 +715,28 @@ %7B%0A var + notSmaller, arrayA @@ -787,18 +787,35 @@ it('-'), + %0A + minorA, minorB, mainA = @@ -867,27 +867,16 @@ t('.'), -notSmaller, %0A len = @@ -1414,126 +1414,417 @@ lse -%7B%0A +if (arrayA.length %3E arrayB.length) %7B%0A notSmaller = 1;%0A %7D else if ( -p ar -seInt(arrayA%5B-1%5D, 10) %3C parseInt(arrayB%5B-1%5D, 10)) %7B%0A notSmaller = -1;%0A break; +rayA.length %3C arrayA.length) %7B%0A notSmaller = -1;%0A %7D else %7B%0A minorA = arrayA.reverse()%5B0%5D.replace(/%5Ba-zA-Z%5D+/,'');%0A minorB = arrayB.reverse()%5B0%5D.replace(/%5Ba-zA-Z%5D+/,'');%0A if (minorA.length !== minorB.length) %7B%0A notSmaller = ((minorA.length - minorB.length) %3E 0) ? 1 : -1; %0A @@ -1832,32 +1832,33 @@ %7D else if + (parseInt(arrayA @@ -1855,25 +1855,23 @@ Int( -arrayA%5B-1%5D +minorA , 10) -%3E +=== par @@ -1880,18 +1880,14 @@ Int( -arrayB%5B-1%5D +minorB , 10 @@ -1908,33 +1908,33 @@ notSmaller = -1 +0 ;%0A br @@ -1933,33 +1933,159 @@ - break;%0A %7D else +%7D else if (parseInt(minorA, 10) %3E parseInt(minorB, 10)) %7B%0A notSmaller = 1;%0A %7D else if (parseInt(minorA, 10) %3C parseInt(minorB, 10)) %7B%0A @@ -2100,33 +2100,34 @@ notSmaller = -0 +-1 ;%0A %7D%0A @@ -2141,22 +2141,16 @@ %0A %7D -%0A else %7B%0A @@ -2213,16 +2213,20 @@ Smaller; + %0A%7D;%0A%0Aexp
141a432018fd83d18f5541b142e0d334035c6bc5
update version number
hover_iframe_over_every_youtube_link.user.js
hover_iframe_over_every_youtube_link.user.js
// ==UserScript== // @name pop-up video iframe over every youtube link // @name:ru всплывающее видео при клике на youtube-ссылку // @description to close video press ESC or click on the grey background // @description:ru для закрытия видео нажмите ESC или кликнике на сервый фон вокруг видео // @namespace github.com/totalamd // @match *://*/* // @exclude // @version 1.0.2.1 // @downloadURL https://github.com/totalamd/GM-scripts/raw/master/hover_iframe_over_every_youtube_link.user.js // @updateURL https://github.com/totalamd/GM-scripts/raw/master/hover_iframe_over_every_youtube_link.user.js // @grant none // ==/UserScript== // TODO: // - [ ] fix catching 'esc' keydown event through youtube iframe // - [ ] deal with removing all 'removing' event listeners if any one fired "use strict"; const l = function(){}, i = function(){}; (function(){ // const l = console.log.bind(console, `${GM_info.script.name} debug:`), i = console.info.bind(console, `${GM_info.script.name} debug:`); const LinksList = Array.from(document.querySelectorAll('a')); LinksList.forEach(function(link) { link.addEventListener('click', openIframe); }); function openIframe (e) { let id; if (e.target.hostname.match(/^(?:www\.)youtube\.com$/) && e.target.search.match(/\?v=([\w_-]+)/)) { id = e.target.search.match(/\?v=([\w_-]+)/)[1]; } else if (e.target.hostname.match(/^youtu\.be$/) && e.target.pathname.match(/\/([\w_-]+)/)) { id = e.target.pathname.match(/\/([\w_-]+)/)[1]; } else {return;} l(id); e.preventDefault(); const width = 853; //1280; const height = 480; //720; const hover = document.createElement('div'); const iframe = document.createElement('iframe'); hover.style.position = 'fixed'; hover.style.width = '100%'; hover.style.height = '100%'; hover.style.top = 0; hover.style.left = 0; hover.style.backgroundColor = 'rgba(200, 200, 200, 0.5)'; iframe.src = `//youtube.com/embed/${id}`; iframe.width = width; iframe.height = height; iframe.allowFullscreen = true; iframe.frameBorder = 0; iframe.style.position = 'absolute'; iframe.style.left = window.innerWidth/2 - width/2 + 'px'; iframe.style.top = window.innerHeight/2 - height/2 + 'px'; hover.appendChild(iframe); document.body.appendChild(hover); i('add'); hover.addEventListener('click', function removeIframeClick(e){ document.body.removeChild(hover); i('remove'); hover.removeEventListener('click', removeIframeClick); }); document.addEventListener('keydown', function removeIframeEsc(e){ i(e); if (e.key === "Escape") { document.body.removeChild(hover); i('remove'); document.removeEventListener('click', removeIframeEsc); } }) } }())
JavaScript
0.000002
@@ -433,17 +433,17 @@ 1.0.2. -1 +2 %0D%0A// @do
076a41f2331aaf91130c4bc93a0e8dee2260f8ee
fix blueprint
blueprints/ember-cli-event-calendar/index.js
blueprints/ember-cli-event-calendar/index.js
JavaScript
0.000001
@@ -0,0 +1,91 @@ +module.exports = %7B%0A%09normalizeEntityName: function(entityName) %7B%0A%09%09return entityName;%0A%09%7D%0A%7D;
e07a03b0b5097daee3ce072247922cda3f62b2e3
Fix #145 for password protected pads too
static/js/clientHooks.js
static/js/clientHooks.js
/** * # Client Hooks Module * * ## License * * 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. * * ## Description * * This module contains client-side hooks used by etherpad. * * ## Client Hooks */ 'use strict'; var $ = require('ep_etherpad-lite/static/js/rjquery').$; exports.postToolbarInit = function (hook_name, args) { var params = {}; if (location.search) { var parts = location.search.substring(1).split('&'); for (var i = 0; i < parts.length; i++) { var nv = parts[i].split('='); if (!nv[0]) continue; params[nv[0]] = nv[1] || true; } } var token = params.auth_token; $('#exportColumn .exportlink').each(function(index) { var element = $(this); var link = element.attr('href'); if (link.indexOf('?') !== -1) { element.attr('href', link+'&auth_token='+params.auth_token); } else { element.attr('href', link+'?auth_token='+params.auth_token); } }); $('li[data-key="showTimeSlider"]').unbind('click'); $('li[data-key="showTimeSlider"] a').attr('href', location.pathname+'/timeslider?auth_token='+params.auth_token); var padLoc = location.pathname.replace(new RegExp('/timeslider$'), ''); $('li[data-key="timeslider_returnToPad"]').unbind('click'); $('li[data-key="timeslider_returnToPad"] a').attr('href', padLoc+'?auth_token='+params.auth_token); }
JavaScript
0
@@ -1338,19 +1338,85 @@ %0A%0A -var token = +if (typeof params.auth_token !== 'undefined') %7B%0A updateLinks('auth_token', par @@ -1429,19 +1429,189 @@ th_token +) ;%0A -%0A + %7D else if (typeof params.mypadspassword !== 'undefined') %7B%0A updateLinks('mypadspassword', params.mypadspassword);%0A %7D%0A%0A function updateLinks(parName, parValue) %7B%0A $('#ex @@ -1658,24 +1658,26 @@ ndex) %7B%0A + var element @@ -1684,24 +1684,26 @@ = $(this);%0A%0A + var link @@ -1728,24 +1728,26 @@ ref');%0A%0A + if (link.ind @@ -1764,32 +1764,34 @@ !== -1) %7B%0A + element.attr('hr @@ -1806,41 +1806,35 @@ k+'& -auth_token='+params.auth_token +'+parName+'='+parValue );%0A + @@ -1842,16 +1842,18 @@ else %7B%0A + el @@ -1882,54 +1882,52 @@ k+'? -auth_token='+params.auth_token +'+parName+'='+parValue );%0A + %7D%0A + + %7D);%0A%0A + $( @@ -1968,32 +1968,34 @@ nbind('click');%0A + $('li%5Bdata-key @@ -2065,42 +2065,36 @@ der? -auth_token='+params.auth_token +'+parName+'='+parValue );%0A%0A + va @@ -2159,24 +2159,26 @@ er$'), '');%0A + $('li%5Bdata @@ -2227,16 +2227,18 @@ lick');%0A + $('li%5B @@ -2302,39 +2302,35 @@ c+'? -auth_token='+params.auth_token); +'+parName+'='+parValue);%0A %7D %0A%7D%0A
d19e1f2564941110b1265ae73c3df7bce5c82bba
fix tests for LessonController
test/integration/services/LessonService.test.js
test/integration/services/LessonService.test.js
'use strict'; var should = require('should'); describe('LessonService', function() { let lesson1 = { name: 'serviceTest1Lesson', datetime: new Date().toISOString(), building: 7, classroom: '214', faculty: 'fizmat', groupId: '36' }, lesson2 = { name: 'serviceTest2Lesson', datetime: new Date().toISOString(), building: 0, classroom: '01', faculty: 'fizmat', groupId: '16' }; describe('createLesson()', function() { it('should create lesson1', function (done) { sails.services.lessonservice.createLesson(lesson1, (err, res) => { if(err) { console.log('Error in LessonService.creteLesson()'); } else { delete lesson1.datetime; res.should.containDeep(lesson1); lesson1.id = res.id; } done(); }); }); it('should create lesson2', function (done) { sails.services.lessonservice.createLesson(lesson2, (err, res) => { if(err) { console.log('Error in LessonService.creteLesson()'); } else { delete lesson2.datetime; res.should.containDeep(lesson2); lesson2.id = res.id; } done(); }); }); }); describe('getLessons()', function() { it('should return only lesson1', function (done) { sails.services.lessonservice.getLessons({id: lesson1.id}, (err, res) => { if(err) { console.log('Error in LessonService.getLessons()'); } else { res.should.be.Array(); res.should.have.length(1); res[0].should.containDeep(lesson1); } done(); }); }); it('should return only lesson2', function (done) { sails.services.lessonservice.getLessons({id: lesson2.id}, (err, res) => { if(err) { console.log('Error in LessonService.getLessons()'); } else { res.should.be.Array(); res.should.have.length(1); res[0].should.containDeep(lesson2); } done(); }); }); it('should return lesson1 and lesson2', function (done) { sails.services.lessonservice.getLessons({faculty: 'fizmat'}, (err, res) => { if(err) { console.log('Error in LessonService.getLessons()'); } else { res.should.be.Array(); res.should.containDeep([lesson1, lesson2]); } done(); }); }); }); describe('updateLesson()', function() { it('should update only lesson1', function (done) { lesson1.classroom = '202'; sails.services.lessonservice.updateLesson(lesson1.id, {classroom: lesson1.classroom}, (err, res) => { if(err) { console.log('Error in LessonService.getLessons()'); } else { res.should.be.Array(); res.should.have.length(1); res[0].should.containEql(lesson1); sails.services.lessonservice.getLessons({id: lesson2.id}, (err, res) => { res.should.be.Array(); res.should.have.length(1); res[0].should.containEql(lesson2); done(); }); } }); }); }); describe('subscribeToLesson()', function() { let testSubscriber = { name: 'subscriberName', surname: 'subscriberSurname', email: '[email protected]', role: 'student' }; it('should create test testSubscriber', function (done) { sails.services.userservice.createUser(testSubscriber, (err, res) => { if(err) { err.should.be.Error(); console.log('testSubscriber already created!\n'); } else { res.should.containEql(testSubscriber); testSubscriber.id = res.id; } done(); }); }); it('should subscribe testSubscriber to lesson1', function(done) { sails.services.lessonservice.subscribeToLesson(lesson1.id, testSubscriber.id, (err, lesson) => { if(err) { console.log('Error in LessonService.subscribeToLesson()'); } else { lesson.lessonId.should.equal(lesson1.id); lesson.subscribedBy.should.be.Array(); lesson.subscribedBy.should.have.length(1); lesson.subscribedBy[0].should.containEql(testSubscriber); } done(); }); }); it('should unsubscribe testSubscriber to lesson1', function(done) { sails.services.lessonservice.unsubscribeToLesson(lesson1.id, testSubscriber.id, (err, lesson) => { if(err) { console.log('Error in LessonService.unsubscribeToLesson()'); } else { lesson.lessonId.should.equal(lesson1.id); lesson.subscribedBy.should.be.Array(); lesson.subscribedBy.should.have.length(0); } done(); }); }); it('should remove testSubscriber from database', function (done) { sails.services.userservice.destroyUser({id : testSubscriber.id}, (err, res) => { if(err) { console.log('Error in UserService.destroyUser()'); } else { res.should.be.Array(); res.should.have.length(1); res[0].should.containEql(testSubscriber); } done(); }); }); }); describe('destroyLesson()', function() { it('should remove lesson1 form database', function (done) { sails.services.lessonservice.destroyLesson(lesson1.id, (err, res) => { if(err) { console.log('Error in LessonService.destroyLesson()'); } else { res.should.be.Array(); res.should.have.length(1); res[0].should.containDeep(lesson1); } done(); }); }); it('should remove lesson2 form database', function (done) { sails.services.lessonservice.destroyLesson(lesson2.id, (err, res) => { if(err) { console.log('Error in LessonService.destroyLesson()'); } else { res.should.be.Array(); res.should.have.length(1); res[0].should.containDeep(lesson2); } done(); }); }); }); });
JavaScript
0.000001
@@ -3480,16 +3480,44 @@ l.com',%0A + password: 'password',%0A ro @@ -3709,115 +3709,128 @@ -err.should.be.Error();%0A console.log('testSubscriber already created!%5Cn');%0A %7D%0A else %7B +throw new Error('Error in UserService.createUser()');%0A %7D%0A else %7B%0A delete testSubscriber.password; %0A
aca3a38d0add24957c80b038239c35a3c84a9277
test for #79
test/lib/rules/no-unused-vars/no-unused-vars.js
test/lib/rules/no-unused-vars/no-unused-vars.js
/** * @fileoverview Tests for no-unused-vars rule * @author Raghav Dua <[email protected]> */ 'use strict'; var Solium = require ('../../../../lib/solium'); var wrappers = require ('../../../utils/wrappers'); var toContract = wrappers.toContract; var toFunction = wrappers.toFunction; var userConfig = { "custom-rules-filename": null, "rules": { "no-unused-vars": true } }; describe ('[RULE] no-unused-vars: Acceptances', function () { it ('should accept all variables that are used at least once in the same program', function (done) { var code = [ 'uint x = 100; function foo () returns (uint) { return x; }', 'bytes32 x = "hello"; function foo () returns (bytes32) { return x; }', 'string x = "hello"; function foo () returns (int) { return x; }', 'address x = 0x0; function foo () returns (address) { return x; }', 'mapping (address => uint) x; function foo () returns (mapping) { return x; }' ]; var errors; code = code.map(function(item){return toContract(item)}); errors = Solium.lint (code [0], userConfig); errors.constructor.name.should.equal ('Array'); errors.length.should.equal (0); errors = Solium.lint (code [1], userConfig); errors.constructor.name.should.equal ('Array'); errors.length.should.equal (0); errors = Solium.lint (code [2], userConfig); errors.constructor.name.should.equal ('Array'); errors.length.should.equal (0); errors = Solium.lint (code [3], userConfig); errors.constructor.name.should.equal ('Array'); errors.length.should.equal (0); errors = Solium.lint (code [4], userConfig); errors.constructor.name.should.equal ('Array'); errors.length.should.equal (0); Solium.reset (); done (); }); }); describe ('[RULE] no-unused-vars: Rejections', function () { it ('should reject all variables that haven\'t been used even once', function (done) { var code = [ 'var x = 100;', 'uint x = 100;', 'bytes32 x = "hello";', 'string x = "hello";', 'address x = 0x0;', 'mapping (address => uint) x;' ]; var errors; code = code.map(function(item){return toFunction(item)}); errors = Solium.lint (code [0], userConfig); errors.constructor.name.should.equal ('Array'); errors.length.should.equal (1); errors = Solium.lint (code [1], userConfig); errors.constructor.name.should.equal ('Array'); errors.length.should.equal (1); errors = Solium.lint (code [2], userConfig); errors.constructor.name.should.equal ('Array'); errors.length.should.equal (1); errors = Solium.lint (code [3], userConfig); errors.constructor.name.should.equal ('Array'); errors.length.should.equal (1); errors = Solium.lint (code [4], userConfig); errors.constructor.name.should.equal ('Array'); errors.length.should.equal (1); errors = Solium.lint (code [5], userConfig); errors.constructor.name.should.equal ('Array'); errors.length.should.equal (1); Solium.reset (); done (); }); });
JavaScript
0.000038
@@ -1667,24 +1667,452 @@ equal (0);%0A%0A +%09%09Solium.reset ();%0A%09%09done ();%0A%09%7D);%0A%0A%09it ('should accept if the variable%5C's usage occurs above its declaration & definition.', function (done) %7B%0A%09%09var code = 'contract Owned %7B%5Cnfunction setOwner(address _new) onlyOwner %7B NewOwner(owner, _new); owner = _new; %7D%5Cnaddress public owner = msg.sender;%7D',%0A%09%09%09errors = Solium.lint (code, userConfig);%0A%0A%09%09errors.constructor.name.should.equal ('Array');%0A%09%09errors.length.should.equal (0);%0A%0A %09%09Solium.res
e60e67c9511836c58c82555e1696c9430c7bfeb2
Fix grammar again
lib/value.js
lib/value.js
'use strict'; /* Value.js * Object to represent CSS Values. */ module.exports = exports = Value; function Value(val, unit){ if (!(this instanceof Value)) return new Value(val, unit); this.val = val; this.unit = unit || null; } Value.prototype.compareUnits = function(otherValue){ if (!(otherValue instanceof Value)) { return new TypeError('otherValue must be a Value'); } // Used for cases where there is no unit // e.g. "100% * 3" or "(10 * 5)px" if (otherValue.unit === null) otherValue.unit = this.unit; return otherValue.unit === this.unit; }; Value.prototype._operation = function(otherValue, callback){ if (typeof otherValue === 'number') otherValue = new Value(otherValue, this.unit); let check = this.compareUnits(otherValue); if (this.unit === null || otherValue.unit === null) return new Value(0); if (check) return new Value(callback(otherValue), this.unit); else try { otherValue = otherValue.convert(this.unit); return new Value(callback(otherValue), this.unit); } catch (e) { throw new TypeError('values must be have same or convertable units'); } }; Value.prototype.plus = Value.prototype.add = function(otherValue){ return this._operation(otherValue, (otherValue) => this.val + otherValue.val); }; Value.prototype.minus = Value.prototype.subtract = function(otherValue){ return this._operation(otherValue, (otherValue) => this.val - otherValue.val); }; Value.prototype.times = Value.prototype.multiply = function(otherValue) { return this._operation(otherValue, (otherValue) => this.val * otherValue.val); }; Value.prototype.divide = function(otherValue){ return this._operation(otherValue, (otherValue) => this.val / otherValue.val); }; Value.prototype.equals = Value.prototype.compare = function(otherValue){ return this.compareUnits(otherValue) && (this.val === otherValue.val); }; Value.prototype.convert = function(unit, options){ if (!options) options = {}; let dpi = options.dpi || 96; // Pixels to inches if ( this.unit === 'px' && unit === 'in' ) return new Value(this.val / dpi, 'in'); // Inches to Pixels else if ( this.unit === 'in' && unit === 'px' ) return new Value(this.val * dpi, 'px'); else { throw new TypeError('invalid value conversion'); } }; Value.prototype.serialize = function(){ return this.val + this.unit; };
JavaScript
0.000164
@@ -1099,20 +1099,20 @@ ertable -unit +type s');%0A %7D
7863fbf16a7a8db8445b639a7dcf03bf0251a79c
Update Unit Test
test/purchasing/purchase-order/report/report.js
test/purchasing/purchase-order/report/report.js
require("should"); var helper = require("../../../helper"); var purchaseRequestDataUtil = require('../../../data').purchasing.purchaseRequest; var validatePR = require("dl-models").validator.purchasing.purchaseRequest; var PurchaseRequestManager = require("../../../../src/managers/purchasing/purchase-request-manager"); var purchaseRequestManager = null; var purchaseRequest; var generateCode = require('../../../../src/utils/code-generator'); var purchaseOrderDataUtil = require('../../../data').purchasing.purchaseOrder; var validatePO = require("dl-models").validator.purchasing.purchaseOrder; var PurchaseOrderManager = require("../../../../src/managers/purchasing/purchase-order-manager"); var purchaseOrderManager = null; var purchaseOrder; var purchaseOrders=[]; var purchaseRequests=[]; var purchaseRequestsPosted=[]; var purchaseOrderExternalDataUtil = require('../../../data').purchasing.purchaseOrderExternal; var validatePO = require("dl-models").validator.purchasing.purchaseOrderExternal; var PurchaseOrderExternalManager = require("../../../../src/managers/purchasing/purchase-order-external-manager"); var purchaseOrderExternalManager = null; var purchaseOrderExternal; before('#00. connect db', function(done) { helper.getDb() .then(db => { purchaseRequestManager = new PurchaseRequestManager(db, { username: 'dev' }); purchaseOrderManager = new PurchaseOrderManager(db, { username: 'dev' }); purchaseOrderExternalManager = new PurchaseOrderExternalManager(db, { username: 'dev' }); done(); }) .catch(e => { done(e); }); }); // var kodeUnik; // var PO; // it('#02. should success when create 20 data PO', function (done) { // var data = []; // var datepr = new Date(); // var tasks=[]; // kodeUnik = generateCode(); // for (var i = 0; i < PR.length; i++) { // var po = purchaseOrderDataUtil.getNew(PR[i]); // data.push(po); // } // Promise.all(data) // .then((result) => { // for (var i = 0; i < PR.length; i++) { // result[i].remark=kodeUnik; // result[i].date= datepr.setDate(datepr.getDate() - (i*2)); // tasks.push(purchaseOrderManager.update(result[i])); // } // PO=result; // Promise.all(tasks) // .then(result => { // resolve(result); // }) // .catch(e => { // done(e); // }); // done(); // }).catch(e => { // done(e); // }); // }); it('#01. should success when create 20 PO External data', function (done) { var data = []; for (var i = 0; i < 20; i++) { purchaseOrderExternalDataUtil.getPosted().then( poe=>{ data.push(poe); } ) } Promise.all(data) .then((result) => { done(); }).catch(e => { done(e); }); }); it('#02. should success when get data report PO Per Unit Per Category', function (done) { purchaseOrderManager.getDataPOUnitCategory() .then(po => { po.should.instanceof(Array); done(); }).catch(e => { done(e); }); }); it('#03. should success when get data report PO Per Unit', function (done) { purchaseOrderManager.getDataPOUnit() .then(po => { po.should.instanceof(Array); done(); }).catch(e => { done(e); }); }); it('#04. should success when get data report Per Category', function (done) { purchaseOrderManager.getDataPOCategory() .then(po => { po.should.instanceof(Array); done(); }).catch(e => { done(e); }); }); var startDate=new Date(); var endDate=new Date(); it('#05. should success when get data report PO Per Unit Per Category with date', function (done) { purchaseOrderManager.getDataPOUnitCategory(startDate,endDate) .then(po => { po.should.instanceof(Array); done(); }).catch(e => { done(e); }); }); it('#06. should success when get data report PO Per Unit with date', function (done) { purchaseOrderManager.getDataPOUnit(startDate,endDate) .then(po => { po.should.instanceof(Array); done(); }).catch(e => { done(e); }); }); it('#07. should success when get data report Per Category with date', function (done) { purchaseOrderManager.getDataPOCategory(startDate,endDate) .then(po => { po.should.instanceof(Array); done(); }).catch(e => { done(e); }); });
JavaScript
0
@@ -4927,28 +4927,308 @@ done(e);%0A %7D);%0A%0A%7D); +%0A%0Ait('#08. should success when get data report Per Supplier with date', function (done) %7B%0A purchaseOrderManager.getDataPOSupplier(startDate,endDate)%0A .then(po =%3E %7B%0A po.should.instanceof(Array);%0A done();%0A %7D).catch(e =%3E %7B%0A done(e);%0A %7D);%0A%0A%7D);