text:
from flask import request
from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth
from werkzeug.security import generate_password_hash, check_password_hash
from itsdangerous import TimedJSONWebSignatureSerializer as JWT
from app.haulers.models import Haulers, HaulersSchema, db
from config import SECRET_KEY, GH_VD_SECRET
import hashlib
from sqlalchemy.sql import text
jwt = JWT(SECRET_KEY, expires_in=3600)

basic_auth = HTTPBasicAuth()
token_auth = HTTPTokenAuth('Bearer')

@basic_auth.verify_password
def verify_password(username, password):
    if len(username) > 0 and len(password) > 0:
        hauler = Haulers.query.with_entities(Haulers.password, Haulers.HAULER_ID).filter_by(email = username, password = password).first()
        if  hauler and hauler.password and check_password_hash(generate_password_hash(hauler.password), password):
            return True
        # Reps Login
        query = db.engine.execute(text("SELECT email, password FROM haulers_representative WHERE email=:e AND password=:p"), {'e':username, 'p':password})
        data = query.fetchall()
        if data:
            for row in data:
                if row.password and check_password_hash(generate_password_hash(row.password), password):
                    return True
    return False

@token_auth.verify_token
def verify_token(token):
    try:
        data = jwt.loads(token)
    except:
        return False
    if 'HAULER_ID' in data:
        return True
    return False

class Auth():
    def find_between( s, first, last ):
        try:
            start = s.index( first ) + len( first )
            end = s.index( last, start )
            return s[start:end]
        except ValueError:
            return ""

    def setToken(HAULER_ID):
        if not HAULER_ID:
            raise ValueError("Invalid Vendor ID")

        user_token = jwt.dumps( {'HAULER_ID':  HAULER_ID} )
        return Auth.find_between( str(user_token), "'", "'" )

    def login(username, password):
        if len(username) > 0 and len(password) > 0:
            hauler = Haulers.query.with_entities(Haulers.password, Haulers.HAULER_ID).filter_by(email = username, password = password).first()
            if  hauler and hauler.password and check_password_hash(generate_password_hash(hauler.password), password):
                user_token = jwt.dumps( {'HAULER_ID':  hauler.HAULER_ID} )
                return Auth.setToken( hauler.HAULER_ID )

        # Reps Login
        query = db.engine.execute(text("SELECT email, password, HAULER_ID FROM haulers_representative WHERE email=:e AND password=:p"), {'e':username, 'p':password})
        data = query.fetchall()
        if data:
            for row in data:
                if row.password and check_password_hash(generate_password_hash(row.password), password):
                    user_token = jwt.dumps( {'HAULER_ID':  row.HAULER_ID} )
                    return Auth.setToken( row.HAULER_ID )

        return False

    def loginByToken(token):
        token = token.strip()
        if token:
            key = GH_VD_SECRET
            query = db.engine.execute("SELECT HAULER_ID, email, password FROM haulers WHERE MD5(CONCAT(HAULER_ID, email,'" + key + "')) = '"+ token +"'" )
            hauler = query.fetchone()
            if hauler:
                user_token = jwt.dumps( {'HAULER_ID':  hauler.HAULER_ID} )
                return Auth.setToken( hauler.HAULER_ID )
        return False

    def validateSignupToken(token):
        token = token.strip()
        if token:
            key = GH_VD_SECRET
            query = db.engine.execute("SELECT HAULER_ID, email, password FROM haulers WHERE MD5(CONCAT(HAULER_ID, email,'" + key + "')) = '"+ token +"'" )
            hauler = query.fetchone()
            if hauler:
                if hauler.password:
                    raise ValueError("token expired, Vendor already has an account.")

                return(hauler.HAULER_ID)

        #raise ValueError("Invalid token")
        return False

    def validateRepsSignupToken(token):
        token = token.strip()
        if token:
            key = GH_VD_SECRET
            query = db.engine.execute("SELECT id, HAULER_ID, email, password FROM haulers_representative WHERE MD5(CONCAT(id, email,'" + key + "')) = '"+ token +"'" )
            hauler = query.fetchone()
            if hauler:
                if hauler.password:
                    raise ValueError("token expired, Vendor Representative already has an account.")

                return(hauler.id)

        raise ValueError("Invalid token")

class Security():
    def getHaulerId(token=False):
        if token:
            access_token = token
        else:
            access_token = request.headers.get('authorization')

        if access_token:
            access_token = access_token.replace('Bearer', '').strip()
            if len(access_token):
                data = jwt.loads(access_token)
                if 'HAULER_ID' in data:
                    return data['HAULER_ID']
        return false


text:
<?php

namespace SequenceBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Etape
 *
 * @ORM\Table(name="etape")
 * @ORM\Entity(repositoryClass="SequenceBundle\Repository\EtapeRepository")
 */
