text:
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview 'password-check-edit-dialog' is the dialog that allows showing
 * a saved password.
 */

import 'chrome://resources/cr_elements/cr_button/cr_button.m.js';
import 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js';
import 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.m.js';
import 'chrome://resources/cr_elements/cr_input/cr_input.m.js';
import 'chrome://resources/cr_elements/cr_icons_css.m.js';
import 'chrome://resources/cr_elements/shared_vars_css.m.js';
import '../icons.js';
import '../settings_shared_css.js';
import '../settings_vars_css.js';
import './passwords_shared_css.js';

import {CrButtonElement} from 'chrome://resources/cr_elements/cr_button/cr_button.m.js';
import {CrDialogElement} from 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js';
import {CrInputElement} from 'chrome://resources/cr_elements/cr_input/cr_input.m.js';
import {assert} from 'chrome://resources/js/assert.m.js';
import {focusWithoutInk} from 'chrome://resources/js/cr/ui/focus_without_ink.m.js';
import {I18nMixin} from 'chrome://resources/js/i18n_mixin.js';
import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {getTemplate} from './password_check_edit_dialog.html.js';

import {PasswordCheckInteraction, PasswordManagerImpl, PasswordManagerProxy} from './password_manager_proxy.js';

export interface SettingsPasswordCheckEditDialogElement {
  $: {
    dialog: CrDialogElement,
    cancel: HTMLElement,
    passwordInput: CrInputElement,
    save: CrButtonElement,
  };
}

const SettingsPasswordCheckEditDialogElementBase = I18nMixin(PolymerElement);

export class SettingsPasswordCheckEditDialogElement extends
    SettingsPasswordCheckEditDialogElementBase {
  static get is() {
    return 'settings-password-check-edit-dialog';
  }

  static get template() {
    return getTemplate();
  }

  static get properties() {
    return {
      /**
       * The password that the user is interacting with now.
       */
      item: Object,

      /**
       * Whether the password is visible or obfuscated.
       */
      visible: {
        type: Boolean,
        value: false,
      },

      /**
       * Whether the input is invalid.
       */
      inputInvalid_: Boolean,
    };
  }

  item: chrome.passwordsPrivate.InsecureCredential|null;
  private visible: boolean;
  private inputInvalid_: boolean;
  private passwordManager_: PasswordManagerProxy =
      PasswordManagerImpl.getInstance();

  override connectedCallback() {
    super.connectedCallback();

    this.$.dialog.showModal();
    focusWithoutInk(this.$.cancel);
  }

  /** Closes the dialog. */
  close() {
    this.$.dialog.close();
  }

  /**
   * Handler for tapping the 'cancel' button. Should just dismiss the dialog.
   */
  private onCancel_() {
    this.close();
  }

  /**
   * Handler for tapping the 'save' button. Should just dismiss the dialog.
   */
  private onSave_() {
    this.passwordManager_.recordPasswordCheckInteraction(
        PasswordCheckInteraction.EDIT_PASSWORD);
    this.passwordManager_
        .changeInsecureCredential(
            assert(this.item!), this.$.passwordInput.value)
        .finally(() => {
          this.close();
        });
  }

  /**
   * @return The title text for the show/hide icon.
   */
  private showPasswordTitle_(): string {
    return this.i18n(this.visible ? 'hidePassword' : 'showPassword');
  }

  /**
   * @return The visibility icon class, depending on whether the password is
   *     already visible.
   */
  private showPasswordIcon_(): string {
    return this.visible ? 'icon-visibility-off' : 'icon-visibility';
  }

  /**
   * @return The type of the password input field (text or password),
   *     depending on whether the password should be obfuscated.
   */
  private getPasswordInputType_(): string {
    return this.visible ? 'text' : 'password';
  }

  /**
   * Handler for tapping the show/hide button.
   */
  private onShowPasswordButtonClick_() {
    this.visible = !this.visible;
  }

  /**
   * @return The text to be displayed as the dialog's footnote.
   */
  private getFootnote_(): string {
    return this.i18n('editPasswordFootnote', this.item!.formattedOrigin);
  }

  /**
   * @return The label for the origin, depending on the whether it's a site or
   *     an app.
   */
  private getSiteOrApp_(): string {
    return this.i18n(
        this.item!.isAndroidCredential ? 'editCompromisedPasswordApp' :
                                         'editCompromisedPasswordSite');
  }
}

declare global {
  interface HTMLElementTagNameMap {
    'settings-password-check-edit-dialog':
        SettingsPasswordCheckEditDialogElement,
  }
}

customElements.define(
    SettingsPasswordCheckEditDialogElement.is,
    SettingsPasswordCheckEditDialogElement);

redpajama_set_name: RedPajamaGithub


text:
/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @file main.cpp
 * @author Gav Wood <i@gavwood.com>
 * @author Tasha Carl <tasha@carl.pro> - I here by place all my contributions in this file under MIT licence, as specified by http://opensource.org/licenses/MIT.
 * @date 2014
 * Ethereum client.
 */

#include <thread>
#include <chrono>
#include <fstream>
#include <iostream>
#include <signal.h>

#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/trim_all.hpp>

#include <libdevcore/FileSystem.h>
#include <libethashseal/EthashAux.h>
#include <libevm/VM.h>
#include <libevm/VMFactory.h>
#include <libethcore/KeyManager.h>
#include <libethcore/ICAP.h>
#include <libethereum/All.h>
#include <libethereum/BlockChainSync.h>
#include <libethashseal/EthashClient.h>
#include <libethashseal/GenesisInfo.h>
#include <libwebthree/WebThree.h>
#if ETH_JSCONSOLE || !ETH_TRUE
#include <libjsconsole/JSLocalConsole.h>
#include <libjsconsole/JSRemoteConsole.h>
#endif
#if ETH_READLINE || !ETH_TRUE
#include <readline/readline.h>
#include <readline/history.h>
#endif
#if ETH_JSONRPC || !ETH_TRUE
#include <libweb3jsonrpc/AccountHolder.h>
#include <libweb3jsonrpc/Eth.h>
#include <libweb3jsonrpc/SafeHttpServer.h>
#include <jsonrpccpp/client/connectors/httpclient.h>
#include <libweb3jsonrpc/ModularServer.h>
#include <libweb3jsonrpc/IpcServer.h>
#include <libweb3jsonrpc/LevelDB.h>
#include <libweb3jsonrpc/Whisper.h>
#include <libweb3jsonrpc/Net.h>
#include <libweb3jsonrpc/Web3.h>
#include <libweb3jsonrpc/SessionManager.h>
#include <libweb3jsonrpc/AdminNet.h>
#include <libweb3jsonrpc/AdminEth.h>
#include <libweb3jsonrpc/AdminUtils.h>
#include <libweb3jsonrpc/Personal.h>
#endif
#include "ethereum/ConfigInfo.h"
#if ETH_JSONRPC || !ETH_TRUE
#include "PhoneHome.h"
#include "Farm.h"
#endif
#include <ethminer/MinerAux.h>
#include "AccountManager.h"
using namespace std;
using namespace dev;
using namespace dev::p2p;
using namespace dev::eth;
using namespace boost::algorithm;

static std::atomic<bool> g_silence = {false};

