text:
using content::BrowserMessageFilter;
using content::BrowserThread;
using content::IndexedDBKey;
using content::IndexedDBKeyPath;
using content::IndexedDBKeyRange;
using content::UserMetricsAction;
using content::SerializedScriptValue;
using webkit_database::DatabaseUtil;
using WebKit::WebDOMStringList;
using WebKit::WebExceptionCode;
using WebKit::WebIDBCallbacks;
using WebKit::WebIDBCursor;
using WebKit::WebIDBDatabase;
using WebKit::WebIDBIndex;
using WebKit::WebIDBKey;
using WebKit::WebIDBMetadata;
using WebKit::WebIDBObjectStore;
using WebKit::WebIDBTransaction;
using WebKit::WebSecurityOrigin;
using WebKit::WebSerializedScriptValue;
using WebKit::WebVector;

namespace {

template <class T>
void DeleteOnWebKitThread(T* obj) {
  if (!BrowserThread::DeleteSoon(BrowserThread::WEBKIT_DEPRECATED,
                                 FROM_HERE, obj))
    delete obj;
}
}

IndexedDBDispatcherHost::IndexedDBDispatcherHost(
    int process_id, IndexedDBContextImpl* indexed_db_context)
    : indexed_db_context_(indexed_db_context),
      ALLOW_THIS_IN_INITIALIZER_LIST(database_dispatcher_host_(
          new DatabaseDispatcherHost(this))),
      ALLOW_THIS_IN_INITIALIZER_LIST(index_dispatcher_host_(
          new IndexDispatcherHost(this))),
      ALLOW_THIS_IN_INITIALIZER_LIST(object_store_dispatcher_host_(
          new ObjectStoreDispatcherHost(this))),
      ALLOW_THIS_IN_INITIALIZER_LIST(cursor_dispatcher_host_(
          new CursorDispatcherHost(this))),
      ALLOW_THIS_IN_INITIALIZER_LIST(transaction_dispatcher_host_(
          new TransactionDispatcherHost(this))),
      process_id_(process_id) {
  DCHECK(indexed_db_context_.get());
}

IndexedDBDispatcherHost::~IndexedDBDispatcherHost() {
}

void IndexedDBDispatcherHost::OnChannelClosing() {
  BrowserMessageFilter::OnChannelClosing();

  bool success = BrowserThread::PostTask(
      BrowserThread::WEBKIT_DEPRECATED, FROM_HERE,
      base::Bind(&IndexedDBDispatcherHost::ResetDispatcherHosts, this));

  if (!success)
    ResetDispatcherHosts();
}

void IndexedDBDispatcherHost::ResetDispatcherHosts() {
  // It is important that the various *_dispatcher_host_ members are reset
  // on the WebKit thread, since there might be incoming messages on that
  // thread, and we must not reset the dispatcher hosts until after those
  // messages are processed.
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED) ||
         CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess));

  database_dispatcher_host_.reset();
  index_dispatcher_host_.reset();
  object_store_dispatcher_host_.reset();
  cursor_dispatcher_host_.reset();
  transaction_dispatcher_host_.reset();
}

void IndexedDBDispatcherHost::OverrideThreadForMessage(
    const IPC::Message& message,
    BrowserThread::ID* thread) {
  if (IPC_MESSAGE_CLASS(message) == IndexedDBMsgStart)
    *thread = BrowserThread::WEBKIT_DEPRECATED;
}

bool IndexedDBDispatcherHost::OnMessageReceived(const IPC::Message& message,
                                                bool* message_was_ok) {
  if (IPC_MESSAGE_CLASS(message) != IndexedDBMsgStart)
    return false;

  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));

  bool handled =
      database_dispatcher_host_->OnMessageReceived(message, message_was_ok) ||
      index_dispatcher_host_->OnMessageReceived(message, message_was_ok) ||
      object_store_dispatcher_host_->OnMessageReceived(
          message, message_was_ok) ||
      cursor_dispatcher_host_->OnMessageReceived(message, message_was_ok) ||
      transaction_dispatcher_host_->OnMessageReceived(message, message_was_ok);

  if (!handled) {
    handled = true;
    IPC_BEGIN_MESSAGE_MAP_EX(IndexedDBDispatcherHost, message, *message_was_ok)
      IPC_MESSAGE_HANDLER(IndexedDBHostMsg_FactoryGetDatabaseNames,
                          OnIDBFactoryGetDatabaseNames)
      IPC_MESSAGE_HANDLER(IndexedDBHostMsg_FactoryOpen, OnIDBFactoryOpen)
      IPC_MESSAGE_HANDLER(IndexedDBHostMsg_FactoryDeleteDatabase,
                          OnIDBFactoryDeleteDatabase)
      IPC_MESSAGE_UNHANDLED(handled = false)
    IPC_END_MESSAGE_MAP()
  }

  return handled;
}

int32 IndexedDBDispatcherHost::Add(WebIDBCursor* idb_cursor) {
  if (!cursor_dispatcher_host_.get()) {
    delete idb_cursor;
    return 0;
  }
  return cursor_dispatcher_host_->map_.Add(idb_cursor);
}

int32 IndexedDBDispatcherHost::Add(WebIDBDatabase* idb_database,
                                   int32 thread_id,
                                   const GURL& origin_url) {
  if (!database_dispatcher_host_.get()) {
    delete idb_database;
    return 0;
  }
  int32 idb_database_id = database_dispatcher_host_->map_.Add(idb_database);
  Context()->ConnectionOpened(origin_url);
  database_dispatcher_host_->database_url_map_[idb_database_id] = origin_url;
  return idb_database_id;
}

int32 IndexedDBDispatcherHost::Add(WebIDBIndex* idb_index) {
  if (!index_dispatcher_host_.get())  {
    delete idb_index;
    return 0;
  }
  if (!idb_index)
    return 0;
  return index_dispatcher_host_->map_.Add(idb_index);
}

int32 IndexedDBDispatcherHost::Add(WebIDBObjectStore* idb_object_store) {
  if (!object_store_dispatcher_host_.get()) {
    delete idb_object_store;
    return 0;
  }
  if (!idb_object_store)
    return 0;
  return object_store_dispatcher_host_->map_.Add(idb_object_store);
}

int32 IndexedDBDispatcherHost::Add(WebIDBTransaction* idb_transaction,
                                   int32 thread_id,
                                   const GURL& url) {
  if (!transaction_dispatcher_host_.get()) {
    delete idb_transaction;
    return 0;
  }
  int32 id = transaction_dispatcher_host_->map_.Add(idb_transaction);
  idb_transaction->setCallbacks(
      new IndexedDBTransactionCallbacks(this, thread_id, id));
  transaction_dispatcher_host_->transaction_url_map_[id] = url;
  return id;
}

WebIDBCursor* IndexedDBDispatcherHost::GetCursorFromId(int32 cursor_id) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  return cursor_dispatcher_host_->map_.Lookup(cursor_id);
}

void IndexedDBDispatcherHost::OnIDBFactoryGetDatabaseNames(
    const IndexedDBHostMsg_FactoryGetDatabaseNames_Params& params) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  FilePath indexed_db_path = indexed_db_context_->data_path();

  WebSecurityOrigin origin(
      WebSecurityOrigin::createFromDatabaseIdentifier(params.origin));

  Context()->GetIDBFactory()->getDatabaseNames(
      new IndexedDBCallbacks<WebDOMStringList>(this, params.thread_id,
      params.response_id), origin, NULL,
      webkit_glue::FilePathToWebString(indexed_db_path));
}

void IndexedDBDispatcherHost::OnIDBFactoryOpen(
    const IndexedDBHostMsg_FactoryOpen_Params& params) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  FilePath indexed_db_path = indexed_db_context_->data_path();

  GURL origin_url = DatabaseUtil::GetOriginFromIdentifier(params.origin);
  WebSecurityOrigin origin(
      WebSecurityOrigin::createFromDatabaseIdentifier(params.origin));

  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));

  // TODO(dgrogan): Don't let a non-existing database be opened (and therefore
  // created) if this origin is already over quota.
  Context()->GetIDBFactory()->open(
      params.name,
      params.version,
      new IndexedDBCallbacks<WebIDBDatabase>(this, params.thread_id,
                                             params.response_id, origin_url),
      origin, NULL, webkit_glue::FilePathToWebString(indexed_db_path));
}

void IndexedDBDispatcherHost::OnIDBFactoryDeleteDatabase(
    const IndexedDBHostMsg_FactoryDeleteDatabase_Params& params) {
  FilePath indexed_db_path = indexed_db_context_->data_path();

  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  Context()->GetIDBFactory()->deleteDatabase(
      params.name,
      new IndexedDBCallbacks<WebSerializedScriptValue>(this,
                                                       params.thread_id,
                                                       params.response_id),
      WebSecurityOrigin::createFromDatabaseIdentifier(params.origin), NULL,
      webkit_glue::FilePathToWebString(indexed_db_path));
}

void IndexedDBDispatcherHost::TransactionComplete(int32 transaction_id) {
  Context()->TransactionComplete(
      transaction_dispatcher_host_->transaction_url_map_[transaction_id]);
}

//////////////////////////////////////////////////////////////////////
// Helper templates.
//

template <typename ObjectType>
ObjectType* IndexedDBDispatcherHost::GetOrTerminateProcess(
    IDMap<ObjectType, IDMapOwnPointer>* map, int32 return_object_id) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  ObjectType* return_object = map->Lookup(return_object_id);
  if (!return_object) {
    NOTREACHED() << "Uh oh, couldn't find object with id " << return_object_id;
    content::RecordAction(UserMetricsAction("BadMessageTerminate_IDBMF"));
    BadMessageReceived();
  }
  return return_object;
}

template <typename ObjectType>
void IndexedDBDispatcherHost::DestroyObject(
    IDMap<ObjectType, IDMapOwnPointer>* map, int32 object_id) {
  GetOrTerminateProcess(map, object_id);
  map->Remove(object_id);
}

//////////////////////////////////////////////////////////////////////
// IndexedDBDispatcherHost::DatabaseDispatcherHost
//

IndexedDBDispatcherHost::DatabaseDispatcherHost::DatabaseDispatcherHost(
    IndexedDBDispatcherHost* parent)
    : parent_(parent) {
  map_.set_check_on_null_data(true);
}

IndexedDBDispatcherHost::DatabaseDispatcherHost::~DatabaseDispatcherHost() {
  for (WebIDBObjectIDToURLMap::iterator iter = database_url_map_.begin();
       iter != database_url_map_.end(); iter++) {
    WebIDBDatabase* database = map_.Lookup(iter->first);
    if (database)
      database->close();
    parent_->Context()->ConnectionClosed(iter->second);
  }
}

bool IndexedDBDispatcherHost::DatabaseDispatcherHost::OnMessageReceived(
    const IPC::Message& message, bool* msg_is_ok) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP_EX(IndexedDBDispatcherHost::DatabaseDispatcherHost,
                           message, *msg_is_ok)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseMetadata, OnMetadata)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseCreateObjectStore,
                        OnCreateObjectStore)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseDeleteObjectStore,
                        OnDeleteObjectStore)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseSetVersion, OnSetVersion)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseTransaction, OnTransaction)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseClose, OnClose)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseOpen, OnOpen)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_DatabaseDestroyed, OnDestroyed)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void IndexedDBDispatcherHost::DatabaseDispatcherHost::Send(
    IPC::Message* message) {
  parent_->Send(message);
}

void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnMetadata(
    int32 idb_database_id, IndexedDBDatabaseMetadata* metadata) {
  WebIDBDatabase* idb_database = parent_->GetOrTerminateProcess(
      &map_, idb_database_id);
  if (!idb_database)
    return;

  WebIDBMetadata web_metadata = idb_database->metadata();
  metadata->name = web_metadata.name;
  metadata->version = web_metadata.version;
  metadata->intVersion = web_metadata.intVersion;

  for (size_t i = 0; i < web_metadata.objectStores.size(); ++i) {
    const WebIDBMetadata::ObjectStore& web_store_metadata =
        web_metadata.objectStores[i];
    IndexedDBObjectStoreMetadata idb_store_metadata;
    idb_store_metadata.name = web_store_metadata.name;
    idb_store_metadata.keyPath = IndexedDBKeyPath(web_store_metadata.keyPath);
    idb_store_metadata.autoIncrement = web_store_metadata.autoIncrement;

    for (size_t j = 0; j < web_store_metadata.indexes.size(); ++j) {
      const WebIDBMetadata::Index& web_index_metadata =
          web_store_metadata.indexes[j];
      IndexedDBIndexMetadata idb_index_metadata;
      idb_index_metadata.name = web_index_metadata.name;
      idb_index_metadata.keyPath = IndexedDBKeyPath(web_index_metadata.keyPath);
      idb_index_metadata.unique = web_index_metadata.unique;
      idb_index_metadata.multiEntry = web_index_metadata.multiEntry;
      idb_store_metadata.indexes.push_back(idb_index_metadata);
    }
    metadata->object_stores.push_back(idb_store_metadata);
  }
}

