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
c881a7f7a3c3cbc7729a3dfaf3e60f202a4a51e8
Add user-agent info to env
lib/env.js
lib/env.js
'use strict'; /** * lib **/ /*global nodeca, _*/ // 3rd-party var Puncher = require('puncher'); //////////////////////////////////////////////////////////////////////////////// var tzOffset = (new Date).getTimezoneOffset(); //////////////////////////////////////////////////////////////////////////////// /** * lib.env(options) -> Object * - options (Object): Environment options. * * Create new request environment object. * * * ##### Options * * - **http**: HTTP origin object that contains `req` and `res`. * - **rpc**: API3 (Ajax) origin that contains `req` and `res`. * - **skip**: Array of middlewares to skip * - **session**: Session object * - **method**: Name of the server method, e.g. `'forums.posts.show'` * - **layout**: Layout name as String **/ module.exports = function env(options) { var ctx = { extras: { puncher: new Puncher() }, helpers: { asset_path: function asset_path(path) { var asset = nodeca.runtime.assets.manifest.assets[path]; return !asset ? "#" : nodeca.runtime.router.linkTo('assets', { path: asset }); } }, origin: { http: options.http, rpc: options.rpc }, skip: (options.skip || []).slice(), session: options.session || null, request: { // FIXME: should be deprecated in flavour of env.origin origin: !!options.rpc ? 'RPC' : 'HTTP', method: options.method, ip: (options.http || options.rpc).req.connection.remoteAddress, namespace: String(options.method).split('.').shift() }, data: {}, runtime: { // FIXME: must be set from cookies theme: 'desktop' }, response: { data: { head: { title: null, // should be filled with default value apiPath: options.method, // List of assets for yepnope, // Each element is an object with properties: // // type: css|js // link: asset_url // // example: assets.push({type: 'js', link: '//example.com/foo.js'}); assets: [] }, menus: {}, widgets: {} }, headers: {}, // Layouts are supporting "nesting" via `dots: // // default.blogs // // In the example above, `default.blogs` will be rendered first and the // result will be provided for rendering to `default`. layout: options.layout || 'default', // Default view template name == server method name // One might override this, to render different view // view: options.method } }; // // env-dependent helper needs to be bounded to env // ctx.helpers.t = function (phrase, params) { var locale = this.runtime.locale || nodeca.config.locales['default']; return nodeca.runtime.i18n.t(locale, phrase, params); }.bind(ctx); ctx.helpers.date = function (value, format) { var locale = this.runtime.locale || nodeca.config.locales['default']; return nodeca.shared.common.date(value, format, locale, tzOffset); }.bind(ctx); return ctx; };
JavaScript
0.000002
@@ -836,16 +836,63 @@ ions) %7B%0A + var req = (options.http %7C%7C options.rpc).req;%0A var ct @@ -1507,66 +1507,81 @@ -(options.http %7C%7C options.rpc).req.connection.remoteAddress +req.connection.remoteAddress,%0A user_agent: req.headers%5B'user-agent'%5D ,%0A
444f5b2a29f2c43ecfa3313de1776ef7016a7047
add separation between selector blocks
lib/css2stylus.js
lib/css2stylus.js
(function (window) { // use global as window in node if (typeof global === 'object' && global && global.global === global) { window = global; } var Css2Stylus = { // constructor Converter: function (css) { this.css = css || ''; this.output = ''; return this; } }; Css2Stylus.Converter.prototype = Css2Stylus.prototype = { // default options options: { // possible indent values: 'tab' or number (of spaces) indent: 2, cssSyntax: false, openingBracket: '', closingBracket: '', semicolon: '', eol: '' }, processCss: function (options) { if (!this.css) { return this.css; } options = options || {}; if (options.indent) { this.options.indent = options.indent; } // keep css punctuation if (options.cssSyntax === true) { this.options.openingBracket = '{'; this.options.closingBracket = '}'; this.options.semicolon = ':'; this.options.eol = ';'; } // indentation if (this.options.indent === 'tab') { this.indentation = '\t'; } else { this.indentation = this.repeat(' ', this.options.indent); } // actualy parse css this.parse(); return this; }, parse: function () { var tree = { children: {} }, self = this; this.css // remove comments .replace(/\/\*[\s\S]*?\*\//gm, '') // process each css block .replace(/([^{]+)\{([^}]+)\}/g, function (group, selector, declaration) { var i, l, _sel, path = tree, selectors; selector = self.trim(selector); // skip grouped selector if (/,/.test(selector)) { path = self.addRule(path, selector); // process } else { // join special chars to prevent from breaking them into parts selector = selector.replace(/\s*([>\+~])\s*/g, ' &$1').replace(/(\w)([:\.])/g, '$1 &$2'); // split on spaces to get full selector path selectors = selector.split(/[\s]+/); for (i = 0, l = selectors.length; i < l; i++) { // fix back special chars _sel = selectors[i].replace(/&(.)/g, '& $1 ').replace(/& ([:\.]) /g, '&$1'); path = self.addRule(path, _sel); } } declaration.replace(/([^:;]+):([^;]+)/g, function (_declaration, property, value) { path.declarations.push({ property: self.trim(property), value: self.trim(value) }); }); }); this.output = this.generateOutput(tree); }, addRule: function (path, selector) { return (path.children[selector] = path.children[selector] || { children: {}, declarations: [] }); }, depth: 0, generateOutput: function (tree) { var output = '', key, j, l, declarations, declaration; for (key in tree.children) { if (tree.children.hasOwnProperty(key)) { output += this.getIndent() + key + (this.options.openingBracket ? ' ' + this.options.openingBracket : '') + '\n'; this.depth++; declarations = tree.children[key].declarations; for (j = 0, l = declarations.length; j < l; j++) { declaration = declarations[j]; output += this.getIndent() + declaration.property + this.options.semicolon + ' ' + declaration.value + this.options.eol + '\n'; } output += this.generateOutput(tree.children[key]); this.depth--; output += this.getIndent() + this.options.closingBracket + '\n' + (this.depth === 0 ? '$n' : ''); } } // remove blank lines (http://stackoverflow.com/a/4123442) output = output.replace(/^\s*$[\n\r]{1,}/gm, '').replace(/\$n/g, '\n'); return output; }, // calculate correct indent getIndent: function () { return this.repeat(this.indentation, this.depth); }, // returns stylus output getStylus: function () { return this.output; }, // string helpers trim: function (str) { // trim tabs and spaces return str.replace(/\t+/, ' ').replace(/^\s+|\s+$/g, ''); }, // repeat same string n times repeat: function (str, n) { n = window.parseInt(n, 10); return new Array(n + 1).join(str); } }; // expose to global window.Css2Stylus = Css2Stylus; // expose as node module if (typeof module === 'object' && module && module.exports === exports) { module.exports = Css2Stylus; // expose as an AMD module } else if (typeof window.define === 'function' && window.define.amd) { window.define('css2stylus', [], function () { return window.Css2Stylus; }); } }).call(this, this);
JavaScript
0.000001
@@ -2994,17 +2994,115 @@ laration -; +,%0A openingBracket = (this.options.openingBracket ? ' ' + this.options.openingBracket : '');%0A %0A%0A @@ -3228,78 +3228,22 @@ y + -(this.options.openingBracket ? ' ' + this.options.openingBracket : '') +openingBracket + ' @@ -3940,16 +3940,37 @@ g, '%5Cn') +//.replace(/%5Cn$/, '') ;%0A%0A
04af36f9e8adf7cfbce8d71c3d31d81a1659aa22
add react route to show the start of Onboard
web-app/src/index.js
web-app/src/index.js
/* global document, window */ import React from 'react'; import { render } from 'react-dom'; import { BrowserRouter as Router, Switch, Route, Redirect } from 'react-router-dom'; import { createStore, applyMiddleware } from 'redux'; import { Provider } from 'react-redux'; import thunk from 'redux-thunk'; import rootReducer from './reducers'; import App from './components/App'; import Login from './components/Login'; import LoginCallback from './components/Login/LoginCallback'; import StartScreen from './components/StartScreen'; import ResetPassword from './components/ResetPassword'; import SignUp from './components/SignUp'; import NotFound from './components/NotFound'; import './index.css'; const configureStore = () => { if (process.env.NODE_ENV === 'production') { return createStore(rootReducer, applyMiddleware(thunk)); } return createStore( rootReducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(), // eslint-disable-line applyMiddleware(thunk), ); }; const isAuthenticated = () => { const token = window.localStorage.getItem('jwt.token'); if (window.location.pathname.startsWith('/') && !token) { return <Route exact path="/" component={StartScreen} />; } if (token === null || token === undefined) { return <Redirect to="/" />; } return <App />; }; const Root = () => ( <Provider store={configureStore()}> <Router> <Switch> <Route exact path="/login" component={Login} /> <Route exact path="/login/callback/facebook/:token" component={LoginCallback} /> <Route exact path="/reset-password" component={ResetPassword} /> <Route exact path="/sign-up" component={SignUp} /> {isAuthenticated()} <Route component={NotFound} /> </Switch> </Router> </Provider> ); render(<Root />, document.getElementById('root'));
JavaScript
0
@@ -671,16 +671,60 @@ tFound'; +%0Aimport OnBoard from './components/OnBoard'; %0A%0Aimport @@ -1384,24 +1384,75 @@ App /%3E;%0A%7D;%0A%0A +// TODO: need to think about the onboarding url's%0A%0A const Root = @@ -1799,24 +1799,82 @@ =%7BSignUp%7D /%3E +%0A %3CRoute exact path=%22/start%22 component=%7BOnBoard%7D /%3E %0A%0A %7Bi
4a501906241c2781ee6d791475216d74703aa417
Fix bug where spec config used wrong name.
lib/decorators.js
lib/decorators.js
import App from "./App"; import SpecConfig from "./Registry"; // We can use a registry for the spec config. export function inject(...args) { return (target) => { target.inject = args; // Provide IOC framework with a place to find out what to inject. }; } var makePropInject = (getPropTarget) => (...nameOfRoles) => { var roles = nameOfRoles.map((nameOfRole) => { var property; if (Array.isArray(nameOfRole)) { [nameOfRole, property] = nameOfRole; } else { property = nameOfRole; } return { property, nameOfRole }; }); return (target) => { target = getPropTarget(target); roles.forEach(({ property, nameOfRole }) => { Object.defineProperty(target, property, { get() { return App.instance().bootstrapper.container[nameOfRole]; } }); }); }; }; export var propInject = makePropInject((target) => target.prototype); export var staticPropInject = makePropInject((target) => target); export function logger(ns) { return (target) => { Object.defineProperty(target.prototype, "logger", { get() { return App.logger(ns); } }); }; } var specConfigs = Object.create(null); export function component(name, metadata = {}) { return (target) => { metadata.name = name; Object.defineProperty(target.prototype, "metadata", { get() { return metadata; } }); Object.defineProperty(target.prototype, "config", { get() { return App.config; } }); target.prototype.createSpecConfig = function (name) { return this.addSpecConfig(new SpecConfig(name)); }; target.prototype.addSpecConfig = function (config) { specConfigs[name] = config; return config; }; target.prototype.specConfig = function (name) { return specConfigs[name]; }; }; }
JavaScript
0
@@ -1920,24 +1920,31 @@ specConfigs%5B +config. name%5D = conf
ec0bb60381ee8be26a4b76240733bfa453bbc83c
Fix chopped off data for twelve hours
ui/src/components/metric/close-button.js
ui/src/components/metric/close-button.js
const React = require('react'); const Styled = require('styled-components'); const fns = require('../../shared/functions'); const constants = require('../../shared/constants'); const CloseIcon = require( '!babel!svg-react!./close.svg?name=CloseIcon' ); const { default: styled } = Styled; const { remcalc } = fns; const { colors } = constants; const StyledButton = styled.button` position: relative; display: flex; margin: 0; padding: ${remcalc(18)} ${remcalc(24)}; color: ${colors.brandPrimaryColor}; float: right; background-color: ${colors.brandPrimaryDark}; line-height: 1.5; border: none; border-left: solid ${remcalc(1)} ${colors.brandPrimaryDarkest}; cursor: pointer; `; const StyledIcon = styled(CloseIcon)` fill: ${colors.brandPrimaryColor}; `; const AddMetricButton = ({ onClick }) => { const onButtonClick = (e) => onClick(); return ( <StyledButton name='close-button' onClick={onButtonClick} > <StyledIcon /> </StyledButton> ); }; AddMetricButton.propTypes = { onClick: React.PropTypes.func, }; module.exports = AddMetricButton;
JavaScript
0.000003
@@ -210,16 +210,23 @@ '!babel +-loader !svg-rea @@ -227,16 +227,23 @@ vg-react +-loader !./close
d6ce6e9022157b2b0995abe95b0a0580cde6481e
Update deployment.js
lib/deployment.js
lib/deployment.js
var exec = require('child_process').exec, fs = require('fs'); module.exports = function(dir, config, callback) { var env = process.env; env['REGI_HOST'] = config.host env['REGI_USER'] = config.user env['REGI_PASSWD'] = config.pass var options = {cwd: dir, env: env}; //fs.renameSync(dir + "/" + config.root, dir + "/tmp"); //fs.mkdirSync(dir + "/" + config.root); console.log("regi.exe create workspace") exec("regi.exe create workspace --force", options, function(err, stdout, stderr) { exec("regi.exe resolve package " + config.root + " --with=local", options, function(err, stdout, stderr) { console.log(err, stdout, stderr) console.log("regi track") exec("regi.exe track " + config.root, options, function(err, stdout, stderr) { console.log(err, stdout, stderr) console.log("regi commit") exec("regi.exe commit", options, function(err, stdout, stderr) { console.log(err, stdout, stderr) console.log("regi activate") exec("regi.exe activate", options, function(err, stdout, stderr) { console.log(err, stdout, stderr) callback(null, "deployed to " + config.host); }); }); }); }); }); };
JavaScript
0.000001
@@ -524,12 +524,11 @@ e re -solv +bas e pa @@ -552,26 +552,8 @@ root - + %22 --with=local%22 , op
6772aedb8d91d0d34c30bb7e28e9c39112ab79b0
update documentation. and use breaks not returns.
lib/gatherPass.js
lib/gatherPass.js
// The Jikken Shading Language Transpiler // // Copyright (c) 2017 Jeffrey Hutchinson // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. var tokenList = require('./tokens'); module.exports.gatherPass = (_lexFN) => { function lexFN() { var lex = _lexFN(); console.log(lex); return lex; } var inputData = {}; var outputData = {}; var uniforms = []; var lex = lexFN(); function skipNewLines() { while (lex.lookAhead.token === tokenList.NEW_LINE) lex = lexFN(); } function getIdentifier() { // Make sure the lookAhead token is an identifier. if (lex.lookAhead.token !== tokenList.IDENTIFIER) { console.log("Syntax error. Must have token " + lex.nextToken.identifier + " be followed by an Identifier"); return null; } // Get identifier lex = lexFN(); var identifier = lex.nextToken.identifier; // Skip new lines. skipNewLines(); return identifier; } function getAttribute() { var attribute = {}; lex = lexFN(); if (lex.nextToken.token !== tokenList.RESERVED_WORD || lex.nextToken.identifier !== 'attribute') { console.log("Syntax error. Must have attribute declared for input type."); return null; } // Skip ( lex = lexFN(); if (lex.nextToken.token !== tokenList.LEFT_PAREN) { console.log("Syntax error. Must have ( after attribute."); return null; } // get location lex = lexFN(); if (lex.nextToken.token !== tokenList.RESERVED_WORD || lex.nextToken.identifier !== 'location') { console.log("Syntax error. Must have location as part of attribute."); return null; } lex = lexFN(); if (lex.nextToken.token !== tokenList.ASSIGNMENT_OP || lex.nextToken.op !== '=') { console.log("Syntax error. Must have assignment after location."); return null; } lex = lexFN(); var location = null; if (!(lex.nextToken.token === tokenList.IDENTIFIER || lex.nextToken.token === tokenList.SPECIAL)) { console.log("Syntax error. Must have identifier after assignment for location."); return null; } location = lex.nextToken.identifier; // check for ) lex = lexFN(); if (lex.nextToken.token !== tokenList.RIGHT_PAREN) { console.log("Syntaex error. Must have ) after ending of attribute."); return null; } attribute.location = location; return attribute; } for (; lex != null; lex = lexFN()) { switch (lex.nextToken.token) { case tokenList.RESERVED_WORD: var identifier; switch (lex.nextToken.identifier) { case 'in': if ((identifier = getIdentifier()) === null) return null; inputData.name = identifier; inputData.attributeList = []; lex = lexFN(); if (lex.nextToken.token !== tokenList.LEFT_BRACE) { console.log("Syntax error. Must have token '{' after IDENTIFIER within an input layout."); return null; } // Skip new lines. skipNewLines(); // Get attribute list. do { var attribute = getAttribute(); if (attribute === null) return; // Get type. and then name. lex = lexFN(); if (lex.nextToken.token !== tokenList.TYPE) { console.log("Syntax error. Must have a type qualifier follow attribute."); return null; } var typeName = lex.nextToken.identifier; lex = lexFN(); if (lex.nextToken.token !== tokenList.IDENTIFIER) { console.log("Syntax error. Must have an identifier after type."); return null; } var name = lex.nextToken.identifier; // check for ; lex = lexFN(); if (lex.nextToken.token !== tokenList.TERMINATOR) { console.log("Syntax error. Must have a ; after name of attribute declaration."); return null; } // Shove a new attribute onto the list. inputData.attributeList.push({ 'location': attribute.location, 'type': typeName, 'name': name }); // skip new lines. skipNewLines(); } while (lex.lookAhead.token !== tokenList.RIGHT_BRACE); break; case 'out': //if ((identifier = getIdentifier()) === null) //return; break; case 'UniformBuffer': //if ((identifier = getIdentifier()) === null) //return; break; case 'uniform': //if ((identifier = getIdentifier()) === null) //return; break; } break; } } console.log("InputData: "); console.log(inputData); return { 'inputData': inputData, 'outputData': outputData, 'uniforms': uniforms }; };
JavaScript
0
@@ -3476,16 +3476,116 @@ e 'in':%0A +%09%09%09%09%09%09// If it doesn't have an identifier right after,it's not an%0A%09%09%09%09%09%09// input layout. Just stop.%0A %09%09%09%09%09%09if @@ -3634,27 +3634,21 @@ %0A%09%09%09%09%09%09%09 +b re -turn null +ak ;%0A%0A%09%09%09%09%09 @@ -5201,38 +5201,37 @@ null)%0A%09%09%09%09%09%09%09// +b re -turn +ak ;%0A%09%09%09%09%09%09break;%0A%09 @@ -5310,38 +5310,37 @@ null)%0A%09%09%09%09%09%09%09// +b re -turn +ak ;%0A%09%09%09%09%09%09break;%0A%09 @@ -5421,22 +5421,21 @@ %09%09%09%09%09%09// +b re -turn +ak ;%0A%09%09%09%09%09%09
ab8009cfabf37ccecac99ca7eb545d336e059c30
Add vertices start
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 libs var request = require('request'); var assert = require('assert'); var _ = require('underscore'); // Global var gds; // Init module.exports = exports = gds = function init(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'); return { vertices: vertices } }
JavaScript
0.000092
@@ -963,16 +963,47 @@ lid');%0A%0A + // vertices%0A var vertices;%0A%0A return
bc474e3c2f9d25b0d873b787e9cb79f38e6027f4
Add I2C read method
lib/i2c.js
lib/i2c.js
var fs = require('fs'); var ioctl = require('ioctl'); var I2C_SLAVE_FORCE = 0x0706; function I2C(bus, address) { this._bus = bus; this._address = address; this._fd = null; } I2C.prototype.open = function(callback) { fs.open('/dev/i2c-' + this._bus, 'r+', function(err, fd) { if (err) { return callback(err); } this._fd = fd; try { ioctl(this._fd, I2C_SLAVE_FORCE, this._address); } catch (e) { return callback(e); } callback(); }.bind(this)); }; I2C.prototype.write = function(address, value, callback) { var buffer = Buffer.concat([ new Buffer([address]), value ]); fs.write(this._fd, buffer, 0, buffer.length, callback); }; I2C.prototype.close = function(callback) { fs.close(this._fd, callback); }; module.exports = I2C;
JavaScript
0.000013
@@ -696,24 +696,332 @@ lback);%0A%7D;%0A%0A +I2C.prototype.read = function(address, size, callback) %7B%0A this.write(address, new Buffer(0), function(err) %7B%0A if (err) %7B%0A return callback(err);%0A %7D%0A%0A fs.read(this._fd, new Buffer(size), 0, size, null, function(err, bytesRead, buffer) %7B%0A callback(err, buffer);%0A %7D);%0A %7D.bind(this));%0A%7D;%0A%0A I2C.prototyp
c3add54fbdb9082d983300795950b0281e8ac766
fix SR meta registration and add docblocks
lib/kafka-avro.js
lib/kafka-avro.js
/* * kafka-avro * Node.js bindings for librdkafka with Avro schema serialization. * https://github.com/waldo/kafka-avro * * Copyright © Waldo, Inc. * Licensed under the MIT license. */ var url = require('url'); var EventEmitter = require('events').EventEmitter; var Promise = require('bluebird'); var cip = require('cip'); var axios = require('axios'); var avro = require('avsc'); var Kafka = require('node-rdkafka'); // // Mixins // var Producer = require('./kafka-producer'); var Consumer = require('./kafka-consumer'); var CeventEmitter = cip.cast(EventEmitter); /** * @fileOverview bootstrap and master exporing module. */ /** * The master module. * * @param {Object} opts The options. * @constructor */ var KafkaAvro = module.exports = CeventEmitter.extend(function(opts) { /** @type {string} The SR url */ this.kafkaBrokerUrl = opts.kafkaBroker; /** @type {string} The SR url */ this.schemaRegistryUrl = opts.schemaRegistry; /** @type {boolean} Indicates if we se/deserialize with MAGIC BYTE */ this.hasMagicByte = !!opts.hasMagicByte; /** * A dict containing all the value schemas with key the bare topic name and * value the instance of the "avsc" package. * * @type {Object} */ this.valueSchemas = {}; /** * A dict containing all the key schemas with key the bare topic name and * value the instance of the "avsc" package. * * @type {Object} */ this.keySchemas = {}; }); /** * Expose the node-rdkafka library's CODES constants. * * @type {Object} */ KafkaAvro.CODES = Kafka.CODES; // // Add Mixins // KafkaAvro.mixin(Producer); KafkaAvro.mixin(Consumer); /** * Initialize the library, fetch schemas and register them locally. * * @return {Promise(Array.<Object>)} A promise with the registered schemas. */ KafkaAvro.prototype.init = Promise.method(function () { return this._fetchAllSchemaTopics() .bind(this) .map(this._fetchSchema, {concurrency: 10}) .map(this._registerSchema); }); /** * Fetch all registered schema topics from SR. * * @return {Promise(Array.<string>)} A Promise with an arrray of string topics. * @private */ KafkaAvro.prototype._fetchAllSchemaTopics = Promise.method(function () { var fetchAllTopicsUrl = url.resolve(this.schemaRegistryUrl, '/subjects'); return Promise.resolve(axios.get(fetchAllTopicsUrl)) .bind(this) .then((response) => { console.log('KafkaAvro :: Fetched total schemas:', response.data.length); return response.data; }) .catch(this._handleAxiosError); }); /** * Fetch a single schema from the SR and return its value along with metadata. * * @return {Promise(Array.<Object>)} A Promise with an array of objects, * see return statement bellow for return schema. * @private */ KafkaAvro.prototype._fetchSchema = Promise.method(function (schemaTopic) { var parts = schemaTopic.split('-'); var schemaType = parts.pop(); var topic = parts.join('-'); var fetchSchemaUrl = url.resolve(this.schemaRegistryUrl, '/subjects/' + schemaTopic + '/versions/latest'); return Promise.resolve(axios.get(fetchSchemaUrl)) .then((response) => { return { schemaType: schemaType, schemaTopicRaw: schemaTopic, topic: topic, schemaRaw: response.data, }; }) .catch(this._handleAxiosError); }); /** * Register the schema locally using avro. * * @return {Promise(Array.<Object>)} A Promise with the object received * augmented with the "type" property which stores the parsed avro schema. * @private */ KafkaAvro.prototype._registerSchema = Promise.method(function (schemaObj) { try { schemaObj.type = avro.parse(schemaObj.schemaRaw.schema, {wrapUnions: true}); } catch(ex) { console.error('KafkaAvro :: Error parsing schema:', schemaObj.schemaTopicRaw, 'Error:', ex.message); } if (schemaObj.schemaType.toLowerCase() === 'value') { this.valueSchemas[schemaObj.topic] = schemaObj.type; } else { this.keySchemas[schemaObj.topic] = schemaObj.type; } return schemaObj; }); KafkaAvro.prototype._handleAxiosError = function (err) { if (!err.port) { // not an axios error, bail early throw err; } console.error('KafkaAvro :: http error:', err.message, 'Url:', err.config.url); throw err; };
JavaScript
0
@@ -1441,16 +1441,428 @@ as = %7B%7D; +%0A%0A /**%0A * A dict containing all the value schemas metadata, with key the bare%0A * topic name and value the SR response on that topic:%0A *%0A * 'subject' %7Bstring%7D The full topic name, including the '-value' suffix.%0A * 'version' %7Bnumber%7D The version number of the schema.%0A * 'id' %7Bnumber%7D The schema id.%0A * 'schema' %7Bstring%7D JSON serialized schema.%0A *%0A * @type %7BObject%7D%0A */%0A this.schemaMeta = %7B%7D; %0A%7D);%0A%0A/* @@ -3562,16 +3562,52 @@ eturn %7B%0A + responseRaw: response.data,%0A @@ -4286,25 +4286,48 @@ message);%0A -%7D + return schemaObj;%0A %7D%0A %0A%0A if (sche @@ -4429,16 +4429,78 @@ j.type;%0A + this.schemaMeta%5BschemaObj.topic%5D = schemaObj.responseRaw;%0A %7D else
7b6c89e8e3cc1715aab453bd5a9162d01f8f64da
Add Chrome 20.0 and Opera 12.0
lib/map.js
lib/map.js
/** * We need to map the useragent IDs that TestSwarm uses to browser definitions in BrowserStack. * TestSwarm useragents.ini: https://github.com/jquery/testswarm/blob/master/config/useragents.ini * BrowserStack API: https://github.com/browserstack/api , http://api.browserstack.com/1/browsers */ var map = { 'Chrome|17':{ name:'chrome', version:'17.0' }, 'Chrome|18':{ name:'chrome', version:'18.0' }, 'Chrome|19':{ name:'chrome', version:'19.0' }, // 'Firefox|3|5': Not in browserstack anymore 'Firefox|3|6':{ name:'firefox', version:'3.6' }, 'Firefox|4':{ name:'firefox', version:'4.0' }, 'Firefox|5':{ name:'firefox', version:'5.0' }, 'Firefox|6':{ name:'firefox', version:'6.0' }, 'Firefox|7':{ name:'firefox', version:'7.0' }, 'Firefox|8':{ name:'firefox', version:'8.0' }, 'Firefox|9':{ name:'firefox', version:'9.0' }, 'Firefox|10':{ name:'firefox', version:'10.0' }, 'Firefox|11':{ name:'firefox', version:'11.0' }, 'Firefox|12':{ name:'firefox', version:'12.0' }, 'Firefox|13':{ name:'firefox', version:'13.0' }, 'IE|6':{ name:'ie', version:'6.0' }, 'IE|7':{ name:'ie', version:'7.0' }, 'IE|8':{ name:'ie', version:'8.0' }, 'IE|9':{ name:'ie', version:'9.0' }, 'IE|10':{ name:'ie', version:'10.0' }, 'Opera|11|10':{ name:'opera', version:'11.1' }, 'Opera|11|50':{ name:'opera', version:'11.5' }, 'Opera|11|60':{ name:'opera', version:'11.6' }, // 'Opera|12|0': No browserstack yet 'Safari|4':{ name:'safari', version:'4.0' }, 'Safari|5|0':{ name:'safari', version:'5.0' }, 'Safari|5|1':{ name:'safari', version:'5.1' } // TODO: Need BrowserStack API v2 for other platforms (issue #19) // 'Android|1|5': {}, // 'Android|1|6': {}, // 'Android|2|1': {}, // 'Android|2|2': {}, // 'Android|2|3': {}, // 'Fennec|4': {}, // 'iPhone|3|2': {}, // 'iPhone|4|3': {}, // 'iPhone|5': {}, // 'iPad|3|2': {}, // 'iPad|4|3': {}, // 'iPad|5': {}, // 'Opera Mobile': {}, // 'Opera Mini|2': {}, // 'Palm Web|1': {}, // 'Palm Web|2': {}, // 'IEMobile|7': {}, }; module.exports = { map:map };
JavaScript
0
@@ -511,32 +511,104 @@ n:'19.0'%0A %7D,%0A + 'Chrome%7C20':%7B%0A name:'chrome',%0A version:'20.0b'%0A %7D,%0A // 'Firefox%7C @@ -1947,32 +1947,103 @@ n:'11.6'%0A %7D,%0A + 'Opera%7C12%7C0':%7B%0A name:'opera',%0A version:'12.0'%0A %7D,%0A // 'Opera%7C12
1cebfa5e2f7544e5e197a5229a70edabaf99787b
debug ocm.Roles
lib/ocm.js
lib/ocm.js
/** * @author Gilles Coomans <[email protected]> * @stability 3 stable * * * * TODO : refactor 'group' in 'modes' * * */ //________________________________________________________________________ OCM for the mass !!! if (typeof define !== 'function') { var define = require('amdefine')(module); } define(["require"], function(require) { var genModes = {}; /* deep.paranos = function(full) { if(full) delete deep.context.protocols; if(deep.context.protocols) { deep.context.protocols = deep.utils.simpleCopy(deep.context.protocols); for(var i in deep.context.protocols) if(deep.context.protocols[i]._deep_ocm_) deep.context.protocols[i] = deep.context.protocols[i](); } // delete deep.context.generalModes; delete deep.context.modes; }; */ /** * OCM for the mass !! * return an Object Capabilities Manager * @param {Object} layer (optional) initial layer * @param {Object} options : { group:"string", init:Func, protocol:"string" }. init = any function that will be fired on newly compiled object * @return {deep.OCM} an Object Capabilities Manager */ var ocm = function(layer, options) { //console.log("deep.ocm : ", layer, options); //console.log("deep.context : ", deep.context) options = options || {}; var params = { group: options.group, layer: layer || {}, currentModes: null, compiled: {}, multiMode: true, compileModes: function(modes, layer) { var self = this, res = null, sheetsPromises = []; if (!this.multiMode && modes.length === 1) res = this.layer[modes[0]] || null; else modes.forEach(function(m) { var r = self.layer[m]; if (typeof r !== 'undefined') { if (options.applySheets && r._deep_sheet_ && res) sheetsPromises.push(deep.sheet(r, res)); else res = deep.utils.up(r, res || {}); } }); if (res === null) { console.warn("OCM : no associate mode found with : ", modes, " for protocol : ", options.protocol); return {}; } if (sheetsPromises.length > 0) res._deep_sheets_ = deep.all(sheetsPromises); return res; }, init: options.init }; var m = function() { var modes = Array.prototype.slice.apply(arguments); if (modes.length === 0 || params.blocked) if (params.currentModes && params.currentModes.length > 0) modes = params.currentModes; else if (params.group) { var checkIn = deep.context.modes || deep.Modes(); if (params.group.forEach) { modes = []; for (var i = 0, len = params.group.length; i < len; ++i) if (checkIn[params.group[i]]) modes = modes.concat(checkIn[params.group[i]]); } else modes = checkIn[params.group]; } if (!modes || modes.length === 0) throw deep.errors.OCM("You need to set a mode before using ocm objects."); if (!modes.forEach) modes = [modes]; var joined = modes; if (typeof modes.join === 'function') joined = modes.join("."); if (params.compiled[joined]) return params.compiled[joined]; var compiled = params.compileModes(modes, params.layer); if (!deep.ocm.nocache) params.compiled[joined] = compiled; if (params.init) params.init.call(compiled); return compiled; }; if (options.protocol) { m.name = options.protocol; deep.protocols[options.protocol] = m; } m._deep_ocm_ = true; m._deep_compiler_ = true; m._deep_flattener_ = true; m.multiMode = function(yes) { params.multiMode = yes; }; m.group = function(arg) { if (params.blocked) return m(); params.group = arg; return m; }; m.mode = function(arg) { if (params.blocked) return m(); if (arg === null) params.currentModes = null; else params.currentModes = Array.prototype.slice.apply(arguments); return m(); }; m.block = function(key) { params.block = true; m.unblock = function(ukey) { if (ukey === key) params.blocked = false; }; }; m.unblock = function(key) {}; m.flatten = function(entry) { if (params.blocked) return deep.when(null); if (entry) { entry.value = params.layer; if (entry.ancestor) entry.ancestor.value[entry.key] = params.layer; } return deep.flatten(entry || params.layer) .done(function() { if (entry) { entry.value = m; if (entry.ancestor) entry.ancestor.value[entry.key] = m; } return m; }); }; m.up = function() { for (var i = 0; i < arguments.length; ++i) params.layer = deep.utils.up(arguments[i], params.layer); return params.layer; }; m.bottom = function() { for (var i = 0; i < arguments.length; ++i) params.layer = deep.utils.bottom(arguments[i], params.layer); return params.layer; }; m.clone = function() { var o = null; if (typeof protocol === 'string') o = deep.ocm(deep.utils.copy(params.layer), options); else o = deep.ocm(deep.utils.copy(params.layer), options); o.multiMode(params.multiMode); if (params.currentModes) o.mode(params.currentModes); return o; }; return m; }; ocm.Roles = function(roles) { if (!roles) return genMode.roles; return output.Modes({ roles: roles }); } ocm.Modes = function(arg, arg2) { if (arguments.length === 0) return genModes; if (typeof arg === 'string') { var obj = {}; obj[arg] = arg2; arg = obj; } for (var i in arg) genModes[i] = arg[i]; }; // deep chain's mode management ocm.modes = function(name, modes) { return deep({}).modes(name, modes); }; // deep chain's roles management ocm.roles = function() { return deep({}).roles(Array.prototype.slice.call(arguments)); }; ocm.nocache = false; return ocm; });
JavaScript
0.000001
@@ -6883,13 +6883,10 @@ rn o -utput +cm .Mod
4b4c55f39612db8c57271d69d4230db781ae8ac7
Fix tasks path
lib/run.js
lib/run.js
var fs = require('fs') var cp = require('child_process') var path = require('path') var formattedOutput = require('./formatted_output') var CommonEnv = require(path.join(process.env.SALINGER_HOME_PATH, 'env')) var scripts = [ { ext: 'sh', cmd: 'sh' }, { ext: 'js', cmd: 'node' }, { ext: 'py', cmd: 'python' }, { ext: 'rb', cmd: 'ruby' }, { ext: 'pl', cmd: 'perl' }, { ext: 'lua', cmd: 'lua' } ] module.exports = function run(taskname, SpecialEnv) { formattedOutput.start({ taskname }) var _env = SpecialEnv ? Object.assign({}, CommonEnv, SpecialEnv) : CommonEnv var env = Object.assign({}, process.env, _env) return execute(taskname, env) .then(formattedOutput.success) .catch(formattedOutput.fail) } function findScript(_path, scriptIndex = 0) { return new Promise((resolve, reject) => { var script = scripts[scriptIndex] var name = `${_path}.${script.ext}` fs.stat(name, err => { if (err) { if (scripts.length > scriptIndex + 1) { return resolve(findScript(_path, scriptIndex + 1)) } return reject({ err, notFound: true }) } resolve(script) }) }) } function execute(taskname, env) { return new Promise((resolve, reject) => { var file = path.join(__dirname, '..', 'tasks', `${taskname}`) findScript(file).then(script => { var command = script.cmd + ' ' + `${file}.${script.ext}` var ps = cp.exec(command, { env }) var stderr = '' ps.stdout.pipe(process.stdout) ps.stderr.pipe(process.stderr) ps.stderr.on('data', data => { stderr += data }) ps.on('close', code => { if (code == 0) { resolve({ taskname }) } else { reject({ taskname, code, stderr }) } }) }).catch(e => reject({ taskname, code: 1, stderr: e.notFound ? `Couldn't find the task "${taskname}".` : e })) }) }
JavaScript
0.00071
@@ -1257,23 +1257,38 @@ oin( -__dirname, '..' +process.env.SALINGER_HOME_PATH , 't
8099f7edf2d75e691a4621d5dc5e389f5a031897
Fix find with NaN id in base-sql
lib/sql.js
lib/sql.js
module.exports = BaseSQL; /** * Base SQL class */ function BaseSQL() { } BaseSQL.prototype.query = function () { throw new Error('query method should be declared in adapter'); }; BaseSQL.prototype.command = function (sql, callback) { return this.query(sql, callback); }; BaseSQL.prototype.queryOne = function (sql, callback) { return this.query(sql, function (err, data) { if (err) return callback(err); callback(err, data[0]); }); }; BaseSQL.prototype.table = function (model) { return this._models[model].model.schema.tableName(model); }; BaseSQL.prototype.escapeName = function (name) { throw new Error('escapeName method should be declared in adapter'); }; BaseSQL.prototype.tableEscaped = function (model) { return this.escapeName(this.table(model)); }; BaseSQL.prototype.define = function (descr) { if (!descr.settings) descr.settings = {}; this._models[descr.model.modelName] = descr; }; BaseSQL.prototype.defineProperty = function (model, prop, params) { this._models[model].properties[prop] = params; }; BaseSQL.prototype.save = function (model, data, callback) { var sql = 'UPDATE ' + this.tableEscaped(model) + ' SET ' + this.toFields(model, data) + ' WHERE ' + this.escapeName('id') + ' = ' + Number(data.id); this.query(sql, function (err) { callback(err); }); }; BaseSQL.prototype.exists = function (model, id, callback) { var sql = 'SELECT 1 FROM ' + this.tableEscaped(model) + ' WHERE ' + this.escapeName('id') + ' = ' + Number(id) + ' LIMIT 1'; this.query(sql, function (err, data) { if (err) return callback(err); callback(null, data.length === 1); }); }; BaseSQL.prototype.find = function find(model, id, callback) { var sql = 'SELECT * FROM ' + this.tableEscaped(model) + ' WHERE ' + this.escapeName('id') + ' = ' + Number(id) + ' LIMIT 1'; this.query(sql, function (err, data) { if (data && data.length === 1) { data[0].id = id; } else { data = [null]; } callback(err, this.fromDatabase(model, data[0])); }.bind(this)); }; BaseSQL.prototype.destroy = function destroy(model, id, callback) { var sql = 'DELETE FROM ' + this.tableEscaped(model) + ' WHERE ' + this.escapeName('id') + ' = ' + Number(id); this.command(sql, function (err) { callback(err); }); }; BaseSQL.prototype.destroyAll = function destroyAll(model, callback) { this.command('DELETE FROM ' + this.tableEscaped(model), function (err) { if (err) { return callback(err, []); } callback(err); }.bind(this)); }; BaseSQL.prototype.count = function count(model, callback, where) { var self = this; var props = this._models[model].properties; this.queryOne('SELECT count(*) as cnt FROM ' + this.tableEscaped(model) + ' ' + buildWhere(where), function (err, res) { if (err) return callback(err); callback(err, res && res.cnt); }); function buildWhere(conds) { var cs = []; Object.keys(conds || {}).forEach(function (key) { var keyEscaped = self.escapeName(key); if (conds[key] === null) { cs.push(keyEscaped + ' IS NULL'); } else { cs.push(keyEscaped + ' = ' + self.toDatabase(props[key], conds[key])); } }); return cs.length ? ' WHERE ' + cs.join(' AND ') : ''; } }; BaseSQL.prototype.updateAttributes = function updateAttrs(model, id, data, cb) { data.id = id; this.save(model, data, cb); }; BaseSQL.prototype.disconnect = function disconnect() { this.client.end(); }; BaseSQL.prototype.automigrate = function (cb) { var self = this; var wait = 0; Object.keys(this._models).forEach(function (model) { wait += 1; self.dropTable(model, function () { // console.log('drop', model); self.createTable(model, function (err) { // console.log('create', model); if (err) console.log(err); done(); }); }); }); if (wait === 0) cb(); function done() { if (--wait === 0 && cb) { cb(); } } }; BaseSQL.prototype.dropTable = function (model, cb) { this.command('DROP TABLE IF EXISTS ' + this.tableEscaped(model), cb); }; BaseSQL.prototype.createTable = function (model, cb) { this.command('CREATE TABLE ' + this.tableEscaped(model) + ' (\n ' + this.propertiesSQL(model) + '\n)', cb); };
JavaScript
0.000001
@@ -1750,32 +1750,147 @@ id, callback) %7B%0A + var idNumber = Number(id);%0A if (isNaN(idNumber)) %7B%0A callback(new Error('id is not a number'));%0A %7D%0A var sql = 'S @@ -1981,34 +1981,32 @@ ) + ' = ' + +id Number -(id) + ' LIMIT 1
cfd95cf5f4bafe8235d9010a71a468d80612bea0
add isSameOrigin method
lib/url.js
lib/url.js
/** * Class for taking a path and compiling it into a regular expression. * * Also has a params method for getting an array of params given a path, and * convenience methods for working with the regexp like test and exec. * * XXX where is resolve? * */ Url = function (url, options) { options = options || {}; this.options = options; this.keys = []; this.regexp = compilePath(url, this.keys, options); _.extend(this, Url.parse(url)); }; /** * Given a relative or absolute path return * a relative path with a leading forward slash and * no search string or hash fragment * * @param {String} path * @return {String} */ Url.normalize = function (url) { if (!url) return url; var parts = Url.parse(url); var pathname = parts.pathname; if (pathname.charAt(0) !== '/') pathname = '/' + pathname; if (pathname.length > 1 && pathname.charAt(pathname.length - 1) === '/') { pathname = pathname.slice(0, pathname.length - 1); } return pathname; }; /** * Given a query string return an object of key value pairs. * * "?p1=value1&p2=value2 => {p1: value1, p2: value2} */ Url.fromQueryString = function (query) { if (!query) return {}; if (typeof query !== 'string') throw new Error("expected string"); // get rid of the leading question mark if (query.charAt(0) === '?') query = query.slice(1); var keyValuePairs = query.split('&'); var result = {}; var parts; _.each(keyValuePairs, function (pair) { parts = pair.split('='); result[parts[0]] = decodeURIComponent(parts[1]); }); return result; }; /** * Given a query object return a query string. */ Url.toQueryString = function (queryObject) { var result = []; if (typeof queryObject !== 'object') throw new Error("expected object"); _.each(queryObject, function (value, key) { result.push(encodeURIComponent(key) + '=' + encodeURIComponent(value)); }); // no sense in adding a pointless question mark if (result.length > 0) return '?' + result.join('&'); else return ''; }; /** * Given a string url return an object with all of the url parts. */ Url.parse = function (url) { if (!url) return {}; //http://tools.ietf.org/html/rfc3986#page-50 //http://www.rfc-editor.org/errata_search.php?rfc=3986 var re = /^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/; var match = url.match(re); var protocol = match[1] ? match[1].toLowerCase() : undefined; var hostWithSlashes = match[3]; var slashes = !!hostWithSlashes; var hostWithAuth= match[4] ? match[4].toLowerCase() : undefined; var hostWithAuthParts = hostWithAuth ? hostWithAuth.split('@') : []; var host, auth; if (hostWithAuthParts.length == 2) { auth = hostWithAuthParts[0]; host = hostWithAuthParts[1]; } else if (hostWithAuthParts.length == 1) { host = hostWithAuthParts[0]; auth = undefined; } else { host = undefined; auth = undefined; } var hostWithPortParts = (host && host.split(':')) || []; var hostname = hostWithPortParts[0]; var port = hostWithPortParts[1]; var origin = (protocol && host) ? protocol + '//' + host : undefined; var pathname = match[5]; var path = pathname + (search || ''); var hash = match[8]; var originalUrl = url; var search = match[6]; var query; var indexOfSearch = (hash && hash.indexOf('?')) || -1; // if we found a search string in the hash and there is no explicit search // string if (~indexOfSearch && !search) { search = hash.slice(indexOfSearch); hash = hash.substr(0, indexOfSearch); // get rid of the ? character query = search.slice(1); } else { query = match[7]; } var queryObject = Url.fromQueryString(query); var rootUrl = [ protocol || '', slashes ? '//' : '', hostWithAuth || '' ].join(''); var href = [ protocol || '', slashes ? '//' : '', hostWithAuth || '', path || '', search || '', hash || '' ].join(''); return { rootUrl: rootUrl || '', originalUrl: url || '', href: href || '', protocol: protocol || '', auth: auth || '', host: host || '', hostname: hostname || '', port: port || '', origin: origin || '', path: path || '', pathname: pathname || '', search: search || '', query: query || '', queryObject: queryObject || '', hash: hash || '', slashes: slashes }; }; /** * Returns true if the path matches and false otherwise. * * @param {String} path * @return {Boolean} */ Url.prototype.test = function (path) { return this.regexp.test(Url.normalize(path)); }; /** * Returns the result of calling exec on the compiled path with * the given path. * * @param {String} path * @return {Array} */ Url.prototype.exec = function (path) { return this.regexp.exec(Url.normalize(path)); }; /** * Returns an array of parameters given a path. The array may have named * properties in addition to indexed values. * * @param {String} path * @return {Array} */ Url.prototype.params = function (path) { if (!path) return []; var params = []; var m = this.exec(path); var queryString; var keys = this.keys; var key; var value; if (!m) throw new Error('The route named "' + this.name + '" does not match the path "' + path + '"'); for (var i = 1, len = m.length; i < len; ++i) { key = keys[i - 1]; value = typeof m[i] == 'string' ? decodeURIComponent(m[i]) : m[i]; if (key) { params[key.name] = params[key.name] !== undefined ? params[key.name] : value; } else params.push(value); } path = decodeURI(path); queryString = path.split('?')[1]; if (queryString) queryString = queryString.split('#')[0]; params.hash = path.split('#')[1]; if (queryString) { _.each(queryString.split('&'), function (paramString) { paramParts = paramString.split('='); params[paramParts[0]] = decodeURIComponent(paramParts[1]); }); } return params; }; Iron = Iron || {}; Iron.Url = Url;
JavaScript
0.000474
@@ -986,24 +986,252 @@ thname;%0A%7D;%0A%0A +/**%0A * Returns true if both a and b are of the same origin.%0A */%0AUrl.isSameOrigin = function (a, b) %7B%0A var aParts = Url.parse(a);%0A var bParts = Url.parse(b);%0A var result = aParts.origin === bParts.origin;%0A return result;%0A%7D;%0A%0A /**%0A * Given
153781daf7e1e86d6ecc8455c07a0ef568056525
Load the commands
library.js
library.js
"use strict"; var NodeBB = require('./lib/nodebb'), Config = require('./lib/config'), Sockets = require('./lib/sockets'), app, Shoutbox = {}; Shoutbox.init = {}; Shoutbox.widget = {}; Shoutbox.settings = {}; Shoutbox.init.load = function(params, callback) { function renderGlobal(req, res, next) { Config.getTemplateData(function(data) { res.render(Config.plugin.id, data); }); } function renderAdmin(req, res, next) { Config.getTemplateData(function(data) { res.render('admin/' + Config.plugin.id, data); }); } var router = params.router; router.get('/' + Config.plugin.id, params.middleware.buildHeader, renderGlobal); router.get('/api/' + Config.plugin.id, renderGlobal); router.get('/admin/plugins/' + Config.plugin.id, params.middleware.admin.buildHeader, renderAdmin); router.get('/api/admin/plugins/' + Config.plugin.id, renderAdmin); NodeBB.SocketPlugins[Config.plugin.id] = Sockets.events; NodeBB.SocketAdmin[Config.plugin.id] = Config.adminSockets; app = params.app; callback(); }; Shoutbox.init.addGlobalNavigation = function(header, callback) { if (Config.global.get('toggles.headerLink')) { header.navigation.push({ class: '', iconClass: 'fa fa-fw ' + Config.plugin.icon, route: '/' + Config.plugin.id, text: Config.plugin.name }); } callback(null, header); }; Shoutbox.init.addAdminNavigation = function(header, callback) { header.plugins.push({ route: '/plugins/' + Config.plugin.id, icon: Config.plugin.icon, name: Config.plugin.name }); callback(null, header); }; Shoutbox.init.getSounds = function(sounds, callback) { sounds.push(__dirname + '/public/sounds/shoutbox-notification.mp3'); sounds.push(__dirname + '/public/sounds/shoutbox-wobblysausage.mp3'); callback(null, sounds); }; Shoutbox.widget.define = function(widgets, callback) { widgets.push({ name: Config.plugin.name, widget: Config.plugin.id, description: Config.plugin.description, content: '' }); callback(null, widgets); }; Shoutbox.widget.render = function(widget, callback) { //Remove any container widget.data.container = ''; Config.user.get({ uid: widget.uid, settings: {} }, function(err, result) { Config.getTemplateData(function(data) { data.hiddenStyle = ''; if (!err && result && result.settings && parseInt(result.settings['shoutbox:toggles:hide'], 10) == 1) { data.hiddenStyle = 'display: none;'; } app.render('shoutbox/panel', data, callback); }); }); }; Shoutbox.settings.addUserSettings = function(settings, callback) { app.render('shoutbox/user/settings', function(err, html) { settings.push({ title: Config.plugin.name, content: html }); callback(null, settings); }); }; Shoutbox.settings.getUserSettings = function(data, callback) { Config.user.get(data, callback); }; Shoutbox.settings.saveUserSettings = function(data) { Config.user.save(data); }; module.exports = Shoutbox;
JavaScript
0.000287
@@ -117,16 +117,55 @@ ckets'), +%0A%09Commands = require('./lib/commands'), %0A%0A%09app,%0A
b9359af7639831cdd3e2a6a55128d4c618bb0973
Fix hiding troll comments and answers
lib/pagestyles.js
lib/pagestyles.js
/*jshint moz:true*/ /*global require, exports*/ var self = require("sdk/self"); var pref = require('./pref'); function createStyle(elements, rules) { 'use strict'; return elements.join(',') + '{' + rules.map(function (rule) { return rule.name + ':' + rule.value + ' !important;'; }).join('') + '}'; } /** * @return string */ function getPageStyle() { 'use strict'; var output = []; var minFontSize = pref.getPref('style_min_fontsize'); var minWidth = pref.getPref('style_wider_sidebar'); if (minFontSize > 0) { output.push(createStyle([ 'body', '#all', '#top-nav', '#top-nav a', '.sidebar .block .content', '#footer', '.node .links' ], [{name: 'font-size', value: minFontSize + 'px'}])); } if (minWidth > 0) { output.push(createStyle(['.sidebar'], [{name: 'width', value: minWidth + 'px'}])); } if (pref.getPref('filtertrolls')) { if (pref.getPref('trollfiltermethod') === 'hilight') { output.push(createStyle(['.trollHeader'], [{name: 'background-color', value: pref.getPref('trollcolor')}])); } else if (pref.getPref('trollfiltermethod') === 'hide') { output.push(createStyle(['.trollComment'], [{name: 'display', value: 'none'}])); output.push(createStyle(['.trollCommentAnswer'], [{name: 'display', value: 'none'}])); } } return output; } /** * @return Array */ function getPageStyleFiles() { 'use strict'; var output = [ self.data.url('indentstyles.css'), self.data.url('hupper.css') ]; if (pref.getPref('style_accessibility')) { output.push(self.data.url('accesibilitystyles.css')); } return output; } exports.getPageStyle = getPageStyle; exports.getPageStyleFiles = getPageStyleFiles;
JavaScript
0
@@ -896,41 +896,26 @@ ef(' +hide troll -filtermethod') === 'hilight' +answers') ) %7B%0A @@ -953,14 +953,15 @@ roll -Header +Comment '%5D, @@ -973,126 +973,36 @@ e: ' -background-color', value: pref.getPref('trollcolor')%7D%5D));%0A%09%09%7D else if (pref.getPref('trollfiltermethod') === 'hide') %7B +display', value: 'none'%7D%5D)); %0A%09%09%09 @@ -1032,32 +1032,38 @@ (%5B'.trollComment +Answer '%5D, %5B%7Bname: 'dis @@ -1080,32 +1080,43 @@ ue: 'none'%7D%5D));%0A +%09%09%7D else %7B%0A %09%09%09output.push(c @@ -1130,35 +1130,28 @@ yle(%5B'.troll -CommentAnsw +Head er'%5D, %5B%7Bname @@ -1153,39 +1153,68 @@ %7Bname: ' -display', value: 'none' +background-color', value: pref.getPref('trollcolor') %7D%5D));%0A%09%09
534d82ea5307a1ea6bb0792a60c026c5a01022ef
create stream with proper type
lib/parse_args.js
lib/parse_args.js
var net = require('net'); module.exports = function (args) { var opts = {}; for (var i = 0; i < args.length; i++) { var arg = args[i]; var m; if (typeof arg === 'number') { opts.port = arg; } else if (typeof arg === 'string') { if (/^\d+$/.test(arg)) { opts.port = parseInt(arg, 10); } else if (/^\.?\//.test(arg)) { opts.unix = arg; } else if ((m = arg.match( /^(?:(http|https):\/\/)?([^:\/]+)?(?::(\d+))?(\/.*)?$/ )) && (m[1] || m[2] || m[3] || m[4])) { opts.tls = (m[1] === "https"); opts.host = m[2] || 'localhost'; opts.port = m[3] || 80; if (m[4]) opts.path = m[4]; } else opts.host = arg; } else if (typeof arg === 'object') { if (arg.write) opts.stream = arg; else { for (var key in arg) { opts[key] = arg[key] } } } } if (opts.stream) return opts; if (opts.unix) { opts.stream = net.connect(opts.unix); } else if (opts.host && opts.port) { opts.stream = net.connect(opts.port, opts.host); } else if (opts.port) { opts.stream = net.connect(opts.port); } return opts; }
JavaScript
0
@@ -17,16 +17,40 @@ e('net') +,%0A tls = require('tls') ;%0A%0Amodul @@ -98,20 +98,16 @@ s = %7B%7D;%0A - %0A for @@ -1179,24 +1179,74 @@ opts;%0A %0A + opts.streamType = (opts.tls ? tls : stream);%0A%0A if (opts @@ -1268,35 +1268,47 @@ opts.stream = -net +opts.streamType .connect(opts.un @@ -1371,35 +1371,47 @@ opts.stream = -net +opts.streamType .connect(opts.po @@ -1480,19 +1480,31 @@ tream = -net +opts.streamType .connect
cd036676d794fb37fa74e02e004a3cffd4f859d6
Add some extras to props
lib/properties.js
lib/properties.js
const date = new Date(); export const defaults = { date: { day: date.getDate(), month: date.getMonth(), fullYear: date.getFullYear() }, user: { name: '', github: '', email: '' }, package: { name: '', description: '' } }; export const properties = { 'user.name': { description: 'Your name: ', message: 'Required', required: true }, 'user.email': { description: 'Your email (will be publicly available, optional): ', pattern: /@/, message: 'Should be a valid e-mail' }, 'user.github': { description: 'Your GitHub public username: ', pattern: /^[a-z0-9]+[a-z0-9\-]+[a-z0-9]+$/i, message: 'Username may only contain alphanumeric characters or single hyphens, and cannot begin or end with a hyphen', required: true }, 'package.name': { description: 'Package name: ', pattern: /^[a-z0-9]+[a-z0-9\-_]+$/, message: 'Package name may only contain alphanumeric characters, hyphens or underscores', required: true }, 'package.description': { description: 'Package description: ' } };
JavaScript
0
@@ -18,16 +18,80 @@ Date();%0A +const %5Bmajor, minor, patch%5D = process.versions.node.split('.');%0A export c @@ -209,16 +209,47 @@ ()%0A %7D,%0A + node: %7Bmajor, minor, patch%7D,%0A user: @@ -322,24 +322,24 @@ name: '',%0A - descript @@ -346,16 +346,62 @@ ion: ''%0A + %7D,%0A curly: %7B%0A left: '%7B',%0A right: '%7D'%0A %7D%0A%7D;%0A%0A
df3738b53d8832669da7d6bef1d3c63a8e9f0616
Remove dead code.
lib/resolve-rc.js
lib/resolve-rc.js
'use strict'; /** * The purpose of this module, is to find the project's .babelrc and * use its contents to bust the babel-loader's internal cache whenever an option * changes. * * This feature is opt-in and it's disabled by default. * * @see https://github.com/babel/babel-loader/issues/62 * @see http://git.io/vLEvu */ var fs = require('fs'); var path = require('path'); var assign = require('object-assign'); var exists = require('./helpers/exists')({}); var isAbsolute = require('path-is-absolute'); var find = function find(start, rel) { var file = path.join(start, rel); var opts = {}; var up = ''; if (exists(file)) { return fs.readFileSync(file, 'utf8'); } up = path.dirname(start); if (up !== start) { // Reached root return find(up, rel); } }; module.exports = function(loc) { var opts = [].slice.call(arguments, 1) || {}; var rel = '.babelrc'; return find(loc, rel); };
JavaScript
0.00001
@@ -823,71 +823,31 @@ (loc -) %7B%0A var opts = %5B%5D.slice.call(arguments, 1) %7C%7C %7B%7D;%0A var +, rel) %7B%0A rel = rel -= +%7C%7C '.b @@ -855,17 +855,16 @@ belrc';%0A -%0A return
f67a789b1080e23f9a1bed9ccfa5d6214d009051
Support Model.find({ prop: null }) (closes #59)
lib/sql/Select.js
lib/sql/Select.js
module.exports = Builder; function Builder(opts) { this.escapeId = opts.escapeId; this.escape = opts.escape; this.clear(); } Builder.prototype.clear = function () { this.opts = { table : [], merge : [], where : [], order : [] }; return this; }; Builder.prototype.count = function () { this.opts.count = true; return this; }; Builder.prototype.fields = function (fields) { this.opts.fields = fields; return this; }; Builder.prototype.table = function (table) { this.opts.table.push(table); return this; }; Builder.prototype.where = function (field, value, comparison) { // stand by for now.. // if (!Array.isArray(value) && typeof(value) === 'object') { // comparison = value.op || value.operator || value.comp || value.comparison; // value = value.value; // } this.opts.where.push({ field : field, value : value, comp : comparison || (Array.isArray(value) ? "IN" : "=") }); return this; }; Builder.prototype.order = function (field, order) { this.opts.order.push({ field : field, order : order || "A" }); return this; }; Builder.prototype.merge = function (from, to) { this.opts.merge.push({ from : from, to : to }); return this; }; Builder.prototype.limit = function (limit) { // allow numbers but also strings (big numbers..) if (typeof limit == "number" || (limit && limit.length)) { this.opts.limit = limit; } else { delete this.opts.limit; } return this; }; Builder.prototype.offset = function (offset) { if (typeof offset == "number") { this.opts.offset = offset; } else { delete this.opts.offset; } return this; }; Builder.prototype.build = function () { var i, lst; var query = "SELECT "; if (this.opts.count) { query += "COUNT(*) AS c"; } else if (Array.isArray(this.opts.fields)) { query += this.opts.fields.map(this.escapeId).join(", "); } else if (this.opts.fields) { query += this.escapeId(this.opts.fields); } else { query += "*"; } query += " FROM "; // tables lst = []; for (i = 0; i < this.opts.table.length; i++) { if (Array.isArray(this.opts.table[i])) { lst.push(this.opts.table[i].map(this.escapeId).join(" JOIN ")); } else { lst.push(this.escapeId(this.opts.table[i])); } } query += lst.join(", "); if (this.opts.merge) { for (i = 0; i < this.opts.merge.length; i++) { query += " LEFT JOIN " + this.escapeId(this.opts.merge[i].from.table) + " ON " + this.escapeId(this.opts.merge[i].from.table + "." + this.opts.merge[i].from.field) + " = " + this.escapeId(this.opts.merge[i].to.table + "." + this.opts.merge[i].to.field); } } // where lst = []; for (i = 0; i < this.opts.where.length; i++) { if (typeof this.opts.where[i].value.orm_special_object == "function") { var op = this.opts.where[i].value.orm_special_object(); switch (op) { case "between": lst.push([ this.escapeId(this.opts.where[i].field), "BETWEEN", this.escape(this.opts.where[i].value.from), "AND", this.escape(this.opts.where[i].value.to) ].join(" ")); break; case "like": lst.push([ this.escapeId(this.opts.where[i].field), "LIKE", this.escape(this.opts.where[i].value.expr) ].join(" ")); break; case "eq": case "ne": case "gt": case "gte": case "lt": case "lte": switch (op) { case "eq" : op = "="; break; case "ne" : op = "<>"; break; case "gt" : op = ">"; break; case "gte" : op = ">="; break; case "lt" : op = "<"; break; case "lte" : op = "<="; break; } lst.push([ this.escapeId(this.opts.where[i].field), op, this.escape(this.opts.where[i].value.val) ].join(" ")); break; } continue; } lst.push([ this.escapeId(this.opts.where[i].field), this.opts.where[i].comp, this.escape((this.opts.where[i].comp == "IN") ? [ this.opts.where[i].value ] : this.opts.where[i].value) ].join(" ")); } if (lst.length > 0) { query += " WHERE " + lst.join(" AND "); } // order if (this.opts.hasOwnProperty("order")) { if (Array.isArray(this.opts.order)) { lst = []; for (i = 0; i < this.opts.order.length; i++) { lst.push(this.escapeId(this.opts.order[i].field) + (this.opts.order[i].order.toLowerCase() == "z" ? " DESC" : " ASC")); } if (lst.length > 0) { query += " ORDER BY " + lst.join(", "); } } else { query += " ORDER BY " + this.escapeId(this.opts.order); } } // limit if (this.opts.hasOwnProperty("limit")) { if (this.opts.hasOwnProperty("offset")) { query += " LIMIT " + this.opts.limit + " OFFSET " + this.opts.offset; } else { query += " LIMIT " + this.opts.limit; } } else if (this.opts.hasOwnProperty("offset")) { query += " OFFSET " + this.opts.offset; } return query; };
JavaScript
0
@@ -2670,24 +2670,174 @@ gth; i++) %7B%0A +%09%09if (this.opts.where%5Bi%5D.value === null) %7B%0A%09%09%09lst.push(%5B%0A%09%09%09%09this.escapeId(this.opts.where%5Bi%5D.field),%0A%09%09%09%09%22IS NULL%22%0A%09%09%09%5D.join(%22 %22));%0A%09%09%09continue;%0A%09%09%7D%0A %09%09if (typeof
bc1555838ba03dc05aecf93492cb8f37735a3c81
Read file sync
lib/submission.js
lib/submission.js
var db = require('./db'); var fs = require('fs'); var exec = require('child_process').exec; var Promise = require('promise'); var SubmissionSchema = db.mongoose.Schema({ user: String, fullPath: String, filePath: String, dirPath: String, isDir: Boolean, date: Number, assign: String, count: Number }); var Submission = db.mongoose.model('Submission', SubmissionSchema); var SubLogSchema = db.mongoose.Schema({ date: Number, message: String, data: Object }); var SubLog = db.mongoose.model('SubLog', SubLogSchema); var getStats = function (assignment) { 'use strict'; var data = fs.readFile(__dirname + '/assignments.json', 'utf-8'), json = JSON.parse(data); return (json[assignment]) ? data.basePath : ''; }; var addLog = function (message, obj) { 'use strict'; var promise = new Promise(); var log = new SubLog({ date: +new Date(), message: message, data: obj }); return db.saveDoc(log); }; var addSubmission = function (astats, user, assign, path, date) { 'use strict'; var sub, dir, promise = new Promise(); fs.stat(path, function (stats, err) { if (err || !stats) { promise.reject(err); return; } Submission.count({user: user, assign: assign}, function (err, count) { if (err) { promise.reject(err); return; } if ((dir = stats.isDirectory()) && path.charAt(path.length - 1) === '/') { path = path.slice(0, -1); } sub = new Submission({ user: user, fullPath: path, filePath: (dir) ? '' : path.substr(path.lastIndexOf('/') + 1), dirPath: (dir) ? dir : path.substr(0, path.lastIndexOf('/')), isDir: dir, date: date, assign: assign, count: count }); if (isDir) { exec("sh /bin/teachingscripts/acp-r.sh '" + sub.dirPath + "/*' '" + astats + '/' + user + '/' + assign + '/' + count + '/', function (err, stdo, stde) { if (err) { promise.reject(err); return; } db.saveDoc(sub).then(function (doc) { promise.resolve(doc); }, function (err) { promise.reject(err); }); }); } }); }); return promise; }; module.exports = { addLog: addLog, addSubmission: addSubmission, getStats: getStats };
JavaScript
0.000001
@@ -639,16 +639,20 @@ readFile +Sync (__dirna
3465f198bcb3384386ee5ba59ea2a5264e7c7c2e
Use options in TestUtils
lib/test-utils.js
lib/test-utils.js
const _ = require('lodash'); const memFs = require('mem-fs'); const editor = require('mem-fs-editor'); const ejs = require('ejs'); const path = require('path'); const json = require('./json2js').json; const fileUtils = require('./file-utils'); module.exports = { defaults() { return { props: { framework: 'react', modules: 'webpack', js: 'js', css: 'css' } }; }, mock(generator) { generator = generator ? generator : 'app'; const Base = require('./Base'); const context = Object.assign({}, this.defaults()); const store = memFs.create(); const fs = editor.create(store); Base.extend = description => { Object.assign(context, description); }; context.mergeJson = (file, content) => { context.mergeJson[file] = content; }; context.updateJson = (file, update) => { context.updateJson[file] = update({}); }; context.copyTemplate = (file, dest, templateScope) => { const scope = Object.assign({}, {json}, context.props, templateScope); const files = {template: file, destination: ''}; fileUtils.renameFiles(files, context.props); const filePath = path.join(`generators/${generator}/templates`, files.template); const content = fs.read(filePath); const rendered = ejs.render(content, scope); context.copyTemplate[file] = rendered; }; return context; }, call(context, method, props) { Object.assign(context.props, props); _.get(context, method).call(context); } };
JavaScript
0
@@ -291,20 +291,22 @@ %7B%0A -pr op +tion s: %7B%0A @@ -1034,20 +1034,22 @@ context. -pr op +tion s, templ @@ -1157,20 +1157,22 @@ context. -pr op +tion s);%0A @@ -1447,20 +1447,22 @@ method, -pr op +tion s) %7B%0A @@ -1488,19 +1488,23 @@ ext. -props, prop +options, option s);%0A
deaf287619844453e2e90c770a3eede5f274657b
Fix quotes module required.
lib/volatility.js
lib/volatility.js
/*jshint node:true */ "use strict"; var options = require('./Quotes.js'); /* The Cumulative Normal Distribution function */ /* 0 1 2 -> 0.5000000 0.8413447 0.9772499 */ function CND(x) { var a1 = 0.319381530, a2 = -0.356563782, a3 = 1.781477937, a4 = -1.821255978, a5 = 1.330274429, p = 0.2316419, k; if (x < 0.0) { return 1 - CND(-x); } else { k = 1.0 / (1.0 + p * x); } return 1.0 - Math.exp(-x * x / 2.0) / Math.sqrt(2 * Math.PI) * k * (a1 + k * (a2 + k * (a3 + k * (a4 + k * a5)))); } /* The Black and Scholes (1973) Stock option formula */ function BS(S, K, T, r, v, type) { var d1, d2, value; type = type || "C"; d1 = (Math.log(S / K) + (r + v * v / 2.0) * T) / (v * Math.sqrt(T)); d2 = d1 - v * Math.sqrt(T); if (type === "C") { value = S * CND(d1) - K * Math.exp(-r * T) * CND(d2); } if (type === "P") { value = K * Math.exp(-r * T) * CND(-d2) - S * CND(-d1); } return value; } /* Function to find BS Implied Vol using Bisection Method */ function impliedVolatility(S, K, T, r, market, type) { var sig = 0.20, sigUp = 1, sigDown = 0.001, count = 0, err; if (market === undefined) { return undefined; } err = BS(S, K, T, r, sig, type) - market; /*repeat until error is sufficiently small or counter hits 1000 */ while (Math.abs(err) > 0.00001 && count < 1000) { if (err < 0) { sigDown = sig; sig = (sigUp + sig) / 2; } else { sigUp = sig; sig = (sigDown + sig) / 2; } err = BS(S, K, T, r, sig, type) - market; count = count + 1; } /* return NA if counter hit 1000 */ if (count === 1000) { return undefined; } else { return sig; } } function getImpliedVolatility(params, callback) { var symbol, S, T, i, n, cVol = [], pVol = []; symbol = params.symbol; options.getOptionChainFromYahoo(symbol, function (err, chain) { S = chain.strike; T = chain.diffdate / 365; options.getRiskFreeRateFromYahoo(function (err, r) { n = chain.calls.length; for (i = 0; i < n; i += 1) { cVol[i] = { strike: chain.calls[i].strike, ask: impliedVolatility(S, chain.calls[i].strike, T, r, chain.calls[i].ask, "C"), bid: impliedVolatility(S, chain.calls[i].strike, T, r, chain.calls[i].bid, "C") }; } n = chain.puts.length; for (i = 0; i < n; i += 1) { pVol[i] = { strike: chain.puts[i].strike, ask: impliedVolatility(S, chain.puts[i].strike, T, r, chain.puts[i].ask, "P"), bid: impliedVolatility(S, chain.puts[i].strike, T, r, chain.puts[i].bid, "P") }; } callback(err, { strike: S, riskFree: r, expDate: chain.expDateStr, callVolatility: cVol, putVolatility: pVol }); }); }); } exports.getImpliedVolatility = getImpliedVolatility;
JavaScript
0
@@ -1,27 +1,4 @@ -/*jshint node:true */%0A%0A %22use @@ -34,20 +34,20 @@ ire( -'./Q +%22./q uotes.js ');%0A @@ -46,9 +46,9 @@ s.js -' +%22 );%0A%0A
73b2db76a428e341334ff9adaae43301154fc969
Remove escaping character in CDATA (#25)
lib/xunit-file.js
lib/xunit-file.js
/** * Module dependencies. */ var mocha = require("mocha") , Base = mocha.reporters.Base , utils = mocha.utils , escape = utils.escape , config = require("../config.json") , fs = require("fs") , path = require("path") , mkdirp = require("mkdirp") , dateFormat = require('dateformat') , filePathParser = require('./file-path-parser')(process, global.Date, dateFormat) , filePath = filePathParser(process.env.XUNIT_FILE || config.file || "${cwd}/xunit.xml") , consoleOutput = process.env.XUNIT_SILENT ? {} : config.consoleOutput || {}; /** * Save timer references to avoid Sinon interfering (see GH-237). */ var Date = global.Date , setTimeout = global.setTimeout , setInterval = global.setInterval , clearTimeout = global.clearTimeout , clearInterval = global.clearInterval; /** * Expose `XUnitFile`. */ exports = module.exports = XUnitFile; /** * Initialize a new `XUnitFile` reporter. * * @param {Runner} runner * @api public */ function XUnitFile(runner) { Base.call(this, runner); var stats = this.stats , tests = [] , fd; mkdirp.sync(path.dirname(filePath)); fd = fs.openSync(filePath, 'w', 0755); runner.on('suite', function(suite){ if(consoleOutput.suite){ console.log(' ' + suite.title); } }); runner.on('test', function(test){ if(consoleOutput.test){ console.log(' ◦ ' + test.title); } }); runner.on('pass', function(test){ tests.push(test); }); runner.on('fail', function(test){ if(consoleOutput.fail){ console.log(' - ' + test.title); } tests.push(test); }); runner.on('pending', function(test) { tests.push(test); }); runner.on('end', function(){ var timestampStr = (new Date).toISOString().split('.', 1)[0]; appendLine(fd, tag('testsuite', { name: process.env.SUITE_NAME || 'Mocha Tests' , tests: stats.tests , failures: stats.failures , errors: 0 , skipped: stats.tests - stats.failures - stats.passes , timestamp: timestampStr , time: stats.duration / 1000 }, false)); if( process.env.XUNIT_LOG_ENV) { logProperties(fd); } tests.forEach(function(test){ writeTest(fd, test); }); appendLine(fd, '</testsuite>'); fs.closeSync(fd); }); } /** * Inherit from `Base.prototype`. */ XUnitFile.prototype.__proto__ = Base.prototype; /** * Writes a list of process and environment variables to the <properties> section in the XML. */ function logProperties(fd) { var attrs = new Object(); var properties = "\n"; properties += logProperty('process.arch', process.arch); properties += logProperty('process.platform', process.platform); properties += logProperty('process.memoryUsage', objectToString(process.memoryUsage())); properties += logProperty('process.cwd', process.cwd()); properties += logProperty('process.execPath', process.execPath) properties += logProperty('process.execArgv', process.execArgv.join( ' ')); properties += logProperty('process.argv', process.argv.join( ' ')); properties += logProperty('process.version', process.version.replace('"','')); properties += logProperty('process.versions', objectToString(process.versions)); properties += logProperty('process.env.PATH', process.env.PATH); properties += logProperty('process.env.NODE_PATH', process.env.NODE_PATH); properties += logProperty('process.env.SUITE_NAME', process.env.SUITE_NAME); properties += logProperty('process.env.XUNIT_FILE', process.env.XUNIT_FILE); properties += logProperty('process.env.LOG_XUNIT', process.env.LOG_XUNIT); appendLine(fd, tag('properties', {}, false, properties)); } /** * Formats a single property value. */ function logProperty( name, value) { return ' ' + tag('property', { name: name, value: value }, true) + '\n'; } /** * Simple utility to convert a flat Object to a readable string. */ function objectToString( obj) { var arrayString = ''; if( obj) { for (var prop in obj) { var propValue = '' + obj[prop]; if( arrayString.length > 0) { arrayString += ', '; } arrayString += prop + ": '" + propValue.replace( "'", "\\'") + "'"; } } return '[ ' + arrayString + ']'; } /** * Output tag for the given `test.` */ function writeTest(fd, test) { var attrs = { classname: test.parent.fullTitle() , name: test.title // , time: test.duration / 1000 //old ,time: test.duration ? test.duration / 1000 : 0 //new }; if ('failed' == test.state) { var err = test.err; appendLine(fd, tag('testcase', attrs, false, tag('failure', { message: escape(err.message) }, false, cdata(err.stack)))); } else if (test.pending) { delete attrs.time; appendLine(fd, tag('testcase', attrs, false, tag('skipped', {}, true))); } else { appendLine(fd, tag('testcase', attrs, true) ); } } /** * HTML tag helper. */ function tag(name, attrs, close, content) { var end = close ? '/>' : '>' , pairs = [] , result; for (var key in attrs) { pairs.push(key + '="' + escape(attrs[key]) + '"'); } result = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end; if (content) result += content + '</' + name + end; return result; } /** * Return cdata escaped CDATA `str`. */ function cdata(str) { return '<![CDATA[' + escape(str) + ']]>'; } function appendLine(fd, line) { if (process.env.LOG_XUNIT) { console.log(line); } fs.writeSync(fd, line + "\n", null, 'utf8'); }
JavaScript
0
@@ -2153,18 +2153,16 @@ ;%0A %7D%0A - %0A tes @@ -2480,17 +2480,16 @@ the XML. - %0A */%0Afun @@ -3704,17 +3704,16 @@ y value. - %0A */%0A%0Afu @@ -3894,17 +3894,16 @@ string. - %0A */%0A%0Afu @@ -5263,22 +5263,8 @@ urn -cdata escaped CDAT @@ -5326,19 +5326,11 @@ ' + -escape( str -) + '
25c6fe95b98fd4dae31bf59c9c8c101c0540e945
exit status 1 if tests fail
web/javascript/gulpfile.js
web/javascript/gulpfile.js
var browserify = require('browserify'); var gulp = require('gulp'); var gutil = require('gulp-util'); var source = require("vinyl-source-stream"); var reactify = require('reactify'); var watchify = require('watchify'); var uglify = require('gulp-uglify'); var buffer = require('vinyl-buffer'); var concat = require('gulp-concat'); var jshint = require('gulp-jshint'); var addsrc = require('gulp-add-src'); var jasmineBrowser = require('gulp-jasmine-browser'); var production = (process.env.NODE_ENV === 'production'); function rebundle(bundler) { var stream = bundler.bundle(). on('error', gutil.log.bind(gutil, 'Browserify Error')). pipe(source('../public/build.js')); if (production) { stream = stream.pipe(buffer()).pipe(uglify()); } stream.pipe(gulp.dest('.')); } gulp.task('compile-build', function () { var bundler = browserify('./event_handler.jsx', { debug: !production }); bundler.transform(reactify); return rebundle(bundler); }); gulp.task('compile-concourse', function () { var stream = gulp.src('./concourse/*.js') .pipe(jshint()) .pipe(jshint.reporter('jshint-stylish')) .pipe(concat('concourse.js')) if (production) { stream = stream.pipe(buffer()).pipe(uglify()); } return stream.pipe(gulp.dest('../public/')); }); // jasmine stuff var externalFiles = ["../public/jquery-2.1.1.min.js", "spec/helpers/**/*.js"] var jsSourceFiles = ["concourse/*.js", "spec/**/*_spec.js"] var hintSpecFiles = function() { gulp.src('spec/**/*_spec.js') } gulp.task('jasmine-cli', function(cb) { return gulp.src(jsSourceFiles) .pipe(jshint()) .pipe(jshint.reporter('jshint-stylish')) .on('error', function(){ process.exit(1); }) .pipe(addsrc(externalFiles)) .pipe(jasmineBrowser.specRunner({console: true})) .pipe(jasmineBrowser.phantomjs()); }); gulp.task('jasmine', function() { return gulp.src(jsSourceFiles) .pipe(addsrc(externalFiles)) .pipe(jasmineBrowser.specRunner()) .pipe(jasmineBrowser.server()); }); gulp.task('watch', function () { var bundler = watchify(browserify('./event_handler.jsx'), { debug: !production }); bundler.transform(reactify); bundler.on('update', function() { rebundle(bundler); }); return rebundle(bundler); }); gulp.task('default', ['compile-build', 'compile-concourse']);
JavaScript
0
@@ -1675,48 +1675,37 @@ r', -function()%7B%0A process.exit(1);%0A %7D +process.exit.bind(process, 1) )%0A @@ -1826,16 +1826,64 @@ tomjs()) +%0A .on('error', process.exit.bind(process, 1)) ;%0A%7D);%0A%0Ag
18cce756a1476d6bf4f88641838b50423ed0aeff
Remove async keyword
src/api-gateway-websocket/WebSocketClients.js
src/api-gateway-websocket/WebSocketClients.js
import { WebSocketConnectEvent, WebSocketDisconnectEvent, WebSocketEvent, } from './lambda-events/index.js' import debugLog from '../debugLog.js' import LambdaFunctionPool from '../LambdaFunctionPool.js' import serverlessLog from '../serverlessLog.js' import { createUniqueId } from '../utils/index.js' const { stringify } = JSON export default class WebSocketClients { constructor(options, config, provider) { this._clients = new Map() this._config = config this._lambdaFunctionPool = new LambdaFunctionPool() this._options = options this._provider = provider this._webSocketRoutes = new Map() this._websocketsApiRouteSelectionExpression = this._provider.websocketsApiRouteSelectionExpression || '$request.body.action' } _addWebSocketClient(client, connectionId) { this._clients.set(client, connectionId) this._clients.set(connectionId, client) } _removeWebSocketClient(client) { const connectionId = this._clients.get(client) this._clients.delete(client) this._clients.delete(connectionId) return connectionId } _getWebSocketClient(connectionId) { return this._clients.get(connectionId) } async _processEvent(websocketClient, connectionId, route, event) { let routeOptions = this._webSocketRoutes.get(route) if (!routeOptions && route !== '$connect' && route !== '$disconnect') { routeOptions = this._webSocketRoutes.get('$default') } if (!routeOptions) { return } const sendError = (err) => { if (websocketClient.readyState === /* OPEN */ 1) { websocketClient.send( stringify({ connectionId, message: 'Internal server error', requestId: '1234567890', }), ) } // mimic AWS behaviour (close connection) when the $connect route handler throws if (route === '$connect') { websocketClient.close() } debugLog(`Error in route handler '${routeOptions}'`, err) } const { functionName, functionObj } = routeOptions const lambdaFunction = this._lambdaFunctionPool.get( functionName, functionObj, this._provider, this._config, this._options, ) const requestId = createUniqueId() lambdaFunction.setEvent(event) lambdaFunction.setRequestId(requestId) // let result try { /* result = */ await lambdaFunction.runHandler() const { billedExecutionTimeInMillis, executionTimeInMillis, } = lambdaFunction serverlessLog( `(λ: ${functionName}) RequestId: ${requestId} Duration: ${executionTimeInMillis.toFixed( 2, )} ms Billed Duration: ${billedExecutionTimeInMillis} ms`, ) // TODO what to do with "result"? } catch (err) { sendError(err) } } async addClient(webSocketClient, connectionId) { this._addWebSocketClient(webSocketClient, connectionId) const connectEvent = new WebSocketConnectEvent(connectionId, this._options) this._processEvent(webSocketClient, connectionId, '$connect', connectEvent) webSocketClient.on('close', () => { debugLog(`disconnect:${connectionId}`) this._removeWebSocketClient(webSocketClient) const disconnectEvent = new WebSocketDisconnectEvent(connectionId) this._processEvent( webSocketClient, connectionId, '$disconnect', disconnectEvent, ) }) webSocketClient.on('message', (message) => { debugLog(`message:${message}`) let route = null if ( this._websocketsApiRouteSelectionExpression.startsWith('$request.body.') ) { // route = request.payload route = message // TODO if (typeof route === 'object') { this._websocketsApiRouteSelectionExpression .replace('$request.body.', '') .split('.') .forEach((key) => { if (route) { route = route[key] } }) } else { route = null } } if (typeof route !== 'string') { route = null } route = route || '$default' debugLog(`route:${route} on connection=${connectionId}`) const event = new WebSocketEvent(connectionId, route, message) this._processEvent(webSocketClient, connectionId, route, event) }) } addRoute(functionName, functionObj, route) { // set the route name this._webSocketRoutes.set(route, { functionName, functionObj, }) serverlessLog(`route '${route}'`) } close(connectionId) { const client = this._getWebSocketClient(connectionId) if (client) { client.close() return true } return false } send(connectionId, payload) { const client = this._getWebSocketClient(connectionId) if (client) { client.send(payload.toString()) return true } return false } }
JavaScript
0.000002
@@ -2849,22 +2849,16 @@ %0A %7D%0A%0A -async addClien
0571b1a4c92b5fe8d6a0495cbe708e326ecbc70e
add error handling for GET
back-end/api.js
back-end/api.js
'use strict'; // API module.exports = (app) => { var PassFailData = require('./models/passfail.js'); // Schema var statusList = require('../mock/passfail.json'); // importing mock data app.get('/', (req, res) => { res.render('index'); }); // CREATE app.post('/api/status', (req, res) => { // URL of request var statusReport = req.body; // the body of the request will be the data for the todo PassFailData.create(passfail, (err, passfail) => { // Store data in MongoDB if (err) { return res.status(500).json({err: err.message}); } res.json({'passfail': passfail, message: 'PassFail Data Created'}); // send json response with key/value pairs }); }); // READ app.get('/api/status', (req, res) => { // res.send('These are the pass/fails!'); res.json({statusList: statusList}); // res.send({todos: []}); // PassFailData.find({}, (err, passfail) => { // The model's 'find' method. // // The first parameter of the find method is going to be a JSON object where you pass conditions of the documents you want to find. // // * An empty object here would return everything // // The second paramenter of the find method is going to be a callback function which takes 2 arguments; a potenial error and the data. // if (err) { // return res.status(500).json({message: err.message}); // } // res.json({passfail: passfail}); // }).sort({"song": 1}); }); // // UPDATE // app.put('/todos/:id', (req, res) => { // add an id parameter for the put route; the syntax for adding parameters is colon then parameter name // var id = req.params.id; // get the id key from the req.params object (this is handled by Express) // var todo = req.body; // the data for the todo // if (todo && todo._id !== id) { // if there is a todo and its id does not match the requested id // return res.status(500).json({err: "IDs don't match!"}); // } // Todo.findByIdAndUpdate(id, todo, {new: true}, (err, todo) => { // The Mongoose model has a 'findByIdAndUpdate' method // // The first parameter is the id from the route which Mongoose will use for lookup // // The second parameter is the new data being sent to MongoDB // // The third parameter is an options parameter, which is an object with our options. This is telling Mongoose to return the new (updated) data. // // The fourth parameter is the callback function with potential error and the new todo // if (err) { // return res.status(500).json({err: err.message}); // } // res.json({'todo': todo, message: 'Todo Updated'}); // send json response with key/value pairs // }); // }); // // // DELETE // app.delete('/todos/:id', function(req, res) { // add an id parameter for the put route; the syntax for adding parameters is colon then parameter name // var id = req.params.id; // get the id key from the req.params object (this is handled by Express) // Todo.findByIdAndRemove(id, function(err, result) { // The Mongoose model has a 'findByIdAndRemove' method // // The first parameter is the id from the route which Mongoose will use for lookup // // The second parameter is the callback function with potential error // if (err) { // return res.status(500).json({ err: err.message }); // } // res.json({ message: 'Todo Deleted' }); // send json response with key/value pair // }); // }); };
JavaScript
0
@@ -734,574 +734,82 @@ %7B%0A -// res.send('These are the pass/fails!');%0A res.json(%7BstatusList: statusList%7D);%0A // res.send(%7Btodos: %5B%5D%7D);%0A // PassFailData.find(%7B%7D, (err, passfail) =%3E %7B // The model's 'find' method.%0A // // The first parameter of the find method is going to be a JSON object where you pass conditions of the documents you want to find.%0A // // * An empty object here would return everything%0A // // The second paramenter of the find method is going to be a callback function which takes 2 arguments; a potenial error and the data.%0A // +PassFailData.find(%7B%7D, (err, passfail) =%3E %7B // The model's 'find' method.%0A @@ -819,19 +819,16 @@ (err) %7B%0A - // re @@ -882,20 +882,15 @@ %7D);%0A - // %7D%0A -// r @@ -902,33 +902,35 @@ on(%7B -passfail: passfail +statusList: statusList %7D);%0A -// %7D). @@ -947,12 +947,42 @@ g%22: +- 1%7D); + // sort in descending order %0A%7D);
a2ad62a77557d2ccd18bcc1ba276b214a142e51a
Bring back mistakenly removed bin files support
lint-directory.js
lint-directory.js
'use strict'; var isCallable = require('es5-ext/object/is-callable') , callable = require('es5-ext/object/valid-callable') , reEscape = require('es5-ext/reg-exp/escape') , endsWith = require('es5-ext/string/#/ends-with') , d = require('d') , deferred = require('deferred') , memoize = require('memoizee/plain') , resolve = require('path').resolve , readdir = require('fs2/readdir') , getOptsReader = require('./lib/options/read').getReader , normalizeOpts = require('./lib/options/normalize') , lintignoreMode = require('./lib/lintignore-mode') , LintFiles = require('./lint-files').LintFiles , isArray = Array.isArray, push = Array.prototype.push , getReExtension, lintDirectory, LintDirectory; getReExtension = memoize(function (ext) { return new RegExp('\\.' + reEscape(ext) + '$'); }); LintDirectory = function () { LintFiles.call(this); }; LintDirectory.prototype = Object.create(LintFiles.prototype, { init: d(function () { var waiting; this.reader = readdir(this.root, { watch: this.watch, depth: this.depth, stream: this.stream, ignoreRules: this.ignoreRules, type: { file: true }, pattern: getReExtension(this.fileExt) }); if (this.watch || this.stream) { if (this.stream) { waiting = []; } this.reader.on('change', function (data) { if (this.promise.resolved) { deferred.map(data.added, this.prelint, this).done(); } else { push.apply(waiting, data.added.map(this.prelint, this)); } data.removed.forEach(function (name) { if (this.linters[name]) { this.linters[name].close(); this.clear(name); } }, this); }.bind(this)); this.reader.on('end', function () { delete this.linters; this.promise.emit('end'); }.bind(this)); } this.reader.done(function (names) { (this.stream ? deferred.map(waiting) : deferred.map(names, this.prelint, this)) .done(this.resolve.bind(this, this.result), this.reject); }.bind(this), this.reject); this.promise.root = this.root; this.promise.xlintId = this.linter.xlintId; return this.promise; }), prelint: d(function (name) { if (endsWith.call(name, this.fileExt)) return this.lint(name); if (this.fileExt !== 'js') return null; return this.checkSheBang(name)(function (isNodeScript) { return isNodeScript ? this.lint(name) : null; }.bind(this)); }), close: d(function () { if (this.linters) { this.reader.close(); LintFiles.prototype.close.call(this); } }) }); lintDirectory = function (linter, path, options) { var lint, orgIsRoot, name, promise; lint = new LintDirectory(); lint.root = path; lint.linter = linter; lint.options = options.options; lint.watch = options.watch; lint.cache = options.cache; lint.depth = options.depth; lint.fileExt = options.fileExt || 'js'; lint.stream = options.stream; if (options.ignoreRules) { lint.ignoreRules = isArray(options.ignoreRules) ? options.ignoreRules.concat('lint') : [String(options.ignoreRules), 'lint']; } else { lint.ignoreRules = ['lint']; } lint.readOptions = getOptsReader(options.watch); name = options.watch ? 'isRootWatcher' : 'isRoot'; orgIsRoot = lintignoreMode[name]; lintignoreMode[name] = lint.readOptions.isRoot; promise = lint.init(); lintignoreMode[name] = orgIsRoot; return promise; }; lintDirectory.returnsPromise = true; module.exports = exports = function (linter, dirname/*, options, cb*/) { var options, cb; callable(linter); dirname = resolve(String(dirname)); options = arguments[2]; cb = arguments[3]; if ((cb == null) && isCallable(options)) { cb = options; options = {}; } else { options = Object(options); if (options.options) { options.options = normalizeOpts(options.options); } } return lintDirectory(linter, dirname, options).cb(cb); }; exports.returnsPromise = true; exports.lintDirectory = lintDirectory; exports.LintDirectory = LintDirectory;
JavaScript
0
@@ -834,28 +834,126 @@ t) %7B - return new RegExp(' +%0A%09if (ext === 'js') %7B%0A%09%09return new RegExp('(?:%5E%7C%5B%5C%5C/%5C%5C%5C%5C%5D)(?:%5B%5C0-%5C%5C-0-%5C%5C%5B%5C%5C%5D-%5Cuffff%5D+%7C' +%0A%09%09%09'%5B%5C0-%5C%5C.0-%5C%5C%5B%5C%5C%5D-%5Cuffff%5D* %5C%5C.' @@ -976,13 +976,66 @@ + ' +) $'); - +%0A%09%7D%0A%09return new RegExp('%5C%5C.' + reEscape(ext) + '$');%0A %7D);%0A
0340126212c52850ec8d2158d5d386ede0c86459
Update UDPefef
benchmark.js
benchmark.js
// /** * Created by tungtouch on 2/9/15. */ var cluster = require('cluster'); var numCPUs = require('os').cpus().length; var colors = require('colors'); var dgram = require('dgram'); var message = new Buffer("Some bytes hello world bo bo bo world HEHEHEHE ahhaha hohoho hehe:"); var client = dgram.createSocket("udp4"); var async = require('async'); var max = 1000; var serverUDP = "128.199.126.250"; //"128.199.149.159"; //128.199.126.250 var port = 4545; var delay = 50; var numCluster = 100; var maxReq = max * numCluster; var arr = []; for (var i = 0; i < max; i++) { arr.push(i); } var a = 0; //[2GB]128.199.126.250 [8GB]128.199.109.202 if (cluster.isMaster) { // Keep track of http requests var numReqs = 0; var totalReqs = 0; var second = 0; setInterval(function() { console.log( colors.red("Gói tin/s: ", numReqs), " | ", colors.yellow("Tổng gói tin: ", totalReqs), " | ", colors.blue("Thời gian: ", second++ +"s")); numReqs = 0; if(totalReqs == maxReq) { console.log(colors.cyan("\n-------------------------------")); console.log("Tổng thời gian: ", second-1 + "s", " | Tổng số gói tin:", totalReqs); console.log(colors.cyan("Kết quả hệ thống: ", colors.bold(totalReqs / second)), " Thiết bị/giây ! \n"); process.exit(1); } }, 1000); // Count requestes function messageHandler(msg) { if (msg.cmd && msg.cmd == 'notifyRequest') { numReqs += 1; totalReqs +=1; } } // Start workers and listen for messages containing notifyRequest for (var i = 0; i < numCluster; i++) { cluster.fork(); } Object.keys(cluster.workers).forEach(function(id) { cluster.workers[id].on('message', messageHandler); }); } else { var q = async.queue(function(index, cb){ //console.log("Index: ", index); setTimeout(function () { client.send(message, 0, message.length, port, serverUDP, function (err) { //console.log("Request : ", a++); process.send({ cmd: 'notifyRequest' }); if(err){ console.log('ERROR :', err); } cb(err); }); }, delay); }); q.push(arr); }
JavaScript
0
@@ -466,18 +466,18 @@ delay = +2 5 -0 ;%0Avar nu
2f65efbe17adbfccecbeec8800e2018fd7534d66
update form-checkbox.js for bootstrap beta-3 (#1508)
src/components/form-checkbox/form-checkbox.js
src/components/form-checkbox/form-checkbox.js
import { idMixin, formRadioCheckMixin, formMixin, formSizeMixin, formStateMixin, formCustomMixin } from '../../mixins' import { isArray } from '../../utils/array' import { looseEqual } from '../../utils' export default { mixins: [idMixin, formRadioCheckMixin, formMixin, formSizeMixin, formStateMixin, formCustomMixin], render (h) { const t = this const input = h( 'input', { ref: 'check', class: [t.is_ButtonMode ? '' : (t.is_Plain ? 'form-check-input' : 'custom-control-input'), t.get_StateClass], directives: [ { name: 'model', rawName: 'v-model', value: t.computedLocalChecked, expression: 'computedLocalChecked' } ], attrs: { id: t.safeId(), type: 'checkbox', name: t.get_Name, disabled: t.is_Disabled, required: t.is_Required, autocomplete: 'off', 'true-value': t.value, 'false-value': t.uncheckedValue, 'aria-required': t.is_Required ? 'true' : null }, domProps: { value: t.value, checked: t.is_Checked }, on: { focus: t.handleFocus, blur: t.handleFocus, change: t.emitChange, __c: (evt) => { const $$a = t.computedLocalChecked const $$el = evt.target if (isArray($$a)) { // Multiple checkbox const $$v = t.value let $$i = t._i($$a, $$v) // Vue's 'loose' Array.indexOf if ($$el.checked) { // Append value to array $$i < 0 && (t.computedLocalChecked = $$a.concat([$$v])) } else { // Remove value from array $$i > -1 && (t.computedLocalChecked = $$a.slice(0, $$i).concat($$a.slice($$i + 1))) } } else { // Single checkbox t.computedLocalChecked = $$el.checked ? t.value : t.uncheckedValue } } } } ) let indicator = h(false) if (!t.is_ButtonMode && !t.is_Plain) { indicator = h('span', { attrs: { 'aria-hidden': 'true' } }) } const description = h( 'span', { class: t.is_ButtonMode ? null : (t.is_Plain ? 'form-check-label' : 'custom-control-label') }, [t.$slots.default] ) const label = h( 'label', { class: [t.is_ButtonMode ? t.buttonClasses : t.is_Plain ? 'form-check-label' : t.labelClasses] }, [input, indicator, description] ) if (t.is_Plain && !t.is_ButtonMode) { return h('div', { class: ['form-check', { 'form-check-inline': !t.is_Stacked }] }, [label]) } else { return label } }, props: { value: { default: true }, uncheckedValue: { // Not applicable in multi-check mode default: false }, indeterminate: { // Not applicable in multi-check mode type: Boolean, default: false } }, computed: { labelClasses () { return [ 'custom-control', 'custom-checkbox', this.get_Size ? `form-control-${this.get_Size}` : '', this.get_StateClass ] }, is_Checked () { const checked = this.computedLocalChecked if (isArray(checked)) { for (let i = 0; i < checked.length; i++) { if (looseEqual(checked[i], this.value)) { return true } } return false } else { return looseEqual(checked, this.value) } } }, watch: { computedLocalChecked (newVal, oldVal) { if (looseEqual(newVal, oldVal)) { return } this.$emit('input', newVal) this.$emit('update:indeterminate', this.$refs.check.indeterminate) }, checked (newVal, oldVal) { if (this.is_Child || looseEqual(newVal, oldVal)) { return } this.computedLocalChecked = newVal }, indeterminate (newVal, oldVal) { this.setIndeterminate(newVal) } }, methods: { emitChange ({ target: { checked } }) { // Change event is only fired via user interaction // And we only emit the value of this checkbox if (this.is_Child || isArray(this.computedLocalChecked)) { this.$emit('change', checked ? this.value : null) if (this.is_Child) { // If we are a child of form-checkbbox-group, emit change on parent this.$parent.$emit('change', this.computedLocalChecked) } } else { // Single radio mode supports unchecked value this.$emit('change', checked ? this.value : this.uncheckedValue) } this.$emit('update:indeterminate', this.$refs.check.indeterminate) }, setIndeterminate (state) { // Indeterminate only supported in single checkbox mode if (this.is_Child || isArray(this.computedLocalChecked)) { return } this.$refs.check.indeterminate = state // Emit update event to prop this.$emit('update:indeterminate', this.$refs.check.indeterminate) } }, mounted () { // Set initial indeterminate state this.setIndeterminate(this.indeterminate) } }
JavaScript
0
@@ -2000,187 +2000,70 @@ -let indicator = h(false)%0A if (!t.is_ButtonMode && !t.is_Plain) %7B%0A indicator = h('span', %7B attrs: %7B 'aria-hidden': 'true' %7D %7D)%0A %7D%0A%0A const description = h(%0A 'span +const description = h(%0A t.is_ButtonMode ? 'span' : 'label ',%0A @@ -2203,21 +2203,44 @@ -const label = +if (!t.is_ButtonMode) %7B%0A return h(%0A @@ -2245,25 +2245,27 @@ (%0A -'label + 'div ',%0A + %7B @@ -2276,43 +2276,18 @@ s: %5B -t.is_ButtonMode ? t.buttonClasses : +%0A t.i @@ -2303,30 +2303,24 @@ 'form-check --label ' : t.labelC @@ -2329,19 +2329,16 @@ sses -%5D %7D ,%0A %5Binp @@ -2337,218 +2337,304 @@ -%5Binput, indicator, description%5D%0A )%0A%0A if (t.is_Plain && !t.is_ButtonMode) %7B%0A return h('div', %7B class: %5B'form-check', %7B 'form-check-inline': !t.is_Stacked %7D%5D %7D, %5Blabel%5D)%0A %7D else %7B%0A return label + %7B 'form-check-inline': t.is_Plain && !t.is_Stacked %7D,%0A %7B 'custom-control-inline': !t.is_Plain && !t.is_Stacked %7D%0A %5D %7D,%0A %5Binput, description%5D%0A )%0A %7D else %7B%0A return h(%0A 'label',%0A %7B class: %5Bt.buttonClasses%5D %7D,%0A %5Binput, description%5D%0A ) %0A
fed03aece2537d4adb667c902894ba3324d05856
add recommender
www/assets/js/main.js
www/assets/js/main.js
'use strict' // initialize Hoodie var hoodie = new Hoodie(); // on ready calls all binds $(function () { if(hoodie.account.username) { hoodie.store.find('settings', 'user-settings') .done(function(settings) { $('#username').append(settings.name || hoodie.account.username) $('h2.welcoming').append(settings.name || hoodie.account.username ) }) .fail(function() { $('#username').append(hoodie.account.username) $('h2.welcoming').append(hoodie.account.username) // console.log((!$('#main') && hoodie.account.username == undefined)) // location.href = 'index.html'; }) } $('#logout').bind('click', signOutUsr); $('#sign-up').bind('submit', submitSignUp); $('#go-on-vacation').bind('click', result); $('.day-ani').bind('live', animateDays) }) // animation of work/vac days in dashboard var animateDays = function animateDays() { alert('jo') } // sign-in on main page var submitSignUp = function submitSignUp() { var usr = $('#email').val(); var pwd = $('#pwd').val(); hoodie.account.signIn(usr, pwd).done(function() { if(hoodie.account.username) { location.href = 'dashboard.html'; } }).fail(function () { hoodie.account.signUp(usr, pwd, pwd) .done(function(){ if(hoodie.account.username) { location.href = 'settings-init.html'; } }) .fail(function () { alert('Your credentials are wrong!'); }) }) return false; } var signOutUsr = function signOutUsr () { hoodie.account.signOut().done(function () { location.href = 'index.html'; }) } var buildUrl = function buildUrl(from, to) { var base = "http://justrelax.rrbone.io/booking/holiday?" var urlReq = base + "from=" + from + "&to=" + to; return hoodie.store.find("settings", "user-settings") .then(function(s) { urlReq += "&location=" + s.favDestination; var adults = parseInt(s.adults, 10); var kids = parseInt(s.kids, 10); var budget = parseInt(s.budget, 10); if (adults > 0) urlReq += "&adults=" + adults; if (kids > 0) urlReq += "&kids=" + kids; if (budget > 0) urlReq += "&budget=" + budget; return urlReq; }) } // return results var result = function result(event) { var e = event.target; var urlReq = e.getAttribute('data-url'); var scores = window.engine.scores() var recommends = window.engine.blocks(scores); for (var i=1; i<=3; i++) { (function(i) { var from = recommends[i-1].start.date; var to = recommends[i-1].end.date; buildUrl(from, to).then(function(urlReq) { $.ajax({ url: urlReq }) .done(function( data ) { var dom = $(".output"); var res = data.results; var f = moment(from).format("DD.MM.YYYY"); var t = moment(to).format("DD.MM.YYYY"); $(".output-option-"+i).text( "Option " + i + ": " + f + " - " + t ) res.slice(0,3).forEach(function (obj) { var li = '<li><a class="btn btn-lage btn-danger r" href="' + obj.link + '" target="_blank">' + obj.price + ' € / p. n. &amp; p. <br /> Book now!</a> <img class="l" src="' + obj.image + '"/> <h3 class="l">' + obj.name + '<br /><small>' + obj.city + '</small></h3></li>' $(".output-"+i).append(li).fadeIn().removeClass('hide');; }) }); }); })(i); } $(".output").fadeIn().removeClass('hide'); $('#dashboard').fadeOut().addClass('hide'); } if (window.recommender) { window.engine = recommender({ dates: dates, lastVacation: moment(), blockedWork: [ { from: '2015-06-28', to: '2015-06-30', days: 3 } ], blockedVac: [ { from: '2015-07-03', to: '2015-07-13', days: 2 } ] }) }
JavaScript
0
@@ -2165,128 +2165,625 @@ %0A%7D%0A%0A -// return results%0Avar result = function result(event) %7B%0A var e = event.target;%0A var urlReq = e.getAttribute('data-url' +function deserializeDaterange(str) %7B%0A var start = moment(str.split(' - ')%5B0%5D)%0A var end = moment(str.split(' - ')%5B1%5D)%0A%0A return %7B%0A from: start.format('YYYY-MM-DD'),%0A end: end.format('YYYY-MM-DD'),%0A days: end.diff(start)%0A %7D%0A%7D%0A%0A// return results%0Avar result = function result(event) %7B%0A var e = event.target;%0A var engine = recommender(%7B%0A dates: dates,%0A lastVacation: moment(),%0A blockedWork: %5B%0A %7B%0A from: '2015-06-28',%0A to: '2015-06-30',%0A days: 3%0A %7D%0A %5D,%0A blockedVac: %5B%0A %7B%0A from: '2015-07-03',%0A to: '2015-07-13',%0A days: 2%0A %7D%0A %5D%0A %7D );%0A%0A @@ -2793,31 +2793,24 @@ ar scores = -window. engine.score @@ -2832,23 +2832,16 @@ mends = -window. engine.b @@ -3945,339 +3945,4 @@ );%0A%7D -%0A%0Aif (window.recommender) %7B%0A window.engine = recommender(%7B%0A dates: dates,%0A lastVacation: moment(),%0A blockedWork: %5B%0A %7B%0A from: '2015-06-28',%0A to: '2015-06-30',%0A days: 3%0A %7D%0A %5D,%0A blockedVac: %5B%0A %7B%0A from: '2015-07-03',%0A to: '2015-07-13',%0A days: 2%0A %7D%0A %5D%0A %7D)%0A%7D%0A
9d332cee98707e8d5a0f5b00b8d064bc053f0684
Fix redirects.
manager.js
manager.js
var _ = require('underscore'); var uri = require('uri-js'); var http = require('http'); var https = require('https'); var config = require('./config.js'); var utils = require('./utils'); var clientConnection = require('./clientConnection'); var modifiers = require('./modifiers'); var everyone = clientConnection.everyone; /* Manages clients, screens, and content. * * - Client: A connected web browser. Shows one or more Screens. * - Screen: A place for content to live. Viewed by one or more clients. * - Content: A thing shown on a screen. */ var screens = []; var nextScreen = 0; /* This is a now.js function. */ exports.getScreens = function() { return screens; }; var nextContent = 0; var contentSet = []; _.each(config.resetUrls, function(url) { contentForUrl(url, Array.prototype.push.bind(contentSet)); }); utils.shuffle(contentSet); exports.addScreen = function(name) { var id = utils.getId(); var screen = { id: id, name: name, content: null, resetId: null }; screens.push(screen); cycleScreen(screen.id); sendScreenAdded(screen); }; removeScreen = function(id) { var screen = findScreen('id', id); if (screen !== undefined) { clearTimeout(screen.timeout); screens = _.without(screens, screen); sendScreenRemoved(screen); } }; findScreen = function(key, value, moveNextScreen) { var found, index; _.each(screens, function(s, i) { if (s[key] === value) { found = s; index = i; } }); if (moveNextScreen && index === nextScreen) { nextScreen = (nextScreen + 1) % screen.length; } return found; }; cycleScreen = function(screen_id) { var screen = findScreen('id', screen_id); if (screen === undefined) { return; } screen.content = getDefaultContent(); sendScreenChanged(screen); screen.timeout = setTimeout(cycleScreen.bind(null, screen_id), config.resetTime); }; /* Put new content on the next screen in the line up. */ exports.setUrl = function(url, screen_name, callback) { var screen; if (screens.length === 0) { utils.async(callback, {msg: 'No screens.'}); return; } if (screen_name) { screen = findScreen('name', screen_name, true); } // The above loop might fail, so check for that. if (screen === undefined) { screen = screens[nextScreen]; nextScreen = (nextScreen + 1) % screens.length; } contentForUrl(url, function(content) { screen.content = content; sendScreenChanged(screen); clearTimeout(screen.timeout); screen.timeout = setTimeout(cycleScreen.bind(null, screen.id), config.resetTime); utils.async(callback, content); }); }; exports.reset = function() { _.each(screens, function(screen) { screen.content = getDefaultContent(); sendScreenChanged(screen); }); }; function getDefaultContent() { var content = contentSet[nextContent]; if (++nextContent >= contentSet.length) { utils.shuffle(contentSet); nextContent = 0; } return content; } function contentForUrl(url, callback) { if (url.indexOf('://') === -1) { url = 'http://' + url; } var components = uri.parse(url); if (components.errors.length) { utils.async(callback, { message: "We couldn't parse a url from that." }); return; } if (components.host === undefined) { utils.async(callback, { message: "Couldn't load URL. (Maybe a bad redirect?)" }); } for (var i=0; i < modifiers.all.length; i++) { var out = modifiers.all[i]({url: url, components: components}); if (out) { utils.async(callback, out); return; } } var path = components.path; if (components.query) { path += '?' + components.query; } var port = components.port; var proto = http; if (components.scheme === 'https') { proto = https; port = 443; } var options = { method: 'HEAD', host: components.host, port: port, path: path }; var req = proto.request(options, function(res) { var headers = {}; _.each(res.headers, function(value, key) { headers[key.toLowerCase()] = value; }); console.log(url); if (res.statusCode >= 300 && res.statusCode < 400) { // redirect, handle it. console.log('redirect ' + headers.location); return _processUrl(headers.location, callback); } if (res.statusCode >= 400) { utils.async(callback, { message: 'There was a problem with the url (' + res.statusCode + ')' }); return; } var contentType = (headers['content-type'] || '').toLowerCase(); if (contentType.indexOf('image/') === 0) { utils.async(callback, { url: url, type: 'image' }); return; } var xframe = (headers['x-frame-options'] || '').toLowerCase(); if (xframe === 'sameorigin' || xframe === 'deny') { utils.async(callback, { message: "That site prevents framing. It won't work." }); return; } utils.async(callback, {type: 'url', url: url}); }); req.on('error', function(err) { console.log('Problem with HEAD request: ' + err.message); // We'll do it live. utils.async(callback, { type: 'url', url: url, message: "We're not sure about that, but we'll give it ago." }); }); req.end(); } /********** Now.js connections **********/ // Now.js sometimes has some different calling conventions, so translate. // Screen objects store some things that can't go over the wire. So don't // include those. function _getWireSafeScreen(screen) { return { 'id': screen.id, 'name': screen.name, 'content': screen.content }; } everyone.now.getScreens = function(callback) { var screens = exports.getScreens(); screens = _.map(screens, _getWireSafeScreen); utils.async(callback, screens); }; everyone.now.addScreen = exports.addScreen; everyone.now.removeScreen = removeScreen; function sendScreenAdded(screen) { everyone.now.screenAdded(_getWireSafeScreen(screen)); } function sendScreenChanged(screen) { everyone.now.screenChanged(_getWireSafeScreen(screen)); } function sendScreenRemoved(screen) { everyone.now.screenRemoved(_getWireSafeScreen(screen)); }
JavaScript
0
@@ -4264,16 +4264,18 @@ urn -_process +contentFor Url(
0110313bef5747237bd3d5b6ff074d3dd42374d7
Rename Renderer.doc to Renderer.docController.
src/renderer.js
src/renderer.js
var Article = require('./article'); var _ = require("underscore"); // Renders an article // -------- // var Renderer = function(doc) { this.doc = doc; // var that = this; // TODO: use reflection this.nodeTypes = Article.nodeTypes; // Collect all node views this.nodes = {}; }; Renderer.Prototype = function() { // Create a node view // -------- // // Experimental: using a factory which creates a view for a given node type // As we want to be able to reuse views // However, as the matter is still under discussion consider the solution here only as provisional. // We should create views, not only elements, as we need more, e.g., event listening stuff // which needs to be disposed later. this.createView = function(node) { var NodeView = this.nodeTypes[node.type].View; if (!NodeView) { throw new Error('Node type "'+node.type+'" not supported'); } // Note: passing the renderer to the node views // to allow creation of nested views var nodeView = new NodeView(node, this); // we connect the listener here to avoid to pass the document itself into the nodeView nodeView.listenTo(this.doc, "operation:applied", nodeView.onGraphUpdate); // register node view to be able to look up nested views later this.nodes[node.id] = nodeView; return nodeView; }; // Render it // -------- // this.render = function() { _.each(this.nodes, function(nodeView) { nodeView.dispose(); }); var frag = document.createDocumentFragment(); var docNodes = this.doc.container.getTopLevelNodes(); _.each(docNodes, function(n) { frag.appendChild(this.createView(n).render().el); }, this); return frag; }; }; Renderer.prototype = new Renderer.Prototype(); module.exports = Renderer;
JavaScript
0
@@ -126,16 +126,26 @@ tion(doc +Controller ) %7B%0A th @@ -150,22 +150,42 @@ this.doc - = doc +Controller = docController ;%0A // v @@ -351,17 +351,16 @@ ion() %7B%0A -%0A // Cre @@ -1192,16 +1192,26 @@ this.doc +Controller , %22opera @@ -1603,16 +1603,26 @@ this.doc +Controller .contain
753cfb719baecca7c13313161f0f76935a05bc58
Update profiler.js
svc/profiler.js
svc/profiler.js
/** * Worker to fetch updated player profiles * */ const async = require('async'); const queries = require('../store/queries'); const db = require('../store/db'); // const redis = require('../store/redis'); const utility = require('../util/utility'); const { insertPlayer, bulkIndexPlayer } = queries; const { getData, generateJob, convert64to32 } = utility; function getSummaries(cb) { db.raw('SELECT account_id from players TABLESAMPLE SYSTEM_ROWS(100)').asCallback((err, result) => { if (err) { return cb(err); } const container = generateJob('api_summaries', { players: result.rows, }); // Request rank_tier data for these players // result.rows.forEach((row) => { // redis.rpush('mmrQueue', JSON.stringify({ // match_id: null, // account_id: row.account_id, // })); // }); return getData(container.url, (err, body) => { if (err) { // couldn't get data from api, non-retryable return cb(JSON.stringify(err)); } const results = body.response.players.filter(player => player.steamid); const bulkUpdate = results.reduce((acc, player) => { acc.push( { update: { _id: Number(convert64to32(player.steamid)), }, }, { doc: { personaname: player.personaname, avatarfull: player.avatarfull, }, doc_as_upsert: true, }, ); return acc; }, []); bulkIndexPlayer(bulkUpdate, (err) => { if (err) { console.log(err); } }); // player summaries response return async.each(results, (player, cb) => { insertPlayer(db, player, false, cb); }, cb); }); }); } function start() { getSummaries((err) => { if (err) { throw err; } return setTimeout(start, 1000); }); } start();
JavaScript
0.000001
@@ -1909,18 +1909,17 @@ (start, -10 +5 00);%0A %7D
77c22a8260d5ef036fb6fb85ef8250092f0b9a82
allow user to specify button for sleepify-ing
Leaflet.Sleep.js
Leaflet.Sleep.js
L.Map.mergeOptions({ sleep: true, sleepTime: 750, wakeTime: 750, wakeMessageTouch: 'Touch to Wake', sleepNote: true, hoverToWake: true, sleepOpacity:.7, sleepButton: null }); L.Control.SleepMapControl = L.Control.extend({ initialize: function(opts){ L.setOptions(this,opts); }, options: { position: 'topright', prompt: 'disable map', styles: { 'backgroundColor': 'white', 'padding': '5px', 'border': '2px solid gray' } }, buildContainer: function(){ var self = this; var container = L.DomUtil.create('p', 'sleep-button'); var boundEvent = this._nonBoundEvent.bind(this); container.appendChild( document.createTextNode( this.options.prompt )); L.DomEvent.addListener(container, 'click', boundEvent); L.DomEvent.addListener(container, 'touchstart', boundEvent); Object.keys(this.options.styles).map(function(key) { container.style[key] = self.options.styles[key]; }); return (this._container = container); }, onAdd: function () { if (this._container) { return this._container } else { return this.buildContainer(); } }, _nonBoundEvent: function(e) { L.DomEvent.stop(e); if (this._map) this._map.sleep._sleepMap(); return false; } }); L.Map.Sleep = L.Handler.extend({ addHooks: function () { var self = this; this.sleepNote = L.DomUtil.create('p', 'sleep-note', this._map._container); this._enterTimeout = null; this._exitTimeout = null; this._sleepButton = new L.Control.SleepMapControl() /* * If the device has only a touchscreen we will never get * a mouseout event, so we add an extra button to put the map * back to sleep manually. */ if (L.Browser.touch) { this._map.addControl(this._sleepButton); } var mapStyle = this._map._container.style; mapStyle.WebkitTransition += 'opacity .5s'; mapStyle.MozTransition += 'opacity .5s'; this._setSleepNoteStyle(); this._sleepMap(); }, removeHooks: function () { if (!this._map.scrollWheelZoom.enabled()){ this._map.scrollWheelZoom.enable(); } L.DomUtil.setOpacity( this._map._container, 1); L.DomUtil.setOpacity( this.sleepNote, 0); this._removeSleepingListeners(); this._removeAwakeListeners(); }, _setSleepNoteStyle: function() { var noteString = ''; if(L.Browser.touch) { noteString = this._map.options.wakeMessageTouch; } else if (this._map.options.wakeMessage) { noteString = this._map.options.wakeMessage; } else if (this._map.options.hoverToWake) { noteString = 'click or hover to wake'; } else { noteString = 'click to wake'; } var style = this.sleepNote.style; if( this._map.options.sleepNote ){ this.sleepNote.appendChild(document.createTextNode( noteString )); style.pointerEvents = 'none'; style.maxWidth = '150px'; style.transitionDuration = '.2s'; style.zIndex = 5000; style.opacity = '.6'; style.margin = 'auto'; style.textAlign = 'center'; style.borderRadius = '4px'; style.top = '50%'; style.position = 'relative'; style.padding = '5px'; style.border = 'solid 2px black'; style.background = 'white'; if(this._map.options.sleepNoteStyle) { var noteStyleOverrides = this._map.options.sleepNoteStyle; Object.keys(noteStyleOverrides).map(function(key) { style[key] = noteStyleOverrides[key]; }); } } }, _wakeMap: function (e) { this._stopWaiting(); this._map.scrollWheelZoom.enable(); if (L.Browser.touch) { this._map.touchZoom.enable(); this._map.dragging.enable(); this._map.tap.enable(); this._map.addControl(this._sleepButton); } L.DomUtil.setOpacity( this._map._container, 1); this.sleepNote.style.opacity = 0; this._addAwakeListeners(); }, _sleepMap: function () { this._stopWaiting(); this._map.scrollWheelZoom.disable(); if (L.Browser.touch) { this._map.touchZoom.disable(); this._map.dragging.disable(); this._map.tap.disable(); this._map.removeControl(this._sleepButton); } L.DomUtil.setOpacity( this._map._container, this._map.options.sleepOpacity); this.sleepNote.style.opacity = .4; this._addSleepingListeners(); }, _wakePending: function () { this._map.once('mousedown', this._wakeMap, this); if (this._map.options.hoverToWake){ var self = this; this._map.once('mouseout', this._sleepMap, this); self._enterTimeout = setTimeout(function(){ self._map.off('mouseout', self._sleepMap, self); self._wakeMap(); } , self._map.options.wakeTime); } }, _sleepPending: function () { var self = this; self._map.once('mouseover', self._wakeMap, self); self._exitTimeout = setTimeout(function(){ self._map.off('mouseover', self._wakeMap, self); self._sleepMap(); } , self._map.options.sleepTime); }, _addSleepingListeners: function(){ this._map.once('mouseover', this._wakePending, this); L.Browser.touch && this._map.once('click', this._wakeMap, this); }, _addAwakeListeners: function(){ this._map.once('mouseout', this._sleepPending, this); }, _removeSleepingListeners: function(){ this._map.options.hoverToWake && this._map.off('mouseover', this._wakePending, this); this._map.off('mousedown', this._wakeMap, this); L.Browser.touch && this._map.off('click', this._wakeMap, this); }, _removeAwakeListeners: function(){ this._map.off('mouseout', this._sleepPending, this); }, _stopWaiting: function () { this._removeSleepingListeners(); this._removeAwakeListeners(); var self = this; if(this._enterTimeout) clearTimeout(self._enterTimeout); if(this._exitTimeout) clearTimeout(self._exitTimeout); this._enterTimeout = null; this._exitTimeout = null; } }); L.Map.addInitHook('addHandler', 'sleep', L.Map.Sleep);
JavaScript
0
@@ -1509,64 +1509,8 @@ ull; -%0A this._sleepButton = new L.Control.SleepMapControl() %0A%0A @@ -1679,17 +1679,215 @@ .%0A * -/ +%0A * a custom control/button can be provided by the user%0A * with the map's %60sleepButton%60 option%0A */%0A this._sleepButton = this._map.options.sleepButton %7C%7C new L.Control.SleepMapControl() %0A if
d8eb64af38dc1de0af2e8ad92538e11c08e61625
use style instead href in NotificationsMenu
lib/header/NotificationsMenu.js
lib/header/NotificationsMenu.js
import React, { PropTypes } from 'react'; import NotificationsMenuItem from './NotificationsMenuItem'; const propTypes = { items: PropTypes.array, onItemClick: PropTypes.func, onFooterClick: PropTypes.func, }; const defaultProps = { items: [], }; function NotificationsMenu({ items, onItemClick, onFooterClick }) { const count = items.length; return ( <li className="dropdown notifications-menu"> <a href="" className="dropdown-toggle" data-toggle="dropdown"> <i className="fa fa-bell-o"></i> <span className="label label-warning">{count}</span> </a> <ul className="dropdown-menu"> <li className="header">You have {count} notifications</li> <li> <ul className="menu"> {items.map(item => <NotificationsMenuItem {...item} onClick={() => onItemClick(item)} > {item.text} </NotificationsMenuItem> )} </ul> </li> <li className="footer"> <a style={{ cursor: 'pointer' }} onClick={onFooterClick}> View all </a> </li> </ul> </li> ); } NotificationsMenu.propTypes = propTypes; NotificationsMenu.defaultProps = defaultProps; export default NotificationsMenu;
JavaScript
0
@@ -422,16 +422,16 @@ %3Ca - href=%22%22 +%0A cla @@ -454,16 +454,24 @@ -toggle%22 +%0A data-to @@ -485,16 +485,61 @@ ropdown%22 +%0A style=%7B%7B cursor: 'pointer' %7D%7D%0A %3E%0A
0fe4f71a8c55334ef3567a5aae146f49df4336e9
Fix timestamp seek thing
www/static/archive.js
www/static/archive.js
$(function(){ // Resize handling from https://github.com/jcubic/jquery.splitter/issues/32#issuecomment-65424376 var splitPosition = 80; var splitter = $("#content").split({ orientation:"vertical", limit:50, position: splitPosition + "%", onDragEnd: function(){ splitPosition = Math.round(splitter.position() / splitter.width() * 100); }, }); $(window).resize(function(){ splitter.position(splitPosition + "%"); }); // Only scroll the chat vertically $("#chat").parent().css("overflow-x", "hidden"); // Allow showing deleted messages $(".deleted").click(function(){ $(this).hide().next(".message").show(); }); // Stop scrolling automatically if the user scrolls manually $("#chat").parent().scroll(stopScrolling); $("#resetscroll").click(startScrolling); window.scrollenable = true; // Prepare timestamp lookup table window.chatlines = []; $(".line").each(function(){ window.chatlines.push({ts: Number($(this).data("timestamp")), obj: $(this)}); }); // Create poll to scroll the chat to the right place window.player = document.getElementById("clip_embed_player_flash"); window.lasttime = -1; setInterval(doScroll, 1000); // just in case the videoPlaying event somehow happens before the init function runs if (window.videoLoaded) onPlayerEvent({event: "videoPlaying", data: {}}); }); function getVideoTime() { if (!window.player) return -1; else if (typeof window.player.getVideoTime == "function") return window.player.getVideoTime(); else if (typeof window.player.getVideoTime == "number") return window.player.getVideoTime; else return -1; } function doScroll() { if (!window.scrollenable) return; var time = getVideoTime(); if (time < 0) return // Don't scroll if we're stuck at the same time (if the video is paused) if (time == window.lasttime) return; window.lasttime = time; scrollChatTo(time + window.start); } function scrollChatTo(time) { // Binary search to find the first line that is after the current time var min = 0; var max = window.chatlines.length; while (min < max) { var mid = (min + max) >> 1; if (window.chatlines[mid].ts < time) min = mid + 1; else max = mid; } // Scroll the chat pane so that this line is below the bottom var line; if (min < window.chatlines.length) { line = window.chatlines[min].obj; } else { line = $("#chatbottom"); } window.autoscroll = true; var chatPane = $("#chat").parent(); chatPane.scrollTop(chatPane.scrollTop() + line.position().top - chatPane.height()); } function onPlayerEvents(data) { data.forEach(onPlayerEvent); } function onPlayerEvent(e) { if (e.event === "videoPlaying") { if (window.videoLoaded) return; window.videoLoaded = true; if (!window.player) return; // When playing starts for the first time, make sure we're at the actual time we wanted // Sometimes, depending on what version of the player we have, the "initial_time" param doesn't work var time = getVideoTime(); // If we're off from the specified initial time by more than, say, 10 seconds, jump to the right time if (window.initial_time && Math.abs(window.initial_time - time) > 10) { window.player.videoSeek(window.initial_time); } } } function stopScrolling() { // don't trigger off our own scrolling if (window.autoscroll) { window.autoscroll = false; return; } window.scrollenable = false; $("#resetscroll").show(); } function startScrolling() { window.scrollenable = true; $("#resetscroll").hide(); doScroll(); } // This (currently, in the browsers I have tested it on) fools the Twitch player into thinking it's playing on the real Twitch site // so it doesn't make it so that clicking the player takes you to the Twitch page window.parent = {location: {hostname: 'www.twitch.tv', search: 'force_embed=1'}} window.videoLoaded = false;
JavaScript
0.000206
@@ -1272,16 +1272,48 @@ oLoaded) + %7B%0A%09%09window.videoLoaded = false; %0A%09%09onPla @@ -1357,16 +1357,19 @@ : %7B%7D%7D);%0A +%09%7D%0A %7D);%0A%0Afun
40021f968a361f860c5605bff4a2889480d79be9
move contract deployer to deploy manager
lib/modules/deployment/index.js
lib/modules/deployment/index.js
let async = require('async'); const utils = require('../utils/utils.js'); //require("../utils/debug_util.js")(__filename, async); const utils = require('../utils/utils.js'); //require("../utils/debug_util.js")(__filename, async); class DeployManager { constructor(options) { const self = this; this.config = options.config; this.logger = options.logger; this.blockchainConfig = this.config.blockchainConfig; this.events = options.events; this.plugins = options.plugins; this.blockchain = options.blockchain; this.gasLimit = false; this.fatalErrors = false; this.deployOnlyOnConfig = false; this.onlyCompile = options.onlyCompile !== undefined ? options.onlyCompile : false; this.events.setCommandHandler('deploy:contracts', (cb) => { self.deployContracts(cb); }); } deployAll(done) { let self = this; self.events.request('contracts:dependencies', (err, contractDependencies) => { self.events.request('contracts:list', (err, contracts) => { if (err) { return done(err); } self.logger.info(__("deploying contracts")); async.waterfall([ function (next) { self.plugins.emitAndRunActionsForEvent("deploy:beforeAll", next); }, function () { const contractDeploys = {}; const errors = []; contracts.forEach(contract => { function deploy(result, callback) { if (typeof result === 'function') { callback = result; } contract._gasLimit = self.gasLimit; self.events.request('deploy:contract', contract, (err) => { if (err) { contract.error = err.message || err; self.logger.error(err.message || err); errors.push(err); } callback(); }); } const className = contract.className; if (!contractDependencies[className] || contractDependencies[className].length === 0) { contractDeploys[className] = deploy; return; } contractDeploys[className] = cloneDeep(contractDependencies[className]); contractDeploys[className].push(deploy); }); try { async.auto(contractDeploys, 1, function(_err, _results) { if (errors.length) { _err = __("Error deploying contracts. Please fix errors to continue."); self.logger.error(_err); self.events.emit("outputError", __("Error deploying contracts, please check console")); return done(_err); } if (contracts.length === 0) { self.logger.info(__("no contracts found")); return done(); } self.logger.info(__("finished deploying contracts")); done(err); }); } catch (e) { self.logger.error(e.message || e); done(__('Error deploying')); } } ]); }); }); } deployContracts(done) { let self = this; if (self.blockchainConfig === {} || self.blockchainConfig.enabled === false) { self.logger.info(__("Blockchain component is disabled in the config").underline); this.events.emit('blockchainDisabled', {}); return done(); } async.waterfall([ function buildContracts(callback) { self.events.request("contracts:build", self.deployOnlyOnConfig, (err) => { callback(err); }); }, // TODO: shouldn't be necessary function checkCompileOnly(callback){ if(self.onlyCompile){ self.events.emit('contractsDeployed'); return done(); } return callback(); }, // TODO: could be implemented as an event (beforeDeployAll) function checkIsConnectedToBlockchain(callback) { callback(); //self.blockchain.onReady(() => { // self.blockchain.assertNodeConnection((err) => { // callback(err); // }); //}); }, // TODO: this can be done on the fly or as part of the initialization function determineDefaultAccount(callback) { self.blockchain.determineDefaultAccount((err) => { callback(err); }); }, function deployAllContracts(callback) { self.deployAll(function (err) { if (!err) { self.events.emit('contractsDeployed'); } if (err && self.fatalErrors) { return callback(err); } callback(); }); }, function runAfterDeploy(callback) { self.plugins.emitAndRunActionsForEvent('contracts:deploy:afterAll', callback); } ], function (err, _result) { done(err); }); } } module.exports = DeployManager;
JavaScript
0
@@ -20,24 +20,84 @@ ('async');%0A%0A +const ContractDeployer = require('./contract_deployer.js');%0A const utils
d99ec02c2d480ce0c9e3b7b51de4cf9a0478b45e
add more messages
message.js
message.js
function err(text){ console.log('\x1b[31mERR! \x1b[39m '+text); } function warning(text){ console.log('\x1b[33mOOPS \x1b[39m '+text); } function success(text){ console.log('\x1b[32mSUCCESS \x1b[39m '+text); } var msg = { apiServerStarted :function(port){ success('server is running on port ' + port); }, portNaN : function(port){ err(port + ' is not a number, try something like 5000 or give 0 to choose landom port'); }, portNotDefined : function(){ err('Could not find port number. try something like 5000 or give 0 to choose landom port'); }, portAlreadyUsed : function(port){ err(port + ' is alreay used by other service, try other numbers'); }, apiAlreadyRunning: function(port){ err('server is alreay running in port ' + port); }, dataFieldNotSpecified: function(path){ warning('Could not find "data" field for your '+path+' api setting '); }, pathFieldNotSpecified: function(index){ warning('could not find "path" field in your request '+index); }, templateNotSpecified: function(name){ warning('Could not find '+name+' template '); }, stubTypeNotFound: function(name){ warning('Could not find '+name+' type '); }, generalError : function(errorMessage){ err(errorMessage); } }; module.exports = msg;
JavaScript
0
@@ -1268,24 +1268,330 @@ ');%0A %7D,%0A + noTemplateType: function(template, type, types)%7B%0A warning('Template ' + template + ' has no type ' + type + ' try '+types.join(' or '))%0A %7D,%0A notEnoughChoice: function(type, list)%7B%0A err('run out of unique choice for '+type+' operation. please give enough elements for '+list)%0A %7D,%0A generalE
303448aa50ec898647a1a652ed7851fd0962239d
allow for errors of requiring libraries
packages/code/core/core_require.js
packages/code/core/core_require.js
/* @author Zakai Hamilton @component CoreRequire */ package.core.require = function CoreRequire(me) { me.require = function(callback, list) { require(list, function () { var modules = []; list.map((path) => { var module = require(path); modules.push(module); }); callback.apply(null, modules); }); }; };
JavaScript
0
@@ -275,22 +275,188 @@ e = -require(path); +null;%0A try %7B%0A module = require(path);%0A %7D%0A catch(e) %7B%0A me.core.console.error(e);%0A %7D %0A
a31be49dc0844395c3f2ef2de230ae99f9de17c9
Add option normalizing method to compile-solidity that used to be in the legacy files
packages/compile-solidity/index.js
packages/compile-solidity/index.js
const debug = require("debug")("compile"); // eslint-disable-line no-unused-vars const path = require("path"); const expect = require("@truffle/expect"); const findContracts = require("@truffle/contract-sources"); const Config = require("@truffle/config"); const Profiler = require("./profiler"); const CompilerSupplier = require("./compilerSupplier"); const { run } = require("./run"); const { normalizeOptions } = require("./legacy/options"); const Compile = { // this takes an object with keys being the name and values being source // material as well as an options object async sources({ sources, options }) { const compilation = await run(sources, normalizeOptions(options)); return compilation.contracts.length > 0 ? { compilations: [compilation] } : { compilations: [] }; }, async all(options) { const paths = [ ...new Set([ ...(await findContracts(options.contracts_directory)), ...(options.files || []) ]) ]; return await Compile.sourcesWithDependencies({ paths, options: Config.default().merge(options) }); }, async necessary(options) { options.logger = options.logger || console; const paths = await Profiler.updated(options); return await Compile.sourcesWithDependencies({ paths, options: Config.default().merge(options) }); }, // this takes an array of paths and options async sourcesWithDependencies({ paths, options }) { options.logger = options.logger || console; options.contracts_directory = options.contracts_directory || process.cwd(); expect.options(options, [ "working_directory", "contracts_directory", "resolver" ]); const config = Config.default().merge(options); const { allSources, compilationTargets } = await Profiler.requiredSources( config.with({ paths, base_path: options.contracts_directory, resolver: options.resolver }) ); const hasTargets = compilationTargets.length; hasTargets ? Compile.display(compilationTargets, options) : Compile.display(allSources, options); // when there are no sources, don't call run if (Object.keys(allSources).length === 0) { return { compilations: [] }; } options.compilationTargets = compilationTargets; const { sourceIndexes, contracts, compiler } = await run( allSources, normalizeOptions(options) ); const { name, version } = compiler; // returns CompilerResult - see @truffle/compile-common return contracts.length > 0 ? { compilations: [ { sourceIndexes, contracts, compiler: { name, version } } ] } : { compilations: [] }; }, display(paths, options) { if (options.quiet !== true) { if (!Array.isArray(paths)) { paths = Object.keys(paths); } const blacklistRegex = /^truffle\//; const sources = paths .sort() .map(contract => { if (path.isAbsolute(contract)) { contract = "." + path.sep + path.relative(options.working_directory, contract); } if (contract.match(blacklistRegex)) return; return contract; }) .filter(contract => contract); options.events.emit("compile:sourcesToCompile", { sourceFileNames: sources }); } } }; module.exports = { Compile, CompilerSupplier };
JavaScript
0
@@ -380,23 +380,22 @@ /run%22);%0A +%0A const - %7B normali @@ -408,39 +408,990 @@ ons -%7D = require(%22./legacy/options%22) += options =%3E %7B%0A if (options.logger === undefined) options.logger = console;%0A%0A expect.options(options, %5B%22contracts_directory%22, %22compilers%22%5D);%0A expect.options(options.compilers, %5B%22solc%22%5D);%0A%0A options.compilers.solc.settings.evmVersion =%0A options.compilers.solc.settings.evmVersion %7C%7C%0A options.compilers.solc.evmVersion;%0A options.compilers.solc.settings.optimizer =%0A options.compilers.solc.settings.optimizer %7C%7C%0A options.compilers.solc.optimizer %7C%7C%0A %7B%7D;%0A%0A // Grandfather in old solc config%0A if (options.solc) %7B%0A options.compilers.solc.settings.evmVersion = options.solc.evmVersion;%0A options.compilers.solc.settings.optimizer = options.solc.optimizer;%0A %7D%0A%0A // Certain situations result in %60%7B%7D%60 as a value for compilationTargets%0A // Previous implementations treated any value lacking %60.length%60 as equivalent%0A // to %60%5B%5D%60%0A if (!options.compilationTargets %7C%7C !options.compilationTargets.length) %7B%0A options.compilationTargets = %5B%5D;%0A %7D%0A%0A return options;%0A%7D ;%0A%0Ac
af696e227926acbc3eeb4e5b25181b99303a1bef
add fields to Table df in webform
frappe/public/js/frappe/web_form/web_form.js
frappe/public/js/frappe/web_form/web_form.js
frappe.ready(function() { const { web_form_doctype, doc_name, web_form_name } = web_form_settings; const wrapper = $(".web-form-wrapper"); if (web_form_settings.login_required && frappe.session.user === "Guest") { const login_required = new frappe.ui.Dialog({ title: __("Not Permitted"), primary_action_label: __("Login"), primary_action: () => { window.location.replace('/login?redirect-to=/' + web_form_name) } }); login_required.set_message(__("You are not permitted to access this page.")); login_required.show(); } else if (web_form_settings.is_list) { web_form_list = new frappe.views.WebFormList({ parent: wrapper, doctype: web_form_doctype, web_form_name: web_form_name }) } else { // If editing is not allowed redirect to a new form if (web_form_settings.doc_name && web_form_settings.allow_edit === 0) { window.location.replace(window.location.pathname + "?new=1") } get_data().then(res => { const data = setup_fields(res.message); data.doc = res.message.doc data.web_form.doc_name = web_form_settings.doc_name let web_form = new frappe.ui.WebForm({ parent: wrapper, fields: data.web_form.web_form_fields, doc: data.doc, ...data.web_form, }); web_form.make(); }); } document.querySelector("body").style.display = "block"; function get_data() { return frappe.call({ method: "frappe.website.doctype.web_form.web_form.get_form_data", args: { doctype: web_form_doctype, docname: doc_name, web_form_name: web_form_name }, freeze: true }); } function setup_fields(form_data) { const query_params = frappe.utils.get_query_params(); form_data.web_form.web_form_fields.map(df => { if (df.fieldtype === "Table") { df.get_data = () => { let data = []; if (form_data.doc) { data = form_data.doc[df.fieldname]; } return data; }; if (df.fieldtype === "Attach") { df.is_private = true; } // Set defaults if ( query_params && query_params["new"] == 1 && df.fieldname in query_params ) { df.default = query_params[df.fieldname]; } df.is_web_form = true; delete df.parent; delete df.parentfield; delete df.parenttype; delete df.doctype; return df; } if (df.fieldtype === "Link") df.only_select = true; }); return form_data; } });
JavaScript
0.000002
@@ -1889,16 +1889,58 @@ %09%09%09%09%7D;%0A%0A +%09%09%09%09df.fields = form_data%5Bdf.fieldname%5D;%0A%0A %09%09%09%09if (
84c23badc7b9f30cfc337836f0b07e9382b18e58
Remove some more comments that were junking things up
packages/compile-solidity/index.js
packages/compile-solidity/index.js
const debug = require("debug")("compile"); // eslint-disable-line no-unused-vars const path = require("path"); const expect = require("@truffle/expect"); const findContracts = require("@truffle/contract-sources"); const Config = require("@truffle/config"); const Profiler = require("./profiler"); const CompilerSupplier = require("./compilerSupplier"); const { run } = require("./run"); const { normalizeOptions } = require("./legacy/options"); const Compile = { async sources({ sources, options }) { const compilation = await run(sources, normalizeOptions(options)); return compilation.contracts.length > 0 ? { compilations: [compilation] } : { compilations: [] }; }, // contracts_directory: String. Directory where .sol files can be found. // quiet: Boolean. Suppress output. Defaults to false. // strict: Boolean. Return compiler warnings as errors. Defaults to false. // files: Array<String>. Explicit files to compile besides detected sources async all(options) { const paths = [ ...new Set([ ...(await findContracts(options.contracts_directory)), ...(options.files || []) ]) ]; return await Compile.sourcesWithDependencies({ sources: paths, options: Config.default().merge(options) }); }, // contracts_directory: String. Directory where .sol files can be found. // build_directory: String. Optional. Directory where .sol.js files can be found. Only required if `all` is false. // all: Boolean. Compile all sources found. Defaults to true. If false, will compare sources against built files // in the build directory to see what needs to be compiled. // quiet: Boolean. Suppress output. Defaults to false. // strict: Boolean. Return compiler warnings as errors. Defaults to false. // files: Array<String>. Explicit files to compile besides detected sources async necessary(options) { options.logger = options.logger || console; const paths = await Profiler.updated(options); return await Compile.sourcesWithDependencies({ sources: paths, options: Config.default().merge(options) }); }, async sourcesWithDependencies({ sources, options }) { options.logger = options.logger || console; options.contracts_directory = options.contracts_directory || process.cwd(); expect.options(options, [ "working_directory", "contracts_directory", "resolver" ]); const config = Config.default().merge(options); const { allSources, compilationTargets } = await Profiler.requiredSources( config.with({ paths: sources, base_path: options.contracts_directory, resolver: options.resolver }) ); const hasTargets = compilationTargets.length; hasTargets ? Compile.display(compilationTargets, options) : Compile.display(allSources, options); // when there are no sources, don't call run if (Object.keys(allSources).length === 0) { return { compilations: [] }; } options.compilationTargets = compilationTargets; const { sourceIndexes, contracts, compiler } = await run( allSources, normalizeOptions(options) ); const { name, version } = compiler; // returns CompilerResult - see @truffle/compile-common return contracts.length > 0 ? { compilations: [ { sourceIndexes, contracts, compiler: { name, version } } ] } : { compilations: [] }; }, display(paths, options) { if (options.quiet !== true) { if (!Array.isArray(paths)) { paths = Object.keys(paths); } const blacklistRegex = /^truffle\//; const sources = paths .sort() .map(contract => { if (path.isAbsolute(contract)) { contract = "." + path.sep + path.relative(options.working_directory, contract); } if (contract.match(blacklistRegex)) return; return contract; }) .filter(contract => contract); options.events.emit("compile:sourcesToCompile", { sourceFileNames: sources }); } } }; module.exports = { Compile, CompilerSupplier };
JavaScript
0
@@ -692,295 +692,8 @@ %7D,%0A%0A - // contracts_directory: String. Directory where .sol files can be found.%0A // quiet: Boolean. Suppress output. Defaults to false.%0A // strict: Boolean. Return compiler warnings as errors. Defaults to false.%0A // files: Array%3CString%3E. Explicit files to compile besides detected sources%0A as @@ -1001,594 +1001,8 @@ %7D,%0A%0A - // contracts_directory: String. Directory where .sol files can be found.%0A // build_directory: String. Optional. Directory where .sol.js files can be found. Only required if %60all%60 is false.%0A // all: Boolean. Compile all sources found. Defaults to true. If false, will compare sources against built files%0A // in the build directory to see what needs to be compiled.%0A // quiet: Boolean. Suppress output. Defaults to false.%0A // strict: Boolean. Return compiler warnings as errors. Defaults to false.%0A // files: Array%3CString%3E. Explicit files to compile besides detected sources%0A as
0910c9cf3528f04ce392dc64bb26ff9dcb694af5
Add more debug output for travis
test/e2e/main.js
test/e2e/main.js
const should = require('should'); const child_process = require('child_process'); const psTree = require('ps-tree'); const isrunning = require('is-running'); const {appPath, electronPath} = require('./helper'); describe('Application', function() { // Spectron doesn't work with apps that don't open a window, // so we use child_process instead. // See https://github.com/electron/spectron/issues/90 // There doesn't seem to be tooling to easily test Tray functionality, // e.g. see // https://discuss.atom.io/t/automated-e2e-testing-of-electron-application-on-windows/21290 /** * Kill a process and all of its children * The tree-kill module doesn't work for me in this context * - the ps process never returns, it gets stuck as a defunct * process. * @param {number} parentPid The root of the process tree to kill */ var tree_kill = function(parentPid) { console.log("tree killing " + parentPid); psTree(parentPid, function(err, children) { children.forEach(function(child) { try { process.kill(child.PID, 'SIGKILL'); } catch (e) { // ignore it } }); try { process.kill(parentPid, 'SIGKILL'); } catch (e) { // ignore it } }); }; /** * @returns {function} which calls callback if pid isn't running, * otherwise schedules itself to run again after a short pause */ var callWhenDead = function(pid, callback) { var check = function() { if (isrunning(pid)) { setTimeout(check, 100); } else { console.log(pid + " is dead"); callback(); } }; return check; }; var app1, app2; // child_process var app1pid, app2pid; it('should only allow one instance to run', function() { this.timeout(10000); app1 = child_process.spawn(electronPath, [ appPath, "--verbose" ]); app1pid = app1.pid; return new Promise(function(fulfill, reject) { var app1startup = function(buffer) { if (buffer.toString().includes("Creating tray")) { app2 = child_process.spawn(electronPath, [ appPath, '--verbose' ]); app2pid = app2.pid; app2.on('exit', function(code) { fulfill(true); }); // don't care which stream the notification will come on app2.stdout.on('data', app2startup); app2.stderr.on('data', app2startup); } }; var app2startup = function(buffer) { if (buffer.toString().includes("starting up")) { reject("Second instance is starting up"); } }; // don't care which stream the notification will come on app1.stdout.on('data', app1startup); app1.stderr.on('data', app1startup); }); }); afterEach(function() { // Kill any processes spawned, and all their descendents. // app[12].kill doesn't work - it kills the node process, but its // descendants live on. if (app1pid) { tree_kill(app1pid); } if (app2pid) { tree_kill(app2pid); } // Only move on from this test when all the processes spawned are dead. // No longer sure if this is necessary, but keeping in case it is helping // with hard-to-debug errors in CI. return new Promise(function(resolve, reject) { // resolve() if/when app2pid doesn't exist var waitapp2 = function() { if (app2pid) { console.log("Waiting on app2: " + app2pid); setTimeout(callWhenDead(app2pid, resolve), 100); } else { resolve(); } }; // Once app1pid is gone, wait for app2pid if (app1pid) { console.log("Waiting on app1: " + app1pid); setTimeout(callWhenDead(app1pid, waitapp2), 100); } else { waitapp2(); } }); }); });
JavaScript
0
@@ -1671,16 +1671,181 @@ ;%0A %7D;%0A%0A + /**%0A * @returns %7Bapp%7D a new instance of the app%0A */%0A var spawnApp = function() %7B%0A return child_process.spawn(electronPath, %5B appPath, '--verbose' %5D);%0A %7D%0A%0A var ap @@ -1871,16 +1871,16 @@ process%0A - var ap @@ -1996,66 +1996,17 @@ 1 = -child_process.spawn(electronPath, %5B appPath, %22--verbose%22 %5D +spawnApp( );%0A @@ -2115,32 +2115,79 @@ ction(buffer) %7B%0A + console.log(%22app1 output: %22 + buffer);%0A if (buff @@ -2250,68 +2250,18 @@ 2 = -child_process.spawn(electronPath, %5B appPath, '--verbose' %5D); +spawnApp() %0A @@ -2527,24 +2527,24 @@ %7D%0A %7D;%0A%0A - var ap @@ -2566,32 +2566,79 @@ ction(buffer) %7B%0A + console.log(%22app2 output: %22 + buffer);%0A if (buff
bd05ccaf596efa2cd39e7de4fa0692e3f7178217
Add resource name input
src/Activities.js
src/Activities.js
import React from 'react'; export default ({onCreateButtonClick})=> ( <div className="Activities"> <button onClick={e => { e.preventDefault() onCreateButtonClick("New Resource") }}>+</button> </div> )
JavaScript
0.000011
@@ -66,40 +66,173 @@ )=%3E -(%0A %3Cdiv className=%22Activities%22%3E +%7B%0A var newResourceNameInput = null;%0A%0A return %3Cdiv className=%22Activities%22%3E%0A %3Cinput%0A type=%22text%22%0A ref=%7B(input) =%3E %7B newResourceNameInput = input; %7D%7D /%3E%0A %0A @@ -317,21 +317,19 @@ ick( -%22N +n ew - Resource %22)%0A @@ -324,17 +324,31 @@ Resource -%22 +NameInput.value )%0A @@ -372,10 +372,10 @@ %3C/div%3E%0A -) +%7D %0A
2a409015fd76cfda067bec3833605eaaf0a63d07
Remove console logs
js/sinbad-app.js
js/sinbad-app.js
appRun(); function appRun() { $(document).ready(function() { console.log("READY"); $(".loading").hide(); $(".complete").show(); //PAGE SWIPES $(document).on('pageinit', function(event){ $('.pages').on("swipeleft", function () { var nextpage = $(this).next('div[data-role="page"]'); if (nextpage.length > 0) { $.mobile.changePage(nextpage, {transition: "slide", changeHash:false }); } }); $('.pages').on("swiperight", function () { var prevpage = $(this).prev('div[data-role="page"]'); if (prevpage.length > 0) { $.mobile.changePage(prevpage, { transition: "slide", reverse: true, changeHash: false }); } }); }); //DRAG AND DROP //initialize dragging $("#watercolor").draggable( { revert: true, cursor: 'move', } ); $("#leaves").draggable( { revert: true, cursor: 'move', } ); $("#bubbles").draggable( { revert: true, cursor: 'move', } ); //initialize droppable callback $("#spritesheet").droppable({ tolerance: "pointer", drop: sinbadChange }); //event handler for drop event function sinbadChange(event, ui) { var currentBrush = ui.draggable.attr('id'); console.log(currentBrush); console.log("in droppable"); if (currentBrush == "watercolor") { $("#spritesheet").removeClass(); $("#spritesheet").addClass("brushfish"); } else if (currentBrush == "leaves") { $("#spritesheet").removeClass(); $("#spritesheet").addClass("leaffish"); } else if (currentBrush == "bubbles") { $("#spritesheet").removeClass(); $("#spritesheet").addClass("bubblefish"); } else { $("#spritesheet").removeClass(); $("#spritesheet").addClass("plainfish"); } } // //add listener to drop event // $("spritesheet").on("drop", function(event, ui) { // }) }); //end jquery } //end appRun
JavaScript
0.000002
@@ -1361,80 +1361,8 @@ ');%0A - console.log(currentBrush);%0A console.log(%22in droppable%22);%0A
19038b9d1c1a98b5a6bd185b3784e32f491682b4
remove .focus-visible on blur & focusout
js/src/button.js
js/src/button.js
/** * -------------------------------------------------------------------------- * Bootstrap (v4.4.1): button.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * -------------------------------------------------------------------------- */ import $ from 'jquery' /** * ------------------------------------------------------------------------ * Constants * ------------------------------------------------------------------------ */ const NAME = 'button' const VERSION = '4.4.1' const DATA_KEY = 'bs.button' const EVENT_KEY = `.${DATA_KEY}` const DATA_API_KEY = '.data-api' const JQUERY_NO_CONFLICT = $.fn[NAME] const ClassName = { ACTIVE : 'active', BUTTON : 'btn', FOCUS : 'focus', FOCUS_VISIBLE : 'focus-FOCUS_VISIBLE' } const Selector = { DATA_TOGGLE_CARROT : '[data-toggle^="button"]', DATA_TOGGLES : '[data-toggle="buttons"]', DATA_TOGGLE : '[data-toggle="button"]', DATA_TOGGLES_BUTTONS : '[data-toggle="buttons"] .btn', INPUT : 'input:not([type="hidden"])', ACTIVE : '.active', BUTTON : '.btn' } const Event = { CLICK_DATA_API : `click${EVENT_KEY}${DATA_API_KEY}`, FOCUS_BLUR_DATA_API : `focus${EVENT_KEY}${DATA_API_KEY} ` + `blur${EVENT_KEY}${DATA_API_KEY}`, LOAD_DATA_API : `load${EVENT_KEY}${DATA_API_KEY}` } /** * ------------------------------------------------------------------------ * Class Definition * ------------------------------------------------------------------------ */ class Button { constructor(element) { this._element = element } // Getters static get VERSION() { return VERSION } // Public toggle() { let triggerChangeEvent = true let addAriaPressed = true const rootElement = $(this._element).closest( Selector.DATA_TOGGLES )[0] if (rootElement) { const input = this._element.querySelector(Selector.INPUT) if (input) { if (input.type === 'radio') { if (input.checked && this._element.classList.contains(ClassName.ACTIVE)) { triggerChangeEvent = false } else { const activeElement = rootElement.querySelector(Selector.ACTIVE) if (activeElement) { $(activeElement).removeClass(ClassName.ACTIVE) } } } else if (input.type === 'checkbox') { if (this._element.tagName === 'LABEL' && input.checked === this._element.classList.contains(ClassName.ACTIVE)) { triggerChangeEvent = false } } else { // if it's not a radio button or checkbox don't add a pointless/invalid checked property to the input triggerChangeEvent = false } if (triggerChangeEvent) { input.checked = !this._element.classList.contains(ClassName.ACTIVE) $(input).trigger('change') } input.focus() addAriaPressed = false } } if (!(this._element.hasAttribute('disabled') || this._element.classList.contains('disabled'))) { if (addAriaPressed) { this._element.setAttribute('aria-pressed', !this._element.classList.contains(ClassName.ACTIVE)) } if (triggerChangeEvent) { $(this._element).toggleClass(ClassName.ACTIVE) } } } dispose() { $.removeData(this._element, DATA_KEY) this._element = null } // Static static _jQueryInterface(config) { return this.each(function () { let data = $(this).data(DATA_KEY) if (!data) { data = new Button(this) $(this).data(DATA_KEY, data) } if (config === 'toggle') { data[config]() } }) } } /** * ------------------------------------------------------------------------ * Data Api implementation * ------------------------------------------------------------------------ */ $(document) .on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE_CARROT, (event) => { let button = event.target if (!$(button).hasClass(ClassName.BUTTON)) { button = $(button).closest(Selector.BUTTON)[0] } if (!button || button.hasAttribute('disabled') || button.classList.contains('disabled')) { event.preventDefault() // work around Firefox bug #1540995 } else { const inputBtn = button.querySelector(Selector.INPUT) if (inputBtn && (inputBtn.hasAttribute('disabled') || inputBtn.classList.contains('disabled'))) { event.preventDefault() // work around Firefox bug #1540995 return } Button._jQueryInterface.call($(button), 'toggle') } }) .on(Event.FOCUS_BLUR_DATA_API, Selector.DATA_TOGGLE_CARROT, (event) => { const button = $(event.target).closest(Selector.BUTTON)[0] $(button).toggleClass(ClassName.FOCUS, /^focus(in)?$/.test(event.type)) // Boosted mod: check if children has focus-visible and delegate it to button if ($(event.target).hasClass(ClassName.FOCUS_VISIBLE)) { $(button).toggleClass(ClassName.FOCUS_VISIBLE) } // end mod }) $(window).on(Event.LOAD_DATA_API, () => { // ensure correct active class is set to match the controls' actual values/states // find all checkboxes/radio buttons inside data-toggle groups let buttons = [].slice.call(document.querySelectorAll(Selector.DATA_TOGGLES_BUTTONS)) for (let i = 0, len = buttons.length; i < len; i++) { const button = buttons[i] const input = button.querySelector(Selector.INPUT) if (input.checked || input.hasAttribute('checked')) { button.classList.add(ClassName.ACTIVE) } else { button.classList.remove(ClassName.ACTIVE) } } // find all button toggles buttons = [].slice.call(document.querySelectorAll(Selector.DATA_TOGGLE)) for (let i = 0, len = buttons.length; i < len; i++) { const button = buttons[i] if (button.getAttribute('aria-pressed') === 'true') { button.classList.add(ClassName.ACTIVE) } else { button.classList.remove(ClassName.ACTIVE) } } }) /** * ------------------------------------------------------------------------ * jQuery * ------------------------------------------------------------------------ */ $.fn[NAME] = Button._jQueryInterface $.fn[NAME].Constructor = Button $.fn[NAME].noConflict = () => { $.fn[NAME] = JQUERY_NO_CONFLICT return Button._jQueryInterface } export default Button
JavaScript
0.000001
@@ -807,29 +807,23 @@ 'focus- -FOCUS_VISIBLE +visible '%0A%7D%0A%0Acon @@ -5071,37 +5071,100 @@ $(button). -toggl +addClass(ClassName.FOCUS_VISIBLE)%0A %7D else %7B%0A $(button).remov eClass(ClassName
5d302859a4bb254afcc3713316abc8d0e1509597
Throw helpful information -- if uncommented
js/test_utils.js
js/test_utils.js
function isequalRel(x, y, tol) { var EPS = Math.pow(2, -52); // IEEE 754 double precision epsilon return (Math.abs(x - y) <= (tol * Math.max(Math.abs(x), Math.abs(y)) + EPS)); } function assert(state, message) { return ok(state, message); }
JavaScript
0
@@ -1,16 +1,39 @@ +/*global ok: true%0A */%0A%0A function isequal @@ -122,22 +122,18 @@ lon%0A -return +if (Math.a @@ -194,16 +194,214 @@ + EPS)) + %7B%0A return true;%0A %7D%0A // Too bad this stops QUnit test, but is handy for finding want/got values%0A //throw new Error(%22isEqualRel x=%22 + x + %22 y=%22 + y + %22 tol=%22 + tol);%0A return false ;%0A%7D%0A%0Afun
a3cc97a1272f2d7337bbbee0d28fbac3d4105277
Set Input.value when rerendering.
packages/input/Input.js
packages/input/Input.js
import Component from '../../ui/Component' import keys from '../../util/keys' export default class Input extends Component { render ($$) { let val = this._getDocumentValue() let el = $$('input').attr({ value: val, type: this.props.type, placeholder: this.props.placeholder }).addClass('sc-input') .on('keydown', this._onKeydown) if (this.props.path) { el.on('change', this._onChange) } if (this.props.centered) { el.addClass('sm-centered') } return el } _onChange () { let editorSession = this.context.editorSession let path = this.props.path let newVal = this.el.val() let oldVal = this._getDocumentValue() if (newVal !== oldVal) { editorSession.transaction(function (tx) { tx.set(path, newVal) }) if (this.props.retainFocus) { // ATTENTION: running the editor flow will rerender the model selection // which takes away the focus from this input this.el.getNativeElement().focus() } } } _getDocumentValue () { if (this.props.val) { return this.props.val } else { let editorSession = this.context.editorSession let path = this.props.path return editorSession.getDocument().get(path) } } _onKeydown (event) { if (event.keyCode === keys.ESCAPE) { event.stopPropagation() event.preventDefault() this.el.val(this._getDocumentValue()) } } }
JavaScript
0
@@ -324,16 +324,32 @@ input')%0A + .val(val)%0A .o
6cd1c3cdf1e66d651c9f7a6481c8520c2a996aa9
Improve performance of no-identical-title
lib/rules/no-identical-title.js
lib/rules/no-identical-title.js
'use strict'; const createAstUtils = require('../util/ast'); function newLayer() { return { describeTitles: [], testTitles: [] }; } function isFirstArgLiteral(node) { return node.arguments && node.arguments[0] && node.arguments[0].type === 'Literal'; } module.exports = { meta: { type: 'suggestion', docs: { description: 'Disallow identical titles' } }, create(context) { const astUtils = createAstUtils(context.settings); const titleLayers = [ newLayer() ]; function handlTestCaseTitles(titles, node, title) { if (astUtils.isTestCase(node)) { if (titles.includes(title)) { context.report({ node, message: 'Test title is used multiple times in the same test suite.' }); } titles.push(title); } } function handlTestSuiteTitles(titles, node, title) { if (!astUtils.isDescribe(node)) { return; } if (titles.includes(title)) { context.report({ node, message: 'Test suite title is used multiple times.' }); } titles.push(title); } return { CallExpression(node) { const currentLayer = titleLayers[titleLayers.length - 1]; if (astUtils.isDescribe(node)) { titleLayers.push(newLayer()); } if (!isFirstArgLiteral(node)) { return; } const title = node.arguments[0].value; handlTestCaseTitles(currentLayer.testTitles, node, title); handlTestSuiteTitles(currentLayer.describeTitles, node, title); }, 'CallExpression:exit'(node) { if (astUtils.isDescribe(node)) { titleLayers.pop(); } } }; } };
JavaScript
0.999357
@@ -198,16 +198,26 @@ return +(%0A node.arg @@ -225,16 +225,24 @@ ments && +%0A node.ar @@ -254,16 +254,24 @@ ts%5B0%5D && +%0A node.ar @@ -299,16 +299,22 @@ Literal' +%0A ) ;%0A%7D%0A%0Amod @@ -536,16 +536,143 @@ tings);%0A + const isTestCase = astUtils.buildIsTestCaseAnswerer();%0A const isDescribe = astUtils.buildIsDescribeAnswerer();%0A%0A @@ -784,25 +784,16 @@ if ( -astUtils. isTestCa @@ -945,24 +945,52 @@ message: +%0A 'Test title @@ -1219,25 +1219,16 @@ if (! -astUtils. isDescri @@ -1670,33 +1670,24 @@ if ( -astUtils. isDescribe(n @@ -2116,32 +2116,32 @@ n:exit'(node) %7B%0A + @@ -2144,25 +2144,16 @@ if ( -astUtils. isDescri
edcd560e4b2c47d6c9b3b5ad92527351df90e337
Fix typo
lib/service/middleware/cache.js
lib/service/middleware/cache.js
'use strict' var memjs = require('memjs') var crypto = require('crypto') module.exports = function (config) { if (!config.MEMCAHE_SERVERS) { throw new Error('MEMCAHE_SERVERS config variable must be set') } var client = memjs.Client.create(config.MEMCAHE_SERVERS, { username: config.MEMCAHE_USERNAME, password: config.MEMCAHE_PASSWORD }) var createKey = function (data) { var key = config.SERVICE_NAME + '_' + JSON.stringify(data) return crypto.createHash('md5').update(key).digest('hex') } var retrieve = function (req, res, next) { var key = createKey(req.data) client.get(key, function (err, val) { if (err) { console.error('CACHE failed to retrieve', key, err) next() return } if (val) { try { res.data = JSON.parse(val.toString()) res.send(null, req, res) return } catch (e) { client.delete(key) } } next() }) } var save = function (req, res, next) { var key = createKey(req.data) client.set(key, JSON.stringify(res.data), function (err, val) { if (err || !val) { console.error('CACHE failed to save', key, err, val) } }, config.CACHE_EXPIRATION) next() // intenionally don't wait for save to finish } var noop = function (req, res, next) { next() } return { middleware: { retrieve: config.CACHE_ENABLED ? retrieve : noop, save: config.CACHE_ENABLED ? save : noop } } }
JavaScript
0.999999
@@ -1272,16 +1272,17 @@ // inten +t ionally
40f706329c79060678830ee7b0cce022ad840554
Add console output for errors deleting items
lib/test/object-readall-hook.js
lib/test/object-readall-hook.js
// test/object-readall-hook.js // // Testing DatabankObject readAll() hooks // // Copyright 2012, StatusNet Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. var assert = require('assert'), Step = require('step'), vows = require('vows'), databank = require('../databank'), Databank = databank.Databank, DatabankObject = require('../databankobject').DatabankObject, keys = ['1932 Ford V8', '1959 Austin Mini', '1955 Chevrolet', '1938 Volkswagen Beetle', '1964 Porsche 911', '1955 Mercedes-Benz 300SL "Gullwing"']; // http://www.insideline.com/features/the-100-greatest-cars-of-all-time.html var objectReadallHookContext = function(driver, params) { var context = {}; context["When we create a " + driver + " databank"] = { topic: function() { if (!params.hasOwnProperty('schema')) { params.schema = {}; } params.schema.auto = { pkey: 'yearmakemodel' }; return Databank.get(driver, params); }, 'We can connect to it': { topic: function(bank) { bank.connect(params, this.callback); }, teardown: function(bank) { var callback = this.callback; Step( function() { var i, group = this.group(); for (i = 0; i < keys.length; i++) { bank.del('auto', keys[i], group()); } }, function(err) { bank.disconnect(this); }, callback ); }, 'without an error': function(err) { assert.ifError(err); }, 'and we can initialize the Auto class': { topic: function(bank) { var Auto; Auto = DatabankObject.subClass('auto'); Auto.bank = function() { return bank; }; return Auto; }, 'which is valid': function(Auto) { assert.isFunction(Auto); }, 'and we can create a few autos': { topic: function(Auto) { var cb = this.callback; Step( function() { var i, group = this.group(); for (i = 0; i < keys.length; i++) { Auto.create({yearmakemodel: keys[i]}, group()); } }, function(err, autos) { cb(err, autos); } ); }, 'it works': function(err, autos) { assert.ifError(err); assert.isArray(autos); }, 'and we read a few back': { topic: function(autos, Auto) { var cb = this.callback, called = { before: 0, after: 0, autos: {} }; Auto.beforeGet = function(yearmakemodel, callback) { called.before++; callback(null, yearmakemodel); }; Auto.prototype.afterGet = function(callback) { called.after++; this.addedByAfter = 23; callback(null, this); }; Auto.readAll(keys, function(err, ppl) { called.autos = ppl; cb(err, called); }); }, 'without an error': function(err, called) { assert.ifError(err); assert.isObject(called); }, 'and the before hook is called': function(err, called) { assert.isObject(called); assert.equal(called.before, keys.length); }, 'and the after hook is called': function(err, called) { assert.equal(called.after, keys.length); }, 'and the after hook modification happened': function(err, called) { var nick; for (nick in called.autos) { assert.isObject(called.autos[nick]); assert.equal(called.autos[nick].addedByAfter, 23); } } } } } } }; return context; }; module.exports = objectReadallHookContext;
JavaScript
0.000001
@@ -2136,32 +2136,141 @@ function(err) %7B%0A + if (err) %7B%0A console.error(err);%0A %7D%0A
e1188d1a36533d7b0521ff3de51ef447ddfd28d3
Use a file to execute clang-query commands
lib/tooling/clang-query-tool.js
lib/tooling/clang-query-tool.js
// Copyright (c) 2018, Compiler Explorer Authors // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. "use strict"; const fs = require('fs-extra'), path = require('path'), BaseTool = require('./base-tool'); class ClangQueryTool extends BaseTool { constructor(toolInfo, env) { super(toolInfo, env); } async runTool(compilationInfo, inputFilepath, args, stdin) { const sourcefile = inputFilepath; const compilerExe = compilationInfo.compiler.exe; const options = compilationInfo.options; const dir = path.dirname(sourcefile); const compileFlags = options.filter(option => (option !== sourcefile)); if (!compilerExe.includes("clang++")) { compileFlags.push(this.tool.options); } await fs.writeFile(path.join(dir, "compile_flags.txt"), compileFlags.join('\n')); const toolResult = await super.runTool(compilationInfo, sourcefile, args, stdin); if (toolResult.stdout.length > 0) { const lastLine = toolResult.stdout.length - 1; toolResult.stdout[lastLine].text = toolResult.stdout[lastLine].text.replace(/(clang-query>\s)/gi, ""); } return toolResult; } } module.exports = ClangQueryTool;
JavaScript
0
@@ -2151,24 +2151,163 @@ oin('%5Cn'));%0A + await fs.writeFile(path.join(dir, %22query_commands.txt%22), stdin);%0A args.push('-f');%0A args.push('query_commands.txt');%0A cons @@ -2374,23 +2374,16 @@ le, args -, stdin );%0A%0A
07d90c7dbec4a1d0a4b06c457b7b9e5e01c3d697
update story
src/components/timerPulser/timerPulser.stories.js
src/components/timerPulser/timerPulser.stories.js
import React from 'react'; import { addStoryInGroup, LOW_LEVEL_BLOCKS } from '../../../.storybook/utils'; import { select } from '@storybook/addon-knobs'; import { TimerPulser } from '../../index'; const sizes = ['small', 'medium', 'large']; export default { component: TimerPulser, title: addStoryInGroup(LOW_LEVEL_BLOCKS, 'TimerPulser'), }; export const basic = () => <TimerPulser size={select('Size', sizes, 'medium')} />;
JavaScript
0
@@ -109,59 +109,8 @@ port - %7B select %7D from '@storybook/addon-knobs';%0Aimport %7B Tim @@ -117,26 +117,24 @@ erPulser - %7D from '. ./../ind @@ -129,64 +129,21 @@ m '. -./../index';%0A%0Aconst sizes = %5B'small', 'medium', 'large'%5D +/TimerPulser' ;%0A%0Ae @@ -264,17 +264,17 @@ nst -b +B asic = ( ) =%3E @@ -269,16 +269,20 @@ asic = ( +args ) =%3E %3CTi @@ -295,45 +295,16 @@ ser -size=%7Bselect('Size', sizes, 'medium') +%7B...args %7D /%3E
aac2d47d90531cf18305d3ea7a451606bc2e473e
normalise arguments to write
medea-compressed.js
medea-compressed.js
var after = require('after') , zlib = require('zlib') , MedeaCompressed = function (db) { if (!(this instanceof MedeaCompressed)) return new MedeaCompressed(db) this.db = db } // borrowed from https://github.com/mafintosh/gunzip-maybe , isGzipped = function (data) { if (data.length < 10) return false // gzip header is 10 bytes if (data[0] !== 0x1f && data[1] !== 0x8b) return false // gzip magic bytes if (data[2] !== 8) return false // is deflating return true } , maybeGunzip = function (data, callback) { if (isGzipped(data)) zlib.gunzip(data, callback) else callback(null, data) } , maybeGzip = function (data, callback) { zlib.gzip(data, function (err, zipped) { if (err) return callback(err) callback(null, zipped.length < data.length ? zipped : data) }) } MedeaCompressed.prototype.get = function (key, snapshot, callback) { if (!callback) { callback = snapshot snapshot = null } this.db.get(key, snapshot, function (err, data) { if (err) return callback(err) if (!data) return callback() maybeGunzip(data, callback) }) } MedeaCompressed.prototype.put = function (key, value, callback) { var self = this maybeGzip(value, function (err, zipped) { if (err) return callback(err) self.db.put(key, zipped, callback) }) } MedeaCompressed.prototype.createBatch = function () { var operations = [] return { put: function (key, value) { operations.push({ key: key, value: value, type: 'put'}) }, remove: function (key) { operations.push({ key: key, type: 'remove' }) }, operations: operations } } MedeaCompressed.prototype.write = function (batch, options, callback) { var self = this , compressedOperations = new Array(batch.operations.length) , done = after(batch.operations.length, function (err) { if (err) return callback(err) var medeaBatch = self.db.createBatch() compressedOperations.forEach(function (operation) { if (operation.type === 'put') { medeaBatch.put(operation.key, operation.value) } else { medeaBatch.remove(operation.key) } }) self.db.write(medeaBatch, options, callback) }) batch.operations.forEach(function (operation, index) { if (operation.type === 'remove') { compressedOperations[index] = { type: 'remove', key: operation.key } done() } else { maybeGzip(operation.value, function (err, zipped) { if (err) return done(err) compressedOperations[index] = { type: 'put', key: operation.key, value: zipped } done() }) } }) } ;[ 'remove', 'createSnapshot', 'compact', 'open', 'close' ].forEach(function (methodName) { MedeaCompressed.prototype[methodName] = function () { return this.db[methodName].apply(this.db, arguments) } }) module.exports = MedeaCompressed
JavaScript
0.000036
@@ -1781,32 +1781,96 @@ ns, callback) %7B%0A + if (!callback) %7B%0A callback = options%0A options = %7B%7D%0A %7D%0A%0A var self = thi
84d91967282d6ad580b3f734cc3480fdf4906e24
fix whitespace in Profile.test.js
src/elements/components/GlobalNav/Profile.test.js
src/elements/components/GlobalNav/Profile.test.js
/** Copyright 2016 Autodesk,Inc. 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. */ import { mount } from 'enzyme'; import * as HIG from 'hig.web'; import React from 'react'; import GlobalNav from './GlobalNav'; import TopNav from './TopNav'; import Profile from './Profile'; import SharedExamples from './SharedExamples'; const onImageClick = function() { return 'onImageClick'; }; const onSignoutClick = function() { return 'onSignoutClick'; }; const Context = props => { return ( <GlobalNav> <TopNav> <Profile open={props.open} image={props.image} onProfileImageClick={onImageClick} name={props.name} email={props.email} signOutLabel={props.signOutLabel} onSignOutClick={onSignoutClick} profileSettingsLabel={props.profileSettingsLabel} profileSettingsLink={props.profileSettingsLink} /> </TopNav> </GlobalNav> ); }; function createHigContext(defaults) { const higContainer = document.createElement('div'); const higNav = new HIG.GlobalNav(); higNav.mount(higContainer); const higTopNav = new higNav.partials.TopNav({}); higNav.addTopNav(higTopNav); const higItem = new higTopNav.partials.Profile(defaults); higTopNav.addProfile(higItem); return { higContainer, higItem }; } function setupProfile() { const defaults = { image: 'something.jpg', name: 'Foo Bears', email: '[email protected]' }; const reactContainer = document.createElement('div'); mount(<Context {...defaults} />, { attachTo: reactContainer }); return { reactContainer }; } describe('<Profile>', () => { describe('constructor', () => { it('has a good snapshot', () => { const { reactContainer } = setupProfile(); expect(reactContainer.firstChild.outerHTML).toMatchSnapshot(); }); }); describe('setting and updating props', () => { const shex = new SharedExamples(Context, createHigContext); const configSets = [ { key: 'email', sampleValue: '[email protected]', updateValue: '[email protected]', mutator: 'setEmail' }, { key: 'name', sampleValue: 'Hello Kitty', updateValue: 'Dear Daniel', mutator: 'setName' }, { key: 'image', sampleValue: '/images/foo.jpg', updateValue: '/images/BAR.PNG', mutator: 'setImage' }, { key: 'signOutLabel', sampleValue: 'Logout', updateValue: 'Sign Out', mutator: 'setSignOutLabel' }, { key: 'profileSettingsLabel', sampleValue: 'Settings', updateValue: 'Preferences', mutator: 'setProfileSettingsLabel' }, { key: 'profileSettingsLink', sampleValue: 'http://www.google.com', updateValue: 'http://www.sanrio.com', mutator: 'setProfileSettingsLink' }, ]; configSets.forEach(function(config) { it(`can set props for ${config.key}`, () => { shex.verifyPropsSet(config); }); it(`can update props for ${config.key}`, () => { shex.verifyPropsUpdate(config); }); }); }); describe('open and close profile flyout', () => { const newContext = props => { return ( <GlobalNav> <TopNav> <Profile open={props.open} /> </TopNav> </GlobalNav> ); }; it('sets the flyout as open if initialized as open', () => { const reactContainer = document.createElement('div'); const wrapper = mount(<Context {...{ open: true }} />, { attachTo: reactContainer }); const elem = reactContainer.getElementsByClassName( 'hig__flyout hig__flyout--open' ); expect(elem.length).toEqual(1); }); it('opens the flyout on prop change', () => { const reactContainer = document.createElement('div'); const wrapper = mount(<Context {...{ open: false }} />, { attachTo: reactContainer }); var elem = reactContainer.getElementsByClassName('hig__flyout'); expect(elem.length).toEqual(1); wrapper.setProps({ open: true }); elem = reactContainer.getElementsByClassName( 'hig__flyout hig__flyout--open' ); expect(elem.length).toEqual(1); }); }); });
JavaScript
0.999956
@@ -3409,18 +3409,16 @@ %0A %7D -,%0A %0A %5D;%0A
fefbb106243eab175510a737bb0241086a82701e
Fix bad reference on webhook response.
lib/webhooks/riskOrderStatus.js
lib/webhooks/riskOrderStatus.js
/* LIB */ const radial = require('../../radial'); const authenticate = require('./authenticate'); /* MODULES */ const xmlConvert = require('xml-js'); /* CONSTRUCTOR */ (function () { var RiskOrderStatus = {}; /* PRIVATE VARIABLES */ /* PUBLIC VARIABLES */ /* PUBLIC FUNCTIONS */ RiskOrderStatus.parse = function (req, fn) { authenticate('riskOrderStatus', req, function (err) { if (err) { return fn({ status: 401, type: 'Authentication Failed', message: err.message }); } var body = req.body; var reply = response.RiskAssessmentReplyList; var assessment = reply.RiskAssessmentReply; return fn(null, { orderId: assessment.OrderId, responseCode: assessment.ResponseCode, storeId: assessment.StoreId, reasonCode: assessment.ReasonCode, reasonCodeDescription: assessment.ReasonCodeDescription }); }); }; /* NPM EXPORT */ if (typeof module === 'object' && module.exports) { module.exports = RiskOrderStatus.parse; } else { throw new Error('This module only works with NPM in NodeJS environments.'); } }());
JavaScript
0.000001
@@ -593,24 +593,20 @@ reply = -response +body .RiskAss
f85db126a9ac5af0a84abb2ab82c73a6efd282ef
fix polyfill bugs
src/inject/generic/win32/polyfill_Notification.js
src/inject/generic/win32/polyfill_Notification.js
import os from 'os'; const osVersion = os.release().split('.'); if (osVersion[0] && (parseInt(osVersion[0], 10) > 6 || parseInt(osVersion[0], 10) === 6 && parseInt(osVersion[1], 10) > 1) { // If we are above windows 7 we can use the system notifications but with // the silent flag forced on require('../silent_Notification'); } else { const NOTIFICATIONS = []; /** * This class is designed to mock the HTML5 Notification API on windows * because the native implementation has annoyed notifcation noises that * can't be turned off. * * This class is intended to follow the API spec here * -- https://developer.mozilla.org/en/docs/Web/API/notification * * This is so it could be used anywhere the actual API is used */ class FakeNotification { constructor(text, options) { /** Instance Properties **/ this.title = text; this.dir = options.dir || null; this.lang = options.lang || null; this.body = options.body || ''; this.tag = options.tag || null; this.icon = options.icon || null; this.data = options; NOTIFICATIONS.push(this); this._id = NOTIFICATIONS.length; Emitter.fire('notify', { _id: this._id, title: this.title, icon: this.icon, body: this.body, }); /** Instance Event Handlers**/ this.onclick = null; this.onerror = null; this.onclose = null; this.onshow = null; } /** Instance Methods **/ close() { Emitter.fire('notify:close', this._id); } } /** Static Properties **/ FakeNotification.permission = 'granted'; /** Static Methods **/ FakeNotification.requestPermission = (callback) => { callback('granted'); }; /** Event Handlers -- Cross Thread **/ // TODO: Implement this event in the notificationPolyfill Emitter.on('notification:clicked', (event, id) => { if (NOTIFICATIONS[id] && NOTIFICATIONS[id].onclick) { NOTIFICATIONS[id].onclick(); } }); // TODO: Implement this event in the notificationPolyfill Emitter.on('notification:error', (event, details) => { const id = details.id; if (NOTIFICATIONS[id] && NOTIFICATIONS[id].onerror) { NOTIFICATIONS[id].onerror(details.error); } }); // TODO: Implement this event in the notificationPolyfill Emitter.on('notification:closed', (event, id) => { if (NOTIFICATIONS[id] && NOTIFICATIONS[id].onclose) { NOTIFICATIONS[id].onclose(); } }); // TODO: Implement this event in the notificationPolyfill Emitter.on('notification:showed', (event, id) => { if (NOTIFICATIONS[id] && NOTIFICATIONS[id].onshow) { NOTIFICATIONS[id].onshow(); } }); window._Notification = window.Notification; window.Notification = FakeNotification; }
JavaScript
0.000001
@@ -181,16 +181,17 @@ 10) %3E 1) +) %7B%0A //
13e90fd8297ee5a4186269b641578532b424644b
Fix nits
js/tss/Format.js
js/tss/Format.js
/** * T'SoundSystem for JavaScript */ /** * Format prototype * * Contain data read and write functions. * TODO: Use this prototype from all files in the library. * @author Takashi Toyoshima <[email protected]> */ var Format = function () { this.endian = Format.BIG_ENDIAN; } Format.BIG_ENDIAN = 0; Format.LITTLE_ENDIAN = 1; Format.readI32BE = function (data, offset) { return (data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3]; }; Format.readU32BE = function (data, offset) { var i32 = Format.readI32BE(data, offset); if (i32 < 0) return 0x100000000 + i32; return i32; }; Format.readI32LE = function (data, offset) { return data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24); }; Format.readU32LE = function (data, offset) { var i32 = Format.readI32LE(data, offset); if (i32 < 0) return 0x100000000 + i32; return i32; }; Format.stringLength = function (data, offset) { var length = 0; for (var i = offset; i < data.byteLength; i++) { if (0 == data[offset]) break; length++; } return length; }; Format.prototype.setDefaultEndian = function (endian) { this.endian = endian; }; Format.prototype.readI32 = function (data, offset) { if (this.endian == Format.BIG_ENDIAN) return Format.readI32BE(data, offset); return Format.readI32LE(data, offset); }; Format.prototype.readU32 = function (data, offset) { if (this.endian == Format.BIG_ENDIAN) return Format.readU32BE(data, offset); return Format.readU32LE(data, offset); };
JavaScript
0.000016
@@ -281,16 +281,17 @@ NDIAN;%0A%7D +; %0A%0AFormat @@ -1123,16 +1123,17 @@ if (0 == += data%5Bof
8f332601da0bf31e7381e24eea4d5af23b74e0fe
Add (sparse) English locale for `main`
js/utils/i18n.js
js/utils/i18n.js
"use strict"; var zoteroI18n = requirePo('./../../../editorsnotes/djotero/locale/%s/LC_MESSAGES/django.po'); module.exports = { main: null, zotero: zoteroI18n }
JavaScript
0
@@ -12,24 +12,34 @@ %22;%0A%0A -var zoteroI18n = +module.exports = %7B%0A main: req @@ -74,15 +74,12 @@ tes/ -djotero +main /loc @@ -112,63 +112,95 @@ po') -;%0A%0Amodule.exports = %7B%0A main: null,%0A zotero: zoteroI18n +,%0A zotero: requirePo('./../../../editorsnotes/djotero/locale/%25s/LC_MESSAGES/django.po') %0A%7D%0A
b1a735f9de6cd95e5d3cc04cbc24fb10df01084a
Update browser.js
bin/browser.js
bin/browser.js
const puppeteer = require('puppeteer'); const request = JSON.parse(process.argv[2]); const callChrome = async () => { let browser; let page; try { browser = await puppeteer.launch({ args: request.options.args || [] }); page = await browser.newPage(); if (request.options && request.options.userAgent) { await page.setUserAgent(request.options.userAgent); } if (request.options && request.options.viewport) { await page.setViewport(request.options.viewport); } const requestOptions = {}; if (request.options && request.options.networkIdleTimeout) { requestOptions.waitUntil = 'networkidle'; requestOptions.networkIdleTimeout = request.options.networkIdleTimeout; } await page.goto(request.url, requestOptions); console.log(await page[request.action](request.options)); await browser.close(); } catch (exception) { if (browser) { await browser.close(); } console.error(exception); process.exit(1); } }; callChrome();
JavaScript
0.000003
@@ -9,16 +9,20 @@ ppeteer + = requir @@ -37,17 +37,16 @@ teer');%0A -%0A const re @@ -51,16 +51,22 @@ request + = JSON.p @@ -106,16 +106,19 @@ lChrome + = async @@ -156,16 +156,156 @@ t page;%0A + const requestOptions = %7B%7D;%0A const returnOptions = %7B%7D;%0A returnOptions.requests = %5B%5D;%0A returnOptions.response = %7B%7D;%0A %0A try @@ -307,16 +307,25 @@ try %7B%0A + %0A @@ -396,17 +396,16 @@ %5B%5D %7D);%0A -%0A @@ -409,16 +409,19 @@ page + = await @@ -439,16 +439,24 @@ Page();%0A + %0A @@ -710,33 +710,32 @@ ;%0A %7D%0A -%0A const reques @@ -726,35 +726,8 @@ -const requestOptions = %7B%7D;%0A %0A @@ -944,130 +944,684 @@ %7D%0A -%0A await page.goto(request.url, requestOptions);%0A%0A console.log(await page%5Brequest.action%5D(request.options));%0A + if (request.options && (request.options.interceptRequests %7C%7C request.options.blockRequestTypes)) %7B%0A await page.setRequestInterception(true);%0A page.on('request', httpRequest =%3E %7B%0A returnOptions.requests.push(httpRequest.url());%0A httpRequest.continue();%0A %7D%0A );%0A %7D%0A let httpResponse = await page.goto(request.url, requestOptions);%0A await page%5Brequest.action%5D(request.options);%0A returnOptions.response.status = httpResponse.status();%0A returnOptions.response.url = request.url;%0A console.log(JSON.stringify(returnOptions)); %0A @@ -1742,25 +1742,24 @@ %7D%0A -%0A console. @@ -1754,22 +1754,39 @@ -consol +returnOptions.respons e.error -( + = exce @@ -1790,19 +1790,77 @@ xception +.message;%0A console.log(JSON.stringify(returnOptions) ); -%0A %0A @@ -1877,9 +1877,9 @@ xit( -1 +0 );%0A @@ -1886,17 +1886,16 @@ %7D%0A%7D;%0A -%0A callChro
cd0700c882c2a2b927d2a6c4dd4d453a955d133b
update lib index.js generator to consider sub dirs and internal
generators/init-lib/templates/plain/index.js
generators/init-lib/templates/plain/index.js
/* ***************************************************************************** * Caleydo - Visualization for Molecular Biology - http://caleydo.org * Copyright (c) The Caleydo Team. All rights reserved. * Licensed under the new BSD license, available at http://caleydo.org/license **************************************************************************** */ /** * generates and object that contain all modules in the src folder accessible as properties */ /*** * magic file name for the pseudo root file * @type {string} */ var INDEX_FILE = './index.ts'; /** * sorts the given filename by name ensuring INDEX is the first one * @param a * @param b * @returns {number} */ function byName(a, b) { if (a === INDEX_FILE) { return a === b ? 0 : -1; } if (b === INDEX_FILE) { return 1; } return a.toLowerCase().localeCompare(b.toLowerCase()); } //list all modules in the src folder excluding the one starting with _ var req = require.context('./src', false, /\/[^_].*\.tsx?$/); var files = req.keys().sort(byName); //root file exists? else use anonymous root object if (files[0] === INDEX_FILE) { module.exports = req(files.shift()); } else { module.exports = {}; } //generate getter for all modules files.forEach(function (f) { Object.defineProperty(module.exports, f.substring(2, f.length - 3), { get: function () { return req(f); }, enumerable: true }); });
JavaScript
0
@@ -709,18 +709,16 @@ a, b) %7B%0A - if (a @@ -735,28 +735,24 @@ FILE) %7B%0A - - return a === @@ -764,26 +764,22 @@ 0 : -1;%0A - %7D%0A - - if (b == @@ -794,20 +794,16 @@ FILE) %7B%0A - retu @@ -810,22 +810,18 @@ rn 1;%0A - %7D%0A +%7D%0A return @@ -981,24 +981,58 @@ c', -false, /%5C/%5B%5E_%5D.* +true, /%5E%5C.%5C/(?!internal)((%5B%5E_%5D%5B%5Cw%5D+)%7C(%5Cw+%5C/index)) %5C.ts @@ -1157,26 +1157,24 @@ X_FILE) %7B%0A - - module.expor @@ -1207,18 +1207,16 @@ else %7B%0A - module @@ -1296,18 +1296,16 @@ n (f) %7B%0A - Object @@ -1358,26 +1358,86 @@ f.l -ength - 3 +astIndexOf('/index.') %3E 0 ? f.lastIndexOf('/index.') : f.lastIndexOf('.') ), %7B%0A - @@ -1454,16 +1454,22 @@ ion () %7B +%0A return @@ -1479,16 +1479,16 @@ (f); - %7D, %0A +%7D,%0A @@ -1504,18 +1504,16 @@ e: true%0A - %7D);%0A%7D)
905ed6106b2c83c23a5c58d5257fd39cac25db5d
use windows 10 with edge
karma.conf-ci.js
karma.conf-ci.js
/*jshint node: true */ /** * Karma configuration options when testing a push or pull request from a branch. * This file expects certain TRAVIS secure environment variables to be set. **/ module.exports = function (config) { 'use strict'; var base = 'BrowserStack', customLaunchers = { bs_windows_ie_11: { base: base, browser: 'ie', browser_version: '11.0', os: 'Windows', os_version: '8.1' }, bs_windows_edge: { base: base, browser: 'edge', os: 'Windows', os_version: '8.1' }, bs_windows_chrome_latest: { base: base, browser: 'chrome', os: 'Windows', os_version: '8.1' }, bs_windows_firefox_latest: { base: base, browser: 'firefox', os: 'Windows', os_version: '8.1' }, bs_osx_safari_latest: { base: base, browser: 'safari', os: 'OS X', os_version: 'Yosemite' }, bs_osx_chrome_latest: { base: base, browser: 'chrome', os: 'OS X', os_version: 'Yosemite' }, bs_osx_firefox_latest: { base: base, browser: 'firefox', os: 'OS X', os_version: 'Yosemite' }, bs_android_samsung_galaxy_s5_4_4: { base: base, device: 'Samsung Galaxy S5', os: 'android', os_version: '4.4' } }, shared = require('./karma.conf-shared.js'); shared.files.push( 'dist/js/locales/sky-locale-en-US.js', 'dist/css/sky-bundle.css', { pattern: 'dist/css/fonts/*.*', included: false, served: true } ); // Add new reporters shared.reporters.push('coveralls'); // Coveralls needs lcov shared.coverageReporter.reporters.push({ type: 'lcov', dir: 'coverage/' }); config.set(shared); config.set({ singleRun: true, customLaunchers: customLaunchers, browsers: Object.keys(customLaunchers), browserDisconnectTimeout: 3e5, browserDisconnectTolerance: 3, browserNoActivityTimeout: 3e5, captureTimeout: 3e5, browserStack: { port: 9876, pollingTimeout: 10000 } }); };
JavaScript
0.000001
@@ -655,35 +655,34 @@ os_version: ' -8. 1 +0 '%0A %7D,
83ae2d9279a8b322b16fe4b0d04c52326119fb36
Add missing 'ko' export
localize/index.js
localize/index.js
'use strict'; module.exports = { en: require('./en'), ar: require('./ar'), cz: require('./cz'), de: require('./de'), es: require('./es'), fr: require('./fr'), hu: require('./hu'), it: require('./it'), ja: require('./ja'), nb: require('./nb'), nl: require('./nl'), pl: require('./pl'), 'pt-BR': require('./pt-BR'), ru: require('./ru'), sk: require('./sk'), sv: require('./sv'), th: require('./th'), zh: require('./zh'), 'zh-TW': require('./zh-TW'), };
JavaScript
0.999811
@@ -248,24 +248,49 @@ re('./ja'),%0A + ko: require('./ko'),%0A nb: requ
3d9275cc3b2d97b9c87934fcd701b922d4ec9d32
FIX in-page nav
wazimap_za/static/js/profiles.js
wazimap_za/static/js/profiles.js
$('.floating-nav').affix({ offset: { top: $('.floating-nav').offset().top, }, }); $('a[href^="#"]').on('click', function(e) { e.preventDefault(); var target = this.hash; var $target = $(target); if ($target.length) { window.scroll(0, $target.offset().top - 90); } });
JavaScript
0
@@ -278,16 +278,99 @@ - 90);%0A + if ('pushState' in window.history) window.history.pushState(%7B%7D, null, target);%0A %7D%0A%7D);%0A
a1a97799dea15e8ef6836f7a527e081644c73a50
fix typo in name
packages/plugin-tab/postinstall.js
packages/plugin-tab/postinstall.js
console.log(`Pattern Lab Node Plugin - "plugin-tab" installed. Use the CLI to install this: patternlab install --plugins @pattern-lab/tab Configure or disable this plugin inside your patternlab-config.json file. Add tabs to the Pattern Lab UI by adding file extensions to the "tabsToAdd" array on the plugins['@pattern-lab/plugin-tab'].options object. `);
JavaScript
0.000005
@@ -127,16 +127,23 @@ ern-lab/ +plugin- tab%0AConf
31c51ea9eb37bbab13867c311dd397e07cd674a0
Add a layer to the document's children list when created and support activeLayer.
src/Doc.js
src/Doc.js
Doc = Base.extend({ initialize: function(canvas) { this.canvas = canvas; this.ctx = this.canvas.getContext('2d'); this.size = new Size(canvas.offsetWidth, canvas.offsetHeight); this.children = []; }, redraw: function() { this.ctx.clearRect(0, 0, this.size.width, this.size.height); for(var i = 0, l = this.children.length; i < l; i++) { this.children[i].draw(this.ctx); } } });
JavaScript
0
@@ -41,24 +41,40 @@ n(canvas) %7B%0A +%09%09if(canvas) %7B%0A%09 %09%09this.canva @@ -85,16 +85,17 @@ canvas;%0A +%09 %09%09this.c @@ -127,24 +127,25 @@ xt('2d');%0A%09%09 +%09 this.size = @@ -201,26 +201,78 @@ ;%0A%09%09 -this.children = %5B%5D +%7D%0A%09%09this.activeLayer = new Layer();%0A%09%09this.children = this.activeLayer ;%0A%09%7D @@ -295,16 +295,37 @@ ion() %7B%0A +%09%09if(this.canvas) %7B%0A%09 %09%09this.c @@ -379,16 +379,17 @@ eight);%0A +%09 %09%09for(va @@ -436,24 +436,25 @@ ; i++) %7B%0A%09%09%09 +%09 this.childre @@ -474,16 +474,21 @@ s.ctx);%0A +%09%09%09%7D%0A %09%09%7D%0A%09%7D%0A%7D
b20a1ef1cc49b4decfc1c34098764eb9ac3f316f
Fix typo and use the weak boolean on the correct place.
packages/reactive-state/package.js
packages/reactive-state/package.js
Package.describe({ name: 'meteorflux:reactive-state', version: '1.3.5', summary: 'ReactiveState is a reactive object to save complex state data.', git: 'https://github.com/worona/meteorflux', documentation: 'README.md' }); Package.onUse(function(api) { api.versionsFrom('1.2'); api.use('meteorflux:[email protected]'); api.imply('meteorflux:namespace'); api.use('ecmascript'); api.use('check'); api.use('underscore'); api.use('tracker'); api.use('blaze-html-templates'); api.addFiles('lib/reactive-state.js', 'client'); api.export('ReactiveState', 'client'); }); Package.onTest(function(api) { api.use('ecmascript'); api.use('check'); api.use('tracker'); api.use('reactive-var'); api.use('tinytest'); api.use('blaze-html-templates', {week: true}); api.use('mongo'); api.use('meteorflux:reactive-state', 'client'); api.addFiles('tests/client/reactive-state-tests.js', 'client'); api.addFiles('tests/client/reactive-state-tests.html', 'client'); });
JavaScript
0.000002
@@ -486,16 +486,32 @@ mplates' +, %7B weak: true %7D );%0A api @@ -786,22 +786,8 @@ tes' -, %7Bweek: true%7D );%0A
86ee50e723cfd34ac855df943971bb5bbc42fb76
use the stringify function in api correctly
src/api.js
src/api.js
var _ = require('./utility'); var Transport = null; var url = null; function init(context) { if (context == 'server') { Transport = require('./server/transport'); url = require('url'); } else { Transport = require('./browser/transport'); url = require('./browser/url'); } } var defaultOptions = { host: 'api.rollbar.com', path: '/api/1', search: null, version: '1', protocol: 'https', port: 443 }; /** * Api is an object that encapsulates methods of communicating with * the Rollbar API. It is a standard interface with some parts implemented * differently for server or browser contexts. It is an object that should * be instantiated when used so it can contain non-global options that may * be different for another instance of RollbarApi. * * @param options { * endpoint: an alternative endpoint to send errors to * must be a valid, fully qualified URL. * The default is: https://api.rollbar.com/api/1 * proxy: if you wish to proxy requests provide an object * with the following keys: * host (required): foo.example.com * port (optional): 123 * protocol (optional): https * } */ function Api(accessToken, options) { this.transport = getTransportFromOptions(options, defaultOptions); this.accessToken = accessToken; } /** * * @param data * @param callback */ Api.prototype.postItem = function(data, callback) { var transportOptions = this._transportOptions('/item/', 'POST') var payload = buildPayload(this.accessToken, data); Transport.post(this.accessToken, transportOptions, payload, callback); }; /** Helpers **/ function buildPayload(accessToken, data) { if (_.isType(data.context, 'object')) { data.context = _.stringify(data.context); if (data.context && data.context.length) { data.context = data.context.substr(0, 255); } } return { access_token: accessToken, data: data }; } function getTransportFromOptions(options, defaults) { var hostname = defaults.hostname; var protocol = defaults.protocol; var port = defaults.port; var path = defaults.path; var search = defaults.search; var proxy = options.proxy; if (options.endpoint) { var opts = url.parse(options.endpoint); hostname = opts.hostname; protocol = opts.protocol.split(':')[0]; port = opts.port; path = opts.pathname; search = opts.search; } return { hostname: hostname, protocol: protocol, port: port, path: path, search: search, proxy: proxy }; } Api.prototype._transportOptions = function(path, method) { var protocol = this.transport.protocol || 'https'; var port = this.transport.port || (protocol === 'http' ? 80 : protocol === 'https' ? 443 : undefined); var hostname = this.transport.hostname; var path = appendPathToPath(this.transport.path, path); if (this.transport.search) { path = path + this.transport.search; } if (this.transport.proxy) { path = protocol + '://' + hostname + path; hostname = this.transport.proxy.host; port = this.transport.proxy.port; protocol = this.transport.proxy.protocol || protocol; } return { protocol: protocol, hostname: hostname, path: path, port: port, method: method }; }; function appendPathToPath(base, path) { var baseTrailingSlash = /\/$/.test(base); var pathBeginningSlash = /^\//.test(path); if (baseTrailingSlash && pathBeginningSlash) { path = path.substring(1); } else if (!baseTrailingSlash && !pathBeginningSlash) { path = '/' + path; } return base + path; } module.exports = function(context) { init(context); return Api; };
JavaScript
0.000043
@@ -61,16 +61,56 @@ = null; +%0Avar json = null;%0Avar jsonBackup = null; %0A%0Afuncti @@ -230,16 +230,82 @@ 'url');%0A + json = JSON;%0A jsonBackup = require('json-stringify-safe');%0A %7D else @@ -347,32 +347,32 @@ er/transport');%0A - url = requir @@ -391,16 +391,40 @@ /url');%0A + json = RollbarJSON;%0A %7D%0A%7D%0A%0Av @@ -1895,24 +1895,42 @@ data.context +, json, jsonBackup );%0A if (d
1bda425022393556dca9388d8c3c3ccc4793248d
Fix language sorthand for danish language
locale/bootstrap-markdown.da.js
locale/bootstrap-markdown.da.js
/** * Danish translation for bootstrap-markdown * Dan Storm <[email protected]> */ (function ($) { $.fn.markdown.messages.nb = { 'Bold': 'Fed', 'Italic': 'Kursiv', 'Heading': 'Overskrift', 'URL/Link': 'URL/Link', 'Image': 'Billede', 'List': 'Liste', 'Preview': 'Forhåndsvisning', 'strong text': 'stærk tekst', 'emphasized text': 'fremhævet tekst', 'heading text': 'overskrift tekst', 'enter link description here': 'Skriv link beskrivelse her', 'Insert Hyperlink': 'Indsæt link', 'enter image description here': 'Indsæt billede beskrivelse her', 'Insert Image Hyperlink': 'Indsæt billede link', 'enter image title here': 'Indsæt billede titel', 'list text here': 'Indsæt liste tekst her', 'quote here': 'Indsæt citat her', 'code text here': 'Indsæt kode her' }; }(jQuery));
JavaScript
0.998494
@@ -129,10 +129,10 @@ ges. -nb +da = %7B
973143a4b719c44eb47c74f844a5dc4a2ca3a322
change lisa to lissie in help message
src/cli.js
src/cli.js
import meow from 'meow' import lissie from './lissie' const cli = meow(` Usage $ lisa <license> Options -a, --author "<your name>" -y, --year <year> -e, --email "<your email>" -p, --project "<project name>" -v, --version -h, --help Examples $ lisa mit $ lisa mit -a "Zach Orlovsky" -y 2016 $ lisa mit -a "Zach Orlovsky" -e "[email protected]" `, { alias: { a: 'author', y: 'year', e: 'email', p: 'project', v: 'version', h: 'help' } } ) console.log( lissie({ license: cli.input[0], author: cli.flags.author, year: cli.flags.year, email: cli.flags.email, project: cli.flags.project }) )
JavaScript
0
@@ -84,17 +84,19 @@ $ lis -a +sie %3Clicens @@ -278,25 +278,27 @@ es%0A $ lis -a +sie mit%0A $ l @@ -291,33 +291,35 @@ ie mit%0A $ lis -a +sie mit -a %22Zach Or @@ -343,17 +343,19 @@ $ lis -a +sie mit -a
d798a919ba8b5d8baa7dabfe237a5320ea3230f2
Update jQuery include to 2.2.2
gamedeals-table-highlighter.user.js
gamedeals-table-highlighter.user.js
// ==UserScript== // @name GameDeals table highlighter // @namespace ohmanger // @grant GM_xmlhttpRequest // @include https://www.reddit.com/r/GameDeals/comments/* // @require http://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js // @updateURL https://raw.githubusercontent.com/ohmanger/userscripts/master/gamedeals-table-highlighter.user.js // @downloadURL https://raw.githubusercontent.com/ohmanger/userscripts/master/gamedeals-table-highlighter.user.js // @version 1.1.1 // ==/UserScript== this.$ = this.jQuery = jQuery.noConflict(true); var users = [ '.author.id-t2_bukfv', // /u/dEnissay '.author.id-t2_in61j', // /u/ABOOD-THE-PLAYER ]; $( users.join(',') ).each( function( index ) { var table = $( this ).parent().parent().find( '.usertext-body table' ); table.after( '<button class="gdth-get-status">Get Steam status</button>' ); }); $( '.sitetable' ).on( 'click', 'button.gdth-get-status', function( event ) { event.preventDefault(); var table_rows = $( this ).siblings( 'table' ).find( 'tbody tr' ); table_rows.each( function ( index ) { var tr = $(this), app_url = tr.html().match( /http:\/\/store\.steampowered\.com\/app\/(\d*)\//ig ); // Skip if no steam URL found if ( app_url === null ) { return 'continue'; } GM_xmlhttpRequest ( { method: "GET", url: app_url[0], onload: function ( response ) { var is_logged_in = response.responseText.indexOf( "Logout();" ) > -1; if ( is_logged_in ) { var in_library = response.responseText.indexOf( '<div class="already_in_library">' ) > -1; if ( in_library ) { tr.css( 'background', 'lightgreen' ); } else { var in_wishlist = response.responseText.indexOf( '<div id="add_to_wishlist_area_success"' ) === -1; if ( in_wishlist ) { tr.css( 'background', 'lightblue' ); } } } } }); }); });
JavaScript
0.000001
@@ -240,17 +240,17 @@ ery/2.2. -0 +2 /jquery.
e1781b8c5931604daf2e618a158a0d653789c17c
Fix PR issues
bin/release.js
bin/release.js
#!/usr/bin/env node const childProcess = require('child_process'); const fs = require('fs'); const path = require('path'); const minimist = require('minimist'); const semver = require('semver'); const argv = minimist(process.argv, { string: ['push-build', 'target-branch', 'build'], default: { 'push-build': null, 'target-branch': null, 'build-command': null } }); const fileExists = fs.existsSync || fs.accessSync; const exec = childProcess.exec; const toVersion = argv._.pop(); const npmPackageDirectory = argv._.pop(); const cdPath = path.resolve(process.cwd(), npmPackageDirectory); const packageJsonPath = path.resolve(process.cwd(), npmPackageDirectory, 'package.json'); const changelogPath = path.resolve(process.cwd(), npmPackageDirectory, 'CHANGELOG.md'); let pushBuildDir; if (argv['push-build']) { pushBuildDir = path.resolve(process.cwd(), npmPackageDirectory, argv['push-build']); } const formattedDate = new Date().toISOString() .replace(/T/, ' ') .replace(/\..+/, ''); if (!toVersion || !fileExists(packageJsonPath) || argv.help) { console.info([ 'Bumps a new versioned release of the current state into CHANGELOG.md and package.json', 'Uses "git" and "npm".\n', 'Usage: release.js NPM_PACKAGE_DIR [<newversion> | major | minor | patch | prerelease] [options]', 'Options:', ' --push-build (optional) Push the build in this ignored folder to the version branch.', ' --target-branch (optional) (default: MAJOR.x) The branch where the release will be pushed to.', [ ' --build-command (optional) Run the build to be able to include the new version from package.json.', 'Also adds the built files if they are not ignored.' ].join(' ') ].join('\n')); process.exit(1); } const packageJson = require(packageJsonPath); let newVersion; // Used as the version that the release should be bumped with if (semver.valid(toVersion) && semver.gt(toVersion, packageJson.version)) { newVersion = toVersion; } else { newVersion = semver.inc(packageJson.version, toVersion); } if (newVersion === null) { console.error(`Current version "${packageJson.version}" just can be bumped to a higher version`); process.exit(1); } // Set the new branch to the major Version if we release to version const majorVersion = semver.parse(newVersion).major; // Used to create|merge a major-branch let newBranchName; if (argv['target-branch']) { newBranchName = argv['target-branch']; } else { newBranchName = `${majorVersion}.x`; } const switchPathCommands = [ `cd ${cdPath} &&` ]; const changelogCommands = fileExists(changelogPath) ? [ '# add version string to CHANGELOG and commit CHANGELOG', `echo "\\n### v${newVersion} / ${formattedDate}\\n\\n$(cat ${changelogPath})" > ${changelogPath} &&`, `git add ${changelogPath} &&`, `git commit -m "Prepare CHANGELOG for version v${newVersion}" &&` ] : []; const pushBuildCommands = [ '# push build', 'rm -rf ./build', `cp -r ${pushBuildDir}/. ./build`, 'git add --force ./build', `git commit -m "Add build in ${argv['push-build']} to branch ${newBranchName}" &&` ]; const pullCurrentUpstreamCommands = [ '# set upstream for curren branch', 'git push -u origin $releaseBranchName', '# pull the current upstream state', 'git pull --all --tags &&' ]; const updatePackageJsonCommands = [ '# updates package.json, does git commit and git tag', `npm --no-git-tag-version version ${newVersion} &&`, `git commit -am "${newVersion}"` ]; const buildCommands = [ '# Run the build script', `${argv['build-command']} &&`, '# Add buildt changes', 'git add --all &&', `git diff-index --quiet HEAD || git commit -m 'Added built files to verion v${newVersion}'` ]; const pushUpstreamCommands = [ '# push everything upstream', 'git push &&', 'git push --tags &&' ]; const saveCurrentBranchNameCommands = [ '# save current branch to return to it later', 'releaseBranchName=$(git symbolic-ref HEAD --short) &&' ]; const createReleaseBranchCommands = [ `echo "### checkout|create branch ${newBranchName}, set upstream to origin" &&`, `git checkout ${newBranchName} 2>/dev/null || git checkout -b ${newBranchName}`, `git branch --set-upstream-to origin/${newBranchName}`, '# when major branch does not exist on remote, then push it to origin', `git ls-remote --exit-code . origin/${newBranchName} || git push origin ${newBranchName} -u &&` ]; const pullCommands = [ '# pull the current upstream state', 'git fetch --all &&' ]; const updateReleaseBranchCommands = [ '# update major branch with changes from this release', 'git merge $releaseBranchName &&', `git tag -a v${newVersion} -m "Tag v${newVersion}"`, `git push -u --force --tags origin ${newBranchName}&&` ]; const switchToCurrentBranchCommands = [ '# go back to release branch', 'git checkout $releaseBranchName' ]; const cmd = [].concat( '############ EXECUTE THE FOLLOWING COMMANDS ################', switchPathCommands, saveCurrentBranchNameCommands, pullCurrentUpstreamCommands, changelogCommands, updatePackageJsonCommands, argv['build-command'] ? buildCommands : [], pushUpstreamCommands, createReleaseBranchCommands, pullCommands, argv['push-build'] ? pushBuildCommands : [], updateReleaseBranchCommands, switchToCurrentBranchCommands, '########### END EXECUTE THE FOLLOWING COMMANDS ##############' ).join('\n'); console.log(cmd); const child = exec(cmd, { maxBuffer: 1024 * 1000 }, (error) => { if (error) { throw error; } }); child.stderr.pipe(process.stderr); child.stdout.pipe(process.stdout);
JavaScript
0.000007
@@ -3585,17 +3585,16 @@ Add buil -d t change
2b5e4d7aa5e436fb5d89de679f0812ea9c92bdf0
Fix sexpr-wast-prototype location
bin/runWast.js
bin/runWast.js
#!/usr/bin/env node const cp = require('child_process') const fs = require('fs') const path = require('path') const Kernal = require('ewasm-kernel') const loc = path.join(process.cwd(), process.argv[2]) cp.execSync(`${__dirname}/../deps/sexpr-wasm-prototype/out/sexpr-wasm ${loc} -o ./temp.wasm`) const opsWasm = fs.readFileSync('./temp.wasm') Kernal.codeHandler(opsWasm)
JavaScript
0.000006
@@ -230,11 +230,12 @@ /../ -dep +tool s/se
7516198c4220db2ea84f26b73ce616a2cae18641
Install plugins when the server starts
packages/rotonde-core/src/index.js
packages/rotonde-core/src/index.js
import Server from 'socket.io'; import server from './server'; import { registerHandlers } from './handlers'; const httpServer = server(app => { console.log(`Rotonde listening on ${app.get('host')}:${app.get('port')}`); const io = new Server(httpServer); registerHandlers(io); });
JavaScript
0.000001
@@ -102,16 +102,60 @@ ndlers'; +%0Aimport %7B installPlugins %7D from './plugins'; %0A%0Aconst @@ -174,16 +174,22 @@ server( +async app =%3E %7B @@ -327,12 +327,94 @@ rs(io);%0A + try %7B%0A await installPlugins();%0A %7D catch (err) %7B%0A console.error(err);%0A %7D%0A %7D);%0A
3a94cf68a71debe4841e974bfb9b2dc8a4aaef60
Use different value for fund age
web/src/js/reducers/data/list.js
web/src/js/reducers/data/list.js
/** * Process list data */ import { fromJS, List as list, Map as map } from 'immutable'; import { YMD } from '../../misc/date'; import { LIST_COLS_SHORT, LIST_COLS_PAGES } from '../../misc/const'; import { TransactionsList } from '../../misc/data'; import { formatAge } from '../../misc/format'; import { getGainComparisons, addPriceHistory, getFormattedHistory, getXRange } from './funds'; /** * process list page data response * @param {Record} reduction: app state * @param {integer} pageIndex: page index * @param {object} raw: api JSON data * @returns {Record} modified reduction */ export const processPageDataList = (reduction, pageIndex, raw) => { const numRows = raw.data.length; const numCols = LIST_COLS_PAGES[pageIndex].length; const total = raw.total; const data = map({ numRows, numCols, total }); const rows = list(raw.data.map(item => { return map({ id: item.I, cols: list(LIST_COLS_SHORT[pageIndex].map(col => { if (col === 'd') { return new YMD(item[col]); } return item[col]; })) }); })); return reduction.setIn(['appState', 'pages', pageIndex], map({ data, rows })); }; export const getFundsCachedValue = (reduction, pageIndex, history) => { const ageText = formatAge( new Date().getTime() / 1000 - history.get('totalTime') - history.get('startTime')); const lastItem = history.get('history').last(); const value = lastItem.get(1).map((price, key) => { const transactions = history.getIn(['funds', 'transactions', key]); const transactionsList = new TransactionsList(transactions, false, true); const units = transactionsList.getTotalUnits(); return units * price; }).reduce((a, b) => a + b, 0); return reduction.setIn(['appState', 'other', 'fundsCachedValue'], map({ ageText, value })); }; export const processPageDataFunds = (reduction, pageIndex, data) => { let newReduction = processPageDataList(reduction, pageIndex, data); const history = fromJS(data.history); const transactionsKey = LIST_COLS_PAGES[pageIndex].indexOf('transactions'); const rows = getGainComparisons(newReduction.getIn( ['appState', 'pages', pageIndex, 'rows'] ).map(row => { const transactionsJson = row.getIn(['cols', transactionsKey]); const transactions = new TransactionsList(transactionsJson); return addPriceHistory(pageIndex, row, history, transactions) .setIn(['cols', transactionsKey], transactions) .set('historyPopout', false); })); const period = reduction.getIn(['appState', 'other', 'graphFunds', 'period']); newReduction = getFundsCachedValue( newReduction .setIn(['appState', 'pages', pageIndex, 'rows'], rows) .setIn(['appState', 'other', 'fundHistoryCache', period], { data: { data: data.history } }), pageIndex, history ); return getFormattedHistory( getXRange(newReduction, data.history.startTime), pageIndex, history); };
JavaScript
0.000006
@@ -1273,166 +1273,185 @@ nst -ageText = formatAge(%0A new Date().getTime() / 1000 - history.get('totalTime') - history.get('startTime'));%0A const lastItem = history.get('history').last(); +lastItem = history.get('history').last();%0A%0A const valueTime = history.get('startTime') + lastItem.get(0);%0A const ageText = formatAge(new Date().getTime() / 1000 - valueTime);%0A %0A c
7bcb9fa0b9380446ab0ef034cd6501eb9b25c41b
Add contributors link to menu
web/src/server/components/app.js
web/src/server/components/app.js
import React, { Component, PropTypes } from 'react' import { connect } from 'react-redux' import { Link } from 'react-router' import classNames from 'classnames' import getMuiTheme from 'material-ui/styles/getMuiTheme' import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider' import AppBar from 'material-ui/AppBar' import {Toolbar, ToolbarGroup, ToolbarSeparator, ToolbarTitle} from 'material-ui/Toolbar' import IconButton from 'material-ui/IconButton' import IconMenu from 'material-ui/IconMenu' import MenuItem from 'material-ui/MenuItem' import FontIcon from 'material-ui/FontIcon' import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert' import NavigationClose from 'material-ui/svg-icons/navigation/close' import ActionHome from 'material-ui/svg-icons/action/home' import { deepOrange700 } from 'material-ui/styles/colors' import HomePage from './home-page' import ProjectsPage from './projects-page' import AuthorsPage from './authors-page' import OrganizationsPage from './organizations-page' export default class App extends Component { constructor(props){ super(props) this.state = { showPage: 'home' } } handlePageClick(showPage) { this.setState({showPage}) } render() { if (!process.browser) return null console.info("App:render") const App = () => { return ( <div id="opendaylight-spectrometer"> <Toolbar className="toolbar"> <ToolbarGroup firstChild={true}> {process.env.NODE_ENV !== 'test' && <img src={require('../../../assets/images/opendaylight.png')} className="logo"/>} <ToolbarTitle text="OpenDaylight Spectrometer" className="toolbar-title" /> </ToolbarGroup> <ToolbarGroup> <FontIcon className="material-icons" title="Home" onClick={this.handlePageClick.bind(this, 'home')}>home</FontIcon> <FontIcon className="material-icons" title="Projects" onClick={this.handlePageClick.bind(this, 'projects')}>folder</FontIcon> <FontIcon className="material-icons" title="Organizations" onClick={this.handlePageClick.bind(this, 'organizations')}>business</FontIcon> {/*<FontIcon className="material-icons" title="Authors" onClick={this.handlePageClick.bind(this, 'authors')}>account_circle</FontIcon>*/} <IconMenu iconButtonElement={<FontIcon className="material-icons more-menu-icon">more_vert</FontIcon>} anchorOrigin={{horizontal: 'left', vertical: 'top'}} targetOrigin={{horizontal: 'left', vertical: 'top'}}> <MenuItem primaryText="Help" linkButton={true} href="http://opendaylight-spectrometer.readthedocs.io/" target="_blank"/> </IconMenu> </ToolbarGroup> </Toolbar> {this.state.showPage === 'home' && <HomePage />} {this.state.showPage === 'projects' && <ProjectsPage />} {this.state.showPage === 'authors' && <AuthorsPage />} {this.state.showPage === 'organizations' && <OrganizationsPage />} </div> ) } return ( <MuiThemeProvider muiTheme={getMuiTheme()}> {App()} </MuiThemeProvider> ) } }
JavaScript
0
@@ -1873,32 +1873,175 @@ home%3C/FontIcon%3E%0A + %3CFontIcon className=%22material-icons%22 title=%22Contributors%22 onClick=%7Bthis.handlePageClick.bind(this, 'authors')%7D%3Epeople%3C/FontIcon%3E%0A %3CF
062e4fd62c14831519691cc63785343642e51d3c
fix typo
yui_modules/request-cache.js
yui_modules/request-cache.js
/*jslint nomen: true, indent: 4*/ /* * Copyright (c) 2013 Yahoo! Inc. All rights reserved. */ YUI.add('request-cache', function (Y, NAME) { 'use strict'; var originalDispatcher = Y.mojito.Dispatcher, OriginalActionContext = Y.mojito.ActionContext, RequestCacheDispatcher = function () { this.dispatch = function (command, adapter) { var cache, cachedResource, newCommand, freshInstance = command.instance; // Build cache if it doesn't exist. adapter.req.globals = adapter.req.globals || {}; if (!adapter.req.globals['request-cache']) { adapter.req.globals['request-cache'] = { addons: {}, mojits: { byBase: {}, byType: {} } }; } // Retrieve the cache and try to get a corresponding cached resource. cache = adapter.req.globals['request-cache']; cachedResource = (freshInstance.base && cache.mojits.byBase[freshInstance.base]) || (freshInstance.type && cache.mojits.byType[freshInstance.type]); // If the is a cached resource, dispatch with that. if (cachedResource) { // Merge the cached command and the fresh command newCommand = Y.merge(cachedResource.actionContext.command, command); // That was brutal - the cached command had properties that we wanted // but they got overwritten by smaller objects from the fresh, unexpanded command. // But we can' use Y.mix with the more delicate (recursive) merging because // the command may contain circular references. So now we need to cherry-pick. // // We need to mix-in the expanded instance from the cache without overwriting // the properties from the fresh command.instance. // Here again we can't use merge because of circular references. Y.mix(newCommand.instance, cachedResource.actionContext.command.instance); // So we didn't overwite the instance.config, but the cached instance bears // some config that we want to retain, but we don't overwite to give // priority to the fresh config. // We're assuming there isn't any circular references here, so we merge. Y.mix(newCommand.instance.config, cachedResource.actionContext.command.instance.config, false, null, 0, true); // The cached AC gets the new command. cachedResource.actionContext.command = newCommand; // Instantiate again the addons that need to be refreshed Y.Array.each(['config', 'params'], function (addonName) { var addonInstance, AddonConstuct = Y.mojito.addons.ac[addonName]; if (AddonConstuct) { addonInstance = new AddonConstuct(newCommand, adapter, cachedResource.actionContext); if (addonInstance.namespace && cachedResource.actionContext[addonInstance.namespace]) { cachedResource.actionContext[addonInstance.namespace] = addonInstance; if (Y.Lang.isFunction(addonInstance.setStore)) { addonInstance.setStore(cachedResource.store); } } } }); // The adapter and its callbacks need to be refreshed cachedResource.actionContext._adapter = adapter; // @see: ActionContext constructor // TODO: handle __call // TODO: handle staticAppConfig.actionTimeout if (Y.Lang.isFunction(cachedResource.controller[newCommand.action])) { cachedResource.controller[newCommand.action](cachedResource.actionContext); } } else { // Expands the command.instance and creates a new AC // which in turn instanciates all the addons and calls the controller originalDispatcher.dispatch.apply(this, arguments); } }; }, ExpandedResource = function (options) { this.actionContext = options.actionContext; this.controller = options.controller; this.store = options.store; }, /** * A superclass for mojito's ActionContext * @param {Object} options.controller * @param {Object} options.command * @param {Object} options.store * @param {Object} options.adapter * @param {Object} options.dispatcher */ RequestCacheActionContext = function (options) { var newExpandedResource = new ExpandedResource({ actionContext: this, controller: options.controller }), instance = options.command.instance, cache = options.adapter.req.globals['request-cache']; // Save the references in either byBase or byType if (instance.base) { cache.mojits.byBase[instance.base] = newExpandedResource; } else if (instance.type) { cache.mojits.byType[instance.type] = newExpandedResource; } // Execute the original constructor: addons + controller call OriginalActionContext.apply(this, arguments); }; RequestCacheDispatcher.prototype = originalDispatcher; RequestCacheActionContext.prototype = OriginalActionContext.prototype; /** * A "superinstance" of mojito's Dispatcher * @type {Object} */ Y.mojito.Dispatcher = new RequestCacheDispatcher(); Y.mojito.ActionContext = RequestCacheActionContext; }, '0.1.0', { requires: [ 'mojito-dispatcher', 'mojito-action-context' ] });
JavaScript
0.999991
@@ -1340,16 +1340,18 @@ / If the +re is a ca
713757d3949bd8df608a2de17d841d4d71ff2821
Update 2G profile to match WPT (#37)
bin/index.js
bin/index.js
#!/usr/bin/env node 'use strict'; const minimist = require('minimist'); const throttler = require('../lib/'); const packageInfo = require('../package'); const defaultUp = 330; const defaultDown = 780; const defaultRtt = 200; const profiles = { '3g': { down: 1600, up: 768, rtt: 150 }, '3gfast': { down: 1600, up: 768, rtt: 75 }, '3gslow': { down: 400, up: 400, rtt: 200 }, '2g': { down: 35, up: 32, rtt: 650 }, cable: { down: 5000, up: 1000, rtt: 14 }, dsl: { down: 1500, up: 384, rtt: 25 }, '3gem': { down: 400, up: 400, rtt: 200 }, '4g': { down: 9000, up: 9000, rtt: 85 }, lte: { down: 12000, up: 12000, rtt: 35 }, edge: { down: 240, up: 200, rtt: 420 }, dial: { down: 49, up: 30, rtt: 60 }, fois: { down: 20000, up: 5000, rtt: 2 } }; const argv = minimist(process.argv.slice(2), { boolean: ['stop', 'localhost'] }); if (argv.help || argv._[0] === 'help') { console.log(' Set the connectivity using the throttler (pfctl/tc)'); console.log(' Usage: throttler [options]'); console.log( ' If you run in Docker throttler will only work on a Linux host' ); console.log(' In Docker make sure to run: sudo modprobe ifb numifbs=1'); console.log(' And run your container with --cap-add=NET_ADMIN\n'); console.log(' Options:'); console.log(' --stop Remove all settings'); console.log(' --up Upload in Kbit/s '); console.log(' --down Download Kbit/s'); console.log(' --rtt RTT in ms'); console.log( ' --profile Premade profiles, set to one of the following' ); Object.keys(profiles).forEach(function(profile) { console.log( ' ' + profile + ': ' + 'up:' + profiles[profile].up + ' down:' + profiles[profile].down + ' rtt:' + profiles[profile].rtt ); }); } else if (argv.version) { console.log(`${packageInfo.version}`); } else { if (argv.stop || argv._[0] === 'stop') { const options = { localhost: argv.localhost }; throttler .stop(options) .then(() => console.log('Stopped throttler')) .catch(() => console.log('No throttler to stop')); } else { let options; if (argv.profile in profiles || argv._[0] in profiles) { options = profiles[argv.profile || argv._[0]]; console.log('Using profile ' + (argv.profile ? argv.profile : argv._[0])); } else { console.log('Using default profile'); options = { up: argv.up || defaultUp, down: argv.down || defaultDown, rtt: argv.rtt || defaultRtt, localhost: argv.localhost }; } throttler.start(options).then(() => { if (options.localhost) { console.log(`Started throttler on localhost RTT:${options.rtt}ms `); } else { console.log( `Started throttler: Down:${options.down}kbit/s Up:${options.up}kbit/s RTT:${options.rtt}ms ` ); } }); } }
JavaScript
0
@@ -437,18 +437,19 @@ down: -35 +280 ,%0A up @@ -454,10 +454,11 @@ up: -3 2 +56 ,%0A @@ -468,10 +468,10 @@ tt: -65 +40 0%0A
feef00606e562935f14535ffd8a6edfa9fe11902
Add strict option to yargs
bin/index.js
bin/index.js
#!/usr/bin/env node var updateNotifier = require('update-notifier') var yargs = require('yargs') var h = require('../lib/h') var pkg = require('../package.json') updateNotifier({pkg: pkg}).notify() var yargs = yargs .usage('$0 [opts] -- <command>') .help('help').alias('help', 'h') .version(pkg.version, 'version').alias('version', 'v') .options({ name: { alias: 'n', describe: 'Set server name' } }) .options({ stop: { describe: 'Stop minihost' } }) .example('~/express$ $0 -- nodemon', 'http://express.127.0.0.1.xip.io:2000') .example('~/express$ $0 -n app -- nodemon', 'http://app.127.0.0.1.xip.io:2000') .example(' ~/static$ $0 -- serve -p PORT', 'http://static.127.0.0.1.xip.io:2000') .example(' ~/front$ $0 -- gulp server', 'http://front.127.0.0.1.xip.io:2000') .epilog('To list running servers, go to http://localhost:2000') var argv = yargs.argv // --stop if (argv.stop) return h.stop(function (err) { if (err) return console.error('minihost is not running') console.log('Successfully stopped minihost') }) // [opts] -- <command> if (argv._.length === 0) return yargs.showHelp() h.run(argv, function (err) { if (err) throw err })
JavaScript
0.000014
@@ -211,16 +211,28 @@ = yargs%0A + .strict()%0A .usage @@ -709,12 +709,14 @@ -p +%5B PORT +%5D ', '
edbe2ea2e8f3c24ebaff4e336ed10e769ccdeeef
Remove unused express var.
bin/query.js
bin/query.js
#!/usr/bin/env node var program = require('commander'), express = require('express'), exec = require('child_process').exec, AuthApp = require('../lib/ManualAuthApp'), debug = require('debug')('queryBin'), secrets = require('../client_secrets'), query = require('./tasks-for-owner-example'); var fs = require('fs'), Q = require('q'), serverBaseUri = secrets.web.server_base_uri, request = require('superagent'); program .version('0.0.1') .option('-c, --count [number]', 'specify how many names to emit. default 1', '1') .parse(process.argv); var app = new AuthApp(), url = app.url(), tokenPromise = app.tokenPromise(), accessTokenDfd = Q.defer(), accessTokenPromise = accessTokenDfd.promise, refreshTokenDfd = Q.defer(), refreshTokenPromise = refreshTokenDfd.promise; function storeTokens(tokens) { var accessToken = tokens.access_token, refreshToken = tokens.refresh_token; debug('storing tokens'); fs.writeFileSync('.tokens', JSON.stringify({accessToken: accessToken, refreshToken: refreshToken})); } try { var tokens = JSON.parse(fs.readFileSync('.tokens')); if (tokens && tokens.refreshToken) { refreshTokenDfd.resolve(tokens.refreshToken); } } catch (err) {} if (refreshTokenPromise.isPending()) { debug("opening web page", url); var browserProcess = exec('open ' + url, function (error, stdout, stderr) { if (error !== null) { debug('error', error); } }); tokenPromise.then(function (token) { var accessToken = token.access_token, refreshToken = token.refresh_token; debug('got a token', token); fs.writeFileSync('.tokens', JSON.stringify({accessToken: accessToken, refreshToken: refreshToken})); accessTokenDfd.resolve(accessToken); refreshTokenDfd.resolve(refreshToken); }); } else { refreshTokenPromise.then(function resolved(refreshToken) { var tokensPromise = app.hitTokenUri({refreshToken: refreshToken}); tokensPromise.then(function resolved(tokens) { debug('successfully refreshed'); storeTokens(tokens); accessTokenDfd.resolve(tokens.access_token); }, function rejected(err) { accessTokenDfd.reject('error refreshing for new access token' + err); }); }); } Q.all([accessTokenPromise, refreshTokenPromise]).spread(function (accessToken, refreshToken) { debug('making a test request with bearer token'/*, accessToken*/); debug('query', query); request .get(serverBaseUri + '/query.v1') .set('Authorization', 'Bearer ' + accessToken) .send(query) .end(function (res) { if (res.ok) { debug('successful request!', JSON.stringify(res.body)); } else { debug("failed to get data", res.text); } }); });
JavaScript
0
@@ -54,42 +54,8 @@ '),%0A - express = require('express'),%0A
668b1f5787faf2370f1ddb8f7e0d2f37a3247fde
Fix hound issue
src/deep-cache/test/Driver/S3FSDriver.spec.js
src/deep-cache/test/Driver/S3FSDriver.spec.js
'use strict'; import chai from 'chai'; import sinon from 'sinon'; import sinonChai from 'sinon-chai'; import {S3FSDriver} from '../../lib.compiled/Driver/S3FSDriver'; import {S3FSDriverMock} from './../Mocks/S3FSDriverMock'; import FSMock from './../Mocks/FSMock'; import {ContainerAware} from '../../node_modules/deep-kernel/lib.compiled/ContainerAware'; chai.use(sinonChai); suite('Driver/S3FSDriver', () => { let containerAware = new ContainerAware(); let s3FsDriver = new S3FSDriverMock(containerAware); let key = 'testKey'; let fsMock = FSMock(); test('Class S3FSDriver exists in Driver/S3FSDriver', () => { chai.expect(S3FSDriver).to.be.an('function'); }); test('Check constructor', () => { chai.expect(s3FsDriver, 'is an instance of S3FSDriver').to.be.an.instanceOf(S3FSDriverMock); chai.expect( s3FsDriver._containerAware, 'is an instance of ContainerAware' ).to.be.an.instanceOf(ContainerAware); }); test('Check _fs getter', () => { let actualResult = s3FsDriver._fs; chai.expect(actualResult).to.be.an('object') }); test('Check _get returns error in callback for readFile', () => { let spyCallback = sinon.spy(); fsMock.setMode(fsMock.constructor.FAILURE_MODE, ['readFile']); let actualResult = s3FsDriver._get(key, spyCallback); chai.expect(actualResult).to.be.equal(undefined); chai.expect(spyCallback).to.have.been.calledWithExactly(fsMock.constructor.ERROR, null); }); test('Check _get executes with exception and returns callback(null, null)', () => { let spyCallback = sinon.spy(); fsMock.setMode(fsMock.constructor.EXCEPTION_MODE, ['readFile']); let actualResult = s3FsDriver._get(key, spyCallback); chai.expect(actualResult).to.be.equal(undefined); chai.expect(spyCallback).to.have.been.calledWithExactly(null, null); }); test('Check _get returns callback(null, value)', () => { let spyCallback = sinon.spy(); fsMock.setMode(fsMock.constructor.DATA_MODE, ['readFile']); let actualResult = s3FsDriver._get(key, spyCallback); chai.expect(actualResult).to.be.equal(undefined); chai.expect(spyCallback).to.have.been.calledWithExactly(null, 'request successfully sent'); }); test('Check _get returns callback(null, null)', () => { let spyCallback = sinon.spy(); fsMock.setMode(fsMock.constructor.UPDATE_MODE, ['readFile']); let actualResult = s3FsDriver._get(key, spyCallback); chai.expect(actualResult).to.be.equal(undefined); chai.expect(spyCallback).to.have.been.calledWithExactly(null, null); }); test('Check _has returns error in callback(error, false)', () => { let spyCallback = sinon.spy(); fsMock.setMode(fsMock.constructor.FAILURE_MODE, ['readFile']); let actualResult = s3FsDriver._has(key, spyCallback); chai.expect(actualResult).to.be.equal(undefined); chai.expect(spyCallback).to.have.been.calledWithExactly(fsMock.constructor.ERROR, false); }); test('Check _invalidate executes callback(null, true) timeout <= 0', () => { let spyCallback = sinon.spy(); fsMock.setMode(fsMock.constructor.DATA_MODE, ['unlink']); let actualResult = s3FsDriver._invalidate(key, 0, spyCallback); chai.expect(actualResult).to.be.equal(undefined); chai.expect(spyCallback).to.have.been.calledWithExactly(null, true); }); test('Check _invalidate executes callback(error, false) for timeout <= 0', () => { let spyCallback = sinon.spy(); fsMock.setMode(fsMock.constructor.FAILURE_MODE, ['unlink']); let actualResult = s3FsDriver._invalidate(key, 0, spyCallback); chai.expect(actualResult).to.be.equal(undefined); chai.expect(spyCallback).to.have.been.calledWithExactly(fsMock.constructor.ERROR, false); }); test('Check _invalidate executes callback(error, null) for !timeout <= 0', () => { let spyCallback = sinon.spy(); fsMock.setMode(fsMock.constructor.FAILURE_MODE, ['readFile']); let actualResult = s3FsDriver._invalidate(key, 1, spyCallback); chai.expect(actualResult).to.be.equal(undefined); chai.expect(spyCallback).to.have.been.calledWithExactly(fsMock.constructor.ERROR, null); }); test('Check _invalidate executes callback(null, true) for !timeout <= 0', () => { let spyCallback = sinon.spy(); fsMock.setMode(fsMock.constructor.DATA_MODE, ['readFile']); fsMock.setMode(fsMock.constructor.DATA_MODE, ['unlink']); let actualResult = s3FsDriver._invalidate(key, 1, spyCallback); chai.expect(actualResult).to.be.equal(undefined); chai.expect(spyCallback).to.have.been.calledWithExactly(null, true); }); });
JavaScript
0.000001
@@ -545,16 +545,20 @@ fsMock = + new FSMock(
5dc8ff025625e13fc107b981180f88d370a5d241
change path prefix from ./ to ../chat/ in chat component
chat/ccm.chat.js
chat/ccm.chat.js
/** * @overview <i>ccm</i> component for simple chats * @author André Kless <[email protected]> 2016 * @license The MIT License (MIT) */ ccm.component( /** @lends ccm.components.chat */ { /*-------------------------------------------- public component members --------------------------------------------*/ /** * @summary component name * @type {ccm.types.name} */ name: 'chat', /** * @summary default instance configuration * @type {ccm.components.chat.types.config} */ config: { html: [ ccm.store, { local: './templates.json' } ], key: 'test', store: [ ccm.store, { url: 'ws://ccm2.inf.h-brs.de/index.js', store: 'chat' } ], style: [ ccm.load, './style.css' ], user: [ ccm.instance, 'https://kaul.inf.h-brs.de/ccm/components/user2.js' ] }, /*-------------------------------------------- public component classes --------------------------------------------*/ /** * @summary constructor for creating <i>ccm</i> instances out of this component * @class */ Instance: function () { /*------------------------------------- private and public instance members --------------------------------------*/ /** * @summary own context * @private */ var self = this; /*------------------------------------------- public instance methods --------------------------------------------*/ /** * @summary initialize <i>ccm</i> instance * @description * Called one-time when this <i>ccm</i> instance is created, all dependencies are solved and before dependent <i>ccm</i> components, instances and datastores are initialized. * This method will be removed by <i>ccm</i> after the one-time call. * @param {function} callback - callback when this instance is initialized */ this.init = function ( callback ) { // listen to change event of ccm realtime datastore => update own content self.store.onChange = function () { self.render(); }; // perform callback callback(); }; /** * @summary render content in own website area * @param {function} [callback] - callback when content is rendered */ this.render = function ( callback ) { /** * website area for own content * @type {ccm.types.element} */ var element = ccm.helper.element( self ); // get dataset for rendering self.store.get( self.key, function ( dataset ) { // dataset not exists? => create new dataset with given key if ( dataset === null ) self.store.set( { key: self.key, messages: [] }, proceed ); else proceed( dataset ); function proceed( dataset ) { // render main html structure element.html( ccm.helper.html( self.html.get( 'main' ) ) ); /** * website area for already existing messages * @type {ccm.types.element} */ var messages_div = ccm.helper.find( self, '.messages' ); // iterate over message datasets for ( var i = 0; i < dataset.messages.length; i++ ) { /** * message dataset * @type {ccm.components.chat.types.message} */ var message = dataset.messages[ i ]; // render html structure for a given message messages_div.append( ccm.helper.html( self.html.get( 'message' ), { name: ccm.helper.val( message.user ), text: ccm.helper.val( message.text ) } ) ); } // render input field for a new message messages_div.append( ccm.helper.html( self.html.get( 'input' ), { onsubmit: function () { /** * submitted massage * @type {string} */ var value = ccm.helper.val( ccm.helper.find( self, 'input' ).val() ).trim(); // message is empty? => abort if ( value === '' ) return; // login user if not logged in self.user.login( function () { // add submitted massage in dataset for rendering dataset.messages.push( { user: self.user.data().key, text: value } ); // update dataset for rendering in datastore self.store.set( dataset, function () { self.render(); } ); } ); // prevent page reload return false; } } ) ); // perform callback if ( callback ) callback(); } } ); }; } /*------------------------------------------------ type definitions ------------------------------------------------*/ /** * @namespace ccm.components.chat */ /** * @namespace ccm.components.chat.types */ /** * @summary <i>ccm</i> instance configuration * @typedef {ccm.types.config} ccm.components.chat.types.config * @property {ccm.types.element} element - <i>ccm</i> instance website area * @property {ccm.types.dependency} html - <i>ccm</i> datastore for html templates * @property {ccm.types.url} style - URL to a css file which contains the styles for own website area * @property {string} classes - html classes for own website area * @property {ccm.types.dependency} store - <i>ccm</i> datastore that contains the [dataset for rendering]{@link ccm.components.chat.types.dataset} * @property {ccm.types.key} key - key of [dataset for rendering]{@link ccm.components.chat.types.dataset} * @property {ccm.types.dependency} user - <i>ccm</i> instance for user authentification * @example { * element: jQuery( 'body' ), * html: [ ccm.store, { local: './templates.json' } ], * style: [ ccm.load, './style.css' ], * classes: 'ccm-chat', * store: [ ccm.store, { url: 'ws://ccm2.inf.h-brs.de/index.js', store: 'chat' } ], * key: 'test', * user: [ ccm.instance, 'https://kaul.inf.h-brs.de/ccm/components/user2.js' ] * } */ /** * @summary dataset for rendering * @typedef {ccm.types.dataset} ccm.components.chat.types.dataset * @property {ccm.types.key} key - dataset key * @property {ccm.components.chat.types.message[]} messages - already existing [message dataset]{@link ccm.components.chat.types.message}s * @example { * key: 'test', * messages: [ * { * text: 'Hello, World!', * user: 'akless' * }, * { * text: 'My second message.', * user: 'akless' * } * ] * } */ /** * @summary message dataset * @typedef {ccm.types.dataset} ccm.components.chat.types.message * @property {string} text - message text * @property {string} user - username of creator * @example { * text: 'Hello, World!', * user: 'akless' * } */ /** * @external ccm.types * @see {@link http://akless.github.io/ccm-developer/api/ccm/ccm.types.html} */ } );
JavaScript
0.000001
@@ -539,32 +539,38 @@ ore, %7B local: '. +./chat /templates.json' @@ -696,32 +696,38 @@ : %5B ccm.load, '. +./chat /style.css' %5D,%0A
3660bd932cf69cb99369fd036e9bf2beb3e1e159
disable sw for now
docs/src/index.js
docs/src/index.js
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { BrowserRouter } from 'react-router-dom'; import { createStore } from 'redux' import { loadComponents } from 'loadable-components' import './index.css'; import App from './App'; import reducer from './reducers'; import registerServiceWorker from './registerServiceWorker'; // Grab the state from a global variable injected into the server-generated HTML const preloadedState = window.__PRELOADED_STATE__ // Allow the passed state to be garbage-collected delete window.__PRELOADED_STATE__ const store = createStore(reducer, preloadedState) loadComponents().then(() => { ReactDOM.hydrate( <Provider store={store}> <BrowserRouter> <App /> </BrowserRouter> </Provider> , document.getElementById('root')); registerServiceWorker(); });
JavaScript
0
@@ -311,24 +311,27 @@ /reducers';%0A +// import regis @@ -844,16 +844,19 @@ ot'));%0A + // registe
73f757dba57e5ababf151d5aa2bdf454b89634ed
Remove waste rows
client/index.es6
client/index.es6
import Backbone from 'backbone' import _ from 'lodash' import React from 'react' import App from 'client/app' window.addEventListener('load', function(){ var app = new App(); window._app = app; var container = window.document.querySelector('#js-game-container'); app.renderTo(container); app.start().then(() => { console.log('Started app at', new Date()); }); });
JavaScript
0.000003
@@ -1,59 +1,4 @@ -import Backbone from 'backbone'%0Aimport _ from 'lodash'%0A impo
2946e89b70a87781e3cc67618063e5618cc76874
add exit
tools/createSchemas.js
tools/createSchemas.js
var redis = require('../libs/redis-client'); var approvedEnvironment = require('../libs/schemas/validator').approvedEnvironment; var models = require('../models'); var fs = require('fs'); var log = require('czagenda-log').from(__filename); var SCHEMAS = [{ "name" : "base", "final" : false, "file" : "base-abstract.json" }, { "name" : "who", "final" : false, "file" : "who-abstract.json" }, { "name" : "who", "final" : true, "file" : "who.json" }, { "name" : "geo", "final" : false, "file" : "geo-abstract.json" }, { "name" : "geo", "final" : true, "file" : "geo.json" }, { "name" : "localization", "final" : false, "file" : "localization-abstract.json" }, { "name" : "localization", "final" : true, "file" : "localization.json" }, { "name" : "event", "final" : false, "file" : "event-abstract.json" }, { "name" : "event", "final" : true, "file" : "event.json" }, { "name" : "entity", "final" : false, "file" : "entity-abstract.json" }, { "name" : "organization", "final" : false, "file" : "organization-abstract.json" }, { "name" : "organization", "final" : true, "file" : "organization.json" }, { "name" : "person", "final" : false, "file" : "person-abstract.json" }, { "name" : "person", "final" : true, "file" : "person.json" },{ "name" : "event-europe", "final" : false, "file" : "event-europe-abstract.json" },{ "name" : "event-europe", "final" : true, "file" : "event-europe.json" }] var createSchema = function() { var data = SCHEMAS.shift(); log.notice("Try to create " + data.name); var schema = new models.Schema(); schema.name = data.name; schema.author = "/user/jh.pinson"; schema['final'] = data['final']; schema.status = 'APPROVED'; schema.schema = JSON.parse(fs.readFileSync("./schemas/" + data.file, 'utf8')); schema.save(function(err, obj) { if(err === null || err instanceof models.errors.ObjectAlreadyExists) { if( err instanceof models.errors.ObjectAlreadyExists) { console.log('ObjectAlreadyExists', data.name); } else { log.notice("Succesfully created " + data.name, obj.id); } if(SCHEMAS.length > 0) { setTimeout(createSchema, 3000); } else { log.notice("All done"); } } else { if( err instanceof models.errors.ValidationError) { console.log(obj.validationErrors, data.name); } else { console.log('Internal error', data.name) } } }); } approvedEnvironment.load(function(err, success) { createSchema(); })
JavaScript
0.000007
@@ -2200,16 +2200,52 @@ done%22);%0A +%09%09%09%09setTimeout(process.exit, 1000);%0A %09%09%09%7D%0A%0A%09%09
833121e7bff1f2a2950386982cf76e12c06e3dd1
Configure prod webpack for dashboard
webpack/dashboard/webpack.prod.config.js
webpack/dashboard/webpack.prod.config.js
const webpack = require('webpack'); const {resolve} = require('path'); const PACKAGE = require('../../package.json'); const version = PACKAGE.version; const isVendor = (module, count) => { const userRequest = module.userRequest; return userRequest && userRequest.indexOf('node_modules') >= 0; }; const entryPoints = { user_feed_new: resolve(__dirname, '../../', 'lib/assets/core/javascripts/dashboard/user-feed.js') }; module.exports = env => { return { entry: entryPoints, output: { filename: `${version}/javascripts/[name].js`, path: resolve(__dirname, '../../', 'public/assets') }, devtool: 'source-map', plugins: Object.keys(entryPoints) .map(entry => new webpack.optimize.CommonsChunkPlugin({ name: `${entry}_vendor`, chunks: [entry], minChunks: isVendor })) .concat([ // Extract common chuncks from the 3 vendor files new webpack.optimize.CommonsChunkPlugin({ name: 'common_dashboard', chunks: Object.keys(entryPoints).map(n => `${n}_vendor`), minChunks: (module, count) => { return count >= Object.keys(entryPoints).length && isVendor(module); } }), // Extract common chuncks from the 3 entry points new webpack.optimize.CommonsChunkPlugin({ children: true, minChunks: Object.keys(entryPoints).length }), new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery' }), new webpack.DefinePlugin({ __IN_DEV__: JSON.stringify(false), __ENV__: JSON.stringify('prod') }), // Minify new webpack.optimize.UglifyJsPlugin({ sourceMap: true, beautify: false, mangle: { screw_ie8: true, keep_fnames: true }, compress: { screw_ie8: true }, comments: false, output: { ascii_only: true } }) ]), module: { rules: [ ] }, node: { fs: 'empty' // This fixes the error Module not found: Error: Can't resolve 'fs' }, stats: { warnings: false } }; };
JavaScript
0
@@ -2092,16 +2092,1252 @@ ules: %5B%0A + %7B%0A test: /%5C.js$/,%0A loader: 'shim-loader',%0A include: %5B%0A resolve(__dirname, '../../', 'node_modules/cartodb.js')%0A %5D,%0A options: %7B%0A shim: %7B%0A 'wax.cartodb.js': %7B%0A exports: 'wax'%0A %7D,%0A 'html-css-sanitizer': %7B%0A exports: 'html'%0A %7D,%0A 'lzma': %7B%0A exports: 'LZMA'%0A %7D%0A %7D%0A %7D%0A %7D,%0A %7B%0A test: /%5C.tpl$/,%0A use: 'tpl-loader',%0A include: %5B%0A resolve(__dirname, '../../', 'lib/assets/core/javascripts/cartodb3'),%0A resolve(__dirname, '../../', 'lib/assets/core/javascripts/dashboard'),%0A resolve(__dirname, '../../', 'node_modules/cartodb.js')%0A %5D%0A %7D,%0A %7B%0A test: /%5C.js$/,%0A loader: 'babel-loader',%0A include: %5B%0A resolve(__dirname, '../../', 'node_modules/tangram-cartocss'),%0A resolve(__dirname, '../../', 'node_modules/tangram.cartodb'),%0A resolve(__dirname, '../../', 'lib/assets/core/javascripts/dashboard')%0A %5D,%0A options: %7B%0A presets: %5B'env'%5D%0A %7D%0A %7D %0A %5D
34370a5a014a70cf5415b404868db0ee722b0d38
Update help.js / sorting
commands/help.js
commands/help.js
exports.run = (client, message, args, level) => { if (!args[0]) { const settings = message.guild ? client.settings.get(message.guild.id) : client.config.defaultSettings; const myCommands = message.guild ? client.commands.filter(cmd => client.levelCache[cmd.conf.permLevel] <= level) : client.commands.filter(cmd => cmd.conf.permLevel <= level && cmd.conf.guildOnly !== true); const commandNames = myCommands.keyArray(); const longest = commandNames.reduce((long, str) => Math.max(long, str.length), 0); let currentCategory = ""; let output = `= Command List =\n\n[Use ${settings.prefix}help <commandname> for details]\n`; const sorted = myCommands.sort((p, c) => p.help.category > c.help.category ? 1 : -1); sorted.forEach( c => { const cat = c.help.category.toProperCase(); if (currentCategory !== cat) { output += `\n== ${cat} ==\n`; currentCategory = cat; } output += `${settings.prefix}${c.help.name}${" ".repeat(longest - c.help.name.length)} :: ${c.help.description}\n`; }); message.channel.send(output, {code:"asciidoc"}); } else { let command = args[0]; if (client.commands.has(command)) { command = client.commands.get(command); if (level < client.levelCache[command.conf.permLevel]) return; message.channel.send(`= ${command.help.name} = \n${command.help.description}\nusage::${command.help.usage}`, {code:"asciidoc"}); } } }; exports.conf = { enabled: true, guildOnly: false, aliases: ["h", "halp"], permLevel: "User" }; exports.help = { name: "help", category: "System", description: "Displays all the available commands for your permission level.", usage: "help [command]" };
JavaScript
0
@@ -720,16 +720,94 @@ category +%0A ? 1 : p.help.name %3E c.help.name && p.help.category === c.help.category ? 1 : - @@ -807,16 +807,21 @@ ? 1 : -1 +%0A );%0A s
0e6f1ecff3472f9ab2e96762ecdc0375b54d0fdd
Disable display editor settings keyboard shortcut.
website/addons/wiki/static/ShareJSDoc.js
website/addons/wiki/static/ShareJSDoc.js
var activeUsers = []; var ShareJSDoc = function(viewModel, url, metadata) { // Initialize Ace and configure settings var editor = ace.edit("editor"); editor.getSession().setMode("ace/mode/markdown"); editor.getSession().setUseSoftTabs(true); // Replace tabs with spaces editor.getSession().setUseWrapMode(true); // Wraps text editor.renderer.setShowGutter(false); // Hides line number editor.setShowPrintMargin(false); // Hides print margin editor.setReadOnly(true); // Read only until initialized // Configure connection var wsUrl = 'ws://' + metadata.sharejsHost + ':' + metadata.sharejsPort; var socket = new ReconnectingWebSocket(wsUrl); var sjs = new sharejs.Connection(socket); var doc = sjs.get('docs', metadata.docId); function whenReady() { // Create a text document if one does not exist if (!doc.type) { doc.create('text'); viewModel.fetchData(function(response) { doc.attachAce(editor); editor.setValue(response.wiki_content); editor.setReadOnly(false); }); } else { doc.attachAce(editor); editor.setReadOnly(false); } } // Send user metadata function register() { socket.send(JSON.stringify(metadata)); } // Inform client of new published version $('#wiki-form').submit(function() { socket.send(JSON.stringify({ publish: true, docId: metadata.docId, content: viewModel.currentText() })); }); // Handle our custom messages separately var onmessage = socket.onmessage; socket.onmessage = function (message) { var data = JSON.parse(message.data); // Meta type is not built into sharejs; we pass it manually if (data.type === 'meta') { // Convert users object into knockout array activeUsers = []; for (var user in data.users) { var userMeta = data.users[user]; userMeta.id = user; activeUsers.push(userMeta); } viewModel.activeUsers(activeUsers); } else if (data.type === 'updatePublished') { console.log('content', data.content); viewModel.publishedText(data.content); } else if (data.type === 'lock') { editor.setReadOnly(true); $('#refresh-modal').modal({ backdrop: 'static', keyboard: false }); } else if (data.type === 'unlock') { // TODO: Wait a certain number of seconds so they can read it? location.reload(); } else { onmessage(message); } }; // This will be called on both connect and reconnect doc.on('subscribe', register); // This will be called when we have a live copy of the server's data. doc.whenReady(whenReady); // Subscribe to changes doc.subscribe(); }; module.exports = ShareJSDoc;
JavaScript
0
@@ -484,16 +484,97 @@ margin%0A + editor.commands.removeCommand('showSettingsMenu'); // Disable settings menu%0A edit
61b2864a3fb57dc05326f838fdfdf8d299834da8
fix readme
markdown-guide.js
markdown-guide.js
(function(window, document, undefined){ 'use strict'; // Helper functions function hasClass(elem, klass) { return (' ' + elem.className + ' ').indexOf(' ' + klass + ' ') > -1; } function addClass(elem, klass) { if (!hasClass(elem, klass)) elem.className = elem.className + " " + klass } function removeClass(elem, klass) { if (hasClass(elem, klass)) { elem.className = elem.className.split(klass).join("").trim(); } } // Constants and Vars var settings = { selector: ".markdown_guide", buttonType: 'button', buttonText: 'Markdown Guide', buttonClass: '', triggerFunction: defaultTriggerFunction, tableStyle: ';border:1px solid black;margin:0 auto;', tdPadding: '10px', tdBorder: '1px solid black', headings: true, italics: true, bold: true, link: true, image: true, ul: true, ol: false, blockquote: true, hardrule: true, code_spaced: true, code_accent: true, strikethrough: true, superscript: true }; var GUIDE; // Used to cache guide var BUTTON_CLASS = "markdown_guide_button"; var TABLE_DATA = { headings: {t: "#H1 Heading <br><br> . . . <br><br> #######H6 Heading", s: "<h1>H1 Heading</h1> . . . <h6>H6 Heading</h6>"}, italics: {t: "*italics*", s: "<em>italics</em>"}, bold: {t: "**bold**", s: "<strong>bold</strong>"}, link: {t: "[Google](http://google.com)", s: "<a href='http://google.com'>Google</a>"}, image: {t: "![alt-text](http://www.placehold.it/75x75)", s: "<img src='http://www.placehold.it/75x75' alt='alt-text'>"}, ul: {t: "* item 1<br>* item 2<br>&nbsp; * item 2a <br>* item 3", s: "<ul><li>item 1</li><li>item 2<ul><li>item 2a </li></ul></li><li>item 3</li></ul>"}, ol: {t: "1. item 1<br>2. item 2<br>3. item 3", s: "<ol><li>item 1</li><li>item 2</li><li>item 3</li></ol>"}, blockquote: {t: "&gt; quoted text<br>unquoted text", s: "<blockquote>quoted text</blockquote>unquoted text</td>"}, hardrule: {t: "A<br>* * *<br>B<br>- - - -<br>C<br>", s: "A<br><hr /><br>B<br><hr /><br>C"}, code_spaced: {t: "Four spaces are treated like code: <br><span style='background-color:gray;margin-left:1px;'>&nbsp;</span><span style='background-color:gray;margin-left:1px;'>&nbsp;</span><span style='background-color:gray;margin-left:1px;'>&nbsp;</span><span style='background-color:gray;margin-left:1px;'>&nbsp;</span>var x = 1;<br>", s: "<pre><code>var x = 1;</code></pre>"}, code_accent: {t: "```<br>def function <br><span style='padding-left:15px'>true</span><br>end <br>```", s: "<p><code>def function <br>&nbsp; true <br> end</code></p>"}, strikethrough: {t: "~~strikethrough~~", s: "<strike>strikethrough</strike>"}, superscript: {t: "super^script", s: "super<sup>script</sup>"} } // Functions function clickElement () { var clickItem = document.createElement(settings.buttonType); clickItem.className = settings.buttonClass + " " + BUTTON_CLASS; // Added Firefox support if (typeof clickItem.textContent !== "undefined") { clickItem.textContent = settings.buttonText; } else { clickItem.innerText = settings.buttonText; } return clickItem; } function addButtons() { [].forEach.call(settings.elems, function(item) { item.innerHTML = ""; // Clear incase of recalling method. item.appendChild(clickElement()); }); } function defaultTriggerFunction(e, guide) { window.test = e.target if (hasClass(e.target, 'active')) { removeClass(e.target, 'active'); e.target.nextElementSibling.remove(); } else { e.target.parentElement.appendChild(guide) addClass(e.target, 'active'); } } function addListeners() { var triggers = document.querySelectorAll("." + BUTTON_CLASS); [].forEach.call(triggers,function(e){e.addEventListener('click', function(e) { settings.triggerFunction(e, generateGuide().cloneNode(true)); }, false)}) } function generateGuide() { if (!GUIDE) { var table = document.createElement('table'); table.setAttribute('style', settings.tableStyle); for (var k in TABLE_DATA){ if (TABLE_DATA.hasOwnProperty(k)) { if (settings[k]) { var tr = table.insertRow(); var td = tr.insertCell(); td.innerHTML = TABLE_DATA[k].t td.style.border = settings.tdBorder; td.style.padding = settings.tdPadding; var td = tr.insertCell(); td.innerHTML = TABLE_DATA[k].s td.style.border = settings.tdBorder; td.style.padding = settings.tdPadding; } } } GUIDE = table; } return GUIDE; } // Initializer window.MarkdownGuide = function (opts) { for (var k in opts){ if (opts.hasOwnProperty(k) && settings.hasOwnProperty(k)) { settings[k] = opts[k]; } } settings.elems = document.querySelectorAll(settings.selector); addButtons(); addListeners(); }; // jQuery support if (typeof window.jQuery == "function") { $.fn.markdownGuide = function (opts) { MarkdownGuide(opts); } }; })(this, document);
JavaScript
0.000001
@@ -659,16 +659,36 @@ nction,%0A + tableClass: '',%0A tabl @@ -1077,17 +1077,16 @@ e%0A %7D;%0A%0A -%0A var GU @@ -4102,24 +4102,68 @@ t('table');%0A + addClass(table, settings.tableClass);%0A table.
82b225804fd3c0f0d87629ebc0005d57a6462f9c
Exit if conjure.test() not called
bootstrap.js
bootstrap.js
/** * Allow test scripts to simply define a module.exports function that receives * a pre-baked conjure instance. * * Also allow custom `--bootstrap <file>` modules to modify that instance * and pass custom arguments to the test module. */ var cli = require('casper').create().cli; var rootDir = cli.raw.get('rootdir'); var testDir = cli.raw.get('testdir'); var conjure = require(rootDir + '/dist/conjure').create(require); conjure.set('cli', cli); var testFile = cli.raw.get('testfile'); var testModuleArgs = [conjure]; var customBootFile = cli.raw.get('bootstrap'); if (customBootFile) { if (/^[^/]/.test(customBootFile)) { // Resolve 'relPath.js' and './relPath.js' customBootFile = rootDir + '/' + customBootFile; } // Append any defined value to the argument set passed to the test script. // Array contents will be appended individually. var customArgs = require(customBootFile)( conjure, testFile.replace(rootDir + '/' + testDir + '/', '') ); if (typeof customArgs !== 'undefined') { testModuleArgs = testModuleArgs.concat(customArgs); } } require(testFile).apply(null, testModuleArgs);
JavaScript
0
@@ -245,18 +245,21 @@ /%0A%0Avar c -li +asper = requi @@ -279,16 +279,34 @@ create() +;%0Avar cli = casper .cli;%0Ava @@ -1147,12 +1147,236 @@ oduleArgs);%0A +%0Aif (!conjure.isRunning()) %7B // Prevent empty tests from timing out.%0A conjure.status('bootstrap.js', 'exit', %7BtestFile: testFile, reason: 'NoTestDefined'%7D);%0A casper.warn('Did not call conjure.test()');%0A casper.exit(1);%0A%7D%0A
2f80a9a036235b9d9c4f937697c25bc24b6c8d79
debug empty count method
js/ai.js
js/ai.js
function AI() { this.moves = [0,1,2,3]; this.brain = new deepqlearn.Brain(19,4, { epsilon_test_time: 0.0 // Shut off random guess }); this.previousMove = 0; } AI.prototype.getMaxVal = function() { var max = 0; this.grid.cells.forEach(function(row){ row.forEach( function( curVal ){ if( curVal && curVal.value > max ) max = curVal.value; }); }); return max; } AI.prototype.getEmptyCount = function() { var count = 0; this.grid.cells.forEach(function(row) { row.forEach( function( curVal ) { if( curVal ) return; console.log('Empty: ', curVal); count++; }); }); return count; } AI.prototype.buildInputs = function(score, moved, timesMoved, previousMove) { var inputs = []; var max = this.getMaxVal(); this.grid.cells.forEach(function(row, index) { row.forEach( function( curVal ) { if( curVal ){ inputs.push( ( 1 + ( -1 / curVal.value ) ) ); }else{ inputs.push(0); } }); }); inputs.push( ( previousMove > 0 ) ? previousMove / 4 : 0 ); inputs.push( ( score > 0 ) ? ( 1 + ( -1 / score ) ) : 0 ); inputs.push( ( moved ) ? 1 : 0 ); inputs.push( ( timesMoved > 0 ) ? ( 1 + (-1 / timesMoved ) ) : 0 ); console.log('Inputs: ', inputs); return inputs; } AI.prototype.getBest = function(meta) { this.grid = meta.grid; var inputs = this.buildInputs( meta.score, meta.moved, meta.timesMoved, meta.previousMove ); var action = this.brain.forward( inputs ); return { move: this.moves[action] }; } AI.prototype.reward = function(meta) { var max = this.getMaxVal(); if( meta.over && meta.won ){ reward = 1; }else if( meta.score != meta.previous ) { reward = ( 1 + (-0.1 / ( meta.score - meta.previous ) ) ); console.log('Score Reward: ', reward); maxReward = ( 1 + ( (-0.1 * max) / meta.score ) ); console.log('Max Reward: ', maxReward); moveReward = ( ( meta.timesMoved > 0 ) ? ( 1 + (-0.1 / meta.timesMoved ) ) : 0 ); console.log('Move Reward: ', moveReward); emptyReward = ( ( meta.empty > 0 ) ? 1 / meta.empty : 0 ); console.log('Empty Reward: ', emptyReward); reward = ( reward + maxReward + moveReward + emptyReward ) / 4; }else{ reward = -(0.5); } if( meta.over && !meta.won ) reward *= -1; console.log('Reward: ', reward ); this.brain.backward( reward ); this.brain.visSelf(document.getElementById('brainInfo')); } AI.prototype.rewardMultiple = function(meta){ var max = this.getMaxVal(); var scoreReward = ( 1 + (-1 / (meta.score - meta.previous ) ) ); var maxReward = ( 1 + ( ( -1 * max ) / meta.score ) ); var movesReward = ( ( meta.timesMoved > 0 ) ? ( 1 + (-1 / meta.timesMoved ) ) : 0); var emptyReward = ( ( meta.empty > 0 ) ? ( 1 + (-1 / meta.empty ) ) : 0 ); this.brain.backward( scoreReward ); this.brain.backward( maxReward ); this.brain.backward( movesReward ); this.brain.backward( emptyReward ); this.brain.visSelf(document.getElementById('brainInfo')); }
JavaScript
0.000002
@@ -549,43 +549,8 @@ %09%09%09%0A -%09%09%09console.log('Empty: ', curVal);%0A %09%09%09c @@ -2056,32 +2056,77 @@ ta.empty : 0 );%0A +%09%09console.log('Empty Count: ', meta.empty );%0A %09%09console.log('E
1bd2841d95a5357df7bc213ec717138b440485d3
Add slight timeout for buying
buy_stuff.js
buy_stuff.js
$(document).ready(function() { console.log("finding something to buy"); var baseTimeout = 150000; var desiredItemName = "Fatty Bearsteak"; var desiredItemPrice = 13; buyDesiredItems(desiredItemName, desiredItemPrice); reloadPage(baseTimeout + getRandomInt(0, baseTimeout)); }); function buyDesiredItems(desiredItemName, desiredItemPrice) { $('.table > table > tbody > tr').each(function(){ var itemId = $(this).attr('id').split('-')[1]; var itemName = $(this).children('.item').children('a').children('strong').html(); var quantity = $(this).children('.quantity').html(); if (itemName == desiredItemName) { var buyoutInGold = $(this).children('.price').children('.price-buyout').children('span:nth-child(1)').html(); var buyoutInSilver = $(this).children('.price').children('.price-buyout').children('span:nth-child(2)').html(); var buyoutInCopper = $(this).children('.price').children('.price-buyout').children('span:nth-child(3)').html(); if (buyoutInGold / quantity <= desiredItemPrice && buyoutInGold != "--") { var totalBuyoutPrice = buyoutInGold * 1000 + buyoutInSilver * 100 + buyoutInCopper; console.log("Trying to buy " + desiredItemName + " x" + quantity + " for " + buyoutInGold + " gold"); Auction.buyout(itemId, totalBuyoutPrice, $(this).children('.options').children('a:nth-child(2)')); saveStatistics(itemName, quantity, buyoutInGold); } } }); } function saveStatistics(itemName, quantity, goldSpent) { var currentQuantity = localStorage.getItem(getQuantityKey(itemName)); var currentGoldSpent = localStorage.getItem(getGoldKey(itemName)); if (currentQuantity == null) { currentQuantity = 0; } if (currentGoldSpent == null) { currentGoldSpent = 0; } localStorage.setItem(getQuantityKey(itemName), parseInt(currentQuantity) + parseInt(quantity)); localStorage.setItem(getGoldKey(itemName), parseInt(currentGoldSpent) + parseInt(goldSpent)); } function printStatistics(itemName) { var currentQuantity = localStorage.getItem(getQuantityKey(itemName)); var currentGoldSpent = localStorage.getItem(getGoldKey(itemName)); console.log("Currently have bought " + currentQuantity + " " + itemName + " for " + currentGoldSpent + " gold"); } function getQuantityKey(itemName) { return itemName.toLowerCase() + "-quantity"; } function getGoldKey(itemName) { return itemName.toLowerCase() + "-gold"; } function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } function reloadPage(timeout) { setTimeout(function(){ location.reload(); }, timeout); }
JavaScript
0
@@ -95,10 +95,10 @@ t = -15 +60 0000 @@ -619,16 +619,41 @@ tml();%0A%0A + var counter = 0;%0A @@ -1136,24 +1136,91 @@ != %22--%22) %7B%0A + counter++;%0A setTimeout(function() %7B%0A%0A @@ -1305,16 +1305,19 @@ Copper;%0A + @@ -1420,24 +1420,27 @@ + %22 gold%22);%0A + @@ -1554,16 +1554,19 @@ + saveStat @@ -1606,16 +1606,69 @@ InGold); +%0A%0A %7D, counter * getRandomInt(100, 175)); %0A
648479c9a81ccc7044c40d124e5d36c0c2a0f592
Update index.js
Name-Block/index.js
Name-Block/index.js
'use strict'; // dont touch const fs = require('fs'); this.command = []; // dont touch this.commandName = []; // dont touch this.gamemodeId = []; // dont touch this.gamemode = []; // dont touch this.addToHelp = []; // dont touch // [General] this.name = "Name-Block"; // Name of plugin REQUIRED this.author = "Andrews54757"; // author REQUIRED this.description = 'blocks certian nicknames'; // Desciprtion this.compatVersion = ''; // compatable with (optional) this.version = '1.0.0'; // version REQUIRED this.gameServer; // [Extra Commands] this.commandName[0] = "nameblock"; // plugin add-on command names this.addToHelp[0] = "nameblock : Nameblock plugin command"; // help command add-on (adds this string to the help command) this.command[0] = function (gameServer, split) { var c = split[1]; if (c == power) { if (gameServer.nameblock) { gameServer.nameblock = false; console.log("[Console] Turned off plugin"); return; } else { gameServer.nameblock = true; console.log("[Console] Turned on plugin"); return; } } if (!gameServer.nameblock) { console.log("[Console] Turn on plugin first"); return; } if (c == 'reload') { var load = ''; try { load = fs.readFileSync('./blockednames.txt', 'utf8').split(/[\r\n]+/).filter(function (x) { return x != ''; // filter empty names }); } catch (e) { fs.writeFileSync('blockednames.txt', ''); } gameServer.blockednames = load; console.log("[Console] Reloaded blocked names"); } else if (c == 'add') { if (!split[2]) { console.log("[Console] Please specify a name"); return; } gameServer.blockednames.push(split[2]); console.log("[Console] Added " + split[2] + " to the blocked name list"); } else { console.log("[Console] Please specify a command, reload, power, add"); } }; // extra command location // [Extra Gamemodes] this.gamemodeId[0] = ''; // gamemodeids of extra plugin gamemodes this.gamemode[0] = ''; // gamemode location this.blockednames; // [Configs] this.config = { preservecase: 0, } this.configfile = 'config.ini' // [Functions] this.init = function (gameServer, config) { this.config = config; gameServer.preservec = this.config.preservecase; this.gameServer = gameServer; var load = ''; try { load = fs.readFileSync('./blockednames.txt', 'utf8').split(/[\r\n]+/).filter(function (x) { return x != ''; // filter empty names }); } catch (e) { fs.writeFileSync('blockednames.txt', ''); } gameServer.blockednames = load; // init, Used to do stuff such as overriding things console.log("[NameBlock] Loaded and file is in src/blockednames.txt"); }; this.beforespawn = function (player) { if (!this.gameServer.nameblock) return true; if (!player.name) return true; if (this.gameServer.preservec == 1) { for (var i in this.gameServer.blockednames) { if (-1 != player.name.indexOf(this.gameServer.blockednames[i])) return false; } } else { var n = player.name.toLowerCase(); for (var i in this.gameServer.blockednames) { if (n.indexOf(this.gameServer.blockednames[i]) != -1) return false; } } return true; }; this.onSecond = function (gameServer) { // called every second }; module.exports = this; // dont touch
JavaScript
0.000002
@@ -2167,16 +2167,47 @@ nfig) %7B%0A + gameServer.nameblock = true;%0A this.c @@ -2936,14 +2936,8 @@ if ( --1 != play @@ -2984,16 +2984,22 @@ ames%5Bi%5D) + != -1 ) return
456116287ecb7ddc9feaf84d3fbf04e11a8dc854
remove old log
admin/src/views/list.js
admin/src/views/list.js
var React = require('react'); var CreateForm = require('../components/CreateForm'); var utils = require('keystone-utils'); var Button = require('elemental').Button; var Dropdown = require('elemental').Dropdown; var View = React.createClass({ displayName: 'ListView', getInitialState: function() { return { createIsVisible: Keystone.showCreateForm, animateCreateForm: false }; }, toggleCreate: function(visible) { this.setState({ createIsVisible: visible, animateCreateForm: true }); }, renderCreateButton: function() { if (Keystone.list.autocreate) { return ( <Button type="success" href={'?new' + Keystone.csrf.query}> <span className="octicon octicon-plus mr-5 mr-5" /> Create {Keystone.list.singular} </Button> ); } return ( <Button type="success" onClick={this.toggleCreate.bind(this, true)}> <span className="octicon octicon-plus mr-5 mr-5" /> Create {Keystone.list.singular} </Button> ); }, renderCreateForm: function() { if (!this.state.createIsVisible) return null; return <CreateForm list={Keystone.list} animate={this.state.animateCreateForm} onCancel={this.toggleCreate.bind(this, false)} values={Keystone.createFormData} err={Keystone.createFormErrors} />; }, render: function() { if (Keystone.list.nocreate) return null; return ( <div className="EditForm__header"> <div className="container"> {this.renderCreateButton()} {this.renderCreateForm()} </div> </div> ); } }); /* ============================== SORT DROPDOWN ============================== */ var ListSortDropdown = React.createClass({ displayName: 'ListSortDropdown', getInitialState: function() { return {}; }, menuItems: function() { return Keystone.list.uiElements.map(function(item, i) { console.log(item); if (item.type === 'heading') { return { type: 'header', label: item.content }; } else { return { type: 'item', label: utils.titlecase(item.field) }; } }); }, renderDropdown: function() { var sort = Keystone.sort; var buttonLabel = 'sort by'; if (sort.label) { buttonLabel = sort.label.toLowerCase(); if (sort.inv) { buttonLabel += ' (descending)'; } } return ( <Dropdown items={this.menuItems()} component='span'> <a href="javascript:;">{buttonLabel}</a> </Dropdown> ); }, render: function() { return this.renderDropdown(); } }); React.render(<View />, document.getElementById('list-view')); React.render(<ListSortDropdown />, document.getElementById('list-sort-dropdown'));
JavaScript
0.00004
@@ -1810,31 +1810,8 @@ ) %7B%0A -%09%09%09console.log(item);%0A%0A %09%09%09i
ab27b49deddbd6f74bad126b9a275b015a7fb6cd
rename autoComplete directive as tabComplete to avoid confusion with the autocomplete html attribute
webclient/room/room-directive.js
webclient/room/room-directive.js
/* Copyright 2014 matrix.org Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ 'use strict'; angular.module('RoomController') .directive('autoComplete', ['$timeout', function ($timeout) { return function (scope, element, attrs) { element.bind("keydown keypress", function (event) { // console.log("event: " + event.which); if (event.which === 9) { if (!scope.autoCompleting) { // cache our starting text // console.log("caching " + element[0].value); scope.autoCompleteOriginal = element[0].value; scope.autoCompleting = true; } if (event.shiftKey) { scope.autoCompleteIndex--; if (scope.autoCompleteIndex < 0) { scope.autoCompleteIndex = 0; } } else { scope.autoCompleteIndex++; } var searchIndex = 0; var targetIndex = scope.autoCompleteIndex; var text = scope.autoCompleteOriginal; // console.log("targetIndex: " + targetIndex + ", text=" + text); // FIXME: use the correct regexp to recognise userIDs var search = /@?([a-zA-Z0-9_\-:\.]+)$/.exec(text); if (targetIndex === 0) { element[0].value = text; } else if (search && search[1]) { // console.log("search found: " + search); var expansion; // FIXME: could do better than linear search here angular.forEach(scope.members, function(item, name) { if (item.displayname && searchIndex < targetIndex) { if (item.displayname.toLowerCase().indexOf(search[1].toLowerCase()) === 0) { expansion = item.displayname; searchIndex++; } } }); if (searchIndex < targetIndex) { // then search raw mxids angular.forEach(scope.members, function(item, name) { if (searchIndex < targetIndex) { if (name.toLowerCase().indexOf(search[1].toLowerCase()) === 1) { expansion = name; searchIndex++; } } }); } if (searchIndex === targetIndex) { // xchat-style tab complete if (search[0].length === text.length) expansion += " : "; else expansion += " "; element[0].value = text.replace(/@?([a-zA-Z0-9_\-:\.]+)$/, expansion); // cancel blink element[0].className = ""; } else { // console.log("wrapped!"); element[0].className = "blink"; // XXX: slightly naughty to bypass angular $timeout(function() { element[0].className = ""; }, 150); element[0].value = text; scope.autoCompleteIndex = 0; } } else { scope.autoCompleteIndex = 0; } event.preventDefault(); } else if (event.which !== 16 && scope.autoCompleting) { scope.autoCompleting = false; scope.autoCompleteIndex = 0; } }); }; }]) // A directive to anchor the scroller position at the bottom when the browser is resizing. // When the screen resizes, the bottom of the element remains the same, not the top. .directive('keepScroll', ['$window', function($window) { return { link: function(scope, elem, attrs) { scope.windowHeight = $window.innerHeight; // Listen to window size change angular.element($window).bind('resize', function() { // If the scroller is scrolled to the bottom, there is nothing to do. // The browser will move it as expected if (elem.scrollTop() + elem.height() !== elem[0].scrollHeight) { // Else, move the scroller position according to the window height change delta var windowHeightDelta = $window.innerHeight - scope.windowHeight; elem.scrollTop(elem.scrollTop() - windowHeightDelta); } // Store the new window height for the next screen size change scope.windowHeight = $window.innerHeight; }); } }; }]);
JavaScript
0
@@ -621,20 +621,19 @@ ective(' -auto +tab Complete @@ -889,28 +889,27 @@ if (!scope. -auto +tab Completing) @@ -1022,36 +1022,35 @@ scope. -auto +tab CompleteOriginal @@ -1088,36 +1088,35 @@ scope. -auto +tab Completing = tru @@ -1209,36 +1209,35 @@ scope. -auto +tab CompleteIndex--; @@ -1263,28 +1263,27 @@ if (scope. -auto +tab CompleteInde @@ -1313,36 +1313,35 @@ scope. -auto +tab CompleteIndex = @@ -1424,36 +1424,35 @@ scope. -auto +tab CompleteIndex++; @@ -1556,36 +1556,35 @@ etIndex = scope. -auto +tab CompleteIndex;%0A @@ -1611,28 +1611,27 @@ ext = scope. -auto +tab CompleteOrig @@ -4157,36 +4157,35 @@ scope. -auto +tab CompleteIndex = @@ -4268,36 +4268,35 @@ scope. -auto +tab CompleteIndex = @@ -4415,28 +4415,27 @@ 16 && scope. -auto +tab Completing) @@ -4454,28 +4454,27 @@ scope. -auto +tab Completing = @@ -4507,12 +4507,11 @@ ope. -auto +tab Comp
753a1e8c1ebf926fe48b90fdd6d31c9fd95d00c5
Fix problem where index_bundle ends up in wrong spot (#3289)
webpack.datascience-ui.config.js
webpack.datascience-ui.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin'); const FixDefaultImportPlugin = require('webpack-fix-default-import-plugin'); const path = require('path'); const CopyWebpackPlugin = require('copy-webpack-plugin') const configFileName = 'tsconfig.datascience-ui.json'; module.exports = { entry: ['babel-polyfill', './src/datascience-ui/history-react/index.tsx'], output: { path: path.join(__dirname, 'out'), filename: 'index_bundle.js', publicPath: './' }, mode: 'development', // Leave as is, we'll need to see stack traces when there are errors. // Use 'eval' for release and `eval-source-map` for development. // We need to use one where source is embedded, due to webviews (they restrict resources to specific schemes, // this seems to prevent chrome from downloading the source maps) devtool: 'eval-source-map', node: { fs: 'empty' }, plugins: [ new HtmlWebpackPlugin({ template: 'src/datascience-ui/history-react/index.html', filename: 'datascience-ui/history-react/index.html' }), new FixDefaultImportPlugin(), new CopyWebpackPlugin([ { from: './**/*.png', to: '.' }, { from: './**/*.svg', to: '.' }, { from: './**/*.css', to: '.' }, { from: './**/*theme*.json', to: '.' } ], { context: 'src' }), ], resolve: { // Add '.ts' and '.tsx' as resolvable extensions. extensions: [".ts", ".tsx", ".js", ".json"] }, module: { rules: [ // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'. { test: /\.tsx?$/, use: { loader: "awesome-typescript-loader", options: { configFileName, reportFiles: [ 'src/datascience-ui/**/*.{ts,tsx}' ] }, } }, { test: /\.css$/, use: [ 'style-loader', 'css-loader' ], }, { test: /\.js$/, include: /node_modules.*remark.*default.*js/, use: [ { loader: path.resolve('./build/datascience/remarkLoader.js'), options: {} } ] }, { test: /\.json$/, type: 'javascript/auto', include: /node_modules.*remark.*/, use: [ { loader: path.resolve('./build/datascience/jsonloader.js'), options: {} } ] } ] } };
JavaScript
0.000001
@@ -457,16 +457,45 @@ ename: ' +datascience-ui/history-react/ index_bu
92d7292f36c07154de8ac2f6f5bc7717fbaad653
disable server-side uglify in all cases
webpack/webpack.config.server.js
webpack/webpack.config.server.js
// @flow import path from 'path' import webpack from 'webpack' import ExtractTextPlugin from 'extract-text-webpack-plugin' import HappyPack from 'happypack' import ProgressBarPlugin from 'progress-bar-webpack-plugin' import nodeExternals from 'webpack-node-externals' import buildDir from '../buildDir' const root = path.resolve(__dirname, '..') const srcDir = path.resolve(root, 'src') const globalCSS = path.join(srcDir, 'styles', 'global') const config = { context: root, devtool: 'source-map', entry: { prerender: './src/server', }, target: 'node', node: { __dirname: false, __filename: false, }, output: { path: buildDir, chunkFilename: '[name]_[chunkhash].js', filename: '[name].js', libraryTarget: 'commonjs2', publicPath: '/static/', }, // ignore anything that throws warnings & doesn't affect the view externals: [ nodeExternals({ modulesDir: path.join(root, 'node_modules'), }), // (context: string, request: string, callback: (error?: ?Error, result?: ?string) => any): any => { // const match = /^meteor\/(.*)$/.exec(request) // if (match) { // return callback(null, 'var Package.' + match[1].replace(/\//g, '.')) // } // callback() // }, ], plugins: [ new webpack.NoErrorsPlugin(), new ExtractTextPlugin('/static/[name].css'), new webpack.optimize.LimitChunkCountPlugin({ maxChunks: 1 }), new webpack.DefinePlugin({ '__CLIENT__': false, '__PRODUCTION__': true, 'Meteor.isClient': false, 'Meteor.isCordova': false, 'Meteor.isServer': true, 'process.env.TARGET': JSON.stringify(process.env.TARGET), 'process.env.NODE_ENV': JSON.stringify('production'), // uncomment this line to hard-disable full SSR // 'process.env.DISABLE_FULL_SSR': JSON.stringify('1'), }), new HappyPack({ id: '1', // https://github.com/amireh/happypack/issues/88 cache: false, loaders: ['babel'], threads: 4, }), ], module: { loaders: [ { test: /\.json$/, loader: 'json-loader' }, { test: /\.txt$/, loader: 'raw-loader' }, { test: /\.(png|jpg|jpeg|gif|svg|woff|woff2)$/, loader: 'url-loader?limit=10000' }, { test: /\.(eot|ttf|wav|mp3)$/, loader: 'file-loader' }, { test: /\.css$/, loader: ExtractTextPlugin.extract( 'fake-style', 'css?modules&importLoaders=1&localIdentName=[name]_[local]_[hash:base64:5]!postcss' ), include: srcDir, exclude: globalCSS, }, { test: /\.css$/, loader: ExtractTextPlugin.extract('fake-style', 'css'), include: globalCSS, }, { test: /\.js$/, loader: 'happypack/loader', include: srcDir, }, ], }, } /* istanbul ignore next */ if (!process.env.CI) config.plugins.push(new ProgressBarPlugin()) if (process.argv.indexOf('--no-uglify') < 0) { config.plugins.push(new webpack.optimize.UglifyJsPlugin({ compressor: { warnings: false } })) } export default config
JavaScript
0
@@ -2904,159 +2904,8 @@ n()) -%0Aif (process.argv.indexOf('--no-uglify') %3C 0) %7B%0A config.plugins.push(new webpack.optimize.UglifyJsPlugin(%7B%0A compressor: %7B warnings: false %7D%0A %7D))%0A%7D %0A%0Aex
0797d873cb66c93bcdd2c1da943d8284792560f7
Fix silly mistake
deploy/deploy_to_s3.js
deploy/deploy_to_s3.js
// node deplpy_to_s3.js [localDirName] [S3DirName] // node deplpy_to_s3.js ../dist production var AWS = require('aws-sdk'); var fs = require('fs'); var path = require('path'); var Q = require('q'); var chalk = require('chalk'); AWS.config.region = 'eu-west-1'; var localDirPath = process.argv[2]; var remoteDirName = process.argv[3] + '/' + process.env.CI_BUILD_REF_NAME + '/' + process.env.CI_BUILD_REF; chalk.blue('Local path is: ', localDirPath); chalk.blue('Remote path is: ', S3DirName); readLocalDir(localDirPath) .then(filterDotDirs) .then(mapFilesToFullPaths(localDirPath)) .then(mapFilesToStreams) .then(function(streams) { streams.forEach(uploadFile(remoteDirName)) }); function readLocalDir(localPath) { chalk.blue('Reading local dir: ', localPath); return Q.nfcall(fs.readdir, localPath); } function filterDotDirs(filesList) { chalk.blue('Files list is here: ', filesList.join("\n")); Q.when(filesList .filter(function(fileName) { return ['..', '.'].indexOf(fileName) === -1; }) ); } function mapFilesToFullPaths(localDirPath) { return function(filesList) { filesList.map(function(fileName) { return path.join(localDirPath, fileName); }); }; } function mapFilesToStreams(filesPaths) { chalk.blue('Create files streams'); return filesPaths.map(function(filePath) { return fs.createReadStream(filePath); }); } function uploadFile(remotePath) { return function(stream) { var S3 = new AWS.S3({params: {Bucket: 'as24-assets-eu-west-1', Key: remotePath + '/' + stream}}); S3.upload({Body: body}) .on('httpUploadProgress', function(evt) { chalk.green('File ' + evt.key + ' is ' + (evt.loaded * 100 / evt.total) + '% loaded'); }) .send(function(err, data) { if (err) return chalk.red(err); return chalk.green('Uploading of ' + data.key + ' is done!\n\tIt is located at ' + data.Location); }); }; }
JavaScript
0.999999
@@ -27,27 +27,25 @@ ocal -DirName%5D %5BS3DirName + dir%5D %5Bremote dir %5D%0A// @@ -476,18 +476,22 @@ is: ', -S3 +remote DirName)