text:
'use strict';
var _ = require('lodash');
var $ = require('preconditions').singleton();
var async = require('async');
var log = require('npmlog');
log.debug = log.verbose;

var WalletUtils = require('bitcore-wallet-utils');
var Bitcore = WalletUtils.Bitcore;
var PublicKey = Bitcore.PublicKey;
var HDPublicKey = Bitcore.HDPublicKey;
var Address = Bitcore.Address;

var ClientError = require('./clienterror');
var Utils = require('./utils');
var Lock = require('./lock');
var Storage = require('./storage');
var NotificationBroadcaster = require('./notificationbroadcaster');
var BlockchainExplorer = require('./blockchainexplorer');

var Wallet = require('./model/wallet');
var Copayer = require('./model/copayer');
var Address = require('./model/address');
var TxProposal = require('./model/txproposal');
var Notification = require('./model/notification');

var initialized = false;
var lock, storage, blockchainExplorer, blockchainExplorerOpts;

/**
 * Creates an instance of the Bitcore Wallet Service.
 * @constructor
 */
function WalletService() {
  if (!initialized)
    throw new Error('Server not initialized');

  this.lock = lock;
  this.storage = storage;
  this.blockchainExplorer = blockchainExplorer;
  this.blockchainExplorerOpts = blockchainExplorerOpts;
  this.notifyTicker = 0;
};

WalletService.onNotification = function(func) {
  NotificationBroadcaster.on('notification', func);
};

/**
 * Initializes global settings for all instances.
 * @param {Object} opts
 * @param {Storage} [opts.storage] - The storage provider.
 * @param {Storage} [opts.blockchainExplorer] - The blockchainExporer provider.
 */
WalletService.initialize = function(opts) {
  opts = opts || {};
  lock = opts.lock || new Lock(opts.lockOpts);
  storage = opts.storage || new Storage(opts.storageOpts);
  blockchainExplorer = opts.blockchainExplorer;
  blockchainExplorerOpts = opts.blockchainExplorerOpts;
  initialized = true;
};

WalletService.getInstance = function() {
  return new WalletService();
};

/**
 * Gets an instance of the server after authenticating the copayer.
 * @param {Object} opts
 * @param {string} opts.copayerId - The copayer id making the request.
 * @param {string} opts.message - The contents of the request to be signed.
 * @param {string} opts.signature - Signature of message to be verified using the copayer's requestPubKey
 */
WalletService.getInstanceWithAuth = function(opts, cb) {

  if (!Utils.checkRequired(opts, ['copayerId', 'message', 'signature']))
    return cb(new ClientError('Required argument missing'));

  var server = new WalletService();
  server.storage.fetchCopayerLookup(opts.copayerId, function(err, copayer) {
    if (err) return cb(err);
    if (!copayer) return cb(new ClientError('NOTAUTHORIZED', 'Copayer not found'));

    var isValid = server._verifySignature(opts.message, opts.signature, copayer.requestPubKey);
    if (!isValid)
      return cb(new ClientError('NOTAUTHORIZED', 'Invalid signature'));

    server.copayerId = opts.copayerId;
    server.walletId = copayer.walletId;
    return cb(null, server);
  });
};

WalletService.prototype._runLocked = function(cb, task) {
  $.checkState(this.walletId);
  this.lock.runLocked(this.walletId, cb, task);
};

/**
 * Creates a new wallet.
 * @param {Object} opts
 * @param {string} opts.id - The wallet id.
 * @param {string} opts.name - The wallet name.
 * @param {number} opts.m - Required copayers.
 * @param {number} opts.n - Total copayers.
 * @param {string} opts.pubKey - Public key to verify copayers joining have access to the wallet secret.
 * @param {string} [opts.network = 'livenet'] - The Bitcoin network for this wallet.
 */
WalletService.prototype.createWallet = function(opts, cb) {
  var self = this,
    pubKey;

  if (!Utils.checkRequired(opts, ['name', 'm', 'n', 'pubKey']))
    return cb(new ClientError('Required argument missing'));

  if (_.isEmpty(opts.name)) return cb(new ClientError('Invalid wallet name'));
  if (!Wallet.verifyCopayerLimits(opts.m, opts.n))
    return cb(new ClientError('Invalid combination of required copayers / total copayers'));

  var network = opts.network || 'livenet';
  if (network != 'livenet' && network != 'testnet')
    return cb(new ClientError('Invalid network'));

  try {
    pubKey = new PublicKey.fromString(opts.pubKey);
  } catch (ex) {
    return cb(new ClientError('Invalid public key'));
  };

  var newWallet;
  async.series([

    function(acb) {
      if (!opts.id)
        return acb();

      self.storage.fetchWallet(opts.id, function(err, wallet) {
        if (wallet) return acb(new ClientError('WEXISTS', 'Wallet already exists'));
        return acb(err);
      });
    },
    function(acb) {
      var wallet = Wallet.create({
        name: opts.name,
        m: opts.m,
        n: opts.n,
        network: network,
        pubKey: pubKey.toString(),
        id: opts.id,
      });
      self.storage.storeWallet(wallet, function(err) {
        log.debug('Wallet created', wallet.id, network);
        newWallet = wallet;
        return acb(err);
      });
    }
  ], function(err) {
    return cb(err, newWallet ? newWallet.id : null);
  });
};

/**
 * Retrieves a wallet from storage.
 * @param {Object} opts
 * @returns {Object} wallet
 */
WalletService.prototype.getWallet = function(opts, cb) {
  var self = this;

  self.storage.fetchWallet(self.walletId, function(err, wallet) {
    if (err) return cb(err);
    if (!wallet) return cb(new ClientError('Wallet not found'));
    return cb(null, wallet);
  });
};

/**
 * Replace temporary request key
 * @param {Object} opts
 * @param {string} opts.name - The copayer name.
 * @param {string} opts.xPubKey - Extended Public Key for this copayer.
 * @param {string} opts.requestPubKey - Public Key used to check requests from this copayer.
 * @param {string} opts.copayerSignature - S(name|xPubKey|requestPubKey). Used by other copayers to verify the that the copayer joining knows the wallet secret.
 */
WalletService.prototype.replaceTemporaryRequestKey = function(opts, cb) {
  var self = this;

  if (!Utils.checkRequired(opts, ['name', 'xPubKey', 'requestPubKey', 'copayerSignature']))
    return cb(new ClientError('Required argument missing'));

  if (_.isEmpty(opts.name))
    return cb(new ClientError('Invalid copayer name'));

  if (opts.isTemporaryRequestKey)
    return cb(new ClientError('Bad arguments'));

  self._runLocked(cb, function(cb) {
    self.storage.fetchWallet(self.walletId, function(err, wallet) {
      if (err) return cb(err);

      if (!wallet) return cb(new ClientError('Wallet not found'));
      var hash = WalletUtils.getCopayerHash(opts.name, opts.xPubKey, opts.requestPubKey);
      if (!self._verifySignature(hash, opts.copayerSignature, wallet.pubKey)) {
        return cb(new ClientError());
      }

      var oldCopayerData = _.find(wallet.copayers, {
        id: self.copayerId
      });
      $.checkState(oldCopayerData);

      if (oldCopayerData.xPubKey !== opts.xPubKey || !oldCopayerData.isTemporaryRequestKey)
        return cb(new ClientError('CDATAMISMATCH', 'Copayer data mismatch'));

      if (wallet.copayers.length != wallet.n)
        return cb(new ClientError('WNOTFULL', 'Replace only works on full wallets'));

      wallet.updateCopayerRequestKey(self.copayerId, opts.requestPubKey, opts.copayerSignature);

      self.storage.storeWalletAndUpdateCopayersLookup(wallet, function(err) {
        if (err) return cb(err);

        self._notify('CopayerUpdated', {
          walletId: opts.walletId,
          copayerId: self.copayerId,
          copayerName: opts.name,
        });

        return cb(null, {
          copayerId: self.copayerId,
          wallet: wallet
        });
      });
    });
  });
};

/**
 * Verifies a signature
 * @param text
 * @param signature
 * @param pubKey
 */
WalletService.prototype._verifySignature = function(text, signature, pubKey) {
  return WalletUtils.verifyMessage(text, signature, pubKey);
};

/**
 * _emit
 *
 * @param {Object} args
 */
WalletService.prototype._emit = function(eventName, args) {
  NotificationBroadcaster.broadcast(eventName, args);
};

/**
 * _notify
 *
 * @param {String} type
 * @param {Object} data
 * @param {Boolean} isGlobal - If true, the notification is not issued on behalf of any particular copayer (defaults to false)
 */
WalletService.prototype._notify = function(type, data, isGlobal) {
  var self = this;

  log.debug('Notification', type, data);

  var walletId = self.walletId || data.walletId;
  var copayerId = self.copayerId || data.copayerId;

  $.checkState(walletId);

  var n = Notification.create({
    type: type,
    data: data,
    ticker: this.notifyTicker++,
    creatorId: isGlobal ? null : copayerId,
    walletId: walletId,
  });
  this.storage.storeNotification(walletId, n, function() {
    self._emit('notification', n);
  });
};

/**
 * Joins a wallet in creation.
 * @param {Object} opts
 * @param {string} opts.walletId - The wallet id.
 * @param {string} opts.name - The copayer name.
 * @param {string} opts.xPubKey - Extended Public Key for this copayer.
 * @param {string} opts.requestPubKey - Public Key used to check requests from this copayer.
 * @param {string} opts.copayerSignature - S(name|xPubKey|requestPubKey). Used by other copayers to verify the that the copayer joining knows the wallet secret.
 * @param {string} opts.isTemporaryRequestKey - requestPubKey will be marked as 'temporary' (only used for Copay migration)
 */
