<commit_before>var postgres       = require("pg");

exports.Driver = Driver;

function Driver(opts, connection) {
	this.opts = opts || {};
	this.db = (connection ? connection : new postgres.Client(opts));

	var escapes = {
		escape   : escape,
		escapeId : escapeId
	};

	this.QuerySelect = new (require("../sql/Select"))(escapes);
	this.QueryInsert = new (require("../sql/Insert"))(escapes);
	this.QueryUpdate = new (require("../sql/Update"))(escapes);
	this.QueryRemove = new (require("../sql/Remove"))(escapes);
}

Driver.prototype.connect = function (cb) {
	this.db.connect(cb);
};

Driver.prototype.close = function (cb) {
	this.db.end(cb);
};

Driver.prototype.find = function (table, conditions, opts, cb) {
	this.QuerySelect
		.clear()
		.table(table);
	if (opts.fields) {
		this.QuerySelect.fields(opts.fields);
	}
	if (opts.merge) {
		this.QuerySelect.merge(opts.merge.from, opts.merge.to);
	}
	if (typeof opts.limit == "number") {
		this.QuerySelect.limit(opts.limit);
	}
	if (opts.order) {
		this.QuerySelect.order(opts.order[0], opts.order[1]);
	}
	for (var k in conditions) {
		this.QuerySelect.where(k, conditions[k]);
	}

	this.db.query(this.QuerySelect.build(), handleQuery(cb));
};

Driver.prototype.insert = function (table, data, cb) {
	this.QueryInsert
		.clear()
		.table(table);
	for (var k in data) {
		this.QueryInsert.set(k, data[k]);
	}

	this.db.query(this.QueryInsert.build() + " RETURNING *", function (err, result) {
		if (err) {
			return cb(err);
		}
		return cb(null, {
			id: result.rows[0].id || null
		});
	});
};

Driver.prototype.update = function (table, changes, id_prop, id, cb) {
	this.QueryUpdate
		.clear()
		.table(table)
		.where(id_prop, id);
	for (var k in changes) {
		this.QueryUpdate.set(k, changes[k]);
	}

	this.db.query(this.QueryUpdate.build(), handleQuery(cb));
};

Driver.prototype.remove = function (table, conditions, cb) {
	this.QueryRemove
		.clear()
		.table(table);
	for (var k in conditions) {
		this.QueryRemove.where(k, conditions[k]);
	}

	this.db.query(this.QueryRemove.build(), handleQuery(cb));
};

Driver.prototype.clear = function (table, cb) {
	this.db.query("TRUNCATE TABLE " + escapeId(table), handleQuery(cb));
};

function handleQuery(cb) {
	return function (err, result) {
		if (err) {
			return cb(err);
		}
		return cb(null, result.rows);
	};
}