void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnCreateObjectStore(
    const IndexedDBHostMsg_DatabaseCreateObjectStore_Params& params,
    int32* object_store_id, WebKit::WebExceptionCode* ec) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBDatabase* idb_database = parent_->GetOrTerminateProcess(
      &map_, params.idb_database_id);
  WebIDBTransaction* idb_transaction = parent_->GetOrTerminateProcess(
      &parent_->transaction_dispatcher_host_->map_, params.transaction_id);
  if (!idb_database || !idb_transaction)
    return;

  *ec = 0;
  WebIDBObjectStore* object_store = idb_database->createObjectStore(
      params.name, params.key_path, params.auto_increment,
      *idb_transaction, *ec);
  *object_store_id = *ec ? 0 : parent_->Add(object_store);
  if (parent_->Context()->IsOverQuota(
      database_url_map_[params.idb_database_id])) {
    idb_transaction->abort();
  }
}

void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnDeleteObjectStore(
    int32 idb_database_id,
    const string16& name,
    int32 transaction_id,
    WebKit::WebExceptionCode* ec) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBDatabase* idb_database = parent_->GetOrTerminateProcess(
      &map_, idb_database_id);
  WebIDBTransaction* idb_transaction = parent_->GetOrTerminateProcess(
      &parent_->transaction_dispatcher_host_->map_, transaction_id);
  if (!idb_database || !idb_transaction)
    return;

  *ec = 0;
  idb_database->deleteObjectStore(name, *idb_transaction, *ec);
}

void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnSetVersion(
    int32 idb_database_id,
    int32 thread_id,
    int32 response_id,
    const string16& version,
    WebKit::WebExceptionCode* ec) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBDatabase* idb_database = parent_->GetOrTerminateProcess(
      &map_, idb_database_id);
  if (!idb_database)
    return;

  *ec = 0;
  idb_database->setVersion(
      version,
      new IndexedDBCallbacks<WebIDBTransaction>(parent_, thread_id, response_id,
          database_url_map_[idb_database_id]),
      *ec);
}

void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnTransaction(
    int32 thread_id,
    int32 idb_database_id,
    const std::vector<string16>& names,
    int32 mode,
    int32* idb_transaction_id,
    WebKit::WebExceptionCode* ec) {
  WebIDBDatabase* database = parent_->GetOrTerminateProcess(
      &map_, idb_database_id);
  if (!database)
      return;

  WebDOMStringList object_stores;
  for (std::vector<string16>::const_iterator it = names.begin();
       it != names.end(); ++it) {
    object_stores.append(*it);
  }

  *ec = 0;
  WebIDBTransaction* transaction = database->transaction(
      object_stores, mode, *ec);
  DCHECK(!transaction != !*ec);
  *idb_transaction_id =
      *ec ? 0 : parent_->Add(transaction, thread_id,
                             database_url_map_[idb_database_id]);
}

void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnOpen(
    int32 idb_database_id, int32 thread_id, int32 response_id) {
  WebIDBDatabase* database = parent_->GetOrTerminateProcess(
      &map_, idb_database_id);
  if (!database)
    return;
  database->open(new IndexedDBDatabaseCallbacks(parent_, thread_id,
                                                response_id));
}

void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnClose(
    int32 idb_database_id) {
  WebIDBDatabase* database = parent_->GetOrTerminateProcess(
      &map_, idb_database_id);
  if (!database)
    return;
  database->close();
}

void IndexedDBDispatcherHost::DatabaseDispatcherHost::OnDestroyed(
    int32 object_id) {
  parent_->Context()->ConnectionClosed(database_url_map_[object_id]);
  database_url_map_.erase(object_id);
  parent_->DestroyObject(&map_, object_id);
}

//////////////////////////////////////////////////////////////////////
// IndexedDBDispatcherHost::IndexDispatcherHost
//

IndexedDBDispatcherHost::IndexDispatcherHost::IndexDispatcherHost(
    IndexedDBDispatcherHost* parent)
    : parent_(parent) {
  map_.set_check_on_null_data(true);
}

IndexedDBDispatcherHost::IndexDispatcherHost::~IndexDispatcherHost() {
}

bool IndexedDBDispatcherHost::IndexDispatcherHost::OnMessageReceived(
    const IPC::Message& message, bool* msg_is_ok) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP_EX(IndexedDBDispatcherHost::IndexDispatcherHost,
                           message, *msg_is_ok)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_IndexOpenObjectCursor,
                                    OnOpenObjectCursor)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_IndexOpenKeyCursor, OnOpenKeyCursor)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_IndexCount, OnCount)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_IndexGetObject, OnGetObject)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_IndexGetKey, OnGetKey)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_IndexDestroyed, OnDestroyed)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void IndexedDBDispatcherHost::IndexDispatcherHost::Send(
    IPC::Message* message) {
  parent_->Send(message);
}

void IndexedDBDispatcherHost::IndexDispatcherHost::OnOpenObjectCursor(
    const IndexedDBHostMsg_IndexOpenCursor_Params& params,
    WebKit::WebExceptionCode* ec) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBIndex* idb_index = parent_->GetOrTerminateProcess(
      &map_, params.idb_index_id);
  WebIDBTransaction* idb_transaction = parent_->GetOrTerminateProcess(
      &parent_->transaction_dispatcher_host_->map_, params.transaction_id);
  if (!idb_transaction || !idb_index)
    return;

  *ec = 0;
  scoped_ptr<WebIDBCallbacks> callbacks(
      new IndexedDBCallbacks<WebIDBCursor>(parent_, params.thread_id,
                                           params.response_id, -1));
  idb_index->openObjectCursor(
      params.key_range, params.direction, callbacks.release(),
      *idb_transaction, *ec);
}

void IndexedDBDispatcherHost::IndexDispatcherHost::OnOpenKeyCursor(
    const IndexedDBHostMsg_IndexOpenCursor_Params& params,
    WebKit::WebExceptionCode* ec) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBIndex* idb_index = parent_->GetOrTerminateProcess(
      &map_, params.idb_index_id);
  WebIDBTransaction* idb_transaction = parent_->GetOrTerminateProcess(
      &parent_->transaction_dispatcher_host_->map_, params.transaction_id);
  if (!idb_transaction || !idb_index)
    return;

  *ec = 0;
  scoped_ptr<WebIDBCallbacks> callbacks(
      new IndexedDBCallbacks<WebIDBCursor>(parent_, params.thread_id,
                                           params.response_id, -1));
  idb_index->openKeyCursor(
      params.key_range, params.direction, callbacks.release(),
      *idb_transaction, *ec);
}

void IndexedDBDispatcherHost::IndexDispatcherHost::OnCount(
    const IndexedDBHostMsg_IndexCount_Params& params,
    WebKit::WebExceptionCode* ec) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBIndex* idb_index = parent_->GetOrTerminateProcess(
      &map_, params.idb_index_id);
  WebIDBTransaction* idb_transaction = parent_->GetOrTerminateProcess(
      &parent_->transaction_dispatcher_host_->map_, params.transaction_id);
  if (!idb_transaction || !idb_index)
    return;

  *ec = 0;
  scoped_ptr<WebIDBCallbacks> callbacks(
      new IndexedDBCallbacks<WebSerializedScriptValue>(parent_,
                                                       params.thread_id,
                                                       params.response_id));
  idb_index->count(
      params.key_range, callbacks.release(), *idb_transaction, *ec);
}

void IndexedDBDispatcherHost::IndexDispatcherHost::OnGetObject(
    int idb_index_id,
    int32 thread_id,
    int32 response_id,
    const IndexedDBKeyRange& key_range,
    int32 transaction_id,
    WebKit::WebExceptionCode* ec) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBIndex* idb_index = parent_->GetOrTerminateProcess(
      &map_, idb_index_id);
  WebIDBTransaction* idb_transaction = parent_->GetOrTerminateProcess(
      &parent_->transaction_dispatcher_host_->map_, transaction_id);
  if (!idb_transaction || !idb_index)
    return;

  *ec = 0;
  scoped_ptr<WebIDBCallbacks> callbacks(
      new IndexedDBCallbacks<WebSerializedScriptValue>(parent_, thread_id,
                                                       response_id));
  idb_index->getObject(key_range, callbacks.release(), *idb_transaction, *ec);
}

void IndexedDBDispatcherHost::IndexDispatcherHost::OnGetKey(
    int idb_index_id,
    int32 thread_id,
    int32 response_id,
    const IndexedDBKeyRange& key_range,
    int32 transaction_id,
    WebKit::WebExceptionCode* ec) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBIndex* idb_index = parent_->GetOrTerminateProcess(
      &map_, idb_index_id);
  WebIDBTransaction* idb_transaction = parent_->GetOrTerminateProcess(
      &parent_->transaction_dispatcher_host_->map_, transaction_id);
  if (!idb_transaction || !idb_index)
    return;

  *ec = 0;
  scoped_ptr<WebIDBCallbacks> callbacks(
      new IndexedDBCallbacks<WebIDBKey>(parent_, thread_id, response_id));
  idb_index->getKey(key_range, callbacks.release(), *idb_transaction, *ec);
}

void IndexedDBDispatcherHost::IndexDispatcherHost::OnDestroyed(
    int32 object_id) {
  parent_->DestroyObject(&map_, object_id);
}

//////////////////////////////////////////////////////////////////////
// IndexedDBDispatcherHost::ObjectStoreDispatcherHost
//

IndexedDBDispatcherHost::ObjectStoreDispatcherHost::ObjectStoreDispatcherHost(
    IndexedDBDispatcherHost* parent)
    : parent_(parent) {
  map_.set_check_on_null_data(true);
}

IndexedDBDispatcherHost::
ObjectStoreDispatcherHost::~ObjectStoreDispatcherHost() {
}

bool IndexedDBDispatcherHost::ObjectStoreDispatcherHost::OnMessageReceived(
    const IPC::Message& message, bool* msg_is_ok) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP_EX(IndexedDBDispatcherHost::ObjectStoreDispatcherHost,
                           message, *msg_is_ok)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_ObjectStoreGet, OnGet)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_ObjectStorePut, OnPut)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_ObjectStoreDelete, OnDelete)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_ObjectStoreClear, OnClear)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_ObjectStoreCreateIndex, OnCreateIndex)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_ObjectStoreIndex, OnIndex)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_ObjectStoreDeleteIndex, OnDeleteIndex)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_ObjectStoreOpenCursor, OnOpenCursor)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_ObjectStoreCount, OnCount)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_ObjectStoreDestroyed, OnDestroyed)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void IndexedDBDispatcherHost::ObjectStoreDispatcherHost::Send(
    IPC::Message* message) {
  parent_->Send(message);
}

void IndexedDBDispatcherHost::ObjectStoreDispatcherHost::OnGet(
    int idb_object_store_id,
    int32 thread_id,
    int32 response_id,
    const IndexedDBKeyRange& key_range,
    int32 transaction_id,
    WebKit::WebExceptionCode* ec) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBObjectStore* idb_object_store = parent_->GetOrTerminateProcess(
      &map_, idb_object_store_id);
  WebIDBTransaction* idb_transaction = parent_->GetOrTerminateProcess(
      &parent_->transaction_dispatcher_host_->map_, transaction_id);
  if (!idb_transaction || !idb_object_store)
    return;

  *ec = 0;
  scoped_ptr<WebIDBCallbacks> callbacks(
      new IndexedDBCallbacks<WebSerializedScriptValue>(parent_, thread_id,
                                                       response_id));
  idb_object_store->get(key_range, callbacks.release(), *idb_transaction, *ec);
}