WalletService.prototype.joinWallet = function(opts, cb) {
  var self = this;

  if (!Utils.checkRequired(opts, ['walletId', 'name', 'xPubKey', 'requestPubKey', 'copayerSignature']))
    return cb(new ClientError('Required argument missing'));

  if (_.isEmpty(opts.name))
    return cb(new ClientError('Invalid copayer name'));

  self.walletId = opts.walletId;
  self._runLocked(cb, function(cb) {
    self.storage.fetchWallet(opts.walletId, function(err, wallet) {

      if (err) return cb(err);
      if (!wallet) return cb(new ClientError('Wallet not found'));

      var hash = WalletUtils.getCopayerHash(opts.name, opts.xPubKey, opts.requestPubKey);
      if (!self._verifySignature(hash, opts.copayerSignature, wallet.pubKey)) {
        return cb(new ClientError());
      }

      if (_.find(wallet.copayers, {
        xPubKey: opts.xPubKey
      })) return cb(new ClientError('CINWALLET', 'Copayer already in wallet'));

      if (wallet.copayers.length == wallet.n)
        return cb(new ClientError('WFULL', 'Wallet full'));

      var copayer = Copayer.create({
        name: opts.name,
        copayerIndex: wallet.copayers.length,
        xPubKey: opts.xPubKey,
        requestPubKey: opts.requestPubKey,
        signature: opts.copayerSignature,
        isTemporaryRequestKey: !!opts.isTemporaryRequestKey,
      });

      self.storage.fetchCopayerLookup(copayer.id, function(err, res) {
        if (err) return cb(err);
        if (res)
          return cb(new ClientError('CREGISTERED', 'Copayer ID already registered on server'));

        wallet.addCopayer(copayer);
        self.storage.storeWalletAndUpdateCopayersLookup(wallet, function(err) {
          if (err) return cb(err);

          self._notify('NewCopayer', {
            walletId: opts.walletId,
            copayerId: copayer.id,
            copayerName: copayer.name,
          });
          return cb(null, {
            copayerId: copayer.id,
            wallet: wallet
          });
        });
      });
    });
  });
};

/**
 * Creates a new address.
 * @param {Object} opts
 * @returns {Address} address
 */
WalletService.prototype.createAddress = function(opts, cb) {
  var self = this;

  self._runLocked(cb, function(cb) {
    self.getWallet({}, function(err, wallet) {
      if (err) return cb(err);
      if (!wallet.isComplete())
        return cb(new ClientError('Wallet is not complete'));

      var address = wallet.createAddress(false);

      self.storage.storeAddressAndWallet(wallet, address, function(err) {
        if (err) return cb(err);

        self._notify('NewAddress', {
          address: address.address,
        });
        return cb(null, address);
      });
    });
  });
};

/**
 * Get all addresses.
 * @param {Object} opts
 * @returns {Address[]}
 */
WalletService.prototype.getMainAddresses = function(opts, cb) {
  var self = this;

  self.storage.fetchAddresses(self.walletId, function(err, addresses) {
    if (err) return cb(err);

    var onlyMain = _.reject(addresses, {
      isChange: true
    });
    return cb(null, onlyMain);
  });
};

/**
 * Verifies that a given message was actually sent by an authorized copayer.
 * @param {Object} opts
 * @param {string} opts.message - The message to verify.
 * @param {string} opts.signature - The signature of message to verify.
 * @returns {truthy} The result of the verification.
 */
WalletService.prototype.verifyMessageSignature = function(opts, cb) {
  var self = this;

  if (!Utils.checkRequired(opts, ['message', 'signature']))
    return cb(new ClientError('Required argument missing'));

  self.getWallet({}, function(err, wallet) {
    if (err) return cb(err);

    var copayer = wallet.getCopayer(self.copayerId);

    var isValid = self._verifySignature(opts.message, opts.signature, copayer.requestPubKey);
    return cb(null, isValid);
  });
};

WalletService.prototype._getBlockchainExplorer = function(provider, network) {
  if (!this.blockchainExplorer) {
    var opts =  {};
    if (this.blockchainExplorerOpts && this.blockchainExplorerOpts[network]) {
      opts =  this.blockchainExplorerOpts[network];
    }
    opts.provider = provider;
    opts.network = network;
    this.blockchainExplorer = new BlockchainExplorer(opts);
  }

  return this.blockchainExplorer;
};

/**
 * _getUtxos
 *
 */
WalletService.prototype._getUtxos = function(cb) {
  var self = this;

  // Get addresses for this wallet
  self.storage.fetchAddresses(self.walletId, function(err, addresses) {
    if (err) return cb(err);
    if (addresses.length == 0) return cb(null, []);

    var addressStrs = _.pluck(addresses, 'address');
    var addressToPath = _.indexBy(addresses, 'address'); // TODO : check performance
    var networkName = Bitcore.Address(addressStrs[0]).toObject().network;

    var bc = self._getBlockchainExplorer('insight', networkName);
    bc.getUnspentUtxos(addressStrs, function(err, inutxos) {
      if (err) return cb(new Error('Could not fetch unspend outputs:' + err));
      var utxos = _.map(inutxos, function(i) {
        return _.pick(i.toObject(), ['txid', 'vout', 'address', 'scriptPubKey', 'amount', 'satoshis']);
      });
      self.getPendingTxs({}, function(err, txps) {
        if (err) return cb(err);

        var utxoKey = function(utxo) {
          return utxo.txid + '|' + utxo.vout
        };

        var inputs = _.chain(txps)
          .pluck('inputs')
          .flatten()
          .map(utxoKey)
          .value();

        var dictionary = _.reduce(utxos, function(memo, utxo) {
          memo[utxoKey(utxo)] = utxo;
          return memo;
        }, {});

        _.each(inputs, function(input) {
          if (dictionary[input]) {
            dictionary[input].locked = true;
          }
        });

        // Needed for the clients to sign UTXOs
        _.each(utxos, function(utxo) {
          utxo.satoshis = utxo.satoshis ? +utxo.satoshis : Utils.strip(utxo.amount * 1e8);
          delete utxo.amount;
          utxo.path = addressToPath[utxo.address].path;
          utxo.publicKeys = addressToPath[utxo.address].publicKeys;
        });

        return cb(null, utxos);
      });
    });
  });
};

WalletService.prototype._totalizeUtxos = function(utxos) {
  var balance = {};
  balance.totalAmount = Utils.strip(_.reduce(utxos, function(sum, utxo) {
    return sum + utxo.satoshis;
  }, 0));

  balance.lockedAmount = Utils.strip(_.reduce(_.filter(utxos, {
    locked: true
  }), function(sum, utxo) {
    return sum + utxo.satoshis;
  }, 0));
  return balance;
};

/**
 * Creates a new transaction proposal.
 * @param {Object} opts
 * @returns {Object} balance - Total amount & locked amount.
 */
WalletService.prototype.getBalance = function(opts, cb) {
  var self = this;

  self._getUtxos(function(err, utxos) {
    if (err) return cb(err);

    var balance = self._totalizeUtxos(utxos);

    // Compute balance by address
    var byAddress = {};
    _.each(_.indexBy(utxos, 'address'), function(value, key) {
      byAddress[key] = {
        address: key,
        path: value.path,
        amount: 0,
      };
    });

    _.each(utxos, function(utxo) {
      byAddress[utxo.address].amount += utxo.satoshis;
    });

    balance.byAddress = _.values(byAddress);

    return cb(null, balance);
  });
};

WalletService.prototype._selectTxInputs = function(txp, cb) {
  var self = this;

  self._getUtxos(function(err, utxos) {
    if (err) return cb(err);

    var balance = self._totalizeUtxos(utxos);

    if (balance.totalAmount < txp.amount)
      return cb(new ClientError('INSUFFICIENTFUNDS', 'Insufficient funds'));
    if ((balance.totalAmount - balance.lockedAmount) < txp.amount)
      return cb(new ClientError('LOCKEDFUNDS', 'Funds are locked by pending transaction proposals'));

    utxos = _.reject(utxos, {
      locked: true
    });

    var i = 0;
    var total = 0;
    var selected = [];
    var inputs = _.sortBy(utxos, 'amount');
    var bitcoreTx, bitcoreError;

    while (i < inputs.length) {
      selected.push(inputs[i]);
      total += inputs[i].satoshis;
      i++;

      if (total >= txp.amount) {
        try {
          txp.inputs = selected;
          bitcoreTx = txp.getBitcoreTx();
          bitcoreError = bitcoreTx.getSerializationError({
            disableIsFullySigned: true,
          });
          if (!bitcoreError) {
            txp.inputPaths = _.pluck(txp.inputs, 'path');
            txp.fee = bitcoreTx.getFee();
            return cb();
          }
        } catch (ex) {
          return cb(ex);
        }
      }
    };

    if (bitcoreError instanceof Bitcore.errors.Transaction.FeeError) {
      return cb(new ClientError('INSUFFICIENTFUNDS', 'Insufficient funds for fee'));
    }
    if (bitcoreError instanceof Bitcore.errors.Transaction.DustOutputs) {
      return cb(new ClientError('DUSTAMOUNT', 'Amount below dust threshold'));
    }

    return cb(bitcoreError || new Error('Could not select tx inputs'));
  });
};

/**
 * Creates a new transaction proposal.
 * @param {Object} opts
 * @param {string} opts.toAddress - Destination address.
 * @param {number} opts.amount - Amount to transfer in satoshi.
 * @param {string} opts.message - A message to attach to this transaction.
 * @param {string} opts.proposalSignature - S(toAddress|amount|message|payProUrl). Used by other copayers to verify the proposal.
 * @param {string} opts.payProUrl - Options: Paypro URL for peers to verify TX
 * @returns {TxProposal} Transaction proposal.
 */