function escape(value) {
	if (Array.isArray(value)) {
		return "(" + value.map(escape) + ")";
	}
	switch (typeof value) {
		case "number":
			return value;
	}

	return "'" + value.replace(/\'/g, "''") + "'";
}

function escapeId(id) {
	var m = id.match(/^(.+)\.\*$/);
	if (m) {
		return '"' + m[1].replace(/\"/g, '""') + '".*';
	}
	return '"' + id.replace(/\"/g, '""').replace(/\./g, '"."') + '"';
}
<commit_msg>Updates postgres driver to support object types (converting to JSON)<commit_after>var postgres       = require("pg");

exports.Driver = Driver;

function Driver(opts, connection) {
	this.opts = opts || {};
	this.db = (connection ? connection : new postgres.Client(opts));

	var escapes = {
		escape   : escape,
		escapeId : escapeId
	};

	this.QuerySelect = new (require("../sql/Select"))(escapes);
	this.QueryInsert = new (require("../sql/Insert"))(escapes);
	this.QueryUpdate = new (require("../sql/Update"))(escapes);
	this.QueryRemove = new (require("../sql/Remove"))(escapes);
}

Driver.prototype.connect = function (cb) {
	this.db.connect(cb);
};

Driver.prototype.close = function (cb) {
	this.db.end(cb);
};

Driver.prototype.find = function (table, conditions, opts, cb) {
	this.QuerySelect
		.clear()
		.table(table);
	if (opts.fields) {
		this.QuerySelect.fields(opts.fields);
	}
	if (opts.merge) {
		this.QuerySelect.merge(opts.merge.from, opts.merge.to);
	}
	if (typeof opts.limit == "number") {
		this.QuerySelect.limit(opts.limit);
	}
	if (opts.order) {
		this.QuerySelect.order(opts.order[0], opts.order[1]);
	}
	for (var k in conditions) {
		this.QuerySelect.where(k, conditions[k]);
	}

	this.db.query(this.QuerySelect.build(), handleQuery(cb));
};

Driver.prototype.insert = function (table, data, cb) {
	this.QueryInsert
		.clear()
		.table(table);
	for (var k in data) {
		this.QueryInsert.set(k, data[k]);
	}

	this.db.query(this.QueryInsert.build() + " RETURNING *", function (err, result) {
		if (err) {
			return cb(err);
		}
		return cb(null, {
			id: result.rows[0].id || null
		});
	});
};

Driver.prototype.update = function (table, changes, id_prop, id, cb) {
	this.QueryUpdate
		.clear()
		.table(table)
		.where(id_prop, id);
	for (var k in changes) {
		this.QueryUpdate.set(k, changes[k]);
	}

	this.db.query(this.QueryUpdate.build(), handleQuery(cb));
};

Driver.prototype.remove = function (table, conditions, cb) {
	this.QueryRemove
		.clear()
		.table(table);
	for (var k in conditions) {
		this.QueryRemove.where(k, conditions[k]);
	}

	this.db.query(this.QueryRemove.build(), handleQuery(cb));
};

Driver.prototype.clear = function (table, cb) {
	this.db.query("TRUNCATE TABLE " + escapeId(table), handleQuery(cb));
};

Driver.prototype.valueToProperty = function (value, property) {
	switch (property.type) {
		case "object":
			try {
				return JSON.parse(value);
			} catch (e) {
				return null;
			}
			break;
		default:
			return value;
	}
};

Driver.prototype.propertyToValue = function (value, property) {
	switch (property.type) {
		case "object":
			return JSON.stringify(value);
		default:
			return value;
	}
};

function handleQuery(cb) {
	return function (err, result) {
		if (err) {
			return cb(err);
		}
		return cb(null, result.rows);
	};
}

function escape(value) {
	if (Array.isArray(value)) {
		return "(" + value.map(escape) + ")";
	}
	switch (typeof value) {
		case "number":
			return value;
	}

	return "'" + value.replace(/\'/g, "''") + "'";
}

function escapeId(id) {
	var m = id.match(/^(.+)\.\*$/);
	if (m) {
		return '"' + m[1].replace(/\"/g, '""') + '".*';
	}
	return '"' + id.replace(/\"/g, '""').replace(/\./g, '"."') + '"';
}
<|endoftext|>


<commit_before>// @flow
const webpack = require('webpack')
const webpackTargetElectronRenderer = require('webpack-target-electron-renderer')
const baseConfig = require('./webpack.config.base')
const getenv = require('getenv')
const UnusedFilesWebpackPlugin = require('unused-files-webpack-plugin').default
const DashboardPlugin = require('webpack-dashboard/plugin')

const USING_DLL = getenv.boolish('USING_DLL', false)
const NO_SERVER = getenv.boolish('NO_SERVER', false)
const NO_SOURCE_MAPS = getenv.boolish('NO_SOURCE_MAPS', false)
const defines = {
  '__DEV__': true,
  '__SCREENSHOT__': false,
  'process.env.NODE_ENV': JSON.stringify('development'),
  '__VERSION__': JSON.stringify('Development'),
}

// $FlowIssue
const config = Object.assign({}, baseConfig)

console.warn('Injecting dev defines: ', defines)

config.debug = true
config.cache = true
config.devtool = NO_SOURCE_MAPS ? undefined : 'eval-source-map'
config.pathinfo = true
config.output.publicPath = 'http://localhost:4000/dist/'

// Uncomment below to figure out packaging bugs
// config.bail = true

config.plugins.push(new UnusedFilesWebpackPlugin({
  pattern: '../shared/**/*.js',
  globOptions: {
    ignore: [
      // Mobile stuff
      '../**/*.native.js',
      '../**/*.ios.js',
      '../**/*.android.js',
      // Flow stuff
      '../shared/constants/folders.js',
      '../shared/constants/types/flux.js',
      '../shared/constants/types/saga.js',
      '../shared/constants/reducer.js',
      '../shared/flow-typed/*.js',
      // Tests
      '../shared/test/**',
      // Misc
      '../shared/packager/wipe-cache.js',
      '../shared/dev/log-send/index.js',
    ],
  },
}))

if (!NO_SERVER) {
  config.plugins.push(new DashboardPlugin())
}

config.plugins.push(new webpack.optimize.OccurenceOrderPlugin())

if (getenv.boolish('HOT', false)) {
  config.plugins.push(new webpack.HotModuleReplacementPlugin())
}

config.plugins.push(
  new webpack.NoErrorsPlugin(),
  new webpack.DefinePlugin(defines)
)

if (USING_DLL) {
  config.plugins.push(
    new webpack.DllReferencePlugin({
      context: './renderer',
      manifest: require('./dll/vendor-manifest.json'),
    })
  )
}

if (getenv.boolish('HOT', false)) {
  config.entry.index = ['react-hot-loader/patch'].concat(config.entry.index)

  const HMR = 'webpack-hot-middleware/client?path=http://localhost:4000/__webpack_hmr'

  Object.keys(config.entry).forEach(k => {
    if (k !== 'main') { // node-only thread can't be hot loaded...
      config.entry[k] = [HMR].concat(config.entry[k]) // Note: all entry points need `if (module.hot) {module.hot.accept()}` to allow hot auto loads to work
    }
  })
}

if (USING_DLL) {
  // If we are running a hot server and using a DLL we want to be fast.
  // So don't waste time in building the main thread bundle in this webpack server
  delete config.entry.main
}

config.target = webpackTargetElectronRenderer(config)
module.exports = config
<commit_msg>fix start-cold paths for fonts (#5027)<commit_after>// @flow
const webpack = require('webpack')
const webpackTargetElectronRenderer = require('webpack-target-electron-renderer')
const baseConfig = require('./webpack.config.base')
const getenv = require('getenv')
const UnusedFilesWebpackPlugin = require('unused-files-webpack-plugin').default
const DashboardPlugin = require('webpack-dashboard/plugin')

const USING_DLL = getenv.boolish('USING_DLL', false)
const NO_SERVER = getenv.boolish('NO_SERVER', false)
const NO_SOURCE_MAPS = getenv.boolish('NO_SOURCE_MAPS', false)
const HOT = getenv.boolish('HOT', false)
const defines = {
  '__DEV__': true,
  '__SCREENSHOT__': false,
  'process.env.NODE_ENV': JSON.stringify('development'),
  '__VERSION__': JSON.stringify('Development'),
}

// $FlowIssue
const config = Object.assign({}, baseConfig)

console.warn('Injecting dev defines: ', defines)

config.debug = true
config.cache = true
config.devtool = NO_SOURCE_MAPS ? undefined : 'eval-source-map'
config.pathinfo = true
config.output.publicPath = HOT ? 'http://localhost:4000/dist/' : '../dist/'

// Uncomment below to figure out packaging bugs
// config.bail = true

config.plugins.push(new UnusedFilesWebpackPlugin({
  pattern: '../shared/**/*.js',
  globOptions: {
    ignore: [
      // Mobile stuff
      '../**/*.native.js',
      '../**/*.ios.js',
      '../**/*.android.js',
      // Flow stuff
      '../shared/constants/folders.js',
      '../shared/constants/types/flux.js',
      '../shared/constants/types/saga.js',
      '../shared/constants/reducer.js',
      '../shared/flow-typed/*.js',
      // Tests
      '../shared/test/**',
      // Misc
      '../shared/packager/wipe-cache.js',
      '../shared/dev/log-send/index.js',
    ],
  },
}))

if (!NO_SERVER) {
  config.plugins.push(new DashboardPlugin())
}

config.plugins.push(new webpack.optimize.OccurenceOrderPlugin())

if (getenv.boolish('HOT', false)) {
  config.plugins.push(new webpack.HotModuleReplacementPlugin())
}

config.plugins.push(
  new webpack.NoErrorsPlugin(),
  new webpack.DefinePlugin(defines)
)

if (USING_DLL) {
  config.plugins.push(
    new webpack.DllReferencePlugin({
      context: './renderer',
      manifest: require('./dll/vendor-manifest.json'),
    })
  )
}

if (getenv.boolish('HOT', false)) {
  config.entry.index = ['react-hot-loader/patch'].concat(config.entry.index)

  const HMR = 'webpack-hot-middleware/client?path=http://localhost:4000/__webpack_hmr'

  Object.keys(config.entry).forEach(k => {
    if (k !== 'main') { // node-only thread can't be hot loaded...
      config.entry[k] = [HMR].concat(config.entry[k]) // Note: all entry points need `if (module.hot) {module.hot.accept()}` to allow hot auto loads to work
    }
  })
}

if (USING_DLL) {
  // If we are running a hot server and using a DLL we want to be fast.
  // So don't waste time in building the main thread bundle in this webpack server
  delete config.entry.main
}

config.target = webpackTargetElectronRenderer(config)
module.exports = config
<|endoftext|>


<commit_before>var React = require('react');
var path = require('path');

var Component = function Component(opts) {
  this.opts = opts;
  this.path = null;
  this.component = null;
};

Component.prototype.getPath = function getPath(cb) {
  if (this.path) {
    return cb(null, this.path);
  }
  if (!this.opts.path) {
    return cb(new Error('Component missing `path` property'));
  }
  this.path = this.opts.path;
  cb(null, this.path);
};

Component.prototype.getComponent = function getComponent(cb) {
  if (this.component) {
    return cb(null, this.component);
  }

  if (this.opts.component) {
    this.component = this.opts.component;
    return cb(null, this.component);
  }

  this.getPath(function(err, path) {
    if (err) return cb(err);

    if (!path) {
      return cb(new Error('Component options missing `path` and `component` properties'));
    }

    try {
      this.component = require(this.path);
    } catch(err) {
      return cb(err);
    }

    cb(null, this.component);
  }.bind(this));
};

Component.prototype._renderRouter = function _renderRouter(props, location, toStaticMarkup, cb) {
  this.getComponent(function(err, component) {
    if (err) return cb(err);

    var render = (
      toStaticMarkup ? React.renderToStaticMarkup : React.renderToString
    ).bind(React);

    try {
      var markup;
      var routes = component.routes;
      var Router = component.Router;
      var router = component.router;
      var locObj = new component.Location(location);
      Router.run(routes, locObj, function(error, initialState, transition) {
        markup = render(router(initialState, props));
      })
    } catch(err) {
      return cb(err);
    }

    cb(null, markup);
  }.bind(this));
};

Component.prototype.renderToString = function renderToString(props, location, cb) {
  this._renderRouter(props, location, false, cb);
};

Component.prototype.renderToStaticMarkup = function renderToStaticMarkup(props, location, cb) {
  this._renderRouter(props, location, true, cb);
};

module.exports = Component;
<commit_msg>Return information about transition state<commit_after>var React = require('react');
var path = require('path');

var Component = function Component(opts) {
  this.opts = opts;
  this.path = null;
  this.component = null;
};

Component.prototype.getPath = function getPath(cb) {
  if (this.path) {
    return cb(null, this.path);
  }
  if (!this.opts.path) {
    return cb(new Error('Component missing `path` property'));
  }
  this.path = this.opts.path;
  cb(null, this.path);
};

Component.prototype.getComponent = function getComponent(cb) {
  if (this.component) {
    return cb(null, this.component);
  }

  if (this.opts.component) {
    this.component = this.opts.component;
    return cb(null, this.component);
  }

  this.getPath(function(err, path) {
    if (err) return cb(err);

    if (!path) {
      return cb(new Error('Component options missing `path` and `component` properties'));
    }

    try {
      this.component = require(this.path);
    } catch(err) {
      return cb(err);
    }

    cb(null, this.component);
  }.bind(this));
};

Component.prototype._renderRouter = function _renderRouter(props, location, toStaticMarkup, cb) {
  this.getComponent(function(err, component) {
    if (err) return cb(err);

    var render = (
      toStaticMarkup ? React.renderToStaticMarkup : React.renderToString
    ).bind(React);

    try {
      var routes = component.routes;
      var Router = component.Router;
      var router = component.router;
      var locObj = new component.Location(location);

      var cbData = {
        markup: null,
        redirectInfo: null,
        match: false,
      }

      Router.run(routes, locObj, function(error, initialState, transition) {
        if (error === null) {
          cbData.markup = render(router(initialState, props));
          cbData.match = true;
        } else {
          if (error === undefined) {
            if (transition.isCancelled) {
              // Transition was cancelled, possible redirect
              if (transition.hasOwnProperty('redirectInfo') && transition.redirectInfo !== null) {
                cbData.redirectInfo = transition.redirectInfo;
              }
            }
          } else {
            throw(error);
          }
        }
      });
    } catch(err) {
      return cb(err);
    }

    cb(null, cbData);
  }.bind(this));
};

Component.prototype.renderToString = function renderToString(props, location, cb) {
  this._renderRouter(props, location, false, cb);
};

Component.prototype.renderToStaticMarkup = function renderToStaticMarkup(props, location, cb) {
  this._renderRouter(props, location, true, cb);
};

module.exports = Component;
<|endoftext|>


<commit_before>"use strict";

const csv = process.argv.includes ('--csv')
    , delimiter = csv ? ',' : '|'
    , ccxt = require ('../../ccxt.js')
    , asTableConfig = { delimiter: ' ' + delimiter + ' ', /* print: require ('string.ify').noPretty  */ }
    , asTable = require ('as-table').configure (asTableConfig)
    , log = require ('ololog').noLocate
    , ansi = require ('ansicolor').nice

console.log (ccxt.iso8601 (ccxt.milliseconds ()))
console.log ('CCXT v' + ccxt.version)
const isWindows = process.platform == 'win32' // fix for windows, as it doesn't show darkred-VS-red well enough

async function main () {

    let total = 0
    let notImplemented = 0
    let inexistentApi = 0
    let implemented = 0
    let emulated = 0

    const exchanges = ccxt.exchanges.map (id => new ccxt[id] ())
    const metainfo = ccxt.flatten (exchanges.map (exchange => Object.keys (exchange.has)))
    const reduced = metainfo.reduce ((previous, current) => {
        previous[current] = (previous[current] || 0) + 1
        return previous
    }, {})
    const unified = Object.entries (reduced).filter (([ _, count ]) => count > 1)
    const methods = unified.map (([ method, _ ]) => method).sort ()
    const table = asTable (exchanges.map (exchange => {
        let result = {};
        const basics = [
            'publicAPI',
            'privateAPI',
            'CORS',
            'margin',
            'swap',
            'future',
            'CORS',
        ];

        ccxt.unique (basics.concat (methods)).forEach (key => {

            total += 1

            const isApiBasics = basics.includes (key)
            let capType = typeof exchange[key]
            let capHas = exchange.has[key]
            let coloredString = '';

            const feature = exchange.has[key]

            if (feature === false) {
                // if explicitly set to 'false' in exchange.has (to exclude mistake, we check if it's undefined too)
                coloredString = isWindows ? exchange.id.lightMagenta : exchange.id.red
                inexistentApi += 1
            } else if (feature === 'emulated') {
                // if explicitly set to 'emulated' in exchange.has
                coloredString = exchange.id.yellow
                emulated += 1
            } else if (feature) {
                // if neither 'false' nor 'emulated', and if  method exists
                coloredString = exchange.id.green
                implemented += 1
            } else {
                coloredString = isWindows ? exchange.id.red : exchange.id.red.dim
                notImplemented += 1
            }

            result[key] = coloredString
        })

        return result
    }))

    if (csv) {
        let lines = table.split ("\n")
        lines = lines.slice (0, 1).concat (lines.slice (2))
        log (lines.join ("\n"))
    } else {
        log (table)
    }

    log ('Summary: ',
        ccxt.exchanges.length.toString (), 'exchanges; ',
        'Methods [' + total.toString () + ' total]: ',
        implemented.toString ().green, 'implemented,',
        emulated.toString ().yellow, 'emulated,',
        (isWindows ? inexistentApi.toString ().lightMagenta : inexistentApi.toString ().red), 'inexistentApi,',
        (isWindows ? notImplemented.toString ().red : notImplemented.toString ().red.dim), 'notImplemented',
    )

    log("\nMessy? Try piping to less (e.g. node script.js | less -S -R)\n".red)

}

main ()
<commit_msg>exchange-capabilities.js minor cleanup #10886<commit_after>"use strict";

const csv = process.argv.includes ('--csv')
    , delimiter = csv ? ',' : '|'
    , ccxt = require ('../../ccxt.js')
    , asTableConfig = { delimiter: ' ' + delimiter + ' ', /* print: require ('string.ify').noPretty  */ }
    , asTable = require ('as-table').configure (asTableConfig)
    , log = require ('ololog').noLocate
    , ansi = require ('ansicolor').nice

console.log (ccxt.iso8601 (ccxt.milliseconds ()))
console.log ('CCXT v' + ccxt.version)
const isWindows = process.platform == 'win32' // fix for windows, as it doesn't show darkred-VS-red well enough

async function main () {

    let total = 0
    let notImplemented = 0
    let inexistentApi = 0
    let implemented = 0
    let emulated = 0

    const exchanges = ccxt.exchanges.map (id => new ccxt[id] ())
    const metainfo = ccxt.flatten (exchanges.map (exchange => Object.keys (exchange.has)))
    const reduced = metainfo.reduce ((previous, current) => {
        previous[current] = (previous[current] || 0) + 1
        return previous
    }, {})
    const unified = Object.entries (reduced).filter (([ _, count ]) => count > 1)
    const methods = unified.map (([ method, _ ]) => method).sort ()
    const table = asTable (exchanges.map (exchange => {
        let result = {};
        const basics = [
            'publicAPI',
            'privateAPI',
            'CORS',
            'margin',
            'swap',
            'future',
            'CORS',
        ];

        ccxt.unique (basics.concat (methods)).forEach (key => {

            total += 1

            let coloredString = '';

            const feature = exchange.has[key]

            if (feature === false) {
                // if explicitly set to 'false' in exchange.has (to exclude mistake, we check if it's undefined too)
                coloredString = isWindows ? exchange.id.lightMagenta : exchange.id.red
                inexistentApi += 1
            } else if (feature === 'emulated') {
                // if explicitly set to 'emulated' in exchange.has
                coloredString = exchange.id.yellow
                emulated += 1
            } else if (feature) {
                // if neither 'false' nor 'emulated', and if  method exists
                coloredString = exchange.id.green
                implemented += 1
            } else {
                coloredString = isWindows ? exchange.id.red : exchange.id.red.dim
                notImplemented += 1
            }

            result[key] = coloredString
        })

        return result
    }))

    if (csv) {
        let lines = table.split ("\n")
        lines = lines.slice (0, 1).concat (lines.slice (2))
        log (lines.join ("\n"))
    } else {
        log (table)
    }

    log ('Summary: ',
        ccxt.exchanges.length.toString (), 'exchanges; ',
        'Methods [' + total.toString () + ' total]: ',
        implemented.toString ().green, 'implemented,',
        emulated.toString ().yellow, 'emulated,',
        (isWindows ? inexistentApi.toString ().lightMagenta : inexistentApi.toString ().red), 'inexistentApi,',
        (isWindows ? notImplemented.toString ().red : notImplemented.toString ().red.dim), 'notImplemented',
    )

    log("\nMessy? Try piping to less (e.g. node script.js | less -S -R)\n".red)

}

main ()
<|endoftext|>


<commit_before>import React, { PropTypes } from "react";

import Label from "./components/Label";

export default class Checkbox extends React.Component {

  state = {
    status: false,
    error: false
  }

  validate = (event) => {
    const value = event.target.value;

    if (!value) {
      this.setState({
        active: false,
        error: false
      });
    }

    if (this.props.validation && typeof(this.props.validation) === "function") {
      this.setState({
        error: !this.props.validation(value)
      });

    }
  }

  setStatus = (message) => {
    this.props.status = message;
  }

  disabled = () => {
    if (this.props.disabled) {
      return disabled;
    }
  }

  renderHelpText(message) {

    if ((this.state.error && this.props.errorText) || this.state.status) {

      return (

          {this.props.errorText || this.state.status}

      );
    }

  }

  render () {
    let inputclasses = [
      "input"
    ];

    // theme overwrite
    if (this.props.theme) { inputclasses = this.props.theme }
    // state mangaged classes
    if (this.state.status) { inputclasses.push("push-double-bottom") }

    if (this.props.type) {
      inputclasses.push(this.props.type);
    } else {
      inputclasses.push("checkbox");
    }

    if (this.props.error) { inputclasses.push("input--alert") }
    // custom added classes
    if (this.props.classes) { inputclasses = inputclasses.concat(this.props.classes) }

    return (

            {this.props.children}

        <input
            ref={this.props.id || this.props.label || this.props.name}
            id={this.props.id || this.props.label || this.props.name}
            type={this.props.type || "checkbox"}
            name={this.props.name || this.props.label}
            className={this.props.inputClasses}
            disabled={this.disabled()}
            defaultChecked={this.props.defaultValue ? "checked": ""}
            onClick={this.props.clicked}
            style={{width: 0}}
        />

        {(() => {
          if (!this.props.hideLabel){
            return (

            );
          }
        })()}

        {this.renderHelpText()}

    );
  }
}
<commit_msg>fixed reference to disabled and removed ref from checkbox<commit_after>import React, { PropTypes } from "react";

import Label from "./components/Label";

export default class Checkbox extends React.Component {

  state = {
    status: false,
    error: false
  }

  validate = (event) => {
    const value = event.target.value;

    if (!value) {
      this.setState({
        active: false,
        error: false
      });
    }

    if (this.props.validation && typeof(this.props.validation) === "function") {
      this.setState({
        error: !this.props.validation(value)
      });

    }
  }

  setStatus = (message) => {
    this.props.status = message;
  }

  disabled = () => {
    if (this.props.disabled) {
      return this.props.disabled;
    }
  }

  renderHelpText(message) {

    if ((this.state.error && this.props.errorText) || this.state.status) {

      return (

          {this.props.errorText || this.state.status}

      );
    }

  }

  render () {
    let inputclasses = [
      "input"
    ];

    // theme overwrite
    if (this.props.theme) { inputclasses = this.props.theme }
    // state mangaged classes
    if (this.state.status) { inputclasses.push("push-double-bottom") }

    if (this.props.type) {
      inputclasses.push(this.props.type);
    } else {
      inputclasses.push("checkbox");
    }

    if (this.props.error) { inputclasses.push("input--alert") }
    // custom added classes
    if (this.props.classes) { inputclasses = inputclasses.concat(this.props.classes) }

    return (

            {this.props.children}

        <input
            id={this.props.id || this.props.label || this.props.name}
            type={this.props.type || "checkbox"}
            name={this.props.name || this.props.label}
            className={this.props.inputClasses}
            disabled={this.disabled()}
            defaultChecked={this.props.defaultValue ? "checked": ""}
            onClick={this.props.clicked}
            style={{width: 0}}
        />

        {(() => {
          if (!this.props.hideLabel){
            return (

            );
          }
        })()}

        {this.renderHelpText()}

    );
  }
}
<|endoftext|>


<commit_before>'use strict'

const Sequelize = require('sequelize')

module.exports = db => db.define('reviews', {
  body: Sequelize.TEXT,
  validate: {
    len: {
      args: 30,
      msg: 'Review must be 30 characters in length'
    }
  }
})

module.exports.associations = (Review, {Product, User}) => {
  Review.belongsToMany(Product, {through: 'ProductReviews'})
  Review.belongsToMany(User, {through: 'UserReviews'})
}

// or this can be in Product / User models where Product.hasMany(Review) and User.hasMany(Review)
<commit_msg>refactor: refactor model<commit_after>'use strict'

const {TEXT} = require('sequelize')

module.exports = db => db.define('reviews', {
  body: {
    type: TEXT,
    validate: {
      len: {
        args: 30,
        msg: 'Review must be 30 characters in length'
      }
    }
  }
})

module.exports.associations = (Review, {Product, User}) => {
  Review.belongsToMany(Product, {through: 'ProductReviews'})
  Review.belongsToMany(User, {through: 'UserReviews'})
}

// or this can be in Product / User models where Product.hasMany(Review) and User.hasMany(Review)
<|endoftext|>


<commit_before>import Ember from 'ember';
import Sortable from 'ui/mixins/sortable';
import C from 'ui/utils/constants';

const notUser = [C.EXTERNALID.KIND_KUBERNETES, C.EXTERNALID.KIND_SYSTEM];

export default Ember.Controller.extend(Sortable, {
  environments: Ember.inject.controller(),
  projects: Ember.inject.service(),
  sortableContent: Ember.computed.alias('filteredStacks'),
  prefs: Ember.inject.service(),

  which: 'user',
  queryParams: ['which'],
  showAddtlInfo: false,
  selectedService: null,

  actions: {
    showAddtlInfo: function(service) {
      this.set('selectedService', service);
      this.set('showAddtlInfo', true);
    },
    dismiss: function() {
      this.set('showAddtlInfo', false);
      this.set('selectedService', null);
    },
    sortResults: function(name) {
      this.get('prefs').set(C.PREFS.SORT_STACKS_BY, name);
      this.send('setSort', name);
    }
  },

  setup: function() {
    var sort = this.get(`prefs.${C.PREFS.SORT_STACKS_BY}`);
    if (sort && sort !== this.get('sortBy')) {
      this.set('sortBy', sort);
    }
  }.on('init'),

  filteredStacks: function() {
    var which = this.get('which');
    var all = this.get('model');
    var out;

    var kubernetes = all.filterBy('externalIdInfo.kind', C.EXTERNALID.KIND_KUBERNETES);
    var system     = all.filterBy('externalIdInfo.kind', C.EXTERNALID.KIND_SYSTEM);
    var user       = all.filter((obj) => {
        return notUser.indexOf(obj.get('externalIdInfo.kind')) === -1;
      });

    if ( which === C.EXTERNALID.KIND_ALL )
    {
      out = all;
    }
    else if ( which === C.EXTERNALID.KIND_KUBERNETES )
    {
      out = kubernetes;
    }
    else if ( which === C.EXTERNALID.KIND_SYSTEM )
    {
      out = system;
    }
    else
    {
      out = user;
    }

    return out;
  }.property('model.[]'),

  sortBy: 'state',
  sorts: {
    state: ['stateSort','name','id'],
    name: ['name','id']
  },

});
<commit_msg>Fix k8s display<commit_after>import Ember from 'ember';
import Sortable from 'ui/mixins/sortable';
import C from 'ui/utils/constants';

const notUser = [C.EXTERNALID.KIND_KUBERNETES, C.EXTERNALID.KIND_SYSTEM];

export default Ember.Controller.extend(Sortable, {
  environments: Ember.inject.controller(),
  projects: Ember.inject.service(),
  sortableContent: Ember.computed.alias('filteredStacks'),
  prefs: Ember.inject.service(),

  which: 'user',
  queryParams: ['which'],
  showAddtlInfo: false,
  selectedService: null,

  actions: {
    showAddtlInfo: function(service) {
      this.set('selectedService', service);
      this.set('showAddtlInfo', true);
    },
    dismiss: function() {
      this.set('showAddtlInfo', false);
      this.set('selectedService', null);
    },
    sortResults: function(name) {
      this.get('prefs').set(C.PREFS.SORT_STACKS_BY, name);
      this.send('setSort', name);
    }
  },

  setup: function() {
    var sort = this.get(`prefs.${C.PREFS.SORT_STACKS_BY}`);
    if (sort && sort !== this.get('sortBy')) {
      this.set('sortBy', sort);
    }
  }.on('init'),

  filteredStacks: function() {
    var which = this.get('which');
    var all = this.get('model');
    var out;

    var kubernetes = all.filterBy('externalIdInfo.kind', C.EXTERNALID.KIND_KUBERNETES);
    var system     = all.filterBy('externalIdInfo.kind', C.EXTERNALID.KIND_SYSTEM);
    var user       = all.filter((obj) => {
        return notUser.indexOf(obj.get('externalIdInfo.kind')) === -1;
      });

    if ( which === C.EXTERNALID.KIND_ALL )
    {
      out = all;
    }
    else if ( which === C.EXTERNALID.KIND_KUBERNETES )
    {
      out = kubernetes;
    }
    else if ( which === C.EXTERNALID.KIND_SYSTEM )
    {
      out = system;
    }
    else
    {
      out = user;
    }

    return out;
  }.property('model.[]','which'),

  sortBy: 'state',
  sorts: {
    state: ['stateSort','name','id'],
    name: ['name','id']
  },

});
<|endoftext|>


<commit_before><commit_msg>add progress bar on preload view<commit_after><|endoftext|>


<commit_before>'use strict';

const uuid = require('uuid');
const _ = require('lodash');
const url = require('url');
const qs = require('querystring');
const mime = require('mimelib');
const Odata = require('./odata');
const util = require('util');
const Expression = require('./expression');

var Batch = function(parent)
{
  this.parent = parent;
  this.boundary = `batch_${uuid.v4()}`;
  this.ops = [];
  this.reset();
  return this;
};

util.inherits(Batch, Odata);

Batch.prototype.addPathComponent = function(component)
{
  this.url.addPathComponent(component);
};

Batch.prototype.addQueryParameter = function(name, value)
{
  this.url.addQueryParameter(name, value);
};

Batch.prototype.reset = function()
{
  if(this.parent._filter) {
    this._filter = new Expression(this.parent._filter);
  } else {
    delete this._filter;
  }
  if(this.parent._select) {
    this._select = _.slice(this.parent._select);
  } else {
    delete this._select;
  }
  this._count = this.parent._count;
  if(this.parent._order) {
    this._order = this.prent._order;
  } else {
    delete this._order;
  }
  if(this.parent._expand) {
    this._expand = this.parent._expand;
  } else {
    delete this._expand;
  }
  if(this.parent._search) {
    this._search = this.parent._search;
  } else {
    delete this._search;
  }
  this.config = this.parent.config;
  this.url = this.parent.url.clone();
};

var process = function(method, options, body)
{
  options = options || {};
  if(method === 'GET') {
    delete this._changeset;
  } else {
    this._changeset = this._changeset || `changeset_${uuid.v4()}`;
  }
  if(options.qs) {
    this.url.addQueryParameters(options.qs);
  }
  return {
    method: method,
    query: this.query(),
    headers: options.headers || {},
    body: body,
    changeset: this._changeset
  }
};

Batch.prototype.get = function(options)
{
  this.ops.push(process.call(this, 'GET', options));
  this.reset();
  return;
};

Batch.prototype.post = function(body, options)
{
  this.ops.push(process.call(this, 'POST', options, body));
  this.reset();
  return;
}

Batch.prototype.put = function(body, options)
{
  this.ops.push(process.call(this, 'PUT', options, body));
  this.reset();
  return;
}

Batch.prototype.patch = function(body, options)
{
  this.ops.push(process.call(this, 'PATCH', options, body));
  this.reset();
  return;
}

Batch.prototype.delete = function(options)
{
  this.ops.push(process.call(this, 'DELETE', options));
  this.reset();
  return;
};

Batch.prototype.body = function()
{
  var msg = `--${this.boundary}\r\n`;
  var last_changeset = '';
  for(let op of this.ops) {
    if(op.changeset) {
      if(op.changeset != last_changeset) {
        if(last_changeset) {
          msg += `--${last_changeset}--\r\n`;
        }
        msg += `Content-Type: multipart/mixed; boundary=${op.changeset}\r\n`;
        msg += 'Content-Transfer-Encoding: binary\r\n\r\n';
        msg += `--${op.changeset}\r\n`;
      }
    } else {
      if(last_changeset) {
        msg += `--${last_changeset}--\r\n`;
      }
      msg += `--${this.boundary}\r\n`;
    }
    last_changeset = op.changeset;
    msg += 'Content-Type: application/http\r\n';
    msg += 'Content-Transfer-Encoding: binary\r\n\r\n';
    msg += `${op.method} ${op.query} HTTP/1.1\r\n`;
    _.forOwn(op.headers, function(v, k) {
      msg += mime.foldLine(`${k}: ${v}`, 76) + '\r\n';
    });
    let body = '';
    if(op.body) {
      let buf = '';
      if(op.headers['Content-Type'] === undefined || _.isPlainObject(op.body)) {
        msg += 'Content-Type: application/json\r\n';
        //msg += 'Content-Transfer-Encoding: binary\r\n';
        buf = JSON.stringify(op.body);
      } else {
        msg += `Content-Type: ${op.headers['Content-Type']}\r\n`;
        //msg += 'Content-Transfer-Encoding: binary\r\n';
        buf = op.body.toString();
      }

      body = `${buf}`;
    }
    msg += `Content-Length: ${body.length}\r\n\r\n${body}\r\n`;
  }
  if(last_changeset) {
    msg += `--${last_changeset}--\r\n`;
  }
  msg += `--${this.boundary}--\r\n`;
  return msg;
};

module.exports = function(q)
{
  return new Batch(q);
};

<commit_msg>Fix mime boundaries<commit_after>'use strict';

const uuid = require('uuid');
const _ = require('lodash');
const url = require('url');
const qs = require('querystring');
const mime = require('mimelib');
const Odata = require('./odata');
const util = require('util');
const Expression = require('./expression');

var Batch = function(parent)
{
  this.parent = parent;
  this.boundary = `batch_${uuid.v4()}`;
  this.ops = [];
  this.reset();
  return this;
};

util.inherits(Batch, Odata);

Batch.prototype.addPathComponent = function(component)
{
  this.url.addPathComponent(component);
};

Batch.prototype.addQueryParameter = function(name, value)
{
  this.url.addQueryParameter(name, value);
};

Batch.prototype.reset = function()
{
  if(this.parent._filter) {
    this._filter = new Expression(this.parent._filter);
  } else {
    delete this._filter;
  }
  if(this.parent._select) {
    this._select = _.slice(this.parent._select);
  } else {
    delete this._select;
  }
  this._count = this.parent._count;
  if(this.parent._order) {
    this._order = this.prent._order;
  } else {
    delete this._order;
  }
  if(this.parent._expand) {
    this._expand = this.parent._expand;
  } else {
    delete this._expand;
  }
  if(this.parent._search) {
    this._search = this.parent._search;
  } else {
    delete this._search;
  }
  this.config = this.parent.config;
  this.url = this.parent.url.clone();
};

var process = function(method, options, body)
{
  options = options || {};
  if(method === 'GET') {
    delete this._changeset;
  } else {
    this._changeset = this._changeset || `changeset_${uuid.v4()}`;
  }
  if(options.qs) {
    this.url.addQueryParameters(options.qs);
  }
  return {
    method: method,
    query: this.query(),
    headers: options.headers || {},
    body: body,
    changeset: this._changeset
  }
};

Batch.prototype.get = function(options)
{
  this.ops.push(process.call(this, 'GET', options));
  this.reset();
  return;
};

Batch.prototype.post = function(body, options)
{
  this.ops.push(process.call(this, 'POST', options, body));
  this.reset();
  return;
}

Batch.prototype.put = function(body, options)
{
  this.ops.push(process.call(this, 'PUT', options, body));
  this.reset();
  return;
}

Batch.prototype.patch = function(body, options)
{
  this.ops.push(process.call(this, 'PATCH', options, body));
  this.reset();
  return;
}

Batch.prototype.delete = function(options)
{
  this.ops.push(process.call(this, 'DELETE', options));
  this.reset();
  return;
};

Batch.prototype.body = function()
{
  var msg = '';
  var last_changeset = '';
  for(let op of this.ops) {
    if(op.changeset) {
      if(op.changeset != last_changeset) {
        if(last_changeset) {
          msg += `--${last_changeset}--\r\n`;
        }
        msg += `--${this.boundary}\r\n`;
        msg += `Content-Type: multipart/mixed; boundary=${op.changeset}\r\n`;
        msg += 'Content-Transfer-Encoding: binary\r\n\r\n';
      }
      msg += `--${op.changeset}\r\n`;
    } else {
      if(last_changeset) {
        msg += `--${last_changeset}--\r\n`;
      }
      msg += `--${this.boundary}\r\n`;
    }
    last_changeset = op.changeset;
    msg += 'Content-Type: application/http\r\n';
    msg += 'Content-Transfer-Encoding: binary\r\n\r\n';
    msg += `${op.method} ${op.query} HTTP/1.1\r\n`;
    _.forOwn(op.headers, function(v, k) {
      msg += mime.foldLine(`${k}: ${v}`, 76) + '\r\n';
    });
    let body = '';
    if(op.body) {
      let buf = '';
      if(op.headers['Content-Type'] === undefined || _.isPlainObject(op.body)) {
        msg += 'Content-Type: application/json\r\n';
        //msg += 'Content-Transfer-Encoding: binary\r\n';
        buf = JSON.stringify(op.body);
      } else {
        msg += `Content-Type: ${op.headers['Content-Type']}\r\n`;
        //msg += 'Content-Transfer-Encoding: binary\r\n';
        buf = op.body.toString();
      }

      body = `${buf}`;
    }
    msg += `Content-Length: ${body.length}\r\n\r\n${body}\r\n`;
  }
  if(last_changeset) {
    msg += `--${last_changeset}--\r\n`;
  }
  if(this.ops.length > 0) {
    msg += `--${this.boundary}--\r\n`;
  }
  return msg;
};

module.exports = function(q)
{
  return new Batch(q);
};

<|endoftext|>


<commit_before>define(['jquery', 'jquery.exists'], function() {

  'use strict';

  var <%= _.classify(name) %> = {
    cacheElements: function() {
    },
    init: function() {
      this.cacheElements();
      this.bindEvents();
    },
    bindEvents: function() {
    }
  };

  <%= _.classify(name) %>.init();

  // return {
  //   : <%= _.classify(name) %>.
  // };

});
<commit_msg>[Bugfix] add cached jquery object and exits function closes #28<commit_after>define(['jquery', 'jquery.exists'], function() {

  'use strict';

  var <%= _.classify(name) %> = {
    cacheElements: function() {
      this.$<%= _.underscored(name) %> = $('.<%= _.slugify(name) %>')
    },
    init: function() {
      this.cacheElements();

      this.$<%= _.underscored(name) %>.exists(function() {
        this.bindEvents();
      });
    },
    bindEvents: function() {
    }
  };

  <%= _.classify(name) %>.init();

  // return {
  //   : <%= _.classify(name) %>.
  // };

});
<|endoftext|>


<commit_before>window.lcl = window.lcl ? window.lcl : {};
window.lcl.topics = {
    greetings: ['hello', 'hi', 'morning', 'afternoon', 'evening'],
    sports: ['hockey', 'football', 'cricket', 'soccer'],
    music: ['rock', 'rap', 'country'],
    languages: ['American', 'Spanglish', 'African', 'German'],
    goodsoccerteams: ['Arsenal', 'Manchester'],
    fruit: ['Apple', 'Pear', 'Orange', 'Banana']
}<commit_msg>Adding additional test data: Diffusion<commit_after>window.lcl = window.lcl ? window.lcl : {};
window.lcl.topics = {
    greetings: ['hello', 'hi', 'morning', 'afternoon', 'evening'],
    sports: ['hockey', 'football', 'cricket', 'soccer'],
    music: ['rock', 'rap', 'country'],
    languages: ['American', 'Spanglish', 'African', 'German'],
    goodsoccerteams: ['Arsenal', 'Manchester'],
    fruit: ['Apple', 'Pear', 'Orange', 'Banana'],
    diffusion: ['continuous','unpredictable','random','flow','equilibrium','predictable','visible','independent','backwards','concentration','ratio','percent','dynamic','inanimate','intend','intention','collective','uniform','simultaneous']
};<|endoftext|>


<commit_before>/* globals gitHubInjection */
'use strict';
const path = location.pathname;
const isDashboard = path === '/';
const isRepo = /^\/[^/]+\/[^/]+/.test(path);
const username = path.split('/')[1];
const repoName = path.split('/')[2];
const isPR = () => /^\/[^/]+\/[^/]+\/pull\/\d+$/.test(location.pathname);
const isReleases = () => isRepo && /^\/[^/]+\/[^/]+\/(releases|tags)/.test(location.pathname);
const getUsername = () => $('meta[name="user-login"]').attr('content');

function linkifyBranchRefs() {
	$('.commit-ref').each((i, el) => {
		const parts = $(el).find('.css-truncate-target');
		let username = parts.eq(0).text();
		let branch = parts.eq(1).text();

		// forked repos can have their name changed; grab it from first commit in PR
		const branchRepo = path.includes(username) ? repoName : $('.commit-id').attr('href').split('/')[2];

		// both branches are from the current repo
		if (!branch) {
			branch = username;
			username = getUsername();
		}

		$(el).wrap(`<a href="https://github.com/${username}/${branchRepo}/tree/${branch}">`);
	});
}

function addReleasesTab() {
	const $repoNav = $('.js-repo-nav');
	let $releasesTab = $repoNav.children('[data-selected-links~="repo_releases"]');
	const hasReleases = $releasesTab.length > 0;

	if (!hasReleases) {
		$releasesTab = $(`
			<svg class="octicon octicon-tag" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path d="M6.73 2.73c-0.47-0.47-1.11-0.73-1.77-0.73H2.5C1.13 2 0 3.13 0 4.5v2.47c0 0.66 0.27 1.3 0.73 1.77l6.06 6.06c0.39 0.39 1.02 0.39 1.41 0l4.59-4.59c0.39-0.39 0.39-1.02 0-1.41L6.73 2.73zM1.38 8.09c-0.31-0.3-0.47-0.7-0.47-1.13V4.5c0-0.88 0.72-1.59 1.59-1.59h2.47c0.42 0 0.83 0.16 1.13 0.47l6.14 6.13-4.73 4.73L1.38 8.09z m0.63-4.09h2v2H2V4z"></path></svg>
			Releases
		`);
	}

	if (isReleases()) {
		$repoNav.find('.selected')
			.removeClass('js-selected-navigation-item selected');

		$releasesTab.addClass('js-selected-navigation-item selected');
	}

	if (!hasReleases) {
		$repoNav.append($releasesTab);
	}
}

document.addEventListener('DOMContentLoaded', () => {
	const username = getUsername();

	if (isDashboard) {
		// hide other users starring/forking your repos
		{
			const hideStarsOwnRepos = () => {
				$('#dashboard .news .watch_started, #dashboard .news .fork')
					.has(`.title a[href^="/${username}"`)
					.css('display', 'none');
			};

			hideStarsOwnRepos();

			new MutationObserver(() => hideStarsOwnRepos())
				.observe($('#dashboard .news').get(0), {childList: true});
		}

		// expand all the news feed pages
		(function more() {
			const btn = $('.ajax-pagination-btn').get(0);

			if (!btn) {
				return;
			}

			btn.click();
			setTimeout(more, 200);
		})();
	}

	if (isRepo) {
		gitHubInjection(window, {wait: 1}, () => {
			addReleasesTab();

			if (isPR()) {
				linkifyBranchRefs();
			}
		});
	}
});
<commit_msg>Close #21 PR: Improve branch name assignment. Fixes #18<commit_after>/* globals gitHubInjection */
'use strict';
const path = location.pathname;
const isDashboard = path === '/';
const isRepo = /^\/[^/]+\/[^/]+/.test(path);
const ownerName = path.split('/')[1];
const repoName = path.split('/')[2];
const isPR = () => /^\/[^/]+\/[^/]+\/pull\/\d+$/.test(location.pathname);
const isReleases = () => isRepo && /^\/[^/]+\/[^/]+\/(releases|tags)/.test(location.pathname);
const getUsername = () => $('meta[name="user-login"]').attr('content');

function linkifyBranchRefs() {
	$('.commit-ref').each((i, el) => {
		const parts = $(el).find('.css-truncate-target');
		let branch = parts.eq(parts.length - 1).text();
		let username = ownerName;

		// if there are two parts the first part is the username
		if (parts.length > 1) {
			username = parts.eq(0).text();
		}

		// forked repos can have their name changed; grab it from first commit in PR
		const branchRepo = path.includes(username) ? repoName : $('.commit-id').attr('href').split('/')[2];

		$(el).wrap(`<a href="https://github.com/${username}/${branchRepo}/tree/${branch}">`);
	});
}

function addReleasesTab() {
	const $repoNav = $('.js-repo-nav');
	let $releasesTab = $repoNav.children('[data-selected-links~="repo_releases"]');
	const hasReleases = $releasesTab.length > 0;

	if (!hasReleases) {
		$releasesTab = $(`
			<svg class="octicon octicon-tag" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path d="M6.73 2.73c-0.47-0.47-1.11-0.73-1.77-0.73H2.5C1.13 2 0 3.13 0 4.5v2.47c0 0.66 0.27 1.3 0.73 1.77l6.06 6.06c0.39 0.39 1.02 0.39 1.41 0l4.59-4.59c0.39-0.39 0.39-1.02 0-1.41L6.73 2.73zM1.38 8.09c-0.31-0.3-0.47-0.7-0.47-1.13V4.5c0-0.88 0.72-1.59 1.59-1.59h2.47c0.42 0 0.83 0.16 1.13 0.47l6.14 6.13-4.73 4.73L1.38 8.09z m0.63-4.09h2v2H2V4z"></path></svg>
			Releases
		`);
	}

	if (isReleases()) {
		$repoNav.find('.selected')
			.removeClass('js-selected-navigation-item selected');

		$releasesTab.addClass('js-selected-navigation-item selected');
	}

	if (!hasReleases) {
		$repoNav.append($releasesTab);
	}
}

document.addEventListener('DOMContentLoaded', () => {
	const username = getUsername();

	if (isDashboard) {
		// hide other users starring/forking your repos
		{
			const hideStarsOwnRepos = () => {
				$('#dashboard .news .watch_started, #dashboard .news .fork')
					.has(`.title a[href^="/${username}"`)
					.css('display', 'none');
			};

			hideStarsOwnRepos();

			new MutationObserver(() => hideStarsOwnRepos())
				.observe($('#dashboard .news').get(0), {childList: true});
		}

		// expand all the news feed pages
		(function more() {
			const btn = $('.ajax-pagination-btn').get(0);

			if (!btn) {
				return;
			}

			btn.click();
			setTimeout(more, 200);
		})();
	}

	if (isRepo) {
		gitHubInjection(window, {wait: 1}, () => {
			addReleasesTab();

			if (isPR()) {
				linkifyBranchRefs();
			}
		});
	}
});
<|endoftext|>


<commit_before>function FamodulusClient(servers, brief) {
    'use strict';
    this.servers = servers;
    this.brief = typeof brief === 'undefined' ? true : brief;
}

FamodulusClient.prototype._request = function (query, callback) {
    'use strict';
    query.brief = this.brief;
    var req = new XMLHttpRequest();
    req.addEventListener('load', function () {
        var res = JSON.parse(this.responseText);
        if (res.modexps.length === 1) {
            callback(res.modexps[0]);
        } else {
            callback(res.modexps);
        }
    });

    req.open('POST', this.servers[0]);
    req.setRequestHeader('Content-type', 'application/json');
    req.send(JSON.stringify(query));
};

FamodulusClient.prototype.modexp = function (base, exponent, modulus, callback) {
    'use strict';
    this._request({modexps: [{b: base, e: exponent, m: modulus}]}, callback);
};

FamodulusClient.prototype.modexps = function () {
    'use strict';
    var modexps = arguments[0];
    var defaultBase;
    var defaultExponent;
    var defaultModulus;
    var callback;

    if (arguments.length === 2) {
        defaultBase = undefined;
        defaultExponent = undefined;
        defaultModulus = undefined;
        callback = arguments[1];
    } else if (arguments.length === 5) {
        defaultBase = arguments[1];
        defaultExponent = arguments[2];
        defaultModulus = arguments[3];
        callback = arguments[4];
    }

    var queryModexps = [];
    for (var i = 0; i < modexps.length; i++) {
        queryModexps.push({b: modexps[i][0], e: modexps[i][1], m: modexps[i][2]});
    }
    this._request({b: defaultBase, e: defaultExponent, m: defaultModulus, modexps: queryModexps}, callback);
};

FamodulusClient.prototype.decExponent = function (uStr, aStr, pStr, callback) {
    'use strict';
    var self = this;
    var BI = require('BigInt');

    var zero = BI.str2bigInt('0', 16, 0);
console.log("zero: " + BI.bigInt2str(zero,16));
    var one = BI.str2bigInt('1', 16, 0);
console.log("one: " + BI.bigInt2str(one,16));
    var a = BI.str2bigInt(aStr, 16, 0);
console.log("a: " + BI.bigInt2str(a,16));
    var p = BI.str2bigInt(pStr, 16, 0);
console.log("p: " + BI.bigInt2str(p,16));
    var q = BI.sub(p, one);     // q = p-1
console.log("q: " + BI.bigInt2str(q,16));

    var qbits = BI.bitSize(q) < 8 ? 8 : BI.bitSize(q);
    var b = BI.randBigInt(qbits,1);
    while (BI.greater(b, q) || BI.equals(b, q) || BI.equals(b,zero)) {
        b = BI.randBigInt(qbits);
    }
console.log("b: " + BI.bigInt2str(b,16));

    var temp = BI.sub(BI.add(a,q), b);
console.log("a-b:" + BI.bigInt2str(temp,16));

    var c = BI.mod(temp, q);
console.log("c: " + BI.bigInt2str(c,16));
    var resultB, resultC;

// @todo randomize servers
    self.modexp(uStr, BI.bigInt2str(b,16), pStr, function (result) {
console.log("u: " + uStr + " b: " + BI.bigInt2str(b,16) + " p: " + pStr + " = " + result.r);
        resultB = result.r;
        if (typeof resultC !== 'undefined') {
            callback({r: BI.bigInt2str(BI.multMod(BI.str2bigInt(resultB, 16, 0), BI.str2bigInt(resultC, 16, 0), p),16)});
            resultC = undefined;
        }
    });
    self.modexp(uStr, BI.bigInt2str(c,16), pStr, function (result) {
console.log("u: " + uStr + " c: " + BI.bigInt2str(c,16) + " p: " + pStr + " = " + result.r);
        resultC = result.r;
        if (typeof resultB !== 'undefined') {
            callback({r: BI.bigInt2str(BI.multMod(BI.str2bigInt(resultB, 16, 0), BI.str2bigInt(resultC, 16, 0), p),16)});
            resultB = undefined;
        }
    });
};

FamodulusClient.prototype.decsExponent = function (u, a, p, callback) {
    'use strict';
    console.log('Not yet implemented!');
};

if (typeof module !== 'undefined' && module.hasOwnProperty('exports')) {
    module.exports = FamodulusClient;
}<commit_msg>removed logging, formatted<commit_after>function FamodulusClient(servers, brief) {
    'use strict';
    this.servers = servers;
    this.brief = typeof brief === 'undefined' ? true : brief;
}

FamodulusClient.prototype._request = function (query, callback) {
    'use strict';
    query.brief = this.brief;
    var req = new XMLHttpRequest();
    req.addEventListener('load', function () {
        var res = JSON.parse(this.responseText);
        if (res.modexps.length === 1) {
            callback(res.modexps[0]);
        } else {
            callback(res.modexps);
        }
    });

    req.open('POST', this.servers[0]);
    req.setRequestHeader('Content-type', 'application/json');
    req.send(JSON.stringify(query));
};

FamodulusClient.prototype.modexp = function (base, exponent, modulus, callback) {
    'use strict';
    this._request({modexps: [{b: base, e: exponent, m: modulus}]}, callback);
};

FamodulusClient.prototype.modexps = function () {
    'use strict';
    var modexps = arguments[0];
    var defaultBase;
    var defaultExponent;
    var defaultModulus;
    var callback;

    if (arguments.length === 2) {
        defaultBase = undefined;
        defaultExponent = undefined;
        defaultModulus = undefined;
        callback = arguments[1];
    } else if (arguments.length === 5) {
        defaultBase = arguments[1];
        defaultExponent = arguments[2];
        defaultModulus = arguments[3];
        callback = arguments[4];
    }

    var queryModexps = [];
    for (var i = 0; i < modexps.length; i++) {
        queryModexps.push({b: modexps[i][0], e: modexps[i][1], m: modexps[i][2]});
    }
    this._request({b: defaultBase, e: defaultExponent, m: defaultModulus, modexps: queryModexps}, callback);
};

FamodulusClient.prototype.decExponent = function (uStr, aStr, pStr, callback) {
    'use strict';
    var self = this;
    var BI = require('BigInt');

    var zero = BI.str2bigInt('0', 16, 0);
    var one = BI.str2bigInt('1', 16, 0);

    var a = BI.str2bigInt(aStr, 16, 0);
    var p = BI.str2bigInt(pStr, 16, 0);
    var q = BI.sub(p, one);                         // q = p-1

    var qbits = BI.bitSize(q) < 8 ? 8 : BI.bitSize(q);
    var b = BI.randBigInt(qbits, 1);
    while (BI.greater(b, q) || BI.equals(b, q) || BI.equals(b, zero)) {
        b = BI.randBigInt(qbits);
    }

    var c = BI.mod(BI.sub(BI.add(a, q), b), q);      // c = (a+q)-b mod q

    var resultB, resultC;

    // @todo randomize servers
    self.modexp(uStr, BI.bigInt2str(b, 16), pStr, function (result) {
        resultB = result.r;
        if (typeof resultC !== 'undefined') {
            callback({r: BI.bigInt2str(BI.multMod(BI.str2bigInt(resultB, 16, 0), BI.str2bigInt(resultC, 16, 0), p), 16)});
            resultC = undefined;
        }
    });
    self.modexp(uStr, BI.bigInt2str(c, 16), pStr, function (result) {
        resultC = result.r;
        if (typeof resultB !== 'undefined') {
            callback({r: BI.bigInt2str(BI.multMod(BI.str2bigInt(resultB, 16, 0), BI.str2bigInt(resultC, 16, 0), p), 16)});
            resultB = undefined;
        }
    });
};

FamodulusClient.prototype.decsExponent = function (u, a, p, callback) {
    'use strict';
    console.log('Not yet implemented!');
};

if (typeof module !== 'undefined' && module.hasOwnProperty('exports')) {
    module.exports = FamodulusClient;
}<|endoftext|>


<commit_before>/**
 * Loader for CTM encoded models generated by OpenCTM tools:
 *	http://openctm.sourceforge.net/
 *
 * Uses js-openctm library by Juan Mellado
 *	http://code.google.com/p/js-openctm/
 *
 * @author alteredq / http://alteredqualia.com/
 */

THREE.CTMLoader = function ( showStatus ) {

	THREE.Loader.call( this, showStatus );

};

THREE.CTMLoader.prototype = Object.create( THREE.Loader.prototype );

// Load multiple CTM parts defined in JSON

THREE.CTMLoader.prototype.loadParts = function( url, callback, parameters ) {

	parameters = parameters || {};

	var scope = this;

	var xhr = new XMLHttpRequest();

	var basePath = parameters.basePath ? parameters.basePath : this.extractUrlBase( url );

	xhr.onreadystatechange = function() {

		if ( xhr.readyState === 4 ) {

			if ( xhr.status === 200 || xhr.status === 0 ) {

				var jsonObject = JSON.parse( xhr.responseText );

				var materials = [], geometries = [], counter = 0;

				function callbackFinal( geometry ) {

					counter += 1;

					geometries.push( geometry );

					if ( counter === jsonObject.offsets.length ) {

						callback( geometries, materials );

					}

				}

				// init materials

				for ( var i = 0; i < jsonObject.materials.length; i ++ ) {

					materials[ i ] = scope.createMaterial( jsonObject.materials[ i ], basePath );

				}

				// load joined CTM file

				var partUrl = basePath + jsonObject.data;
				var parametersPart = { useWorker: parameters.useWorker, offsets: jsonObject.offsets };
				scope.load( partUrl, callbackFinal, parametersPart );

			}

		}

	}

	xhr.open( "GET", url, true );
	xhr.setRequestHeader( "Content-Type", "text/plain" );
	xhr.send( null );

};

// Load CTMLoader compressed models
//	- parameters
//		- url (required)
//		- callback (required)

THREE.CTMLoader.prototype.load = function( url, callback, parameters ) {

	parameters = parameters || {};

	var scope = this;

	var offsets = parameters.offsets !== undefined ? parameters.offsets : [ 0 ];

	var xhr = new XMLHttpRequest(),
		callbackProgress = null;

	var length = 0;

	xhr.onreadystatechange = function() {

		if ( xhr.readyState === 4 ) {

			if ( xhr.status === 200 || xhr.status === 0 ) {

				var binaryData = new Uint8Array(xhr.response);

				var s = Date.now();

				if ( parameters.useWorker ) {

					var worker = new Worker( "js/loaders/ctm/CTMWorker.js" );

					worker.onmessage = function( event ) {

						var files = event.data;

						for ( var i = 0; i < files.length; i ++ ) {

							var ctmFile = files[ i ];

							var e1 = Date.now();
							// console.log( "CTM data parse time [worker]: " + (e1-s) + " ms" );

							scope.createModel( ctmFile, callback );

							var e = Date.now();
							console.log( "model load time [worker]: " + (e-e1) + " ms, total: " + (e-s));

						}

					};

					worker.postMessage( { "data": binaryData, "offsets": offsets } );

				} else {

					for ( var i = 0; i < offsets.length; i ++ ) {

						var stream = new CTM.Stream( binaryData );
						stream.offset = offsets[ i ];

						var ctmFile = new CTM.File( stream );

						scope.createModel( ctmFile, callback );

					}

					//var e = Date.now();
					//console.log( "CTM data parse time [inline]: " + (e-s) + " ms" );

				}

			} else {

				console.error( "Couldn't load [" + url + "] [" + xhr.status + "]" );

			}

		} else if ( xhr.readyState === 3 ) {

			if ( callbackProgress ) {

				if ( length === 0 ) {

					length = xhr.getResponseHeader( "Content-Length" );

				}

				callbackProgress( { total: length, loaded: xhr.responseText.length } );

			}

		} else if ( xhr.readyState === 2 ) {

			length = xhr.getResponseHeader( "Content-Length" );

		}

	}

	xhr.open( "GET", url, true );
	xhr.responseType = "arraybuffer";

	xhr.send( null );

};

THREE.CTMLoader.prototype.createModel = function ( file, callback ) {

	var Model = function () {

		THREE.BufferGeometry.call( this );

		this.materials = [];

		var indices = file.body.indices,
		positions = file.body.vertices,
		normals = file.body.normals;

		var uvs, colors;

		var uvMaps = file.body.uvMaps;

		if ( uvMaps !== undefined && uvMaps.length > 0 ) {

			uvs = uvMaps[ 0 ].uv;

		}

		var attrMaps = file.body.attrMaps;

		if ( attrMaps !== undefined && attrMaps.length > 0 && attrMaps[ 0 ].name === 'Color' ) {

			colors = attrMaps[ 0 ].attr;

		}

		this.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ) );
		this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );

		if ( normals !== undefined ) {

			this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );

		}

		if ( uvs !== undefined ) {

			this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );

		}

		if ( colors !== undefined ) {

			this.addAttribute( 'color', new THREE.BufferAttribute( colors, 4 ) );

		}

	}

	Model.prototype = Object.create( THREE.BufferGeometry.prototype );

	var geometry = new Model();

	geometry.computeOffsets();

	// compute vertex normals if not present in the CTM model
	if ( geometry.attributes[ "normal" ] === undefined ) {
		geometry.computeVertexNormals();
	}

	callback( geometry );

};
<commit_msg>THREE.CTMLoader.load : new option to manage workers outside the laoder<commit_after>/**
 * Loader for CTM encoded models generated by OpenCTM tools:
 *	http://openctm.sourceforge.net/
 *
 * Uses js-openctm library by Juan Mellado
 *	http://code.google.com/p/js-openctm/
 *
 * @author alteredq / http://alteredqualia.com/
 */