void help()
{
	cout
		<< "Usage eth [OPTIONS]" << endl
		<< "Options:" << endl << endl
		<< "Operating mode (default is non-interactive node):" << endl;
#if ETH_JSCONSOLE || !ETH_TRUE
	cout
		<< "    console  Enter interactive console mode (default: non-interactive)." << endl
		<< "    attach  Ether interactive console mode of already-running eth." << endl
		<< "    import <file>  Import file as a concatenated series of blocks." << endl
		<< "    export <file>  Export file as a concatenated series of blocks." << endl;

#endif
	cout
		<< endl;
	AccountManager::streamAccountHelp(cout);
	AccountManager::streamWalletHelp(cout);
	cout
		<< endl;
	cout
		<< "Client mode (default):" << endl
		<< "    --olympic  Use the Olympic (0.9) protocol." << endl
		<< "    --frontier  Use the Frontier (1.0) protocol." << endl
		<< "    --morden  Use the Morden testnet." << endl
		<< "    --private <name>  Use a private chain." << endl
		<< "    --config <file>  Configure specialised blockchain using given JSON information." << endl
		<< endl
		<< "    -o,--mode <full/peer>  Start a full node or a peer node (default: full)." << endl
		<< endl
#if ETH_JSONRPC || !ETH_TRUE
		<< "    -j,--json-rpc  Enable JSON-RPC server (default: off)." << endl
		<< "    --ipc  Enable IPC server (default: on)." << endl
		<< "    --admin-via-http  Expose admin interface via http - UNSAFE! (default: off)." << endl
		<< "    --no-ipc  Disable IPC server." << endl
		<< "    --json-rpc-port <n>  Specify JSON-RPC server port (implies '-j', default: " << SensibleHttpPort << ")." << endl
		<< "    --rpccorsdomain <domain>  Domain on which to send Access-Control-Allow-Origin header." << endl
		<< "    --admin <password>  Specify admin session key for JSON-RPC (default: auto-generated and printed at start-up)." << endl
#endif
		<< "    -K,--kill  Kill the blockchain first." << endl
		<< "    -R,--rebuild  Rebuild the blockchain from the existing database." << endl
		<< "    --rescue  Attempt to rescue a corrupt database." << endl
		<< endl
		<< "    --import-presale <file>  Import a pre-sale key; you'll need to specify the password to this key." << endl
		<< "    -s,--import-secret <secret>  Import a secret key into the key store and use as the default." << endl
		<< "    -S,--import-session-secret <secret>  Import a secret key into the key store and use as the default for this session only." << endl
		<< "    --sign-key <address>  Sign all transactions with the key of the given address." << endl
		<< "    --session-sign-key <address>  Sign all transactions with the key of the given address for this session only." << endl
		<< "    --master <password>  Give the master password for the key store." << endl
		<< "    --password <password>  Give a password for a private key." << endl
		<< endl
		<< "Console mode:" << endl
		<< "    --script <script>  Run the given script after startup." << endl
		<< endl
		<< "Client transacting:" << endl
		/*<< "    -B,--block-fees <n>  Set the block fee profit in the reference unit, e.g. ¢ (default: 15)." << endl
		<< "    -e,--ether-price <n>  Set the ether price in the reference unit, e.g. ¢ (default: 30.679)." << endl
		<< "    -P,--priority <0 - 100>  Set the default priority percentage (%) of a transaction (default: 50)." << endl*/
		<< "    --ask <wei>  Set the minimum ask gas price under which no transaction will be mined (default " << toString(DefaultGasPrice) << " )." << endl
		<< "    --bid <wei>  Set the bid gas price to pay for transactions (default " << toString(DefaultGasPrice) << " )." << endl
		<< "    --unsafe-transactions  Allow all transactions to proceed without verification. EXTREMELY UNSAFE."
		<< endl
		<< "Client mining:" << endl
		<< "    -a,--address <addr>  Set the author (mining payout) address to given address (default: auto)." << endl
		<< "    -m,--mining <on/off/number>  Enable mining, optionally for a specified number of blocks (default: off)." << endl
		<< "    -f,--force-mining  Mine even when there are no transactions to mine (default: off)." << endl
		<< "    --mine-on-wrong-chain  Mine even when we know that it is the wrong chain (default: off)." << endl
		<< "    -C,--cpu  When mining, use the CPU." << endl
		<< "    -G,--opencl  When mining, use the GPU via OpenCL." << endl
		<< "    --opencl-platform <n>  When mining using -G/--opencl, use OpenCL platform n (default: 0)." << endl
		<< "    --opencl-device <n>  When mining using -G/--opencl, use OpenCL device n (default: 0)." << endl
		<< "    -t, --mining-threads <n>  Limit number of CPU/GPU miners to n (default: use everything available on selected platform)." << endl
		<< endl
		<< "Client networking:" << endl
		<< "    --client-name <name>  Add a name to your client's version string (default: blank)." << endl
		<< "    --bootstrap  Connect to the default Ethereum peer servers (default unless --no-discovery used)." << endl
		<< "    --no-bootstrap  Do not connect to the default Ethereum peer servers (default only when --no-discovery is used)." << endl
		<< "    -x,--peers <number>  Attempt to connect to a given number of peers (default: 11)." << endl
		<< "    --peer-stretch <number>  Give the accepted connection multiplier (default: 7)." << endl

		<< "    --public-ip <ip>  Force advertised public IP to the given IP (default: auto)." << endl
		<< "    --listen-ip <ip>(:<port>)  Listen on the given IP for incoming connections (default: 0.0.0.0)." << endl
		<< "    --listen <port>  Listen on the given port for incoming connections (default: 30303)." << endl
		<< "    -r,--remote <host>(:<port>)  Connect to the given remote host (default: none)." << endl
		<< "    --port <port>  Connect to the given remote port (default: 30303)." << endl
		<< "    --network-id <n>  Only connect to other hosts with this network id." << endl
		<< "    --upnp <on/off>  Use UPnP for NAT (default: on)." << endl

		<< "    --peerset <list>  Space delimited list of peers; element format: type:publickey@ipAddress[:port]." << endl
		<< "        Types:" << endl
		<< "        default		Attempt connection when no other peers are available and pinning is disabled." << endl
		<< "        required		Keep connected at all times." << endl
// TODO:
//		<< "	--trust-peers <filename>  Space delimited list of publickeys." << endl

		<< "    --no-discovery  Disable node discovery, implies --no-bootstrap." << endl
		<< "    --pin  Only accept or connect to trusted peers." << endl
		<< "    --hermit  Equivalent to --no-discovery --pin." << endl
		<< "    --sociable  Force discovery and no pinning." << endl
		<< endl;
	MinerCLI::streamHelp(cout);
	cout
		<< "Attach mode:" << endl
		<< "    --session-key <hex>  Use the given session key when attaching to the remote eth instance." << endl
		<< "    --url <url>  Attach to the remote eth instance with the given URL." << endl
		<< endl
		<< "Import/export modes:" << endl
		<< "    --from <n>  Export only from block n; n may be a decimal, a '0x' prefixed hash, or 'latest'." << endl
		<< "    --to <n>  Export only to block n (inclusive); n may be a decimal, a '0x' prefixed hash, or 'latest'." << endl
		<< "    --only <n>  Equivalent to --export-from n --export-to n." << endl
		<< "    --dont-check  Prevent checking some block aspects. Faster importing, but to apply only when the data is known to be valid." << endl
		<< endl
		<< "General Options:" << endl
		<< "    -d,--db-path,--datadir <path>  Load database from path (default: " << getDataDir() << ")." << endl
#if ETH_EVMJIT || !ETH_TRUE
		<< "    --vm <vm-kind>  Select VM; options are: interpreter, jit or smart (default: interpreter)." << endl
#endif
		<< "    -v,--verbosity <0 - 9>  Set the log verbosity from 0 to 9 (default: 8)." << endl
		<< "    -V,--version  Show the version and exit." << endl
		<< "    -h,--help  Show this help message and exit." << endl
		<< endl
		<< "Experimental / Proof of Concept:" << endl
		<< "    --shh  Enable Whisper." << endl
		<< endl
		;
		exit(0);
}

string ethCredits(bool _interactive = false)
{
	std::ostringstream cout;
	if (_interactive)
		cout
			<< "Type 'exit' to quit" << endl << endl;
	return credits() + cout.str();
}

void version()
{
	cout << "eth version " << dev::Version << endl;
	cout << "eth network protocol version: " << dev::eth::c_protocolVersion << endl;
	cout << "Client database version: " << dev::eth::c_databaseVersion << endl;
	cout << "Build: " << DEV_QUOTED(ETH_BUILD_PLATFORM) << "/" << DEV_QUOTED(ETH_BUILD_TYPE) << endl;
	exit(0);
}

void importPresale(KeyManager& _km, string const& _file, function<string()> _pass)
{
	KeyPair k = _km.presaleSecret(contentsString(_file), [&](bool){ return _pass(); });
	_km.import(k.secret(), "Presale wallet" + _file + " (insecure)");
}

Address c_config = Address("ccdeac59d35627b7de09332e819d5159e7bb7250");
string pretty(h160 _a, dev::eth::State const& _st)
{
	string ns;
	h256 n;
	if (h160 nameReg = (u160)_st.storage(c_config, 0))
		n = _st.storage(nameReg, (u160)(_a));
	if (n)
	{
		std::string s((char const*)n.data(), 32);
		if (s.find_first_of('\0') != string::npos)
			s.resize(s.find_first_of('\0'));
		ns = " " + s;
	}
	return ns;
}

inline bool isPrime(unsigned _number)
{
	if (((!(_number & 1)) && _number != 2 ) || (_number < 2) || (_number % 3 == 0 && _number != 3))
		return false;
	for(unsigned k = 1; 36 * k * k - 12 * k < _number; ++k)
		if ((_number % (6 * k + 1) == 0) || (_number % (6 * k - 1) == 0))
			return false;
	return true;
}

enum class NodeMode
{
	PeerServer,
	Full
};

enum class OperationMode
{
	Node,
	Import,
	Export,
	Attach
};

enum class Format
{
	Binary,
	Hex,
	Human
};

void stopSealingAfterXBlocks(eth::Client* _c, unsigned _start, unsigned& io_mining)
{
	try
	{
		if (io_mining != ~(unsigned)0 && io_mining && asEthashClient(_c)->isMining() && _c->blockChain().details().number - _start == io_mining)
		{
			_c->stopSealing();
			io_mining = ~(unsigned)0;
		}
	}
	catch (InvalidSealEngine&)
	{
	}

	this_thread::sleep_for(chrono::milliseconds(100));
}

class ExitHandler: public SystemManager
{
public:
	void exit() { exitHandler(0); }
	static void exitHandler(int) { s_shouldExit = true; }
	bool shouldExit() const { return s_shouldExit; }

private:
	static bool s_shouldExit;
};

bool ExitHandler::s_shouldExit = false;