void IndexedDBDispatcherHost::ObjectStoreDispatcherHost::OnPut(
    const IndexedDBHostMsg_ObjectStorePut_Params& params,
    WebKit::WebExceptionCode* ec) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBObjectStore* idb_object_store = parent_->GetOrTerminateProcess(
      &map_, params.idb_object_store_id);
  WebIDBTransaction* idb_transaction = parent_->GetOrTerminateProcess(
      &parent_->transaction_dispatcher_host_->map_, params.transaction_id);
  if (!idb_transaction || !idb_object_store)
    return;

  *ec = 0;
  scoped_ptr<WebIDBCallbacks> callbacks(
      new IndexedDBCallbacks<WebIDBKey>(parent_, params.thread_id,
                                        params.response_id));
  idb_object_store->putWithIndexKeys(params.serialized_value, params.key,
                                     params.put_mode, callbacks.release(),
                                     *idb_transaction, params.index_names,
                                     params.index_keys, *ec);
  if (*ec)
    return;
  int64 size = UTF16ToUTF8(params.serialized_value.data()).size();
  WebIDBTransactionIDToSizeMap* map =
      &parent_->transaction_dispatcher_host_->transaction_size_map_;
  (*map)[params.transaction_id] += size;
}

void IndexedDBDispatcherHost::ObjectStoreDispatcherHost::OnDelete(
    int idb_object_store_id,
    int32 thread_id,
    int32 response_id,
    const IndexedDBKeyRange& key_range,
    int32 transaction_id,
    WebKit::WebExceptionCode* ec) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBObjectStore* idb_object_store = parent_->GetOrTerminateProcess(
      &map_, idb_object_store_id);
  WebIDBTransaction* idb_transaction = parent_->GetOrTerminateProcess(
      &parent_->transaction_dispatcher_host_->map_, transaction_id);
  if (!idb_transaction || !idb_object_store)
    return;

  *ec = 0;
  scoped_ptr<WebIDBCallbacks> callbacks(
      new IndexedDBCallbacks<WebSerializedScriptValue>(parent_, thread_id,
                                                       response_id));
  idb_object_store->deleteFunction(
      key_range, callbacks.release(), *idb_transaction, *ec);
}

void IndexedDBDispatcherHost::ObjectStoreDispatcherHost::OnClear(
    int idb_object_store_id,
    int32 thread_id,
    int32 response_id,
    int32 transaction_id,
    WebKit::WebExceptionCode* ec) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBObjectStore* idb_object_store = parent_->GetOrTerminateProcess(
      &map_, idb_object_store_id);
  WebIDBTransaction* idb_transaction = parent_->GetOrTerminateProcess(
      &parent_->transaction_dispatcher_host_->map_, transaction_id);
  if (!idb_transaction || !idb_object_store)
    return;

  *ec = 0;
  scoped_ptr<WebIDBCallbacks> callbacks(
      new IndexedDBCallbacks<WebSerializedScriptValue>(parent_, thread_id,
                                                       response_id));
  idb_object_store->clear(callbacks.release(), *idb_transaction, *ec);
}

void IndexedDBDispatcherHost::ObjectStoreDispatcherHost::OnCreateIndex(
    const IndexedDBHostMsg_ObjectStoreCreateIndex_Params& params,
    int32* index_id, WebKit::WebExceptionCode* ec) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBObjectStore* idb_object_store = parent_->GetOrTerminateProcess(
      &map_, params.idb_object_store_id);
  WebIDBTransaction* idb_transaction = parent_->GetOrTerminateProcess(
      &parent_->transaction_dispatcher_host_->map_, params.transaction_id);
  if (!idb_object_store || !idb_transaction)
    return;

  *ec = 0;
  WebIDBIndex* index = idb_object_store->createIndex(
      params.name, params.key_path, params.unique, params.multi_entry,
      *idb_transaction, *ec);
  *index_id = *ec ? 0 : parent_->Add(index);
  WebIDBObjectIDToURLMap* transaction_url_map =
      &parent_->transaction_dispatcher_host_->transaction_url_map_;
  if (parent_->Context()->IsOverQuota(
      (*transaction_url_map)[params.transaction_id])) {
    idb_transaction->abort();
  }
}

void IndexedDBDispatcherHost::ObjectStoreDispatcherHost::OnIndex(
    int32 idb_object_store_id,
    const string16& name,
    int32* idb_index_id,
    WebKit::WebExceptionCode* ec) {
  WebIDBObjectStore* idb_object_store = parent_->GetOrTerminateProcess(
      &map_, idb_object_store_id);
  if (!idb_object_store)
    return;

  *ec = 0;
  WebIDBIndex* index = idb_object_store->index(name, *ec);
  *idb_index_id = parent_->Add(index);
}

void IndexedDBDispatcherHost::ObjectStoreDispatcherHost::OnDeleteIndex(
    int32 idb_object_store_id,
    const string16& name,
    int32 transaction_id,
    WebKit::WebExceptionCode* ec) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBObjectStore* idb_object_store = parent_->GetOrTerminateProcess(
      &map_, idb_object_store_id);
  WebIDBTransaction* idb_transaction = parent_->GetOrTerminateProcess(
      &parent_->transaction_dispatcher_host_->map_, transaction_id);
  if (!idb_object_store || !idb_transaction)
    return;

  *ec = 0;
  idb_object_store->deleteIndex(name, *idb_transaction, *ec);
}

void IndexedDBDispatcherHost::ObjectStoreDispatcherHost::OnOpenCursor(
    const IndexedDBHostMsg_ObjectStoreOpenCursor_Params& params,
    WebKit::WebExceptionCode* ec) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBObjectStore* idb_object_store = parent_->GetOrTerminateProcess(
      &parent_->object_store_dispatcher_host_->map_,
      params.idb_object_store_id);
  WebIDBTransaction* idb_transaction = parent_->GetOrTerminateProcess(
      &parent_->transaction_dispatcher_host_->map_, params.transaction_id);
  if (!idb_transaction || !idb_object_store)
    return;

  *ec = 0;
  scoped_ptr<WebIDBCallbacks> callbacks(
      new IndexedDBCallbacks<WebIDBCursor>(parent_, params.thread_id,
                                           params.response_id, -1));
  idb_object_store->openCursor(
      params.key_range, params.direction, callbacks.release(),
      *idb_transaction, *ec);
}

void IndexedDBDispatcherHost::ObjectStoreDispatcherHost::OnCount(
    const IndexedDBHostMsg_ObjectStoreCount_Params& params,
    WebKit::WebExceptionCode* ec) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBObjectStore* idb_object_store = parent_->GetOrTerminateProcess(
      &parent_->object_store_dispatcher_host_->map_,
      params.idb_object_store_id);
  WebIDBTransaction* idb_transaction = parent_->GetOrTerminateProcess(
      &parent_->transaction_dispatcher_host_->map_, params.transaction_id);
  if (!idb_transaction || !idb_object_store)
    return;

  *ec = 0;
  scoped_ptr<WebIDBCallbacks> callbacks(
      new IndexedDBCallbacks<WebSerializedScriptValue>(parent_,
                                                       params.thread_id,
                                                       params.response_id));
  idb_object_store->count(
      params.key_range, callbacks.release(), *idb_transaction, *ec);
}

void IndexedDBDispatcherHost::ObjectStoreDispatcherHost::OnDestroyed(
    int32 object_id) {
  parent_->DestroyObject(&map_, object_id);
}

//////////////////////////////////////////////////////////////////////
// IndexedDBDispatcherHost::CursorDispatcherHost
//

IndexedDBDispatcherHost::CursorDispatcherHost::CursorDispatcherHost(
    IndexedDBDispatcherHost* parent)
    : parent_(parent) {
  map_.set_check_on_null_data(true);
}

IndexedDBDispatcherHost::CursorDispatcherHost::~CursorDispatcherHost() {
}

bool IndexedDBDispatcherHost::CursorDispatcherHost::OnMessageReceived(
    const IPC::Message& message, bool* msg_is_ok) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP_EX(IndexedDBDispatcherHost::CursorDispatcherHost,
                           message, *msg_is_ok)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_CursorAdvance, OnAdvance)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_CursorContinue, OnContinue)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_CursorPrefetch, OnPrefetch)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_CursorPrefetchReset, OnPrefetchReset)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_CursorDelete, OnDelete)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_CursorDestroyed, OnDestroyed)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void IndexedDBDispatcherHost::CursorDispatcherHost::Send(
    IPC::Message* message) {
  parent_->Send(message);
}

void IndexedDBDispatcherHost::CursorDispatcherHost::OnKey(
    int32 object_id, IndexedDBKey* key) {
  WebIDBCursor* idb_cursor = parent_->GetOrTerminateProcess(&map_, object_id);
  if (!idb_cursor)
    return;

  *key = IndexedDBKey(idb_cursor->key());
}

void IndexedDBDispatcherHost::CursorDispatcherHost::OnPrimaryKey(
    int32 object_id, IndexedDBKey* primary_key) {
  WebIDBCursor* idb_cursor = parent_->GetOrTerminateProcess(&map_, object_id);
  if (!idb_cursor)
    return;

  *primary_key = IndexedDBKey(idb_cursor->primaryKey());
}

void IndexedDBDispatcherHost::CursorDispatcherHost::OnValue(
    int32 object_id,
    SerializedScriptValue* script_value) {
  WebIDBCursor* idb_cursor = parent_->GetOrTerminateProcess(&map_, object_id);
  if (!idb_cursor)
    return;

  *script_value = SerializedScriptValue(idb_cursor->value());
}

void IndexedDBDispatcherHost::CursorDispatcherHost::OnAdvance(
    int32 cursor_id,
    int32 thread_id,
    int32 response_id,
    unsigned long count,
    WebKit::WebExceptionCode* ec) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBCursor* idb_cursor = parent_->GetOrTerminateProcess(&map_, cursor_id);
  if (!idb_cursor)
    return;

  *ec = 0;
  idb_cursor->advance(count,
                      new IndexedDBCallbacks<WebIDBCursor>(parent_,
                                                           thread_id,
                                                           response_id,
                                                           cursor_id),
                      *ec);
}

void IndexedDBDispatcherHost::CursorDispatcherHost::OnContinue(
    int32 cursor_id,
    int32 thread_id,
    int32 response_id,
    const IndexedDBKey& key,
    WebKit::WebExceptionCode* ec) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBCursor* idb_cursor = parent_->GetOrTerminateProcess(&map_, cursor_id);
  if (!idb_cursor)
    return;

  *ec = 0;
  idb_cursor->continueFunction(
      key, new IndexedDBCallbacks<WebIDBCursor>(parent_, thread_id, response_id,
                                                cursor_id), *ec);
}

void IndexedDBDispatcherHost::CursorDispatcherHost::OnPrefetch(
    int32 cursor_id,
    int32 thread_id,
    int32 response_id,
    int n,
    WebKit::WebExceptionCode* ec) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBCursor* idb_cursor = parent_->GetOrTerminateProcess(&map_, cursor_id);
  if (!idb_cursor)
    return;

  *ec = 0;
  idb_cursor->prefetchContinue(
      n, new IndexedDBCallbacks<WebIDBCursor>(parent_, thread_id, response_id,
                                              cursor_id), *ec);
}

void IndexedDBDispatcherHost::CursorDispatcherHost::OnPrefetchReset(
    int32 cursor_id, int used_prefetches, int unused_prefetches) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBCursor* idb_cursor = parent_->GetOrTerminateProcess(&map_, cursor_id);
  if (!idb_cursor)
    return;

  idb_cursor->prefetchReset(used_prefetches, unused_prefetches);
}

void IndexedDBDispatcherHost::CursorDispatcherHost::OnDelete(
    int32 cursor_id,
    int32 thread_id,
    int32 response_id,
    WebKit::WebExceptionCode* ec) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBCursor* idb_cursor = parent_->GetOrTerminateProcess(&map_, cursor_id);
  if (!idb_cursor)
    return;

  *ec = 0;
  idb_cursor->deleteFunction(
      new IndexedDBCallbacks<WebSerializedScriptValue>(parent_, thread_id,
                                                       response_id), *ec);
}

void IndexedDBDispatcherHost::CursorDispatcherHost::OnDestroyed(
    int32 object_id) {
  parent_->DestroyObject(&map_, object_id);
}

//////////////////////////////////////////////////////////////////////
// IndexedDBDispatcherHost::TransactionDispatcherHost
//