THREE.CTMLoader = function ( showStatus ) {

	THREE.Loader.call( this, showStatus );

};

THREE.CTMLoader.prototype = Object.create( THREE.Loader.prototype );

// Load multiple CTM parts defined in JSON

THREE.CTMLoader.prototype.loadParts = function( url, callback, parameters ) {

	parameters = parameters || {};

	var scope = this;

	var xhr = new XMLHttpRequest();

	var basePath = parameters.basePath ? parameters.basePath : this.extractUrlBase( url );

	xhr.onreadystatechange = function() {

		if ( xhr.readyState === 4 ) {

			if ( xhr.status === 200 || xhr.status === 0 ) {

				var jsonObject = JSON.parse( xhr.responseText );

				var materials = [], geometries = [], counter = 0;

				function callbackFinal( geometry ) {

					counter += 1;

					geometries.push( geometry );

					if ( counter === jsonObject.offsets.length ) {

						callback( geometries, materials );

					}

				}

				// init materials

				for ( var i = 0; i < jsonObject.materials.length; i ++ ) {

					materials[ i ] = scope.createMaterial( jsonObject.materials[ i ], basePath );

				}

				// load joined CTM file

				var partUrl = basePath + jsonObject.data;
				var parametersPart = { useWorker: parameters.useWorker, offsets: jsonObject.offsets };
				scope.load( partUrl, callbackFinal, parametersPart );

			}

		}

	}

	xhr.open( "GET", url, true );
	xhr.setRequestHeader( "Content-Type", "text/plain" );
	xhr.send( null );

};

