text:
// Copyright (c) 2015-2021 Jeevan James
// This file is licensed to you under the Apache License, Version 2.0.
// See the LICENSE file in the project root for more information.

using System;
using System.Globalization;
using System.Linq;

namespace ConsoleFx.CmdLine.Validators.Bases
{
    /// <summary>
    ///     Base class for all validators.
    /// </summary>
    //TODO: The conversion performed by this class seems redundant considering the type conversion
    //details specified by the option itself (using its Type and TypeConverter properties). Can we
    //perform the conversion once and then pass the converted value into this class for the typed
    //validation. Also, consider that the conversion logic for validators and that for the option
    //could be different, leading to inconsistencies.
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
    public abstract class Validator : Attribute, IValidator
    {
        protected Validator()
        {
            ExpectedType = typeof(string);
        }

        protected Validator(Type expectedType)
        {
            if (expectedType is null)
                throw new ArgumentNullException(nameof(expectedType));
            ExpectedType = expectedType;
        }

        public Type ExpectedType { get; }

        public object Value { get; private set; }

        /// <summary>
        ///     Validates the specified parameter value and throws an exception if the validation fails.
        /// </summary>
        /// <param name="parameterValue">The parameter value to validate.</param>
        /// <exception cref="ValidationException">Thrown if the validation fails.</exception>
        /// <exception cref="InvalidOperationException">
        ///     Thrown if the validation returns an object whose type does not match the
        ///     <seealso cref="ExpectedType"/>.
        /// </exception>
        public virtual void Validate(string parameterValue)
        {
            Value = ValidateAsString(parameterValue);

            // If there is a value, check that it is compatible with the expected type.
#pragma warning disable S2219 // Runtime type checking should be simplified
            if (Value is not null && !ExpectedType.IsAssignableFrom(Value.GetType()))
#pragma warning restore S2219 // Runtime type checking should be simplified
                throw new InvalidOperationException($"The {GetType()} validator should validate an arg as a {ExpectedType} type, but is validating as a {Value.GetType()} type.");

            // If the type is not a string, call the ValidateAsActualType method to perform additional
            // validations.
            if (ExpectedType != typeof(string))
                ValidateAsActualType(Value, parameterValue);
        }

        /// <summary>
        ///     Validates the parameter value as a string. Converts to the actual type if the validation
        ///     succeeds and returns that value. This method must be overridden in derived classes.
        /// </summary>
        /// <param name="parameterValue">The parameter value as a string.</param>
        /// <returns>The parameter value converted to its actual type.</returns>
        /// <exception cref="ValidationException">Thrown if the validation fails.</exception>
        protected abstract object ValidateAsString(string parameterValue);

        /// <summary>
        ///     Once the parameter has been validated as a string, it is converted to its actual type and passed here for
        ///     additional validations.
        ///     This is useful for additional validations that can only be performed on the actual typed value.
        /// </summary>
        /// <param name="value">The typed parameter value.</param>
        /// <param name="parameterValue">The parameter value as a string.</param>
        /// <exception cref="ValidationException">Thrown if the validation fails.</exception>
        protected virtual void ValidateAsActualType(object value, string parameterValue)
        {
        }

        /// <summary>
        ///     Shortcut method for throwing a failed validation exception. Use this from derived
        ///     classes, instead of throwing the exception directly.
        /// </summary>
        /// <param name="message">The validation error message.</param>
        /// <param name="parameterValue">The parameter value that caused the validation to fail.</param>
        /// <param name="args">Optional arguments to the message.</param>
        protected void ValidationFailed(string message, string parameterValue, params object[] args)
        {
            object[] formatArgs = new object[] { parameterValue }.Concat(args).ToArray();
            throw new ValidationException(string.Format(CultureInfo.CurrentCulture, message, formatArgs),
                GetType(), parameterValue);
        }
    }
}


text:
<?php
namespace Dzasa\OpenExchangeRates;

use Exception;
use Memcache;

/**
 * Cache wrapper for Memcache, APC and file caching method
 *
 * @author Jasenko Rakovic <naucnik@gmail.com>
 */
class Cache {

    private $handler;
    private $memcache;
    private $memcacheConfig = array(
        'host' => null,
        'port' => null
    );
    private $fileCacheConfig = array(
        'cache_dir' => null
    );

    function __construct($handler, $config = array()) {
        $this->handler = $handler;
        if ($handler === 'memcache') {
            $this->memcache = $config;

            if (class_exists("Memcache")) {
                try {
                    $this->memcache = new Memcache;
                    $this->memcacheConfig = $config;
                    $connection = @$this->memcache->connect($this->memcacheConfig['host'], $this->memcacheConfig['port']);

                    if (!$connection) {
                        throw new Exception("Cannot connect to Memcache server!");
                    }
                } catch (Exception $e) {
                    throw $e;
                }
            } else {
                throw new Exception("You don't have Memecache support installed!");
            }
        } else if ($handler === 'apc') {
            if (!extension_loaded('apc')) {
                throw new Exception("You don't have APC installed!");
            }
        } else if($handler === 'file'){
            $this->fileCacheConfig = $config;

            if(!isset($this->fileCacheConfig['cache_dir'])){
                throw new Exception("Caching directory must be defined!");
            } else if(!is_writable($this->fileCacheConfig['cache_dir'])){
                throw new Exception("Caching directory must exist and be writable!");
            }
        }
    }

    /**
     * Get cached data
     *
     * @param string $key
     * @return mixed
     */
    public function get($key) {
        switch ($this->handler) {
            case "memcache":
                return $this->memcache->get($key);
                break;
            case "apc":
                return apc_fetch($key);
                break;
            case "file":
                $fileContent = @file_get_contents($this->fileCacheConfig['cache_dir']."/".$key);

                if(!$fileContent){
                    return false;
                }
                return unserialize($fileContent);
                break;
        }
    }