int main(int argc, char** argv)
{
	// Init defaults
	Defaults::get();

#if ETH_DEBUG
	g_logVerbosity = 4;
#else
	g_logVerbosity = 1;
#endif

	/// Operating mode.
	OperationMode mode = OperationMode::Node;
//	unsigned prime = 0;
//	bool yesIReallyKnowWhatImDoing = false;
	strings scripts;

	/// When attaching.
	string remoteURL = contentsString(getDataDir("web3") + "/session.url");
	if (remoteURL.empty())
		remoteURL = "http://localhost:8545";
	string remoteSessionKey = contentsString(getDataDir("web3") + "/session.key");

	/// File name for import/export.
	string filename;
	bool safeImport = false;

	/// Hashes/numbers for export range.
	string exportFrom = "1";
	string exportTo = "latest";
	Format exportFormat = Format::Binary;

	/// General params for Node operation
	NodeMode nodeMode = NodeMode::Full;
	bool interactive = false;
#if ETH_JSONRPC || !ETH_TRUE
	int jsonRPCURL = -1;
	bool adminViaHttp = false;
	bool ipc = true;
	std::string rpcCorsDomain = "";
#endif
	string jsonAdmin;
	ChainParams chainParams(genesisInfo(eth::Network::Frontier), genesisStateRoot(eth::Network::Frontier));
	u256 gasFloor = Invalid256;
	string privateChain;

	bool upnp = true;
	WithExisting withExisting = WithExisting::Trust;

	/// Networking params.
	string clientName;
	string listenIP;
	unsigned short listenPort = 30303;
	string publicIP;
	string remoteHost;
	unsigned short remotePort = 30303;

	unsigned peers = 11;
	unsigned peerStretch = 7;
	std::map<NodeID, pair<NodeIPEndpoint,bool>> preferredNodes;
	bool bootstrap = true;
	bool disableDiscovery = false;
	bool pinning = false;
	bool enableDiscovery = false;
	bool noPinning = false;
	static const unsigned NoNetworkID = (unsigned)-1;
	unsigned networkID = NoNetworkID;

	/// Mining params
	unsigned mining = 0;
	bool mineOnWrongChain = false;
	Address signingKey;
	Address sessionKey;
	Address author = signingKey;
	strings presaleImports;
	bytes extraData;

	/// Transaction params
//	TransactionPriority priority = TransactionPriority::Medium;
//	double etherPrice = 30.679;
//	double blockFees = 15.0;
	u256 askPrice = DefaultGasPrice;
	u256 bidPrice = DefaultGasPrice;
	bool alwaysConfirm = true;

	// javascript console
	bool useConsole = false;

	/// Wallet password stuff
	string masterPassword;
	bool masterSet = false;

	/// Whisper
	bool useWhisper = false;

	string configFile = getDataDir() + "/config.rlp";
	bytes b = contents(configFile);

	strings passwordsToNote;
	Secrets toImport;
	if (b.size())
	{
		try
		{
			RLP config(b);
			signingKey = config[0].toHash<Address>();
			author = config[1].toHash<Address>();
		}
		catch (...) {}
	}

	if (argc > 1 && (string(argv[1]) == "wallet" || string(argv[1]) == "account"))
	{
		AccountManager accountm;
		return !accountm.execute(argc, argv);
	}

	MinerCLI m(MinerCLI::OperationMode::None);

	string configJSON;
	string genesisJSON;
	for (int i = 1; i < argc; ++i)
	{
		string arg = argv[i];
		if (m.interpretOption(i, argc, argv)) {}
		else if (arg == "--url" && i + 1 < argc)
			remoteURL = argv[++i];
		else if (arg == "--session-key" && i + 1 < argc)
			remoteSessionKey = argv[++i];
		else if (arg == "--listen-ip" && i + 1 < argc)
			listenIP = argv[++i];
		else if ((arg == "--listen" || arg == "--listen-port") && i + 1 < argc)
		{
			listenPort = (short)atoi(argv[++i]);
		}
		else if ((arg == "--public-ip" || arg == "--public") && i + 1 < argc)
		{
			publicIP = argv[++i];
		}
		else if ((arg == "-r" || arg == "--remote") && i + 1 < argc)
		{
			string host = argv[++i];
			string::size_type found = host.find_first_of(':');
			if (found != std::string::npos)
			{
				remoteHost = host.substr(0, found);
				remotePort = (short)atoi(host.substr(found + 1, host.length()).c_str());
			}
			else
				remoteHost = host;
		}
		else if (arg == "--port" && i + 1 < argc)
		{
			remotePort = (short)atoi(argv[++i]);
		}
		else if (arg == "--password" && i + 1 < argc)
			passwordsToNote.push_back(argv[++i]);
		else if (arg == "--master" && i + 1 < argc)
		{
			masterPassword = argv[++i];
			masterSet = true;
		}
		else if ((arg == "-I" || arg == "--import" || arg == "import") && i + 1 < argc)
		{
			mode = OperationMode::Import;
			filename = argv[++i];
		}
		else if (arg == "--dont-check")
			safeImport = true;
		else if ((arg == "-E" || arg == "--export" || arg == "export") && i + 1 < argc)
		{
			mode = OperationMode::Export;
			filename = argv[++i];
		}
		else if (arg == "--mine-on-wrong-chain")
			mineOnWrongChain = true;
		else if (arg == "--script" && i + 1 < argc)
			scripts.push_back(argv[++i]);
		else if (arg == "--format" && i + 1 < argc)
		{
			string m = argv[++i];
			if (m == "binary")
				exportFormat = Format::Binary;
			else if (m == "hex")
				exportFormat = Format::Hex;
			else if (m == "human")
				exportFormat = Format::Human;
			else
			{
				cerr << "Bad " << arg << " option: " << m << endl;
				return -1;
			}
		}
		else if (arg == "attach")
			mode = OperationMode::Attach;
		else if (arg == "--to" && i + 1 < argc)
			exportTo = argv[++i];
		else if (arg == "--from" && i + 1 < argc)
			exportFrom = argv[++i];
		else if (arg == "--only" && i + 1 < argc)
			exportTo = exportFrom = argv[++i];
		else if (arg == "--upnp" && i + 1 < argc)
		{
			string m = argv[++i];
			if (isTrue(m))
				upnp = true;
			else if (isFalse(m))
				upnp = false;
			else
			{
				cerr << "Bad " << arg << " option: " << m << endl;
				return -1;
			}
		}
		else if (arg == "--network-id" && i + 1 < argc)
			try {
				networkID = stol(argv[++i]);
			}
			catch (...)
			{
				cerr << "Bad " << arg << " option: " << argv[i] << endl;
				return -1;
			}
		else if (arg == "--private" && i + 1 < argc)
			try {
				privateChain = argv[++i];
			}
			catch (...)
			{
				cerr << "Bad " << arg << " option: " << argv[i] << endl;
				return -1;
			}
		else if (arg == "--independent" && i + 1 < argc)
			try {
				privateChain = argv[++i];
				noPinning = enableDiscovery = true;
			}
			catch (...)
			{
				cerr << "Bad " << arg << " option: " << argv[i] << endl;
				return -1;
			}
		else if (arg == "-K" || arg == "--kill-blockchain" || arg == "--kill")
			withExisting = WithExisting::Kill;
		else if (arg == "-R" || arg == "--rebuild")
			withExisting = WithExisting::Verify;
		else if (arg == "-R" || arg == "--rescue")
			withExisting = WithExisting::Rescue;
		else if (arg == "--client-name" && i + 1 < argc)
			clientName = argv[++i];
		else if ((arg == "-a" || arg == "--address" || arg == "--author") && i + 1 < argc)
			try {
				author = h160(fromHex(argv[++i], WhenError::Throw));
			}
			catch (BadHexCharacter&)
			{
				cerr << "Bad hex in " << arg << " option: " << argv[i] << endl;
				return -1;
			}
			catch (...)
			{
				cerr << "Bad " << arg << " option: " << argv[i] << endl;
				return -1;
			}
		else if ((arg == "-s" || arg == "--import-secret") && i + 1 < argc)
		{
			Secret s(fromHex(argv[++i]));
			toImport.emplace_back(s);
			signingKey = toAddress(s);
		}
		else if ((arg == "-S" || arg == "--import-session-secret") && i + 1 < argc)
		{
			Secret s(fromHex(argv[++i]));
			toImport.emplace_back(s);
			sessionKey = toAddress(s);
		}
		else if ((arg == "--sign-key") && i + 1 < argc)
			sessionKey = Address(fromHex(argv[++i]));
		else if ((arg == "--session-sign-key") && i + 1 < argc)
			sessionKey = Address(fromHex(argv[++i]));
		else if ((arg == "-d" || arg == "--path" || arg == "--db-path" || arg == "--datadir") && i + 1 < argc)
			setDataDir(argv[++i]);
		else if ((arg == "--genesis-json" || arg == "--genesis") && i + 1 < argc)
		{
			try
			{
				genesisJSON = contentsString(argv[++i]);
			}
			catch (...)
			{
				cerr << "Bad " << arg << " option: " << argv[i] << endl;
				return -1;
			}
		}
		else if (arg == "--config" && i + 1 < argc)
		{
			try
			{
				configJSON = contentsString(argv[++i]);
			}
			catch (...)
			{
				cerr << "Bad " << arg << " option: " << argv[i] << endl;
				return -1;
			}
		}
		else if (arg == "--extra-data" && i + 1 < argc)
		{
			try
			{
				extraData = fromHex(argv[++i]);
			}
			catch (...)
			{
				cerr << "Bad " << arg << " option: " << argv[i] << endl;
				return -1;
			}
		}
		else if (arg == "--gas-floor" && i + 1 < argc)
			gasFloor = u256(argv[++i]);
		else if (arg == "--frontier")
			chainParams = ChainParams(genesisInfo(eth::Network::Frontier), genesisStateRoot(eth::Network::Frontier));
		else if (arg == "--olympic")
			chainParams = ChainParams(genesisInfo(eth::Network::Olympic));
		else if (arg == "--morden" || arg == "--testnet")
			chainParams = ChainParams(genesisInfo(eth::Network::Morden), genesisStateRoot(eth::Network::Morden));
		else if (arg == "--bob")
		{
			cout << "Asking Bob for blocks (this should work in theoreum)..." << endl;
			while (true)
			{
				u256 x(h256::random());
				u256 c;
				for (; x != 1; ++c)
				{
					x = (x & 1) == 0 ? x / 2 : 3 * x + 1;
					cout << toHex(x) << endl;
					this_thread::sleep_for(chrono::seconds(1));
				}
				cout << "Block number: " << hex << c << endl;
				exit(0);
			}
		}
/*		else if ((arg == "-B" || arg == "--block-fees") && i + 1 < argc)
		{
			try
			{
				blockFees = stof(argv[++i]);
			}
			catch (...)
			{
				cerr << "Bad " << arg << " option: " << argv[i] << endl;
				return -1;
			}
		}
		else if ((arg == "-e" || arg == "--ether-price") && i + 1 < argc)
		{
			try
			{
				etherPrice = stof(argv[++i]);
			}
			catch (...)
			{
				cerr << "Bad " << arg << " option: " << argv[i] << endl;
				return -1;
			}
		}*/
		else if (arg == "--ask" && i + 1 < argc)
		{
			try
			{
				askPrice = u256(argv[++i]);
			}
			catch (...)
			{
				cerr << "Bad " << arg << " option: " << argv[i] << endl;
				return -1;
			}
		}
		else if (arg == "--bid" && i + 1 < argc)
		{
			try
			{
				bidPrice = u256(argv[++i]);
			}
			catch (...)
			{
				cerr << "Bad " << arg << " option: " << argv[i] << endl;
				return -1;
			}
		}
/*		else if ((arg == "-P" || arg == "--priority") && i + 1 < argc)
		{
			string m = boost::to_lower_copy(string(argv[++i]));
			if (m == "lowest")
				priority = TransactionPriority::Lowest;
			else if (m == "low")
				priority = TransactionPriority::Low;
			else if (m == "medium" || m == "mid" || m == "default" || m == "normal")
				priority = TransactionPriority::Medium;
			else if (m == "high")
				priority = TransactionPriority::High;
			else if (m == "highest")
				priority = TransactionPriority::Highest;
			else
				try {
					priority = (TransactionPriority)(max(0, min(100, stoi(m))) * 8 / 100);
				}
				catch (...) {
					cerr << "Unknown " << arg << " option: " << m << endl;
					return -1;
				}
		}*/
		else if ((arg == "-m" || arg == "--mining") && i + 1 < argc)
		{
			string m = argv[++i];
			if (isTrue(m))
				mining = ~(unsigned)0;
			else if (isFalse(m))
				mining = 0;
			else
				try {
					mining = stoi(m);
				}
				catch (...) {
					cerr << "Unknown " << arg << " option: " << m << endl;
					return -1;
				}
		}
		else if (arg == "-b" || arg == "--bootstrap")
			bootstrap = true;
		else if (arg == "--no-bootstrap")
			bootstrap = false;
		else if (arg == "--no-discovery")
		{
			disableDiscovery = true;
			bootstrap = false;
		}
		else if (arg == "--pin")
			pinning = true;
		else if (arg == "--hermit")
			pinning = disableDiscovery = true;
		else if (arg == "--sociable")
			noPinning = enableDiscovery = true;
		else if (arg == "--unsafe-transactions")
			alwaysConfirm = false;
		else if (arg == "--import-presale" && i + 1 < argc)
			presaleImports.push_back(argv[++i]);
		else if (arg == "--old-interactive")
			interactive = true;
#if ETH_JSONRPC || !ETH_TRUE
		else if ((arg == "-j" || arg == "--json-rpc"))
			jsonRPCURL = jsonRPCURL == -1 ? SensibleHttpPort : jsonRPCURL;
		else if (arg == "--admin-via-http")
			adminViaHttp = true;
		else if (arg == "--json-rpc-port" && i + 1 < argc)
			jsonRPCURL = atoi(argv[++i]);
		else if (arg == "--rpccorsdomain" && i + 1 < argc)
			rpcCorsDomain = argv[++i];
		else if (arg == "--json-admin" && i + 1 < argc)
			jsonAdmin = argv[++i];
		else if (arg == "--ipc")
			ipc = true;
		else if (arg == "--no-ipc")
			ipc = false;
#endif
#if ETH_JSCONSOLE || !ETH_TRUE
		else if (arg == "-i" || arg == "--interactive" || arg == "--console" || arg == "console")
			useConsole = true;
#endif
		else if ((arg == "-v" || arg == "--verbosity") && i + 1 < argc)
			g_logVerbosity = atoi(argv[++i]);
		else if ((arg == "-x" || arg == "--peers") && i + 1 < argc)
			peers = atoi(argv[++i]);
		else if (arg == "--peer-stretch" && i + 1 < argc)
			peerStretch = atoi(argv[++i]);
		else if (arg == "--peerset" && i + 1 < argc)
		{
			string peerset = argv[++i];
			if (peerset.empty())
			{
				cerr << "--peerset argument must not be empty";
				return -1;
			}

			vector<string> each;
			boost::split(each, peerset, boost::is_any_of("\t "));
			for (auto const& p: each)
			{
				string type;
				string pubk;
				string hostIP;
				unsigned short port = c_defaultListenPort;

				// type:key@ip[:port]
				vector<string> typeAndKeyAtHostAndPort;
				boost::split(typeAndKeyAtHostAndPort, p, boost::is_any_of(":"));
				if (typeAndKeyAtHostAndPort.size() < 2 || typeAndKeyAtHostAndPort.size() > 3)
					continue;

				type = typeAndKeyAtHostAndPort[0];
				if (typeAndKeyAtHostAndPort.size() == 3)
					port = (uint16_t)atoi(typeAndKeyAtHostAndPort[2].c_str());

				vector<string> keyAndHost;
				boost::split(keyAndHost, typeAndKeyAtHostAndPort[1], boost::is_any_of("@"));
				if (keyAndHost.size() != 2)
					continue;
				pubk = keyAndHost[0];
				if (pubk.size() != 128)
					continue;
				hostIP = keyAndHost[1];

				// todo: use Network::resolveHost()
				if (hostIP.size() < 4 /* g.it */)
					continue;

				bool required = type == "required";
				if (!required && type != "default")
					continue;

				Public publicKey(fromHex(pubk));
				try
				{
					preferredNodes[publicKey] = make_pair(NodeIPEndpoint(bi::address::from_string(hostIP), port, port), required);
				}
				catch (...)
				{
					cerr << "Unrecognized peerset: " << peerset << endl;
					return -1;
				}
			}
		}
		else if ((arg == "-o" || arg == "--mode") && i + 1 < argc)
		{
			string m = argv[++i];
			if (m == "full")
				nodeMode = NodeMode::Full;
			else if (m == "peer")
				nodeMode = NodeMode::PeerServer;
			else
			{
				cerr << "Unknown mode: " << m << endl;
				return -1;
			}
		}
#if ETH_EVMJIT
		else if (arg == "--vm" && i + 1 < argc)
		{
			string vmKind = argv[++i];
			if (vmKind == "interpreter")
				VMFactory::setKind(VMKind::Interpreter);
			else if (vmKind == "jit")
				VMFactory::setKind(VMKind::JIT);
			else if (vmKind == "smart")
				VMFactory::setKind(VMKind::Smart);
			else
			{
				cerr << "Unknown VM kind: " << vmKind << endl;
				return -1;
			}
		}
#endif
		else if (arg == "--shh")
			useWhisper = true;
		else if (arg == "-h" || arg == "--help")
			help();
		else if (arg == "-V" || arg == "--version")
			version();
		else
		{
			cerr << "Invalid argument: " << arg << endl;
			exit(-1);
		}
	}

	if (mode == OperationMode::Attach)
	{
		if (remoteURL.find_last_of("-1") == remoteURL.size() - 1)
		{
			cerr << "json-rpc server not found, please start eth with the --json-rpc option (note that this might make it accessible from the network)";
			return 0;
		}
#if ETH_JSCONSOLE || !ETH_TRUE
		JSRemoteConsole console(remoteURL);
		if (!remoteSessionKey.empty())
			console.eval("web3.admin.setSessionKey('" + remoteSessionKey + "')");
		while (true)
			console.readAndEval();
#endif
		return 0;
	}

	if (!configJSON.empty())
		chainParams = chainParams.loadConfig(configJSON);

	if (!genesisJSON.empty())
		chainParams = chainParams.loadGenesis(genesisJSON);

	if (!privateChain.empty())
	{
		chainParams.extraData = sha3(privateChain).asBytes();
		chainParams.difficulty = chainParams.u256Param("minimumDifficulty");
		chainParams.gasLimit = u256(1) << 32;
	}
	// TODO: Open some other API path
//	if (gasFloor != Invalid256)
//		c_gasFloorTarget = gasFloor;

	if (g_logVerbosity > 0)
		cout << EthGrayBold "(++)Ethereum" EthReset << endl;

	m.execute();

	KeyManager keyManager;
	for (auto const& s: passwordsToNote)
		keyManager.notePassword(s);

	writeFile(configFile, rlpList(signingKey, author));

	if (sessionKey)
		signingKey = sessionKey;

	if (!clientName.empty())
		clientName += "/";

	string logbuf;
	std::string additional;
	if (interactive)
		g_logPost = [&](std::string const& a, char const*){
			static SpinLock s_lock;
			SpinGuard l(s_lock);

			if (g_silence)
				logbuf += a + "\n";
			else
				cout << "\r           \r" << a << endl << additional << flush;

			// helpful to use OutputDebugString on windows
	#if defined(_WIN32)
			{
				OutputDebugStringA(a.data());
				OutputDebugStringA("\n");
			}
	#endif
		};

	auto getPassword = [&](string const& prompt) {
		bool s = g_silence;
		g_silence = true;
		cout << endl;
		string ret = dev::getPassword(prompt);
		g_silence = s;
		return ret;
	};
	auto getResponse = [&](string const& prompt, unordered_set<string> const& acceptable) {
		bool s = g_silence;
		g_silence = true;
		cout << endl;
		string ret;
		while (true)
		{
			cout << prompt;
			getline(cin, ret);
			if (acceptable.count(ret))
				break;
			cout << "Invalid response: " << ret << endl;
		}
		g_silence = s;
		return ret;
	};
	auto getAccountPassword = [&](Address const& a){
		return getPassword("Enter password for address " + keyManager.accountName(a) + " (" + a.abridged() + "; hint:" + keyManager.passwordHint(a) + "): ");
	};

	auto netPrefs = publicIP.empty() ? NetworkPreferences(listenIP, listenPort, upnp) : NetworkPreferences(publicIP, listenIP ,listenPort, upnp);
	netPrefs.discovery = (privateChain.empty() && !disableDiscovery) || enableDiscovery;
	netPrefs.pin = (pinning || !privateChain.empty()) && !noPinning;

	auto nodesState = contents(getDataDir() + "/network.rlp");
	auto caps = useWhisper ? set<string>{"eth", "shh"} : set<string>{"eth"};
	dev::WebThreeDirect web3(
		WebThreeDirect::composeClientVersion("eth"),
		getDataDir(),
		chainParams,
		withExisting,
		nodeMode == NodeMode::Full ? caps : set<string>(),
		netPrefs,
		&nodesState);
	web3.ethereum()->setSealOption("sealOnBadChain", rlp(mineOnWrongChain));
	if (!extraData.empty())
		web3.ethereum()->setExtraData(extraData);

	auto toNumber = [&](string const& s) -> unsigned {
		if (s == "latest")
			return web3.ethereum()->number();
		if (s.size() == 64 || (s.size() == 66 && s.substr(0, 2) == "0x"))
			return web3.ethereum()->blockChain().number(h256(s));
		try {
			return stol(s);
		}
		catch (...)
		{
			cerr << "Bad block number/hash option: " << s << endl;
			exit(-1);
		}
	};

	if (mode == OperationMode::Export)
	{
		ofstream fout(filename, std::ofstream::binary);
		ostream& out = (filename.empty() || filename == "--") ? cout : fout;

		unsigned last = toNumber(exportTo);
		for (unsigned i = toNumber(exportFrom); i <= last; ++i)
		{
			bytes block = web3.ethereum()->blockChain().block(web3.ethereum()->blockChain().numberHash(i));
			switch (exportFormat)
			{
			case Format::Binary: out.write((char const*)block.data(), block.size()); break;
			case Format::Hex: out << toHex(block) << endl; break;
			case Format::Human: out << RLP(block) << endl; break;
			default:;
			}
		}
		return 0;
	}

	if (mode == OperationMode::Import)
	{
		ifstream fin(filename, std::ifstream::binary);
		istream& in = (filename.empty() || filename == "--") ? cin : fin;
		unsigned alreadyHave = 0;
		unsigned good = 0;
		unsigned futureTime = 0;
		unsigned unknownParent = 0;
		unsigned bad = 0;
		chrono::steady_clock::time_point t = chrono::steady_clock::now();
		double last = 0;
		unsigned lastImported = 0;
		unsigned imported = 0;
		while (in.peek() != -1)
		{
			bytes block(8);
			in.read((char*)block.data(), 8);
			block.resize(RLP(block, RLP::LaissezFaire).actualSize());
			in.read((char*)block.data() + 8, block.size() - 8);

			switch (web3.ethereum()->queueBlock(block, safeImport))
			{
			case ImportResult::Success: good++; break;
			case ImportResult::AlreadyKnown: alreadyHave++; break;
			case ImportResult::UnknownParent: unknownParent++; break;
			case ImportResult::FutureTimeUnknown: unknownParent++; futureTime++; break;
			case ImportResult::FutureTimeKnown: futureTime++; break;
			default: bad++; break;
			}

			// sync chain with queue
			tuple<ImportRoute, bool, unsigned> r = web3.ethereum()->syncQueue(10);
			imported += get<2>(r);

			double e = chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - t).count() / 1000.0;
			if ((unsigned)e >= last + 10)
			{
				auto i = imported - lastImported;
				auto d = e - last;
				cout << i << " more imported at " << (round(i * 10 / d) / 10) << " blocks/s. " << imported << " imported in " << e << " seconds at " << (round(imported * 10 / e) / 10) << " blocks/s (#" << web3.ethereum()->number() << ")" << endl;
				last = (unsigned)e;
				lastImported = imported;
//				cout << web3.ethereum()->blockQueueStatus() << endl;
			}
		}

		while (web3.ethereum()->blockQueue().items().first + web3.ethereum()->blockQueue().items().second > 0)
		{
			this_thread::sleep_for(chrono::seconds(1));
			web3.ethereum()->syncQueue(100000);
		}
		double e = chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now() - t).count() / 1000.0;
		cout << imported << " imported in " << e << " seconds at " << (round(imported * 10 / e) / 10) << " blocks/s (#" << web3.ethereum()->number() << ")" << endl;
		return 0;
	}

	try
	{
		if (keyManager.exists())
		{
			if (!keyManager.load(masterPassword))
			{
				if (masterSet)
				{
					cerr << "Incorrect password specified." << endl;
					return -1;
				}
				while (true)
				{
					masterPassword = getPassword("Please enter your MASTER password: ");
					if (keyManager.load(masterPassword))
						break;
					cout << "The password you entered is incorrect. If you have forgotten your password, and you wish to start afresh, manually remove the file: " + getDataDir("ethereum") + "/keys.info" << endl;
				}
			}
		}
		else
		{
			if (!masterSet)
				while (true)
				{
					masterPassword = getPassword("Please enter a MASTER password to protect your key store (make it strong!): ");
					string confirm = getPassword("Please confirm the password by entering it again: ");
					if (masterPassword == confirm)
						break;
					cout << "Passwords were different. Try again." << endl;
				}
			keyManager.create(masterPassword);
		}
	}
	catch(...)
	{
		cerr << "Error initializing key manager: " << boost::current_exception_diagnostic_information() << endl;
		return -1;
	}

	for (auto const& presale: presaleImports)
		importPresale(keyManager, presale, [&](){ return getPassword("Enter your wallet password for " + presale + ": "); });

	for (auto const& s: toImport)
	{
		keyManager.import(s, "Imported key (UNSAFE)");
		if (!signingKey)
			signingKey = toAddress(s);
	}

	if (keyManager.accounts().empty())
	{
		h128 uuid = keyManager.import(ICAP::createDirect(), "Default key");
		if (!author)
			author = keyManager.address(uuid);
		if (!signingKey)
			signingKey = keyManager.address(uuid);
		writeFile(configFile, rlpList(signingKey, author));
	}

	cout << ethCredits();
	web3.setIdealPeerCount(peers);
	web3.setPeerStretch(peerStretch);