IndexedDBDispatcherHost::TransactionDispatcherHost::TransactionDispatcherHost(
    IndexedDBDispatcherHost* parent)
    : parent_(parent) {
  map_.set_check_on_null_data(true);
}

IndexedDBDispatcherHost::
    TransactionDispatcherHost::~TransactionDispatcherHost() {
  MapType::iterator it(&map_);
  while (!it.IsAtEnd()) {
    it.GetCurrentValue()->abort();
    it.Advance();
  }
}

bool IndexedDBDispatcherHost::TransactionDispatcherHost::OnMessageReceived(
    const IPC::Message& message, bool* msg_is_ok) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP_EX(IndexedDBDispatcherHost::TransactionDispatcherHost,
                           message, *msg_is_ok)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_TransactionCommit, OnCommit)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_TransactionAbort, OnAbort)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_TransactionObjectStore, OnObjectStore)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_TransactionDidCompleteTaskEvents,
                        OnDidCompleteTaskEvents)
    IPC_MESSAGE_HANDLER(IndexedDBHostMsg_TransactionDestroyed, OnDestroyed)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void IndexedDBDispatcherHost::TransactionDispatcherHost::Send(
    IPC::Message* message) {
  parent_->Send(message);
}

void IndexedDBDispatcherHost::TransactionDispatcherHost::OnCommit(
    int32 transaction_id) {
  WebIDBTransaction* idb_transaction = parent_->GetOrTerminateProcess(
      &map_, transaction_id);
  if (!idb_transaction)
    return;

  idb_transaction->commit();
}

void IndexedDBDispatcherHost::TransactionDispatcherHost::OnAbort(
    int32 transaction_id) {
  WebIDBTransaction* idb_transaction = parent_->GetOrTerminateProcess(
      &map_, transaction_id);
  if (!idb_transaction)
    return;

  idb_transaction->abort();
}

void IndexedDBDispatcherHost::TransactionDispatcherHost::OnObjectStore(
    int32 transaction_id, const string16& name, int32* object_store_id,
    WebKit::WebExceptionCode* ec) {
  WebIDBTransaction* idb_transaction = parent_->GetOrTerminateProcess(
      &map_, transaction_id);
  if (!idb_transaction)
    return;

  *ec = 0;
  WebIDBObjectStore* object_store = idb_transaction->objectStore(name, *ec);
  *object_store_id = object_store ? parent_->Add(object_store) : 0;
}

void IndexedDBDispatcherHost::
    TransactionDispatcherHost::OnDidCompleteTaskEvents(int transaction_id) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT_DEPRECATED));
  WebIDBTransaction* idb_transaction = parent_->GetOrTerminateProcess(
      &map_, transaction_id);
  if (!idb_transaction)
    return;

  // TODO(dgrogan): Tell the page the transaction aborted because of quota.
  // http://crbug.com/113118
  if (parent_->Context()->WouldBeOverQuota(
      transaction_url_map_[transaction_id],
      transaction_size_map_[transaction_id])) {
    idb_transaction->abort();
    return;
  }
  idb_transaction->didCompleteTaskEvents();
}

void IndexedDBDispatcherHost::TransactionDispatcherHost::OnDestroyed(
    int32 object_id) {
  // TODO(dgrogan): This doesn't seem to be happening with some version change
  // transactions. Possibly introduced with integer version support.
  transaction_size_map_.erase(object_id);
  transaction_url_map_.erase(object_id);
  parent_->DestroyObject(&map_, object_id);
}


text:
#include "dsp/occlusion_calculator.h"

#include <algorithm>

#include "third_party/googletest/googletest/include/gtest/gtest.h"
#include "base/constants_and_types.h"
#include "base/misc_math.h"

namespace vraudio {

namespace {

// Spherical coordinates of listener relative to source.
const float kListenerAheadRads[2] = {0.0f, 0.0f};
const float kListenerBesideRads[2] = {0.0f, static_cast<float>(M_PI_2)};
const float kListenerAboveAndAheadRads[2] = {static_cast<float>(M_PI_4), 0.0f};

// Test case data structure.
struct DirectivityTestParams {
  // Directivity function's alpha weighting.
  const float alpha;
  // Directivity function's order.
  const float order;
  // Spherical angle of the listener relative to the source.
  const float* relative_spherical_angle;
  // Expected value produced by the directivity function for the given input
  // parameters.
  const float expected_directivity;
};

// This test runs through a series of parametrized test cases and checks that
// the directivity value calculated according to those parameters is correct.
class DirectivityCalculatorParametrizedTest
    : public testing::Test,
      public testing::WithParamInterface<DirectivityTestParams> {};

// Parametrized test which verifies that the directivity value calculated from
// the test parameters matches the expected value supplied.
TEST_P(DirectivityCalculatorParametrizedTest, CalculateDirectivityTest) {
  // Test parameters.
  const DirectivityTestParams test_params = GetParam();

  // Construct test angle.
  const float elevation_rad = test_params.relative_spherical_angle[0];
  const float azimuth_rad = test_params.relative_spherical_angle[1];
  SphericalAngle test_angle(elevation_rad, azimuth_rad);

  // Calculate directivity.
  const float directivity =
      CalculateDirectivity(test_params.alpha, test_params.order, test_angle);

  // Check calculated directivity.
  EXPECT_NEAR(test_params.expected_directivity, directivity, kEpsilonFloat);
}

// Test parameters, according to struct |DirectivityParams|.
DirectivityTestParams test_cases[] = {
    // Omnidirectional.
    {0.0f, 1.0f, &(kListenerAheadRads[0]), 1.0f},
    {0.0f, 1.0f, &(kListenerBesideRads[0]), 1.0f},
    {0.0f, 1.0f, &(kListenerAboveAndAheadRads[0]), 1.0f},
    {0.0f, 2.0f, &(kListenerAboveAndAheadRads[0]), 1.0f},
    {0.0f, 0.5f, &(kListenerAboveAndAheadRads[0]), 1.0f},
    // Hypocardioid.
    {0.25f, 1.0f, &(kListenerAheadRads[0]), 1.0f},
    {0.25f, 1.0f, &(kListenerBesideRads[0]), 0.75f},
    {0.25f, 1.0f, &(kListenerAboveAndAheadRads[0]), 0.926777f},
    {0.25f, 2.0f, &(kListenerAboveAndAheadRads[0]), 0.858915f},
    {0.25f, 0.5f, &(kListenerAboveAndAheadRads[0]), 0.926777f},
    // Cardioid.
    {0.5f, 1.0f, &(kListenerAheadRads[0]), 1.0f},
    {0.5f, 1.0f, &(kListenerBesideRads[0]), 0.5f},
    {0.5f, 1.0f, &(kListenerAboveAndAheadRads[0]), 0.853553f},
    {0.5f, 2.0f, &(kListenerAboveAndAheadRads[0]), 0.728553f},
    // Hypercardioid.
    {0.75f, 1.0f, &(kListenerAheadRads[0]), 1.0f},
    {0.75f, 1.0f, &(kListenerBesideRads[0]), 0.25f},
    {0.75f, 1.0f, &(kListenerAboveAndAheadRads[0]), 0.780330f},
    {0.75f, 2.0f, &(kListenerAboveAndAheadRads[0]), 0.608915f},
    {0.75f, 0.5f, &(kListenerAboveAndAheadRads[0]), 0.780330f},
    // Dipole.
    {1.0f, 1.0f, &(kListenerAheadRads[0]), 1.0f},
    {1.0f, 1.0f, &(kListenerBesideRads[0]), 0.0f},
    {1.0f, 1.0f, &(kListenerAboveAndAheadRads[0]), 0.707107f},
    {1.0f, 2.0f, &(kListenerAboveAndAheadRads[0]), 0.5f},
    {1.0f, 0.5f, &(kListenerAboveAndAheadRads[0]), 0.707107f}};

INSTANTIATE_TEST_CASE_P(Instance, DirectivityCalculatorParametrizedTest,
                        testing::ValuesIn(test_cases));

TEST(DirectivityTest, CalculateOcclusionFilterCoefficientTest) {
  // When there is no occlusion (occlusion == 0) expect the filter coefficient
  // to be 1 - directivity.
  const std::vector<float> directivities = {0.0f, 0.3f, 0.5f, 0.7f, 0.9f, 1.5f};
  for (size_t i = 0; i < directivities.size() - 1; ++i) {
    const float coefficient =
        CalculateOcclusionFilterCoefficient(directivities[i], 0.0f);
    EXPECT_EQ(1.0f - directivities[i], coefficient);
  }
  // Ensure the minimum value returned is 0.
  const float coefficient =
      CalculateOcclusionFilterCoefficient(directivities.back(), 0.0f);
  EXPECT_EQ(0.0f, coefficient);
}

TEST(OcclusionTest, CalculateOcclusionFilterCoefficientTest) {
  // When there is no effect on directivity, expect the filter coefficient
  // to be  1 / (x + 1)^4 where x is the occlusion intensity.
  const std::vector<float> occlusions = {0.01f, 0.1f, 1.0f, 10.0f, 100.0f};
  std::vector<float> expected_coefficients = occlusions;
  // Calculate 1 / (x + 1)^4 where x is the occlusion intensity.
  std::for_each(expected_coefficients.begin(), expected_coefficients.end(),
                [](float& n) { n = 1.0f - 1.0f / IntegerPow(n + 1.0f, 4); });
  for (size_t i = 0; i < expected_coefficients.size(); ++i) {
    const float coefficient =
        CalculateOcclusionFilterCoefficient(1.0f, occlusions[i]);
    EXPECT_EQ(expected_coefficients[i], coefficient);
  }
}

}  // namespace

}  // namespace vraudio

redpajama_set_name: RedPajamaGithub


text:
tomcat8Webapps=/opt/tomcat8/webapps

if ! [ -f $tomcat8Webapps/unprotectedWar.war ]; then
    cd /vagrant/sampleApps/unprotectedWar
    gradle clean war
    rm -rf $tomcat8Webapps/unprotectedWar*
    cp build/libs/unprotectedWar.war $tomcat8Webapps
fi

if ! cat /etc/rc.local | grep tomcat8
then
    sudo chmod 777 /etc/rc.local
    echo 'sudo su vagrant -c /opt/tomcat8/bin/startup.sh' >> /etc/rc.local
    sudo chmod 755 /etc/rc.local
fi


text:
namespace std {
using ::int16_t;
using ::int32_t;
using ::int8_t;
using ::size_t;
using ::uint16_t;
using ::uint32_t;
using ::uint8_t;
using ::uintptr_t;
}  // namespace std
#endif

#include <algorithm>
#include <cassert>
#include <cstdlib>

#ifdef GEMMLOWP_PROFILING
#include <cstring>
#include <set>
#endif

#include "./pthread_everywhere.h"

namespace gemmlowp {

inline void ReleaseBuildAssertion(bool condition, const char* msg) {
  if (!condition) {
    fprintf(stderr, "gemmlowp error: %s\n", msg);
    abort();
  }
}

class Mutex {
 public:
  Mutex(const Mutex&) = delete;
  Mutex& operator=(const Mutex&) = delete;

  Mutex() { pthread_mutex_init(&m, NULL); }
  ~Mutex() { pthread_mutex_destroy(&m); }

  void Lock() { pthread_mutex_lock(&m); }
  void Unlock() { pthread_mutex_unlock(&m); }

 private:
  pthread_mutex_t m;
};

class GlobalMutexes {
 public:
  static Mutex* Profiler() {
    static Mutex m;
    return &m;
  }

  static Mutex* EightBitIntGemm() {
    static Mutex m;
    return &m;
  }
};

// A very simple RAII helper to lock and unlock a Mutex
struct ScopedLock {
  ScopedLock(Mutex* m) : _m(m) { _m->Lock(); }
  ~ScopedLock() { _m->Unlock(); }

 private:
  Mutex* _m;
};

// Profiling definitions. Two paths: when profiling is enabled,
// and when profiling is disabled.
#ifdef GEMMLOWP_PROFILING
// This code path is when profiling is enabled.

// A pseudo-call-stack. Contrary to a real call-stack, this only
// contains pointers to literal strings that were manually entered
// in the instrumented code (see ScopedProfilingLabel).
struct ProfilingStack {
  static const std::size_t kMaxSize = 30;
  typedef const char* LabelsArrayType[kMaxSize];
  LabelsArrayType labels;
  std::size_t size;
  Mutex* lock;