WalletService.prototype.createTx = function(opts, cb) {
  var self = this;

  if (!Utils.checkRequired(opts, ['toAddress', 'amount', 'proposalSignature']))
    return cb(new ClientError('Required argument missing'));

  self._runLocked(cb, function(cb) {
    self.getWallet({}, function(err, wallet) {
      if (err) return cb(err);
      if (!wallet.isComplete()) return cb(new ClientError('Wallet is not complete'));

      var copayer = wallet.getCopayer(self.copayerId);
      var hash = WalletUtils.getProposalHash(opts.toAddress, opts.amount, opts.message, opts.payProUrl);
      if (!self._verifySignature(hash, opts.proposalSignature, copayer.requestPubKey))
        return cb(new ClientError('Invalid proposal signature'));

      var toAddress;
      try {
        toAddress = new Bitcore.Address(opts.toAddress);
      } catch (ex) {
        return cb(new ClientError('INVALIDADDRESS', 'Invalid address'));
      }
      if (toAddress.network != wallet.getNetworkName())
        return cb(new ClientError('INVALIDADDRESS', 'Incorrect address network'));

      if (opts.amount <= 0)
        return cb(new ClientError('Invalid amount'));

      if (opts.amount < Bitcore.Transaction.DUST_AMOUNT)
        return cb(new ClientError('DUSTAMOUNT', 'Amount below dust threshold'));

      var changeAddress = wallet.createAddress(true);

      var txp = TxProposal.create({
        walletId: self.walletId,
        creatorId: self.copayerId,
        toAddress: opts.toAddress,
        amount: opts.amount,
        message: opts.message,
        proposalSignature: opts.proposalSignature,
        payProUrl: opts.payProUrl,
        changeAddress: changeAddress,
        requiredSignatures: wallet.m,
        requiredRejections: Math.min(wallet.m, wallet.n - wallet.m + 1),
      });

      self._selectTxInputs(txp, function(err) {
        if (err) return cb(err);

        $.checkState(txp.inputs);

        self.storage.storeAddressAndWallet(wallet, changeAddress, function(err) {
          if (err) return cb(err);

          self.storage.storeTx(wallet.id, txp, function(err) {
            if (err) return cb(err);

            self._notify('NewTxProposal', {
              amount: opts.amount
            });
            return cb(null, txp);
          });
        });
      });
    });
  });
};

/**
 * Retrieves a tx from storage.
 * @param {Object} opts
 * @param {string} opts.txProposalId - The tx id.
 * @returns {Object} txProposal
 */
WalletService.prototype.getTx = function(opts, cb) {
  var self = this;

  self.storage.fetchTx(self.walletId, opts.txProposalId, function(err, txp) {
    if (err) return cb(err);
    if (!txp) return cb(new ClientError('Transaction proposal not found'));
    return cb(null, txp);
  });
};

/**
 * removeWallet
 *
 * @param opts
 * @param cb
 * @return {undefined}
 */
WalletService.prototype.removeWallet = function(opts, cb) {
  var self = this;

  self._runLocked(cb, function(cb) {
    self.storage.removeWallet(self.walletId, cb);
  });
};

/**
 * removePendingTx
 *
 * @param opts
 * @param {string} opts.txProposalId - The tx id.
 * @return {undefined}
 */
WalletService.prototype.removePendingTx = function(opts, cb) {
  var self = this;

  if (!Utils.checkRequired(opts, ['txProposalId']))
    return cb(new ClientError('Required argument missing'));

  self._runLocked(cb, function(cb) {

    self.getTx({
      txProposalId: opts.txProposalId,
    }, function(err, txp) {
      if (err) return cb(err);

      if (!txp.isPending())
        return cb(new ClientError('TXNOTPENDING', 'Transaction proposal not pending'));

      if (txp.creatorId !== self.copayerId)
        return cb(new ClientError('Only creators can remove pending proposals'));

      var actors = txp.getActors();

      if (actors.length > 1 || (actors.length == 1 && actors[0] !== self.copayerId))
        return cb(new ClientError('TXACTIONED', 'Cannot remove a proposal signed/rejected by other copayers'));

      self._notify('TxProposalRemoved');
      self.storage.removeTx(self.walletId, txp.id, cb);
    });
  });
};

WalletService.prototype._broadcastTx = function(txp, cb) {
  var raw;
  try {
    raw = txp.getRawTx();
  } catch (ex) {
    return cb(ex);
  }
  var bc = this._getBlockchainExplorer('insight', txp.getNetworkName());
  bc.broadcast(raw, function(err, txid) {
    return cb(err, txid);
  })
};

/**
 * Sign a transaction proposal.
 * @param {Object} opts
 * @param {string} opts.txProposalId - The identifier of the transaction.
 * @param {string} opts.signatures - The signatures of the inputs of this tx for this copayer (in apperance order)
 */
WalletService.prototype.signTx = function(opts, cb) {
  var self = this;

  if (!Utils.checkRequired(opts, ['txProposalId', 'signatures']))
    return cb(new ClientError('Required argument missing'));

  self.getWallet({}, function(err, wallet) {
    if (err) return cb(err);

    self.getTx({
      txProposalId: opts.txProposalId
    }, function(err, txp) {
      if (err) return cb(err);

      var action = _.find(txp.actions, {
        copayerId: self.copayerId
      });
      if (action)
        return cb(new ClientError('CVOTED', 'Copayer already voted on this transaction proposal'));
      if (!txp.isPending())
        return cb(new ClientError('TXNOTPENDING', 'The transaction proposal is not pending'));

      var copayer = wallet.getCopayer(self.copayerId);

      if (!txp.sign(self.copayerId, opts.signatures, copayer.xPubKey))
        return cb(new ClientError('BADSIGNATURES', 'Bad signatures'));

      self.storage.storeTx(self.walletId, txp, function(err) {
        if (err) return cb(err);

        self._notify('TxProposalAcceptedBy', {
          txProposalId: opts.txProposalId,
          copayerId: self.copayerId,
        });

        if (txp.isAccepted()) {
          self._notify('TxProposalFinallyAccepted', {
            txProposalId: opts.txProposalId,
          });
        }

        return cb(null, txp);
      });
    });
  });
};

/**
 * Broadcast a transaction proposal.
 * @param {Object} opts
 * @param {string} opts.txProposalId - The identifier of the transaction.
 */
WalletService.prototype.broadcastTx = function(opts, cb) {
  var self = this;

  if (!Utils.checkRequired(opts, ['txProposalId']))
    return cb(new ClientError('Required argument missing'));

  self.getWallet({}, function(err, wallet) {
    if (err) return cb(err);

    self.getTx({
      txProposalId: opts.txProposalId
    }, function(err, txp) {
      if (err) return cb(err);

      if (txp.status == 'broadcasted')
        return cb(new ClientError('TXALREADYBROADCASTED', 'The transaction proposal is already broadcasted'));

      if (txp.status != 'accepted')
        return cb(new ClientError('TXNOTACCEPTED', 'The transaction proposal is not accepted'));

      self._broadcastTx(txp, function(err, txid) {
        if (err) return cb(err);

        txp.setBroadcasted(txid);
        self.storage.storeTx(self.walletId, txp, function(err) {
          if (err) return cb(err);

          self._notify('NewOutgoingTx', {
            txProposalId: opts.txProposalId,
            txid: txid
          });

          return cb(null, txp);
        });
      });
    });
  });
};

/**
 * Reject a transaction proposal.
 * @param {Object} opts
 * @param {string} opts.txProposalId - The identifier of the transaction.
 * @param {string} [opts.reason] - A message to other copayers explaining the rejection.
 */
WalletService.prototype.rejectTx = function(opts, cb) {
  var self = this;

  if (!Utils.checkRequired(opts, ['txProposalId']))
    return cb(new ClientError('Required argument missing'));

  self.getTx({
    txProposalId: opts.txProposalId
  }, function(err, txp) {
    if (err) return cb(err);

    var action = _.find(txp.actions, {
      copayerId: self.copayerId
    });
    if (action)
      return cb(new ClientError('CVOTED', 'Copayer already voted on this transaction proposal'));

    if (txp.status != 'pending')
      return cb(new ClientError('TXNOTPENDING', 'The transaction proposal is not pending'));

    txp.reject(self.copayerId, opts.reason);

    self.storage.storeTx(self.walletId, txp, function(err) {
      if (err) return cb(err);

      self._notify('TxProposalRejectedBy', {
        txProposalId: opts.txProposalId,
        copayerId: self.copayerId,
      });

      if (txp.status == 'rejected') {
        self._notify('TxProposalFinallyRejected', {
          txProposalId: opts.txProposalId,
        });
      };

      return cb(null, txp);
    });
  });
};

/**
 * Retrieves pending transaction proposals.
 * @param {Object} opts
 * @returns {TxProposal[]} Transaction proposal.
 */
WalletService.prototype.getPendingTxs = function(opts, cb) {
  var self = this;

  self.storage.fetchPendingTxs(self.walletId, function(err, txps) {
    if (err) return cb(err);

    return cb(null, txps);
  });
};

/**
 * Retrieves all transaction proposals in the range (maxTs-minTs)
 * Times are in UNIX EPOCH
 *
 * @param {Object} opts.minTs (defaults to 0)
 * @param {Object} opts.maxTs (defaults to now)
 * @param {Object} opts.limit
 * @returns {TxProposal[]} Transaction proposals, first newer
 */
WalletService.prototype.getTxs = function(opts, cb) {
  var self = this;
  self.storage.fetchTxs(self.walletId, opts, function(err, txps) {
    if (err) return cb(err);
    return cb(null, txps);
  });
};

/**
 * Retrieves notifications in the range (maxTs-minTs).
 * Times are in UNIX EPOCH. Order is assured even for events with the same time
 *
 * @param {Object} opts.minTs (defaults to 0)
 * @param {Object} opts.maxTs (defaults to now)
 * @param {Object} opts.limit
 * @param {Object} opts.reverse (default false)
 * @returns {Notification[]} Notifications
 */
WalletService.prototype.getNotifications = function(opts, cb) {
  var self = this;
  self.storage.fetchNotifications(self.walletId, opts, function(err, notifications) {
    if (err) return cb(err);
    return cb(null, notifications);
  });
};

WalletService.prototype._normalizeTxHistory = function(txs) {
  return _.map(txs, function(tx) {
    var inputs = _.map(tx.vin, function(item) {
      return {
        address: item.addr,
        amount: item.valueSat,
      }
    });

    var outputs = _.map(tx.vout, function(item) {
      var itemAddr;
      // If classic multisig, ignore
      if (item.scriptPubKey && item.scriptPubKey.addresses.length == 1) {
        itemAddr = item.scriptPubKey.addresses[0];
      }

      return {
        address: itemAddr,
        amount: parseInt((item.value * 1e8).toFixed(0)),
      }
    });

    return {
      txid: tx.txid,
      confirmations: tx.confirmations,
      fees: parseInt((tx.fees * 1e8).toFixed(0)),
      time: !_.isNaN(tx.time) ? tx.time : Math.floor(Date.now() / 1000),
      inputs: inputs,
      outputs: outputs,
    };
  });
};