//	std::shared_ptr<eth::BasicGasPricer> gasPricer = make_shared<eth::BasicGasPricer>(u256(double(ether / 1000) / etherPrice), u256(blockFees * 1000));
	std::shared_ptr<eth::TrivialGasPricer> gasPricer = make_shared<eth::TrivialGasPricer>(askPrice, bidPrice);
	eth::Client* c = nodeMode == NodeMode::Full ? web3.ethereum() : nullptr;
	if (c)
	{
		c->setGasPricer(gasPricer);
		DEV_IGNORE_EXCEPTIONS(asEthashClient(c)->setShouldPrecomputeDAG(m.shouldPrecompute()));
		c->setSealer(m.minerType());
		c->setAuthor(author);
		if (networkID != NoNetworkID)
			c->setNetworkId(networkID);
	}

	auto renderFullAddress = [&](Address const& _a) -> std::string
	{
		return ICAP(_a).encoded() + " (" + toUUID(keyManager.uuid(_a)) + " - " + toHex(_a.ref().cropped(0, 4)) + ")";
	};

	cout << "Transaction Signer: " << renderFullAddress(signingKey) << endl;
	cout << "Mining Beneficiary: " << renderFullAddress(author) << endl;
	cout << "Foundation: " << renderFullAddress(Address("de0b295669a9fd93d5f28d9ec85e40f4cb697bae")) << endl;

	if (bootstrap || !remoteHost.empty() || enableDiscovery)
	{
		web3.startNetwork();
		cout << "Node ID: " << web3.enode() << endl;
	}
	else
		cout << "Networking disabled. To start, use netstart or pass --bootstrap or a remote host." << endl;