  ProfilingStack() { memset(this, 0, sizeof(ProfilingStack)); }
  ~ProfilingStack() { delete lock; }

  void Push(const char* label) {
    ScopedLock sl(lock);
    ReleaseBuildAssertion(size < kMaxSize, "ProfilingStack overflow");
    labels[size] = label;
    size++;
  }

  void Pop() {
    ScopedLock sl(lock);
    ReleaseBuildAssertion(size > 0, "ProfilingStack underflow");
    size--;
  }

  void UpdateTop(const char* new_label) {
    ScopedLock sl(lock);
    assert(size);
    labels[size - 1] = new_label;
  }

  ProfilingStack& operator=(const ProfilingStack& other) {
    memcpy(this, &other, sizeof(ProfilingStack));
    return *this;
  }

  bool operator==(const ProfilingStack& other) const {
    return !memcmp(this, &other, sizeof(ProfilingStack));
  }
};

static_assert(
    !(sizeof(ProfilingStack) & (sizeof(ProfilingStack) - 1)),
    "ProfilingStack should have power-of-two size to fit in cache lines");

struct ThreadInfo;

// The global set of threads being profiled.
inline std::set<ThreadInfo*>& ThreadsUnderProfiling() {
  static std::set<ThreadInfo*> v;
  return v;
}

struct ThreadInfo {
  pthread_key_t key;  // used only to get a callback at thread exit.
  ProfilingStack stack;

  ThreadInfo() {
    pthread_key_create(&key, ThreadExitCallback);
    pthread_setspecific(key, this);
    stack.lock = new Mutex();
  }

  static void ThreadExitCallback(void* ptr) {
    ScopedLock sl(GlobalMutexes::Profiler());
    ThreadInfo* self = static_cast<ThreadInfo*>(ptr);
    ThreadsUnderProfiling().erase(self);
  }
};

inline ThreadInfo& ThreadLocalThreadInfo() {
  static pthread_key_t key;
  static auto DeleteThreadInfo = [](void* threadInfoPtr) {
    ThreadInfo* threadInfo = static_cast<ThreadInfo*>(threadInfoPtr);
    if (threadInfo) {
      delete threadInfo;
    }
  };

  // key_result is unused. The purpose of this 'static' local object is
  // to have its initializer (the pthread_key_create call) performed exactly
  // once, in a way that is guaranteed (since C++11) to be reentrant.
  static const int key_result = pthread_key_create(&key, DeleteThreadInfo);
  (void)key_result;

  ThreadInfo* threadInfo = static_cast<ThreadInfo*>(pthread_getspecific(key));
  if (!threadInfo) {
    threadInfo = new ThreadInfo();
    pthread_setspecific(key, threadInfo);
  }
  return *threadInfo;
}

// ScopedProfilingLabel is how one instruments code for profiling
// with this profiler. Construct local ScopedProfilingLabel variables,
// passing a literal string describing the local code. Profile
// samples will then be annotated with this label, while it is in scope
// (whence the name --- also known as RAII).
// See the example in profiler.h.
class ScopedProfilingLabel {
  ProfilingStack* profiling_stack_;

 public:
  explicit ScopedProfilingLabel(const char* label)
      : profiling_stack_(&ThreadLocalThreadInfo().stack) {
    profiling_stack_->Push(label);
  }

  ~ScopedProfilingLabel() { profiling_stack_->Pop(); }

  void Update(const char* new_label) { profiling_stack_->UpdateTop(new_label); }
};

// To be called once on each thread to be profiled.
inline void RegisterCurrentThreadForProfiling() {
  ScopedLock sl(GlobalMutexes::Profiler());
  ThreadsUnderProfiling().insert(&ThreadLocalThreadInfo());
}

#else  // not GEMMLOWP_PROFILING
// This code path is when profiling is disabled.

// This empty definition of ScopedProfilingLabel ensures that
// it has zero runtime overhead when profiling is disabled.
struct ScopedProfilingLabel {
  explicit ScopedProfilingLabel(const char*) {}
  void Update(const char*) {}
};

inline void RegisterCurrentThreadForProfiling() {}

#endif

}  // end namespace gemmlowp

#endif  // GEMMLOWP_PROFILING_INSTRUMENTATION_H_


text:
package org.apache.ignite.ml.math.impls.matrix;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Collection;
import java.util.Set;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.internal.util.IgniteUtils;
import org.apache.ignite.ml.math.Matrix;
import org.apache.ignite.ml.math.distributed.DistributedStorage;
import org.apache.ignite.ml.math.distributed.keys.impl.BlockMatrixKey;
import org.apache.ignite.ml.math.exceptions.UnsupportedOperationException;
import org.apache.ignite.ml.math.impls.MathTestConstants;
import org.apache.ignite.ml.math.impls.storage.matrix.BlockMatrixStorage;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.apache.ignite.testframework.junits.common.GridCommonTest;

import static org.apache.ignite.ml.math.impls.MathTestConstants.UNEXPECTED_VAL;

/**
 * Tests for {@link SparseBlockDistributedMatrix}.
 */
@GridCommonTest(group = "Distributed Models")
public class SparseDistributedBlockMatrixTest extends GridCommonAbstractTest {
    /** Number of nodes in grid */
    private static final int NODE_COUNT = 3;
    /** Precision. */
    private static final double PRECISION = 0.0;
    /** Grid instance. */
    private Ignite ignite;
    /** Matrix rows */
    private final int rows = MathTestConstants.STORAGE_SIZE;
    /** Matrix cols */
    private final int cols = MathTestConstants.STORAGE_SIZE;
    /** Matrix for tests */
    private SparseBlockDistributedMatrix cacheMatrix;

    /**
     * Default constructor.
     */
    public SparseDistributedBlockMatrixTest() {
        super(false);
    }

    /** {@inheritDoc} */
    @Override protected void beforeTestsStarted() throws Exception {
        for (int i = 1; i <= NODE_COUNT; i++)
            startGrid(i);
    }

    /** {@inheritDoc} */
    @Override protected void afterTestsStopped() throws Exception {
        stopAllGrids();
    }

    /**
     * {@inheritDoc}
     */
    @Override protected void beforeTest() throws Exception {
        ignite = grid(NODE_COUNT);

        ignite.configuration().setPeerClassLoadingEnabled(true);
    }

    /** {@inheritDoc} */
    @Override protected void afterTest() throws Exception {
        if (cacheMatrix != null) {
            cacheMatrix.destroy();
            cacheMatrix = null;
        }
    }

    /** */
    public void testGetSet() throws Exception {
        IgniteUtils.setCurrentIgniteName(ignite.configuration().getIgniteInstanceName());

        cacheMatrix = new SparseBlockDistributedMatrix(rows, cols);

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                double v = Math.random();
                cacheMatrix.set(i, j, v);

                assertEquals("Unexpected value for matrix element["+ i +" " + j + "]", v, cacheMatrix.get(i, j), PRECISION);
            }
        }
    }

    /** */
    public void testExternalize() throws IOException, ClassNotFoundException {
        IgniteUtils.setCurrentIgniteName(ignite.configuration().getIgniteInstanceName());

        cacheMatrix = new SparseBlockDistributedMatrix(rows, cols);

        cacheMatrix.set(1, 1, 1.0);

        ByteArrayOutputStream byteArrOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objOutputStream = new ObjectOutputStream(byteArrOutputStream);

        objOutputStream.writeObject(cacheMatrix);

        ByteArrayInputStream byteArrInputStream = new ByteArrayInputStream(byteArrOutputStream.toByteArray());
        ObjectInputStream objInputStream = new ObjectInputStream(byteArrInputStream);

        SparseBlockDistributedMatrix objRestored = (SparseBlockDistributedMatrix)objInputStream.readObject();

        assertTrue(MathTestConstants.VAL_NOT_EQUALS, cacheMatrix.equals(objRestored));
        assertEquals(MathTestConstants.VAL_NOT_EQUALS, objRestored.get(1, 1), 1.0, PRECISION);
    }

    /** Test simple math. */
    public void testMath() {
        IgniteUtils.setCurrentIgniteName(ignite.configuration().getIgniteInstanceName());

        cacheMatrix = new SparseBlockDistributedMatrix(rows, cols);
        initMtx(cacheMatrix);

        cacheMatrix.assign(2.0);
        for (int i = 0; i < cacheMatrix.rowSize(); i++)
            for (int j = 0; j < cacheMatrix.columnSize(); j++)
                assertEquals(UNEXPECTED_VAL, 2.0, cacheMatrix.get(i, j), PRECISION);

        cacheMatrix.plus(3.0);
        for (int i = 0; i < cacheMatrix.rowSize(); i++)
            for (int j = 0; j < cacheMatrix.columnSize(); j++)
                assertEquals(UNEXPECTED_VAL, 5.0, cacheMatrix.get(i, j), PRECISION);

        cacheMatrix.times(2.0);
        for (int i = 0; i < cacheMatrix.rowSize(); i++)
            for (int j = 0; j < cacheMatrix.columnSize(); j++)
                assertEquals(UNEXPECTED_VAL, 10.0, cacheMatrix.get(i, j), PRECISION);

        cacheMatrix.divide(10.0);
        for (int i = 0; i < cacheMatrix.rowSize(); i++)
            for (int j = 0; j < cacheMatrix.columnSize(); j++)
                assertEquals(UNEXPECTED_VAL, 1.0, cacheMatrix.get(i, j), PRECISION);

        assertEquals(UNEXPECTED_VAL, cacheMatrix.rowSize() * cacheMatrix.columnSize(), cacheMatrix.sum(), PRECISION);
    }

    /** */
    public void testMinMax() {
        IgniteUtils.setCurrentIgniteName(ignite.configuration().getIgniteInstanceName());

        cacheMatrix = new SparseBlockDistributedMatrix(rows, cols);

        for (int i = 0; i < cacheMatrix.rowSize(); i++)
            for (int j = 0; j < cacheMatrix.columnSize(); j++)
                cacheMatrix.set(i, j, i * cols + j + 1);

        assertEquals(UNEXPECTED_VAL, 1.0, cacheMatrix.minValue(), PRECISION);
        assertEquals(UNEXPECTED_VAL, rows * cols, cacheMatrix.maxValue(), PRECISION);

        for (int i = 0; i < cacheMatrix.rowSize(); i++)
            for (int j = 0; j < cacheMatrix.columnSize(); j++)
                cacheMatrix.set(i, j, -1.0 * (i * cols + j + 1));

        assertEquals(UNEXPECTED_VAL, -rows * cols, cacheMatrix.minValue(), PRECISION);
        assertEquals(UNEXPECTED_VAL, -1.0, cacheMatrix.maxValue(), PRECISION);

        for (int i = 0; i < cacheMatrix.rowSize(); i++)
            for (int j = 0; j < cacheMatrix.columnSize(); j++)
                cacheMatrix.set(i, j, i * cols + j);

        assertEquals(UNEXPECTED_VAL, 0.0, cacheMatrix.minValue(), PRECISION);
        assertEquals(UNEXPECTED_VAL, rows * cols - 1.0, cacheMatrix.maxValue(), PRECISION);
    }

    /** */
    public void testMap() {
        IgniteUtils.setCurrentIgniteName(ignite.configuration().getIgniteInstanceName());

        cacheMatrix = new SparseBlockDistributedMatrix(rows, cols);
        initMtx(cacheMatrix);

        cacheMatrix.map(i -> 100.0);
        for (int i = 0; i < cacheMatrix.rowSize(); i++)
            for (int j = 0; j < cacheMatrix.columnSize(); j++)
                assertEquals(UNEXPECTED_VAL, 100.0, cacheMatrix.get(i, j), PRECISION);
    }

    /** */
    public void testCopy() {
        IgniteUtils.setCurrentIgniteName(ignite.configuration().getIgniteInstanceName());

        cacheMatrix = new SparseBlockDistributedMatrix(rows, cols);

        try {
            cacheMatrix.copy();
            fail("UnsupportedOperationException expected.");
        }
        catch (UnsupportedOperationException e) {
            return;
        }
        fail("UnsupportedOperationException expected.");
    }

    /** */
    public void testCacheBehaviour(){
        IgniteUtils.setCurrentIgniteName(ignite.configuration().getIgniteInstanceName());

        SparseBlockDistributedMatrix cacheMatrix1 = new SparseBlockDistributedMatrix(rows, cols);
        SparseBlockDistributedMatrix cacheMatrix2 = new SparseBlockDistributedMatrix(rows, cols);

        initMtx(cacheMatrix1);
        initMtx(cacheMatrix2);

        Collection<String> cacheNames = ignite.cacheNames();

        assert cacheNames.contains(((DistributedStorage)cacheMatrix1.getStorage()).cacheName());

        IgniteCache<BlockMatrixKey, Object> cache = ignite.getOrCreateCache(((DistributedStorage)cacheMatrix1.getStorage()).cacheName());

        Set<BlockMatrixKey> keySet1 = buildKeySet(cacheMatrix1);
        Set<BlockMatrixKey> keySet2 = buildKeySet(cacheMatrix2);

        assert cache.containsKeys(keySet1);
        assert cache.containsKeys(keySet2);

        cacheMatrix2.destroy();

        assert cache.containsKeys(keySet1);
        assert !cache.containsKeys(keySet2);

        cacheMatrix1.destroy();

        assert !cache.containsKeys(keySet1);
    }

    /** */
    public void testLike() {
        IgniteUtils.setCurrentIgniteName(ignite.configuration().getIgniteInstanceName());

        cacheMatrix = new SparseBlockDistributedMatrix(rows, cols);

        assertNotNull(cacheMatrix.like(1, 1));
    }

    /** */
    public void testLikeVector() {
        IgniteUtils.setCurrentIgniteName(ignite.configuration().getIgniteInstanceName());

        cacheMatrix = new SparseBlockDistributedMatrix(rows, cols);

        try {
            cacheMatrix.likeVector(1);
            fail("UnsupportedOperationException expected.");
        }
        catch (UnsupportedOperationException e) {
            return;
        }
        fail("UnsupportedOperationException expected.");
    }

    /**
     * Simple test for two square matrices.
     */
    public void testSquareMatrixTimes(){
        IgniteUtils.setCurrentIgniteName(ignite.configuration().getIgniteInstanceName());

        int size = 100;

        Matrix cacheMatrix1 = new SparseBlockDistributedMatrix(size, size);
        Matrix cacheMatrix2 = new SparseBlockDistributedMatrix(size, size);

        for (int i = 0; i < size; i++) {
            cacheMatrix1.setX(i, i, i);
            cacheMatrix2.setX(i, i, i);
        }

        Matrix res = cacheMatrix1.times(cacheMatrix2);

        BlockMatrixStorage storage = (BlockMatrixStorage)res.getStorage();

        for(int i = 0; i < size; i++)
            for(int j = 0; j < size; j++)
                if (i == j)
                    assertEquals(UNEXPECTED_VAL + " for "+ i +":"+ j, i * i, res.get(i, j), PRECISION);
                else
                    assertEquals(UNEXPECTED_VAL + " for "+ i +":"+ j, 0, res.get(i, j), PRECISION);
    }

    /**
     *
     */
    public void testNonSquareMatrixTimes(){
        IgniteUtils.setCurrentIgniteName(ignite.configuration().getIgniteInstanceName());

        int size = BlockEntry.MAX_BLOCK_SIZE + 1;
        int size2 = BlockEntry.MAX_BLOCK_SIZE * 2 + 1;

        Matrix cacheMatrix1 = new SparseBlockDistributedMatrix(size2, size);
        Matrix cacheMatrix2 = new SparseBlockDistributedMatrix(size, size2);

        for (int i = 0; i < size; i++) {
            cacheMatrix1.setX(i, i, i);
            cacheMatrix2.setX(i, i, i);
        }

        Matrix res = cacheMatrix1.times(cacheMatrix2);

        for(int i = 0; i < size; i++)
            for(int j = 0; j < size; j++)
                if (i == j)
                    assertEquals(UNEXPECTED_VAL + " for "+ i +":"+ j, i * i, res.get(i, j), PRECISION);
                else
                    assertEquals(UNEXPECTED_VAL + " for "+ i +":"+ j, 0, res.get(i, j), PRECISION);
    }

    /**
     *
     */
    public void testNonSquareMatrixTimes2(){
        IgniteUtils.setCurrentIgniteName(ignite.configuration().getIgniteInstanceName());

        int size = BlockEntry.MAX_BLOCK_SIZE + 1;
        int size2 = BlockEntry.MAX_BLOCK_SIZE * 2 + 1;

        Matrix cacheMatrix1 = new SparseBlockDistributedMatrix(size, size2);
        Matrix cacheMatrix2 = new SparseBlockDistributedMatrix(size2, size);

        for (int i = 0; i < size; i++) {
            cacheMatrix1.setX(i, i, i);
            cacheMatrix2.setX(i, i, i);
        }

        Matrix res = cacheMatrix1.times(cacheMatrix2);

        for(int i = 0; i < size; i++)
            for(int j = 0; j < size; j++)
                if (i == j)
                    assertEquals(UNEXPECTED_VAL + " for "+ i +":"+ j, i * i, res.get(i, j), PRECISION);
                else
                    assertEquals(UNEXPECTED_VAL + " for "+ i +":"+ j, 0, res.get(i, j), PRECISION);
    }

    /** */
    private void initMtx(Matrix m) {
        for (int i = 0; i < m.rowSize(); i++)
            for (int j = 0; j < m.columnSize(); j++)
                m.set(i, j, 1.0);
    }

    /** Build key set for SparseBlockDistributedMatrix. */
    private Set<BlockMatrixKey> buildKeySet(SparseBlockDistributedMatrix m){
        BlockMatrixStorage storage = (BlockMatrixStorage)m.getStorage();

        return storage.getAllKeys();
    }
}