// Load CTMLoader compressed models
//	- parameters
//		- url (required)
//		- callback (required)

THREE.CTMLoader.prototype.load = function( url, callback, parameters ) {

	parameters = parameters || {};

	var scope = this;

	var offsets = parameters.offsets !== undefined ? parameters.offsets : [ 0 ];

	var xhr = new XMLHttpRequest(),
		callbackProgress = null;

	var length = 0;

	xhr.onreadystatechange = function() {

		if ( xhr.readyState === 4 ) {

			if ( xhr.status === 200 || xhr.status === 0 ) {

				var binaryData = new Uint8Array(xhr.response);

				var s = Date.now();

				if ( parameters.useWorker ) {

					var worker = parameters.worker || new Worker( "js/loaders/ctm/CTMWorker.js" );

					worker.onmessage = function( event ) {

						var files = event.data;

						for ( var i = 0; i < files.length; i ++ ) {

							var ctmFile = files[ i ];

							var e1 = Date.now();
							// console.log( "CTM data parse time [worker]: " + (e1-s) + " ms" );

							scope.createModel( ctmFile, callback );

							var e = Date.now();
							console.log( "model load time [worker]: " + (e-e1) + " ms, total: " + (e-s));

						}

					};

					worker.postMessage( { "data": binaryData, "offsets": offsets } );

				} else {

					for ( var i = 0; i < offsets.length; i ++ ) {

						var stream = new CTM.Stream( binaryData );
						stream.offset = offsets[ i ];

						var ctmFile = new CTM.File( stream );

						scope.createModel( ctmFile, callback );

					}

					//var e = Date.now();
					//console.log( "CTM data parse time [inline]: " + (e-s) + " ms" );

				}

			} else {

				console.error( "Couldn't load [" + url + "] [" + xhr.status + "]" );

			}

		} else if ( xhr.readyState === 3 ) {

			if ( callbackProgress ) {

				if ( length === 0 ) {

					length = xhr.getResponseHeader( "Content-Length" );

				}

				callbackProgress( { total: length, loaded: xhr.responseText.length } );

			}

		} else if ( xhr.readyState === 2 ) {

			length = xhr.getResponseHeader( "Content-Length" );

		}

	}

	xhr.open( "GET", url, true );
	xhr.responseType = "arraybuffer";

	xhr.send( null );

};