#if ETH_JSONRPC || !ETH_TRUE
	unique_ptr<ModularServer<>> jsonrpcHttpServer;
	unique_ptr<ModularServer<>> jsonrpcIpcServer;
	unique_ptr<rpc::SessionManager> sessionManager;
	unique_ptr<SimpleAccountHolder> accountHolder;

	AddressHash allowedDestinations;

	auto authenticator = [&](TransactionSkeleton const& _t, bool isProxy) -> bool {
		// "unlockAccount" functionality is done in the AccountHolder.
		if (!alwaysConfirm || allowedDestinations.count(_t.to))
			return true;

		string r = getResponse(_t.userReadable(isProxy,
			[&](TransactionSkeleton const& _t) -> pair<bool, string>
			{
				h256 contractCodeHash = web3.ethereum()->postState().codeHash(_t.to);
				if (contractCodeHash == EmptySHA3)
					return std::make_pair(false, std::string());
				// TODO: actually figure out the natspec. we'll need the natspec database here though.
				return std::make_pair(true, std::string());
			}, [&](Address const& _a) { return ICAP(_a).encoded() + " (" + _a.abridged() + ")"; }
		) + "\nEnter yes/no/always (always to this address): ", {"yes", "n", "N", "no", "NO", "always"});
		if (r == "always")
			allowedDestinations.insert(_t.to);
		return r == "yes" || r == "always";
	};

	ExitHandler exitHandler;

	if (jsonRPCURL > -1 || ipc)
	{
		sessionManager.reset(new rpc::SessionManager());
		accountHolder.reset(new SimpleAccountHolder([&](){ return web3.ethereum(); }, getAccountPassword, keyManager, authenticator));
		auto ethFace = new rpc::Eth(*web3.ethereum(), *accountHolder.get());
		auto adminEthFace = new rpc::AdminEth(*web3.ethereum(), *gasPricer.get(), keyManager, *sessionManager.get());
		if (jsonRPCURL >= 0)
		{
			if (adminViaHttp)
				jsonrpcHttpServer.reset(new ModularServer<
					rpc::EthFace, rpc::DBFace, rpc::WhisperFace,
					rpc::NetFace, rpc::Web3Face, rpc::PersonalFace,
					rpc::AdminEthFace, rpc::AdminNetFace, rpc::AdminUtilsFace
				>(
					ethFace, new rpc::LevelDB(), new rpc::Whisper(web3, {}),
					new rpc::Net(web3), new rpc::Web3(web3.clientVersion()), new rpc::Personal(keyManager, *accountHolder),
					adminEthFace, new rpc::AdminNet(web3, *sessionManager.get()), new rpc::AdminUtils(*sessionManager.get())
				));
			else
				jsonrpcHttpServer.reset(new ModularServer<
					rpc::EthFace, rpc::DBFace, rpc::WhisperFace,
					rpc::NetFace, rpc::Web3Face
				>(
					ethFace, new rpc::LevelDB(), new rpc::Whisper(web3, {}),
					new rpc::Net(web3), new rpc::Web3(web3.clientVersion())
				));
			auto httpConnector = new SafeHttpServer(jsonRPCURL, "", "", SensibleHttpThreads);
			httpConnector->setAllowedOrigin(rpcCorsDomain);
			jsonrpcHttpServer->addConnector(httpConnector);
			jsonrpcHttpServer->StartListening();
		}
		if (ipc)
		{
			jsonrpcIpcServer.reset(new ModularServer<
				rpc::EthFace, rpc::DBFace, rpc::WhisperFace,
				rpc::NetFace, rpc::Web3Face, rpc::PersonalFace,
				rpc::AdminEthFace, rpc::AdminNetFace, rpc::AdminUtilsFace
			>(
				ethFace, new rpc::LevelDB(), new rpc::Whisper(web3, {}), new rpc::Net(web3),
				new rpc::Web3(web3.clientVersion()), new rpc::Personal(keyManager, *accountHolder),
				adminEthFace, new rpc::AdminNet(web3, *sessionManager.get()),
				new rpc::AdminUtils(*sessionManager.get())
			));
			auto ipcConnector = new IpcServer("geth");
			jsonrpcIpcServer->addConnector(ipcConnector);
			ipcConnector->StartListening();
		}

		if (jsonAdmin.empty())
			jsonAdmin = sessionManager->newSession(rpc::SessionPermissions{{rpc::Privilege::Admin}});
		else
			sessionManager->addSession(jsonAdmin, rpc::SessionPermissions{{rpc::Privilege::Admin}});

		cout << "JSONRPC Admin Session Key: " << jsonAdmin << endl;
		writeFile(getDataDir("web3") + "/session.key", jsonAdmin);
		writeFile(getDataDir("web3") + "/session.url", "http://localhost:" + toString(jsonRPCURL));
	}
#endif

	for (auto const& p: preferredNodes)
		if (p.second.second)
			web3.requirePeer(p.first, p.second.first);
		else
			web3.addNode(p.first, p.second.first);

	if (bootstrap && privateChain.empty())
		for (auto const& i: Host::pocHosts())
			web3.requirePeer(i.first, i.second);
	if (!remoteHost.empty())
		web3.addNode(p2p::NodeID(), remoteHost + ":" + toString(remotePort));

	signal(SIGABRT, &ExitHandler::exitHandler);
	signal(SIGTERM, &ExitHandler::exitHandler);
	signal(SIGINT, &ExitHandler::exitHandler);

	if (c)
	{
		unsigned n = c->blockChain().details().number;
		if (mining)
			c->startSealing();
		if (useConsole || !scripts.empty())
		{
#if ETH_JSCONSOLE || !ETH_TRUE
			SimpleAccountHolder accountHolder([&](){ return web3.ethereum(); }, getAccountPassword, keyManager, authenticator);
			rpc::SessionManager sessionManager;
			string sessionKey = sessionManager.newSession(rpc::SessionPermissions{{rpc::Privilege::Admin}});

			auto ethFace = new rpc::Eth(*web3.ethereum(), accountHolder);
			auto adminEthFace = new rpc::AdminEth(*web3.ethereum(), *gasPricer.get(), keyManager, sessionManager);
			auto adminNetFace = new rpc::AdminNet(web3, sessionManager);
			auto adminUtilsFace = new rpc::AdminUtils(sessionManager);

			ModularServer<
				rpc::EthFace, rpc::DBFace, rpc::WhisperFace,
				rpc::NetFace, rpc::Web3Face, rpc::PersonalFace,
				rpc::AdminEthFace, rpc::AdminNetFace, rpc::AdminUtilsFace
			> rpcServer(
				ethFace, new rpc::LevelDB(), new rpc::Whisper(web3, {}),
				new rpc::Net(web3), new rpc::Web3(web3.clientVersion()), new rpc::Personal(keyManager, accountHolder),
				adminEthFace, adminNetFace, adminUtilsFace
			);

			JSLocalConsole console;
			rpcServer.addConnector(console.createConnector());
			rpcServer.StartListening();

			console.eval("web3.admin.setSessionKey('" + sessionKey + "')");

			for (auto const& s: scripts)
			{
				string c = contentsString(s);
				console.eval(c.empty() ? s : c);
			}
			while (!exitHandler.shouldExit())
			{
				if (useConsole)
					console.readAndEval();
				stopSealingAfterXBlocks(c, n, mining);
			}
			rpcServer.StopListening();
#endif
		}
		else
			while (!exitHandler.shouldExit())
				stopSealingAfterXBlocks(c, n, mining);
	}
	else
		while (!exitHandler.shouldExit())
			this_thread::sleep_for(chrono::milliseconds(1000));

#if ETH_JSONRPC
	if (jsonrpcHttpServer.get())
		jsonrpcHttpServer->StopListening();
	if (jsonrpcIpcServer.get())
		jsonrpcIpcServer->StopListening();
#endif

	auto netData = web3.saveNetwork();
	if (!netData.empty())
		writeFile(getDataDir() + "/network.rlp", netData);
	return 0;
}


text:
package com.intellij.codeInspection.actions;

import com.intellij.codeInsight.intention.EmptyIntentionAction;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInspection.*;
import com.intellij.codeInspection.ex.*;
import com.intellij.codeInspection.reference.RefManagerImpl;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.ReadonlyStatusHandler;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * User: anna
 * Date: 21-Feb-2006
 */
public class CleanupInspectionIntention implements IntentionAction {
  private final LocalInspectionTool myTool;
  private final Class myQuickfixClass;

  public CleanupInspectionIntention(final LocalInspectionTool tool, Class quickFixClass) {
    myTool = tool;
    myQuickfixClass = quickFixClass;
  }

  @NotNull
  public String getText() {
    return InspectionsBundle.message("fix.all.inspection.problems.in.file", myTool.getDisplayName());
  }