text:
<?php
use yii\helpers\Html;

$user = Yii::$app->user->identity;

$name = $user->profile->name==''?$user->username:$user->profile->name;
?>

        <img src="http://gravatar.com/avatar/<?= $user->profile->gravatar_id ?>?s=160" class="img-circle" alt="<?=$name?>"/>

<?= $name ?>

         Online


text:
static void NSObject_to_lua(lua_State* L, id obj) {
    if (obj == nil || [obj isEqual: [NSNull null]]) { lua_pushnil(L); }
    else if ([obj isKindOfClass: [NSNumber class]]) {
        NSNumber* number = obj;
        if (number == (id)kCFBooleanTrue)
            lua_pushboolean(L, YES);
        else if (number == (id)kCFBooleanFalse)
            lua_pushboolean(L, NO);
        else if (CFNumberIsFloatType((CFNumberRef)number))
            lua_pushnumber(L, [number doubleValue]);
        else
            lua_pushinteger(L, [number intValue]);
    } else if ([obj isKindOfClass: [NSString class]]) {
        NSString* string = obj;
        lua_pushstring(L, [string UTF8String]);
    } else {
        lua_pushstring(L, [[NSString stringWithFormat:@"<Object> : %@", obj] UTF8String]) ;
    }
}

static int _push_dict_key_value(lua_State* L, NSDictionary* dict, NSString* key) {
    id value = [dict objectForKey:key];
    NSObject_to_lua(L, value);
    return 1;
}

// Gets battery info from IOPM API.
NSDictionary* get_iopm_battery_info() {
    mach_port_t masterPort;
    CFArrayRef batteryInfo;

    if (kIOReturnSuccess == IOMasterPort(MACH_PORT_NULL, &masterPort) &&
        kIOReturnSuccess == IOPMCopyBatteryInfo(masterPort, &batteryInfo) &&
        CFArrayGetCount(batteryInfo))
    {
        CFDictionaryRef battery = CFDictionaryCreateCopy(NULL, CFArrayGetValueAtIndex(batteryInfo, 0));
        CFRelease(batteryInfo);
        return (__bridge_transfer NSDictionary*) battery;
    }
    return NULL;
}

// Get battery info from IOPS API.
NSDictionary* get_iops_battery_info() {
    CFTypeRef info = IOPSCopyPowerSourcesInfo();

    if (info == NULL)
        return NULL;

    CFArrayRef list = IOPSCopyPowerSourcesList(info);

    // Nothing we care about here...
    if (list == NULL || !CFArrayGetCount(list)) {
        if (list)
            CFRelease(list);

        CFRelease(info);
        return NULL;
    }

    CFDictionaryRef battery = CFDictionaryCreateCopy(NULL, IOPSGetPowerSourceDescription(info, CFArrayGetValueAtIndex(list, 0)));

    // Battery is released by ARC transfer.
    CFRelease(list);
    CFRelease(info);

    return (__bridge_transfer NSDictionary* ) battery;
}

// Get battery info from IOPMPS Apple Smart Battery API.
NSDictionary* get_iopmps_battery_info() {
    io_registry_entry_t entry = 0;
    entry = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceNameMatching("AppleSmartBattery"));
    if (entry == IO_OBJECT_NULL)
        return nil;

    CFMutableDictionaryRef battery;
    IORegistryEntryCreateCFProperties(entry, &battery, NULL, 0);
    return (__bridge_transfer NSDictionary *) battery;
}

/// hs.battery.cycles() -> number
/// Function
/// Returns the number of discharge cycles of the battery
///
/// Parameters:
///  * None
///
/// Returns:
///  * The number of cycles
///
/// Notes:
///  * One cycle is a full discharge of the battery, followed by a full charge. This may also be an aggregate of many smaller discharge-then-charge cycles (e.g. 10 iterations of discharging the battery from 100% to 90% and then charging back to 100% each time, is considered to be one cycle)
static int battery_cycles(lua_State *L) {
    return _push_dict_key_value(L, get_iopm_battery_info(), @kIOBatteryCycleCountKey);
}

/// hs.battery.name() -> string
/// Function
/// Returns the name of the battery
///
/// Parameters:
///  * None
///
/// Returns:
///  * A string containing the name of the battery
static int battery_name(lua_State *L) {
    return _push_dict_key_value(L, get_iops_battery_info(), @kIOPSNameKey);
}

/// hs.battery.maxCapacity() -> number
/// Function
/// Returns the maximum capacity of the battery in mAh
///
/// Parameters:
///  * None
///
/// Returns:
///  * A number containing the observed maximum capacity of the battery in mAh
///
/// Notes:
///  * This may exceed the value of `hs.battery.designCapacity()` due to small variations in the production chemistry vs the design
static int battery_maxcapacity(lua_State *L) {
    return _push_dict_key_value(L, get_iopm_battery_info(), @kIOBatteryCapacityKey);
}

/// hs.battery.capacity() -> number
/// Function
/// Returns the current capacity of the battery in mAh
///
/// Parameters:
///  * None
///
/// Returns:
///  * A number containing the current capacity of the battery in mAh
///
/// Notes:
///  * This is the measure of how charged the battery is, vs the value of `hs.battery.maxCapacity()`
static int battery_capacity(lua_State *L) {
    return _push_dict_key_value(L, get_iopm_battery_info(), @kIOBatteryCurrentChargeKey);
}

/// hs.battery.designCapacity() -> number
/// Function
/// Returns the design capacity of the battery in mAh.
///
/// Parameters:
///  * None
///
/// Returns:
///  * A number containing the rated maximum capacity of the battery
static int battery_designcapacity(lua_State *L) {
    return _push_dict_key_value(L, get_iopmps_battery_info(), @kIOPMPSDesignCapacityKey);
}

/// hs.battery.voltage() -> number
/// Function
/// Returns the current voltage of the battery in mV
///
/// Parameters:
///  * None
///
/// Returns:
///  * A number containing the current voltage of the battery
static int battery_voltage(lua_State *L) {
    return _push_dict_key_value(L, get_iopm_battery_info(), @kIOBatteryVoltageKey);
}

/// hs.battery.amperage() -> number
/// Function
/// Returns the amount of current flowing through the battery, in mAh
///
/// Parameters:
///  * None
///
/// Returns:
///  * A number containing the amount of current flowing through the battery. The value may be:
///   * Less than zero if the battery is being discharged (i.e. the computer is running on battery power)
///   * Zero if the battery is being neither charged nor discharged
///   * Greater than zero if the battery is being charged
static int battery_amperage(lua_State *L) {
    return _push_dict_key_value(L, get_iopm_battery_info(), @kIOBatteryAmperageKey);
}