class Etape
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="libelle", type="string", length=255, unique=false)
     */
    private $libelle;

    /**
     * @var string
     *
     * @ORM\Column(name="image", type="string", length=255, nullable=true, unique=false)
     *
     * @Assert\NotBlank(message="Veuillez uploader un fichier jpg / png / gif / bitmap")
     * @Assert\File(mimeTypes={ "image/jpeg", "image/jpg", "image/png", "image/gif", "image/bitmap" })
     */
    private $image;

    /**
     * @var integer
     *
     * @ORM\Column(name="position", type="integer", unique=false)
     */
    private $position;

    /**
      * @ORM\ManyToOne(targetEntity="UserBundle\Entity\User")
      */
    private $createur;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set libelle
     *
     * @param string $libelle
     * @return Etape
     */
    public function setLibelle($libelle)
    {
        $this->libelle = $libelle;

        return $this;
    }

    /**
     * Get libelle
     *
     * @return string
     */
    public function getLibelle()
    {
        return $this->libelle;
    }

    /**
     * Set image
     *
     * @param string $image
     * @return Etape
     */
    public function setImage($image)
    {
        $this->image = $image;

        return $this;
    }

    /**
     * Get image
     *
     * @return string
     */
    public function getImage()
    {
        return $this->image;
    }

    /**
     * Set position
     *
     * @param integer $position
     * @return Etape
     */
    public function setPosition($position)
    {
        $this->position = $position;

        return $this;
    }

    /**
     * Get position
     *
     * @return integer
     */
    public function getPosition()
    {
        return $this->position;
    }

    public function __toString(){
        return $this->libelle;
    }

    /**
     * Set createur
     *
     * @param string $createur
     * @return Etape
     */
    public function setCreateur($createur)
    {
        $this->createur = $createur;

        return $this;
    }

    /**
     * Get createur
     *
     * @return string
     */
    public function getCreateur()
    {
        return $this->createur;
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace CodeHollow.FeedReader.Feeds.MediaRSS
{
    /// <summary>
    /// Specifies the type of an object
    /// </summary>
    public enum Medium
    {
        /// <summary>
        /// Image
        /// </summary>
        Image,

        /// <summary>
        /// Audio
        /// </summary>
        Audio,

        /// <summary>
        /// Video
        /// </summary>
        Video,

        /// <summary>
        /// Document
        /// </summary>
        Document,

        /// <summary>
        /// Executable
        /// </summary>
        Executable,

        /// <summary>
        /// Type could not be determined
        /// </summary>
        Unknown

    }
}


text:
package org.jboss.as.quickstarts.helloworld;

/**
 * A simple CDI service which is able to say hello to someone
 *
 * @author Giriraj Sharma
 *
 */
public class HelloService {

    String createHelloMessage(String name) {
        return "Hello " + name + "!" + " Mutual SSL client authentication is successful and your war app is secured.!!";
    }

}


text:
#import <Cocoa/Cocoa.h>

NSSize sizeScalaedToDimension(NSSize size, float dimension);

NSSize sizeConstrainedByDimension(NSSize size, float dimension);

NSSize scaleSize(NSSize aSize, float scale);

NSRect rectWithSizeCenteredInRect(NSSize size, NSRect rect);

NSRect rectFromNegativeRect(NSRect rect);

NSImage * imageScaledToSizeFromImage(NSSize size, NSImage * image);

NSPoint centerPointOfRect(NSRect rect);

NSBezierPath * roundedRectWithCornerRadius(NSRect aRect, float radius);

CGImageRef CGImageRefNamed(NSString * name) CF_RETURNS_RETAINED;

CGFloat RadiansToDegrees(CGFloat radians);

CGFloat DegreesToRadians(CGFloat degrees);


text:
using Cirrious.CrossCore;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace Paragon.Container.Core
{
    internal sealed class ProductsDatabase : IProductsDatabase
    {
        public ProductsDatabase()
        {
            Common.IFileAccessorFactory fileAccessorFactory = Mvx.Resolve<Common.IFileAccessorFactory>();
            _fileAccessor = fileAccessorFactory.GetLocalFileAccessor();

            ReadDatabase();
        }

        public event Action<int> ProductAdded;
        public event Action<int> ProductExpired;

        public int ProductsCount
        {
            get
            {
                _locker.WaitOne();
                return _model.Products.Count;
            }
        }

        public void AddProduct(int productId)
        {
            _locker.WaitOne();
            lock (_locker)
            {
                DatabaseProductModel newProduct = new DatabaseProductModel();
                newProduct.Id = productId;
                newProduct.Date = DateTime.UtcNow.ToBinary();

                AddProductToDatabase(newProduct);
            }
        }
        public void AddProduct(int productId, DateTime expire)
        {
            _locker.WaitOne();
            lock (_locker)
            {
                DatabaseProductModel newProduct = new DatabaseProductModel();
                newProduct.Id = productId;
                newProduct.Date = DateTime.UtcNow.ToBinary();
                newProduct.Expire = expire.ToBinary();

                AddProductToDatabase(newProduct);
            }
        }
        public bool HasProduct(int productId)
        {
            _locker.WaitOne();
            lock (_locker)
            {
                List<DatabaseProductModel> products = _model.Products;
                foreach (DatabaseProductModel product in products)
                {
                    if (productId == product.Id)
                    {
                        if (!ValidateProduct(product))
                        {
                            return false;
                        }

                        return true;
                    }
                }

                return false;
            }
        }

        private void AddProductToDatabase(DatabaseProductModel model)
        {
            List<DatabaseProductModel> products = _model.Products.Where(p => p.Id == model.Id).ToList();
            if (products.Count != 0)
            {
                DatabaseProductModel existingProduct = products[0];
                if (existingProduct.Expire == 0)
                {
                    return;
                }

                DateTime existingProductExpire = DateTime.FromBinary(existingProduct.Expire);
                DateTime newProductExpire = DateTime.FromBinary(model.Expire);
                if (existingProductExpire > newProductExpire)
                {
                    return;
                }
            }

            _model.Products.Add(model);
            WriteDatabase();

            Common.Delegate.Call<int>(ProductAdded, model.Id);
        }

        private bool ValidateProduct(DatabaseProductModel model)
        {
            if (model.Expire != 0)
            {
                DateTime productExpire = DateTime.FromBinary(model.Expire);
                if (productExpire < DateTime.UtcNow)
                {
                    _model.Products.Remove(model);
                    WriteDatabase();
                    Common.Delegate.Call(ProductExpired, model.Id);
                    return false;
                }
            }

            return true;
        }

        private async void ReadDatabase()
        {
            _locker.Reset();
            await Task.Factory.StartNew(async () =>
                {
                    try
                    {
                        string text = await _fileAccessor.ReadFile(DatabaseFileUri);
                        if (string.IsNullOrEmpty(text))
                        {
                            CreateModel();
                            return;
                        }

                        text = ProductsDatabaseEncrypter.Decrypt(text);

                        XmlSerializer serializer = new XmlSerializer(typeof(ProductsDatabaseModel));
                        using (TextReader reader = new StringReader(text))
                        {
                            _model = (ProductsDatabaseModel)serializer.Deserialize(reader);
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message);
                        CreateModel();
                    }
                    finally
                    {
                        _locker.Set();
                    }
                });
        }
        private async void WriteDatabase()
        {
            _locker.Reset();
            await Task.Factory.StartNew(async () =>
                {
                    _model.Version = DatabaseVersion;

                    XmlSerializer serializer = new XmlSerializer(typeof(ProductsDatabaseModel));
                    StringBuilder builder = new StringBuilder();
                    using (TextWriter writer = new StringWriter(builder))
                    {
                        serializer.Serialize(writer, _model);
                    }

                    string encodedText = ProductsDatabaseEncrypter.Encrypt(builder.ToString());
                    await _fileAccessor.WriteFile(DatabaseFileUri, encodedText);

                    _locker.Set();
                });
        }

        private void CreateModel()
        {
            _model = new ProductsDatabaseModel();
            _model.Products = new List<DatabaseProductModel>();
            _model.Version = DatabaseVersion;
        }

        private ProductsDatabaseModel _model;
        private readonly Common.IFileAccessor _fileAccessor;
        private readonly ManualResetEvent _locker = new ManualResetEvent(true);

        private const int DatabaseVersion = 2;
        private readonly Uri DatabaseFileUri = new Uri("products_data.bin", UriKind.Relative);
    }
}


text:
using namespace std::chrono_literals;

using std::chrono::milliseconds;
using testing::AssertionFailure;
using testing::AssertionResult;
using testing::AssertionSuccess;

namespace Envoy {
FakeStream::FakeStream(FakeHttpConnection& parent, Http::StreamEncoder& encoder,
                       Event::TestTimeSystem& time_system)
    : parent_(parent), encoder_(encoder), time_system_(time_system) {
  encoder.getStream().addCallbacks(*this);
}

void FakeStream::decodeHeaders(Http::HeaderMapPtr&& headers, bool end_stream) {
  Thread::LockGuard lock(lock_);
  headers_ = std::move(headers);
  setEndStream(end_stream);
  decoder_event_.notifyOne();
}

void FakeStream::decodeData(Buffer::Instance& data, bool end_stream) {
  received_data_ = true;
  Thread::LockGuard lock(lock_);
  body_.add(data);
  setEndStream(end_stream);
  decoder_event_.notifyOne();
}

void FakeStream::decodeTrailers(Http::HeaderMapPtr&& trailers) {
  Thread::LockGuard lock(lock_);
  setEndStream(true);
  trailers_ = std::move(trailers);
  decoder_event_.notifyOne();
}

void FakeStream::decodeMetadata(Http::MetadataMapPtr&& metadata_map_ptr) {
  for (const auto& metadata : *metadata_map_ptr) {
    duplicated_metadata_key_count_[metadata.first]++;
    metadata_map_.insert(metadata);
  }
}

void FakeStream::encode100ContinueHeaders(const Http::HeaderMapImpl& headers) {
  std::shared_ptr<Http::HeaderMapImpl> headers_copy(
      new Http::HeaderMapImpl(static_cast<const Http::HeaderMap&>(headers)));
  parent_.connection().dispatcher().post(
      [this, headers_copy]() -> void { encoder_.encode100ContinueHeaders(*headers_copy); });
}

void FakeStream::encodeHeaders(const Http::HeaderMapImpl& headers, bool end_stream) {
  std::shared_ptr<Http::HeaderMapImpl> headers_copy(
      new Http::HeaderMapImpl(static_cast<const Http::HeaderMap&>(headers)));
  if (add_served_by_header_) {
    headers_copy->addCopy(Http::LowerCaseString("x-served-by"),
                          parent_.connection().localAddress()->asString());
  }
  parent_.connection().dispatcher().post([this, headers_copy, end_stream]() -> void {
    encoder_.encodeHeaders(*headers_copy, end_stream);
  });
}

void FakeStream::encodeData(absl::string_view data, bool end_stream) {
  parent_.connection().dispatcher().post([this, data, end_stream]() -> void {
    Buffer::OwnedImpl fake_data(data.data(), data.size());
    encoder_.encodeData(fake_data, end_stream);
  });
}

void FakeStream::encodeData(uint64_t size, bool end_stream) {
  parent_.connection().dispatcher().post([this, size, end_stream]() -> void {
    Buffer::OwnedImpl data(std::string(size, 'a'));
    encoder_.encodeData(data, end_stream);
  });
}

void FakeStream::encodeData(Buffer::Instance& data, bool end_stream) {
  std::shared_ptr<Buffer::Instance> data_copy(new Buffer::OwnedImpl(data));
  parent_.connection().dispatcher().post(
      [this, data_copy, end_stream]() -> void { encoder_.encodeData(*data_copy, end_stream); });
}

void FakeStream::encodeTrailers(const Http::HeaderMapImpl& trailers) {
  std::shared_ptr<Http::HeaderMapImpl> trailers_copy(
      new Http::HeaderMapImpl(static_cast<const Http::HeaderMap&>(trailers)));
  parent_.connection().dispatcher().post(
      [this, trailers_copy]() -> void { encoder_.encodeTrailers(*trailers_copy); });
}

void FakeStream::encodeResetStream() {
  parent_.connection().dispatcher().post(
      [this]() -> void { encoder_.getStream().resetStream(Http::StreamResetReason::LocalReset); });
}

void FakeStream::encodeMetadata(const Http::MetadataMapVector& metadata_map_vector) {
  parent_.connection().dispatcher().post(
      [this, &metadata_map_vector]() -> void { encoder_.encodeMetadata(metadata_map_vector); });
}

void FakeStream::onResetStream(Http::StreamResetReason, absl::string_view) {
  Thread::LockGuard lock(lock_);
  saw_reset_ = true;
  decoder_event_.notifyOne();
}

AssertionResult FakeStream::waitForHeadersComplete(milliseconds timeout) {
  Thread::LockGuard lock(lock_);
  auto end_time = time_system_.monotonicTime() + timeout;
  while (!headers_) {
    if (time_system_.monotonicTime() >= end_time) {
      return AssertionFailure() << "Timed out waiting for headers.";
    }
    time_system_.waitFor(lock_, decoder_event_, 5ms);
  }
  return AssertionSuccess();
}

AssertionResult FakeStream::waitForData(Event::Dispatcher& client_dispatcher, uint64_t body_length,
                                        milliseconds timeout) {
  Thread::LockGuard lock(lock_);
  auto start_time = time_system_.monotonicTime();
  while (bodyLength() < body_length) {
    if (time_system_.monotonicTime() >= start_time + timeout) {
      return AssertionFailure() << "Timed out waiting for data.";
    }
    time_system_.waitFor(lock_, decoder_event_, 5ms);
    if (bodyLength() < body_length) {
      // Run the client dispatcher since we may need to process window updates, etc.
      client_dispatcher.run(Event::Dispatcher::RunType::NonBlock);
    }
  }
  return AssertionSuccess();
}

AssertionResult FakeStream::waitForData(Event::Dispatcher& client_dispatcher,
                                        absl::string_view data, milliseconds timeout) {
  auto succeeded = waitForData(client_dispatcher, data.length(), timeout);
  if (succeeded) {
    Buffer::OwnedImpl buffer(data.data(), data.length());
    if (!TestUtility::buffersEqual(body(), buffer)) {
      return AssertionFailure() << body().toString() << " not equal to " << data;
    }
  }
  return succeeded;
}

AssertionResult FakeStream::waitForEndStream(Event::Dispatcher& client_dispatcher,
                                             milliseconds timeout) {
  Thread::LockGuard lock(lock_);
  auto start_time = time_system_.monotonicTime();
  while (!end_stream_) {
    if (time_system_.monotonicTime() >= start_time + timeout) {
      return AssertionFailure() << "Timed out waiting for end of stream.";
    }
    time_system_.waitFor(lock_, decoder_event_, 5ms);
    if (!end_stream_) {
      // Run the client dispatcher since we may need to process window updates, etc.
      client_dispatcher.run(Event::Dispatcher::RunType::NonBlock);
    }
  }
  return AssertionSuccess();
}

AssertionResult FakeStream::waitForReset(milliseconds timeout) {
  Thread::LockGuard lock(lock_);
  auto start_time = time_system_.monotonicTime();
  while (!saw_reset_) {
    if (time_system_.monotonicTime() >= start_time + timeout) {
      return AssertionFailure() << "Timed out waiting for reset.";
    }
    // Safe since CondVar::waitFor won't throw.
    time_system_.waitFor(lock_, decoder_event_, 5ms);
  }
  return AssertionSuccess();
}

void FakeStream::startGrpcStream() {
  encodeHeaders(Http::TestHeaderMapImpl{{":status", "200"}}, false);
}

void FakeStream::finishGrpcStream(Grpc::Status::GrpcStatus status) {
  encodeTrailers(
      Http::TestHeaderMapImpl{{"grpc-status", std::to_string(static_cast<uint32_t>(status))}});
}

FakeHttpConnection::FakeHttpConnection(SharedConnectionWrapper& shared_connection,
                                       Stats::Store& store, Type type,
                                       Event::TestTimeSystem& time_system,
                                       uint32_t max_request_headers_kb,
                                       uint32_t max_request_headers_count)
    : FakeConnectionBase(shared_connection, time_system) {
  if (type == Type::HTTP1) {
    Http::Http1Settings http1_settings;
    // For the purpose of testing, we always have the upstream encode the trailers if any
    http1_settings.enable_trailers_ = true;
    codec_ = std::make_unique<Http::Http1::ServerConnectionImpl>(
        shared_connection_.connection(), store, *this, http1_settings, max_request_headers_kb,
        max_request_headers_count);
  } else {
    auto settings = Http::Http2Settings();
    settings.allow_connect_ = true;
    settings.allow_metadata_ = true;
    codec_ = std::make_unique<Http::Http2::ServerConnectionImpl>(
        shared_connection_.connection(), *this, store, settings, max_request_headers_kb,
        max_request_headers_count);
    ASSERT(type == Type::HTTP2);
  }

  shared_connection_.connection().addReadFilter(
      Network::ReadFilterSharedPtr{new ReadFilter(*this)});
}

AssertionResult FakeConnectionBase::close(std::chrono::milliseconds timeout) {
  return shared_connection_.executeOnDispatcher(
      [](Network::Connection& connection) {
        connection.close(Network::ConnectionCloseType::FlushWrite);
      },
      timeout);
}

AssertionResult FakeConnectionBase::readDisable(bool disable, std::chrono::milliseconds timeout) {
  return shared_connection_.executeOnDispatcher(
      [disable](Network::Connection& connection) { connection.readDisable(disable); }, timeout);
}

AssertionResult FakeConnectionBase::enableHalfClose(bool enable,
                                                    std::chrono::milliseconds timeout) {
  return shared_connection_.executeOnDispatcher(
      [enable](Network::Connection& connection) { connection.enableHalfClose(enable); }, timeout);
}

Http::StreamDecoder& FakeHttpConnection::newStream(Http::StreamEncoder& encoder, bool) {
  Thread::LockGuard lock(lock_);
  new_streams_.emplace_back(new FakeStream(*this, encoder, time_system_));
  connection_event_.notifyOne();
  return *new_streams_.back();
}

AssertionResult FakeConnectionBase::waitForDisconnect(bool ignore_spurious_events,
                                                      milliseconds timeout) {
  ENVOY_LOG(trace, "FakeConnectionBase waiting for disconnect");
  auto end_time = time_system_.monotonicTime() + timeout;
  Thread::LockGuard lock(lock_);
  while (shared_connection_.connected()) {
    if (time_system_.monotonicTime() >= end_time) {
      return AssertionFailure() << "Timed out waiting for disconnect.";
    }
    Thread::CondVar::WaitStatus status = time_system_.waitFor(lock_, connection_event_, 5ms);
    // The default behavior of waitForDisconnect is to assume the test cleanly
    // calls waitForData, waitForNewStream, etc. to handle all events on the
    // connection. If the caller explicitly notes that other events should be
    // ignored, continue looping until a disconnect is detected. Otherwise fall
    // through and hit the assert below.
    if ((status == Thread::CondVar::WaitStatus::NoTimeout) && !ignore_spurious_events) {
      break;
    }
  }

  if (shared_connection_.connected()) {
    return AssertionFailure() << "Expected disconnect, but got a different event.";
  }
  ENVOY_LOG(trace, "FakeConnectionBase done waiting for disconnect");
  return AssertionSuccess();
}

AssertionResult FakeConnectionBase::waitForHalfClose(bool ignore_spurious_events,
                                                     milliseconds timeout) {
  auto end_time = time_system_.monotonicTime() + timeout;
  Thread::LockGuard lock(lock_);
  while (!half_closed_) {
    if (time_system_.monotonicTime() >= end_time) {
      return AssertionFailure() << "Timed out waiting for half close.";
    }
    Thread::CondVar::WaitStatus status = time_system_.waitFor(lock_, connection_event_, 5ms);
    // The default behavior of waitForHalfClose is to assume the test cleanly
    // calls waitForData, waitForNewStream, etc. to handle all events on the
    // connection. If the caller explicitly notes that other events should be
    // ignored, continue looping until a disconnect is detected. Otherwise fall
    // through and hit the assert below.
    if (status == Thread::CondVar::WaitStatus::NoTimeout && !ignore_spurious_events) {
      break;
    }
  }

  return half_closed_
             ? AssertionSuccess()
             : (AssertionFailure() << "Expected half close event, but got a different event.");
}

AssertionResult FakeHttpConnection::waitForNewStream(Event::Dispatcher& client_dispatcher,
                                                     FakeStreamPtr& stream,
                                                     bool ignore_spurious_events,
                                                     milliseconds timeout) {
  auto end_time = time_system_.monotonicTime() + timeout;
  Thread::LockGuard lock(lock_);
  while (new_streams_.empty()) {
    if (time_system_.monotonicTime() >= end_time) {
      return AssertionFailure() << "Timed out waiting for new stream.";
    }
    Thread::CondVar::WaitStatus status = time_system_.waitFor(lock_, connection_event_, 5ms);
    // As with waitForDisconnect, by default, waitForNewStream returns after the next event.
    // If the caller explicitly notes other events should be ignored, it will instead actually
    // wait for the next new stream, ignoring other events such as onData()
    if (status == Thread::CondVar::WaitStatus::NoTimeout && !ignore_spurious_events) {
      break;
    }
    if (new_streams_.empty()) {
      // Run the client dispatcher since we may need to process window updates, etc.
      client_dispatcher.run(Event::Dispatcher::RunType::NonBlock);
    }
  }

  if (new_streams_.empty()) {
    return AssertionFailure() << "Expected new stream event, but got a different event.";
  }
  stream = std::move(new_streams_.front());
  new_streams_.pop_front();
  return AssertionSuccess();
}

FakeUpstream::FakeUpstream(const std::string& uds_path, FakeHttpConnection::Type type,
                           Event::TestTimeSystem& time_system)
    : FakeUpstream(Network::Test::createRawBufferSocketFactory(),
                   Network::SocketPtr{new Network::UdsListenSocket(
                       std::make_shared<Network::Address::PipeInstance>(uds_path))},
                   type, time_system, false) {
  ENVOY_LOG(info, "starting fake server on unix domain socket {}", uds_path);
}

static Network::SocketPtr
makeTcpListenSocket(const Network::Address::InstanceConstSharedPtr& address) {
  return std::make_unique<Network::TcpListenSocket>(address, nullptr, true);
}

static Network::SocketPtr makeTcpListenSocket(uint32_t port, Network::Address::IpVersion version) {
  return makeTcpListenSocket(
      Network::Utility::parseInternetAddress(Network::Test::getAnyAddressString(version), port));
}

static Network::SocketPtr
makeUdpListenSocket(const Network::Address::InstanceConstSharedPtr& address) {
  auto socket = std::make_unique<Network::UdpListenSocket>(address, nullptr, true);
  // TODO(mattklein123): These options are set in multiple locations. We should centralize them for
  // UDP listeners.
  socket->addOptions(Network::SocketOptionFactory::buildIpPacketInfoOptions());
  socket->addOptions(Network::SocketOptionFactory::buildRxQueueOverFlowOptions());
  return socket;
}

FakeUpstream::FakeUpstream(const Network::Address::InstanceConstSharedPtr& address,
                           FakeHttpConnection::Type type, Event::TestTimeSystem& time_system,
                           bool enable_half_close, bool udp_fake_upstream)
    : FakeUpstream(Network::Test::createRawBufferSocketFactory(),
                   udp_fake_upstream ? makeUdpListenSocket(address) : makeTcpListenSocket(address),
                   type, time_system, enable_half_close) {
  ENVOY_LOG(info, "starting fake server on socket {}:{}. Address version is {}. UDP={}",
            address->ip()->addressAsString(), address->ip()->port(),
            Network::Test::addressVersionAsString(address->ip()->version()), udp_fake_upstream);
}

FakeUpstream::FakeUpstream(uint32_t port, FakeHttpConnection::Type type,
                           Network::Address::IpVersion version, Event::TestTimeSystem& time_system,
                           bool enable_half_close)
    : FakeUpstream(Network::Test::createRawBufferSocketFactory(),
                   makeTcpListenSocket(port, version), type, time_system, enable_half_close) {
  ENVOY_LOG(info, "starting fake server on port {}. Address version is {}",
            localAddress()->ip()->port(), Network::Test::addressVersionAsString(version));
}

FakeUpstream::FakeUpstream(Network::TransportSocketFactoryPtr&& transport_socket_factory,
                           uint32_t port, FakeHttpConnection::Type type,
                           Network::Address::IpVersion version, Event::TestTimeSystem& time_system)
    : FakeUpstream(std::move(transport_socket_factory), makeTcpListenSocket(port, version), type,
                   time_system, false) {
  ENVOY_LOG(info, "starting fake SSL server on port {}. Address version is {}",
            localAddress()->ip()->port(), Network::Test::addressVersionAsString(version));
}

FakeUpstream::FakeUpstream(Network::TransportSocketFactoryPtr&& transport_socket_factory,
                           Network::SocketPtr&& listen_socket, FakeHttpConnection::Type type,
                           Event::TestTimeSystem& time_system, bool enable_half_close)
    : http_type_(type), socket_(Network::SocketSharedPtr(listen_socket.release())),
      socket_factory_(std::make_shared<FakeListenSocketFactory>(socket_)),
      api_(Api::createApiForTest(stats_store_)), time_system_(time_system),
      dispatcher_(api_->allocateDispatcher()),
      handler_(new Server::ConnectionHandlerImpl(*dispatcher_, "fake_upstream")),
      allow_unexpected_disconnects_(false), read_disable_on_new_connection_(true),
      enable_half_close_(enable_half_close), listener_(*this),
      filter_chain_(Network::Test::createEmptyFilterChain(std::move(transport_socket_factory))) {
  thread_ = api_->threadFactory().createThread([this]() -> void { threadRoutine(); });
  server_initialized_.waitReady();
}

FakeUpstream::~FakeUpstream() { cleanUp(); };

void FakeUpstream::cleanUp() {
  if (thread_.get()) {
    dispatcher_->exit();
    thread_->join();
    thread_.reset();
  }
}

bool FakeUpstream::createNetworkFilterChain(Network::Connection& connection,
                                            const std::vector<Network::FilterFactoryCb>&) {
  Thread::LockGuard lock(lock_);
  if (read_disable_on_new_connection_) {
    connection.readDisable(true);
  }
  auto connection_wrapper =
      std::make_unique<QueuedConnectionWrapper>(connection, allow_unexpected_disconnects_);
  connection_wrapper->moveIntoListBack(std::move(connection_wrapper), new_connections_);
  upstream_event_.notifyOne();
  return true;
}

bool FakeUpstream::createListenerFilterChain(Network::ListenerFilterManager&) { return true; }

void FakeUpstream::createUdpListenerFilterChain(Network::UdpListenerFilterManager& udp_listener,
                                                Network::UdpReadFilterCallbacks& callbacks) {
  udp_listener.addReadFilter(std::make_unique<FakeUpstreamUdpFilter>(*this, callbacks));
}

void FakeUpstream::threadRoutine() {
  handler_->addListener(listener_);
  server_initialized_.setReady();
  dispatcher_->run(Event::Dispatcher::RunType::Block);
  handler_.reset();
  {
    Thread::LockGuard lock(lock_);
    new_connections_.clear();
    consumed_connections_.clear();
  }
}

AssertionResult FakeUpstream::waitForHttpConnection(Event::Dispatcher& client_dispatcher,
                                                    FakeHttpConnectionPtr& connection,
                                                    milliseconds timeout,
                                                    uint32_t max_request_headers_kb,
                                                    uint32_t max_request_headers_count) {
  Event::TestTimeSystem& time_system = timeSystem();
  auto end_time = time_system.monotonicTime() + timeout;
  {
    Thread::LockGuard lock(lock_);
    while (new_connections_.empty()) {
      if (time_system.monotonicTime() >= end_time) {
        return AssertionFailure() << "Timed out waiting for new connection.";
      }
      time_system_.waitFor(lock_, upstream_event_, 5ms);
      if (new_connections_.empty()) {
        // Run the client dispatcher since we may need to process window updates, etc.
        client_dispatcher.run(Event::Dispatcher::RunType::NonBlock);
      }
    }

    if (new_connections_.empty()) {
      return AssertionFailure() << "Got a new connection event, but didn't create a connection.";
    }
    connection = std::make_unique<FakeHttpConnection>(consumeConnection(), stats_store_, http_type_,
                                                      time_system, max_request_headers_kb,
                                                      max_request_headers_count);
  }
  VERIFY_ASSERTION(connection->initialize());
  VERIFY_ASSERTION(connection->readDisable(false));
  return AssertionSuccess();
}

AssertionResult
FakeUpstream::waitForHttpConnection(Event::Dispatcher& client_dispatcher,
                                    std::vector<std::unique_ptr<FakeUpstream>>& upstreams,
                                    FakeHttpConnectionPtr& connection, milliseconds timeout) {
  if (upstreams.empty()) {
    return AssertionFailure() << "No upstreams configured.";
  }
  Event::TestTimeSystem& time_system = upstreams[0]->timeSystem();
  auto end_time = time_system.monotonicTime() + timeout;
  while (time_system.monotonicTime() < end_time) {
    for (auto& it : upstreams) {
      FakeUpstream& upstream = *it;
      Thread::ReleasableLockGuard lock(upstream.lock_);
      if (upstream.new_connections_.empty()) {
        time_system.waitFor(upstream.lock_, upstream.upstream_event_, 5ms);
      }

      if (upstream.new_connections_.empty()) {
        // Run the client dispatcher since we may need to process window updates, etc.
        client_dispatcher.run(Event::Dispatcher::RunType::NonBlock);
      } else {
        connection = std::make_unique<FakeHttpConnection>(
            upstream.consumeConnection(), upstream.stats_store_, upstream.http_type_,
            upstream.timeSystem(), Http::DEFAULT_MAX_REQUEST_HEADERS_KB,
            Http::DEFAULT_MAX_HEADERS_COUNT);
        lock.release();
        VERIFY_ASSERTION(connection->initialize());
        VERIFY_ASSERTION(connection->readDisable(false));
        return AssertionSuccess();
      }
    }
  }
  return AssertionFailure() << "Timed out waiting for HTTP connection.";
}

AssertionResult FakeUpstream::waitForRawConnection(FakeRawConnectionPtr& connection,
                                                   milliseconds timeout) {
  {
    Thread::LockGuard lock(lock_);
    if (new_connections_.empty()) {
      ENVOY_LOG(debug, "waiting for raw connection");
      time_system_.waitFor(lock_, upstream_event_,
                           timeout); // Safe since CondVar::waitFor won't throw.
    }

    if (new_connections_.empty()) {
      return AssertionFailure() << "Timed out waiting for raw connection";
    }
    connection = std::make_unique<FakeRawConnection>(consumeConnection(), timeSystem());
  }
  VERIFY_ASSERTION(connection->initialize());
  VERIFY_ASSERTION(connection->readDisable(false));
  VERIFY_ASSERTION(connection->enableHalfClose(enable_half_close_));
  return AssertionSuccess();
}

SharedConnectionWrapper& FakeUpstream::consumeConnection() {
  ASSERT(!new_connections_.empty());
  auto* const connection_wrapper = new_connections_.front().get();
  connection_wrapper->set_parented();
  connection_wrapper->moveBetweenLists(new_connections_, consumed_connections_);
  return connection_wrapper->shared_connection();
}

testing::AssertionResult FakeUpstream::waitForUdpDatagram(Network::UdpRecvData& data_to_fill,
                                                          std::chrono::milliseconds timeout) {
  Thread::LockGuard lock(lock_);
  auto end_time = time_system_.monotonicTime() + timeout;
  while (received_datagrams_.empty()) {
    if (time_system_.monotonicTime() >= end_time) {
      return AssertionFailure() << "Timed out waiting for UDP datagram.";
    }
    time_system_.waitFor(lock_, upstream_event_, 5ms); // Safe since CondVar::waitFor won't throw.
  }
  data_to_fill = std::move(received_datagrams_.front());
  received_datagrams_.pop_front();
  return AssertionSuccess();
}

void FakeUpstream::onRecvDatagram(Network::UdpRecvData& data) {
  Thread::LockGuard lock(lock_);
  received_datagrams_.emplace_back(std::move(data));
  upstream_event_.notifyOne();
}

void FakeUpstream::sendUdpDatagram(const std::string& buffer,
                                   const Network::Address::InstanceConstSharedPtr& peer) {
  dispatcher_->post([this, buffer, peer] {
    const auto rc = Network::Utility::writeToSocket(socket_->ioHandle(), Buffer::OwnedImpl(buffer),
                                                    nullptr, *peer);
    EXPECT_TRUE(rc.rc_ == buffer.length());
  });
}

AssertionResult FakeRawConnection::waitForData(uint64_t num_bytes, std::string* data,
                                               milliseconds timeout) {
  Thread::LockGuard lock(lock_);
  ENVOY_LOG(debug, "waiting for {} bytes of data", num_bytes);
  auto end_time = time_system_.monotonicTime() + timeout;
  while (data_.size() != num_bytes) {
    if (time_system_.monotonicTime() >= end_time) {
      return AssertionFailure() << "Timed out waiting for data.";
    }
    time_system_.waitFor(lock_, connection_event_, 5ms); // Safe since CondVar::waitFor won't throw.
  }
  if (data != nullptr) {
    *data = data_;
  }
  return AssertionSuccess();
}

AssertionResult
FakeRawConnection::waitForData(const std::function<bool(const std::string&)>& data_validator,
                               std::string* data, milliseconds timeout) {
  Thread::LockGuard lock(lock_);
  ENVOY_LOG(debug, "waiting for data");
  auto end_time = time_system_.monotonicTime() + timeout;
  while (!data_validator(data_)) {
    if (time_system_.monotonicTime() >= end_time) {
      return AssertionFailure() << "Timed out waiting for data.";
    }
    time_system_.waitFor(lock_, connection_event_, 5ms); // Safe since CondVar::waitFor won't throw.
  }
  if (data != nullptr) {
    *data = data_;
  }
  return AssertionSuccess();
}

AssertionResult FakeRawConnection::write(const std::string& data, bool end_stream,
                                         milliseconds timeout) {
  return shared_connection_.executeOnDispatcher(
      [&data, end_stream](Network::Connection& connection) {
        Buffer::OwnedImpl to_write(data);
        connection.write(to_write, end_stream);
      },
      timeout);
}

Network::FilterStatus FakeRawConnection::ReadFilter::onData(Buffer::Instance& data,
                                                            bool end_stream) {
  Thread::LockGuard lock(parent_.lock_);
  ENVOY_LOG(debug, "got {} bytes, end_stream {}", data.length(), end_stream);
  parent_.data_.append(data.toString());
  parent_.half_closed_ = end_stream;
  data.drain(data.length());
  parent_.connection_event_.notifyOne();
  return Network::FilterStatus::StopIteration;
}
} // namespace Envoy


text:
import { Input, Output, Component, EventEmitter} from '@angular/core';

/* Lazy loaded*/

@Component ({
  moduleId: module.id,
  selector: 'citythumb',
  templateUrl: 'citythumb.component.html',
  styleUrls: ['citythumb.component.css'],

})

export class CityThumbComponent {
    citynames: any[];
    @Input() thumb: any;
    @Output() getCity: EventEmitter<any> = new EventEmitter();

    constructor() {
      this.citynames = [
        {id: 1, name: 'Allahabad'},
        {id: 2, name: 'Bhagalpur'},
        {id: 3, name: 'Chennai'},
        {id: 4, name: 'Deherahun'},
        {id: 5, name: 'Eernakulam'},
        {id: 6, name: 'Firozabad'}
      ];
    }

    cityClicked(cityname) {
      this.getCity.emit(cityname);
    }

  }


text:
define([
    'asset/js/accounting'
], function(){
    return alt.component({
        name: 'altNumber',
        templateUrl: 'component/alt/number/view.html',
        scope: {
            number: '=?altNumber',
            setting: '=?'
        },
        isskip: true,
        link: ['$scope', '$log', '$element', '$alert', '$validate', function($scope, $log, $element, $alert, $validate){
            $scope.number = $scope.number || '';

            $scope.setting      = alt.extend({
                number: 0,
                type: 'text',
                class: 'form-control',
                style: {'text-align': 'right'},
                show: true,
                prepend: {
                    show: false,
                    title: 'Rp'
                },
                append: {
                    show: false,
                    title: {
                        normal : '',
                        power : ''
                    }
                },
                required: false,
                disabled: false,
                decimals: 2,
                allowempty: false,
                allownegative: false,
                thousandSeparator: ".",
                decimalSeparator: ",",
                onchange: angular.noop
            }, $scope.setting);

            $scope.$watch('number', function(newvalue, oldvalue){
                var tmp     = (newvalue + '').split('.'),
                    decimals= $scope.setting.decimals > 0 ? (tmp.length > 1 ? (tmp[1].length > 0 ? (tmp[1].length > $scope.setting.decimals ? $scope.setting.decimals : tmp[1].length) : 1) : 0) : $scope.setting.decimals;
                if ($scope.setting.allowempty && $scope.number == ''){
                    $scope.setting.number = '';
                }else {
                    $scope.setting.number = accounting.formatNumber(newvalue, decimals, $scope.setting.thousandSeparator, $scope.setting.decimalSeparator);
                }
            });

            $scope.$watch('setting.number', function(newvalue, oldvalue){
                var regex = $scope.setting.allownegative ? /[^\-0-9\.\,]+/g : /[^0-9\.\,]+/g;
                $scope.setting.number = ($scope.setting.number + '').replace(regex, '');
                if ($scope.setting.allowempty && $scope.setting.number == ''){
                    $scope.number = '';
                }else {
                    $scope.number = accounting.unformat($scope.setting.number || 0, $scope.setting.decimalSeparator);
                }
            });
        }]
    });
});


text:
package org.jnosql.artemis.column;

import org.jnosql.artemis.CDIExtension;
import org.jnosql.artemis.Converters;
import org.jnosql.artemis.PreparedStatementAsync;
import org.jnosql.artemis.model.Movie;
import org.jnosql.artemis.model.Person;
import org.jnosql.artemis.reflection.ClassMappings;
import org.jnosql.diana.api.NonUniqueResultException;
import org.jnosql.diana.api.column.Column;
import org.jnosql.diana.api.column.ColumnCondition;
import org.jnosql.diana.api.column.ColumnDeleteQuery;
import org.jnosql.diana.api.column.ColumnEntity;
import org.jnosql.diana.api.column.ColumnFamilyManagerAsync;
import org.jnosql.diana.api.column.ColumnQuery;
import org.jnosql.diana.api.column.query.ColumnQueryBuilder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;

import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import java.time.Duration;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.awaitility.Awaitility.await;
import static org.jnosql.diana.api.column.query.ColumnQueryBuilder.delete;
import static org.jnosql.diana.api.column.query.ColumnQueryBuilder.select;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.verify;

@ExtendWith(CDIExtension.class)
public class DefaultColumnTemplateAsyncTest {

    private Person person = Person.builder().
            withAge().
            withPhones(asList("234", "432")).
            withName("Name")
            .withId(19)
            .withIgnore().build();

    private Column[] columns = new Column[]{
            Column.of("age", 10),
            Column.of("phones", asList("234", "432")),
            Column.of("name", "Name"),
            Column.of("id", 19L),
    };

    @Inject
    private ColumnEntityConverter converter;

    @Inject
    private ClassMappings classMappings;

    @Inject
    private Converters converters;

    private ColumnFamilyManagerAsync managerMock;

    private DefaultColumnTemplateAsync subject;

    private ArgumentCaptor<ColumnEntity> captor;

    @SuppressWarnings("unchecked")
    @BeforeEach
    public void setUp() {
        managerMock = Mockito.mock(ColumnFamilyManagerAsync.class);
        ColumnEventPersistManager columnEventPersistManager = Mockito.mock(ColumnEventPersistManager.class);
        captor = ArgumentCaptor.forClass(ColumnEntity.class);
        Instance<ColumnFamilyManagerAsync> instance = Mockito.mock(Instance.class);
        Mockito.when(instance.get()).thenReturn(managerMock);
        this.subject = new DefaultColumnTemplateAsync(converter, instance, classMappings, converters);
    }

    @Test
    public void shouldCheckNullParameterInInsert() {

        assertThrows(NullPointerException.class, () -> subject.insert(null));
        assertThrows(NullPointerException.class, () -> subject.insert(null));
        assertThrows(NullPointerException.class, () -> subject.insert(this.person, (Duration) null));
        assertThrows(NullPointerException.class, () -> subject.insert(null, Duration.ofSeconds(1L)));
        assertThrows(NullPointerException.class, () -> subject.insert(this.person, (Consumer<Person>) null));
        assertThrows(NullPointerException.class, () -> subject.insert(null, System.out::println));

    }

    @Test
    public void shouldInsert() {
        ColumnEntity entity = ColumnEntity.of("Person");
        entity.addAll(Stream.of(columns).collect(Collectors.toList()));

        subject.insert(this.person);
        verify(managerMock).insert(captor.capture(), Mockito.any(Consumer.class));
        ColumnEntity value = captor.getValue();
        assertEquals(entity.getName(), value.getName());
    }

    @Test
    public void shouldInsertTTL() {
        ColumnEntity entity = ColumnEntity.of("Person");
        entity.addAll(Stream.of(columns).collect(Collectors.toList()));

        subject.insert(this.person, Duration.ofSeconds(1L));
        verify(managerMock).insert(Mockito.any(ColumnEntity.class), Mockito.eq(Duration.ofSeconds(1L)), Mockito.any(Consumer.class));
    }

    @Test
    public void shouldInsertIterable() {
        ColumnEntity entity = ColumnEntity.of("Person");
        entity.addAll(Stream.of(columns).collect(Collectors.toList()));

        subject.insert(singletonList(this.person));
        verify(managerMock).insert(captor.capture(), Mockito.any(Consumer.class));
        ColumnEntity value = captor.getValue();
        assertEquals(entity.getName(), value.getName());
    }

    @Test
    public void shouldInsertIterableTTL() {
        ColumnEntity entity = ColumnEntity.of("Person");
        entity.addAll(Stream.of(columns).collect(Collectors.toList()));

        subject.insert(singletonList(this.person), Duration.ofSeconds(1L));
        verify(managerMock).insert(Mockito.any(ColumnEntity.class), Mockito.eq(Duration.ofSeconds(1L)), Mockito.any(Consumer.class));
    }

    @Test
    public void shouldCheckNullParameterInUpdate() {
        assertThrows(NullPointerException.class, () -> subject.update(null));
        assertThrows(NullPointerException.class, () -> subject.update((Iterable) null));
        assertThrows(NullPointerException.class, () -> subject.update(singletonList(person), null));
        assertThrows(NullPointerException.class, () -> subject.update((Iterable) null, System.out::println));
    }

    @Test
    public void shouldUpdate() {
        ColumnEntity entity = ColumnEntity.of("Person");
        entity.addAll(Stream.of(columns).collect(Collectors.toList()));

        subject.update(this.person);
        verify(managerMock).update(captor.capture(), Mockito.any(Consumer.class));
        ColumnEntity value = captor.getValue();
        assertEquals(entity.getName(), value.getName());
    }

    @Test
    public void shouldUpdateIterable() {
        ColumnEntity entity = ColumnEntity.of("Person");
        entity.addAll(Stream.of(columns).collect(Collectors.toList()));

        subject.update(singletonList(this.person));
        verify(managerMock).update(captor.capture(), Mockito.any(Consumer.class));
        ColumnEntity value = captor.getValue();
        assertEquals(entity.getName(), value.getName());
    }

    @Test
    public void shouldCheckNullParameterInDelete() {
        assertThrows(NullPointerException.class, () -> subject.delete(null));
        assertThrows(NullPointerException.class, () -> subject.delete(delete().from("delete").build(), null));
        assertThrows(NullPointerException.class, () -> subject.delete(Person.class, null));
        assertThrows(NullPointerException.class, () -> subject.delete((Class) null, 10L));
        assertThrows(NullPointerException.class, () -> subject.delete(Person.class, 10L, null));
    }

    @Test
    public void shouldDelete() {

        ColumnDeleteQuery query = delete().from("delete").build();
        subject.delete(query);
        verify(managerMock).delete(query);
    }

    @Test
    public void shouldDeleteCallBack() {

        ColumnDeleteQuery query = delete().from("delete").build();
        Consumer<Void> callback = v -> {

        };
        subject.delete(query, callback);
        verify(managerMock).delete(query, callback);
    }

    @Test
    public void shouldDeleteByEntity() {
        subject.delete(Person.class, 10L);

        ArgumentCaptor<ColumnDeleteQuery> queryCaptor = ArgumentCaptor.forClass(ColumnDeleteQuery.class);
        verify(managerMock).delete(queryCaptor.capture());

        ColumnDeleteQuery query = queryCaptor.getValue();
        assertEquals("Person", query.getColumnFamily());
        assertEquals(ColumnCondition.eq(Column.of("_id", 10L)), query.getCondition().get());

    }

    @Test
    public void shouldDeleteByEntityCallBack() {

        Consumer<Void> callback = v -> {
        };
        subject.delete(Person.class, 10L, callback);

        ArgumentCaptor<ColumnDeleteQuery> queryCaptor = ArgumentCaptor.forClass(ColumnDeleteQuery.class);
        verify(managerMock).delete(queryCaptor.capture(), Mockito.eq(callback));

        ColumnDeleteQuery query = queryCaptor.getValue();
        assertEquals("Person", query.getColumnFamily());
        assertEquals(ColumnCondition.eq(Column.of("_id", 10L)), query.getCondition().get());

    }

    @Test
    public void shouldCheckNullParameterInSelect() {
        assertThrows(NullPointerException.class, () -> subject.select(null, null));
        assertThrows(NullPointerException.class, () -> subject.select(null, System.out::println));
        assertThrows(NullPointerException.class, () -> subject.select(select().from("Person").build(),
                null));
    }

    @Test
    public void shouldSelect() {

        ArgumentCaptor<Consumer<List<ColumnEntity>>> dianaCallbackCaptor = ArgumentCaptor.forClass(Consumer.class);
        ColumnQuery query = ColumnQueryBuilder.select().from("Person").build();
        AtomicBoolean condition = new AtomicBoolean(false);
        Consumer<List<Person>> callback = l -> condition.set(true);
        subject.select(query, callback);
        verify(managerMock).select(Mockito.any(ColumnQuery.class), dianaCallbackCaptor.capture());
        Consumer<List<ColumnEntity>> dianaCallBack = dianaCallbackCaptor.getValue();
        dianaCallBack.accept(singletonList(ColumnEntity.of("Person", asList(columns))));
        verify(managerMock).select(Mockito.eq(query), Mockito.any());
        await().untilTrue(condition);
    }

    @Test
    public void shouldReturnSingleResult() {

        ArgumentCaptor<Consumer<List<ColumnEntity>>> dianaCallbackCaptor = ArgumentCaptor.forClass(Consumer.class);
        ColumnQuery query = ColumnQueryBuilder.select().from("Person").build();
        AtomicBoolean condition = new AtomicBoolean(false);
        AtomicReference<Person> atomicReference = new AtomicReference<>();
        Consumer<Optional<Person>> callback = p -> {
            condition.set(true);
            p.ifPresent(atomicReference::set);
        };
        subject.singleResult(query, callback);
        verify(managerMock).select(Mockito.any(ColumnQuery.class), dianaCallbackCaptor.capture());
        Consumer<List<ColumnEntity>> dianaCallBack = dianaCallbackCaptor.getValue();
        dianaCallBack.accept(singletonList(ColumnEntity.of("Person", asList(columns))));
        verify(managerMock).select(Mockito.eq(query), Mockito.any());
        await().untilTrue(condition);
        assertNotNull(atomicReference.get());
    }

    @Test
    public void shouldReturnEmptySingleResult() {

        ArgumentCaptor<Consumer<List<ColumnEntity>>> dianaCallbackCaptor = ArgumentCaptor.forClass(Consumer.class);
        ColumnQuery query = ColumnQueryBuilder.select().from("Person").build();
        AtomicBoolean condition = new AtomicBoolean(false);
        AtomicReference<Person> atomicReference = new AtomicReference<>();
        Consumer<Optional<Person>> callback = p -> {
            condition.set(true);
            p.ifPresent(atomicReference::set);
        };
        subject.singleResult(query, callback);
        verify(managerMock).select(Mockito.any(ColumnQuery.class), dianaCallbackCaptor.capture());
        Consumer<List<ColumnEntity>> dianaCallBack = dianaCallbackCaptor.getValue();
        dianaCallBack.accept(emptyList());
        verify(managerMock).select(Mockito.eq(query), Mockito.any());
        await().untilTrue(condition);
        assertNull(atomicReference.get());
    }

    @Test
    public void shouldReturnErrorWhenThereIsMoreThanOneResultInSingleResult() {

        assertThrows(NonUniqueResultException.class, () -> {
            ArgumentCaptor<Consumer<List<ColumnEntity>>> dianaCallbackCaptor = ArgumentCaptor.forClass(Consumer.class);
            ColumnQuery query = ColumnQueryBuilder.select().from("Person").build();
            Consumer<Optional<Person>> callback = l -> {
            };
            subject.singleResult(query, callback);
            verify(managerMock).select(Mockito.any(ColumnQuery.class), dianaCallbackCaptor.capture());
            Consumer<List<ColumnEntity>> dianaCallBack = dianaCallbackCaptor.getValue();
            dianaCallBack.accept(asList(ColumnEntity.of("Person", asList(columns)),
                    ColumnEntity.of("Person", asList(columns))));

        });
    }

    @Test
    public void shouldCheckNullParameterInFindById() {
        assertThrows(NullPointerException.class, () -> subject.find(null, null, null));
        assertThrows(NullPointerException.class, () -> subject.find(Person.class, null, null));
        assertThrows(NullPointerException.class, () -> subject.find(Person.class, 10L, null));
        assertThrows(NullPointerException.class, () -> subject.find(Person.class, null, System.out::println));
        assertThrows(NullPointerException.class, () -> subject.find(null, null, System.out::println));
        assertThrows(NullPointerException.class, () -> subject.find(null, 10L, System.out::println));
        assertThrows(NullPointerException.class, () -> subject.find(null, 10L, null));
    }

    @Test
    public void shouldFindById() {
        ArgumentCaptor<Consumer<List<ColumnEntity>>> dianaCallbackCaptor = ArgumentCaptor.forClass(Consumer.class);

        ArgumentCaptor<ColumnQuery> queryCaptor = ArgumentCaptor.forClass(ColumnQuery.class);
        AtomicBoolean condition = new AtomicBoolean(false);
        AtomicReference<Person> atomicReference = new AtomicReference<>();
        Consumer<Optional<Person>> callback = p -> {
            condition.set(true);
            p.ifPresent(atomicReference::set);
        };

        subject.find(Person.class, 10L, callback);
        verify(managerMock).select(queryCaptor.capture(), dianaCallbackCaptor.capture());
        Consumer<List<ColumnEntity>> dianaCallBack = dianaCallbackCaptor.getValue();
        dianaCallBack.accept(singletonList(ColumnEntity.of("Person", asList(columns))));
        ColumnQuery query = queryCaptor.getValue();
        assertEquals("Person", query.getColumnFamily());
        assertEquals(ColumnCondition.eq(Column.of("_id", 10L)), query.getCondition().get());
        assertNotNull(atomicReference.get());

    }

    @Test
    public void shouldFindByIdReturnEmptyWhenElementDoesNotFind() {
        ArgumentCaptor<Consumer<List<ColumnEntity>>> dianaCallbackCaptor = ArgumentCaptor.forClass(Consumer.class);

        ArgumentCaptor<ColumnQuery> queryCaptor = ArgumentCaptor.forClass(ColumnQuery.class);
        AtomicBoolean condition = new AtomicBoolean(false);
        AtomicReference<Person> atomicReference = new AtomicReference<>();
        Consumer<Optional<Person>> callback = p -> {
            condition.set(true);
            p.ifPresent(atomicReference::set);
        };

        subject.find(Person.class, 10L, callback);
        verify(managerMock).select(queryCaptor.capture(), dianaCallbackCaptor.capture());
        Consumer<List<ColumnEntity>> dianaCallBack = dianaCallbackCaptor.getValue();
        dianaCallBack.accept(emptyList());
        ColumnQuery query = queryCaptor.getValue();
        assertEquals("Person", query.getColumnFamily());
        assertEquals(ColumnCondition.eq(Column.of("_id", 10L)), query.getCondition().get());
        assertNull(atomicReference.get());

    }

    @Test
    public void shouldReturnErrorFindByIdReturnMoreThanOne() {

        assertThrows(NonUniqueResultException.class, () -> {
            ArgumentCaptor<Consumer<List<ColumnEntity>>> dianaCallbackCaptor = ArgumentCaptor.forClass(Consumer.class);

            ArgumentCaptor<ColumnQuery> queryCaptor = ArgumentCaptor.forClass(ColumnQuery.class);
            AtomicBoolean condition = new AtomicBoolean(false);
            AtomicReference<Person> atomicReference = new AtomicReference<>();
            Consumer<Optional<Person>> callback = p -> {
                condition.set(true);
                p.ifPresent(atomicReference::set);
            };

            subject.find(Person.class, 10L, callback);
            verify(managerMock).select(queryCaptor.capture(), dianaCallbackCaptor.capture());
            Consumer<List<ColumnEntity>> dianaCallBack = dianaCallbackCaptor.getValue();
            dianaCallBack.accept(asList(ColumnEntity.of("Person", asList(columns)), ColumnEntity.of("Person", asList(columns))));
        });

    }

    @Test
    public void shouldExecuteQuery() {
        Consumer<List<Person>> callback = l ->{};
        subject.query("select * from Person", callback);
        ArgumentCaptor<ColumnQuery> queryCaptor = ArgumentCaptor.forClass(ColumnQuery.class);
        verify(managerMock).select(queryCaptor.capture(), Mockito.any(Consumer.class));
        ColumnQuery query = queryCaptor.getValue();
        assertEquals("Person", query.getColumnFamily());
    }

    @Test
    public void shouldConvertEntity() {
        Consumer<List<Movie>> callback = l ->{};
        subject.query("select * from Movie", callback);
        ArgumentCaptor<ColumnQuery> queryCaptor = ArgumentCaptor.forClass(ColumnQuery.class);
        verify(managerMock).select(queryCaptor.capture(), Mockito.any(Consumer.class));
        ColumnQuery query = queryCaptor.getValue();
        assertEquals("movie", query.getColumnFamily());
    }

    @Test
    public void shouldPreparedStatement() {
        Consumer<List<Person>> callback = l ->{};
        PreparedStatementAsync preparedStatement = subject.prepare("select * from Person where name = @name");
        preparedStatement.bind("name", "Ada");
        preparedStatement.getResultList(callback);
        ArgumentCaptor<ColumnQuery> queryCaptor = ArgumentCaptor.forClass(ColumnQuery.class);
        verify(managerMock).select(queryCaptor.capture(), Mockito.any(Consumer.class));
        ColumnQuery query = queryCaptor.getValue();
        assertEquals("Person", query.getColumnFamily());
    }

    @Test
    public void shouldCount() {
        Consumer<Long> callback = l ->{};
        subject.count("Person", callback);
        verify(managerMock).count("Person", callback);
    }

    @Test
    public void shouldCountFromEntityClass() {
        Consumer<Long> callback = l ->{};
        subject.count(Person.class, callback);
        verify(managerMock).count("Person", callback);
    }
}


text:
package jp.android.a.akira.library.okwear;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.wearable.DataApi;
import com.google.android.gms.wearable.DataEventBuffer;
import com.google.android.gms.wearable.MessageApi;
import com.google.android.gms.wearable.MessageEvent;
import com.google.android.gms.wearable.Node;
import com.google.android.gms.wearable.NodeApi;
import com.google.android.gms.wearable.PutDataRequest;
import com.google.android.gms.wearable.Wearable;

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

import jp.android.a.akira.library.okwear.listener.NodeChangeListener;
import jp.android.a.akira.library.okwear.listener.SendResultListener;
import jp.android.a.akira.library.okwear.task.SendDataTask;
import jp.android.a.akira.library.okwear.task.SendMessageTask;

public class ConnectionHelper implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
        DataApi.DataListener, MessageApi.MessageListener, NodeApi.NodeListener {

    private static final String TAG = ConnectionHelper.class.getSimpleName();

    private static ConnectionHelper mConnectinoHelper;

    private GoogleApiClient mGoogleApiClient;
    private CallBackListener mListener;

    public static ConnectionHelper getInstance(final Context context) {
        if (mConnectinoHelper == null) {
            mConnectinoHelper = new ConnectionHelper(context);
        }
        return mConnectinoHelper;
    }

    private ConnectionHelper(final Context context) {
        mGoogleApiClient = buildGoogleApiClient(context);
    }

    public void setListener(final CallBackListener listener) {
        mListener = listener;
    }

    private GoogleApiClient buildGoogleApiClient(final Context context) {
        return new GoogleApiClient.Builder(context)
                .addConnectionCallbacks(this)
                .addApi(Wearable.API)
                .build();
    }

    protected GoogleApiClient getGoogleApiClient() {
        return mGoogleApiClient;
    }

    @Override
    public void onConnected(final Bundle bundle) {
        Log.d(TAG, "onConnected");
        Wearable.DataApi.addListener(mGoogleApiClient, this);
        Wearable.MessageApi.addListener(mGoogleApiClient, this);
        Wearable.NodeApi.addListener(mGoogleApiClient, this);
    }

    @Override
    public void onConnectionSuspended(final int i) {
        Log.d(TAG, "connection suspend");
    }

    @Override
    public void onConnectionFailed(final ConnectionResult connectionResult) {
        Log.d(TAG, "connection failed");
    }

    public void connect() {
        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }

    public void disconnect() {
        if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
            Wearable.DataApi.removeListener(mGoogleApiClient, this);
            Wearable.MessageApi.removeListener(mGoogleApiClient, this);
            Wearable.NodeApi.removeListener(mGoogleApiClient, this);
        }
    }

    @Override
    public void onMessageReceived(final MessageEvent messageEvent) {
        if (mListener != null) {
            mListener.onMessageReceived(messageEvent);
        }
    }

    @Override
    public void onDataChanged(final DataEventBuffer dataEventBuffer) {
        if (mListener != null) {
            mListener.onDataChanged(dataEventBuffer);
        }
    }

    @Override
    public void onPeerConnected(Node node) {
        Log.v(TAG, "peer connect" + node.getId());
    }

    @Override
    public void onPeerDisconnected(Node node) {
        Log.v(TAG, "peer disconnect" + node.getId());
    }

    public void getNodes(@NonNull final NodeChangeListener listener) {
        final List<Node> nodeList = new ArrayList<>();
        final PendingResult<NodeApi.GetConnectedNodesResult> nodes = Wearable.NodeApi.getConnectedNodes(mGoogleApiClient);
        nodes.setResultCallback(new ResultCallback<NodeApi.GetConnectedNodesResult>() {
            @Override
            public void onResult(NodeApi.GetConnectedNodesResult result) {
                for (Node node : result.getNodes()) {
                    nodeList.add(node);
                    listener.onReceiveNodes(nodeList);
                }
            }
        });
    }

    /**
     * send message
     * you don't have to send anything
     *
     * @param node     送信先node
     * @param payload
     * @param path
     * @param listener
     */
    public void sendMessage(@NonNull final Node node, @Nullable final byte[] payload,
                            @NonNull final String path, @Nullable final SendResultListener<MessageApi.SendMessageResult> listener) {
        final PendingResult<MessageApi.SendMessageResult> messageResult =
                Wearable.MessageApi.sendMessage(mGoogleApiClient, node.getId(), path, payload);
        messageResult.setResultCallback(new ResultCallback<MessageApi.SendMessageResult>() {
            @Override
            public void onResult(final MessageApi.SendMessageResult sendMessageResult) {
                Log.d(TAG, "Status: " + sendMessageResult.getStatus());
                if (listener != null) {
                    listener.onResult(sendMessageResult);
                }
            }
        });

    }

    /**
     * send message using AsyncTask
     * you don't have to send anything
     *
     * @param node
     * @param payload
     * @param path
     * @param listener
     */
    public void sendMessageAsync(@NonNull final Node node, @Nullable final byte[] payload,
                                 @NonNull final String path, @Nullable final SendResultListener<MessageApi.SendMessageResult> listener) {

        if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
            new SendMessageTask(mGoogleApiClient, node, payload, path, listener).execute();
        }
    }

    /**
     * you need to renew the data if it uses same key
     *
     * @param request
     * @param listener
     */
    public void syncData(@NonNull final PutDataRequest request, @Nullable final SendResultListener<DataApi.DataItemResult> listener) {
        final PendingResult<DataApi.DataItemResult> pendingResult = Wearable.DataApi.putDataItem(mGoogleApiClient, request);
        pendingResult.setResultCallback(new ResultCallback<DataApi.DataItemResult>() {
            @Override
            public void onResult(DataApi.DataItemResult dataItemResult) {
                if (listener != null) {
                    listener.onResult(dataItemResult);
                }
            }
        });
    }

    /**
     * you need to renew the data if it uses same key
     * using AsyncTask
     *
     * @param request
     * @param listener
     */
    public void syncDataAsync(@NonNull final PutDataRequest request, @Nullable final SendResultListener<DataApi.DataItemResult> listener) {
        if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
            new SendDataTask(mGoogleApiClient, request, listener).execute();
        }
    }

    public interface CallBackListener {

        public void onMessageReceived(final MessageEvent messageEvent);

        public void onDataChanged(final DataEventBuffer dataEventBuffer);
    }
}