  @NotNull
  public String getFamilyName() {
    return getText();
  }

  public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file) throws IncorrectOperationException {
    final ReadonlyStatusHandler.OperationStatus status = ReadonlyStatusHandler.getInstance(project)
      .ensureFilesWritable(file.getVirtualFile());
    if (status.hasReadonlyFiles()) return;
    final InspectionManagerEx managerEx = ((InspectionManagerEx)InspectionManagerEx.getInstance(project));
    final GlobalInspectionContextImpl context = managerEx.createNewGlobalContext(false);
    final LocalInspectionToolWrapper tool = new LocalInspectionToolWrapper(myTool);
    tool.initialize(context);
    ((RefManagerImpl)context.getRefManager()).inspectionReadActionStarted();
    tool.processFile(file, true, managerEx, true);
    final List<CommonProblemDescriptor> descriptions = new ArrayList<CommonProblemDescriptor>(tool.getProblemDescriptors());
    Collections.sort(descriptions, new Comparator<CommonProblemDescriptor>() {
      public int compare(final CommonProblemDescriptor o1, final CommonProblemDescriptor o2) {
        final ProblemDescriptorImpl d1 = (ProblemDescriptorImpl)o1;
        final ProblemDescriptorImpl d2 = (ProblemDescriptorImpl)o2;
        return d2.getTextRange().getStartOffset() - d1.getTextRange().getStartOffset();
      }
    });
    for (CommonProblemDescriptor descriptor : descriptions) {
      final QuickFix[] fixes = descriptor.getFixes();
      if (fixes != null && fixes.length > 0) {
        for (QuickFix fix : fixes) {
          if (fix != null && fix.getClass().isAssignableFrom(myQuickfixClass)) {
            final PsiElement element = ((ProblemDescriptor)descriptor).getPsiElement();
            if (element != null && element.isValid()) {
              fix.applyFix(project, descriptor);
            }
            break;
          }
        }
      }
    }
    ((RefManagerImpl)context.getRefManager()).inspectionReadActionFinished();
    context.cleanup(managerEx);
  }

  public boolean isAvailable(@NotNull final Project project, final Editor editor, final PsiFile file) {
    return myQuickfixClass != null && myQuickfixClass != EmptyIntentionAction.class && !(myTool instanceof UnfairLocalInspectionTool);
  }

  public boolean startInWriteAction() {
    return true;
  }
}