/// hs.battery.watts() -> number
/// Function
/// Returns the power entering or leaving the battery, in W
///
/// Parameters:
///  * None
///
/// Returns:
///  * A number containing the rate of energy conversion in the battery. The value may be:
///   * Less than zero if the battery is being discharged (i.e. the computer is running on battery power)
///   * Zero if the battery is being neither charged nor discharged
///   * Greater than zero if the battery is being charged
static int battery_watts(lua_State *L) {
    NSDictionary* battery = get_iopm_battery_info();

    NSNumber *amperage = [battery objectForKey:@kIOBatteryVoltageKey];
    NSNumber *voltage = [battery objectForKey:@kIOBatteryAmperageKey];

    if (amperage && voltage) {
        double battery_wattage = ([amperage doubleValue] * [voltage doubleValue]) / 1000000;
        lua_pushnumber(L, battery_wattage);
    } else
        lua_pushnil(L);

    return 1;
}

/// hs.battery.health() -> string
/// Function
/// Returns the health status of the battery.
///
/// Parameters:
///  * None
///
/// Returns:
///  * A string containing one of {Good, Fair, Poor}, as determined by the Apple Smart Battery controller
static int battery_health(lua_State *L) {
    return _push_dict_key_value(L, get_iops_battery_info(), @kIOPSBatteryHealthKey);
}

/// hs.battery.healthCondition() -> string or nil
/// Function
/// Returns the health condition status of the battery.
///
/// Parameters:
///  * None
///
/// Returns:
///  * Nil if there are no health conditions to report, or a string containing either:
///   * "Check Battery"
///   * "Permanent Battery Failure"
static int battery_healthcondition(lua_State *L) {
    return _push_dict_key_value(L, get_iops_battery_info(), @kIOPSBatteryHealthConditionKey);
}

/// hs.battery.percentage() -> number
/// Function
/// Returns the current percentage of battery charge
///
/// Parameters:
///  * None
///
/// Returns:
///  * A number containing the percentage of battery charge
static int battery_percentage(lua_State *L) {
    NSDictionary* battery = get_iops_battery_info();

    // IOPS Gives the proper percentage reading, that the OS displays...
    // IOPM... oddly enough... is a few percentage points off.
    NSNumber *maxCapacity = [battery objectForKey:@kIOPSMaxCapacityKey];
    NSNumber *currentCapacity = [battery objectForKey:@kIOPSCurrentCapacityKey];

    if (maxCapacity && currentCapacity) {
        double battery_percentage = ([currentCapacity doubleValue] / [maxCapacity doubleValue]) * 100;
        lua_pushnumber(L, battery_percentage);
    } else
        lua_pushnil(L);

    return 1;
}

/// hs.battery.timeRemaining() -> number
/// Function
/// Returns the battery life remaining, in minutes
///
/// Parameters:
///  * None
///
/// Returns:
///  * A number containing the minutes of battery life remaining. The value may be:
///   * Greater than zero to indicate the number of minutes remaining
///   * -1 if the remaining battery life is still being calculated
///   * -2 if there is unlimited time remaining (i.e. the system is on AC power)
static int battery_timeremaining(lua_State* L) {
    CFTimeInterval remaining = IOPSGetTimeRemainingEstimate();

    if (remaining > 0)
        remaining /= 60;

    lua_pushnumber(L, remaining);
    return 1;
}

/// hs.battery.timeToFullCharge() -> number
/// Function
/// Returns the time remaining for the battery to be fully charged, in minutes
///
/// Parameters:
///  * None
///
/// Returns:
///  * A number containing the time (in minutes) remaining for the battery to be fully charged, or -1 if the remaining time is still being calculated
static int battery_timetofullcharge(lua_State* L) {
    return _push_dict_key_value(L, get_iops_battery_info(), @kIOPSTimeToFullChargeKey);
}

/// hs.battery.isCharging() -> boolean
/// Function
/// Returns the charging state of the battery
///
/// Parameters:
///  * None
///
/// Returns:
///  * True if the battery is being charged, false if not
static int battery_ischarging(lua_State* L) {
    return _push_dict_key_value(L, get_iops_battery_info(), @kIOPSIsChargingKey);
}

/// hs.battery.isCharged() -> boolean
/// Function
/// Returns the charged state of the battery
///
/// Parameters:
///  * None
///
/// Returns:
///  * True if the battery is charged, false if not
static int battery_ischarged(lua_State* L) {
    return _push_dict_key_value(L, get_iops_battery_info(), @kIOPSIsChargedKey);
}

/// hs.battery.isFinishingCharge() -> boolean or string
/// Function
/// Returns true if battery is finishing its charge
///
/// Parameters:
///  * None
///
/// Returns:
///  * True if the battery is in its final charging state (i.e. trickle charging), false if not, or "n/a" if the battery is not charging at all
static int battery_isfinishingcharge(lua_State* L) {
    return _push_dict_key_value(L, get_iops_battery_info(), @kIOPSIsFinishingChargeKey);
}

/// hs.battery.powerSource() -> string
/// Function
/// Returns current source of power
///
/// Parameters:
///  * None
///
/// Returns:
///  * A string containing one of {AC Power, Battery Power, Off Line}.
static int battery_powersource(lua_State* L) {
    return _push_dict_key_value(L, get_iops_battery_info(), @kIOPSPowerSourceStateKey);
}

/// hs.battery.psuSerial() -> integer
/// Function
/// Returns the serial number of the attached power supply, if present
///
/// Parameters:
///  * None
///
/// Returns:
///  * An integer containing the power supply's serial number, or 0 if no serial can be found
static int battery_psuSerial(lua_State* L) {
    int serial = 0;

    CFDictionaryRef psuInfo = IOPSCopyExternalPowerAdapterDetails();
    if (psuInfo) {
        NSNumber *serialNumber = (__bridge NSNumber *)CFDictionaryGetValue(psuInfo, CFSTR(kIOPSPowerAdapterSerialNumberKey));
        if (serialNumber) {
            serial = [serialNumber intValue];
        }
        CFRelease(psuInfo);
    }

    lua_pushinteger(L, serial);
    return 1;
}

static const luaL_Reg battery_lib[] = {
    {"cycles", battery_cycles},
    {"name", battery_name},
    {"maxCapacity", battery_maxcapacity},
    {"capacity", battery_capacity},
    {"designCapacity", battery_designcapacity},
    {"percentage", battery_percentage},
    {"voltage", battery_voltage},
    {"amperage", battery_amperage},
    {"watts", battery_watts},
    {"health", battery_health},
    {"healthCondition", battery_healthcondition},
    {"timeRemaining", battery_timeremaining},
    {"timeToFullCharge", battery_timetofullcharge},
    {"isCharging", battery_ischarging},
    {"isCharged", battery_ischarged},
    {"isFinishingCharge", battery_isfinishingcharge},
    {"powerSource", battery_powersource},
    {"psuSerial", battery_psuSerial},
    {NULL, NULL}
};

int luaopen_hs_battery_internal(lua_State* L) {
    luaL_newlib(L, battery_lib);
    return 1;
}


text:
Template.gameLostPage.helpers({

  playerName: function(){
    return Meteor.users.findOne(Meteor.userId()).username;
  }

});


text:
<?xml version="1.0" encoding="utf-8"?>

 <FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#aeaeae">

    <android.support.v7.widget.CardView
        android:id="@+id/card"
        android:layout_width="350dp"
        android:layout_height="300dp"
        android:layout_gravity="center"
        android:background="@color/white"
        app:cardCornerRadius="10dp"
        app:cardElevation="12dp"
        app:cardUseCompatPadding="true">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
            <ImageView
                android:id="@+id/cardImage"
                android:layout_width="fill_parent"
                android:layout_height="150dp"
                android:scaleType="fitXY" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="30dp"
                android:orientation="horizontal">
                <TextView
                    android:id="@+id/cardTitle"
                    android:layout_width="250dp"
                    android:layout_height="20dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    android:layout_marginTop="10dp"
                    android:textStyle="bold" />
                <ImageView
                    android:id="@+id/favBtn"
                    android:layout_width="20dp"
                    android:layout_height="20dp"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="10dp"
                    android:layout_marginTop="10dp" />
            </LinearLayout>
            <TextView
                android:id="@+id/cardContent"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="30dp" />
        </LinearLayout>
    </android.support.v7.widget.CardView>
</FrameLayout>


text:
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

int main()
{
	// Read input image
	cv::Mat image= cv::imread("../boldt.jpg",0);
	if (!image.data)
		return 0;

    // Display the image
	cv::namedWindow("Original Image");
	cv::imshow("Original Image",image);

	// Blur the image
	cv::Mat result;
	cv::GaussianBlur(image,result,cv::Size(5,5),1.5);

    // Display the blurred image
	cv::namedWindow("Gaussian filtered Image");
	cv::imshow("Gaussian filtered Image",result);

	// Get the gaussian kernel (1.5)
	cv::Mat gauss= cv::getGaussianKernel(9,1.5,CV_32F);

	// Display kernel values
	cv::Mat_<float>::const_iterator it= gauss.begin<float>();
	cv::Mat_<float>::const_iterator itend= gauss.end<float>();
	std::cout << "[";
	for ( ; it!= itend; ++it) {
		std::cout << *it << " ";
	}
	std::cout << "]" << std::endl;

	// Get the gaussian kernel (0.5)
	gauss= cv::getGaussianKernel(9,0.5,CV_32F);

	// Display kernel values
	it= gauss.begin<float>();
	itend= gauss.end<float>();
	std::cout << "[";
	for ( ; it!= itend; ++it) {
		std::cout << *it << " ";
	}
	std::cout << "]" << std::endl;

	// Get the gaussian kernel (2.5)
	gauss= cv::getGaussianKernel(9,2.5,CV_32F);

	// Display kernel values
	it= gauss.begin<float>();
	itend= gauss.end<float>();
	std::cout << "[";
	for ( ; it!= itend; ++it) {
		std::cout << *it << " ";
	}
	std::cout << "]" << std::endl;

	// Get the Deriv kernel (2.5)
	cv::Mat kx, ky;
    cv::getDerivKernels(kx,ky,2,2,7,true);

	// Display kernel values
	cv::Mat_<float>::const_iterator kit= kx.begin<float>();
	cv::Mat_<float>::const_iterator kitend= kx.end<float>();
	std::cout << "[";
	for ( ; kit!= kitend; ++kit) {
		std::cout << *kit << " ";
	}
	std::cout << "]" << std::endl;

	// Blur the image with a mean filter
	cv::blur(image,result,cv::Size(5,5));

    // Display the blurred image
	cv::namedWindow("Mean filtered Image");
	cv::imshow("Mean filtered Image",result);

	// Read input image with salt&pepper noise
	image= cv::imread("../salted.bmp",0);
	if (!image.data)
		return 0;

    // Display the S&P image
	cv::namedWindow("S&P Image");
	cv::imshow("S&P Image",image);

	// Blur the image with a mean filter
	cv::blur(image,result,cv::Size(5,5));

    // Display the blurred image
	cv::namedWindow("Mean filtered S&P Image");
	cv::imshow("Mean filtered S&P Image",result);

	// Applying a median filter
	cv::medianBlur(image,result,5);

    // Display the blurred image
	cv::namedWindow("Median filtered S&P Image");
	cv::imshow("Median filtered S&P Image",result);

	// Reduce by 4 the size of the image (the wrong way)
	image= cv::imread("../boldt.jpg",0);
	cv::Mat reduced(image.rows/2,image.cols/2,CV_8U);

	for (int i=0; i<reduced.rows; i++)
		for (int j=0; j<reduced.cols; j++)
			reduced.at<uchar>(i,j)= image.at<uchar>(i*2,j*2);

    // Display the reduced image
	cv::namedWindow("Badly reduced Image");
	cv::imshow("Badly reduced Image",reduced);

	cv::waitKey();
	return 0;
}


text:
import { Controller } from 'angular-ecmascript/module-helpers';

export default class MainCtrl extends Controller {
  constructor() {
    super(...arguments);
  }
}

MainCtrl.$name = 'AboutCtrl';
MainCtrl.$inject = [];


text:
namespace chromeos {

namespace {

class VirtualFileProviderClientImpl : public VirtualFileProviderClient {
 public:
  VirtualFileProviderClientImpl() {}
  ~VirtualFileProviderClientImpl() override = default;