text:
import vtk

def get_program_parameters():
    import argparse
    description = 'Read a polydata file of a surface and determine if it is a closed surface.'
    epilogue = '''
This example illustrates how to extract the cells that exist inside a closed surface.
It uses vtkSelectEnclosedPoints to mark points that are inside and outside the surface.
vtkMultiThreshold is used to extract the three meshes into three vtkMultiBlockDataSet's.
The cells completely outside are shown in crimson, completely inside are yellow and
 border cells are green.
A translucent copy of the closed surface helps illustrate the selection process.

If two polydata datasets are provided, the example uses the second as the closed surface.
If only one dataset is provided, the closed surface is generated by rotating the
 first dataset by 90 degrees around its Y axis.

   '''
    parser = argparse.ArgumentParser(description=description, epilog=epilogue,
                                     formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('filename1', help='Enter a polydata file e.g cow.g.')
    parser.add_argument('filename2', default=None, nargs='?', help='Enter another polydata file e.g cow.g.')
    args = parser.parse_args()
    return args.filename1, args.filename2

def ReadPolyData(file_name):
    import os
    path, extension = os.path.splitext(file_name)
    extension = extension.lower()
    if extension == ".ply":
        reader = vtk.vtkPLYReader()
        reader.SetFileName(file_name)
        reader.Update()
        poly_data = reader.GetOutput()
    elif extension == ".vtp":
        reader = vtk.vtkXMLpoly_dataReader()
        reader.SetFileName(file_name)
        reader.Update()
        poly_data = reader.GetOutput()
    elif extension == ".obj":
        reader = vtk.vtkOBJReader()
        reader.SetFileName(file_name)
        reader.Update()
        poly_data = reader.GetOutput()
    elif extension == ".stl":
        reader = vtk.vtkSTLReader()
        reader.SetFileName(file_name)
        reader.Update()
        poly_data = reader.GetOutput()
    elif extension == ".vtk":
        reader = vtk.vtkpoly_dataReader()
        reader.SetFileName(file_name)
        reader.Update()
        poly_data = reader.GetOutput()
    elif extension == ".g":
        reader = vtk.vtkBYUReader()
        reader.SetGeometryFileName(file_name)
        reader.Update()
        poly_data = reader.GetOutput()
    else:
        # Return a None if the extension is unknown.
        poly_data = None
    return poly_data

def main():
    fn1, fn2 = get_program_parameters()
    polyData1 = ReadPolyData(fn1)
    if fn2:
        polyData2 = ReadPolyData(fn1)
    else:
        # If only one polydata is present, generate a second polydata by
        # rotating the original about its center.
        print('Generating modified polyData1')
        center = polyData1.GetCenter()
        transform = vtk.vtkTransform()
        transform.Translate(center[0], center[1], center[2])
        transform.RotateY(90.0)
        transform.Translate(-center[0], -center[1], -center[2])
        transformPD = vtk.vtkTransformPolyDataFilter()
        transformPD.SetTransform(transform)
        transformPD.SetInputData(polyData1)
        transformPD.Update()
        polyData2 = transformPD.GetOutput()

    # Mark points inside with 1 and outside with a 0
    select = vtk.vtkSelectEnclosedPoints()
    select.SetInputData(polyData1)
    select.SetSurfaceData(polyData2)

    # Extract three meshes, one completely inside, one completely
    # outside and on the border between the inside and outside.

    threshold = vtk.vtkMultiThreshold()
    # Outside points have a 0 value in ALL points of a cell
    outsideId = threshold.AddBandpassIntervalSet(
        0, 0,
        vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, "SelectedPoints",
        0, 1)
    # Inside points have a 1 value in ALL points of a cell
    insideId = threshold.AddBandpassIntervalSet(
        1, 1,
        vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, "SelectedPoints",
        0, 1)
    # Border points have a 0 or a 1 in at least one point of a cell
    borderId = threshold.AddIntervalSet(
        0, 1,
        vtk.vtkMultiThreshold.OPEN, vtk.vtkMultiThreshold.OPEN,
        vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, "SelectedPoints",
        0, 0)

    threshold.SetInputConnection(select.GetOutputPort())

    # Select the intervals to be output
    threshold.OutputSet(outsideId)
    threshold.OutputSet(insideId)
    threshold.OutputSet(borderId)
    threshold.Update()

    # Visualize
    colors = vtk.vtkNamedColors()
    outsideColor = colors.GetColor3d("Crimson")
    insideColor = colors.GetColor3d("Banana")
    borderColor = colors.GetColor3d("Mint")
    surfaceColor = colors.GetColor3d("Peacock")
    backgroundColor = colors.GetColor3d("Silver")

    # Outside
    outsideMapper = vtk.vtkDataSetMapper()
    outsideMapper.SetInputData(threshold.GetOutput().GetBlock(outsideId).GetBlock(0))
    outsideMapper.ScalarVisibilityOff()

    outsideActor = vtk.vtkActor()
    outsideActor.SetMapper(outsideMapper)
    outsideActor.GetProperty().SetDiffuseColor(outsideColor)
    outsideActor.GetProperty().SetSpecular(.6)
    outsideActor.GetProperty().SetSpecularPower(30)

    # Inside
    insideMapper = vtk.vtkDataSetMapper()
    insideMapper.SetInputData(threshold.GetOutput().GetBlock(insideId).GetBlock(0))
    insideMapper.ScalarVisibilityOff()

    insideActor = vtk.vtkActor()
    insideActor.SetMapper(insideMapper)
    insideActor.GetProperty().SetDiffuseColor(insideColor)
    insideActor.GetProperty().SetSpecular(.6)
    insideActor.GetProperty().SetSpecularPower(30)
    insideActor.GetProperty().EdgeVisibilityOn()

    # Border
    borderMapper = vtk.vtkDataSetMapper()
    borderMapper.SetInputData(threshold.GetOutput().GetBlock(borderId).GetBlock(0))
    borderMapper.ScalarVisibilityOff()

    borderActor = vtk.vtkActor()
    borderActor.SetMapper(borderMapper)
    borderActor.GetProperty().SetDiffuseColor(borderColor)
    borderActor.GetProperty().SetSpecular(.6)
    borderActor.GetProperty().SetSpecularPower(30)
    borderActor.GetProperty().EdgeVisibilityOn()

    surfaceMapper = vtk.vtkDataSetMapper()
    surfaceMapper.SetInputData(polyData2)
    surfaceMapper.ScalarVisibilityOff()

    # Surface of object containing cell
    surfaceActor = vtk.vtkActor()
    surfaceActor.SetMapper(surfaceMapper)
    surfaceActor.GetProperty().SetDiffuseColor(surfaceColor)
    surfaceActor.GetProperty().SetOpacity(.1)

    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindow.SetSize(640, 480)

    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    renderer.SetBackground(backgroundColor)
    renderer.UseHiddenLineRemovalOn()

    renderer.AddActor(surfaceActor)
    renderer.AddActor(outsideActor)
    renderer.AddActor(insideActor)
    renderer.AddActor(borderActor)

    renderWindow.SetWindowName('CellsInsideObject')
    renderWindow.Render()
    renderer.GetActiveCamera().Azimuth(30)
    renderer.GetActiveCamera().Elevation(30)
    renderer.GetActiveCamera().Dolly(1.25)
    renderWindow.Render()

    renderWindowInteractor.Start()

if __name__ == '__main__':
    main()


text:
"""Hardware interfaces for triggering"""

# Authors: Dan McCloy <drmccloy@uw.edu>
#          Eric Larson <larsoner@uw.edu>
#
# License: BSD (3-clause)

import sys
import numpy as np

from ._utils import verbose_dec, string_types, logger

class ParallelTrigger(object):
    """Parallel port and dummy triggering support.

    .. warning:: When using the parallel port, calling
                 :meth:`expyfun.ExperimentController.start_stimulus`
                 will automatically invoke a stamping of the 1 trigger, which
                 will in turn cause a delay equal to that of
                 ``trigger_duration``.
                 This can effect e.g. :class:`EyelinkController` timing.

    Parameters
    ----------
    mode : str
        'parallel' for real use. 'dummy', passes all calls.
    address : str | int | None
        The address to use. On Linux this should be a string path like
        ``'/dev/parport0'`` (equivalent to None), on Windows it should be an
        integer address like ``888`` or ``0x378`` (equivalent to None).
        The config variable ``TRIGGER_ADDRESS`` can be used to set this
        permanently.
    trigger_duration : float
        Amount of time (seconds) to leave the trigger high whenever
        sending a trigger.
    ec : instance of ExperimentController
        The ExperimentController.
    verbose : bool, str, int, or None
        If not None, override default verbose level.

    Notes
    -----
    Parallel port activation is enabled by using the ``trigger_controller``
    argument of :class:`expyfun.ExperimentController`.
    """

    @verbose_dec
    def __init__(self, mode='dummy', address=None, trigger_duration=0.01,
                 ec=None, verbose=None):
        self.ec = ec
        if mode == 'parallel':
            if sys.platform.startswith('linux'):
                address = '/dev/parport0' if address is None else address
                if not isinstance(address, string_types):
                    raise ValueError('addrss must be a string or None, got %s '
                                     'of type %s' % (address, type(address)))
                from parallel import Parallel
                logger.info('Expyfun: Using address %s' % (address,))
                self._port = Parallel(address)
                self._portname = address
                self._set_data = self._port.setData
            elif sys.platform.startswith('win'):
                from ctypes import windll
                if not hasattr(windll, 'inpout32'):
                    raise SystemError(
                        'Must have inpout32 installed, see:\n\n'
                        'http://www.highrez.co.uk/downloads/inpout32/')

                base = '0x378' if address is None else address
                logger.info('Expyfun: Using base address %s' % (base,))
                if isinstance(base, string_types):
                    base = int(base, 16)
                if not isinstance(base, int):
                    raise ValueError('address must be int or None, got %s of '
                                     'type %s' % (base, type(base)))
                self._port = windll.inpout32
                mask = np.uint8(1 << 5 | 1 << 6 | 1 << 7)
                # Use ECP to put the port into byte mode
                val = int((self._port.Inp32(base + 0x402) & ~mask) | (1 << 5))
                self._port.Out32(base + 0x402, val)

                # Now to make sure the port is in output mode we need to make
                # sure that bit 5 of the control register is not set
                val = int(self._port.Inp32(base + 2) & ~np.uint8(1 << 5))
                self._port.Out32(base + 2, val)
                self._set_data = lambda data: self._port.Out32(base, data)
                self._portname = str(base)
            else:
                raise NotImplementedError('Parallel port triggering only '
                                          'supported on Linux and Windows')
        else:  # mode == 'dummy':
            self._port = self._portname = None
            self._trigger_list = list()
            self._set_data = lambda x: (self._trigger_list.append(x)
                                        if x != 0 else None)
        self.trigger_duration = trigger_duration
        self.mode = mode

    def __repr__(self):
        return '<ParallelTrigger : %s (%s)>' % (self.mode, self._portname)

    def _stamp_trigger(self, trig):
        """Fake stamping."""
        self._set_data(int(trig))
        self.ec.wait_secs(self.trigger_duration)
        self._set_data(0)

    def stamp_triggers(self, triggers, delay=None, wait_for_last=True,
                       is_trial_id=False):
        """Stamp a list of triggers with a given inter-trigger delay.

        Parameters
        ----------
        triggers : list
            No input checking is done, so ensure triggers is a list,
            with each entry an integer with fewer than 8 bits (max 255).
        delay : float | None
            The inter-trigger-onset delay (includes "on" time).
            If None, will use twice the trigger duration (50% duty cycle).
        wait_for_last : bool
            If True, wait for last trigger to be stamped before returning.
        is_trial_id : bool
            No effect for this trigger controller.
        """
        if delay is None:
            delay = 2 * self.trigger_duration
        for ti, trig in enumerate(triggers):
            self._stamp_trigger(trig)
            if ti < len(triggers) - 1 or wait_for_last:
                self.ec.wait_secs(delay - self.trigger_duration)

    def close(self):
        """Release hardware interfaces."""
        if hasattr(self, '_port'):
            del self._port

    def __del__(self):
        return self.close()

def decimals_to_binary(decimals, n_bits):
    """Convert a sequence of decimal numbers to a sequence of binary numbers.

    Parameters
    ----------
    decimals : array-like
        Array of integers to convert. Must all be >= 0.
    n_bits : array-like
        Array of the number of bits to use to represent each decimal number.

    Returns
    -------
    binary : list
        Binary representation.

    Notes
    -----
    This function is useful for generating IDs to be stamped using the TDT.
    """
    decimals = np.array(decimals, int)
    if decimals.ndim != 1 or (decimals < 0).any():
        raise ValueError('decimals must be 1D with all nonnegative values')
    n_bits = np.array(n_bits, int)
    if decimals.shape != n_bits.shape:
        raise ValueError('n_bits must have same shape as decimals')
    if (n_bits <= 0).any():
        raise ValueError('all n_bits must be positive')
    binary = list()
    for d, b in zip(decimals, n_bits):
        if d > 2 ** b - 1:
            raise ValueError('cannot convert number {0} using {1} bits'
                             ''.format(d, b))
        binary.extend([int(bb) for bb in np.binary_repr(d, b)])
    assert len(binary) == n_bits.sum()  # make sure we didn't do something dumb
    return binary

def binary_to_decimals(binary, n_bits):
    """Convert a sequence of binary numbers to a sequence of decimal numbers.

    Parameters
    ----------
    binary : array-like
        Array of integers to convert. Must all be 0 or 1.
    n_bits : array-like
        Array of the number of bits used to represent each decimal number.

    Returns
    -------
    decimals : array-like
        Array of integers.
    """
    if not np.array_equal(binary, np.array(binary, bool)):
        raise ValueError('binary must only contain zeros and ones')
    binary = np.array(binary, bool)
    if binary.ndim != 1:
        raise ValueError('binary must be 1 dimensional')
    n_bits = np.atleast_1d(n_bits).astype(int)
    if np.any(n_bits <= 0):
        raise ValueError('n_bits must all be > 0')
    if n_bits.sum() != len(binary):
        raise ValueError('the sum of n_bits must be equal to the number of '
                         'elements in binary')
    offset = 0
    outs = []
    for nb in n_bits:
        outs.append(np.sum(binary[offset:offset + nb] *
                           (2 ** np.arange(nb - 1, -1, -1))))
        offset += nb
    assert offset == len(binary)
    return np.array(outs)


text:
require "guard/dsl_describer"
require "guard/guardfile/result"

RSpec.describe Guard::DslDescriber, :stub_ui do
  let(:guardfile_result) { Guard::Guardfile::Result.new }
  let(:interactor) { instance_double(Guard::Interactor) }
  let(:env) { double("ENV") }

  subject { described_class.new(guardfile_result) }

  before do
    guardfile_result.plugins << [:another, {}] << [:test, {}]
    allow(env).to receive(:[]).with("GUARD_NOTIFY_PID")
    allow(env).to receive(:[]).with("GUARD_NOTIFY")
    allow(env).to receive(:[]).with("GUARD_NOTIFIERS")
    allow(env).to receive(:[]=).with("GUARD_NOTIFIERS", anything)

    allow(Guard::Notifier).to receive(:turn_on)

    @output = +""

    # Strip escape sequences
    allow(STDOUT).to receive(:tty?).and_return(false)

    # Capture formatador output
    Thread.current[:formatador] = Formatador.new
    allow(Thread.current[:formatador]).to receive(:print) do |msg|
      @output << msg
    end
  end

  describe "#list" do
    let(:result) do
      <<-OUTPUT
  +---------+-----------+
  | Plugin  | Guardfile |
  +---------+-----------+
  | Another | ✔        |
  | Even    | ✘        |
  | More    | ✘        |
  | Test    | ✔        |
  +---------+-----------+
      OUTPUT
    end

    before do
      allow(Guard::PluginUtil).to receive(:plugin_names) do
        %w[test another even more]
      end
    end

    it "lists the available Guards declared as strings or symbols" do
      subject.list
      expect(@output).to eq result
    end
  end

  describe ".show" do
    let(:result) do
      <<-OUTPUT
  +---------+---------+--------+-------+
  | Group   | Plugin  | Option | Value |
  +---------+---------+--------+-------+
  | default | test    | a      | :b    |
  |         |         | c      | :d    |
  +---------+---------+--------+-------+
  | a       | test    | x      | 1     |
  |         |         | y      | 2     |
  +---------+---------+--------+-------+
  | b       | another |        |       |
  +---------+---------+--------+-------+
      OUTPUT
    end

    before do
      guardfile_result.groups.merge!(default: {}, a: {}, b: {})
      guardfile_result.plugins << [:test, { a: :b, c: :d, group: :default }]
      guardfile_result.plugins << [:test, { x: 1, y: 2, group: :a }]
      guardfile_result.plugins << [:another, { group: :b }]
    end

    it "shows the Guards and their options" do
      subject.show
      expect(@output).to eq result
    end
  end

  describe ".notifiers" do
    let(:result) do
      <<-OUTPUT
  +----------------+-----------+------+--------+-------+
  | Name           | Available | Used | Option | Value |
  +----------------+-----------+------+--------+-------+
  | gntp           | ✔        | ✔   | sticky | true  |
  +----------------+-----------+------+--------+-------+
  | terminal_title | ✘        | ✘   |        |       |
  +----------------+-----------+------+--------+-------+
      OUTPUT
    end

    before do
      allow(Guard::Notifier).to receive(:supported).and_return(
        gntp: ::Notiffany::Notifier::GNTP,
        terminal_title: ::Notiffany::Notifier::TerminalTitle
      )

      allow(Guard::Notifier).to receive(:connect).once
      allow(Guard::Notifier).to receive(:detected)
        .and_return([{ name: :gntp, options: { sticky: true } }])

      allow(Guard::Notifier).to receive(:disconnect).once
    end

    it "properly connects and disconnects" do
      expect(Guard::Notifier).to receive(:connect).once.ordered
      expect(::Guard::Notifier).to receive(:detected).once.ordered.and_return [
        { name: :gntp, options: { sticky: true } }
      ]

      expect(Guard::Notifier).to receive(:disconnect).once.ordered

      subject.notifiers
    end

    it "shows the notifiers and their options" do
      subject.notifiers
      expect(@output).to eq result
    end
  end
end


text:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.lukti.android.mmdb.mobilemoviedatabase.DetailActivityFragment"
    tools:showIn="@layout/activity_detail">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:adjustViewBounds="true"
            android:id="@+id/detail_poster"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/text_color"
            android:textSize="@dimen/title_size"
            android:layout_marginTop="@dimen/top_margin"
            android:id="@+id/detail_title"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/top_margin"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@color/text_color"
                android:textSize="@dimen/date_size"
                android:layout_weight="1"
                android:id="@+id/detail_date"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@color/text_color"
                android:textSize="@dimen/date_size"
                android:layout_weight="1"
                android:layout_gravity="center_horizontal"
                android:id="@+id/detail_rating"/>

        </LinearLayout>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/text_color"
            android:textSize="@dimen/plot_size"
            android:layout_marginTop="@dimen/top_margin"
            android:id="@+id/detail_plot"/>

    </LinearLayout>
</ScrollView>