THREE.CTMLoader.prototype.createModel = function ( file, callback ) {

	var Model = function () {

		THREE.BufferGeometry.call( this );

		this.materials = [];

		var indices = file.body.indices,
		positions = file.body.vertices,
		normals = file.body.normals;

		var uvs, colors;

		var uvMaps = file.body.uvMaps;

		if ( uvMaps !== undefined && uvMaps.length > 0 ) {

			uvs = uvMaps[ 0 ].uv;

		}

		var attrMaps = file.body.attrMaps;

		if ( attrMaps !== undefined && attrMaps.length > 0 && attrMaps[ 0 ].name === 'Color' ) {

			colors = attrMaps[ 0 ].attr;

		}

		this.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ) );
		this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );

		if ( normals !== undefined ) {

			this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );

		}

		if ( uvs !== undefined ) {

			this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );

		}

		if ( colors !== undefined ) {

			this.addAttribute( 'color', new THREE.BufferAttribute( colors, 4 ) );

		}

	}

	Model.prototype = Object.create( THREE.BufferGeometry.prototype );

	var geometry = new Model();

	geometry.computeOffsets();

	// compute vertex normals if not present in the CTM model
	if ( geometry.attributes[ "normal" ] === undefined ) {
		geometry.computeVertexNormals();
	}

	callback( geometry );

};
<|endoftext|>