  // VirtualFileProviderClient override:
  void OpenFile(int64_t size, OpenFileCallback callback) override {
    dbus::MethodCall method_call(
        virtual_file_provider::kVirtualFileProviderInterface,
        virtual_file_provider::kOpenFileMethod);
    dbus::MessageWriter writer(&method_call);
    writer.AppendInt64(size);
    proxy_->CallMethod(
        &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
        base::BindOnce(&VirtualFileProviderClientImpl::OnOpenFile,
                       weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
  }

 protected:
  // DBusClient override.
  void Init(dbus::Bus* bus) override {
    proxy_ = bus->GetObjectProxy(
        virtual_file_provider::kVirtualFileProviderServiceName,
        dbus::ObjectPath(
            virtual_file_provider::kVirtualFileProviderServicePath));
  }

 private:
  // Runs the callback with OpenFile method call result.
  void OnOpenFile(OpenFileCallback callback, dbus::Response* response) {
    if (!response) {
      std::move(callback).Run(std::string(), base::ScopedFD());
      return;
    }
    dbus::MessageReader reader(response);
    std::string id;
    base::ScopedFD fd;
    if (!reader.PopString(&id) || !reader.PopFileDescriptor(&fd)) {
      LOG(ERROR) << "Invalid method call result.";
      std::move(callback).Run(std::string(), base::ScopedFD());
      return;
    }
    std::move(callback).Run(id, std::move(fd));
  }

  dbus::ObjectProxy* proxy_ = nullptr;

  base::WeakPtrFactory<VirtualFileProviderClientImpl> weak_ptr_factory_{this};

  DISALLOW_COPY_AND_ASSIGN(VirtualFileProviderClientImpl);
};

}  // namespace

VirtualFileProviderClient::VirtualFileProviderClient() = default;

VirtualFileProviderClient::~VirtualFileProviderClient() = default;

// static
std::unique_ptr<VirtualFileProviderClient> VirtualFileProviderClient::Create() {
  return std::make_unique<VirtualFileProviderClientImpl>();
}

}  // namespace chromeos


text:
package de.hshannover.f4.trust.visitmeta.dataservice.graphservice;

import java.util.Map;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;

import de.hshannover.f4.trust.visitmeta.dataservice.util.SimpleNamespaceContext;
import de.hshannover.f4.trust.visitmeta.interfaces.GraphFilter;
import de.hshannover.f4.trust.visitmeta.interfaces.Identifier;

public class GraphFilterImpl implements GraphFilter {

	private Identifier mStartIdentifier;
	private int mMaxDepth;
	private boolean mMatchMetaEverything;
	private boolean mMatchMetaNothing;
	private boolean mMatchLinkEverything;
	private boolean mMatchLinkNothing;
	private XPathExpression mResultFilter;
	private XPathExpression mMatchLinks;

	private static XPathFactory xpathFactory;

	private static final Logger log = Logger.getLogger(GraphFilterImpl.class);

	public GraphFilterImpl(Identifier startIdentifier, String resultFilter,
			String matchLinks, int maxDepth, Map<String, String> prefixMap) {
		mStartIdentifier = startIdentifier;
		mMaxDepth = maxDepth;
		mMatchMetaNothing = resultFilter != null
				&& resultFilter.length() == 0;
		mMatchMetaEverything = resultFilter == null;

		mMatchLinkEverything = matchLinks != null
				&& matchLinks.length() == 0;
		mMatchLinkNothing = matchLinks == null;

		xpathFactory = XPathFactory.newInstance();
		XPath xpath = xpathFactory.newXPath();

		xpath.setNamespaceContext(new SimpleNamespaceContext(prefixMap));

		try {
			if (resultFilter != null
					&& resultFilter.length() > 0) {
				mResultFilter = xpath.compile(adaptFilterString(resultFilter));
			}
		} catch (XPathExpressionException e1) {
			log.error("Error at compiling result filter: "
					+ e1.getLocalizedMessage());
		}

		try {
			if (matchLinks != null
					&& matchLinks.length() > 0) {
				mMatchLinks = xpath.compile(adaptFilterString(matchLinks));
			}
		} catch (XPathExpressionException e1) {
			log.error("Error at compiling match-links filter: "
					+ e1.getLocalizedMessage());
		}
	}

	@Override
	public Identifier getStartIdentifier() {
		return mStartIdentifier;
	}

	@Override
	public int getMaxDepth() {
		return mMaxDepth;
	}

	@Override
	public boolean matchMeta(Document meta) {
		if (mMatchMetaEverything) {
			return true;
		}
		if (mMatchMetaNothing) {
			return false;
		}
		if (mResultFilter == null) {
			return false;
		}

		Object ret = null;
		try {
			ret = mResultFilter.evaluate(meta, XPathConstants.BOOLEAN);
		} catch (XPathExpressionException e) {
			return false;
		}
		return ((Boolean) ret).booleanValue();
	}

	@Override
	public boolean matchLink(Document meta) {
		if (mMatchLinkNothing) {
			return false;
		}
		if (mMatchLinkEverything) {
			return true;
		}
		if (mMatchLinks == null) {
			return false;
		}

		Object ret = null;
		try {
			ret = mMatchLinks.evaluate(meta, XPathConstants.BOOLEAN);
		} catch (XPathExpressionException e) {
			return false;
		}
		return ((Boolean) ret).booleanValue();
	}

	@Override
	public boolean matchEverything() {
		return mMatchMetaEverything;
	}

	@Override
	public boolean matchNothing() {
		return mMatchMetaNothing;
	}

	private String adaptFilterString(String fs) {
		String first = fs.replaceAll("^\\[", "*[");
		return first.replace(" [", " *[");
	}

}


text:
title: OnClientLoad
page_title: OnClientLoad | RadTileList for ASP.NET AJAX Documentation
description: OnClientLoad
slug: tilelist/client-side-programming/client-side-events/onclientload
tags: onclientload
published: True
position: 1
---

# OnClientLoad

The **OnClientLoad** event is raised when the RadTileList object is initialized. It can notify the developer that the control isavailable (e.g. to store a reference to its client-side object for later use). For example, event handlers can be attached dynamically through the [Client-side API]({%slug tilelist/client-side-programming/tilelist-object%}) of the RadTileList.

The event handler receives two arguments:

1. the [RadTileList object]({%slug tilelist/client-side-programming/tilelist-object%}) that fired the event

1. an empty event arguments object

The following example shows how to set the **SelectionMode** of a RadTileList in its **OnClientLoad** event.

````JavaScript
<telerik:RadTileList runat="server" ID="RadTileList1" OnClientLoad="OnClientLoad" AutoPostBack="true">
	<Groups>
		<telerik:TileGroup>
			<telerik:RadTextTile Name="Sample Text Tile" Text="Lorem ipsum dolor sit amet" Title-Text="Sample"></telerik:RadTextTile>
		</telerik:TileGroup>
	</Groups>
</telerik:RadTileList>

<telerik:RadCodeBlock runat="server" ID="RadCodeBlock1">
	<script type="text/javascript">
		function OnClientLoad(sender, args) {
			var tileList = $find("<%= RadTileList1.ClientID %>");

			tileList.set_selectionMode(Telerik.Web.UI.TileList.TileListSelectionMode.Single);
			//equivalent to tileList.set_selectionMode(2);

			//tileList.set_selectionMode(Telerik.Web.UI.TileList.TileListSelectionMode.None);
			//equivalent to tileList.set_selectionMode(1);

			//tileList.set_selectionMode(Telerik.Web.UI.TileList.TileListSelectionMode.Multiple);
			//equivalent to tileList.set_selectionMode(4);

			alert(String.format("Selection Mode set to: Single, ({0})", tileList.get_selectionMode()));
		}
	</script>
</telerik:RadCodeBlock>
````

The code snippet below demonstrates how an event handler can be attached in the **OnClientLoad** event of the **RadTileList**.

````JavaScript
		<telerik:RadTileList runat="server" ID="RadTileList1" OnClientLoad="OnClientLoad" AutoPostBack="false">
			<Groups>
				<telerik:TileGroup>
					<telerik:RadTextTile Name="Sample Text Tile" Text="Lorem ipsum dolor sit amet" Title-Text="Sample"></telerik:RadTextTile>
				</telerik:TileGroup>
			</Groups>
		</telerik:RadTileList>

		<script type="text/javascript">
			function OnClientLoad(tileList, args) {
				tileList.add_tileClicked(OnTileClickHandler);
			}

			function OnTileClickHandler() {
				alert('A Tile is clicked.');
			}
		</script>
````


text:
============================================
Rule ``phpdoc_var_annotation_correct_order``
============================================

``@var`` and ``@type`` annotations must have type and name in the correct order.

Examples
--------

Example #1
~~~~~~~~~~

.. code-block:: diff

   --- Original
   +++ New
   @@ -1,3 +1,3 @@
    <?php
   -/** @var $foo int */
   +/** @var int $foo */
    $foo = 2 + 2;

Rule sets
---------

The rule is part of the following rule set:

@PhpCsFixer
  Using the ``@PhpCsFixer`` rule set will enable the ``phpdoc_var_annotation_correct_order`` rule.


text:
/*
 * @(#)VersionString.java	1.8 10/03/24
 *
 * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Oracle or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */

package jnlp.sample.util;
import java.util.ArrayList;
import java.util.StringTokenizer;

/*
 * Utility class that knows to handle version strings
 * A version string is of the form:
 *
 *  (version-id ('+'?) ' ') *
 *
 */
public class VersionString {
    private ArrayList _versionIds;

    /** Constructs a VersionString object from string */
    public VersionString(String vs) {
	_versionIds = new ArrayList();
	if (vs != null) {
	    StringTokenizer st = new StringTokenizer(vs, " ", false);
	    while(st.hasMoreElements()) {
		// Note: The VersionID class takes care of a postfixed '+'
		_versionIds.add(new VersionID(st.nextToken()));
	    }
	}
    }

    /** Check if this VersionString object contains the VersionID m */
    public boolean contains(VersionID m) {
	for(int i = 0; i < _versionIds.size(); i++) {
	    VersionID vi = (VersionID)_versionIds.get(i);
	    boolean check = vi.match(m);
	    if (check) return true;
	}
	return false;
    }

    /** Check if this VersionString object contains the VersionID m, given as a string */
    public boolean contains(String versionid) {
	return contains(new VersionID(versionid));
    }

    /** Check if this VersionString object contains anything greater than m */
    public boolean containsGreaterThan(VersionID m) {
        for(int i = 0; i < _versionIds.size(); i++) {
            VersionID vi = (VersionID)_versionIds.get(i);
            boolean check = vi.isGreaterThan(m);
            if (check) return true;
        }
        return false;
    }

    /** Check if this VersionString object contains anything greater than the VersionID m, given as a string */
    public boolean containsGreaterThan(String versionid) {
	return containsGreaterThan(new VersionID(versionid));
    }

    /** Check if the versionString 'vs' contains the VersionID 'vi' */
    static public boolean contains(String vs, String vi) {
	return (new VersionString(vs)).contains(vi);
    }

    /** Pretty-print object */
    public String toString() {
	StringBuffer sb = new StringBuffer();
	for(int i = 0; i < _versionIds.size(); i++) {
	    sb.append(_versionIds.get(i).toString());
	    sb.append(' ');
	}
	return sb.toString();
    }
}


text:
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import classNames from 'classnames';

class Toggle extends Component {
  static propTypes = {
    checked: PropTypes.bool.isRequired,
    id: PropTypes.string.isRequired,
    type: PropTypes.oneOf(['checkbox', 'radio']).isRequired,
    checkedIcon: PropTypes.node.isRequired,
    uncheckedIcon: PropTypes.node.isRequired,
  }

  render() {
    const { checkedIcon, uncheckedIcon, ...passthroughProps } = this.props;
    const toggleClasses = {
      'toggle-icon': true,
      'toggle-icon--checked': passthroughProps.checked,
      [`toggle-icon--${passthroughProps.type}`]: passthroughProps.type,
    }
    return (

        <input { ...passthroughProps } style={{ display: 'none' }} />

          {passthroughProps.checked ? checkedIcon : uncheckedIcon}

    );
  }
}

export default Toggle;


text:
from django.contrib import admin
from pickleback.apps.packages.models import Package

class PackageAdmin(admin.ModelAdmin):
    list_display = ('name', 'url', 'description', 'canonical')

admin.site.register(Package, PackageAdmin)