    /**
     * Cache data
     *
     * @param string $key
     * @param mixed $value
     */
    public function set($key, $value) {
        switch ($this->handler) {
            case "memcache":
                $this->memcache->set($key, $value);
                break;
            case "apc":
                apc_store($key, $value);
                break;
            case "file":
                $serializedValue = serialize($value);

                file_put_contents($this->fileCacheConfig['cache_dir']."/".$key, $serializedValue);
                break;
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<title>Algoritmos y Programación - Capítulo VII - Comandos de entrada de datos</title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="../estilos/estilos.css" />
<meta name="description" content="Curso Algoritmos y Programación. Proyecto Open Course Ware de la Universidad de Panamá" />

	Algoritmos y Programación - Facultad de informática, electrónica y conunicación - Universidad de Panamá

Comandos de entrada de datos

Ariel Vernaza

Facultad de informática, electrónica y conunicación

Universidad de Panamá

(Wikibooks, 2011; Docs Python, 2011b; Penzilla, 2011)

El teclado en el ordenador es el primer elemento disponible para entrada de información y  los lenguajes de programación disponen de comando para esperar que el usuario ingrese algún dato antes de continuar el proceso.

En Python se dispone de dos funciones para la entrada de información desde el teclado: los comandos raw_input() e input(). El comando raw_input() recibe la información siempre como una cadena de caracteres directamente desde el teclado y hace la pausa en el programa hasta cuando se ingresa totalmente la información terminada por la tecla de entrar ( 'enter').  El argumento de entrada en la función es un comentario que aparecerá en la pantalla antes del espacio de ingreso de datos. Veamos un ejemplo de su aplicación en el interface de Python (Python shell):

>>>dato1 = raw_input('Escriba un dato aqui: ')
Escriba un dato aquí: TECLADO
>>>dato1
'TECLADO'
>>>type(dato1)
<type 'str'>
>>>

La primera línea define que se asignará en la variable dato1 lo que se escriba desde el teclado y aparecerá primero un mensaje diciendo Escriba un datos aquí: para esperar la entrada del dato. Al escribir la palabra TECLADO, ésta se guardará en la variable tipo alfanumérica ( 'str' ) denominada dato1 como se muestra al usar la función type().

Es importante recalcar que aún cuando se solicita un número, la función siempre interpretará la entrada como caracteres, tal como se muestra en el siguiente ejemplo:

>>>dato2 = raw_input('Escriba un numero: ')
Escriba un numero: 6.2827
>>>dato2
'6.2827'
>>>type(dato2)
<type 'str'>
>>>dato2n=float(dato2)
>>>type(dato2n)
<type 'float'>
>>>

La variable dato2 es una cadena de caracteres y no un número para realizar operaciones matemáticas. Si se requiere un número será necesario transformar la variable dato2, usando float() y obtener una nueva variable numérica dato2n como lo muestran las últimas líneas.

Una opción alternativa que dispone Python es el comando input(), el cual interpreta la información de entrada a un tipo de variable adecuado. Veamos el siguiente ejemplo:

>>>dato3 = input('Entre un numero entero : ')
Entre un numero entero : 34
>>>dato3
34
>>>type(dato3)
<type 'int'>
>>>dato4 = input('Entre un numero real : ')
Entre un numero real : 4.3421
>>>dato4
4.3421
>>>type(dato4)
<type 'float'>
>>>

Observe que dato3 y dato4 son variables de diferente tipo, la primera es de tipo entero ('int') y la segunda de tipo real ('float'). Este proceso de interpretación lo realiza directamente el comando antes de asignar el dato a la variable.

El uso de la función input() requiere especial atención cuando se requiere usar información de tipo alfanumérico o lógico, ya que puede presentar un error al ingreso de la información. Veamos estos dos casos para ilustrar el resultado:

>>>dato5 = input('Escriba Si o No : ')
Escriba Si o No : si

Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
  	dato5 = input('Escriba Si o No : ')
  File "<string>", line 1, in <module>
NameError: name 'si' is not defined
>>>dato5 = input('Escriba Si o No : ')
Escriba Si o No : 'si'
>>>dato5
'si'
>>>type(dato5)
<type 'str'>
>>>

Aquí en el primer intento aparece un mensaje de error informando que el nombre si no está definido ("name 'si' is not defined"), ya que el comando trató de interpretar si como un objeto y no encontró ninguna referencia de esa palabra. En la segunda opción se escribió entre comillas la palabra si ('si') y se interpretó como un dato tipo caracteres o alfanumérico.

>>>dato6 = input('Es true or false ? ')
Es true or false ? true

Traceback (most recent call last):
  File "<pyshell#23>", line 1, in <module>
	dato6 = input('Es true or false ? ')
  File "<string>", line 1, in <module>
NameError: name 'true' is not defined
>>>dato6 = input('Es true or false ? ')
Es true or false ? True
>>>dato6
True
>>>type(dato6)
<type 'bool'>
>>>

Aquí también se presenta el mismo mensaje de error ya que el dato lógico True requiere ser escrito con una mayúscula inicial.

	Esta obra esta protegida bajo una licencia de creative commons

      Universidad de Panamá

          2018


text:
'use strict';

var assert = require('assert');
var BN = require('bn.js');
var consensus = require('../lib/protocol/consensus');
var encoding = require('../lib/utils/encoding');
var co = require('../lib/utils/co');
var Coin = require('../lib/primitives/coin');
var Script = require('../lib/script/script');
var Chain = require('../lib/blockchain/chain');
var Miner = require('../lib/mining/miner');
var MTX = require('../lib/primitives/mtx');
var MemWallet = require('./util/memwallet');
var Network = require('../lib/protocol/network');
var Output = require('../lib/primitives/output');
var util = require('../lib/utils/util');
var opcodes = Script.opcodes;

describe('Chain', function() {
  var network = Network.get('regtest');
  var chain = new Chain({ db: 'memory', network: network });
  var miner = new Miner({ chain: chain, version: 4 });
  var wallet = new MemWallet({ network: network });
  var wwallet = new MemWallet({ network: network, witness: true });
  var tip1, tip2, addBlock, mineCSV;

  this.timeout(45000);

  addBlock = co(function* addBlock(attempt) {
    var block = yield attempt.mineAsync();
    var entry;

    try {
      entry = yield chain.add(block);
    } catch (e) {
      assert(e.type === 'VerifyError');
      return e.reason;
    }

    if (!entry)
      return 'bad-prevblk';

    return 'OK';
  });

  mineCSV = co(function* mineCSV(tx) {
    var attempt = yield miner.createBlock();
    var rtx;

    rtx = new MTX();

    rtx.addOutput({
      script: [
        Script.array(new BN(1)),
        Script.opcodes.OP_CHECKSEQUENCEVERIFY
      ],
      value: 10000
    });

    rtx.addTX(tx, 0);

    rtx.setLocktime(chain.height);

    wallet.sign(rtx);

    attempt.addTX(rtx.toTX(), rtx.view);

    return yield attempt.mineAsync();
  });

  chain.on('connect', function(entry, block) {
    wallet.addBlock(entry, block.txs);
  });

  chain.on('disconnect', function(entry, block) {
    wallet.removeBlock(entry, block.txs);
  });

  it('should open chain and miner', co(function* () {
    yield chain.open();
    yield miner.open();
  }));

  it('should add addrs to miner', co(function* () {
    miner.addresses.length = 0;
    miner.addAddress(wallet.getReceive());
  }));

  it('should mine 200 blocks', co(function* () {
    var i, block;

    for (i = 0; i < 200; i++) {
      block = yield miner.mineBlock();
      assert(block);
      assert(yield chain.add(block));
    }

    assert.equal(chain.height, 200);
  }));

  it('should mine competing chains', co(function* () {
    var i, mtx, at1, at2, blk1, blk2, hash1, hash2;

    for (i = 0; i < 10; i++) {
      at1 = yield miner.createBlock(tip1);
      at2 = yield miner.createBlock(tip2);

      mtx = yield wallet.create({
        outputs: [{
          address: wallet.getAddress(),
          value: 10 * 1e8
        }]
      });

      at1.addTX(mtx.toTX(), mtx.view);
      at2.addTX(mtx.toTX(), mtx.view);

      blk1 = yield at1.mineAsync();
      blk2 = yield at2.mineAsync();

      hash1 = blk1.hash('hex');
      hash2 = blk2.hash('hex');

      assert(yield chain.add(blk1));
      assert(yield chain.add(blk2));

      assert(chain.tip.hash === hash1);

      tip1 = yield chain.db.getEntry(hash1);
      tip2 = yield chain.db.getEntry(hash2);

      assert(tip1);
      assert(tip2);

      assert(!(yield tip2.isMainChain()));
    }
  }));

  it('should have correct chain value', function() {
    assert.equal(chain.db.state.value, 897500000000);
    assert.equal(chain.db.state.coin, 220);
    assert.equal(chain.db.state.tx, 221);
  });

  it('should have correct wallet balance', co(function* () {
    assert.equal(wallet.balance, 897500000000);
  }));

  it('should handle a reorg', co(function* () {
    var forked = false;
    var entry, block;

    assert.equal(chain.height, 210);

    entry = yield chain.db.getEntry(tip2.hash);
    assert(entry);
    assert(chain.height === entry.height);

    block = yield miner.mineBlock(entry);
    assert(block);

    chain.once('reorganize', function() {
      forked = true;
    });

    assert(yield chain.add(block));

    assert(forked);
    assert(chain.tip.hash === block.hash('hex'));
    assert(chain.tip.chainwork.cmp(tip1.chainwork) > 0);
  }));

  it('should have correct chain value', function() {
    assert.equal(chain.db.state.value, 900000000000);
    assert.equal(chain.db.state.coin, 221);
    assert.equal(chain.db.state.tx, 222);
  });

  it('should have correct wallet balance', co(function* () {
    assert.equal(wallet.balance, 900000000000);
  }));

  it('should check main chain', co(function* () {
    var result = yield tip1.isMainChain();
    assert(!result);
  }));

  it('should mine a block after a reorg', co(function* () {
    var block = yield miner.mineBlock();
    var hash, entry, result;

    assert(yield chain.add(block));

    hash = block.hash('hex');
    entry = yield chain.db.getEntry(hash);

    assert(entry);
    assert(chain.tip.hash === entry.hash);

    result = yield entry.isMainChain();
    assert(result);
  }));

  it('should prevent double spend on new chain', co(function* () {
    var attempt = yield miner.createBlock();
    var mtx, block;

    mtx = yield wallet.create({
      outputs: [{
        address: wallet.getAddress(),
        value: 10 * 1e8
      }]
    });

    attempt.addTX(mtx.toTX(), mtx.view);

    block = yield attempt.mineAsync();

    assert(yield chain.add(block));

    attempt = yield miner.createBlock();

    assert(mtx.outputs.length > 1);
    mtx.outputs.pop();

    attempt.addTX(mtx.toTX(), mtx.view);

    assert.equal(yield addBlock(attempt), 'bad-txns-inputs-missingorspent');
  }));

  it('should fail to connect coins on an alternate chain', co(function* () {
    var block = yield chain.db.getBlock(tip1.hash);
    var cb = block.txs[0];
    var mtx = new MTX();
    var attempt;

    mtx.addTX(cb, 0);
    mtx.addOutput(wallet.getAddress(), 10 * 1e8);

    wallet.sign(mtx);

    attempt = yield miner.createBlock();
    attempt.addTX(mtx.toTX(), mtx.view);

    assert.equal(yield addBlock(attempt), 'bad-txns-inputs-missingorspent');
  }));

  it('should have correct chain value', function() {
    assert.equal(chain.db.state.value, 905000000000);
    assert.equal(chain.db.state.coin, 224);
    assert.equal(chain.db.state.tx, 225);
  });

  it('should get coin', co(function* () {
    var mtx, attempt, block, tx, output, coin;

    mtx = yield wallet.send({
      outputs: [
        {
          address: wallet.getAddress(),
          value: 1e8
        },
        {
          address: wallet.getAddress(),
          value: 1e8
        },
        {
          address: wallet.getAddress(),
          value: 1e8
        }
      ]
    });

    attempt = yield miner.createBlock();
    attempt.addTX(mtx.toTX(), mtx.view);

    block = yield attempt.mineAsync();
    assert(yield chain.add(block));

    tx = block.txs[1];
    output = Coin.fromTX(tx, 2, chain.height);

    coin = yield chain.db.getCoin(tx.hash('hex'), 2);

    assert.deepEqual(coin.toRaw(), output.toRaw());
  }));

  it('should have correct wallet balance', co(function* () {
    assert.equal(wallet.balance, 907500000000);
    assert.equal(wallet.receiveDepth, 15);
    assert.equal(wallet.changeDepth, 14);
    assert.equal(wallet.txs, 226);
  }));

  it('should get tips and remove chains', co(function* () {
    var tips = yield chain.db.getTips();

    assert.notEqual(tips.indexOf(chain.tip.hash), -1);
    assert.equal(tips.length, 2);

    yield chain.db.removeChains();

    tips = yield chain.db.getTips();

    assert.notEqual(tips.indexOf(chain.tip.hash), -1);
    assert.equal(tips.length, 1);
  }));

  it('should rescan for transactions', co(function* () {
    var total = 0;

    yield chain.db.scan(0, wallet.filter, function(block, txs) {
      total += txs.length;
      return Promise.resolve();
    });

    assert.equal(total, 226);
  }));

  it('should activate csv', co(function* () {
    var deployments = network.deployments;
    var i, block, prev, state, cache;

    miner.options.version = -1;

    assert.equal(chain.height, 214);

    prev = yield chain.tip.getPrevious();
    state = yield chain.getState(prev, deployments.csv);
    assert.equal(state, 1);

    for (i = 0; i < 417; i++) {
      block = yield miner.mineBlock();
      assert(yield chain.add(block));
      switch (chain.height) {
        case 288:
          prev = yield chain.tip.getPrevious();
          state = yield chain.getState(prev, deployments.csv);
          assert.equal(state, 1);
          break;
        case 432:
          prev = yield chain.tip.getPrevious();
          state = yield chain.getState(prev, deployments.csv);
          assert.equal(state, 2);
          break;
        case 576:
          prev = yield chain.tip.getPrevious();
          state = yield chain.getState(prev, deployments.csv);
          assert.equal(state, 3);
          break;
      }
    }

    assert.equal(chain.height, 631);
    assert(chain.state.hasCSV());
    assert(chain.state.hasWitness());

    cache = yield chain.db.getStateCache();
    assert.deepEqual(cache, chain.db.stateCache);
    assert.equal(chain.db.stateCache.updates.length, 0);
    assert(yield chain.db.verifyDeployments());
  }));

  it('should have activated segwit', co(function* () {
    var deployments = network.deployments;
    var prev = yield chain.tip.getPrevious();
    var state = yield chain.getState(prev, deployments.segwit);
    assert.equal(state, 3);
  }));

  it('should test csv', co(function* () {
    var tx = (yield chain.db.getBlock(chain.height - 100)).txs[0];
    var block = yield mineCSV(tx);
    var csv, attempt, rtx;

    assert(yield chain.add(block));

    csv = block.txs[1];

    rtx = new MTX();

    rtx.addOutput({
      script: [
        Script.array(new BN(2)),
        Script.opcodes.OP_CHECKSEQUENCEVERIFY
      ],
      value: 10000
    });

    rtx.addTX(csv, 0);
    rtx.setSequence(0, 1, false);

    attempt = yield miner.createBlock();

    attempt.addTX(rtx.toTX(), rtx.view);

    block = yield attempt.mineAsync();

    assert(yield chain.add(block));
  }));

  it('should fail csv with bad sequence', co(function* () {
    var csv = (yield chain.db.getBlock(chain.height - 100)).txs[0];
    var rtx = new MTX();
    var attempt;

    rtx.addOutput({
      script: [
        Script.array(new BN(1)),
        Script.opcodes.OP_CHECKSEQUENCEVERIFY
      ],
      value: 1 * 1e8
    });

    rtx.addTX(csv, 0);
    rtx.setSequence(0, 1, false);

    attempt = yield miner.createBlock();
    attempt.addTX(rtx.toTX(), rtx.view);

    assert.equal(yield addBlock(attempt), 'mandatory-script-verify-flag-failed');
  }));

  it('should mine a block', co(function* () {
    var block = yield miner.mineBlock();
    assert(block);
    assert(yield chain.add(block));
  }));

  it('should fail csv lock checks', co(function* () {
    var tx = (yield chain.db.getBlock(chain.height - 100)).txs[0];
    var block = yield mineCSV(tx);
    var csv, attempt, rtx;

    assert(yield chain.add(block));

    csv = block.txs[1];

    rtx = new MTX();

    rtx.addOutput({
      script: [
        Script.array(new BN(2)),
        Script.opcodes.OP_CHECKSEQUENCEVERIFY
      ],
      value: 1 * 1e8
    });

    rtx.addTX(csv, 0);
    rtx.setSequence(0, 2, false);

    attempt = yield miner.createBlock();
    attempt.addTX(rtx.toTX(), rtx.view);

    assert.equal(yield addBlock(attempt), 'bad-txns-nonfinal');
  }));

  it('should have correct wallet balance', co(function* () {
    assert.equal(wallet.balance, 1412499980000);
  }));

  it('should fail to connect bad bits', co(function* () {
    var attempt = yield miner.createBlock();
    attempt.block.bits = 553713663;
    assert.equal(yield addBlock(attempt), 'bad-diffbits');
  }));

  it('should fail to connect bad MTP', co(function* () {
    var mtp = yield chain.tip.getMedianTime();
    var attempt = yield miner.createBlock();
    attempt.block.ts = mtp - 1;
    assert.equal(yield addBlock(attempt), 'time-too-old');
  }));

  it('should fail to connect bad time', co(function* () {
    var attempt = yield miner.createBlock();
    var now = network.now() + 3 * 60 * 60;
    attempt.block.ts = now;
    assert.equal(yield addBlock(attempt), 'time-too-new');
  }));

  it('should fail to connect bad locktime', co(function* () {
    var attempt = yield miner.createBlock();
    var tx = yield wallet.send({ locktime: 100000 });
    attempt.block.txs.push(tx.toTX());
    attempt.refresh();
    assert.equal(yield addBlock(attempt), 'bad-txns-nonfinal');
  }));

  it('should fail to connect bad cb height', co(function* () {
    var bip34height = network.block.bip34height;
    var attempt = yield miner.createBlock();
    var tx = attempt.block.txs[0];
    var input = tx.inputs[0];

    input.script.set(0, new BN(10));
    input.script.compile();
    attempt.refresh();

    try {
      network.block.bip34height = 0;
      assert.equal(yield addBlock(attempt), 'bad-cb-height');
    } finally {
      network.block.bip34height = bip34height;
    }
  }));

  it('should fail to connect bad witness nonce size', co(function* () {
    var attempt = yield miner.createBlock();
    var tx = attempt.block.txs[0];
    var input = tx.inputs[0];
    input.witness.set(0, new Buffer(33));
    input.witness.compile();
    assert.equal(yield addBlock(attempt), 'bad-witness-nonce-size');
  }));

  it('should fail to connect bad witness nonce', co(function* () {
    var attempt = yield miner.createBlock();
    var tx = attempt.block.txs[0];
    var input = tx.inputs[0];
    input.witness.set(0, encoding.ONE_HASH);
    input.witness.compile();
    assert.equal(yield addBlock(attempt), 'bad-witness-merkle-match');
  }));

  it('should fail to connect bad witness commitment', co(function* () {
    var attempt = yield miner.createBlock();
    var tx = attempt.block.txs[0];
    var output = tx.outputs[1];
    var commit;

    assert(output.script.isCommitment());

    commit = util.copy(output.script.get(1));
    commit.fill(0, 10);
    output.script.set(1, commit);
    output.script.compile();

    attempt.updateMerkle();
    assert.equal(yield addBlock(attempt), 'bad-witness-merkle-match');
  }));

  it('should fail to connect unexpected witness', co(function* () {
    var attempt = yield miner.createBlock();
    var tx = attempt.block.txs[0];
    var output = tx.outputs[1];
    assert(output.script.isCommitment());
    tx.outputs.pop();
    attempt.updateMerkle();
    assert.equal(yield addBlock(attempt), 'unexpected-witness');
  }));

  it('should add wit addrs to miner', co(function* () {
    miner.addresses.length = 0;
    miner.addAddress(wwallet.getReceive());
    assert.equal(wwallet.getReceive().getType(), 'witnesspubkeyhash');
  }));

  it('should mine 2000 witness blocks', co(function* () {
    var i, block;

    for (i = 0; i < 2001; i++) {
      block = yield miner.mineBlock();
      assert(block);
      assert(yield chain.add(block));
    }

    assert.equal(chain.height, 2636);
  }));

  it('should mine a witness tx', co(function* () {
    var block = yield chain.db.getBlock(chain.height - 2000);
    var cb = block.txs[0];
    var mtx = new MTX();
    var attempt;

    mtx.addTX(cb, 0);
    mtx.addOutput(wwallet.getAddress(), 1000);

    wwallet.sign(mtx);

    attempt = yield miner.createBlock();
    attempt.addTX(mtx.toTX(), mtx.view);

    block = yield attempt.mineAsync();

    assert(yield chain.add(block));
  }));

  it('should mine fail to connect too much weight', co(function* () {
    var start = chain.height - 2000;
    var end = chain.height - 200;
    var attempt = yield miner.createBlock();
    var mtx = new MTX();
    var i, j, block, cb;

    for (i = start; i <= end; i++) {
      block = yield chain.db.getBlock(i);
      cb = block.txs[0];

      mtx = new MTX();
      mtx.addTX(cb, 0);

      for (j = 0; j < 16; j++)
        mtx.addOutput(wwallet.getAddress(), 1);

      wwallet.sign(mtx);

      attempt.block.txs.push(mtx.toTX());
    }

    attempt.refresh();

    assert.equal(yield addBlock(attempt), 'bad-blk-weight');
  }));

  it('should mine fail to connect too much size', co(function* () {
    var start = chain.height - 2000;
    var end = chain.height - 200;
    var attempt = yield miner.createBlock();
    var mtx = new MTX();
    var i, j, block, cb;

    for (i = start; i <= end; i++) {
      block = yield chain.db.getBlock(i);
      cb = block.txs[0];

      mtx = new MTX();
      mtx.addTX(cb, 0);

      for (j = 0; j < 20; j++)
        mtx.addOutput(wwallet.getAddress(), 1);

      wwallet.sign(mtx);

      attempt.block.txs.push(mtx.toTX());
    }

    attempt.refresh();

    assert.equal(yield addBlock(attempt), 'bad-blk-length');
  }));

  it('should mine a big block', co(function* () {
    var start = chain.height - 2000;
    var end = chain.height - 200;
    var attempt = yield miner.createBlock();
    var mtx = new MTX();
    var i, j, block, cb;

    for (i = start; i <= end; i++) {
      block = yield chain.db.getBlock(i);
      cb = block.txs[0];

      mtx = new MTX();
      mtx.addTX(cb, 0);

      for (j = 0; j < 15; j++)
        mtx.addOutput(wwallet.getAddress(), 1);

      wwallet.sign(mtx);

      attempt.block.txs.push(mtx.toTX());
    }

    attempt.refresh();

    assert.equal(yield addBlock(attempt), 'OK');
  }));

  it('should fail to connect bad versions', co(function* () {
    var i, attempt;

    for (i = 0; i <= 3; i++) {
      attempt = yield miner.createBlock();
      attempt.block.version = i;
      assert.equal(yield addBlock(attempt), 'bad-version');
    }
  }));

  it('should fail to connect bad amount', co(function* () {
    var attempt = yield miner.createBlock();

    attempt.block.txs[0].outputs[0].value += 1;
    attempt.updateMerkle();
    assert.equal(yield addBlock(attempt), 'bad-cb-amount');
  }));

  it('should fail to connect premature cb spend', co(function* () {
    var attempt = yield miner.createBlock();
    var block = yield chain.db.getBlock(chain.height - 98);
    var cb = block.txs[0];
    var mtx = new MTX();

    mtx.addTX(cb, 0);
    mtx.addOutput(wwallet.getAddress(), 1);

    wwallet.sign(mtx);

    attempt.addTX(mtx.toTX(), mtx.view);

    assert.equal(yield addBlock(attempt),
      'bad-txns-premature-spend-of-coinbase');
  }));

  it('should fail to connect vout belowout', co(function* () {
    var attempt = yield miner.createBlock();
    var block = yield chain.db.getBlock(chain.height - 99);
    var cb = block.txs[0];
    var mtx = new MTX();

    mtx.addTX(cb, 0);
    mtx.addOutput(wwallet.getAddress(), 1e8);

    wwallet.sign(mtx);

    attempt.block.txs.push(mtx.toTX());
    attempt.refresh();

    assert.equal(yield addBlock(attempt),
      'bad-txns-in-belowout');
  }));

  it('should fail to connect outtotal toolarge', co(function* () {
    var attempt = yield miner.createBlock();
    var block = yield chain.db.getBlock(chain.height - 99);
    var cb = block.txs[0];
    var mtx = new MTX();

    mtx.addTX(cb, 0);
    mtx.addOutput(wwallet.getAddress(), Math.floor(consensus.MAX_MONEY / 2));
    mtx.addOutput(wwallet.getAddress(), Math.floor(consensus.MAX_MONEY / 2));
    mtx.addOutput(wwallet.getAddress(), Math.floor(consensus.MAX_MONEY / 2));

    wwallet.sign(mtx);

    attempt.block.txs.push(mtx.toTX());
    attempt.refresh();

    assert.equal(yield addBlock(attempt),
      'bad-txns-txouttotal-toolarge');
  }));

  it('should mine 111 multisig blocks', co(function* () {
    var i, j, script, attempt, cb, output, val, block;

    script = new Script();
    script.push(new BN(20));

    for (i = 0; i < 20; i++)
      script.push(encoding.ZERO_KEY);

    script.push(new BN(20));
    script.push(opcodes.OP_CHECKMULTISIG);
    script.compile();

    script = Script.fromScripthash(script.hash160());

    for (i = 0; i < 111; i++) {
      attempt = yield miner.createBlock();
      cb = attempt.block.txs[0];
      val = cb.outputs[0].value;

      cb.outputs[0].value = 0;

      for (j = 0; j < Math.min(100, val); j++) {
        output = new Output();
        output.script = script.clone();
        output.value = 1;

        cb.outputs.push(output);
      }

      attempt.updateMerkle();

      block = yield attempt.mineAsync();
      assert(yield chain.add(block));
    }

    assert.equal(chain.height, 2749);
  }));

  it('should fail to connect too many sigops', co(function* () {
    var start = chain.height - 110;
    var end = chain.height - 100;
    var attempt = yield miner.createBlock();
    var i, j, mtx, script, block, cb;

    script = new Script();
    script.push(new BN(20));

    for (i = 0; i < 20; i++)
      script.push(encoding.ZERO_KEY);

    script.push(new BN(20));
    script.push(opcodes.OP_CHECKMULTISIG);
    script.compile();

    for (i = start; i <= end; i++) {
      block = yield chain.db.getBlock(i);
      cb = block.txs[0];

      if (cb.outputs.length === 2)
        continue;

      mtx = new MTX();

      for (j = 2; j < cb.outputs.length; j++) {
        mtx.addTX(cb, j);
        mtx.inputs[j - 2].script = new Script([script.toRaw()]);
      }

      mtx.addOutput(wwallet.getAddress(), 1);

      attempt.block.txs.push(mtx.toTX());
    }

    attempt.refresh();

    assert.equal(yield addBlock(attempt), 'bad-blk-sigops');
  }));

  it('should cleanup', co(function* () {
    yield miner.close();
    yield chain.close();
  }));
});


text:
@interface CCParticleSystem(Extras)

@property (nonatomic, readonly) float elapsed;

-(void) matchScale: (CCNode *) node;

+(id) particleWithFile:(NSString *)plistFile params: (NSDictionary *) params;
-(id) initWithFile:(NSString *)plistFile params: (NSDictionary *) params;
-(void) stopSystemAndCleanup;
-(void) cleanupWhenDone;
-(void) moveToParentsParent;

@end


text:
<?php

add_action('wp_rp_admin_notices', 'wp_rp_display_admin_notices');

function wp_rp_display_admin_notices() {
	global $wp_rp_admin_notices;

	foreach ((array) $wp_rp_admin_notices as $notice) {
		echo '

' . $notice[1] . '

';
	}
}

function wp_rp_add_admin_notice($type = 'updated', $message = '') {
	global $wp_rp_admin_notices;

	if (strtolower($type) == 'updated' && $message != '') {
		$wp_rp_admin_notices[] = array('updated', $message);
		return true;
	}

	if (strtolower($type) == 'error' && $message != '') {
		$wp_rp_admin_notices[] = array ('error', $message);
		return true;
	}

	return false;
}


text:
This theme is just a mod of the **[Breeze
Flat](http://kde-look.org/content/show.php/Breeze+Flat+(Plasma+5)?content=169919)**
plasma theme to match the color scheme

## Install

Copy the **gruvbox** folder to **${XDG\_DATA\_HOME}/plasma/desktoptheme** (usually
**~/.local/share/color-schemes**)


text:
mshadow-ps
====
This folder contains mshadow-ps parameter server interface for mshadow GPU/CPU Tensor. See [guide on mshadow-ps](../guide/mshadow-ps) for introduction of the interface.


text:
from a10sdk.common.A10BaseClass import A10BaseClass

class Member(A10BaseClass):

    """This class does not support CRUD Operations please use parent.

    :param member_name: {"platform-specific-default": 1, "type": "string", "description": "Service name", "format": "string-rlx"}
    :param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`

    """
    def __init__(self, **kwargs):
        self.ERROR_MSG = ""

        self.b_key = "member"
        self.DeviceProxy = ""
        self.member_name = ""

        for keys, value in kwargs.items():
            setattr(self,keys, value)

class DisableSiteList(A10BaseClass):

    """This class does not support CRUD Operations please use parent.

    :param disable_site: {"minLength": 1, "maxLength": 63, "type": "string", "description": "Site name", "format": "string"}
    :param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`

    """
    def __init__(self, **kwargs):
        self.ERROR_MSG = ""

        self.b_key = "disable-site-list"
        self.DeviceProxy = ""
        self.disable_site = ""

        for keys, value in kwargs.items():
            setattr(self,keys, value)

class ServiceGroup(A10BaseClass):

    """Class Description::
    Specify GSLB Service Group.

    Class service-group supports CRUD Operations and inherits from `common/A10BaseClass`.
    This class is the `"PARENT"` class for this module.`

    :param member: {"minItems": 1, "items": {"type": "object"}, "uniqueItems": true, "type": "array", "array": [{"properties": {"member-name": {"platform-specific-default": 1, "type": "string", "description": "Service name", "format": "string-rlx"}, "optional": true}}]}
    :param service_group_name: {"description": "Specify Service Group name", "format": "string", "minLength": 1, "optional": false, "maxLength": 63, "type": "string"}
    :param disable_site_list: {"minItems": 1, "items": {"type": "object"}, "uniqueItems": true, "type": "array", "array": [{"properties": {"optional": true, "disable-site": {"minLength": 1, "maxLength": 63, "type": "string", "description": "Site name", "format": "string"}}}]}
    :param uuid: {"description": "uuid of the object", "format": "string", "minLength": 1, "modify-not-allowed": 1, "optional": true, "maxLength": 64, "type": "string"}
    :param disable: {"default": 0, "optional": true, "type": "number", "description": "Disable all members", "format": "flag"}
    :param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`

    URL for this object::
    `https://<Hostname|Ip address>//axapi/v3/gslb/service-group/{service_group_name}`.

    """
    def __init__(self, **kwargs):
        self.ERROR_MSG = ""
        self.required = [ "service_group_name"]

        self.b_key = "service-group"
        self.a10_url="/axapi/v3/gslb/service-group/{service_group_name}"
        self.DeviceProxy = ""
        self.member = []
        self.service_group_name = ""
        self.disable_site_list = []
        self.uuid = ""
        self.disable = ""

        for keys, value in kwargs.items():
            setattr(self,keys, value)


text:
package io.quarkus.arc.test.interceptors.finalmethod;

import static org.junit.jupiter.api.Assertions.assertEquals;

import javax.annotation.PostConstruct;
import javax.annotation.Priority;
import javax.inject.Singleton;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.quarkus.arc.Arc;
import io.quarkus.arc.test.ArcTestContainer;
import io.quarkus.arc.test.interceptors.Simple;

public class FinalNonInterceptedMethodTest {

    static final String VAL = "ping";

    @RegisterExtension
    public ArcTestContainer container = new ArcTestContainer(Simple.class, SimpleBean.class,
            SimpleInterceptor.class);

    @Test
    public void testInvocation() {
        SimpleBean bean = Arc.container().instance(SimpleBean.class).get();
        assertEquals(VAL, bean.foo());
        assertEquals("a" + VAL, bean.bar());
    }

    @Singleton
    static class SimpleBean {

        private String val;

        @PostConstruct
        void init() {
            val = VAL;
        }

        // This method is final but not intercepted = OK
        final String foo() {
            return val;
        }

        @Simple
        String bar() {
            return val;
        }

    }

    @Simple
    @Priority(1)
    @Interceptor
    static class SimpleInterceptor {

        @AroundInvoke
        Object mySuperCoolAroundInvoke(InvocationContext ctx) throws Exception {
            return "a" + ctx.proceed();
        }
    }

}


text:
namespace dlib
{

// ----------------------------------------------------------------------------------------

    namespace impl
    {

        template <typename T>
        class helper_parallel_for
        {
        public:
            helper_parallel_for (
                T& obj_,
                void (T::*funct_)(long)
            ) :
                obj(obj_),
                funct(funct_)
            {}

            T& obj;
            void (T::*funct)(long);

            void process_block (long begin, long end)
            {
                for (long i = begin; i < end; ++i)
                    (obj.*funct)(i);
            }
        };

        template <typename T>
        class helper_parallel_for_funct
        {
        public:
            helper_parallel_for_funct (
                const T& funct_
            ) : funct(funct_) {}

            const T& funct;

            void run(long i)
            {
                funct(i);
            }
        };

        template <typename T>
        class helper_parallel_for_funct2
        {
        public:
            helper_parallel_for_funct2 (
                const T& funct_
            ) : funct(funct_) {}

            const T& funct;

            void run(long begin, long end)
            {
                funct(begin, end);
            }
        };
    }

// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------

    template <typename T>
    void parallel_for_blocked (
        thread_pool& tp,
        long begin,
        long end,
        T& obj,
        void (T::*funct)(long, long),
        long chunks_per_thread = 8
    )
    {
        // make sure requires clause is not broken
        DLIB_ASSERT(begin <= end && chunks_per_thread > 0,
            "\t void parallel_for_blocked()"
            << "\n\t Invalid inputs were given to this function"
            << "\n\t begin: " << begin
            << "\n\t end:   " << end
            << "\n\t chunks_per_thread: " << chunks_per_thread
            );

        if (tp.num_threads_in_pool() != 0)
        {
            const long num = end-begin;
            const long num_workers = static_cast<long>(tp.num_threads_in_pool());
            // How many samples to process in a single task (aim for chunks_per_thread jobs per worker)
            const long block_size = std::max(1L, num/(num_workers*chunks_per_thread));
            for (long i = 0; i < num; i+=block_size)
            {
                tp.add_task(obj, funct, begin+i, begin+std::min(i+block_size, num));
            }
            tp.wait_for_all_tasks();
        }
        else
        {
            // Since there aren't any threads in the pool we might as well just invoke
            // the function directly since that's all the thread_pool object would do.
            // But doing it ourselves skips a mutex lock.
            (obj.*funct)(begin, end);
        }
    }

// ----------------------------------------------------------------------------------------

    template <typename T>
    void parallel_for_blocked (
        unsigned long num_threads,
        long begin,
        long end,
        T& obj,
        void (T::*funct)(long, long),
        long chunks_per_thread = 8
    )
    {
        // make sure requires clause is not broken
        DLIB_ASSERT(begin <= end && chunks_per_thread > 0,
            "\t void parallel_for_blocked()"
            << "\n\t Invalid inputs were given to this function"
            << "\n\t begin: " << begin
            << "\n\t end:   " << end
            << "\n\t chunks_per_thread: " << chunks_per_thread
            );

        thread_pool tp(num_threads);
        parallel_for_blocked(tp, begin, end, obj, funct, chunks_per_thread);
    }

// ----------------------------------------------------------------------------------------

    template <typename T>
    void parallel_for_blocked (
        thread_pool& tp,
        long begin,
        long end,
        const T& funct,
        long chunks_per_thread = 8
    )
    {
        // make sure requires clause is not broken
        DLIB_ASSERT(begin <= end && chunks_per_thread > 0,
            "\t void parallel_for_blocked()"
            << "\n\t Invalid inputs were given to this function"
            << "\n\t begin: " << begin
            << "\n\t end:   " << end
            << "\n\t chunks_per_thread: " << chunks_per_thread
            );

        impl::helper_parallel_for_funct2<T> helper(funct);
        parallel_for_blocked(tp, begin, end,  helper, &impl::helper_parallel_for_funct2<T>::run,  chunks_per_thread);
    }

// ----------------------------------------------------------------------------------------

    template <typename T>
    void parallel_for_blocked (
        unsigned long num_threads,
        long begin,
        long end,
        const T& funct,
        long chunks_per_thread = 8
    )
    {
        // make sure requires clause is not broken
        DLIB_ASSERT(begin <= end && chunks_per_thread > 0,
            "\t void parallel_for_blocked()"
            << "\n\t Invalid inputs were given to this function"
            << "\n\t begin: " << begin
            << "\n\t end:   " << end
            << "\n\t chunks_per_thread: " << chunks_per_thread
            );

        thread_pool tp(num_threads);
        parallel_for_blocked(tp, begin, end, funct, chunks_per_thread);
    }

// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------

    template <typename T>
    void parallel_for (
        thread_pool& tp,
        long begin,
        long end,
        T& obj,
        void (T::*funct)(long),
        long chunks_per_thread = 8
    )
    {
        // make sure requires clause is not broken
        DLIB_ASSERT(begin <= end && chunks_per_thread > 0,
            "\t void parallel_for()"
            << "\n\t Invalid inputs were given to this function"
            << "\n\t begin: " << begin
            << "\n\t end:   " << end
            << "\n\t chunks_per_thread: " << chunks_per_thread
            );

        impl::helper_parallel_for<T> helper(obj, funct);
        parallel_for_blocked(tp, begin, end, helper, &impl::helper_parallel_for<T>::process_block, chunks_per_thread);
    }

// ----------------------------------------------------------------------------------------

    template <typename T>
    void parallel_for (
        unsigned long num_threads,
        long begin,
        long end,
        T& obj,
        void (T::*funct)(long),
        long chunks_per_thread = 8
    )
    {
        // make sure requires clause is not broken
        DLIB_ASSERT(begin <= end && chunks_per_thread > 0,
            "\t void parallel_for()"
            << "\n\t Invalid inputs were given to this function"
            << "\n\t begin: " << begin
            << "\n\t end:   " << end
            << "\n\t chunks_per_thread: " << chunks_per_thread
            );

        thread_pool tp(num_threads);
        parallel_for(tp, begin, end, obj, funct, chunks_per_thread);
    }

// ----------------------------------------------------------------------------------------

    template <typename T>
    void parallel_for (
        thread_pool& tp,
        long begin,
        long end,
        const T& funct,
        long chunks_per_thread = 8
    )
    {
        // make sure requires clause is not broken
        DLIB_ASSERT(begin <= end && chunks_per_thread > 0,
            "\t void parallel_for()"
            << "\n\t Invalid inputs were given to this function"
            << "\n\t begin: " << begin
            << "\n\t end:   " << end
            << "\n\t chunks_per_thread: " << chunks_per_thread
            );

        impl::helper_parallel_for_funct<T> helper(funct);
        parallel_for(tp, begin, end,  helper, &impl::helper_parallel_for_funct<T>::run,  chunks_per_thread);
    }

// ----------------------------------------------------------------------------------------

    template <typename T>
    void parallel_for (
        unsigned long num_threads,
        long begin,
        long end,
        const T& funct,
        long chunks_per_thread = 8
    )
    {
        // make sure requires clause is not broken
        DLIB_ASSERT(begin <= end && chunks_per_thread > 0,
            "\t void parallel_for()"
            << "\n\t Invalid inputs were given to this function"
            << "\n\t begin: " << begin
            << "\n\t end:   " << end
            << "\n\t chunks_per_thread: " << chunks_per_thread
            );

        thread_pool tp(num_threads);
        parallel_for(tp, begin, end, funct, chunks_per_thread);
    }

// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------

    namespace impl
    {
        template <typename T>
        class parfor_verbose_helper
        {
        public:
            parfor_verbose_helper(T& obj_, void (T::*funct_)(long), long begin, long end) :
                obj(obj_), funct(funct_), pbar(end-begin)
            {
                count = 0;
                wrote_to_screen = pbar.print_status(0);
            }

            ~parfor_verbose_helper()
            {
                if (wrote_to_screen)
                    std::cout << std::endl;
            }

            mutable long count;
            T& obj;
            void (T::*funct)(long);
            mutable console_progress_indicator pbar;
            mutable bool wrote_to_screen;
            mutex m;

            void operator()(long i) const
            {
                (obj.*funct)(i);
                {
                    auto_mutex lock(m);
                    wrote_to_screen = pbar.print_status(++count) || wrote_to_screen;
                }
            }

        };

        template <typename T>
        class parfor_verbose_helper3
        {
        public:
            parfor_verbose_helper3(T& obj_, void (T::*funct_)(long,long), long begin, long end) :
                obj(obj_), funct(funct_), pbar(end-begin)
            {
                count = 0;
                wrote_to_screen = pbar.print_status(0);
            }

            ~parfor_verbose_helper3()
            {
                if (wrote_to_screen)
                    std::cout << std::endl;
            }

            mutable long count;
            T& obj;
            void (T::*funct)(long,long);
            mutable console_progress_indicator pbar;
            mutable bool wrote_to_screen;
            mutex m;

            void operator()(long begin, long end) const
            {
                (obj.*funct)(begin, end);
                {
                    auto_mutex lock(m);
                    count += end-begin;
                    wrote_to_screen = pbar.print_status(count) || wrote_to_screen;
                }
            }
        };

        template <typename T>
        class parfor_verbose_helper2
        {
        public:
            parfor_verbose_helper2(const T& obj_, long begin, long end) : obj(obj_), pbar(end-begin)
            {
                count = 0;
                wrote_to_screen = pbar.print_status(0);
            }

            ~parfor_verbose_helper2()
            {
                if (wrote_to_screen)
                    std::cout << std::endl;
            }

            mutable long count;
            const T& obj;
            mutable console_progress_indicator pbar;
            mutable bool wrote_to_screen;
            mutex m;

            void operator()(long i) const
            {
                obj(i);
                {
                    auto_mutex lock(m);
                    wrote_to_screen = pbar.print_status(++count) || wrote_to_screen;
                }
            }

            void operator()(long begin, long end) const
            {
                obj(begin, end);
                {
                    auto_mutex lock(m);
                    count += end-begin;
                    wrote_to_screen = pbar.print_status(count) || wrote_to_screen;
                }
            }
        };
    }

    template <typename T>
    void parallel_for_verbose (
        thread_pool& tp,
        long begin,
        long end,
        T& obj,
        void (T::*funct)(long),
        long chunks_per_thread = 8
    )
    {
        // make sure requires clause is not broken
        DLIB_ASSERT(begin <= end && chunks_per_thread > 0,
            "\t void parallel_for_verbose()"
            << "\n\t Invalid inputs were given to this function"
            << "\n\t begin: " << begin
            << "\n\t end:   " << end
            << "\n\t chunks_per_thread: " << chunks_per_thread
            );

        impl::parfor_verbose_helper<T> helper(obj, funct, begin, end);
        parallel_for(tp, begin, end, helper, chunks_per_thread);
    }

// ----------------------------------------------------------------------------------------

    template <typename T>
    void parallel_for_verbose (
        unsigned long num_threads,
        long begin,
        long end,
        T& obj,
        void (T::*funct)(long),
        long chunks_per_thread = 8
    )
    {
        // make sure requires clause is not broken
        DLIB_ASSERT(begin <= end && chunks_per_thread > 0,
            "\t void parallel_for_verbose()"
            << "\n\t Invalid inputs were given to this function"
            << "\n\t begin: " << begin
            << "\n\t end:   " << end
            << "\n\t chunks_per_thread: " << chunks_per_thread
            );

        impl::parfor_verbose_helper<T> helper(obj, funct, begin, end);
        parallel_for(num_threads, begin, end, helper, chunks_per_thread);
    }

// ----------------------------------------------------------------------------------------

    template <typename T>
    void parallel_for_verbose (
        thread_pool& tp,
        long begin,
        long end,
        const T& funct,
        long chunks_per_thread = 8
    )
    {
        // make sure requires clause is not broken
        DLIB_ASSERT(begin <= end && chunks_per_thread > 0,
            "\t void parallel_for_verbose()"
            << "\n\t Invalid inputs were given to this function"
            << "\n\t begin: " << begin
            << "\n\t end:   " << end
            << "\n\t chunks_per_thread: " << chunks_per_thread
            );

        impl::parfor_verbose_helper2<T> helper(funct, begin, end);
        parallel_for(tp, begin, end,  helper, chunks_per_thread);
    }

// ----------------------------------------------------------------------------------------

    template <typename T>
    void parallel_for_verbose (
        unsigned long num_threads,
        long begin,
        long end,
        const T& funct,
        long chunks_per_thread = 8
    )
    {
        // make sure requires clause is not broken
        DLIB_ASSERT(begin <= end && chunks_per_thread > 0,
            "\t void parallel_for_verbose()"
            << "\n\t Invalid inputs were given to this function"
            << "\n\t begin: " << begin
            << "\n\t end:   " << end
            << "\n\t chunks_per_thread: " << chunks_per_thread
            );

        impl::parfor_verbose_helper2<T> helper(funct, begin, end);
        parallel_for(num_threads, begin, end, helper, chunks_per_thread);
    }

// ----------------------------------------------------------------------------------------

    template <typename T>
    void parallel_for_blocked_verbose (
        thread_pool& tp,
        long begin,
        long end,
        T& obj,
        void (T::*funct)(long,long),
        long chunks_per_thread = 8
    )
    {
        // make sure requires clause is not broken
        DLIB_ASSERT(begin <= end && chunks_per_thread > 0,
            "\t void parallel_for_blocked_verbose()"
            << "\n\t Invalid inputs were given to this function"
            << "\n\t begin: " << begin
            << "\n\t end:   " << end
            << "\n\t chunks_per_thread: " << chunks_per_thread
            );

        impl::parfor_verbose_helper3<T> helper(obj, funct, begin, end);
        parallel_for_blocked(tp, begin, end, helper, chunks_per_thread);
    }

// ----------------------------------------------------------------------------------------

    template <typename T>
    void parallel_for_blocked_verbose (
        unsigned long num_threads,
        long begin,
        long end,
        T& obj,
        void (T::*funct)(long,long),
        long chunks_per_thread = 8
    )
    {
        // make sure requires clause is not broken
        DLIB_ASSERT(begin <= end && chunks_per_thread > 0,
            "\t void parallel_for_blocked_verbose()"
            << "\n\t Invalid inputs were given to this function"
            << "\n\t begin: " << begin
            << "\n\t end:   " << end
            << "\n\t chunks_per_thread: " << chunks_per_thread
            );

        impl::parfor_verbose_helper3<T> helper(obj, funct, begin, end);
        parallel_for_blocked(num_threads, begin, end, helper, chunks_per_thread);
    }

// ----------------------------------------------------------------------------------------

    template <typename T>
    void parallel_for_blocked_verbose (
        thread_pool& tp,
        long begin,
        long end,
        const T& funct,
        long chunks_per_thread = 8
    )
    {
        // make sure requires clause is not broken
        DLIB_ASSERT(begin <= end && chunks_per_thread > 0,
            "\t void parallel_for_blocked_verbose()"
            << "\n\t Invalid inputs were given to this function"
            << "\n\t begin: " << begin
            << "\n\t end:   " << end
            << "\n\t chunks_per_thread: " << chunks_per_thread
            );

        impl::parfor_verbose_helper2<T> helper(funct, begin, end);
        parallel_for_blocked(tp, begin, end,  helper, chunks_per_thread);
    }

// ----------------------------------------------------------------------------------------

    template <typename T>
    void parallel_for_blocked_verbose (
        unsigned long num_threads,
        long begin,
        long end,
        const T& funct,
        long chunks_per_thread = 8
    )
    {
        // make sure requires clause is not broken
        DLIB_ASSERT(begin <= end && chunks_per_thread > 0,
            "\t void parallel_for_blocked_verbose()"
            << "\n\t Invalid inputs were given to this function"
            << "\n\t begin: " << begin
            << "\n\t end:   " << end
            << "\n\t chunks_per_thread: " << chunks_per_thread
            );

        impl::parfor_verbose_helper2<T> helper(funct, begin, end);
        parallel_for_blocked(num_threads, begin, end, helper, chunks_per_thread);
    }

// ----------------------------------------------------------------------------------------

}

#endif // DLIB_PARALLEL_FoR_Hh_


text:
package org.ovirt.engine.ui.uicommonweb.models.datacenters;

import java.util.ArrayList;
import java.util.List;

import org.ovirt.engine.core.common.VdcActionUtils;
import org.ovirt.engine.core.common.action.AttachStorageDomainToPoolParameters;
import org.ovirt.engine.core.common.action.DetachStorageDomainFromPoolParameters;
import org.ovirt.engine.core.common.action.RemoveStorageDomainParameters;
import org.ovirt.engine.core.common.action.StorageDomainPoolParametersBase;
import org.ovirt.engine.core.common.action.VdcActionParametersBase;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.businessentities.StorageDomain;
import org.ovirt.engine.core.common.businessentities.StorageDomainSharedStatus;
import org.ovirt.engine.core.common.businessentities.StorageDomainStatic;
import org.ovirt.engine.core.common.businessentities.StorageDomainStatus;
import org.ovirt.engine.core.common.businessentities.StorageDomainType;
import org.ovirt.engine.core.common.businessentities.StorageFormatType;
import org.ovirt.engine.core.common.businessentities.StoragePool;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.storage.StorageType;
import org.ovirt.engine.core.common.queries.IdQueryParameters;
import org.ovirt.engine.core.common.queries.VdcQueryReturnValue;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.core.compat.Version;
import org.ovirt.engine.ui.frontend.AsyncQuery;
import org.ovirt.engine.ui.frontend.Frontend;
import org.ovirt.engine.ui.frontend.INewAsyncCallback;
import org.ovirt.engine.ui.uicommonweb.Linq;
import org.ovirt.engine.ui.uicommonweb.UICommand;
import org.ovirt.engine.ui.uicommonweb.dataprovider.AsyncDataProvider;
import org.ovirt.engine.ui.uicommonweb.help.HelpTag;
import org.ovirt.engine.ui.uicommonweb.models.ConfirmationModel;
import org.ovirt.engine.ui.uicommonweb.models.EntityModel;
import org.ovirt.engine.ui.uicommonweb.models.ListModel;
import org.ovirt.engine.ui.uicommonweb.models.Model;
import org.ovirt.engine.ui.uicommonweb.models.SearchableListModel;
import org.ovirt.engine.ui.uicompat.ConstantsManager;
import org.ovirt.engine.ui.uicompat.FrontendMultipleActionAsyncResult;
import org.ovirt.engine.ui.uicompat.IFrontendMultipleActionAsyncCallback;
import org.ovirt.engine.ui.uicompat.NotifyCollectionChangedEventArgs;
import org.ovirt.engine.ui.uicompat.PropertyChangedEventArgs;

@SuppressWarnings("unused")
public class DataCenterStorageListModel extends SearchableListModel<StoragePool, StorageDomain> {

    private UICommand privateAttachStorageCommand;

    public UICommand getAttachStorageCommand() {
        return privateAttachStorageCommand;
    }

    private void setAttachStorageCommand(UICommand value) {
        privateAttachStorageCommand = value;
    }

    private UICommand privateAttachISOCommand;

    public UICommand getAttachISOCommand() {
        return privateAttachISOCommand;
    }

    private void setAttachISOCommand(UICommand value) {
        privateAttachISOCommand = value;
    }

    private UICommand privateAttachBackupCommand;

    public UICommand getAttachBackupCommand() {
        return privateAttachBackupCommand;
    }

    private void setAttachBackupCommand(UICommand value) {
        privateAttachBackupCommand = value;
    }

    private UICommand privateDetachCommand;

    public UICommand getDetachCommand() {
        return privateDetachCommand;
    }

    private void setDetachCommand(UICommand value) {
        privateDetachCommand = value;
    }

    private UICommand privateActivateCommand;

    public UICommand getActivateCommand() {
        return privateActivateCommand;
    }

    private void setActivateCommand(UICommand value) {
        privateActivateCommand = value;
    }

    private UICommand privateMaintenanceCommand;

    public UICommand getMaintenanceCommand() {
        return privateMaintenanceCommand;
    }

    private void setMaintenanceCommand(UICommand value) {
        privateMaintenanceCommand = value;
    }

    public void setEntity(StoragePool value) {
        super.setEntity(value);
    }

    private StorageDomainType privateStorageDomainType = getStorageDomainType().values()[0];

    public StorageDomainType getStorageDomainType() {
        return privateStorageDomainType;
    }

    public void setStorageDomainType(StorageDomainType value) {
        privateStorageDomainType = value;
    }

    // A list of 'detach' action parameters
    private ArrayList<VdcActionParametersBase> privatepb_detach;

    private ArrayList<VdcActionParametersBase> getpb_detach() {
        return privatepb_detach;
    }

    private void setpb_detach(ArrayList<VdcActionParametersBase> value) {
        privatepb_detach = value;
    }

    // A list of 'remove' action parameters
    private ArrayList<VdcActionParametersBase> privatepb_remove;

    private ArrayList<VdcActionParametersBase> getpb_remove() {
        return privatepb_remove;
    }

    private void setpb_remove(ArrayList<VdcActionParametersBase> value) {
        privatepb_remove = value;
    }

    private ArrayList<StorageDomain> selectedStorageDomains;

    public DataCenterStorageListModel() {
        setTitle(ConstantsManager.getInstance().getConstants().storageTitle());
        setHelpTag(HelpTag.storage);
        setHashName("storage"); //$NON-NLS-1$

        setAttachStorageCommand(new UICommand("AttachStorage", this)); //$NON-NLS-1$
        setAttachISOCommand(new UICommand("AttachISO", this)); //$NON-NLS-1$
        setAttachBackupCommand(new UICommand("AttachBackup", this)); //$NON-NLS-1$
        setDetachCommand(new UICommand("Detach", this)); //$NON-NLS-1$
        setActivateCommand(new UICommand("Activate", this)); //$NON-NLS-1$
        setMaintenanceCommand(new UICommand("Maintenance", this)); //$NON-NLS-1$

        updateActionAvailability();
    }

    @Override
    protected void onEntityChanged() {
        super.onEntityChanged();
        getSearchCommand().execute();
    }

    @Override
    public void search() {
        if (getEntity() != null) {
            // omer - overriding AsyncSearch - using query instead of search
            // SearchString = StringFormat.format("storage: datacenter={0}", Entity.name);
            super.search();
        }
    }

    @Override
    protected void syncSearch() {
        AsyncQuery _asyncQuery = new AsyncQuery();
        _asyncQuery.setModel(this);
        _asyncQuery.asyncCallback = new INewAsyncCallback() {
            @Override
            public void onSuccess(Object model, Object ReturnValue) {
                setItems((ArrayList<StorageDomain>) ((VdcQueryReturnValue) ReturnValue).getReturnValue());
            }
        };

        IdQueryParameters tempVar = new IdQueryParameters(getEntity().getId());
        tempVar.setRefresh(getIsQueryFirstTime());
        Frontend.getInstance().runQuery(VdcQueryType.GetStorageDomainsByStoragePoolId, tempVar, _asyncQuery);
    }

    public void onMaintenance() {
        ArrayList<VdcActionParametersBase> pb = new ArrayList<VdcActionParametersBase>();
        for (StorageDomain a : Linq.<StorageDomain> cast(getSelectedItems())) {
            pb.add(new StorageDomainPoolParametersBase(a.getId(), getEntity().getId()));
        }

        final ConfirmationModel confirmationModel = (ConfirmationModel) getWindow();
        confirmationModel.startProgress(null);

        Frontend.getInstance().runMultipleAction(VdcActionType.DeactivateStorageDomainWithOvfUpdate, pb, new IFrontendMultipleActionAsyncCallback() {
            @Override
            public void executed(FrontendMultipleActionAsyncResult result) {
                confirmationModel.stopProgress();
                setWindow(null);
            }
        });
    }

    private void maintenance() {
        ConfirmationModel model = new ConfirmationModel();
        model.setTitle(ConstantsManager.getInstance().getConstants().maintenanceStorageDomainsTitle());
        model.setMessage(ConstantsManager.getInstance().getConstants().areYouSureYouWantToPlaceFollowingStorageDomainsIntoMaintenanceModeMsg());
        model.setHashName("maintenance_storage_domain"); //$NON-NLS-1$
        setWindow(model);

        ArrayList<String> items = new ArrayList<String>();
        for (Object selected : getSelectedItems()) {
            items.add(((StorageDomain) selected).getName());
        }
        model.setItems(items);

        UICommand maintenance = UICommand.createDefaultOkUiCommand("OnMaintenance", this); //$NON-NLS-1$
        model.getCommands().add(maintenance);

        UICommand cancel = UICommand.createCancelUiCommand("Cancel", this); //$NON-NLS-1$
        model.getCommands().add(cancel);
    }

    public void activate() {
        ArrayList<VdcActionParametersBase> pb = new ArrayList<VdcActionParametersBase>();
        for (StorageDomain a : Linq.<StorageDomain> cast(getSelectedItems())) {
            pb.add(new StorageDomainPoolParametersBase(a.getId(), getEntity().getId()));
        }

        Frontend.getInstance().runMultipleAction(VdcActionType.ActivateStorageDomain, pb);
    }

    public void attachBackup() {
        ListModel listModel = new ListModel();
        listModel.setTitle(ConstantsManager.getInstance().getConstants().attachExportDomainTitle());
        listModel.setHelpTag(HelpTag.attach_export_domain);
        listModel.setHashName("attach_export_domain"); //$NON-NLS-1$
        attachInternal(listModel, StorageDomainType.ImportExport);
    }

    public void attachISO() {
        ListModel listModel = new ListModel();
        listModel.setTitle(ConstantsManager.getInstance().getConstants().attachISOLibraryTitle());
        listModel.setHelpTag(HelpTag.attach_iso_library);
        listModel.setHashName("attach_iso_library"); //$NON-NLS-1$
        attachInternal(listModel, StorageDomainType.ISO);
    }

    public void attachStorage() {
        ListModel listModel = new ListModel();
        listModel.setTitle(ConstantsManager.getInstance().getConstants().attachStorageTitle());
        listModel.setHelpTag(HelpTag.attach_storage);
        listModel.setHashName("attach_storage"); //$NON-NLS-1$
        attachInternal(listModel, StorageDomainType.Data);
    }

    private void attachInternal(ListModel listModel, StorageDomainType storageType) {
        if (getWindow() != null) {
            return;
        }

        this.setStorageDomainType(storageType);

        setWindow(listModel);

        if (storageType == StorageDomainType.ISO) {
            AsyncQuery _asyncQuery = new AsyncQuery();
            _asyncQuery.setModel(this);
            _asyncQuery.asyncCallback = new INewAsyncCallback() {
                @Override
                public void onSuccess(Object model, Object result) {
                    ArrayList<StorageDomain> list = (ArrayList<StorageDomain>) result;
                    DataCenterStorageListModel dcStorageModel = (DataCenterStorageListModel) model;
                    ArrayList<EntityModel> models;
                    models = new ArrayList<EntityModel>();
                    ArrayList<StorageDomain> items =
                            dcStorageModel.getItems() != null ? new ArrayList<StorageDomain>(Linq.<StorageDomain> cast(dcStorageModel.getItems()))
                                    : new ArrayList<StorageDomain>();
                    for (StorageDomain a : list) {
                        if (!Linq.isSDItemExistInList(items, a.getId())) {
                            EntityModel tempVar = new EntityModel();
                            tempVar.setEntity(a);
                            models.add(tempVar);
                        }
                    }
                    dcStorageModel.postAttachInternal(models);

                }
            };
            AsyncDataProvider.getInstance().getISOStorageDomainList(_asyncQuery);
        }
        else {

            AsyncQuery _asyncQuery = new AsyncQuery();
            _asyncQuery.setModel(this);
            _asyncQuery.asyncCallback = new INewAsyncCallback() {
                @Override
                public void onSuccess(Object model, Object result) {
                    DataCenterStorageListModel dcStorageModel = (DataCenterStorageListModel) model;
                    ArrayList<StorageDomain> list = (ArrayList<StorageDomain>) result;
                    ArrayList<EntityModel> models = new ArrayList<EntityModel>();
                    boolean addToList;
                    ArrayList<StorageDomain> items =
                            dcStorageModel.getItems() != null ? new ArrayList<StorageDomain>(Linq.<StorageDomain> cast(dcStorageModel.getItems()))
                                    : new ArrayList<StorageDomain>();
                    for (StorageDomain a : list) {
                        addToList = false;
                        if (Linq.isSDItemExistInList(items, a.getId()) ||
                                a.getStorageDomainSharedStatus() != StorageDomainSharedStatus.Unattached) {
                            continue;
                        }
                        if (a.getStorageDomainType() == StorageDomainType.Volume) {
                            addToList = true;
                        }
                        else if (a.getStorageDomainType() == dcStorageModel.getStorageDomainType()) {
                            if (dcStorageModel.getStorageDomainType() == StorageDomainType.Data) {
                                if (dcStorageModel.getEntity().getStoragePoolFormatType() == null) {
                                    // skip V3 format for DC ver <= 3
                                    if (a.getStorageStaticData().getStorageFormat() == StorageFormatType.V3
                                            && dcStorageModel.getEntity()
                                                    .getCompatibilityVersion()
                                                    .compareTo(Version.v3_0) <= 0) {
                                        continue;
                                    }

                                    addToList = true;
                                }
                                else if (dcStorageModel.getEntity().getStoragePoolFormatType() == a.getStorageStaticData()
                                        .getStorageFormat()) {
                                    addToList = true;
                                }
                                else if (dcStorageModel.getEntity().getCompatibilityVersion().compareTo(Version.v3_1) >= 0) {
                                    // if DC is >= 3.1 we support upgrading
                                    if (a.getStorageStaticData().getStorageFormat() == StorageFormatType.V1
                                            || a.getStorageStaticData().getStorageFormat() == StorageFormatType.V2) {
                                        addToList = true;
                                    }
                                }
                            }
                            else if (dcStorageModel.getStorageDomainType() == StorageDomainType.ImportExport) {
                                addToList = true;
                            }
                        }
                        if (addToList) {
                            EntityModel tempVar2 = new EntityModel();
                            tempVar2.setEntity(a);
                            models.add(tempVar2);
                        }
                    }
                    dcStorageModel.postAttachInternal(models);
                }
            };
            AsyncDataProvider.getInstance().getStorageDomainList(_asyncQuery);
        }

    }

    private void postAttachInternal(ArrayList<EntityModel> models) {
        ListModel listModel = (ListModel) getWindow();
        listModel.setItems(models);

        if (models.isEmpty()) {
            listModel.setMessage(ConstantsManager.getInstance()
                    .getConstants()
                    .thereAreNoCompatibleStorageDomainsAttachThisDcMsg());

            UICommand tempVar = new UICommand("Cancel", this); //$NON-NLS-1$
            tempVar.setTitle(ConstantsManager.getInstance().getConstants().close());
            tempVar.setIsDefault(true);
            tempVar.setIsCancel(true);
            listModel.getCommands().add(tempVar);
        }
        else {
            UICommand tempVar2 = UICommand.createDefaultOkUiCommand("OnAttach", this); //$NON-NLS-1$
            listModel.getCommands().add(tempVar2);
            UICommand tempVar3 = UICommand.createCancelUiCommand("Cancel", this); //$NON-NLS-1$
            listModel.getCommands().add(tempVar3);
        }
    }

    public void onAttach() {
        ListModel model = (ListModel) getWindow();
        ArrayList<StorageDomain> selectedDataStorageDomains = new ArrayList<StorageDomain>();

        if (getEntity() == null) {
            cancel();
            return;
        }

        selectedStorageDomains = new ArrayList<StorageDomain>();
        for (EntityModel a : Linq.<EntityModel> cast(model.getItems())) {
            if (a.getIsSelected()) {
                StorageDomain storageDomain = (StorageDomain) a.getEntity();
                selectedStorageDomains.add(storageDomain);
                if (storageDomain.getStorageDomainType() == StorageDomainType.Data) {
                    selectedDataStorageDomains.add(storageDomain);
                }
            }
        }

        if (selectedStorageDomains.isEmpty()) {
            cancel();
            return;
        }

        AsyncDataProvider.getInstance().getStorageDomainsWithAttachedStoragePoolGuid(
                new AsyncQuery(this, new INewAsyncCallback() {
                    @Override
                    public void onSuccess(Object target, Object returnValue) {
                        DataCenterStorageListModel dataCenterStorageListModel = (DataCenterStorageListModel) target;
                        List<StorageDomainStatic> attachedStorageDomains = (List<StorageDomainStatic>) returnValue;
                        if (!attachedStorageDomains.isEmpty()) {
                            ConfirmationModel model = new ConfirmationModel();
                            dataCenterStorageListModel.setWindow(null);
                            dataCenterStorageListModel.setWindow(model);

                            List<String> stoageDomainNames = new ArrayList<String>();
                            for (StorageDomainStatic domain : attachedStorageDomains) {
                                stoageDomainNames.add(domain.getStorageName());
                            }
                            model.setItems(stoageDomainNames);

                            model.setTitle(ConstantsManager.getInstance()
                                    .getConstants()
                                    .storageDomainsAttachedToDataCenterWarningTitle());
                            model.setMessage(ConstantsManager.getInstance()
                                    .getConstants()
                                    .storageDomainsAttachedToDataCenterWarningMessage());

                            model.setHelpTag(HelpTag.attach_storage_domain_confirmation);
                            model.setHashName("attach_storage_domain_confirmation"); //$NON-NLS-1$

                            model.getLatch().setIsAvailable(true);
                            model.getLatch().setIsChangeable(true);

                            UICommand onApprove = new UICommand("OnAttachApprove", dataCenterStorageListModel); //$NON-NLS-1$
                            onApprove.setTitle(ConstantsManager.getInstance().getConstants().ok());
                            onApprove.setIsDefault(true);
                            model.getCommands().add(onApprove);

                            UICommand cancel = new UICommand("Cancel", dataCenterStorageListModel); //$NON-NLS-1$
                            cancel.setTitle(ConstantsManager.getInstance().getConstants().cancel());
                            cancel.setIsCancel(true);
                            model.getCommands().add(cancel);
                        } else {
                            executeAttachStorageDomains();
                        }
                    }
                }), getEntity(), selectedDataStorageDomains);
    }

    public void onAttachApprove() {
        ConfirmationModel model = (ConfirmationModel) getWindow();
        if (!model.validate()) {
            return;
        }

        executeAttachStorageDomains();
    }

    public void executeAttachStorageDomains() {
        ArrayList<VdcActionParametersBase> pb = new ArrayList<VdcActionParametersBase>();
        for (StorageDomain storageDomain : selectedStorageDomains) {
            pb.add(new AttachStorageDomainToPoolParameters(storageDomain.getId(), getEntity().getId()));
        }
        Frontend.getInstance().runMultipleAction(VdcActionType.AttachStorageDomainToPool, pb);
        cancel();
    }

    public void detach() {
        if (getWindow() != null) {
            return;
        }

        ConfirmationModel model = new ConfirmationModel();
        setWindow(model);
        model.setTitle(ConstantsManager.getInstance().getConstants().detachStorageTitle());
        model.setHelpTag(HelpTag.detach_storage);
        model.setHashName("detach_storage"); //$NON-NLS-1$
        model.setMessage(ConstantsManager.getInstance().getConstants().areYouSureYouWantDetachFollowingStoragesMsg());

        ArrayList<String> list = new ArrayList<String>();
        boolean shouldAddressWarnning = false;
        for (StorageDomain item : Linq.<StorageDomain> cast(getSelectedItems())) {
            list.add(item.getStorageName());
            if (item.getStorageDomainType().isDataDomain()) {
                shouldAddressWarnning = true;
                break;
            }
        }
        model.setItems(list);

        if (containsLocalStorage(model)) {
            shouldAddressWarnning = false;
            model.getForce().setIsAvailable(true);
            model.getForce().setIsChangeable(true);
            model.setForceLabel(ConstantsManager.getInstance().getConstants().storageRemovePopupFormatLabel());

            model.setNote(ConstantsManager.getInstance().getMessages().detachNote(getLocalStoragesFormattedString()));
        }

        if (shouldAddressWarnning) {
            model.setNote(ConstantsManager.getInstance().getConstants().detachWarnningNote());
        }
        UICommand tempVar = UICommand.createDefaultOkUiCommand("OnDetach", this); //$NON-NLS-1$
        model.getCommands().add(tempVar);
        UICommand tempVar2 = UICommand.createCancelUiCommand("Cancel", this); //$NON-NLS-1$
        model.getCommands().add(tempVar2);
    }

    private String getLocalStoragesFormattedString() {
        StringBuilder localStorages = new StringBuilder();
        for (StorageDomain a : Linq.<StorageDomain> cast(getSelectedItems())) {
            if (a.getStorageType() == StorageType.LOCALFS) {
                localStorages.append(a.getStorageName()).append(", "); //$NON-NLS-1$
            }
        }
        return localStorages.substring(0, localStorages.length() - 2);
    }

    private boolean containsLocalStorage(ConfirmationModel model) {
        for (StorageDomain a : Linq.<StorageDomain> cast(getSelectedItems())) {
            if (a.getStorageType() == StorageType.LOCALFS) {
                return true;
            }
        }
        return false;
    }

    public void onDetach() {
        final ConfirmationModel confirmModel = (ConfirmationModel) getWindow();

        if (confirmModel.getProgress() != null) {
            return;
        }

        if (!confirmModel.validate()) {
            return;
        }

        // A list of 'detach' action parameters
        setpb_detach(new ArrayList<VdcActionParametersBase>());
        // A list of 'remove' action parameters
        setpb_remove(new ArrayList<VdcActionParametersBase>());
        String localStorgaeDC = null;
        for (StorageDomain a : Linq.<StorageDomain> cast(getSelectedItems())) {
            // For local storage - remove; otherwise - detach
            if (a.getStorageType() == StorageType.LOCALFS && a.getStorageDomainType() != StorageDomainType.ISO) {
                getpb_remove().add(new RemoveStorageDomainParameters(a.getId()));
                localStorgaeDC = a.getStoragePoolName();
            }
            else {
                getpb_detach().add(new DetachStorageDomainFromPoolParameters(a.getId(), getEntity().getId()));
            }
        }

        confirmModel.startProgress(null);

        if (getpb_remove().size() > 0) {
            AsyncQuery _asyncQuery = new AsyncQuery();
            _asyncQuery.setModel(this);
            _asyncQuery.asyncCallback = new INewAsyncCallback() {
                @Override
                public void onSuccess(Object model, Object result) {
                    DataCenterStorageListModel dataCenterStorageListModel = (DataCenterStorageListModel) model;
                    VDS locaVds = (VDS) result;
                    for (VdcActionParametersBase item : dataCenterStorageListModel.getpb_remove()) {
                        ((RemoveStorageDomainParameters) item).setVdsId((locaVds != null ? locaVds.getId() : null));
                        ((RemoveStorageDomainParameters) item).setDoFormat(confirmModel.getForce().getEntity());
                    }

                    dataCenterStorageListModel.postDetach(dataCenterStorageListModel.getWindow());
                }
            };
            AsyncDataProvider.getInstance().getLocalStorageHost(_asyncQuery, localStorgaeDC);
        }
        else {
            postDetach(confirmModel);
        }
    }

    public void postDetach(Model model) {
        Frontend.getInstance().runMultipleAction(VdcActionType.RemoveStorageDomain, getpb_remove(),
                new IFrontendMultipleActionAsyncCallback() {
                    @Override
                    public void executed(FrontendMultipleActionAsyncResult result1) {

                        Object[] array = (Object[]) result1.getState();
                        ConfirmationModel localModel1 = (ConfirmationModel) array[0];
                        ArrayList<VdcActionParametersBase> parameters =
                                (ArrayList<VdcActionParametersBase>) array[1];
                        Frontend.getInstance().runMultipleAction(VdcActionType.DetachStorageDomainFromPool, parameters,
                                new IFrontendMultipleActionAsyncCallback() {
                                    @Override
                                    public void executed(FrontendMultipleActionAsyncResult result2) {

                                        ConfirmationModel localModel2 = (ConfirmationModel) result2.getState();
                                        localModel2.stopProgress();
                                        cancel();

                                    }
                                }, localModel1);

                    }
                }, new Object[] { model, getpb_detach() });
    }

    public void cancel() {
        setWindow(null);
    }

    @Override
    protected void onSelectedItemChanged() {
        super.onSelectedItemChanged();
        updateActionAvailability();
    }

    @Override
    protected void selectedItemsChanged() {
        super.selectedItemsChanged();
        updateActionAvailability();
    }

    @Override
    protected void itemsCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e) {
        super.itemsCollectionChanged(sender, e);
        updateActionAvailability();
    }

    @Override
    protected void itemsChanged() {
        super.itemsChanged();
        updateActionAvailability();
    }

    @Override
    protected void selectedItemPropertyChanged(Object sender, PropertyChangedEventArgs e) {
        super.selectedItemPropertyChanged(sender, e);

        if (e.propertyName.equals("status")) { //$NON-NLS-1$
            updateActionAvailability();
        }
    }

    @Override
    protected void itemPropertyChanged(Object sender, PropertyChangedEventArgs e) {
        super.itemPropertyChanged(sender, e);

        if (e.propertyName.equals("status")) { //$NON-NLS-1$
            updateActionAvailability();
        }
    }

    @Override
    protected boolean getNotifyPropertyChangeForAnyItem() {
        return true;
    }

    private void updateActionAvailability() {
        ArrayList<StorageDomain> items =
                getItems() != null ? Linq.<StorageDomain> cast(getItems())
                        : new ArrayList<StorageDomain>();
        ArrayList<StorageDomain> selectedItems =
                getSelectedItems() != null ? Linq.<StorageDomain> cast(getSelectedItems())
                        : new ArrayList<StorageDomain>();

        if (getEntity() != null) {
            getAttachStorageCommand().setIsExecutionAllowed(!getEntity().isLocal());
        }

        boolean isMasterPresent = false;
        boolean isISOPresent = false;
        boolean isBackupPresent = false;
        for (StorageDomain domain : items) {
            if (isDomainMasterAndActive(domain)) {
                isMasterPresent = true;
            } else if (domain.getStorageDomainType() == StorageDomainType.ISO) {
                isISOPresent = true;
            } else if (domain.getStorageDomainType() == StorageDomainType.ImportExport) {
                isBackupPresent = true;
            }

            if (isMasterPresent && isISOPresent && isBackupPresent) {
                break;
            }
        }

        getAttachISOCommand().setIsExecutionAllowed(false);
        getAttachISOCommand().setIsExecutionAllowed(items.size() > 0 && isMasterPresent && !isISOPresent);

        getAttachBackupCommand().setIsExecutionAllowed(items.size() > 0 && isMasterPresent && !isBackupPresent);

        getDetachCommand().setIsExecutionAllowed(selectedItems.size() > 0
                && VdcActionUtils.canExecute(selectedItems,
                StorageDomain.class,
                VdcActionType.DetachStorageDomainFromPool));

        getActivateCommand().setIsExecutionAllowed(selectedItems.size() == 1
                && VdcActionUtils.canExecute(selectedItems, StorageDomain.class, VdcActionType.ActivateStorageDomain));

        getMaintenanceCommand().setIsExecutionAllowed(selectedItems.size() == 1
                && VdcActionUtils.canExecute(selectedItems,
                StorageDomain.class,
                VdcActionType.DeactivateStorageDomainWithOvfUpdate));
    }

    private boolean isDomainMasterAndActive(StorageDomain domain) {
        return domain.getStorageDomainType() == StorageDomainType.Master && domain.getStatus() == StorageDomainStatus.Active;
    }

    @Override
    public void executeCommand(UICommand command) {
        super.executeCommand(command);

        if (command == getAttachStorageCommand()) {
            attachStorage();
        }
        else if (command == getAttachISOCommand()) {
            attachISO();
        }
        else if (command == getAttachBackupCommand()) {
            attachBackup();
        }
        else if (command == getDetachCommand()) {
            detach();
        }
        else if (command == getActivateCommand()) {
            activate();
        }
        else if (command == getMaintenanceCommand()) {
            maintenance();
        }
        else if ("OnAttach".equals(command.getName())) { //$NON-NLS-1$
            onAttach();
        }
        else if ("OnAttachApprove".equals(command.getName())) { //$NON-NLS-1$
            onAttachApprove();
        }
        else if ("OnDetach".equals(command.getName())) { //$NON-NLS-1$
            onDetach();
        }
        else if ("OnMaintenance".equals(command.getName())) { //$NON-NLS-1$
            onMaintenance();
        }
        else if ("Cancel".equals(command.getName())) { //$NON-NLS-1$
            cancel();
        }
    }

    @Override
    protected String getListName() {
        return "DataCenterStorageListModel"; //$NON-NLS-1$
    }
}