<commit_before>var {computed, when, h, Value} = require('mutant')
var nest = require('depnest')
var sustained = require('../../../lib/sustained')
const pull = require('pull-stream')

exports.gives = nest('app.html.progressNotifier')

exports.needs = nest({
  'sbot.pull.stream': 'first',
  'progress.html.render': 'first',
  'progress.obs': {
    indexes: 'first',
    replicate: 'first',
    migration: 'first'
  },
  'intl.sync.i18n': 'first'
})

exports.create = function (api) {
  const i18n = api.intl.sync.i18n
  return nest('app.html.progressNotifier', function (id) {
    var replicateProgress = api.progress.obs.replicate()
    var indexes = api.progress.obs.indexes()
    var migration = api.progress.obs.migration()
    var waiting = Waiting(replicateProgress)

    var pending = computed(indexes, (progress) => progress.target - progress.current || 0)
    var pendingMigration = computed(migration, (progress) => progress.target - progress.current || 0)

    var indexProgress = computed(indexes, calcProgress)
    var migrationProgress = computed(migration, calcProgress)

    var downloadProgress = computed([replicateProgress.feeds, replicateProgress.incompleteFeeds], (feeds, incomplete) => {
      if (feeds) {
        return clamp((feeds - incomplete) / feeds)
      } else {
        return 1
      }
    })

    var hidden = sustained(computed([waiting, replicateProgress.incompleteFeeds, pending, pendingMigration], (waiting, incomplete, pending, pendingMigration) => {
      return !waiting && incomplete < 5 && !pending && !pendingMigration
    }), 2000)

    // HACK: css animations take up WAY TO MUCH cpu, remove from dom when inactive
    var displaying = computed(sustained(hidden, 500, x => !x), hidden => !hidden)

    return h('div.info', { hidden }, [
      h('div.status', [
        when(displaying, h('Loading -small', [
          when(pendingMigration,
            [h('span.info', i18n('Upgrading database')), h('progress', { style: {'margin-left': '10px'}, min: 0, max: 1, value: migrationProgress })],
            when(computed(replicateProgress.incompleteFeeds, (v) => v > 5),
              [h('span.info', i18n('Downloading new messages')), h('progress', { style: {'margin-left': '10px'}, min: 0, max: 1, value: downloadProgress })],
              when(pending, [
                [h('span.info', i18n('Indexing database')), h('progress', { style: {'margin-left': '10px'}, min: 0, max: 1, value: indexProgress })]
              ], i18n('Scuttling...'))
            )
          )
        ]))
      ])
    ])
  })

  // scoped

  function Waiting (progress) {
    var waiting = Value()
    var lastTick = Date.now()

    progress && progress(update)

    pull(
      api.sbot.pull.stream(sbot => sbot.patchwork.heartbeat()),
      pull.drain(update)
    )

    setInterval(function () {
      if (lastTick < Date.now() - 1000) {
        waiting.set(true)
      }
    }, 1000)

    return waiting

    // scoped

    function update () {
      lastTick = Date.now()
      waiting.set(false)
    }
  }
}