/**
 * Retrieves all transactions (incoming & outgoing)
 * Times are in UNIX EPOCH
 *
 * @param {Object} opts
 * @param {Number} opts.skip (defaults to 0)
 * @param {Number} opts.limit
 * @returns {TxProposal[]} Transaction proposals, first newer
 */
WalletService.prototype.getTxHistory = function(opts, cb) {
  var self = this;

  function decorate(txs, addresses, proposals) {

    var indexedAddresses = _.indexBy(addresses, 'address');
    var indexedProposals = _.indexBy(proposals, 'txid');

    function sum(items, isMine, isChange) {
      var filter = {};
      if (_.isBoolean(isMine)) filter.isMine = isMine;
      if (_.isBoolean(isChange)) filter.isChange = isChange;
      return _.reduce(_.where(items, filter),
        function(memo, item) {
          return memo + item.amount;
        }, 0);
    };

    function classify(items) {
      return _.map(items, function(item) {
        var address = indexedAddresses[item.address];
        return {
          address: item.address,
          amount: item.amount,
          isMine: !!address,
          isChange: address ? address.isChange : false,
        }
      });
    };

    var now = Math.floor(Date.now() / 1000);

    return _.map(txs, function(tx) {
      var inputs = classify(tx.inputs);
      var outputs = classify(tx.outputs);

      var amountIn = sum(inputs, true);
      var amountOut = sum(outputs, true, false);
      var amountOutChange = sum(outputs, true, true);
      var amount, action, addressTo;
      if (amountIn == (amountOut + amountOutChange + (amountIn > 0 ? tx.fees : 0))) {
        amount = amountOut;
        action = 'moved';
      } else {
        amount = amountIn - amountOut - amountOutChange - (amountIn > 0 ? tx.fees : 0);
        action = amount > 0 ? 'sent' : 'received';
      }

      amount = Math.abs(amount);
      if (action == 'sent' || action == 'moved') {
        var firstExternalOutput = _.find(outputs, {
          isMine: false
        });
        addressTo = firstExternalOutput ? firstExternalOutput.address : 'N/A';
      };

      var newTx = {
        txid: tx.txid,
        action: action,
        amount: amount,
        fees: tx.fees,
        time: tx.time || now,
        addressTo: addressTo,
        confirmations: tx.confirmations,
      };

      var proposal = indexedProposals[tx.txid];
      if (proposal) {
        newTx.proposalId = proposal.id;
        newTx.creatorName = proposal.creatorName;
        newTx.message = proposal.message;
        newTx.actions = _.map(proposal.actions, function(action) {
          return _.pick(action, ['createdOn', 'type', 'copayerId', 'copayerName', 'comment']);
        });
        // newTx.sentTs = proposal.sentTs;
        // newTx.merchant = proposal.merchant;
        //newTx.paymentAckMemo = proposal.paymentAckMemo;
      }

      return newTx;
    });
  };

  function paginate(txs) {
    var skip = opts.skip || 0;
    var limited = _.isNumber(opts.limit) && opts.limit != -1;

    var sliced = _.slice(_.sortBy(txs, function(tx) {
      return -tx.time;
    }), skip);

    return limited ? _.take(sliced, opts.limit) : sliced;
  };

  // Get addresses for this wallet
  self.storage.fetchAddresses(self.walletId, function(err, addresses) {
    if (err) return cb(err);
    if (addresses.length == 0) return cb(null, []);

    var addressStrs = _.pluck(addresses, 'address');
    var networkName = Bitcore.Address(addressStrs[0]).toObject().network;

    var bc = self._getBlockchainExplorer('insight', networkName);
    async.parallel([

      function(next) {
        self.storage.fetchTxs(self.walletId, opts, function(err, txps) {
          if (err) return next(err);
          next(null, txps);
        });
      },
      function(next) {
        bc.getTransactions(addressStrs, null, null, function(err, txs) {
          if (err) return next(new Error('Could not fetch transactions: ' + err));

          next(null, self._normalizeTxHistory(txs));
        });
      },
    ], function(err, res) {
      if (err) return cb(err);

      var proposals = res[0];
      var txs = res[1];

      txs = paginate(decorate(txs, addresses, proposals));

      return cb(null, txs);
    });
  });
};

WalletService.scanConfig = {
  SCAN_WINDOW: 20,
  DERIVATION_DELAY: 10, // in milliseconds
};

/**
 * Scan the blockchain looking for addresses having some activity
 *
 * @param {Object} opts
 * @param {Boolean} opts.includeCopayerBranches (defaults to false)
 */
WalletService.prototype.scan = function(opts, cb) {
  var self = this;

  opts = opts || {};

  function deriveAddresses(size, derivator, cb) {
    async.mapSeries(_.range(size), function(i, next) {
      setTimeout(function() {
        next(null, derivator());
      }, WalletService.scanConfig.DERIVATION_DELAY)
    }, cb);
  };

  function checkActivity(addresses, networkName, cb) {
    var bc = self._getBlockchainExplorer('insight', networkName);
    bc.getAddressActivity(addresses, cb);
  };

  function scanBranch(derivator, cb) {
    var activity = true;
    var allAddresses = [];
    var networkName;
    async.whilst(function() {
      return activity;
    }, function(next) {
      deriveAddresses(WalletService.scanConfig.SCAN_WINDOW, derivator, function(err, addresses) {
        if (err) return next(err);
        networkName = networkName || Bitcore.Address(addresses[0].address).toObject().network;
        allAddresses.push(addresses);
        checkActivity(_.pluck(addresses, 'address'), networkName, function(err, thereIsActivity) {
          if (err) return next(new Error('Could not fetch TX activity:' + err));
          activity = thereIsActivity;
          next();
        });
      });
    }, function(err) {
      return cb(err, _.flatten(allAddresses));
    });
  };

  self._runLocked(cb, function(cb) {
    self.getWallet({}, function(err, wallet) {
      if (err) return cb(err);
      if (!wallet.isComplete()) return cb(new ClientError('Wallet is not complete'));

      wallet.scanStatus = 'running';
      self.storage.storeWallet(wallet, function(err) {
        if (err) return cb(err);

        var derivators = [];
        _.each([false, true], function(isChange) {
          derivators.push(_.bind(wallet.createAddress, wallet, isChange));
          if (opts.includeCopayerBranches) {
            _.each(wallet.copayers, function(copayer) {
              derivators.push(_.bind(copayer.createAddress, copayer, wallet, isChange));
            });
          }
        });

        async.eachSeries(derivators, function(derivator, next) {
          scanBranch(derivator, function(err, addresses) {
            if (err) return next(err);
            self.storage.storeAddressAndWallet(wallet, addresses, next);
          });
        }, function(err) {
          wallet.scanStatus = err ? 'error' : 'success';
          self.storage.storeWallet(wallet, function() {
            return cb(err);
          });
        });
      });
    });
  });
};

/**
 * Start a scan process.
 *
 * @param {Object} opts
 * @param {Boolean} opts.includeCopayerBranches (defaults to false)
 */
WalletService.prototype.startScan = function(opts, cb) {
  var self = this;

  function scanFinished(err) {
    var data = {
      result: err ? 'error' : 'success',
    };
    if (err) data.error = err;
    self._notify('ScanFinished', data, true);
  };

  self.getWallet({}, function(err, wallet) {
    if (err) return cb(err);
    if (!wallet.isComplete()) return cb(new ClientError('Wallet is not complete'));

    setTimeout(function() {
      self.scan(opts, scanFinished);
    }, 100);

    return cb(null, {
      started: true
    });
  });
};

module.exports = WalletService;
module.exports.ClientError = ClientError;


text:
package de.ahlfeld.breminale.app.services;

import android.content.Intent;

import com.google.android.gms.iid.InstanceIDListenerService;

/**
 * Created by bjornahlfeld on 25.04.16.
 */
public class BreminaleInstanceIDListenerService extends InstanceIDListenerService {

    /**
     * Called if InstanceID token is updated. This may occur if the security of
     * the previous token had been compromised. This call is initiated by the
     * InstanceID provider.
     */
    //[START refresh_token]
    @Override
    public void onTokenRefresh() {
        Intent intent = new Intent(this, GcmRegistrationService.class);
        startService(intent);
    }
    //[END refresh_token]
}

redpajama_set_name: RedPajamaGithub


text:
An example chat application implemented in Clojure and ClojureScript

## Overview

FIXME: Write a paragraph about the library/project and highlight its goals.

## Project Organization

- `src/common`
  Contains `.cljc` files that are shared between the backend server
  code and the frontend web client code
- `src/web`
  Contains `.cljs` and `.clj` (macro) files making up the bulk of web client code
- `src/server`
  Contains `.clj` files making up the bulk of the backend server code

## Setup