text:
define([
	'intern!tdd',
	'intern/chai!assert',
	'dojo/_base/declare',
	'dojo/_base/lang',
	'dojo/Deferred',
	'dojo/on',
	'dojo/promise/all',
	'dojo/query',
	'dojo/when',
	'dijit/registry',
	'dijit/form/TextBox',
	'dgrid/Grid',
	'dgrid/OnDemandGrid',
	'dgrid/Editor',
	'dgrid/extensions/Pagination',
	'dgrid/test/data/createSyncStore',
	'dgrid/test/data/orderedData',
	'../addCss!'
], function (test, assert, declare, lang, Deferred, on, all, query, when, registry, TextBox,
		Grid, OnDemandGrid, Editor, Pagination, createSyncStore, orderedData) {

	var testOrderedData = orderedData.items,
		EditorGrid = declare([ Grid, Editor ]),
		grid;

	test.suite('Editor mixin', function () {

		test.afterEach(function () {
			if (grid) {
				grid.destroy();
			}
		});

		test.test('canEdit - always-on (instance-per-row) editor', function () {
			var results = {};
			var data = [
				{id: 1, data1: 'Data 1.a', data2: 'Data 2.a'},
				{id: 2, data1: 'Data 1.b', data2: 'Data 2.b'},
				{id: 3, data1: 'Data 1.c', data2: 'Data 2.c'}
			];
			grid = new EditorGrid({
				columns: [
					{
						field: 'data1',
						label: 'Data 1'
					},
					{
						editor: 'text',
						field: 'data2',
						label: 'Data 2',
						canEdit: function (object, value) {
							results[object.id] = value;
						}
					}
				]
			});
			document.body.appendChild(grid.domNode);
			grid.startup();
			grid.renderArray(data);

			assert.strictEqual(results[1], 'Data 2.a',
				'canEdit should have been called (item 1)');
			assert.strictEqual(results[2], 'Data 2.b',
				'canEdit should have been called (item 2)');
			assert.strictEqual(results[3], 'Data 2.c',
				'canEdit should have been called (item 3)');
		});

		test.test('canEdit - editOn (shared) editor', function () {
			var results = {};
			var data = [
				{id: 1, data1: 'Data 1.a', data2: 'Data 2.a'},
				{id: 2, data1: 'Data 1.b', data2: 'Data 2.b'},
				{id: 3, data1: 'Data 1.c', data2: 'Data 2.c'}
			];
			grid = new EditorGrid({
				columns: [
					{
						field: 'data1',
						label: 'Data 1',
						id: 'data1'
					},
					{
						editor: TextBox,
						editOn: 'click',
						field: 'data2',
						label: 'Data 2',
						id: 'data2',
						canEdit: function (object, value) {
							results[object.id] = value;
						}
					}
				]
			});
			document.body.appendChild(grid.domNode);
			grid.startup();
			grid.renderArray(data);

			assert.isUndefined(results[1],
				'canEdit should not have been called yet for editOn editor (item 1)');
			assert.isUndefined(results[2],
				'canEdit should not have been called yet for editOn editor (item 2)');
			assert.isUndefined(results[3],
				'canEdit should not have been called yet for editOn editor (item 3)');

			// Note: The "Data 2" column's canEdit method always returns false so none of the following
			// grid.edit calls will return a promise and no editor will receive focus.
			grid.edit(grid.cell(1, 'data2'));
			assert.isUndefined(results[1],
				'canEdit should not have been called yet for editOn editor (item 1)');
			assert.strictEqual(results[2], 'Data 2.b',
				'canEdit should have been called for editOn editor (item 2)');
			assert.isUndefined(results[3],
				'canEdit should not have been called yet for editOn editor (item 3)');

			grid.edit(grid.cell(0, 'data2'));
			assert.strictEqual(results[1], 'Data 2.a',
				'canEdit should have been called for editOn editor (item 1)');
			assert.strictEqual(results[2], 'Data 2.b',
				'canEdit should have been called for editOn editor (item 2)');
			assert.isUndefined(results[3],
				'canEdit should not have been called yet for editOn editor (item 3)');

			grid.edit(grid.cell(2, 'data2'));
			assert.strictEqual(results[1], 'Data 2.a',
				'canEdit should have been called for editOn editor (item 1)');
			assert.strictEqual(results[2], 'Data 2.b',
				'canEdit should have been called for editOn editor (item 2)');
			assert.strictEqual(results[3], 'Data 2.c',
				'canEdit should have been called for editOn editor (item 3)');
		});

		test.test('canEdit always-on editor - suppress on false', function () {
			var rowCount,
				cell,
				matchedNodes,
				dfd = this.async();

			function canEdit(data) {
				return data.order % 2;
			}

			grid = new EditorGrid({
				columns: {
					order: 'step',
					name: {
						editor: 'text',
						label: 'Name',
						canEdit: canEdit
					},
					description: {
						editor: 'text',
						label: 'Description',
						editOn: 'click',
						canEdit: canEdit
					}
				}
			});

			document.body.appendChild(grid.domNode);
			grid.startup();
			grid.renderArray(testOrderedData);
			rowCount = testOrderedData.length;

			function testRow(rowIndex) {
				cell = grid.cell(rowIndex, 'name');
				when(grid.edit(cell)).then(dfd.rejectOnError(function () {
					matchedNodes = query('input', cell.element);
					if (canEdit(cell.row.data)) {
						assert.strictEqual(1, matchedNodes.length,
							'Cell with canEdit=>true should have an editor element');
					}
					else {
						assert.strictEqual(0, matchedNodes.length,
							'Cell with canEdit=>false should not have an editor element');
					}
					rowIndex++;
					if (rowIndex < rowCount) {
						testRow(rowIndex);
					}
					else {
						dfd.resolve();
					}
				}));
			}
			testRow(0);

			return dfd;
		});

		test.test('canEdit edit-on click editor - suppress on false', function () {
			var rowCount,
				cell,
				matchedNodes,
				dfd = this.async();

			function canEdit(data) {
				return data.order % 2;
			}

			grid = new EditorGrid({
				columns: {
					order: 'step',
					name: {
						editor: 'text',
						label: 'Name',
						canEdit: canEdit
					},
					description: {
						editor: 'text',
						label: 'Description',
						editOn: 'click',
						canEdit: canEdit
					}
				}
			});

			document.body.appendChild(grid.domNode);
			grid.startup();
			grid.renderArray(testOrderedData);
			rowCount = testOrderedData.length;

			function testRow(rowIndex) {
				cell = grid.cell(rowIndex, 'description');
				when(grid.edit(cell)).then(dfd.rejectOnError(function () {
					matchedNodes = query('input', cell.element);
					if (canEdit(cell.row.data)) {
						assert.strictEqual(1, matchedNodes.length,
							'Cell with canEdit=>true should have an editor element');
					}
					else {
						assert.strictEqual(0, matchedNodes.length,
							'Cell with canEdit=>false should not have an editor element');
					}
					rowIndex++;
					if (rowIndex < rowCount) {
						testRow(rowIndex);
					}
					else {
						dfd.resolve();
					}
				}));
			}
			testRow(0);

			return dfd;
		});

		test.test('destroy editor widgets - native', function () {
			var matchedNodes;

			matchedNodes = query('input');
			assert.strictEqual(0, matchedNodes.length,
				'Before grid is created there should be 0 input elements on the page');

			grid = new EditorGrid({
				columns: {
					order: 'step',
					name: {
						label: 'Name',
						editor: 'text'
					},
					description: {
						label: 'Description',
						editor: 'text',
						editOn: 'click'
					}
				}
			});
			document.body.appendChild(grid.domNode);
			grid.startup();
			grid.renderArray(testOrderedData);

			matchedNodes = query('input');
			assert.strictEqual(testOrderedData.length, matchedNodes.length,
					'There should be ' + testOrderedData.length + ' input elements for the grid\'s editors');

			grid.destroy();

			matchedNodes = query('input');
			assert.strictEqual(0, matchedNodes.length,
				'After grid is destroyed there should be 0 input elements on the page');
		});

		test.test('destroy editor widgets - Dijit', function () {
			assert.strictEqual(0, registry.length,
				'Before grid is created there should be 0 widgets on the page');

			grid = new EditorGrid({
				columns: {
					order: 'step',
					name: {
						label: 'Name',
						editor: TextBox
					},
					description: {
						label: 'Description',
						editor: TextBox,
						editOn: 'click'
					}
				}
			});
			document.body.appendChild(grid.domNode);
			grid.startup();
			grid.renderArray(testOrderedData);

			// Expected is data length + 1 due to widget for editOn editor
			assert.strictEqual(testOrderedData.length + 1, registry.length,
					'There should be ' + (testOrderedData.length + 1) + ' widgets for the grid\'s editors');

			grid.destroy();

			assert.strictEqual(0, registry.length,
				'After grid is destroyed there should be 0 widgets on the page');
		});

		test.test('editor widget startup called at appropriate time', function () {
			var assertionMessage;
			var AssertionTextBox = declare(TextBox, {
				startup: function () {
					if (this._started) {
						return;
					}
					assert.isTrue(this.domNode.offsetHeight > 0,
						assertionMessage + ': startup should not be called before widgets are in flow');
					this.inherited(arguments);
				}
			});

			grid = new (declare([ OnDemandGrid, Editor ]))({
				columns: {
					order: 'step',
					name: {
						label: 'Name',
						editor: AssertionTextBox
					},
					description: {
						label: 'Description',
						editor: AssertionTextBox,
						editOn: 'click'
					}
				},
				collection: createSyncStore({
					data: testOrderedData,
					idProperty: 'order'
				})
			});
			document.body.appendChild(grid.domNode);

			assertionMessage = 'always-on';
			grid.startup();

			// Assertions will automatically run for always-on editor;
			// test activating an editOn editor and also test updating a row
			assertionMessage = 'editOn + edit()';
			grid.edit(grid.cell(1, 'description'));
			assertionMessage = 'editOn + Trackable';
			grid.collection.put(grid.collection.getSync(2));
		});

		test.test('editor focus with always-on editor', function () {
			var rowCount,
				cell,
				cellEditor,
				dfd = this.async();

			grid = new EditorGrid({
				columns: {
					order: 'step',
					name: {
						label: 'Name',
						editor: 'text'
					},
					description: {
						label: 'Description',
						editor: 'text',
						editOn: 'click'
					}
				}
			});
			document.body.appendChild(grid.domNode);
			grid.startup();
			grid.renderArray(testOrderedData);
			rowCount = testOrderedData.length;

			function testRow(rowIndex) {
				// Test calling 'grid.edit()' in an always-on cell
				cell = grid.cell(rowIndex, 'name');
				grid.edit(cell).then(dfd.rejectOnError(function (node) {
					cellEditor = query('input', cell.element)[0];
					assert.strictEqual(cellEditor, node,
						'edit method\'s promise should return the active editor');
					assert.strictEqual(cellEditor, document.activeElement,
						'Editing a cell should make the cell\'s editor active');
					rowIndex++;
					if (rowIndex < rowCount) {
						testRow(rowIndex);
					}
					else {
						dfd.resolve();
					}
				}));
			}
			testRow(0);

			return dfd;
		});

		test.test('editor focus and show event with edit-on click editor', function () {
			var rowCount,
				cell,
				cellEditor,
				dfd = this.async();

			grid = new EditorGrid({
				columns: {
					order: 'step',
					name: {
						label: 'Name',
						editor: 'text'
					},
					description: {
						label: 'Description',
						editor: 'text',
						editOn: 'click'
					}
				}
			});
			document.body.appendChild(grid.domNode);
			grid.startup();
			grid.renderArray(testOrderedData);
			rowCount = testOrderedData.length;

			function testRow(rowIndex) {
				var dfdEvent = new Deferred();
				// Test calling 'grid.edit()' in an always-on cell
				cell = grid.cell(rowIndex, 'description');
				// Respond to the "dgrid-editor-show" event to ensure the
				// correct cell has an editor.  This event actually fires
				// synchronously, so we don't need to use this.async.
				on.once(grid, 'dgrid-editor-show', dfd.rejectOnError(function (event) {
					assert.strictEqual(cell.element, event.cell.element,
						'The activated cell should be being edited'
					);
					dfdEvent.resolve();
				}));
				// Don't move on to the next row until the editor has received focus and the show event has fired.
				all([grid.edit(cell), dfdEvent]).then(dfd.rejectOnError(function () {
					cellEditor = query('input', cell.element)[0];
					assert.strictEqual(cellEditor, document.activeElement,
						'Editing a cell should make the cell\'s editor active');
					rowIndex++;
					if (rowIndex < rowCount) {
						testRow(rowIndex);
					}
					else {
						dfd.resolve();
					}
				}));
			}
			testRow(0);

			return dfd;
		});

		test.test('Maintain shared widgets on refresh in IE', function() {
			grid = new (declare([ OnDemandGrid, Editor ]))({
				columns: {
					name: {
						editor: TextBox,
						editOn: 'click'
					}
				},
				collection: createSyncStore({
					data: testOrderedData,
					idProperty: 'order'
				})
			});
			document.body.appendChild(grid.domNode);
			grid.startup();

			var cell = grid.cell(1, 'name');
			var cellContent;
			return grid.edit(cell).then(function () {
				cellContent = cell.element.innerHTML;
				grid.refresh();
				cell = grid.cell(1, 'name');
				return grid.edit(cell);
			}).then(function () {
				assert.strictEqual(cell.element.innerHTML, cellContent, 'Widget should be identical to before refresh');
			});
		});

		test.suite('Listener cleanup', function () {
			function testCellListeners(rowCount, editorColumnCount) {
				var rowEntryCount = 0;
				for (var rowKey in grid._editorCellListeners) {
					rowEntryCount++;
					var listenerCount = 0;
					var rowCellListeners = grid._editorCellListeners[rowKey];

					for (var cellKey in rowCellListeners) {
						assert.ok(rowCellListeners[cellKey].remove, 'Object in hash should be a listener handle');
						listenerCount++;
					}

					assert.strictEqual(listenerCount, editorColumnCount, 'Should have two listeners per row');
				}
				assert.strictEqual(rowEntryCount, rowCount, 'Should only have one entry for each row');
			}

			function buildPaginatedGrid (GridConstructor, rowsPerPage) {
				var paginatedGrid = new GridConstructor({
					rowsPerPage: rowsPerPage || 10,
					columns: {
						name: {
							editor: 'text',
							editOn: 'click'
						},
						description: {
							editor: 'text',
							editOn: 'click'
						}
					},
					collection: createSyncStore({
						data: testOrderedData,
						idProperty: 'order'
					})
				});

				document.body.appendChild(paginatedGrid.domNode);
				paginatedGrid.startup();
				return paginatedGrid;
			}

			test.test('clean up after refresh cell', function () {
				// Test with Pagination mixed in first
				grid = buildPaginatedGrid(declare([ Grid, Pagination, Editor ]));
				for (var i = 1; i < 10;i ++) {
					grid.refreshCell(grid.cell(i, 'name'));
					grid.refreshCell(grid.cell(i, 'description'));
				}
				testCellListeners(9, 2);
				grid.destroy();

				// Test with Editor mixed in first
				grid = buildPaginatedGrid(declare([ Grid, Editor, Pagination ]));
				for (i = 1; i < 10;i ++) {
					grid.refreshCell(grid.cell(i, 'name'));
					grid.refreshCell(grid.cell(i, 'description'));
				}
				testCellListeners(9, 2);
			});

			test.test('clean up after row is rerendered', function () {
				grid = buildPaginatedGrid(declare([Grid, Pagination, Editor]));
				for (var i = 0; i < 9; i++) {
					grid.collection.put(
						lang.mixin(lang.clone(orderedData.items[i]), {description: 'modified'})
					);
				}
				testCellListeners(9, 2);
			});

			test.test('clean up when switching pages', function () {
				grid = buildPaginatedGrid(declare([Grid, Pagination, Editor]), 5);
				testCellListeners(5, 2);
				grid.gotoPage(2);
				testCellListeners(4, 2);
			});

			test.test('clean up when scrolling', function () {
				var data = [];
				for (var i = 0; i < 1000; i++) {
					data[i] = {
						id: i,
						name: 'Name ' + i
					};
				}
				grid = new (declare([OnDemandGrid, Editor]))({
					columns: {
						name: {
							editor: 'text',
							editOn: 'click'
						}
					},
					minRowsPerPage: 250,
					collection: createSyncStore({
						data: data
					})
				});

				document.body.appendChild(grid.domNode);
				grid.startup();

				testCellListeners(250, 1);
				grid.bodyNode.scrollTop = '10000';
				return when(grid._processScroll(), function () {
					testCellListeners(250, 1);
				});
			});
		});

		test.suite('Editor#refreshCell', function () {
			var store;

			function createGrid(columnOptions) {
				store = createSyncStore({
					data: testOrderedData,
					idProperty: 'order'
				});

				grid = new (declare([ OnDemandGrid, Editor ]))({
					columns: {
						name: lang.mixin({
							label: 'Name'
						}, columnOptions)
					},
					collection: store,
					shouldTrackCollection: false // Disable normal row-based observation hooks to test refreshCell
				});

				document.body.appendChild(grid.domNode);
				grid.startup();
			}

			function createTest(columnOptions) {
				return function () {
					createGrid(columnOptions);
					var cell = grid.cell(1, 'name');
					var originalElement;
					var originalValue;

					// Test refreshing an active cell before its value is committed (should revert value, keep focus)

					return grid.edit(cell).then(function () {
						originalElement = document.activeElement;
						originalValue = originalElement.value;
						originalElement.value = 'new name';

						return grid.refreshCell(cell);
					}).then(function () {
						assert.strictEqual(document.activeElement, originalElement,
							'The same editor should still be focused after refreshCell is called on the active cell');
						assert.strictEqual(originalElement.value, originalValue,
							'The editor should revert to its stored value upon refresh');

						// Test refreshing a cell with changed data that is not the active cell

						store.putSync(lang.mixin(store.getSync(2), { name: 'new name 2'}));

						return grid.refreshCell(grid.cell(2, 'name'));
					}).then(function () {
						var cellElement = grid.cell(2, 'name').element;
						var name = columnOptions.editOn ? cellElement.textContent :
							cellElement.widget ? cellElement.widget.get('value') : cellElement.input.value;

						assert.strictEqual(document.activeElement, originalElement,
							'The same editor should still be focused after refreshCell is called on another cell');
						assert.strictEqual(name, 'new name 2',
							'Cell should contain expected new value after refresh');
					});
				};
			}

			test.afterEach(function () {
				if (grid) {
					grid.destroy();
					grid = null;
				}
			});

			test.test('HTML input, always-on', createTest({ editor: 'text' }));
			test.test('HTML input, editOn', createTest({ editor: 'text', editOn: 'click' }));
			test.test('Dijit TextBox, always-on', createTest({ editor: TextBox }));
			test.test('Dijit TextBox, editOn', createTest({ editor: TextBox, editOn: 'click' }));
		});
	});
});


text:
<?php

namespace Exchange\Market;

use Exchange\Market\Option\Execute;
use Exchange\Trade\Call;
use Exchange\Trade\Future;
use Exchange\Trade\Put;
use Exchange\Trade\Short;
use Exchange\Trade\Trade;

class Context
{
    // <Context> class for strategy pattern

    public function Call()
    {
        return new Trade( new Call() );
    }
    public function Put()
    {
        return new Trade( new Put() );
    }
    public function Short()
    {
        return new Trade( new Short() );
    }
    public function Future()
    {
        return new Trade( new Future() );
    }
}