function clamp (value) {
  return Math.min(1, Math.max(0, value)) || 0
}

function calcProgress (progress) {
  var range = progress.target - progress.start
  if (range) {
    return (progress.current - progress.start) / range
  } else {
    return 1
  }
}
<commit_msg>reset download progress once completed<commit_after>var {computed, when, h, Value} = require('mutant')
var nest = require('depnest')
var sustained = require('../../../lib/sustained')
const pull = require('pull-stream')

exports.gives = nest('app.html.progressNotifier')

exports.needs = nest({
  'sbot.pull.stream': 'first',
  'progress.html.render': 'first',
  'progress.obs': {
    indexes: 'first',
    replicate: 'first',
    migration: 'first'
  },
  'intl.sync.i18n': 'first'
})

exports.create = function (api) {
  const i18n = api.intl.sync.i18n
  return nest('app.html.progressNotifier', function (id) {
    var replicateProgress = api.progress.obs.replicate()
    var indexes = api.progress.obs.indexes()
    var migration = api.progress.obs.migration()
    var waiting = Waiting(replicateProgress)

    var pending = computed(indexes, (progress) => progress.target - progress.current || 0)
    var pendingMigration = computed(migration, (progress) => progress.target - progress.current || 0)

    var indexProgress = computed(indexes, calcProgress)
    var migrationProgress = computed(migration, calcProgress)

    var incompleteFeedsFrom = 0

    var downloadProgress = computed([replicateProgress.feeds, replicateProgress.incompleteFeeds], (feeds, incomplete) => {
      if (incomplete > incompleteFeedsFrom) {
        incompleteFeedsFrom = incomplete
      } else if (incomplete === 0) {
        incompleteFeedsFrom = 0
      }
      if (feeds && incomplete) {
        return clamp((feeds - incomplete) / incompleteFeedsFrom)
      } else {
        return 1
      }
    })

    var hidden = sustained(computed([waiting, replicateProgress.incompleteFeeds, pending, pendingMigration], (waiting, incomplete, pending, pendingMigration) => {
      return !waiting && incomplete < 5 && !pending && !pendingMigration
    }), 2000)

    // HACK: css animations take up WAY TO MUCH cpu, remove from dom when inactive
    var displaying = computed(sustained(hidden, 500, x => !x), hidden => !hidden)

    return h('div.info', { hidden }, [
      h('div.status', [
        when(displaying, h('Loading -small', [
          when(pendingMigration,
            [h('span.info', i18n('Upgrading database')), h('progress', { style: {'margin-left': '10px'}, min: 0, max: 1, value: migrationProgress })],
            when(computed(replicateProgress.incompleteFeeds, (v) => v > 5),
              [h('span.info', i18n('Downloading new messages')), h('progress', { style: {'margin-left': '10px'}, min: 0, max: 1, value: downloadProgress })],
              when(pending, [
                [h('span.info', i18n('Indexing database')), h('progress', { style: {'margin-left': '10px'}, min: 0, max: 1, value: indexProgress })]
              ], i18n('Scuttling...'))
            )
          )
        ]))
      ])
    ])
  })

  // scoped

  function Waiting (progress) {
    var waiting = Value()
    var lastTick = Date.now()

    progress && progress(update)

    pull(
      api.sbot.pull.stream(sbot => sbot.patchwork.heartbeat()),
      pull.drain(update)
    )

    setInterval(function () {
      if (lastTick < Date.now() - 1000) {
        waiting.set(true)
      }
    }, 1000)

    return waiting

    // scoped

    function update () {
      lastTick = Date.now()
      waiting.set(false)
    }
  }
}