These instructions assume you have correctly installed and configured
[Java 8](http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html)
and
[Leiningen](http://leiningen.org/).

To get an interactive development environment run:

    lein figwheel

and open your browser at [localhost:3449](http://localhost:3449/).
This will auto compile and send all changes to the browser without the
need to reload. After the compilation process is complete, you will
get a Browser Connected REPL. An easy way to try it is:

    (js/alert "Am I connected?")

and you should see an alert in the browser window.

To clean all compiled files:

    lein clean

To create a production build run:

    lein cljsbuild once min

And open your browser in `resources/public/index.html`. You will not
get live reloading, nor a REPL.

## License

```
The MIT License (MIT)

Copyright (c) 2015 Jedidiah T Clinger

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```


text:
"""Methods to allow pandas.DataFrame."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from tensorflow.python.estimator.inputs.pandas_import import HAS_PANDAS
from tensorflow.python.estimator.inputs.pandas_io import pandas_input_fn  # pylint: disable=unused-import

if HAS_PANDAS:
  # pylint: disable=g-import-not-at-top
  import pandas as pd

PANDAS_DTYPES = {
    'int8': 'int',
    'int16': 'int',
    'int32': 'int',
    'int64': 'int',
    'uint8': 'int',
    'uint16': 'int',
    'uint32': 'int',
    'uint64': 'int',
    'float16': 'float',
    'float32': 'float',
    'float64': 'float',
    'bool': 'i'
}

def extract_pandas_data(data):
  """Extract data from pandas.DataFrame for predictors.

  Given a DataFrame, will extract the values and cast them to float. The
  DataFrame is expected to contain values of type int, float or bool.

  Args:
    data: `pandas.DataFrame` containing the data to be extracted.

  Returns:
    A numpy `ndarray` of the DataFrame's values as floats.

  Raises:
    ValueError: if data contains types other than int, float or bool.
  """
  if not isinstance(data, pd.DataFrame):
    return data

  bad_data = [column for column in data
              if data[column].dtype.name not in PANDAS_DTYPES]

  if not bad_data:
    return data.values.astype('float')
  else:
    error_report = [("'" + str(column) + "' type='" +
                     data[column].dtype.name + "'") for column in bad_data]
    raise ValueError('Data types for extracting pandas data must be int, '
                     'float, or bool. Found: ' + ', '.join(error_report))

def extract_pandas_matrix(data):
  """Extracts numpy matrix from pandas DataFrame.

  Args:
    data: `pandas.DataFrame` containing the data to be extracted.

  Returns:
    A numpy `ndarray` of the DataFrame's values.
  """
  if not isinstance(data, pd.DataFrame):
    return data

  return data.as_matrix()

def extract_pandas_labels(labels):
  """Extract data from pandas.DataFrame for labels.

  Args:
    labels: `pandas.DataFrame` or `pandas.Series` containing one column of
      labels to be extracted.

  Returns:
    A numpy `ndarray` of labels from the DataFrame.

  Raises:
    ValueError: if more than one column is found or type is not int, float or
      bool.
  """
  if isinstance(labels,
                pd.DataFrame):  # pandas.Series also belongs to DataFrame
    if len(labels.columns) > 1:
      raise ValueError('Only one column for labels is allowed.')

    bad_data = [column for column in labels
                if labels[column].dtype.name not in PANDAS_DTYPES]
    if not bad_data:
      return labels.values
    else:
      error_report = ["'" + str(column) + "' type="
                      + str(labels[column].dtype.name) for column in bad_data]
      raise ValueError('Data types for extracting labels must be int, '
                       'float, or bool. Found: ' + ', '.join(error_report))
  else:
    return labels


text:
#include "test_precomp.hpp"
#ifdef HAVE_OPENCL
namespace
{
    /////////////////////////////////////////////////////////////////////////////////////////////////
    // BruteForceMatcher
    CV_ENUM(DistType, BruteForceMatcher_OCL_base::L1Dist,
                      BruteForceMatcher_OCL_base::L2Dist,
                      BruteForceMatcher_OCL_base::HammingDist)
    IMPLEMENT_PARAM_CLASS(DescriptorSize, int)
    PARAM_TEST_CASE(BruteForceMatcher, DistType, DescriptorSize)
    {
        cv::ocl::BruteForceMatcher_OCL_base::DistType distType;
        int normCode;
        int dim;

        int queryDescCount;
        int countFactor;

        cv::Mat query, train;

        virtual void SetUp()
        {
            distType = (cv::ocl::BruteForceMatcher_OCL_base::DistType)(int)GET_PARAM(0);
            dim = GET_PARAM(1);

            queryDescCount = 300; // must be even number because we split train data in some cases in two
            countFactor = 4; // do not change it

            cv::Mat queryBuf, trainBuf;

            // Generate query descriptors randomly.
            // Descriptor vector elements are integer values.
            queryBuf.create(queryDescCount, dim, CV_32SC1);
            rng.fill(queryBuf, cv::RNG::UNIFORM, cv::Scalar::all(0), cv::Scalar::all(3));
            queryBuf.convertTo(queryBuf, CV_32FC1);

            // Generate train decriptors as follows:
            // copy each query descriptor to train set countFactor times
            // and perturb some one element of the copied descriptors in
            // in ascending order. General boundaries of the perturbation
            // are (0.f, 1.f).
            trainBuf.create(queryDescCount * countFactor, dim, CV_32FC1);
            float step = 1.f / countFactor;
            for (int qIdx = 0; qIdx < queryDescCount; qIdx++)
            {
                cv::Mat queryDescriptor = queryBuf.row(qIdx);
                for (int c = 0; c < countFactor; c++)
                {
                    int tIdx = qIdx * countFactor + c;
                    cv::Mat trainDescriptor = trainBuf.row(tIdx);
                    queryDescriptor.copyTo(trainDescriptor);
                    int elem = rng(dim);
                    float diff = rng.uniform(step * c, step * (c + 1));
                    trainDescriptor.at<float>(0, elem) += diff;
                }
            }

            queryBuf.convertTo(query, CV_32F);
            trainBuf.convertTo(train, CV_32F);
        }
    };

#ifdef ANDROID
    OCL_TEST_P(BruteForceMatcher, DISABLED_Match_Single)
#else
    OCL_TEST_P(BruteForceMatcher, Match_Single)
#endif
    {
        cv::ocl::BruteForceMatcher_OCL_base matcher(distType);

        std::vector<cv::DMatch> matches;
        matcher.match(cv::ocl::oclMat(query),  cv::ocl::oclMat(train),  matches);

        ASSERT_EQ(static_cast<size_t>(queryDescCount), matches.size());

        int badCount = 0;
        for (size_t i = 0; i < matches.size(); i++)
        {
            cv::DMatch match = matches[i];
            if ((match.queryIdx != (int)i) || (match.trainIdx != (int)i * countFactor) || (match.imgIdx != 0))
                badCount++;
        }

        ASSERT_EQ(0, badCount);
    }

#ifdef ANDROID
    OCL_TEST_P(BruteForceMatcher, DISABLED_KnnMatch_2_Single)
#else
    OCL_TEST_P(BruteForceMatcher, KnnMatch_2_Single)
#endif
    {
        const int knn = 2;

        cv::ocl::BruteForceMatcher_OCL_base matcher(distType);

        std::vector< std::vector<cv::DMatch> > matches;
        matcher.knnMatch(cv::ocl::oclMat(query), cv::ocl::oclMat(train), matches, knn);

        ASSERT_EQ(static_cast<size_t>(queryDescCount), matches.size());

        int badCount = 0;
        for (size_t i = 0; i < matches.size(); i++)
        {
            if ((int)matches[i].size() != knn)
                badCount++;
            else
            {
                int localBadCount = 0;
                for (int k = 0; k < knn; k++)
                {
                    cv::DMatch match = matches[i][k];
                    if ((match.queryIdx != (int)i) || (match.trainIdx != (int)i * countFactor + k) || (match.imgIdx != 0))
                        localBadCount++;
                }
                badCount += localBadCount > 0 ? 1 : 0;
            }
        }

        ASSERT_EQ(0, badCount);
    }

#ifdef ANDROID
    OCL_TEST_P(BruteForceMatcher, DISABLED_RadiusMatch_Single)
#else
    OCL_TEST_P(BruteForceMatcher, RadiusMatch_Single)
#endif
    {
        float radius = 1.f / countFactor;

        cv::ocl::BruteForceMatcher_OCL_base matcher(distType);

        std::vector< std::vector<cv::DMatch> > matches;
        matcher.radiusMatch(cv::ocl::oclMat(query), cv::ocl::oclMat(train), matches, radius);

        ASSERT_EQ(static_cast<size_t>(queryDescCount), matches.size());

        int badCount = 0;
        for (size_t i = 0; i < matches.size(); i++)
        {
            if ((int)matches[i].size() != 1)
            {
                badCount++;
            }
            else
            {
                cv::DMatch match = matches[i][0];
                if ((match.queryIdx != (int)i) || (match.trainIdx != (int)i * countFactor) || (match.imgIdx != 0))
                    badCount++;
            }
        }

        ASSERT_EQ(0, badCount);
    }

    INSTANTIATE_TEST_CASE_P(OCL_Features2D, BruteForceMatcher,
        testing::Combine(
        testing::Values(
            DistType(cv::ocl::BruteForceMatcher_OCL_base::L1Dist),
            DistType(cv::ocl::BruteForceMatcher_OCL_base::L2Dist)/*,
            DistType(cv::ocl::BruteForceMatcher_OCL_base::HammingDist)*/
        ),
        testing::Values(
            DescriptorSize(57),
            DescriptorSize(64),
            DescriptorSize(83),
            DescriptorSize(128),
            DescriptorSize(179),
            DescriptorSize(256),
            DescriptorSize(304))
        )
    );
} // namespace
#endif


text:
<form class="company-search-container form-group">
    <input class="form-control" id="company-search-input" type="text" placeholder="Search for a company, e.g. Allianz" ng-model="search.query">
    <button id="company-search-button" class="btn btn-default" type="submit" ng-click="searchForCompany()" >Submit</button>
    Number of results per source :<input id="nb-results-input" type="text" ng-model="search.nbResults" value="5" max="25" ng-touch-spin>
</form>

        ×

Tweets

                    <twitter-widget twitter-widget-id="tweet.id"></twitter-widget>

LinkedIn profiles

Location :

Field of study :

Current companies :

Previous companies :

    {{ rawResult }}


text:
layout: post
author: jpulliza
categories: post
title: Jonathan's Flask Guide
---

This will serve as a guide to installing Flask on your local machine to serve up dynamic webpages.

Install Flask: `pip install Flask`

Install Flaskr (a Flask blog example on GitHub):
`git clone https://github.com/silshack/flaskr.git`
`cd flaskr`
`python flaskr.py`

The program is now looking in your Flaskr directory for files to serve up to your web browser at `http://127.0.0.1:5000/`

The log in is admin and password is default. This can be changed in the file `flaskr.py`

Instead of static pages, Flask uses what they call "routes" to return a page when the user asks for it. We will now create an about page as an example.

Go into templates and create a file called `about.html`

The file will be a mix of HTML and *Jinja* (similar to Liquid) as template for a page.

```html
{% raw %}
{% extends "layout.html" %}
{% block body %}
  <h2>About</h2>
  <p> This is being written between two &ltp&gt tags.</p>
{% endblock %}
{% endraw %}
```

Notice the special characters for '<' and '>' since this is actually HTML between the `<p>` tags.

Now we will add the route to the `flaskr.py` file in the flaskr directory. Copy and paste the below code to go right beneath the last route, which should be logout.

```python
@app.route('/about')
def about():
    return render_template('about.html')
```

Now we add a link in the `layout.html` file found in templates. This goes right after `<div class=metanav>` and before `{% raw %}{% if not session.logged_in %}{% endraw %}`.

`<a href="{{ url_for('about') }}">about</a>`

If everything worked out you should have a new `about` link that should point to a page that looks like this.

![flask about page](https://dl.dropboxusercontent.com/u/4614624/flask_about.png)


text:
package io.chark.undead_ninja_cop.engine.system.pickup.chain;

import io.chark.undead_ninja_cop.engine.system.pickup.TouchPickupEvent;

public class ProcessNothing implements TouchPickupEventChain {

    @Override
    public void process(TouchPickupEvent event) {
    }
}


text:
package me.chanjar.weixin.common.util.http.jodd;

import jodd.http.*;
import jodd.util.StringPool;

import me.chanjar.weixin.common.error.WxError;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.util.http.RequestHttp;
import me.chanjar.weixin.common.util.http.SimpleGetRequestExecutor;

import java.io.IOException;

/**
 * Created by ecoolper on 2017/5/4.
 */
public class JoddHttpSimpleGetRequestExecutor extends SimpleGetRequestExecutor<HttpConnectionProvider, ProxyInfo> {

  public JoddHttpSimpleGetRequestExecutor(RequestHttp requestHttp) {
    super(requestHttp);
  }

  @Override
  public String execute(String uri, String queryParam) throws WxErrorException, IOException {
    if (queryParam != null) {
      if (uri.indexOf('?') == -1) {
        uri += '?';
      }
      uri += uri.endsWith("?") ? queryParam : '&' + queryParam;
    }

    HttpRequest request = HttpRequest.get(uri);
    if (requestHttp.getRequestHttpProxy() != null) {
      requestHttp.getRequestHttpClient().useProxy(requestHttp.getRequestHttpProxy());
    }
    request.withConnectionProvider(requestHttp.getRequestHttpClient());
    HttpResponse response = request.send();
    response.charset(StringPool.UTF_8);

    String responseContent = response.bodyText();

    WxError error = WxError.fromJson(responseContent);
    if (error.getErrorCode() != 0) {
      throw new WxErrorException(error);
    }
    return responseContent;
  }

}


text:
typedef NSString *BRAContentType;

@class BRARelationship;

@interface BRAContentTypes : BRAOpenXmlElement

- (BOOL)hasOverrideForPart:(NSString *)partName;
- (BOOL)hasContentTypeForPart:(NSString *)partName;
- (void)addContentTypeForExtension:(NSString *)extension;
- (void)overrideContentType:(NSString *)contentType forPart:(NSString *)partName;

@property (nonatomic, strong) NSArray *defaultExtensions;
@property (nonatomic, strong) NSArray *overrides;

@end


text:
package com.ctrip.hermes.core.message.payload;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import org.unidal.helper.Files.AutoClose;
import org.unidal.helper.Files.IO;
import org.unidal.lookup.annotation.Named;

import com.ctrip.hermes.meta.entity.Codec;

@Named(type = PayloadCodec.class, value = com.ctrip.hermes.meta.entity.Codec.GZIP)
public class GZipPayloadCodec extends AbstractPayloadCodec {

	@Override
	public String getType() {
		// not top level codec, won't be called
		return Codec.GZIP;
	}

	@Override
	public byte[] doEncode(String topic, Object obj) {
		if (!(obj instanceof byte[])) {
			throw new IllegalArgumentException(String.format("Can not encode input of type %s",
			      obj == null ? "null" : obj.getClass()));
		}

		ByteArrayInputStream input = new ByteArrayInputStream((byte[]) obj);
		ByteArrayOutputStream bout = new ByteArrayOutputStream();
		try {
			GZIPOutputStream gout = new GZIPOutputStream(bout);
			IO.INSTANCE.copy(input, gout, AutoClose.INPUT_OUTPUT);
		} catch (IOException e) {
			throw new RuntimeException(String.format("Unexpected exception when encode %s of topic %s", obj, topic), e);
		}

		return bout.toByteArray();
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T doDecode(byte[] input, Class<T> clazz) {
		GZIPInputStream gin = null;
		try {
			gin = new GZIPInputStream(new ByteArrayInputStream(input));
			ByteArrayOutputStream bout = new ByteArrayOutputStream();
			IO.INSTANCE.copy(gin, bout);
			return (T) bout.toByteArray();
		} catch (IOException e) {
			throw new RuntimeException(String.format("Unexpected exception when decoding"), e);
		} finally {
			if (gin != null) {
				try {
					gin.close();
				} catch (IOException e) {
					throw new RuntimeException(String.format("Failed to close GZIPInputStream!"), e);
				}
			}
		}
	}

}


text:
package org.apache.hadoop.hive.ql.metadata;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.hive.metastore.api.FieldSchema;

/**
 * A Hive Table Partition: is a fundamental storage unit within a Table. Currently, Hive does not support
 * hierarchical partitions - For eg: if partition ds=1, hr=1 exists, there is no way to access ds=1
 *
 * Hierarchical partitions are needed in some cases, for eg. locking. For now, create a dummy partition to
 * satisfy this
 */
public class DummyPartition extends Partition {

  @SuppressWarnings("nls")
  private static final Logger LOG = LoggerFactory
      .getLogger("hive.ql.metadata.DummyPartition");

  private String name;
  private LinkedHashMap<String, String> partSpec;
  public DummyPartition() {
  }

  public DummyPartition(Table tbl, String name) throws HiveException {
    setTable(tbl);
    this.name = name;
  }

  public DummyPartition(Table tbl, String name,
      Map<String, String> partSpec) throws HiveException {
    setTable(tbl);
    this.name = name;
    this.partSpec = new LinkedHashMap<String, String>(partSpec);
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getCompleteName() {
    return getName();
  }

  @Override
  public LinkedHashMap<String, String> getSpec() {
    return partSpec;
  }

  @Override
  public List<String> getValues() {
    List<String> values = new ArrayList<String>();
    for (FieldSchema fs : this.getTable().getPartCols()) {
      values.add(partSpec.get(fs.getName()));
    }
    return values;
  }

}


text:
static NSString* responseBody;
static NSInteger statusCode;
static NSError*  requestError;

@interface TestURLProtocol : NSURLProtocol
@end

@implementation TestURLProtocol
+ (BOOL)canInitWithRequest:(NSURLRequest *)request
{
    return [[[request URL] scheme] isEqualToString:@"test"];
}
+ (NSURLRequest*)canonicalRequestForRequest:(NSURLRequest *)request
{
    return request;
}
- (void)startLoading
{
    if(!requestError) {
        NSData* body1 = [[responseBody substringToIndex:  [responseBody length] / 2] dataUsingEncoding:NSUTF8StringEncoding];
        NSData* body2 = [[responseBody substringFromIndex:[responseBody length] / 2] dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            NSDictionary* headers = @{
                @"Content-Type": @"text/plain",
                @"Content-Length": [[NSString alloc] initWithFormat:@"%d", [body1 length] + [body2 length]]
            };
            NSHTTPURLResponse* response = [[NSHTTPURLResponse alloc] initWithURL:self.request.URL statusCode:statusCode HTTPVersion:@"1.1" headerFields:headers];
            [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowedInMemoryOnly];
        });
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.client URLProtocol:self didLoadData:body1];
        });
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.client URLProtocol:self didLoadData:body2];
        });
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.client URLProtocolDidFinishLoading:self];
        });
    } else {
        [self.client URLProtocol:self didFailWithError:requestError];
    }
}
- (void)stopLoading
{
}
@end

static id extractDelegate(NSURLConnection* connection) {
    return [AsyncResultInjector getValueForKey:@"privateResult" from:connection];
}

SPEC_BEGIN(NSURLConnectionSpec)

describe(@"NSURLConnection", ^{
    registerMatchers(@"AR");

    __block HandlerMock*  handler  = nil;
    __block NSURLRequest* request  = nil;

    beforeAll(^{
        [NSURLProtocol registerClass:[TestURLProtocol class]];
    });

    beforeEach(^{
        handler = [[HandlerMock alloc] init];
        request = [[NSURLRequest alloc] initWithURL:[[NSURL alloc] initWithString:@"test://localhost/"]];
    });

    afterEach(^{
        handler      = [handler clear];
        request      = nil;
        responseBody = nil;
        requestError = nil;
    });

    afterAll(^{
        [NSURLProtocol unregisterClass:[TestURLProtocol class]];
    });

    context(@"direct result", ^{

        it(@"should contain a response on success", ^{
            responseBody = @"Hello World!";
            statusCode   = 200;
            NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request];
            asyncWait(connection, handler.block);

            [[expectFutureValue(handler) shouldEventuallyBeforeTimingOutAfter(3.0)] beCalled];

            HandlerMock*       lastCall = handler.lastCall;
            NSHTTPURLResponse* response = [lastCall.metadata objectForKey:@"response"];
            [[theValue(lastCall.result.asyncState) should] equal:theValue(AsyncResultStateSuccess)];
            [[response should] isKindOfClass:[NSHTTPURLResponse class]];
            [[theValue(response.statusCode) should] equal:theValue(200)];
            [[[[NSString alloc] initWithData:lastCall.value encoding:NSUTF8StringEncoding] should] equal:@"Hello World!"];
            [[[[NSString alloc] initWithData:[lastCall.metadata objectForKey:@"body"] encoding:NSUTF8StringEncoding] should] equal:@"Hello World!"];
            [[theValue([connection asyncCancel]) should] beNo];
        });

        it(@"should be canceled when the connection is canceled", ^{
            responseBody = @"Hello World!";
            statusCode   = 200;
            NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request startImmediately:YES];
            asyncWait(connection, handler.block);
            [connection asyncCancel];
            [[handler should] beCalled];
            [[theValue(connection.asyncIsCanceled) should] beYes];
            [[theValue([connection asyncCancel]) should] beNo];
        });

        it(@"should contain an error when the connection is failed", ^{
            requestError = [[NSError alloc] initWithDomain:NSURLErrorDomain code:-1004 userInfo:@{}];
            NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request];
            asyncWait(connection, handler.block);

            [[expectFutureValue(handler) shouldEventually] beCalled];

            [[theValue(connection.asyncState) should] equal:theValue(AsyncResultStateError)];
            NSError* error = connection.asyncError;
            [[error should] beKindOfClass:[NSError class]];
            [[error.domain should] equal:requestError.domain];
            [[theValue(error.code) should] equal:theValue(requestError.code)];
        });

    });

    context(@"http result", ^{

        it(@"should contain a response body on success", ^{
            responseBody = @"Hello World!";
            statusCode   = 200;
            NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request];
            id<AsyncResult>  result     = connection.asyncResponseText;
            asyncWait(result, handler.block);

            [[expectFutureValue(handler) shouldEventuallyBeforeTimingOutAfter(3.0)] beCalledWithValue:@"Hello World!" onMainThread:YES];

            HandlerMock*       lastCall = handler.lastCall;
            NSHTTPURLResponse* response = [lastCall.metadata objectForKey:@"response"];
            [[response should] isKindOfClass:[NSHTTPURLResponse class]];
            [[theValue(response.statusCode) should] equal:theValue(200)];
            [[[[NSString alloc] initWithData:[lastCall.metadata objectForKey:@"body"] encoding:NSUTF8StringEncoding] should] equal:@"Hello World!"];
            [[theValue(connection.asyncState) should] equal:theValue(AsyncResultStateSuccess)];
        });

        it(@"should success with specified status code", ^{
            responseBody = @"Hello World!";
            statusCode   = 401;
            id<AsyncResult> result = [[[NSURLConnection alloc] initWithRequest:request] asyncResponseTextOnStatuses:@[@401]];
            asyncWait(result, handler.block);
            [[expectFutureValue(handler) shouldEventually] beCalledWithValue:@"Hello World!" onMainThread:YES];
            [[theValue(result.asyncState) should] equal:theValue(AsyncResultStateSuccess)];
        });

        it(@"should contain a response on error response", ^{
            responseBody = @"Hello World!";
            statusCode   = 202;
            id<AsyncResult> result = [[NSURLConnection alloc] initWithRequest:request].asyncResponseText;
            asyncWait(result, handler.block);

            [[expectFutureValue(handler) shouldEventually] beCalled];

            HandlerMock*       lastCall = handler.lastCall;
            NSHTTPURLResponse* response = [lastCall.metadata objectForKey:@"response"];
            [[theValue(result.asyncState) should] equal:theValue(AsyncResultStateError)];
            [[response should] isKindOfClass:[NSHTTPURLResponse class]];
            [[theValue(response.statusCode) should] equal:theValue(202)];
            [[[[NSString alloc] initWithData:[lastCall.metadata objectForKey:@"body"] encoding:NSUTF8StringEncoding] should] equal:@"Hello World!"];
        });

        it(@"should fail with unspecified status code", ^{
            responseBody = @"Hello World!";
            statusCode   = 200;
            id<AsyncResult> result = [[[NSURLConnection alloc] initWithRequest:request] asyncResponseTextOnStatuses:@[@401]];
            asyncWait(result, handler.block);

            [[expectFutureValue(handler) shouldEventually] beCalled];

            HandlerMock*       lastCall = handler.lastCall;
            NSHTTPURLResponse* response = [lastCall.metadata objectForKey:@"response"];
            [[theValue(result.asyncState) should] equal:theValue(AsyncResultStateError)];
            [[response should] isKindOfClass:[NSHTTPURLResponse class]];
            [[theValue(response.statusCode) should] equal:theValue(200)];
            [[[[NSString alloc] initWithData:[lastCall.metadata objectForKey:@"body"] encoding:NSUTF8StringEncoding] should] equal:@"Hello World!"];
        });

        it(@"should be canceled when the connection is canceled", ^{
            responseBody = @"Hello World!";
            statusCode   = 200;
            NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request];
            id<AsyncResult>  result     = connection.asyncResponseText;
            asyncWait(result, handler.block);

            [connection asyncCancel];

            [[expectFutureValue(handler) shouldEventually] beCalled];
            [[theValue(result.asyncIsCanceled) should] beYes];
        });

        it(@"should contain an error when the connection is failed", ^{
            requestError = [[NSError alloc] initWithDomain:NSURLErrorDomain code:-1004 userInfo:@{}];
            id<AsyncResult> result = [NSURLConnection connectionWithRequest:request].asyncResponseText;
            asyncWait(result, handler.block);

            [[expectFutureValue(handler) shouldEventually] beCalled];

            [[theValue(result.asyncState) should] equal:theValue(AsyncResultStateError)];
            NSError* error = result.asyncError;
            [[error should] beKindOfClass:[NSError class]];
            [[error.domain should] equal:error.domain];
            [[theValue(error.code) should] equal:theValue(error.code)];
        });

    });

    context(@"json result", ^{

        it(@"should contain a response body on success", ^{
            responseBody = @"[\"Hello World!\"]";
            statusCode   = 200;
            NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request];
            id<AsyncResult>  result     = connection.asyncResponseJson;
            asyncWait(result, handler.block);

            [[expectFutureValue(handler) shouldEventually] beCalledWithValue:@[@"Hello World!"] onMainThread:YES];

            HandlerMock*       lastCall = handler.lastCall;
            NSHTTPURLResponse* response = [lastCall.metadata objectForKey:@"response"];
            [[response should] isKindOfClass:[NSHTTPURLResponse class]];
            [[theValue(response.statusCode) should] equal:theValue(200)];
            [[[[NSString alloc] initWithData:[lastCall.metadata objectForKey:@"body"] encoding:NSUTF8StringEncoding] should] equal:@"[\"Hello World!\"]"];
            [[theValue(connection.asyncState) should] equal:theValue(AsyncResultStateSuccess)];
        });

        it(@"should success with specified status code", ^{
            responseBody = @"[\"Hello World!\"]";
            statusCode   = 401;
            id<AsyncResult> result = [[[NSURLConnection alloc] initWithRequest:request] asyncResponseJsonOnStatuses:@[@401]];
            asyncWait(result, handler.block);
            [[expectFutureValue(handler) shouldEventually] beCalledWithValue:@[@"Hello World!"] onMainThread:YES];
            [[theValue(result.asyncState) should] equal:theValue(AsyncResultStateSuccess)];
        });

        it(@"should contain a response on error response", ^{
            responseBody = @"[\"Hello World!\"]";
            statusCode   = 202;
            id<AsyncResult> result = [[NSURLConnection alloc] initWithRequest:request].asyncResponseJson;
            asyncWait(result, handler.block);

            [[expectFutureValue(handler) shouldEventually] beCalled];

            HandlerMock*       lastCall = handler.lastCall;
            NSHTTPURLResponse* response = [lastCall.metadata objectForKey:@"response"];
            [[theValue(result.asyncState) should] equal:theValue(AsyncResultStateError)];
            [[response should] isKindOfClass:[NSHTTPURLResponse class]];
            [[theValue(response.statusCode) should] equal:theValue(202)];
            [[[[NSString alloc] initWithData:[lastCall.metadata objectForKey:@"body"] encoding:NSUTF8StringEncoding] should] equal:@"[\"Hello World!\"]"];
        });

        it(@"should fail with unspecified status code", ^{
            responseBody = @"[\"Hello World!\"]";
            statusCode   = 200;
            id<AsyncResult> result = [[[NSURLConnection alloc] initWithRequest:request] asyncResponseJsonOnStatuses:@[@401]];
            asyncWait(result, handler.block);

            [[expectFutureValue(handler) shouldEventually] beCalled];

            HandlerMock*        lastCall = handler.lastCall;
             NSHTTPURLResponse* response = [lastCall.metadata objectForKey:@"response"];
            [[theValue(result.asyncState) should] equal:theValue(AsyncResultStateError)];
            [[response should] isKindOfClass:[NSHTTPURLResponse class]];
            [[theValue(response.statusCode) should] equal:theValue(200)];
            [[[[NSString alloc] initWithData:[lastCall.metadata objectForKey:@"body"] encoding:NSUTF8StringEncoding] should] equal:@"[\"Hello World!\"]"];
        });

        it(@"should be canceled when the connection is canceled", ^{
            responseBody = @"[\"Hello World!\"]";
            statusCode   = 200;
            NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request];
            id<AsyncResult>  result     = connection.asyncResponseJson;
            asyncWait(result, handler.block);

            [connection asyncCancel];

            [[expectFutureValue(handler) shouldEventually] beCalled];
            [[theValue(result.asyncIsCanceled) should] beYes];
        });

        it(@"should contain an error when the connection is failed", ^{
            requestError = [[NSError alloc] initWithDomain:NSURLErrorDomain code:-1004 userInfo:@{}];
            id<AsyncResult> result = [NSURLConnection connectionWithRequest:request].asyncResponseJson;
            asyncWait(result, handler.block);

            [[expectFutureValue(handler) shouldEventually] beCalled];

            [[theValue(result.asyncState) should] equal:theValue(AsyncResultStateError)];
            NSError* error = result.asyncError;
            [[error should] beKindOfClass:[NSError class]];
            [[error.domain should] equal:error.domain];
            [[theValue(error.code) should] equal:theValue(error.code)];
        });

    });

});

SPEC_END


text:
num1 = 7
describe 'num1' do
  it "is defined as a local variable" do
    expect(defined?(num1)).to eq 'local-variable'
  end

  it "is an integer" do
    expect(num1).to be_a Fixnum
  end
end
num2 = 2
describe 'num2' do
  it "is defined as a local variable" do
    expect(defined?(num2)).to eq 'local-variable'
  end

  it "is an integer" do
    expect(num2).to be_a Fixnum
  end
end
sum = num1 + num2
describe 'sum' do
  it "is defined as a local variable" do
    expect(defined?(sum)).to eq 'local-variable'
  end

  it "is assigned the value of num1 + num2" do
    expect(sum).to eq num1 + num2
  end
end
difference = num1- num2
describe 'difference' do
  it "is defined as a local variable" do
    expect(defined?(difference)).to eq 'local-variable'
  end

  it "is assigned the value of num1 - num2" do
    expect(difference).to eq num1 - num2
  end
end
product = num1 * num2
describe 'product' do
  it "is defined as a local variable" do
    expect(defined?(product)).to eq 'local-variable'
  end

  it "is assigned the value of num1 * num2" do
    expect(product).to eq num1 * num2
  end
end
quotient = num1.to_f / num2.to_f
describe 'quotient' do
  it "is defined as a local variable" do
    expect(defined?(quotient)).to eq 'local-variable'
  end

  it "is assigned the value of num1 / num2" do
    expect(quotient).to eq num1.to_f / num2.to_f
  end
end
modulus = num1 % num2
describe 'modulus' do
  it "is defined as a local variable" do
    expect(defined?(modulus)).to eq 'local-variable'
  end

  it "is assigned the value of num1 % num2" do
    expect(modulus).to eq num1.to_f % num2.to_f
  end
end


text:
#ifndef _PGTABLE_NOPMD_H
#define _PGTABLE_NOPMD_H

#ifndef __ASSEMBLY__

#include <asm-generic/pgtable-nopud.h>

struct mm_struct;

#define __PAGETABLE_PMD_FOLDED

/*
 * Having the pmd type consist of a pud gets the size right, and allows
 * us to conceptually access the pud entry that this pmd is folded into
 * without casting.
 */
typedef struct { pud_t pud; } pmd_t;

#define PMD_SHIFT	PUD_SHIFT
#define PTRS_PER_PMD	1
#define PMD_SIZE  	(1UL << PMD_SHIFT)
#define PMD_MASK  	(~(PMD_SIZE-1))

/*
 * The "pud_xxx()" functions here are trivial for a folded two-level
 * setup: the pmd is never bad, and a pmd always exists (as it's folded
 * into the pud entry)
 */
static inline int pud_none(pud_t pud)		{ return 0; }
static inline int pud_bad(pud_t pud)		{ return 0; }
static inline int pud_present(pud_t pud)	{ return 1; }
static inline void pud_clear(pud_t *pud)	{ }
#define pmd_ERROR(pmd)				(pud_ERROR((pmd).pud))

#define pud_populate(mm, pmd, pte)		do { } while (0)

/*
 * (pmds are folded into puds so this doesn't get actually called,
 * but the define is needed for a generic inline function.)
 */
#define set_pud(pudptr, pudval)			set_pmd((pmd_t *)(pudptr), (pmd_t) { pudval })

static inline pmd_t * pmd_offset(pud_t * pud, unsigned long address)
{
	return (pmd_t *)pud;
}

#define pmd_val(x)				(pud_val((x).pud))
#define __pmd(x)				((pmd_t) { __pud(x) } )

#define pud_page(pud)				(pmd_page((pmd_t){ pud }))
#define pud_page_vaddr(pud)			(pmd_page_vaddr((pmd_t){ pud }))

/*
 * allocating and freeing a pmd is trivial: the 1-entry pmd is
 * inside the pud, so has no extra memory associated with it.
 */
#define pmd_alloc_one(mm, address)		NULL
static inline void pmd_free(struct mm_struct *mm, pmd_t *pmd)
{
}
#define __pmd_free_tlb(tlb, x, a)		do { } while (0)

#undef  pmd_addr_end
#define pmd_addr_end(addr, end)			(end)

#endif /* __ASSEMBLY__ */

#endif /* _PGTABLE_NOPMD_H */


text:
package com.github.mkopylec.charon.forwarding;

import okhttp3.OkHttpClient.Builder;

public class OkClientHttpRequestFactoryCreatorConfigurer extends ClientHttpRequestFactoryCreatorConfigurer<OkClientHttpRequestFactoryCreator> {

    private OkClientHttpRequestFactoryCreatorConfigurer() {
        super(new OkClientHttpRequestFactoryCreator());
    }

    public static OkClientHttpRequestFactoryCreatorConfigurer okClientHttpRequestFactoryCreator() {
        return new OkClientHttpRequestFactoryCreatorConfigurer();
    }

    public OkClientHttpRequestFactoryCreatorConfigurer httpClient(Builder httpClient) {
        configuredObject.setHttpClient(httpClient.build());
        return this;
    }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;

namespace Microsoft.CodeAnalysis.CodeRefactorings.MoveType
{
    internal abstract partial class AbstractMoveTypeService<TService, TTypeDeclarationSyntax, TNamespaceDeclarationSyntax, TMemberDeclarationSyntax, TCompilationUnitSyntax>
    {
        private class RenameFileEditor : Editor
        {
            public RenameFileEditor(TService service, State state, string fileName, CancellationToken cancellationToken)
                : base(service, state, fileName, cancellationToken)
            {
            }

            public override Task<ImmutableArray<CodeActionOperation>> GetOperationsAsync()
                => Task.FromResult(RenameFileToMatchTypeName());

            public override Task<Solution> GetModifiedSolutionAsync()
            {
                var modifiedSolution = SemanticDocument.Project.Solution
                    .WithDocumentName(SemanticDocument.Document.Id, FileName);

                return Task.FromResult(modifiedSolution);
            }

            /// <summary>
            /// Renames the file to match the type contained in it.
            /// </summary>
            private ImmutableArray<CodeActionOperation> RenameFileToMatchTypeName()
            {
                var documentId = SemanticDocument.Document.Id;
                var oldSolution = SemanticDocument.Document.Project.Solution;
                var newSolution = oldSolution.WithDocumentName(documentId, FileName);

                return ImmutableArray.Create<CodeActionOperation>(
                    new ApplyChangesOperation(newSolution));
            }
        }
    }
}


text:
//
// Copyright 2018 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@class EDOServicePort;

/**
 * A naming service which holds information about each @c EDOHostService and the port on which
 * it's being served.
 *
 * All services that originate from this process are tracked by this class. Users can query for the
 * port on which the service is hosted by calling @c -portForServiceWithName: and providing the
 * unique name associated with the service.
 * The service is not serving by default when initialized.
 */
@interface EDOHostNamingService : NSObject

/** The default port number 11237 which the naming service will be listening on. */
@property(class, readonly) UInt16 namingServerPort;

/** Shared singleton instance. */
@property(class, readonly) EDOHostNamingService *sharedService;

/**
 * The port for service registration. Clients can connect to this port to register their
 * services by name.
 */
@property(readonly) UInt16 serviceConnectionPort;

- (instancetype)init NS_UNAVAILABLE;

/**
 * Returns the service port info with given service name.
 */
- (UInt16)portForServiceWithName:(NSString *)name;

/**
 * Starts serving host port information by creating an @c EDOHostService on @c namingServerPort.
 * Once started, any client can connect to the naming server on @c namingServerPort and query for
 * hosted objects by name.
 *
 * @return @c NO if fails to start serving on the default port.
 *
 * @note Only one @c EDOHostNamingService instance can start serving on a single machine.
 */
- (BOOL)start;

/**
 * Stops serving host port information for remote clients.
 */
- (void)stop;

@end

NS_ASSUME_NONNULL_END


text:
pub struct Buffer {
    pub size: Option<usize>,
    pub position: u64,
    pub max_end_position: Option<u64>,
    pub buffer: Vec<u8>,
}

impl Buffer {
    pub fn create() -> Buffer {
        Buffer {
            size: None,
            position: 0,
            max_end_position: None,
            buffer: Vec::new(),
        }
    }

    pub fn get_cached_size(&self) -> usize {
        self.buffer.len()
    }

    pub fn get_data(&mut self, buf: &mut [u8]) -> bool {
        if buf.len() > self.buffer.len() {
            return false;
        }
        let next_data = self.buffer.split_off(buf.len());
        buf.clone_from_slice(&self.buffer);
        self.buffer = next_data;

        debug!("left #{:?}", self.buffer.len());
        true
    }

    pub fn append_data(&mut self, full_data: &[u8]) {
        self.buffer.extend_from_slice(full_data);
    }

    pub fn reset(&mut self) {
        self.buffer = vec![];
        self.position = 0;
    }
}


text:
@interface MESettingsViewController : UITableViewController
- (IBAction)menuButtonTapped:(id)sender;
@end


text:
package org.apache.hadoop.http;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Used by Load Balancers to detect the active NameNode/ResourceManager/Router.
 */
public abstract class IsActiveServlet extends HttpServlet {

  /** Default serial identifier. */
  private static final long serialVersionUID = 1L;

  public static final String SERVLET_NAME = "isActive";
  public static final String PATH_SPEC = "/isActive";

  public static final String RESPONSE_ACTIVE =
      "I am Active!";

  public static final String RESPONSE_NOT_ACTIVE =
      "I am not Active!";

  /**
   * Check whether this instance is the Active one.
   * @param req HTTP request
   * @param resp HTTP response to write to
   */
  @Override
  public void doGet(
      final HttpServletRequest req, final HttpServletResponse resp)
      throws IOException {

    // By default requests are persistent. We don't want long-lived connections
    // on server side.
    resp.addHeader("Connection", "close");

    if (!isActive()) {
      // Report not SC_OK
      resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED,
          RESPONSE_NOT_ACTIVE);
      return;
    }
    resp.setStatus(HttpServletResponse.SC_OK);
    resp.getWriter().write(RESPONSE_ACTIVE);
    resp.getWriter().flush();
  }

  /**
   * @return true if this instance is in Active HA state.
   */
  protected abstract boolean isActive();
}


text: ./node_modules/.bin/jasmine-node --verbose ./test/spec


text:
using System;

public class FF9ITEM_IMPORTANT
{
	public Int16 name;

	public Int16 help;

	public Int16 help_size;

	public Int16 skin;
}