text:
declare namespace Jymfony.Component.Console.Exception {
    export class CommandNotFoundException extends InvalidArgumentException {
        public alternatives: string[];

        /**
         * Constructor.
         */
        // @ts-ignore
        __construct(message: string, alternatives: string[], previous?: Error): void;
        constructor(message: string, alternatives: string[], previous?: Error);
    }
}


text:
package com.jvm_bloggers.frontend.public_area.all_issues;

import com.jvm_bloggers.domain.query.newsletter_issue_for_listing.NewsletterIssueForListing;
import com.jvm_bloggers.frontend.public_area.AbstractFrontendPage;

import com.jvm_bloggers.frontend.public_area.FireInOvhPage;
import io.vavr.collection.Map;
import io.vavr.collection.Seq;

import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.wicketstuff.annotation.mount.MountPath;

import java.time.YearMonth;

@MountPath("all-issues")
public class AllIssuesPage extends AbstractFrontendPage {

    @SpringBean
    private AllIssuesPageBackingBean backingBean;

    public AllIssuesPage() {
        Map<YearMonth, Seq<NewsletterIssueForListing>> issuesGroupedByMonthYear =
            backingBean.getIssuesGroupedByYearMonth();
        RepeatingView issuesInMonth = new RepeatingView("issuesInMonthPanel");
        issuesGroupedByMonthYear.forEach((monthYear, issues) -> issuesInMonth.add(
            new IssuesInMonthPanel(issuesInMonth.newChildId(), monthYear, issues)
        ));
        add(issuesInMonth);
        add(new BookmarkablePageLink<>("fireInOvhLink", FireInOvhPage.class));
    }

    @Override
    protected String getPageTitle() {
        return "Archiwum";
    }

}


text:
require 'cucumber'
require 'cucumber/core/ast/location'

module Cucumber
  class FileSpecs
    FILE_COLON_LINE_PATTERN = /^([\w\W]*?)(?::([\d:]+))?$/ #:nodoc:

    def initialize(file_specs)
      Cucumber.logger.debug("Features:\n")
      @file_specs = file_specs.map { |s| FileSpec.new(s) }
      Cucumber.logger.debug("\n")
    end

    def locations
      @file_specs.map(&:locations).flatten
    end

    def files
      @file_specs.map(&:file).uniq
    end

    class FileSpec
      def initialize(s)
        @file, @lines = *FILE_COLON_LINE_PATTERN.match(s).captures
        Cucumber.logger.debug("  * #{@file}\n")
        @lines = String(@lines).split(':').map { |line| Integer(line) }
      end

      attr_reader :file

      def locations
        return [ Core::Ast::Location.new(@file) ] if @lines.empty?
        @lines.map { |line| Core::Ast::Location.new(@file, line) }
      end
    end
  end
end


text:
package ca.willenborg.games.flappybird.states;

import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;

import ca.willenborg.games.flappybird.AssetStore;
import ca.willenborg.games.flappybird.sprites.Bird;

public class PlayState extends State {

	private Bird bird;

	protected PlayState(GameStateManager gsm) {
		super(gsm);
		bird = new Bird( 50, 100 );
	}

	@Override
	public void handleInput() {
		// TODO Auto-generated method stub

	}

	@Override
	public void update(float deltaTime) {
		handleInput();
		bird.update( deltaTime );
	}

	@Override
	public void render(SpriteBatch sb) {
		sb.setProjectionMatrix(camera.combined);
		sb.begin();
		sb.draw( bird.getTextureRegion(),
				bird.getPosition().x,
				bird.getPosition().y );
		sb.end();
	}

	@Override
	public void dispose() {
		// TODO Auto-generated method stub

	}

}


text:
#!/usr/bin/php
<?php
if(!defined('DOKU_INC')) define('DOKU_INC', realpath(dirname(__FILE__).'/../').'/');
define('NOSESSION', 1);
require_once(DOKU_INC.'inc/init.php');

/**
 * Checkout and commit pages from the command line while maintaining the history
 */
class PageCLI extends DokuCLI {

    protected $force = false;
    protected $username = '';

    /**
     * Register options and arguments on the given $options object
     *
     * @param DokuCLI_Options $options
     * @return void
     */
    protected function setup(DokuCLI_Options $options) {
        /* global */
        $options->registerOption(
            'force',
            'force obtaining a lock for the page (generally bad idea)',
            'f'
        );
        $options->registerOption(
            'user',
            'work as this user. defaults to current CLI user',
            'u',
            'username'
        );
        $options->setHelp(
            'Utility to help command line Dokuwiki page editing, allow '.
            'pages to be checked out for editing then committed after changes'
        );

        /* checkout command */
        $options->registerCommand(
            'checkout',
            'Checks out a file from the repository, using the wiki id and obtaining '.
            'a lock for the page. '."\n".
            'If a working_file is specified, this is where the page is copied to. '.
            'Otherwise defaults to the same as the wiki page in the current '.
            'working directory.'
        );
        $options->registerArgument(
            'wikipage',
            'The wiki page to checkout',
            true,
            'checkout'
        );
        $options->registerArgument(
            'workingfile',
            'How to name the local checkout',
            false,
            'checkout'
        );

        /* commit command */
        $options->registerCommand(
            'commit',
            'Checks in the working_file into the repository using the specified '.
            'wiki id, archiving the previous version.'
        );
        $options->registerArgument(
            'workingfile',
            'The local file to commit',
            true,
            'commit'
        );
        $options->registerArgument(
            'wikipage',
            'The wiki page to create or update',
            true,
            'commit'
        );
        $options->registerOption(
            'message',
            'Summary describing the change (required)',
            'm',
            'summary',
            'commit'
        );
        $options->registerOption(
            'trivial',
            'minor change',
            't',
            false,
            'commit'
        );

        /* lock command */
        $options->registerCommand(
            'lock',
            'Obtains or updates a lock for a wiki page'
        );
        $options->registerArgument(
            'wikipage',
            'The wiki page to lock',
            true,
            'lock'
        );

        /* unlock command */
        $options->registerCommand(
            'unlock',
            'Removes a lock for a wiki page.'
        );
        $options->registerArgument(
            'wikipage',
            'The wiki page to unlock',
            true,
            'unlock'
        );
    }

    /**
     * Your main program
     *
     * Arguments and options have been parsed when this is run
     *
     * @param DokuCLI_Options $options
     * @return void
     */
    protected function main(DokuCLI_Options $options) {
        $this->force    = $options->getOpt('force', false);
        $this->username = $options->getOpt('user', $this->getUser());

        $command = $options->getCmd();
        switch($command) {
            case 'checkout':
                $wiki_id   = array_shift($options->args);
                $localfile = array_shift($options->args);
                $this->commandCheckout($wiki_id, $localfile);
                break;
            case 'commit':
                $localfile = array_shift($options->args);
                $wiki_id   = array_shift($options->args);
                $this->commandCommit(
                    $localfile,
                    $wiki_id,
                    $options->getOpt('message', ''),
                    $options->getOpt('trivial', false)
                );
                break;
            case 'lock':
                $wiki_id = array_shift($options->args);
                $this->obtainLock($wiki_id);
                $this->success("$wiki_id locked");
                break;
            case 'unlock':
                $wiki_id = array_shift($options->args);
                $this->clearLock($wiki_id);
                $this->success("$wiki_id unlocked");
                break;
            default:
                echo $options->help();
        }
    }

    /**
     * Check out a file
     *
     * @param string $wiki_id
     * @param string $localfile
     */
    protected function commandCheckout($wiki_id, $localfile) {
        global $conf;

        $wiki_id = cleanID($wiki_id);
        $wiki_fn = wikiFN($wiki_id);

        if(!file_exists($wiki_fn)) {
            $this->fatal("$wiki_id does not yet exist");
        }

        if(empty($localfile)) {
            $localfile = getcwd().'/'.utf8_basename($wiki_fn);
        }

        if(!file_exists(dirname($localfile))) {
            $this->fatal("Directory ".dirname($localfile)." does not exist");
        }

        if(stristr(realpath(dirname($localfile)), realpath($conf['datadir'])) !== false) {
            $this->fatal("Attempt to check out file into data directory - not allowed");
        }

        $this->obtainLock($wiki_id);

        if(!copy($wiki_fn, $localfile)) {
            $this->clearLock($wiki_id);
            $this->fatal("Unable to copy $wiki_fn to $localfile");
        }

        $this->success("$wiki_id > $localfile");
    }

    /**
     * Save a file as a new page revision
     *
     * @param string $localfile
     * @param string $wiki_id
     * @param string $message
     * @param bool   $minor
     */
    protected function commandCommit($localfile, $wiki_id, $message, $minor) {
        $wiki_id = cleanID($wiki_id);
        $message = trim($message);

        if(!file_exists($localfile)) {
            $this->fatal("$localfile does not exist");
        }

        if(!is_readable($localfile)) {
            $this->fatal("Cannot read from $localfile");
        }

        if(!$message) {
            $this->fatal("Summary message required");
        }

        $this->obtainLock($wiki_id);

        saveWikiText($wiki_id, file_get_contents($localfile), $message, $minor);

        $this->clearLock($wiki_id);

        $this->success("$localfile > $wiki_id");
    }

    /**
     * Lock the given page or exit
     *
     * @param string $wiki_id
     */
    protected function obtainLock($wiki_id) {
        if($this->force) $this->deleteLock($wiki_id);

        $_SERVER['REMOTE_USER'] = $this->username;

        if(checklock($wiki_id)) {
            $this->error("Page $wiki_id is already locked by another user");
            exit(1);
        }

        lock($wiki_id);

        if(checklock($wiki_id)) {
            $this->error("Unable to obtain lock for $wiki_id ");
            var_dump(checklock($wiki_id));
            exit(1);
        }
    }

    /**
     * Clear the lock on the given page
     *
     * @param string $wiki_id
     */
    protected function clearLock($wiki_id) {
        if($this->force) $this->deleteLock($wiki_id);

        $_SERVER['REMOTE_USER'] = $this->username;
        if(checklock($wiki_id)) {
            $this->error("Page $wiki_id is locked by another user");
            exit(1);
        }

        unlock($wiki_id);

        if(file_exists(wikiLockFN($wiki_id))) {
            $this->error("Unable to clear lock for $wiki_id");
            exit(1);
        }
    }

    /**
     * Forcefully remove a lock on the page given
     *
     * @param string $wiki_id
     */
    protected function deleteLock($wiki_id) {
        $wikiLockFN = wikiLockFN($wiki_id);

        if(file_exists($wikiLockFN)) {
            if(!unlink($wikiLockFN)) {
                $this->error("Unable to delete $wikiLockFN");
                exit(1);
            }
        }
    }

    /**
     * Get the current user's username from the environment
     *
     * @return string
     */
    protected function getUser() {
        $user = getenv('USER');
        if(empty ($user)) {
            $user = getenv('USERNAME');
        } else {
            return $user;
        }
        if(empty ($user)) {
            $user = 'admin';
        }
        return $user;
    }
}

// Main
$cli = new PageCLI();
$cli->run();