function clamp (value) {
  return Math.min(1, Math.max(0, value)) || 0
}

function calcProgress (progress) {
  var range = progress.target - progress.start
  if (range) {
    return (progress.current - progress.start) / range
  } else {
    return 1
  }
}
<|endoftext|>


<commit_before>/*
 * grunt-lib-phantomjs
 * http://gruntjs.com/
 *
 * Copyright (c) 2012 "Cowboy" Ben Alman, contributors
 * Licensed under the MIT license.
 */

/*global phantom:true*/

'use strict';

var fs = require('fs');

// The temporary file used for communications.
var tmpfile = phantom.args[0];
// The page .html file to load.
var url = phantom.args[1];
// Extra, optionally overridable stuff.
var options = JSON.parse(phantom.args[2] || {});

// Default options.
if (!options.timeout) { options.timeout = 5000; }

// Keep track of the last time a client message was sent.
var last = new Date();

// Messages are sent to the parent by appending them to the tempfile.
var sendMessage = function(arg) {
  var args = Array.isArray(arg) ? arg : [].slice.call(arguments);
  last = new Date();
  fs.write(tmpfile, JSON.stringify(args) + '\n', 'a');
};

// This allows grunt to abort if the PhantomJS version isn't adequate.
sendMessage('private', 'version', phantom.version);

// Abort if the page doesn't send any messages for a while.
setInterval(function() {
  if (new Date() - last > options.timeout) {
    sendMessage('fail.timeout');
    phantom.exit();
  }
}, 100);

// Create a new page.
var page = require('webpage').create();

// Inject bridge script into client page.
var injected;
var inject = function() {
  if (injected) { return; }
  // Inject client-side helper script.
  sendMessage('inject', options.inject);
  page.injectJs(options.inject);
  injected = true;
};

// Keep track if the client-side helper script already has been injected.
page.onUrlChanged = function(newUrl) {
  injected = false;
  sendMessage('onUrlChanged', newUrl);
};

// The client page must send its messages via alert(jsonstring).
page.onAlert = function(str) {
  // The only thing that should ever alert "inject" is the custom event
  // handler this script adds to be executed on DOMContentLoaded.
  if (str === 'inject') {
    inject();
    return;
  }
  // Otherwise, parse the specified message string and send it back to grunt.
  // Unless there's a parse error. Then, complain.
  try {
    sendMessage(JSON.parse(str));
  } catch(err) {
    sendMessage('error.invalidJSON', str);
  }
};

// Relay console logging messages.
page.onConsoleMessage = function(message) {
  sendMessage('console', message);
};

// For debugging.
page.onResourceRequested = function(request) {
  sendMessage('onResourceRequested', request.url);
};

page.onResourceReceived = function(request) {
  if (request.stage === 'end') {
    sendMessage('onResourceReceived', request.url);
  }
};

page.onError = function(msg, trace) {
  sendMessage('error.onError', msg, trace);
};

// Run before the page is loaded.
page.onInitialized = function() {
  sendMessage('onInitialized');
  // Abort if there is no bridge to inject.
  if (!options.inject) { return; }
  // Tell the client that when DOMContentLoaded fires, it needs to tell this
  // script to inject the bridge. This should ensure that the bridge gets
  // injected before any other DOMContentLoaded or window.load event handler.
  page.evaluate(function() {
    /*jshint browser:true, devel:true */
    document.addEventListener('DOMContentLoaded', function() {
      alert('inject');
    }, false);
  });
};

// Run when the page has finished loading.
page.onLoadFinished = function(status) {
  // The window has loaded.
  sendMessage('onLoadFinished', status);
  if (status !== 'success') {
    // File loading failure.
    sendMessage('fail.load', url);
    phantom.exit();
  }
};

// Actually load url.
page.open(url);
<commit_msg>The "inject" option may now also be an Array. Closes gh-26.<commit_after>/*
 * grunt-lib-phantomjs
 * http://gruntjs.com/
 *
 * Copyright (c) 2012 "Cowboy" Ben Alman, contributors
 * Licensed under the MIT license.
 */

/*global phantom:true*/

'use strict';

var fs = require('fs');

// The temporary file used for communications.
var tmpfile = phantom.args[0];
// The page .html file to load.
var url = phantom.args[1];
// Extra, optionally overridable stuff.
var options = JSON.parse(phantom.args[2] || {});

// Default options.
if (!options.timeout) { options.timeout = 5000; }

// Keep track of the last time a client message was sent.
var last = new Date();

// Messages are sent to the parent by appending them to the tempfile.
var sendMessage = function(arg) {
  var args = Array.isArray(arg) ? arg : [].slice.call(arguments);
  last = new Date();
  fs.write(tmpfile, JSON.stringify(args) + '\n', 'a');
};

// This allows grunt to abort if the PhantomJS version isn't adequate.
sendMessage('private', 'version', phantom.version);

// Abort if the page doesn't send any messages for a while.
setInterval(function() {
  if (new Date() - last > options.timeout) {
    sendMessage('fail.timeout');
    phantom.exit();
  }
}, 100);

// Create a new page.
var page = require('webpage').create();

// Inject bridge script into client page.
var injected;
var inject = function() {
  if (injected) { return; }
  // Inject client-side helper script.
  var scripts = Array.isArray(options.inject) ? options.inject : [options.inject];
  sendMessage('inject', options.inject);
  scripts.forEach(page.injectJs);
  injected = true;
};

// Keep track if the client-side helper script already has been injected.
page.onUrlChanged = function(newUrl) {
  injected = false;
  sendMessage('onUrlChanged', newUrl);
};

// The client page must send its messages via alert(jsonstring).
page.onAlert = function(str) {
  // The only thing that should ever alert "inject" is the custom event
  // handler this script adds to be executed on DOMContentLoaded.
  if (str === 'inject') {
    inject();
    return;
  }
  // Otherwise, parse the specified message string and send it back to grunt.
  // Unless there's a parse error. Then, complain.
  try {
    sendMessage(JSON.parse(str));
  } catch(err) {
    sendMessage('error.invalidJSON', str);
  }
};

// Relay console logging messages.
page.onConsoleMessage = function(message) {
  sendMessage('console', message);
};

// For debugging.
page.onResourceRequested = function(request) {
  sendMessage('onResourceRequested', request.url);
};

page.onResourceReceived = function(request) {
  if (request.stage === 'end') {
    sendMessage('onResourceReceived', request.url);
  }
};

page.onError = function(msg, trace) {
  sendMessage('error.onError', msg, trace);
};

// Run before the page is loaded.
page.onInitialized = function() {
  sendMessage('onInitialized');
  // Abort if there is no bridge to inject.
  if (!options.inject) { return; }
  // Tell the client that when DOMContentLoaded fires, it needs to tell this
  // script to inject the bridge. This should ensure that the bridge gets
  // injected before any other DOMContentLoaded or window.load event handler.
  page.evaluate(function() {
    /*jshint browser:true, devel:true */
    document.addEventListener('DOMContentLoaded', function() {
      alert('inject');
    }, false);
  });
};

// Run when the page has finished loading.
page.onLoadFinished = function(status) {
  // The window has loaded.
  sendMessage('onLoadFinished', status);
  if (status !== 'success') {
    // File loading failure.
    sendMessage('fail.load', url);
    phantom.exit();
  }
};

// Actually load url.
page.open(url);
<|endoftext|>


<commit_before>
"use strict";

var protobufjs = require('protobufjs');
var fs = require('fs');
var path = require('path');

var map = {
    0: 'Version',
    1: 'UDPTunnel',
    2: 'Authenticate',
    3: 'Ping',
    4: 'Reject',
    5: 'ServerSync',
    6: 'ChannelRemove',
    7: 'ChannelState',
    8: 'UserRemove',
    9: 'UserState',
    10: 'BanList',
    11: 'TextMessage',
    12: 'PermissionDenied',
    13: 'ACL',
    14: 'QueryUsers',
    15: 'CryptSetup',
    16: 'ContextActionModify',
    17: 'ContextAction',
    18: 'UserList',
    19: 'VoiceTarget',
    20: 'PermissionQuery',
    21: 'CodecVersion',
    22: 'UserStats',
    23: 'RequestBlob',
    24: 'ServerConfig',
    25: 'SuggestConfig'
};

//var mumble = new Schema(fs.readFileSync( __dirname + '/mumble.desc'));
var builder = protobufjs.loadProtoFile(path.join(__dirname, mumble.proto));
var mumble = builder.build('MumbleProto');
var messages = {};
var context = {schema: mumble};

module.exports.buildPacket = function (type, payload) {
    return new context.schema[type](payload || {})
}

module.exports.decodePacket = function (type_id, payload) {
    var type = map[type_id]
    return new context.schema[type].decode(payload || {})
}

module.exports.idByName = {};
module.exports.nameById = {};

for (var k in map) {
    module.exports.idByName[map[k]] = k * 1;
    module.exports.nameById[k] = map[k];
}<commit_msg>dont leave commented code in<commit_after>
"use strict";

var protobufjs = require('protobufjs');
var fs = require('fs');
var path = require('path');

var map = {
    0: 'Version',
    1: 'UDPTunnel',
    2: 'Authenticate',
    3: 'Ping',
    4: 'Reject',
    5: 'ServerSync',
    6: 'ChannelRemove',
    7: 'ChannelState',
    8: 'UserRemove',
    9: 'UserState',
    10: 'BanList',
    11: 'TextMessage',
    12: 'PermissionDenied',
    13: 'ACL',
    14: 'QueryUsers',
    15: 'CryptSetup',
    16: 'ContextActionModify',
    17: 'ContextAction',
    18: 'UserList',
    19: 'VoiceTarget',
    20: 'PermissionQuery',
    21: 'CodecVersion',
    22: 'UserStats',
    23: 'RequestBlob',
    24: 'ServerConfig',
    25: 'SuggestConfig'
};

var builder = protobufjs.loadProtoFile(path.join(__dirname, mumble.proto));
var mumble = builder.build('MumbleProto');
var messages = {};
var context = {schema: mumble};

module.exports.buildPacket = function (type, payload) {
    return new context.schema[type](payload || {})
}

module.exports.decodePacket = function (type_id, payload) {
    var type = map[type_id]
    return new context.schema[type].decode(payload || {})
}

module.exports.idByName = {};
module.exports.nameById = {};

for (var k in map) {
    module.exports.idByName[map[k]] = k * 1;
    module.exports.nameById[k] = map[k];
}<|endoftext|>