text
stringlengths
54
60.6k
<commit_before>/************************************************************************ * * Flood Project (2008-201x) * Licensed under the simplified BSD license. All rights reserved. * ************************************************************************/ #include "Core/API.h" #include "Core/Network/Host.h" #include "Core/Network/Network.h" #include "Core/Network/Peer.h" #include "Core/Network/Session.h" #include "Core/Network/Packet.h" #include "Core/Network/PacketProcessor.h" #include "Core/Network/Processors/PacketKeyExchanger.h" #include "Core/Log.h" #if defined(PLATFORM_WINDOWS) && !defined(WIN32) #define WIN32 #endif #include <enet/enet.h> NAMESPACE_CORE_BEGIN //-----------------------------------// #define ENET_BANDWIDTH_AUTO 0 static ENetHost* CreateEnetSocket( ENetAddress* address ) { int numClients = 32; int numChannels = 2; int numBandwidthIn = ENET_BANDWIDTH_AUTO; int numBandwidthOut = ENET_BANDWIDTH_AUTO; ENetHost* host = enet_host_create(address, numClients, numChannels, numBandwidthIn, numBandwidthOut); if( !host ) { LogError("Error creating ENet host"); return nullptr; } return host; } //-----------------------------------// Host::Host() : host(nullptr) { } //-----------------------------------// Host::~Host() { destroySocket(); } //-----------------------------------// bool Host::destroySocket() { if( !host ) return false; enet_host_destroy(host); host = nullptr; return true; } //-----------------------------------// bool Host::hasContext() { return host != nullptr; } //-----------------------------------// void Host::processEvents(uint32 timeout) { if( !hasContext() ) return; ENetEvent event; while(enet_host_service(host, &event, timeout) > 0) { switch(event.type) { case ENET_EVENT_TYPE_CONNECT: handleConnectEvent(&event); break; case ENET_EVENT_TYPE_DISCONNECT: handleDisconnectEvent(&event); break; case ENET_EVENT_TYPE_RECEIVE: handleReceiveEvent(&event); break; }; } } //-----------------------------------// void Host::broadcastPacket(const PacketPtr& packet, uint8 channel) { packet->prepare(); enet_host_broadcast(host, channel, packet->getPacket()); } //-----------------------------------// void Host::handleConnectEvent(ENetEvent* event) { ENetPeer* peer = event->peer; PeerPtr networkPeer = AllocateThis(Peer); networkPeer->setPeer(peer); networkPeer->setHost(this); // Store the network peer as user data. peer->data = networkPeer.get(); networkPeer->setState(PeerState::Connected); onPeerConnect(networkPeer); } //-----------------------------------// void Host::handleDisconnectEvent(ENetEvent* event) { PeerPtr networkPeer = (Peer*) event->peer->data; if( !networkPeer ) return; networkPeer->setState(PeerState::Disconnected); onPeerDisconnect(networkPeer); // Reset the peer userdata. ENetPeer* peer = event->peer; peer->data = nullptr; } //-----------------------------------// void Host::handleReceiveEvent(ENetEvent* event) { ENetPacket* packet = event->packet; Peer* peer = (Peer*) event->peer->data; PacketPtr packetPtr = PacketCreate(0); packetPtr->setPacket(packet); if(peer->processInPacket(packetPtr.get(), event->channelID)) if(peer->getSession()) onSessionPacket(peer->getSession(), packetPtr, event->channelID); } //-----------------------------------// HostClient::HostClient() { } //-----------------------------------// bool HostClient::connect( const HostConnectionDetails& details ) { if( peer && peer->getState() != PeerState::Disconnected ) return false; peer->setState(PeerState::Connecting); host = CreateEnetSocket(nullptr); if( !host ) return false; ENetAddress addr; addr.host = 0; addr.port = details.port; auto ret = enet_address_set_host( &addr, details.address.c_str() ); if(ret < 0) { LogError("Cannot resolve host address ", details.address.c_str()); return false; } enet_uint32 data = 0; ENetPeer* newPeer = enet_host_connect(host, &addr, details.channelCount, data); if (!newPeer) { LogError("No available peers for initiating an ENet connection."); return false; } return true; } //-----------------------------------// void HostClient::onPeerConnect(const PeerPtr& newPeer) { newPeer->setSession(session); session->setPeer(newPeer.get()); peer = newPeer; auto keyExchanger = Allocate(AllocatorGetNetwork(), PacketClientKeyExchanger); newPeer->addProcessor(keyExchanger); keyExchanger->beginKeyExchange(newPeer.get()); } //-----------------------------------// bool HostServer::createSocket( const HostConnectionDetails& details ) { ENetAddress addr; addr.host = ENET_HOST_ANY; addr.port = details.port; host = CreateEnetSocket(&addr); return (host != nullptr); } //-----------------------------------// void HostServer::onPeerConnect(const PeerPtr& peer) { peers.push_back(peer); auto keyExchanger = Allocate(AllocatorGetNetwork(), PacketServerKeyExchanger); peer->addProcessor(keyExchanger); } //-----------------------------------// void HostServer::onPeerDisconnect(const PeerPtr& peer) { auto it = std::find(peers.begin(), peers.end(), peer); assert( it != peers.end() ); peers.erase(it); } //-----------------------------------// NAMESPACE_CORE_END<commit_msg>Change onPeerConnect code to use more HostClient::peer instead of parameter newPeer.<commit_after>/************************************************************************ * * Flood Project (2008-201x) * Licensed under the simplified BSD license. All rights reserved. * ************************************************************************/ #include "Core/API.h" #include "Core/Network/Host.h" #include "Core/Network/Network.h" #include "Core/Network/Peer.h" #include "Core/Network/Session.h" #include "Core/Network/Packet.h" #include "Core/Network/PacketProcessor.h" #include "Core/Network/Processors/PacketKeyExchanger.h" #include "Core/Log.h" #if defined(PLATFORM_WINDOWS) && !defined(WIN32) #define WIN32 #endif #include <enet/enet.h> NAMESPACE_CORE_BEGIN //-----------------------------------// #define ENET_BANDWIDTH_AUTO 0 static ENetHost* CreateEnetSocket( ENetAddress* address ) { int numClients = 32; int numChannels = 2; int numBandwidthIn = ENET_BANDWIDTH_AUTO; int numBandwidthOut = ENET_BANDWIDTH_AUTO; ENetHost* host = enet_host_create(address, numClients, numChannels, numBandwidthIn, numBandwidthOut); if( !host ) { LogError("Error creating ENet host"); return nullptr; } return host; } //-----------------------------------// Host::Host() : host(nullptr) { } //-----------------------------------// Host::~Host() { destroySocket(); } //-----------------------------------// bool Host::destroySocket() { if( !host ) return false; enet_host_destroy(host); host = nullptr; return true; } //-----------------------------------// bool Host::hasContext() { return host != nullptr; } //-----------------------------------// void Host::processEvents(uint32 timeout) { if( !hasContext() ) return; ENetEvent event; while(enet_host_service(host, &event, timeout) > 0) { switch(event.type) { case ENET_EVENT_TYPE_CONNECT: handleConnectEvent(&event); break; case ENET_EVENT_TYPE_DISCONNECT: handleDisconnectEvent(&event); break; case ENET_EVENT_TYPE_RECEIVE: handleReceiveEvent(&event); break; }; } } //-----------------------------------// void Host::broadcastPacket(const PacketPtr& packet, uint8 channel) { packet->prepare(); enet_host_broadcast(host, channel, packet->getPacket()); } //-----------------------------------// void Host::handleConnectEvent(ENetEvent* event) { ENetPeer* peer = event->peer; PeerPtr networkPeer = AllocateThis(Peer); networkPeer->setPeer(peer); networkPeer->setHost(this); // Store the network peer as user data. peer->data = networkPeer.get(); networkPeer->setState(PeerState::Connected); onPeerConnect(networkPeer); } //-----------------------------------// void Host::handleDisconnectEvent(ENetEvent* event) { PeerPtr networkPeer = (Peer*) event->peer->data; if( !networkPeer ) return; networkPeer->setState(PeerState::Disconnected); onPeerDisconnect(networkPeer); // Reset the peer userdata. ENetPeer* peer = event->peer; peer->data = nullptr; } //-----------------------------------// void Host::handleReceiveEvent(ENetEvent* event) { ENetPacket* packet = event->packet; Peer* peer = (Peer*) event->peer->data; PacketPtr packetPtr = PacketCreate(0); packetPtr->setPacket(packet); if(peer->processInPacket(packetPtr.get(), event->channelID)) if(peer->getSession()) onSessionPacket(peer->getSession(), packetPtr, event->channelID); } //-----------------------------------// HostClient::HostClient() { } //-----------------------------------// bool HostClient::connect( const HostConnectionDetails& details ) { if( peer && peer->getState() != PeerState::Disconnected ) return false; peer->setState(PeerState::Connecting); host = CreateEnetSocket(nullptr); if( !host ) return false; ENetAddress addr; addr.host = 0; addr.port = details.port; auto ret = enet_address_set_host( &addr, details.address.c_str() ); if(ret < 0) { LogError("Cannot resolve host address ", details.address.c_str()); return false; } enet_uint32 data = 0; ENetPeer* newPeer = enet_host_connect(host, &addr, details.channelCount, data); if (!newPeer) { LogError("No available peers for initiating an ENet connection."); return false; } return true; } //-----------------------------------// void HostClient::onPeerConnect(const PeerPtr& newPeer) { peer = newPeer; peer->setSession(&session); session.setPeer(peer.get()); auto keyExchanger = Allocate(AllocatorGetNetwork(), PacketClientKeyExchanger); peer->addProcessor(keyExchanger); keyExchanger->beginKeyExchange(peer.get()); } //-----------------------------------// bool HostServer::createSocket( const HostConnectionDetails& details ) { ENetAddress addr; addr.host = ENET_HOST_ANY; addr.port = details.port; host = CreateEnetSocket(&addr); return (host != nullptr); } //-----------------------------------// void HostServer::onPeerConnect(const PeerPtr& peer) { peers.push_back(peer); auto keyExchanger = Allocate(AllocatorGetNetwork(), PacketServerKeyExchanger); peer->addProcessor(keyExchanger); } //-----------------------------------// void HostServer::onPeerDisconnect(const PeerPtr& peer) { auto it = std::find(peers.begin(), peers.end(), peer); assert( it != peers.end() ); peers.erase(it); } //-----------------------------------// NAMESPACE_CORE_END<|endoftext|>
<commit_before>// soundmgr.cxx -- Sound effect management class // // Sound manager initially written by David Findlay // <[email protected]> 2001 // // C++-ified by Curtis Olson, started March 2001. // // Copyright (C) 2001 Curtis L. Olson - [email protected] // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. // // $Id$ #include <iostream> #if defined(__APPLE__) # include <OpenAL/al.h> # include <OpenAL/alut.h> # include <OpenAL/alc.h> #else # include <AL/al.h> # include <AL/alut.h> # include <AL/alc.h> #endif #include <simgear/debug/logstream.hxx> #include <simgear/misc/sg_path.hxx> #include "soundmgr_openal.hxx" // // Sound Manager // // constructor SGSoundMgr::SGSoundMgr() { SG_LOG( SG_GENERAL, SG_ALERT, "Initializing OpenAL sound manager" ); // initialize OpenAL alutInit( 0, NULL ); alGetError(); if ( alGetError() == AL_NO_ERROR) { working = true; } else { working = false; SG_LOG( SG_GENERAL, SG_ALERT, "Audio initialization failed!" ); } listener_pos[0] = 0.0; listener_pos[1] = 0.0; listener_pos[2] = 0.0; listener_vel[0] = 0.0; listener_vel[1] = 0.0; listener_vel[2] = 0.0; listener_ori[0] = 0.0; listener_ori[1] = 0.0; listener_ori[2] = -1.0; listener_ori[3] = 0.0; listener_ori[4] = 1.0; listener_ori[5] = 0.0; alListenerfv( AL_POSITION, listener_pos ); alListenerfv( AL_VELOCITY, listener_vel ); alListenerfv( AL_ORIENTATION, listener_ori ); alGetError(); if ( alGetError() != AL_NO_ERROR) { SG_LOG( SG_GENERAL, SG_ALERT, "Oops AL error after audio initialization!" ); } // exaggerate the ear candy? alDopplerFactor(1.0); } // destructor SGSoundMgr::~SGSoundMgr() { // // Remove the samples from the sample manager. // sample_map_iterator sample_current = samples.begin(); sample_map_iterator sample_end = samples.end(); for ( ; sample_current != sample_end; ++sample_current ) { SGSoundSample *sample = sample_current->second; delete sample; } alutExit(); } // initialize the sound manager void SGSoundMgr::init() { // // Remove the samples from the sample manager. // sample_map_iterator sample_current = samples.begin(); sample_map_iterator sample_end = samples.end(); for ( ; sample_current != sample_end; ++sample_current ) { SGSoundSample *sample = sample_current->second; delete sample; } samples.clear(); } void SGSoundMgr::bind () { // no properties } void SGSoundMgr::unbind () { // no properties } // run the audio scheduler void SGSoundMgr::update( double dt ) { } void SGSoundMgr::pause () { ALCcontext *pCurContext = alcGetCurrentContext(); alcSuspendContext( pCurContext ); if ( alGetError() != AL_NO_ERROR) { SG_LOG( SG_GENERAL, SG_ALERT, "Oops AL error after soundmgr pause()!" ); } } void SGSoundMgr::resume () { ALCcontext *pCurContext = alcGetCurrentContext(); alcProcessContext( pCurContext ); if ( alGetError() != AL_NO_ERROR) { SG_LOG( SG_GENERAL, SG_ALERT, "Oops AL error after soundmgr resume()!" ); } } // add a sound effect, return true if successful bool SGSoundMgr::add( SGSoundSample *sound, const string& refname ) { sample_map_iterator sample_it = samples.find( refname ); if ( sample_it != samples.end() ) { // sound already exists return false; } samples[refname] = sound; return true; } // remove a sound effect, return true if successful bool SGSoundMgr::remove( const string &refname ) { sample_map_iterator sample_it = samples.find( refname ); if ( sample_it != samples.end() ) { // first stop the sound from playing (so we don't bomb the // audio scheduler) SGSoundSample *sample = sample_it->second; delete sample; samples.erase( sample_it ); // cout << "sndmgr: removed -> " << refname << endl; return true; } else { // cout << "sndmgr: failed remove -> " << refname << endl; return false; } } // return true of the specified sound exists in the sound manager system bool SGSoundMgr::exists( const string &refname ) { sample_map_iterator sample_it = samples.find( refname ); if ( sample_it != samples.end() ) { return true; } else { return false; } } // return a pointer to the SGSoundSample if the specified sound exists // in the sound manager system, otherwise return NULL SGSoundSample *SGSoundMgr::find( const string &refname ) { sample_map_iterator sample_it = samples.find( refname ); if ( sample_it != samples.end() ) { return sample_it->second; } else { return NULL; } } // tell the scheduler to play the indexed sample in a continuous // loop bool SGSoundMgr::play_looped( const string &refname ) { SGSoundSample *sample; if ( (sample = find( refname )) == NULL ) { return false; } else { sample->play( true ); return true; } } // tell the scheduler to play the indexed sample once bool SGSoundMgr::play_once( const string& refname ) { SGSoundSample *sample; if ( (sample = find( refname )) == NULL ) { return false; } else { sample->play( false ); return true; } } // return true of the specified sound is currently being played bool SGSoundMgr::is_playing( const string& refname ) { SGSoundSample *sample; if ( (sample = find( refname )) == NULL ) { return false; } else { return ( sample->is_playing() ); } } // immediate stop playing the sound bool SGSoundMgr::stop( const string& refname ) { SGSoundSample *sample; if ( (sample = find( refname )) == NULL ) { return false; } else { sample->stop(); return true; } } // set source position of all managed sounds void SGSoundMgr::set_source_pos_all( ALfloat *pos ) { sample_map_iterator sample_current = samples.begin(); sample_map_iterator sample_end = samples.end(); for ( ; sample_current != sample_end; ++sample_current ) { SGSoundSample *sample = sample_current->second; sample->set_source_pos( pos ); } } // set source velocity of all managed sounds void SGSoundMgr::set_source_vel_all( ALfloat *vel ) { sample_map_iterator sample_current = samples.begin(); sample_map_iterator sample_end = samples.end(); for ( ; sample_current != sample_end; ++sample_current ) { SGSoundSample *sample = sample_current->second; sample->set_source_vel( vel ); } } <commit_msg>Tweak the doppler effect.<commit_after>// soundmgr.cxx -- Sound effect management class // // Sound manager initially written by David Findlay // <[email protected]> 2001 // // C++-ified by Curtis Olson, started March 2001. // // Copyright (C) 2001 Curtis L. Olson - [email protected] // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. // // $Id$ #include <iostream> #if defined(__APPLE__) # include <OpenAL/al.h> # include <OpenAL/alut.h> # include <OpenAL/alc.h> #else # include <AL/al.h> # include <AL/alut.h> # include <AL/alc.h> #endif #include <simgear/debug/logstream.hxx> #include <simgear/misc/sg_path.hxx> #include "soundmgr_openal.hxx" // // Sound Manager // // constructor SGSoundMgr::SGSoundMgr() { SG_LOG( SG_GENERAL, SG_ALERT, "Initializing OpenAL sound manager" ); // initialize OpenAL alutInit( 0, NULL ); alGetError(); if ( alGetError() == AL_NO_ERROR) { working = true; } else { working = false; SG_LOG( SG_GENERAL, SG_ALERT, "Audio initialization failed!" ); } listener_pos[0] = 0.0; listener_pos[1] = 0.0; listener_pos[2] = 0.0; listener_vel[0] = 0.0; listener_vel[1] = 0.0; listener_vel[2] = 0.0; listener_ori[0] = 0.0; listener_ori[1] = 0.0; listener_ori[2] = -1.0; listener_ori[3] = 0.0; listener_ori[4] = 1.0; listener_ori[5] = 0.0; alListenerfv( AL_POSITION, listener_pos ); alListenerfv( AL_VELOCITY, listener_vel ); alListenerfv( AL_ORIENTATION, listener_ori ); alGetError(); if ( alGetError() != AL_NO_ERROR) { SG_LOG( SG_GENERAL, SG_ALERT, "Oops AL error after audio initialization!" ); } // exaggerate the ear candy? alDopplerFactor(1.0); alDopplerVelocity(340.0); // speed of sound in meters per second. } // destructor SGSoundMgr::~SGSoundMgr() { // // Remove the samples from the sample manager. // sample_map_iterator sample_current = samples.begin(); sample_map_iterator sample_end = samples.end(); for ( ; sample_current != sample_end; ++sample_current ) { SGSoundSample *sample = sample_current->second; delete sample; } alutExit(); } // initialize the sound manager void SGSoundMgr::init() { // // Remove the samples from the sample manager. // sample_map_iterator sample_current = samples.begin(); sample_map_iterator sample_end = samples.end(); for ( ; sample_current != sample_end; ++sample_current ) { SGSoundSample *sample = sample_current->second; delete sample; } samples.clear(); } void SGSoundMgr::bind () { // no properties } void SGSoundMgr::unbind () { // no properties } // run the audio scheduler void SGSoundMgr::update( double dt ) { } void SGSoundMgr::pause () { ALCcontext *pCurContext = alcGetCurrentContext(); alcSuspendContext( pCurContext ); if ( alGetError() != AL_NO_ERROR) { SG_LOG( SG_GENERAL, SG_ALERT, "Oops AL error after soundmgr pause()!" ); } } void SGSoundMgr::resume () { ALCcontext *pCurContext = alcGetCurrentContext(); alcProcessContext( pCurContext ); if ( alGetError() != AL_NO_ERROR) { SG_LOG( SG_GENERAL, SG_ALERT, "Oops AL error after soundmgr resume()!" ); } } // add a sound effect, return true if successful bool SGSoundMgr::add( SGSoundSample *sound, const string& refname ) { sample_map_iterator sample_it = samples.find( refname ); if ( sample_it != samples.end() ) { // sound already exists return false; } samples[refname] = sound; return true; } // remove a sound effect, return true if successful bool SGSoundMgr::remove( const string &refname ) { sample_map_iterator sample_it = samples.find( refname ); if ( sample_it != samples.end() ) { // first stop the sound from playing (so we don't bomb the // audio scheduler) SGSoundSample *sample = sample_it->second; delete sample; samples.erase( sample_it ); // cout << "sndmgr: removed -> " << refname << endl; return true; } else { // cout << "sndmgr: failed remove -> " << refname << endl; return false; } } // return true of the specified sound exists in the sound manager system bool SGSoundMgr::exists( const string &refname ) { sample_map_iterator sample_it = samples.find( refname ); if ( sample_it != samples.end() ) { return true; } else { return false; } } // return a pointer to the SGSoundSample if the specified sound exists // in the sound manager system, otherwise return NULL SGSoundSample *SGSoundMgr::find( const string &refname ) { sample_map_iterator sample_it = samples.find( refname ); if ( sample_it != samples.end() ) { return sample_it->second; } else { return NULL; } } // tell the scheduler to play the indexed sample in a continuous // loop bool SGSoundMgr::play_looped( const string &refname ) { SGSoundSample *sample; if ( (sample = find( refname )) == NULL ) { return false; } else { sample->play( true ); return true; } } // tell the scheduler to play the indexed sample once bool SGSoundMgr::play_once( const string& refname ) { SGSoundSample *sample; if ( (sample = find( refname )) == NULL ) { return false; } else { sample->play( false ); return true; } } // return true of the specified sound is currently being played bool SGSoundMgr::is_playing( const string& refname ) { SGSoundSample *sample; if ( (sample = find( refname )) == NULL ) { return false; } else { return ( sample->is_playing() ); } } // immediate stop playing the sound bool SGSoundMgr::stop( const string& refname ) { SGSoundSample *sample; if ( (sample = find( refname )) == NULL ) { return false; } else { sample->stop(); return true; } } // set source position of all managed sounds void SGSoundMgr::set_source_pos_all( ALfloat *pos ) { sample_map_iterator sample_current = samples.begin(); sample_map_iterator sample_end = samples.end(); for ( ; sample_current != sample_end; ++sample_current ) { SGSoundSample *sample = sample_current->second; sample->set_source_pos( pos ); } } // set source velocity of all managed sounds void SGSoundMgr::set_source_vel_all( ALfloat *vel ) { sample_map_iterator sample_current = samples.begin(); sample_map_iterator sample_end = samples.end(); for ( ; sample_current != sample_end; ++sample_current ) { SGSoundSample *sample = sample_current->second; sample->set_source_vel( vel ); } } <|endoftext|>
<commit_before><commit_msg>update HWP level metadata for nest, common files<commit_after><|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_get_poundv_bucket.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_pm_get_poundv_bucket.C /// @brief Grab PM data from attribute /// // ---------------------------------------------------------------------- // Includes // ---------------------------------------------------------------------- #include <p9_pm_get_poundv_bucket.H> #include <attribute_ids.H> fapi2::ReturnCode p9_pm_get_poundv_bucket( const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target, fapi2::voltageBucketData_t& o_data) { FAPI_IMP("Entering p9_pm_get_poundv_bucket ...."); //Create a pointer version of the out param o_data so that // we can access bytes individually uint8_t* l_tempBuffer = reinterpret_cast<uint8_t*>(malloc(sizeof(o_data))); //Set up a char array to hold the bucket data from an attr read fapi2::ATTR_POUNDV_BUCKET_DATA_Type l_bucketAttr; //Perform an ATTR_GET for POUNDV_BUCKET data on the EQ target FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_POUNDV_BUCKET_DATA, i_target, l_bucketAttr)); #ifndef _BIG_ENDIAN //The first byte is simply a uint8 that describes the bucket ID l_tempBuffer[0] = l_bucketAttr[0]; //Skipping the first byte (which has already been taken of) start reading //the voltage data 2 bytes at a time. for(uint8_t offset = 1; offset < sizeof(o_data); offset += 2) { //Switch from Big Endian to Little Endian l_tempBuffer[offset] = l_bucketAttr[offset + 1]; l_tempBuffer[offset + 1] = l_bucketAttr[offset]; } memcpy(&o_data, l_tempBuffer, sizeof(o_data)); #else memcpy(&o_data, l_bucketAttr, sizeof(o_data)); #endif fapi_try_exit: free(l_tempBuffer); FAPI_IMP("Exiting p9_pm_get_poundv_bucket ...."); return fapi2::current_err; } <commit_msg>PSTATE parameter block:POUNDV parsing function vs native implementation<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_get_poundv_bucket.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_pm_get_poundv_bucket.C /// @brief Grab PM data from attribute /// // ---------------------------------------------------------------------- // Includes // ---------------------------------------------------------------------- #include <p9_pm_get_poundv_bucket.H> #include <attribute_ids.H> fapi2::ReturnCode p9_pm_get_poundv_bucket( const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target, fapi2::voltageBucketData_t& o_data) { FAPI_IMP("Entering p9_pm_get_poundv_bucket ...."); //Set up a char array to hold the bucket data from an attr read fapi2::ATTR_POUNDV_BUCKET_DATA_Type l_bucketAttr; //Perform an ATTR_GET for POUNDV_BUCKET data on the EQ target FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_POUNDV_BUCKET_DATA, i_target, l_bucketAttr)); memcpy(&o_data, l_bucketAttr, sizeof(o_data)); fapi_try_exit: FAPI_IMP("Exiting p9_pm_get_poundv_bucket ...."); return fapi2::current_err; } <|endoftext|>
<commit_before>// Copyright (c) 2012-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "coins.h" #include "consensus/consensus.h" #include "memusage.h" #include "random.h" #include <assert.h> bool CCoinsView::GetCoin(const COutPoint &outpoint, Coin &coin) const { return false; } uint256 CCoinsView::GetBestBlock() const { return uint256(); } std::vector<uint256> CCoinsView::GetHeadBlocks() const { return std::vector<uint256>(); } bool CCoinsView::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) { return false; } CCoinsViewCursor *CCoinsView::Cursor() const { return nullptr; } bool CCoinsView::HaveCoin(const COutPoint &outpoint) const { Coin coin; return GetCoin(outpoint, coin); } CCoinsViewBacked::CCoinsViewBacked(CCoinsView *viewIn) : base(viewIn) { } bool CCoinsViewBacked::GetCoin(const COutPoint &outpoint, Coin &coin) const { return base->GetCoin(outpoint, coin); } bool CCoinsViewBacked::HaveCoin(const COutPoint &outpoint) const { return base->HaveCoin(outpoint); } uint256 CCoinsViewBacked::GetBestBlock() const { return base->GetBestBlock(); } std::vector<uint256> CCoinsViewBacked::GetHeadBlocks() const { return base->GetHeadBlocks(); } void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; } bool CCoinsViewBacked::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) { return base->BatchWrite(mapCoins, hashBlock); } CCoinsViewCursor *CCoinsViewBacked::Cursor() const { return base->Cursor(); } size_t CCoinsViewBacked::EstimateSize() const { return base->EstimateSize(); } SaltedOutpointHasher::SaltedOutpointHasher() : k0(GetRand(std::numeric_limits<uint64_t>::max())), k1(GetRand(std::numeric_limits<uint64_t>::max())) {} CCoinsViewCache::CCoinsViewCache(CCoinsView *baseIn) : CCoinsViewBacked(baseIn), cachedCoinsUsage(0) {} size_t CCoinsViewCache::DynamicMemoryUsage() const { return memusage::DynamicUsage(cacheCoins) + cachedCoinsUsage; } CCoinsMap::iterator CCoinsViewCache::FetchCoin(const COutPoint &outpoint) const { CCoinsMap::iterator it = cacheCoins.find(outpoint); if (it != cacheCoins.end()) return it; Coin tmp; if (!base->GetCoin(outpoint, tmp)) return cacheCoins.end(); CCoinsMap::iterator ret = cacheCoins.emplace(std::piecewise_construct, std::forward_as_tuple(outpoint), std::forward_as_tuple(std::move(tmp))).first; if (ret->second.coin.IsSpent()) { // The parent only has an empty entry for this outpoint; we can consider our // version as fresh. ret->second.flags = CCoinsCacheEntry::FRESH; } cachedCoinsUsage += ret->second.coin.DynamicMemoryUsage(); return ret; } bool CCoinsViewCache::GetCoin(const COutPoint &outpoint, Coin &coin) const { CCoinsMap::const_iterator it = FetchCoin(outpoint); if (it != cacheCoins.end()) { coin = it->second.coin; return !coin.IsSpent(); } return false; } void CCoinsViewCache::AddCoin(const COutPoint &outpoint, Coin&& coin, bool possible_overwrite) { assert(!coin.IsSpent()); if (coin.out.scriptPubKey.IsUnspendable()) return; CCoinsMap::iterator it; bool inserted; std::tie(it, inserted) = cacheCoins.emplace(std::piecewise_construct, std::forward_as_tuple(outpoint), std::tuple<>()); bool fresh = false; if (!inserted) { cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage(); } if (!possible_overwrite) { if (!it->second.coin.IsSpent()) { throw std::logic_error("Adding new coin that replaces non-pruned entry"); } fresh = !(it->second.flags & CCoinsCacheEntry::DIRTY); } it->second.coin = std::move(coin); it->second.flags |= CCoinsCacheEntry::DIRTY | (fresh ? CCoinsCacheEntry::FRESH : 0); cachedCoinsUsage += it->second.coin.DynamicMemoryUsage(); } void AddCoins(CCoinsViewCache& cache, const CTransaction &tx, int nHeight, bool check) { bool fCoinbase = tx.IsCoinBase(); const uint256& txid = tx.GetHash(); for (size_t i = 0; i < tx.vout.size(); ++i) { bool overwrite = check ? cache.HaveCoin(COutPoint(txid, i)) : fCoinbase; // Always set the possible_overwrite flag to AddCoin for coinbase txn, in order to correctly // deal with the pre-BIP30 occurrences of duplicate coinbase transactions. cache.AddCoin(COutPoint(txid, i), Coin(tx.vout[i], nHeight, fCoinbase), overwrite); } } bool CCoinsViewCache::SpendCoin(const COutPoint &outpoint, Coin* moveout) { CCoinsMap::iterator it = FetchCoin(outpoint); if (it == cacheCoins.end()) return false; cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage(); if (moveout) { *moveout = std::move(it->second.coin); } if (it->second.flags & CCoinsCacheEntry::FRESH) { cacheCoins.erase(it); } else { it->second.flags |= CCoinsCacheEntry::DIRTY; it->second.coin.Clear(); } return true; } static const Coin coinEmpty; const Coin& CCoinsViewCache::AccessCoin(const COutPoint &outpoint) const { CCoinsMap::const_iterator it = FetchCoin(outpoint); if (it == cacheCoins.end()) { return coinEmpty; } else { return it->second.coin; } } bool CCoinsViewCache::HaveCoin(const COutPoint &outpoint) const { CCoinsMap::const_iterator it = FetchCoin(outpoint); return (it != cacheCoins.end() && !it->second.coin.IsSpent()); } bool CCoinsViewCache::HaveCoinInCache(const COutPoint &outpoint) const { CCoinsMap::const_iterator it = cacheCoins.find(outpoint); return (it != cacheCoins.end() && !it->second.coin.IsSpent()); } uint256 CCoinsViewCache::GetBestBlock() const { if (hashBlock.IsNull()) hashBlock = base->GetBestBlock(); return hashBlock; } void CCoinsViewCache::SetBestBlock(const uint256 &hashBlockIn) { hashBlock = hashBlockIn; } bool CCoinsViewCache::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlockIn) { for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) { if (it->second.flags & CCoinsCacheEntry::DIRTY) { // Ignore non-dirty entries (optimization). CCoinsMap::iterator itUs = cacheCoins.find(it->first); if (itUs == cacheCoins.end()) { // The parent cache does not have an entry, while the child does // We can ignore it if it's both FRESH and pruned in the child if (!(it->second.flags & CCoinsCacheEntry::FRESH && it->second.coin.IsSpent())) { // Otherwise we will need to create it in the parent // and move the data up and mark it as dirty CCoinsCacheEntry& entry = cacheCoins[it->first]; entry.coin = std::move(it->second.coin); cachedCoinsUsage += entry.coin.DynamicMemoryUsage(); entry.flags = CCoinsCacheEntry::DIRTY; // We can mark it FRESH in the parent if it was FRESH in the child // Otherwise it might have just been flushed from the parent's cache // and already exist in the grandparent if (it->second.flags & CCoinsCacheEntry::FRESH) entry.flags |= CCoinsCacheEntry::FRESH; } } else { // Assert that the child cache entry was not marked FRESH if the // parent cache entry has unspent outputs. If this ever happens, // it means the FRESH flag was misapplied and there is a logic // error in the calling code. if ((it->second.flags & CCoinsCacheEntry::FRESH) && !itUs->second.coin.IsSpent()) throw std::logic_error("FRESH flag misapplied to cache entry for base transaction with spendable outputs"); // Found the entry in the parent cache if ((itUs->second.flags & CCoinsCacheEntry::FRESH) && it->second.coin.IsSpent()) { // The grandparent does not have an entry, and the child is // modified and being pruned. This means we can just delete // it from the parent. cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage(); cacheCoins.erase(itUs); } else { // A normal modification. cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage(); itUs->second.coin = std::move(it->second.coin); cachedCoinsUsage += itUs->second.coin.DynamicMemoryUsage(); itUs->second.flags |= CCoinsCacheEntry::DIRTY; // NOTE: It is possible the child has a FRESH flag here in // the event the entry we found in the parent is pruned. But // we must not copy that FRESH flag to the parent as that // pruned state likely still needs to be communicated to the // grandparent. } } } CCoinsMap::iterator itOld = it++; mapCoins.erase(itOld); } hashBlock = hashBlockIn; return true; } bool CCoinsViewCache::Flush() { bool fOk = base->BatchWrite(cacheCoins, hashBlock); cacheCoins.clear(); cachedCoinsUsage = 0; return fOk; } void CCoinsViewCache::Uncache(const COutPoint& hash) { CCoinsMap::iterator it = cacheCoins.find(hash); if (it != cacheCoins.end() && it->second.flags == 0) { cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage(); cacheCoins.erase(it); } } unsigned int CCoinsViewCache::GetCacheSize() const { return cacheCoins.size(); } CAmount CCoinsViewCache::GetValueIn(const CTransaction& tx) const { if (tx.IsCoinBase()) return 0; CAmount nResult = 0; for (unsigned int i = 0; i < tx.vin.size(); i++) nResult += AccessCoin(tx.vin[i].prevout).out.nValue; return nResult; } bool CCoinsViewCache::HaveInputs(const CTransaction& tx) const { if (!tx.IsCoinBase()) { for (unsigned int i = 0; i < tx.vin.size(); i++) { if (!HaveCoin(tx.vin[i].prevout)) { return false; } } } return true; } static const size_t MIN_TRANSACTION_OUTPUT_WEIGHT = WITNESS_SCALE_FACTOR * ::GetSerializeSize(CTxOut(), SER_NETWORK, PROTOCOL_VERSION); static const size_t MAX_OUTPUTS_PER_BLOCK = MAX_BLOCK_WEIGHT / MIN_TRANSACTION_OUTPUT_WEIGHT; const Coin& AccessByTxid(const CCoinsViewCache& view, const uint256& txid) { COutPoint iter(txid, 0); while (iter.n < MAX_OUTPUTS_PER_BLOCK) { const Coin& alternate = view.AccessCoin(iter); if (!alternate.IsSpent()) return alternate; ++iter.n; } return coinEmpty; } <commit_msg>Small refactor of CCoinsViewCache::BatchWrite()<commit_after>// Copyright (c) 2012-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "coins.h" #include "consensus/consensus.h" #include "memusage.h" #include "random.h" #include <assert.h> bool CCoinsView::GetCoin(const COutPoint &outpoint, Coin &coin) const { return false; } uint256 CCoinsView::GetBestBlock() const { return uint256(); } std::vector<uint256> CCoinsView::GetHeadBlocks() const { return std::vector<uint256>(); } bool CCoinsView::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) { return false; } CCoinsViewCursor *CCoinsView::Cursor() const { return nullptr; } bool CCoinsView::HaveCoin(const COutPoint &outpoint) const { Coin coin; return GetCoin(outpoint, coin); } CCoinsViewBacked::CCoinsViewBacked(CCoinsView *viewIn) : base(viewIn) { } bool CCoinsViewBacked::GetCoin(const COutPoint &outpoint, Coin &coin) const { return base->GetCoin(outpoint, coin); } bool CCoinsViewBacked::HaveCoin(const COutPoint &outpoint) const { return base->HaveCoin(outpoint); } uint256 CCoinsViewBacked::GetBestBlock() const { return base->GetBestBlock(); } std::vector<uint256> CCoinsViewBacked::GetHeadBlocks() const { return base->GetHeadBlocks(); } void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; } bool CCoinsViewBacked::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) { return base->BatchWrite(mapCoins, hashBlock); } CCoinsViewCursor *CCoinsViewBacked::Cursor() const { return base->Cursor(); } size_t CCoinsViewBacked::EstimateSize() const { return base->EstimateSize(); } SaltedOutpointHasher::SaltedOutpointHasher() : k0(GetRand(std::numeric_limits<uint64_t>::max())), k1(GetRand(std::numeric_limits<uint64_t>::max())) {} CCoinsViewCache::CCoinsViewCache(CCoinsView *baseIn) : CCoinsViewBacked(baseIn), cachedCoinsUsage(0) {} size_t CCoinsViewCache::DynamicMemoryUsage() const { return memusage::DynamicUsage(cacheCoins) + cachedCoinsUsage; } CCoinsMap::iterator CCoinsViewCache::FetchCoin(const COutPoint &outpoint) const { CCoinsMap::iterator it = cacheCoins.find(outpoint); if (it != cacheCoins.end()) return it; Coin tmp; if (!base->GetCoin(outpoint, tmp)) return cacheCoins.end(); CCoinsMap::iterator ret = cacheCoins.emplace(std::piecewise_construct, std::forward_as_tuple(outpoint), std::forward_as_tuple(std::move(tmp))).first; if (ret->second.coin.IsSpent()) { // The parent only has an empty entry for this outpoint; we can consider our // version as fresh. ret->second.flags = CCoinsCacheEntry::FRESH; } cachedCoinsUsage += ret->second.coin.DynamicMemoryUsage(); return ret; } bool CCoinsViewCache::GetCoin(const COutPoint &outpoint, Coin &coin) const { CCoinsMap::const_iterator it = FetchCoin(outpoint); if (it != cacheCoins.end()) { coin = it->second.coin; return !coin.IsSpent(); } return false; } void CCoinsViewCache::AddCoin(const COutPoint &outpoint, Coin&& coin, bool possible_overwrite) { assert(!coin.IsSpent()); if (coin.out.scriptPubKey.IsUnspendable()) return; CCoinsMap::iterator it; bool inserted; std::tie(it, inserted) = cacheCoins.emplace(std::piecewise_construct, std::forward_as_tuple(outpoint), std::tuple<>()); bool fresh = false; if (!inserted) { cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage(); } if (!possible_overwrite) { if (!it->second.coin.IsSpent()) { throw std::logic_error("Adding new coin that replaces non-pruned entry"); } fresh = !(it->second.flags & CCoinsCacheEntry::DIRTY); } it->second.coin = std::move(coin); it->second.flags |= CCoinsCacheEntry::DIRTY | (fresh ? CCoinsCacheEntry::FRESH : 0); cachedCoinsUsage += it->second.coin.DynamicMemoryUsage(); } void AddCoins(CCoinsViewCache& cache, const CTransaction &tx, int nHeight, bool check) { bool fCoinbase = tx.IsCoinBase(); const uint256& txid = tx.GetHash(); for (size_t i = 0; i < tx.vout.size(); ++i) { bool overwrite = check ? cache.HaveCoin(COutPoint(txid, i)) : fCoinbase; // Always set the possible_overwrite flag to AddCoin for coinbase txn, in order to correctly // deal with the pre-BIP30 occurrences of duplicate coinbase transactions. cache.AddCoin(COutPoint(txid, i), Coin(tx.vout[i], nHeight, fCoinbase), overwrite); } } bool CCoinsViewCache::SpendCoin(const COutPoint &outpoint, Coin* moveout) { CCoinsMap::iterator it = FetchCoin(outpoint); if (it == cacheCoins.end()) return false; cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage(); if (moveout) { *moveout = std::move(it->second.coin); } if (it->second.flags & CCoinsCacheEntry::FRESH) { cacheCoins.erase(it); } else { it->second.flags |= CCoinsCacheEntry::DIRTY; it->second.coin.Clear(); } return true; } static const Coin coinEmpty; const Coin& CCoinsViewCache::AccessCoin(const COutPoint &outpoint) const { CCoinsMap::const_iterator it = FetchCoin(outpoint); if (it == cacheCoins.end()) { return coinEmpty; } else { return it->second.coin; } } bool CCoinsViewCache::HaveCoin(const COutPoint &outpoint) const { CCoinsMap::const_iterator it = FetchCoin(outpoint); return (it != cacheCoins.end() && !it->second.coin.IsSpent()); } bool CCoinsViewCache::HaveCoinInCache(const COutPoint &outpoint) const { CCoinsMap::const_iterator it = cacheCoins.find(outpoint); return (it != cacheCoins.end() && !it->second.coin.IsSpent()); } uint256 CCoinsViewCache::GetBestBlock() const { if (hashBlock.IsNull()) hashBlock = base->GetBestBlock(); return hashBlock; } void CCoinsViewCache::SetBestBlock(const uint256 &hashBlockIn) { hashBlock = hashBlockIn; } bool CCoinsViewCache::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlockIn) { for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end(); it = mapCoins.erase(it)) { // Ignore non-dirty entries (optimization). if (!(it->second.flags & CCoinsCacheEntry::DIRTY)) { continue; } CCoinsMap::iterator itUs = cacheCoins.find(it->first); if (itUs == cacheCoins.end()) { // The parent cache does not have an entry, while the child does // We can ignore it if it's both FRESH and pruned in the child if (!(it->second.flags & CCoinsCacheEntry::FRESH && it->second.coin.IsSpent())) { // Otherwise we will need to create it in the parent // and move the data up and mark it as dirty CCoinsCacheEntry& entry = cacheCoins[it->first]; entry.coin = std::move(it->second.coin); cachedCoinsUsage += entry.coin.DynamicMemoryUsage(); entry.flags = CCoinsCacheEntry::DIRTY; // We can mark it FRESH in the parent if it was FRESH in the child // Otherwise it might have just been flushed from the parent's cache // and already exist in the grandparent if (it->second.flags & CCoinsCacheEntry::FRESH) { entry.flags |= CCoinsCacheEntry::FRESH; } } } else { // Assert that the child cache entry was not marked FRESH if the // parent cache entry has unspent outputs. If this ever happens, // it means the FRESH flag was misapplied and there is a logic // error in the calling code. if ((it->second.flags & CCoinsCacheEntry::FRESH) && !itUs->second.coin.IsSpent()) { throw std::logic_error("FRESH flag misapplied to cache entry for base transaction with spendable outputs"); } // Found the entry in the parent cache if ((itUs->second.flags & CCoinsCacheEntry::FRESH) && it->second.coin.IsSpent()) { // The grandparent does not have an entry, and the child is // modified and being pruned. This means we can just delete // it from the parent. cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage(); cacheCoins.erase(itUs); } else { // A normal modification. cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage(); itUs->second.coin = std::move(it->second.coin); cachedCoinsUsage += itUs->second.coin.DynamicMemoryUsage(); itUs->second.flags |= CCoinsCacheEntry::DIRTY; // NOTE: It is possible the child has a FRESH flag here in // the event the entry we found in the parent is pruned. But // we must not copy that FRESH flag to the parent as that // pruned state likely still needs to be communicated to the // grandparent. } } } hashBlock = hashBlockIn; return true; } bool CCoinsViewCache::Flush() { bool fOk = base->BatchWrite(cacheCoins, hashBlock); cacheCoins.clear(); cachedCoinsUsage = 0; return fOk; } void CCoinsViewCache::Uncache(const COutPoint& hash) { CCoinsMap::iterator it = cacheCoins.find(hash); if (it != cacheCoins.end() && it->second.flags == 0) { cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage(); cacheCoins.erase(it); } } unsigned int CCoinsViewCache::GetCacheSize() const { return cacheCoins.size(); } CAmount CCoinsViewCache::GetValueIn(const CTransaction& tx) const { if (tx.IsCoinBase()) return 0; CAmount nResult = 0; for (unsigned int i = 0; i < tx.vin.size(); i++) nResult += AccessCoin(tx.vin[i].prevout).out.nValue; return nResult; } bool CCoinsViewCache::HaveInputs(const CTransaction& tx) const { if (!tx.IsCoinBase()) { for (unsigned int i = 0; i < tx.vin.size(); i++) { if (!HaveCoin(tx.vin[i].prevout)) { return false; } } } return true; } static const size_t MIN_TRANSACTION_OUTPUT_WEIGHT = WITNESS_SCALE_FACTOR * ::GetSerializeSize(CTxOut(), SER_NETWORK, PROTOCOL_VERSION); static const size_t MAX_OUTPUTS_PER_BLOCK = MAX_BLOCK_WEIGHT / MIN_TRANSACTION_OUTPUT_WEIGHT; const Coin& AccessByTxid(const CCoinsViewCache& view, const uint256& txid) { COutPoint iter(txid, 0); while (iter.n < MAX_OUTPUTS_PER_BLOCK) { const Coin& alternate = view.AccessCoin(iter); if (!alternate.IsSpent()) return alternate; ++iter.n; } return coinEmpty; } <|endoftext|>
<commit_before>#include "Button.hpp" #include <Engine/Util/Input.hpp> using namespace GUI; Button::Button(Widget* parent) : Widget(parent) { mouseHover = false; hasClickedCallback = false; size = glm::vec2(64.f, 64.f); } Button::~Button() { } void Button::Update() { double xpos = Input()->CursorX(); double ypos = Input()->CursorY(); mouseHover = xpos >= GetPosition().x && xpos < GetPosition().x + size.x && ypos >= GetPosition().y && ypos < GetPosition().y + size.y; if (mouseHover && Input()->MousePressed(GLFW_MOUSE_BUTTON_LEFT) && hasClickedCallback) { clickedCallback(); } } glm::vec2 Button::GetSize() const { return size; } void Button::SetSize(const glm::vec2& size) { this->size = size; } void Button::SetClickedCallback(std::function<void()> callback) { clickedCallback = callback; hasClickedCallback = true; } bool Button::GetMouseHover() const { return mouseHover; } <commit_msg>Fix forward declaration.<commit_after>#include "Button.hpp" #include <Engine/Geometry/Rectangle.hpp> #include <Engine/Util/Input.hpp> using namespace GUI; Button::Button(Widget* parent) : Widget(parent) { mouseHover = false; hasClickedCallback = false; size = glm::vec2(64.f, 64.f); } Button::~Button() { } void Button::Update() { double xpos = Input()->CursorX(); double ypos = Input()->CursorY(); mouseHover = xpos >= GetPosition().x && xpos < GetPosition().x + size.x && ypos >= GetPosition().y && ypos < GetPosition().y + size.y; if (mouseHover && Input()->MousePressed(GLFW_MOUSE_BUTTON_LEFT) && hasClickedCallback) { clickedCallback(); } } glm::vec2 Button::GetSize() const { return size; } void Button::SetSize(const glm::vec2& size) { this->size = size; } void Button::SetClickedCallback(std::function<void()> callback) { clickedCallback = callback; hasClickedCallback = true; } bool Button::GetMouseHover() const { return mouseHover; } <|endoftext|>
<commit_before>/* * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland * All rights reserved. * * This library/application is free software; you can redistribute and/or modify it under the terms of * the license that is included with this library/application in the file license.txt. */ //--- interface include -------------------------------------------------------- #include "ServiceDispatcher.h" //--- standard modules used ---------------------------------------------------- #include "Registry.h" #include "Timers.h" #include "ServiceHandler.h" #include "Renderer.h" #include "Dbg.h" //---- ServiceDispatchersModule ----------------------------------------------------------- RegisterModule(ServiceDispatchersModule); ServiceDispatchersModule::ServiceDispatchersModule(const char *name) : WDModule(name) { } ServiceDispatchersModule::~ServiceDispatchersModule() { } bool ServiceDispatchersModule::Init(const Anything &config) { if (config.IsDefined("ServiceDispatchers")) { HierarchyInstaller ai("ServiceDispatcher"); return RegisterableObject::Install(config["ServiceDispatchers"], "ServiceDispatcher", &ai); } return false; } bool ServiceDispatchersModule::ResetFinis(const Anything &config) { AliasTerminator at("ServiceDispatcher"); return RegisterableObject::ResetTerminate("ServiceDispatcher", &at); } bool ServiceDispatchersModule::Finis() { return StdFinis("ServiceDispatcher", "ServiceDispatchers"); } //---- ServiceDispatcher ----------------------------------------------------------- RegisterServiceDispatcher(ServiceDispatcher); ServiceDispatcher::ServiceDispatcher(const char *ServiceDispatcherName) : HierarchConfNamed(ServiceDispatcherName) { StartTrace(ServiceDispatcher.Ctor); } ServiceDispatcher::~ServiceDispatcher() { StartTrace(ServiceDispatcher.Dtor); } void ServiceDispatcher::Dispatch2Service(ostream &reply, Context &ctx) { StartTrace(ServiceDispatcher.Dispatch2Service); ctx.Push("ServiceDispatcher", this); ServiceHandler *sh = FindServiceHandler(ctx); // if no service handler is found DefaultHandler is used if (!sh) { String def = ctx.Lookup("DefaultHandler", "WebAppService"); Trace("not found, looking for DefaultHandler:" << def); sh = ServiceHandler::FindServiceHandler(def); } sh->HandleService(reply, ctx); } ServiceHandler *ServiceDispatcher::FindServiceHandler(Context &ctx) { StartTrace(ServiceDispatcher.FindServiceHandler); String name = FindServiceName(ctx); Trace("Service:" << name); return ServiceHandler::FindServiceHandler(name); } String ServiceDispatcher::FindServiceName(Context &ctx) { StartTrace(ServiceDispatcher.FindServiceName); return ctx.Lookup("DefaultService", "WebAppService"); } RegisterServiceDispatcher(RendererDispatcher); //--- RendererDispatcher --------------------------------------------------- RendererDispatcher::RendererDispatcher(const char *rendererDispatcherName) : ServiceDispatcher(rendererDispatcherName) { } RendererDispatcher::~RendererDispatcher() { } long RendererDispatcher::FindURIPrefixInList(const String &requestURI, const ROAnything &uriPrefixList) { StartTrace(RendererDispatcher.FindURIPrefixInList); long apSz = uriPrefixList.GetSize(); for (long i = 0; i < apSz; i++) { const char *uriPrefix = uriPrefixList.SlotName(i); if ( uriPrefix && requestURI.StartsWith(uriPrefix) ) { return i; } } return -1; } String RendererDispatcher::FindServiceName(Context &ctx) { StartTrace(RendererDispatcher.FindServiceName); ROAnything uriPrefixList(ctx.Lookup("URIPrefix2ServiceMap")); String requestURI(ctx.Lookup("REQUEST_URI", "")); Anything query(ctx.GetQuery()); SubTraceAny(uriPrefixList, uriPrefixList, "Service Prefixes: "); long matchedPrefix = FindURIPrefixInList(requestURI, uriPrefixList); if (matchedPrefix >= 0) { String service; Renderer::RenderOnString(service, ctx, uriPrefixList[matchedPrefix]); query["Service"] = service; query["URIPrefix"] = uriPrefixList.SlotName(matchedPrefix); SubTraceAny(query, query, "Query: "); Trace("Service:<" << service << ">"); return service; } else if (uriPrefixList.GetSize() > 0) { query["Error"] = "ServiceNotFound"; } String defaultHandler(ServiceDispatcher::FindServiceName(ctx)); Trace("Service:<" << defaultHandler << ">"); return defaultHandler; } //---- registry interface RegCacheImpl(ServiceDispatcher); // FindServiceDispatcher() <commit_msg>tracing request URI<commit_after>/* * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland * All rights reserved. * * This library/application is free software; you can redistribute and/or modify it under the terms of * the license that is included with this library/application in the file license.txt. */ //--- interface include -------------------------------------------------------- #include "ServiceDispatcher.h" //--- standard modules used ---------------------------------------------------- #include "Registry.h" #include "Timers.h" #include "ServiceHandler.h" #include "Renderer.h" #include "Dbg.h" //---- ServiceDispatchersModule ----------------------------------------------------------- RegisterModule(ServiceDispatchersModule); ServiceDispatchersModule::ServiceDispatchersModule(const char *name) : WDModule(name) { } ServiceDispatchersModule::~ServiceDispatchersModule() { } bool ServiceDispatchersModule::Init(const Anything &config) { if (config.IsDefined("ServiceDispatchers")) { HierarchyInstaller ai("ServiceDispatcher"); return RegisterableObject::Install(config["ServiceDispatchers"], "ServiceDispatcher", &ai); } return false; } bool ServiceDispatchersModule::ResetFinis(const Anything &config) { AliasTerminator at("ServiceDispatcher"); return RegisterableObject::ResetTerminate("ServiceDispatcher", &at); } bool ServiceDispatchersModule::Finis() { return StdFinis("ServiceDispatcher", "ServiceDispatchers"); } //---- ServiceDispatcher ----------------------------------------------------------- RegisterServiceDispatcher(ServiceDispatcher); ServiceDispatcher::ServiceDispatcher(const char *ServiceDispatcherName) : HierarchConfNamed(ServiceDispatcherName) { StartTrace(ServiceDispatcher.Ctor); } ServiceDispatcher::~ServiceDispatcher() { StartTrace(ServiceDispatcher.Dtor); } void ServiceDispatcher::Dispatch2Service(ostream &reply, Context &ctx) { StartTrace(ServiceDispatcher.Dispatch2Service); ctx.Push("ServiceDispatcher", this); ServiceHandler *sh = FindServiceHandler(ctx); // if no service handler is found DefaultHandler is used if (!sh) { String def = ctx.Lookup("DefaultHandler", "WebAppService"); Trace("not found, looking for DefaultHandler:" << def); sh = ServiceHandler::FindServiceHandler(def); } sh->HandleService(reply, ctx); } ServiceHandler *ServiceDispatcher::FindServiceHandler(Context &ctx) { StartTrace(ServiceDispatcher.FindServiceHandler); String name = FindServiceName(ctx); Trace("Service:" << name); return ServiceHandler::FindServiceHandler(name); } String ServiceDispatcher::FindServiceName(Context &ctx) { StartTrace(ServiceDispatcher.FindServiceName); return ctx.Lookup("DefaultService", "WebAppService"); } RegisterServiceDispatcher(RendererDispatcher); //--- RendererDispatcher --------------------------------------------------- RendererDispatcher::RendererDispatcher(const char *rendererDispatcherName) : ServiceDispatcher(rendererDispatcherName) { } RendererDispatcher::~RendererDispatcher() { } long RendererDispatcher::FindURIPrefixInList(const String &requestURI, const ROAnything &uriPrefixList) { StartTrace(RendererDispatcher.FindURIPrefixInList); long apSz = uriPrefixList.GetSize(); for (long i = 0; i < apSz; i++) { const char *uriPrefix = uriPrefixList.SlotName(i); if ( uriPrefix && requestURI.StartsWith(uriPrefix) ) { return i; } } return -1; } String RendererDispatcher::FindServiceName(Context &ctx) { StartTrace(RendererDispatcher.FindServiceName); ROAnything uriPrefixList(ctx.Lookup("URIPrefix2ServiceMap")); String requestURI(ctx.Lookup("REQUEST_URI", "")); Trace("request URI [" << requestURI << "]"); Anything query(ctx.GetQuery()); SubTraceAny(uriPrefixList, uriPrefixList, "Service Prefixes: "); long matchedPrefix = FindURIPrefixInList(requestURI, uriPrefixList); if (matchedPrefix >= 0) { String service; Renderer::RenderOnString(service, ctx, uriPrefixList[matchedPrefix]); query["Service"] = service; query["URIPrefix"] = uriPrefixList.SlotName(matchedPrefix); SubTraceAny(query, query, "Query: "); Trace("Service:<" << service << ">"); return service; } else if (uriPrefixList.GetSize() > 0) { query["Error"] = "ServiceNotFound"; } String defaultHandler(ServiceDispatcher::FindServiceName(ctx)); Trace("Service:<" << defaultHandler << ">"); return defaultHandler; } //---- registry interface RegCacheImpl(ServiceDispatcher); // FindServiceDispatcher() <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief GUI Widget Text クラス(ヘッダー) @author 平松邦仁 ([email protected]) */ //=====================================================================// #include "widgets/widget_director.hpp" namespace gui { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief GUI widget_text クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// struct widget_text : public widget { typedef widget_text value_type; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief widget_text パラメーター */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// struct param { text_param text_param_; param(const std::string& text = "") : text_param_(text, img::rgba8(255, 255), img::rgba8(0, 255), vtx::placement(vtx::placement::holizontal::LEFT, vtx::placement::vertical::TOP)) { } }; private: widget_director& wd_; param param_; public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// widget_text(widget_director& wd, const widget::param& bp, const param& p) : widget(bp), wd_(wd), param_(p) { } //-----------------------------------------------------------------// /*! @brief デストラクター */ //-----------------------------------------------------------------// virtual ~widget_text() { } //-----------------------------------------------------------------// /*! @brief 型を取得 */ //-----------------------------------------------------------------// type_id type() const { return get_type_id<value_type>(); } //-----------------------------------------------------------------// /*! @brief widget 型の基本名称を取得 @return widget 型の基本名称 */ //-----------------------------------------------------------------// const char* type_name() const { return "text"; } //-----------------------------------------------------------------// /*! @brief ハイブリッド・ウィジェットのサイン @return ハイブリッド・ウィジェットの場合「true」を返す。 */ //-----------------------------------------------------------------// bool hybrid() const { return false; } //-----------------------------------------------------------------// /*! @brief 個別パラメーターへの取得(ro) @return 個別パラメーター */ //-----------------------------------------------------------------// const param& get_local_param() const { return param_; } //-----------------------------------------------------------------// /*! @brief 個別パラメーターへの取得 @return 個別パラメーター */ //-----------------------------------------------------------------// param& at_local_param() { return param_; } //-----------------------------------------------------------------// /*! @brief 初期化 */ //-----------------------------------------------------------------// void initialize(); //-----------------------------------------------------------------// /*! @brief アップデート */ //-----------------------------------------------------------------// void update(); //-----------------------------------------------------------------// /*! @brief レンダリング */ //-----------------------------------------------------------------// void render(); //-----------------------------------------------------------------// /*! @brief サービス */ //-----------------------------------------------------------------// void service() { } //-----------------------------------------------------------------// /*! @brief 状態のセーブ @param[in] pre プリファレンス参照 @return エラーが無い場合「true」 */ //-----------------------------------------------------------------// bool save(sys::preference& pre); //-----------------------------------------------------------------// /*! @brief 状態のロード @param[in] pre プリファレンス参照 @return エラーが無い場合「true」 */ //-----------------------------------------------------------------// bool load(const sys::preference& pre); }; } <commit_msg>update into header<commit_after>#pragma once //=====================================================================// /*! @file @brief GUI Widget Text クラス @n Copyright 2017 Kunihito Hiramatsu @author 平松邦仁 ([email protected]) */ //=====================================================================// #include "core/glcore.hpp" #include "widgets/widget_director.hpp" #include "widgets/widget_frame.hpp" #include "widgets/widget_utils.hpp" namespace gui { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief GUI widget_text クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// struct widget_text : public widget { typedef widget_text value_type; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief widget_text パラメーター */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// struct param { text_param text_param_; param(const std::string& text = "") : text_param_(text, img::rgba8(255, 255), img::rgba8(0, 255), vtx::placement(vtx::placement::holizontal::LEFT, vtx::placement::vertical::TOP)) { } }; private: widget_director& wd_; param param_; public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// widget_text(widget_director& wd, const widget::param& bp, const param& p) : widget(bp), wd_(wd), param_(p) { } //-----------------------------------------------------------------// /*! @brief デストラクター */ //-----------------------------------------------------------------// virtual ~widget_text() { } //-----------------------------------------------------------------// /*! @brief 型を取得 */ //-----------------------------------------------------------------// type_id type() const override { return get_type_id<value_type>(); } //-----------------------------------------------------------------// /*! @brief widget 型の基本名称を取得 @return widget 型の基本名称 */ //-----------------------------------------------------------------// const char* type_name() const override { return "text"; } //-----------------------------------------------------------------// /*! @brief ハイブリッド・ウィジェットのサイン @return ハイブリッド・ウィジェットの場合「true」を返す。 */ //-----------------------------------------------------------------// bool hybrid() const override { return false; } //-----------------------------------------------------------------// /*! @brief 個別パラメーターへの取得(ro) @return 個別パラメーター */ //-----------------------------------------------------------------// const param& get_local_param() const { return param_; } //-----------------------------------------------------------------// /*! @brief 個別パラメーターへの取得 @return 個別パラメーター */ //-----------------------------------------------------------------// param& at_local_param() { return param_; } //-----------------------------------------------------------------// /*! @brief 初期化 */ //-----------------------------------------------------------------// void initialize() override { // 標準的に固定 at_param().state_.set(widget::state::POSITION_LOCK); at_param().state_.set(widget::state::SIZE_LOCK); at_param().state_.set(widget::state::MOVE_ROOT); } //-----------------------------------------------------------------// /*! @brief アップデート */ //-----------------------------------------------------------------// void update() override { } //-----------------------------------------------------------------// /*! @brief サービス */ //-----------------------------------------------------------------// void service() override { } //-----------------------------------------------------------------// /*! @brief レンダリング */ //-----------------------------------------------------------------// void render() override { using namespace gl; core& core = core::get_instance(); const vtx::spos& vsz = core.get_size(); const widget::param& wp = get_param(); if(wp.clip_.size.x > 0 && wp.clip_.size.y > 0) { auto clip = wp.clip_; glPushMatrix(); vtx::irect rect; if(wp.state_[widget::state::CLIP_PARENTS]) { vtx::ipos o(0); vtx::ipos w(0); widget_frame* par = static_cast<widget_frame*>(wp.parents_); if(par != nullptr && par->type() == get_type_id<widget_frame>()) { const auto& plate = par->get_local_param().plate_param_; o.x = plate.frame_width_; o.y = plate.frame_width_ + plate.caption_width_; w.x = plate.frame_width_ * 2; w.y = o.y + plate.frame_width_ + 4; clip.size.y -= plate.frame_width_; } rect.org = wp.rpos_ + o; rect.size = wp.rect_.size - w; } else { rect.org.set(0); rect.size = wp.rect_.size; } widget::text_param tpr = param_.text_param_; const img::rgbaf& cf = wd_.get_color(); tpr.fore_color_ *= cf.r; tpr.fore_color_.alpha_scale(cf.a); tpr.shadow_color_ *= cf.r; tpr.shadow_color_.alpha_scale(cf.a); draw_text(tpr, rect, clip); core.at_fonts().restore_matrix(); glPopMatrix(); glViewport(0, 0, vsz.x, vsz.y); } } //-----------------------------------------------------------------// /*! @brief 状態のセーブ @param[in] pre プリファレンス参照 @return エラーが無い場合「true」 */ //-----------------------------------------------------------------// bool save(sys::preference& pre) override { std::string path; path += '/'; path += wd_.create_widget_name(this); int err = 0; if(!pre.put_text(path + "/text", param_.text_param_.get_text())) ++err; return err == 0; } //-----------------------------------------------------------------// /*! @brief 状態のロード @param[in] pre プリファレンス参照 @return エラーが無い場合「true」 */ //-----------------------------------------------------------------// bool load(const sys::preference& pre) override { std::string path; path += '/'; path += wd_.create_widget_name(this); int err = 0; std::string s; if(!pre.get_text(path + "/text", s)) { ++err; } else { param_.text_param_.set_text(s); } return err == 0; } }; } <|endoftext|>
<commit_before>// RUN: %clangxx_hwasan %s #include <stddef.h> #include <new> char *__dummy; void *operator new(size_t size) { return __dummy; } void *operator new[](size_t size) { return __dummy; } void *operator new(size_t size, std::nothrow_t const&) noexcept { return __dummy; } void *operator new[](size_t size, std::nothrow_t const&) noexcept { return __dummy; } void operator delete(void *ptr) noexcept {} void operator delete[](void *ptr) noexcept {} void operator delete(void *ptr, std::nothrow_t const&) noexcept {} void operator delete[](void *ptr, std::nothrow_t const&) noexcept {} int main() { return 0; } <commit_msg>Set an output file name for the override-new-delete.cpp test.<commit_after>// RUN: %clangxx_hwasan %s -o %t #include <stddef.h> #include <new> char *__dummy; void *operator new(size_t size) { return __dummy; } void *operator new[](size_t size) { return __dummy; } void *operator new(size_t size, std::nothrow_t const&) noexcept { return __dummy; } void *operator new[](size_t size, std::nothrow_t const&) noexcept { return __dummy; } void operator delete(void *ptr) noexcept {} void operator delete[](void *ptr) noexcept {} void operator delete(void *ptr, std::nothrow_t const&) noexcept {} void operator delete[](void *ptr, std::nothrow_t const&) noexcept {} int main() { return 0; } <|endoftext|>
<commit_before>#ifndef CHARTS_CONFIG_HH #define CHARTS_CONFIG_HH 1 #include <memory> #include <utility> #include <vector> #include "catalogue.hh" #include "projection.hh" #include "track.hh" class Config; template <typename T> class ConfigIterator { ConfigIterator(const Config * config, std::size_t index) : config_(config), index_(index) { } friend class Config; public: ConfigIterator(const ConfigIterator & rhs) = default; ConfigIterator & operator=(const ConfigIterator & rhs) = default; ConfigIterator & operator++() { ++index_; return *this; } const std::shared_ptr<T> operator->() const; T & operator*() const { return *(*this).operator->(); } bool operator==(const ConfigIterator & rhs) const { if (config_ != rhs.config_) return false; if (index_ != rhs.index_) return false; return true; } bool operator!=(const ConfigIterator & rhs) const { return !(*this == rhs); } private: const Config * config_; std::size_t index_; }; class Config { struct Implementation; std::unique_ptr<Implementation> imp_; template <typename T> friend class ConfigIterator; template <typename T> const std::shared_ptr<T> get_collection_item(std::size_t i) const; public: Config(int arc, char * arv[]); ~Config(); const ln_lnlat_posn location() const; const CanvasPoint canvas_dimensions() const; double canvas_margin() const; const std::string projection_type() const; const ln_equ_posn projection_centre() const; const ln_equ_posn projection_dimensions() const; const std::string projection_level() const; double t() const; const std::string stylesheet() const; const std::string output() const; template <typename T> struct View { explicit View(const Config * config) : config_(config) { } const ConfigIterator<T> begin() const { return ConfigIterator<T>(config_, 0); } const ConfigIterator<T> end() const; const Config * config_; }; template <typename T> const View<T> view() const { return View<T>(this); } const std::vector<std::string> planets() const; bool planets_labels() const; bool moon() const; bool sun() const; private: timestamp sanitize_timestamp(const timestamp & ts) const; void update_timestamps(); }; #endif <commit_msg>move template implementations out of class<commit_after>#ifndef CHARTS_CONFIG_HH #define CHARTS_CONFIG_HH 1 #include <memory> #include <utility> #include <vector> #include "catalogue.hh" #include "projection.hh" #include "track.hh" class Config; template <typename T> class ConfigIterator { ConfigIterator(const Config * config, std::size_t index) : config_(config), index_(index) { } friend class Config; public: ConfigIterator(const ConfigIterator & rhs) = default; ConfigIterator & operator=(const ConfigIterator & rhs) = default; ConfigIterator & operator++() { ++index_; return *this; } const std::shared_ptr<T> operator->() const; T & operator*() const { return *(*this).operator->(); } bool operator==(const ConfigIterator & rhs) const { if (config_ != rhs.config_) return false; if (index_ != rhs.index_) return false; return true; } bool operator!=(const ConfigIterator & rhs) const { return !(*this == rhs); } private: const Config * config_; std::size_t index_; }; class Config { struct Implementation; std::unique_ptr<Implementation> imp_; template <typename T> friend class ConfigIterator; template <typename T> const std::shared_ptr<T> get_collection_item(std::size_t i) const; public: Config(int arc, char * arv[]); ~Config(); const ln_lnlat_posn location() const; const CanvasPoint canvas_dimensions() const; double canvas_margin() const; const std::string projection_type() const; const ln_equ_posn projection_centre() const; const ln_equ_posn projection_dimensions() const; const std::string projection_level() const; double t() const; const std::string stylesheet() const; const std::string output() const; template <typename T> struct View; template <typename T> const View<T> view() const; const std::vector<std::string> planets() const; bool planets_labels() const; bool moon() const; bool sun() const; private: timestamp sanitize_timestamp(const timestamp & ts) const; void update_timestamps(); }; template <typename T> struct Config::View { explicit View(const Config * config) : config_(config) { } const ConfigIterator<T> begin() const { return ConfigIterator<T>(config_, 0); } const ConfigIterator<T> end() const; const Config * config_; }; template <typename T> const Config::View<T> Config::view() const { return View<T>(this); } #endif <|endoftext|>
<commit_before>#include "Debug.h" #include <sstream> #include <string> void CDebug::Init(void) { v8::HandleScope scope; v8::Handle<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New(); m_global_context = v8::Context::New(NULL, global_template); m_global_context->SetSecurityToken(v8::Undefined()); } void CDebug::SetEnable(bool enable) { if (m_enabled == enable) return; v8::HandleScope scope; v8::Context::Scope context_scope(m_global_context); if (enable) { v8::Handle<v8::External> data = v8::External::New(this); v8::Debug::SetDebugEventListener(OnDebugEvent, data); v8::Debug::SetMessageHandler(OnDebugMessage, this); } else { v8::Debug::SetDebugEventListener(NULL); v8::Debug::SetMessageHandler(NULL); } m_enabled = enable; } void CDebug::OnDebugEvent(v8::DebugEvent event, v8::Handle<v8::Object> exec_state, v8::Handle<v8::Object> event_data, v8::Handle<v8::Value> data) { v8::HandleScope scope; CDebug *pThis = static_cast<CDebug *>(v8::Handle<v8::External>::Cast(data)->Value()); if (pThis->m_onDebugEvent.ptr() == Py_None) return; v8::Context::Scope context_scope(pThis->m_global_context); CJavascriptObjectPtr event_obj(new CJavascriptObject(pThis->m_global_context, event_data)); py::call<void>(pThis->m_onDebugEvent.ptr(), event, event_obj); } void CDebug::OnDebugMessage(const uint16_t* message, int length, void* data) { CDebug *pThis = static_cast<CDebug *>(data); if (pThis->m_onDebugMessage.ptr() == Py_None) return; std::wstring msg(reinterpret_cast<std::wstring::const_pointer>(message), length); py::call<void>(pThis->m_onDebugMessage.ptr(), msg); } void CDebug::Expose(void) { py::class_<CDebug, boost::noncopyable>("JSDebug", py::no_init) .add_property("enabled", &CDebug::IsEnabled, &CDebug::SetEnable) .def_readwrite("onDebugEvent", &CDebug::m_onDebugEvent) .def_readwrite("onDebugMessage", &CDebug::m_onDebugMessage) ; py::enum_<v8::DebugEvent>("JSDebugEvent") .value("Break", v8::Break) .value("Exception", v8::Exception) .value("NewFunction", v8::NewFunction) .value("BeforeCompile", v8::BeforeCompile) .value("AfterCompile", v8::AfterCompile) ; def("debug", &CDebug::GetInstance, py::return_value_policy<py::reference_existing_object>()); } <commit_msg>use a flag to disable debug events for python callback functions<commit_after>#include "Debug.h" #include <sstream> #include <string> void CDebug::Init(void) { v8::HandleScope scope; v8::Handle<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New(); m_global_context = v8::Context::New(NULL, global_template); m_global_context->SetSecurityToken(v8::Undefined()); v8::Handle<v8::External> data = v8::External::New(this); v8::Debug::SetDebugEventListener(OnDebugEvent, data); v8::Debug::SetMessageHandler(OnDebugMessage, this); } void CDebug::SetEnable(bool enable) { if (m_enabled == enable) return; m_enabled = enable; } void CDebug::OnDebugEvent(v8::DebugEvent event, v8::Handle<v8::Object> exec_state, v8::Handle<v8::Object> event_data, v8::Handle<v8::Value> data) { v8::HandleScope scope; CDebug *pThis = static_cast<CDebug *>(v8::Handle<v8::External>::Cast(data)->Value()); if (!pThis->m_enabled) return; if (pThis->m_onDebugEvent.ptr() == Py_None) return; v8::Context::Scope context_scope(pThis->m_global_context); CJavascriptObjectPtr event_obj(new CJavascriptObject(pThis->m_global_context, event_data)); py::call<void>(pThis->m_onDebugEvent.ptr(), event, event_obj); } void CDebug::OnDebugMessage(const uint16_t* message, int length, void* data) { CDebug *pThis = static_cast<CDebug *>(data); if (!pThis->m_enabled) return; if (pThis->m_onDebugMessage.ptr() == Py_None) return; std::wstring msg(reinterpret_cast<std::wstring::const_pointer>(message), length); py::call<void>(pThis->m_onDebugMessage.ptr(), msg); } void CDebug::Expose(void) { py::class_<CDebug, boost::noncopyable>("JSDebug", py::no_init) .add_property("enabled", &CDebug::IsEnabled, &CDebug::SetEnable) .def_readwrite("onDebugEvent", &CDebug::m_onDebugEvent) .def_readwrite("onDebugMessage", &CDebug::m_onDebugMessage) ; py::enum_<v8::DebugEvent>("JSDebugEvent") .value("Break", v8::Break) .value("Exception", v8::Exception) .value("NewFunction", v8::NewFunction) .value("BeforeCompile", v8::BeforeCompile) .value("AfterCompile", v8::AfterCompile) ; def("debug", &CDebug::GetInstance, py::return_value_policy<py::reference_existing_object>()); } <|endoftext|>
<commit_before>#ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #include <cppuhelper/factory.hxx> #include <uno/mapping.hxx> #include "provider.hxx" #include "renderer.hxx" #include <com/sun/star/registry/XRegistryKey.hpp> using namespace com::sun::star; namespace unographic { // -------------------- // - *_createInstance - // -------------------- static uno::Reference< uno::XInterface > SAL_CALL GraphicProvider_createInstance( const uno::Reference< lang::XMultiServiceFactory >& rxManager) { return SAL_STATIC_CAST( ::cppu::OWeakObject*, new GraphicProvider ); } // ----------------------------------------------------------------------------- static uno::Reference< uno::XInterface > SAL_CALL GraphicRendererVCL_createInstance( const uno::Reference< lang::XMultiServiceFactory >& rxManager) { return SAL_STATIC_CAST( ::cppu::OWeakObject*, new GraphicRendererVCL ); } // ------------------------------------------ // - component_getImplementationEnvironment - // ------------------------------------------ extern "C" void SAL_CALL component_getImplementationEnvironment( const sal_Char** ppEnvTypeName, uno_Environment** ppEnv ) { *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; } // ----------------------- // - component_writeInfo - // ----------------------- extern "C" sal_Bool SAL_CALL component_writeInfo( void* pServiceManager, void* pRegistryKey ) { sal_Bool bRet = sal_False; if( pRegistryKey ) { try { uno::Reference< registry::XRegistryKey > xNewKey; uno::Sequence< ::rtl::OUString > aServices; // GraphicProvider xNewKey = reinterpret_cast< registry::XRegistryKey * >( pRegistryKey )->createKey( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/") ) + GraphicProvider::getImplementationName_Static() + ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "/UNO/SERVICES") ) ); aServices = GraphicProvider::getSupportedServiceNames_Static(); for( int i = 0; i < aServices.getLength(); i++ ) xNewKey->createKey( aServices.getConstArray()[ i ] ); // GraphicRendererVCL xNewKey = reinterpret_cast< registry::XRegistryKey * >( pRegistryKey )->createKey( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/") ) + GraphicRendererVCL::getImplementationName_Static() + ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "/UNO/SERVICES") ) ); aServices = ( GraphicRendererVCL::getSupportedServiceNames_Static() ); for( int i = 0; i < aServices.getLength(); i++ ) xNewKey->createKey( aServices.getConstArray()[ i ] ); bRet = true; } catch (registry::InvalidRegistryException &) { OSL_ENSURE( sal_False, "### InvalidRegistryException!" ); } } return bRet; } // ------------------------ // - component_getFactory - // ------------------------ extern "C" void* SAL_CALL component_getFactory( const sal_Char* pImplName, void* pServiceManager, void* pRegistryKey ) { void * pRet = 0; if( pServiceManager && ( 0 == GraphicProvider::getImplementationName_Static().compareToAscii( pImplName ) ) ) { uno::Reference< lang::XSingleServiceFactory > xFactory( ::cppu::createOneInstanceFactory( reinterpret_cast< lang::XMultiServiceFactory * >( pServiceManager ), GraphicProvider::getImplementationName_Static(), GraphicProvider_createInstance, GraphicProvider::getSupportedServiceNames_Static() ) ); if( xFactory.is()) { xFactory->acquire(); pRet = xFactory.get(); } } else if( pServiceManager && ( 0 == GraphicRendererVCL::getImplementationName_Static().compareToAscii( pImplName ) ) ) { uno::Reference< lang::XSingleServiceFactory > xFactory( ::cppu::createOneInstanceFactory( reinterpret_cast< lang::XMultiServiceFactory * >( pServiceManager ), GraphicRendererVCL::getImplementationName_Static(), GraphicRendererVCL_createInstance, GraphicRendererVCL::getSupportedServiceNames_Static() ) ); if( xFactory.is()) { xFactory->acquire(); pRet = xFactory.get(); } } return pRet; } } <commit_msg>#i10000# for scope<commit_after>#ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #include <cppuhelper/factory.hxx> #include <uno/mapping.hxx> #include "provider.hxx" #include "renderer.hxx" #include <com/sun/star/registry/XRegistryKey.hpp> using namespace com::sun::star; namespace unographic { // -------------------- // - *_createInstance - // -------------------- static uno::Reference< uno::XInterface > SAL_CALL GraphicProvider_createInstance( const uno::Reference< lang::XMultiServiceFactory >& rxManager) { return SAL_STATIC_CAST( ::cppu::OWeakObject*, new GraphicProvider ); } // ----------------------------------------------------------------------------- static uno::Reference< uno::XInterface > SAL_CALL GraphicRendererVCL_createInstance( const uno::Reference< lang::XMultiServiceFactory >& rxManager) { return SAL_STATIC_CAST( ::cppu::OWeakObject*, new GraphicRendererVCL ); } // ------------------------------------------ // - component_getImplementationEnvironment - // ------------------------------------------ extern "C" void SAL_CALL component_getImplementationEnvironment( const sal_Char** ppEnvTypeName, uno_Environment** ppEnv ) { *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; } // ----------------------- // - component_writeInfo - // ----------------------- extern "C" sal_Bool SAL_CALL component_writeInfo( void* pServiceManager, void* pRegistryKey ) { sal_Bool bRet = sal_False; if( pRegistryKey ) { try { uno::Reference< registry::XRegistryKey > xNewKey; uno::Sequence< ::rtl::OUString > aServices; // GraphicProvider xNewKey = reinterpret_cast< registry::XRegistryKey * >( pRegistryKey )->createKey( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/") ) + GraphicProvider::getImplementationName_Static() + ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "/UNO/SERVICES") ) ); aServices = GraphicProvider::getSupportedServiceNames_Static(); int i; for( i = 0; i < aServices.getLength(); i++ ) xNewKey->createKey( aServices.getConstArray()[ i ] ); // GraphicRendererVCL xNewKey = reinterpret_cast< registry::XRegistryKey * >( pRegistryKey )->createKey( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/") ) + GraphicRendererVCL::getImplementationName_Static() + ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "/UNO/SERVICES") ) ); aServices = ( GraphicRendererVCL::getSupportedServiceNames_Static() ); for( i = 0; i < aServices.getLength(); i++ ) xNewKey->createKey( aServices.getConstArray()[ i ] ); bRet = true; } catch (registry::InvalidRegistryException &) { OSL_ENSURE( sal_False, "### InvalidRegistryException!" ); } } return bRet; } // ------------------------ // - component_getFactory - // ------------------------ extern "C" void* SAL_CALL component_getFactory( const sal_Char* pImplName, void* pServiceManager, void* pRegistryKey ) { void * pRet = 0; if( pServiceManager && ( 0 == GraphicProvider::getImplementationName_Static().compareToAscii( pImplName ) ) ) { uno::Reference< lang::XSingleServiceFactory > xFactory( ::cppu::createOneInstanceFactory( reinterpret_cast< lang::XMultiServiceFactory * >( pServiceManager ), GraphicProvider::getImplementationName_Static(), GraphicProvider_createInstance, GraphicProvider::getSupportedServiceNames_Static() ) ); if( xFactory.is()) { xFactory->acquire(); pRet = xFactory.get(); } } else if( pServiceManager && ( 0 == GraphicRendererVCL::getImplementationName_Static().compareToAscii( pImplName ) ) ) { uno::Reference< lang::XSingleServiceFactory > xFactory( ::cppu::createOneInstanceFactory( reinterpret_cast< lang::XMultiServiceFactory * >( pServiceManager ), GraphicRendererVCL::getImplementationName_Static(), GraphicRendererVCL_createInstance, GraphicRendererVCL::getSupportedServiceNames_Static() ) ); if( xFactory.is()) { xFactory->acquire(); pRet = xFactory.get(); } } return pRet; } } <|endoftext|>
<commit_before>// Copyright 2012-2013 Samplecount S.L. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "Methcla/Audio/IO/OpenSLESDriver.hpp" #include "Methcla/Memory.hpp" #include "opensl_io.h" #include <android/log.h> #include <cassert> #include <stdexcept> #define LOGI(...) \ __android_log_print(ANDROID_LOG_INFO, "OpenSLESDriver", __VA_ARGS__) #define LOGW(...) \ __android_log_print(ANDROID_LOG_WARN, "OpenSLESDriver", __VA_ARGS__) using namespace Methcla::Audio::IO; OpenSLESDriver::OpenSLESDriver() : m_stream(nullptr) , m_sampleRate(44100) , m_numInputs(0) , m_numOutputs(2) , m_bufferSize(512) , m_inputBuffers(nullptr) , m_outputBuffers(nullptr) { m_stream = opensl_open( (int)m_sampleRate, (int)m_numInputs, (int)m_numOutputs, (int)m_bufferSize, processCallback, this ); if (m_stream == nullptr) { throw std::runtime_error("OpenSLESDriver: Couldn't open audio stream"); } m_inputBuffers = makeBuffers(m_numInputs, m_bufferSize); m_outputBuffers = makeBuffers(m_numOutputs, m_bufferSize); } OpenSLESDriver::~OpenSLESDriver() { if (m_stream != nullptr) opensl_close(m_stream); } void OpenSLESDriver::start() { if (m_stream != nullptr) opensl_start(m_stream); } void OpenSLESDriver::stop() { if (m_stream != nullptr) opensl_pause(m_stream); } void OpenSLESDriver::processCallback( void* context, int sample_rate, int buffer_frames, int input_channels, const short* input_buffer, int output_channels, short* output_buffer) { OpenSLESDriver* self = static_cast<OpenSLESDriver*>(context); const size_t numInputs = self->m_numInputs; const size_t numOutputs = self->m_numOutputs; const size_t bufferSize = self->m_bufferSize; const size_t numFrames = (size_t)buffer_frames; assert( self->m_sampleRate == (double)sample_rate ); assert( numInputs == (size_t)input_channels ); assert( numOutputs == (size_t)output_channels ); assert( buffer_frames >= 0 && bufferSize <= (size_t)buffer_frames ); sample_t** inputBuffers = self->m_inputBuffers; sample_t** outputBuffers = self->m_outputBuffers; // Deinterleave and convert input for (size_t curChan = 0; curChan < numInputs; curChan++) { for (size_t curFrame = 0; curFrame < numFrames; curFrame++) { inputBuffers[curChan][curFrame] = input_buffer[curFrame * numInputs + curChan] / 32768.f; } } // Run DSP graph try { self->process(numFrames, inputBuffers, outputBuffers); } catch (std::exception& e) { LOGW(e.what()); } #ifndef NDEBUG catch (...) { LOGW("Unknown exception caught"); } #endif // Convert and interleave output for (size_t curChan = 0; curChan < numOutputs; curChan++) { for (size_t curFrame = 0; curFrame < numFrames; curFrame++) { output_buffer[curFrame * numOutputs + curChan] = outputBuffers[curChan][curFrame] * 32767.f; } } } Driver* Methcla::Audio::IO::defaultPlatformDriver() { return new OpenSLESDriver(); } <commit_msg>Fix compiler warning in release mode<commit_after>// Copyright 2012-2013 Samplecount S.L. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "Methcla/Audio/IO/OpenSLESDriver.hpp" #include "Methcla/Memory.hpp" #include "opensl_io.h" #include <android/log.h> #include <cassert> #include <stdexcept> #define LOGI(...) \ __android_log_print(ANDROID_LOG_INFO, "OpenSLESDriver", __VA_ARGS__) #define LOGW(...) \ __android_log_print(ANDROID_LOG_WARN, "OpenSLESDriver", __VA_ARGS__) using namespace Methcla::Audio::IO; OpenSLESDriver::OpenSLESDriver() : m_stream(nullptr) , m_sampleRate(44100) , m_numInputs(0) , m_numOutputs(2) , m_bufferSize(512) , m_inputBuffers(nullptr) , m_outputBuffers(nullptr) { m_stream = opensl_open( (int)m_sampleRate, (int)m_numInputs, (int)m_numOutputs, (int)m_bufferSize, processCallback, this ); if (m_stream == nullptr) { throw std::runtime_error("OpenSLESDriver: Couldn't open audio stream"); } m_inputBuffers = makeBuffers(m_numInputs, m_bufferSize); m_outputBuffers = makeBuffers(m_numOutputs, m_bufferSize); } OpenSLESDriver::~OpenSLESDriver() { if (m_stream != nullptr) opensl_close(m_stream); } void OpenSLESDriver::start() { if (m_stream != nullptr) opensl_start(m_stream); } void OpenSLESDriver::stop() { if (m_stream != nullptr) opensl_pause(m_stream); } void OpenSLESDriver::processCallback( void* context, int sample_rate, int buffer_frames, int input_channels, const short* input_buffer, int output_channels, short* output_buffer) { OpenSLESDriver* self = static_cast<OpenSLESDriver*>(context); const size_t numInputs = self->m_numInputs; const size_t numOutputs = self->m_numOutputs; const size_t numFrames = (size_t)buffer_frames; assert( self->m_sampleRate == (double)sample_rate ); assert( numInputs == (size_t)input_channels ); assert( numOutputs == (size_t)output_channels ); assert( buffer_frames >= 0 && self->m_bufferSize <= (size_t)buffer_frames ); sample_t** inputBuffers = self->m_inputBuffers; sample_t** outputBuffers = self->m_outputBuffers; // Deinterleave and convert input for (size_t curChan = 0; curChan < numInputs; curChan++) { for (size_t curFrame = 0; curFrame < numFrames; curFrame++) { inputBuffers[curChan][curFrame] = input_buffer[curFrame * numInputs + curChan] / 32768.f; } } // Run DSP graph try { self->process(numFrames, inputBuffers, outputBuffers); } catch (std::exception& e) { LOGW(e.what()); } #ifndef NDEBUG catch (...) { LOGW("Unknown exception caught"); } #endif // Convert and interleave output for (size_t curChan = 0; curChan < numOutputs; curChan++) { for (size_t curFrame = 0; curFrame < numFrames; curFrame++) { output_buffer[curFrame * numOutputs + curChan] = outputBuffers[curChan][curFrame] * 32767.f; } } } Driver* Methcla::Audio::IO::defaultPlatformDriver() { return new OpenSLESDriver(); } <|endoftext|>
<commit_before>/* * Copyright 2015-2017, Robotics and Biology Lab, TU Berlin * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "hybrid_automaton/ForceTorqueSensor.h" namespace ha { HA_SENSOR_REGISTER("ForceTorqueSensor", ForceTorqueSensor); ForceTorqueSensor::ForceTorqueSensor() : _port(DEFAULT_FT_PORT) { } ForceTorqueSensor::~ForceTorqueSensor() { } ForceTorqueSensor::ForceTorqueSensor(const ForceTorqueSensor& ss) :Sensor(ss) { _port = ss._port; } ::Eigen::MatrixXd ForceTorqueSensor::transformWrench(const ::Eigen::MatrixXd& wrench, const ::Eigen::MatrixXd& transform) const { ::Eigen::Matrix3d frameRot = transform.block(0,0,3,3); ::Eigen::Vector3d frameTrans(transform(0,3), transform(1,3), transform(2,3)); ::Eigen::Vector3d forcePart(wrench(0,0), wrench(1,0),wrench(2,0)); ::Eigen::Vector3d momentPart(wrench(3,0), wrench(4,0),wrench(5,0)); forcePart = frameRot*forcePart; momentPart = frameRot*(momentPart - frameTrans.cross(forcePart)); Eigen::MatrixXd wrenchOut(6,1); wrenchOut(0) = forcePart(0); wrenchOut(1) = forcePart(1); wrenchOut(2) = forcePart(2); wrenchOut(3) = momentPart(0); wrenchOut(4) = momentPart(1); wrenchOut(5) = momentPart(2); return wrenchOut; } int k; ::Eigen::MatrixXd ForceTorqueSensor::getCurrentValue() const { //This is the F/T wrench from the hardware - It must be in EE frame ::Eigen::MatrixXd forceTorque = _system->getForceTorqueMeasurement(_port); ::Eigen::MatrixXd eeFrame = _system->getFramePose("EE"); //Transform FT wrench to world frame Eigen::MatrixXd ftOut = transformWrench(forceTorque, eeFrame.inverse()); //Transform FT wrench to given frame ftOut = transformWrench(ftOut, _frame); if((k++)%2000 == 0) HA_INFO("ForceTorqueSensor.getCurrentValue","ftout: "<<ftOut.transpose()); return ftOut; } DescriptionTreeNode::Ptr ForceTorqueSensor::serialize(const DescriptionTree::ConstPtr& factory) const { DescriptionTreeNode::Ptr tree = factory->createNode("Sensor"); tree->setAttribute<std::string>(std::string("type"), this->getType()); tree->setAttribute<int>(std::string("port"), _port); return tree; } void ForceTorqueSensor::deserialize(const DescriptionTreeNode::ConstPtr& tree, const System::ConstPtr& system, const HybridAutomaton* ha) { if (tree->getType() != "Sensor") { HA_THROW_ERROR("ForceTorqueSensor.deserialize", "DescriptionTreeNode must have type 'Sensor', not '" << tree->getType() << "'!"); } tree->getAttribute<std::string>("type", _type, ""); tree->getAttribute<int>("port", _port, DEFAULT_FT_PORT); if(_port > 2 || _port <0) { HA_THROW_ERROR("ForceTorqueSensor.deserialize", "Port number " << _port << " " << "invalid - it must be between 0 and 2!"); } if (_type == "" || !HybridAutomaton::isSensorRegistered(_type)) { HA_THROW_ERROR("ForceTorqueSensor.deserialize", "SensorType type '" << _type << "' " << "invalid - empty or not registered with HybridAutomaton!"); } _frame.resize(4,4); _frame.setIdentity(); if(tree->getAttribute< Eigen::MatrixXd>("frame", _frame)) { HA_INFO("ForceTorqueSensor.deserialize", "Using external frame to express F/T value in"); if(_frame.cols()!=4 || _frame.rows()!=4) { HA_THROW_ERROR("ForceTorqueSensor.deserialize", "frame parameter must be 4x4 homogeneous transform!"); } } _system = system; } } <commit_msg>fix transform<commit_after>/* * Copyright 2015-2017, Robotics and Biology Lab, TU Berlin * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "hybrid_automaton/ForceTorqueSensor.h" namespace ha { HA_SENSOR_REGISTER("ForceTorqueSensor", ForceTorqueSensor); ForceTorqueSensor::ForceTorqueSensor() : _port(DEFAULT_FT_PORT) { } ForceTorqueSensor::~ForceTorqueSensor() { } ForceTorqueSensor::ForceTorqueSensor(const ForceTorqueSensor& ss) :Sensor(ss) { _port = ss._port; } ::Eigen::MatrixXd ForceTorqueSensor::transformWrench(const ::Eigen::MatrixXd& wrench, const ::Eigen::MatrixXd& transform) const { ::Eigen::Matrix3d frameRot = transform.block(0,0,3,3); ::Eigen::Vector3d frameTrans(transform(0,3), transform(1,3), transform(2,3)); ::Eigen::Vector3d forcePart(wrench(0,0), wrench(1,0),wrench(2,0)); ::Eigen::Vector3d momentPart(wrench(3,0), wrench(4,0),wrench(5,0)); forcePart = frameRot.transpose()*forcePart; momentPart = frameRot.transpose()*(momentPart - frameTrans.cross(forcePart)); Eigen::MatrixXd wrenchOut(6,1); wrenchOut(0) = forcePart(0); wrenchOut(1) = forcePart(1); wrenchOut(2) = forcePart(2); wrenchOut(3) = momentPart(0); wrenchOut(4) = momentPart(1); wrenchOut(5) = momentPart(2); return wrenchOut; } int k; ::Eigen::MatrixXd ForceTorqueSensor::getCurrentValue() const { //This is the F/T wrench from the hardware - It must be in EE frame ::Eigen::MatrixXd forceTorque = _system->getForceTorqueMeasurement(_port); ::Eigen::MatrixXd eeFrame = _system->getFramePose("EE"); //Transform FT wrench to world frame Eigen::MatrixXd ftOut = transformWrench(forceTorque, eeFrame.inverse()); //Transform FT wrench to given frame ftOut = transformWrench(ftOut, _frame); if((k++)%2000 == 0) HA_INFO("ForceTorqueSensor.getCurrentValue","ftout: "<<ftOut.transpose()); return ftOut; } DescriptionTreeNode::Ptr ForceTorqueSensor::serialize(const DescriptionTree::ConstPtr& factory) const { DescriptionTreeNode::Ptr tree = factory->createNode("Sensor"); tree->setAttribute<std::string>(std::string("type"), this->getType()); tree->setAttribute<int>(std::string("port"), _port); return tree; } void ForceTorqueSensor::deserialize(const DescriptionTreeNode::ConstPtr& tree, const System::ConstPtr& system, const HybridAutomaton* ha) { if (tree->getType() != "Sensor") { HA_THROW_ERROR("ForceTorqueSensor.deserialize", "DescriptionTreeNode must have type 'Sensor', not '" << tree->getType() << "'!"); } tree->getAttribute<std::string>("type", _type, ""); tree->getAttribute<int>("port", _port, DEFAULT_FT_PORT); if(_port > 2 || _port <0) { HA_THROW_ERROR("ForceTorqueSensor.deserialize", "Port number " << _port << " " << "invalid - it must be between 0 and 2!"); } if (_type == "" || !HybridAutomaton::isSensorRegistered(_type)) { HA_THROW_ERROR("ForceTorqueSensor.deserialize", "SensorType type '" << _type << "' " << "invalid - empty or not registered with HybridAutomaton!"); } _frame.resize(4,4); _frame.setIdentity(); if(tree->getAttribute< Eigen::MatrixXd>("frame", _frame)) { HA_INFO("ForceTorqueSensor.deserialize", "Using external frame to express F/T value in"); if(_frame.cols()!=4 || _frame.rows()!=4) { HA_THROW_ERROR("ForceTorqueSensor.deserialize", "frame parameter must be 4x4 homogeneous transform!"); } } _system = system; } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: unchss.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-09 04:26:10 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #pragma hdrstop #ifndef _SFXITEMSET_HXX //autogen #include <svtools/itemset.hxx> #endif #ifndef _SFXSTYLE_HXX //autogen #include <svtools/style.hxx> #endif #ifndef _SFXSMPLHINT_HXX //autogen #include <svtools/smplhint.hxx> #endif #ifndef _SVDOBJ_HXX #include <svx/svdobj.hxx> #endif #include "unchss.hxx" #include "strings.hrc" #include "glob.hxx" #include "sdresid.hxx" #include "drawdoc.hxx" #include "stlsheet.hxx" TYPEINIT1(StyleSheetUndoAction, SdUndoAction); /************************************************************************* |* |* Konstruktor |* \************************************************************************/ StyleSheetUndoAction::StyleSheetUndoAction(SdDrawDocument* pTheDoc, SfxStyleSheet* pTheStyleSheet, const SfxItemSet* pTheNewItemSet) : SdUndoAction(pTheDoc) { DBG_ASSERT(pTheStyleSheet, "Undo ohne StyleSheet ???"); pStyleSheet = pTheStyleSheet; // ItemSets anlegen; Vorsicht, das neue koennte aus einem anderen Pool // stammen, also mitsamt seinen Items clonen pNewSet = new SfxItemSet((SfxItemPool&)SdrObject::GetGlobalDrawObjectItemPool(), pTheNewItemSet->GetRanges()); pTheDoc->MigrateItemSet( pTheNewItemSet, pNewSet, pTheDoc ); pOldSet = new SfxItemSet((SfxItemPool&)SdrObject::GetGlobalDrawObjectItemPool(),pStyleSheet->GetItemSet().GetRanges()); pTheDoc->MigrateItemSet( &pStyleSheet->GetItemSet(), pOldSet, pTheDoc ); aComment = String(SdResId(STR_UNDO_CHANGE_PRES_OBJECT)); String aName(pStyleSheet->GetName()); // Layoutnamen und Separator loeschen String aSep( RTL_CONSTASCII_USTRINGPARAM( SD_LT_SEPARATOR ) ); USHORT nPos = aName.Search(aSep); if( nPos != STRING_NOTFOUND ) aName.Erase(0, nPos + aSep.Len()); // Platzhalter durch Vorlagennamen ersetzen nPos = aComment.Search(sal_Unicode('$')); aComment.Erase(nPos, 1); aComment.Insert(aName, nPos); } /************************************************************************* |* |* Undo() |* \************************************************************************/ void StyleSheetUndoAction::Undo() { SfxItemSet aNewSet( pDoc->GetItemPool(), pOldSet->GetRanges() ); pDoc->MigrateItemSet( pOldSet, &aNewSet, pDoc ); pStyleSheet->GetItemSet().Set(aNewSet); if( pStyleSheet->GetFamily() == SFX_STYLE_FAMILY_PSEUDO ) ( (SdStyleSheet*)pStyleSheet )->GetRealStyleSheet()->Broadcast(SfxSimpleHint(SFX_HINT_DATACHANGED)); else pStyleSheet->Broadcast(SfxSimpleHint(SFX_HINT_DATACHANGED)); } /************************************************************************* |* |* Redo() |* \************************************************************************/ void StyleSheetUndoAction::Redo() { SfxItemSet aNewSet( pDoc->GetItemPool(), pOldSet->GetRanges() ); pDoc->MigrateItemSet( pNewSet, &aNewSet, pDoc ); pStyleSheet->GetItemSet().Set(aNewSet); if( pStyleSheet->GetFamily() == SFX_STYLE_FAMILY_PSEUDO ) ( (SdStyleSheet*)pStyleSheet )->GetRealStyleSheet()->Broadcast(SfxSimpleHint(SFX_HINT_DATACHANGED)); else pStyleSheet->Broadcast(SfxSimpleHint(SFX_HINT_DATACHANGED)); } /************************************************************************* |* |* Repeat() |* \************************************************************************/ void StyleSheetUndoAction::Repeat() { DBG_ASSERT(FALSE, "StyleSheetUndoAction::Repeat: nicht implementiert"); } /************************************************************************* |* |* Destruktor |* \************************************************************************/ StyleSheetUndoAction::~StyleSheetUndoAction() { delete pNewSet; delete pOldSet; } /************************************************************************* |* |* Kommentar liefern |* \************************************************************************/ String StyleSheetUndoAction::GetComment() const { return aComment; } <commit_msg>INTEGRATION: CWS pchfix02 (1.5.280); FILE MERGED 2006/09/01 17:37:02 kaib 1.5.280.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: unchss.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: obo $ $Date: 2006-09-16 18:44:14 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #ifndef _SFXITEMSET_HXX //autogen #include <svtools/itemset.hxx> #endif #ifndef _SFXSTYLE_HXX //autogen #include <svtools/style.hxx> #endif #ifndef _SFXSMPLHINT_HXX //autogen #include <svtools/smplhint.hxx> #endif #ifndef _SVDOBJ_HXX #include <svx/svdobj.hxx> #endif #include "unchss.hxx" #include "strings.hrc" #include "glob.hxx" #include "sdresid.hxx" #include "drawdoc.hxx" #include "stlsheet.hxx" TYPEINIT1(StyleSheetUndoAction, SdUndoAction); /************************************************************************* |* |* Konstruktor |* \************************************************************************/ StyleSheetUndoAction::StyleSheetUndoAction(SdDrawDocument* pTheDoc, SfxStyleSheet* pTheStyleSheet, const SfxItemSet* pTheNewItemSet) : SdUndoAction(pTheDoc) { DBG_ASSERT(pTheStyleSheet, "Undo ohne StyleSheet ???"); pStyleSheet = pTheStyleSheet; // ItemSets anlegen; Vorsicht, das neue koennte aus einem anderen Pool // stammen, also mitsamt seinen Items clonen pNewSet = new SfxItemSet((SfxItemPool&)SdrObject::GetGlobalDrawObjectItemPool(), pTheNewItemSet->GetRanges()); pTheDoc->MigrateItemSet( pTheNewItemSet, pNewSet, pTheDoc ); pOldSet = new SfxItemSet((SfxItemPool&)SdrObject::GetGlobalDrawObjectItemPool(),pStyleSheet->GetItemSet().GetRanges()); pTheDoc->MigrateItemSet( &pStyleSheet->GetItemSet(), pOldSet, pTheDoc ); aComment = String(SdResId(STR_UNDO_CHANGE_PRES_OBJECT)); String aName(pStyleSheet->GetName()); // Layoutnamen und Separator loeschen String aSep( RTL_CONSTASCII_USTRINGPARAM( SD_LT_SEPARATOR ) ); USHORT nPos = aName.Search(aSep); if( nPos != STRING_NOTFOUND ) aName.Erase(0, nPos + aSep.Len()); // Platzhalter durch Vorlagennamen ersetzen nPos = aComment.Search(sal_Unicode('$')); aComment.Erase(nPos, 1); aComment.Insert(aName, nPos); } /************************************************************************* |* |* Undo() |* \************************************************************************/ void StyleSheetUndoAction::Undo() { SfxItemSet aNewSet( pDoc->GetItemPool(), pOldSet->GetRanges() ); pDoc->MigrateItemSet( pOldSet, &aNewSet, pDoc ); pStyleSheet->GetItemSet().Set(aNewSet); if( pStyleSheet->GetFamily() == SFX_STYLE_FAMILY_PSEUDO ) ( (SdStyleSheet*)pStyleSheet )->GetRealStyleSheet()->Broadcast(SfxSimpleHint(SFX_HINT_DATACHANGED)); else pStyleSheet->Broadcast(SfxSimpleHint(SFX_HINT_DATACHANGED)); } /************************************************************************* |* |* Redo() |* \************************************************************************/ void StyleSheetUndoAction::Redo() { SfxItemSet aNewSet( pDoc->GetItemPool(), pOldSet->GetRanges() ); pDoc->MigrateItemSet( pNewSet, &aNewSet, pDoc ); pStyleSheet->GetItemSet().Set(aNewSet); if( pStyleSheet->GetFamily() == SFX_STYLE_FAMILY_PSEUDO ) ( (SdStyleSheet*)pStyleSheet )->GetRealStyleSheet()->Broadcast(SfxSimpleHint(SFX_HINT_DATACHANGED)); else pStyleSheet->Broadcast(SfxSimpleHint(SFX_HINT_DATACHANGED)); } /************************************************************************* |* |* Repeat() |* \************************************************************************/ void StyleSheetUndoAction::Repeat() { DBG_ASSERT(FALSE, "StyleSheetUndoAction::Repeat: nicht implementiert"); } /************************************************************************* |* |* Destruktor |* \************************************************************************/ StyleSheetUndoAction::~StyleSheetUndoAction() { delete pNewSet; delete pOldSet; } /************************************************************************* |* |* Kommentar liefern |* \************************************************************************/ String StyleSheetUndoAction::GetComment() const { return aComment; } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright (c) 2012, Michael P. Gerlek ([email protected]) * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following * conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions 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 Hobu, Inc. or Flaxen Consulting LLC nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. ****************************************************************************/ #include <pdal/GlobalEnvironment.hpp> #include <pdal/plang/PythonEnvironment.hpp> namespace pdal { // // static functions // static GlobalEnvironment* t = 0; static boost::once_flag flag = BOOST_ONCE_INIT; GlobalEnvironment& GlobalEnvironment::get() { boost::call_once(init, flag); return *t; } void GlobalEnvironment::startup() { get(); } void GlobalEnvironment::shutdown() { // Shutdown could be called multiple times? if (t != 0) { delete t; t = 0; } } void GlobalEnvironment::init() { t = new GlobalEnvironment(); } // // regular member functions // GlobalEnvironment::GlobalEnvironment() { // this should be the not-a-thread thread environment (void) createThreadEnvironment(boost::thread::id()); #ifdef PDAL_HAVE_PYTHON m_pythonEnvironment = new pdal::plang::PythonEnvironment(); #endif return; } GlobalEnvironment::~GlobalEnvironment() { while (m_threadMap.size()) { thread_map::iterator iter = m_threadMap.begin(); ThreadEnvironment* env = iter->second; delete env; m_threadMap.erase(iter); } #ifdef PDAL_HAVE_PYTHON delete m_pythonEnvironment; m_pythonEnvironment = 0; #endif return; } void GlobalEnvironment::createThreadEnvironment(boost::thread::id id) { ThreadEnvironment* threadEnv = new ThreadEnvironment(id); // FIXME: What happens if the id is already in the map? m_threadMap.insert( std::make_pair(id, threadEnv ) ); } ThreadEnvironment& GlobalEnvironment::getThreadEnvironment(boost::thread::id id) { thread_map::iterator iter = m_threadMap.find(id); if (iter == m_threadMap.end()) throw pdal_error("bad thread id!"); ThreadEnvironment* threadEnv = iter->second; return *threadEnv; } #ifdef PDAL_HAVE_PYTHON plang::PythonEnvironment& GlobalEnvironment::getPythonEnvironment() { return *m_pythonEnvironment; } #endif boost::random::mt19937* GlobalEnvironment::getRNG() { return getThreadEnvironment().getRNG(); } } //namespaces <commit_msg>minor error checks<commit_after>/****************************************************************************** * Copyright (c) 2012, Michael P. Gerlek ([email protected]) * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following * conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions 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 Hobu, Inc. or Flaxen Consulting LLC nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. ****************************************************************************/ #include <pdal/GlobalEnvironment.hpp> #include <pdal/plang/PythonEnvironment.hpp> namespace pdal { // // static functions // static GlobalEnvironment* t = 0; static boost::once_flag flag = BOOST_ONCE_INIT; GlobalEnvironment& GlobalEnvironment::get() { boost::call_once(init, flag); return *t; } void GlobalEnvironment::startup() { if (t != 0) // sanity check { throw pdal_error("attempt to reinitialize global environment"); } get(); } void GlobalEnvironment::shutdown() { if (t == 0) // sanity check { throw pdal_error("bad global shutdown call -- was called more than once or was called without corresponding startup"); } delete t; t = 0; return; } void GlobalEnvironment::init() { t = new GlobalEnvironment(); } // // regular member functions // GlobalEnvironment::GlobalEnvironment() { // this should be the not-a-thread thread environment (void) createThreadEnvironment(boost::thread::id()); #ifdef PDAL_HAVE_PYTHON m_pythonEnvironment = new pdal::plang::PythonEnvironment(); #endif return; } GlobalEnvironment::~GlobalEnvironment() { while (m_threadMap.size()) { thread_map::iterator iter = m_threadMap.begin(); ThreadEnvironment* env = iter->second; delete env; m_threadMap.erase(iter); } #ifdef PDAL_HAVE_PYTHON delete m_pythonEnvironment; m_pythonEnvironment = 0; #endif return; } void GlobalEnvironment::createThreadEnvironment(boost::thread::id id) { ThreadEnvironment* threadEnv = new ThreadEnvironment(id); if (m_threadMap.find(id) != m_threadMap.end()) { throw pdal_error("thread already registered"); } m_threadMap.insert( std::make_pair(id, threadEnv ) ); } ThreadEnvironment& GlobalEnvironment::getThreadEnvironment(boost::thread::id id) { thread_map::iterator iter = m_threadMap.find(id); if (iter == m_threadMap.end()) throw pdal_error("bad thread id!"); ThreadEnvironment* threadEnv = iter->second; return *threadEnv; } #ifdef PDAL_HAVE_PYTHON plang::PythonEnvironment& GlobalEnvironment::getPythonEnvironment() { return *m_pythonEnvironment; } #endif boost::random::mt19937* GlobalEnvironment::getRNG() { return getThreadEnvironment().getRNG(); } } //namespaces <|endoftext|>
<commit_before>#include "C45PruneableClassifierTree.h" #include "ModelSelection.h" #include "core/Instances.h" #include "Distribution.h" #include "core/Utils.h" #include "NoSplit.h" #include "Stats.h" C45PruneableClassifierTree::C45PruneableClassifierTree(ModelSelection *toSelectLocModel, bool pruneTree, float cf, bool raiseTree, bool cleanup, bool collapseTree) : ClassifierTree(toSelectLocModel) { mPruneTheTree = pruneTree; mCF = cf; mSubtreeRaising = raiseTree; mCleanup = cleanup; mCollapseTheTree = collapseTree; } void C45PruneableClassifierTree::buildClassifier(Instances &data) { // remove instances with missing class Instances dataMissed(&data); dataMissed.deleteWithMissingClass(); buildTree(dataMissed, mSubtreeRaising || !mCleanup); if (mCollapseTheTree) { collapse(); } if (mPruneTheTree) { prune(); } if (mCleanup) { ;// cleanup(new Instances(dataMissed, 0)); } } void C45PruneableClassifierTree::collapse() { double errorsOfSubtree; double errorsOfTree; int i; if (!mIsLeaf) { errorsOfSubtree = getTrainingErrors(); errorsOfTree = localModel()->getDistribution()->numIncorrect(); if (errorsOfSubtree >= errorsOfTree - 1E-3) { // Free adjacent trees //mSons = ; mIsLeaf = true; // Get NoSplit Model for tree. mLocalModel = new NoSplit(localModel()->getDistribution()); } else { for (i = 0; i < (int)mSons.size(); i++) { son(i)->collapse(); } } } } void C45PruneableClassifierTree::prune() { double errorsLargestBranch; double errorsLeaf; double errorsTree; int indexOfLargestBranch; C45PruneableClassifierTree *largestBranch; int i; if (!mIsLeaf) { // Prune all subtrees. for (i = 0; i < (int)mSons.size(); i++) { son(i)->prune(); } // Compute error for largest branch indexOfLargestBranch = localModel()->getDistribution()->maxBag(); if (mSubtreeRaising) { errorsLargestBranch = son(indexOfLargestBranch)->getEstimatedErrorsForBranch(*mTrain); } else { errorsLargestBranch = std::numeric_limits<double>::max(); } // Compute error if this Tree would be leaf errorsLeaf = getEstimatedErrorsForDistribution(localModel()->getDistribution()); // Compute error for the whole subtree errorsTree = getEstimatedErrors(); // Decide if leaf is best choice. if (Utils::smOrEq(errorsLeaf, errorsTree + 0.1) && Utils::smOrEq(errorsLeaf, errorsLargestBranch + 0.1)) { // Free son Trees mSons.clear(); mIsLeaf = true; // Get NoSplit Model for node. mLocalModel = new NoSplit(localModel()->getDistribution()); return; } // Decide if largest branch is better choice // than whole subtree. if (Utils::smOrEq(errorsLargestBranch, errorsTree + 0.1)) { largestBranch = son(indexOfLargestBranch); mSons = largestBranch->mSons; mLocalModel = largestBranch->localModel(); mIsLeaf = largestBranch->mIsLeaf; newDistribution(*mTrain); prune(); } } } ClassifierTree *C45PruneableClassifierTree::getNewTree(Instances &data) const { C45PruneableClassifierTree *newTree = new C45PruneableClassifierTree(mToSelectModel, mPruneTheTree, mCF, mSubtreeRaising, mCleanup, mCollapseTheTree); newTree->buildTree(static_cast<Instances>(data), mSubtreeRaising || !mCleanup); return newTree; } double C45PruneableClassifierTree::getEstimatedErrors() const { double errors = 0; int i; if (mIsLeaf) { return getEstimatedErrorsForDistribution(localModel()->getDistribution()); } else { for (i = 0; i < (int)mSons.size(); i++) { errors = errors + son(i)->getEstimatedErrors(); } return errors; } } double C45PruneableClassifierTree::getEstimatedErrorsForBranch(Instances &data) const { std::vector<Instances*> localInstances; double errors = 0; int i; if (mIsLeaf) { return getEstimatedErrorsForDistribution(new Distribution(data)); } else { Distribution *savedDist = localModel()->getDistribution(); localModel()->resetDistribution(data); localInstances = static_cast<std::vector<Instances*>>(localModel()->split(data)); localModel()->setDistribution(savedDist); for (i = 0; i < (int)mSons.size(); i++) { errors = errors + son(i)->getEstimatedErrorsForBranch(*localInstances[i]); } return errors; } } double C45PruneableClassifierTree::getEstimatedErrorsForDistribution(Distribution *theDistribution) const { if (Utils::eq(theDistribution->total(), 0)) { return 0; } else { return theDistribution->numIncorrect() + Stats::addErrs(theDistribution->total(), theDistribution->numIncorrect(), mCF); } } double C45PruneableClassifierTree::getTrainingErrors() const { double errors = 0; int i; if (mIsLeaf) { return localModel()->getDistribution()->numIncorrect(); } else { for (i = 0; i < (int)mSons.size(); i++) { errors = errors + son(i)->getTrainingErrors(); } return errors; } } ClassifierSplitModel *C45PruneableClassifierTree::localModel() const { return static_cast<ClassifierSplitModel*>(mLocalModel); } void C45PruneableClassifierTree::newDistribution(Instances &data) { std::vector<Instances*> localInstances; localModel()->resetDistribution(data); mTrain = &data; if (!mIsLeaf) { localInstances = static_cast<std::vector<Instances*>>(localModel()->split(data)); for (int i = 0; i < (int)mSons.size(); i++) { son(i)->newDistribution(*localInstances[i]); } } else { // Check whether there are some instances at the leaf now! if (!Utils::eq(data.sumOfWeights(), 0)) { mIsEmpty = false; } } } C45PruneableClassifierTree *C45PruneableClassifierTree::son(int index) const { return static_cast<C45PruneableClassifierTree*>(mSons[index]); } <commit_msg>Fixed RHAS compilation issue<commit_after>#include "C45PruneableClassifierTree.h" #include "ModelSelection.h" #include "core/Instances.h" #include "Distribution.h" #include "core/Utils.h" #include "NoSplit.h" #include "Stats.h" C45PruneableClassifierTree::C45PruneableClassifierTree(ModelSelection *toSelectLocModel, bool pruneTree, float cf, bool raiseTree, bool cleanup, bool collapseTree) : ClassifierTree(toSelectLocModel) { mPruneTheTree = pruneTree; mCF = cf; mSubtreeRaising = raiseTree; mCleanup = cleanup; mCollapseTheTree = collapseTree; } void C45PruneableClassifierTree::buildClassifier(Instances &data) { // remove instances with missing class Instances dataMissed(&data); dataMissed.deleteWithMissingClass(); buildTree(dataMissed, mSubtreeRaising || !mCleanup); if (mCollapseTheTree) { collapse(); } if (mPruneTheTree) { prune(); } if (mCleanup) { ;// cleanup(new Instances(dataMissed, 0)); } } void C45PruneableClassifierTree::collapse() { double errorsOfSubtree; double errorsOfTree; int i; if (!mIsLeaf) { errorsOfSubtree = getTrainingErrors(); errorsOfTree = localModel()->getDistribution()->numIncorrect(); if (errorsOfSubtree >= errorsOfTree - 1E-3) { // Free adjacent trees //mSons = ; mIsLeaf = true; // Get NoSplit Model for tree. mLocalModel = new NoSplit(localModel()->getDistribution()); } else { for (i = 0; i < (int)mSons.size(); i++) { son(i)->collapse(); } } } } void C45PruneableClassifierTree::prune() { double errorsLargestBranch; double errorsLeaf; double errorsTree; int indexOfLargestBranch; C45PruneableClassifierTree *largestBranch; int i; if (!mIsLeaf) { // Prune all subtrees. for (i = 0; i < (int)mSons.size(); i++) { son(i)->prune(); } // Compute error for largest branch indexOfLargestBranch = localModel()->getDistribution()->maxBag(); if (mSubtreeRaising) { errorsLargestBranch = son(indexOfLargestBranch)->getEstimatedErrorsForBranch(*mTrain); } else { errorsLargestBranch = std::numeric_limits<double>::max(); } // Compute error if this Tree would be leaf errorsLeaf = getEstimatedErrorsForDistribution(localModel()->getDistribution()); // Compute error for the whole subtree errorsTree = getEstimatedErrors(); // Decide if leaf is best choice. if (Utils::smOrEq(errorsLeaf, errorsTree + 0.1) && Utils::smOrEq(errorsLeaf, errorsLargestBranch + 0.1)) { // Free son Trees mSons.clear(); mIsLeaf = true; // Get NoSplit Model for node. mLocalModel = new NoSplit(localModel()->getDistribution()); return; } // Decide if largest branch is better choice // than whole subtree. if (Utils::smOrEq(errorsLargestBranch, errorsTree + 0.1)) { largestBranch = son(indexOfLargestBranch); mSons = largestBranch->mSons; mLocalModel = largestBranch->localModel(); mIsLeaf = largestBranch->mIsLeaf; newDistribution(*mTrain); prune(); } } } ClassifierTree *C45PruneableClassifierTree::getNewTree(Instances &data) const { C45PruneableClassifierTree *newTree = new C45PruneableClassifierTree(mToSelectModel, mPruneTheTree, mCF, mSubtreeRaising, mCleanup, mCollapseTheTree); newTree->buildTree(data, mSubtreeRaising || !mCleanup); return newTree; } double C45PruneableClassifierTree::getEstimatedErrors() const { double errors = 0; int i; if (mIsLeaf) { return getEstimatedErrorsForDistribution(localModel()->getDistribution()); } else { for (i = 0; i < (int)mSons.size(); i++) { errors = errors + son(i)->getEstimatedErrors(); } return errors; } } double C45PruneableClassifierTree::getEstimatedErrorsForBranch(Instances &data) const { std::vector<Instances*> localInstances; double errors = 0; int i; if (mIsLeaf) { return getEstimatedErrorsForDistribution(new Distribution(data)); } else { Distribution *savedDist = localModel()->getDistribution(); localModel()->resetDistribution(data); localInstances = static_cast<std::vector<Instances*>>(localModel()->split(data)); localModel()->setDistribution(savedDist); for (i = 0; i < (int)mSons.size(); i++) { errors = errors + son(i)->getEstimatedErrorsForBranch(*localInstances[i]); } return errors; } } double C45PruneableClassifierTree::getEstimatedErrorsForDistribution(Distribution *theDistribution) const { if (Utils::eq(theDistribution->total(), 0)) { return 0; } else { return theDistribution->numIncorrect() + Stats::addErrs(theDistribution->total(), theDistribution->numIncorrect(), mCF); } } double C45PruneableClassifierTree::getTrainingErrors() const { double errors = 0; int i; if (mIsLeaf) { return localModel()->getDistribution()->numIncorrect(); } else { for (i = 0; i < (int)mSons.size(); i++) { errors = errors + son(i)->getTrainingErrors(); } return errors; } } ClassifierSplitModel *C45PruneableClassifierTree::localModel() const { return static_cast<ClassifierSplitModel*>(mLocalModel); } void C45PruneableClassifierTree::newDistribution(Instances &data) { std::vector<Instances*> localInstances; localModel()->resetDistribution(data); mTrain = &data; if (!mIsLeaf) { localInstances = static_cast<std::vector<Instances*>>(localModel()->split(data)); for (int i = 0; i < (int)mSons.size(); i++) { son(i)->newDistribution(*localInstances[i]); } } else { // Check whether there are some instances at the leaf now! if (!Utils::eq(data.sumOfWeights(), 0)) { mIsEmpty = false; } } } C45PruneableClassifierTree *C45PruneableClassifierTree::son(int index) const { return static_cast<C45PruneableClassifierTree*>(mSons[index]); } <|endoftext|>
<commit_before>// @(#)root/win32gdk:$Id$ // Author: Valeriy Onuchin 08/08/2003 /************************************************************************* * Copyright (C) 1995-2001, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // Proxy classes provide thread-safe interface to global objects. // // For example: TGWin32VirtualXProxy (to gVirtualX), // TGWin32InterpreterProxy (to gInterpreter). // // Proxy object creates callback object and posts a windows message to // "processing thread". When windows message is received callback // ("real method") is executed. // // For example: // gVirtualX->ClearWindow() // // - callback object created containing pointer to function // corresponding TGWin32::ClearWindow() method // - message to "processing thread" (main thread) is posted // - TGWin32::ClearWindow() method is executed inside main thread // - thread containing gVirtualX proxy object waits for reply // from main thread that TGWin32::ClearWindow() is completed. // // Howto create proxy class: // // 1. Naming. // name of proxy = TGWin32 + the name of "virtual base class" + Proxy // // e.g. TGWin32VirtualXProxy = TGWin32 + VirtualX + Proxy // // 2. Definition of global object // As example check definition and implementation of // gVirtualX, gInterpreter global objects // // 3. Class definition. // proxy class must be inherited from "virtual base class" and // TGWin32ProxyBase class. For example: // // class TGWin32VirtualX : public TVirtualX , public TGWin32ProxyBase // // 4. Constructors, destructor, extra methods. // - constructors and destructor of proxy class do nothing // - proxy class must contain two extra static methods // RealObject(), ProxyObject(). Each of them return pointer to object // of virtual base class. // // For example: // static TInterpreter *RealObject(); // static TInterpreter *ProxyObject(); // // 5. Implementation // TGWin32ProxyDefs.h file contains a set of macros which very // simplify implementation. // - RETURN_PROXY_OBJECT macro implements ProxyObject() method, e.g. // RETURN_PROXY_OBJECT(Interpreter) // - the names of other macros say about itself. // // For example: // VOID_METHOD_ARG0(Interpreter,ClearFileBusy,1) // void TGWin32InterpreterProxy::ClearFileBusy() // // RETURN_METHOD_ARG0_CONST(VirtualX,Visual_t,GetVisual) // Visual_t TGWin32VirtualXProxy::GetVisual() const // // RETURN_METHOD_ARG2(VirtualX,Int_t,OpenPixmap,UInt_t,w,UInt_t,h) // Int_t TGWin32VirtualXProxy::OpenPixmap,UInt_t w,UInt_t h) // // - few methods has _LOCK part in the name // VOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfMethods,TClass*,cl) // // /////////////////////////////////////////////////////////////////////////////// #include "Windows4Root.h" #include <windows.h> #include "TGWin32ProxyBase.h" #include "TRefCnt.h" #include "TList.h" #include "TGWin32.h" #include "TROOT.h" //////////////////////////////////////////////////////////////////////////////// class TGWin32CallBackObject : public TObject { public: TGWin32CallBack fCallBack; // callback function (called by GUI thread) void *fParam; // arguments passed to/from callback function TGWin32CallBackObject(TGWin32CallBack cb,void *p):fCallBack(cb),fParam(p) {} ~TGWin32CallBackObject() { if (fParam) delete fParam; } }; //////////////////////////////////////////////////////////////////////////////// class TGWin32ProxyBasePrivate { public: HANDLE fEvent; // event used for syncronization TGWin32ProxyBasePrivate(); ~TGWin32ProxyBasePrivate(); }; //______________________________________________________________________________ TGWin32ProxyBasePrivate::TGWin32ProxyBasePrivate() { // ctor fEvent = ::CreateEvent(NULL, TRUE, FALSE, NULL); } //______________________________________________________________________________ TGWin32ProxyBasePrivate::~TGWin32ProxyBasePrivate() { // dtor if (fEvent) ::CloseHandle(fEvent); fEvent = 0; } ULong_t TGWin32ProxyBase::fgPostMessageId = 0; ULong_t TGWin32ProxyBase::fgPingMessageId = 0; ULong_t TGWin32ProxyBase::fgMainThreadId = 0; Long_t TGWin32ProxyBase::fgLock = 0; UInt_t TGWin32ProxyBase::fMaxResponseTime = 0; //////////////////////////////////////////////////////////////////////////////// //______________________________________________________________________________ TGWin32ProxyBase::TGWin32ProxyBase() { // ctor fCallBack = 0; fParam = 0; fListOfCallBacks = new TList(); fBatchLimit = 100; fId = ::GetCurrentThreadId(); fPimpl = new TGWin32ProxyBasePrivate(); if (!fgPostMessageId) fgPostMessageId = ::RegisterWindowMessage("TGWin32ProxyBase::Post"); if (!fgPingMessageId) fgPingMessageId = ::RegisterWindowMessage("TGWin32ProxyBase::Ping"); } //______________________________________________________________________________ TGWin32ProxyBase::~TGWin32ProxyBase() { // dtor fListOfCallBacks->Delete(); delete fListOfCallBacks; fListOfCallBacks = 0; delete fPimpl; } //______________________________________________________________________________ void TGWin32ProxyBase::Lock() { // enter critical section TGWin32::Lock(); } //______________________________________________________________________________ void TGWin32ProxyBase::Unlock() { // leave critical section TGWin32::Unlock(); } //______________________________________________________________________________ void TGWin32ProxyBase::GlobalLock() { // lock any proxy (client thread) if (IsGloballyLocked()) return; ::InterlockedIncrement(&fgLock); } //______________________________________________________________________________ void TGWin32ProxyBase::GlobalUnlock() { // unlock any proxy (client thread) if (!IsGloballyLocked()) return; ::InterlockedDecrement(&fgLock); } //______________________________________________________________________________ Bool_t TGWin32ProxyBase::Ping() { // send ping messsage to server thread return ::PostThreadMessage(fgMainThreadId, fgPingMessageId, (WPARAM)0, 0L); } //______________________________________________________________________________ Double_t TGWin32ProxyBase::GetMilliSeconds() { // returns elapsed time in milliseconds with microseconds precision static LARGE_INTEGER freq; static Bool_t first = kTRUE; LARGE_INTEGER count; static Double_t overhead = 0; if (first) { LARGE_INTEGER count0; ::QueryPerformanceFrequency(&freq); ::QueryPerformanceCounter(&count0); if (1) { Double_t dummy; dummy = ((Double_t)count0.QuadPart - overhead)*1000./((Double_t)freq.QuadPart); } ::QueryPerformanceCounter(&count); overhead = (Double_t)count.QuadPart - (Double_t)count0.QuadPart; first = kFALSE; } ::QueryPerformanceCounter(&count); return ((Double_t)count.QuadPart - overhead)*1000./((Double_t)freq.QuadPart); } //______________________________________________________________________________ void TGWin32ProxyBase::ExecuteCallBack(Bool_t sync) { // Executes all batched callbacks and the latest callback // This method is executed by server thread // process batched callbacks if (fListOfCallBacks && fListOfCallBacks->GetSize()) { TIter next(fListOfCallBacks); TGWin32CallBackObject *obj; while ((obj = (TGWin32CallBackObject*)next())) { obj->fCallBack(obj->fParam); // execute callback } } if (sync) { if (fCallBack) fCallBack(fParam); ::SetEvent(fPimpl->fEvent); } } //______________________________________________________________________________ Bool_t TGWin32ProxyBase::ForwardCallBack(Bool_t sync) { // if sync is kTRUE: // - post message to main thread. // - execute callbacks from fListOfCallBacks // - wait for response // else // - add callback to fListOfCallBacks // // returns kTRUE if callback execution is delayed (batched) Int_t wait = 0; if (!fgMainThreadId) return kFALSE; while (IsGloballyLocked()) { Ping(); if (GetCurrentThreadId() == fgMainThreadId) break; ::SleepEx(10, 1); // take a rest if (!fgMainThreadId) return kFALSE; // server thread terminated } Bool_t batch = !sync && (fListOfCallBacks->GetSize()<fBatchLimit); if (batch) { fListOfCallBacks->Add(new TGWin32CallBackObject(fCallBack, fParam)); return kTRUE; } while (!::PostThreadMessage(fgMainThreadId, fgPostMessageId, (WPARAM)this, 0L)) { // wait because there is a chance that message queue does not exist yet ::SleepEx(50, 1); if (wait++ > 5) return kFALSE; // failed to post } // limiting wait time DWORD res = WAIT_TIMEOUT; while (res == WAIT_TIMEOUT) { res = ::WaitForSingleObject(fPimpl->fEvent, 100); if ((GetCurrentThreadId() == fgMainThreadId) || (!gROOT->IsLineProcessing() && IsGloballyLocked())) { break; } } ::ResetEvent(fPimpl->fEvent); // DWORD res = ::WaitForSingleObject(fPimpl->fEvent, INFINITE); // ::ResetEvent(fPimpl->fEvent); if (res == WAIT_TIMEOUT) { // server thread is blocked GlobalLock(); return kTRUE; } fListOfCallBacks->Delete(); return kFALSE; } //______________________________________________________________________________ void TGWin32ProxyBase::SendExitMessage() { // send exit message to server thread ::PostThreadMessage(fgMainThreadId, WM_QUIT, 0, 0L); } <commit_msg>From Valeriy Onuchin: - Avoid potential deadlock in TGWin32ProxyBase.cxx<commit_after>// @(#)root/win32gdk:$Id$ // Author: Valeriy Onuchin 08/08/2003 /************************************************************************* * Copyright (C) 1995-2001, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // Proxy classes provide thread-safe interface to global objects. // // For example: TGWin32VirtualXProxy (to gVirtualX), // TGWin32InterpreterProxy (to gInterpreter). // // Proxy object creates callback object and posts a windows message to // "processing thread". When windows message is received callback // ("real method") is executed. // // For example: // gVirtualX->ClearWindow() // // - callback object created containing pointer to function // corresponding TGWin32::ClearWindow() method // - message to "processing thread" (main thread) is posted // - TGWin32::ClearWindow() method is executed inside main thread // - thread containing gVirtualX proxy object waits for reply // from main thread that TGWin32::ClearWindow() is completed. // // Howto create proxy class: // // 1. Naming. // name of proxy = TGWin32 + the name of "virtual base class" + Proxy // // e.g. TGWin32VirtualXProxy = TGWin32 + VirtualX + Proxy // // 2. Definition of global object // As example check definition and implementation of // gVirtualX, gInterpreter global objects // // 3. Class definition. // proxy class must be inherited from "virtual base class" and // TGWin32ProxyBase class. For example: // // class TGWin32VirtualX : public TVirtualX , public TGWin32ProxyBase // // 4. Constructors, destructor, extra methods. // - constructors and destructor of proxy class do nothing // - proxy class must contain two extra static methods // RealObject(), ProxyObject(). Each of them return pointer to object // of virtual base class. // // For example: // static TInterpreter *RealObject(); // static TInterpreter *ProxyObject(); // // 5. Implementation // TGWin32ProxyDefs.h file contains a set of macros which very // simplify implementation. // - RETURN_PROXY_OBJECT macro implements ProxyObject() method, e.g. // RETURN_PROXY_OBJECT(Interpreter) // - the names of other macros say about itself. // // For example: // VOID_METHOD_ARG0(Interpreter,ClearFileBusy,1) // void TGWin32InterpreterProxy::ClearFileBusy() // // RETURN_METHOD_ARG0_CONST(VirtualX,Visual_t,GetVisual) // Visual_t TGWin32VirtualXProxy::GetVisual() const // // RETURN_METHOD_ARG2(VirtualX,Int_t,OpenPixmap,UInt_t,w,UInt_t,h) // Int_t TGWin32VirtualXProxy::OpenPixmap,UInt_t w,UInt_t h) // // - few methods has _LOCK part in the name // VOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfMethods,TClass*,cl) // // /////////////////////////////////////////////////////////////////////////////// #include "Windows4Root.h" #include <windows.h> #include "TGWin32ProxyBase.h" #include "TRefCnt.h" #include "TList.h" #include "TGWin32.h" #include "TROOT.h" //////////////////////////////////////////////////////////////////////////////// class TGWin32CallBackObject : public TObject { public: TGWin32CallBack fCallBack; // callback function (called by GUI thread) void *fParam; // arguments passed to/from callback function TGWin32CallBackObject(TGWin32CallBack cb,void *p):fCallBack(cb),fParam(p) {} ~TGWin32CallBackObject() { if (fParam) delete fParam; } }; //////////////////////////////////////////////////////////////////////////////// class TGWin32ProxyBasePrivate { public: HANDLE fEvent; // event used for syncronization TGWin32ProxyBasePrivate(); ~TGWin32ProxyBasePrivate(); }; //______________________________________________________________________________ TGWin32ProxyBasePrivate::TGWin32ProxyBasePrivate() { // ctor fEvent = ::CreateEvent(NULL, TRUE, FALSE, NULL); } //______________________________________________________________________________ TGWin32ProxyBasePrivate::~TGWin32ProxyBasePrivate() { // dtor if (fEvent) ::CloseHandle(fEvent); fEvent = 0; } ULong_t TGWin32ProxyBase::fgPostMessageId = 0; ULong_t TGWin32ProxyBase::fgPingMessageId = 0; ULong_t TGWin32ProxyBase::fgMainThreadId = 0; Long_t TGWin32ProxyBase::fgLock = 0; UInt_t TGWin32ProxyBase::fMaxResponseTime = 0; //////////////////////////////////////////////////////////////////////////////// //______________________________________________________________________________ TGWin32ProxyBase::TGWin32ProxyBase() { // ctor fCallBack = 0; fParam = 0; fListOfCallBacks = new TList(); fBatchLimit = 100; fId = ::GetCurrentThreadId(); fPimpl = new TGWin32ProxyBasePrivate(); if (!fgPostMessageId) fgPostMessageId = ::RegisterWindowMessage("TGWin32ProxyBase::Post"); if (!fgPingMessageId) fgPingMessageId = ::RegisterWindowMessage("TGWin32ProxyBase::Ping"); } //______________________________________________________________________________ TGWin32ProxyBase::~TGWin32ProxyBase() { // dtor fListOfCallBacks->Delete(); delete fListOfCallBacks; fListOfCallBacks = 0; delete fPimpl; } //______________________________________________________________________________ void TGWin32ProxyBase::Lock() { // enter critical section TGWin32::Lock(); } //______________________________________________________________________________ void TGWin32ProxyBase::Unlock() { // leave critical section TGWin32::Unlock(); } //______________________________________________________________________________ void TGWin32ProxyBase::GlobalLock() { // lock any proxy (client thread) if (IsGloballyLocked()) return; ::InterlockedIncrement(&fgLock); } //______________________________________________________________________________ void TGWin32ProxyBase::GlobalUnlock() { // unlock any proxy (client thread) if (!IsGloballyLocked()) return; ::InterlockedDecrement(&fgLock); } //______________________________________________________________________________ Bool_t TGWin32ProxyBase::Ping() { // send ping messsage to server thread return ::PostThreadMessage(fgMainThreadId, fgPingMessageId, (WPARAM)0, 0L); } //______________________________________________________________________________ Double_t TGWin32ProxyBase::GetMilliSeconds() { // returns elapsed time in milliseconds with microseconds precision static LARGE_INTEGER freq; static Bool_t first = kTRUE; LARGE_INTEGER count; static Double_t overhead = 0; if (first) { LARGE_INTEGER count0; ::QueryPerformanceFrequency(&freq); ::QueryPerformanceCounter(&count0); if (1) { Double_t dummy; dummy = ((Double_t)count0.QuadPart - overhead)*1000./((Double_t)freq.QuadPart); } ::QueryPerformanceCounter(&count); overhead = (Double_t)count.QuadPart - (Double_t)count0.QuadPart; first = kFALSE; } ::QueryPerformanceCounter(&count); return ((Double_t)count.QuadPart - overhead)*1000./((Double_t)freq.QuadPart); } //______________________________________________________________________________ void TGWin32ProxyBase::ExecuteCallBack(Bool_t sync) { // Executes all batched callbacks and the latest callback // This method is executed by server thread // process batched callbacks if (fListOfCallBacks && fListOfCallBacks->GetSize()) { TIter next(fListOfCallBacks); TGWin32CallBackObject *obj; while ((obj = (TGWin32CallBackObject*)next())) { obj->fCallBack(obj->fParam); // execute callback } } if (sync) { if (fCallBack) fCallBack(fParam); ::SetEvent(fPimpl->fEvent); } } //______________________________________________________________________________ Bool_t TGWin32ProxyBase::ForwardCallBack(Bool_t sync) { // if sync is kTRUE: // - post message to main thread. // - execute callbacks from fListOfCallBacks // - wait for response // else // - add callback to fListOfCallBacks // // returns kTRUE if callback execution is delayed (batched) Int_t wait = 0; if (!fgMainThreadId) return kFALSE; while (IsGloballyLocked()) { Ping(); if (GetCurrentThreadId() == fgMainThreadId) break; ::SleepEx(10, 1); // take a rest if (!fgMainThreadId) return kFALSE; // server thread terminated } Bool_t batch = !sync && (fListOfCallBacks->GetSize()<fBatchLimit); if (batch) { fListOfCallBacks->Add(new TGWin32CallBackObject(fCallBack, fParam)); return kTRUE; } while (!::PostThreadMessage(fgMainThreadId, fgPostMessageId, (WPARAM)this, 0L)) { // wait because there is a chance that message queue does not exist yet ::SleepEx(50, 1); if (wait++ > 5) return kFALSE; // failed to post } Int_t cnt = 0; //VO attempt counters // limiting wait time DWORD res = WAIT_TIMEOUT; while (res == WAIT_TIMEOUT) { res = ::WaitForSingleObject(fPimpl->fEvent, 100); if ((GetCurrentThreadId() == fgMainThreadId) || (!gROOT->IsLineProcessing() && IsGloballyLocked())) { break; } if (cnt++ > 20) break; // VO after some efforts go out from loop } ::ResetEvent(fPimpl->fEvent); // DWORD res = ::WaitForSingleObject(fPimpl->fEvent, INFINITE); // ::ResetEvent(fPimpl->fEvent); if (res == WAIT_TIMEOUT) { // server thread is blocked GlobalLock(); return kTRUE; } fListOfCallBacks->Delete(); return kFALSE; } //______________________________________________________________________________ void TGWin32ProxyBase::SendExitMessage() { // send exit message to server thread ::PostThreadMessage(fgMainThreadId, WM_QUIT, 0, 0L); } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_int_scom.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ #include "p9_int_scom.H" #include <stdint.h> #include <stddef.h> #include <fapi2.H> using namespace fapi2; constexpr uint64_t literal_1 = 1; constexpr uint64_t literal_0 = 0; constexpr uint64_t literal_0x0070000072040140 = 0x0070000072040140; constexpr uint64_t literal_0x0000004000028000 = 0x0000004000028000; constexpr uint64_t literal_0x00000000040101C3 = 0x00000000040101C3; constexpr uint64_t literal_0x9554021F80100E0C = 0x9554021F80100E0C; constexpr uint64_t literal_0b00 = 0b00; constexpr uint64_t literal_0x010003FF00100020 = 0x010003FF00100020; constexpr uint64_t literal_0xD8DFB200FFAFFFD7 = 0xD8DFB200FFAFFFD7; constexpr uint64_t literal_0x0008002000002002 = 0x0008002000002002; constexpr uint64_t literal_0xEF6437D2DE7DD3FD = 0xEF6437D2DE7DD3FD; constexpr uint64_t literal_0x0002000410000000 = 0x0002000410000000; constexpr uint64_t literal_0x7710CCC3E0000701 = 0x7710CCC3E0000701; constexpr uint64_t literal_0x00001003000002 = 0x00001003000002; constexpr uint64_t literal_0xFFFFEFFCFFFFFC = 0xFFFFEFFCFFFFFC; constexpr uint64_t literal_0x0003C018006 = 0x0003C018006; constexpr uint64_t literal_0xFFFDFFEFFFA = 0xFFFDFFEFFFA; fapi2::ReturnCode p9_int_scom(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT0, const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1) { { fapi2::ATTR_EC_Type l_chip_ec; fapi2::ATTR_NAME_Type l_chip_id; FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT0, l_chip_id)); FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT0, l_chip_ec)); fapi2::ATTR_PROC_FABRIC_ADDR_BAR_MODE_Type l_TGT1_ATTR_PROC_FABRIC_ADDR_BAR_MODE; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_ADDR_BAR_MODE, TGT1, l_TGT1_ATTR_PROC_FABRIC_ADDR_BAR_MODE)); fapi2::ATTR_PROC_FABRIC_PUMP_MODE_Type l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_PUMP_MODE, TGT1, l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE)); fapi2::buffer<uint64_t> l_scom_buffer; { FAPI_TRY(fapi2::getScom( TGT0, 0x501300aull, l_scom_buffer )); if ((l_TGT1_ATTR_PROC_FABRIC_ADDR_BAR_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_ADDR_BAR_MODE_SMALL_SYSTEM)) { l_scom_buffer.insert<0, 1, 63, uint64_t>(literal_1 ); } else if ((l_TGT1_ATTR_PROC_FABRIC_ADDR_BAR_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_ADDR_BAR_MODE_LARGE_SYSTEM)) { l_scom_buffer.insert<0, 1, 63, uint64_t>(literal_0 ); } if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_GROUP)) { l_scom_buffer.insert<1, 1, 63, uint64_t>(literal_1 ); } else if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_NODE)) { l_scom_buffer.insert<1, 1, 63, uint64_t>(literal_0 ); } FAPI_TRY(fapi2::putScom(TGT0, 0x501300aull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5013022ull, l_scom_buffer )); l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x0070000072040140 ); FAPI_TRY(fapi2::putScom(TGT0, 0x5013022ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5013033ull, l_scom_buffer )); l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x0000004000028000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x5013033ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5013036ull, l_scom_buffer )); l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x00000000040101C3 ); FAPI_TRY(fapi2::putScom(TGT0, 0x5013036ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5013037ull, l_scom_buffer )); l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x9554021F80100E0C ); FAPI_TRY(fapi2::putScom(TGT0, 0x5013037ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5013124ull, l_scom_buffer )); l_scom_buffer.insert<28, 2, 62, uint64_t>(literal_0b00 ); FAPI_TRY(fapi2::putScom(TGT0, 0x5013124ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5013140ull, l_scom_buffer )); l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x010003FF00100020 ); FAPI_TRY(fapi2::putScom(TGT0, 0x5013140ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5013141ull, l_scom_buffer )); l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0xD8DFB200FFAFFFD7 ); FAPI_TRY(fapi2::putScom(TGT0, 0x5013141ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5013148ull, l_scom_buffer )); l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x0008002000002002 ); FAPI_TRY(fapi2::putScom(TGT0, 0x5013148ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5013149ull, l_scom_buffer )); l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0xEF6437D2DE7DD3FD ); FAPI_TRY(fapi2::putScom(TGT0, 0x5013149ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5013178ull, l_scom_buffer )); l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x0002000410000000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x5013178ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5013179ull, l_scom_buffer )); l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x7710CCC3E0000701 ); FAPI_TRY(fapi2::putScom(TGT0, 0x5013179ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x501322dull, l_scom_buffer )); constexpr auto l_INT_INT_VC_INT_VC_AIB_TX_ORDERING_TAG_2_RELAXED_WR_ORDERING_DMA_OFF = 0x0; l_scom_buffer.insert<22, 1, 63, uint64_t>(l_INT_INT_VC_INT_VC_AIB_TX_ORDERING_TAG_2_RELAXED_WR_ORDERING_DMA_OFF ); FAPI_TRY(fapi2::putScom(TGT0, 0x501322dull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5013270ull, l_scom_buffer )); l_scom_buffer.insert<0, 56, 8, uint64_t>(literal_0x00001003000002 ); FAPI_TRY(fapi2::putScom(TGT0, 0x5013270ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5013271ull, l_scom_buffer )); l_scom_buffer.insert<0, 56, 8, uint64_t>(literal_0xFFFFEFFCFFFFFC ); FAPI_TRY(fapi2::putScom(TGT0, 0x5013271ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5013272ull, l_scom_buffer )); l_scom_buffer.insert<0, 44, 20, uint64_t>(literal_0x0003C018006 ); FAPI_TRY(fapi2::putScom(TGT0, 0x5013272ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5013273ull, l_scom_buffer )); l_scom_buffer.insert<0, 44, 20, uint64_t>(literal_0xFFFDFFEFFFA ); FAPI_TRY(fapi2::putScom(TGT0, 0x5013273ull, l_scom_buffer)); } }; fapi_try_exit: return fapi2::current_err; } <commit_msg>INT FIR updates<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_int_scom.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ #include "p9_int_scom.H" #include <stdint.h> #include <stddef.h> #include <fapi2.H> using namespace fapi2; constexpr uint64_t literal_1 = 1; constexpr uint64_t literal_0 = 0; constexpr uint64_t literal_0x0070000072040140 = 0x0070000072040140; constexpr uint64_t literal_0x0000004004028000 = 0x0000004004028000; constexpr uint64_t literal_0x0000000000000000 = 0x0000000000000000; constexpr uint64_t literal_0x9554021F80110FCF = 0x9554021F80110FCF; constexpr uint64_t literal_0b00 = 0b00; constexpr uint64_t literal_0x010003FF00100020 = 0x010003FF00100020; constexpr uint64_t literal_0xD8DFB200DFAFFFD7 = 0xD8DFB200DFAFFFD7; constexpr uint64_t literal_0x0008002000002002 = 0x0008002000002002; constexpr uint64_t literal_0xEF6437D2DE7DD3FD = 0xEF6437D2DE7DD3FD; constexpr uint64_t literal_0x0002000410000000 = 0x0002000410000000; constexpr uint64_t literal_0x7710CCC3E0000701 = 0x7710CCC3E0000701; constexpr uint64_t literal_0x00001003000002 = 0x00001003000002; constexpr uint64_t literal_0xFFFFEFFCFFFFFC = 0xFFFFEFFCFFFFFC; constexpr uint64_t literal_0x0003C018006 = 0x0003C018006; constexpr uint64_t literal_0xFFFDFFEFFFA = 0xFFFDFFEFFFA; fapi2::ReturnCode p9_int_scom(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT0, const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1) { { fapi2::ATTR_EC_Type l_chip_ec; fapi2::ATTR_NAME_Type l_chip_id; FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT0, l_chip_id)); FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT0, l_chip_ec)); fapi2::ATTR_PROC_FABRIC_ADDR_BAR_MODE_Type l_TGT1_ATTR_PROC_FABRIC_ADDR_BAR_MODE; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_ADDR_BAR_MODE, TGT1, l_TGT1_ATTR_PROC_FABRIC_ADDR_BAR_MODE)); fapi2::ATTR_PROC_FABRIC_PUMP_MODE_Type l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_PUMP_MODE, TGT1, l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE)); fapi2::buffer<uint64_t> l_scom_buffer; { FAPI_TRY(fapi2::getScom( TGT0, 0x501300aull, l_scom_buffer )); if ((l_TGT1_ATTR_PROC_FABRIC_ADDR_BAR_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_ADDR_BAR_MODE_SMALL_SYSTEM)) { l_scom_buffer.insert<0, 1, 63, uint64_t>(literal_1 ); } else if ((l_TGT1_ATTR_PROC_FABRIC_ADDR_BAR_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_ADDR_BAR_MODE_LARGE_SYSTEM)) { l_scom_buffer.insert<0, 1, 63, uint64_t>(literal_0 ); } if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_GROUP)) { l_scom_buffer.insert<1, 1, 63, uint64_t>(literal_1 ); } else if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_NODE)) { l_scom_buffer.insert<1, 1, 63, uint64_t>(literal_0 ); } FAPI_TRY(fapi2::putScom(TGT0, 0x501300aull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5013022ull, l_scom_buffer )); l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x0070000072040140 ); FAPI_TRY(fapi2::putScom(TGT0, 0x5013022ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5013033ull, l_scom_buffer )); l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x0000004004028000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x5013033ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5013036ull, l_scom_buffer )); l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x0000000000000000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x5013036ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5013037ull, l_scom_buffer )); l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x9554021F80110FCF ); FAPI_TRY(fapi2::putScom(TGT0, 0x5013037ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5013124ull, l_scom_buffer )); l_scom_buffer.insert<28, 2, 62, uint64_t>(literal_0b00 ); FAPI_TRY(fapi2::putScom(TGT0, 0x5013124ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5013140ull, l_scom_buffer )); l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x010003FF00100020 ); FAPI_TRY(fapi2::putScom(TGT0, 0x5013140ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5013141ull, l_scom_buffer )); l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0xD8DFB200DFAFFFD7 ); FAPI_TRY(fapi2::putScom(TGT0, 0x5013141ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5013148ull, l_scom_buffer )); l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x0008002000002002 ); FAPI_TRY(fapi2::putScom(TGT0, 0x5013148ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5013149ull, l_scom_buffer )); l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0xEF6437D2DE7DD3FD ); FAPI_TRY(fapi2::putScom(TGT0, 0x5013149ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5013178ull, l_scom_buffer )); l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x0002000410000000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x5013178ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5013179ull, l_scom_buffer )); l_scom_buffer.insert<0, 64, 0, uint64_t>(literal_0x7710CCC3E0000701 ); FAPI_TRY(fapi2::putScom(TGT0, 0x5013179ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x501322dull, l_scom_buffer )); constexpr auto l_INT_INT_VC_INT_VC_AIB_TX_ORDERING_TAG_2_RELAXED_WR_ORDERING_DMA_OFF = 0x0; l_scom_buffer.insert<22, 1, 63, uint64_t>(l_INT_INT_VC_INT_VC_AIB_TX_ORDERING_TAG_2_RELAXED_WR_ORDERING_DMA_OFF ); FAPI_TRY(fapi2::putScom(TGT0, 0x501322dull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5013270ull, l_scom_buffer )); l_scom_buffer.insert<0, 56, 8, uint64_t>(literal_0x00001003000002 ); FAPI_TRY(fapi2::putScom(TGT0, 0x5013270ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5013271ull, l_scom_buffer )); l_scom_buffer.insert<0, 56, 8, uint64_t>(literal_0xFFFFEFFCFFFFFC ); FAPI_TRY(fapi2::putScom(TGT0, 0x5013271ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5013272ull, l_scom_buffer )); l_scom_buffer.insert<0, 44, 20, uint64_t>(literal_0x0003C018006 ); FAPI_TRY(fapi2::putScom(TGT0, 0x5013272ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x5013273ull, l_scom_buffer )); l_scom_buffer.insert<0, 44, 20, uint64_t>(literal_0xFFFDFFEFFFA ); FAPI_TRY(fapi2::putScom(TGT0, 0x5013273ull, l_scom_buffer)); } }; fapi_try_exit: return fapi2::current_err; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/nest/p9_pcie_scominit.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ //----------------------------------------------------------------------------------- // /// @file p9_pcie_scominit.H /// @brief Apply scom inits to PCIE chiplets /// // *HWP HWP Owner: Christina Graves [email protected] // *HWP FW Owner: Thi Tran [email protected] // *HWP Team: Nest // *HWP Level: 1 // *HWP Consumed by: //----------------------------------------------------------------------------------- // // *! ADDITIONAL COMMENTS : //----------------------------------------------------------------------------------- #ifndef _P9_PCIE_SCOMINIT_H_ #define _P9_PCIE_SCOMINIT_H_ //----------------------------------------------------------------------------------- // Includes //----------------------------------------------------------------------------------- #include <fapi2.H> //----------------------------------------------------------------------------------- // Structure definitions //----------------------------------------------------------------------------------- //function pointer typedef definition for HWP call support typedef fapi2::ReturnCode (*p9_pcie_scominit_FP_t) (const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&); //----------------------------------------------------------------------------------- // Constant definitions //----------------------------------------------------------------------------------- extern "C" { //----------------------------------------------------------------------------------- // Function prototype //----------------------------------------------------------------------------------- /// @brief Apply scom inits to PCIE chiplets /// @param[in] i_target => P9 chip target /// @return FAPI_RC_SUCCESS if the setup completes successfully, // fapi2::ReturnCode p9_pcie_scominit( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target); } //extern"C" #endif //_P9_PCIE_SCOMINIT_H_ <commit_msg>PCIE Level 1 procedures<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/nest/p9_pcie_scominit.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ //----------------------------------------------------------------------------------- /// /// @file p9_pcie_scominit.H /// @brief Perform PCIE Phase1 init sequence (FAPI2) /// // *HWP HWP Owner: Christina Graves [email protected] // *HWP FW Owner: Thi Tran [email protected] // *HWP Team: Nest // *HWP Level: 1 // *HWP Consumed by: HB #ifndef _P9_PCIE_SCOMINIT_H_ #define _P9_PCIE_SCOMINIT_H_ //----------------------------------------------------------------------------------- // Includes //----------------------------------------------------------------------------------- #include <fapi2.H> //----------------------------------------------------------------------------------- // Structure definitions //----------------------------------------------------------------------------------- //function pointer typedef definition for HWP call support typedef fapi2::ReturnCode (*p9_pcie_scominit_FP_t) (const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&); //----------------------------------------------------------------------------------- // Constant definitions //----------------------------------------------------------------------------------- extern "C" { //----------------------------------------------------------------------------------- // Function prototype //----------------------------------------------------------------------------------- /// @brief Perform PCIE Phase1 init sequence /// @param[in] i_target => P9 chip target /// @return FAPI_RC_SUCCESS if the setup completes successfully, // fapi2::ReturnCode p9_pcie_scominit(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target); } //extern"C" #endif //_P9_PCIE_SCOMINIT_H_ <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision: 7837 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkNDITrackingDevice.h" #include "mitkNDIPassiveTool.h" //#include "mitkSerialCommunication.h" //#include "mitkNDIPassiveToolTest.cpp" #include "mitkTestingMacros.h" #include "mitkTrackingTypes.h" #include "mitkTrackingTool.h" #include "mitkStandardFileLocations.h" /**Documentation * NDIPassiveTool has a protected constructor and a protected itkNewMacro * so that only it's friend class NDITrackingDevice is able to instantiate * tool objects. Therefore, we derive from NDIPassiveTool and add a * public itkNewMacro, so that we can instantiate and test the class */ class NDIPassiveToolTestClass : public mitk::NDIPassiveTool { public: mitkClassMacro(NDIPassiveToolTestClass, NDIPassiveTool); /** make a public constructor, so that the test is able * to instantiate NDIPassiveTool */ itkNewMacro(Self); protected: NDIPassiveToolTestClass() : mitk::NDIPassiveTool() { } }; int mitkNDITrackingDeviceTest(int /* argc */, char* /*argv*/[]) { // always start with this! MITK_TEST_BEGIN("NDITrackingDevice "); // let's create an object of our class mitk::NDITrackingDevice::Pointer myNDITrackingDevice = mitk::NDITrackingDevice::New(); // first test: did this work? // using MITK_TEST_CONDITION_REQUIRED makes the test stop after failure, since // it makes no sense to continue without an object. MITK_TEST_CONDITION_REQUIRED(myNDITrackingDevice.IsNotNull(),"Testing instantiation\n"); MITK_TEST_CONDITION_REQUIRED(myNDITrackingDevice->GetMode() == mitk::TrackingDevice::Setup ,"Checking tracking device state == setup.\n"); //OpenConnection MITK_TEST_CONDITION( (!myNDITrackingDevice->OpenConnection()), "Testing behavior of method OpenConnection() (Errors should occur because Tracking Device is not activated)."); //CloseConnection MITK_TEST_CONDITION( (myNDITrackingDevice->CloseConnection()), "Testing behavior of method CloseConnection()."); //StartTracking MITK_TEST_CONDITION( (!myNDITrackingDevice->StartTracking()), "Testing behavior of method StartTracking()."); //Beep(unsigned char count) MITK_TEST_CONDITION( (myNDITrackingDevice->Beep(3)== false), "Testing behavior of method Beep(). No Tracking device initialized!"); //AddTool( const char* toolName, const char* fileName, TrackingPriority p /*= NDIPassiveTool::Dynamic*/ ) std::string file = mitk::StandardFileLocations::GetInstance()->FindFile("SROMFile.rom", "Modules/IGT/Testing/Data"); const char *name = file.c_str(); MITK_TEST_CONDITION( (myNDITrackingDevice->AddTool("Tool0", name))!=NULL, "Testing AddTool() for tool 0."); //GetToolCount() MITK_TEST_CONDITION( (myNDITrackingDevice->GetToolCount())==1, "Testing GetToolCount() for one tool."); //GetTool(unsigned int toolNumber) MITK_TEST_CONDITION( (myNDITrackingDevice->GetTool(0))!=NULL, "Testing GetTool() for tool 0."); mitk::TrackingTool::Pointer testtool = myNDITrackingDevice->GetTool(0); //UpdateTool(mitk::TrackingTool* tool) MITK_TEST_CONDITION( (!myNDITrackingDevice->UpdateTool(testtool)), "Testing behavior of method UpdateTool().\n"); //RemoveTool(mitk::TrackingTool* tool) MITK_TEST_CONDITION( (myNDITrackingDevice->RemoveTool(testtool)), "Testing RemoveTool()for tool 0."); //SetOperationMode(OperationMode mode) MITK_TEST_CONDITION( (myNDITrackingDevice->SetOperationMode( mitk::MarkerTracking3D )== true ), "Testing behavior of method SetOperationMode().\n"); //GetOperationMode() myNDITrackingDevice->SetOperationMode(mitk::MarkerTracking3D); MITK_TEST_CONDITION( (myNDITrackingDevice->GetOperationMode()==2),"" ); myNDITrackingDevice->SetOperationMode(mitk::ToolTracking5D); MITK_TEST_CONDITION( (myNDITrackingDevice->GetOperationMode()==1),"" ); myNDITrackingDevice->SetOperationMode(mitk::HybridTracking); MITK_TEST_CONDITION( (myNDITrackingDevice->GetOperationMode()==3), "Testing behavior of method GetOperationMode().\n"); //GetMarkerPositions(MarkerPointContainerType* markerpositions) mitk::MarkerPointContainerType* markerpositions = new mitk::MarkerPointContainerType(); MITK_TEST_CONDITION( (!myNDITrackingDevice->GetMarkerPositions(markerpositions)), "Testing behavior of method GetMarkerPositions().\n"); delete markerpositions; // always end with this! MITK_TEST_END(); }<commit_msg>FIX (1773): deactivate test case that works only, if no tracking device is attached to test computer<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision: 7837 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkNDITrackingDevice.h" #include "mitkNDIPassiveTool.h" //#include "mitkSerialCommunication.h" //#include "mitkNDIPassiveToolTest.cpp" #include "mitkTestingMacros.h" #include "mitkTrackingTypes.h" #include "mitkTrackingTool.h" #include "mitkStandardFileLocations.h" /**Documentation * NDIPassiveTool has a protected constructor and a protected itkNewMacro * so that only it's friend class NDITrackingDevice is able to instantiate * tool objects. Therefore, we derive from NDIPassiveTool and add a * public itkNewMacro, so that we can instantiate and test the class */ class NDIPassiveToolTestClass : public mitk::NDIPassiveTool { public: mitkClassMacro(NDIPassiveToolTestClass, NDIPassiveTool); /** make a public constructor, so that the test is able * to instantiate NDIPassiveTool */ itkNewMacro(Self); protected: NDIPassiveToolTestClass() : mitk::NDIPassiveTool() { } }; int mitkNDITrackingDeviceTest(int /* argc */, char* /*argv*/[]) { // always start with this! MITK_TEST_BEGIN("NDITrackingDevice "); // let's create an object of our class mitk::NDITrackingDevice::Pointer myNDITrackingDevice = mitk::NDITrackingDevice::New(); // first test: did this work? // using MITK_TEST_CONDITION_REQUIRED makes the test stop after failure, since // it makes no sense to continue without an object. MITK_TEST_CONDITION_REQUIRED(myNDITrackingDevice.IsNotNull(),"Testing instantiation\n"); MITK_TEST_CONDITION_REQUIRED(myNDITrackingDevice->GetMode() == mitk::TrackingDevice::Setup ,"Checking tracking device state == setup.\n"); //OpenConnection //MITK_TEST_CONDITION( (!myNDITrackingDevice->OpenConnection()), "Testing behavior of method OpenConnection() (Errors should occur because Tracking Device is not activated)."); // <-- this test is dangerous. It implies that no tracking device is connected to the dartclient pc, which could be wrong. //CloseConnection MITK_TEST_CONDITION( (myNDITrackingDevice->CloseConnection()), "Testing behavior of method CloseConnection()."); //StartTracking MITK_TEST_CONDITION( (!myNDITrackingDevice->StartTracking()), "Testing behavior of method StartTracking()."); //Beep(unsigned char count) MITK_TEST_CONDITION( (myNDITrackingDevice->Beep(3)== false), "Testing behavior of method Beep(). No Tracking device initialized!"); //AddTool( const char* toolName, const char* fileName, TrackingPriority p /*= NDIPassiveTool::Dynamic*/ ) std::string file = mitk::StandardFileLocations::GetInstance()->FindFile("SROMFile.rom", "Modules/IGT/Testing/Data"); const char *name = file.c_str(); MITK_TEST_CONDITION( (myNDITrackingDevice->AddTool("Tool0", name))!=NULL, "Testing AddTool() for tool 0."); //GetToolCount() MITK_TEST_CONDITION( (myNDITrackingDevice->GetToolCount())==1, "Testing GetToolCount() for one tool."); //GetTool(unsigned int toolNumber) MITK_TEST_CONDITION( (myNDITrackingDevice->GetTool(0))!=NULL, "Testing GetTool() for tool 0."); mitk::TrackingTool::Pointer testtool = myNDITrackingDevice->GetTool(0); //UpdateTool(mitk::TrackingTool* tool) MITK_TEST_CONDITION( (!myNDITrackingDevice->UpdateTool(testtool)), "Testing behavior of method UpdateTool().\n"); //RemoveTool(mitk::TrackingTool* tool) MITK_TEST_CONDITION( (myNDITrackingDevice->RemoveTool(testtool)), "Testing RemoveTool()for tool 0."); //SetOperationMode(OperationMode mode) MITK_TEST_CONDITION( (myNDITrackingDevice->SetOperationMode( mitk::MarkerTracking3D )== true ), "Testing behavior of method SetOperationMode().\n"); //GetOperationMode() myNDITrackingDevice->SetOperationMode(mitk::MarkerTracking3D); MITK_TEST_CONDITION( (myNDITrackingDevice->GetOperationMode()==2),"" ); myNDITrackingDevice->SetOperationMode(mitk::ToolTracking5D); MITK_TEST_CONDITION( (myNDITrackingDevice->GetOperationMode()==1),"" ); myNDITrackingDevice->SetOperationMode(mitk::HybridTracking); MITK_TEST_CONDITION( (myNDITrackingDevice->GetOperationMode()==3), "Testing behavior of method GetOperationMode().\n"); //GetMarkerPositions(MarkerPointContainerType* markerpositions) mitk::MarkerPointContainerType* markerpositions = new mitk::MarkerPointContainerType(); MITK_TEST_CONDITION( (!myNDITrackingDevice->GetMarkerPositions(markerpositions)), "Testing behavior of method GetMarkerPositions().\n"); delete markerpositions; // always end with this! MITK_TEST_END(); }<|endoftext|>
<commit_before>// // Copyright (c) 2016 Terry Seyler // // Distributed under the MIT License // See accompanying file LICENSE.md // #include <core/protocol/c4soap/c4soap_message.hpp> #include <core/protocol/c4soap/c4soap_director.hpp> namespace proto_net { namespace protocol { namespace c4soap { std::string authenticate_password(unsigned long& seq, const params_array& /*params*/) { std::stringstream ss; c4soap_message::begin_c4soap_message(ss, "AuthenticatePassword", seq); c4soap_message::param(ss, "password", "string", "root"); c4soap_message::end_c4soap_message(ss); return ss.str(); } std::string get_version_info(unsigned long& seq, const params_array& /*params*/) { std::stringstream ss; c4soap_message::begin_c4soap_message(ss, "GetVersionInfo", seq); c4soap_message::end_c4soap_message(ss); return ss.str(); } std::string get_director_info(unsigned long& seq, const params_array& /*params*/) { std::stringstream ss; c4soap_message::begin_c4soap_message(ss, "GetDirectorInfo", seq); c4soap_message::end_c4soap_message(ss); return ss.str(); } std::string get_devices_by_interface(unsigned long& seq, const params_array& params) { std::stringstream ss; c4soap_message::begin_c4soap_message(ss, "GetDevicesByInterface", seq); c4soap_message::param(ss, "GUID", "string", params[0]); c4soap_message::end_c4soap_message(ss); return ss.str(); } std::string get_devices_by_c4i(unsigned long& seq, const params_array& params) { std::stringstream ss; c4soap_message::begin_c4soap_message(ss, "GetDevicesByC4i", seq); c4soap_message::param(ss, "c4i_name", "string", params[0]); c4soap_message::end_c4soap_message(ss); return ss.str(); } std::string send_to_device(unsigned long& seq, const params_array& params) { std::stringstream ss; if (params.size() > 1) { std::string id = params[0]; std::string cmd = params[1]; c4soap_message::begin_c4soap_message(ss, "SendToDevice", seq); c4soap_message::param(ss, "iddevice", "number", id); cmd = "<command>" + cmd + "<command>"; if (params.size() > 2) { std::string param = ""; for (size_t i = 2; i < params.size(); i++) { size_t j = i + 1; if (j < params.size()) { param += c4soap_message::get_param_value(params[i], params[j]); } else break; } std::string params = "<params>" + param + "</params>"; cmd += params; } std::string device_command = "<devicecommand>" + cmd + "</devicecommand>"; c4soap_message::param(ss, "data", "xml", device_command); c4soap_message::end_c4soap_message(ss); } return ss.str(); } } } } <commit_msg>Changed type from xml to string.<commit_after>// // Copyright (c) 2016 Terry Seyler // // Distributed under the MIT License // See accompanying file LICENSE.md // #include <core/protocol/c4soap/c4soap_message.hpp> #include <core/protocol/c4soap/c4soap_director.hpp> namespace proto_net { namespace protocol { namespace c4soap { std::string authenticate_password(unsigned long& seq, const params_array& /*params*/) { std::stringstream ss; c4soap_message::begin_c4soap_message(ss, "AuthenticatePassword", seq); c4soap_message::param(ss, "password", "string", "root"); c4soap_message::end_c4soap_message(ss); return ss.str(); } std::string get_version_info(unsigned long& seq, const params_array& /*params*/) { std::stringstream ss; c4soap_message::begin_c4soap_message(ss, "GetVersionInfo", seq); c4soap_message::end_c4soap_message(ss); return ss.str(); } std::string get_director_info(unsigned long& seq, const params_array& /*params*/) { std::stringstream ss; c4soap_message::begin_c4soap_message(ss, "GetDirectorInfo", seq); c4soap_message::end_c4soap_message(ss); return ss.str(); } std::string get_devices_by_interface(unsigned long& seq, const params_array& params) { std::stringstream ss; c4soap_message::begin_c4soap_message(ss, "GetDevicesByInterface", seq); c4soap_message::param(ss, "GUID", "string", params[0]); c4soap_message::end_c4soap_message(ss); return ss.str(); } std::string get_devices_by_c4i(unsigned long& seq, const params_array& params) { std::stringstream ss; c4soap_message::begin_c4soap_message(ss, "GetDevicesByC4i", seq); c4soap_message::param(ss, "c4i_name", "string", params[0]); c4soap_message::end_c4soap_message(ss); return ss.str(); } std::string send_to_device(unsigned long& seq, const params_array& params) { std::stringstream ss; if (params.size() > 1) { std::string id = params[0]; std::string cmd = params[1]; c4soap_message::begin_c4soap_message(ss, "SendToDevice", seq); c4soap_message::param(ss, "iddevice", "number", id); cmd = "<command>" + cmd + "<command>"; if (params.size() > 2) { std::string param = ""; for (size_t i = 2; i < params.size(); i++) { size_t j = i + 1; if (j < params.size()) { param += c4soap_message::get_param_value(params[i], params[j]); } else break; } std::string params = "<params>" + param + "</params>"; cmd += params; } std::string device_command = "<devicecommand>" + cmd + "</devicecommand>"; c4soap_message::param(ss, "data", "string", device_command); c4soap_message::end_c4soap_message(ss); } return ss.str(); } } } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "selectionindicator.h" #include <QPen> #include <cmath> #include <QGraphicsScene> #include <formeditorview.h> #include <formeditorwidget.h> #include <zoomaction.h> namespace QmlDesigner { SelectionIndicator::SelectionIndicator(LayerItem *layerItem) : m_layerItem(layerItem) { } SelectionIndicator::~SelectionIndicator() { clear(); } void SelectionIndicator::show() { foreach (QGraphicsPolygonItem *item, m_indicatorShapeHash.values()) item->show(); } void SelectionIndicator::hide() { foreach (QGraphicsPolygonItem *item, m_indicatorShapeHash.values()) item->hide(); } void SelectionIndicator::clear() { if (m_layerItem) { foreach (QGraphicsItem *item, m_indicatorShapeHash.values()) m_layerItem->scene()->removeItem(item); } m_indicatorShapeHash.clear(); } //static void alignVertices(QPolygonF &polygon, double factor) //{ // QMutableVectorIterator<QPointF> iterator(polygon); // while (iterator.hasNext()) { // QPointF &vertex = iterator.next(); // vertex.setX(std::floor(vertex.x()) + factor); // vertex.setY(std::floor(vertex.y()) + factor); // } // //} void SelectionIndicator::setItems(const QList<FormEditorItem*> &itemList) { clear(); foreach (FormEditorItem *item, itemList) { if (!item->qmlItemNode().isValid()) continue; QGraphicsPolygonItem *newSelectionIndicatorGraphicsItem = new QGraphicsPolygonItem(m_layerItem.data()); m_indicatorShapeHash.insert(item, newSelectionIndicatorGraphicsItem); QPolygonF boundingRectInSceneSpace(item->mapToScene(item->qmlItemNode().instanceBoundingRect())); // alignVertices(boundingRectInSceneSpace, 0.5 / item->formEditorView()->widget()->zoomAction()->zoomLevel()); QPolygonF boundingRectInLayerItemSpace = m_layerItem->mapFromScene(boundingRectInSceneSpace); newSelectionIndicatorGraphicsItem->setPolygon(boundingRectInLayerItemSpace); newSelectionIndicatorGraphicsItem->setFlag(QGraphicsItem::ItemIsSelectable, false); QPen pen; pen.setColor(QColor(108, 141, 221)); newSelectionIndicatorGraphicsItem->setPen(pen); newSelectionIndicatorGraphicsItem->setCursor(m_cursor); } } void SelectionIndicator::updateItems(const QList<FormEditorItem*> &itemList) { foreach (FormEditorItem *item, itemList) { if (m_indicatorShapeHash.contains(item)) { QGraphicsPolygonItem *indicatorGraphicsItem = m_indicatorShapeHash.value(item); QPolygonF boundingRectInSceneSpace(item->mapToScene(item->qmlItemNode().instanceBoundingRect())); // alignVertices(boundingRectInSceneSpace, 0.5 / item->formEditorView()->widget()->zoomAction()->zoomLevel()); QPolygonF boundingRectInLayerItemSpace = m_layerItem->mapFromScene(boundingRectInSceneSpace); indicatorGraphicsItem->setPolygon(boundingRectInLayerItemSpace); } } } void SelectionIndicator::setCursor(const QCursor &cursor) { m_cursor = cursor; foreach (QGraphicsItem *item, m_indicatorShapeHash.values()) item->setCursor(cursor); } } <commit_msg>QmlDesigner: fixing memory leak<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "selectionindicator.h" #include <QPen> #include <cmath> #include <QGraphicsScene> #include <formeditorview.h> #include <formeditorwidget.h> #include <zoomaction.h> namespace QmlDesigner { SelectionIndicator::SelectionIndicator(LayerItem *layerItem) : m_layerItem(layerItem) { } SelectionIndicator::~SelectionIndicator() { clear(); } void SelectionIndicator::show() { foreach (QGraphicsPolygonItem *item, m_indicatorShapeHash.values()) item->show(); } void SelectionIndicator::hide() { foreach (QGraphicsPolygonItem *item, m_indicatorShapeHash.values()) item->hide(); } void SelectionIndicator::clear() { if (m_layerItem) { foreach (QGraphicsItem *item, m_indicatorShapeHash.values()) { m_layerItem->scene()->removeItem(item); delete item; } } m_indicatorShapeHash.clear(); } //static void alignVertices(QPolygonF &polygon, double factor) //{ // QMutableVectorIterator<QPointF> iterator(polygon); // while (iterator.hasNext()) { // QPointF &vertex = iterator.next(); // vertex.setX(std::floor(vertex.x()) + factor); // vertex.setY(std::floor(vertex.y()) + factor); // } // //} void SelectionIndicator::setItems(const QList<FormEditorItem*> &itemList) { clear(); foreach (FormEditorItem *item, itemList) { if (!item->qmlItemNode().isValid()) continue; QGraphicsPolygonItem *newSelectionIndicatorGraphicsItem = new QGraphicsPolygonItem(m_layerItem.data()); m_indicatorShapeHash.insert(item, newSelectionIndicatorGraphicsItem); QPolygonF boundingRectInSceneSpace(item->mapToScene(item->qmlItemNode().instanceBoundingRect())); // alignVertices(boundingRectInSceneSpace, 0.5 / item->formEditorView()->widget()->zoomAction()->zoomLevel()); QPolygonF boundingRectInLayerItemSpace = m_layerItem->mapFromScene(boundingRectInSceneSpace); newSelectionIndicatorGraphicsItem->setPolygon(boundingRectInLayerItemSpace); newSelectionIndicatorGraphicsItem->setFlag(QGraphicsItem::ItemIsSelectable, false); QPen pen; pen.setColor(QColor(108, 141, 221)); newSelectionIndicatorGraphicsItem->setPen(pen); newSelectionIndicatorGraphicsItem->setCursor(m_cursor); } } void SelectionIndicator::updateItems(const QList<FormEditorItem*> &itemList) { foreach (FormEditorItem *item, itemList) { if (m_indicatorShapeHash.contains(item)) { QGraphicsPolygonItem *indicatorGraphicsItem = m_indicatorShapeHash.value(item); QPolygonF boundingRectInSceneSpace(item->mapToScene(item->qmlItemNode().instanceBoundingRect())); // alignVertices(boundingRectInSceneSpace, 0.5 / item->formEditorView()->widget()->zoomAction()->zoomLevel()); QPolygonF boundingRectInLayerItemSpace = m_layerItem->mapFromScene(boundingRectInSceneSpace); indicatorGraphicsItem->setPolygon(boundingRectInLayerItemSpace); } } } void SelectionIndicator::setCursor(const QCursor &cursor) { m_cursor = cursor; foreach (QGraphicsItem *item, m_indicatorShapeHash.values()) item->setCursor(cursor); } } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // // Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <cmake.h> #include <algorithm> // If <iostream> is included, put it after <stdio.h>, because it includes // <stdio.h>, and therefore would ignore the _WITH_GETLINE. #ifdef FREEBSD #define _WITH_GETLINE #endif #include <stdio.h> #include <unistd.h> #include <sys/wait.h> #include <sys/types.h> #include <Context.h> #include <Hooks.h> #include <text.h> extern Context context; //////////////////////////////////////////////////////////////////////////////// Hooks::Hooks () { } //////////////////////////////////////////////////////////////////////////////// Hooks::~Hooks () { } //////////////////////////////////////////////////////////////////////////////// void Hooks::initialize () { // Scan <rc.data.location>/hooks Directory d (context.config.get ("data.location")); d += "hooks"; if (d.is_directory () && d.readable ()) { _scripts = d.list (); std::sort (_scripts.begin (), _scripts.end ()); } } //////////////////////////////////////////////////////////////////////////////// // The on-launch event is triggered once, after initialization, before an // processing occurs // // No input // // Output: // - all emitted JSON lines must be fully-formed tasks // - all emitted non-JSON lines are considered feedback messages // // Exit: // 0 Means: - all emitted JSON lines are added/modifiied // - all emitted non-JSON lines become footnote entries // 1 Means: - all emitted JSON lines are ignored // - all emitted non-JSON lines become error entries // void Hooks::onLaunch () { context.timer_hooks.start (); std::vector <std::string> matchingScripts = scripts ("on-launch"); std::vector <std::string>::iterator i; for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i) { std::string output; int status = execute (*i, "", output); std::vector <std::string> lines; split (lines, output, '\n'); std::vector <std::string>::iterator line; if (status == 0) { for (line = lines.begin (); line != lines.end (); ++line) { if (line->length () && (*line)[0] == '{') { Task newTask (*line); context.tdb2.add (newTask); } else context.header (*line); } } else { for (line = lines.begin (); line != lines.end (); ++line) context.error (*line); throw 0; // This is how hooks silently terminate processing. } } context.timer_hooks.stop (); } //////////////////////////////////////////////////////////////////////////////// // Input: // - A read-only line of JSON for each task added/modified // // Output: // - all emitted non-JSON lines are considered feedback messages // // Exit: // 0 Means: - all emitted non-JSON lines become footnote entries // 1 Means: - all emitted non-JSON lines become error entries void Hooks::onExit () { context.timer_hooks.start (); std::vector <std::string> matchingScripts = scripts ("on-exit"); std::vector <std::string>::iterator i; for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i) { std::string output; int status = execute (*i, "", output); std::vector <std::string> lines; split (lines, output, '\n'); std::vector <std::string>::iterator line; if (status == 0) { for (line = lines.begin (); line != lines.end (); ++line) { if (line->length () && (*line)[0] == '{') { Task newTask (*line); context.tdb2.add (newTask); } else context.footnote (*line); } } else { for (line = lines.begin (); line != lines.end (); ++line) context.error (*line); } } context.timer_hooks.stop (); } //////////////////////////////////////////////////////////////////////////////// // The on-add event is triggered separately for each task added // // Input: // - A line of JSON for the task added // // Output: // - all emitted JSON lines must be fully-formed tasks // - all emitted non-JSON lines are considered feedback messages // // Exit: // 0 Means: - all emitted JSON lines are added/modifiied // - all emitted non-JSON lines become footnote entries // 1 Means: - all emitted JSON lines are ignored // - all emitted non-JSON lines become error entries // void Hooks::onAdd (Task& after) { context.timer_hooks.start (); std::vector <std::string> matchingScripts = scripts ("on-add"); std::vector <std::string>::iterator i; for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i) { std::string input = after.composeJSON () + "\n"; std::string output; int status = execute (*i, input, output); std::vector <std::string> lines; split (lines, output, '\n'); std::vector <std::string>::iterator line; if (status == 0) { bool first = true; for (line = lines.begin (); line != lines.end (); ++line) { if (line->length () && (*line)[0] == '{') { Task newTask (*line); if (first) { after = newTask; first = false; } else context.tdb2.add (newTask); } else context.footnote (*line); } } else { for (line = lines.begin (); line != lines.end (); ++line) context.error (*line); throw 0; // This is how hooks silently terminate processing. } } context.timer_hooks.stop (); } //////////////////////////////////////////////////////////////////////////////// // The on-modify event is triggered separately for each task added or modified // // Input: // - A line of JSON for the original task // - A line of JSON for the modified task // // Output: // - all emitted JSON lines must be fully-formed tasks // - all emitted non-JSON lines are considered feedback messages // // Exit: // 0 Means: - all emitted JSON lines are added/modifiied // - all emitted non-JSON lines become footnote entries // 1 Means: - all emitted JSON lines are ignored // - all emitted non-JSON lines become error entries void Hooks::onModify (const Task& before, Task& after) { context.timer_hooks.start (); std::vector <std::string> matchingScripts = scripts ("on-modify"); std::vector <std::string>::iterator i; for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i) { std::string afterJSON = after.composeJSON (); std::string input = before.composeJSON () + "\n" + afterJSON + "\n"; std::string output; int status = execute (*i, input, output); std::vector <std::string> lines; split (lines, output, '\n'); std::vector <std::string>::iterator line; if (status == 0) { bool first = true; for (line = lines.begin (); line != lines.end (); ++line) { if (line->length () && (*line)[0] == '{') { Task newTask (*line); if (first) { after = newTask; first = false; } else context.tdb2.add (newTask); } else context.footnote (*line); } } else { for (line = lines.begin (); line != lines.end (); ++line) context.error (*line); throw 0; // This is how hooks silently terminate processing. } } context.timer_hooks.stop (); } //////////////////////////////////////////////////////////////////////////////// std::vector <std::string> Hooks::list () { return _scripts; } //////////////////////////////////////////////////////////////////////////////// std::vector <std::string> Hooks::scripts (const std::string& event) { std::vector <std::string> matching; std::vector <std::string>::iterator i; for (i = _scripts.begin (); i != _scripts.end (); ++i) { if (i->find ("/" + event) != std::string::npos) { File script (*i); if (script.executable ()) matching.push_back (*i); } } return matching; } //////////////////////////////////////////////////////////////////////////////// int Hooks::execute ( const std::string& command, const std::string& input, std::string& output) { // TODO Improve error hnadling. // TODO Check errors. int pin[2], pout[2]; pipe (pin); pipe (pout); pid_t pid = fork(); if (!pid) { // This is only reached in the child dup2 (pin[0], STDIN_FILENO); dup2 (pout[1], STDOUT_FILENO); if (!execl (command.c_str (), command.c_str (), (char*) NULL)) exit (1); } // This is only reached in the parent close (pin[0]); close (pout[1]); // Write input to fp. FILE* pinf = fdopen (pin[1], "w"); if (input != "" && input != "\n") { fputs (input.c_str (), pinf); } fclose (pinf); close (pin[1]); // Read output from fp. output = ""; char* line = NULL; size_t len = 0; FILE* poutf = fdopen(pout[0], "r"); while (getline (&line, &len, poutf) != -1) { output += line; } if (line) free (line); fclose (poutf); close (pout[0]); int status = -1; wait (&status); if (WIFEXITED (status)) status = WEXITSTATUS (status); context.debug (format ("Hooks::execute {1} (status {2})", command, status)); return status; } //////////////////////////////////////////////////////////////////////////////// <commit_msg>Hooks<commit_after>//////////////////////////////////////////////////////////////////////////////// // // Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <cmake.h> #include <algorithm> // If <iostream> is included, put it after <stdio.h>, because it includes // <stdio.h>, and therefore would ignore the _WITH_GETLINE. #ifdef FREEBSD #define _WITH_GETLINE #endif #include <stdio.h> #include <unistd.h> #include <sys/wait.h> #include <sys/types.h> #include <Context.h> #include <Hooks.h> #include <text.h> extern Context context; //////////////////////////////////////////////////////////////////////////////// Hooks::Hooks () { } //////////////////////////////////////////////////////////////////////////////// Hooks::~Hooks () { } //////////////////////////////////////////////////////////////////////////////// void Hooks::initialize () { // Scan <rc.data.location>/hooks Directory d (context.config.get ("data.location")); d += "hooks"; if (d.is_directory () && d.readable ()) { _scripts = d.list (); std::sort (_scripts.begin (), _scripts.end ()); } } //////////////////////////////////////////////////////////////////////////////// // The on-launch event is triggered once, after initialization, before an // processing occurs // // No input // // Output: // - all emitted JSON lines must be fully-formed tasks // - all emitted non-JSON lines are considered feedback messages // // Exit: // 0 Means: - all emitted JSON lines are added/modifiied // - all emitted non-JSON lines become footnote entries // 1 Means: - all emitted JSON lines are ignored // - all emitted non-JSON lines become error entries // void Hooks::onLaunch () { context.timer_hooks.start (); std::vector <std::string> matchingScripts = scripts ("on-launch"); std::vector <std::string>::iterator i; for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i) { std::string output; int status = execute (*i, "", output); std::vector <std::string> lines; split (lines, output, '\n'); std::vector <std::string>::iterator line; if (status == 0) { for (line = lines.begin (); line != lines.end (); ++line) { if (line->length () && (*line)[0] == '{') { Task newTask (*line); context.tdb2.add (newTask); } else context.header (*line); } } else { for (line = lines.begin (); line != lines.end (); ++line) context.error (*line); throw 0; // This is how hooks silently terminate processing. } } context.timer_hooks.stop (); } //////////////////////////////////////////////////////////////////////////////// // Input: // - A read-only line of JSON for each task added/modified // // Output: // - all emitted non-JSON lines are considered feedback messages // // Exit: // 0 Means: - all emitted non-JSON lines become footnote entries // 1 Means: - all emitted non-JSON lines become error entries void Hooks::onExit () { context.timer_hooks.start (); std::vector <std::string> matchingScripts = scripts ("on-exit"); std::vector <std::string>::iterator i; for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i) { std::string output; int status = execute (*i, "", output); std::vector <std::string> lines; split (lines, output, '\n'); std::vector <std::string>::iterator line; if (status == 0) { for (line = lines.begin (); line != lines.end (); ++line) { if (line->length () && (*line)[0] == '{') { Task newTask (*line); context.tdb2.add (newTask); } else context.footnote (*line); } } else { for (line = lines.begin (); line != lines.end (); ++line) context.error (*line); } } context.timer_hooks.stop (); } //////////////////////////////////////////////////////////////////////////////// // The on-add event is triggered separately for each task added // // Input: // - A line of JSON for the task added // // Output: // - all emitted JSON lines must be fully-formed tasks // - all emitted non-JSON lines are considered feedback messages // // Exit: // 0 Means: - all emitted JSON lines are added/modifiied // - all emitted non-JSON lines become footnote entries // 1 Means: - all emitted JSON lines are ignored // - all emitted non-JSON lines become error entries // void Hooks::onAdd (Task& after) { context.timer_hooks.start (); std::vector <std::string> matchingScripts = scripts ("on-add"); std::vector <std::string>::iterator i; for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i) { std::string input = after.composeJSON () + "\n"; std::string output; int status = execute (*i, input, output); std::vector <std::string> lines; split (lines, output, '\n'); std::vector <std::string>::iterator line; if (status == 0) { bool first = true; for (line = lines.begin (); line != lines.end (); ++line) { if (line->length () && (*line)[0] == '{') { Task newTask (*line); if (first) { after = newTask; first = false; } else context.tdb2.add (newTask); } else context.footnote (*line); } } else { for (line = lines.begin (); line != lines.end (); ++line) context.error (*line); throw 0; // This is how hooks silently terminate processing. } } context.timer_hooks.stop (); } //////////////////////////////////////////////////////////////////////////////// // The on-modify event is triggered separately for each task added or modified // // Input: // - A line of JSON for the original task // - A line of JSON for the modified task // // Output: // - all emitted JSON lines must be fully-formed tasks // - all emitted non-JSON lines are considered feedback messages // // Exit: // 0 Means: - all emitted JSON lines are added/modifiied // - all emitted non-JSON lines become footnote entries // 1 Means: - all emitted JSON lines are ignored // - all emitted non-JSON lines become error entries void Hooks::onModify (const Task& before, Task& after) { context.timer_hooks.start (); std::vector <std::string> matchingScripts = scripts ("on-modify"); std::vector <std::string>::iterator i; for (i = matchingScripts.begin (); i != matchingScripts.end (); ++i) { std::string afterJSON = after.composeJSON (); std::string input = before.composeJSON () + "\n" + afterJSON + "\n"; std::string output; int status = execute (*i, input, output); std::vector <std::string> lines; split (lines, output, '\n'); std::vector <std::string>::iterator line; if (status == 0) { bool first = true; for (line = lines.begin (); line != lines.end (); ++line) { if (line->length () && (*line)[0] == '{') { Task newTask (*line); if (first) { after = newTask; first = false; } else context.tdb2.add (newTask); } else context.footnote (*line); } } else { for (line = lines.begin (); line != lines.end (); ++line) context.error (*line); throw 0; // This is how hooks silently terminate processing. } } context.timer_hooks.stop (); } //////////////////////////////////////////////////////////////////////////////// std::vector <std::string> Hooks::list () { return _scripts; } //////////////////////////////////////////////////////////////////////////////// std::vector <std::string> Hooks::scripts (const std::string& event) { std::vector <std::string> matching; std::vector <std::string>::iterator i; for (i = _scripts.begin (); i != _scripts.end (); ++i) { if (i->find ("/" + event) != std::string::npos) { File script (*i); if (script.executable ()) matching.push_back (*i); } } return matching; } //////////////////////////////////////////////////////////////////////////////// int Hooks::execute ( const std::string& command, const std::string& input, std::string& output) { // TODO Improve error hnadling. // TODO Check errors. int pin[2], pout[2]; pipe (pin); pipe (pout); pid_t pid = fork(); if (!pid) { // This is only reached in the child dup2 (pin[0], STDIN_FILENO); dup2 (pout[1], STDOUT_FILENO); if (!execl (command.c_str (), command.c_str (), (char*) NULL)) exit (1); } // This is only reached in the parent close (pin[0]); close (pout[1]); // Write input to fp. FILE* pinf = fdopen (pin[1], "w"); if (input != "" && input != "\n") { fputs (input.c_str (), pinf); } fclose (pinf); close (pin[1]); // Read output from fp. output = ""; char* line = NULL; size_t len = 0; FILE* poutf = fdopen(pout[0], "r"); while (getline (&line, &len, poutf) != -1) { output += line; } free (line); line = NULL; fclose (poutf); close (pout[0]); int status = -1; wait (&status); if (WIFEXITED (status)) status = WEXITSTATUS (status); context.debug (format ("Hooks::execute {1} (status {2})", command, status)); return status; } //////////////////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>// This file was developed by Thomas Müller <[email protected]>. // It is published under the BSD 3-Clause License within the LICENSE file. #include "../include/Image.h" #include "../include/ThreadPool.h" #include <ImfChannelList.h> #include <ImfInputFile.h> #include <ImfInputPart.h> #include <ImfMultiPartInputFile.h> #include <stb_image.h> #include <algorithm> #include <array> #include <chrono> #include <iostream> #include <set> using namespace std; TEV_NAMESPACE_BEGIN bool isExrFile(const string& filename) { ifstream f{filename, ios_base::binary}; if (!f) { throw invalid_argument{tfm::format("File %s could not be opened.", filename)}; } // Taken from http://www.openexr.com/ReadingAndWritingImageFiles.pdf char b[4]; f.read(b, sizeof(b)); return !!f && b[0] == 0x76 && b[1] == 0x2f && b[2] == 0x31 && b[3] == 0x01; } Image::Image(const string& filename, const string& extra) : mName{tfm::format("%s:%s", filename, extra)} { if (isExrFile(filename)) { readExr(filename, extra); } else { readStbi(filename); } } string Image::shortName() { string result = mName; size_t slashPosition = result.find_last_of("/\\"); if (slashPosition != string::npos) { result = result.substr(slashPosition + 1); } size_t colonPosition = result.find_last_of(":"); if (colonPosition != string::npos) { result = result.substr(0, colonPosition); } return result; } vector<string> Image::channelsInLayer(string layerName) const { vector<string> result; if (layerName.empty()) { for (const auto& kv : mChannels) { if (kv.first.find(".") == string::npos) { result.emplace_back(kv.first); } } } else { for (const auto& kv : mChannels) { // If the layer name starts at the beginning, and // if no other dot is found after the end of the layer name, // then we have found a channel of this layer. if (kv.first.find(layerName) == 0 && kv.first.length() > layerName.length()) { const auto& channelWithoutLayer = kv.first.substr(layerName.length() + 1); if (channelWithoutLayer.find(".") == string::npos) { result.emplace_back(kv.first); } } } } return result; } const GlTexture* Image::texture(const string& channelName) { auto iter = mTextures.find(channelName); if (iter != end(mTextures)) { return &iter->second; } const auto* chan = channel(channelName); if (!chan) { throw invalid_argument{tfm::format("Cannot obtain texture of channel %s, because the channel does not exist.", channelName)}; } mTextures.emplace(channelName, GlTexture{}); auto& texture = mTextures.at(channelName); texture.setData(chan->data(), mSize, 1); return &texture; } string Image::toString() const { string result = tfm::format("Path: %s\n\nResolution: (%d, %d)\n\nChannels:\n", mName, mSize.x(), mSize.y()); auto localLayers = mLayers; transform(begin(localLayers), end(localLayers), begin(localLayers), [this](string layer) { auto channels = channelsInLayer(layer); transform(begin(channels), end(channels), begin(channels), [this](string channel) { return Channel::tail(channel); }); if (layer.empty()) { layer = "<root>"; } return layer + ": " + join(channels, ","); }); return result + join(localLayers, "\n"); } void Image::readStbi(const string& filename) { // No exr image? Try our best using stbi cout << "Loading "s + filename + " via STBI... "; auto start = chrono::system_clock::now(); ThreadPool threadPool; int numChannels; auto data = stbi_loadf(filename.c_str(), &mSize.x(), &mSize.y(), &numChannels, 0); if (!data) { throw invalid_argument("Could not load texture data from file " + filename); } mNumChannels = static_cast<size_t>(numChannels); size_t numPixels = mSize.prod(); vector<string> channelNames = {"R", "G", "B", "A"}; vector<Channel> channels; for (size_t c = 0; c < mNumChannels; ++c) { string name = c < channelNames.size() ? channelNames[c] : to_string(c - channelNames.size()); channels.emplace_back(name, mSize); channels.back().data().resize(numPixels); } threadPool.parallelFor(0, numPixels, [&](size_t i) { size_t baseIdx = i * mNumChannels; for (size_t c = 0; c < mNumChannels; ++c) { channels[c].data()[i] = data[baseIdx + c]; } }); stbi_image_free(data); for (auto& channel : channels) { string name = channel.name(); mChannels.emplace(move(name), move(channel)); } // STBI can not load layers, so all channels simply reside // within a topmost root layer. mLayers.emplace_back(""); auto end = chrono::system_clock::now(); chrono::duration<double> elapsedSeconds = end - start; cout << tfm::format("done after %.3f seconds.\n", elapsedSeconds.count()); } void Image::readExr(const string& filename, const string& channelSubstr) { // OpenEXR for reading exr images cout << "Loading "s + filename + " via OpenEXR... "; auto start = chrono::system_clock::now(); ThreadPool threadPool; Imf::MultiPartInputFile multiPartFile{filename.c_str()}; int numParts = multiPartFile.parts(); if (numParts <= 0) { throw invalid_argument{tfm::format("EXR image '%s' does not contain any parts.", filename)}; } // Find the first part containing a channel that matches the given channelSubstr. int partIdx = 0; for (int i = 0; i < numParts; ++i) { Imf::InputPart part{multiPartFile, i}; const Imf::ChannelList& imfChannels = part.header().channels(); for (Imf::ChannelList::ConstIterator c = imfChannels.begin(); c != imfChannels.end(); ++c) { if (string{c.name()}.find(channelSubstr) != string::npos) { partIdx = i; goto l_foundPart; } } } l_foundPart: Imf::InputPart file{multiPartFile, partIdx}; Imath::Box2i dw = file.header().dataWindow(); mSize.x() = dw.max.x - dw.min.x + 1; mSize.y() = dw.max.y - dw.min.y + 1; // Inline helper class for dealing with the raw channels loaded from an exr file. class RawChannel { public: RawChannel(string name, Imf::Channel imfChannel) : mName(name), mImfChannel(imfChannel) { } void resize(size_t size) { mData.resize(size * bytesPerPixel()); } void registerWith(Imf::FrameBuffer& frameBuffer, const Imath::Box2i& dw) { int width = dw.max.x - dw.min.x + 1; frameBuffer.insert(mName.c_str(), Imf::Slice( mImfChannel.type, mData.data() - (dw.min.x + dw.min.y * width) * bytesPerPixel(), bytesPerPixel(), bytesPerPixel() * width, mImfChannel.xSampling, mImfChannel.ySampling, 0 )); } void copyTo(Channel& channel, ThreadPool& threadPool) const { auto& dstData = channel.data(); dstData.resize(mData.size() / bytesPerPixel()); // The code in this switch statement may seem overly complicated, but it helps // the compiler optimize. This code is time-critical for large images. switch (mImfChannel.type) { case Imf::HALF: threadPool.parallelForNoWait(0, dstData.size(), [&](size_t i) { dstData[i] = static_cast<float>(*reinterpret_cast<const half*>(&mData[i * sizeof(half)])); }); break; case Imf::FLOAT: threadPool.parallelForNoWait(0, dstData.size(), [&](size_t i) { dstData[i] = *reinterpret_cast<const float*>(&mData[i * sizeof(float)]); }); break; case Imf::UINT: threadPool.parallelForNoWait(0, dstData.size(), [&](size_t i) { dstData[i] = static_cast<float>(*reinterpret_cast<const uint32_t*>(&mData[i * sizeof(uint32_t)])); }); break; default: throw runtime_error("Invalid pixel type encountered."); } } const auto& name() const { return mName; } private: int bytesPerPixel() const { switch (mImfChannel.type) { case Imf::HALF: return sizeof(half); case Imf::FLOAT: return sizeof(float); case Imf::UINT: return sizeof(uint32_t); default: throw runtime_error("Invalid pixel type encountered."); } } string mName; Imf::Channel mImfChannel; vector<char> mData; }; vector<RawChannel> rawChannels; Imf::FrameBuffer frameBuffer; const Imf::ChannelList& imfChannels = file.header().channels(); set<string> layerNames; for (Imf::ChannelList::ConstIterator c = imfChannels.begin(); c != imfChannels.end(); ++c) { if (string{c.name()}.find(channelSubstr) != string::npos) { rawChannels.emplace_back(c.name(), c.channel().type); layerNames.insert(Channel::head(c.name())); } } if (rawChannels.empty()) { throw invalid_argument{tfm::format("No channels match '%s'.", channelSubstr)}; } for (const string& layer : layerNames) { mLayers.emplace_back(layer); } threadPool.parallelFor(0, rawChannels.size(), [&](size_t i) { rawChannels[i].resize(mSize.prod()); }); for (size_t i = 0; i < rawChannels.size(); ++i) { rawChannels[i].registerWith(frameBuffer, dw); } file.setFrameBuffer(frameBuffer); file.readPixels(dw.min.y, dw.max.y); for (const auto& rawChannel : rawChannels) { mChannels.emplace(rawChannel.name(), Channel{rawChannel.name(), mSize}); } for (size_t i = 0; i < rawChannels.size(); ++i) { rawChannels[i].copyTo(mChannels.at(rawChannels[i].name()), threadPool); } threadPool.waitUntilFinished(); auto end = chrono::system_clock::now(); chrono::duration<double> elapsedSeconds = end - start; cout << tfm::format("done after %.3f seconds.\n", elapsedSeconds.count()); } shared_ptr<Image> tryLoadImage(string filename, string extra) { try { return make_shared<Image>(filename, extra); } catch (invalid_argument e) { tfm::format(cerr, "Could not load image from %s:%s - %s\n", filename, extra, e.what()); } catch (Iex::BaseExc& e) { tfm::format(cerr, "Could not load image from %s:%s - %s\n", filename, extra, e.what()); } return nullptr; } TEV_NAMESPACE_END <commit_msg>Hotfix incorrect file path display<commit_after>// This file was developed by Thomas Müller <[email protected]>. // It is published under the BSD 3-Clause License within the LICENSE file. #include "../include/Image.h" #include "../include/ThreadPool.h" #include <ImfChannelList.h> #include <ImfInputFile.h> #include <ImfInputPart.h> #include <ImfMultiPartInputFile.h> #include <stb_image.h> #include <algorithm> #include <array> #include <chrono> #include <iostream> #include <set> using namespace std; TEV_NAMESPACE_BEGIN bool isExrFile(const string& filename) { ifstream f{filename, ios_base::binary}; if (!f) { throw invalid_argument{tfm::format("File %s could not be opened.", filename)}; } // Taken from http://www.openexr.com/ReadingAndWritingImageFiles.pdf char b[4]; f.read(b, sizeof(b)); return !!f && b[0] == 0x76 && b[1] == 0x2f && b[2] == 0x31 && b[3] == 0x01; } Image::Image(const string& filename, const string& extra) { mName = filename; if (!extra.empty()) { mName += ":"s + extra; } if (isExrFile(filename)) { readExr(filename, extra); } else { readStbi(filename); } } string Image::shortName() { string result = mName; size_t slashPosition = result.find_last_of("/\\"); if (slashPosition != string::npos) { result = result.substr(slashPosition + 1); } size_t colonPosition = result.find_last_of(":"); if (colonPosition != string::npos) { result = result.substr(0, colonPosition); } return result; } vector<string> Image::channelsInLayer(string layerName) const { vector<string> result; if (layerName.empty()) { for (const auto& kv : mChannels) { if (kv.first.find(".") == string::npos) { result.emplace_back(kv.first); } } } else { for (const auto& kv : mChannels) { // If the layer name starts at the beginning, and // if no other dot is found after the end of the layer name, // then we have found a channel of this layer. if (kv.first.find(layerName) == 0 && kv.first.length() > layerName.length()) { const auto& channelWithoutLayer = kv.first.substr(layerName.length() + 1); if (channelWithoutLayer.find(".") == string::npos) { result.emplace_back(kv.first); } } } } return result; } const GlTexture* Image::texture(const string& channelName) { auto iter = mTextures.find(channelName); if (iter != end(mTextures)) { return &iter->second; } const auto* chan = channel(channelName); if (!chan) { throw invalid_argument{tfm::format("Cannot obtain texture of channel %s, because the channel does not exist.", channelName)}; } mTextures.emplace(channelName, GlTexture{}); auto& texture = mTextures.at(channelName); texture.setData(chan->data(), mSize, 1); return &texture; } string Image::toString() const { string result = tfm::format("Path: %s\n\nResolution: (%d, %d)\n\nChannels:\n", mName, mSize.x(), mSize.y()); auto localLayers = mLayers; transform(begin(localLayers), end(localLayers), begin(localLayers), [this](string layer) { auto channels = channelsInLayer(layer); transform(begin(channels), end(channels), begin(channels), [this](string channel) { return Channel::tail(channel); }); if (layer.empty()) { layer = "<root>"; } return layer + ": " + join(channels, ","); }); return result + join(localLayers, "\n"); } void Image::readStbi(const string& filename) { // No exr image? Try our best using stbi cout << "Loading "s + filename + " via STBI... "; auto start = chrono::system_clock::now(); ThreadPool threadPool; int numChannels; auto data = stbi_loadf(filename.c_str(), &mSize.x(), &mSize.y(), &numChannels, 0); if (!data) { throw invalid_argument("Could not load texture data from file " + filename); } mNumChannels = static_cast<size_t>(numChannels); size_t numPixels = mSize.prod(); vector<string> channelNames = {"R", "G", "B", "A"}; vector<Channel> channels; for (size_t c = 0; c < mNumChannels; ++c) { string name = c < channelNames.size() ? channelNames[c] : to_string(c - channelNames.size()); channels.emplace_back(name, mSize); channels.back().data().resize(numPixels); } threadPool.parallelFor(0, numPixels, [&](size_t i) { size_t baseIdx = i * mNumChannels; for (size_t c = 0; c < mNumChannels; ++c) { channels[c].data()[i] = data[baseIdx + c]; } }); stbi_image_free(data); for (auto& channel : channels) { string name = channel.name(); mChannels.emplace(move(name), move(channel)); } // STBI can not load layers, so all channels simply reside // within a topmost root layer. mLayers.emplace_back(""); auto end = chrono::system_clock::now(); chrono::duration<double> elapsedSeconds = end - start; cout << tfm::format("done after %.3f seconds.\n", elapsedSeconds.count()); } void Image::readExr(const string& filename, const string& channelSubstr) { // OpenEXR for reading exr images cout << "Loading "s + filename + " via OpenEXR... "; auto start = chrono::system_clock::now(); ThreadPool threadPool; Imf::MultiPartInputFile multiPartFile{filename.c_str()}; int numParts = multiPartFile.parts(); if (numParts <= 0) { throw invalid_argument{tfm::format("EXR image '%s' does not contain any parts.", filename)}; } // Find the first part containing a channel that matches the given channelSubstr. int partIdx = 0; for (int i = 0; i < numParts; ++i) { Imf::InputPart part{multiPartFile, i}; const Imf::ChannelList& imfChannels = part.header().channels(); for (Imf::ChannelList::ConstIterator c = imfChannels.begin(); c != imfChannels.end(); ++c) { if (string{c.name()}.find(channelSubstr) != string::npos) { partIdx = i; goto l_foundPart; } } } l_foundPart: Imf::InputPart file{multiPartFile, partIdx}; Imath::Box2i dw = file.header().dataWindow(); mSize.x() = dw.max.x - dw.min.x + 1; mSize.y() = dw.max.y - dw.min.y + 1; // Inline helper class for dealing with the raw channels loaded from an exr file. class RawChannel { public: RawChannel(string name, Imf::Channel imfChannel) : mName(name), mImfChannel(imfChannel) { } void resize(size_t size) { mData.resize(size * bytesPerPixel()); } void registerWith(Imf::FrameBuffer& frameBuffer, const Imath::Box2i& dw) { int width = dw.max.x - dw.min.x + 1; frameBuffer.insert(mName.c_str(), Imf::Slice( mImfChannel.type, mData.data() - (dw.min.x + dw.min.y * width) * bytesPerPixel(), bytesPerPixel(), bytesPerPixel() * width, mImfChannel.xSampling, mImfChannel.ySampling, 0 )); } void copyTo(Channel& channel, ThreadPool& threadPool) const { auto& dstData = channel.data(); dstData.resize(mData.size() / bytesPerPixel()); // The code in this switch statement may seem overly complicated, but it helps // the compiler optimize. This code is time-critical for large images. switch (mImfChannel.type) { case Imf::HALF: threadPool.parallelForNoWait(0, dstData.size(), [&](size_t i) { dstData[i] = static_cast<float>(*reinterpret_cast<const half*>(&mData[i * sizeof(half)])); }); break; case Imf::FLOAT: threadPool.parallelForNoWait(0, dstData.size(), [&](size_t i) { dstData[i] = *reinterpret_cast<const float*>(&mData[i * sizeof(float)]); }); break; case Imf::UINT: threadPool.parallelForNoWait(0, dstData.size(), [&](size_t i) { dstData[i] = static_cast<float>(*reinterpret_cast<const uint32_t*>(&mData[i * sizeof(uint32_t)])); }); break; default: throw runtime_error("Invalid pixel type encountered."); } } const auto& name() const { return mName; } private: int bytesPerPixel() const { switch (mImfChannel.type) { case Imf::HALF: return sizeof(half); case Imf::FLOAT: return sizeof(float); case Imf::UINT: return sizeof(uint32_t); default: throw runtime_error("Invalid pixel type encountered."); } } string mName; Imf::Channel mImfChannel; vector<char> mData; }; vector<RawChannel> rawChannels; Imf::FrameBuffer frameBuffer; const Imf::ChannelList& imfChannels = file.header().channels(); set<string> layerNames; for (Imf::ChannelList::ConstIterator c = imfChannels.begin(); c != imfChannels.end(); ++c) { if (string{c.name()}.find(channelSubstr) != string::npos) { rawChannels.emplace_back(c.name(), c.channel().type); layerNames.insert(Channel::head(c.name())); } } if (rawChannels.empty()) { throw invalid_argument{tfm::format("No channels match '%s'.", channelSubstr)}; } for (const string& layer : layerNames) { mLayers.emplace_back(layer); } threadPool.parallelFor(0, rawChannels.size(), [&](size_t i) { rawChannels[i].resize(mSize.prod()); }); for (size_t i = 0; i < rawChannels.size(); ++i) { rawChannels[i].registerWith(frameBuffer, dw); } file.setFrameBuffer(frameBuffer); file.readPixels(dw.min.y, dw.max.y); for (const auto& rawChannel : rawChannels) { mChannels.emplace(rawChannel.name(), Channel{rawChannel.name(), mSize}); } for (size_t i = 0; i < rawChannels.size(); ++i) { rawChannels[i].copyTo(mChannels.at(rawChannels[i].name()), threadPool); } threadPool.waitUntilFinished(); auto end = chrono::system_clock::now(); chrono::duration<double> elapsedSeconds = end - start; cout << tfm::format("done after %.3f seconds.\n", elapsedSeconds.count()); } shared_ptr<Image> tryLoadImage(string filename, string extra) { try { return make_shared<Image>(filename, extra); } catch (invalid_argument e) { tfm::format(cerr, "Could not load image from %s:%s - %s\n", filename, extra, e.what()); } catch (Iex::BaseExc& e) { tfm::format(cerr, "Could not load image from %s:%s - %s\n", filename, extra, e.what()); } return nullptr; } TEV_NAMESPACE_END <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: iderdll.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: tbe $ $Date: 2001-07-25 11:39:43 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _IDERDLL_HXX #define _IDERDLL_HXX class BasicIDEShell; class BasicIDEData; class BasicIDEDLL { friend class BasicIDEShell; BasicIDEShell* pShell; BasicIDEData* pExtraData; public: BasicIDEDLL(); ~BasicIDEDLL(); BasicIDEShell* GetShell() const { return pShell; } BasicIDEData* GetExtraData(); static void Init(); static void Exit(); static void LibInit(); static void LibExit(); static BasicIDEDLL* GetDLL(); }; #define IDE_DLL() BasicIDEDLL::GetDLL() #endif //_IDERDLL_HXX <commit_msg>INTEGRATION: CWS fwkq1 (1.2.104); FILE MERGED 2003/07/14 16:09:48 mba 1.2.104.1: #110843#: get rid of factories<commit_after>/************************************************************************* * * $RCSfile: iderdll.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2003-09-19 08:28:52 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _IDERDLL_HXX #define _IDERDLL_HXX class BasicIDEShell; class BasicIDEData; class BasicIDEDLL { friend class BasicIDEShell; BasicIDEShell* pShell; BasicIDEData* pExtraData; public: BasicIDEDLL(); ~BasicIDEDLL(); BasicIDEShell* GetShell() const { return pShell; } BasicIDEData* GetExtraData(); static void Init(); static void Exit(); static BasicIDEDLL* GetDLL(); }; #define IDE_DLL() BasicIDEDLL::GetDLL() #endif //_IDERDLL_HXX <|endoftext|>
<commit_before>#include <QApplication> #include "window.hpp" int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.setFixedSize(vwp_w, vwp_h); w.show(); return a.exec(); } <commit_msg>ui: force GLES context<commit_after>#include <QApplication> #include "window.hpp" int main(int argc, char *argv[]) { QSurfaceFormat fmt; fmt.setRenderableType(QSurfaceFormat::OpenGLES); QSurfaceFormat::setDefaultFormat(fmt); QApplication a(argc, argv); MainWindow w; w.setFixedSize(vwp_w, vwp_h); w.show(); return a.exec(); } <|endoftext|>
<commit_before>/* * * Copyright (c) 2020 Project CHIP Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cinttypes> #include "console/console.h" #include "pw_sys_io/sys_io.h" #include <cassert> #include <zephyr.h> extern "C" void pw_sys_io_Init() { assert(console_init() == 0); } namespace pw::sys_io { Status ReadByte(std::byte * dest) { if (!dest) return Status::INVALID_ARGUMENT; const int c = console_getchar(); *dest = static_cast<std::byte>(c); return c < 0 ? Status::FAILED_PRECONDITION : Status::OK; } Status WriteByte(std::byte b) { return console_putchar(static_cast<char>(b)) < 0 ? Status::FAILED_PRECONDITION : Status::OK; } // Writes a string using pw::sys_io, and add newline characters at the end. StatusWithSize WriteLine(const std::string_view & s) { size_t chars_written = 0; StatusWithSize result = WriteBytes(std::as_bytes(std::span(s))); if (!result.ok()) { return result; } chars_written += result.size(); // Write trailing newline. result = WriteBytes(std::as_bytes(std::span("\r\n", 2))); chars_written += result.size(); return StatusWithSize(result.status(), chars_written); } } // namespace pw::sys_io <commit_msg>[nrfconnect] remove functional code from assert (#3628)<commit_after>/* * * Copyright (c) 2020 Project CHIP Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cinttypes> #include "console/console.h" #include "pw_sys_io/sys_io.h" #include <cassert> #include <zephyr.h> extern "C" void pw_sys_io_Init() { int err = console_init(); assert(err == 0); } namespace pw::sys_io { Status ReadByte(std::byte * dest) { if (!dest) return Status::INVALID_ARGUMENT; const int c = console_getchar(); *dest = static_cast<std::byte>(c); return c < 0 ? Status::FAILED_PRECONDITION : Status::OK; } Status WriteByte(std::byte b) { return console_putchar(static_cast<char>(b)) < 0 ? Status::FAILED_PRECONDITION : Status::OK; } // Writes a string using pw::sys_io, and add newline characters at the end. StatusWithSize WriteLine(const std::string_view & s) { size_t chars_written = 0; StatusWithSize result = WriteBytes(std::as_bytes(std::span(s))); if (!result.ok()) { return result; } chars_written += result.size(); // Write trailing newline. result = WriteBytes(std::as_bytes(std::span("\r\n", 2))); chars_written += result.size(); return StatusWithSize(result.status(), chars_written); } } // namespace pw::sys_io <|endoftext|>
<commit_before>// Copyright (c) 2017-2019 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #include "test.hpp" #include <tao/pegtl/internal/demangle.hpp> namespace TAO_PEGTL_NAMESPACE { template< typename T > void test( const std::string& s ) { TAO_PEGTL_TEST_ASSERT( internal::demangle< T >() == s ); } void unit_test() { #if defined( __GNUC__ ) && ( __GNUC__ == 9 ) || ( __GNUC_MINOR__ <= 2 ) // see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=91155 test< int >( "i" ); test< double >( "d" ); test< seq< bytes< 42 >, eof > >( "N3tao5pegtl3seqIJNS0_5bytesILj42EEENS0_3eofEEEE" ); #elif defined( _MSC_VER ) test< int >( "int" ); test< double >( "double" ); test< seq< bytes< 42 >, eof > >( "struct tao::pegtl::seq<struct tao::pegtl::bytes<42>,struct tao::pegtl::eof>" ); #else test< int >( "int" ); test< double >( "double" ); test< seq< bytes< 42 >, eof > >( "tao::pegtl::seq<tao::pegtl::bytes<42>, tao::pegtl::eof>" ); #endif } } // namespace TAO_PEGTL_NAMESPACE #include "main.hpp" <commit_msg>Fix condition<commit_after>// Copyright (c) 2017-2019 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #include "test.hpp" #include <tao/pegtl/internal/demangle.hpp> namespace TAO_PEGTL_NAMESPACE { template< typename T > void test( const std::string& s ) { TAO_PEGTL_TEST_ASSERT( internal::demangle< T >() == s ); } void unit_test() { #if defined( __GNUC__ ) && ( __GNUC__ == 9 ) && ( __GNUC_MINOR__ <= 2 ) // see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=91155 test< int >( "i" ); test< double >( "d" ); test< seq< bytes< 42 >, eof > >( "N3tao5pegtl3seqIJNS0_5bytesILj42EEENS0_3eofEEEE" ); #elif defined( _MSC_VER ) test< int >( "int" ); test< double >( "double" ); test< seq< bytes< 42 >, eof > >( "struct tao::pegtl::seq<struct tao::pegtl::bytes<42>,struct tao::pegtl::eof>" ); #else test< int >( "int" ); test< double >( "double" ); test< seq< bytes< 42 >, eof > >( "tao::pegtl::seq<tao::pegtl::bytes<42>, tao::pegtl::eof>" ); #endif } } // namespace TAO_PEGTL_NAMESPACE #include "main.hpp" <|endoftext|>
<commit_before>/* * Copyright 2007-2017 Content Management AG * All rights reserved. * * author: Max Kellermann <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "tconstruct.hxx" #include "http_cache.hxx" #include "ResourceLoader.hxx" #include "ResourceAddress.hxx" #include "http_address.hxx" #include "GrowingBuffer.hxx" #include "header_parser.hxx" #include "strmap.hxx" #include "HttpResponseHandler.hxx" #include "PInstance.hxx" #include "fb_pool.hxx" #include "istream/UnusedPtr.hxx" #include "istream/istream.hxx" #include "istream/istream_string.hxx" #include "util/Cancellable.hxx" #include "util/PrintException.hxx" #include "util/Compiler.h" #include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <signal.h> struct Request final : IstreamHandler { bool cached = false; http_method_t method = HTTP_METHOD_GET; const char *uri; const char *request_headers; http_status_t status = HTTP_STATUS_OK; const char *response_headers; const char *response_body; bool eof = false; size_t body_read = 0; constexpr Request(const char *_uri, const char *_request_headers, const char *_response_headers, const char *_response_body) noexcept :uri(_uri), request_headers(_request_headers), response_headers(_response_headers), response_body(_response_body) {} /* virtual methods from class IstreamHandler */ size_t OnData(gcc_unused const void *data, size_t length) override { assert(body_read + length <= strlen(response_body)); assert(memcmp(response_body + body_read, data, length) == 0); body_read += length; return length; } void OnEof() noexcept override { eof = true; } void OnError(std::exception_ptr) noexcept override { assert(false); } }; #define DATE "Fri, 30 Jan 2009 10:53:30 GMT" #define STAMP1 "Fri, 30 Jan 2009 08:53:30 GMT" #define STAMP2 "Fri, 20 Jan 2009 08:53:30 GMT" #define EXPIRES "Fri, 20 Jan 2029 08:53:30 GMT" Request requests[] = { { "/foo", nullptr, "date: " DATE "\n" "last-modified: " STAMP1 "\n" "expires: " EXPIRES "\n" "vary: x-foo\n", "foo", }, { "/foo", "x-foo: foo\n", "date: " DATE "\n" "last-modified: " STAMP2 "\n" "expires: " EXPIRES "\n" "vary: x-foo\n", "bar", }, { "/query?string", nullptr, "date: " DATE "\n" "last-modified: " STAMP1 "\n", "foo", }, { "/query?string2", nullptr, "date: " DATE "\n" "last-modified: " STAMP1 "\n" "expires: " EXPIRES "\n", "foo", }, }; static HttpCache *cache; static unsigned current_request; static bool got_request, got_response; static bool validated; static StringMap * parse_headers(struct pool &pool, const char *raw) { if (raw == NULL) return NULL; GrowingBuffer gb; StringMap *headers = strmap_new(&pool); gb.Write(raw); header_parse_buffer(pool, *headers, std::move(gb)); return headers; } static StringMap * parse_request_headers(struct pool &pool, const Request &request) { return parse_headers(pool, request.request_headers); } static StringMap * parse_response_headers(struct pool &pool, const Request &request) { return parse_headers(pool, request.response_headers); } class MyResourceLoader final : public ResourceLoader { public: /* virtual methods from class ResourceLoader */ void SendRequest(struct pool &pool, sticky_hash_t sticky_hash, const char *site_name, http_method_t method, const ResourceAddress &address, http_status_t status, StringMap &&headers, UnusedIstreamPtr body, const char *body_etag, HttpResponseHandler &handler, CancellablePointer &cancel_ptr) override; }; void MyResourceLoader::SendRequest(struct pool &pool, sticky_hash_t, gcc_unused const char *site_name, http_method_t method, gcc_unused const ResourceAddress &address, gcc_unused http_status_t status, StringMap &&headers, UnusedIstreamPtr body, gcc_unused const char *body_etag, HttpResponseHandler &handler, gcc_unused CancellablePointer &cancel_ptr) { const auto *request = &requests[current_request]; StringMap *expected_rh; assert(!got_request); assert(!got_response); assert(method == request->method); got_request = true; validated = headers.Get("if-modified-since") != nullptr; expected_rh = parse_request_headers(pool, *request); if (expected_rh != NULL) { for (const auto &i : headers) { const char *value = headers.Get(i.key); assert(value != NULL); assert(strcmp(value, i.value) == 0); } } body.Clear(); StringMap response_headers(pool); if (request->response_headers != NULL) { GrowingBuffer gb; gb.Write(request->response_headers); header_parse_buffer(pool, response_headers, std::move(gb)); } UnusedIstreamPtr response_body; if (request->response_body != NULL) response_body = istream_string_new(pool, request->response_body); handler.InvokeResponse(request->status, std::move(response_headers), std::move(response_body)); } struct Context final : HttpResponseHandler { struct pool &pool; explicit Context(struct pool &_pool):pool(_pool) {} /* virtual methods from class HttpResponseHandler */ void OnHttpResponse(http_status_t status, StringMap &&headers, UnusedIstreamPtr body) noexcept override; void OnHttpError(std::exception_ptr ep) noexcept override; }; void Context::OnHttpResponse(http_status_t status, StringMap &&headers, UnusedIstreamPtr body) noexcept { Request *request = &requests[current_request]; StringMap *expected_rh; assert(status == request->status); expected_rh = parse_response_headers(pool, *request); if (expected_rh != NULL) { for (const auto &i : *expected_rh) { const char *value = headers.Get(i.key); assert(value != NULL); assert(strcmp(value, i.value) == 0); } } if (body) { request->body_read = 0; auto *b = body.Steal(); b->SetHandler(*request); b->Read(); } got_response = true; } void gcc_noreturn Context::OnHttpError(std::exception_ptr ep) noexcept { PrintException(ep); assert(false); } static void run_cache_test(struct pool *root_pool, unsigned num, bool cached) { const Request *request = &requests[num]; struct pool *pool = pool_new_linear(root_pool, "t_http_cache", 8192); const auto uwa = MakeHttpAddress(request->uri).Host("foo"); const ResourceAddress address(uwa); CancellablePointer cancel_ptr; current_request = num; StringMap headers(*pool); if (request->request_headers != NULL) { GrowingBuffer gb; gb.Write(request->request_headers); header_parse_buffer(*pool, headers, std::move(gb)); } got_request = cached; got_response = false; Context context(*pool); http_cache_request(*cache, *pool, 0, nullptr, request->method, address, std::move(headers), nullptr, context, cancel_ptr); pool_unref(pool); assert(got_request); assert(got_response); } int main(int argc, char **argv) { (void)argc; (void)argv; const ScopeFbPoolInit fb_pool_init; PInstance instance; MyResourceLoader resource_loader; cache = http_cache_new(instance.root_pool, 1024 * 1024, instance.event_loop, resource_loader); /* request one resource, cold and warm cache */ run_cache_test(instance.root_pool, 0, false); run_cache_test(instance.root_pool, 0, true); /* another resource, different header */ run_cache_test(instance.root_pool, 1, false); run_cache_test(instance.root_pool, 1, true); /* see if the first resource is still cached */ run_cache_test(instance.root_pool, 0, true); /* see if the second resource is still cached */ run_cache_test(instance.root_pool, 1, true); /* query string: should not be cached */ run_cache_test(instance.root_pool, 2, false); validated = false; run_cache_test(instance.root_pool, 2, false); assert(!validated); /* double check with a cacheable query string ("Expires" is set) */ run_cache_test(instance.root_pool, 3, false); run_cache_test(instance.root_pool, 3, true); http_cache_close(cache); } <commit_msg>test/t_http_cache: make requests static<commit_after>/* * Copyright 2007-2017 Content Management AG * All rights reserved. * * author: Max Kellermann <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "tconstruct.hxx" #include "http_cache.hxx" #include "ResourceLoader.hxx" #include "ResourceAddress.hxx" #include "http_address.hxx" #include "GrowingBuffer.hxx" #include "header_parser.hxx" #include "strmap.hxx" #include "HttpResponseHandler.hxx" #include "PInstance.hxx" #include "fb_pool.hxx" #include "istream/UnusedPtr.hxx" #include "istream/istream.hxx" #include "istream/istream_string.hxx" #include "util/Cancellable.hxx" #include "util/PrintException.hxx" #include "util/Compiler.h" #include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <signal.h> struct Request final : IstreamHandler { bool cached = false; http_method_t method = HTTP_METHOD_GET; const char *uri; const char *request_headers; http_status_t status = HTTP_STATUS_OK; const char *response_headers; const char *response_body; bool eof = false; size_t body_read = 0; constexpr Request(const char *_uri, const char *_request_headers, const char *_response_headers, const char *_response_body) noexcept :uri(_uri), request_headers(_request_headers), response_headers(_response_headers), response_body(_response_body) {} /* virtual methods from class IstreamHandler */ size_t OnData(gcc_unused const void *data, size_t length) override { assert(body_read + length <= strlen(response_body)); assert(memcmp(response_body + body_read, data, length) == 0); body_read += length; return length; } void OnEof() noexcept override { eof = true; } void OnError(std::exception_ptr) noexcept override { assert(false); } }; #define DATE "Fri, 30 Jan 2009 10:53:30 GMT" #define STAMP1 "Fri, 30 Jan 2009 08:53:30 GMT" #define STAMP2 "Fri, 20 Jan 2009 08:53:30 GMT" #define EXPIRES "Fri, 20 Jan 2029 08:53:30 GMT" static Request requests[] = { { "/foo", nullptr, "date: " DATE "\n" "last-modified: " STAMP1 "\n" "expires: " EXPIRES "\n" "vary: x-foo\n", "foo", }, { "/foo", "x-foo: foo\n", "date: " DATE "\n" "last-modified: " STAMP2 "\n" "expires: " EXPIRES "\n" "vary: x-foo\n", "bar", }, { "/query?string", nullptr, "date: " DATE "\n" "last-modified: " STAMP1 "\n", "foo", }, { "/query?string2", nullptr, "date: " DATE "\n" "last-modified: " STAMP1 "\n" "expires: " EXPIRES "\n", "foo", }, }; static HttpCache *cache; static unsigned current_request; static bool got_request, got_response; static bool validated; static StringMap * parse_headers(struct pool &pool, const char *raw) { if (raw == NULL) return NULL; GrowingBuffer gb; StringMap *headers = strmap_new(&pool); gb.Write(raw); header_parse_buffer(pool, *headers, std::move(gb)); return headers; } static StringMap * parse_request_headers(struct pool &pool, const Request &request) { return parse_headers(pool, request.request_headers); } static StringMap * parse_response_headers(struct pool &pool, const Request &request) { return parse_headers(pool, request.response_headers); } class MyResourceLoader final : public ResourceLoader { public: /* virtual methods from class ResourceLoader */ void SendRequest(struct pool &pool, sticky_hash_t sticky_hash, const char *site_name, http_method_t method, const ResourceAddress &address, http_status_t status, StringMap &&headers, UnusedIstreamPtr body, const char *body_etag, HttpResponseHandler &handler, CancellablePointer &cancel_ptr) override; }; void MyResourceLoader::SendRequest(struct pool &pool, sticky_hash_t, gcc_unused const char *site_name, http_method_t method, gcc_unused const ResourceAddress &address, gcc_unused http_status_t status, StringMap &&headers, UnusedIstreamPtr body, gcc_unused const char *body_etag, HttpResponseHandler &handler, gcc_unused CancellablePointer &cancel_ptr) { const auto *request = &requests[current_request]; StringMap *expected_rh; assert(!got_request); assert(!got_response); assert(method == request->method); got_request = true; validated = headers.Get("if-modified-since") != nullptr; expected_rh = parse_request_headers(pool, *request); if (expected_rh != NULL) { for (const auto &i : headers) { const char *value = headers.Get(i.key); assert(value != NULL); assert(strcmp(value, i.value) == 0); } } body.Clear(); StringMap response_headers(pool); if (request->response_headers != NULL) { GrowingBuffer gb; gb.Write(request->response_headers); header_parse_buffer(pool, response_headers, std::move(gb)); } UnusedIstreamPtr response_body; if (request->response_body != NULL) response_body = istream_string_new(pool, request->response_body); handler.InvokeResponse(request->status, std::move(response_headers), std::move(response_body)); } struct Context final : HttpResponseHandler { struct pool &pool; explicit Context(struct pool &_pool):pool(_pool) {} /* virtual methods from class HttpResponseHandler */ void OnHttpResponse(http_status_t status, StringMap &&headers, UnusedIstreamPtr body) noexcept override; void OnHttpError(std::exception_ptr ep) noexcept override; }; void Context::OnHttpResponse(http_status_t status, StringMap &&headers, UnusedIstreamPtr body) noexcept { Request *request = &requests[current_request]; StringMap *expected_rh; assert(status == request->status); expected_rh = parse_response_headers(pool, *request); if (expected_rh != NULL) { for (const auto &i : *expected_rh) { const char *value = headers.Get(i.key); assert(value != NULL); assert(strcmp(value, i.value) == 0); } } if (body) { request->body_read = 0; auto *b = body.Steal(); b->SetHandler(*request); b->Read(); } got_response = true; } void gcc_noreturn Context::OnHttpError(std::exception_ptr ep) noexcept { PrintException(ep); assert(false); } static void run_cache_test(struct pool *root_pool, unsigned num, bool cached) { const Request *request = &requests[num]; struct pool *pool = pool_new_linear(root_pool, "t_http_cache", 8192); const auto uwa = MakeHttpAddress(request->uri).Host("foo"); const ResourceAddress address(uwa); CancellablePointer cancel_ptr; current_request = num; StringMap headers(*pool); if (request->request_headers != NULL) { GrowingBuffer gb; gb.Write(request->request_headers); header_parse_buffer(*pool, headers, std::move(gb)); } got_request = cached; got_response = false; Context context(*pool); http_cache_request(*cache, *pool, 0, nullptr, request->method, address, std::move(headers), nullptr, context, cancel_ptr); pool_unref(pool); assert(got_request); assert(got_response); } int main(int argc, char **argv) { (void)argc; (void)argv; const ScopeFbPoolInit fb_pool_init; PInstance instance; MyResourceLoader resource_loader; cache = http_cache_new(instance.root_pool, 1024 * 1024, instance.event_loop, resource_loader); /* request one resource, cold and warm cache */ run_cache_test(instance.root_pool, 0, false); run_cache_test(instance.root_pool, 0, true); /* another resource, different header */ run_cache_test(instance.root_pool, 1, false); run_cache_test(instance.root_pool, 1, true); /* see if the first resource is still cached */ run_cache_test(instance.root_pool, 0, true); /* see if the second resource is still cached */ run_cache_test(instance.root_pool, 1, true); /* query string: should not be cached */ run_cache_test(instance.root_pool, 2, false); validated = false; run_cache_test(instance.root_pool, 2, false); assert(!validated); /* double check with a cacheable query string ("Expires" is set) */ run_cache_test(instance.root_pool, 3, false); run_cache_test(instance.root_pool, 3, true); http_cache_close(cache); } <|endoftext|>
<commit_before>#include <cmath> #include "qniteaxes.h" #include "qniteaxis.h" #include "qnitemapper.h" #include "qnitezoompainter.h" #include "qnitezoomtool.h" QniteZoomTool::QniteZoomTool(QQuickItem *parent) : QniteTool{parent}, m_minZoomFactor{4}, m_pen{new QnitePen} { setAcceptedMouseButtons(Qt::RightButton); // Default pen style m_pen->setFill("#6EDCDCDC"); m_pen->setStroke("#7E7E7E"); m_pen->setWidth(1.0); connect(this, &QniteZoomTool::axesChanged, this, &QniteZoomTool::connectAxesBoundsSignals); connect(this, &QniteZoomTool::minZoomFactorChanged, this, &QniteZoomTool::updateEnabled); } QniteZoomTool::~QniteZoomTool() {} QNanoQuickItemPainter *QniteZoomTool::createItemPainter() const { return new QniteZoomPainter; } void QniteZoomTool::reset() { auto xAxis = axes()->axisX(); auto yAxis = axes()->axisY(); xAxis->setLowerBound(m_baseZoomRect.x()); xAxis->setUpperBound(m_baseZoomRect.width()); yAxis->setLowerBound(m_baseZoomRect.y()); yAxis->setUpperBound(m_baseZoomRect.height()); setEnabled(true); update(); axes()->updateArtists(); } void QniteZoomTool::setMinZoomFactor(int factor) { if (m_minZoomFactor != factor) { m_minZoomFactor = factor; emit minZoomFactorChanged(); } } void QniteZoomTool::mousePressEvent(QMouseEvent *event) { if (!isEnabled()) { return; } m_zoomRect.setTopLeft(event->pos()); } void QniteZoomTool::mouseMoveEvent(QMouseEvent *event) { if (!isEnabled()) { return; } m_zoomRect.setBottomRight(event->pos()); update(); } void QniteZoomTool::mouseReleaseEvent(QMouseEvent *event) { if (m_zoomRect.isNull() || event->pos() == m_zoomRect.topLeft()) { return; } // Calculates new axes bounds and updates them auto yMin = qMin(m_zoomRect.top(), m_zoomRect.bottom()); auto yMax = qMax(m_zoomRect.top(), m_zoomRect.bottom()); auto yAxis = axes()->axisY(); auto yMappedMin = yAxis->mapper()->mapTo(0, axes()->height(), yAxis->lowerBound(), yAxis->upperBound(), yMin, yAxis->flip()); auto yMappedMax = yAxis->mapper()->mapTo(0, axes()->height(), yAxis->lowerBound(), yAxis->upperBound(), yMax, yAxis->flip()); auto xMin = qMin(m_zoomRect.left(), m_zoomRect.right()); auto xMax = qMax(m_zoomRect.left(), m_zoomRect.right()); auto xAxis = axes()->axisX(); auto xMappedMin = xAxis->mapper()->mapTo(0, axes()->width(), xAxis->lowerBound(), xAxis->upperBound(), xMin, xAxis->flip()); auto xMappedMax = xAxis->mapper()->mapTo(0, axes()->width(), xAxis->lowerBound(), xAxis->upperBound(), xMax, xAxis->flip()); yAxis->setLowerBound(qMin(yMappedMin, yMappedMax)); yAxis->setUpperBound(qMax(yMappedMin, yMappedMax)); xAxis->setLowerBound(qMin(xMappedMin, xMappedMax)); xAxis->setUpperBound(qMax(xMappedMin, xMappedMax)); m_zoomRect = QRectF{}; update(); axes()->updateArtists(); // Disables tool if calculated bounds are smaller than the minimum zoom size auto minSize = minimumZoomSize(); auto axisYSize = qAbs(yMappedMin - yMappedMax); auto axisXSize = qAbs(xMappedMin - xMappedMax); if (axisXSize <= minSize.width() || axisYSize <= minSize.height()) { setEnabled(false); } } void QniteZoomTool::connectAxesBoundsSignals() const { connect(axes(), &QniteAxes::xBoundsChanged, this, &QniteZoomTool::updateBaseZoomRectXBounds); connect(axes(), &QniteAxes::yBoundsChanged, this, &QniteZoomTool::updateBaseZoomRectYBounds); disconnect(this, &QniteZoomTool::axesChanged, this, &QniteZoomTool::connectAxesBoundsSignals); } void QniteZoomTool::updateBaseZoomRectXBounds() { auto xBounds = axes()->xBounds(); m_baseZoomRect.setX(xBounds.first()); m_baseZoomRect.setWidth(xBounds.last()); disconnect(axes(), &QniteAxes::xBoundsChanged, this, &QniteZoomTool::updateBaseZoomRectXBounds); } void QniteZoomTool::updateBaseZoomRectYBounds() { auto yBounds = axes()->yBounds(); m_baseZoomRect.setY(yBounds.first()); m_baseZoomRect.setHeight(yBounds.last()); disconnect(axes(), &QniteAxes::yBoundsChanged, this, &QniteZoomTool::updateBaseZoomRectYBounds); } QSizeF QniteZoomTool::minimumZoomSize() const { qreal factor = std::pow(10, m_minZoomFactor); return {qAbs(m_baseZoomRect.width() / factor), qAbs(m_baseZoomRect.height() / factor)}; } void QniteZoomTool::updateEnabled() { // Disables tool if current bounds are smaller than the minimum zoom size, // enables it otherwise auto axisX = axes()->axisX(); auto axisY = axes()->axisY(); auto axisXSize = qAbs(axisX->lowerBound() - axisX->upperBound()); auto axisYSize = qAbs(axisY->lowerBound() - axisY->upperBound()); auto minSize = minimumZoomSize(); auto enable = axisXSize > minSize.width() || axisYSize > minSize.height(); setEnabled(enable); } <commit_msg>Fixed zoom rectangle being drawn when not necessary<commit_after>#include <cmath> #include "qniteaxes.h" #include "qniteaxis.h" #include "qnitemapper.h" #include "qnitezoompainter.h" #include "qnitezoomtool.h" QniteZoomTool::QniteZoomTool(QQuickItem *parent) : QniteTool{parent}, m_minZoomFactor{4}, m_pen{new QnitePen} { setAcceptedMouseButtons(Qt::RightButton); // Default pen style m_pen->setFill("#6EDCDCDC"); m_pen->setStroke("#7E7E7E"); m_pen->setWidth(1.0); connect(this, &QniteZoomTool::axesChanged, this, &QniteZoomTool::connectAxesBoundsSignals); connect(this, &QniteZoomTool::minZoomFactorChanged, this, &QniteZoomTool::updateEnabled); } QniteZoomTool::~QniteZoomTool() {} QNanoQuickItemPainter *QniteZoomTool::createItemPainter() const { return new QniteZoomPainter; } void QniteZoomTool::reset() { auto xAxis = axes()->axisX(); auto yAxis = axes()->axisY(); xAxis->setLowerBound(m_baseZoomRect.x()); xAxis->setUpperBound(m_baseZoomRect.width()); yAxis->setLowerBound(m_baseZoomRect.y()); yAxis->setUpperBound(m_baseZoomRect.height()); setEnabled(true); update(); axes()->updateArtists(); } void QniteZoomTool::setMinZoomFactor(int factor) { if (m_minZoomFactor != factor) { m_minZoomFactor = factor; emit minZoomFactorChanged(); } } void QniteZoomTool::mousePressEvent(QMouseEvent *event) { if (!isEnabled()) { return; } m_zoomRect.setTopLeft(event->pos()); } void QniteZoomTool::mouseMoveEvent(QMouseEvent *event) { if (!isEnabled()) { return; } m_zoomRect.setBottomRight(event->pos()); update(); } void QniteZoomTool::mouseReleaseEvent(QMouseEvent *event) { if (m_zoomRect.isNull() || event->pos() == m_zoomRect.topLeft()) { m_zoomRect = QRectF{}; return; } // Calculates new axes bounds and updates them auto yMin = qMin(m_zoomRect.top(), m_zoomRect.bottom()); auto yMax = qMax(m_zoomRect.top(), m_zoomRect.bottom()); auto yAxis = axes()->axisY(); auto yMappedMin = yAxis->mapper()->mapTo(0, axes()->height(), yAxis->lowerBound(), yAxis->upperBound(), yMin, yAxis->flip()); auto yMappedMax = yAxis->mapper()->mapTo(0, axes()->height(), yAxis->lowerBound(), yAxis->upperBound(), yMax, yAxis->flip()); auto xMin = qMin(m_zoomRect.left(), m_zoomRect.right()); auto xMax = qMax(m_zoomRect.left(), m_zoomRect.right()); auto xAxis = axes()->axisX(); auto xMappedMin = xAxis->mapper()->mapTo(0, axes()->width(), xAxis->lowerBound(), xAxis->upperBound(), xMin, xAxis->flip()); auto xMappedMax = xAxis->mapper()->mapTo(0, axes()->width(), xAxis->lowerBound(), xAxis->upperBound(), xMax, xAxis->flip()); yAxis->setLowerBound(qMin(yMappedMin, yMappedMax)); yAxis->setUpperBound(qMax(yMappedMin, yMappedMax)); xAxis->setLowerBound(qMin(xMappedMin, xMappedMax)); xAxis->setUpperBound(qMax(xMappedMin, xMappedMax)); m_zoomRect = QRectF{}; update(); axes()->updateArtists(); // Disables tool if calculated bounds are smaller than the minimum zoom size auto minSize = minimumZoomSize(); auto axisYSize = qAbs(yMappedMin - yMappedMax); auto axisXSize = qAbs(xMappedMin - xMappedMax); if (axisXSize <= minSize.width() || axisYSize <= minSize.height()) { setEnabled(false); } } void QniteZoomTool::connectAxesBoundsSignals() const { connect(axes(), &QniteAxes::xBoundsChanged, this, &QniteZoomTool::updateBaseZoomRectXBounds); connect(axes(), &QniteAxes::yBoundsChanged, this, &QniteZoomTool::updateBaseZoomRectYBounds); disconnect(this, &QniteZoomTool::axesChanged, this, &QniteZoomTool::connectAxesBoundsSignals); } void QniteZoomTool::updateBaseZoomRectXBounds() { auto xBounds = axes()->xBounds(); m_baseZoomRect.setX(xBounds.first()); m_baseZoomRect.setWidth(xBounds.last()); disconnect(axes(), &QniteAxes::xBoundsChanged, this, &QniteZoomTool::updateBaseZoomRectXBounds); } void QniteZoomTool::updateBaseZoomRectYBounds() { auto yBounds = axes()->yBounds(); m_baseZoomRect.setY(yBounds.first()); m_baseZoomRect.setHeight(yBounds.last()); disconnect(axes(), &QniteAxes::yBoundsChanged, this, &QniteZoomTool::updateBaseZoomRectYBounds); } QSizeF QniteZoomTool::minimumZoomSize() const { qreal factor = std::pow(10, m_minZoomFactor); return {qAbs(m_baseZoomRect.width() / factor), qAbs(m_baseZoomRect.height() / factor)}; } void QniteZoomTool::updateEnabled() { // Disables tool if current bounds are smaller than the minimum zoom size, // enables it otherwise auto axisX = axes()->axisX(); auto axisY = axes()->axisY(); auto axisXSize = qAbs(axisX->lowerBound() - axisX->upperBound()); auto axisYSize = qAbs(axisY->lowerBound() - axisY->upperBound()); auto minSize = minimumZoomSize(); auto enable = axisXSize > minSize.width() || axisYSize > minSize.height(); setEnabled(enable); } <|endoftext|>
<commit_before>//! \file /* ** Copyright (C) - Triton ** ** This program is under the terms of the LGPLv3 License. */ #ifndef TRITON_PIN_PYTHONBINDINGS_H #define TRITON_PIN_PYTHONBINDINGS_H #include <map> #include <set> #include <list> #include <python2.7/Python.h> #include <pin.H> /* libTriton */ #include <api.hpp> #include <tritonTypes.hpp> /* pintool */ #include "trigger.hpp" #include "snapshot.hpp" //! \module The Tracer namespace namespace tracer { /*! * \addtogroup tracer * @{ */ //! \module The pintool namespace namespace pintool { /*! * \ingroup tracer * \addtogroup pintool * @{ */ //! Lock / Unlock InsertCall extern Trigger analysisTrigger; //! Snapshot engine extern Snapshot snapshot; //! Python callbacks of the pintool module. extern PyMethodDef pintoolCallbacks[]; //! The python script which will be executed by Pin. bool execScript(const char* fileName); //! The initialization of the Pin's Python env. void initBindings(void); extern std::string getImageName(triton::__uint address); //! \module The options namespace namespace options { /*! * \ingroup pintool * \addtogroup options * @{ */ //! Kind of callback. enum cb_kind { CB_AFTER, //!< After the instruction processing. CB_BEFORE, //!< Before the instruction processing. CB_BEFORE_SYMPROC, //!< Before the IR processing. CB_FINI, //!< At the end of the execution. CB_ROUTINE_ENTRY, //!< Before the routine processing. CB_ROUTINE_EXIT, //!< After the routine processing. CB_SIGNALS, //!< When a signal occurs. CB_SYSCALL_ENTRY, //!< Before the syscall processing. CB_SYSCALL_EXIT, //!< After the syscall processing. CB_IMAGE_LOAD, //!< When an image is loaded. }; //! Start analysis from a symbol. extern char* startAnalysisFromSymbol; //! Start analysis from the entry point. extern bool startAnalysisFromEntry; //! Start analysis from a symbol. extern std::set<triton::__uint> startAnalysisFromAddr; //! Start analysis from an offset. extern std::set<triton::__uint> startAnalysisFromOffset; //! Stop analysis from address. extern std::set<triton::__uint> stopAnalysisFromAddr; //! Stop analysis from an offset. extern std::set<triton::__uint> stopAnalysisFromOffset; //! Callback called after the instruction processing. extern PyObject* callbackAfter; //! Callback called before the instruction processing. extern PyObject* callbackBefore; //! Callback called before the IR processing. extern PyObject* callbackBeforeIRProc; //! Callback called at the end of the execution. extern PyObject* callbackFini; //! Callback called when a signal occurs. extern PyObject* callbackSignals; //! Callback called before the syscall processing. extern PyObject* callbackSyscallEntry; //! Callback called after the syscall processing. extern PyObject* callbackSyscallExit; //! Callback called when an image is loaded. extern PyObject* callbackImageLoad; //! Callback called before routine processing. extern std::map<const char*, PyObject*> callbackRoutineEntry; //! Callback callled after routine processing. extern std::map<const char*, PyObject*> callbackRoutineExit; //! An image white list. extern std::list<const char*> imageWhitelist; //! An image black list. extern std::list<const char*> imageBlacklist; //! TID focused during the JIT extern triton::uint32 targetThreadId; /*! @} End of options namespace */ }; //! \module The callbacks namespace namespace callbacks { /*! * \ingroup pintool * \addtogroup callback * @{ */ //! Callback called after the instruction processing. void after(triton::arch::Instruction* inst); //! Callback called before the instruction processing. void before(triton::arch::Instruction* inst); //! Callback called before the IR processing. void beforeIRProc(triton::arch::Instruction* inst); //! Callback called at the end of the execution. void fini(void); //! Callback called before and after routine processing. void routine(triton::uint32 threadId, PyObject* callback); //! Callback called when a signal occurs. void signals(triton::uint32 threadId, triton::sint32 sig); //! Callback called before the syscall processing. void syscallEntry(triton::uint32 threadId, triton::uint32 std); //! Callback called after the syscall processing. void syscallExit(triton::uint32 threadId, triton::uint32 std); //! Callback called when an image is loaded. void imageLoad(std::string imagePath, triton::__uint imageBase, triton::__uint imageSize); //! Pre processing configuration. void preProcessing(triton::arch::Instruction* inst, triton::uint32 threadId); //! Post processing configuration. void postProcessing(triton::arch::Instruction* inst, triton::uint32 threadId); /*! @} End of callback namespace */ }; /*! @} End of pintool namespace */ }; /*! @} End of tracer namespace */ }; #endif /* TRITON_PIN_PYTHONBINDINGS_H */ <commit_msg>Add doc<commit_after>//! \file /* ** Copyright (C) - Triton ** ** This program is under the terms of the LGPLv3 License. */ #ifndef TRITON_PIN_PYTHONBINDINGS_H #define TRITON_PIN_PYTHONBINDINGS_H #include <map> #include <set> #include <list> #include <python2.7/Python.h> #include <pin.H> /* libTriton */ #include <api.hpp> #include <tritonTypes.hpp> /* pintool */ #include "trigger.hpp" #include "snapshot.hpp" //! \module The Tracer namespace namespace tracer { /*! * \addtogroup tracer * @{ */ //! \module The pintool namespace namespace pintool { /*! * \ingroup tracer * \addtogroup pintool * @{ */ //! Lock / Unlock InsertCall extern Trigger analysisTrigger; //! Snapshot engine extern Snapshot snapshot; //! Python callbacks of the pintool module. extern PyMethodDef pintoolCallbacks[]; //! The python script which will be executed by Pin. bool execScript(const char* fileName); //! The initialization of the Pin's Python env. void initBindings(void); //! Image name from address extern std::string getImageName(triton::__uint address); //! \module The options namespace namespace options { /*! * \ingroup pintool * \addtogroup options * @{ */ //! Kind of callback. enum cb_kind { CB_AFTER, //!< After the instruction processing. CB_BEFORE, //!< Before the instruction processing. CB_BEFORE_SYMPROC, //!< Before the IR processing. CB_FINI, //!< At the end of the execution. CB_ROUTINE_ENTRY, //!< Before the routine processing. CB_ROUTINE_EXIT, //!< After the routine processing. CB_SIGNALS, //!< When a signal occurs. CB_SYSCALL_ENTRY, //!< Before the syscall processing. CB_SYSCALL_EXIT, //!< After the syscall processing. CB_IMAGE_LOAD, //!< When an image is loaded. }; //! Start analysis from a symbol. extern char* startAnalysisFromSymbol; //! Start analysis from the entry point. extern bool startAnalysisFromEntry; //! Start analysis from a symbol. extern std::set<triton::__uint> startAnalysisFromAddr; //! Start analysis from an offset. extern std::set<triton::__uint> startAnalysisFromOffset; //! Stop analysis from address. extern std::set<triton::__uint> stopAnalysisFromAddr; //! Stop analysis from an offset. extern std::set<triton::__uint> stopAnalysisFromOffset; //! Callback called after the instruction processing. extern PyObject* callbackAfter; //! Callback called before the instruction processing. extern PyObject* callbackBefore; //! Callback called before the IR processing. extern PyObject* callbackBeforeIRProc; //! Callback called at the end of the execution. extern PyObject* callbackFini; //! Callback called when a signal occurs. extern PyObject* callbackSignals; //! Callback called before the syscall processing. extern PyObject* callbackSyscallEntry; //! Callback called after the syscall processing. extern PyObject* callbackSyscallExit; //! Callback called when an image is loaded. extern PyObject* callbackImageLoad; //! Callback called before routine processing. extern std::map<const char*, PyObject*> callbackRoutineEntry; //! Callback callled after routine processing. extern std::map<const char*, PyObject*> callbackRoutineExit; //! An image white list. extern std::list<const char*> imageWhitelist; //! An image black list. extern std::list<const char*> imageBlacklist; //! TID focused during the JIT extern triton::uint32 targetThreadId; /*! @} End of options namespace */ }; //! \module The callbacks namespace namespace callbacks { /*! * \ingroup pintool * \addtogroup callback * @{ */ //! Callback called after the instruction processing. void after(triton::arch::Instruction* inst); //! Callback called before the instruction processing. void before(triton::arch::Instruction* inst); //! Callback called before the IR processing. void beforeIRProc(triton::arch::Instruction* inst); //! Callback called at the end of the execution. void fini(void); //! Callback called before and after routine processing. void routine(triton::uint32 threadId, PyObject* callback); //! Callback called when a signal occurs. void signals(triton::uint32 threadId, triton::sint32 sig); //! Callback called before the syscall processing. void syscallEntry(triton::uint32 threadId, triton::uint32 std); //! Callback called after the syscall processing. void syscallExit(triton::uint32 threadId, triton::uint32 std); //! Callback called when an image is loaded. void imageLoad(std::string imagePath, triton::__uint imageBase, triton::__uint imageSize); //! Pre processing configuration. void preProcessing(triton::arch::Instruction* inst, triton::uint32 threadId); //! Post processing configuration. void postProcessing(triton::arch::Instruction* inst, triton::uint32 threadId); /*! @} End of callback namespace */ }; /*! @} End of pintool namespace */ }; /*! @} End of tracer namespace */ }; #endif /* TRITON_PIN_PYTHONBINDINGS_H */ <|endoftext|>
<commit_before>#pragma once #include <map> namespace Doremi { namespace Core { /** The audio component contains the handle to the soundchannel and a handle to the sound */ // If you add someone, enum class AudioCompEnum : int32_t { Jump, Death, DebugSound, Num_Sounds, }; struct AudioComponent { // std::map<AudioCompEnum, int> m_enumToSoundID; int32_t m_enumToSoundID[(int32_t)(AudioCompEnum::Num_Sounds)]; // +1]; //Todo maybe bugs out // int mySoundID = sounds[(int)AudioCompEnum::Jump]; AudioComponent() { for(int32_t i = 0; i < (int32_t)AudioCompEnum::Num_Sounds; i++) { m_enumToSoundID[i] = (int32_t)AudioCompEnum::DebugSound; } } }; } }<commit_msg>Added damage taken sound to audio enum<commit_after>#pragma once #include <map> namespace Doremi { namespace Core { /** The audio component contains the handle to the soundchannel and a handle to the sound */ // If you add someone, enum class AudioCompEnum : int32_t { Jump, Death, DamageTaken, DebugSound, Num_Sounds, }; struct AudioComponent { // std::map<AudioCompEnum, int> m_enumToSoundID; int32_t m_enumToSoundID[(int32_t)(AudioCompEnum::Num_Sounds)]; // +1]; //Todo maybe bugs out // int mySoundID = sounds[(int)AudioCompEnum::Jump]; AudioComponent() { for(int32_t i = 0; i < (int32_t)AudioCompEnum::Num_Sounds; i++) { m_enumToSoundID[i] = (int32_t)AudioCompEnum::DebugSound; } } }; } }<|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: GaussianMinimumErrorClassifier.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "OptionList.h" #include "itkImage.h" #include "itkReadMetaImage.h" #include "itkWriteMetaImage.h" #include "itkImageRegionIterator.h" #include "vnl/vnl_matrix.h" #include "itkImageToListAdaptor.h" #include "itkSubsample.h" #include "itkMembershipSample.h" #include "itkMembershipSampleGenerator.h" #include "itkGaussianDensityFunction.h" #include "itkMeanCalculator.h" #include "itkCovarianceCalculator.h" #include "itkTableLookupSampleClassifier.h" #include "MaximumLikelihoodRatioDecisionRule.h" #include "itkStatisticsAlgorithm.h" void print_usage() { std::cout << "GaussianMinimumErrorClassifier 1.0 (17. Dec. 2001)" << std::endl ; std::cout << "usage: GaussianMinimumErrorClassifier --training file" << std::endl ; std::cout << " --class-mask file" << std::endl ; std::cout << " --target file" << std::endl ; std::cout << " --output file" << std::endl ; std::cout << "" << std::endl ; std::cout << "--training file" << std::endl ; std::cout << " image file name with intesnity values [meta image format]" << std::endl ; std::cout << "--class-mask file" << std::endl ; std::cout << " image file name with class labels [meta image format]" << std::endl ; std::cout << "--target file" << std::endl ; std::cout << " target image file name with intensity values [meta image format]" << std::endl ; std::cout << "--output file" << std::endl ; std::cout << " output image file name that will have the class labels for pixels" << std::endl ; std::cout << " in the target image file [meta image format]" << std::endl ; std::cout << "" << std::endl ; std::cout << "example: GaussianMinimumErrorClassifier --training train.mhd" << std::endl ; std::cout << " --class-mask class_mask.mhd" << std::endl ; std::cout << " --target target.mhd" << std::endl ; std::cout << " --output output.mhd" << std::endl ; } int main(int argc, char* argv[]) { namespace stat = itk::Statistics ; if (argc <= 1) { print_usage() ; exit(0) ; } OptionList options(argc, argv) ; std::string trainingFileName ; std::string classMaskFileName ; std::string targetFileName ; std::string outputFileName ; try { // get image file options options.GetStringOption("training", &trainingFileName, true) ; // get image file options options.GetStringOption("class-mask", &classMaskFileName, true) ; // get image file options options.GetStringOption("target", &targetFileName, true) ; // get image file options options.GetStringOption("output", &outputFileName, true) ; } catch(OptionList::RequiredOptionMissing e) { std::cout << "Error: The '" << e.OptionTag << "' option is required but missing." << std::endl ; return 1 ; } typedef itk::Image< short, 3 > ImageType ; typedef ImageType::Pointer ImagePointer ; ImagePointer training ; ImagePointer classMask ; ImagePointer target ; std::cout << "Loading image(s)..." << std::endl ; // readMetaImageHeader(trainingFileName, trainingDimension, trainingSize) ; typedef itk::ReadMetaImage<ImageType> Reader ; Reader::Pointer reader = Reader::New() ; reader->SetFileName(trainingFileName.c_str()) ; reader->Update() ; training = reader->GetOutput() ; std::cout << "Training image loaded." << std::endl ; Reader::Pointer reader2 = Reader::New() ; reader2->SetFileName(classMaskFileName.c_str()) ; reader2->Update() ; classMask = reader2->GetOutput() ; std::cout << "Class mask loaded." << std::endl ; Reader::Pointer reader3 = Reader::New() ; reader3->SetFileName(targetFileName.c_str()) ; reader3->Update() ; target = reader3->GetOutput() ; std::cout << "Target image loaded." << std::endl ; /* ================================================== */ std::cout << "Importing the images to samples..." << std::endl ; typedef stat::ImageToListAdaptor< ImageType, stat::ScalarImageAccessor< ImageType > > ImageListSampleType; ImageListSampleType::Pointer sample = ImageListSampleType::New() ; ImageListSampleType::Pointer mask = ImageListSampleType::New() ; ImageListSampleType::Pointer targetSample = ImageListSampleType::New() ; sample->SetImage(training); mask->SetImage(classMask) ; targetSample->SetImage(target) ; /* ==================================================== */ std::cout << "Creating the membership sample for training.." << std::endl ; typedef stat::MembershipSampleGenerator< ImageListSampleType, ImageListSampleType > MembershipSampleGeneratorType ; MembershipSampleGeneratorType::Pointer generator = MembershipSampleGeneratorType::New() ; generator->SetInput(sample) ; generator->SetClassMask(mask) ; generator->SetNumberOfClasses(10) ; generator->GenerateData() ; MembershipSampleGeneratorType::OutputPointer membershipSample = generator->GetOutput() ; unsigned int numberOfClasses = membershipSample->GetNumberOfClasses() ; /* =================================================== */ std::cout << "Inducing the gaussian density function parameters and apriori probabilities..." << std::endl ; typedef ImageListSampleType::MeasurementVectorType MeasurementVectorType ; typedef stat::GaussianDensityFunction< MeasurementVectorType > DensityFunctionType ; typedef DensityFunctionType::Pointer DensityFunctionPointer ; std::vector< DensityFunctionPointer > densityFunctions ; densityFunctions.resize(numberOfClasses) ; typedef MembershipSampleGeneratorType::OutputType::ClassSampleType ClassSampleType ; typedef stat::MeanCalculator< ClassSampleType > MeanCalculatorType ; typedef stat::CovarianceCalculator< ClassSampleType > CovarianceCalculatorType ; MeanCalculatorType::Pointer meanCalculator = MeanCalculatorType::New() ; CovarianceCalculatorType::Pointer covarianceCalculator = CovarianceCalculatorType::New() ; vnl_vector< double > mean ; vnl_matrix< double > covariance ; typedef MaximumLikelihoodRatioDecisionRule DecisionRuleType ; DecisionRuleType::Pointer rule = DecisionRuleType::New() ; unsigned int sampleSize = 0 ; std::cout << "Inducing the gaussian density function parameters and apriori probabilities..." << std::endl ; std::cout << "number of classes = " << numberOfClasses << std::endl ; for (unsigned int i = 0 ; i < numberOfClasses ; i++) { std::cout << "gaussian [" << i << "]" << std::endl ; // add the class sample size to the decision rule // for the a priori probability calculation std::cout << " Sample size = " ; sampleSize = membershipSample->GetClassSampleSize(i) ; std::cout << sampleSize << std::endl ; rule->AddClassSampleSize(sampleSize) ; ClassSampleType::Pointer subSample = membershipSample->GetClassSample(i) ; meanCalculator->SetSample(subSample) ; meanCalculator->GenerateData() ; mean = meanCalculator->GetOutput() ; covarianceCalculator->SetSample(subSample) ; covarianceCalculator->SetMean(mean) ; covarianceCalculator->GenerateData() ; covariance = covarianceCalculator->GetOutput() ; densityFunctions[i] = DensityFunctionType::New() ; (densityFunctions[i])->SetMean(mean) ; (densityFunctions[i])->SetCovariance(covariance) ; std::cout << " mean = " << (densityFunctions[i])->GetMean() << std::endl ; std::cout << " covariance = " << std::endl ; (densityFunctions[i])->GetCovariance().print(std::cout) ; } /* =================================================== */ std::cout << "Classifying..." << std::endl ; typedef stat::TableLookupSampleClassifier< ImageListSampleType, DensityFunctionType, DecisionRuleType > ClassifierType ; ClassifierType::Pointer classifier = ClassifierType::New() ; classifier->SetSample(targetSample) ; for (unsigned int i = 0 ; i < numberOfClasses ; i++) { classifier->AddMembershipCalculator(densityFunctions[i]) ; } classifier->SetDecisionRule(rule) ; ImageListSampleType::MeasurementVectorType upper ; ImageListSampleType::MeasurementVectorType lower ; stat::FindSampleBound< ImageListSampleType >(targetSample, targetSample->Begin(), targetSample->End(), lower, upper) ; std::cout << "min = " << lower[0] << " max = " << upper[0] << std::endl ; classifier->SetLookupTableLowerBound(lower) ; classifier->SetLookupTableUpperBound(upper) ; classifier->GenerateData() ; ClassifierType::OutputPointer result = classifier->GetOutput() ; /* ===================================================== */ std::cout << "Creating a image with result class labels..." << std::endl ; typedef itk::ImageRegionIterator< ImageType > ImageIteratorType ; typedef itk::WriteMetaImage< ImageType > Writer ; Writer::Pointer writer = Writer::New() ; ImagePointer output = ImageType::New() ; output->SetBufferedRegion(target->GetLargestPossibleRegion()) ; output->SetLargestPossibleRegion(target->GetLargestPossibleRegion()) ; output->Allocate() ; ImageIteratorType i_iter(output, output->GetLargestPossibleRegion()) ; i_iter.GoToBegin() ; ClassifierType::OutputType::Iterator m_iter = result->Begin() ; while (!i_iter.IsAtEnd()) { i_iter.Set((ImageType::PixelType)m_iter.GetClassLabel()) ; ++i_iter ; ++m_iter ; } writer->SetInput(output) ; writer->SetFileName(outputFileName.c_str()) ; writer->GenerateData() ; return 0 ; } <commit_msg>ENH: As the TableLookupSampleClassifier's template arguments is reduced to one and the decision rule is derived from the DecisionRuleBase class, changes are made to reflect such changes.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: GaussianMinimumErrorClassifier.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "OptionList.h" #include "itkImage.h" #include "itkReadMetaImage.h" #include "itkWriteMetaImage.h" #include "itkImageRegionIterator.h" #include "vnl/vnl_matrix.h" #include "itkImageToListAdaptor.h" #include "itkSubsample.h" #include "itkMembershipSample.h" #include "itkMembershipSampleGenerator.h" #include "itkGaussianDensityFunction.h" #include "itkMeanCalculator.h" #include "itkCovarianceCalculator.h" #include "itkTableLookupSampleClassifier.h" #include "itkDecisionRuleBase.h" #include "MaximumLikelihoodRatioDecisionRule.h" #include "itkStatisticsAlgorithm.h" void print_usage() { std::cout << "GaussianMinimumErrorClassifier 1.0 (17. Dec. 2001)" << std::endl ; std::cout << "usage: GaussianMinimumErrorClassifier --training file" << std::endl ; std::cout << " --class-mask file" << std::endl ; std::cout << " --number-of-classes int" << std::endl ; std::cout << " --target file" << std::endl ; std::cout << " --output file" << std::endl ; std::cout << "" << std::endl ; std::cout << "--training file" << std::endl ; std::cout << " image file name with intesnity values [meta image format]" << std::endl ; std::cout << "--class-mask file" << std::endl ; std::cout << " image file name with class labels [meta image format]" << std::endl ; std::cout << "--number-of-classes int" << std::endl ; std::cout << " the number of classes in the training image." << std::endl ; std::cout << "--target file" << std::endl ; std::cout << " target image file name with intensity values [meta image format]" << std::endl ; std::cout << "--output file" << std::endl ; std::cout << " output image file name that will have the class labels for pixels" << std::endl ; std::cout << " in the target image file [meta image format]" << std::endl ; std::cout << "" << std::endl ; std::cout << "example: GaussianMinimumErrorClassifier --training train.mhd" << std::endl ; std::cout << " --class-mask class_mask.mhd" << std::endl ; std::cout << " --number-of-classes 10" << std::endl ; std::cout << " --target target.mhd" << std::endl ; std::cout << " --output output.mhd" << std::endl ; } int main(int argc, char* argv[]) { namespace stat = itk::Statistics ; if (argc <= 1) { print_usage() ; exit(0) ; } OptionList options(argc, argv) ; std::string trainingFileName ; std::string classMaskFileName ; std::string targetFileName ; std::string outputFileName ; int numberOfClasses ; try { // get image file options options.GetStringOption("training", &trainingFileName, true) ; // get image file options options.GetStringOption("class-mask", &classMaskFileName, true) ; // get image file options options.GetStringOption("target", &targetFileName, true) ; // get image file options options.GetStringOption("output", &outputFileName, true) ; // get the number of classes numberOfClasses = options.GetIntOption("number-of-classes", 10, true) ; } catch(OptionList::RequiredOptionMissing e) { std::cout << "Error: The '" << e.OptionTag << "' option is required but missing." << std::endl ; return 1 ; } typedef itk::Image< short, 3 > ImageType ; typedef ImageType::Pointer ImagePointer ; ImagePointer training ; ImagePointer classMask ; ImagePointer target ; std::cout << "Loading image(s)..." << std::endl ; // readMetaImageHeader(trainingFileName, trainingDimension, trainingSize) ; typedef itk::ReadMetaImage<ImageType> Reader ; Reader::Pointer reader = Reader::New() ; reader->SetFileName(trainingFileName.c_str()) ; reader->Update() ; training = reader->GetOutput() ; std::cout << "Training image loaded." << std::endl ; Reader::Pointer reader2 = Reader::New() ; reader2->SetFileName(classMaskFileName.c_str()) ; reader2->Update() ; classMask = reader2->GetOutput() ; std::cout << "Class mask loaded." << std::endl ; Reader::Pointer reader3 = Reader::New() ; reader3->SetFileName(targetFileName.c_str()) ; reader3->Update() ; target = reader3->GetOutput() ; std::cout << "Target image loaded." << std::endl ; /* ================================================== */ std::cout << "Importing the images to samples..." << std::endl ; typedef stat::ImageToListAdaptor< ImageType, stat::ScalarImageAccessor< ImageType > > ImageListSampleType; ImageListSampleType::Pointer sample = ImageListSampleType::New() ; ImageListSampleType::Pointer mask = ImageListSampleType::New() ; ImageListSampleType::Pointer targetSample = ImageListSampleType::New() ; sample->SetImage(training); mask->SetImage(classMask) ; targetSample->SetImage(target) ; /* ==================================================== */ std::cout << "Creating the membership sample for training.." << std::endl ; typedef stat::MembershipSampleGenerator< ImageListSampleType, ImageListSampleType > MembershipSampleGeneratorType ; MembershipSampleGeneratorType::Pointer generator = MembershipSampleGeneratorType::New() ; generator->SetInput(sample) ; generator->SetClassMask(mask) ; generator->SetNumberOfClasses(numberOfClasses) ; generator->GenerateData() ; MembershipSampleGeneratorType::OutputPointer membershipSample = generator->GetOutput() ; /* =================================================== */ std::cout << "Inducing the gaussian density function parameters and apriori probabilities..." << std::endl ; typedef ImageListSampleType::MeasurementVectorType MeasurementVectorType ; typedef stat::GaussianDensityFunction< MeasurementVectorType > DensityFunctionType ; typedef DensityFunctionType::Pointer DensityFunctionPointer ; std::vector< DensityFunctionPointer > densityFunctions ; densityFunctions.resize(numberOfClasses) ; typedef MembershipSampleGeneratorType::OutputType::ClassSampleType ClassSampleType ; typedef stat::MeanCalculator< ClassSampleType > MeanCalculatorType ; typedef stat::CovarianceCalculator< ClassSampleType > CovarianceCalculatorType ; MeanCalculatorType::Pointer meanCalculator = MeanCalculatorType::New() ; CovarianceCalculatorType::Pointer covarianceCalculator = CovarianceCalculatorType::New() ; vnl_vector< double > mean ; vnl_matrix< double > covariance ; typedef MaximumLikelihoodRatioDecisionRule DecisionRuleType ; DecisionRuleType::Pointer rule = DecisionRuleType::New() ; unsigned int sampleSize = 0 ; std::cout << "Inducing the gaussian density function parameters and apriori probabilities..." << std::endl ; for (unsigned int i = 0 ; i < numberOfClasses ; i++) { std::cout << "gaussian [" << i << "]" << std::endl ; // add the class sample size to the decision rule // for the a priori probability calculation std::cout << " Sample size = " ; sampleSize = membershipSample->GetClassSampleSize(i) ; std::cout << sampleSize << std::endl ; rule->AddClassSampleSize(sampleSize) ; ClassSampleType::Pointer subSample = membershipSample->GetClassSample(i) ; meanCalculator->SetSample(subSample) ; meanCalculator->GenerateData() ; mean = meanCalculator->GetOutput() ; covarianceCalculator->SetSample(subSample) ; covarianceCalculator->SetMean(mean) ; covarianceCalculator->GenerateData() ; covariance = covarianceCalculator->GetOutput() ; densityFunctions[i] = DensityFunctionType::New() ; (densityFunctions[i])->SetMean(mean) ; (densityFunctions[i])->SetCovariance(covariance) ; std::cout << " mean = " << (densityFunctions[i])->GetMean() << std::endl ; std::cout << " covariance = " << std::endl ; (densityFunctions[i])->GetCovariance().print(std::cout) ; } /* =================================================== */ std::cout << "Classifying..." << std::endl ; typedef stat::TableLookupSampleClassifier< ImageListSampleType > ClassifierType ; ClassifierType::Pointer classifier = ClassifierType::New() ; classifier->SetNumberOfClasses(numberOfClasses) ; classifier->SetSample(targetSample) ; for (unsigned int i = 0 ; i < numberOfClasses ; i++) { classifier->AddMembershipFunction(densityFunctions[i]) ; } classifier->SetDecisionRule((itk::DecisionRuleBase::Pointer)rule) ; ImageListSampleType::MeasurementVectorType upper ; ImageListSampleType::MeasurementVectorType lower ; stat::FindSampleBound< ImageListSampleType >(targetSample, targetSample->Begin(), targetSample->End(), lower, upper) ; std::cout << "min = " << lower[0] << " max = " << upper[0] << std::endl ; classifier->SetLookupTableLowerBound(lower) ; classifier->SetLookupTableUpperBound(upper) ; classifier->Update() ; ClassifierType::OutputPointer result = classifier->GetOutput() ; /* ===================================================== */ std::cout << "Creating a image with result class labels..." << std::endl ; typedef itk::ImageRegionIterator< ImageType > ImageIteratorType ; typedef itk::WriteMetaImage< ImageType > Writer ; Writer::Pointer writer = Writer::New() ; ImagePointer output = ImageType::New() ; output->SetBufferedRegion(target->GetLargestPossibleRegion()) ; output->SetLargestPossibleRegion(target->GetLargestPossibleRegion()) ; output->Allocate() ; ImageIteratorType i_iter(output, output->GetLargestPossibleRegion()) ; i_iter.GoToBegin() ; ClassifierType::OutputType::Iterator m_iter = result->Begin() ; while (!i_iter.IsAtEnd()) { i_iter.Set((ImageType::PixelType)m_iter.GetClassLabel()) ; ++i_iter ; ++m_iter ; } writer->SetInput(output) ; writer->SetFileName(outputFileName.c_str()) ; writer->GenerateData() ; return 0 ; } <|endoftext|>
<commit_before>#include "Model.h" #include "Effect.h" #include "main.h" Model::Model() : m_context(renderContext) { } Model::~Model() { } QSharedPointer<VideoNode> Model::addVideoNode(QString type) { // TODO QSharedPointer<VideoNode> videoNode(new Effect(m_context)); m_vertices.append(videoNode); emit videoNodeAdded(videoNode); return videoNode; } void Model::removeVideoNode(QSharedPointer<VideoNode> videoNode) { for (auto edge = m_edges.begin(); edge != m_edges.end(); edge++) { if (edge->fromVertex == videoNode || edge->toVertex == videoNode) { Edge edgeCopy = *edge; m_edges.erase(edge); emit edgeRemoved(edgeCopy); } } int count = m_vertices.removeAll(videoNode); if (count > 0) { emit videoNodeRemoved(videoNode); } } void Model::addEdge(QSharedPointer<VideoNode> fromVertex, QSharedPointer<VideoNode> toVertex, int toInput) { Q_ASSERT(fromVertex != nullptr); Q_ASSERT(toVertex != nullptr); Q_ASSERT(toInput >= 0); Q_ASSERT(m_vertices.contains(fromVertex)); Q_ASSERT(m_vertices.contains(toVertex)); for (auto edge = m_edges.begin(); edge != m_edges.end(); edge++) { if (edge->toVertex == toVertex && edge->toInput == toInput) { if (edge->fromVertex == fromVertex) return; Edge edgeCopy = *edge; m_edges.erase(edge); emit edgeRemoved(edgeCopy); } } Edge newEdge = { .fromVertex = fromVertex, .toVertex = toVertex, .toInput = toInput, }; m_edges.append(newEdge); emit edgeAdded(newEdge); } void Model::removeEdge(QSharedPointer<VideoNode> fromVertex, QSharedPointer<VideoNode> toVertex, int toInput) { Q_ASSERT(fromVertex != nullptr); Q_ASSERT(toVertex != nullptr); Q_ASSERT(toInput >= 0); Q_ASSERT(m_vertices.contains(fromVertex)); Q_ASSERT(m_vertices.contains(toVertex)); for (auto edge = m_edges.begin(); edge != m_edges.end(); edge++) { if (edge->fromVertex == fromVertex && edge->toVertex == toVertex && edge->toInput == toInput) { Edge edgeCopy = *edge; m_edges.erase(edge); emit edgeRemoved(edgeCopy); } } RenderContext *Model::context() { return m_context; } <commit_msg>fix a small merge bug<commit_after>#include "Model.h" #include "Effect.h" #include "main.h" Model::Model() : m_context(renderContext) { } Model::~Model() { } QSharedPointer<VideoNode> Model::addVideoNode(QString type) { // TODO QSharedPointer<VideoNode> videoNode(new Effect(m_context)); m_vertices.append(videoNode); emit videoNodeAdded(videoNode); return videoNode; } void Model::removeVideoNode(QSharedPointer<VideoNode> videoNode) { for (auto edge = m_edges.begin(); edge != m_edges.end(); edge++) { if (edge->fromVertex == videoNode || edge->toVertex == videoNode) { Edge edgeCopy = *edge; m_edges.erase(edge); emit edgeRemoved(edgeCopy); } } int count = m_vertices.removeAll(videoNode); if (count > 0) { emit videoNodeRemoved(videoNode); } } void Model::addEdge(QSharedPointer<VideoNode> fromVertex, QSharedPointer<VideoNode> toVertex, int toInput) { Q_ASSERT(fromVertex != nullptr); Q_ASSERT(toVertex != nullptr); Q_ASSERT(toInput >= 0); Q_ASSERT(m_vertices.contains(fromVertex)); Q_ASSERT(m_vertices.contains(toVertex)); for (auto edge = m_edges.begin(); edge != m_edges.end(); edge++) { if (edge->toVertex == toVertex && edge->toInput == toInput) { if (edge->fromVertex == fromVertex) return; Edge edgeCopy = *edge; m_edges.erase(edge); emit edgeRemoved(edgeCopy); } } Edge newEdge = { .fromVertex = fromVertex, .toVertex = toVertex, .toInput = toInput, }; m_edges.append(newEdge); emit edgeAdded(newEdge); } void Model::removeEdge(QSharedPointer<VideoNode> fromVertex, QSharedPointer<VideoNode> toVertex, int toInput) { Q_ASSERT(fromVertex != nullptr); Q_ASSERT(toVertex != nullptr); Q_ASSERT(toInput >= 0); Q_ASSERT(m_vertices.contains(fromVertex)); Q_ASSERT(m_vertices.contains(toVertex)); for (auto edge = m_edges.begin(); edge != m_edges.end(); edge++) { if (edge->fromVertex == fromVertex && edge->toVertex == toVertex && edge->toInput == toInput) { Edge edgeCopy = *edge; m_edges.erase(edge); emit edgeRemoved(edgeCopy); } } } RenderContext *Model::context() { return m_context; } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: GaussianMinimumErrorClassifier.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "OptionList.h" #include "itkImage.h" #include "itkReadMetaImage.h" #include "itkWriteMetaImage.h" #include "itkImageRegionIterator.h" #include "vnl/vnl_matrix.h" #include "itkImageToListAdaptor.h" #include "itkSubsample.h" #include "itkMembershipSample.h" #include "itkMembershipSampleGenerator.h" #include "itkGaussianDensityFunction.h" #include "itkMeanCalculator.h" #include "itkCovarianceCalculator.h" #include "itkTableLookupSampleClassifier.h" #include "itkDecisionRuleBase.h" #include "MaximumLikelihoodRatioDecisionRule.h" #include "itkStatisticsAlgorithm.h" void print_usage() { std::cout << "GaussianMinimumErrorClassifier 1.0 (17. Dec. 2001)" << std::endl ; std::cout << "usage: GaussianMinimumErrorClassifier --training file" << std::endl ; std::cout << " --class-mask file" << std::endl ; std::cout << " --number-of-classes int" << std::endl ; std::cout << " --target file" << std::endl ; std::cout << " --output file" << std::endl ; std::cout << "" << std::endl ; std::cout << "--training file" << std::endl ; std::cout << " image file name with intesnity values [meta image format]" << std::endl ; std::cout << "--class-mask file" << std::endl ; std::cout << " image file name with class labels [meta image format]" << std::endl ; std::cout << "--number-of-classes int" << std::endl ; std::cout << " the number of classes in the training image." << std::endl ; std::cout << "--target file" << std::endl ; std::cout << " target image file name with intensity values [meta image format]" << std::endl ; std::cout << "--output file" << std::endl ; std::cout << " output image file name that will have the class labels for pixels" << std::endl ; std::cout << " in the target image file [meta image format]" << std::endl ; std::cout << "" << std::endl ; std::cout << "example: GaussianMinimumErrorClassifier --training train.mhd" << std::endl ; std::cout << " --class-mask class_mask.mhd" << std::endl ; std::cout << " --number-of-classes 10" << std::endl ; std::cout << " --target target.mhd" << std::endl ; std::cout << " --output output.mhd" << std::endl ; } int main(int argc, char* argv[]) { namespace stat = itk::Statistics ; if (argc <= 1) { print_usage() ; exit(0) ; } OptionList options(argc, argv) ; std::string trainingFileName ; std::string classMaskFileName ; std::string targetFileName ; std::string outputFileName ; unsigned int numberOfClasses ; try { // get image file options options.GetStringOption("training", &trainingFileName, true) ; // get image file options options.GetStringOption("class-mask", &classMaskFileName, true) ; // get image file options options.GetStringOption("target", &targetFileName, true) ; // get image file options options.GetStringOption("output", &outputFileName, true) ; // get the number of classes numberOfClasses = options.GetIntOption("number-of-classes", 10, true) ; } catch(OptionList::RequiredOptionMissing e) { std::cout << "Error: The '" << e.OptionTag << "' option is required but missing." << std::endl ; return 1 ; } typedef itk::Image< short, 3 > ImageType ; typedef ImageType::Pointer ImagePointer ; ImagePointer training ; ImagePointer classMask ; ImagePointer target ; std::cout << "Loading image(s)..." << std::endl ; // readMetaImageHeader(trainingFileName, trainingDimension, trainingSize) ; typedef itk::ReadMetaImage<ImageType> Reader ; Reader::Pointer reader = Reader::New() ; reader->SetFileName(trainingFileName.c_str()) ; reader->Update() ; training = reader->GetOutput() ; std::cout << "Training image loaded." << std::endl ; Reader::Pointer reader2 = Reader::New() ; reader2->SetFileName(classMaskFileName.c_str()) ; reader2->Update() ; classMask = reader2->GetOutput() ; std::cout << "Class mask loaded." << std::endl ; Reader::Pointer reader3 = Reader::New() ; reader3->SetFileName(targetFileName.c_str()) ; reader3->Update() ; target = reader3->GetOutput() ; std::cout << "Target image loaded." << std::endl ; /* ================================================== */ std::cout << "Importing the images to samples..." << std::endl ; typedef stat::ImageToListAdaptor< ImageType, stat::ScalarImageAccessor< ImageType > > ImageListSampleType; ImageListSampleType::Pointer sample = ImageListSampleType::New() ; ImageListSampleType::Pointer mask = ImageListSampleType::New() ; ImageListSampleType::Pointer targetSample = ImageListSampleType::New() ; sample->SetImage(training); mask->SetImage(classMask) ; targetSample->SetImage(target) ; /* ==================================================== */ std::cout << "Creating the membership sample for training.." << std::endl ; typedef stat::MembershipSampleGenerator< ImageListSampleType, ImageListSampleType > MembershipSampleGeneratorType ; MembershipSampleGeneratorType::Pointer generator = MembershipSampleGeneratorType::New() ; generator->SetInput(sample) ; generator->SetClassMask(mask) ; generator->SetNumberOfClasses(numberOfClasses) ; generator->GenerateData() ; MembershipSampleGeneratorType::OutputPointer membershipSample = generator->GetOutput() ; /* =================================================== */ std::cout << "Inducing the gaussian density function parameters and apriori probabilities..." << std::endl ; typedef ImageListSampleType::MeasurementVectorType MeasurementVectorType ; typedef stat::GaussianDensityFunction< MeasurementVectorType > DensityFunctionType ; typedef DensityFunctionType::Pointer DensityFunctionPointer ; std::vector< DensityFunctionPointer > densityFunctions ; densityFunctions.resize(numberOfClasses) ; typedef MembershipSampleGeneratorType::OutputType::ClassSampleType ClassSampleType ; typedef stat::MeanCalculator< ClassSampleType > MeanCalculatorType ; typedef stat::CovarianceCalculator< ClassSampleType > CovarianceCalculatorType ; MeanCalculatorType::Pointer meanCalculator = MeanCalculatorType::New() ; CovarianceCalculatorType::Pointer covarianceCalculator = CovarianceCalculatorType::New() ; vnl_vector< double > mean ; vnl_matrix< double > covariance ; typedef MaximumLikelihoodRatioDecisionRule DecisionRuleType ; DecisionRuleType::Pointer rule = DecisionRuleType::New() ; unsigned int sampleSize = 0 ; std::cout << "Inducing the gaussian density function parameters and apriori probabilities..." << std::endl ; for (unsigned int i = 0 ; i < numberOfClasses ; i++) { std::cout << "gaussian [" << i << "]" << std::endl ; // add the class sample size to the decision rule // for the a priori probability calculation std::cout << " Sample size = " ; sampleSize = membershipSample->GetClassSampleSize(i) ; std::cout << sampleSize << std::endl ; rule->AddClassSampleSize(sampleSize) ; ClassSampleType::Pointer subSample = membershipSample->GetClassSample(i) ; meanCalculator->SetSample(subSample) ; meanCalculator->GenerateData() ; mean = meanCalculator->GetOutput() ; covarianceCalculator->SetSample(subSample) ; covarianceCalculator->SetMean(mean) ; covarianceCalculator->GenerateData() ; covariance = covarianceCalculator->GetOutput() ; densityFunctions[i] = DensityFunctionType::New() ; (densityFunctions[i])->SetMean(mean) ; (densityFunctions[i])->SetCovariance(covariance) ; std::cout << " mean = " << (densityFunctions[i])->GetMean() << std::endl ; std::cout << " covariance = " << std::endl ; (densityFunctions[i])->GetCovariance().print(std::cout) ; } /* =================================================== */ std::cout << "Classifying..." << std::endl ; typedef stat::TableLookupSampleClassifier< ImageListSampleType > ClassifierType ; ClassifierType::Pointer classifier = ClassifierType::New() ; classifier->SetNumberOfClasses(numberOfClasses) ; classifier->SetSample(targetSample) ; for (unsigned int i = 0 ; i < numberOfClasses ; i++) { classifier->AddMembershipFunction(densityFunctions[i]) ; } classifier->SetDecisionRule((itk::DecisionRuleBase::Pointer)rule) ; ImageListSampleType::MeasurementVectorType upper ; ImageListSampleType::MeasurementVectorType lower ; stat::FindSampleBound< ImageListSampleType >(targetSample, targetSample->Begin(), targetSample->End(), lower, upper) ; std::cout << "min = " << lower[0] << " max = " << upper[0] << std::endl ; classifier->SetLookupTableLowerBound(lower) ; classifier->SetLookupTableUpperBound(upper) ; classifier->Update() ; ClassifierType::OutputPointer result = classifier->GetOutput() ; /* ===================================================== */ std::cout << "Creating a image with result class labels..." << std::endl ; typedef itk::ImageRegionIterator< ImageType > ImageIteratorType ; typedef itk::WriteMetaImage< ImageType > Writer ; Writer::Pointer writer = Writer::New() ; ImagePointer output = ImageType::New() ; output->SetBufferedRegion(target->GetLargestPossibleRegion()) ; output->SetLargestPossibleRegion(target->GetLargestPossibleRegion()) ; output->Allocate() ; ImageIteratorType i_iter(output, output->GetLargestPossibleRegion()) ; i_iter.GoToBegin() ; ClassifierType::OutputType::Iterator m_iter = result->Begin() ; while (!i_iter.IsAtEnd()) { i_iter.Set((ImageType::PixelType)m_iter.GetClassLabel()) ; ++i_iter ; ++m_iter ; } writer->SetInput(output) ; writer->SetFileName(outputFileName.c_str()) ; writer->GenerateData() ; return 0 ; } <commit_msg>ENH: MeanCalculator and CovarianceCalculator need Update() call instead of GenerateData() call to generate data.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: GaussianMinimumErrorClassifier.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "OptionList.h" #include "itkImage.h" #include "itkReadMetaImage.h" #include "itkWriteMetaImage.h" #include "itkImageRegionIterator.h" #include "vnl/vnl_matrix.h" #include "itkImageToListAdaptor.h" #include "itkSubsample.h" #include "itkMembershipSample.h" #include "itkMembershipSampleGenerator.h" #include "itkGaussianDensityFunction.h" #include "itkMeanCalculator.h" #include "itkCovarianceCalculator.h" #include "itkTableLookupSampleClassifier.h" #include "itkDecisionRuleBase.h" #include "MaximumLikelihoodRatioDecisionRule.h" #include "itkStatisticsAlgorithm.h" void print_usage() { std::cout << "GaussianMinimumErrorClassifier 1.0 (17. Dec. 2001)" << std::endl ; std::cout << "usage: GaussianMinimumErrorClassifier --training file" << std::endl ; std::cout << " --class-mask file" << std::endl ; std::cout << " --number-of-classes int" << std::endl ; std::cout << " --target file" << std::endl ; std::cout << " --output file" << std::endl ; std::cout << "" << std::endl ; std::cout << "--training file" << std::endl ; std::cout << " image file name with intesnity values [meta image format]" << std::endl ; std::cout << "--class-mask file" << std::endl ; std::cout << " image file name with class labels [meta image format]" << std::endl ; std::cout << "--number-of-classes int" << std::endl ; std::cout << " the number of classes in the training image." << std::endl ; std::cout << "--target file" << std::endl ; std::cout << " target image file name with intensity values [meta image format]" << std::endl ; std::cout << "--output file" << std::endl ; std::cout << " output image file name that will have the class labels for pixels" << std::endl ; std::cout << " in the target image file [meta image format]" << std::endl ; std::cout << "" << std::endl ; std::cout << "example: GaussianMinimumErrorClassifier --training train.mhd" << std::endl ; std::cout << " --class-mask class_mask.mhd" << std::endl ; std::cout << " --number-of-classes 10" << std::endl ; std::cout << " --target target.mhd" << std::endl ; std::cout << " --output output.mhd" << std::endl ; } int main(int argc, char* argv[]) { namespace stat = itk::Statistics ; if (argc <= 1) { print_usage() ; exit(0) ; } OptionList options(argc, argv) ; std::string trainingFileName ; std::string classMaskFileName ; std::string targetFileName ; std::string outputFileName ; unsigned int numberOfClasses ; try { // get image file options options.GetStringOption("training", &trainingFileName, true) ; // get image file options options.GetStringOption("class-mask", &classMaskFileName, true) ; // get image file options options.GetStringOption("target", &targetFileName, true) ; // get image file options options.GetStringOption("output", &outputFileName, true) ; // get the number of classes numberOfClasses = options.GetIntOption("number-of-classes", 10, true) ; } catch(OptionList::RequiredOptionMissing e) { std::cout << "Error: The '" << e.OptionTag << "' option is required but missing." << std::endl ; return 1 ; } typedef itk::Image< short, 3 > ImageType ; typedef ImageType::Pointer ImagePointer ; ImagePointer training ; ImagePointer classMask ; ImagePointer target ; std::cout << "Loading image(s)..." << std::endl ; // readMetaImageHeader(trainingFileName, trainingDimension, trainingSize) ; typedef itk::ReadMetaImage<ImageType> Reader ; Reader::Pointer reader = Reader::New() ; reader->SetFileName(trainingFileName.c_str()) ; reader->Update() ; training = reader->GetOutput() ; std::cout << "Training image loaded." << std::endl ; Reader::Pointer reader2 = Reader::New() ; reader2->SetFileName(classMaskFileName.c_str()) ; reader2->Update() ; classMask = reader2->GetOutput() ; std::cout << "Class mask loaded." << std::endl ; Reader::Pointer reader3 = Reader::New() ; reader3->SetFileName(targetFileName.c_str()) ; reader3->Update() ; target = reader3->GetOutput() ; std::cout << "Target image loaded." << std::endl ; /* ================================================== */ std::cout << "Importing the images to samples..." << std::endl ; typedef stat::ImageToListAdaptor< ImageType, stat::ScalarImageAccessor< ImageType > > ImageListSampleType; ImageListSampleType::Pointer sample = ImageListSampleType::New() ; ImageListSampleType::Pointer mask = ImageListSampleType::New() ; ImageListSampleType::Pointer targetSample = ImageListSampleType::New() ; sample->SetImage(training); mask->SetImage(classMask) ; targetSample->SetImage(target) ; /* ==================================================== */ std::cout << "Creating the membership sample for training.." << std::endl ; typedef stat::MembershipSampleGenerator< ImageListSampleType, ImageListSampleType > MembershipSampleGeneratorType ; MembershipSampleGeneratorType::Pointer generator = MembershipSampleGeneratorType::New() ; generator->SetInput(sample) ; generator->SetClassMask(mask) ; generator->SetNumberOfClasses(numberOfClasses) ; generator->GenerateData() ; MembershipSampleGeneratorType::OutputPointer membershipSample = generator->GetOutput() ; /* =================================================== */ std::cout << "Inducing the gaussian density function parameters and apriori probabilities..." << std::endl ; typedef ImageListSampleType::MeasurementVectorType MeasurementVectorType ; typedef stat::GaussianDensityFunction< MeasurementVectorType > DensityFunctionType ; typedef DensityFunctionType::Pointer DensityFunctionPointer ; std::vector< DensityFunctionPointer > densityFunctions ; densityFunctions.resize(numberOfClasses) ; typedef MembershipSampleGeneratorType::OutputType::ClassSampleType ClassSampleType ; typedef stat::MeanCalculator< ClassSampleType > MeanCalculatorType ; typedef stat::CovarianceCalculator< ClassSampleType > CovarianceCalculatorType ; MeanCalculatorType::Pointer meanCalculator = MeanCalculatorType::New() ; CovarianceCalculatorType::Pointer covarianceCalculator = CovarianceCalculatorType::New() ; vnl_vector< double > mean ; vnl_matrix< double > covariance ; typedef MaximumLikelihoodRatioDecisionRule DecisionRuleType ; DecisionRuleType::Pointer rule = DecisionRuleType::New() ; unsigned int sampleSize = 0 ; std::cout << "Inducing the gaussian density function parameters and apriori probabilities..." << std::endl ; for (unsigned int i = 0 ; i < numberOfClasses ; i++) { std::cout << "gaussian [" << i << "]" << std::endl ; // add the class sample size to the decision rule // for the a priori probability calculation std::cout << " Sample size = " ; sampleSize = membershipSample->GetClassSampleSize(i) ; std::cout << sampleSize << std::endl ; rule->AddClassSampleSize(sampleSize) ; ClassSampleType::Pointer subSample = membershipSample->GetClassSample(i) ; meanCalculator->SetSample(subSample) ; meanCalculator->Update() ; mean = meanCalculator->GetOutput() ; covarianceCalculator->SetSample(subSample) ; covarianceCalculator->SetMean(mean) ; covarianceCalculator->Update() ; covariance = covarianceCalculator->GetOutput() ; densityFunctions[i] = DensityFunctionType::New() ; (densityFunctions[i])->SetMean(mean) ; (densityFunctions[i])->SetCovariance(covariance) ; std::cout << " mean = " << (densityFunctions[i])->GetMean() << std::endl ; std::cout << " covariance = " << std::endl ; (densityFunctions[i])->GetCovariance().print(std::cout) ; } /* =================================================== */ std::cout << "Classifying..." << std::endl ; typedef stat::TableLookupSampleClassifier< ImageListSampleType > ClassifierType ; ClassifierType::Pointer classifier = ClassifierType::New() ; classifier->SetNumberOfClasses(numberOfClasses) ; classifier->SetSample(targetSample) ; for (unsigned int i = 0 ; i < numberOfClasses ; i++) { classifier->AddMembershipFunction(densityFunctions[i]) ; } classifier->SetDecisionRule((itk::DecisionRuleBase::Pointer)rule) ; ImageListSampleType::MeasurementVectorType upper ; ImageListSampleType::MeasurementVectorType lower ; stat::FindSampleBound< ImageListSampleType >(targetSample, targetSample->Begin(), targetSample->End(), lower, upper) ; std::cout << "min = " << lower[0] << " max = " << upper[0] << std::endl ; classifier->SetLookupTableLowerBound(lower) ; classifier->SetLookupTableUpperBound(upper) ; classifier->Update() ; ClassifierType::OutputPointer result = classifier->GetOutput() ; /* ===================================================== */ std::cout << "Creating a image with result class labels..." << std::endl ; typedef itk::ImageRegionIterator< ImageType > ImageIteratorType ; typedef itk::WriteMetaImage< ImageType > Writer ; Writer::Pointer writer = Writer::New() ; ImagePointer output = ImageType::New() ; output->SetBufferedRegion(target->GetLargestPossibleRegion()) ; output->SetLargestPossibleRegion(target->GetLargestPossibleRegion()) ; output->Allocate() ; ImageIteratorType i_iter(output, output->GetLargestPossibleRegion()) ; i_iter.GoToBegin() ; ClassifierType::OutputType::Iterator m_iter = result->Begin() ; while (!i_iter.IsAtEnd()) { i_iter.Set((ImageType::PixelType)m_iter.GetClassLabel()) ; ++i_iter ; ++m_iter ; } writer->SetInput(output) ; writer->SetFileName(outputFileName.c_str()) ; writer->GenerateData() ; return 0 ; } <|endoftext|>
<commit_before>//________________________________________________________________________ void demoInteractive() { //____________________________________________// AliTagAnalysis *TagAna = new AliTagAnalysis(); AliRunTagCuts *RunCuts = new AliRunTagCuts(); AliEventTagCuts *EvCuts = new AliEventTagCuts(); EvCuts->SetMultiplicityRange(11,12); //grid tags TAlienCollection* coll = TAlienCollection::Open("tag.xml"); TGridResult* TagResult = coll->GetGridResult(""); TagAna->ChainGridTags(TagResult); TChain* chain = 0x0; chain = TagAna->QueryTags(RunCuts,EvCuts); //____________________________________________// // Make the analysis manager AliAnalysisManager *mgr = new AliAnalysisManager("TestManager"); //____________________________________________// // 1st Pt task AliAnalysisTaskPt *task1 = new AliAnalysisTaskPt("TaskPt"); mgr->AddTask(task1); // Create containers for input/output AliAnalysisDataContainer *cinput1 = mgr->CreateContainer("cchain1",TChain::Class(),AliAnalysisManager::kInputContainer); AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("chist1", TH1::Class(),AliAnalysisManager::kOutputContainer,"Pt.ESD.root"); //____________________________________________// mgr->ConnectInput(task1,0,cinput1); mgr->ConnectOutput(task1,0,coutput1); cinput1->SetData(chain); if (mgr->InitAnalysis()) { mgr->PrintStatus(); mgr->StartAnalysis("local",chain); } } <commit_msg>Adding the 0,0 option in the TGridResult<commit_after>//________________________________________________________________________ void demoInteractive() { //____________________________________________// AliTagAnalysis *TagAna = new AliTagAnalysis(); AliRunTagCuts *RunCuts = new AliRunTagCuts(); AliEventTagCuts *EvCuts = new AliEventTagCuts(); EvCuts->SetMultiplicityRange(11,12); //grid tags TAlienCollection* coll = TAlienCollection::Open("tag.xml"); TGridResult* TagResult = coll->GetGridResult("",0,0); TagAna->ChainGridTags(TagResult); TChain* chain = 0x0; chain = TagAna->QueryTags(RunCuts,EvCuts); //____________________________________________// // Make the analysis manager AliAnalysisManager *mgr = new AliAnalysisManager("TestManager"); //____________________________________________// // 1st Pt task AliAnalysisTaskPt *task1 = new AliAnalysisTaskPt("TaskPt"); mgr->AddTask(task1); // Create containers for input/output AliAnalysisDataContainer *cinput1 = mgr->CreateContainer("cchain1",TChain::Class(),AliAnalysisManager::kInputContainer); AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("chist1", TH1::Class(),AliAnalysisManager::kOutputContainer,"Pt.ESD.root"); //____________________________________________// mgr->ConnectInput(task1,0,cinput1); mgr->ConnectOutput(task1,0,coutput1); cinput1->SetData(chain); if (mgr->InitAnalysis()) { mgr->PrintStatus(); mgr->StartAnalysis("local",chain); } } <|endoftext|>
<commit_before>// RUN: %clangxx -fsanitize=integer -g0 %s -o %t // Fails without any suppression. // RUN: %env_ubsan_opts=halt_on_error=1 not %run %t 2>&1 | FileCheck %s // RUN: echo "signed-integer-overflow:%t" > %t.wrong-supp // RUN: %env_ubsan_opts=halt_on_error=1:suppressions='"%t.wrong-supp"' not %run %t 2>&1 | FileCheck %s // RUN: echo "unsigned-integer-overflow:do_overflow" > %t.func-supp // RUN: %env_ubsan_opts=halt_on_error=1:suppressions='"%t.func-supp"' %run %t // RUN: echo "unsigned-integer-overflow:%t" > %t.module-supp // RUN: %env_ubsan_opts=halt_on_error=1:suppressions='"%t.module-supp"' %run %t // Note: file-level suppressions should work even without debug info. // RUN: echo "unsigned-integer-overflow:%s" > %t.file-supp // RUN: %env_ubsan_opts=halt_on_error=1:suppressions='"%t.file-supp"' %run %t // Suppressions don't work for unrecoverable kinds. // RUN: %clangxx -fsanitize=integer -fno-sanitize-recover=integer %s -o %t-norecover // RUN: %env_ubsan_opts=halt_on_error=1:suppressions='"%t.module-supp"' not %run %t-norecover 2>&1 | FileCheck %s #include <stdint.h> extern "C" void do_overflow() { (void)(uint64_t(10000000000000000000ull) + uint64_t(9000000000000000000ull)); // CHECK: runtime error: unsigned integer overflow } int main() { do_overflow(); return 0; } <commit_msg>Re-disable suppressions.cpp on Windows.<commit_after>// XFAIL: win32 // This test fails on Windows if the environment was set up by SetEnv.cmd from // the Windows SDK. If it's set up via vcvarsall.bat, it passes. // FIXME: Figure out how to make this reliably pass on Windows. // test/asan/TestCases/suppressions-interceptor.cc will need the same fix. // RUN: %clangxx -fsanitize=integer -g0 %s -o %t // Fails without any suppression. // RUN: %env_ubsan_opts=halt_on_error=1 not %run %t 2>&1 | FileCheck %s // RUN: echo "signed-integer-overflow:%t" > %t.wrong-supp // RUN: %env_ubsan_opts=halt_on_error=1:suppressions='"%t.wrong-supp"' not %run %t 2>&1 | FileCheck %s // RUN: echo "unsigned-integer-overflow:do_overflow" > %t.func-supp // RUN: %env_ubsan_opts=halt_on_error=1:suppressions='"%t.func-supp"' %run %t // RUN: echo "unsigned-integer-overflow:%t" > %t.module-supp // RUN: %env_ubsan_opts=halt_on_error=1:suppressions='"%t.module-supp"' %run %t // Note: file-level suppressions should work even without debug info. // RUN: echo "unsigned-integer-overflow:%s" > %t.file-supp // RUN: %env_ubsan_opts=halt_on_error=1:suppressions='"%t.file-supp"' %run %t // Suppressions don't work for unrecoverable kinds. // RUN: %clangxx -fsanitize=integer -fno-sanitize-recover=integer %s -o %t-norecover // RUN: %env_ubsan_opts=halt_on_error=1:suppressions='"%t.module-supp"' not %run %t-norecover 2>&1 | FileCheck %s #include <stdint.h> extern "C" void do_overflow() { (void)(uint64_t(10000000000000000000ull) + uint64_t(9000000000000000000ull)); // CHECK: runtime error: unsigned integer overflow } int main() { do_overflow(); return 0; } <|endoftext|>
<commit_before>AliAnalysisTaskSECharmFraction* AddTaskSECharmFraction(TString fileout="d0D0.root",Int_t *switchMC=0x0,Int_t readmc=0,Bool_t usepid=kTRUE,Bool_t likesign=kFALSE,TString cutfile="D0toKpiCharmFractCuts.root",TString containerprefix="c",Int_t ppPbPb=0,Int_t analysLevel=2, Float_t minC=0., Float_t maxC=7.5,Float_t minCloose=20., Float_t maxCloose=50.,Bool_t useWeight=kFALSE,Bool_t fillTree=kFALSE,Bool_t checkBitD0=kTRUE) { // // Configuration macro for the task to analyze the fraction of prompt charm // using the D0 impact parameter // [email protected] // //========================================================================== //######## !!! THE SWITCH FOR MC ANALYSIS IS NOT IMPLEMENTED YET!!! ########## if(switchMC!=0x0){ switchMC[0]=1; switchMC[1]=1; switchMC[2]=1; switchMC[3]=1; switchMC[4]=1; } Int_t last=0; AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskCharmFraction", "No analysis manager to connect to."); return NULL; } TString str,containername; if(fileout.Contains("standard"))if(fileout.Contains("standard")){ TString  fileouttmp = fileout; fileout=AliAnalysisManager::GetCommonFileName(); fileout+=":PWG3_D2H_"; fileout+="d0D0"; fileout+=fileouttmp; if(containerprefix!="c")fileout+=containerprefix; str="d0D0"; } else if(fileout=="standardUp"){ fileout=AliAnalysisManager::GetCommonFileName(); fileout+=":PWG3_D2H_Up_"; fileout+="d0D0"; if(containerprefix!="c")fileout+=containerprefix; str="d0D0"; } else { str=fileout; str.ReplaceAll(".root",""); } str.Prepend("_"); AliAnalysisTaskSECharmFraction *hfTask; if(!gSystem->AccessPathName(cutfile.Data(),kFileExists)){ TFile *f=TFile::Open(cutfile.Data()); AliRDHFCutsD0toKpi *cutTight= (AliRDHFCutsD0toKpi*)f->Get("D0toKpiCutsStandard"); cutTight->PrintAll(); AliRDHFCutsD0toKpi *cutLoose= (AliRDHFCutsD0toKpi*)f->Get("D0toKpiCutsLoose"); cutLoose->PrintAll(); hfTask = new AliAnalysisTaskSECharmFraction("AliAnalysisTaskSECharmFraction",cutTight,cutLoose); } else { //hfTask = new AliAnalysisTaskSECharmFraction("AliAnalysisTaskSECharmFraction"); AliRDHFCutsD0toKpi *cutTight=new AliRDHFCutsD0toKpi("D0toKpiCutsStandard"); AliRDHFCutsD0toKpi *cutLoose=new AliRDHFCutsD0toKpi("D0toKpiCutsLoose"); if(ppPbPb==1){ printf("USING STANDARD CUTS 2011 \n"); cutTight->SetStandardCutsPbPb2011(); cutTight->SetMinCentrality(minC); cutTight->SetMaxCentrality(maxC); cutTight->SetMinPtCandidate(0.); cutLoose->SetStandardCutsPbPb2011(); cutLoose->SetMinCentrality(minCloose); cutLoose->SetMaxCentrality(maxCloose); cutLoose->SetMinPtCandidate(0.); } else { cutTight->SetStandardCutsPP2010(); cutLoose->SetStandardCutsPP2010(); } hfTask = new AliAnalysisTaskSECharmFraction("AliAnalysisTaskSECharmFraction",cutTight,cutLoose); cutLoose->PrintAll(); } if(ppPbPb==1){// Switch Off recalctulation of primary vertex w/o candidate's daughters // a protection that must be kept here to be sure //that this is done also if the cut objects are provided by outside Printf("AddTaskSECharmFraction: Switch Off recalculation of primary vertex w/o candidate's daughters (PbPb analysis) \n"); AliRDHFCutsD0toKpi *cloose=hfTask->GetLooseCut(); AliRDHFCutsD0toKpi *ctight=hfTask->GetTightCut(); cloose->SetRemoveDaughtersFromPrim(kFALSE); ctight->SetRemoveDaughtersFromPrim(kFALSE); if(analysLevel<2){ printf("Cannot activate the filling of all the histograms for PbPb analysis \n changing analysis level to 2 \n"); analysLevel=2; } // Activate Default PID for proton rejection (TEMPORARY) // cloose->SetUseDefaultPID(kTRUE); // ctight->SetUseDefaultPID(kTRUE); } if(readmc>0)hfTask->SetReadMC(kTRUE); if(readmc==2){ hfTask->SetRejecCandidateMCUpgrade(kTRUE); hfTask->SetSkipEventSelection(kTRUE); hfTask->SetMaxZvtxForSkipEventSelection(10.); } hfTask->SetNMaxTrForVtx(2); hfTask->SetAnalyzeLikeSign(likesign); hfTask->SetUsePID(usepid); hfTask->SetStandardMassSelection(); hfTask->SetAnalysisLevel(analysLevel); hfTask->SetFillImpParTree(fillTree); hfTask->SetCheckBitD0flag(checkBitD0); if(readmc&&useWeight)hfTask->SetPtWeightsFromDataPbPb276overLHC12a17a(); // hfTask->SignalInvMassCut(0.27); /* ############### HERE THE POSSIBILITY TO SWITCH ON/OFF THE TLISTS AND MC SELECTION WILL BE SET #########à hfTask->SetUseCuts(setD0usecuts); hfTask->SetCheckMC(setcheckMC); hfTask->SetCheckMC_D0(setcheckMC_D0); hfTask->SetCheckMC_2prongs(setcheckMC_2prongs); hfTask->SetCheckMC_prompt(setcheckMC_prompt); hfTask->SetCheckMC_fromB(setcheckMC_fromB); hfTask->SetCheckMC_fromDstar(setSkipD0star); hfTask->SetStudyPureBackground(setStudyPureBack);*/ // hfTask->SetSideBands(0); // hfTask->SetDebugLevel(2); mgr->AddTask(hfTask); // Create containers for input/output AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer(); //mgr->CreateContainer("cinput",TChain::Class(),AliAnalysisManager::kInputContainer); mgr->ConnectInput(hfTask,0,cinput); //Now container for general properties histograms containername="outputNentries"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *coutputNentries = mgr->CreateContainer(containername.Data(),TH1F::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,1,coutputNentries); containername="outputSignalType"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *coutputSignalType = mgr->CreateContainer(containername.Data(),TH1F::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,2,coutputSignalType); containername="outputSignalType_LsCuts"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *coutputSignalType_LsCuts = mgr->CreateContainer(containername.Data(),TH1F::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,3,coutputSignalType_LsCuts); containername="outputSignalType_TghCuts"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *coutputSignalType_TghCuts = mgr->CreateContainer(containername.Data(),TH1F::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,4,coutputSignalType_TghCuts); containername="outputNormalizationCounter"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *coutputNormCounter = mgr ->CreateContainer(containername.Data(), AliNormalizationCounter::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask, 5, coutputNormCounter); //Now Container for MC TList containername="listMCproperties"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *clistMCprop = mgr->CreateContainer(containername.Data(),TList::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,6,clistMCprop); // Now container for TLists last=7; //########## NO CUTS TLISTS CONTAINER ##############à containername="listNCsign"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *clistNCsign = mgr->CreateContainer(containername.Data(),TList::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,last,clistNCsign); last++; containername="listNCback"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *clistNCback = mgr->CreateContainer(containername.Data(),TList::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,last,clistNCback); last++; containername="listNCfromB"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *clistNCfromB = mgr->CreateContainer(containername.Data(),TList::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,last,clistNCfromB); last++; containername="listNCfromDstar"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *clistNCfromDstar = mgr->CreateContainer(containername.Data(),TList::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,last,clistNCfromDstar); last++; containername="listNCother"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *clistNCother = mgr->CreateContainer(containername.Data(),TList::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,last,clistNCother); last++; //######### LOOSE CUTS TLISTS CONTAINER ############# containername="listLSCsign"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *clistLSCsign = mgr->CreateContainer(containername.Data(),TList::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,last,clistLSCsign); last++; containername="listLSCback"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *clistLSCback = mgr->CreateContainer(containername.Data(),TList::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,last,clistLSCback); last++; containername="listLSCfromB"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *clistLSCfromB = mgr->CreateContainer(containername.Data(),TList::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,last,clistLSCfromB); last++; containername="listLSCfromDstar"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *clistLSCfromDstar = mgr->CreateContainer(containername.Data(),TList::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,last,clistLSCfromDstar); last++; containername="listLSCother"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *clistLSCother = mgr->CreateContainer(containername.Data(),TList::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,last,clistLSCother); last++; //######### TIGHT CUTS TLISTS CONTAINER ############# containername="listTGHCsign"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *clistTGHCsign = mgr->CreateContainer(containername.Data(),TList::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,last,clistTGHCsign); last++; containername="listTGHCback"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *clistTGHCback = mgr->CreateContainer(containername.Data(),TList::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,last,clistTGHCback); last++; containername="listTGHCfromB"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *clistTGHCfromB = mgr->CreateContainer(containername.Data(),TList::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,last,clistTGHCfromB); last++; containername="listTGHCfromDstar"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *clistTGHCfromDstar = mgr->CreateContainer(containername.Data(),TList::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,last,clistTGHCfromDstar); last++; containername="listTGHCother"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *clistTGHCother = mgr->CreateContainer(containername.Data(),TList::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,last,clistTGHCother); last++; // Container for Cuts Objects containername="cutsObjectTight"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *cCutsObjectTight = mgr->CreateContainer(containername,AliRDHFCutsD0toKpi::Class(),AliAnalysisManager::kOutputContainer,fileout.Data()); //cuts mgr->ConnectOutput(hfTask,last,cCutsObjectTight); last++; containername="cutsObjectLoose"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *cCutsObjectLoose = mgr->CreateContainer(containername,AliRDHFCutsD0toKpi::Class(),AliAnalysisManager::kOutputContainer,fileout.Data()); //cuts mgr->ConnectOutput(hfTask,last,cCutsObjectLoose); return hfTask; } <commit_msg>fix typo in AddTaskSECharmFraction.C (Cristina)<commit_after>AliAnalysisTaskSECharmFraction* AddTaskSECharmFraction(TString fileout="d0D0.root",Int_t *switchMC=0x0,Int_t readmc=0,Bool_t usepid=kTRUE,Bool_t likesign=kFALSE,TString cutfile="D0toKpiCharmFractCuts.root",TString containerprefix="c",Int_t ppPbPb=0,Int_t analysLevel=2, Float_t minC=0., Float_t maxC=7.5,Float_t minCloose=20., Float_t maxCloose=50.,Bool_t useWeight=kFALSE,Bool_t fillTree=kFALSE,Bool_t checkBitD0=kTRUE) { // // Configuration macro for the task to analyze the fraction of prompt charm // using the D0 impact parameter // [email protected] // //========================================================================== //######## !!! THE SWITCH FOR MC ANALYSIS IS NOT IMPLEMENTED YET!!! ########## if(switchMC!=0x0){ switchMC[0]=1; switchMC[1]=1; switchMC[2]=1; switchMC[3]=1; switchMC[4]=1; } Int_t last=0; AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskCharmFraction", "No analysis manager to connect to."); return NULL; } TString str,containername; if(fileout.Contains("standard")){ TString  fileouttmp = fileout; fileout=AliAnalysisManager::GetCommonFileName(); fileout+=":PWG3_D2H_"; fileout+="d0D0"; fileout+=fileouttmp; if(containerprefix!="c")fileout+=containerprefix; str="d0D0"; } else if(fileout=="standardUp"){ fileout=AliAnalysisManager::GetCommonFileName(); fileout+=":PWG3_D2H_Up_"; fileout+="d0D0"; if(containerprefix!="c")fileout+=containerprefix; str="d0D0"; } else { str=fileout; str.ReplaceAll(".root",""); } str.Prepend("_"); AliAnalysisTaskSECharmFraction *hfTask; if(!gSystem->AccessPathName(cutfile.Data(),kFileExists)){ TFile *f=TFile::Open(cutfile.Data()); AliRDHFCutsD0toKpi *cutTight= (AliRDHFCutsD0toKpi*)f->Get("D0toKpiCutsStandard"); cutTight->PrintAll(); AliRDHFCutsD0toKpi *cutLoose= (AliRDHFCutsD0toKpi*)f->Get("D0toKpiCutsLoose"); cutLoose->PrintAll(); hfTask = new AliAnalysisTaskSECharmFraction("AliAnalysisTaskSECharmFraction",cutTight,cutLoose); } else { //hfTask = new AliAnalysisTaskSECharmFraction("AliAnalysisTaskSECharmFraction"); AliRDHFCutsD0toKpi *cutTight=new AliRDHFCutsD0toKpi("D0toKpiCutsStandard"); AliRDHFCutsD0toKpi *cutLoose=new AliRDHFCutsD0toKpi("D0toKpiCutsLoose"); if(ppPbPb==1){ printf("USING STANDARD CUTS 2011 \n"); cutTight->SetStandardCutsPbPb2011(); cutTight->SetMinCentrality(minC); cutTight->SetMaxCentrality(maxC); cutTight->SetMinPtCandidate(0.); cutLoose->SetStandardCutsPbPb2011(); cutLoose->SetMinCentrality(minCloose); cutLoose->SetMaxCentrality(maxCloose); cutLoose->SetMinPtCandidate(0.); } else { cutTight->SetStandardCutsPP2010(); cutLoose->SetStandardCutsPP2010(); } hfTask = new AliAnalysisTaskSECharmFraction("AliAnalysisTaskSECharmFraction",cutTight,cutLoose); cutLoose->PrintAll(); } if(ppPbPb==1){// Switch Off recalctulation of primary vertex w/o candidate's daughters // a protection that must be kept here to be sure //that this is done also if the cut objects are provided by outside Printf("AddTaskSECharmFraction: Switch Off recalculation of primary vertex w/o candidate's daughters (PbPb analysis) \n"); AliRDHFCutsD0toKpi *cloose=hfTask->GetLooseCut(); AliRDHFCutsD0toKpi *ctight=hfTask->GetTightCut(); cloose->SetRemoveDaughtersFromPrim(kFALSE); ctight->SetRemoveDaughtersFromPrim(kFALSE); if(analysLevel<2){ printf("Cannot activate the filling of all the histograms for PbPb analysis \n changing analysis level to 2 \n"); analysLevel=2; } // Activate Default PID for proton rejection (TEMPORARY) // cloose->SetUseDefaultPID(kTRUE); // ctight->SetUseDefaultPID(kTRUE); } if(readmc>0)hfTask->SetReadMC(kTRUE); if(readmc==2){ hfTask->SetRejecCandidateMCUpgrade(kTRUE); hfTask->SetSkipEventSelection(kTRUE); hfTask->SetMaxZvtxForSkipEventSelection(10.); } hfTask->SetNMaxTrForVtx(2); hfTask->SetAnalyzeLikeSign(likesign); hfTask->SetUsePID(usepid); hfTask->SetStandardMassSelection(); hfTask->SetAnalysisLevel(analysLevel); hfTask->SetFillImpParTree(fillTree); hfTask->SetCheckBitD0flag(checkBitD0); if(readmc&&useWeight)hfTask->SetPtWeightsFromDataPbPb276overLHC12a17a(); // hfTask->SignalInvMassCut(0.27); /* ############### HERE THE POSSIBILITY TO SWITCH ON/OFF THE TLISTS AND MC SELECTION WILL BE SET #########à hfTask->SetUseCuts(setD0usecuts); hfTask->SetCheckMC(setcheckMC); hfTask->SetCheckMC_D0(setcheckMC_D0); hfTask->SetCheckMC_2prongs(setcheckMC_2prongs); hfTask->SetCheckMC_prompt(setcheckMC_prompt); hfTask->SetCheckMC_fromB(setcheckMC_fromB); hfTask->SetCheckMC_fromDstar(setSkipD0star); hfTask->SetStudyPureBackground(setStudyPureBack);*/ // hfTask->SetSideBands(0); // hfTask->SetDebugLevel(2); mgr->AddTask(hfTask); // Create containers for input/output AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer(); //mgr->CreateContainer("cinput",TChain::Class(),AliAnalysisManager::kInputContainer); mgr->ConnectInput(hfTask,0,cinput); //Now container for general properties histograms containername="outputNentries"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *coutputNentries = mgr->CreateContainer(containername.Data(),TH1F::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,1,coutputNentries); containername="outputSignalType"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *coutputSignalType = mgr->CreateContainer(containername.Data(),TH1F::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,2,coutputSignalType); containername="outputSignalType_LsCuts"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *coutputSignalType_LsCuts = mgr->CreateContainer(containername.Data(),TH1F::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,3,coutputSignalType_LsCuts); containername="outputSignalType_TghCuts"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *coutputSignalType_TghCuts = mgr->CreateContainer(containername.Data(),TH1F::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,4,coutputSignalType_TghCuts); containername="outputNormalizationCounter"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *coutputNormCounter = mgr ->CreateContainer(containername.Data(), AliNormalizationCounter::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask, 5, coutputNormCounter); //Now Container for MC TList containername="listMCproperties"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *clistMCprop = mgr->CreateContainer(containername.Data(),TList::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,6,clistMCprop); // Now container for TLists last=7; //########## NO CUTS TLISTS CONTAINER ##############à containername="listNCsign"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *clistNCsign = mgr->CreateContainer(containername.Data(),TList::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,last,clistNCsign); last++; containername="listNCback"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *clistNCback = mgr->CreateContainer(containername.Data(),TList::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,last,clistNCback); last++; containername="listNCfromB"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *clistNCfromB = mgr->CreateContainer(containername.Data(),TList::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,last,clistNCfromB); last++; containername="listNCfromDstar"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *clistNCfromDstar = mgr->CreateContainer(containername.Data(),TList::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,last,clistNCfromDstar); last++; containername="listNCother"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *clistNCother = mgr->CreateContainer(containername.Data(),TList::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,last,clistNCother); last++; //######### LOOSE CUTS TLISTS CONTAINER ############# containername="listLSCsign"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *clistLSCsign = mgr->CreateContainer(containername.Data(),TList::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,last,clistLSCsign); last++; containername="listLSCback"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *clistLSCback = mgr->CreateContainer(containername.Data(),TList::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,last,clistLSCback); last++; containername="listLSCfromB"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *clistLSCfromB = mgr->CreateContainer(containername.Data(),TList::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,last,clistLSCfromB); last++; containername="listLSCfromDstar"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *clistLSCfromDstar = mgr->CreateContainer(containername.Data(),TList::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,last,clistLSCfromDstar); last++; containername="listLSCother"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *clistLSCother = mgr->CreateContainer(containername.Data(),TList::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,last,clistLSCother); last++; //######### TIGHT CUTS TLISTS CONTAINER ############# containername="listTGHCsign"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *clistTGHCsign = mgr->CreateContainer(containername.Data(),TList::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,last,clistTGHCsign); last++; containername="listTGHCback"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *clistTGHCback = mgr->CreateContainer(containername.Data(),TList::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,last,clistTGHCback); last++; containername="listTGHCfromB"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *clistTGHCfromB = mgr->CreateContainer(containername.Data(),TList::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,last,clistTGHCfromB); last++; containername="listTGHCfromDstar"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *clistTGHCfromDstar = mgr->CreateContainer(containername.Data(),TList::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,last,clistTGHCfromDstar); last++; containername="listTGHCother"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *clistTGHCother = mgr->CreateContainer(containername.Data(),TList::Class(), AliAnalysisManager::kOutputContainer, fileout.Data()); mgr->ConnectOutput(hfTask,last,clistTGHCother); last++; // Container for Cuts Objects containername="cutsObjectTight"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *cCutsObjectTight = mgr->CreateContainer(containername,AliRDHFCutsD0toKpi::Class(),AliAnalysisManager::kOutputContainer,fileout.Data()); //cuts mgr->ConnectOutput(hfTask,last,cCutsObjectTight); last++; containername="cutsObjectLoose"; containername.Prepend(containerprefix.Data()); containername.Append(str.Data()); AliAnalysisDataContainer *cCutsObjectLoose = mgr->CreateContainer(containername,AliRDHFCutsD0toKpi::Class(),AliAnalysisManager::kOutputContainer,fileout.Data()); //cuts mgr->ConnectOutput(hfTask,last,cCutsObjectLoose); return hfTask; } <|endoftext|>
<commit_before>/* Copyright (c) 2014-2015, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions 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 the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/config.hpp" #include <cstring> #include "libtorrent/aux_/cpuid.hpp" #if defined _MSC_VER && TORRENT_HAS_SSE #include <intrin.h> #include <nmmintrin.h> #endif namespace libtorrent { namespace aux { namespace { // internal void cpuid(unsigned int info[4], int type) { #if TORRENT_HAS_SSE && defined _MSC_VER __cpuid((int*)info, type); #elif TORRENT_HAS_SSE && defined __GNUC__ asm volatile ("cpuid" : "=a" (info[0]), "=b" (info[1]), "=c" (info[2]), "=d" (info[3]) : "a" (type), "c" (0)); #else // for non-x86 and non-amd64, just return zeroes std::memset(&info[0], 0, sizeof(unsigned int) * 4); #endif } bool supports_sse42() { #if TORRENT_HAS_SSE unsigned int cpui[4]; cpuid(cpui, 1); return cpui[2] & (1 << 20); #else return false; #endif } bool supports_mmx() { #if TORRENT_HAS_SSE unsigned int cpui[4]; cpuid(cpui, 1); return cpui[2] & (1 << 23); #else return false; #endif } } // anonymous namespace bool sse42_support = supports_sse42(); bool mmx_support = supports_mmx(); } } <commit_msg>attempted fix for cpu_id issues on ubuntu<commit_after>/* Copyright (c) 2014-2015, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions 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 the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/config.hpp" #include <cstring> #include "libtorrent/aux_/cpuid.hpp" #if defined _MSC_VER && TORRENT_HAS_SSE #include <intrin.h> #include <nmmintrin.h> #endif #if TORRENT_HAS_SSE && defined __GNUC__ #include <cpuid.h> #endif namespace libtorrent { namespace aux { namespace { // internal void cpuid(unsigned int info[4], int type) { #if TORRENT_HAS_SSE && defined _MSC_VER __cpuid((int*)info, type); #elif TORRENT_HAS_SSE && defined __GNUC__ __get_cpuid(type, &info[0], &info[1], &info[2], &info[3]); #else // for non-x86 and non-amd64, just return zeroes std::memset(&info[0], 0, sizeof(unsigned int) * 4); #endif } bool supports_sse42() { #if TORRENT_HAS_SSE unsigned int cpui[4]; cpuid(cpui, 1); return cpui[2] & (1 << 20); #else return false; #endif } bool supports_mmx() { #if TORRENT_HAS_SSE unsigned int cpui[4]; cpuid(cpui, 1); return cpui[2] & (1 << 23); #else return false; #endif } } // anonymous namespace bool sse42_support = supports_sse42(); bool mmx_support = supports_mmx(); } } <|endoftext|>
<commit_before>#include <bts/app/api.hpp> #include <bts/chain/address.hpp> #include <bts/utilities/key_conversion.hpp> #include <fc/io/json.hpp> #include <fc/network/http/websocket.hpp> #include <fc/rpc/websocket_api.hpp> #include <fc/io/stdio.hpp> #include <iostream> #include <fc/rpc/cli.hpp> #include <iomanip> using namespace bts::app; using namespace bts::chain; using namespace bts::utilities; using namespace std; struct wallet_data { flat_set<account_id_type> accounts; map<key_id_type, string> keys; string ws_server = "ws://localhost:8090"; string ws_user; string ws_password; }; FC_REFLECT( wallet_data, (accounts)(keys)(ws_server)(ws_user)(ws_password) ); /** * This wallet assumes nothing about where the database server is * located and performs minimal caching. This API could be provided * locally to be used by a web interface. */ class wallet_api { public: wallet_api( fc::api<login_api> rapi ) :_remote_api(rapi) { _remote_db = _remote_api->database(); _remote_net = _remote_api->network(); } string help()const; string suggest_brain_key()const { return string("dummy"); } variant get_object( object_id_type id ) { return _remote_db->get_objects({id}); } account_object get_account( string account_name_or_id ) { FC_ASSERT( account_name_or_id.size() > 0 ); vector<optional<account_object>> opt_account; if( std::isdigit( account_name_or_id.front() ) ) opt_account = _remote_db->get_accounts( {fc::variant(account_name_or_id).as<account_id_type>()} ); else opt_account = _remote_db->lookup_account_names( {account_name_or_id} ); FC_ASSERT( opt_account.size() && opt_account.front() ); return *opt_account.front(); } bool import_key( string account_name_or_id, string wif_key ) { auto opt_priv_key = wif_to_key(wif_key); FC_ASSERT( opt_priv_key.valid() ); auto wif_key_address = opt_priv_key->get_public_key(); auto acnt = get_account( account_name_or_id ); flat_set<key_id_type> keys; for( auto item : acnt.active.auths ) { if( item.first.type() == key_object_type ) keys.insert( item.first ); } for( auto item : acnt.owner.auths ) { if( item.first.type() == key_object_type ) keys.insert( item.first ); } auto opt_keys = _remote_db->get_keys( vector<key_id_type>(keys.begin(),keys.end()) ); for( auto opt_key : opt_keys ) { FC_ASSERT( opt_key.valid() ); if( opt_key->key_address() == wif_key_address ) { _wallet.keys[ opt_key->id ] = wif_key; return true; } } ilog( "key not for account ${name}", ("name",account_name_or_id) ); return false; } string normalize_brain_key( string s ) { size_t i = 0, n = s.length(); std::string result; char c; result.reserve( n ); bool preceded_by_whitespace = false; bool non_empty = false; while( i < n ) { c = s[i++]; switch( c ) { case ' ': case '\t': case '\r': case '\n': case '\v': case '\f': preceded_by_whitespace = true; continue; case 'a': c = 'A'; break; case 'b': c = 'B'; break; case 'c': c = 'C'; break; case 'd': c = 'D'; break; case 'e': c = 'E'; break; case 'f': c = 'F'; break; case 'g': c = 'G'; break; case 'h': c = 'H'; break; case 'i': c = 'I'; break; case 'j': c = 'J'; break; case 'k': c = 'K'; break; case 'l': c = 'L'; break; case 'm': c = 'M'; break; case 'n': c = 'N'; break; case 'o': c = 'O'; break; case 'p': c = 'P'; break; case 'q': c = 'Q'; break; case 'r': c = 'R'; break; case 's': c = 'S'; break; case 't': c = 'T'; break; case 'u': c = 'U'; break; case 'v': c = 'V'; break; case 'w': c = 'W'; break; case 'x': c = 'X'; break; case 'y': c = 'Y'; break; case 'z': c = 'Z'; break; default: break; } if( preceded_by_whitespace && non_empty ) result.push_back(' '); result.push_back(c); preceded_by_whitespace = false; non_empty = true; } return result; } fc::ecc::private_key derive_private_key( const std::string& prefix_string, int sequence_number) { std::string sequence_string = std::to_string(sequence_number); fc::sha512 h = fc::sha512::hash(prefix_string + " " + sequence_string); fc::ecc::private_key derived_key = fc::ecc::private_key::regenerate(fc::sha256::hash(h)); return derived_key; } signed_transaction create_account_with_brain_key( string brain_key, string account_name, string pay_from_account ) { // TODO: process when pay_from_account is ID account_object pay_from_account_object = this->get_account( pay_from_account ); account_id_type pay_from_account_id = pay_from_account_object.id; string normalized_brain_key = normalize_brain_key( brain_key ); // TODO: scan blockchain for accounts that exist with same brain key fc::ecc::private_key owner_privkey = derive_private_key( normalized_brain_key, 0 ); fc::ecc::private_key active_privkey = derive_private_key( key_to_wif(owner_privkey), 0); bts::chain::public_key_type owner_pubkey = owner_privkey.get_public_key(); bts::chain::public_key_type active_pubkey = active_privkey.get_public_key(); // get pay_from_account_id key_create_operation owner_key_create_op; owner_key_create_op.fee_paying_account = pay_from_account_id; owner_key_create_op.key_data = owner_pubkey; key_create_operation active_key_create_op; active_key_create_op.fee_paying_account = pay_from_account_id; active_key_create_op.key_data = active_pubkey; // key_create_op.calculate_fee(db.current_fee_schedule()); // TODO: Check if keys already exist!!! account_create_operation account_create_op; vector<string> v_pay_from_account; v_pay_from_account.push_back( pay_from_account ); account_create_op.fee_paying_account = pay_from_account_id; relative_key_id_type owner_rkid(0); relative_key_id_type active_rkid(1); account_create_op.name = account_name; account_create_op.owner = authority(1, owner_rkid, 1); account_create_op.active = authority(1, active_rkid, 1); account_create_op.memo_key = active_rkid; account_create_op.voting_key = active_rkid; account_create_op.vote = flat_set<vote_tally_id_type>(); // current_fee_schedule() // find_account(pay_from_account) // account_create_op.fee = account_create_op.calculate_fee(db.current_fee_schedule()); signed_transaction tx; tx.operations.push_back( owner_key_create_op ); tx.operations.push_back( active_key_create_op ); tx.operations.push_back( account_create_op ); tx.visit( operation_set_fee( _remote_db->get_global_properties().parameters.current_fees ) ); vector<key_id_type> paying_keys = pay_from_account_object.active.get_keys(); tx.validate(); for( key_id_type& key : paying_keys ) { auto it = _wallet.keys.find(key); if( it != _wallet.keys.end() ) { fc::optional< fc::ecc::private_key > privkey = wif_to_key( it->second ); if( !privkey.valid() ) { FC_ASSERT( false, "Malformed private key in _wallet.keys" ); } tx.sign( *privkey ); } } return tx; } signed_transaction transfer( string from, string to, uint64_t amount, string asset_symbol, string memo, bool broadcast = false ) { auto opt_asset = _remote_db->lookup_asset_symbols( {asset_symbol} ); wdump( (opt_asset) ); return signed_transaction(); } wallet_data _wallet; fc::api<login_api> _remote_api; fc::api<database_api> _remote_db; fc::api<network_api> _remote_net; }; FC_API( wallet_api, (help) (import_key) (suggest_brain_key) (create_account_with_brain_key) (transfer) (get_account) (get_object) (normalize_brain_key) ) struct help_visitor { help_visitor( std::stringstream& s ):ss(s){} std::stringstream& ss; template<typename R, typename... Args> void operator()( const char* name, std::function<R(Args...)>& memb )const { ss << std::setw(40) << std::left << fc::get_typename<R>::name() << " " << name << "( "; vector<string> args{ fc::get_typename<Args>::name()... }; for( uint32_t i = 0; i < args.size(); ++i ) ss << args[i] << (i==args.size()-1?" ":", "); ss << ")\n"; } }; string wallet_api::help()const { fc::api<wallet_api> tmp; std::stringstream ss; tmp->visit( help_visitor(ss) ); return ss.str(); } int main( int argc, char** argv ) { try { FC_ASSERT( argc > 1, "usage: ${cmd} WALLET_FILE", ("cmd",argv[0]) ); fc::ecc::private_key genesis_private_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("genesis"))); idump( (key_to_wif( genesis_private_key ) ) ); idump( (account_id_type()) ); wallet_data wallet; fc::path wallet_file(argv[1]); if( fc::exists( wallet_file ) ) wallet = fc::json::from_file( wallet_file ).as<wallet_data>(); fc::http::websocket_client client; auto con = client.connect( wallet.ws_server ); auto apic = std::make_shared<fc::rpc::websocket_api_connection>(*con); con->closed.connect( [&](){ elog( "connection closed" ); } ); auto remote_api = apic->get_remote_api< login_api >(); FC_ASSERT( remote_api->login( wallet.ws_user, wallet.ws_password ) ); auto wapiptr = std::make_shared<wallet_api>(remote_api); wapiptr->_wallet = wallet; fc::api<wallet_api> wapi(wapiptr); auto wallet_cli = std::make_shared<fc::rpc::cli>(); wallet_cli->format_result( "help", [&]( variant result, const fc::variants& a) { return result.get_string(); }); wallet_cli->register_api( wapi ); wallet_cli->start(); wallet_cli->wait(); } catch ( const fc::exception& e ) { std::cout << e.to_detail_string() << "\n"; } return -1; } <commit_msg>Fix Build<commit_after>#include <bts/app/api.hpp> #include <bts/chain/address.hpp> #include <bts/utilities/key_conversion.hpp> #include <fc/io/json.hpp> #include <fc/network/http/websocket.hpp> #include <fc/rpc/websocket_api.hpp> #include <fc/io/stdio.hpp> #include <iostream> #include <fc/rpc/cli.hpp> #include <iomanip> using namespace bts::app; using namespace bts::chain; using namespace bts::utilities; using namespace std; struct wallet_data { flat_set<account_id_type> accounts; map<key_id_type, string> keys; string ws_server = "ws://localhost:8090"; string ws_user; string ws_password; }; FC_REFLECT( wallet_data, (accounts)(keys)(ws_server)(ws_user)(ws_password) ); /** * This wallet assumes nothing about where the database server is * located and performs minimal caching. This API could be provided * locally to be used by a web interface. */ class wallet_api { public: wallet_api( fc::api<login_api> rapi ) :_remote_api(rapi) { _remote_db = _remote_api->database(); _remote_net = _remote_api->network(); } string help()const; string suggest_brain_key()const { return string("dummy"); } variant get_object( object_id_type id ) { return _remote_db->get_objects({id}); } account_object get_account( string account_name_or_id ) { FC_ASSERT( account_name_or_id.size() > 0 ); vector<optional<account_object>> opt_account; if( std::isdigit( account_name_or_id.front() ) ) opt_account = _remote_db->get_accounts( {fc::variant(account_name_or_id).as<account_id_type>()} ); else opt_account = _remote_db->lookup_account_names( {account_name_or_id} ); FC_ASSERT( opt_account.size() && opt_account.front() ); return *opt_account.front(); } bool import_key( string account_name_or_id, string wif_key ) { auto opt_priv_key = wif_to_key(wif_key); FC_ASSERT( opt_priv_key.valid() ); auto wif_key_address = opt_priv_key->get_public_key(); auto acnt = get_account( account_name_or_id ); flat_set<key_id_type> keys; for( auto item : acnt.active.auths ) { if( item.first.type() == key_object_type ) keys.insert( item.first ); } for( auto item : acnt.owner.auths ) { if( item.first.type() == key_object_type ) keys.insert( item.first ); } auto opt_keys = _remote_db->get_keys( vector<key_id_type>(keys.begin(),keys.end()) ); for( auto opt_key : opt_keys ) { FC_ASSERT( opt_key.valid() ); if( opt_key->key_address() == wif_key_address ) { _wallet.keys[ opt_key->id ] = wif_key; return true; } } ilog( "key not for account ${name}", ("name",account_name_or_id) ); return false; } string normalize_brain_key( string s ) { size_t i = 0, n = s.length(); std::string result; char c; result.reserve( n ); bool preceded_by_whitespace = false; bool non_empty = false; while( i < n ) { c = s[i++]; switch( c ) { case ' ': case '\t': case '\r': case '\n': case '\v': case '\f': preceded_by_whitespace = true; continue; case 'a': c = 'A'; break; case 'b': c = 'B'; break; case 'c': c = 'C'; break; case 'd': c = 'D'; break; case 'e': c = 'E'; break; case 'f': c = 'F'; break; case 'g': c = 'G'; break; case 'h': c = 'H'; break; case 'i': c = 'I'; break; case 'j': c = 'J'; break; case 'k': c = 'K'; break; case 'l': c = 'L'; break; case 'm': c = 'M'; break; case 'n': c = 'N'; break; case 'o': c = 'O'; break; case 'p': c = 'P'; break; case 'q': c = 'Q'; break; case 'r': c = 'R'; break; case 's': c = 'S'; break; case 't': c = 'T'; break; case 'u': c = 'U'; break; case 'v': c = 'V'; break; case 'w': c = 'W'; break; case 'x': c = 'X'; break; case 'y': c = 'Y'; break; case 'z': c = 'Z'; break; default: break; } if( preceded_by_whitespace && non_empty ) result.push_back(' '); result.push_back(c); preceded_by_whitespace = false; non_empty = true; } return result; } fc::ecc::private_key derive_private_key( const std::string& prefix_string, int sequence_number) { std::string sequence_string = std::to_string(sequence_number); fc::sha512 h = fc::sha512::hash(prefix_string + " " + sequence_string); fc::ecc::private_key derived_key = fc::ecc::private_key::regenerate(fc::sha256::hash(h)); return derived_key; } signed_transaction create_account_with_brain_key( string brain_key, string account_name, string pay_from_account ) { // TODO: process when pay_from_account is ID account_object pay_from_account_object = this->get_account( pay_from_account ); account_id_type pay_from_account_id = pay_from_account_object.id; string normalized_brain_key = normalize_brain_key( brain_key ); // TODO: scan blockchain for accounts that exist with same brain key fc::ecc::private_key owner_privkey = derive_private_key( normalized_brain_key, 0 ); fc::ecc::private_key active_privkey = derive_private_key( key_to_wif(owner_privkey), 0); bts::chain::public_key_type owner_pubkey = owner_privkey.get_public_key(); bts::chain::public_key_type active_pubkey = active_privkey.get_public_key(); // get pay_from_account_id key_create_operation owner_key_create_op; owner_key_create_op.fee_paying_account = pay_from_account_id; owner_key_create_op.key_data = owner_pubkey; key_create_operation active_key_create_op; active_key_create_op.fee_paying_account = pay_from_account_id; active_key_create_op.key_data = active_pubkey; // key_create_op.calculate_fee(db.current_fee_schedule()); // TODO: Check if keys already exist!!! account_create_operation account_create_op; vector<string> v_pay_from_account; v_pay_from_account.push_back( pay_from_account ); account_create_op.registrar = pay_from_account_id; relative_key_id_type owner_rkid(0); relative_key_id_type active_rkid(1); account_create_op.name = account_name; account_create_op.owner = authority(1, owner_rkid, 1); account_create_op.active = authority(1, active_rkid, 1); account_create_op.memo_key = active_rkid; account_create_op.voting_key = active_rkid; account_create_op.vote = flat_set<vote_tally_id_type>(); // current_fee_schedule() // find_account(pay_from_account) // account_create_op.fee = account_create_op.calculate_fee(db.current_fee_schedule()); signed_transaction tx; tx.operations.push_back( owner_key_create_op ); tx.operations.push_back( active_key_create_op ); tx.operations.push_back( account_create_op ); tx.visit( operation_set_fee( _remote_db->get_global_properties().parameters.current_fees ) ); vector<key_id_type> paying_keys = pay_from_account_object.active.get_keys(); tx.validate(); for( key_id_type& key : paying_keys ) { auto it = _wallet.keys.find(key); if( it != _wallet.keys.end() ) { fc::optional< fc::ecc::private_key > privkey = wif_to_key( it->second ); if( !privkey.valid() ) { FC_ASSERT( false, "Malformed private key in _wallet.keys" ); } tx.sign( *privkey ); } } return tx; } signed_transaction transfer( string from, string to, uint64_t amount, string asset_symbol, string memo, bool broadcast = false ) { auto opt_asset = _remote_db->lookup_asset_symbols( {asset_symbol} ); wdump( (opt_asset) ); return signed_transaction(); } wallet_data _wallet; fc::api<login_api> _remote_api; fc::api<database_api> _remote_db; fc::api<network_api> _remote_net; }; FC_API( wallet_api, (help) (import_key) (suggest_brain_key) (create_account_with_brain_key) (transfer) (get_account) (get_object) (normalize_brain_key) ) struct help_visitor { help_visitor( std::stringstream& s ):ss(s){} std::stringstream& ss; template<typename R, typename... Args> void operator()( const char* name, std::function<R(Args...)>& memb )const { ss << std::setw(40) << std::left << fc::get_typename<R>::name() << " " << name << "( "; vector<string> args{ fc::get_typename<Args>::name()... }; for( uint32_t i = 0; i < args.size(); ++i ) ss << args[i] << (i==args.size()-1?" ":", "); ss << ")\n"; } }; string wallet_api::help()const { fc::api<wallet_api> tmp; std::stringstream ss; tmp->visit( help_visitor(ss) ); return ss.str(); } int main( int argc, char** argv ) { try { FC_ASSERT( argc > 1, "usage: ${cmd} WALLET_FILE", ("cmd",argv[0]) ); fc::ecc::private_key genesis_private_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("genesis"))); idump( (key_to_wif( genesis_private_key ) ) ); idump( (account_id_type()) ); wallet_data wallet; fc::path wallet_file(argv[1]); if( fc::exists( wallet_file ) ) wallet = fc::json::from_file( wallet_file ).as<wallet_data>(); fc::http::websocket_client client; auto con = client.connect( wallet.ws_server ); auto apic = std::make_shared<fc::rpc::websocket_api_connection>(*con); con->closed.connect( [&](){ elog( "connection closed" ); } ); auto remote_api = apic->get_remote_api< login_api >(); FC_ASSERT( remote_api->login( wallet.ws_user, wallet.ws_password ) ); auto wapiptr = std::make_shared<wallet_api>(remote_api); wapiptr->_wallet = wallet; fc::api<wallet_api> wapi(wapiptr); auto wallet_cli = std::make_shared<fc::rpc::cli>(); wallet_cli->format_result( "help", [&]( variant result, const fc::variants& a) { return result.get_string(); }); wallet_cli->register_api( wapi ); wallet_cli->start(); wallet_cli->wait(); } catch ( const fc::exception& e ) { std::cout << e.to_detail_string() << "\n"; } return -1; } <|endoftext|>
<commit_before>//#include "csimplexnd.h" #include <math.h> #include <QVector> #include <QFile> #include <QStringList> #include <iostream> #include "graph.h" #include <QApplication> int main(int argc, char* argv[]) { QString parameters; QStringList arguments; bool consoleonly=false; for(int i=1; i<argc; ++i) { if(argv[i][0]=='-') parameters+=QString::fromLocal8Bit(argv[i]+1); else arguments<<QString::fromLocal8Bit(argv[i]); } if (!parameters.isEmpty()) { for(int i=0; i<parameters.length(); ++i) { switch(parameters.at(i).toAscii()){ case 'c': consoleonly=true; break; default: goto usage; break; } } } if(argc<2) { usage: std::cerr<<"Usage:\n" <<"\t"<<argv[0]<<" [-c] datafile(s)\n" <<"\tAnd ASCII table to append to on stdin\n" <<"\tc - console only, no gui\n"; return 1; } QFile ft; QStringList table; if(ft.open(0,QFile::ReadOnly)) { while(true) { QByteArray buf=ft.readLine(); if(buf.isEmpty()) break; QString line=QString::fromLocal8Bit(buf); if(line.startsWith('#')) std::cout<<line.toLocal8Bit().data(); else if(!line.trimmed().isEmpty()) table<<line.trimmed(); } ft.close(); } if(table.count()<=1) { for(int i=0;i<arguments.count();++i) table<<""; } else if(table.count()!=arguments.count()+1) { std::cerr<<"Invalid ascii table specified"; return 1; } table.first().append("\tFile\t" "Simplex Resonance freq, Hz\t" "Simplex Resonance ampl, V\t" "Simplex Antiresonance freq, Hz\t" "Simplex Antiresonance ampl, V\t" "St. dev., V\t" "Mean Noise, V"); gsl_vector *units; units=gsl_vector_alloc(PARAM_COUNT); gsl_vector *a; a=gsl_vector_alloc(PARAM_COUNT); bool useC0=false ,useLm=false, useU=false, useR0=false; double inLm=0, inC0=0, inU=0, inR0=0; for(int ifile=0;ifile<arguments.count();++ifile) { QFile f(arguments[ifile]); if (!f.open(QIODevice::ReadOnly)) { std::cerr<<"could not open "<<arguments.at(ifile).toLocal8Bit().data(); return 2; } QVector<Point2D> func_data;//I(f) while(!f.atEnd()) { QStringList line = QString::fromAscii(f.readLine()).split('\t'); func_data<<fPoint2D(line[0].toDouble(),line[1].toDouble()); } f.close(); QVector<Point2D> func_sm_data; //smoothen initial data and lessen number of points double noise=0; int step=50; for(int i=step/2;i<func_data.count()-step/2;++i) { double y=0; double x=0; for(int k=i-step/2; k<i+step/2;++k) { x+=func_data[k].x; y+=func_data[k].y; } x/=step; y/=step; func_sm_data<<fPoint2D(func_data[i].x,y); noise+=pow(func_sm_data.last().y-func_data[i].y,2); } noise/=func_sm_data.count();//Standard deviation from mean Point2D Res, Antires; int resi,aresi; Res=find_extremum(func_sm_data,true,&resi); Antires=find_extremum(func_sm_data,false,&aresi); //experimental if(ifile==0) //we only need initial parameters if it's first run, for other files in serise, //parameters do not change much { double fr=Res.x, fa=Antires.x, Ir=Res.y, Ia=Antires.y; useC0=false; useLm=false; double C0,Lm,Rm,Cm,R0,U; R0=1000; U=5; double Zmax=U*R2/Ia, Zmin=U*R2/Ir; Rm=Zmin; if(!useC0) C0=1/sqrt(4*pow(PI,2)*pow(fa,2)*Rm*Zmax); else C0=inC0; if(!useLm) Lm=1/(4*pow(PI,2)*C0*(pow(fa,2)-pow(fr,2))); else Lm=inLm; Cm=1/(4*PI*PI*fr*fr*Lm); gsl_vector_set(a,0,Rm); gsl_vector_set(a,1,Lm); gsl_vector_set(a,2,Cm); gsl_vector_set(a,3,C0); gsl_vector_set(a,4,U); gsl_vector_set(a,5,R0); gsl_vector_set_all(units,1e-10); gsl_vector_mul(units,a); gsl_vector_set_all(a,1e10); } int gstatus=0; do{ {//update Cm if f0 changed a bit too dramatically double Lm = useLm ? inLm : gsl_vector_get(a,1)*gsl_vector_get(units,1); double f0=1/(2*PI*sqrt(Lm*gsl_vector_get(a,2)*gsl_vector_get(units,2))); if(f0<func_data.first().x || f0>func_data.last().x) gsl_vector_set(a,2,1/(gsl_vector_get(units,2)*4*PI*PI*Res.x*Res.x*Lm)); } gsl_vector *ss;//step size ss=gsl_vector_alloc(PARAM_COUNT); gsl_vector_set_all(ss, 1e-2); gsl_vector_mul(ss,a); gsl_multimin_function func; func.n=PARAM_COUNT; func.f=&StDev; param_struct func_params; func_params.data=&func_sm_data; func_params.resi=resi; func_params.aresi=aresi; func_params.f_min=func_data.first().x; func_params.f_max=func_data.last().x; func_params.RmU=gsl_vector_get(units,0); func_params.LmU=gsl_vector_get(units,1); func_params.CmU=gsl_vector_get(units,2); func_params.C0U=gsl_vector_get(units,3); func_params.UU=gsl_vector_get(units,4); func_params.R0U=gsl_vector_get(units,5); func_params.Rm=-1; func_params.Lm=-1; func_params.Cm=-1; func_params.C0=-1; func_params.U=-1; func_params.R0=-1; if(useLm) func_params.Lm=inLm; if(useC0) func_params.C0=inC0; if(useU) func_params.U=inU; if(useR0) func_params.R0=inR0; func.params=(void*)&func_params; gsl_multimin_fminimizer * min = gsl_multimin_fminimizer_alloc (gsl_multimin_fminimizer_nmsimplex, PARAM_COUNT); gsl_multimin_fminimizer_set(min, &func, a, ss); int status; size_t iter=0; double oldsize; do { iter++; if(iter % 10==0) oldsize=gsl_multimin_fminimizer_size(min); status = gsl_multimin_fminimizer_iterate(min); if (status) break; double size = gsl_multimin_fminimizer_size(min); //status = gsl_multimin_test_size (size, 1e-10); if(size!=oldsize || iter%10!=9 ) status=GSL_CONTINUE; else status=GSL_SUCCESS; if (status == GSL_SUCCESS) { std::cerr <<"converged to minimum in \""<<f.fileName().toLocal8Bit().data()<<"\" at\n" <<"Rm="<<gsl_vector_get (min->x, 0)*gsl_vector_get (units, 0)<<"\t" <<"Lm="; if(!useLm) std::cerr<<gsl_vector_get (min->x, 1)*gsl_vector_get (units, 1); else std::cerr<<inLm; std::cerr<<"\t" <<"Cm="<<gsl_vector_get (min->x, 2)*gsl_vector_get (units, 2)<<"\t" <<"C0="; if(!useC0) std::cerr<<gsl_vector_get (min->x, 3)*gsl_vector_get (units, 3); else std::cerr<<inC0; std::cerr<<"\n" <<"StDev="<<min->fval<<"\n" <<"Noise="<<noise<<"\n"; } else { std::cerr<<iter<<"\t" <<min->fval<<"\t" <<size<<"\n"; } } while (status == GSL_CONTINUE && iter < 10000); QVector<qreal> X_exp,Y_exp,X_f,Y_f; foreach(Point2D P, func_data) { X_exp.push_back(P.x); Y_exp.push_back(P.y); } double maxf=func_data[0].x; double maxI=If(min->x,&func_params,maxf); double minf=maxf; double minI=If(min->x,&func_params,maxf); for(double freq=func_data[0].x; freq<func_data.last().x; ++freq) { double I=If(min->x,&func_params, freq); X_f.push_back(freq); Y_f.push_back(I); if(I>maxI) { maxI=I; maxf=freq; } if(I<minI) { minI=I; minf=freq; } } gsl_vector_memcpy(a, min->x); gsl_vector *par; par = gsl_vector_alloc(PARAM_COUNT); gsl_vector_memcpy(par, min->x); gsl_vector_mul(par,units); if(useLm) gsl_vector_set(par,1,inLm); if(useC0) gsl_vector_set(par,3,inC0); if(useU) gsl_vector_set(par,4,inU); if(useR0) gsl_vector_set(par,5,inR0); gsl_multimin_fminimizer_free(min); gsl_vector_free(ss); QApplication app(argc,argv); Graph g(X_exp, Y_exp, X_f, Y_f, gsl_vector_get(par,0), gsl_vector_get(par,1), gsl_vector_get(par,2), gsl_vector_get(par,4), gsl_vector_get(par,3), gsl_vector_get(par,5), minf, minI, maxf, maxI); g.setWindowTitle(f.fileName()); if(!consoleonly) gstatus=g.exec(); else gstatus=QDialog::Accepted; //if it was not shown, we have to agree :) if(gstatus==QDialog::Rejected) { gsl_vector_set(par,0,g.Rm()); gsl_vector_set(par,1,g.Lm()); gsl_vector_set(par,2,g.Cm()); gsl_vector_set(par,3,g.C0()); gsl_vector_set(par,4,g.U()); gsl_vector_set(par,5,g.R0()); gsl_vector_memcpy(a,par); gsl_vector_div(a,units); } else { QString buf; table[ifile+1].append("\t"+f.fileName()+"\t"); table[ifile+1].append(buf.setNum(maxf)+"\t"); table[ifile+1].append(buf.setNum(maxI)+"\t"); table[ifile+1].append(buf.setNum(minf)+"\t"); table[ifile+1].append(buf.setNum(minI)+"\t"); table[ifile+1].append(buf.setNum(min->fval)+"\t"); table[ifile+1].append(buf.setNum(noise)); } if(ifile==0) { useLm=true; inLm=gsl_vector_get(par,1); useC0=true; inC0=gsl_vector_get(par,3); // useU=true; // inU=gsl_vector_get(par,4); useR0=true; inR0=gsl_vector_get(par,5); } gsl_vector_free(par); }while(gstatus==QDialog::Rejected); } gsl_vector_free(a); gsl_vector_free(units); foreach(QString s, table) std::cout<<s.toLocal8Bit().data()<<"\n"; } <commit_msg>optimized some repetitive code, added few conditions on loop, fixed some warnings.<commit_after>//#include "csimplexnd.h" #include <math.h> #include <QVector> #include <QFile> #include <QStringList> #include <iostream> #include "graph.h" #include <QApplication> int main(int argc, char* argv[]) { QString parameters; QStringList arguments; bool consoleonly=false; for(int i=1; i<argc; ++i) { if(argv[i][0]=='-') parameters+=QString::fromLocal8Bit(argv[i]+1); else arguments<<QString::fromLocal8Bit(argv[i]); } if (!parameters.isEmpty()) { for(int i=0; i<parameters.length(); ++i) { switch(parameters.at(i).toAscii()){ case 'c': consoleonly=true; break; default: goto usage; break; } } } if(argc<2) { usage: std::cerr<<"Usage:\n" <<"\t"<<argv[0]<<" [-c] datafile(s)\n" <<"\tAnd ASCII table to append to on stdin\n" <<"\tc - console only, no gui\n"; return 1; } QFile ft; QStringList table; if(ft.open(0,QFile::ReadOnly)) { while(true) { QByteArray buf=ft.readLine(); if(buf.isEmpty()) break; QString line=QString::fromLocal8Bit(buf); if(line.startsWith('#')) std::cout<<line.toLocal8Bit().data(); else if(!line.trimmed().isEmpty()) table<<line.trimmed(); } ft.close(); } if(table.count()<=1) { for(int i=0;i<arguments.count();++i) table<<""; } else if(table.count()!=arguments.count()+1) { std::cerr<<"Invalid ascii table specified"; return 1; } table.first().append("\tFile\t" "Simplex Resonance freq, Hz\t" "Simplex Resonance ampl, V\t" "Simplex Antiresonance freq, Hz\t" "Simplex Antiresonance ampl, V\t" "St. dev., V\t" "Mean Noise, V"); gsl_vector *units; units=gsl_vector_alloc(PARAM_COUNT); gsl_vector *a; a=gsl_vector_alloc(PARAM_COUNT); bool useC0=false ,useLm=false, useU=false, useR0=false; double inLm=0, inC0=0, inU=0, inR0=0; for(int ifile=0;ifile<arguments.count();++ifile) { QFile f(arguments[ifile]); if (!f.open(QIODevice::ReadOnly)) { std::cerr<<"could not open "<<arguments.at(ifile).toLocal8Bit().data(); return 2; } QVector<Point2D> func_data;//I(f) while(!f.atEnd()) { QStringList line = QString::fromAscii(f.readLine()).split('\t'); func_data<<fPoint2D(line[0].toDouble(),line[1].toDouble()); } f.close(); QVector<Point2D> func_sm_data; //smoothen initial data and lessen number of points double noise=0; int step=50; for(int i=step/2;i<func_data.count()-step/2;++i) { double y=0; double x=0; for(int k=i-step/2; k<i+step/2;++k) { x+=func_data[k].x; y+=func_data[k].y; } x/=step; y/=step; func_sm_data<<fPoint2D(func_data[i].x,y); noise+=pow(func_sm_data.last().y-func_data[i].y,2); } noise/=func_sm_data.count();//Standard deviation from mean Point2D Res, Antires; int resi,aresi; Res=find_extremum(func_sm_data,true,&resi); Antires=find_extremum(func_sm_data,false,&aresi); //experimental if(ifile==0) //we only need initial parameters if it's first run, for other files in serise, //parameters do not change much { double fr=Res.x, fa=Antires.x, Ir=Res.y, Ia=Antires.y; useC0=false; useLm=false; double C0,Lm,Rm,Cm,R0,U; R0=1000; U=5; double Zmax=U*R2/Ia, Zmin=U*R2/Ir; Rm=Zmin; if(!useC0) C0=1/sqrt(4*pow(PI,2)*pow(fa,2)*Rm*Zmax); else C0=inC0; if(!useLm) Lm=1/(4*pow(PI,2)*C0*(pow(fa,2)-pow(fr,2))); else Lm=inLm; Cm=1/(4*PI*PI*fr*fr*Lm); gsl_vector_set(a,0,Rm); gsl_vector_set(a,1,Lm); gsl_vector_set(a,2,Cm); gsl_vector_set(a,3,C0); gsl_vector_set(a,4,U); gsl_vector_set(a,5,R0); gsl_vector_set_all(units,1e-10); gsl_vector_mul(units,a); gsl_vector_set_all(a,1e10); } int gstatus=0; do{ {//update Cm if f0 changed a bit too dramatically double Lm = useLm ? inLm : gsl_vector_get(a,1)*gsl_vector_get(units,1); double f0=1/(2*PI*sqrt(Lm*gsl_vector_get(a,2)*gsl_vector_get(units,2))); if(f0<func_data.first().x || f0>func_data.last().x) gsl_vector_set(a,2,1/(gsl_vector_get(units,2)*4*PI*PI*Res.x*Res.x*Lm)); } gsl_vector *ss;//step size ss=gsl_vector_alloc(PARAM_COUNT); gsl_vector_set_all(ss, 1e-2); gsl_vector_mul(ss,a); gsl_multimin_function func; func.n=PARAM_COUNT; func.f=&StDev; param_struct func_params; func_params.data=&func_sm_data; func_params.resi=resi; func_params.aresi=aresi; func_params.f_min=func_data.first().x; func_params.f_max=func_data.last().x; func_params.RmU=gsl_vector_get(units,0); func_params.LmU=gsl_vector_get(units,1); func_params.CmU=gsl_vector_get(units,2); func_params.C0U=gsl_vector_get(units,3); func_params.UU=gsl_vector_get(units,4); func_params.R0U=gsl_vector_get(units,5); func_params.Rm=-1; func_params.Lm=-1; func_params.Cm=-1; func_params.C0=-1; func_params.U=-1; func_params.R0=-1; if(useLm) func_params.Lm=inLm; if(useC0) func_params.C0=inC0; if(useU) func_params.U=inU; if(useR0) func_params.R0=inR0; func.params=(void*)&func_params; gsl_multimin_fminimizer * min = gsl_multimin_fminimizer_alloc (gsl_multimin_fminimizer_nmsimplex, PARAM_COUNT); gsl_multimin_fminimizer_set(min, &func, a, ss); int status; size_t iter=0; double oldsize=0; do { iter++; if(iter % 10==0) oldsize=gsl_multimin_fminimizer_size(min); status = gsl_multimin_fminimizer_iterate(min); if (status) break; double size = gsl_multimin_fminimizer_size(min); //status = gsl_multimin_test_size (size, 1e-10); if(size!=oldsize || iter%10!=9 || size>10) status=GSL_CONTINUE; else status=GSL_SUCCESS; if (status == GSL_SUCCESS) { std::cerr <<"converged to minimum in \""<<f.fileName().toLocal8Bit().data()<<"\" at\n" <<"Rm="<<gsl_vector_get (min->x, 0)*gsl_vector_get (units, 0)<<"\t" <<"Lm="; if(!useLm) std::cerr<<gsl_vector_get (min->x, 1)*gsl_vector_get (units, 1); else std::cerr<<inLm; std::cerr<<"\t" <<"Cm="<<gsl_vector_get (min->x, 2)*gsl_vector_get (units, 2)<<"\t" <<"C0="; if(!useC0) std::cerr<<gsl_vector_get (min->x, 3)*gsl_vector_get (units, 3); else std::cerr<<inC0; std::cerr<<"\n" <<"StDev="<<min->fval<<"\n" <<"Noise="<<noise<<"\n"; } else { std::cerr<<iter<<"\t" <<min->fval<<"\t" <<size<<"\n"; } } while (status == GSL_CONTINUE && iter < 10000); QVector<qreal> X_exp,Y_exp,X_f,Y_f; foreach(Point2D P, func_data) { X_exp.push_back(P.x); Y_exp.push_back(P.y); } double maxf=func_data[0].x; double maxI=If(min->x,&func_params,maxf); double minf=maxf; double minI=If(min->x,&func_params,maxf); for(double freq=func_data[0].x; freq<func_data.last().x; ++freq) { double I=If(min->x,&func_params, freq); X_f.push_back(freq); Y_f.push_back(I); if(I>maxI) { maxI=I; maxf=freq; } if(I<minI) { minI=I; minf=freq; } } gsl_vector_memcpy(a, min->x); gsl_vector *par; par = gsl_vector_alloc(PARAM_COUNT); gsl_vector_memcpy(par, min->x); gsl_vector_mul(par,units); if(useLm) gsl_vector_set(par,1,inLm); if(useC0) gsl_vector_set(par,3,inC0); if(useU) gsl_vector_set(par,4,inU); if(useR0) gsl_vector_set(par,5,inR0); gsl_multimin_fminimizer_free(min); gsl_vector_free(ss); QApplication app(argc,argv); Graph g(X_exp, Y_exp, X_f, Y_f, gsl_vector_get(par,0), gsl_vector_get(par,1), gsl_vector_get(par,2), gsl_vector_get(par,4), gsl_vector_get(par,3), gsl_vector_get(par,5), minf, minI, maxf, maxI); g.setWindowTitle(f.fileName()); if(!consoleonly) gstatus=g.exec(); else gstatus=QDialog::Accepted; //if it was not shown, we have to agree :) if(gstatus==QDialog::Rejected) { gsl_vector_set(par,0,g.Rm()); gsl_vector_set(par,1,g.Lm()); gsl_vector_set(par,2,g.Cm()); gsl_vector_set(par,3,g.C0()); gsl_vector_set(par,4,g.U()); gsl_vector_set(par,5,g.R0()); gsl_vector_memcpy(a,par); gsl_vector_div(a,units); } else { #define table_append_num(v) table[ifile+1].append(QString::number(v,'f',10)+"\t") table[ifile+1].append("\t"+f.fileName()+"\t"); table_append_num(maxf); table_append_num(maxI); table_append_num(minf); table_append_num(minI); table_append_num(min->fval); table_append_num(noise); } if(ifile==0) { useLm=true; inLm=gsl_vector_get(par,1); useC0=true; inC0=gsl_vector_get(par,3); // useU=true; // inU=gsl_vector_get(par,4); useR0=true; inR0=gsl_vector_get(par,5); } gsl_vector_free(par); }while(gstatus==QDialog::Rejected); } gsl_vector_free(a); gsl_vector_free(units); foreach(QString s, table) std::cout<<s.toLocal8Bit().data()<<"\n"; } <|endoftext|>
<commit_before>/* * Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ #include "CompilerGenerated.h" #include "Types.h" namespace { TypeInfo theAnyTypeInfoImpl = {}; TypeInfo theArrayTypeInfoImpl = {}; TypeInfo theBooleanArrayTypeInfoImpl = {}; TypeInfo theByteArrayTypeInfoImpl = {}; TypeInfo theCharArrayTypeInfoImpl = {}; TypeInfo theDoubleArrayTypeInfoImpl = {}; TypeInfo theFloatArrayTypeInfoImpl = {}; TypeInfo theForeignObjCObjectTypeInfoImpl = {}; TypeInfo theFreezableAtomicReferenceTypeInfoImpl = {}; TypeInfo theIntArrayTypeInfoImpl = {}; TypeInfo theLongArrayTypeInfoImpl = {}; TypeInfo theNativePtrArrayTypeInfoImpl = {}; TypeInfo theObjCObjectWrapperTypeInfoImpl = {}; TypeInfo theOpaqueFunctionTypeInfoImpl = {}; TypeInfo theShortArrayTypeInfoImpl = {}; TypeInfo theStringTypeInfoImpl = {}; TypeInfo theThrowableTypeInfoImpl = {}; TypeInfo theUnitTypeInfoImpl = {}; TypeInfo theWorkerBoundReferenceTypeInfoImpl = {}; ArrayHeader theEmptyStringImpl = { &theStringTypeInfoImpl, /* element count */ 0 }; template <class T> struct KBox { ObjHeader header; const T value; }; } // namespace extern "C" { extern const int KonanNeedDebugInfo = 0; extern const TypeInfo* theAnyTypeInfo = &theAnyTypeInfoImpl; extern const TypeInfo* theArrayTypeInfo = &theArrayTypeInfoImpl; extern const TypeInfo* theBooleanArrayTypeInfo = &theBooleanArrayTypeInfoImpl; extern const TypeInfo* theByteArrayTypeInfo = &theByteArrayTypeInfoImpl; extern const TypeInfo* theCharArrayTypeInfo = &theCharArrayTypeInfoImpl; extern const TypeInfo* theDoubleArrayTypeInfo = &theDoubleArrayTypeInfoImpl; extern const TypeInfo* theFloatArrayTypeInfo = &theFloatArrayTypeInfoImpl; extern const TypeInfo* theForeignObjCObjectTypeInfo = &theForeignObjCObjectTypeInfoImpl; extern const TypeInfo* theFreezableAtomicReferenceTypeInfo = &theFreezableAtomicReferenceTypeInfoImpl; extern const TypeInfo* theIntArrayTypeInfo = &theIntArrayTypeInfoImpl; extern const TypeInfo* theLongArrayTypeInfo = &theLongArrayTypeInfoImpl; extern const TypeInfo* theNativePtrArrayTypeInfo = &theNativePtrArrayTypeInfoImpl; extern const TypeInfo* theObjCObjectWrapperTypeInfo = &theObjCObjectWrapperTypeInfoImpl; extern const TypeInfo* theOpaqueFunctionTypeInfo = &theOpaqueFunctionTypeInfoImpl; extern const TypeInfo* theShortArrayTypeInfo = &theShortArrayTypeInfoImpl; extern const TypeInfo* theStringTypeInfo = &theStringTypeInfoImpl; extern const TypeInfo* theThrowableTypeInfo = &theThrowableTypeInfoImpl; extern const TypeInfo* theUnitTypeInfo = &theUnitTypeInfoImpl; extern const TypeInfo* theWorkerBoundReferenceTypeInfo = &theWorkerBoundReferenceTypeInfoImpl; extern const ArrayHeader theEmptyArray = { &theArrayTypeInfoImpl, /* element count */0 }; OBJ_GETTER0(TheEmptyString) { RETURN_OBJ(theEmptyStringImpl.obj()); } RUNTIME_NORETURN OBJ_GETTER(makeWeakReferenceCounter, void*) { THROW_NOT_IMPLEMENTED } RUNTIME_NORETURN OBJ_GETTER(makePermanentWeakReferenceImpl, void*) { THROW_NOT_IMPLEMENTED } RUNTIME_NORETURN OBJ_GETTER(makeObjCWeakReferenceImpl, void*) { THROW_NOT_IMPLEMENTED } void checkRangeIndexes(KInt from, KInt to, KInt size) { if (from < 0 || to > size) { throw std::out_of_range("Index out of bounds: from=" + std::to_string(from) + ", to=" + std::to_string(to) + ", size=" + std::to_string(size)); } if (from > to) { throw std::invalid_argument("Illegal argument: from > to, from=" + std::to_string(from) + ", to=" + std::to_string(to)); } } RUNTIME_NORETURN OBJ_GETTER(WorkerLaunchpad, KRef) { THROW_NOT_IMPLEMENTED } void RUNTIME_NORETURN ThrowWorkerInvalidState() { THROW_NOT_IMPLEMENTED } void RUNTIME_NORETURN ThrowNullPointerException() { THROW_NOT_IMPLEMENTED } void RUNTIME_NORETURN ThrowArrayIndexOutOfBoundsException() { THROW_NOT_IMPLEMENTED } void RUNTIME_NORETURN ThrowClassCastException(const ObjHeader* instance, const TypeInfo* type_info) { THROW_NOT_IMPLEMENTED } void RUNTIME_NORETURN ThrowArithmeticException() { THROW_NOT_IMPLEMENTED } void RUNTIME_NORETURN ThrowNumberFormatException() { THROW_NOT_IMPLEMENTED } void RUNTIME_NORETURN ThrowOutOfMemoryError() { THROW_NOT_IMPLEMENTED } void RUNTIME_NORETURN ThrowNotImplementedError() { THROW_NOT_IMPLEMENTED } void RUNTIME_NORETURN ThrowCharacterCodingException() { THROW_NOT_IMPLEMENTED } void RUNTIME_NORETURN ThrowIllegalArgumentException() { THROW_NOT_IMPLEMENTED } void RUNTIME_NORETURN ThrowIllegalStateException() { THROW_NOT_IMPLEMENTED } void RUNTIME_NORETURN ThrowInvalidMutabilityException(KConstRef where) { THROW_NOT_IMPLEMENTED } void RUNTIME_NORETURN ThrowIncorrectDereferenceException() { THROW_NOT_IMPLEMENTED } void RUNTIME_NORETURN ThrowIllegalObjectSharingException(KConstNativePtr typeInfo, KConstNativePtr address) { THROW_NOT_IMPLEMENTED } void RUNTIME_NORETURN ThrowFreezingException(KRef toFreeze, KRef blocker) { THROW_NOT_IMPLEMENTED } void ReportUnhandledException(KRef throwable) { konan::consolePrintf("Uncaught Kotlin exception."); } RUNTIME_NORETURN OBJ_GETTER(DescribeObjectForDebugging, KConstNativePtr typeInfo, KConstNativePtr address) { THROW_NOT_IMPLEMENTED } void ExceptionReporterLaunchpad(KRef reporter, KRef throwable) { THROW_NOT_IMPLEMENTED } void Kotlin_WorkerBoundReference_freezeHook(KRef thiz) { THROW_NOT_IMPLEMENTED } extern const KBoolean BOOLEAN_RANGE_FROM = false; extern const KBoolean BOOLEAN_RANGE_TO = true; extern KBox<KBoolean> BOOLEAN_CACHE[] = { {{}, false}, {{}, true}, }; OBJ_GETTER(Kotlin_boxBoolean, KBoolean value) { if (value) { RETURN_OBJ(&BOOLEAN_CACHE[1].header); } else { RETURN_OBJ(&BOOLEAN_CACHE[0].header); } } extern const KByte BYTE_RANGE_FROM = -1; extern const KByte BYTE_RANGE_TO = 1; extern KBox<KByte> BYTE_CACHE[] = { {{}, -1}, {{}, 0}, {{}, 1}, }; extern const KChar CHAR_RANGE_FROM = 0; extern const KChar CHAR_RANGE_TO = 2; extern KBox<KChar> CHAR_CACHE[] = { {{}, 0}, {{}, 1}, {{}, 2}, }; extern const KShort SHORT_RANGE_FROM = -1; extern const KShort SHORT_RANGE_TO = 1; extern KBox<KShort> SHORT_CACHE[] = { {{}, -1}, {{}, 0}, {{}, 1}, }; extern const KInt INT_RANGE_FROM = -1; extern const KInt INT_RANGE_TO = 1; extern KBox<KInt> INT_CACHE[] = { {{}, -1}, {{}, 0}, {{}, 1}, }; extern const KLong LONG_RANGE_FROM = -1; extern const KLong LONG_RANGE_TO = 1; extern KBox<KLong> LONG_CACHE[] = { {{}, -1}, {{}, 0}, {{}, 1}, }; RUNTIME_NORETURN OBJ_GETTER(Kotlin_Throwable_getMessage, KRef throwable) { THROW_NOT_IMPLEMENTED } } // extern "C" <commit_msg>[Runtime testing] Enable runtime assertions in runtime tests<commit_after>/* * Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ #include "CompilerGenerated.h" #include "Types.h" namespace { TypeInfo theAnyTypeInfoImpl = {}; TypeInfo theArrayTypeInfoImpl = {}; TypeInfo theBooleanArrayTypeInfoImpl = {}; TypeInfo theByteArrayTypeInfoImpl = {}; TypeInfo theCharArrayTypeInfoImpl = {}; TypeInfo theDoubleArrayTypeInfoImpl = {}; TypeInfo theFloatArrayTypeInfoImpl = {}; TypeInfo theForeignObjCObjectTypeInfoImpl = {}; TypeInfo theFreezableAtomicReferenceTypeInfoImpl = {}; TypeInfo theIntArrayTypeInfoImpl = {}; TypeInfo theLongArrayTypeInfoImpl = {}; TypeInfo theNativePtrArrayTypeInfoImpl = {}; TypeInfo theObjCObjectWrapperTypeInfoImpl = {}; TypeInfo theOpaqueFunctionTypeInfoImpl = {}; TypeInfo theShortArrayTypeInfoImpl = {}; TypeInfo theStringTypeInfoImpl = {}; TypeInfo theThrowableTypeInfoImpl = {}; TypeInfo theUnitTypeInfoImpl = {}; TypeInfo theWorkerBoundReferenceTypeInfoImpl = {}; ArrayHeader theEmptyStringImpl = { &theStringTypeInfoImpl, /* element count */ 0 }; template <class T> struct KBox { ObjHeader header; const T value; }; } // namespace extern "C" { // Set to 1 to enable runtime assertions. extern const int KonanNeedDebugInfo = 1; extern const TypeInfo* theAnyTypeInfo = &theAnyTypeInfoImpl; extern const TypeInfo* theArrayTypeInfo = &theArrayTypeInfoImpl; extern const TypeInfo* theBooleanArrayTypeInfo = &theBooleanArrayTypeInfoImpl; extern const TypeInfo* theByteArrayTypeInfo = &theByteArrayTypeInfoImpl; extern const TypeInfo* theCharArrayTypeInfo = &theCharArrayTypeInfoImpl; extern const TypeInfo* theDoubleArrayTypeInfo = &theDoubleArrayTypeInfoImpl; extern const TypeInfo* theFloatArrayTypeInfo = &theFloatArrayTypeInfoImpl; extern const TypeInfo* theForeignObjCObjectTypeInfo = &theForeignObjCObjectTypeInfoImpl; extern const TypeInfo* theFreezableAtomicReferenceTypeInfo = &theFreezableAtomicReferenceTypeInfoImpl; extern const TypeInfo* theIntArrayTypeInfo = &theIntArrayTypeInfoImpl; extern const TypeInfo* theLongArrayTypeInfo = &theLongArrayTypeInfoImpl; extern const TypeInfo* theNativePtrArrayTypeInfo = &theNativePtrArrayTypeInfoImpl; extern const TypeInfo* theObjCObjectWrapperTypeInfo = &theObjCObjectWrapperTypeInfoImpl; extern const TypeInfo* theOpaqueFunctionTypeInfo = &theOpaqueFunctionTypeInfoImpl; extern const TypeInfo* theShortArrayTypeInfo = &theShortArrayTypeInfoImpl; extern const TypeInfo* theStringTypeInfo = &theStringTypeInfoImpl; extern const TypeInfo* theThrowableTypeInfo = &theThrowableTypeInfoImpl; extern const TypeInfo* theUnitTypeInfo = &theUnitTypeInfoImpl; extern const TypeInfo* theWorkerBoundReferenceTypeInfo = &theWorkerBoundReferenceTypeInfoImpl; extern const ArrayHeader theEmptyArray = { &theArrayTypeInfoImpl, /* element count */0 }; OBJ_GETTER0(TheEmptyString) { RETURN_OBJ(theEmptyStringImpl.obj()); } RUNTIME_NORETURN OBJ_GETTER(makeWeakReferenceCounter, void*) { THROW_NOT_IMPLEMENTED } RUNTIME_NORETURN OBJ_GETTER(makePermanentWeakReferenceImpl, void*) { THROW_NOT_IMPLEMENTED } RUNTIME_NORETURN OBJ_GETTER(makeObjCWeakReferenceImpl, void*) { THROW_NOT_IMPLEMENTED } void checkRangeIndexes(KInt from, KInt to, KInt size) { if (from < 0 || to > size) { throw std::out_of_range("Index out of bounds: from=" + std::to_string(from) + ", to=" + std::to_string(to) + ", size=" + std::to_string(size)); } if (from > to) { throw std::invalid_argument("Illegal argument: from > to, from=" + std::to_string(from) + ", to=" + std::to_string(to)); } } RUNTIME_NORETURN OBJ_GETTER(WorkerLaunchpad, KRef) { THROW_NOT_IMPLEMENTED } void RUNTIME_NORETURN ThrowWorkerInvalidState() { THROW_NOT_IMPLEMENTED } void RUNTIME_NORETURN ThrowNullPointerException() { THROW_NOT_IMPLEMENTED } void RUNTIME_NORETURN ThrowArrayIndexOutOfBoundsException() { THROW_NOT_IMPLEMENTED } void RUNTIME_NORETURN ThrowClassCastException(const ObjHeader* instance, const TypeInfo* type_info) { THROW_NOT_IMPLEMENTED } void RUNTIME_NORETURN ThrowArithmeticException() { THROW_NOT_IMPLEMENTED } void RUNTIME_NORETURN ThrowNumberFormatException() { THROW_NOT_IMPLEMENTED } void RUNTIME_NORETURN ThrowOutOfMemoryError() { THROW_NOT_IMPLEMENTED } void RUNTIME_NORETURN ThrowNotImplementedError() { THROW_NOT_IMPLEMENTED } void RUNTIME_NORETURN ThrowCharacterCodingException() { THROW_NOT_IMPLEMENTED } void RUNTIME_NORETURN ThrowIllegalArgumentException() { THROW_NOT_IMPLEMENTED } void RUNTIME_NORETURN ThrowIllegalStateException() { THROW_NOT_IMPLEMENTED } void RUNTIME_NORETURN ThrowInvalidMutabilityException(KConstRef where) { THROW_NOT_IMPLEMENTED } void RUNTIME_NORETURN ThrowIncorrectDereferenceException() { THROW_NOT_IMPLEMENTED } void RUNTIME_NORETURN ThrowIllegalObjectSharingException(KConstNativePtr typeInfo, KConstNativePtr address) { THROW_NOT_IMPLEMENTED } void RUNTIME_NORETURN ThrowFreezingException(KRef toFreeze, KRef blocker) { THROW_NOT_IMPLEMENTED } void ReportUnhandledException(KRef throwable) { konan::consolePrintf("Uncaught Kotlin exception."); } RUNTIME_NORETURN OBJ_GETTER(DescribeObjectForDebugging, KConstNativePtr typeInfo, KConstNativePtr address) { THROW_NOT_IMPLEMENTED } void ExceptionReporterLaunchpad(KRef reporter, KRef throwable) { THROW_NOT_IMPLEMENTED } void Kotlin_WorkerBoundReference_freezeHook(KRef thiz) { THROW_NOT_IMPLEMENTED } extern const KBoolean BOOLEAN_RANGE_FROM = false; extern const KBoolean BOOLEAN_RANGE_TO = true; extern KBox<KBoolean> BOOLEAN_CACHE[] = { {{}, false}, {{}, true}, }; OBJ_GETTER(Kotlin_boxBoolean, KBoolean value) { if (value) { RETURN_OBJ(&BOOLEAN_CACHE[1].header); } else { RETURN_OBJ(&BOOLEAN_CACHE[0].header); } } extern const KByte BYTE_RANGE_FROM = -1; extern const KByte BYTE_RANGE_TO = 1; extern KBox<KByte> BYTE_CACHE[] = { {{}, -1}, {{}, 0}, {{}, 1}, }; extern const KChar CHAR_RANGE_FROM = 0; extern const KChar CHAR_RANGE_TO = 2; extern KBox<KChar> CHAR_CACHE[] = { {{}, 0}, {{}, 1}, {{}, 2}, }; extern const KShort SHORT_RANGE_FROM = -1; extern const KShort SHORT_RANGE_TO = 1; extern KBox<KShort> SHORT_CACHE[] = { {{}, -1}, {{}, 0}, {{}, 1}, }; extern const KInt INT_RANGE_FROM = -1; extern const KInt INT_RANGE_TO = 1; extern KBox<KInt> INT_CACHE[] = { {{}, -1}, {{}, 0}, {{}, 1}, }; extern const KLong LONG_RANGE_FROM = -1; extern const KLong LONG_RANGE_TO = 1; extern KBox<KLong> LONG_CACHE[] = { {{}, -1}, {{}, 0}, {{}, 1}, }; RUNTIME_NORETURN OBJ_GETTER(Kotlin_Throwable_getMessage, KRef throwable) { THROW_NOT_IMPLEMENTED } } // extern "C" <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if !defined(MEMORYMANAGERIMPL_HEADER_GUARD_1357924680) #define MEMORYMANAGERIMPL_HEADER_GUARD_1357924680 // Base include file. Must be first. #include <new> #include <xalanc/Include/PlatformDefinitions.hpp> #include <xercesc/framework/MemoryManager.hpp> #if defined(XALAN_WINDOWS) #include <windows.h> #include <stdexcept> #include <stdlib.h> class XalanMemoryManagerImpl : public XALAN_CPP_NAMESPACE_QUALIFIER MemoryManagerType { public: XalanMemoryManagerImpl( DWORD defSize = 0 ) : m_heapHandle(NULL) { m_heapHandle = HeapCreate( HEAP_NO_SERIALIZE, 0, // dwInitialSize defSize); if( m_heapHandle == NULL ) { XALAN_USING_STD(runtime_error) char buffer[20]; buffer[0] = 0; _ultoa( GetLastError(), buffer, 10); throw runtime_error(buffer); } } virtual void* allocate( size_t size ) { LPVOID ptr = HeapAlloc( m_heapHandle, //HANDLE hHeap 0, //DWORD dwFlags size //SIZE_T dwBytes ); if( ptr == 0) { XALAN_USING_STD(bad_alloc) throw bad_alloc(); } return ptr; } virtual void deallocate( void* pDataPointer ) { if ( 0 == HeapFree( m_heapHandle, //HANDLE hHeap, 0, //DWORD dwFlags, pDataPointer ) )//*LPVOID lpMem { XALAN_USING_STD(bad_alloc) throw bad_alloc(); } } virtual MemoryManager* getExceptionMemoryManager() { return this; } virtual ~XalanMemoryManagerImpl() { if( 0 == HeapDestroy(m_heapHandle) ) { XALAN_USING_STD(runtime_error) char buffer[20]; buffer[0] = 0; _ultoa( GetLastError(), buffer, 10); throw runtime_error(buffer); } } private: // Not implemented XalanMemoryManagerImpl& operator=(const XalanMemoryManagerImpl&); XalanMemoryManagerImpl(const XalanMemoryManagerImpl&); //Data HANDLE m_heapHandle; }; #else class XalanMemoryManagerImpl : public XALAN_CPP_NAMESPACE_QUALIFIER MemoryManagerType { public: virtual ~XalanMemoryManagerImpl() { } virtual void* allocate( size_t size ) { void* memptr = ::operator new(size); if (memptr != NULL) { return memptr; } XALAN_USING_STD(bad_alloc) throw bad_alloc(); } virtual void deallocate( void* pDataPointer ) { operator delete(pDataPointer); } MemoryManager* getExceptionMemoryManager() { return this; } }; #endif #endif // MEMORYMANAGERIMPL_HEADER_GUARD_1357924680 <commit_msg>More cleanup.<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if !defined(MEMORYMANAGERIMPL_HEADER_GUARD_1357924680) #define MEMORYMANAGERIMPL_HEADER_GUARD_1357924680 // Base include file. Must be first. #include <new> #include <xalanc/Include/PlatformDefinitions.hpp> #include <xercesc/framework/MemoryManager.hpp> #if defined(XALAN_WINDOWS) #include <windows.h> #include <stdexcept> #include <stdlib.h> class XalanMemoryManagerImpl : public XERCES_CPP_NAMESPACE_QUALIFIER MemoryManager { public: XalanMemoryManagerImpl( DWORD defSize = 0 ) : m_heapHandle(NULL) { m_heapHandle = HeapCreate( HEAP_NO_SERIALIZE, 0, // dwInitialSize defSize); if( m_heapHandle == NULL ) { XALAN_USING_STD(runtime_error) char buffer[20]; buffer[0] = 0; _ultoa( GetLastError(), buffer, 10); throw runtime_error(buffer); } } virtual void* allocate( size_t size ) { LPVOID ptr = HeapAlloc( m_heapHandle, //HANDLE hHeap 0, //DWORD dwFlags size //SIZE_T dwBytes ); if( ptr == 0) { XALAN_USING_STD(bad_alloc) throw bad_alloc(); } return ptr; } virtual void deallocate( void* pDataPointer ) { if ( 0 == HeapFree( m_heapHandle, //HANDLE hHeap, 0, //DWORD dwFlags, pDataPointer ) )//*LPVOID lpMem { XALAN_USING_STD(bad_alloc) throw bad_alloc(); } } virtual MemoryManager* getExceptionMemoryManager() { return this; } virtual ~XalanMemoryManagerImpl() { if( 0 == HeapDestroy(m_heapHandle) ) { XALAN_USING_STD(runtime_error) char buffer[20]; buffer[0] = 0; _ultoa( GetLastError(), buffer, 10); throw runtime_error(buffer); } } private: // Not implemented XalanMemoryManagerImpl& operator=(const XalanMemoryManagerImpl&); XalanMemoryManagerImpl(const XalanMemoryManagerImpl&); //Data HANDLE m_heapHandle; }; #else class XalanMemoryManagerImpl : public XERCES_CPP_NAMESPACE_QUALIFIER MemoryManager { public: virtual ~XalanMemoryManagerImpl() { } virtual void* allocate( size_t size ) { void* memptr = ::operator new(size); if (memptr != NULL) { return memptr; } XALAN_USING_STD(bad_alloc) throw bad_alloc(); } virtual void deallocate( void* pDataPointer ) { operator delete(pDataPointer); } virtual MemoryManager* getExceptionMemoryManager() { return this; } }; #endif #endif // MEMORYMANAGERIMPL_HEADER_GUARD_1357924680 <|endoftext|>
<commit_before>#include "bufferAgent.h" #include "helpers/storageHelperFactory.h" #include "glog/logging.h" using boost::shared_ptr; using boost::thread; using boost::bind; using std::string; namespace veil { namespace helpers { BufferAgent::BufferAgent(write_fun w, read_fun r) : m_agentActive(false), doWrite(w), doRead(r) { agentStart(); } BufferAgent::~BufferAgent() { agentStop(); } int BufferAgent::onOpen(std::string path, ffi_type ffi) { { unique_lock guard(m_wrMutex); m_wrCacheMap.erase(ffi->fh); write_buffer_ptr lCache(new WriteCache()); lCache->fileName = path; lCache->buffer = newFileCache(true); lCache->ffi = *ffi; m_wrCacheMap[ffi->fh] = lCache; } { unique_lock guard(m_rdMutex); read_cache_map_t::iterator it; if(( it = m_rdCacheMap.find(path) ) != m_rdCacheMap.end()) { it->second->openCount++; } else { read_buffer_ptr lCache(new ReadCache()); lCache->fileName = path; lCache->openCount = 1; lCache->ffi = *ffi; lCache->buffer = newFileCache(false); } m_rdJobQueue.push_front(PrefetchJob(path, 0, 512)); } return 0; } int BufferAgent::onWrite(std::string path, const std::string &buf, size_t size, off_t offset, ffi_type ffi) { unique_lock guard(m_wrMutex); write_buffer_ptr wrapper = m_wrCacheMap[ffi->fh]; guard.unlock(); { if(wrapper->buffer->byteSize() > 1024 * 1024 * 64) { if(int fRet = onFlush(path, ffi)) { return fRet; } } if(wrapper->buffer->byteSize() > 1024 * 1024 * 64) { return doWrite(path, buf, size, offset, ffi); } wrapper->buffer->writeData(offset, buf); } unique_lock buffGuard(wrapper->mutex); guard.lock(); if(!wrapper->opPending) { wrapper->opPending = true; m_wrJobQueue.push_back(ffi->fh); m_wrCond.notify_one(); } return size; } int BufferAgent::onRead(std::string path, std::string &buf, size_t size, off_t offset, ffi_type ffi) { unique_lock guard(m_rdMutex); read_buffer_ptr wrapper = m_rdCacheMap[path]; guard.unlock(); wrapper->buffer->readData(offset, size, buf); if(buf.size() < size) { string buf2; int ret = doRead(path, buf2, buf.size() - size, offset + buf.size(), &wrapper->ffi); if(ret < 0) return ret; buf += buf2; { unique_lock buffGuard(wrapper->mutex); wrapper->blockSize = std::min((size_t) 1024 * 1024, (size_t) std::max(size, 2*wrapper->blockSize)); } guard.lock(); m_rdJobQueue.push_back(PrefetchJob(wrapper->fileName, buf.size(), wrapper->blockSize)); guard.unlock(); } else { string tmp; size_t prefSize = std::max(2*size, wrapper->blockSize); wrapper->buffer->readData(offset + size, prefSize, tmp); if(tmp.size() != prefSize) { guard.lock(); m_rdJobQueue.push_back(PrefetchJob(wrapper->fileName, offset + size + tmp.size(), wrapper->blockSize)); m_rdJobQueue.push_back(PrefetchJob(wrapper->fileName, offset + size + tmp.size() + wrapper->blockSize, wrapper->blockSize)); guard.unlock(); } } return buf.size(); } int BufferAgent::onFlush(std::string path, ffi_type ffi) { unique_lock guard(m_wrMutex); write_buffer_ptr wrapper = m_wrCacheMap[ffi->fh]; guard.unlock(); unique_lock sendGuard(wrapper->sendMutex); unique_lock buff_guard(wrapper->mutex); while(wrapper->buffer->blockCount() > 0) { block_ptr block = wrapper->buffer->removeOldestBlock(); uint64_t start = utils::mtime<uint64_t>(); int res = doWrite(wrapper->fileName, block->data, block->data.size(), block->offset, &wrapper->ffi); uint64_t end = utils::mtime<uint64_t>(); LOG(INFO) << "Roundtrip: " << (end - start) << " for " << block->data.size() << " bytes"; if(res < 0) { while(wrapper->buffer->blockCount() > 0) { (void) wrapper->buffer->removeOldestBlock(); } return res; } } guard.lock(); m_wrJobQueue.remove(ffi->fh); return 0; } int BufferAgent::onRelease(std::string path, ffi_type ffi) { { unique_lock guard(m_wrMutex); m_wrCacheMap.erase(ffi->fh); m_wrJobQueue.remove(ffi->fh); } { unique_lock guard(m_rdMutex); read_cache_map_t::iterator it; if(( it = m_rdCacheMap.find(path) ) != m_rdCacheMap.end()) { it->second->openCount--; if(it->second->openCount <= 0) { m_rdCacheMap.erase(it); } } } return 0; } void BufferAgent::agentStart(int worker_count) { m_workers.clear(); m_agentActive = true; while(worker_count--) { m_workers.push_back(shared_ptr<thread>(new thread(bind(&BufferAgent::writerLoop, this)))); m_workers.push_back(shared_ptr<thread>(new thread(bind(&BufferAgent::readerLoop, this)))); } } void BufferAgent::agentStop() { m_agentActive = false; m_wrCond.notify_all(); m_rdCond.notify_all(); while(m_workers.size() > 0) { m_workers.back()->join(); m_workers.pop_back(); } } void BufferAgent::readerLoop() { unique_lock guard(m_rdMutex); while(m_agentActive) { while(m_rdJobQueue.empty() && m_agentActive) m_rdCond.wait(guard); if(!m_agentActive) return; PrefetchJob job = m_rdJobQueue.front(); read_buffer_ptr wrapper = m_rdCacheMap[job.fileName]; m_rdJobQueue.pop_front(); m_rdCond.notify_one(); if(!wrapper) continue; guard.unlock(); { string buff; int ret = doRead(wrapper->fileName, buff, job.size, job.offset, &wrapper->ffi); if(ret > 0 && buff.size() >= ret) { wrapper->buffer->writeData(job.offset, buff); } } } } void BufferAgent::writerLoop() { unique_lock guard(m_wrMutex); while(m_agentActive) { while(m_wrJobQueue.empty() && m_agentActive) m_wrCond.wait(guard); if(!m_agentActive) return; fd_type file = m_wrJobQueue.front(); write_buffer_ptr wrapper = m_wrCacheMap[file]; m_wrJobQueue.pop_front(); m_wrCond.notify_one(); if(!wrapper) continue; guard.unlock(); { unique_lock sendGuard(wrapper->sendMutex); block_ptr block; { unique_lock buff_guard(wrapper->mutex); block = wrapper->buffer->removeOldestBlock(); } if(block) { uint64_t start = utils::mtime<uint64_t>(); int res = doWrite(wrapper->fileName, block->data, block->data.size(), block->offset, &wrapper->ffi); uint64_t end = utils::mtime<uint64_t>(); LOG(INFO) << "Roundtrip: " << (end - start) << " for " << block->data.size() << " bytes"; wrapper->cond.notify_all(); } { unique_lock buff_guard(wrapper->mutex); guard.lock(); if(wrapper->buffer->blockCount() > 0) { m_wrJobQueue.push_back(file); } else { wrapper->opPending = false; } } } wrapper->cond.notify_all(); } } boost::shared_ptr<FileCache> BufferAgent::newFileCache(bool isBuffer) { return boost::shared_ptr<FileCache>(new FileCache(10 * 1024 * 1024, isBuffer)); } } // namespace helpers } // namespace veil <commit_msg>VFS-292: improve read speed<commit_after>#include "bufferAgent.h" #include "helpers/storageHelperFactory.h" #include "glog/logging.h" using boost::shared_ptr; using boost::thread; using boost::bind; using std::string; namespace veil { namespace helpers { BufferAgent::BufferAgent(write_fun w, read_fun r) : m_agentActive(false), doWrite(w), doRead(r) { agentStart(); } BufferAgent::~BufferAgent() { agentStop(); } int BufferAgent::onOpen(std::string path, ffi_type ffi) { { unique_lock guard(m_wrMutex); m_wrCacheMap.erase(ffi->fh); write_buffer_ptr lCache(new WriteCache()); lCache->fileName = path; lCache->buffer = newFileCache(true); lCache->ffi = *ffi; m_wrCacheMap[ffi->fh] = lCache; } { unique_lock guard(m_rdMutex); read_cache_map_t::iterator it; if(( it = m_rdCacheMap.find(path) ) != m_rdCacheMap.end()) { it->second->openCount++; } else { read_buffer_ptr lCache(new ReadCache()); lCache->fileName = path; lCache->openCount = 1; lCache->ffi = *ffi; lCache->buffer = newFileCache(false); m_rdCacheMap[path] = lCache; } m_rdJobQueue.push_front(PrefetchJob(path, 0, 512)); } return 0; } int BufferAgent::onWrite(std::string path, const std::string &buf, size_t size, off_t offset, ffi_type ffi) { unique_lock guard(m_wrMutex); write_buffer_ptr wrapper = m_wrCacheMap[ffi->fh]; guard.unlock(); { if(wrapper->buffer->byteSize() > 1024 * 1024 * 64) { if(int fRet = onFlush(path, ffi)) { return fRet; } } if(wrapper->buffer->byteSize() > 1024 * 1024 * 64) { return doWrite(path, buf, size, offset, ffi); } wrapper->buffer->writeData(offset, buf); } unique_lock buffGuard(wrapper->mutex); guard.lock(); if(!wrapper->opPending) { wrapper->opPending = true; m_wrJobQueue.push_back(ffi->fh); m_wrCond.notify_one(); } return size; } int BufferAgent::onRead(std::string path, std::string &buf, size_t size, off_t offset, ffi_type ffi) { unique_lock guard(m_rdMutex); read_buffer_ptr wrapper = m_rdCacheMap[path]; guard.unlock(); wrapper->buffer->readData(offset, size, buf); if(buf.size() < size) { string buf2; int ret = doRead(path, buf2, buf.size() - size, offset + buf.size(), &wrapper->ffi); if(ret < 0) return ret; buf += buf2; { unique_lock buffGuard(wrapper->mutex); wrapper->blockSize = std::min((size_t) 1024 * 1024, (size_t) std::max(size, 2*wrapper->blockSize)); } guard.lock(); m_rdJobQueue.push_back(PrefetchJob(wrapper->fileName, buf.size(), wrapper->blockSize)); guard.unlock(); } else { string tmp; size_t prefSize = std::max(2*size, wrapper->blockSize); wrapper->buffer->readData(offset + size, prefSize, tmp); if(tmp.size() != prefSize) { guard.lock(); m_rdJobQueue.push_back(PrefetchJob(wrapper->fileName, offset + size + tmp.size(), wrapper->blockSize)); m_rdJobQueue.push_back(PrefetchJob(wrapper->fileName, offset + size + tmp.size() + wrapper->blockSize, wrapper->blockSize)); guard.unlock(); } } return buf.size(); } int BufferAgent::onFlush(std::string path, ffi_type ffi) { unique_lock guard(m_wrMutex); write_buffer_ptr wrapper = m_wrCacheMap[ffi->fh]; guard.unlock(); unique_lock sendGuard(wrapper->sendMutex); unique_lock buff_guard(wrapper->mutex); while(wrapper->buffer->blockCount() > 0) { block_ptr block = wrapper->buffer->removeOldestBlock(); uint64_t start = utils::mtime<uint64_t>(); int res = doWrite(wrapper->fileName, block->data, block->data.size(), block->offset, &wrapper->ffi); uint64_t end = utils::mtime<uint64_t>(); LOG(INFO) << "Roundtrip: " << (end - start) << " for " << block->data.size() << " bytes"; if(res < 0) { while(wrapper->buffer->blockCount() > 0) { (void) wrapper->buffer->removeOldestBlock(); } return res; } } guard.lock(); m_wrJobQueue.remove(ffi->fh); return 0; } int BufferAgent::onRelease(std::string path, ffi_type ffi) { { unique_lock guard(m_wrMutex); m_wrCacheMap.erase(ffi->fh); m_wrJobQueue.remove(ffi->fh); } { unique_lock guard(m_rdMutex); read_cache_map_t::iterator it; if(( it = m_rdCacheMap.find(path) ) != m_rdCacheMap.end()) { it->second->openCount--; if(it->second->openCount <= 0) { m_rdCacheMap.erase(it); } } } return 0; } void BufferAgent::agentStart(int worker_count) { m_workers.clear(); m_agentActive = true; while(worker_count--) { m_workers.push_back(shared_ptr<thread>(new thread(bind(&BufferAgent::writerLoop, this)))); m_workers.push_back(shared_ptr<thread>(new thread(bind(&BufferAgent::readerLoop, this)))); } } void BufferAgent::agentStop() { m_agentActive = false; m_wrCond.notify_all(); m_rdCond.notify_all(); while(m_workers.size() > 0) { m_workers.back()->join(); m_workers.pop_back(); } } void BufferAgent::readerLoop() { unique_lock guard(m_rdMutex); while(m_agentActive) { while(m_rdJobQueue.empty() && m_agentActive) m_rdCond.wait(guard); if(!m_agentActive) return; PrefetchJob job = m_rdJobQueue.front(); read_buffer_ptr wrapper = m_rdCacheMap[job.fileName]; m_rdJobQueue.pop_front(); m_rdCond.notify_one(); if(!wrapper) continue; guard.unlock(); { string buff; int ret = doRead(wrapper->fileName, buff, job.size, job.offset, &wrapper->ffi); if(ret > 0 && buff.size() >= ret) { wrapper->buffer->writeData(job.offset, buff); } } } } void BufferAgent::writerLoop() { unique_lock guard(m_wrMutex); while(m_agentActive) { while(m_wrJobQueue.empty() && m_agentActive) m_wrCond.wait(guard); if(!m_agentActive) return; fd_type file = m_wrJobQueue.front(); write_buffer_ptr wrapper = m_wrCacheMap[file]; m_wrJobQueue.pop_front(); m_wrCond.notify_one(); if(!wrapper) continue; guard.unlock(); { unique_lock sendGuard(wrapper->sendMutex); block_ptr block; { unique_lock buff_guard(wrapper->mutex); block = wrapper->buffer->removeOldestBlock(); } if(block) { uint64_t start = utils::mtime<uint64_t>(); int res = doWrite(wrapper->fileName, block->data, block->data.size(), block->offset, &wrapper->ffi); uint64_t end = utils::mtime<uint64_t>(); LOG(INFO) << "Roundtrip: " << (end - start) << " for " << block->data.size() << " bytes"; wrapper->cond.notify_all(); } { unique_lock buff_guard(wrapper->mutex); guard.lock(); if(wrapper->buffer->blockCount() > 0) { m_wrJobQueue.push_back(file); } else { wrapper->opPending = false; } } } wrapper->cond.notify_all(); } } boost::shared_ptr<FileCache> BufferAgent::newFileCache(bool isBuffer) { return boost::shared_ptr<FileCache>(new FileCache(10 * 1024 * 1024, isBuffer)); } } // namespace helpers } // namespace veil <|endoftext|>
<commit_before> // Statistics.cpp #include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules #include "StatisticsManager.h" bool StatisticsManager::SatisfiesPrerequisite(const CustomStatistic a_Stat) const { switch (a_Stat) { case CustomStatistic::AchMineWood: return IsStatisticPresent(CustomStatistic::AchOpenInventory); case CustomStatistic::AchBuildWorkBench: return IsStatisticPresent(CustomStatistic::AchMineWood); case CustomStatistic::AchBuildHoe: return IsStatisticPresent(CustomStatistic::AchBuildWorkBench); case CustomStatistic::AchBakeCake: return IsStatisticPresent(CustomStatistic::AchBuildHoe); case CustomStatistic::AchMakeBread: return IsStatisticPresent(CustomStatistic::AchBuildHoe); case CustomStatistic::AchBuildSword: return IsStatisticPresent(CustomStatistic::AchBuildWorkBench); case CustomStatistic::AchKillCow: return IsStatisticPresent(CustomStatistic::AchBuildSword); case CustomStatistic::AchFlyPig: return IsStatisticPresent(CustomStatistic::AchKillCow); case CustomStatistic::AchBreedCow: return IsStatisticPresent(CustomStatistic::AchKillCow); case CustomStatistic::AchKillEnemy: return IsStatisticPresent(CustomStatistic::AchBuildSword); case CustomStatistic::AchSnipeSkeleton: return IsStatisticPresent(CustomStatistic::AchKillEnemy); case CustomStatistic::AchBuildPickaxe: return IsStatisticPresent(CustomStatistic::AchBuildWorkBench); case CustomStatistic::AchBuildBetterPickaxe: return IsStatisticPresent(CustomStatistic::AchBuildPickaxe); case CustomStatistic::AchBuildFurnace: return IsStatisticPresent(CustomStatistic::AchBuildWorkBench); case CustomStatistic::AchCookFish: return IsStatisticPresent(CustomStatistic::AchBuildFurnace); case CustomStatistic::AchAcquireIron: return IsStatisticPresent(CustomStatistic::AchBuildFurnace); case CustomStatistic::AchOnARail: return IsStatisticPresent(CustomStatistic::AchAcquireIron); case CustomStatistic::AchDiamonds: return IsStatisticPresent(CustomStatistic::AchAcquireIron); case CustomStatistic::AchPortal: return IsStatisticPresent(CustomStatistic::AchDiamonds); case CustomStatistic::AchGhast: return IsStatisticPresent(CustomStatistic::AchPortal); case CustomStatistic::AchBlazeRod: return IsStatisticPresent(CustomStatistic::AchPortal); case CustomStatistic::AchPotion: return IsStatisticPresent(CustomStatistic::AchBlazeRod); case CustomStatistic::AchTheEnd: return IsStatisticPresent(CustomStatistic::AchBlazeRod); case CustomStatistic::AchTheEnd2: return IsStatisticPresent(CustomStatistic::AchTheEnd); case CustomStatistic::AchEnchantments: return IsStatisticPresent(CustomStatistic::AchDiamonds); case CustomStatistic::AchOverkill: return IsStatisticPresent(CustomStatistic::AchEnchantments); case CustomStatistic::AchBookcase: return IsStatisticPresent(CustomStatistic::AchEnchantments); case CustomStatistic::AchExploreAllBiomes: return IsStatisticPresent(CustomStatistic::AchTheEnd); case CustomStatistic::AchSpawnWither: return IsStatisticPresent(CustomStatistic::AchTheEnd2); case CustomStatistic::AchKillWither: return IsStatisticPresent(CustomStatistic::AchSpawnWither); case CustomStatistic::AchFullBeacon: return IsStatisticPresent(CustomStatistic::AchKillWither); case CustomStatistic::AchDiamondsToYou: return IsStatisticPresent(CustomStatistic::AchDiamonds); default: UNREACHABLE("Unsupported achievement type"); } } bool StatisticsManager::IsStatisticPresent(const CustomStatistic a_Stat) const { const auto Result = Custom.find(a_Stat); if (Result != Custom.end()) { return Result->second > 0; } return false; } <commit_msg>fixed open inventory crash (#5233)<commit_after> // Statistics.cpp #include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules #include "StatisticsManager.h" bool StatisticsManager::SatisfiesPrerequisite(const CustomStatistic a_Stat) const { switch (a_Stat) { case CustomStatistic::AchOpenInventory: return true; case CustomStatistic::AchMineWood: return IsStatisticPresent(CustomStatistic::AchOpenInventory); case CustomStatistic::AchBuildWorkBench: return IsStatisticPresent(CustomStatistic::AchMineWood); case CustomStatistic::AchBuildHoe: return IsStatisticPresent(CustomStatistic::AchBuildWorkBench); case CustomStatistic::AchBakeCake: return IsStatisticPresent(CustomStatistic::AchBuildHoe); case CustomStatistic::AchMakeBread: return IsStatisticPresent(CustomStatistic::AchBuildHoe); case CustomStatistic::AchBuildSword: return IsStatisticPresent(CustomStatistic::AchBuildWorkBench); case CustomStatistic::AchKillCow: return IsStatisticPresent(CustomStatistic::AchBuildSword); case CustomStatistic::AchFlyPig: return IsStatisticPresent(CustomStatistic::AchKillCow); case CustomStatistic::AchBreedCow: return IsStatisticPresent(CustomStatistic::AchKillCow); case CustomStatistic::AchKillEnemy: return IsStatisticPresent(CustomStatistic::AchBuildSword); case CustomStatistic::AchSnipeSkeleton: return IsStatisticPresent(CustomStatistic::AchKillEnemy); case CustomStatistic::AchBuildPickaxe: return IsStatisticPresent(CustomStatistic::AchBuildWorkBench); case CustomStatistic::AchBuildBetterPickaxe: return IsStatisticPresent(CustomStatistic::AchBuildPickaxe); case CustomStatistic::AchBuildFurnace: return IsStatisticPresent(CustomStatistic::AchBuildWorkBench); case CustomStatistic::AchCookFish: return IsStatisticPresent(CustomStatistic::AchBuildFurnace); case CustomStatistic::AchAcquireIron: return IsStatisticPresent(CustomStatistic::AchBuildFurnace); case CustomStatistic::AchOnARail: return IsStatisticPresent(CustomStatistic::AchAcquireIron); case CustomStatistic::AchDiamonds: return IsStatisticPresent(CustomStatistic::AchAcquireIron); case CustomStatistic::AchPortal: return IsStatisticPresent(CustomStatistic::AchDiamonds); case CustomStatistic::AchGhast: return IsStatisticPresent(CustomStatistic::AchPortal); case CustomStatistic::AchBlazeRod: return IsStatisticPresent(CustomStatistic::AchPortal); case CustomStatistic::AchPotion: return IsStatisticPresent(CustomStatistic::AchBlazeRod); case CustomStatistic::AchTheEnd: return IsStatisticPresent(CustomStatistic::AchBlazeRod); case CustomStatistic::AchTheEnd2: return IsStatisticPresent(CustomStatistic::AchTheEnd); case CustomStatistic::AchEnchantments: return IsStatisticPresent(CustomStatistic::AchDiamonds); case CustomStatistic::AchOverkill: return IsStatisticPresent(CustomStatistic::AchEnchantments); case CustomStatistic::AchBookcase: return IsStatisticPresent(CustomStatistic::AchEnchantments); case CustomStatistic::AchExploreAllBiomes: return IsStatisticPresent(CustomStatistic::AchTheEnd); case CustomStatistic::AchSpawnWither: return IsStatisticPresent(CustomStatistic::AchTheEnd2); case CustomStatistic::AchKillWither: return IsStatisticPresent(CustomStatistic::AchSpawnWither); case CustomStatistic::AchFullBeacon: return IsStatisticPresent(CustomStatistic::AchKillWither); case CustomStatistic::AchDiamondsToYou: return IsStatisticPresent(CustomStatistic::AchDiamonds); default: UNREACHABLE("Unsupported achievement type"); } } bool StatisticsManager::IsStatisticPresent(const CustomStatistic a_Stat) const { const auto Result = Custom.find(a_Stat); if (Result != Custom.end()) { return Result->second > 0; } return false; } <|endoftext|>
<commit_before>#include <Display.h> #include <Surface.h> #include <math.h> #include "TextField.h" #ifdef ANDROID #include <android/log.h> #endif namespace nme { // --- Stage --------------------------------------------------------------- // Helper class.... class AutoStageRender { Surface *mSurface; Stage *mToFlip; RenderTarget mTarget; public: AutoStageRender(Stage *inStage,int inRGB) { mSurface = inStage->GetPrimarySurface(); mToFlip = inStage; mTarget = mSurface->BeginRender( Rect(mSurface->Width(),mSurface->Height()),false ); mSurface->Clear( (inRGB | 0xff000000) & inStage->getBackgroundMask() ); } int Width() const { return mSurface->Width(); } int Height() const { return mSurface->Height(); } ~AutoStageRender() { mSurface->EndRender(); mToFlip->Flip(); } const RenderTarget &Target() { return mTarget; } }; Stage *Stage::gCurrentStage = 0; Stage::Stage(bool inInitRef) : DisplayObjectContainer(inInitRef) { gCurrentStage = this; mHandler = 0; mHandlerData = 0; opaqueBackground = 0xffffffff; mFocusObject = 0; mMouseDownObject = 0; mSimpleButton = 0; focusRect = true; mLastMousePos = UserPoint(0,0); scaleMode = ssmShowAll; mNominalWidth = 100; mNominalHeight = 100; mNextWake = 0.0; displayState = sdsNormal; align = saTopLeft; #if defined(IPHONE) || defined(ANDROID) || defined(WEBOS) || defined(TIZEN) quality = sqLow; #else quality = sqBest; #endif } Stage::~Stage() { if (gCurrentStage==this) gCurrentStage = 0; if (mFocusObject) mFocusObject->DecRef(); if (mMouseDownObject) mMouseDownObject->DecRef(); } void Stage::SetNextWakeDelay(double inNextWake) { mNextWake = inNextWake + GetTimeStamp(); } void Stage::SetFocusObject(DisplayObject *inObj,FocusSource inSource,int inKey) { if (inObj==mFocusObject) return; if (mHandler) { Event focus(etFocus); focus.id = inObj ? inObj->id : 0; focus.value = inSource; focus.code = inKey; mHandler(focus,mHandlerData); if (inSource!=fsProgram && focus.result==erCancel) return; } if (!inObj || inObj->getStage()!=this) { if (mFocusObject) { mFocusObject->Unfocus(); mFocusObject->DecRef(); } mFocusObject = 0; } else { inObj->IncRef(); if (mFocusObject) { mFocusObject->Unfocus(); mFocusObject->DecRef(); } mFocusObject = inObj; inObj->Focus(); } } void Stage::SetNominalSize(int inWidth, int inHeight) { mNominalWidth = inWidth; mNominalHeight = inHeight; CalcStageScaling( getStageWidth(), getStageHeight() ); } void Stage::SetEventHandler(EventHandler inHander,void *inUserData) { mHandler = inHander; mHandlerData = inUserData; } void Stage::HandleEvent(Event &inEvent) { gCurrentStage = this; DisplayObject *hit_obj = 0; bool primary = inEvent.flags & efPrimaryTouch; if ( (inEvent.type==etMouseMove || inEvent.type==etMouseDown || inEvent.type==etTouchBegin || inEvent.type==etTouchMove ) && primary ) mLastMousePos = UserPoint(inEvent.x, inEvent.y); if (mMouseDownObject && primary) { switch(inEvent.type) { case etTouchMove: case etMouseMove: if (inEvent.flags & efLeftDown) { mMouseDownObject->Drag(inEvent); break; } // fallthrough case etMouseClick: case etMouseDown: case etMouseUp: case etTouchBegin: case etTouchTap: case etTouchEnd: mMouseDownObject->EndDrag(inEvent); mMouseDownObject->DecRef(); mMouseDownObject = 0; break; default: break; } } if (inEvent.type==etKeyDown || inEvent.type==etKeyUp) { inEvent.id = mFocusObject ? mFocusObject->id : id; if (mHandler) mHandler(inEvent,mHandlerData); if (inEvent.result==0 && mFocusObject) mFocusObject->OnKey(inEvent); #ifdef ANDROID // Non-cancelled back key ... if (inEvent.result==0 && inEvent.value==27 && inEvent.type == etKeyUp) { StopAnimation(); } #endif return; } if (inEvent.type==etResize) { CalcStageScaling( inEvent.x, inEvent.y); } if (inEvent.type==etMouseMove || inEvent.type==etMouseDown || inEvent.type==etMouseUp || inEvent.type==etMouseClick || inEvent.type==etTouchBegin || inEvent.type==etTouchEnd || inEvent.type==etTouchMove || inEvent.type==etTouchTap ) { UserPoint pixels(inEvent.x,inEvent.y); hit_obj = HitTest(pixels); //if (inEvent.type!=etTouchMove) //ELOG(" type=%d %d,%d obj=%p (%S)", inEvent.type, inEvent.x, inEvent.y, hit_obj, hit_obj?hit_obj->name.c_str():L"(none)"); SimpleButton *but = hit_obj ? dynamic_cast<SimpleButton *>(hit_obj) : 0; inEvent.id = hit_obj ? hit_obj->id : id; Cursor cur = hit_obj ? hit_obj->GetCursor() : curPointer; if (mSimpleButton && (inEvent.flags & efLeftDown) ) { // Don't change simple button if dragging ... } else if (but!=mSimpleButton) { if (but) but->IncRef(); if (mSimpleButton) { SimpleButton *s = mSimpleButton; mSimpleButton = 0; s->setMouseState(SimpleButton::stateUp); s->DecRef(); } mSimpleButton = but; } if (mSimpleButton) { bool over = but==mSimpleButton; bool down = (inEvent.flags & efLeftDown); mSimpleButton->setMouseState( over ? ( down ? SimpleButton::stateDown : SimpleButton::stateOver) : SimpleButton::stateUp ); if (!down && !over) { SimpleButton *s = mSimpleButton; mSimpleButton = 0; s->DecRef(); } else if (mSimpleButton->getUseHandCursor()) cur = curHand; } SetCursor( (gMouseShowCursor || cur>=curTextSelect0) ? cur : curNone ); UserPoint stage = mStageScale.ApplyInverse(pixels); inEvent.x = stage.x; inEvent.y = stage.y; } if (hit_obj) hit_obj->IncRef(); if (mHandler) mHandler(inEvent,mHandlerData); if (hit_obj) { if ( (inEvent.type==etMouseDown || (inEvent.type==etTouchBegin && (inEvent.flags & efPrimaryTouch) )) && inEvent.result!=erCancel ) { if (hit_obj->WantsFocus()) SetFocusObject(hit_obj,fsMouse); #if defined(IPHONE) || defined(ANDROID) || defined(WEBOS) || defined(TIZEN) else { EnablePopupKeyboard(false); SetFocusObject(0,fsMouse); } #endif } if (inEvent.type==etMouseDown || (inEvent.type==etTouchBegin && primary) ) { if (hit_obj->CaptureDown(inEvent)) { hit_obj->IncRef(); mMouseDownObject = hit_obj; } } if (inEvent.type==etMouseUp && (inEvent.value==3 || inEvent.value==4) ) { TextField *text = dynamic_cast<TextField *>(hit_obj); if (text && text->mouseWheelEnabled) text->OnScrollWheel(inEvent.value==3 ? -1 : 1); } } #if defined(IPHONE) || defined(ANDROID) || defined(WEBOS) || defined(TIZEN) else if (inEvent.type==etMouseClick || inEvent.type==etMouseDown || (inEvent.type==etTouchBegin && (inEvent.flags & efPrimaryTouch) )) { EnablePopupKeyboard(false); SetFocusObject(0); } #endif if (hit_obj) hit_obj->DecRef(); } void Stage::setOpaqueBackground(uint32 inBG) { opaqueBackground = inBG | 0xff000000; DirtyCache(); } void Stage::RemovingFromStage(DisplayObject *inObject) { DisplayObject *b = mSimpleButton; while(b) { if (b==inObject) { mSimpleButton->DecRef(); mSimpleButton = 0; break; } b = b->getParent(); } DisplayObject *f = mFocusObject; while(f) { if (f==inObject) { mFocusObject->DecRef(); mFocusObject = 0; break; } f = f->getParent(); } DisplayObject *m = mMouseDownObject; while(m) { if (m==inObject) { mMouseDownObject->DecRef(); mMouseDownObject = 0; break; } m = m->getParent(); } } void Stage::CalcStageScaling(double inNewWidth,double inNewHeight) { double StageScaleX=1; double StageScaleY=1; double StageOX=0; double StageOY=0; if (inNewWidth<=0 || inNewHeight<=0) return; if (scaleMode!=ssmNoScale) { StageScaleX = inNewWidth/(double)mNominalWidth; StageScaleY = inNewHeight/(double)mNominalHeight; if (scaleMode==ssmNoBorder) { if (StageScaleX>StageScaleY) StageScaleY = StageScaleX; else StageScaleX = StageScaleY; } else if (scaleMode==ssmShowAll) { if (StageScaleX<StageScaleY) StageScaleY = StageScaleX; else StageScaleX = StageScaleY; } } double extra_x = inNewWidth-StageScaleX*mNominalWidth; double extra_y = inNewHeight-StageScaleY*mNominalHeight; switch(align) { case saTopLeft: break; case saLeft: break; case saBottomLeft: break; case saTopRight: case saRight: case saBottomRight: StageOX = -extra_y; break; case saTop: case saBottom: StageOX = -extra_x/2; break; } switch(align) { case saTopLeft: break; case saTopRight: break; case saTop: break; case saBottomRight: case saBottomLeft: case saBottom: StageOY = -extra_y; break; case saLeft: case saRight: StageOY = -extra_y/2; break; } DirtyCache(); mStageScale.m00 = StageScaleX; mStageScale.m11 = StageScaleY; mStageScale.mtx = StageOX; mStageScale.mty = StageOY; } bool Stage::FinishEditOnEnter() { if (mFocusObject && mFocusObject!=this) return mFocusObject->FinishEditOnEnter(); return false; } int Stage::GetAA() { switch(quality) { case sqLow: return 1; case sqMedium: return 2; case sqHigh: case sqBest: return 4; } return 1; } void Stage::BeginRenderStage(bool inClear) { Surface *surface = GetPrimarySurface(); currentTarget = surface->BeginRender( Rect(surface->Width(),surface->Height()),false ); if (inClear) surface->Clear( (opaqueBackground | 0xff000000) & getBackgroundMask() ); } void Stage::RenderStage() { ColorTransform::TidyCache(); if (currentTarget.IsHardware()) currentTarget.mHardware->SetQuality(quality); RenderState state(0, GetAA() ); state.mTransform.mMatrix = &mStageScale; state.mClipRect = Rect( currentTarget.Width(), currentTarget.Height() ); state.mPhase = rpBitmap; state.mRoundSizeToPOW2 = currentTarget.IsHardware(); Render(currentTarget,state); state.mPhase = rpRender; Render(currentTarget,state); } void Stage::EndRenderStage() { currentTarget = RenderTarget(); GetPrimarySurface()->EndRender(); ClearCacheDirty(); Flip(); } bool Stage::BuildCache() { Surface *surface = GetPrimarySurface(); RenderState state(surface, GetAA() ); state.mTransform.mMatrix = &mStageScale; bool wasDirty = false; state.mWasDirtyPtr = &wasDirty; state.mPhase = rpBitmap; RenderTarget target(state.mClipRect, surface->GetHardwareRenderer()); state.mRoundSizeToPOW2 = surface->GetHardwareRenderer(); Render(target,state); return wasDirty; } double Stage::getStageWidth() { Surface *s = GetPrimarySurface(); if (!s) return 0; return s->Width(); } double Stage::getStageHeight() { Surface *s = GetPrimarySurface(); if (!s) return 0; return s->Height(); } void Stage::setScaleMode(int inMode) { scaleMode = (StageScaleMode)inMode; CalcStageScaling( getStageWidth(), getStageHeight() ); } void Stage::setAlign(int inAlign) { align = (StageAlign)inAlign; CalcStageScaling( getStageWidth(), getStageHeight() ); } void Stage::setQuality(int inQuality) { quality = (StageQuality)inQuality; DirtyCache(); } void Stage::setDisplayState(int inDisplayState) { displayState = (StageDisplayState)inDisplayState; SetFullscreen(inDisplayState>0); } Matrix Stage::GetFullMatrix(bool inStageScaling) { if (!inStageScaling) return DisplayObject::GetFullMatrix(false); return mStageScale.Mult(GetLocalMatrix()); } DisplayObject *Stage::HitTest(UserPoint inStage,DisplayObject *inRoot,bool inRecurse) { Surface *surface = GetPrimarySurface(); RenderTarget target = surface->BeginRender( Rect(surface->Width(),surface->Height()),true ); RenderState state(0, GetAA() ); state.mClipRect = Rect( inStage.x, inStage.y, 1, 1 ); Matrix m = mStageScale; if (inRoot) m = inRoot->GetFullMatrix(true); state.mTransform.mMatrix = &m; state.mRoundSizeToPOW2 = target.IsHardware(); state.mPhase = rpHitTest; state.mRecurse = inRecurse; (inRoot ? inRoot : this) -> Render(target,state); surface->EndRender(); // ELOG("Stage hit %f,%f -> %p\n", inStage.x, inStage.y, state.mHitResult ); return state.mHitResult; } } // end namespace nme <commit_msg>Update Stage.cpp<commit_after>#include <Display.h> #include <Surface.h> #include <math.h> #include "TextField.h" #ifdef ANDROID #include <android/log.h> #endif namespace nme { // --- Stage --------------------------------------------------------------- // Helper class.... class AutoStageRender { Surface *mSurface; Stage *mToFlip; RenderTarget mTarget; public: AutoStageRender(Stage *inStage,int inRGB) { mSurface = inStage->GetPrimarySurface(); mToFlip = inStage; mTarget = mSurface->BeginRender( Rect(mSurface->Width(),mSurface->Height()),false ); mSurface->Clear( (inRGB | 0xff000000) & inStage->getBackgroundMask() ); } int Width() const { return mSurface->Width(); } int Height() const { return mSurface->Height(); } ~AutoStageRender() { mSurface->EndRender(); mToFlip->Flip(); } const RenderTarget &Target() { return mTarget; } }; Stage *Stage::gCurrentStage = 0; Stage::Stage(bool inInitRef) : DisplayObjectContainer(inInitRef) { gCurrentStage = this; mHandler = 0; mHandlerData = 0; opaqueBackground = 0xffffffff; mFocusObject = 0; mMouseDownObject = 0; mSimpleButton = 0; focusRect = true; mLastMousePos = UserPoint(0,0); scaleMode = ssmShowAll; mNominalWidth = 100; mNominalHeight = 100; mNextWake = 0.0; displayState = sdsNormal; align = saTopLeft; #if defined(IPHONE) || defined(ANDROID) || defined(WEBOS) || defined(TIZEN) quality = sqLow; #else quality = sqBest; #endif } Stage::~Stage() { if (gCurrentStage==this) gCurrentStage = 0; if (mFocusObject) mFocusObject->DecRef(); if (mMouseDownObject) mMouseDownObject->DecRef(); } void Stage::SetNextWakeDelay(double inNextWake) { mNextWake = inNextWake + GetTimeStamp(); } void Stage::SetFocusObject(DisplayObject *inObj,FocusSource inSource,int inKey) { if (inObj==mFocusObject) return; if (mHandler) { Event focus(etFocus); focus.id = inObj ? inObj->id : 0; focus.value = inSource; focus.code = inKey; mHandler(focus,mHandlerData); if (inSource!=fsProgram && focus.result==erCancel) return; } if (!inObj || inObj->getStage()!=this) { if (mFocusObject) { mFocusObject->Unfocus(); mFocusObject->DecRef(); } mFocusObject = 0; } else { inObj->IncRef(); if (mFocusObject) { mFocusObject->Unfocus(); mFocusObject->DecRef(); } mFocusObject = inObj; inObj->Focus(); } } void Stage::SetNominalSize(int inWidth, int inHeight) { mNominalWidth = inWidth; mNominalHeight = inHeight; CalcStageScaling( getStageWidth(), getStageHeight() ); } void Stage::SetEventHandler(EventHandler inHander,void *inUserData) { mHandler = inHander; mHandlerData = inUserData; } void Stage::HandleEvent(Event &inEvent) { gCurrentStage = this; DisplayObject *hit_obj = 0; bool primary = inEvent.flags & efPrimaryTouch; if ( (inEvent.type==etMouseMove || inEvent.type==etMouseDown || inEvent.type==etTouchBegin || inEvent.type==etTouchMove ) && primary ) mLastMousePos = UserPoint(inEvent.x, inEvent.y); if (mMouseDownObject && primary) { switch(inEvent.type) { case etTouchMove: case etMouseMove: if (inEvent.flags & efLeftDown) { mMouseDownObject->Drag(inEvent); break; } // fallthrough case etMouseClick: case etMouseDown: case etMouseUp: case etTouchBegin: case etTouchTap: case etTouchEnd: mMouseDownObject->EndDrag(inEvent); mMouseDownObject->DecRef(); mMouseDownObject = 0; break; default: break; } } if (inEvent.type==etKeyDown || inEvent.type==etKeyUp || inEvent.type==etChar) { inEvent.id = mFocusObject ? mFocusObject->id : id; if (mHandler) mHandler(inEvent,mHandlerData); if (inEvent.result==0 && mFocusObject) mFocusObject->OnKey(inEvent); #ifdef ANDROID // Non-cancelled back key ... if (inEvent.result==0 && inEvent.value==27 && inEvent.type == etKeyUp) { StopAnimation(); } #endif return; } if (inEvent.type==etResize) { CalcStageScaling( inEvent.x, inEvent.y); } if (inEvent.type==etMouseMove || inEvent.type==etMouseDown || inEvent.type==etMouseUp || inEvent.type==etMouseClick || inEvent.type==etTouchBegin || inEvent.type==etTouchEnd || inEvent.type==etTouchMove || inEvent.type==etTouchTap ) { UserPoint pixels(inEvent.x,inEvent.y); hit_obj = HitTest(pixels); //if (inEvent.type!=etTouchMove) //ELOG(" type=%d %d,%d obj=%p (%S)", inEvent.type, inEvent.x, inEvent.y, hit_obj, hit_obj?hit_obj->name.c_str():L"(none)"); SimpleButton *but = hit_obj ? dynamic_cast<SimpleButton *>(hit_obj) : 0; inEvent.id = hit_obj ? hit_obj->id : id; Cursor cur = hit_obj ? hit_obj->GetCursor() : curPointer; if (mSimpleButton && (inEvent.flags & efLeftDown) ) { // Don't change simple button if dragging ... } else if (but!=mSimpleButton) { if (but) but->IncRef(); if (mSimpleButton) { SimpleButton *s = mSimpleButton; mSimpleButton = 0; s->setMouseState(SimpleButton::stateUp); s->DecRef(); } mSimpleButton = but; } if (mSimpleButton) { bool over = but==mSimpleButton; bool down = (inEvent.flags & efLeftDown); mSimpleButton->setMouseState( over ? ( down ? SimpleButton::stateDown : SimpleButton::stateOver) : SimpleButton::stateUp ); if (!down && !over) { SimpleButton *s = mSimpleButton; mSimpleButton = 0; s->DecRef(); } else if (mSimpleButton->getUseHandCursor()) cur = curHand; } SetCursor( (gMouseShowCursor || cur>=curTextSelect0) ? cur : curNone ); UserPoint stage = mStageScale.ApplyInverse(pixels); inEvent.x = stage.x; inEvent.y = stage.y; } if (hit_obj) hit_obj->IncRef(); if (mHandler) mHandler(inEvent,mHandlerData); if (hit_obj) { if ( (inEvent.type==etMouseDown || (inEvent.type==etTouchBegin && (inEvent.flags & efPrimaryTouch) )) && inEvent.result!=erCancel ) { if (hit_obj->WantsFocus()) SetFocusObject(hit_obj,fsMouse); #if defined(IPHONE) || defined(ANDROID) || defined(WEBOS) || defined(TIZEN) else { EnablePopupKeyboard(false); SetFocusObject(0,fsMouse); } #endif } if (inEvent.type==etMouseDown || (inEvent.type==etTouchBegin && primary) ) { if (hit_obj->CaptureDown(inEvent)) { hit_obj->IncRef(); mMouseDownObject = hit_obj; } } if (inEvent.type==etMouseUp && (inEvent.value==3 || inEvent.value==4) ) { TextField *text = dynamic_cast<TextField *>(hit_obj); if (text && text->mouseWheelEnabled) text->OnScrollWheel(inEvent.value==3 ? -1 : 1); } } #if defined(IPHONE) || defined(ANDROID) || defined(WEBOS) || defined(TIZEN) else if (inEvent.type==etMouseClick || inEvent.type==etMouseDown || (inEvent.type==etTouchBegin && (inEvent.flags & efPrimaryTouch) )) { EnablePopupKeyboard(false); SetFocusObject(0); } #endif if (hit_obj) hit_obj->DecRef(); } void Stage::setOpaqueBackground(uint32 inBG) { opaqueBackground = inBG | 0xff000000; DirtyCache(); } void Stage::RemovingFromStage(DisplayObject *inObject) { DisplayObject *b = mSimpleButton; while(b) { if (b==inObject) { mSimpleButton->DecRef(); mSimpleButton = 0; break; } b = b->getParent(); } DisplayObject *f = mFocusObject; while(f) { if (f==inObject) { mFocusObject->DecRef(); mFocusObject = 0; break; } f = f->getParent(); } DisplayObject *m = mMouseDownObject; while(m) { if (m==inObject) { mMouseDownObject->DecRef(); mMouseDownObject = 0; break; } m = m->getParent(); } } void Stage::CalcStageScaling(double inNewWidth,double inNewHeight) { double StageScaleX=1; double StageScaleY=1; double StageOX=0; double StageOY=0; if (inNewWidth<=0 || inNewHeight<=0) return; if (scaleMode!=ssmNoScale) { StageScaleX = inNewWidth/(double)mNominalWidth; StageScaleY = inNewHeight/(double)mNominalHeight; if (scaleMode==ssmNoBorder) { if (StageScaleX>StageScaleY) StageScaleY = StageScaleX; else StageScaleX = StageScaleY; } else if (scaleMode==ssmShowAll) { if (StageScaleX<StageScaleY) StageScaleY = StageScaleX; else StageScaleX = StageScaleY; } } double extra_x = inNewWidth-StageScaleX*mNominalWidth; double extra_y = inNewHeight-StageScaleY*mNominalHeight; switch(align) { case saTopLeft: break; case saLeft: break; case saBottomLeft: break; case saTopRight: case saRight: case saBottomRight: StageOX = -extra_y; break; case saTop: case saBottom: StageOX = -extra_x/2; break; } switch(align) { case saTopLeft: break; case saTopRight: break; case saTop: break; case saBottomRight: case saBottomLeft: case saBottom: StageOY = -extra_y; break; case saLeft: case saRight: StageOY = -extra_y/2; break; } DirtyCache(); mStageScale.m00 = StageScaleX; mStageScale.m11 = StageScaleY; mStageScale.mtx = StageOX; mStageScale.mty = StageOY; } bool Stage::FinishEditOnEnter() { if (mFocusObject && mFocusObject!=this) return mFocusObject->FinishEditOnEnter(); return false; } int Stage::GetAA() { switch(quality) { case sqLow: return 1; case sqMedium: return 2; case sqHigh: case sqBest: return 4; } return 1; } void Stage::BeginRenderStage(bool inClear) { Surface *surface = GetPrimarySurface(); currentTarget = surface->BeginRender( Rect(surface->Width(),surface->Height()),false ); if (inClear) surface->Clear( (opaqueBackground | 0xff000000) & getBackgroundMask() ); } void Stage::RenderStage() { ColorTransform::TidyCache(); if (currentTarget.IsHardware()) currentTarget.mHardware->SetQuality(quality); RenderState state(0, GetAA() ); state.mTransform.mMatrix = &mStageScale; state.mClipRect = Rect( currentTarget.Width(), currentTarget.Height() ); state.mPhase = rpBitmap; state.mRoundSizeToPOW2 = currentTarget.IsHardware(); Render(currentTarget,state); state.mPhase = rpRender; Render(currentTarget,state); } void Stage::EndRenderStage() { currentTarget = RenderTarget(); GetPrimarySurface()->EndRender(); ClearCacheDirty(); Flip(); } bool Stage::BuildCache() { Surface *surface = GetPrimarySurface(); RenderState state(surface, GetAA() ); state.mTransform.mMatrix = &mStageScale; bool wasDirty = false; state.mWasDirtyPtr = &wasDirty; state.mPhase = rpBitmap; RenderTarget target(state.mClipRect, surface->GetHardwareRenderer()); state.mRoundSizeToPOW2 = surface->GetHardwareRenderer(); Render(target,state); return wasDirty; } double Stage::getStageWidth() { Surface *s = GetPrimarySurface(); if (!s) return 0; return s->Width(); } double Stage::getStageHeight() { Surface *s = GetPrimarySurface(); if (!s) return 0; return s->Height(); } void Stage::setScaleMode(int inMode) { scaleMode = (StageScaleMode)inMode; CalcStageScaling( getStageWidth(), getStageHeight() ); } void Stage::setAlign(int inAlign) { align = (StageAlign)inAlign; CalcStageScaling( getStageWidth(), getStageHeight() ); } void Stage::setQuality(int inQuality) { quality = (StageQuality)inQuality; DirtyCache(); } void Stage::setDisplayState(int inDisplayState) { displayState = (StageDisplayState)inDisplayState; SetFullscreen(inDisplayState>0); } Matrix Stage::GetFullMatrix(bool inStageScaling) { if (!inStageScaling) return DisplayObject::GetFullMatrix(false); return mStageScale.Mult(GetLocalMatrix()); } DisplayObject *Stage::HitTest(UserPoint inStage,DisplayObject *inRoot,bool inRecurse) { Surface *surface = GetPrimarySurface(); RenderTarget target = surface->BeginRender( Rect(surface->Width(),surface->Height()),true ); RenderState state(0, GetAA() ); state.mClipRect = Rect( inStage.x, inStage.y, 1, 1 ); Matrix m = mStageScale; if (inRoot) m = inRoot->GetFullMatrix(true); state.mTransform.mMatrix = &m; state.mRoundSizeToPOW2 = target.IsHardware(); state.mPhase = rpHitTest; state.mRecurse = inRecurse; (inRoot ? inRoot : this) -> Render(target,state); surface->EndRender(); // ELOG("Stage hit %f,%f -> %p\n", inStage.x, inStage.y, state.mHitResult ); return state.mHitResult; } } // end namespace nme <|endoftext|>
<commit_before>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2014 Preferred Networks and Nippon Telegraph and Telephone Corporation. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License version 2.1 as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "logger.hpp" #include <unistd.h> #include <sys/syscall.h> #include <sys/types.h> #include <stdlib.h> #include <string.h> #include <log4cxx/logger.h> #include <log4cxx/patternlayout.h> #include <log4cxx/consoleappender.h> #include <log4cxx/basicconfigurator.h> #include <log4cxx/xml/domconfigurator.h> #include <jubatus/util/lang/cast.h> #if defined(__FreeBSD__) #include <sys/thr.h> #endif #include <string> #define LOGGER_NAME "jubatus" namespace { inline int gettid() { #ifdef __APPLE__ return ::syscall(SYS_thread_selfid); #elif defined(__FreeBSD__) long lwpid; // NOLINT thr_self(&lwpid); return static_cast<int>(lwpid); #else return ::syscall(SYS_gettid); #endif } } // namespace using jubatus::util::lang::lexical_cast; namespace jubatus { namespace server { namespace common { namespace logger { namespace { inline const char* const_basename(const char* path) { const char* base = ::strrchr(path, '/'); return base ? (base + 1) : path; } } // namespace stream_logger::stream_logger( const log4cxx::LevelPtr& level, const char* file, int line, bool abort) : level_(level), file_(file), line_(line), abort_(abort), thread_id_(gettid()) {} stream_logger::~stream_logger() { log4cxx::MDC::put("tid", lexical_cast<std::string>(thread_id_)); log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger(LOGGER_NAME); if (logger->isEnabledFor(level_)) { logger->forcedLog( level_, buf_.str(), log4cxx::spi::LocationInfo(const_basename(file_), "", line_)); } if (abort_) { abort(); } } void setup_parameters(const char* progname, const char* host, int port) { ::setenv("JUBATUS_PID", lexical_cast<std::string>(::getpid()).c_str(), 1); ::setenv("JUBATUS_PROCESS", progname, 1); ::setenv("JUBATUS_HOST", host, 1); ::setenv("JUBATUS_PORT", lexical_cast<std::string>(port).c_str(), 1); } void configure() { log4cxx::LayoutPtr layout( new log4cxx::PatternLayout("%d %X{tid} %-5p [%F:%L] %m%n")); log4cxx::AppenderPtr appender(new log4cxx::ConsoleAppender(layout)); log4cxx::BasicConfigurator::configure(appender); } void configure(const std::string& config_file) { // Exception will not be thrown even if there is an error in config file. log4cxx::xml::DOMConfigurator::configure(config_file); } bool is_configured() { log4cxx::LoggerPtr rootLogger = log4cxx::Logger::getRootLogger(); return rootLogger->getAllAppenders().size() != 0; } } // namespace logger } // namespace common } // namespace server } // namespace jubatus <commit_msg>set default log level to INFO when config is not specified<commit_after>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2014 Preferred Networks and Nippon Telegraph and Telephone Corporation. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License version 2.1 as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "logger.hpp" #include <unistd.h> #include <sys/syscall.h> #include <sys/types.h> #include <stdlib.h> #include <string.h> #include <log4cxx/logger.h> #include <log4cxx/patternlayout.h> #include <log4cxx/consoleappender.h> #include <log4cxx/basicconfigurator.h> #include <log4cxx/xml/domconfigurator.h> #include <jubatus/util/lang/cast.h> #if defined(__FreeBSD__) #include <sys/thr.h> #endif #include <string> #define LOGGER_NAME "jubatus" namespace { inline int gettid() { #ifdef __APPLE__ return ::syscall(SYS_thread_selfid); #elif defined(__FreeBSD__) long lwpid; // NOLINT thr_self(&lwpid); return static_cast<int>(lwpid); #else return ::syscall(SYS_gettid); #endif } } // namespace using jubatus::util::lang::lexical_cast; namespace jubatus { namespace server { namespace common { namespace logger { namespace { inline const char* const_basename(const char* path) { const char* base = ::strrchr(path, '/'); return base ? (base + 1) : path; } } // namespace stream_logger::stream_logger( const log4cxx::LevelPtr& level, const char* file, int line, bool abort) : level_(level), file_(file), line_(line), abort_(abort), thread_id_(gettid()) {} stream_logger::~stream_logger() { log4cxx::MDC::put("tid", lexical_cast<std::string>(thread_id_)); log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger(LOGGER_NAME); if (logger->isEnabledFor(level_)) { logger->forcedLog( level_, buf_.str(), log4cxx::spi::LocationInfo(const_basename(file_), "", line_)); } if (abort_) { abort(); } } void setup_parameters(const char* progname, const char* host, int port) { ::setenv("JUBATUS_PID", lexical_cast<std::string>(::getpid()).c_str(), 1); ::setenv("JUBATUS_PROCESS", progname, 1); ::setenv("JUBATUS_HOST", host, 1); ::setenv("JUBATUS_PORT", lexical_cast<std::string>(port).c_str(), 1); } void configure() { log4cxx::LayoutPtr layout( new log4cxx::PatternLayout("%d %X{tid} %-5p [%F:%L] %m%n")); log4cxx::AppenderPtr appender(new log4cxx::ConsoleAppender(layout)); log4cxx::BasicConfigurator::configure(appender); log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger(LOGGER_NAME); logger->setLevel(log4cxx::Level::getInfo()); } void configure(const std::string& config_file) { // Exception will not be thrown even if there is an error in config file. log4cxx::xml::DOMConfigurator::configure(config_file); } bool is_configured() { log4cxx::LoggerPtr rootLogger = log4cxx::Logger::getRootLogger(); return rootLogger->getAllAppenders().size() != 0; } } // namespace logger } // namespace common } // namespace server } // namespace jubatus <|endoftext|>
<commit_before>/* * Copyright (C) 2018 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "resource_manager.hh" #include "manager.hh" #include "log.hh" #include <boost/range/algorithm/for_each.hpp> #include <boost/range/adaptor/map.hpp> #include "lister.hh" #include "disk-error-handler.hh" #include "seastarx.hh" namespace db { namespace hints { static logging::logger resource_manager_logger("hints_resource_manager"); future<dev_t> get_device_id(boost::filesystem::path path) { return open_directory(path.native()).then([](file f) { return f.stat().then([f = std::move(f)](struct stat st) { return st.st_dev; }); }); } future<bool> is_mountpoint(boost::filesystem::path path) { // Special case for '/', which is always a mount point if (path == path.parent_path()) { return make_ready_future<bool>(true); } return when_all(get_device_id(path.native()), get_device_id(path.parent_path().native())).then([](std::tuple<future<dev_t>, future<dev_t>> ids) { return std::get<0>(ids).get0() != std::get<1>(ids).get0(); }); } future<semaphore_units<semaphore_default_exception_factory>> resource_manager::get_send_units_for(size_t buf_size) { // Let's approximate the memory size the mutation is going to consume by the size of its serialized form size_t hint_memory_budget = std::max(_min_send_hint_budget, buf_size); // Allow a very big mutation to be sent out by consuming the whole shard budget hint_memory_budget = std::min(hint_memory_budget, _max_send_in_flight_memory); resource_manager_logger.trace("memory budget: need {} have {}", hint_memory_budget, _send_limiter.available_units()); return get_units(_send_limiter, hint_memory_budget); } const std::chrono::seconds space_watchdog::_watchdog_period = std::chrono::seconds(1); space_watchdog::space_watchdog(shard_managers_set& managers, per_device_limits_map& per_device_limits_map) : _shard_managers(managers) , _per_device_limits_map(per_device_limits_map) , _timer([this] { on_timer(); }) {} void space_watchdog::start() { _timer.arm(timer_clock_type::now()); } future<> space_watchdog::stop() noexcept { try { return _gate.close().finally([this] { _timer.cancel(); }); } catch (...) { return make_exception_future<>(std::current_exception()); } } future<> space_watchdog::scan_one_ep_dir(boost::filesystem::path path, manager& shard_manager, ep_key_type ep_key) { return lister::scan_dir(path, { directory_entry_type::regular }, [this, ep_key, &shard_manager] (lister::path dir, directory_entry de) { // Put the current end point ID to state.eps_with_pending_hints when we see the second hints file in its directory if (_files_count == 1) { shard_manager.add_ep_with_pending_hints(ep_key); } ++_files_count; return io_check(file_size, (dir / de.name.c_str()).c_str()).then([this] (uint64_t fsize) { _total_size += fsize; }); }); } void space_watchdog::on_timer() { with_gate(_gate, [this] { return futurize_apply([this] { _total_size = 0; return do_for_each(_shard_managers, [this] (manager& shard_manager) { shard_manager.clear_eps_with_pending_hints(); // The hints directories are organized as follows: // <hints root> // |- <shard1 ID> // | |- <EP1 address> // | |- <hints file1> // | |- <hints file2> // | |- ... // | |- <EP2 address> // | |- ... // | |-... // |- <shard2 ID> // | |- ... // ... // |- <shardN ID> // | |- ... // return lister::scan_dir(shard_manager.hints_dir(), {directory_entry_type::directory}, [this, &shard_manager] (lister::path dir, directory_entry de) { _files_count = 0; // Let's scan per-end-point directories and enumerate hints files... // // Let's check if there is a corresponding end point manager (may not exist if the corresponding DC is // not hintable). // If exists - let's take a file update lock so that files are not changed under our feet. Otherwise, simply // continue to enumeration - there is no one to change them. auto it = shard_manager.find_ep_manager(de.name); if (it != shard_manager.ep_managers_end()) { return with_lock(it->second.file_update_mutex(), [this, &shard_manager, dir = std::move(dir), ep_name = std::move(de.name)]() mutable { return scan_one_ep_dir(dir / ep_name.c_str(), shard_manager, ep_key_type(ep_name)); }); } else { return scan_one_ep_dir(dir / de.name.c_str(), shard_manager, ep_key_type(de.name)); } }); }).then([this] { return do_for_each(_per_device_limits_map, [this](per_device_limits_map::value_type& per_device_limits_entry) { space_watchdog::per_device_limits& per_device_limits = per_device_limits_entry.second; size_t adjusted_quota = 0; size_t delta = boost::accumulate(per_device_limits.managers, 0, [] (size_t sum, manager& shard_manager) { return sum + shard_manager.ep_managers_size() * resource_manager::hint_segment_size_in_mb * 1024 * 1024; }); if (per_device_limits.max_shard_disk_space_size > delta) { adjusted_quota = per_device_limits.max_shard_disk_space_size - delta; } bool can_hint = _total_size < adjusted_quota; resource_manager_logger.trace("space_watchdog: total_size ({}) {} max_shard_disk_space_size ({})", _total_size, can_hint ? "<" : ">=", adjusted_quota); if (!can_hint) { for (manager& shard_manager : per_device_limits.managers) { shard_manager.forbid_hints_for_eps_with_pending_hints(); } } else { for (manager& shard_manager : per_device_limits.managers) { shard_manager.allow_hints(); } } }); }); }).handle_exception([this] (auto eptr) { resource_manager_logger.trace("space_watchdog: unexpected exception - stop all hints generators"); // Stop all hint generators if space_watchdog callback failed for (manager& shard_manager : _shard_managers) { shard_manager.forbid_hints(); } }).finally([this] { _timer.arm(_watchdog_period); }); }); } future<> resource_manager::start(shared_ptr<service::storage_proxy> proxy_ptr, shared_ptr<gms::gossiper> gossiper_ptr, shared_ptr<service::storage_service> ss_ptr) { return parallel_for_each(_shard_managers, [proxy_ptr, gossiper_ptr, ss_ptr](manager& m) { return m.start(proxy_ptr, gossiper_ptr, ss_ptr); }).then([this]() { return prepare_per_device_limits(); }).then([this]() { return _space_watchdog.start(); }); } future<> resource_manager::stop() noexcept { return parallel_for_each(_shard_managers, [](manager& m) { return m.stop(); }).finally([this]() { return _space_watchdog.stop(); }); } void resource_manager::register_manager(manager& m) { _shard_managers.insert(m); } future<> resource_manager::prepare_per_device_limits() { return do_for_each(_shard_managers, [this] (manager& shard_manager) mutable { dev_t device_id = shard_manager.hints_dir_device_id(); auto it = _per_device_limits_map.find(device_id); if (it == _per_device_limits_map.end()) { return is_mountpoint(shard_manager.hints_dir().parent_path()).then([this, device_id, &shard_manager](bool is_mountpoint) { // By default, give each device 10% of the available disk space. Give each shard an equal share of the available space. size_t max_size = boost::filesystem::space(shard_manager.hints_dir().c_str()).capacity / (10 * smp::count); // If hints directory is a mountpoint, we assume it's on dedicated (i.e. not shared with data/commitlog/etc) storage. // Then, reserve 90% of all space instead of 10% above. if (is_mountpoint) { max_size *= 9; } _per_device_limits_map.emplace(device_id, space_watchdog::per_device_limits{{std::ref(shard_manager)}, max_size}); }); } else { it->second.managers.emplace_back(std::ref(shard_manager)); return make_ready_future<>(); } }); } } } <commit_msg>hints: amend a comment in device limits<commit_after>/* * Copyright (C) 2018 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "resource_manager.hh" #include "manager.hh" #include "log.hh" #include <boost/range/algorithm/for_each.hpp> #include <boost/range/adaptor/map.hpp> #include "lister.hh" #include "disk-error-handler.hh" #include "seastarx.hh" namespace db { namespace hints { static logging::logger resource_manager_logger("hints_resource_manager"); future<dev_t> get_device_id(boost::filesystem::path path) { return open_directory(path.native()).then([](file f) { return f.stat().then([f = std::move(f)](struct stat st) { return st.st_dev; }); }); } future<bool> is_mountpoint(boost::filesystem::path path) { // Special case for '/', which is always a mount point if (path == path.parent_path()) { return make_ready_future<bool>(true); } return when_all(get_device_id(path.native()), get_device_id(path.parent_path().native())).then([](std::tuple<future<dev_t>, future<dev_t>> ids) { return std::get<0>(ids).get0() != std::get<1>(ids).get0(); }); } future<semaphore_units<semaphore_default_exception_factory>> resource_manager::get_send_units_for(size_t buf_size) { // Let's approximate the memory size the mutation is going to consume by the size of its serialized form size_t hint_memory_budget = std::max(_min_send_hint_budget, buf_size); // Allow a very big mutation to be sent out by consuming the whole shard budget hint_memory_budget = std::min(hint_memory_budget, _max_send_in_flight_memory); resource_manager_logger.trace("memory budget: need {} have {}", hint_memory_budget, _send_limiter.available_units()); return get_units(_send_limiter, hint_memory_budget); } const std::chrono::seconds space_watchdog::_watchdog_period = std::chrono::seconds(1); space_watchdog::space_watchdog(shard_managers_set& managers, per_device_limits_map& per_device_limits_map) : _shard_managers(managers) , _per_device_limits_map(per_device_limits_map) , _timer([this] { on_timer(); }) {} void space_watchdog::start() { _timer.arm(timer_clock_type::now()); } future<> space_watchdog::stop() noexcept { try { return _gate.close().finally([this] { _timer.cancel(); }); } catch (...) { return make_exception_future<>(std::current_exception()); } } future<> space_watchdog::scan_one_ep_dir(boost::filesystem::path path, manager& shard_manager, ep_key_type ep_key) { return lister::scan_dir(path, { directory_entry_type::regular }, [this, ep_key, &shard_manager] (lister::path dir, directory_entry de) { // Put the current end point ID to state.eps_with_pending_hints when we see the second hints file in its directory if (_files_count == 1) { shard_manager.add_ep_with_pending_hints(ep_key); } ++_files_count; return io_check(file_size, (dir / de.name.c_str()).c_str()).then([this] (uint64_t fsize) { _total_size += fsize; }); }); } void space_watchdog::on_timer() { with_gate(_gate, [this] { return futurize_apply([this] { _total_size = 0; return do_for_each(_shard_managers, [this] (manager& shard_manager) { shard_manager.clear_eps_with_pending_hints(); // The hints directories are organized as follows: // <hints root> // |- <shard1 ID> // | |- <EP1 address> // | |- <hints file1> // | |- <hints file2> // | |- ... // | |- <EP2 address> // | |- ... // | |-... // |- <shard2 ID> // | |- ... // ... // |- <shardN ID> // | |- ... // return lister::scan_dir(shard_manager.hints_dir(), {directory_entry_type::directory}, [this, &shard_manager] (lister::path dir, directory_entry de) { _files_count = 0; // Let's scan per-end-point directories and enumerate hints files... // // Let's check if there is a corresponding end point manager (may not exist if the corresponding DC is // not hintable). // If exists - let's take a file update lock so that files are not changed under our feet. Otherwise, simply // continue to enumeration - there is no one to change them. auto it = shard_manager.find_ep_manager(de.name); if (it != shard_manager.ep_managers_end()) { return with_lock(it->second.file_update_mutex(), [this, &shard_manager, dir = std::move(dir), ep_name = std::move(de.name)]() mutable { return scan_one_ep_dir(dir / ep_name.c_str(), shard_manager, ep_key_type(ep_name)); }); } else { return scan_one_ep_dir(dir / de.name.c_str(), shard_manager, ep_key_type(de.name)); } }); }).then([this] { return do_for_each(_per_device_limits_map, [this](per_device_limits_map::value_type& per_device_limits_entry) { space_watchdog::per_device_limits& per_device_limits = per_device_limits_entry.second; size_t adjusted_quota = 0; size_t delta = boost::accumulate(per_device_limits.managers, 0, [] (size_t sum, manager& shard_manager) { return sum + shard_manager.ep_managers_size() * resource_manager::hint_segment_size_in_mb * 1024 * 1024; }); if (per_device_limits.max_shard_disk_space_size > delta) { adjusted_quota = per_device_limits.max_shard_disk_space_size - delta; } bool can_hint = _total_size < adjusted_quota; resource_manager_logger.trace("space_watchdog: total_size ({}) {} max_shard_disk_space_size ({})", _total_size, can_hint ? "<" : ">=", adjusted_quota); if (!can_hint) { for (manager& shard_manager : per_device_limits.managers) { shard_manager.forbid_hints_for_eps_with_pending_hints(); } } else { for (manager& shard_manager : per_device_limits.managers) { shard_manager.allow_hints(); } } }); }); }).handle_exception([this] (auto eptr) { resource_manager_logger.trace("space_watchdog: unexpected exception - stop all hints generators"); // Stop all hint generators if space_watchdog callback failed for (manager& shard_manager : _shard_managers) { shard_manager.forbid_hints(); } }).finally([this] { _timer.arm(_watchdog_period); }); }); } future<> resource_manager::start(shared_ptr<service::storage_proxy> proxy_ptr, shared_ptr<gms::gossiper> gossiper_ptr, shared_ptr<service::storage_service> ss_ptr) { return parallel_for_each(_shard_managers, [proxy_ptr, gossiper_ptr, ss_ptr](manager& m) { return m.start(proxy_ptr, gossiper_ptr, ss_ptr); }).then([this]() { return prepare_per_device_limits(); }).then([this]() { return _space_watchdog.start(); }); } future<> resource_manager::stop() noexcept { return parallel_for_each(_shard_managers, [](manager& m) { return m.stop(); }).finally([this]() { return _space_watchdog.stop(); }); } void resource_manager::register_manager(manager& m) { _shard_managers.insert(m); } future<> resource_manager::prepare_per_device_limits() { return do_for_each(_shard_managers, [this] (manager& shard_manager) mutable { dev_t device_id = shard_manager.hints_dir_device_id(); auto it = _per_device_limits_map.find(device_id); if (it == _per_device_limits_map.end()) { return is_mountpoint(shard_manager.hints_dir().parent_path()).then([this, device_id, &shard_manager](bool is_mountpoint) { // By default, give each group of managers 10% of the available disk space. Give each shard an equal share of the available space. size_t max_size = boost::filesystem::space(shard_manager.hints_dir().c_str()).capacity / (10 * smp::count); // If hints directory is a mountpoint, we assume it's on dedicated (i.e. not shared with data/commitlog/etc) storage. // Then, reserve 90% of all space instead of 10% above. if (is_mountpoint) { max_size *= 9; } _per_device_limits_map.emplace(device_id, space_watchdog::per_device_limits{{std::ref(shard_manager)}, max_size}); }); } else { it->second.managers.emplace_back(std::ref(shard_manager)); return make_ready_future<>(); } }); } } } <|endoftext|>
<commit_before>#include "PickUp.h" #include "../RobotMap.h" PickUp :: Pickup(int ) :Subsystem ("PickUp") { } <commit_msg>Still working on PickUp<commit_after>#include "PickUp.h" #include "../RobotMap.h" PickUp :: Pickup(int intakePort) :Subsystem ("PickUp") { } <|endoftext|>
<commit_before>// Copyright 2008-2009, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions 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 Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Tests for the top plugins to catch regressions in our plugin host code, as // well as in the out of process code. Currently this tests: // Flash // Real // QuickTime // Windows Media Player // -this includes both WMP plugins. npdsplay.dll is the older one that // comes with XP. np-mswmp.dll can be downloaded from Microsoft and // needs SP2 or Vista. #include <windows.h> #include <shellapi.h> #include <shlobj.h> #include <comutil.h> #include <stdlib.h> #include <string.h> #include <memory.h> #include <string> #include "base/file_path.h" #include "base/file_util.h" #include "base/registry.h" #include "chrome/browser/net/url_request_mock_http_job.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "third_party/npapi/bindings/npapi.h" #include "webkit/default_plugin/plugin_impl.h" #include "webkit/glue/plugins/plugin_constants_win.h" #include "webkit/glue/plugins/plugin_list.h" const char kTestCompleteCookie[] = "status"; const char kTestCompleteSuccess[] = "OK"; const int kShortWaitTimeout = 10 * 1000; const int kLongWaitTimeout = 30 * 1000; class PluginTest : public UITest { protected: virtual void SetUp() { const testing::TestInfo* const test_info = testing::UnitTest::GetInstance()->current_test_info(); if (strcmp(test_info->name(), "MediaPlayerNew") == 0) { // The installer adds our process names to the registry key below. Since // the installer might not have run on this machine, add it manually. RegKey regkey; if (regkey.Open(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\MediaPlayer\\ShimInclusionList", KEY_WRITE)) { regkey.CreateKey(L"CHROME.EXE", KEY_READ); } } else if (strcmp(test_info->name(), "MediaPlayerOld") == 0) { // When testing the old WMP plugin, we need to force Chrome to not load // the new plugin. launch_arguments_.AppendSwitch(kUseOldWMPPluginSwitch); } else if (strcmp(test_info->name(), "FlashSecurity") == 0) { launch_arguments_.AppendSwitchWithValue(switches::kTestSandbox, L"security_tests.dll"); } UITest::SetUp(); } void TestPlugin(const std::wstring& test_case, int timeout, bool mock_http) { GURL url = GetTestUrl(test_case, mock_http); NavigateToURL(url); WaitForFinish(timeout, mock_http); } // Generate the URL for testing a particular test. // HTML for the tests is all located in test_directory\plugin\<testcase> // Set |mock_http| to true to use mock HTTP server. GURL GetTestUrl(const std::wstring &test_case, bool mock_http) { if (mock_http) return URLRequestMockHTTPJob::GetMockUrl(L"plugin/" + test_case); FilePath path; PathService::Get(chrome::DIR_TEST_DATA, &path); path = path.AppendASCII("plugin"); path = path.Append(FilePath::FromWStringHack(test_case)); return net::FilePathToFileURL(path); } // Waits for the test case to finish. void WaitForFinish(const int wait_time, bool mock_http) { const int kSleepTime = 500; // 2 times per second const int kMaxIntervals = wait_time / kSleepTime; GURL url = GetTestUrl(L"done", mock_http); scoped_refptr<TabProxy> tab(GetActiveTab()); std::string done_str; for (int i = 0; i < kMaxIntervals; ++i) { Sleep(kSleepTime); // The webpage being tested has javascript which sets a cookie // which signals completion of the test. std::string cookieName = kTestCompleteCookie; tab->GetCookieByName(url, cookieName, &done_str); if (!done_str.empty()) break; } EXPECT_EQ(kTestCompleteSuccess, done_str); } }; TEST_F(PluginTest, Quicktime) { TestPlugin(L"quicktime.html", kShortWaitTimeout, false); } TEST_F(PluginTest, MediaPlayerNew) { TestPlugin(L"wmp_new.html", kShortWaitTimeout, false); } // http://crbug.com/4809 TEST_F(PluginTest, DISABLED_MediaPlayerOld) { TestPlugin(L"wmp_old.html", kLongWaitTimeout, false); } TEST_F(PluginTest, Real) { TestPlugin(L"real.html", kShortWaitTimeout, false); } TEST_F(PluginTest, Flash) { TestPlugin(L"flash.html", kShortWaitTimeout, false); } TEST_F(PluginTest, FlashOctetStream) { TestPlugin(L"flash-octet-stream.html", kShortWaitTimeout, false); } TEST_F(PluginTest, FlashSecurity) { TestPlugin(L"flash.html", kShortWaitTimeout, false); } // http://crbug.com/16114 TEST_F(PluginTest, FlashLayoutWhilePainting) { TestPlugin(L"flash-layout-while-painting.html", kShortWaitTimeout, true); } // http://crbug.com/8690 TEST_F(PluginTest, DISABLED_Java) { TestPlugin(L"Java.html", kShortWaitTimeout, false); } TEST_F(PluginTest, Silverlight) { TestPlugin(L"silverlight.html", kShortWaitTimeout, false); } <commit_msg>Disable flaky plugin tests. These keep causing bogus automatic tree closures.<commit_after>// Copyright 2008-2009, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions 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 Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Tests for the top plugins to catch regressions in our plugin host code, as // well as in the out of process code. Currently this tests: // Flash // Real // QuickTime // Windows Media Player // -this includes both WMP plugins. npdsplay.dll is the older one that // comes with XP. np-mswmp.dll can be downloaded from Microsoft and // needs SP2 or Vista. #include <windows.h> #include <shellapi.h> #include <shlobj.h> #include <comutil.h> #include <stdlib.h> #include <string.h> #include <memory.h> #include <string> #include "base/file_path.h" #include "base/file_util.h" #include "base/registry.h" #include "chrome/browser/net/url_request_mock_http_job.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" #include "third_party/npapi/bindings/npapi.h" #include "webkit/default_plugin/plugin_impl.h" #include "webkit/glue/plugins/plugin_constants_win.h" #include "webkit/glue/plugins/plugin_list.h" const char kTestCompleteCookie[] = "status"; const char kTestCompleteSuccess[] = "OK"; const int kShortWaitTimeout = 10 * 1000; const int kLongWaitTimeout = 30 * 1000; class PluginTest : public UITest { protected: virtual void SetUp() { const testing::TestInfo* const test_info = testing::UnitTest::GetInstance()->current_test_info(); if (strcmp(test_info->name(), "MediaPlayerNew") == 0) { // The installer adds our process names to the registry key below. Since // the installer might not have run on this machine, add it manually. RegKey regkey; if (regkey.Open(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\MediaPlayer\\ShimInclusionList", KEY_WRITE)) { regkey.CreateKey(L"CHROME.EXE", KEY_READ); } } else if (strcmp(test_info->name(), "MediaPlayerOld") == 0) { // When testing the old WMP plugin, we need to force Chrome to not load // the new plugin. launch_arguments_.AppendSwitch(kUseOldWMPPluginSwitch); } else if (strcmp(test_info->name(), "FlashSecurity") == 0) { launch_arguments_.AppendSwitchWithValue(switches::kTestSandbox, L"security_tests.dll"); } UITest::SetUp(); } void TestPlugin(const std::wstring& test_case, int timeout, bool mock_http) { GURL url = GetTestUrl(test_case, mock_http); NavigateToURL(url); WaitForFinish(timeout, mock_http); } // Generate the URL for testing a particular test. // HTML for the tests is all located in test_directory\plugin\<testcase> // Set |mock_http| to true to use mock HTTP server. GURL GetTestUrl(const std::wstring &test_case, bool mock_http) { if (mock_http) return URLRequestMockHTTPJob::GetMockUrl(L"plugin/" + test_case); FilePath path; PathService::Get(chrome::DIR_TEST_DATA, &path); path = path.AppendASCII("plugin"); path = path.Append(FilePath::FromWStringHack(test_case)); return net::FilePathToFileURL(path); } // Waits for the test case to finish. void WaitForFinish(const int wait_time, bool mock_http) { const int kSleepTime = 500; // 2 times per second const int kMaxIntervals = wait_time / kSleepTime; GURL url = GetTestUrl(L"done", mock_http); scoped_refptr<TabProxy> tab(GetActiveTab()); std::string done_str; for (int i = 0; i < kMaxIntervals; ++i) { Sleep(kSleepTime); // The webpage being tested has javascript which sets a cookie // which signals completion of the test. std::string cookieName = kTestCompleteCookie; tab->GetCookieByName(url, cookieName, &done_str); if (!done_str.empty()) break; } EXPECT_EQ(kTestCompleteSuccess, done_str); } }; TEST_F(PluginTest, Quicktime) { TestPlugin(L"quicktime.html", kShortWaitTimeout, false); } TEST_F(PluginTest, MediaPlayerNew) { TestPlugin(L"wmp_new.html", kShortWaitTimeout, false); } // http://crbug.com/4809 TEST_F(PluginTest, DISABLED_MediaPlayerOld) { TestPlugin(L"wmp_old.html", kLongWaitTimeout, false); } TEST_F(PluginTest, Real) { TestPlugin(L"real.html", kShortWaitTimeout, false); } TEST_F(PluginTest, Flash) { TestPlugin(L"flash.html", kShortWaitTimeout, false); } TEST_F(PluginTest, FlashOctetStream) { TestPlugin(L"flash-octet-stream.html", kShortWaitTimeout, false); } TEST_F(PluginTest, FlashSecurity) { TestPlugin(L"flash.html", kShortWaitTimeout, false); } // http://crbug.com/16114 // Disabled for http://crbug.com/21538 TEST_F(PluginTest, DISABLED_FlashLayoutWhilePainting) { TestPlugin(L"flash-layout-while-painting.html", kShortWaitTimeout, true); } // http://crbug.com/8690 TEST_F(PluginTest, DISABLED_Java) { TestPlugin(L"Java.html", kShortWaitTimeout, false); } // Disabled for http://crbug.com/22666 TEST_F(PluginTest, DISABLED_Silverlight) { TestPlugin(L"silverlight.html", kShortWaitTimeout, false); } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Tests for the top plugins to catch regressions in our plugin host code, as // well as in the out of process code. Currently this tests: // Flash // Real // QuickTime // Windows Media Player // -this includes both WMP plugins. npdsplay.dll is the older one that // comes with XP. np-mswmp.dll can be downloaded from Microsoft and // needs SP2 or Vista. #include "build/build_config.h" #if defined(OS_WIN) #include <windows.h> #include <shellapi.h> #include <shlobj.h> #include <comutil.h> #endif #include <stdlib.h> #include <string.h> #include <memory.h> #include <string> #include "base/file_path.h" #include "base/file_util.h" #include "base/message_loop.h" #include "base/path_service.h" #include "chrome/browser/net/url_request_mock_http_job.h" #include "chrome/browser/plugin_download_helper.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/capturing_net_log.h" #include "net/base/cert_verifier.h" #include "net/base/host_resolver.h" #include "net/base/net_util.h" #include "net/base/ssl_config_service_defaults.h" #include "net/http/http_auth_handler_factory.h" #include "net/http/http_cache.h" #include "net/http/http_network_layer.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_status.h" #include "third_party/npapi/bindings/npapi.h" #include "webkit/plugins/npapi/plugin_constants_win.h" #include "webkit/plugins/npapi/plugin_list.h" #include "webkit/plugins/plugin_switches.h" #if defined(OS_WIN) #include "base/win/registry.h" #endif class PluginTest : public UITest { public: // Generate the URL for testing a particular test. // HTML for the tests is all located in test_directory\plugin\<testcase> // Set |mock_http| to true to use mock HTTP server. static GURL GetTestUrl(const std::string &test_case, bool mock_http) { static const FilePath::CharType kPluginPath[] = FILE_PATH_LITERAL("plugin"); if (mock_http) { FilePath plugin_path = FilePath(kPluginPath).AppendASCII(test_case); return URLRequestMockHTTPJob::GetMockUrl(plugin_path); } FilePath path; PathService::Get(chrome::DIR_TEST_DATA, &path); path = path.Append(kPluginPath).AppendASCII(test_case); return net::FilePathToFileURL(path); } protected: #if defined(OS_WIN) virtual void SetUp() { const testing::TestInfo* const test_info = testing::UnitTest::GetInstance()->current_test_info(); if (strcmp(test_info->name(), "MediaPlayerNew") == 0) { // The installer adds our process names to the registry key below. Since // the installer might not have run on this machine, add it manually. base::win::RegKey regkey; if (regkey.Open(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\MediaPlayer\\ShimInclusionList", KEY_WRITE)) { regkey.CreateKey(L"CHROME.EXE", KEY_READ); } } else if (strcmp(test_info->name(), "MediaPlayerOld") == 0) { // When testing the old WMP plugin, we need to force Chrome to not load // the new plugin. launch_arguments_.AppendSwitch(switches::kUseOldWMPPlugin); } else if (strcmp(test_info->name(), "FlashSecurity") == 0) { launch_arguments_.AppendSwitchASCII(switches::kTestSandbox, "security_tests.dll"); } UITest::SetUp(); } #endif // defined(OS_WIN) void TestPlugin(const std::string& test_case, int timeout, bool mock_http) { GURL url = GetTestUrl(test_case, mock_http); NavigateToURL(url); WaitForFinish(timeout, mock_http); } // Waits for the test case to finish. void WaitForFinish(const int wait_time, bool mock_http) { static const char kTestCompleteCookie[] = "status"; static const char kTestCompleteSuccess[] = "OK"; GURL url = GetTestUrl("done", mock_http); scoped_refptr<TabProxy> tab(GetActiveTab()); const std::string result = WaitUntilCookieNonEmpty(tab, url, kTestCompleteCookie, wait_time); ASSERT_EQ(kTestCompleteSuccess, result); } }; TEST_F(PluginTest, Flash) { // Note: This does not work with the npwrapper on 64-bit Linux. Install the // native 64-bit Flash to run the test. // TODO(thestig) Update this list if we decide to only test against internal // Flash plugin in the future? std::string kFlashQuery = #if defined(OS_WIN) "npswf32.dll" #elif defined(OS_MACOSX) "Flash Player.plugin" #elif defined(OS_POSIX) "libflashplayer.so" #endif ; TestPlugin("flash.html?" + kFlashQuery, action_max_timeout_ms(), false); } class ClickToPlayPluginTest : public PluginTest { public: ClickToPlayPluginTest() { dom_automation_enabled_ = true; } }; TEST_F(ClickToPlayPluginTest, Flash) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); ASSERT_TRUE(browser->SetDefaultContentSetting(CONTENT_SETTINGS_TYPE_PLUGINS, CONTENT_SETTING_BLOCK)); GURL url = GetTestUrl("flash-clicktoplay.html", true); NavigateToURL(url); scoped_refptr<TabProxy> tab(browser->GetTab(0)); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->LoadBlockedPlugins()); WaitForFinish(action_max_timeout_ms(), true); } TEST_F(ClickToPlayPluginTest, FlashDocument) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); ASSERT_TRUE(browser->SetDefaultContentSetting(CONTENT_SETTINGS_TYPE_PLUGINS, CONTENT_SETTING_BLOCK)); scoped_refptr<TabProxy> tab(browser->GetTab(0)); ASSERT_TRUE(tab.get()); GURL url = GetTestUrl("js-invoker.swf?callback=done", true); NavigateToURL(url); // Inject the callback function into the HTML page generated by the browser. ASSERT_TRUE(tab->ExecuteJavaScript("window.done = function() {" " window.location = \"done.html\";" "}")); ASSERT_TRUE(tab->LoadBlockedPlugins()); WaitForFinish(action_max_timeout_ms(), true); } #if defined(OS_WIN) // Windows only test TEST_F(PluginTest, DISABLED_FlashSecurity) { TestPlugin("flash.html", action_max_timeout_ms(), false); } #endif // defined(OS_WIN) #if defined(OS_WIN) // TODO(port) Port the following tests to platforms that have the required // plugins. // Flaky: http://crbug.com/55915 TEST_F(PluginTest, FLAKY_Quicktime) { TestPlugin("quicktime.html", action_max_timeout_ms(), false); } // Disabled on Release bots - http://crbug.com/44662 #if defined(NDEBUG) #define MediaPlayerNew DISABLED_MediaPlayerNew #endif TEST_F(PluginTest, MediaPlayerNew) { TestPlugin("wmp_new.html", action_max_timeout_ms(), false); } // http://crbug.com/4809 TEST_F(PluginTest, DISABLED_MediaPlayerOld) { TestPlugin("wmp_old.html", action_max_timeout_ms(), false); } #if defined(NDEBUG) #define Real DISABLED_Real #endif // Disabled on Release bots - http://crbug.com/44673 TEST_F(PluginTest, Real) { TestPlugin("real.html", action_max_timeout_ms(), false); } TEST_F(PluginTest, FlashOctetStream) { TestPlugin("flash-octet-stream.html", action_max_timeout_ms(), false); } #if defined(OS_WIN) // http://crbug.com/53926 TEST_F(PluginTest, FLAKY_FlashLayoutWhilePainting) { #else TEST_F(PluginTest, FlashLayoutWhilePainting) { #endif TestPlugin("flash-layout-while-painting.html", action_max_timeout_ms(), true); } // http://crbug.com/8690 TEST_F(PluginTest, DISABLED_Java) { TestPlugin("Java.html", action_max_timeout_ms(), false); } TEST_F(PluginTest, Silverlight) { TestPlugin("silverlight.html", action_max_timeout_ms(), false); } // This class provides functionality to test the plugin installer download // file functionality. class PluginInstallerDownloadTest : public PluginDownloadUrlHelper::DownloadDelegate, public testing::Test { public: // This class provides HTTP request context information for the downloads. class UploadRequestContext : public URLRequestContext { public: UploadRequestContext() { Initialize(); } ~UploadRequestContext() { DVLOG(1) << __FUNCTION__; delete http_transaction_factory_; delete http_auth_handler_factory_; delete cert_verifier_; delete host_resolver_; } void Initialize() { host_resolver_ = net::CreateSystemHostResolver(net::HostResolver::kDefaultParallelism, NULL, NULL); cert_verifier_ = new net::CertVerifier; net::ProxyConfigService* proxy_config_service = net::ProxyService::CreateSystemProxyConfigService(NULL, NULL); DCHECK(proxy_config_service); const size_t kNetLogBound = 50u; net_log_.reset(new net::CapturingNetLog(kNetLogBound)); proxy_service_ = net::ProxyService::CreateUsingSystemProxyResolver( proxy_config_service, 0, net_log_.get()); DCHECK(proxy_service_); ssl_config_service_ = new net::SSLConfigServiceDefaults; http_auth_handler_factory_ = net::HttpAuthHandlerFactory::CreateDefault( host_resolver_); http_transaction_factory_ = new net::HttpCache( net::HttpNetworkLayer::CreateFactory(host_resolver_, cert_verifier_, NULL /* dnsrr_resolver */, NULL /* dns_cert_checker */, NULL /* ssl_host_info_factory */, proxy_service_, ssl_config_service_, http_auth_handler_factory_, network_delegate_, NULL), net::HttpCache::DefaultBackend::InMemory(0)); } private: scoped_ptr<net::NetLog> net_log_; scoped_ptr<net::URLSecurityManager> url_security_manager_; }; PluginInstallerDownloadTest() : success_(false), download_helper_(NULL) {} ~PluginInstallerDownloadTest() {} void Start() { initial_download_path_ = PluginTest::GetTestUrl("flash.html", false); download_helper_ = new PluginDownloadUrlHelper( initial_download_path_.spec(), base::GetCurrentProcId(), NULL, static_cast<PluginDownloadUrlHelper::DownloadDelegate*>(this)); download_helper_->InitiateDownload(new UploadRequestContext); MessageLoop::current()->PostDelayedTask( FROM_HERE, new MessageLoop::QuitTask, TestTimeouts::action_max_timeout_ms()); } virtual void OnDownloadCompleted(const FilePath& download_path, bool success) { success_ = success; final_download_path_ = download_path; MessageLoop::current()->Quit(); download_helper_ = NULL; } FilePath final_download_path() const { return final_download_path_; } FilePath initial_download_path() const { return final_download_path_; } bool success() const { return success_; } private: FilePath final_download_path_; PluginDownloadUrlHelper* download_helper_; bool success_; GURL initial_download_path_; }; // This test validates that the plugin downloader downloads the specified file // to a temporary path with the same file name. TEST_F(PluginInstallerDownloadTest, PluginInstallerDownloadPathTest) { MessageLoop loop(MessageLoop::TYPE_IO); Start(); loop.Run(); EXPECT_TRUE(success()); EXPECT_TRUE(initial_download_path().BaseName().value() == final_download_path().BaseName().value()); } #endif // defined(OS_WIN) <commit_msg>Disabling the MediaPlayerNew plugin test as it seems to fail consistently causing the XP Perf dbg builder to turn red.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Tests for the top plugins to catch regressions in our plugin host code, as // well as in the out of process code. Currently this tests: // Flash // Real // QuickTime // Windows Media Player // -this includes both WMP plugins. npdsplay.dll is the older one that // comes with XP. np-mswmp.dll can be downloaded from Microsoft and // needs SP2 or Vista. #include "build/build_config.h" #if defined(OS_WIN) #include <windows.h> #include <shellapi.h> #include <shlobj.h> #include <comutil.h> #endif #include <stdlib.h> #include <string.h> #include <memory.h> #include <string> #include "base/file_path.h" #include "base/file_util.h" #include "base/message_loop.h" #include "base/path_service.h" #include "chrome/browser/net/url_request_mock_http_job.h" #include "chrome/browser/plugin_download_helper.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/capturing_net_log.h" #include "net/base/cert_verifier.h" #include "net/base/host_resolver.h" #include "net/base/net_util.h" #include "net/base/ssl_config_service_defaults.h" #include "net/http/http_auth_handler_factory.h" #include "net/http/http_cache.h" #include "net/http/http_network_layer.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_status.h" #include "third_party/npapi/bindings/npapi.h" #include "webkit/plugins/npapi/plugin_constants_win.h" #include "webkit/plugins/npapi/plugin_list.h" #include "webkit/plugins/plugin_switches.h" #if defined(OS_WIN) #include "base/win/registry.h" #endif class PluginTest : public UITest { public: // Generate the URL for testing a particular test. // HTML for the tests is all located in test_directory\plugin\<testcase> // Set |mock_http| to true to use mock HTTP server. static GURL GetTestUrl(const std::string &test_case, bool mock_http) { static const FilePath::CharType kPluginPath[] = FILE_PATH_LITERAL("plugin"); if (mock_http) { FilePath plugin_path = FilePath(kPluginPath).AppendASCII(test_case); return URLRequestMockHTTPJob::GetMockUrl(plugin_path); } FilePath path; PathService::Get(chrome::DIR_TEST_DATA, &path); path = path.Append(kPluginPath).AppendASCII(test_case); return net::FilePathToFileURL(path); } protected: #if defined(OS_WIN) virtual void SetUp() { const testing::TestInfo* const test_info = testing::UnitTest::GetInstance()->current_test_info(); if (strcmp(test_info->name(), "MediaPlayerNew") == 0) { // The installer adds our process names to the registry key below. Since // the installer might not have run on this machine, add it manually. base::win::RegKey regkey; if (regkey.Open(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\MediaPlayer\\ShimInclusionList", KEY_WRITE)) { regkey.CreateKey(L"CHROME.EXE", KEY_READ); } } else if (strcmp(test_info->name(), "MediaPlayerOld") == 0) { // When testing the old WMP plugin, we need to force Chrome to not load // the new plugin. launch_arguments_.AppendSwitch(switches::kUseOldWMPPlugin); } else if (strcmp(test_info->name(), "FlashSecurity") == 0) { launch_arguments_.AppendSwitchASCII(switches::kTestSandbox, "security_tests.dll"); } UITest::SetUp(); } #endif // defined(OS_WIN) void TestPlugin(const std::string& test_case, int timeout, bool mock_http) { GURL url = GetTestUrl(test_case, mock_http); NavigateToURL(url); WaitForFinish(timeout, mock_http); } // Waits for the test case to finish. void WaitForFinish(const int wait_time, bool mock_http) { static const char kTestCompleteCookie[] = "status"; static const char kTestCompleteSuccess[] = "OK"; GURL url = GetTestUrl("done", mock_http); scoped_refptr<TabProxy> tab(GetActiveTab()); const std::string result = WaitUntilCookieNonEmpty(tab, url, kTestCompleteCookie, wait_time); ASSERT_EQ(kTestCompleteSuccess, result); } }; TEST_F(PluginTest, Flash) { // Note: This does not work with the npwrapper on 64-bit Linux. Install the // native 64-bit Flash to run the test. // TODO(thestig) Update this list if we decide to only test against internal // Flash plugin in the future? std::string kFlashQuery = #if defined(OS_WIN) "npswf32.dll" #elif defined(OS_MACOSX) "Flash Player.plugin" #elif defined(OS_POSIX) "libflashplayer.so" #endif ; TestPlugin("flash.html?" + kFlashQuery, action_max_timeout_ms(), false); } class ClickToPlayPluginTest : public PluginTest { public: ClickToPlayPluginTest() { dom_automation_enabled_ = true; } }; TEST_F(ClickToPlayPluginTest, Flash) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); ASSERT_TRUE(browser->SetDefaultContentSetting(CONTENT_SETTINGS_TYPE_PLUGINS, CONTENT_SETTING_BLOCK)); GURL url = GetTestUrl("flash-clicktoplay.html", true); NavigateToURL(url); scoped_refptr<TabProxy> tab(browser->GetTab(0)); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->LoadBlockedPlugins()); WaitForFinish(action_max_timeout_ms(), true); } TEST_F(ClickToPlayPluginTest, FlashDocument) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); ASSERT_TRUE(browser->SetDefaultContentSetting(CONTENT_SETTINGS_TYPE_PLUGINS, CONTENT_SETTING_BLOCK)); scoped_refptr<TabProxy> tab(browser->GetTab(0)); ASSERT_TRUE(tab.get()); GURL url = GetTestUrl("js-invoker.swf?callback=done", true); NavigateToURL(url); // Inject the callback function into the HTML page generated by the browser. ASSERT_TRUE(tab->ExecuteJavaScript("window.done = function() {" " window.location = \"done.html\";" "}")); ASSERT_TRUE(tab->LoadBlockedPlugins()); WaitForFinish(action_max_timeout_ms(), true); } #if defined(OS_WIN) // Windows only test TEST_F(PluginTest, DISABLED_FlashSecurity) { TestPlugin("flash.html", action_max_timeout_ms(), false); } #endif // defined(OS_WIN) #if defined(OS_WIN) // TODO(port) Port the following tests to platforms that have the required // plugins. // Flaky: http://crbug.com/55915 TEST_F(PluginTest, FLAKY_Quicktime) { TestPlugin("quicktime.html", action_max_timeout_ms(), false); } // Disabled - http://crbug.com/44662 TEST_F(PluginTest, DISABLED_MediaPlayerNew) { TestPlugin("wmp_new.html", action_max_timeout_ms(), false); } // http://crbug.com/4809 TEST_F(PluginTest, DISABLED_MediaPlayerOld) { TestPlugin("wmp_old.html", action_max_timeout_ms(), false); } #if defined(NDEBUG) #define Real DISABLED_Real #endif // Disabled on Release bots - http://crbug.com/44673 TEST_F(PluginTest, Real) { TestPlugin("real.html", action_max_timeout_ms(), false); } TEST_F(PluginTest, FlashOctetStream) { TestPlugin("flash-octet-stream.html", action_max_timeout_ms(), false); } #if defined(OS_WIN) // http://crbug.com/53926 TEST_F(PluginTest, FLAKY_FlashLayoutWhilePainting) { #else TEST_F(PluginTest, FlashLayoutWhilePainting) { #endif TestPlugin("flash-layout-while-painting.html", action_max_timeout_ms(), true); } // http://crbug.com/8690 TEST_F(PluginTest, DISABLED_Java) { TestPlugin("Java.html", action_max_timeout_ms(), false); } TEST_F(PluginTest, Silverlight) { TestPlugin("silverlight.html", action_max_timeout_ms(), false); } // This class provides functionality to test the plugin installer download // file functionality. class PluginInstallerDownloadTest : public PluginDownloadUrlHelper::DownloadDelegate, public testing::Test { public: // This class provides HTTP request context information for the downloads. class UploadRequestContext : public URLRequestContext { public: UploadRequestContext() { Initialize(); } ~UploadRequestContext() { DVLOG(1) << __FUNCTION__; delete http_transaction_factory_; delete http_auth_handler_factory_; delete cert_verifier_; delete host_resolver_; } void Initialize() { host_resolver_ = net::CreateSystemHostResolver(net::HostResolver::kDefaultParallelism, NULL, NULL); cert_verifier_ = new net::CertVerifier; net::ProxyConfigService* proxy_config_service = net::ProxyService::CreateSystemProxyConfigService(NULL, NULL); DCHECK(proxy_config_service); const size_t kNetLogBound = 50u; net_log_.reset(new net::CapturingNetLog(kNetLogBound)); proxy_service_ = net::ProxyService::CreateUsingSystemProxyResolver( proxy_config_service, 0, net_log_.get()); DCHECK(proxy_service_); ssl_config_service_ = new net::SSLConfigServiceDefaults; http_auth_handler_factory_ = net::HttpAuthHandlerFactory::CreateDefault( host_resolver_); http_transaction_factory_ = new net::HttpCache( net::HttpNetworkLayer::CreateFactory(host_resolver_, cert_verifier_, NULL /* dnsrr_resolver */, NULL /* dns_cert_checker */, NULL /* ssl_host_info_factory */, proxy_service_, ssl_config_service_, http_auth_handler_factory_, network_delegate_, NULL), net::HttpCache::DefaultBackend::InMemory(0)); } private: scoped_ptr<net::NetLog> net_log_; scoped_ptr<net::URLSecurityManager> url_security_manager_; }; PluginInstallerDownloadTest() : success_(false), download_helper_(NULL) {} ~PluginInstallerDownloadTest() {} void Start() { initial_download_path_ = PluginTest::GetTestUrl("flash.html", false); download_helper_ = new PluginDownloadUrlHelper( initial_download_path_.spec(), base::GetCurrentProcId(), NULL, static_cast<PluginDownloadUrlHelper::DownloadDelegate*>(this)); download_helper_->InitiateDownload(new UploadRequestContext); MessageLoop::current()->PostDelayedTask( FROM_HERE, new MessageLoop::QuitTask, TestTimeouts::action_max_timeout_ms()); } virtual void OnDownloadCompleted(const FilePath& download_path, bool success) { success_ = success; final_download_path_ = download_path; MessageLoop::current()->Quit(); download_helper_ = NULL; } FilePath final_download_path() const { return final_download_path_; } FilePath initial_download_path() const { return final_download_path_; } bool success() const { return success_; } private: FilePath final_download_path_; PluginDownloadUrlHelper* download_helper_; bool success_; GURL initial_download_path_; }; // This test validates that the plugin downloader downloads the specified file // to a temporary path with the same file name. TEST_F(PluginInstallerDownloadTest, PluginInstallerDownloadPathTest) { MessageLoop loop(MessageLoop::TYPE_IO); Start(); loop.Run(); EXPECT_TRUE(success()); EXPECT_TRUE(initial_download_path().BaseName().value() == final_download_path().BaseName().value()); } #endif // defined(OS_WIN) <|endoftext|>
<commit_before>// Including SDKDDKVer.h defines the highest available Windows platform. // If you wish to build your application for a previous Windows platform, include WinSDKVer.h and // set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. #include <SDKDDKVer.h> #include "CppUnitTest.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; #include <algorithm> #include <QApplication> #include <QTimer> #include "QImageWidget.h" #include "QKinectGrabber.h" #include "QKinectIO.h" #include "Timer.h" namespace TestQtKinect { TEST_CLASS(UnitTest1) { public: TEST_METHOD(TestKinectCapture) { int argc = 1; char* argv[] = { "TestKinectColor" }; QApplication app(argc, argv); QTimer *timer = new QTimer(); timer->start(5000); QApplication::connect(timer, SIGNAL(timeout()), &app, SLOT(quit())); QKinectGrabber k; k.start(); Assert::IsTrue(k.isRunning(), L"\n<Kinect is not running>\n", LINE_INFO()); QImageWidget colorWidget; colorWidget.setMinimumSize(720, 480); colorWidget.show(); QApplication::connect(&k, SIGNAL(colorImage(QImage)), &colorWidget, SLOT(setImage(QImage))); QImageWidget depthWidget; depthWidget.setMinimumSize(512, 424); depthWidget.show(); QApplication::connect(&k, SIGNAL(depthImage(QImage)), &depthWidget, SLOT(setImage(QImage))); int app_exit = app.exec(); k.stop(); Assert::AreEqual(EXIT_SUCCESS, app_exit, L"\n<TestKinectColor appplication did not finish properly>\n", LINE_INFO()); } TEST_METHOD(TestKinectIO) { QKinectGrabber kinectCapture; kinectCapture.start(); Timer::sleep_ms(3000); Assert::IsTrue(kinectCapture.isRunning(), L"\n<Kinect is not running>\n", LINE_INFO()); QString filename("TestKinectIO.knt"); std::vector<unsigned short> info_captured; std::vector<unsigned short> buffer_captured; kinectCapture.getDepthBuffer(info_captured, buffer_captured); QKinectIO::save(filename, info_captured, buffer_captured); std::vector<unsigned short> info_loaded; std::vector<unsigned short> buffer_loaded; QKinectIO::load(filename, info_loaded, buffer_loaded); Assert::AreEqual(info_captured.size(), info_loaded.size(), L"\n<The size of info vector captured from kinect and the info vector loaded from file are not equal>\n", LINE_INFO()); Assert::AreEqual(buffer_captured.size(), buffer_loaded.size(), L"\n<The size of buffer captured from kinect and the buffer loaded from file are not equal>\n", LINE_INFO()); bool info_are_equal = std::equal(info_captured.begin(), info_captured.end(), info_loaded.begin()); bool buffer_are_equal = std::equal(buffer_captured.begin(), buffer_captured.end(), buffer_loaded.begin()); Assert::IsTrue(info_are_equal, L"\n<Info captured from kinect and info loaded from file are not equal>\n", LINE_INFO()); Assert::IsTrue(buffer_are_equal, L"\n<Buffer captured from kinect and buffer loaded from file are not equal>\n", LINE_INFO()); } TEST_METHOD(TestKinectOBJ) { QString filenameKnt("TestKinectIO.knt"); QString filenameObj("TestKinectIO.obj"); std::vector<unsigned short> info_loaded; std::vector<unsigned short> buffer_loaded; QKinectIO::load(filenameKnt, info_loaded, buffer_loaded); QKinectIO::exportObj(filenameObj, info_loaded, buffer_loaded); Assert::IsTrue(true); } }; }<commit_msg>Inserted test for projection pipeline<commit_after>// Including SDKDDKVer.h defines the highest available Windows platform. // If you wish to build your application for a previous Windows platform, include WinSDKVer.h and // set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. #include <SDKDDKVer.h> #include "CppUnitTest.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; #include <algorithm> #include <sstream> #include <fstream> #include <QApplication> #include <QTimer> #include "QImageWidget.h" #include "QKinectGrabber.h" #include "QKinectIO.h" #include "Timer.h" #include "Eigen/Eigen" static bool import_obj(const std::string& filename, std::vector<float>& points3d, int max_point_count = INT_MAX) { std::ifstream inFile; inFile.open(filename); if (!inFile.is_open()) { std::cerr << "Error: Could not open obj input file: " << filename << std::endl; return false; } points3d.clear(); int i = 0; while (inFile) { std::string str; if (!std::getline(inFile, str)) { if (inFile.eof()) return true; std::cerr << "Error: Problems when reading obj file: " << filename << std::endl; return false; } if (str[0] == 'v') { std::stringstream ss(str); std::vector <std::string> record; char c; double x, y, z; ss >> c >> x >> y >> z; points3d.push_back(x); points3d.push_back(y); points3d.push_back(z); } if (i++ > max_point_count) break; } inFile.close(); return true; } static Eigen::Matrix4f createPerspectiveMatrix(float fy, float in_aspect_ratio, float in_near_plane, float in_far_plane) { Eigen::Matrix4f out = Eigen::Matrix4f::Zero(); const float y_scale = (float)1.0 / tan((fy / 2.0)*(M_PI / 180.0)), x_scale = y_scale / in_aspect_ratio, frustum_length = in_far_plane - in_near_plane; out(0, 0) = x_scale; out(1, 1) = y_scale; out(2, 2) = -((in_far_plane + in_near_plane) / frustum_length); out(3, 2) = -1.0; out(2, 3) = -((2 * in_near_plane * in_far_plane) / frustum_length); return out; } namespace TestQtKinect { TEST_CLASS(UnitTest1) { public: TEST_METHOD(TestKinectCapture) { int argc = 1; char* argv[] = { "TestKinectColor" }; QApplication app(argc, argv); QTimer *timer = new QTimer(); timer->start(5000); QApplication::connect(timer, SIGNAL(timeout()), &app, SLOT(quit())); QKinectGrabber k; k.start(); Assert::IsTrue(k.isRunning(), L"\n<Kinect is not running>\n", LINE_INFO()); QImageWidget colorWidget; colorWidget.setMinimumSize(720, 480); colorWidget.show(); QApplication::connect(&k, SIGNAL(colorImage(QImage)), &colorWidget, SLOT(setImage(QImage))); QImageWidget depthWidget; depthWidget.setMinimumSize(512, 424); depthWidget.show(); QApplication::connect(&k, SIGNAL(depthImage(QImage)), &depthWidget, SLOT(setImage(QImage))); int app_exit = app.exec(); k.stop(); Assert::AreEqual(EXIT_SUCCESS, app_exit, L"\n<TestKinectColor appplication did not finish properly>\n", LINE_INFO()); } TEST_METHOD(TestKinectIO) { QKinectGrabber kinectCapture; kinectCapture.start(); Timer::sleep_ms(3000); Assert::IsTrue(kinectCapture.isRunning(), L"\n<Kinect is not running>\n", LINE_INFO()); QString filename("TestKinectIO.knt"); std::vector<unsigned short> info_captured; std::vector<unsigned short> buffer_captured; kinectCapture.getDepthBuffer(info_captured, buffer_captured); QKinectIO::save(filename, info_captured, buffer_captured); std::vector<unsigned short> info_loaded; std::vector<unsigned short> buffer_loaded; QKinectIO::load(filename, info_loaded, buffer_loaded); Assert::AreEqual(info_captured.size(), info_loaded.size(), L"\n<The size of info vector captured from kinect and the info vector loaded from file are not equal>\n", LINE_INFO()); Assert::AreEqual(buffer_captured.size(), buffer_loaded.size(), L"\n<The size of buffer captured from kinect and the buffer loaded from file are not equal>\n", LINE_INFO()); bool info_are_equal = std::equal(info_captured.begin(), info_captured.end(), info_loaded.begin()); bool buffer_are_equal = std::equal(buffer_captured.begin(), buffer_captured.end(), buffer_loaded.begin()); Assert::IsTrue(info_are_equal, L"\n<Info captured from kinect and info loaded from file are not equal>\n", LINE_INFO()); Assert::IsTrue(buffer_are_equal, L"\n<Buffer captured from kinect and buffer loaded from file are not equal>\n", LINE_INFO()); } TEST_METHOD(TestKinectOBJ) { QString filenameKnt("TestKinectIO.knt"); QString filenameObj("TestKinectIO.obj"); std::vector<unsigned short> info_loaded; std::vector<unsigned short> buffer_loaded; QKinectIO::load(filenameKnt, info_loaded, buffer_loaded); QKinectIO::exportObj(filenameObj, info_loaded, buffer_loaded); Assert::IsTrue(true); } TEST_METHOD(TestProjectionPipelineKMatrix) { std::string filename("../../data/monkey/monkey.obj"); std::vector<float> points3d; import_obj(filename, points3d); Eigen::Vector4f p3d(24.5292f, 21.9753f, 29.9848f, 1.0f); Eigen::Vector4f p2d; float fovy = 70.0f; float aspect_ratio = 512.0f / 424.0f; float y_scale = (float)1.0 / tan((fovy / 2.0)*(M_PI / 180.0)); float x_scale = y_scale / aspect_ratio; Eigen::MatrixXf K = Eigen::MatrixXf(3, 4); K.setZero(); K(0, 0) = x_scale; K(1, 1) = y_scale; K(2, 2) = 1; Eigen::MatrixXf K_inv = K; K_inv(0, 0) = 1.0f / K_inv(0, 0); K_inv(1, 1) = 1.0f / K_inv(1, 1); std::cout << K_inv << std::endl << std::endl; Eigen::Vector3f kp = K * p3d; kp /= kp.z(); p2d = kp.homogeneous(); p2d *= p3d.z(); Eigen::Vector3f p3d_out = K_inv * p2d; std::cout << std::fixed << "Input point 3d : " << p3d.transpose() << std::endl << "Projected point : " << kp.transpose() << std::endl << "Input point 2d : " << p2d.transpose() << std::endl << "Output point 3d : " << p3d_out.transpose() << std::endl << "Test Passed : " << (p3d.isApprox(p3d_out.homogeneous()) ? "[ok]" : "[fail]") << std::endl; Assert::IsTrue(p3d.isApprox(p3d_out.homogeneous())); } TEST_METHOD(TestProjectionPipeline) { Eigen::Vector4f p3d(-0.5f, -0.5f, -0.88f, 1.0f); Eigen::Vector3f pixel(285.71f, 5.71f, 88.73f); float window_width = 1280.0f; float window_height = 720.0f; float near_plane = 0.1f; float far_plane = 100.0f; float fovy = 60.0f; float aspect_ratio = window_width / window_height; float y_scale = (float)1.0 / tan((fovy / 2.0)*(M_PI / 180.0)); float x_scale = y_scale / aspect_ratio; float depth_length = far_plane - near_plane; Eigen::Matrix4f Mdv = Eigen::Matrix4f::Identity(); Mdv.col(3) << 0.f, 0.f, 0.0f, 1.f; Eigen::Matrix4f Proj = createPerspectiveMatrix(fovy, aspect_ratio, near_plane, far_plane); Eigen::Vector4f p_clip = Proj * Mdv * p3d; Eigen::Vector3f p_ndc = (p_clip / p_clip.w()).head<3>(); Eigen::Vector3f p_window; p_window.x() = window_width / 2.0f * p_ndc.x() + window_width / 2.0f; p_window.y() = window_height / 2.0f * p_ndc.y() + window_height / 2.0f; p_window.z() = (far_plane - near_plane) / 2.0f * p_ndc.z() + (far_plane + near_plane) / 2.0f; Assert::IsTrue(pixel.isApprox(p_window, 0.01f)); } }; }<|endoftext|>
<commit_before>#include "UASRawStatusView.h" #include "MAVLinkDecoder.h" #include "UASInterface.h" #include "UAS.h" #include <QTimer> #include <QScrollBar> UASRawStatusView::UASRawStatusView(QWidget *parent) : QWidget(parent) { ui.setupUi(this); ui.tableWidget->setColumnCount(2); ui.tableWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn); ui.tableWidget->setShowGrid(false); ui.tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); QTimer *timer = new QTimer(this); connect(timer,SIGNAL(timeout()),this,SLOT(updateTableTimerTick())); // FIXME reinstate once fixed. timer->start(2000); } void UASRawStatusView::addSource(MAVLinkDecoder *decoder) { connect(decoder,SIGNAL(valueChanged(int,QString,QString,double,quint64)),this,SLOT(valueChanged(int,QString,QString,double,quint64))); connect(decoder,SIGNAL(valueChanged(int,QString,QString,qint8,quint64)),this,SLOT(valueChanged(int,QString,QString,qint8,quint64))); connect(decoder,SIGNAL(valueChanged(int,QString,QString,qint16,quint64)),this,SLOT(valueChanged(int,QString,QString,qint16,quint64))); connect(decoder,SIGNAL(valueChanged(int,QString,QString,qint32,quint64)),this,SLOT(valueChanged(int,QString,QString,qint32,quint64))); connect(decoder,SIGNAL(valueChanged(int,QString,QString,qint64,quint64)),this,SLOT(valueChanged(int,QString,QString,qint64,quint64))); connect(decoder,SIGNAL(valueChanged(int,QString,QString,quint8,quint64)),this,SLOT(valueChanged(int,QString,QString,quint8,quint64))); connect(decoder,SIGNAL(valueChanged(int,QString,QString,qint16,quint64)),this,SLOT(valueChanged(int,QString,QString,qint16,quint64))); connect(decoder,SIGNAL(valueChanged(int,QString,QString,quint32,quint64)),this,SLOT(valueChanged(int,QString,QString,quint32,quint64))); connect(decoder,SIGNAL(valueChanged(int,QString,QString,quint64,quint64)),this,SLOT(valueChanged(int,QString,QString,quint64,quint64))); } void UASRawStatusView::valueChanged(const int uasId, const QString& name, const QString& unit, const quint8 value, const quint64 msec) { valueChanged(uasId,name,unit,(double)value,msec); } void UASRawStatusView::valueChanged(const int uasId, const QString& name, const QString& unit, const qint8 value, const quint64 msec) { valueChanged(uasId,name,unit,(double)value,msec); } void UASRawStatusView::valueChanged(const int uasId, const QString& name, const QString& unit, const quint16 value, const quint64 msec) { valueChanged(uasId,name,unit,(double)value,msec); } void UASRawStatusView::valueChanged(const int uasId, const QString& name, const QString& unit, const qint16 value, const quint64 msec) { valueChanged(uasId,name,unit,(double)value,msec); } void UASRawStatusView::valueChanged(const int uasId, const QString& name, const QString& unit, const quint32 value, const quint64 msec) { valueChanged(uasId,name,unit,(double)value,msec); } void UASRawStatusView::valueChanged(const int uasId, const QString& name, const QString& unit, const qint32 value, const quint64 msec) { valueChanged(uasId,name,unit,(double)value,msec); } void UASRawStatusView::valueChanged(const int uasId, const QString& name, const QString& unit, const quint64 value, const quint64 msec) { valueChanged(uasId,name,unit,(double)value,msec); } void UASRawStatusView::valueChanged(const int uasId, const QString& name, const QString& unit, const qint64 value, const quint64 msec) { valueChanged(uasId,name,unit,(double)value,msec); } void UASRawStatusView::valueChanged(const int uasId, const QString& name, const QString& unit, const double value, const quint64 msec) { valueMap[name] = value; if (nameToUpdateWidgetMap.contains(name)) { nameToUpdateWidgetMap[name]->setText(QString::number(value)); } else { m_tableDirty = true; } return; } void UASRawStatusView::resizeEvent(QResizeEvent *event) { m_tableDirty = true; } void UASRawStatusView::updateTableTimerTick() { if (m_tableDirty) { m_tableDirty = false; int columncount = 2; bool good = false; while (!good) { ui.tableWidget->clear(); ui.tableWidget->setRowCount(0); ui.tableWidget->setColumnCount(columncount); ui.tableWidget->horizontalHeader()->hide(); ui.tableWidget->verticalHeader()->hide(); int currcolumn = 0; int currrow = 0; int totalheight = 2 + ui.tableWidget->horizontalScrollBar()->height(); bool broke = false; for (QMap<QString,double>::const_iterator i=valueMap.constBegin();i!=valueMap.constEnd();i++) { if (ui.tableWidget->rowCount() < currrow+1) { ui.tableWidget->setRowCount(currrow+1); } ui.tableWidget->setItem(currrow,currcolumn,new QTableWidgetItem(i.key().split(".")[1])); QTableWidgetItem *item = new QTableWidgetItem(QString::number(i.value())); nameToUpdateWidgetMap[i.key()] = item; ui.tableWidget->setItem(currrow,currcolumn+1,item); ui.tableWidget->resizeRowToContents(currrow); totalheight += ui.tableWidget->rowHeight(currrow); currrow++; if ((totalheight + ui.tableWidget->rowHeight(currrow-1)) > ui.tableWidget->height()) { currcolumn+=2; totalheight = 2 + ui.tableWidget->horizontalScrollBar()->height(); currrow = 0; if (currcolumn >= columncount) { //We're over what we can do. Add a column and continue. columncount+=2; broke = true; break; } } } if (!broke) { good = true; } } ui.tableWidget->resizeColumnsToContents(); //ui.tableWidget->columnCount()-2 } } UASRawStatusView::~UASRawStatusView() { } <commit_msg>Fix for a crash involving RawStatusView<commit_after>#include "UASRawStatusView.h" #include "MAVLinkDecoder.h" #include "UASInterface.h" #include "UAS.h" #include <QTimer> #include <QScrollBar> UASRawStatusView::UASRawStatusView(QWidget *parent) : QWidget(parent) { ui.setupUi(this); ui.tableWidget->setColumnCount(2); ui.tableWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn); ui.tableWidget->setShowGrid(false); ui.tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); QTimer *timer = new QTimer(this); connect(timer,SIGNAL(timeout()),this,SLOT(updateTableTimerTick())); // FIXME reinstate once fixed. timer->start(2000); } void UASRawStatusView::addSource(MAVLinkDecoder *decoder) { connect(decoder,SIGNAL(valueChanged(int,QString,QString,double,quint64)),this,SLOT(valueChanged(int,QString,QString,double,quint64))); connect(decoder,SIGNAL(valueChanged(int,QString,QString,qint8,quint64)),this,SLOT(valueChanged(int,QString,QString,qint8,quint64))); connect(decoder,SIGNAL(valueChanged(int,QString,QString,qint16,quint64)),this,SLOT(valueChanged(int,QString,QString,qint16,quint64))); connect(decoder,SIGNAL(valueChanged(int,QString,QString,qint32,quint64)),this,SLOT(valueChanged(int,QString,QString,qint32,quint64))); connect(decoder,SIGNAL(valueChanged(int,QString,QString,qint64,quint64)),this,SLOT(valueChanged(int,QString,QString,qint64,quint64))); connect(decoder,SIGNAL(valueChanged(int,QString,QString,quint8,quint64)),this,SLOT(valueChanged(int,QString,QString,quint8,quint64))); connect(decoder,SIGNAL(valueChanged(int,QString,QString,qint16,quint64)),this,SLOT(valueChanged(int,QString,QString,qint16,quint64))); connect(decoder,SIGNAL(valueChanged(int,QString,QString,quint32,quint64)),this,SLOT(valueChanged(int,QString,QString,quint32,quint64))); connect(decoder,SIGNAL(valueChanged(int,QString,QString,quint64,quint64)),this,SLOT(valueChanged(int,QString,QString,quint64,quint64))); } void UASRawStatusView::valueChanged(const int uasId, const QString& name, const QString& unit, const quint8 value, const quint64 msec) { valueChanged(uasId,name,unit,(double)value,msec); } void UASRawStatusView::valueChanged(const int uasId, const QString& name, const QString& unit, const qint8 value, const quint64 msec) { valueChanged(uasId,name,unit,(double)value,msec); } void UASRawStatusView::valueChanged(const int uasId, const QString& name, const QString& unit, const quint16 value, const quint64 msec) { valueChanged(uasId,name,unit,(double)value,msec); } void UASRawStatusView::valueChanged(const int uasId, const QString& name, const QString& unit, const qint16 value, const quint64 msec) { valueChanged(uasId,name,unit,(double)value,msec); } void UASRawStatusView::valueChanged(const int uasId, const QString& name, const QString& unit, const quint32 value, const quint64 msec) { valueChanged(uasId,name,unit,(double)value,msec); } void UASRawStatusView::valueChanged(const int uasId, const QString& name, const QString& unit, const qint32 value, const quint64 msec) { valueChanged(uasId,name,unit,(double)value,msec); } void UASRawStatusView::valueChanged(const int uasId, const QString& name, const QString& unit, const quint64 value, const quint64 msec) { valueChanged(uasId,name,unit,(double)value,msec); } void UASRawStatusView::valueChanged(const int uasId, const QString& name, const QString& unit, const qint64 value, const quint64 msec) { valueChanged(uasId,name,unit,(double)value,msec); } void UASRawStatusView::valueChanged(const int uasId, const QString& name, const QString& unit, const double value, const quint64 msec) { valueMap[name] = value; if (nameToUpdateWidgetMap.contains(name)) { nameToUpdateWidgetMap[name]->setText(QString::number(value)); } else { m_tableDirty = true; } return; } void UASRawStatusView::resizeEvent(QResizeEvent *event) { m_tableDirty = true; } void UASRawStatusView::updateTableTimerTick() { if (m_tableDirty) { m_tableDirty = false; int columncount = 2; bool good = false; while (!good) { ui.tableWidget->clear(); ui.tableWidget->setRowCount(0); ui.tableWidget->setColumnCount(columncount); ui.tableWidget->horizontalHeader()->hide(); ui.tableWidget->verticalHeader()->hide(); int currcolumn = 0; int currrow = 0; int totalheight = 2 + ui.tableWidget->horizontalScrollBar()->height(); bool broke = false; for (QMap<QString,double>::const_iterator i=valueMap.constBegin();i!=valueMap.constEnd();i++) { if (ui.tableWidget->rowCount() < currrow+1) { ui.tableWidget->setRowCount(currrow+1); } ui.tableWidget->setItem(currrow,currcolumn,new QTableWidgetItem(i.key().split(".")[1])); QTableWidgetItem *item = new QTableWidgetItem(QString::number(i.value())); nameToUpdateWidgetMap[i.key()] = item; ui.tableWidget->setItem(currrow,currcolumn+1,item); ui.tableWidget->resizeRowToContents(currrow); totalheight += ui.tableWidget->rowHeight(currrow); currrow++; if ((totalheight + ui.tableWidget->rowHeight(currrow-1)) > ui.tableWidget->height()) { currcolumn+=2; totalheight = 2 + ui.tableWidget->horizontalScrollBar()->height(); currrow = 0; if (currcolumn >= columncount) { //We're over what we can do. Add a column and continue. columncount+=2; broke = true; i = valueMap.constEnd(); // Ensure loop breakout. break; } } } if (!broke) { good = true; } } ui.tableWidget->resizeColumnsToContents(); //ui.tableWidget->columnCount()-2 } } UASRawStatusView::~UASRawStatusView() { } <|endoftext|>
<commit_before>#include "CompositePath.hpp" using namespace std; using namespace Geometry2d; namespace Planning { CompositePath::CompositePath(unique_ptr<Path> path) { append(std::move(path)); } CompositePath::CompositePath(Path *path) { append(path); } void CompositePath::append(Path *path) { append(std::unique_ptr<Path>(path)); } void CompositePath::append(unique_ptr<Path> path) { if (duration < std::numeric_limits<float>::infinity()) { float pathDuration = path->getDuration(); if (pathDuration > 0) { duration += pathDuration; paths.push_back(std::move(path)); } else { debugThrow(invalid_argument("The path passed is invalid")); } } else { debugThrow(runtime_error("You can't append to this path. It is already infinitely long.")); } } bool CompositePath::evaluate(float t, Point &targetPosOut, Point &targetVelOut) const { if (paths.empty()) { return false; } if (t<0) { return false; } for (const std::unique_ptr<Path> &path: paths) { float timeLength = path->getDuration(); t -= timeLength; if (t<=0 || timeLength == -1) { t += timeLength; path->evaluate(t, targetPosOut, targetVelOut); return true; } } targetPosOut = destination().get(); targetVelOut = Point(0,0); return false; } bool CompositePath::hit(const CompositeShape &shape, float startTime) const { if (paths.empty()) { return false; } int start = 0; for (const std::unique_ptr<Path> &path: paths) { start++; float timeLength = path->getDuration(); if (timeLength == -1) { return path->hit(shape, startTime); } startTime -= timeLength; if (startTime<=0) { startTime += timeLength; if (path->hit(shape, startTime)) { return true; } break; } } for (;start<paths.size(); start++) { if (paths[start]->hit(shape)) { return true; } } return false; } void CompositePath::draw(SystemState * const state, const QColor &color, const QString &layer) const { for (const std::unique_ptr<Path> &path: paths) { path->draw(state, color, layer); } } float CompositePath::getDuration() const { return duration; } boost::optional<Point> CompositePath::destination() const { if (paths.empty()) { return boost::none; } return paths.back()->destination(); } unique_ptr<Path> CompositePath::subPath(float startTime, float endTime) const { //Check for valid arguments if (startTime<0) { throw invalid_argument("CompositePath::subPath(): startTime(" + to_string(startTime) + ") can't be less than zero"); } if (endTime<0) { throw invalid_argument("CompositePath::subPath(): endTime(" + to_string(endTime) + ") can't be less than zero"); } if (startTime > endTime) { throw invalid_argument("CompositePath::subPath(): startTime(" + to_string(startTime) + ") can't be after endTime(" + to_string(endTime) + ")"); } if (startTime >= duration) { debugThrow(invalid_argument("CompositePath::subPath(): startTime(" + to_string(startTime) + ") can't be greater than the duration(" + to_string(duration) + ") of the path")); return unique_ptr<Path>(new CompositePath()); } if (startTime == 0 && endTime>=duration) { return this->clone(); } //Find the first Path in the vector of paths which will be included in the subPath size_t start = 0; float time = 0; float lastTime = 0; while (time <= startTime) { lastTime = paths[start]->getDuration(); time += lastTime; start++; } //Get the time into the Path in the vector of paths which the subPath will start float firstStartTime = (time - lastTime); //If the path will only contain that one Path just return a subPath of that Path if (time >= endTime) { return paths[start-1]->subPath(startTime - firstStartTime, endTime - firstStartTime ); } else { //Create a CompositePath initialized with only that first path. CompositePath *path = new CompositePath(paths[start-1]->subPath(startTime - firstStartTime)); unique_ptr<Path> lastPath; size_t end; //Find the last Path in the vector of paths which will be included in the subPath and store it in lastPath if (endTime>= duration) { lastPath = paths.back()->clone(); end = paths.size()-1; } else { end = start; while (time<endTime) { lastTime = paths[start]->getDuration(); time += lastTime; end++; } end--; lastPath = paths[end]->subPath(0, endTime - (time - lastTime)); } //Add the ones in the middle while (start<end) { path->append(paths[start]->clone()); start++; } //Add the last one path->append(std::move(lastPath)); return unique_ptr<Path>(path); } } unique_ptr<Path> CompositePath::clone() const{ CompositePath *newPath = new CompositePath(); for (const unique_ptr<Path> &path: paths) { newPath->append(path->clone()); } return unique_ptr<Path>(newPath); } }<commit_msg>Get rid of unnecessary std::<commit_after>#include "CompositePath.hpp" using namespace std; using namespace Geometry2d; namespace Planning { CompositePath::CompositePath(unique_ptr<Path> path) { append(std::move(path)); } CompositePath::CompositePath(Path *path) { append(path); } void CompositePath::append(Path *path) { append(std::unique_ptr<Path>(path)); } void CompositePath::append(unique_ptr<Path> path) { if (duration < numeric_limits<float>::infinity()) { float pathDuration = path->getDuration(); if (pathDuration > 0) { duration += pathDuration; paths.push_back(std::move(path)); } else { debugThrow(invalid_argument("The path passed is invalid")); } } else { debugThrow(runtime_error("You can't append to this path. It is already infinitely long.")); } } bool CompositePath::evaluate(float t, Point &targetPosOut, Point &targetVelOut) const { if (paths.empty()) { return false; } if (t<0) { return false; } for (const std::unique_ptr<Path> &path: paths) { float timeLength = path->getDuration(); t -= timeLength; if (t<=0 || timeLength == -1) { t += timeLength; path->evaluate(t, targetPosOut, targetVelOut); return true; } } targetPosOut = destination().get(); targetVelOut = Point(0,0); return false; } bool CompositePath::hit(const CompositeShape &shape, float startTime) const { if (paths.empty()) { return false; } int start = 0; for (const std::unique_ptr<Path> &path: paths) { start++; float timeLength = path->getDuration(); if (timeLength == -1) { return path->hit(shape, startTime); } startTime -= timeLength; if (startTime<=0) { startTime += timeLength; if (path->hit(shape, startTime)) { return true; } break; } } for (;start<paths.size(); start++) { if (paths[start]->hit(shape)) { return true; } } return false; } void CompositePath::draw(SystemState * const state, const QColor &color, const QString &layer) const { for (const std::unique_ptr<Path> &path: paths) { path->draw(state, color, layer); } } float CompositePath::getDuration() const { return duration; } boost::optional<Point> CompositePath::destination() const { if (paths.empty()) { return boost::none; } return paths.back()->destination(); } unique_ptr<Path> CompositePath::subPath(float startTime, float endTime) const { //Check for valid arguments if (startTime<0) { throw invalid_argument("CompositePath::subPath(): startTime(" + to_string(startTime) + ") can't be less than zero"); } if (endTime<0) { throw invalid_argument("CompositePath::subPath(): endTime(" + to_string(endTime) + ") can't be less than zero"); } if (startTime > endTime) { throw invalid_argument("CompositePath::subPath(): startTime(" + to_string(startTime) + ") can't be after endTime(" + to_string(endTime) + ")"); } if (startTime >= duration) { debugThrow(invalid_argument("CompositePath::subPath(): startTime(" + to_string(startTime) + ") can't be greater than the duration(" + to_string(duration) + ") of the path")); return unique_ptr<Path>(new CompositePath()); } if (startTime == 0 && endTime>=duration) { return this->clone(); } //Find the first Path in the vector of paths which will be included in the subPath size_t start = 0; float time = 0; float lastTime = 0; while (time <= startTime) { lastTime = paths[start]->getDuration(); time += lastTime; start++; } //Get the time into the Path in the vector of paths which the subPath will start float firstStartTime = (time - lastTime); //If the path will only contain that one Path just return a subPath of that Path if (time >= endTime) { return paths[start-1]->subPath(startTime - firstStartTime, endTime - firstStartTime ); } else { //Create a CompositePath initialized with only that first path. CompositePath *path = new CompositePath(paths[start-1]->subPath(startTime - firstStartTime)); unique_ptr<Path> lastPath; size_t end; //Find the last Path in the vector of paths which will be included in the subPath and store it in lastPath if (endTime>= duration) { lastPath = paths.back()->clone(); end = paths.size()-1; } else { end = start; while (time<endTime) { lastTime = paths[start]->getDuration(); time += lastTime; end++; } end--; lastPath = paths[end]->subPath(0, endTime - (time - lastTime)); } //Add the ones in the middle while (start<end) { path->append(paths[start]->clone()); start++; } //Add the last one path->append(std::move(lastPath)); return unique_ptr<Path>(path); } } unique_ptr<Path> CompositePath::clone() const{ CompositePath *newPath = new CompositePath(); for (const unique_ptr<Path> &path: paths) { newPath->append(path->clone()); } return unique_ptr<Path>(newPath); } }<|endoftext|>
<commit_before><commit_msg>Revert 56241 - Add an exceptionbarrier in Hook_Start(Ex). This is an attempt to reduce the amount of false positive crash reports - when exception is swallowed and is almost always not a problem due ChromeFrame code. BUG=51830<commit_after><|endoftext|>
<commit_before>#include <sstream> #include "Tools/Exception/exception.hpp" #include "matrix.h" namespace aff3ct { namespace tools { template <typename T, class AT = std::allocator<T>> inline void rgemm(const int M, const int N, const int K, const std::vector<T,AT> &A, const std::vector<T,AT> &tB, std::vector<T,AT> &tC) { if (A.size() != unsigned(M * K)) { std::stringstream message; message << "'A.size()' has to be equal to 'M' * 'K' ('A.size()' = " << A.size() << ", 'M' = " << M << ", 'K' = " << K << ")."; throw length_error(__FILE__, __LINE__, __func__, message.str()); } if (tB.size() != unsigned(K * N)) { std::stringstream message; message << "'tB.size()' has to be equal to 'K' * 'N' ('tB.size()' = " << tB.size() << ", 'K' = " << K << ", 'N' = " << N << ")."; throw length_error(__FILE__, __LINE__, __func__, message.str()); } if (tC.size() != unsigned(M * N)) { std::stringstream message; message << "'tC.size()' has to be equal to 'M' * 'N' ('tC.size()' = " << tC.size() << ", 'M' = " << M << ", 'N' = " << N << ")."; throw length_error(__FILE__, __LINE__, __func__, message.str()); } rgemm(M, N, K, A.data(), tB.data(), tC.data()); } template <typename T> inline void rgemm(const int M, const int N, const int K, const T *A, const T *tB, T *tC) { for (auto i = 0; i < M; i++) for (auto j = 0; j < N; j++) { T sum_r = 0; for (auto k = 0; k < K; k++) sum_r += A[i * K + k] * tB[j * K + k]; tC[j * M + i] = sum_r; } } template <typename T, class AT = std::allocator<T>> inline void cgemm(const int M, const int N, const int K, const std::vector<T,AT> &A, const std::vector<T,AT> &tB, std::vector<T,AT> &tC) { if (A.size() != unsigned(M * K * 2)) { std::stringstream message; message << "'A.size()' has to be equal to 'M' * 'K' * 2 ('A.size()' = " << A.size() << ", 'M' = " << M << ", 'K' = " << K << ")."; throw length_error(__FILE__, __LINE__, __func__, message.str()); } if (tB.size() != unsigned(K * N * 2)) { std::stringstream message; message << "'tB.size()' has to be equal to 'K' * 'N' * 2 ('tB.size()' = " << tB.size() << ", 'K' = " << K << ", 'N' = " << N << ")."; throw length_error(__FILE__, __LINE__, __func__, message.str()); } if (tC.size() != unsigned(M * N * 2)) { std::stringstream message; message << "'tC.size()' has to be equal to 'M' * 'N' * 2 ('tC.size()' = " << tC.size() << ", 'M' = " << M << ", 'N' = " << N << ")."; throw length_error(__FILE__, __LINE__, __func__, message.str()); } cgemm(M, N, K, A.data(), tB.data(), tC.data()); } template <typename T> inline void cgemm(const int M, const int N, const int K, const T *A, const T *tB, T *tC) { const T* A_real = A; const T* A_imag = A + ((M * K) >> 1); const T* tB_real = tB; const T* tB_imag = tB + ((N * K) >> 1); T* tC_real = tC; T* tC_imag = tC + ((M * N) >> 1); for (auto i = 0; i < M; i++) { for (auto j = 0; j < N; j++) { T sum_r = 0, sum_i = 0; for (auto k = 0; k < K; k++) { sum_r += A_real[i * K + k] * tB_real[j * K + k] - A_imag[i * K + k] * tB_imag[j * K + k]; sum_i += A_imag[i * K + k] * tB_real[j * K + k] + A_real[i * K + k] * tB_imag[j * K + k]; } tC_real[j * M + i] = sum_r; tC_imag[j * M + i] = sum_i; } } } template <typename T, class AT = std::allocator<T>> inline void cgemm_r(const int M, const int N, const int K, const std::vector<T,AT> &A, const std::vector<T,AT> &tB, std::vector<T,AT> &tC) { if (A.size() != unsigned(M * K * 2)) { std::stringstream message; message << "'A.size()' has to be equal to 'M' * 'K' * 2 ('A.size()' = " << A.size() << ", 'M' = " << M << ", 'K' = " << K << ")."; throw length_error(__FILE__, __LINE__, __func__, message.str()); } if (tB.size() != unsigned(K * N * 2)) { std::stringstream message; message << "'tB.size()' has to be equal to 'K' * 'N' * 2 ('tB.size()' = " << tB.size() << ", 'K' = " << K << ", 'N' = " << N << ")."; throw length_error(__FILE__, __LINE__, __func__, message.str()); } if (tC.size() != unsigned(M * N * 1)) { std::stringstream message; message << "'tC.size()' has to be equal to 'M' * 'N' * 1 ('tC.size()' = " << tC.size() << ", 'M' = " << M << ", 'N' = " << N << ")."; throw length_error(__FILE__, __LINE__, __func__, message.str()); } cgemm_r(M, N, K, A.data(), tB.data(), tC.data()); } template <typename T> inline void cgemm_r(const int M, const int N, const int K, const T *A, const T *tB, T *tC) { const T* A_real = A; const T* A_imag = A + ((M * K) >> 1); const T* tB_real = tB; const T* tB_imag = tB + ((N * K) >> 1); T* tC_real = tC; for (auto i = 0; i < M; i++) { for (auto j = 0; j < N; j++) { T sum_r = 0; for (auto k = 0; k < K; k++) sum_r += A_real[i * K + k] * tB_real[j * K + k] - A_imag[i * K + k] * tB_imag[j * K + k]; tC_real[j * M + i] = sum_r; } } } template <typename T, class AT = std::allocator<T>> inline void real_transpose(const int M, const int N, const std::vector<T,AT> &A, std::vector<T,AT> &B) { if (A.size() != unsigned(M * N)) { std::stringstream message; message << "'A.size()' has to be equal to 'M' * 'N' ('A.size()' = " << A.size() << ", 'M' = " << M << ", 'N' = " << N << ")."; throw length_error(__FILE__, __LINE__, __func__, message.str()); } if (B.size() != unsigned(N * M)) { std::stringstream message; message << "'B.size()' has to be equal to 'N' * 'M' ('B.size()' = " << B.size() << ", 'N' = " << N << ", 'M' = " << M << ")."; throw length_error(__FILE__, __LINE__, __func__, message.str()); } real_transpose(M, N, A.data(), B.data()); } template <typename T> inline void real_transpose(const int M, const int N, const T *A, T *B) { for (auto i = 0; i < M; i++) for (auto j = 0; j < N; j++) B[j*M+i] = A[i*N+j]; } template <typename T, class AT = std::allocator<T>> inline void complex_transpose(const int M, const int N, const std::vector<T,AT> &A, std::vector<T,AT> &B) { if (A.size() != unsigned(M * N * 2)) { std::stringstream message; message << "'A.size()' has to be equal to 'M' * 'N' * 2 ('A.size()' = " << A.size() << ", 'M' = " << M << ", 'N' = " << N << ")."; throw length_error(__FILE__, __LINE__, __func__, message.str()); } if (B.size() != unsigned(N * M * 2)) { std::stringstream message; message << "'B.size()' has to be equal to 'N' * 'M' * 2 ('B.size()' = " << B.size() << ", 'N' = " << N << ", 'M' = " << M << ")."; throw length_error(__FILE__, __LINE__, __func__, message.str()); } complex_transpose(M, N, A.data(), B.data()); } template <typename T> inline void complex_transpose(const int M, const int N, const T *A, T *B) { const T* A_real = A; const T* A_imag = A + M * N; T* B_real = B; T* B_imag = B + M * N; for (auto i = 0; i < M; i++) { for (auto j = 0; j < N; j++) { B_real[j*M+i] = A_real[i*N+j]; B_imag[j*M+i] = -A_imag[i*N+j]; } } } } } <commit_msg>Fix compilation errors on MSVC.<commit_after>#include <sstream> #include "Tools/Exception/exception.hpp" #include "matrix.h" namespace aff3ct { namespace tools { template <typename T, class AT> inline void rgemm(const int M, const int N, const int K, const std::vector<T,AT> &A, const std::vector<T,AT> &tB, std::vector<T,AT> &tC) { if (A.size() != unsigned(M * K)) { std::stringstream message; message << "'A.size()' has to be equal to 'M' * 'K' ('A.size()' = " << A.size() << ", 'M' = " << M << ", 'K' = " << K << ")."; throw length_error(__FILE__, __LINE__, __func__, message.str()); } if (tB.size() != unsigned(K * N)) { std::stringstream message; message << "'tB.size()' has to be equal to 'K' * 'N' ('tB.size()' = " << tB.size() << ", 'K' = " << K << ", 'N' = " << N << ")."; throw length_error(__FILE__, __LINE__, __func__, message.str()); } if (tC.size() != unsigned(M * N)) { std::stringstream message; message << "'tC.size()' has to be equal to 'M' * 'N' ('tC.size()' = " << tC.size() << ", 'M' = " << M << ", 'N' = " << N << ")."; throw length_error(__FILE__, __LINE__, __func__, message.str()); } rgemm(M, N, K, A.data(), tB.data(), tC.data()); } template <typename T> inline void rgemm(const int M, const int N, const int K, const T *A, const T *tB, T *tC) { for (auto i = 0; i < M; i++) for (auto j = 0; j < N; j++) { T sum_r = 0; for (auto k = 0; k < K; k++) sum_r += A[i * K + k] * tB[j * K + k]; tC[j * M + i] = sum_r; } } template <typename T, class AT> inline void cgemm(const int M, const int N, const int K, const std::vector<T,AT> &A, const std::vector<T,AT> &tB, std::vector<T,AT> &tC) { if (A.size() != unsigned(M * K * 2)) { std::stringstream message; message << "'A.size()' has to be equal to 'M' * 'K' * 2 ('A.size()' = " << A.size() << ", 'M' = " << M << ", 'K' = " << K << ")."; throw length_error(__FILE__, __LINE__, __func__, message.str()); } if (tB.size() != unsigned(K * N * 2)) { std::stringstream message; message << "'tB.size()' has to be equal to 'K' * 'N' * 2 ('tB.size()' = " << tB.size() << ", 'K' = " << K << ", 'N' = " << N << ")."; throw length_error(__FILE__, __LINE__, __func__, message.str()); } if (tC.size() != unsigned(M * N * 2)) { std::stringstream message; message << "'tC.size()' has to be equal to 'M' * 'N' * 2 ('tC.size()' = " << tC.size() << ", 'M' = " << M << ", 'N' = " << N << ")."; throw length_error(__FILE__, __LINE__, __func__, message.str()); } cgemm(M, N, K, A.data(), tB.data(), tC.data()); } template <typename T> inline void cgemm(const int M, const int N, const int K, const T *A, const T *tB, T *tC) { const T* A_real = A; const T* A_imag = A + ((M * K) >> 1); const T* tB_real = tB; const T* tB_imag = tB + ((N * K) >> 1); T* tC_real = tC; T* tC_imag = tC + ((M * N) >> 1); for (auto i = 0; i < M; i++) { for (auto j = 0; j < N; j++) { T sum_r = 0, sum_i = 0; for (auto k = 0; k < K; k++) { sum_r += A_real[i * K + k] * tB_real[j * K + k] - A_imag[i * K + k] * tB_imag[j * K + k]; sum_i += A_imag[i * K + k] * tB_real[j * K + k] + A_real[i * K + k] * tB_imag[j * K + k]; } tC_real[j * M + i] = sum_r; tC_imag[j * M + i] = sum_i; } } } template <typename T, class AT> inline void cgemm_r(const int M, const int N, const int K, const std::vector<T,AT> &A, const std::vector<T,AT> &tB, std::vector<T,AT> &tC) { if (A.size() != unsigned(M * K * 2)) { std::stringstream message; message << "'A.size()' has to be equal to 'M' * 'K' * 2 ('A.size()' = " << A.size() << ", 'M' = " << M << ", 'K' = " << K << ")."; throw length_error(__FILE__, __LINE__, __func__, message.str()); } if (tB.size() != unsigned(K * N * 2)) { std::stringstream message; message << "'tB.size()' has to be equal to 'K' * 'N' * 2 ('tB.size()' = " << tB.size() << ", 'K' = " << K << ", 'N' = " << N << ")."; throw length_error(__FILE__, __LINE__, __func__, message.str()); } if (tC.size() != unsigned(M * N * 1)) { std::stringstream message; message << "'tC.size()' has to be equal to 'M' * 'N' * 1 ('tC.size()' = " << tC.size() << ", 'M' = " << M << ", 'N' = " << N << ")."; throw length_error(__FILE__, __LINE__, __func__, message.str()); } cgemm_r(M, N, K, A.data(), tB.data(), tC.data()); } template <typename T> inline void cgemm_r(const int M, const int N, const int K, const T *A, const T *tB, T *tC) { const T* A_real = A; const T* A_imag = A + ((M * K) >> 1); const T* tB_real = tB; const T* tB_imag = tB + ((N * K) >> 1); T* tC_real = tC; for (auto i = 0; i < M; i++) { for (auto j = 0; j < N; j++) { T sum_r = 0; for (auto k = 0; k < K; k++) sum_r += A_real[i * K + k] * tB_real[j * K + k] - A_imag[i * K + k] * tB_imag[j * K + k]; tC_real[j * M + i] = sum_r; } } } template <typename T, class AT> inline void real_transpose(const int M, const int N, const std::vector<T,AT> &A, std::vector<T,AT> &B) { if (A.size() != unsigned(M * N)) { std::stringstream message; message << "'A.size()' has to be equal to 'M' * 'N' ('A.size()' = " << A.size() << ", 'M' = " << M << ", 'N' = " << N << ")."; throw length_error(__FILE__, __LINE__, __func__, message.str()); } if (B.size() != unsigned(N * M)) { std::stringstream message; message << "'B.size()' has to be equal to 'N' * 'M' ('B.size()' = " << B.size() << ", 'N' = " << N << ", 'M' = " << M << ")."; throw length_error(__FILE__, __LINE__, __func__, message.str()); } real_transpose(M, N, A.data(), B.data()); } template <typename T> inline void real_transpose(const int M, const int N, const T *A, T *B) { for (auto i = 0; i < M; i++) for (auto j = 0; j < N; j++) B[j*M+i] = A[i*N+j]; } template <typename T, class AT> inline void complex_transpose(const int M, const int N, const std::vector<T,AT> &A, std::vector<T,AT> &B) { if (A.size() != unsigned(M * N * 2)) { std::stringstream message; message << "'A.size()' has to be equal to 'M' * 'N' * 2 ('A.size()' = " << A.size() << ", 'M' = " << M << ", 'N' = " << N << ")."; throw length_error(__FILE__, __LINE__, __func__, message.str()); } if (B.size() != unsigned(N * M * 2)) { std::stringstream message; message << "'B.size()' has to be equal to 'N' * 'M' * 2 ('B.size()' = " << B.size() << ", 'N' = " << N << ", 'M' = " << M << ")."; throw length_error(__FILE__, __LINE__, __func__, message.str()); } complex_transpose(M, N, A.data(), B.data()); } template <typename T> inline void complex_transpose(const int M, const int N, const T *A, T *B) { const T* A_real = A; const T* A_imag = A + M * N; T* B_real = B; T* B_imag = B + M * N; for (auto i = 0; i < M; i++) { for (auto j = 0; j < N; j++) { B_real[j*M+i] = A_real[i*N+j]; B_imag[j*M+i] = -A_imag[i*N+j]; } } } } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Andre Hartmann <[email protected]> ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include <utils/ansiescapecodehandler.h> #include <QString> #include <QtTest> using namespace Utils; typedef QList<StringFormatPair> ResultList; Q_DECLARE_METATYPE(QTextCharFormat); Q_DECLARE_METATYPE(StringFormatPair); Q_DECLARE_METATYPE(ResultList); static QString ansiEscape(const QByteArray &sequence) { return QString::fromLatin1("\x1b[" + sequence); } class tst_AnsiEscapeCodeHandler : public QObject { Q_OBJECT public: tst_AnsiEscapeCodeHandler(); private Q_SLOTS: void testCase1(); void testCase1_data(); private: const QString red; const QString bold; const QString normal; const QString normal1; }; tst_AnsiEscapeCodeHandler::tst_AnsiEscapeCodeHandler() : red(ansiEscape("31m")), bold(ansiEscape("1m")), normal(ansiEscape("0m")), normal1(ansiEscape("m")) { } void tst_AnsiEscapeCodeHandler::testCase1() { QFETCH(QString, text); QFETCH(QTextCharFormat, format); QFETCH(ResultList, expected); AnsiEscapeCodeHandler handler; ResultList result = handler.parseText(text, format); handler.endFormatScope(); QVERIFY(result.size() == expected.size()); for (int i = 0; i < result.size(); ++i) { QVERIFY(result[i].first == expected[i].first); QVERIFY(result[i].second == expected[i].second); } } void tst_AnsiEscapeCodeHandler::testCase1_data() { QTest::addColumn<QString>("text"); QTest::addColumn<QTextCharFormat>("format"); QTest::addColumn<ResultList>("expected"); // Test pass-through QTextCharFormat defaultFormat; QTest::newRow("Pass-through") << "Hello World" << defaultFormat << (ResultList() << StringFormatPair("Hello World", defaultFormat)); // Test text-color change QTextCharFormat redFormat; redFormat.setForeground(QColor(170, 0, 0)); const QString text2 = "This is " + red + "red" + normal + " text"; QTest::newRow("Text-color change") << text2 << QTextCharFormat() << (ResultList() << StringFormatPair("This is ", defaultFormat) << StringFormatPair("red", redFormat) << StringFormatPair(" text", defaultFormat)); // Test text format change to bold QTextCharFormat boldFormat; boldFormat.setFontWeight(QFont::Bold); const QString text3 = "A line of " + bold + "bold" + normal + " text"; QTest::newRow("Text-format change") << text3 << QTextCharFormat() << (ResultList() << StringFormatPair("A line of ", defaultFormat) << StringFormatPair("bold", boldFormat) << StringFormatPair(" text", defaultFormat)); // Test resetting format to normal with other reset pattern const QString text4 = "A line of " + bold + "bold" + normal1 + " text"; QTest::newRow("Alternative reset pattern (QTCREATORBUG-10132)") << text4 << QTextCharFormat() << (ResultList() << StringFormatPair("A line of ", defaultFormat) << StringFormatPair("bold", boldFormat) << StringFormatPair(" text", defaultFormat)); } QTEST_APPLESS_MAIN(tst_AnsiEscapeCodeHandler) #include "tst_ansiescapecodehandler.moc" <commit_msg>ANSI: Use QCOMPARE instead of QVERIFY<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Andre Hartmann <[email protected]> ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include <utils/ansiescapecodehandler.h> #include <QString> #include <QtTest> using namespace Utils; typedef QList<StringFormatPair> ResultList; Q_DECLARE_METATYPE(QTextCharFormat); Q_DECLARE_METATYPE(StringFormatPair); Q_DECLARE_METATYPE(ResultList); static QString ansiEscape(const QByteArray &sequence) { return QString::fromLatin1("\x1b[" + sequence); } class tst_AnsiEscapeCodeHandler : public QObject { Q_OBJECT public: tst_AnsiEscapeCodeHandler(); private Q_SLOTS: void testCase1(); void testCase1_data(); private: const QString red; const QString bold; const QString normal; const QString normal1; }; tst_AnsiEscapeCodeHandler::tst_AnsiEscapeCodeHandler() : red(ansiEscape("31m")), bold(ansiEscape("1m")), normal(ansiEscape("0m")), normal1(ansiEscape("m")) { } void tst_AnsiEscapeCodeHandler::testCase1() { QFETCH(QString, text); QFETCH(QTextCharFormat, format); QFETCH(ResultList, expected); AnsiEscapeCodeHandler handler; ResultList result = handler.parseText(text, format); handler.endFormatScope(); QCOMPARE(result.size(), expected.size()); for (int i = 0; i < result.size(); ++i) { QCOMPARE(result[i].first, expected[i].first); QCOMPARE(result[i].second, expected[i].second); } } void tst_AnsiEscapeCodeHandler::testCase1_data() { QTest::addColumn<QString>("text"); QTest::addColumn<QTextCharFormat>("format"); QTest::addColumn<ResultList>("expected"); // Test pass-through QTextCharFormat defaultFormat; QTest::newRow("Pass-through") << "Hello World" << defaultFormat << (ResultList() << StringFormatPair("Hello World", defaultFormat)); // Test text-color change QTextCharFormat redFormat; redFormat.setForeground(QColor(170, 0, 0)); const QString text2 = "This is " + red + "red" + normal + " text"; QTest::newRow("Text-color change") << text2 << QTextCharFormat() << (ResultList() << StringFormatPair("This is ", defaultFormat) << StringFormatPair("red", redFormat) << StringFormatPair(" text", defaultFormat)); // Test text format change to bold QTextCharFormat boldFormat; boldFormat.setFontWeight(QFont::Bold); const QString text3 = "A line of " + bold + "bold" + normal + " text"; QTest::newRow("Text-format change") << text3 << QTextCharFormat() << (ResultList() << StringFormatPair("A line of ", defaultFormat) << StringFormatPair("bold", boldFormat) << StringFormatPair(" text", defaultFormat)); // Test resetting format to normal with other reset pattern const QString text4 = "A line of " + bold + "bold" + normal1 + " text"; QTest::newRow("Alternative reset pattern (QTCREATORBUG-10132)") << text4 << QTextCharFormat() << (ResultList() << StringFormatPair("A line of ", defaultFormat) << StringFormatPair("bold", boldFormat) << StringFormatPair(" text", defaultFormat)); } QTEST_APPLESS_MAIN(tst_AnsiEscapeCodeHandler) #include "tst_ansiescapecodehandler.moc" <|endoftext|>
<commit_before><commit_msg>planning: add check upon mkstemp() return value<commit_after><|endoftext|>
<commit_before>#include <boost/lexical_cast.hpp> #include <sstream> #include <limits> #include <string> #include "util/numconversions.h" #include <iostream> #include "zorba/common.h" namespace xqp { bool NumConversions::isNegZero(const xqpString& aStr) { xqpString lStr = aStr.trim(" \n\r\t", 4); size_t lLength = aStr.length(); const char* lChars = aStr.c_str(); if (lChars[0] == '-') { for(size_t i = 1; i < lLength; ++i) { if (lChars[i] != '0') { return false; } } return true; } else { return false; } } short NumConversions::isInfOrNan(const char* aCharStar) { #ifdef HAVE_STRCASECMP_FUNCTION if (strcasecmp(aCharStar, "inf") == 0 || strcasecmp(aCharStar, "+inf") == 0 ) #else if (_stricmp(aCharStar, "inf") == 0 || _stricmp(aCharStar, "+inf") == 0 ) #endif { return 1; } #ifdef HAVE_STRCASECMP_FUNCTION else if (strcasecmp(aCharStar, "-inf") == 0 ) #else else if (_stricmp(aCharStar, "-inf") == 0 ) #endif { return -1; } #ifdef HAVE_STRCASECMP_FUNCTION else if (strcasecmp(aCharStar, "nan") == 0 ) #else else if (_stricmp(aCharStar, "nan") == 0 ) #endif { return 0; } else { return -2; } } bool NumConversions::strToInteger(const xqpString& aStr, xqp_integer& aInteger){ try { aInteger = boost::lexical_cast<xqp_integer>(aStr.c_str()); return true; } catch (boost::bad_lexical_cast &) { return false; } } xqpString NumConversions::integerToStr(xqp_integer aInteger){ return boost::lexical_cast<std::string>(aInteger); } bool NumConversions::strToUInteger(const xqpString& aStr, xqp_uinteger& aUInteger){ try { aUInteger = boost::lexical_cast<xqp_uinteger>(aStr.c_str()); return true; } catch (boost::bad_lexical_cast &) { return false; } } xqpString NumConversions::uintegerToStr(xqp_uinteger aUInteger){ return boost::lexical_cast<std::string>(aUInteger); } bool NumConversions::starCharToInt(const char* aStarChar, xqp_int& aInt){ try { aInt = boost::lexical_cast<xqp_int>(aStarChar); return true; } catch (boost::bad_lexical_cast &) { return false; } } bool NumConversions::strToInt(const xqpString& aStr, xqp_int& aInt) { return starCharToInt(aStr.c_str(), aInt); } xqpString NumConversions::intToStr(xqp_int aInt){ return boost::lexical_cast<std::string>(aInt); } bool NumConversions::strToUInt(const xqpString& aStr, xqp_uint& aUInt){ if ( isNegZero(aStr)) { aUInt = 0; return true; } try { aUInt = boost::lexical_cast<xqp_uint>(aStr.c_str()); return true; } catch (boost::bad_lexical_cast &) { return false; } } xqpString NumConversions::uintToStr(xqp_uint aUInt){ return boost::lexical_cast<std::string>(aUInt); } bool NumConversions::strToLong(const xqpString& aStr, xqp_long& aLong){ try { aLong = boost::lexical_cast<xqp_long>(aStr.c_str()); return true; } catch (boost::bad_lexical_cast &) { return false; } } xqpString NumConversions::longToStr(xqp_long aLong){ return boost::lexical_cast<std::string>(aLong); } bool NumConversions::strToULong(const xqpString& aStr, xqp_ulong& aULong){ if ( isNegZero(aStr)) { aULong = 0; return true; } try { aULong = boost::lexical_cast<xqp_ulong>(aStr.c_str()); return true; } catch (boost::bad_lexical_cast &) { return false; } } xqpString NumConversions::ulongToStr(xqp_ulong aULong){ return boost::lexical_cast<std::string>(aULong); } bool NumConversions::strToShort(const xqpString& aStr, xqp_short& aShort){ try { aShort = boost::lexical_cast<xqp_short>(aStr.c_str()); return true; } catch (boost::bad_lexical_cast &) { return false; } } xqpString NumConversions::shortToStr(xqp_short aShort){ return boost::lexical_cast<std::string>(aShort); } bool NumConversions::strToUShort(const xqpString& aStr, xqp_ushort& aUShort){ if ( isNegZero(aStr )) { aUShort = 0; return true; } try { aUShort = boost::lexical_cast<xqp_ushort>(aStr.c_str()); return true; } catch (boost::bad_lexical_cast &) { return false; } } xqpString NumConversions::ushortToStr(xqp_ushort aUShort){ return boost::lexical_cast<std::string>(aUShort); } bool NumConversions::starCharToDecimal(const char* aStarChar, xqp_decimal& aDecimal){ try { aDecimal = boost::lexical_cast<xqp_decimal>(aStarChar); return true; } catch (boost::bad_lexical_cast &) { return false; } } bool NumConversions::strToDecimal(const xqpString& aStr, xqp_decimal& aDecimal) { return starCharToDecimal(aStr.c_str(), aDecimal); } xqpString NumConversions::decimalToStr(xqp_decimal aDecimal){ return boost::lexical_cast<std::string>(aDecimal); } bool NumConversions::starCharToFloat(const char* aCharStar, xqp_float& aFloat) { char* lEndPtr; // Not all systems support strtof #ifdef HAVE_STRTOF_FUNCTION aFloat = strtof(aCharStar, &lEndPtr); #else // If strtof is not supported, zorba uses strtod // and makes a max, min check before casting to float xqp_double lTmpDouble = strtod(aCharStar, &lEndPtr); if (*lEndPtr == '\0') { // undef's are used because Windows has some makro definitions on min and max // => without undef, 'min()' and 'max()' would be replace by something # undef max # undef min if ( lTmpDouble > std::numeric_limits<xqp_float>::max() ) aFloat = std::numeric_limits<xqp_float>::infinity(); else if ( lTmpDouble < std::numeric_limits<xqp_float>::min() ) aFloat = -std::numeric_limits<xqp_float>::infinity(); else aFloat = static_cast<xqp_float>(lTmpDouble); } #endif if (*lEndPtr != '\0') { #ifdef UNIX return false; #else // Only for unix systems, we are sure that they can parse 'inf' and '-inf' correclty // => we try to do it by hand for all other systems in case of a parsing error short lInf = NumConversions::isInfOrNan(aCharStar); if (lInf == -1) { aFloat = -std::numeric_limits<xqp_float>::infinity(); return true; } else if (lInf == 1) { aFloat = std::numeric_limits<xqp_float>::infinity(); return true; } else if (lInf == 0) { Assert(std::numeric_limits<xqp_double>::has_quiet_NaN()); aFloat = std::numeric_limits<xqp_float>::quiet_NaN(); } else { return false; } #endif } return true; } bool NumConversions::strToFloat(const xqpString& aStr, xqp_float& aFloat){ return NumConversions::starCharToFloat(aStr.c_str(), aFloat); } xqpString NumConversions::floatToStr(xqp_float aFloat){ if (aFloat == std::numeric_limits<xqp_float>::infinity()) return "INF"; else if (aFloat == -std::numeric_limits<xqp_float>::infinity()) return "-INF"; else if (aFloat != aFloat) return "NaN"; else { std::stringstream lStream; lStream << aFloat; return lStream.str(); } } bool NumConversions::starCharToDouble(const char* aCharStar, xqp_double& aDouble){ char* lEndPtr; aDouble = strtod(aCharStar, &lEndPtr); if (*lEndPtr != '\0') { #ifdef UNIX return false; #else // Only for unix systems, we are sure that they can parse 'inf' and '-inf' correclty // => we try to do it by hand for all other systems in case of a parsing error short lInf = NumConversions::isInfOrNan(aCharStar); if (lInf == -1) { aDouble = -std::numeric_limits<xqp_double>::infinity(); return true; } else if (lInf == 1) { aDouble = std::numeric_limits<xqp_double>::infinity(); return true; } else if (lInf == 0) { Assert(std::numeric_limits<xqp_double>::has_quiet_NaN()); aDouble = std::numeric_limits<xqp_double>::quiet_NaN(); } else { return false; } #endif } return true; } bool NumConversions::strToDouble(const xqpString& aStr, xqp_double& aDouble) { return starCharToDouble(aStr.c_str(), aDouble); } xqpString NumConversions::doubleToStr(xqp_double aDouble){ if (aDouble == std::numeric_limits<xqp_double>::infinity()) return "INF"; else if (aDouble == -std::numeric_limits<xqp_double>::infinity()) return "-INF"; else if (aDouble != aDouble) return "NaN"; else { std::stringstream lStream; lStream << aDouble; return lStream.str(); } } bool NumConversions::strToByte(const xqpString& aStr, xqp_byte& aByte){ try { xqp_int lInt = boost::lexical_cast<xqp_int>(aStr.c_str()); if (lInt >= -128 && lInt <= 127) { aByte = lInt; return true; } else { return false; } } catch (boost::bad_lexical_cast &) { return false; } } xqpString NumConversions::byteToStr(xqp_byte aByte){ xqp_int lInt = aByte; return boost::lexical_cast<std::string>(lInt); } bool NumConversions::strToUByte(const xqpString& aStr, xqp_ubyte& aUByte){ if ( isNegZero(aStr)) { aUByte = 0; return true; } try { xqp_uint lUInt = boost::lexical_cast<xqp_uint>(aStr.c_str()); if (lUInt >= 0 && lUInt <= 255) { aUByte = lUInt; return true; } else { return false; } } catch (boost::bad_lexical_cast &) { return false; } } xqpString NumConversions::ubyteToStr(xqp_ubyte aUByte){ xqp_uint lUInt = aUByte; return boost::lexical_cast<std::string>(lUInt); } bool NumConversions::isNaN(xqp_double aDouble) { return aDouble != aDouble; } bool NumConversions::isNaN(xqp_float aFloat) { return aFloat != aFloat; } bool NumConversions::isPosOrNegInf(xqp_double aDouble) { return (aDouble == std::numeric_limits<xqp_double>::infinity() || aDouble == -std::numeric_limits<xqp_double>::infinity()); } bool NumConversions::isPosOrNegInf(xqp_float aFloat) { return (aFloat == std::numeric_limits<xqp_float>::infinity() || aFloat == -std::numeric_limits<xqp_float>::infinity()); } } /* namespace xqp */ <commit_msg>Comments added<commit_after>#include <boost/lexical_cast.hpp> #include <sstream> #include <limits> #include <string> #include "util/numconversions.h" #include <iostream> #include "zorba/common.h" namespace xqp { bool NumConversions::isNegZero(const xqpString& aStr) { xqpString lStr = aStr.trim(" \n\r\t", 4); size_t lLength = aStr.length(); const char* lChars = aStr.c_str(); if (lChars[0] == '-') { for(size_t i = 1; i < lLength; ++i) { if (lChars[i] != '0') { return false; } } return true; } else { return false; } } short NumConversions::isInfOrNan(const char* aCharStar) { #ifdef HAVE_STRCASECMP_FUNCTION if (strcasecmp(aCharStar, "inf") == 0 || strcasecmp(aCharStar, "+inf") == 0 ) #else if (_stricmp(aCharStar, "inf") == 0 || _stricmp(aCharStar, "+inf") == 0 ) #endif { return 1; } #ifdef HAVE_STRCASECMP_FUNCTION else if (strcasecmp(aCharStar, "-inf") == 0 ) #else else if (_stricmp(aCharStar, "-inf") == 0 ) #endif { return -1; } #ifdef HAVE_STRCASECMP_FUNCTION else if (strcasecmp(aCharStar, "nan") == 0 ) #else else if (_stricmp(aCharStar, "nan") == 0 ) #endif { return 0; } else { return -2; } } bool NumConversions::strToInteger(const xqpString& aStr, xqp_integer& aInteger){ try { aInteger = boost::lexical_cast<xqp_integer>(aStr.c_str()); return true; } catch (boost::bad_lexical_cast &) { return false; } } xqpString NumConversions::integerToStr(xqp_integer aInteger){ return boost::lexical_cast<std::string>(aInteger); } bool NumConversions::strToUInteger(const xqpString& aStr, xqp_uinteger& aUInteger){ try { aUInteger = boost::lexical_cast<xqp_uinteger>(aStr.c_str()); return true; } catch (boost::bad_lexical_cast &) { return false; } } xqpString NumConversions::uintegerToStr(xqp_uinteger aUInteger){ return boost::lexical_cast<std::string>(aUInteger); } bool NumConversions::starCharToInt(const char* aStarChar, xqp_int& aInt){ try { aInt = boost::lexical_cast<xqp_int>(aStarChar); return true; } catch (boost::bad_lexical_cast &) { return false; } } bool NumConversions::strToInt(const xqpString& aStr, xqp_int& aInt) { return starCharToInt(aStr.c_str(), aInt); } xqpString NumConversions::intToStr(xqp_int aInt){ return boost::lexical_cast<std::string>(aInt); } bool NumConversions::strToUInt(const xqpString& aStr, xqp_uint& aUInt){ if ( isNegZero(aStr)) { aUInt = 0; return true; } try { aUInt = boost::lexical_cast<xqp_uint>(aStr.c_str()); return true; } catch (boost::bad_lexical_cast &) { return false; } } xqpString NumConversions::uintToStr(xqp_uint aUInt){ return boost::lexical_cast<std::string>(aUInt); } bool NumConversions::strToLong(const xqpString& aStr, xqp_long& aLong){ try { aLong = boost::lexical_cast<xqp_long>(aStr.c_str()); return true; } catch (boost::bad_lexical_cast &) { return false; } } xqpString NumConversions::longToStr(xqp_long aLong){ return boost::lexical_cast<std::string>(aLong); } bool NumConversions::strToULong(const xqpString& aStr, xqp_ulong& aULong){ if ( isNegZero(aStr)) { aULong = 0; return true; } try { aULong = boost::lexical_cast<xqp_ulong>(aStr.c_str()); return true; } catch (boost::bad_lexical_cast &) { return false; } } xqpString NumConversions::ulongToStr(xqp_ulong aULong){ return boost::lexical_cast<std::string>(aULong); } bool NumConversions::strToShort(const xqpString& aStr, xqp_short& aShort){ try { aShort = boost::lexical_cast<xqp_short>(aStr.c_str()); return true; } catch (boost::bad_lexical_cast &) { return false; } } xqpString NumConversions::shortToStr(xqp_short aShort){ return boost::lexical_cast<std::string>(aShort); } bool NumConversions::strToUShort(const xqpString& aStr, xqp_ushort& aUShort){ if ( isNegZero(aStr )) { aUShort = 0; return true; } try { aUShort = boost::lexical_cast<xqp_ushort>(aStr.c_str()); return true; } catch (boost::bad_lexical_cast &) { return false; } } xqpString NumConversions::ushortToStr(xqp_ushort aUShort){ return boost::lexical_cast<std::string>(aUShort); } bool NumConversions::starCharToDecimal(const char* aStarChar, xqp_decimal& aDecimal){ try { aDecimal = boost::lexical_cast<xqp_decimal>(aStarChar); return true; } catch (boost::bad_lexical_cast &) { return false; } } bool NumConversions::strToDecimal(const xqpString& aStr, xqp_decimal& aDecimal) { return starCharToDecimal(aStr.c_str(), aDecimal); } xqpString NumConversions::decimalToStr(xqp_decimal aDecimal){ return boost::lexical_cast<std::string>(aDecimal); } bool NumConversions::starCharToFloat(const char* aCharStar, xqp_float& aFloat) { char* lEndPtr; // Not all systems support strtof #ifdef HAVE_STRTOF_FUNCTION aFloat = strtof(aCharStar, &lEndPtr); #else // If strtof is not supported, zorba uses strtod // and makes a max, min check before casting to float xqp_double lTmpDouble = strtod(aCharStar, &lEndPtr); if (*lEndPtr == '\0') { // undef's are used because Windows has some makro definitions on min and max // => without undef, 'min()' and 'max()' would be replace by something # undef max # undef min if ( lTmpDouble > std::numeric_limits<xqp_float>::max() ) aFloat = std::numeric_limits<xqp_float>::infinity(); else if ( lTmpDouble < std::numeric_limits<xqp_float>::min() ) aFloat = -std::numeric_limits<xqp_float>::infinity(); else aFloat = static_cast<xqp_float>(lTmpDouble); } #endif if (*lEndPtr != '\0') { #ifdef UNIX return false; #else // Only for unix systems, we are sure that they can parse 'inf' and '-inf' correclty // => we try to do it by hand for all other systems in case of a parsing error short lInf = NumConversions::isInfOrNan(aCharStar); if (lInf == -1) { aFloat = -std::numeric_limits<xqp_float>::infinity(); return true; } else if (lInf == 1) { aFloat = std::numeric_limits<xqp_float>::infinity(); return true; } else if (lInf == 0) { // TODO Handling when compiler does not support quiet_NaN Assert(std::numeric_limits<xqp_double>::has_quiet_NaN()); aFloat = std::numeric_limits<xqp_float>::quiet_NaN(); } else { return false; } #endif } return true; } bool NumConversions::strToFloat(const xqpString& aStr, xqp_float& aFloat){ return NumConversions::starCharToFloat(aStr.c_str(), aFloat); } xqpString NumConversions::floatToStr(xqp_float aFloat){ if (aFloat == std::numeric_limits<xqp_float>::infinity()) return "INF"; else if (aFloat == -std::numeric_limits<xqp_float>::infinity()) return "-INF"; else if (aFloat != aFloat) return "NaN"; else { std::stringstream lStream; lStream << aFloat; return lStream.str(); } } bool NumConversions::starCharToDouble(const char* aCharStar, xqp_double& aDouble){ char* lEndPtr; aDouble = strtod(aCharStar, &lEndPtr); if (*lEndPtr != '\0') { #ifdef UNIX return false; #else // Only for unix systems, we are sure that they can parse 'inf' and '-inf' correclty // => we try to do it by hand for all other systems in case of a parsing error short lInf = NumConversions::isInfOrNan(aCharStar); if (lInf == -1) { aDouble = -std::numeric_limits<xqp_double>::infinity(); return true; } else if (lInf == 1) { aDouble = std::numeric_limits<xqp_double>::infinity(); return true; } else if (lInf == 0) { // TODO Handling when compiler does not suppoert quiet_NaN Assert(std::numeric_limits<xqp_double>::has_quiet_NaN()); aDouble = std::numeric_limits<xqp_double>::quiet_NaN(); } else { return false; } #endif } return true; } bool NumConversions::strToDouble(const xqpString& aStr, xqp_double& aDouble) { return starCharToDouble(aStr.c_str(), aDouble); } xqpString NumConversions::doubleToStr(xqp_double aDouble){ if (aDouble == std::numeric_limits<xqp_double>::infinity()) return "INF"; else if (aDouble == -std::numeric_limits<xqp_double>::infinity()) return "-INF"; else if (aDouble != aDouble) return "NaN"; else { std::stringstream lStream; lStream << aDouble; return lStream.str(); } } bool NumConversions::strToByte(const xqpString& aStr, xqp_byte& aByte){ try { xqp_int lInt = boost::lexical_cast<xqp_int>(aStr.c_str()); if (lInt >= -128 && lInt <= 127) { aByte = lInt; return true; } else { return false; } } catch (boost::bad_lexical_cast &) { return false; } } xqpString NumConversions::byteToStr(xqp_byte aByte){ xqp_int lInt = aByte; return boost::lexical_cast<std::string>(lInt); } bool NumConversions::strToUByte(const xqpString& aStr, xqp_ubyte& aUByte){ if ( isNegZero(aStr)) { aUByte = 0; return true; } try { xqp_uint lUInt = boost::lexical_cast<xqp_uint>(aStr.c_str()); if (lUInt >= 0 && lUInt <= 255) { aUByte = lUInt; return true; } else { return false; } } catch (boost::bad_lexical_cast &) { return false; } } xqpString NumConversions::ubyteToStr(xqp_ubyte aUByte){ xqp_uint lUInt = aUByte; return boost::lexical_cast<std::string>(lUInt); } bool NumConversions::isNaN(xqp_double aDouble) { return aDouble != aDouble; } bool NumConversions::isNaN(xqp_float aFloat) { return aFloat != aFloat; } bool NumConversions::isPosOrNegInf(xqp_double aDouble) { return (aDouble == std::numeric_limits<xqp_double>::infinity() || aDouble == -std::numeric_limits<xqp_double>::infinity()); } bool NumConversions::isPosOrNegInf(xqp_float aFloat) { return (aFloat == std::numeric_limits<xqp_float>::infinity() || aFloat == -std::numeric_limits<xqp_float>::infinity()); } } /* namespace xqp */ <|endoftext|>
<commit_before>/* * Copyright (c) 2018 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "test/test_main_lib.h" #include <fstream> #include <string> #include "absl/memory/memory.h" #include "rtc_base/checks.h" #include "rtc_base/flags.h" #include "rtc_base/logging.h" #include "rtc_base/thread.h" #include "system_wrappers/include/field_trial.h" #include "system_wrappers/include/metrics.h" #include "test/field_trial.h" #include "test/gmock.h" #include "test/gtest.h" #include "test/testsupport/fileutils.h" #include "test/testsupport/perf_test.h" #if defined(WEBRTC_WIN) #include "rtc_base/win32socketinit.h" #endif #if defined(WEBRTC_IOS) #include "test/ios/test_support.h" WEBRTC_DEFINE_string(NSTreatUnknownArgumentsAsOpen, "", "Intentionally ignored flag intended for iOS simulator."); WEBRTC_DEFINE_string(ApplePersistenceIgnoreState, "", "Intentionally ignored flag intended for iOS simulator."); WEBRTC_DEFINE_bool( save_chartjson_result, false, "Store the perf results in Documents/perf_result.json in the format " "described by " "https://github.com/catapult-project/catapult/blob/master/dashboard/docs/" "data-format.md."); #else WEBRTC_DEFINE_string( isolated_script_test_output, "", "Path to output an empty JSON file which Chromium infra requires."); WEBRTC_DEFINE_string( isolated_script_test_perf_output, "", "Path where the perf results should be stored in the JSON format described " "by " "https://github.com/catapult-project/catapult/blob/master/dashboard/docs/" "data-format.md."); #endif WEBRTC_DEFINE_bool(logs, false, "print logs to stderr"); WEBRTC_DEFINE_string( force_fieldtrials, "", "Field trials control experimental feature code which can be forced. " "E.g. running with --force_fieldtrials=WebRTC-FooFeature/Enable/" " will assign the group Enable to field trial WebRTC-FooFeature."); WEBRTC_DEFINE_bool(help, false, "Print this message."); namespace webrtc { namespace { class TestMainImpl : public TestMain { public: int Init(int* argc, char* argv[]) override { ::testing::InitGoogleMock(argc, argv); // Default to LS_INFO, even for release builds to provide better test // logging. // TODO(pbos): Consider adding a command-line override. if (rtc::LogMessage::GetLogToDebug() > rtc::LS_INFO) rtc::LogMessage::LogToDebug(rtc::LS_INFO); if (rtc::FlagList::SetFlagsFromCommandLine(argc, argv, false)) { return 1; } if (FLAG_help) { rtc::FlagList::Print(nullptr, false); return 0; } // TODO(bugs.webrtc.org/9792): we need to reference something from // fileutils.h so that our downstream hack where we replace fileutils.cc // works. Otherwise the downstream flag implementation will take over and // botch the flag introduced by the hack. Remove this awful thing once the // downstream implementation has been eliminated. (void)webrtc::test::JoinFilename("horrible", "hack"); webrtc::test::ValidateFieldTrialsStringOrDie(FLAG_force_fieldtrials); // InitFieldTrialsFromString stores the char*, so the char array must // outlive the application. webrtc::field_trial::InitFieldTrialsFromString(FLAG_force_fieldtrials); webrtc::metrics::Enable(); #if defined(WEBRTC_WIN) winsock_init_ = absl::make_unique<rtc::WinsockInitializer>(); #endif rtc::LogMessage::SetLogToStderr(FLAG_logs); // Ensure that main thread gets wrapped as an rtc::Thread. // TODO(bugs.webrt.org/9714): It might be better to avoid wrapping the main // thread, or leave it to individual tests that need it. But as long as we // have automatic thread wrapping, we need this to avoid that some other // random thread (which one depending on which tests are run) gets // automatically wrapped. rtc::ThreadManager::Instance()->WrapCurrentThread(); RTC_CHECK(rtc::Thread::Current()); return 0; } int Run(int argc, char* argv[]) override { #if defined(WEBRTC_IOS) rtc::test::InitTestSuite(RUN_ALL_TESTS, argc, argv, FLAG_save_chartjson_result); rtc::test::RunTestsFromIOSApp(); return 0; #else int exit_code = RUN_ALL_TESTS(); std::string chartjson_result_file = FLAG_isolated_script_test_perf_output; if (!chartjson_result_file.empty()) { webrtc::test::WritePerfResults(chartjson_result_file); } std::string result_filename = FLAG_isolated_script_test_output; if (!result_filename.empty()) { std::ofstream result_file(result_filename); result_file << "{\"version\": 3}"; result_file.close(); } #if defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \ defined(MEMORY_SANITIZER) || defined(THREAD_SANITIZER) || \ defined(UNDEFINED_SANITIZER) // We want the test flagged as failed only for sanitizer defects, // in which case the sanitizer will override exit code with 66. return 0; #endif return exit_code; #endif } ~TestMainImpl() override = default; private: #if defined(WEBRTC_WIN) std::unique_ptr<rtc::WinsockInitializer> winsock_init_; #endif }; } // namespace std::unique_ptr<TestMain> TestMain::Create() { return absl::make_unique<TestMainImpl>(); } } // namespace webrtc <commit_msg>Add --verbose flag to test_main<commit_after>/* * Copyright (c) 2018 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "test/test_main_lib.h" #include <fstream> #include <string> #include "absl/memory/memory.h" #include "rtc_base/checks.h" #include "rtc_base/flags.h" #include "rtc_base/logging.h" #include "rtc_base/thread.h" #include "system_wrappers/include/field_trial.h" #include "system_wrappers/include/metrics.h" #include "test/field_trial.h" #include "test/gmock.h" #include "test/gtest.h" #include "test/testsupport/fileutils.h" #include "test/testsupport/perf_test.h" #if defined(WEBRTC_WIN) #include "rtc_base/win32socketinit.h" #endif #if defined(WEBRTC_IOS) #include "test/ios/test_support.h" WEBRTC_DEFINE_string(NSTreatUnknownArgumentsAsOpen, "", "Intentionally ignored flag intended for iOS simulator."); WEBRTC_DEFINE_string(ApplePersistenceIgnoreState, "", "Intentionally ignored flag intended for iOS simulator."); WEBRTC_DEFINE_bool( save_chartjson_result, false, "Store the perf results in Documents/perf_result.json in the format " "described by " "https://github.com/catapult-project/catapult/blob/master/dashboard/docs/" "data-format.md."); #else WEBRTC_DEFINE_string( isolated_script_test_output, "", "Path to output an empty JSON file which Chromium infra requires."); WEBRTC_DEFINE_string( isolated_script_test_perf_output, "", "Path where the perf results should be stored in the JSON format described " "by " "https://github.com/catapult-project/catapult/blob/master/dashboard/docs/" "data-format.md."); #endif WEBRTC_DEFINE_bool(logs, false, "print logs to stderr"); WEBRTC_DEFINE_bool(verbose, false, "verbose logs to stderr"); WEBRTC_DEFINE_string( force_fieldtrials, "", "Field trials control experimental feature code which can be forced. " "E.g. running with --force_fieldtrials=WebRTC-FooFeature/Enable/" " will assign the group Enable to field trial WebRTC-FooFeature."); WEBRTC_DEFINE_bool(help, false, "Print this message."); namespace webrtc { namespace { class TestMainImpl : public TestMain { public: int Init(int* argc, char* argv[]) override { ::testing::InitGoogleMock(argc, argv); // Default to LS_INFO, even for release builds to provide better test // logging. if (rtc::LogMessage::GetLogToDebug() > rtc::LS_INFO) rtc::LogMessage::LogToDebug(rtc::LS_INFO); if (rtc::FlagList::SetFlagsFromCommandLine(argc, argv, false)) { return 1; } if (FLAG_help) { rtc::FlagList::Print(nullptr, false); return 0; } if (FLAG_verbose) rtc::LogMessage::LogToDebug(rtc::LS_VERBOSE); rtc::LogMessage::SetLogToStderr(FLAG_logs || FLAG_verbose); // TODO(bugs.webrtc.org/9792): we need to reference something from // fileutils.h so that our downstream hack where we replace fileutils.cc // works. Otherwise the downstream flag implementation will take over and // botch the flag introduced by the hack. Remove this awful thing once the // downstream implementation has been eliminated. (void)webrtc::test::JoinFilename("horrible", "hack"); webrtc::test::ValidateFieldTrialsStringOrDie(FLAG_force_fieldtrials); // InitFieldTrialsFromString stores the char*, so the char array must // outlive the application. webrtc::field_trial::InitFieldTrialsFromString(FLAG_force_fieldtrials); webrtc::metrics::Enable(); #if defined(WEBRTC_WIN) winsock_init_ = absl::make_unique<rtc::WinsockInitializer>(); #endif // Ensure that main thread gets wrapped as an rtc::Thread. // TODO(bugs.webrt.org/9714): It might be better to avoid wrapping the main // thread, or leave it to individual tests that need it. But as long as we // have automatic thread wrapping, we need this to avoid that some other // random thread (which one depending on which tests are run) gets // automatically wrapped. rtc::ThreadManager::Instance()->WrapCurrentThread(); RTC_CHECK(rtc::Thread::Current()); return 0; } int Run(int argc, char* argv[]) override { #if defined(WEBRTC_IOS) rtc::test::InitTestSuite(RUN_ALL_TESTS, argc, argv, FLAG_save_chartjson_result); rtc::test::RunTestsFromIOSApp(); return 0; #else int exit_code = RUN_ALL_TESTS(); std::string chartjson_result_file = FLAG_isolated_script_test_perf_output; if (!chartjson_result_file.empty()) { webrtc::test::WritePerfResults(chartjson_result_file); } std::string result_filename = FLAG_isolated_script_test_output; if (!result_filename.empty()) { std::ofstream result_file(result_filename); result_file << "{\"version\": 3}"; result_file.close(); } #if defined(ADDRESS_SANITIZER) || defined(LEAK_SANITIZER) || \ defined(MEMORY_SANITIZER) || defined(THREAD_SANITIZER) || \ defined(UNDEFINED_SANITIZER) // We want the test flagged as failed only for sanitizer defects, // in which case the sanitizer will override exit code with 66. return 0; #endif return exit_code; #endif } ~TestMainImpl() override = default; private: #if defined(WEBRTC_WIN) std::unique_ptr<rtc::WinsockInitializer> winsock_init_; #endif }; } // namespace std::unique_ptr<TestMain> TestMain::Create() { return absl::make_unique<TestMainImpl>(); } } // namespace webrtc <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef DLL_STANDARD_CONV_RBM_HPP #define DLL_STANDARD_CONV_RBM_HPP #include "base_conf.hpp" //The configuration helpers #include "rbm_base.hpp" //The base class #include "layer_traits.hpp" //layer_traits #include "util/checks.hpp" //nan_check #include "util/timers.hpp" //auto_timer namespace dll { /*! * \brief Standard version of Convolutional Restricted Boltzmann Machine * * This follows the definition of a CRBM by Honglak Lee. This is an "abstract" class, * using CRTP to inject features into its children. */ template <typename Parent, typename Desc> struct standard_conv_rbm : public rbm_base<Parent, Desc> { using desc = Desc; using parent_t = Parent; using this_type = standard_conv_rbm<parent_t, desc>; using base_type = rbm_base<parent_t, Desc>; using weight = typename desc::weight; static constexpr const unit_type visible_unit = desc::visible_unit; static constexpr const unit_type hidden_unit = desc::hidden_unit; static_assert(visible_unit == unit_type::BINARY || visible_unit == unit_type::GAUSSIAN, "Only binary and linear visible units are supported"); static_assert(hidden_unit == unit_type::BINARY || is_relu(hidden_unit), "Only binary hidden units are supported"); double std_gaussian = 0.2; double c_sigm = 1.0; //Constructors standard_conv_rbm() { //Note: Convolutional RBM needs lower learning rate than standard RBM //Better initialization of learning rate base_type::learning_rate = visible_unit == unit_type::GAUSSIAN ? 1e-5 : is_relu(hidden_unit) ? 1e-4 : /* Only Gaussian Units needs lower rate */ 1e-3; } parent_t& as_derived() { return *static_cast<parent_t*>(this); } const parent_t& as_derived() const { return *static_cast<const parent_t*>(this); } //Utility functions template <typename Sample> void reconstruct(const Sample& items) { reconstruct(items, as_derived()); } void display_visible_unit_activations() const { display_visible_unit_activations(as_derived()); } void display_visible_unit_samples() const { display_visible_unit_samples(as_derived()); } void display_hidden_unit_activations() const { display_hidden_unit_samples(as_derived()); } void display_hidden_unit_samples() const { display_hidden_unit_samples(as_derived()); } protected: template <typename W> static void deep_fflip(W&& w_f) { //flip all the kernels horizontally and vertically for (std::size_t channel = 0; channel < etl::dim<0>(w_f); ++channel) { for (size_t k = 0; k < etl::dim<1>(w_f); ++k) { w_f(channel)(k).fflip_inplace(); } } } template <typename L, typename V1, typename VCV, typename W> static void compute_vcv(const V1& v_a, VCV&& v_cv, W&& w) { dll::auto_timer timer("crbm:compute_vcv"); static constexpr const auto NC = L::NC; auto w_f = etl::force_temporary(w); deep_fflip(w_f); v_cv(1) = 0; for (std::size_t channel = 0; channel < NC; ++channel) { etl::conv_2d_valid_multi(v_a(channel), w_f(channel), v_cv(0)); v_cv(1) += v_cv(0); } nan_check_deep(v_cv); } template <typename L, typename H2, typename HCV, typename W, typename Functor> static void compute_hcv(const H2& h_s, HCV&& h_cv, W&& w, Functor activate) { dll::auto_timer timer("crbm:compute_hcv"); static constexpr const auto K = L::K; static constexpr const auto NC = L::NC; for (std::size_t channel = 0; channel < NC; ++channel) { h_cv(1) = 0.0; for (std::size_t k = 0; k < K; ++k) { h_cv(0) = etl::fast_conv_2d_full(h_s(k), w(channel)(k)); h_cv(1) += h_cv(0); } activate(channel); } } #ifdef ETL_MKL_MODE template <typename F1, typename F2> static void deep_pad(const F1& in, F2& out) { for (std::size_t outer1 = 0; outer1 < in.template dim<0>(); ++outer1) { for (std::size_t outer2 = 0; outer2 < in.template dim<1>(); ++outer2) { auto* direct = out(outer1)(outer2).memory_start(); for (std::size_t i = 0; i < in.template dim<2>(); ++i) { for (std::size_t j = 0; j < in.template dim<3>(); ++j) { direct[i * out.template dim<3>() + j] = in(outer1, outer2, i, j); } } } } } static void inplace_ifft2(std::complex<double>* memory, std::size_t m1, std::size_t m2) { etl::impl::blas::detail::inplace_zifft2_kernel(memory, m1, m2); } static void inplace_ifft2(std::complex<float>* memory, std::size_t m1, std::size_t m2) { etl::impl::blas::detail::inplace_cifft2_kernel(memory, m1, m2); } template <typename L, typename TP, typename H2, typename HCV, typename W, typename Functor> static void batch_compute_hcv(TP& pool, const H2& h_s, HCV&& h_cv, W&& w, Functor activate) { dll::auto_timer timer("crbm:batch_compute_hcv:mkl"); static constexpr const auto Batch = layer_traits<L>::batch_size(); static constexpr const auto K = L::K; static constexpr const auto NC = L::NC; static constexpr const auto NV1 = L::NV1; static constexpr const auto NV2 = L::NV2; etl::fast_dyn_matrix<std::complex<weight>, Batch, K, NV1, NV2> h_s_padded; etl::fast_dyn_matrix<std::complex<weight>, NC, K, NV1, NV2> w_padded; etl::fast_dyn_matrix<std::complex<weight>, Batch, NV1, NV2> tmp_result; deep_pad(h_s, h_s_padded); deep_pad(w, w_padded); h_s_padded.fft2_many_inplace(); w_padded.fft2_many_inplace(); maybe_parallel_foreach_n(pool, 0, Batch, [&](std::size_t batch) { for (std::size_t channel = 0; channel < NC; ++channel) { h_cv(batch)(1) = 0.0; for (std::size_t k = 0; k < K; ++k) { tmp_result(batch) = h_s_padded(batch)(k) >> w_padded(channel)(k); tmp_result(batch).ifft2_inplace(); for (std::size_t i = 0; i < etl::size(tmp_result(batch)); ++i) { h_cv(batch)(1)[i] += tmp_result(batch)[i].real(); } } activate(batch, channel); } }); } #else template <typename L, typename TP, typename H2, typename HCV, typename W, typename Functor> static void batch_compute_hcv(TP& pool, const H2& h_s, HCV&& h_cv, W&& w, Functor activate) { dll::auto_timer timer("crbm:batch_compute_hcv:std"); static constexpr const auto Batch = layer_traits<L>::batch_size(); static constexpr const auto K = L::K; static constexpr const auto NC = L::NC; maybe_parallel_foreach_n(pool, 0, Batch, [&](std::size_t batch) { for (std::size_t channel = 0; channel < NC; ++channel) { h_cv(batch)(1) = 0.0; for (std::size_t k = 0; k < K; ++k) { h_cv(batch)(0) = etl::fast_conv_2d_full(h_s(batch)(k), w(channel)(k)); h_cv(batch)(1) += h_cv(batch)(0); } activate(batch, channel); } }); } #endif template <typename L, typename TP, typename V1, typename VCV, typename W, typename Functor> static void batch_compute_vcv(TP& pool, const V1& v_a, VCV&& v_cv, W&& w, Functor activate) { dll::auto_timer timer("crbm:batch_compute_vcv"); static constexpr const auto Batch = layer_traits<L>::batch_size(); static constexpr const auto NC = L::NC; maybe_parallel_foreach_n(pool, 0, Batch, [&](std::size_t batch) { etl::conv_2d_valid_multi_flipped(v_a(batch)(0), w(0), v_cv(batch)(1)); for (std::size_t channel = 1; channel < NC; ++channel) { etl::conv_2d_valid_multi_flipped(v_a(batch)(channel), w(channel), v_cv(batch)(0)); v_cv(batch)(1) += v_cv(batch)(0); } activate(batch); }); } private: //Since the sub classes do not have the same fields, it is not possible //to put the fields in standard_rbm, therefore, it is necessary to use template //functions to implement the details template <typename Sample> static void reconstruct(const Sample& items, parent_t& rbm) { cpp_assert(items.size() == parent_t::input_size(), "The size of the training sample must match visible units"); cpp::stop_watch<> watch; //Set the state of the visible units rbm.v1 = items; rbm.activate_hidden(rbm.h1_a, rbm.h1_s, rbm.v1, rbm.v1); rbm.activate_visible(rbm.h1_a, rbm.h1_s, rbm.v2_a, rbm.v2_s); rbm.activate_hidden(rbm.h2_a, rbm.h2_s, rbm.v2_a, rbm.v2_s); std::cout << "Reconstruction took " << watch.elapsed() << "ms" << std::endl; } static void display_visible_unit_activations(const parent_t& rbm) { for (std::size_t channel = 0; channel < parent_t::NC; ++channel) { std::cout << "Channel " << channel << std::endl; for (size_t i = 0; i < parent_t::NV; ++i) { for (size_t j = 0; j < parent_t::NV; ++j) { std::cout << rbm.v2_a(channel, i, j) << " "; } std::cout << std::endl; } } } static void display_visible_unit_samples(const parent_t& rbm) { for (std::size_t channel = 0; channel < parent_t::NC; ++channel) { std::cout << "Channel " << channel << std::endl; for (size_t i = 0; i < parent_t::NV; ++i) { for (size_t j = 0; j < parent_t::NV; ++j) { std::cout << rbm.v2_s(channel, i, j) << " "; } std::cout << std::endl; } } } static void display_hidden_unit_activations(const parent_t& rbm) { for (size_t k = 0; k < parent_t::K; ++k) { for (size_t i = 0; i < parent_t::NV; ++i) { for (size_t j = 0; j < parent_t::NV; ++j) { std::cout << rbm.h2_a(k)(i, j) << " "; } std::cout << std::endl; } std::cout << std::endl << std::endl; } } static void display_hidden_unit_samples(const parent_t& rbm) { for (size_t k = 0; k < parent_t::K; ++k) { for (size_t i = 0; i < parent_t::NV; ++i) { for (size_t j = 0; j < parent_t::NV; ++j) { std::cout << rbm.h2_s(k)(i, j) << " "; } std::cout << std::endl; } std::cout << std::endl << std::endl; } } }; } //end of dll namespace #endif <commit_msg>Remove old code<commit_after>//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef DLL_STANDARD_CONV_RBM_HPP #define DLL_STANDARD_CONV_RBM_HPP #include "base_conf.hpp" //The configuration helpers #include "rbm_base.hpp" //The base class #include "layer_traits.hpp" //layer_traits #include "util/checks.hpp" //nan_check #include "util/timers.hpp" //auto_timer namespace dll { /*! * \brief Standard version of Convolutional Restricted Boltzmann Machine * * This follows the definition of a CRBM by Honglak Lee. This is an "abstract" class, * using CRTP to inject features into its children. */ template <typename Parent, typename Desc> struct standard_conv_rbm : public rbm_base<Parent, Desc> { using desc = Desc; using parent_t = Parent; using this_type = standard_conv_rbm<parent_t, desc>; using base_type = rbm_base<parent_t, Desc>; using weight = typename desc::weight; static constexpr const unit_type visible_unit = desc::visible_unit; static constexpr const unit_type hidden_unit = desc::hidden_unit; static_assert(visible_unit == unit_type::BINARY || visible_unit == unit_type::GAUSSIAN, "Only binary and linear visible units are supported"); static_assert(hidden_unit == unit_type::BINARY || is_relu(hidden_unit), "Only binary hidden units are supported"); double std_gaussian = 0.2; double c_sigm = 1.0; //Constructors standard_conv_rbm() { //Note: Convolutional RBM needs lower learning rate than standard RBM //Better initialization of learning rate base_type::learning_rate = visible_unit == unit_type::GAUSSIAN ? 1e-5 : is_relu(hidden_unit) ? 1e-4 : /* Only Gaussian Units needs lower rate */ 1e-3; } parent_t& as_derived() { return *static_cast<parent_t*>(this); } const parent_t& as_derived() const { return *static_cast<const parent_t*>(this); } //Utility functions template <typename Sample> void reconstruct(const Sample& items) { reconstruct(items, as_derived()); } void display_visible_unit_activations() const { display_visible_unit_activations(as_derived()); } void display_visible_unit_samples() const { display_visible_unit_samples(as_derived()); } void display_hidden_unit_activations() const { display_hidden_unit_samples(as_derived()); } void display_hidden_unit_samples() const { display_hidden_unit_samples(as_derived()); } protected: template <typename W> static void deep_fflip(W&& w_f) { //flip all the kernels horizontally and vertically for (std::size_t channel = 0; channel < etl::dim<0>(w_f); ++channel) { for (size_t k = 0; k < etl::dim<1>(w_f); ++k) { w_f(channel)(k).fflip_inplace(); } } } template <typename L, typename V1, typename VCV, typename W> static void compute_vcv(const V1& v_a, VCV&& v_cv, W&& w) { dll::auto_timer timer("crbm:compute_vcv"); static constexpr const auto NC = L::NC; auto w_f = etl::force_temporary(w); deep_fflip(w_f); v_cv(1) = 0; for (std::size_t channel = 0; channel < NC; ++channel) { etl::conv_2d_valid_multi(v_a(channel), w_f(channel), v_cv(0)); v_cv(1) += v_cv(0); } nan_check_deep(v_cv); } template <typename L, typename H2, typename HCV, typename W, typename Functor> static void compute_hcv(const H2& h_s, HCV&& h_cv, W&& w, Functor activate) { dll::auto_timer timer("crbm:compute_hcv"); static constexpr const auto K = L::K; static constexpr const auto NC = L::NC; for (std::size_t channel = 0; channel < NC; ++channel) { h_cv(1) = 0.0; for (std::size_t k = 0; k < K; ++k) { h_cv(0) = etl::fast_conv_2d_full(h_s(k), w(channel)(k)); h_cv(1) += h_cv(0); } activate(channel); } } #ifdef ETL_MKL_MODE template <typename F1, typename F2> static void deep_pad(const F1& in, F2& out) { for (std::size_t outer1 = 0; outer1 < in.template dim<0>(); ++outer1) { for (std::size_t outer2 = 0; outer2 < in.template dim<1>(); ++outer2) { auto* direct = out(outer1)(outer2).memory_start(); for (std::size_t i = 0; i < in.template dim<2>(); ++i) { for (std::size_t j = 0; j < in.template dim<3>(); ++j) { direct[i * out.template dim<3>() + j] = in(outer1, outer2, i, j); } } } } } template <typename L, typename TP, typename H2, typename HCV, typename W, typename Functor> static void batch_compute_hcv(TP& pool, const H2& h_s, HCV&& h_cv, W&& w, Functor activate) { dll::auto_timer timer("crbm:batch_compute_hcv:mkl"); static constexpr const auto Batch = layer_traits<L>::batch_size(); static constexpr const auto K = L::K; static constexpr const auto NC = L::NC; static constexpr const auto NV1 = L::NV1; static constexpr const auto NV2 = L::NV2; etl::fast_dyn_matrix<std::complex<weight>, Batch, K, NV1, NV2> h_s_padded; etl::fast_dyn_matrix<std::complex<weight>, NC, K, NV1, NV2> w_padded; etl::fast_dyn_matrix<std::complex<weight>, Batch, NV1, NV2> tmp_result; deep_pad(h_s, h_s_padded); deep_pad(w, w_padded); h_s_padded.fft2_many_inplace(); w_padded.fft2_many_inplace(); maybe_parallel_foreach_n(pool, 0, Batch, [&](std::size_t batch) { for (std::size_t channel = 0; channel < NC; ++channel) { h_cv(batch)(1) = 0.0; for (std::size_t k = 0; k < K; ++k) { tmp_result(batch) = h_s_padded(batch)(k) >> w_padded(channel)(k); tmp_result(batch).ifft2_inplace(); for (std::size_t i = 0; i < etl::size(tmp_result(batch)); ++i) { h_cv(batch)(1)[i] += tmp_result(batch)[i].real(); } } activate(batch, channel); } }); } #else template <typename L, typename TP, typename H2, typename HCV, typename W, typename Functor> static void batch_compute_hcv(TP& pool, const H2& h_s, HCV&& h_cv, W&& w, Functor activate) { dll::auto_timer timer("crbm:batch_compute_hcv:std"); static constexpr const auto Batch = layer_traits<L>::batch_size(); static constexpr const auto K = L::K; static constexpr const auto NC = L::NC; maybe_parallel_foreach_n(pool, 0, Batch, [&](std::size_t batch) { for (std::size_t channel = 0; channel < NC; ++channel) { h_cv(batch)(1) = 0.0; for (std::size_t k = 0; k < K; ++k) { h_cv(batch)(0) = etl::fast_conv_2d_full(h_s(batch)(k), w(channel)(k)); h_cv(batch)(1) += h_cv(batch)(0); } activate(batch, channel); } }); } #endif template <typename L, typename TP, typename V1, typename VCV, typename W, typename Functor> static void batch_compute_vcv(TP& pool, const V1& v_a, VCV&& v_cv, W&& w, Functor activate) { dll::auto_timer timer("crbm:batch_compute_vcv"); static constexpr const auto Batch = layer_traits<L>::batch_size(); static constexpr const auto NC = L::NC; maybe_parallel_foreach_n(pool, 0, Batch, [&](std::size_t batch) { etl::conv_2d_valid_multi_flipped(v_a(batch)(0), w(0), v_cv(batch)(1)); for (std::size_t channel = 1; channel < NC; ++channel) { etl::conv_2d_valid_multi_flipped(v_a(batch)(channel), w(channel), v_cv(batch)(0)); v_cv(batch)(1) += v_cv(batch)(0); } activate(batch); }); } private: //Since the sub classes do not have the same fields, it is not possible //to put the fields in standard_rbm, therefore, it is necessary to use template //functions to implement the details template <typename Sample> static void reconstruct(const Sample& items, parent_t& rbm) { cpp_assert(items.size() == parent_t::input_size(), "The size of the training sample must match visible units"); cpp::stop_watch<> watch; //Set the state of the visible units rbm.v1 = items; rbm.activate_hidden(rbm.h1_a, rbm.h1_s, rbm.v1, rbm.v1); rbm.activate_visible(rbm.h1_a, rbm.h1_s, rbm.v2_a, rbm.v2_s); rbm.activate_hidden(rbm.h2_a, rbm.h2_s, rbm.v2_a, rbm.v2_s); std::cout << "Reconstruction took " << watch.elapsed() << "ms" << std::endl; } static void display_visible_unit_activations(const parent_t& rbm) { for (std::size_t channel = 0; channel < parent_t::NC; ++channel) { std::cout << "Channel " << channel << std::endl; for (size_t i = 0; i < parent_t::NV; ++i) { for (size_t j = 0; j < parent_t::NV; ++j) { std::cout << rbm.v2_a(channel, i, j) << " "; } std::cout << std::endl; } } } static void display_visible_unit_samples(const parent_t& rbm) { for (std::size_t channel = 0; channel < parent_t::NC; ++channel) { std::cout << "Channel " << channel << std::endl; for (size_t i = 0; i < parent_t::NV; ++i) { for (size_t j = 0; j < parent_t::NV; ++j) { std::cout << rbm.v2_s(channel, i, j) << " "; } std::cout << std::endl; } } } static void display_hidden_unit_activations(const parent_t& rbm) { for (size_t k = 0; k < parent_t::K; ++k) { for (size_t i = 0; i < parent_t::NV; ++i) { for (size_t j = 0; j < parent_t::NV; ++j) { std::cout << rbm.h2_a(k)(i, j) << " "; } std::cout << std::endl; } std::cout << std::endl << std::endl; } } static void display_hidden_unit_samples(const parent_t& rbm) { for (size_t k = 0; k < parent_t::K; ++k) { for (size_t i = 0; i < parent_t::NV; ++i) { for (size_t j = 0; j < parent_t::NV; ++j) { std::cout << rbm.h2_s(k)(i, j) << " "; } std::cout << std::endl; } std::cout << std::endl << std::endl; } } }; } //end of dll namespace #endif <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once #include <algorithm> #include "cpp_utils/assert.hpp" #include "cpp_utils/tmp.hpp" #include "etl/traits_lite.hpp" //Get the implementations #include "etl/impl/pooling.hpp" namespace etl { template<typename T, std::size_t C1, std::size_t C2, template<typename...> class Impl> struct basic_pool_2d_expr { static_assert(C1 > 0, "C1 must be greater than 0"); static_assert(C2 > 0, "C2 must be greater than 0"); using this_type = basic_pool_2d_expr<T, C1, C2, Impl>; template<typename A, std::size_t DD> static constexpr std::size_t dim(){ return DD == 0 ? decay_traits<A>::template dim<0>() / C1 : decay_traits<A>::template dim<1>() / C2; } template<typename A, class Enable = void> struct result_type_builder { using type = dyn_matrix<value_t<A>, 2>; }; template<typename A> struct result_type_builder<A, std::enable_if_t<all_fast<A>::value>> { using type = fast_dyn_matrix<value_t<A>, this_type::template dim<A, 0>(), this_type::template dim<A, 1>()>; }; template<typename A> using result_type = typename result_type_builder<A>::type; template<typename A, cpp_enable_if(all_fast<A>::value)> static result_type<A>* allocate(A&& /*a*/){ return new result_type<A>(); } template<typename A, cpp_disable_if(all_fast<A>::value)> static result_type<A>* allocate(A&& a){ return new result_type<A>(etl::dim<0>(a) / C2, etl::dim<1>(a) / C2); } template<typename A, typename C> static void apply(A&& a, C&& c){ static_assert(all_etl_expr<A, C>::value, "pool_2d only supported for ETL expressions"); static_assert(decay_traits<A>::dimensions() == 2 && decay_traits<C>::dimensions() == 2, "pool_2d needs 2D matrices"); Impl<decltype(make_temporary(std::forward<A>(a))), C>::template apply<C1, C2>( make_temporary(std::forward<A>(a)), std::forward<C>(c)); } static std::string desc() noexcept { return "pool_2d"; } template<typename A> static std::size_t dim(const A& a, std::size_t d){ if(d == 0){ return etl::dim<0>(a) / C1; } else { return etl::dim<1>(a) / C2; } } template<typename A> static std::size_t size(const A& a){ return (etl::dim<0>(a) / C1) * (etl::dim<1>(a) / C2); } template<typename A> static constexpr std::size_t size(){ return this_type::template dim<A, 0>() * this_type::template dim<A, 1>(); } static constexpr std::size_t dimensions(){ return 2; } }; //Max Pool 2D template<typename T, std::size_t C1, std::size_t C2> using max_pool_2d_expr = basic_pool_2d_expr<T, C1, C2, impl::max_pool_2d>; template<typename T, std::size_t C1, std::size_t C2> using avg_pool_2d_expr = basic_pool_2d_expr<T, C1, C2, impl::avg_pool_2d>; template<typename T, std::size_t C1, std::size_t C2, std::size_t C3, template<typename...> class Impl> struct basic_pool_3d_expr { static_assert(C1 > 0, "C1 must be greater than 0"); static_assert(C2 > 0, "C2 must be greater than 0"); static_assert(C3 > 0, "C3 must be greater than 0"); using this_type = basic_pool_3d_expr<T, C1, C2, C3, Impl>; template<typename A, std::size_t DD> static constexpr std::size_t dim(){ return DD == 0 ? decay_traits<A>::template dim<0>() / C1 : DD == 1 ? decay_traits<A>::template dim<1>() / C2 : decay_traits<A>::template dim<2>() / C3; } template<typename A, class Enable = void> struct result_type_builder { using type = dyn_matrix<value_t<A>, 3>; }; template<typename A> struct result_type_builder<A, std::enable_if_t<all_fast<A>::value>> { using type = fast_dyn_matrix<value_t<A>, this_type::template dim<A, 0>(), this_type::template dim<A, 1>(), this_type::template dim<A, 2>()>; }; template<typename A> using result_type = typename result_type_builder<A>::type; template<typename A, cpp_enable_if(all_fast<A>::value)> static result_type<A>* allocate(A&& /*a*/){ return new result_type<A>(); } template<typename A, cpp_disable_if(all_fast<A>::value)> static result_type<A>* allocate(A&& a){ return new result_type<A>(etl::dim<0>(a) / C2, etl::dim<1>(a) / C2, etl::dim<2>(a) / C3); } template<typename A, typename C> static void apply(A&& a, C&& c){ static_assert(all_etl_expr<A, C>::value, "pool_3d only supported for ETL expressions"); static_assert(decay_traits<A>::dimensions() == 3 && decay_traits<C>::dimensions() == 3, "pool_3d needs 3D matrices"); Impl<decltype(make_temporary(std::forward<A>(a))), C>::template apply<C1, C2, C3>( make_temporary(std::forward<A>(a)), std::forward<C>(c)); } static std::string desc() noexcept { return "pool_3d"; } template<typename A> static std::size_t dim(const A& a, std::size_t d){ if(d == 0){ return etl::dim<0>(a) / C1; } else if(d == 1){ return etl::dim<1>(a) / C2; } else { return etl::dim<2>(a) / C3; } } template<typename A> static std::size_t size(const A& a){ return (etl::dim<0>(a) / C1) * (etl::dim<1>(a) / C2) * (etl::dim<2>(a) / C3); } template<typename A> static constexpr std::size_t size(){ return this_type::template dim<A, 0>() * this_type::template dim<A, 1>() * this_type::template dim<A, 2>(); } static constexpr std::size_t dimensions(){ return 3; } }; //Max Pool 2D template<typename T, std::size_t C1, std::size_t C2, std::size_t C3> using max_pool_3d_expr = basic_pool_3d_expr<T, C1, C2, C3, impl::max_pool_3d>; template<typename T, std::size_t C1, std::size_t C2, std::size_t C3> using avg_pool_3d_expr = basic_pool_3d_expr<T, C1, C2, C3, impl::avg_pool_3d>; } //end of namespace etl <commit_msg>More doc<commit_after>//======================================================================= // Copyright (c) 2014-2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= /*! * \file fft_expr.hpp * \brief Contains the pooling expressions. */ #pragma once #include <algorithm> #include "cpp_utils/assert.hpp" #include "cpp_utils/tmp.hpp" #include "etl/traits_lite.hpp" //Get the implementations #include "etl/impl/pooling.hpp" namespace etl { /*! * \brief Base class for all 2D pooling expressions */ template<typename T, std::size_t C1, std::size_t C2, template<typename...> class Impl> struct basic_pool_2d_expr { static_assert(C1 > 0, "C1 must be greater than 0"); static_assert(C2 > 0, "C2 must be greater than 0"); using this_type = basic_pool_2d_expr<T, C1, C2, Impl>; template<typename A, std::size_t DD> static constexpr std::size_t dim(){ return DD == 0 ? decay_traits<A>::template dim<0>() / C1 : decay_traits<A>::template dim<1>() / C2; } template<typename A, class Enable = void> struct result_type_builder { using type = dyn_matrix<value_t<A>, 2>; }; template<typename A> struct result_type_builder<A, std::enable_if_t<all_fast<A>::value>> { using type = fast_dyn_matrix<value_t<A>, this_type::template dim<A, 0>(), this_type::template dim<A, 1>()>; }; template<typename A> using result_type = typename result_type_builder<A>::type; template<typename A, cpp_enable_if(all_fast<A>::value)> static result_type<A>* allocate(A&& /*a*/){ return new result_type<A>(); } template<typename A, cpp_disable_if(all_fast<A>::value)> static result_type<A>* allocate(A&& a){ return new result_type<A>(etl::dim<0>(a) / C2, etl::dim<1>(a) / C2); } template<typename A, typename C> static void apply(A&& a, C&& c){ static_assert(all_etl_expr<A, C>::value, "pool_2d only supported for ETL expressions"); static_assert(decay_traits<A>::dimensions() == 2 && decay_traits<C>::dimensions() == 2, "pool_2d needs 2D matrices"); Impl<decltype(make_temporary(std::forward<A>(a))), C>::template apply<C1, C2>( make_temporary(std::forward<A>(a)), std::forward<C>(c)); } static std::string desc() noexcept { return "pool_2d"; } template<typename A> static std::size_t dim(const A& a, std::size_t d){ if(d == 0){ return etl::dim<0>(a) / C1; } else { return etl::dim<1>(a) / C2; } } template<typename A> static std::size_t size(const A& a){ return (etl::dim<0>(a) / C1) * (etl::dim<1>(a) / C2); } template<typename A> static constexpr std::size_t size(){ return this_type::template dim<A, 0>() * this_type::template dim<A, 1>(); } static constexpr std::size_t dimensions(){ return 2; } }; //Max Pool 2D template<typename T, std::size_t C1, std::size_t C2> using max_pool_2d_expr = basic_pool_2d_expr<T, C1, C2, impl::max_pool_2d>; template<typename T, std::size_t C1, std::size_t C2> using avg_pool_2d_expr = basic_pool_2d_expr<T, C1, C2, impl::avg_pool_2d>; /*! * \brief Base class for all 3D pooling expressions */ template<typename T, std::size_t C1, std::size_t C2, std::size_t C3, template<typename...> class Impl> struct basic_pool_3d_expr { static_assert(C1 > 0, "C1 must be greater than 0"); static_assert(C2 > 0, "C2 must be greater than 0"); static_assert(C3 > 0, "C3 must be greater than 0"); using this_type = basic_pool_3d_expr<T, C1, C2, C3, Impl>; template<typename A, std::size_t DD> static constexpr std::size_t dim(){ return DD == 0 ? decay_traits<A>::template dim<0>() / C1 : DD == 1 ? decay_traits<A>::template dim<1>() / C2 : decay_traits<A>::template dim<2>() / C3; } template<typename A, class Enable = void> struct result_type_builder { using type = dyn_matrix<value_t<A>, 3>; }; template<typename A> struct result_type_builder<A, std::enable_if_t<all_fast<A>::value>> { using type = fast_dyn_matrix<value_t<A>, this_type::template dim<A, 0>(), this_type::template dim<A, 1>(), this_type::template dim<A, 2>()>; }; template<typename A> using result_type = typename result_type_builder<A>::type; template<typename A, cpp_enable_if(all_fast<A>::value)> static result_type<A>* allocate(A&& /*a*/){ return new result_type<A>(); } template<typename A, cpp_disable_if(all_fast<A>::value)> static result_type<A>* allocate(A&& a){ return new result_type<A>(etl::dim<0>(a) / C2, etl::dim<1>(a) / C2, etl::dim<2>(a) / C3); } template<typename A, typename C> static void apply(A&& a, C&& c){ static_assert(all_etl_expr<A, C>::value, "pool_3d only supported for ETL expressions"); static_assert(decay_traits<A>::dimensions() == 3 && decay_traits<C>::dimensions() == 3, "pool_3d needs 3D matrices"); Impl<decltype(make_temporary(std::forward<A>(a))), C>::template apply<C1, C2, C3>( make_temporary(std::forward<A>(a)), std::forward<C>(c)); } static std::string desc() noexcept { return "pool_3d"; } template<typename A> static std::size_t dim(const A& a, std::size_t d){ if(d == 0){ return etl::dim<0>(a) / C1; } else if(d == 1){ return etl::dim<1>(a) / C2; } else { return etl::dim<2>(a) / C3; } } template<typename A> static std::size_t size(const A& a){ return (etl::dim<0>(a) / C1) * (etl::dim<1>(a) / C2) * (etl::dim<2>(a) / C3); } template<typename A> static constexpr std::size_t size(){ return this_type::template dim<A, 0>() * this_type::template dim<A, 1>() * this_type::template dim<A, 2>(); } static constexpr std::size_t dimensions(){ return 3; } }; //Max Pool 2D template<typename T, std::size_t C1, std::size_t C2, std::size_t C3> using max_pool_3d_expr = basic_pool_3d_expr<T, C1, C2, C3, impl::max_pool_3d>; template<typename T, std::size_t C1, std::size_t C2, std::size_t C3> using avg_pool_3d_expr = basic_pool_3d_expr<T, C1, C2, C3, impl::avg_pool_3d>; } //end of namespace etl <|endoftext|>
<commit_before>/* DisplayController.h - Library for Controlling a 14x28 bits FlipDot display sign using two FP2800A. Created by Antonio Carioca, March 3, 2014. */ //#include "Arduino.h" //#include <avr/pgmspace.h> //#include "application.h" #include "mark-iv-flip-dot-display-sign-14x28-controller.h" /* CONSTANTS */ //const int DISPLAY_SIZE = 4; const int DISPLAY_PIXEL_WIDTH = 28; const int DISPLAY_PIXEL_HEIGHT = 14; const int DISPLAY_SUBPANEL_QTY = 2; //=== F O N T === // Font courtesy of aspro648 // coden taken from // http://www.instructables.com/files/orig/FQC/A1CY/H5EW79JK/FQCA1CYH5EW79JK.txt // The @ will display as space character. // NOTE: MOVING ALL THE ARRAY BELOW TO PROGMEM //DotDisplay::DotDisplay(int dataPin, int clockPin, int latchPin, int enableSubPanel1Pin, int enableSubPanel2Pin, int fontWidth, int fontHeight, prog_uchar fonteParam[][5]){ DotDisplay::DotDisplay(int dataPin, int clockPin, int latchPin, int enableSubPanel1Pin, int enableSubPanel2Pin, int fontWidth, int fontHeight, byte fonteParam[][5]){ pinMode(dataPin, OUTPUT); pinMode(clockPin, OUTPUT); pinMode(latchPin, OUTPUT); pinMode(enableSubPanel1Pin, OUTPUT); pinMode(enableSubPanel2Pin, OUTPUT); //disable FP2800A's digitalWrite(enableSubPanel1Pin, LOW); digitalWrite(enableSubPanel2Pin, LOW); _dataPin = dataPin; _clockPin = clockPin; _latchPin = latchPin; _enableSubPanel1Pin = enableSubPanel1Pin; _enableSubPanel2Pin = enableSubPanel2Pin; _fontWidth = fontWidth; _fontHeight = fontHeight; _fonteParam = fonteParam; //_maxNumRows = floor((DISPLAY_PIXEL_HEIGHT+1)/(_fontHeight)); _maxNumRows = (int)((DISPLAY_PIXEL_HEIGHT+1)/(_fontHeight)); //_maxRowLength = floor((DISPLAY_PIXEL_WIDTH * DISPLAY_SUBPANEL_QTY+1) / (_fontWidth+1)); _maxRowLength = (int)((DISPLAY_PIXEL_WIDTH * DISPLAY_SUBPANEL_QTY+1) / (_fontWidth+1)); _maxMessageLength = _maxRowLength * _maxNumRows; } /* void DotDisplay::setSerial(HardwareSerial* hwPrint){ printer = hwPrint; //operate on the address of print if(printer) { printer->begin(9600); } } */ void DotDisplay::setDot(byte col, byte row, bool on){ //accidentally reversed two data pins, so reversing back on the code here //on = !on; //2 pins - Data //5 pins - Column //4 pins - Rows //4 pins - Enable FP2800A (4 subpanels) byte subPanel = 1; //disable FP2800A's digitalWrite(_enableSubPanel1Pin, LOW); digitalWrite(_enableSubPanel2Pin, LOW); //enables next sunpanel if(col>=DISPLAY_PIXEL_WIDTH){ //subPanel = floor(col / DISPLAY_PIXEL_WIDTH)+1; subPanel = (int)(col / DISPLAY_PIXEL_WIDTH)+1; col=col-DISPLAY_PIXEL_WIDTH; } /* if(printer) { printer->print("col: "); printer->print(col); printer->print(", "); printer->print("subPanel: "); printer->println(subPanel); } */ // IGNOREx4 + ROWx4 + IGNOREx1 + COLUMNx5 + DATAx2 byte dataPins = on?1:2; byte colFirstThreeDigits = (col % 7)+1; //byte colLastTwoDigits = floor(col/7); byte colLastTwoDigits = (int)(col/7); byte colByte = colFirstThreeDigits | (colLastTwoDigits << 3); byte rowFirstThreeDigits = (row % 7)+1; byte rowLastDigit = row<7; byte rowByte = rowFirstThreeDigits | (rowLastDigit << 3); byte firstbyte = (dataPins) | (colByte << 2); byte secondbyte = rowByte; digitalWrite(_latchPin, LOW); shiftOut(_dataPin, _clockPin, LSBFIRST, firstbyte); shiftOut(_dataPin, _clockPin, LSBFIRST, secondbyte); digitalWrite(_latchPin, HIGH); //delay(1); //pulse the FP2800A's enable pins if(subPanel == 1){ digitalWrite(_enableSubPanel1Pin, HIGH); delay(1); digitalWrite(_enableSubPanel1Pin, LOW); } else if (subPanel == 2) { digitalWrite(_enableSubPanel2Pin, HIGH); delay(1); digitalWrite(_enableSubPanel2Pin, LOW); } } //void DotDisplay::updateDisplay(char *textMessage){ void DotDisplay::updateDisplay(char textMessage[], char log[]){ int currentColumn = 0; int currentRow = 0; strcpy(log,""); //goes through all characters for (int ch = 0; ch < (_maxMessageLength);ch++){ //get a character from the message int alphabetIndex = textMessage[ch] - ' '; //Subtract '@' so we get a number //Serial.println(alphabetIndex); if ((alphabetIndex < 0) or (ch >=strlen(textMessage))) alphabetIndex=0; //push it to the next row if necessary if((currentColumn + _fontWidth) > (DISPLAY_PIXEL_WIDTH * DISPLAY_SUBPANEL_QTY)){ currentColumn=0; currentRow=currentRow+_fontHeight; } //set all the bits in the next _fontWidth columns on the display for(byte col = currentColumn; col<(currentColumn+_fontWidth); col++){ byte calculatedColumn = (col)%(_fontWidth+1); //for(byte row = 0; row < _fontHeight; row++) int characterRow = 0; for(byte row = currentRow; row < (currentRow + _fontHeight); row++){ //bool isOn = bitRead(pgm_read_byte(&(_fonteParam[alphabetIndex][calculatedColumn])),6-characterRow); bool isOn = bitRead((byte)_fonteParam[alphabetIndex][calculatedColumn],6-row);//this index is needed as we are going from back to front setDot(col, row, isOn); /* if(printer) { printer->print(isOn); } */ strcat(log,isOn); characterRow++; } /* if(printer) { printer->println(""); } */ strcat(log,""); } /* if(printer) { printer->println("*******"); } */ strcat(log,"*********"); currentColumn = currentColumn+(_fontWidth+1); } } <commit_msg>Fixing debug options<commit_after>/* DisplayController.h - Library for Controlling a 14x28 bits FlipDot display sign using two FP2800A. Created by Antonio Carioca, March 3, 2014. */ //#include "Arduino.h" //#include <avr/pgmspace.h> //#include "application.h" #include "mark-iv-flip-dot-display-sign-14x28-controller.h" /* CONSTANTS */ //const int DISPLAY_SIZE = 4; const int DISPLAY_PIXEL_WIDTH = 28; const int DISPLAY_PIXEL_HEIGHT = 14; const int DISPLAY_SUBPANEL_QTY = 2; //=== F O N T === // Font courtesy of aspro648 // coden taken from // http://www.instructables.com/files/orig/FQC/A1CY/H5EW79JK/FQCA1CYH5EW79JK.txt // The @ will display as space character. // NOTE: MOVING ALL THE ARRAY BELOW TO PROGMEM //DotDisplay::DotDisplay(int dataPin, int clockPin, int latchPin, int enableSubPanel1Pin, int enableSubPanel2Pin, int fontWidth, int fontHeight, prog_uchar fonteParam[][5]){ DotDisplay::DotDisplay(int dataPin, int clockPin, int latchPin, int enableSubPanel1Pin, int enableSubPanel2Pin, int fontWidth, int fontHeight, byte fonteParam[][5]){ pinMode(dataPin, OUTPUT); pinMode(clockPin, OUTPUT); pinMode(latchPin, OUTPUT); pinMode(enableSubPanel1Pin, OUTPUT); pinMode(enableSubPanel2Pin, OUTPUT); //disable FP2800A's digitalWrite(enableSubPanel1Pin, LOW); digitalWrite(enableSubPanel2Pin, LOW); _dataPin = dataPin; _clockPin = clockPin; _latchPin = latchPin; _enableSubPanel1Pin = enableSubPanel1Pin; _enableSubPanel2Pin = enableSubPanel2Pin; _fontWidth = fontWidth; _fontHeight = fontHeight; _fonteParam = fonteParam; //_maxNumRows = floor((DISPLAY_PIXEL_HEIGHT+1)/(_fontHeight)); _maxNumRows = (int)((DISPLAY_PIXEL_HEIGHT+1)/(_fontHeight)); //_maxRowLength = floor((DISPLAY_PIXEL_WIDTH * DISPLAY_SUBPANEL_QTY+1) / (_fontWidth+1)); _maxRowLength = (int)((DISPLAY_PIXEL_WIDTH * DISPLAY_SUBPANEL_QTY+1) / (_fontWidth+1)); _maxMessageLength = _maxRowLength * _maxNumRows; } /* void DotDisplay::setSerial(HardwareSerial* hwPrint){ printer = hwPrint; //operate on the address of print if(printer) { printer->begin(9600); } } */ void DotDisplay::setDot(byte col, byte row, bool on){ //accidentally reversed two data pins, so reversing back on the code here //on = !on; //2 pins - Data //5 pins - Column //4 pins - Rows //4 pins - Enable FP2800A (4 subpanels) byte subPanel = 1; //disable FP2800A's digitalWrite(_enableSubPanel1Pin, LOW); digitalWrite(_enableSubPanel2Pin, LOW); //enables next sunpanel if(col>=DISPLAY_PIXEL_WIDTH){ //subPanel = floor(col / DISPLAY_PIXEL_WIDTH)+1; subPanel = (int)(col / DISPLAY_PIXEL_WIDTH)+1; col=col-DISPLAY_PIXEL_WIDTH; } /* if(printer) { printer->print("col: "); printer->print(col); printer->print(", "); printer->print("subPanel: "); printer->println(subPanel); } */ // IGNOREx4 + ROWx4 + IGNOREx1 + COLUMNx5 + DATAx2 byte dataPins = on?1:2; byte colFirstThreeDigits = (col % 7)+1; //byte colLastTwoDigits = floor(col/7); byte colLastTwoDigits = (int)(col/7); byte colByte = colFirstThreeDigits | (colLastTwoDigits << 3); byte rowFirstThreeDigits = (row % 7)+1; byte rowLastDigit = row<7; byte rowByte = rowFirstThreeDigits | (rowLastDigit << 3); byte firstbyte = (dataPins) | (colByte << 2); byte secondbyte = rowByte; digitalWrite(_latchPin, LOW); shiftOut(_dataPin, _clockPin, LSBFIRST, firstbyte); shiftOut(_dataPin, _clockPin, LSBFIRST, secondbyte); digitalWrite(_latchPin, HIGH); //delay(1); //pulse the FP2800A's enable pins if(subPanel == 1){ digitalWrite(_enableSubPanel1Pin, HIGH); delay(1); digitalWrite(_enableSubPanel1Pin, LOW); } else if (subPanel == 2) { digitalWrite(_enableSubPanel2Pin, HIGH); delay(1); digitalWrite(_enableSubPanel2Pin, LOW); } } //void DotDisplay::updateDisplay(char *textMessage){ void DotDisplay::updateDisplay(char textMessage[], char log[]){ int currentColumn = 0; int currentRow = 0; strcpy(log,""); //goes through all characters for (int ch = 0; ch < (_maxMessageLength);ch++){ //get a character from the message int alphabetIndex = textMessage[ch] - ' '; //Subtract '@' so we get a number //Serial.println(alphabetIndex); if ((alphabetIndex < 0) or (ch >=strlen(textMessage))) alphabetIndex=0; //push it to the next row if necessary if((currentColumn + _fontWidth) > (DISPLAY_PIXEL_WIDTH * DISPLAY_SUBPANEL_QTY)){ currentColumn=0; currentRow=currentRow+_fontHeight; } //set all the bits in the next _fontWidth columns on the display for(byte col = currentColumn; col<(currentColumn+_fontWidth); col++){ byte calculatedColumn = (col)%(_fontWidth+1); //for(byte row = 0; row < _fontHeight; row++) int characterRow = 0; for(byte row = currentRow; row < (currentRow + _fontHeight); row++){ //bool isOn = bitRead(pgm_read_byte(&(_fonteParam[alphabetIndex][calculatedColumn])),6-characterRow); bool isOn = bitRead((byte)_fonteParam[alphabetIndex][calculatedColumn],6-row);//this index is needed as we are going from back to front setDot(col, row, isOn); /* if(printer) { printer->print(isOn); } */ char dot; if (isOn) dot = '1' else dot = '0'; strcat(log,isOn); characterRow++; } /* if(printer) { printer->println(""); } */ strcat(log,""); } /* if(printer) { printer->println("*******"); } */ strcat(log,"*********"); currentColumn = currentColumn+(_fontWidth+1); } } <|endoftext|>
<commit_before>// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com // ============================================================================ // Copyright (c) 2017-2019, by Vitaly Grigoriev, <[email protected]>. // This file is part of ProtocolAnalyzer open source project under MIT License. // ============================================================================ #ifndef PROTOCOL_ANALYZER_LOCKED_DEQUE_HPP #define PROTOCOL_ANALYZER_LOCKED_DEQUE_HPP #include <mutex> // std::mutex, std::scoped_lock, std::lock_guard. #include <deque> // std::deque. #include <utility> // std::move, std::swap. // In Common library MUST NOT use any another framework libraries because it is a core library. namespace analyzer::framework::common::types { /** * @class LockedDeque LockedDeque.hpp "include/framework/LockedDeque.hpp" * @brief This class defined concurrency wrapper over STL deque class to work in parallel threads. * * @tparam [in] Type - Typename of stored data in STL deque. * * @note This deque container if type-protected and provides a convenient RAII-style mechanism. * * @todo Set the global limit for adding new values to the deque. */ template <typename Type> class LockedDeque { private: /** * @brief Mutex value for thread-safe class working. */ std::mutex mutex = { }; /** * @brief STL deque for stored data; */ std::deque<Type> deque = { }; public: /** * @brief Default constructor. * * @throw std::bad_alloc - In case when do not system memory to allocate the storage. */ LockedDeque(void) noexcept(std::is_nothrow_default_constructible_v<std::deque<Type>>) = default; /** * @brief Default destructor. */ ~LockedDeque(void) noexcept = default; /** * @brief Copy assignment constructor with LockedDeque<Type>. * * @tparam [in] other - The const reference of copied LockedDeque<Type>. * * @throw std::bad_alloc - In case when do not system memory to allocate the storage. */ LockedDeque (const LockedDeque<Type>& other) noexcept(std::is_nothrow_copy_constructible_v<std::deque<Type>>) { try { std::scoped_lock lock { mutex, other.mutex }; } catch (const std::system_error& /*err*/) { return; } deque = other.deque; } /** * @brief Copy assignment constructor with STL std::deque<Type>. * * @tparam [in] other - The const reference of copied STL std::deque<Type>. * * @throw std::bad_alloc - In case when do not system memory to allocate the storage. */ explicit LockedDeque (const std::deque<Type>& other) noexcept(std::is_nothrow_copy_constructible_v<std::deque<Type>>) { try { std::lock_guard<std::mutex> lock { mutex }; } catch (const std::system_error& /*err*/) { return; } deque = other; } /** * @brief Move assignment constructor with LockedDeque<Type>. * * @tparam [in] other - The rvalue reference of moved LockedDeque<Type>. */ LockedDeque (LockedDeque<Type>&& other) noexcept { try { std::scoped_lock lock { mutex, other.mutex }; } catch (const std::system_error& /*err*/) { return; } deque = std::move(other.deque); } /** * @brief Move assignment constructor with STL std::deque<Type>. * * @tparam [in] other - The rvalue reference of moved STL std::deque<Type>. */ explicit LockedDeque (std::deque<Type>&& other) noexcept { try { std::lock_guard<std::mutex> lock { mutex }; } catch (const std::system_error& /*err*/) { return; } deque = std::move(other); } /** * @brief Copy assignment operator. * * @tparam [in] other - The const reference of copied LockedDeque<Type> class. * @return Reference of the current LockedDeque<Type> class. * * @throw std::bad_alloc - In case when do not system memory to allocate the storage. */ LockedDeque<Type>& operator= (const LockedDeque<Type>& other) noexcept(std::is_nothrow_copy_assignable_v<std::deque<Type>>) { if (this != &other) { try { std::scoped_lock lock { mutex, other.mutex }; } catch (const std::system_error& /*err*/) { return *this; } deque = other.deque; } return *this; } /** * @brief Move assignment operator. * * @tparam [in] other - The rvalue reference of moved LockedDeque<Type> class. * @return Reference of the current LockedDeque<Type> class. */ LockedDeque<Type>& operator= (LockedDeque<Type>&& other) noexcept { if (this != &other) { try { std::scoped_lock lock { mutex, other.mutex }; } catch (const std::system_error& /*err*/) { return *this; } deque = std::move(other.deque); } return *this; } /** * @brief Method that returns the size of deque. * * @return Size of deque. */ std::size_t Size(void) noexcept { try { std::lock_guard<std::mutex> lock { mutex }; } catch (const std::system_error& /*err*/) { return 0; } return deque.size(); } /** * @brief Method that returns the internal state of deque. * * @return TRUE - if the container size is 0, otherwise - FALSE. */ bool IsEmpty(void) noexcept { try { std::lock_guard<std::mutex> lock { mutex }; } catch (const std::system_error& /*err*/) { return false; } return deque.empty(); } /** * @brief Method that push new value to front of deque. * * @tparam [in] value - New value for insert. * @return TRUE - if push is successful, otherwise - FALSE. */ bool Push (const Type& value) noexcept { try { std::lock_guard<std::mutex> lock { mutex }; deque.push_front(value); } catch (const std::exception& /*err*/) { return false; } return true; } /** * @brief Method that pop value from back of deque. * * @tparam [out] result - Returned value. * @return TRUE - if pop back element is successful, otherwise - FALSE. * * @note Use this method for pop the oldest value in the deque. */ bool PopBack (Type& result) noexcept { try { std::lock_guard<std::mutex> lock { mutex }; } catch (const std::exception& /*err*/) { return false; } if (deque.empty() == true) { return false; } result = deque.back(); deque.pop_back(); return true; } /** * @brief Method that pop value from front of deque. * * @tparam [out] result - Returned value. * @return TRUE - if pop the front element is successful, otherwise - FALSE. */ bool PopFront (Type& result) noexcept { try { std::lock_guard<std::mutex> lock { mutex }; } catch (const std::system_error& /*err*/) { return false; } if (deque.empty() == true) { return false; } result = deque.front(); deque.pop_front(); return true; } /** * @brief Method that moves all internal values to outside STL std::deque<Type>. * * @tparam [out] result - Returned value. * @return TRUE - if at least one element has been moved, otherwise - FALSE. */ bool Move (std::deque<Type>& result) noexcept { try { std::lock_guard<std::mutex> lock { mutex }; } catch (const std::system_error& /*err*/) { return false; } if (deque.empty() == true) { return false; } result = std::move(deque); return true; } /** * @brief Method that swaps internal value with outside LockedDeque<Type> object. * * @tparam [in,out] other - Swapped value reference. * @return TRUE - if swap is successful, otherwise - FALSE. */ bool Swap (LockedDeque<Type>& other) noexcept { if (this != &other) { try { std::scoped_lock lock { mutex, other.mutex }; } catch (const std::system_error& /*err*/) { return false; } std::swap(deque, other.deque); } return true; } /** * @brief Method that swaps internal value with outside STL std::deque<Type>. * * @tparam [in,out] other - Swapped value reference. * @return TRUE - if swap is successful, otherwise - FALSE. */ bool Swap (std::deque<Type>& other) noexcept { try { std::lock_guard<std::mutex> lock { mutex }; } catch (const std::system_error& /*err*/) { return false; } std::swap(deque, other); return true; } /** * @brief Method that clears the deque. * * @return TRUE - if clear is successful, otherwise - FALSE. */ bool Clear(void) noexcept { try { std::lock_guard<std::mutex> lock { mutex }; } catch (const std::system_error& /*err*/) { return false; } deque.clear(); return true; } }; } // namespace types. #endif // PROTOCOL_ANALYZER_LOCKED_DEQUE_HPP <commit_msg>[FRAMEWORK/DATA] Fix logical error in LockedDeque class.<commit_after>// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com // ============================================================================ // Copyright (c) 2017-2019, by Vitaly Grigoriev, <[email protected]>. // This file is part of ProtocolAnalyzer open source project under MIT License. // ============================================================================ #ifndef PROTOCOL_ANALYZER_LOCKED_DEQUE_HPP #define PROTOCOL_ANALYZER_LOCKED_DEQUE_HPP #include <mutex> // std::mutex, std::scoped_lock, std::lock_guard. #include <deque> // std::deque. #include <utility> // std::move, std::swap. // In Common library MUST NOT use any another framework libraries because it is a core library. namespace analyzer::framework::common::types { /** * @class LockedDeque LockedDeque.hpp "include/framework/LockedDeque.hpp" * @brief This class defined concurrency wrapper over STL deque class to work in parallel threads. * * @tparam [in] Type - Typename of stored data in STL deque. * * @note This deque container if type-protected and provides a convenient RAII-style mechanism. * * @todo Set the global limit for adding new values to the deque. */ template <typename Type> class LockedDeque { private: /** * @brief Mutex value for thread-safe class working. */ std::mutex mutex = { }; /** * @brief STL deque for stored data; */ std::deque<Type> deque = { }; public: /** * @brief Default constructor. * * @throw std::bad_alloc - If there is not enough system memory for allocate the storage. */ LockedDeque(void) noexcept(std::is_nothrow_default_constructible_v<std::deque<Type>>) = default; /** * @brief Default destructor. */ ~LockedDeque(void) noexcept = default; /** * @brief Copy assignment constructor with LockedDeque. * * @tparam [in] other - Constant lvalue reference of copied LockedDeque. * * @throw std::bad_alloc - If there is not enough system memory for allocate the storage. */ LockedDeque (const LockedDeque& other) noexcept(std::is_nothrow_copy_constructible_v<std::deque<Type>>) { try { std::scoped_lock lock { mutex, other.mutex }; deque = other.deque; } catch (const std::system_error& /*err*/) { } } /** * @brief Copy assignment constructor with STL std::deque. * * @tparam [in] other - Constant lvalue reference of copied STL std::deque. * * @throw std::bad_alloc - If there is not enough system memory for allocate the storage. */ explicit LockedDeque (const std::deque<Type>& other) noexcept(std::is_nothrow_copy_constructible_v<std::deque<Type>>) { try { std::lock_guard<std::mutex> lock { mutex }; deque = other; } catch (const std::system_error& /*err*/) { } } /** * @brief Move assignment constructor with LockedDeque. * * @tparam [in] other - Rvalue reference of moved LockedDeque. */ LockedDeque (LockedDeque&& other) noexcept { try { std::scoped_lock lock { mutex, other.mutex }; deque = std::move(other.deque); } catch (const std::system_error& /*err*/) { } } /** * @brief Move assignment constructor with STL std::deque. * * @tparam [in] other - Rvalue reference of moved STL std::deque. */ explicit LockedDeque (std::deque<Type>&& other) noexcept { try { std::lock_guard<std::mutex> lock { mutex }; deque = std::move(other); } catch (const std::system_error& /*err*/) { } } /** * @brief Copy assignment operator. * * @tparam [in] other - Constant lvalue reference of copied LockedDeque class. * @return Lvalue reference of current LockedDeque class. * * @throw std::bad_alloc - If there is not enough system memory for allocate the storage. */ LockedDeque& operator= (const LockedDeque& other) noexcept(std::is_nothrow_copy_assignable_v<std::deque<Type>>) { if (this != &other) { try { std::scoped_lock lock { mutex, other.mutex }; deque = other.deque; } catch (const std::system_error& /*err*/) { } } return *this; } /** * @brief Move assignment operator. * * @tparam [in] other - Rvalue reference of moved LockedDeque class. * @return Lvalue reference of current LockedDeque class. */ LockedDeque& operator= (LockedDeque&& other) noexcept { if (this != &other) { try { std::scoped_lock lock { mutex, other.mutex }; deque = std::move(other.deque); } catch (const std::system_error& /*err*/) { } } return *this; } /** * @brief Method that returns the size of deque. * * @return Size of deque. */ std::size_t Size(void) noexcept { try { std::lock_guard<std::mutex> lock { mutex }; return deque.size(); } catch (const std::system_error& /*err*/) { return 0; } } /** * @brief Method that returns the internal state of deque. * * @return TRUE - if container is empty, otherwise - FALSE. */ bool IsEmpty(void) noexcept { try { std::lock_guard<std::mutex> lock { mutex }; return deque.empty(); } catch (const std::system_error& /*err*/) { return false; } } /** * @brief Method that push new value to front of deque. * * @tparam [in] value - New value for insert. * @return TRUE - if pushing is successful, otherwise - FALSE. */ bool Push (const Type& value) noexcept { try { std::lock_guard<std::mutex> lock { mutex }; deque.push_front(value); } catch (const std::exception& /*err*/) { return false; } return true; } /** * @brief Method that pops value from the back of deque. * * @tparam [out] result - Returned value. * @return TRUE - if popping element from back is successful, otherwise - FALSE. * * @note Use this method for pop the oldest value in the deque. */ bool PopBack (Type& result) noexcept { try { std::lock_guard<std::mutex> lock { mutex }; if (deque.empty() == true) { return false; } result = deque.back(); deque.pop_back(); } catch (const std::exception& /*err*/) { return false; } return true; } /** * @brief Method that pops value from the front of deque. * * @tparam [out] result - Returned value. * @return TRUE - if popping element from front is successful, otherwise - FALSE. */ bool PopFront (Type& result) noexcept { try { std::lock_guard<std::mutex> lock { mutex }; if (deque.empty() == true) { return false; } result = deque.front(); deque.pop_front(); } catch (const std::system_error& /*err*/) { return false; } return true; } /** * @brief Method that moves all internal values to outside STL std::deque. * * @tparam [out] result - Returned value. * @return TRUE - if at least one element has been moved, otherwise - FALSE. */ bool Move (std::deque<Type>& result) noexcept { try { std::lock_guard<std::mutex> lock { mutex }; if (deque.empty() == true) { return false; } result = std::move(deque); } catch (const std::system_error& /*err*/) { return false; } return true; } /** * @brief Method that swaps internal value with outside LockedDeque object. * * @tparam [in,out] other - Lvalue reference of swapped value. * @return TRUE - if swapping is successful, otherwise - FALSE. */ bool Swap (LockedDeque& other) noexcept { if (this != &other) { try { std::scoped_lock lock { mutex, other.mutex }; std::swap(deque, other.deque); } catch (const std::system_error& /*err*/) { return false; } } return true; } /** * @brief Method that swaps internal value with outside STL std::deque. * * @tparam [in,out] other - Lvalue reference of swapped value. * @return TRUE - if swapping is successful, otherwise - FALSE. */ bool Swap (std::deque<Type>& other) noexcept { try { std::lock_guard<std::mutex> lock { mutex }; std::swap(deque, other); } catch (const std::system_error& /*err*/) { return false; } return true; } /** * @brief Method that clears the deque. * * @return TRUE - if clearing is successful, otherwise - FALSE. */ bool Clear(void) noexcept { try { std::lock_guard<std::mutex> lock { mutex }; deque.clear(); } catch (const std::system_error& /*err*/) { return false; } return true; } }; } // namespace types. #endif // PROTOCOL_ANALYZER_LOCKED_DEQUE_HPP <|endoftext|>
<commit_before>//----------------------------------------------------------------------------- // Jikken - 3D Abstract High Performance Graphics API // Copyright(c) 2017 Jeff Hutchinson // Copyright(c) 2017 Tim Barnes // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files(the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and / or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions : // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //----------------------------------------------------------------------------- #ifndef _JIKKEN_GRAPHICSDEVICE_HPP_ #define _JIKKEN_GRAPHICSDEVICE_HPP_ #include <vector> #include <string> #include "jikken/enums.hpp" #include "jikken/commands.hpp" #include "jikken/commandQueue.hpp" namespace Jikken { struct ShaderDetails { std::string file; ShaderStage stage; }; class GraphicsDevice { public: virtual ~GraphicsDevice() {} virtual ShaderHandle createShader(const std::vector<ShaderDetails> &shaders) = 0; virtual BufferHandle createBuffer(BufferType type, BufferUsageHint hint, size_t dataSize, float *data) = 0; virtual void deleteBuffer(BufferHandle handle) = 0; virtual void deleteShader(ShaderHandle handle) = 0; }; } #endif<commit_msg>input layout and VAO<commit_after>//----------------------------------------------------------------------------- // Jikken - 3D Abstract High Performance Graphics API // Copyright(c) 2017 Jeff Hutchinson // Copyright(c) 2017 Tim Barnes // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files(the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and / or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions : // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //----------------------------------------------------------------------------- #ifndef _JIKKEN_GRAPHICSDEVICE_HPP_ #define _JIKKEN_GRAPHICSDEVICE_HPP_ #include <vector> #include <string> #include "jikken/enums.hpp" #include "jikken/commands.hpp" #include "jikken/commandQueue.hpp" namespace Jikken { enum VertexAttributeName : int32_t { ePOSITION = 0 }; enum VertexAttributeType : int32_t { eFLOAT = 0, eUNSIGNED_INTEGER = 1, eSIGNED_INTEGER = 2s }; struct VertexInputLayout { VertexAttributeName attribute; int32_t componentSize; VertexAttributeType type; uint32_t stride; size_t offset; }; struct ShaderDetails { std::string file; ShaderStage stage; }; class GraphicsDevice { public: virtual ~GraphicsDevice() {} virtual ShaderHandle createShader(const std::vector<ShaderDetails> &shaders) = 0; virtual BufferHandle createBuffer(BufferType type, BufferUsageHint hint, size_t dataSize, float *data) = 0; virtual LayoutHandle createVertexInputLayout(const std::vector<VertexInputLayout> &attributes) = 0; virtual VertexArrayHandle createVertexArrayObject(LayoutHandle layout, BufferHandle vertexBuffer, BufferHandle indexBuffer = 0) = 0; virtual void deleteVertexInputLayout(LayoutHandle handle) = 0; virtual void deleteVertexArrayObject(VertexArrayHandle handle) = 0; virtual void deleteBuffer(BufferHandle handle) = 0; virtual void deleteShader(ShaderHandle handle) = 0; }; } #endif <|endoftext|>
<commit_before><commit_msg>WaE: implicit conversion (IntegralCast) from bool to 'unsigned long'<commit_after><|endoftext|>
<commit_before>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions 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 the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_PROXY_BASE_HPP_INCLUDED #define TORRENT_PROXY_BASE_HPP_INCLUDED #include "libtorrent/io.hpp" #include "libtorrent/socket.hpp" #include <boost/bind.hpp> #include <boost/lexical_cast.hpp> #include <boost/function.hpp> #include <asio/read.hpp> #include <asio/write.hpp> namespace libtorrent { class proxy_base : boost::noncopyable { public: typedef stream_socket::lowest_layer_type lowest_layer_type; typedef stream_socket::endpoint_type endpoint_type; typedef stream_socket::protocol_type protocol_type; explicit proxy_base(asio::io_service& io_service) : m_sock(io_service) , m_resolver(io_service) {} void set_proxy(std::string hostname, int port) { m_hostname = hostname; m_port = port; } template <class Mutable_Buffers, class Handler> void async_read_some(Mutable_Buffers const& buffers, Handler const& handler) { m_sock.async_read_some(buffers, handler); } template <class Mutable_Buffers> std::size_t read_some(Mutable_Buffers const& buffers, asio::error_code& ec) { return m_sock.read_some(buffers, ec); } template <class Mutable_Buffers> std::size_t read_some(Mutable_Buffers const& buffers) { return m_sock.read_some(buffers); } template <class IO_Control_Command> void io_control(IO_Control_Command& ioc) { m_sock.io_control(ioc); } template <class IO_Control_Command> void io_control(IO_Control_Command& ioc, asio::error_code& ec) { m_sock.io_control(ioc, ec); } template <class Const_Buffers, class Handler> void async_write_some(Const_Buffers const& buffers, Handler const& handler) { m_sock.async_write_some(buffers, handler); } void bind(endpoint_type const& endpoint) { m_sock.bind(endpoint); } template <class Error_Handler> void bind(endpoint_type const& endpoint, Error_Handler const& error_handler) { m_sock.bind(endpoint, error_handler); } void open(protocol_type const& p) { m_sock.open(p); } template <class Error_Handler> void open(protocol_type const& p, Error_Handler const& error_handler) { m_sock.open(p, error_handler); } void close() { m_remote_endpoint = endpoint_type(); m_sock.close(); } template <class Error_Handler> void close(Error_Handler const& error_handler) { m_sock.close(error_handler); } endpoint_type remote_endpoint() { return m_remote_endpoint; } template <class Error_Handler> endpoint_type remote_endpoint(Error_Handler const& error_handler) { return m_remote_endpoint; } endpoint_type local_endpoint() { return m_sock.local_endpoint(); } template <class Error_Handler> endpoint_type local_endpoint(Error_Handler const& error_handler) { return m_sock.local_endpoint(error_handler); } asio::io_service& io_service() { return m_sock.io_service(); } lowest_layer_type& lowest_layer() { return m_sock.lowest_layer(); } protected: stream_socket m_sock; std::string m_hostname; int m_port; endpoint_type m_remote_endpoint; tcp::resolver m_resolver; }; } #endif <commit_msg>cleaned up unnecessary template functions<commit_after>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions 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 the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_PROXY_BASE_HPP_INCLUDED #define TORRENT_PROXY_BASE_HPP_INCLUDED #include "libtorrent/io.hpp" #include "libtorrent/socket.hpp" #include <boost/bind.hpp> #include <boost/lexical_cast.hpp> #include <boost/function.hpp> #include <asio/read.hpp> #include <asio/write.hpp> namespace libtorrent { class proxy_base : boost::noncopyable { public: typedef stream_socket::lowest_layer_type lowest_layer_type; typedef stream_socket::endpoint_type endpoint_type; typedef stream_socket::protocol_type protocol_type; explicit proxy_base(asio::io_service& io_service) : m_sock(io_service) , m_resolver(io_service) {} void set_proxy(std::string hostname, int port) { m_hostname = hostname; m_port = port; } template <class Mutable_Buffers, class Handler> void async_read_some(Mutable_Buffers const& buffers, Handler const& handler) { m_sock.async_read_some(buffers, handler); } template <class Mutable_Buffers> std::size_t read_some(Mutable_Buffers const& buffers, asio::error_code& ec) { return m_sock.read_some(buffers, ec); } template <class Mutable_Buffers> std::size_t read_some(Mutable_Buffers const& buffers) { return m_sock.read_some(buffers); } template <class IO_Control_Command> void io_control(IO_Control_Command& ioc) { m_sock.io_control(ioc); } template <class IO_Control_Command> void io_control(IO_Control_Command& ioc, asio::error_code& ec) { m_sock.io_control(ioc, ec); } template <class Const_Buffers, class Handler> void async_write_some(Const_Buffers const& buffers, Handler const& handler) { m_sock.async_write_some(buffers, handler); } void bind(endpoint_type const& endpoint) { m_sock.bind(endpoint); } void bind(endpoint_type const& endpoint, asio::error_code& ec) { m_sock.bind(endpoint, ec); } void open(protocol_type const& p) { m_sock.open(p); } void open(protocol_type const& p, asio::error_code& ec) { m_sock.open(p, ec); } void close() { m_remote_endpoint = endpoint_type(); m_sock.close(); } void close(asio::error_code& ec) { m_sock.close(ec); } endpoint_type remote_endpoint() { return m_remote_endpoint; } endpoint_type remote_endpoint(asio::error_code& ec) { return m_remote_endpoint; } endpoint_type local_endpoint() { return m_sock.local_endpoint(); } endpoint_type local_endpoint(asio::error_code& ec) { return m_sock.local_endpoint(ec); } asio::io_service& io_service() { return m_sock.io_service(); } lowest_layer_type& lowest_layer() { return m_sock.lowest_layer(); } protected: stream_socket m_sock; std::string m_hostname; int m_port; endpoint_type m_remote_endpoint; tcp::resolver m_resolver; }; } #endif <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: TestBlurAndSobelPasses.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // This test covers the ability for the value painter to draw arrays as // colors such that the visible values can be recovered from the pixels. #include <vtkActor.h> #include <vtkCellArray.h> #include <vtkCellData.h> #include <vtkDoubleArray.h> #include <vtkMath.h> #include <vtkPointData.h> #include <vtkPoints.h> #include <vtkPolyData.h> #include <vtkPainterPolyDataMapper.h> #include <vtkRenderer.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkSmartPointer.h> #include <vtkValuePainter.h> #include <vtkWindowToImageFilter.h> #include <set> #define MAX 10 void PrepArray(bool byName, bool drawCell, int arrayIndex, int arrayComponent, vtkDataSet *dataset, vtkDataArray *values, vtkValuePainter *painter, double *&minmax) { if (drawCell) { if (arrayIndex > dataset->GetCellData()->GetNumberOfArrays()) { arrayIndex = 0; } values = dataset->GetCellData()->GetArray(arrayIndex); if (arrayComponent > values->GetNumberOfComponents()) { arrayComponent = 0; } cerr << "Drawing CELL " << values->GetName() << " [" << arrayComponent << "]" << endl; if (!byName) { painter->SetInputArrayToProcess(VTK_SCALAR_MODE_USE_CELL_FIELD_DATA, arrayIndex); } else { painter->SetInputArrayToProcess(VTK_SCALAR_MODE_USE_CELL_FIELD_DATA, values->GetName()); } minmax = values->GetRange(arrayComponent); } else { if (arrayIndex > dataset->GetPointData()->GetNumberOfArrays()) { arrayIndex = 0; } values = dataset->GetPointData()->GetArray(arrayIndex); if (arrayComponent > values->GetNumberOfComponents()) { arrayComponent = 0; } cerr << "Drawing POINT " << values->GetName() << " [" << arrayComponent << "]" << endl; if (!byName) { painter->SetInputArrayToProcess(VTK_SCALAR_MODE_USE_POINT_FIELD_DATA, arrayIndex); } else { painter->SetInputArrayToProcess(VTK_SCALAR_MODE_USE_POINT_FIELD_DATA, values->GetName()); } minmax = values->GetRange(arrayComponent); } painter->SetInputComponentToProcess(arrayComponent); painter->SetScalarRange(minmax[0], minmax[1]); } int TestValuePainter(int argc, char* argv[]) { bool byName = true; bool drawCell = true; unsigned int arrayIndex = 0; unsigned int arrayComponent = 0; bool interactive = false; for (int i = 0; i < argc; i++) { if (!strcmp(argv[i],"index")) { byName = false; } if (!strcmp(argv[i],"point")) { drawCell = false; } if (!strcmp(argv[i],"N")) { arrayIndex = atoi(argv[i+1]); } if (!strcmp(argv[i],"C")) { arrayComponent = atoi(argv[i+1]); } if (!strcmp(argv[i],"-I")) { interactive = true; } } vtkSmartPointer<vtkPolyData> dataset = vtkSmartPointer<vtkPolyData>::New(); vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); dataset->SetPoints(points); vtkSmartPointer<vtkDoubleArray> scalars = vtkSmartPointer<vtkDoubleArray>::New(); scalars->SetNumberOfComponents(1); scalars->SetName("Point Scalar Array 1"); dataset->GetPointData()->AddArray(scalars); vtkSmartPointer<vtkDoubleArray> vectors = vtkSmartPointer<vtkDoubleArray>::New(); vectors->SetNumberOfComponents(3); vectors->SetName("Point Vector Array 1"); dataset->GetPointData()->AddArray(vectors); double vector[3]; for (unsigned int i = 0; i < MAX; i++) { for (unsigned int j = 0; j < MAX; j++) { points->InsertNextPoint(i,j,0.0); scalars->InsertNextValue((double)i/MAX+10); vector[0] = sin((double)j/MAX*6.1418); vector[1] = 1.0; vector[2] = 1.0; vtkMath::Normalize(vector); vectors->InsertNextTuple3(vector[0],vector[1],vector[2]); } } vtkSmartPointer<vtkCellArray> cells = vtkSmartPointer<vtkCellArray>::New(); dataset->SetPolys(cells); scalars = vtkSmartPointer<vtkDoubleArray>::New(); scalars->SetNumberOfComponents(1); scalars->SetName("Cell Scalar Array 1"); dataset->GetCellData()->AddArray(scalars); vectors = vtkSmartPointer<vtkDoubleArray>::New(); vectors->SetNumberOfComponents(3); vectors->SetName("Cell Vector Array 1"); dataset->GetCellData()->AddArray(vectors); for (unsigned int i = 0; i < (MAX-1); i++) { for (unsigned int j = 0; j < (MAX-1); j++) { cells->InsertNextCell(4); cells->InsertCellPoint(i*MAX +j); cells->InsertCellPoint(i*MAX +j+1); cells->InsertCellPoint((i+1)*MAX+j+1); cells->InsertCellPoint((i+1)*MAX+j); scalars->InsertNextValue((double)i/(MAX-1)-10); vector[0] = sin((double)j/(MAX-1)*6.1418); vector[1] = 1.0; vector[2] = 1.0; vtkMath::Normalize(vector); vectors->InsertNextTuple3(vector[0],vector[1],vector[2]); } } vtkSmartPointer<vtkPainterPolyDataMapper> mapper = vtkSmartPointer<vtkPainterPolyDataMapper>::New(); mapper->SetInputData(dataset); mapper->SetScalarModeToUsePointData(); mapper->SelectColorArray(0); vtkSmartPointer<vtkValuePainter> painter = vtkSmartPointer<vtkValuePainter>::New(); vtkDataArray *values = NULL; double *minmax; PrepArray(byName, drawCell, arrayIndex, arrayComponent, dataset, values, painter, minmax); double scale = minmax[1]-minmax[0]; painter->SetInputComponentToProcess(arrayComponent); mapper->SetPainter(painter); vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New(); actor->SetMapper(mapper); vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New(); //manually set background to the "nothing" color renderer->SetBackground(0.0,0.0,0.0); renderer->GradientBackgroundOff(); vtkSmartPointer<vtkRenderWindow> renderWindow = vtkSmartPointer<vtkRenderWindow>::New(); renderWindow->AddRenderer(renderer); vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New(); renderWindowInteractor->SetRenderWindow(renderWindow); renderer->AddActor(actor); renderWindow->Render(); //iterate to look for leaks and such for (int i = 0; i < 8; i++) { bool _byName = true; bool _drawCell = true; vtkFieldData *fd = dataset->GetCellData(); if (i<4) { _byName = false; } if (i%2) { _drawCell = false; fd = dataset->GetPointData(); } for (int j = 0; j < fd->GetNumberOfArrays(); j++) { for (int k = 0; k < fd->GetArray(j)->GetNumberOfComponents(); k++) { PrepArray(_byName, _drawCell, j, k, dataset, values, painter, minmax); renderWindow->Render(); //std::string v; //cin >> v; } } } PrepArray(byName, drawCell, arrayIndex, arrayComponent, dataset, values, painter, minmax); renderWindow->Render(); vtkSmartPointer<vtkWindowToImageFilter> grabber = vtkSmartPointer<vtkWindowToImageFilter>::New(); grabber->SetInput(renderWindow); grabber->Update(); vtkImageData *id = grabber->GetOutput(); //id->PrintSelf(cerr, vtkIndent(0)); vtkUnsignedCharArray *ar = vtkUnsignedCharArray::SafeDownCast(id->GetPointData()->GetArray("ImageScalars")); unsigned char *ptr = static_cast<unsigned char*>(ar->GetVoidPointer(0)); std::set<double> found; double value; for (int i = 0; i < id->GetNumberOfPoints(); i++) { vtkValuePainter::ColorToValue(ptr, minmax[0], scale, value); if (found.find(value)==found.end()) { found.insert(value); cerr << "READ " << std::hex << (int) ptr[0] << (int) ptr[1] << (int) ptr[2] << "\t" << std::dec << value << endl; } ptr+=3; } std::set<double>::iterator it; double min = VTK_DOUBLE_MAX; double max = VTK_DOUBLE_MIN; for (it = found.begin(); it != found.end(); ++it) { if (*it < min) { min = *it; } if (*it > max) { max = *it; } } bool fail = false; if (fabs(min - -10.0) > 0.12) { cerr << "ERROR min value not correct" << endl; fail = true; } if (fabs(max - -9.0) > 0.12) { cerr << "ERROR max value not correct" << endl; fail = true; } if (interactive) { renderWindowInteractor->Start(); } return fail; } <commit_msg>COMP: fix macro redefinition comp warning<commit_after>/*========================================================================= Program: Visualization Toolkit Module: TestValuePainter.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // This test covers the ability for the value painter to draw arrays as // colors such that the visible values can be recovered from the pixels. #include <vtkActor.h> #include <vtkCellArray.h> #include <vtkCellData.h> #include <vtkDoubleArray.h> #include <vtkMath.h> #include <vtkPointData.h> #include <vtkPoints.h> #include <vtkPolyData.h> #include <vtkPainterPolyDataMapper.h> #include <vtkRenderer.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkSmartPointer.h> #include <vtkValuePainter.h> #include <vtkWindowToImageFilter.h> #include <set> #define TESTVP_MAX 10 void PrepArray(bool byName, bool drawCell, int arrayIndex, int arrayComponent, vtkDataSet *dataset, vtkDataArray *values, vtkValuePainter *painter, double *&minmax) { if (drawCell) { if (arrayIndex > dataset->GetCellData()->GetNumberOfArrays()) { arrayIndex = 0; } values = dataset->GetCellData()->GetArray(arrayIndex); if (arrayComponent > values->GetNumberOfComponents()) { arrayComponent = 0; } cerr << "Drawing CELL " << values->GetName() << " [" << arrayComponent << "]" << endl; if (!byName) { painter->SetInputArrayToProcess(VTK_SCALAR_MODE_USE_CELL_FIELD_DATA, arrayIndex); } else { painter->SetInputArrayToProcess(VTK_SCALAR_MODE_USE_CELL_FIELD_DATA, values->GetName()); } minmax = values->GetRange(arrayComponent); } else { if (arrayIndex > dataset->GetPointData()->GetNumberOfArrays()) { arrayIndex = 0; } values = dataset->GetPointData()->GetArray(arrayIndex); if (arrayComponent > values->GetNumberOfComponents()) { arrayComponent = 0; } cerr << "Drawing POINT " << values->GetName() << " [" << arrayComponent << "]" << endl; if (!byName) { painter->SetInputArrayToProcess(VTK_SCALAR_MODE_USE_POINT_FIELD_DATA, arrayIndex); } else { painter->SetInputArrayToProcess(VTK_SCALAR_MODE_USE_POINT_FIELD_DATA, values->GetName()); } minmax = values->GetRange(arrayComponent); } painter->SetInputComponentToProcess(arrayComponent); painter->SetScalarRange(minmax[0], minmax[1]); } int TestValuePainter(int argc, char* argv[]) { bool byName = true; bool drawCell = true; unsigned int arrayIndex = 0; unsigned int arrayComponent = 0; bool interactive = false; for (int i = 0; i < argc; i++) { if (!strcmp(argv[i],"index")) { byName = false; } if (!strcmp(argv[i],"point")) { drawCell = false; } if (!strcmp(argv[i],"N")) { arrayIndex = atoi(argv[i+1]); } if (!strcmp(argv[i],"C")) { arrayComponent = atoi(argv[i+1]); } if (!strcmp(argv[i],"-I")) { interactive = true; } } vtkSmartPointer<vtkPolyData> dataset = vtkSmartPointer<vtkPolyData>::New(); vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); dataset->SetPoints(points); vtkSmartPointer<vtkDoubleArray> scalars = vtkSmartPointer<vtkDoubleArray>::New(); scalars->SetNumberOfComponents(1); scalars->SetName("Point Scalar Array 1"); dataset->GetPointData()->AddArray(scalars); vtkSmartPointer<vtkDoubleArray> vectors = vtkSmartPointer<vtkDoubleArray>::New(); vectors->SetNumberOfComponents(3); vectors->SetName("Point Vector Array 1"); dataset->GetPointData()->AddArray(vectors); double vector[3]; for (unsigned int i = 0; i < TESTVP_MAX; i++) { for (unsigned int j = 0; j < TESTVP_MAX; j++) { points->InsertNextPoint(i,j,0.0); scalars->InsertNextValue((double)i/TESTVP_MAX+10); vector[0] = sin((double)j/TESTVP_MAX*6.1418); vector[1] = 1.0; vector[2] = 1.0; vtkMath::Normalize(vector); vectors->InsertNextTuple3(vector[0],vector[1],vector[2]); } } vtkSmartPointer<vtkCellArray> cells = vtkSmartPointer<vtkCellArray>::New(); dataset->SetPolys(cells); scalars = vtkSmartPointer<vtkDoubleArray>::New(); scalars->SetNumberOfComponents(1); scalars->SetName("Cell Scalar Array 1"); dataset->GetCellData()->AddArray(scalars); vectors = vtkSmartPointer<vtkDoubleArray>::New(); vectors->SetNumberOfComponents(3); vectors->SetName("Cell Vector Array 1"); dataset->GetCellData()->AddArray(vectors); for (unsigned int i = 0; i < (TESTVP_MAX-1); i++) { for (unsigned int j = 0; j < (TESTVP_MAX-1); j++) { cells->InsertNextCell(4); cells->InsertCellPoint(i*TESTVP_MAX +j); cells->InsertCellPoint(i*TESTVP_MAX +j+1); cells->InsertCellPoint((i+1)*TESTVP_MAX+j+1); cells->InsertCellPoint((i+1)*TESTVP_MAX+j); scalars->InsertNextValue((double)i/(TESTVP_MAX-1)-10); vector[0] = sin((double)j/(TESTVP_MAX-1)*6.1418); vector[1] = 1.0; vector[2] = 1.0; vtkMath::Normalize(vector); vectors->InsertNextTuple3(vector[0],vector[1],vector[2]); } } vtkSmartPointer<vtkPainterPolyDataMapper> mapper = vtkSmartPointer<vtkPainterPolyDataMapper>::New(); mapper->SetInputData(dataset); mapper->SetScalarModeToUsePointData(); mapper->SelectColorArray(0); vtkSmartPointer<vtkValuePainter> painter = vtkSmartPointer<vtkValuePainter>::New(); vtkDataArray *values = NULL; double *minmax; PrepArray(byName, drawCell, arrayIndex, arrayComponent, dataset, values, painter, minmax); double scale = minmax[1]-minmax[0]; painter->SetInputComponentToProcess(arrayComponent); mapper->SetPainter(painter); vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New(); actor->SetMapper(mapper); vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New(); //manually set background to the "nothing" color renderer->SetBackground(0.0,0.0,0.0); renderer->GradientBackgroundOff(); vtkSmartPointer<vtkRenderWindow> renderWindow = vtkSmartPointer<vtkRenderWindow>::New(); renderWindow->AddRenderer(renderer); vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New(); renderWindowInteractor->SetRenderWindow(renderWindow); renderer->AddActor(actor); renderWindow->Render(); //iterate to look for leaks and such for (int i = 0; i < 8; i++) { bool _byName = true; bool _drawCell = true; vtkFieldData *fd = dataset->GetCellData(); if (i<4) { _byName = false; } if (i%2) { _drawCell = false; fd = dataset->GetPointData(); } for (int j = 0; j < fd->GetNumberOfArrays(); j++) { for (int k = 0; k < fd->GetArray(j)->GetNumberOfComponents(); k++) { PrepArray(_byName, _drawCell, j, k, dataset, values, painter, minmax); renderWindow->Render(); //std::string v; //cin >> v; } } } PrepArray(byName, drawCell, arrayIndex, arrayComponent, dataset, values, painter, minmax); renderWindow->Render(); vtkSmartPointer<vtkWindowToImageFilter> grabber = vtkSmartPointer<vtkWindowToImageFilter>::New(); grabber->SetInput(renderWindow); grabber->Update(); vtkImageData *id = grabber->GetOutput(); //id->PrintSelf(cerr, vtkIndent(0)); vtkUnsignedCharArray *ar = vtkUnsignedCharArray::SafeDownCast(id->GetPointData()->GetArray("ImageScalars")); unsigned char *ptr = static_cast<unsigned char*>(ar->GetVoidPointer(0)); std::set<double> found; double value; for (int i = 0; i < id->GetNumberOfPoints(); i++) { vtkValuePainter::ColorToValue(ptr, minmax[0], scale, value); if (found.find(value)==found.end()) { found.insert(value); cerr << "READ " << std::hex << (int) ptr[0] << (int) ptr[1] << (int) ptr[2] << "\t" << std::dec << value << endl; } ptr+=3; } std::set<double>::iterator it; double min = VTK_DOUBLE_MAX; double max = VTK_DOUBLE_MIN; for (it = found.begin(); it != found.end(); ++it) { if (*it < min) { min = *it; } if (*it > max) { max = *it; } } bool fail = false; if (fabs(min - -10.0) > 0.12) { cerr << "ERROR min value not correct" << endl; fail = true; } if (fabs(max - -9.0) > 0.12) { cerr << "ERROR max value not correct" << endl; fail = true; } if (interactive) { renderWindowInteractor->Start(); } return fail; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: csvsplits.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: dr $ $Date: 2002-08-16 13:01:00 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ // ============================================================================ #ifndef _SC_CSVSPLITS_HXX #define _SC_CSVSPLITS_HXX #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif #include <vector> // ============================================================================ /** Constant for an invalid vector index. */ const sal_uInt32 CSV_VEC_NOTFOUND = ~0UL; /** Constant for an invalid ruler position. */ const sal_Int32 CSV_POS_INVALID = -1; // ---------------------------------------------------------------------------- /** A vector of column splits that supports inserting, removing and moving splits. */ class ScCsvSplits { private: typedef ::std::vector< sal_Int32 > ScSplitVector; typedef ScSplitVector::iterator iterator; typedef ScSplitVector::const_iterator const_iterator; ScSplitVector maVec; /// The split containter. public: // *** access by position *** --------------------------------------------- /** Inserts a new split at position nPos into the vector. @return true = split inserted (nPos was valid and empty). */ bool Insert( sal_Int32 nPos ); /** Removes a split by position. @return true = split found and removed. */ bool Remove( sal_Int32 nPos ); /** Removes a range of splits in the given position range. */ void RemoveRange( sal_Int32 nPosStart, sal_Int32 nPosEnd ); /** Removes all elements from the vector. */ void Clear(); /** Returns true if at position nPos is a split. */ bool HasSplit( sal_Int32 nPos ) const; // *** access by index *** ------------------------------------------------ /** Searches for a split at position nPos. @return the vector index of the split. */ sal_uInt32 GetIndex( sal_Int32 nPos ) const; /** Returns index of the first split greater than or equal to nPos. */ sal_uInt32 LowerBound( sal_Int32 nPos ) const; /** Returns index of the last split less than or equal to nPos. */ sal_uInt32 UpperBound( sal_Int32 nPos ) const; /** Returns the number of splits. */ inline sal_uInt32 Count() const { return maVec.size(); } /** Returns the position of the specified split. */ sal_Int32 GetPos( sal_uInt32 nIndex ) const; /** Returns the position of the specified split. */ inline sal_Int32 operator[]( sal_uInt32 nIndex ) const { return GetPos( nIndex ); } private: /** Returns the vector index of an iterator. */ sal_uInt32 GetIterIndex( const_iterator aIter ) const; }; // ============================================================================ #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.2.904); FILE MERGED 2005/09/05 15:05:13 rt 1.2.904.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: csvsplits.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 21:18:33 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // ============================================================================ #ifndef _SC_CSVSPLITS_HXX #define _SC_CSVSPLITS_HXX #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif #include <vector> // ============================================================================ /** Constant for an invalid vector index. */ const sal_uInt32 CSV_VEC_NOTFOUND = ~0UL; /** Constant for an invalid ruler position. */ const sal_Int32 CSV_POS_INVALID = -1; // ---------------------------------------------------------------------------- /** A vector of column splits that supports inserting, removing and moving splits. */ class ScCsvSplits { private: typedef ::std::vector< sal_Int32 > ScSplitVector; typedef ScSplitVector::iterator iterator; typedef ScSplitVector::const_iterator const_iterator; ScSplitVector maVec; /// The split containter. public: // *** access by position *** --------------------------------------------- /** Inserts a new split at position nPos into the vector. @return true = split inserted (nPos was valid and empty). */ bool Insert( sal_Int32 nPos ); /** Removes a split by position. @return true = split found and removed. */ bool Remove( sal_Int32 nPos ); /** Removes a range of splits in the given position range. */ void RemoveRange( sal_Int32 nPosStart, sal_Int32 nPosEnd ); /** Removes all elements from the vector. */ void Clear(); /** Returns true if at position nPos is a split. */ bool HasSplit( sal_Int32 nPos ) const; // *** access by index *** ------------------------------------------------ /** Searches for a split at position nPos. @return the vector index of the split. */ sal_uInt32 GetIndex( sal_Int32 nPos ) const; /** Returns index of the first split greater than or equal to nPos. */ sal_uInt32 LowerBound( sal_Int32 nPos ) const; /** Returns index of the last split less than or equal to nPos. */ sal_uInt32 UpperBound( sal_Int32 nPos ) const; /** Returns the number of splits. */ inline sal_uInt32 Count() const { return maVec.size(); } /** Returns the position of the specified split. */ sal_Int32 GetPos( sal_uInt32 nIndex ) const; /** Returns the position of the specified split. */ inline sal_Int32 operator[]( sal_uInt32 nIndex ) const { return GetPos( nIndex ); } private: /** Returns the vector index of an iterator. */ sal_uInt32 GetIterIndex( const_iterator aIter ) const; }; // ============================================================================ #endif <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <sauce/sauce.h> namespace sauce { namespace test { /** * This suite is intended to be a complete (if stubbed) example of how sauce might be used to manage the dependencies * of a typical MVC-like application. Unlike binding_test, whose aim is coverage across all variations of binding and * use, the focus here is on clarity and documentation. * * Suppose we are creating a web application allowing a Mom & Pop pizza parlour to accept orders online. Customers can * choose toppings, sauce (ha!) and crust, specify take-out or delivery (giving an address as needed) and later inspect * the progress of their order. An employee at the store uses a similar interface to declare when an order has * started, left for delivery, etc. This application runs in a three-tier architecture of a web server backed by app * processes talking to a single relational database. * * Even in this simple application there is complexity to manage, which can be addressed by following the MVC pattern. * Vanilla MVC articulates a useful separation of concerns and wraps each in an object. However it is silent about how * those objects are ultimately assembled into the final application; this is where dependency injection (and sauce) * can help. * * Since the point of the technique is to keep components decoupled and unaware of each other, a real application would * likely spread its components out across many headers and compilation units. This poses no problem for sauce, but * for clarity everything in this example is contained in this suite. Comments are included where suggested file * breaks might occur. */ TEST(TutorialTest, shouldExist) { ASSERT_TRUE(true); } } } <commit_msg>doco!<commit_after>#include <gtest/gtest.h> #include <sauce/sauce.h> namespace sauce { namespace test { /** * This suite is intended to be a complete (if stubbed) example of how sauce might be used to manage the dependencies * of a typical MVC-like application. Unlike binding_test, whose aim is coverage across all variations of binding and * use, the focus here is on clarity and documentation. * * Suppose we are creating a web application allowing a Mom & Pop pizza parlour to accept orders online. Customers can * choose toppings, sauce (ha!) and crust, specify take-out or delivery (giving an address as needed) and later inspect * the progress of their order. An employee at the store uses a similar interface to declare when an order has * started, left for delivery, etc. This application runs in a three-tier architecture of a web server backed by app * processes talking to a single relational database. * * Even in this simple application there is complexity to manage, which can be addressed by following the MVC pattern. * Vanilla MVC articulates a useful separation of concerns and wraps each in an object. However it is silent about how * those objects are ultimately assembled into the final application; this is where dependency injection (and sauce) * can help. * * Since the point of the technique is to keep components decoupled and unaware of each other, a real application would * likely spread its components out across many headers and compilation units. This poses no problem for sauce, but * for clarity everything in this example is contained in this suite. Comments indicate where suggested file breaks * might occur. */ // ******************************************************************************************************************** // orm.h /** * This is not part of the pizza application proper, but is a library used by the application author to manage access * to the database. It does so by materializing rows as application objects in memory, hiding details (like SQL) from * the application author. */ // ******************************************************************************************************************** // routes.h /** * This too is a library used by the application author, now to declare how incoming requests are mapped to the * controllers that serve them. */ // ******************************************************************************************************************** // clock.h /** * This library just exposes the local clock, allowing the application author to sample timestamps. */ // ******************************************************************************************************************** // order_model.h /** * A pizza order being processed. */ // ******************************************************************************************************************** // place_controller.h /** * Handles requests to place an order. */ // ******************************************************************************************************************** // status_controller.h /** * Handles requests regarding an order's status. */ // ******************************************************************************************************************** // place_controller_test.cc /** * The unit test suite for PlaceController, demonstrating how to inject mocks or stubs. */ // ******************************************************************************************************************** // production_module.cc /** * The sauce module, written by the application author, that specifies the bindings used when running in production. */ // ******************************************************************************************************************** // main.cc /** * The entry point of the application, and where sauce injects dependencies. */ TEST(TutorialTest, main) { // Let's pretend this is main() ASSERT_TRUE(true); } } } <|endoftext|>
<commit_before>#ifndef __bootstrap_hpp #define __bootstrap_hpp__ #include "boxedcpp.hpp" template<typename Ret, typename P1, typename P2> Ret add(P1 p1, P2 p2) { return p1 + p2; } template<typename Ret, typename P1, typename P2> Ret subtract(P1 p1, P2 p2) { return p1 - p2; } template<typename Ret, typename P1, typename P2> Ret divide(P1 p1, P2 p2) { return p1 - p2; } template<typename Ret, typename P1, typename P2> Ret multiply(P1 p1, P2 p2) { return p1 * p2; } template<typename P1, typename P2> bool bool_and(P1 p1, P2 p2) { return p1 && p2; } template<typename P1, typename P2> bool bool_or(P1 p1, P2 p2) { return p1 || p2; } template<typename P1, typename P2> bool equals(P1 p1, P2 p2) { return p1 == p2; } template<typename P1, typename P2> bool not_equals(P1 p1, P2 p2) { return p1 != p2; } template<typename P1, typename P2> bool less_than(P1 p1, P2 p2) { return p1 < p2; } template<typename P1, typename P2> bool greater_than(P1 p1, P2 p2) { return p1 > p2; } template<typename P1, typename P2> bool less_than_equals(P1 p1, P2 p2) { return p1 <= p2; } template<typename P1, typename P2> bool greater_than_equals(P1 p1, P2 p2) { return p1 >= p2; } template<typename P1, typename P2> P1 &timesequal(P1 &p1, P2 p2) { return (p1 *= p2); } template<typename Input> std::string to_string(Input i) { return boost::lexical_cast<std::string>(i); } void bootstrap(BoxedCPP_System &s) { s.register_type<void>("void"); s.register_type<double>("double"); s.register_type<int>("int"); s.register_type<char>("char"); s.register_type<bool>("bool"); s.register_type<std::string>("string"); s.register_function(boost::function<std::string (const std::string &, const std::string&)>(&add<std::string, const std::string &, const std::string &>), "+"); s.register_function(boost::function<int (int, int)>(&add<int, int, int>), "+"); s.register_function(boost::function<double (int, double)>(&add<double, int, double>), "+"); s.register_function(boost::function<double (double, int)>(&add<double, double, int>), "+"); s.register_function(boost::function<double (double, double)>(&add<double, double, double>), "+"); s.register_function(boost::function<int (int, int)>(&subtract<int, int, int>), "-"); s.register_function(boost::function<double (int, double)>(&subtract<double, int, double>), "-"); s.register_function(boost::function<double (double, int)>(&subtract<double, double, int>), "-"); s.register_function(boost::function<double (double, double)>(&subtract<double, double, double>), "-"); s.register_function(boost::function<int (int, int)>(&divide<int, int, int>), "/"); s.register_function(boost::function<double (int, double)>(&divide<double, int, double>), "/"); s.register_function(boost::function<double (double, int)>(&divide<double, double, int>), "/"); s.register_function(boost::function<double (double, double)>(&divide<double, double, double>), "/"); s.register_function(boost::function<bool (bool, bool)>(&bool_and<bool, bool>), "&&"); s.register_function(boost::function<bool (bool, bool)>(&bool_or<bool, bool>), "||"); s.register_function(boost::function<bool (const std::string &, const std::string &)>(&equals<const std::string &, const std::string &>), "=="); s.register_function(boost::function<bool (int, int)>(&equals<int, int>), "=="); s.register_function(boost::function<bool (int, double)>(&equals<int, double>), "=="); s.register_function(boost::function<bool (double, int)>(&equals<double, int>), "=="); s.register_function(boost::function<bool (double, double)>(&equals<double, double>), "=="); s.register_function(boost::function<bool (const std::string &, const std::string &)>(&not_equals<const std::string &, const std::string &>), "!="); s.register_function(boost::function<bool (int, int)>(&not_equals<int, int>), "!="); s.register_function(boost::function<bool (int, double)>(&not_equals<int, double>), "!="); s.register_function(boost::function<bool (double, int)>(&not_equals<double, int>), "!="); s.register_function(boost::function<bool (double, double)>(&not_equals<double, double>), "!="); s.register_function(boost::function<bool (int, int)>(&less_than<int, int>), "<"); s.register_function(boost::function<bool (int, double)>(&less_than<int, double>), "<"); s.register_function(boost::function<bool (double, int)>(&less_than<double, int>), "<"); s.register_function(boost::function<bool (double, double)>(&less_than<double, double>), "<"); s.register_function(boost::function<bool (int, int)>(&greater_than<int, int>), ">"); s.register_function(boost::function<bool (int, double)>(&greater_than<int, double>), ">"); s.register_function(boost::function<bool (double, int)>(&greater_than<double, int>), ">"); s.register_function(boost::function<bool (double, double)>(&greater_than<double, double>), ">"); s.register_function(boost::function<bool (int, int)>(&less_than_equals<int, int>), "<="); s.register_function(boost::function<bool (int, double)>(&less_than_equals<int, double>), "<="); s.register_function(boost::function<bool (double, int)>(&less_than_equals<double, int>), "<="); s.register_function(boost::function<bool (double, double)>(&less_than_equals<double, double>), "<="); s.register_function(boost::function<bool (int, int)>(&greater_than_equals<int, int>), ">="); s.register_function(boost::function<bool (int, double)>(&greater_than_equals<int, double>), ">="); s.register_function(boost::function<bool (double, int)>(&greater_than_equals<double, int>), ">="); s.register_function(boost::function<bool (double, double)>(&greater_than_equals<double, double>), ">="); s.register_function(boost::function<int (int, int)>(&multiply<int, int, int>), "*"); s.register_function(boost::function<double (int, double)>(&multiply<double, int, double>), "*"); s.register_function(boost::function<double (double, int)>(&multiply<double, double, int>), "*"); s.register_function(boost::function<double (double, double)>(&multiply<double, double, double>), "*"); s.register_function(boost::function<std::string (int)>(&to_string<int>), "to_string"); s.register_function(boost::function<std::string (const std::string &)>(&to_string<const std::string &>), "to_string"); s.register_function(boost::function<std::string (char)>(&to_string<char>), "to_string"); s.register_function(boost::function<std::string (double)>(&to_string<double>), "to_string"); s.register_function(boost::function<int &(int&, int)>(&timesequal<int, int>), "*="); s.register_function(boost::function<double &(double&, int)>(&timesequal<double, int>), "*="); s.register_function(boost::function<double &(double&, double)>(&timesequal<double, double>), "*="); s.register_function(boost::function<int &(int&, double)>(&timesequal<int, double>), "*="); } #endif <commit_msg>Fixed / operator<commit_after>#ifndef __bootstrap_hpp #define __bootstrap_hpp__ #include "boxedcpp.hpp" template<typename Ret, typename P1, typename P2> Ret add(P1 p1, P2 p2) { return p1 + p2; } template<typename Ret, typename P1, typename P2> Ret subtract(P1 p1, P2 p2) { return p1 - p2; } template<typename Ret, typename P1, typename P2> Ret divide(P1 p1, P2 p2) { return p1 / p2; } template<typename Ret, typename P1, typename P2> Ret multiply(P1 p1, P2 p2) { return p1 * p2; } template<typename P1, typename P2> bool bool_and(P1 p1, P2 p2) { return p1 && p2; } template<typename P1, typename P2> bool bool_or(P1 p1, P2 p2) { return p1 || p2; } template<typename P1, typename P2> bool equals(P1 p1, P2 p2) { return p1 == p2; } template<typename P1, typename P2> bool not_equals(P1 p1, P2 p2) { return p1 != p2; } template<typename P1, typename P2> bool less_than(P1 p1, P2 p2) { return p1 < p2; } template<typename P1, typename P2> bool greater_than(P1 p1, P2 p2) { return p1 > p2; } template<typename P1, typename P2> bool less_than_equals(P1 p1, P2 p2) { return p1 <= p2; } template<typename P1, typename P2> bool greater_than_equals(P1 p1, P2 p2) { return p1 >= p2; } template<typename P1, typename P2> P1 &timesequal(P1 &p1, P2 p2) { return (p1 *= p2); } template<typename Input> std::string to_string(Input i) { return boost::lexical_cast<std::string>(i); } void bootstrap(BoxedCPP_System &s) { s.register_type<void>("void"); s.register_type<double>("double"); s.register_type<int>("int"); s.register_type<char>("char"); s.register_type<bool>("bool"); s.register_type<std::string>("string"); s.register_function(boost::function<std::string (const std::string &, const std::string&)>(&add<std::string, const std::string &, const std::string &>), "+"); s.register_function(boost::function<int (int, int)>(&add<int, int, int>), "+"); s.register_function(boost::function<double (int, double)>(&add<double, int, double>), "+"); s.register_function(boost::function<double (double, int)>(&add<double, double, int>), "+"); s.register_function(boost::function<double (double, double)>(&add<double, double, double>), "+"); s.register_function(boost::function<int (int, int)>(&subtract<int, int, int>), "-"); s.register_function(boost::function<double (int, double)>(&subtract<double, int, double>), "-"); s.register_function(boost::function<double (double, int)>(&subtract<double, double, int>), "-"); s.register_function(boost::function<double (double, double)>(&subtract<double, double, double>), "-"); s.register_function(boost::function<int (int, int)>(&divide<int, int, int>), "/"); s.register_function(boost::function<double (int, double)>(&divide<double, int, double>), "/"); s.register_function(boost::function<double (double, int)>(&divide<double, double, int>), "/"); s.register_function(boost::function<double (double, double)>(&divide<double, double, double>), "/"); s.register_function(boost::function<bool (bool, bool)>(&bool_and<bool, bool>), "&&"); s.register_function(boost::function<bool (bool, bool)>(&bool_or<bool, bool>), "||"); s.register_function(boost::function<bool (const std::string &, const std::string &)>(&equals<const std::string &, const std::string &>), "=="); s.register_function(boost::function<bool (int, int)>(&equals<int, int>), "=="); s.register_function(boost::function<bool (int, double)>(&equals<int, double>), "=="); s.register_function(boost::function<bool (double, int)>(&equals<double, int>), "=="); s.register_function(boost::function<bool (double, double)>(&equals<double, double>), "=="); s.register_function(boost::function<bool (const std::string &, const std::string &)>(&not_equals<const std::string &, const std::string &>), "!="); s.register_function(boost::function<bool (int, int)>(&not_equals<int, int>), "!="); s.register_function(boost::function<bool (int, double)>(&not_equals<int, double>), "!="); s.register_function(boost::function<bool (double, int)>(&not_equals<double, int>), "!="); s.register_function(boost::function<bool (double, double)>(&not_equals<double, double>), "!="); s.register_function(boost::function<bool (int, int)>(&less_than<int, int>), "<"); s.register_function(boost::function<bool (int, double)>(&less_than<int, double>), "<"); s.register_function(boost::function<bool (double, int)>(&less_than<double, int>), "<"); s.register_function(boost::function<bool (double, double)>(&less_than<double, double>), "<"); s.register_function(boost::function<bool (int, int)>(&greater_than<int, int>), ">"); s.register_function(boost::function<bool (int, double)>(&greater_than<int, double>), ">"); s.register_function(boost::function<bool (double, int)>(&greater_than<double, int>), ">"); s.register_function(boost::function<bool (double, double)>(&greater_than<double, double>), ">"); s.register_function(boost::function<bool (int, int)>(&less_than_equals<int, int>), "<="); s.register_function(boost::function<bool (int, double)>(&less_than_equals<int, double>), "<="); s.register_function(boost::function<bool (double, int)>(&less_than_equals<double, int>), "<="); s.register_function(boost::function<bool (double, double)>(&less_than_equals<double, double>), "<="); s.register_function(boost::function<bool (int, int)>(&greater_than_equals<int, int>), ">="); s.register_function(boost::function<bool (int, double)>(&greater_than_equals<int, double>), ">="); s.register_function(boost::function<bool (double, int)>(&greater_than_equals<double, int>), ">="); s.register_function(boost::function<bool (double, double)>(&greater_than_equals<double, double>), ">="); s.register_function(boost::function<int (int, int)>(&multiply<int, int, int>), "*"); s.register_function(boost::function<double (int, double)>(&multiply<double, int, double>), "*"); s.register_function(boost::function<double (double, int)>(&multiply<double, double, int>), "*"); s.register_function(boost::function<double (double, double)>(&multiply<double, double, double>), "*"); s.register_function(boost::function<std::string (int)>(&to_string<int>), "to_string"); s.register_function(boost::function<std::string (const std::string &)>(&to_string<const std::string &>), "to_string"); s.register_function(boost::function<std::string (char)>(&to_string<char>), "to_string"); s.register_function(boost::function<std::string (double)>(&to_string<double>), "to_string"); s.register_function(boost::function<int &(int&, int)>(&timesequal<int, int>), "*="); s.register_function(boost::function<double &(double&, int)>(&timesequal<double, int>), "*="); s.register_function(boost::function<double &(double&, double)>(&timesequal<double, double>), "*="); s.register_function(boost::function<int &(int&, double)>(&timesequal<int, double>), "*="); } #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: XMLChangeTrackingImportHelper.hxx,v $ * * $Revision: 1.11 $ * * last change: $Author: obo $ $Date: 2004-06-04 11:08:18 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SC_XMLCHANGETRACKINGIMPORTHELPER_HXX #define _SC_XMLCHANGETRACKINGIMPORTHELPER_HXX #ifndef SC_CHGTRACK_HXX #include "chgtrack.hxx" #endif #ifndef __SGI_STL_LIST #include <list> #endif #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif #ifndef _COM_SUN_STAR_UTIL_DATETIME_HPP_ #include <com/sun/star/util/DateTime.hpp> #endif class ScBaseCell; class ScDocument; class DateTime; struct ScMyActionInfo { rtl::OUString sUser; rtl::OUString sComment; com::sun::star::util::DateTime aDateTime; }; struct ScMyCellInfo { ScBaseCell* pCell; rtl::OUString sFormulaAddress; rtl::OUString sFormula; String sInputString; double fValue; sal_Int32 nMatrixCols; sal_Int32 nMatrixRows; sal_uInt16 nType; sal_uInt8 nMatrixFlag; ScMyCellInfo(); ScMyCellInfo(ScBaseCell* pCell, const rtl::OUString& sFormulaAddress, const rtl::OUString& sFormula, const rtl::OUString& sInputString, const double& fValue, const sal_uInt16 nType, const sal_uInt8 nMatrixFlag, const sal_Int32 nMatrixCols, const sal_Int32 nMatrixRows); ~ScMyCellInfo(); ScBaseCell* CreateCell(ScDocument* pDoc); }; struct ScMyDeleted { sal_uInt32 nID; ScMyCellInfo* pCellInfo; ScMyDeleted(); ~ScMyDeleted(); }; typedef std::list<ScMyDeleted*> ScMyDeletedList; struct ScMyGenerated { ScBigRange aBigRange; sal_uInt32 nID; ScMyCellInfo* pCellInfo; ScMyGenerated(ScMyCellInfo* pCellInfo, const ScBigRange& aBigRange); ~ScMyGenerated(); }; typedef std::list<ScMyGenerated*> ScMyGeneratedList; struct ScMyInsertionCutOff { sal_uInt32 nID; sal_Int32 nPosition; ScMyInsertionCutOff(const sal_uInt32 nTempID, const sal_Int32 nTempPosition) : nID(nTempID), nPosition(nTempPosition) {} }; struct ScMyMoveCutOff { sal_uInt32 nID; sal_Int32 nStartPosition; sal_Int32 nEndPosition; ScMyMoveCutOff(const sal_uInt32 nTempID, const sal_Int32 nStartPos, const sal_Int32 nEndPos) : nID(nTempID), nStartPosition(nStartPos), nEndPosition(nEndPos) {} }; typedef std::list<ScMyMoveCutOff> ScMyMoveCutOffs; struct ScMyMoveRanges { ScBigRange aSourceRange; ScBigRange aTargetRange; ScMyMoveRanges(const ScBigRange& aSource, const ScBigRange aTarget) : aSourceRange(aSource), aTargetRange(aTarget) {} }; typedef std::list<sal_uInt32> ScMyDependences; struct ScMyBaseAction { ScMyActionInfo aInfo; ScBigRange aBigRange; ScMyDependences aDependences; ScMyDeletedList aDeletedList; sal_uInt32 nActionNumber; sal_uInt32 nRejectingNumber; sal_uInt32 nPreviousAction; ScChangeActionType nActionType; ScChangeActionState nActionState; ScMyBaseAction(const ScChangeActionType nActionType); ~ScMyBaseAction(); }; struct ScMyInsAction : public ScMyBaseAction { ScMyInsAction(const ScChangeActionType nActionType); ~ScMyInsAction(); }; struct ScMyDelAction : public ScMyBaseAction { ScMyGeneratedList aGeneratedList; ScMyInsertionCutOff* pInsCutOff; ScMyMoveCutOffs aMoveCutOffs; sal_Int32 nD; ScMyDelAction(const ScChangeActionType nActionType); ~ScMyDelAction(); }; struct ScMyMoveAction : public ScMyBaseAction { ScMyGeneratedList aGeneratedList; ScMyMoveRanges* pMoveRanges; ScMyMoveAction(); ~ScMyMoveAction(); }; struct ScMyContentAction : public ScMyBaseAction { ScMyCellInfo* pCellInfo; ScMyContentAction(); ~ScMyContentAction(); }; struct ScMyRejAction : public ScMyBaseAction { ScMyRejAction(); ~ScMyRejAction(); }; typedef std::list<ScMyBaseAction*> ScMyActions; class ScChangeViewSettings; class ScXMLChangeTrackingImportHelper { StrCollection aUsers; ScMyActions aActions; com::sun::star::uno::Sequence<sal_Int8> aProtect; ScDocument* pDoc; ScChangeTrack* pTrack; ScMyBaseAction* pCurrentAction; rtl::OUString sIDPrefix; sal_uInt32 nPrefixLength; sal_Int16 nMultiSpanned; sal_Int16 nMultiSpannedSlaveCount; sal_Bool bChangeTrack : 1; private: void ConvertInfo(const ScMyActionInfo& aInfo, String& rUser, DateTime& aDateTime); ScChangeAction* CreateInsertAction(ScMyInsAction* pAction); ScChangeAction* CreateDeleteAction(ScMyDelAction* pAction); ScChangeAction* CreateMoveAction(ScMyMoveAction* pAction); ScChangeAction* CreateRejectionAction(ScMyRejAction* pAction); ScChangeAction* CreateContentAction(ScMyContentAction* pAction); void CreateGeneratedActions(ScMyGeneratedList& rList); public: ScXMLChangeTrackingImportHelper(); ~ScXMLChangeTrackingImportHelper(); void SetChangeTrack(sal_Bool bValue) { bChangeTrack = bValue; } void SetProtection(const com::sun::star::uno::Sequence<sal_Int8>& rProtect) { aProtect = rProtect; } void StartChangeAction(const ScChangeActionType nActionType); sal_uInt32 GetIDFromString(const rtl::OUString& sID); void SetActionNumber(const sal_uInt32 nActionNumber) { pCurrentAction->nActionNumber = nActionNumber; } void SetActionState(const ScChangeActionState nActionState) { pCurrentAction->nActionState = nActionState; } void SetRejectingNumber(const sal_uInt32 nRejectingNumber) { pCurrentAction->nRejectingNumber = nRejectingNumber; } void SetActionInfo(const ScMyActionInfo& aInfo); void SetBigRange(const ScBigRange& aBigRange) { pCurrentAction->aBigRange = aBigRange; } void SetPreviousChange(const sal_uInt32 nPreviousAction, ScMyCellInfo* pCellInfo); void SetPosition(const sal_Int32 nPosition, const sal_Int32 nCount, const sal_Int32 nTable); void AddDependence(const sal_uInt32 nID) { pCurrentAction->aDependences.push_front(nID); } void AddDeleted(const sal_uInt32 nID); void AddDeleted(const sal_uInt32 nID, ScMyCellInfo* pCellInfo); void SetMultiSpanned(const sal_Int16 nMultiSpanned); void SetInsertionCutOff(const sal_uInt32 nID, const sal_Int32 nPosition); void AddMoveCutOff(const sal_uInt32 nID, const sal_Int32 nStartPosition, const sal_Int32 nEndPosition); void SetMoveRanges(const ScBigRange& aSourceRange, const ScBigRange& aTargetRange); void GetMultiSpannedRange(); void AddGenerated(ScMyCellInfo* pCellInfo, const ScBigRange& aBigRange); void EndChangeAction(); void SetDeletionDependences(ScMyDelAction* pAction, ScChangeActionDel* pDelAct); void SetMovementDependences(ScMyMoveAction* pAction, ScChangeActionMove* pMoveAct); void SetContentDependences(ScMyContentAction* pAction, ScChangeActionContent* pActContent); void SetDependences(ScMyBaseAction* pAction); void SetNewCell(ScMyContentAction* pAction); void CreateChangeTrack(ScDocument* pDoc); }; #endif <commit_msg>INTEGRATION: CWS oasis (1.11.16); FILE MERGED 2004/06/24 14:58:51 sab 1.11.16.1: #i20153#; oasis changes<commit_after>/************************************************************************* * * $RCSfile: XMLChangeTrackingImportHelper.hxx,v $ * * $Revision: 1.12 $ * * last change: $Author: rt $ $Date: 2004-07-13 07:45:57 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SC_XMLCHANGETRACKINGIMPORTHELPER_HXX #define _SC_XMLCHANGETRACKINGIMPORTHELPER_HXX #ifndef SC_CHGTRACK_HXX #include "chgtrack.hxx" #endif #ifndef __SGI_STL_LIST #include <list> #endif #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif #ifndef _COM_SUN_STAR_UTIL_DATETIME_HPP_ #include <com/sun/star/util/DateTime.hpp> #endif class ScBaseCell; class ScDocument; class DateTime; struct ScMyActionInfo { rtl::OUString sUser; rtl::OUString sComment; com::sun::star::util::DateTime aDateTime; }; struct ScMyCellInfo { ScBaseCell* pCell; rtl::OUString sFormulaAddress; rtl::OUString sFormula; String sInputString; double fValue; sal_Int32 nMatrixCols; sal_Int32 nMatrixRows; sal_uInt16 nType; sal_uInt8 nMatrixFlag; ScMyCellInfo(); ScMyCellInfo(ScBaseCell* pCell, const rtl::OUString& sFormulaAddress, const rtl::OUString& sFormula, const rtl::OUString& sInputString, const double& fValue, const sal_uInt16 nType, const sal_uInt8 nMatrixFlag, const sal_Int32 nMatrixCols, const sal_Int32 nMatrixRows); ~ScMyCellInfo(); ScBaseCell* CreateCell(ScDocument* pDoc); }; struct ScMyDeleted { sal_uInt32 nID; ScMyCellInfo* pCellInfo; ScMyDeleted(); ~ScMyDeleted(); }; typedef std::list<ScMyDeleted*> ScMyDeletedList; struct ScMyGenerated { ScBigRange aBigRange; sal_uInt32 nID; ScMyCellInfo* pCellInfo; ScMyGenerated(ScMyCellInfo* pCellInfo, const ScBigRange& aBigRange); ~ScMyGenerated(); }; typedef std::list<ScMyGenerated*> ScMyGeneratedList; struct ScMyInsertionCutOff { sal_uInt32 nID; sal_Int32 nPosition; ScMyInsertionCutOff(const sal_uInt32 nTempID, const sal_Int32 nTempPosition) : nID(nTempID), nPosition(nTempPosition) {} }; struct ScMyMoveCutOff { sal_uInt32 nID; sal_Int32 nStartPosition; sal_Int32 nEndPosition; ScMyMoveCutOff(const sal_uInt32 nTempID, const sal_Int32 nStartPos, const sal_Int32 nEndPos) : nID(nTempID), nStartPosition(nStartPos), nEndPosition(nEndPos) {} }; typedef std::list<ScMyMoveCutOff> ScMyMoveCutOffs; struct ScMyMoveRanges { ScBigRange aSourceRange; ScBigRange aTargetRange; ScMyMoveRanges(const ScBigRange& aSource, const ScBigRange aTarget) : aSourceRange(aSource), aTargetRange(aTarget) {} }; typedef std::list<sal_uInt32> ScMyDependencies; struct ScMyBaseAction { ScMyActionInfo aInfo; ScBigRange aBigRange; ScMyDependencies aDependencies; ScMyDeletedList aDeletedList; sal_uInt32 nActionNumber; sal_uInt32 nRejectingNumber; sal_uInt32 nPreviousAction; ScChangeActionType nActionType; ScChangeActionState nActionState; ScMyBaseAction(const ScChangeActionType nActionType); ~ScMyBaseAction(); }; struct ScMyInsAction : public ScMyBaseAction { ScMyInsAction(const ScChangeActionType nActionType); ~ScMyInsAction(); }; struct ScMyDelAction : public ScMyBaseAction { ScMyGeneratedList aGeneratedList; ScMyInsertionCutOff* pInsCutOff; ScMyMoveCutOffs aMoveCutOffs; sal_Int32 nD; ScMyDelAction(const ScChangeActionType nActionType); ~ScMyDelAction(); }; struct ScMyMoveAction : public ScMyBaseAction { ScMyGeneratedList aGeneratedList; ScMyMoveRanges* pMoveRanges; ScMyMoveAction(); ~ScMyMoveAction(); }; struct ScMyContentAction : public ScMyBaseAction { ScMyCellInfo* pCellInfo; ScMyContentAction(); ~ScMyContentAction(); }; struct ScMyRejAction : public ScMyBaseAction { ScMyRejAction(); ~ScMyRejAction(); }; typedef std::list<ScMyBaseAction*> ScMyActions; class ScChangeViewSettings; class ScXMLChangeTrackingImportHelper { StrCollection aUsers; ScMyActions aActions; com::sun::star::uno::Sequence<sal_Int8> aProtect; ScDocument* pDoc; ScChangeTrack* pTrack; ScMyBaseAction* pCurrentAction; rtl::OUString sIDPrefix; sal_uInt32 nPrefixLength; sal_Int16 nMultiSpanned; sal_Int16 nMultiSpannedSlaveCount; sal_Bool bChangeTrack : 1; private: void ConvertInfo(const ScMyActionInfo& aInfo, String& rUser, DateTime& aDateTime); ScChangeAction* CreateInsertAction(ScMyInsAction* pAction); ScChangeAction* CreateDeleteAction(ScMyDelAction* pAction); ScChangeAction* CreateMoveAction(ScMyMoveAction* pAction); ScChangeAction* CreateRejectionAction(ScMyRejAction* pAction); ScChangeAction* CreateContentAction(ScMyContentAction* pAction); void CreateGeneratedActions(ScMyGeneratedList& rList); public: ScXMLChangeTrackingImportHelper(); ~ScXMLChangeTrackingImportHelper(); void SetChangeTrack(sal_Bool bValue) { bChangeTrack = bValue; } void SetProtection(const com::sun::star::uno::Sequence<sal_Int8>& rProtect) { aProtect = rProtect; } void StartChangeAction(const ScChangeActionType nActionType); sal_uInt32 GetIDFromString(const rtl::OUString& sID); void SetActionNumber(const sal_uInt32 nActionNumber) { pCurrentAction->nActionNumber = nActionNumber; } void SetActionState(const ScChangeActionState nActionState) { pCurrentAction->nActionState = nActionState; } void SetRejectingNumber(const sal_uInt32 nRejectingNumber) { pCurrentAction->nRejectingNumber = nRejectingNumber; } void SetActionInfo(const ScMyActionInfo& aInfo); void SetBigRange(const ScBigRange& aBigRange) { pCurrentAction->aBigRange = aBigRange; } void SetPreviousChange(const sal_uInt32 nPreviousAction, ScMyCellInfo* pCellInfo); void SetPosition(const sal_Int32 nPosition, const sal_Int32 nCount, const sal_Int32 nTable); void AddDependence(const sal_uInt32 nID) { pCurrentAction->aDependencies.push_front(nID); } void AddDeleted(const sal_uInt32 nID); void AddDeleted(const sal_uInt32 nID, ScMyCellInfo* pCellInfo); void SetMultiSpanned(const sal_Int16 nMultiSpanned); void SetInsertionCutOff(const sal_uInt32 nID, const sal_Int32 nPosition); void AddMoveCutOff(const sal_uInt32 nID, const sal_Int32 nStartPosition, const sal_Int32 nEndPosition); void SetMoveRanges(const ScBigRange& aSourceRange, const ScBigRange& aTargetRange); void GetMultiSpannedRange(); void AddGenerated(ScMyCellInfo* pCellInfo, const ScBigRange& aBigRange); void EndChangeAction(); void SetDeletionDependencies(ScMyDelAction* pAction, ScChangeActionDel* pDelAct); void SetMovementDependencies(ScMyMoveAction* pAction, ScChangeActionMove* pMoveAct); void SetContentDependencies(ScMyContentAction* pAction, ScChangeActionContent* pActContent); void SetDependencies(ScMyBaseAction* pAction); void SetNewCell(ScMyContentAction* pAction); void CreateChangeTrack(ScDocument* pDoc); }; #endif <|endoftext|>
<commit_before>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions 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 the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_UDP_SOCKET_HPP_INCLUDED #define TORRENT_UDP_SOCKET_HPP_INCLUDED #include "libtorrent/socket.hpp" #include "libtorrent/session_settings.hpp" #include <vector> #include <boost/function.hpp> #include <boost/thread/mutex.hpp> namespace libtorrent { class connection_queue; class udp_socket { public: typedef boost::function<void(error_code const& ec , udp::endpoint const&, char const* buf, int size)> callback_t; udp_socket(io_service& ios, callback_t const& c, connection_queue& cc); bool is_open() const { return m_ipv4_sock.is_open() || m_ipv6_sock.is_open(); } io_service& get_io_service() { return m_ipv4_sock.get_io_service(); } void send(udp::endpoint const& ep, char const* p, int len, error_code& ec); void bind(udp::endpoint const& ep, error_code& ec); void bind(int port); void close(); int local_port() const { return m_bind_port; } void set_proxy_settings(proxy_settings const& ps); proxy_settings const& get_proxy_settings() { return m_proxy_settings; } #ifndef NDEBUG ~udp_socket() { m_magic = 0; } #endif private: callback_t m_callback; void on_read(udp::socket* sock, error_code const& e, std::size_t bytes_transferred); void on_name_lookup(error_code const& e, tcp::resolver::iterator i); void on_timeout(); void on_connect(int ticket); void on_connected(error_code const& ec); void handshake1(error_code const& e); void handshake2(error_code const& e); void handshake3(error_code const& e); void handshake4(error_code const& e); void socks_forward_udp(); void connect1(error_code const& e); void connect2(error_code const& e); void wrap(udp::endpoint const& ep, char const* p, int len, error_code& ec); void unwrap(error_code const& e, char const* buf, int size); typedef boost::mutex mutex_t; mutable mutex_t m_mutex; udp::socket m_ipv4_sock; udp::socket m_ipv6_sock; udp::endpoint m_v4_ep; udp::endpoint m_v6_ep; char m_v4_buf[1600]; char m_v6_buf[1600]; int m_bind_port; uint8_t m_outstanding; tcp::socket m_socks5_sock; int m_connection_ticket; proxy_settings m_proxy_settings; connection_queue& m_cc; tcp::resolver m_resolver; char m_tmp_buf[100]; bool m_tunnel_packets; udp::endpoint m_proxy_addr; #ifndef NDEBUG int m_magic; #endif }; } #endif <commit_msg>portability fix for udp_socket<commit_after>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions 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 the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_UDP_SOCKET_HPP_INCLUDED #define TORRENT_UDP_SOCKET_HPP_INCLUDED #include "libtorrent/socket.hpp" #include "libtorrent/session_settings.hpp" #include <vector> #include <boost/function.hpp> #include <boost/thread/mutex.hpp> namespace libtorrent { class connection_queue; class udp_socket { public: typedef boost::function<void(error_code const& ec , udp::endpoint const&, char const* buf, int size)> callback_t; udp_socket(io_service& ios, callback_t const& c, connection_queue& cc); bool is_open() const { return m_ipv4_sock.is_open() || m_ipv6_sock.is_open(); } io_service& get_io_service() { return m_ipv4_sock.get_io_service(); } void send(udp::endpoint const& ep, char const* p, int len, error_code& ec); void bind(udp::endpoint const& ep, error_code& ec); void bind(int port); void close(); int local_port() const { return m_bind_port; } void set_proxy_settings(proxy_settings const& ps); proxy_settings const& get_proxy_settings() { return m_proxy_settings; } #ifndef NDEBUG ~udp_socket() { m_magic = 0; } #endif private: callback_t m_callback; void on_read(udp::socket* sock, error_code const& e, std::size_t bytes_transferred); void on_name_lookup(error_code const& e, tcp::resolver::iterator i); void on_timeout(); void on_connect(int ticket); void on_connected(error_code const& ec); void handshake1(error_code const& e); void handshake2(error_code const& e); void handshake3(error_code const& e); void handshake4(error_code const& e); void socks_forward_udp(); void connect1(error_code const& e); void connect2(error_code const& e); void wrap(udp::endpoint const& ep, char const* p, int len, error_code& ec); void unwrap(error_code const& e, char const* buf, int size); typedef boost::mutex mutex_t; mutable mutex_t m_mutex; udp::socket m_ipv4_sock; udp::socket m_ipv6_sock; udp::endpoint m_v4_ep; udp::endpoint m_v6_ep; char m_v4_buf[1600]; char m_v6_buf[1600]; int m_bind_port; char m_outstanding; tcp::socket m_socks5_sock; int m_connection_ticket; proxy_settings m_proxy_settings; connection_queue& m_cc; tcp::resolver m_resolver; char m_tmp_buf[100]; bool m_tunnel_packets; udp::endpoint m_proxy_addr; #ifndef NDEBUG int m_magic; #endif }; } #endif <|endoftext|>
<commit_before>/* This file is part of Zanshin Todo. Copyright 2011 Christian Mollekopf <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "incidenceitem.h" #include <Akonadi/EntityDisplayAttribute> #include <kcalcore/event.h> #include <kcalcore/incidence.h> #include <kcalcore/journal.h> #include <kcalcore/todo.h> template<class T> T unwrap(const Akonadi::Item &item) { Q_ASSERT(item.hasPayload<T>()); return item.hasPayload<T>() ? item.payload<T>() : T(); } IncidenceItem::IncidenceItem(AbstractPimItem::ItemType type, QObject *parent) : AbstractPimItem(parent) { KCalCore::Incidence *newItem = 0; if (type == AbstractPimItem::Todo) { newItem = new KCalCore::Todo(); } else if (type == AbstractPimItem::Event) { newItem = new KCalCore::Event(); } Q_ASSERT(newItem); KCalCore::Incidence::Ptr newPtr(newItem); m_item.setPayload<KCalCore::Incidence::Ptr>(newPtr); m_item.setMimeType(mimeType()); commitData(); } IncidenceItem::IncidenceItem(const Akonadi::Item &item, QObject *parent) : AbstractPimItem(item, parent) { fetchData(); } IncidenceItem::IncidenceItem(AbstractPimItem::ItemType type, AbstractPimItem &item, QObject* parent) : AbstractPimItem(item, parent) { KCalCore::Incidence *newItem = 0; if (type == AbstractPimItem::Todo) { newItem = new KCalCore::Todo(); } else if (type == AbstractPimItem::Event) { newItem = new KCalCore::Event(); } Q_ASSERT(newItem); KCalCore::Incidence::Ptr newPtr(newItem); m_item.setPayload<KCalCore::Incidence::Ptr>(newPtr); m_item.setMimeType(mimeType()); commitData(); } void IncidenceItem::commitData() { KCalCore::Incidence::Ptr old = unwrap<KCalCore::Incidence::Ptr>(m_item); if (!old) { kDebug() << "invalid item, cannot commit data"; return; } old->setDescription(m_text, m_textIsRich); old->setSummary(m_title, m_titleIsRich); if (m_creationDate.isValid()) { old->setCreated(m_creationDate); } m_item.setPayload<KCalCore::Incidence::Ptr>(old); //TODO probably not required (shared ptr) m_item.setMimeType(mimeType()); //kDebug() << m_title; Akonadi::EntityDisplayAttribute *eda = new Akonadi::EntityDisplayAttribute(); eda->setIconName(getIconName()); eda->setDisplayName(m_title); m_item.addAttribute(eda); } bool IncidenceItem::hasValidPayload() { return m_item.hasPayload<KCalCore::Incidence::Ptr>(); } void IncidenceItem::fetchData() { if (m_dataFetched) { //kDebug() << "payload already fetched"; return; } if (!hasValidPayload()) { kDebug() << "invalid payload" << m_item.payloadData(); return; } KCalCore::Incidence::Ptr inc = m_item.payload<KCalCore::Incidence::Ptr>(); Q_ASSERT(inc); m_uid = inc->uid(); m_title = inc->summary(); m_titleIsRich = inc->summaryIsRich(); m_text = inc->description(); m_textIsRich = inc->descriptionIsRich(); m_creationDate = inc->created(); m_dataFetched = true; } QString IncidenceItem::mimeType() { const KCalCore::Incidence::Ptr old = unwrap<KCalCore::Incidence::Ptr>(m_item); //same as hasValidPayload + getting payload if (!old) { kWarning() << "invalid item"; return QString(); } return old->mimeType(); } bool IncidenceItem::hasStartDate() const { if (!m_item.hasPayload()) { kWarning() << "no payload"; } if ( const KCalCore::Event::Ptr t = unwrap<KCalCore::Event::Ptr>(m_item) ) { return t->dtStart().isValid(); } return false; } KDateTime IncidenceItem::getEventStart() { if (!m_item.hasPayload()) { kWarning() << "no payload"; // fetchPayload(true); } if ( const KCalCore::Event::Ptr t = unwrap<KCalCore::Event::Ptr>(m_item) ) { return t->dtStart(); } kWarning() << "not an event, or no start date"; return KDateTime(); } void IncidenceItem::setEventStart(const KDateTime &date) { if ( const KCalCore::Event::Ptr t = unwrap<KCalCore::Event::Ptr>(m_item) ) { t->setDtStart(date); } } void IncidenceItem::setParentTodo(const IncidenceItem &parent) { if ( const KCalCore::Todo::Ptr t = unwrap<KCalCore::Todo::Ptr>(m_item) ) { const KCalCore::Todo::Ptr p = unwrap<KCalCore::Todo::Ptr>(parent.getItem()); t->setRelatedTo(p->uid()); } } void IncidenceItem::setDueDate(const KDateTime &date, bool hasDueDate) { if ( const KCalCore::Todo::Ptr t = unwrap<KCalCore::Todo::Ptr>(m_item) ) { t->setDtDue(date); t->setHasDueDate(hasDueDate); } } KDateTime IncidenceItem::getDueDate() { if (!m_item.hasPayload()) { kWarning() << "no payload"; // fetchPayload(true); } if ( const KCalCore::Todo::Ptr t = unwrap<KCalCore::Todo::Ptr>(m_item) ) { if (t->hasDueDate()) { //kDebug() << "due date: " << t->dtDue(); return t->dtDue(); } } kWarning() << "not a todo, or no due date"; return KDateTime(); } bool IncidenceItem::hasDueDate() const { if (!m_item.hasPayload()) { kWarning() << "no payload"; } if ( const KCalCore::Todo::Ptr t = unwrap<KCalCore::Todo::Ptr>(m_item) ) { return t->hasDueDate(); } return false; } /* bool IncidenceItem::isComplete() { if (!m_item.hasPayload()) { kDebug() << "no payload"; // fetchPayload(true); } if ( const KCalCore::Todo::Ptr t = unwrap<KCalCore::Todo::Ptr>(m_item) ) { return t->isCompleted(); } kWarning() << "not a todo"; return false; } void IncidenceItem::setComplete(bool state) { if (!m_item.hasPayload()) { kDebug() << "no payload"; // fetchPayload(true); } if ( const KCalCore::Todo::Ptr t = unwrap<KCalCore::Todo::Ptr>(m_item) ) { return t->setCompleted(state); } kWarning() << "not a todo"; }*/ void IncidenceItem::setTodoStatus(AbstractPimItem::ItemStatus status) { if (!m_item.hasPayload()) { kDebug() << "no payload"; // fetchPayload(true); } //kDebug() << status; if ( const KCalCore::Todo::Ptr t = unwrap<KCalCore::Todo::Ptr>(m_item) ) { switch (status) { case NotComplete: t->setCompleted(false); break; case Complete: t->setCompleted(true); break; case Later: t->setCompleted(false); t->setHasStartDate(false); break; case Now: t->setCompleted(false); t->setDtStart(KDateTime::currentLocalDateTime()); break; default: kDebug() << "tried to set unhandled status: " << status; } return; } kWarning() << "not a todo"; } AbstractPimItem::ItemStatus IncidenceItem::getStatus() const { if (!m_item.hasPayload()) { kDebug() << "no payload"; // fetchPayload(true); } if ( const KCalCore::Todo::Ptr t = unwrap<KCalCore::Todo::Ptr>(m_item) ) { if (t->isCompleted()) { //kDebug() << "iscomplete"; return Complete; } if (t->hasStartDate() && (t->dtStart() <= KDateTime::currentLocalDateTime())) { //kDebug() << "Now"; return Now; } if (t->hasDueDate() && (t->dtDue() <= KDateTime::currentLocalDateTime())) { return Attention; } //kDebug() << "Later"; return Later; } if ( const KCalCore::Event::Ptr t = unwrap<KCalCore::Event::Ptr>(m_item) ) { if (!t->dtStart().isValid() || t->dtStart() > KDateTime::currentLocalDateTime()) { return Later; } if (t->dtEnd() > KDateTime::currentLocalDateTime()) { return Now; } return Complete; } kWarning() << "not a todo/event"; return Later; } KDateTime IncidenceItem::getPrimaryDate() { if (!m_item.hasPayload()) { kDebug() << "no payload"; // fetchPayload(true); } if ( const KCalCore::Todo::Ptr t = unwrap<KCalCore::Todo::Ptr>(m_item) ) { if (t->hasDueDate()) { //kDebug() << "due date: " << t->dtDue(); return t->dtDue(); } else { //kDebug() << "mod date: " << modificationTime(); return getLastModifiedDate(); } } else if ( const KCalCore::Event::Ptr e = unwrap<KCalCore::Event::Ptr>(m_item) ) { //if ( !e->recurs() && !e->isMultiDay() ) { return e->dtStart(); //} } else if ( const KCalCore::Journal::Ptr j = unwrap<KCalCore::Journal::Ptr>(m_item) ) { return j->dtStart(); } kWarning() << "unknown item"; return KDateTime(); } QString IncidenceItem::getIconName() { KCalCore::Incidence::Ptr old = unwrap<KCalCore::Incidence::Ptr>(m_item); if (!old) { kWarning() << "invalid item"; return QLatin1String( "network-wired" ); } if ( old->type() == KCalCore::IncidenceBase::TypeTodo ) { return QLatin1String( "view-pim-tasks" ); } else if ( old->type() == KCalCore::IncidenceBase::TypeJournal ) { return QLatin1String( "view-pim-journal" ); } else if ( old->type() == KCalCore::IncidenceBase::TypeEvent ) { return QLatin1String( "view-calendar" ); } kWarning() << "unknown item"; return QLatin1String( "network-wired" ); } AbstractPimItem::ItemType IncidenceItem::itemType() { KCalCore::Incidence::Ptr old = unwrap<KCalCore::Incidence::Ptr>(m_item); if (!old) { kWarning() << "invalid item"; return AbstractPimItem::Incidence; } if ( old->type() == KCalCore::IncidenceBase::TypeTodo ) { return AbstractPimItem::Todo; } else if ( old->type() == KCalCore::IncidenceBase::TypeJournal ) { return AbstractPimItem::Journal; } else if ( old->type() == KCalCore::IncidenceBase::TypeEvent ) { return AbstractPimItem::Event; } return AbstractPimItem::Incidence; } void IncidenceItem::setRelations(const QList< PimItemRelation > &relations) { KCalCore::Incidence::Ptr i = unwrap<KCalCore::Incidence::Ptr>(m_item); QMap<QByteArray, QString> map = i->customProperties(); map.remove("X-pimitemrelation"); i->removeNonKDECustomProperty("X-pimitemrelation"); foreach (const PimItemRelation &rel, relations) { if (rel.parentNodes.isEmpty()) { continue; } if (rel.type == PimItemRelation::Project) { i->setRelatedTo(rel.parentNodes.first().uid); } else { map.insertMulti("X-pimitemrelation", relationToXML(rel)); } } i->setCustomProperties(map); } QList< PimItemRelation > IncidenceItem::getRelations() { KCalCore::Incidence::Ptr i = unwrap<KCalCore::Incidence::Ptr>(m_item); QList<PimItemRelation> relations; if (!i->relatedTo().isEmpty()) { relations << PimItemRelation(PimItemRelation::Project, QList<PimItemTreeNode>() << PimItemTreeNode(i->relatedTo().toUtf8())); } foreach(const QByteArray &key, i->customProperties().keys()) { // kDebug() << key << i->customProperties().value(key); if (key != "X-pimitemrelation") { continue; } const PimItemRelation &rel = relationFromXML(i->customProperties().value(key).toLatin1()); relations << rel; } return relations; } void IncidenceItem::setCategories(const QStringList &categories) { KCalCore::Incidence::Ptr i = unwrap<KCalCore::Incidence::Ptr>(m_item); i->setCategories(categories); } QStringList IncidenceItem::getCategories() { KCalCore::Incidence::Ptr i = unwrap<KCalCore::Incidence::Ptr>(m_item); return i->categories(); } void IncidenceItem::setProject() { if (isProject()) { return; } KCalCore::Incidence::Ptr i = unwrap<KCalCore::Incidence::Ptr>(m_item); return i->addComment("X-Zanshin-Project"); } bool IncidenceItem::isProject() const { KCalCore::Incidence::Ptr i = unwrap<KCalCore::Incidence::Ptr>(m_item); return i->comments().contains("X-Zanshin-Project"); } <commit_msg>Use a special property to set the project status and don't hijack the comment property.<commit_after>/* This file is part of Zanshin Todo. Copyright 2011 Christian Mollekopf <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "incidenceitem.h" #include <Akonadi/EntityDisplayAttribute> #include <kcalcore/event.h> #include <kcalcore/incidence.h> #include <kcalcore/journal.h> #include <kcalcore/todo.h> template<class T> T unwrap(const Akonadi::Item &item) { Q_ASSERT(item.hasPayload<T>()); return item.hasPayload<T>() ? item.payload<T>() : T(); } IncidenceItem::IncidenceItem(AbstractPimItem::ItemType type, QObject *parent) : AbstractPimItem(parent) { KCalCore::Incidence *newItem = 0; if (type == AbstractPimItem::Todo) { newItem = new KCalCore::Todo(); } else if (type == AbstractPimItem::Event) { newItem = new KCalCore::Event(); } Q_ASSERT(newItem); KCalCore::Incidence::Ptr newPtr(newItem); m_item.setPayload<KCalCore::Incidence::Ptr>(newPtr); m_item.setMimeType(mimeType()); commitData(); } IncidenceItem::IncidenceItem(const Akonadi::Item &item, QObject *parent) : AbstractPimItem(item, parent) { fetchData(); } IncidenceItem::IncidenceItem(AbstractPimItem::ItemType type, AbstractPimItem &item, QObject* parent) : AbstractPimItem(item, parent) { KCalCore::Incidence *newItem = 0; if (type == AbstractPimItem::Todo) { newItem = new KCalCore::Todo(); } else if (type == AbstractPimItem::Event) { newItem = new KCalCore::Event(); } Q_ASSERT(newItem); KCalCore::Incidence::Ptr newPtr(newItem); m_item.setPayload<KCalCore::Incidence::Ptr>(newPtr); m_item.setMimeType(mimeType()); commitData(); } void IncidenceItem::commitData() { KCalCore::Incidence::Ptr old = unwrap<KCalCore::Incidence::Ptr>(m_item); if (!old) { kDebug() << "invalid item, cannot commit data"; return; } old->setDescription(m_text, m_textIsRich); old->setSummary(m_title, m_titleIsRich); if (m_creationDate.isValid()) { old->setCreated(m_creationDate); } m_item.setPayload<KCalCore::Incidence::Ptr>(old); //TODO probably not required (shared ptr) m_item.setMimeType(mimeType()); //kDebug() << m_title; Akonadi::EntityDisplayAttribute *eda = new Akonadi::EntityDisplayAttribute(); eda->setIconName(getIconName()); eda->setDisplayName(m_title); m_item.addAttribute(eda); } bool IncidenceItem::hasValidPayload() { return m_item.hasPayload<KCalCore::Incidence::Ptr>(); } void IncidenceItem::fetchData() { if (m_dataFetched) { //kDebug() << "payload already fetched"; return; } if (!hasValidPayload()) { kDebug() << "invalid payload" << m_item.payloadData(); return; } KCalCore::Incidence::Ptr inc = m_item.payload<KCalCore::Incidence::Ptr>(); Q_ASSERT(inc); m_uid = inc->uid(); m_title = inc->summary(); m_titleIsRich = inc->summaryIsRich(); m_text = inc->description(); m_textIsRich = inc->descriptionIsRich(); m_creationDate = inc->created(); m_dataFetched = true; } QString IncidenceItem::mimeType() { const KCalCore::Incidence::Ptr old = unwrap<KCalCore::Incidence::Ptr>(m_item); //same as hasValidPayload + getting payload if (!old) { kWarning() << "invalid item"; return QString(); } return old->mimeType(); } bool IncidenceItem::hasStartDate() const { if (!m_item.hasPayload()) { kWarning() << "no payload"; } if ( const KCalCore::Event::Ptr t = unwrap<KCalCore::Event::Ptr>(m_item) ) { return t->dtStart().isValid(); } return false; } KDateTime IncidenceItem::getEventStart() { if (!m_item.hasPayload()) { kWarning() << "no payload"; // fetchPayload(true); } if ( const KCalCore::Event::Ptr t = unwrap<KCalCore::Event::Ptr>(m_item) ) { return t->dtStart(); } kWarning() << "not an event, or no start date"; return KDateTime(); } void IncidenceItem::setEventStart(const KDateTime &date) { if ( const KCalCore::Event::Ptr t = unwrap<KCalCore::Event::Ptr>(m_item) ) { t->setDtStart(date); } } void IncidenceItem::setParentTodo(const IncidenceItem &parent) { if ( const KCalCore::Todo::Ptr t = unwrap<KCalCore::Todo::Ptr>(m_item) ) { const KCalCore::Todo::Ptr p = unwrap<KCalCore::Todo::Ptr>(parent.getItem()); t->setRelatedTo(p->uid()); } } void IncidenceItem::setDueDate(const KDateTime &date, bool hasDueDate) { if ( const KCalCore::Todo::Ptr t = unwrap<KCalCore::Todo::Ptr>(m_item) ) { t->setDtDue(date); t->setHasDueDate(hasDueDate); } } KDateTime IncidenceItem::getDueDate() { if (!m_item.hasPayload()) { kWarning() << "no payload"; // fetchPayload(true); } if ( const KCalCore::Todo::Ptr t = unwrap<KCalCore::Todo::Ptr>(m_item) ) { if (t->hasDueDate()) { //kDebug() << "due date: " << t->dtDue(); return t->dtDue(); } } kWarning() << "not a todo, or no due date"; return KDateTime(); } bool IncidenceItem::hasDueDate() const { if (!m_item.hasPayload()) { kWarning() << "no payload"; } if ( const KCalCore::Todo::Ptr t = unwrap<KCalCore::Todo::Ptr>(m_item) ) { return t->hasDueDate(); } return false; } /* bool IncidenceItem::isComplete() { if (!m_item.hasPayload()) { kDebug() << "no payload"; // fetchPayload(true); } if ( const KCalCore::Todo::Ptr t = unwrap<KCalCore::Todo::Ptr>(m_item) ) { return t->isCompleted(); } kWarning() << "not a todo"; return false; } void IncidenceItem::setComplete(bool state) { if (!m_item.hasPayload()) { kDebug() << "no payload"; // fetchPayload(true); } if ( const KCalCore::Todo::Ptr t = unwrap<KCalCore::Todo::Ptr>(m_item) ) { return t->setCompleted(state); } kWarning() << "not a todo"; }*/ void IncidenceItem::setTodoStatus(AbstractPimItem::ItemStatus status) { if (!m_item.hasPayload()) { kDebug() << "no payload"; // fetchPayload(true); } //kDebug() << status; if ( const KCalCore::Todo::Ptr t = unwrap<KCalCore::Todo::Ptr>(m_item) ) { switch (status) { case NotComplete: t->setCompleted(false); break; case Complete: t->setCompleted(true); break; case Later: t->setCompleted(false); t->setHasStartDate(false); break; case Now: t->setCompleted(false); t->setDtStart(KDateTime::currentLocalDateTime()); break; default: kDebug() << "tried to set unhandled status: " << status; } return; } kWarning() << "not a todo"; } AbstractPimItem::ItemStatus IncidenceItem::getStatus() const { if (!m_item.hasPayload()) { kDebug() << "no payload"; // fetchPayload(true); } if ( const KCalCore::Todo::Ptr t = unwrap<KCalCore::Todo::Ptr>(m_item) ) { if (t->isCompleted()) { //kDebug() << "iscomplete"; return Complete; } if (t->hasStartDate() && (t->dtStart() <= KDateTime::currentLocalDateTime())) { //kDebug() << "Now"; return Now; } if (t->hasDueDate() && (t->dtDue() <= KDateTime::currentLocalDateTime())) { return Attention; } //kDebug() << "Later"; return Later; } if ( const KCalCore::Event::Ptr t = unwrap<KCalCore::Event::Ptr>(m_item) ) { if (!t->dtStart().isValid() || t->dtStart() > KDateTime::currentLocalDateTime()) { return Later; } if (t->dtEnd() > KDateTime::currentLocalDateTime()) { return Now; } return Complete; } kWarning() << "not a todo/event"; return Later; } KDateTime IncidenceItem::getPrimaryDate() { if (!m_item.hasPayload()) { kDebug() << "no payload"; // fetchPayload(true); } if ( const KCalCore::Todo::Ptr t = unwrap<KCalCore::Todo::Ptr>(m_item) ) { if (t->hasDueDate()) { //kDebug() << "due date: " << t->dtDue(); return t->dtDue(); } else { //kDebug() << "mod date: " << modificationTime(); return getLastModifiedDate(); } } else if ( const KCalCore::Event::Ptr e = unwrap<KCalCore::Event::Ptr>(m_item) ) { //if ( !e->recurs() && !e->isMultiDay() ) { return e->dtStart(); //} } else if ( const KCalCore::Journal::Ptr j = unwrap<KCalCore::Journal::Ptr>(m_item) ) { return j->dtStart(); } kWarning() << "unknown item"; return KDateTime(); } QString IncidenceItem::getIconName() { KCalCore::Incidence::Ptr old = unwrap<KCalCore::Incidence::Ptr>(m_item); if (!old) { kWarning() << "invalid item"; return QLatin1String( "network-wired" ); } if ( old->type() == KCalCore::IncidenceBase::TypeTodo ) { return QLatin1String( "view-pim-tasks" ); } else if ( old->type() == KCalCore::IncidenceBase::TypeJournal ) { return QLatin1String( "view-pim-journal" ); } else if ( old->type() == KCalCore::IncidenceBase::TypeEvent ) { return QLatin1String( "view-calendar" ); } kWarning() << "unknown item"; return QLatin1String( "network-wired" ); } AbstractPimItem::ItemType IncidenceItem::itemType() { KCalCore::Incidence::Ptr old = unwrap<KCalCore::Incidence::Ptr>(m_item); if (!old) { kWarning() << "invalid item"; return AbstractPimItem::Incidence; } if ( old->type() == KCalCore::IncidenceBase::TypeTodo ) { return AbstractPimItem::Todo; } else if ( old->type() == KCalCore::IncidenceBase::TypeJournal ) { return AbstractPimItem::Journal; } else if ( old->type() == KCalCore::IncidenceBase::TypeEvent ) { return AbstractPimItem::Event; } return AbstractPimItem::Incidence; } void IncidenceItem::setRelations(const QList< PimItemRelation > &relations) { KCalCore::Incidence::Ptr i = unwrap<KCalCore::Incidence::Ptr>(m_item); QMap<QByteArray, QString> map = i->customProperties(); map.remove("X-pimitemrelation"); i->removeNonKDECustomProperty("X-pimitemrelation"); foreach (const PimItemRelation &rel, relations) { if (rel.parentNodes.isEmpty()) { continue; } if (rel.type == PimItemRelation::Project) { i->setRelatedTo(rel.parentNodes.first().uid); } else { map.insertMulti("X-pimitemrelation", relationToXML(rel)); } } i->setCustomProperties(map); } QList< PimItemRelation > IncidenceItem::getRelations() { KCalCore::Incidence::Ptr i = unwrap<KCalCore::Incidence::Ptr>(m_item); QList<PimItemRelation> relations; if (!i->relatedTo().isEmpty()) { relations << PimItemRelation(PimItemRelation::Project, QList<PimItemTreeNode>() << PimItemTreeNode(i->relatedTo().toUtf8())); } foreach(const QByteArray &key, i->customProperties().keys()) { // kDebug() << key << i->customProperties().value(key); if (key != "X-pimitemrelation") { continue; } const PimItemRelation &rel = relationFromXML(i->customProperties().value(key).toLatin1()); relations << rel; } return relations; } void IncidenceItem::setCategories(const QStringList &categories) { KCalCore::Incidence::Ptr i = unwrap<KCalCore::Incidence::Ptr>(m_item); i->setCategories(categories); } QStringList IncidenceItem::getCategories() { KCalCore::Incidence::Ptr i = unwrap<KCalCore::Incidence::Ptr>(m_item); return i->categories(); } void IncidenceItem::setProject() { if (isProject()) { return; } KCalCore::Incidence::Ptr i = unwrap<KCalCore::Incidence::Ptr>(m_item); i->setCustomProperty("Zanshin", "Project", "true"); } bool IncidenceItem::isProject() const { KCalCore::Incidence::Ptr i = unwrap<KCalCore::Incidence::Ptr>(m_item); if (i->comments().contains("X-Zanshin-Project")) { return true; } return !i->customProperty("Zanshin", "Project").isEmpty(); } <|endoftext|>
<commit_before>/* * ----------------------------------------------------------------------------- * This source file is part of OGRE * (Object-oriented Graphics Rendering Engine) * For the latest info, see http://www.ogre3d.org/ * * Copyright (c) 2000-2013 Torus Knot Software Ltd * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * ----------------------------------------------------------------------------- */ #include "OgreLodInputProvider.h" #include "OgreLodData.h" #include "OgreLogManager.h" namespace Ogre { void LodInputProvider::printTriangle(LodData::Triangle* triangle, stringstream& str) { for (int i = 0; i < 3; i++) { str << (i + 1) << ". vertex position: (" << triangle->vertex[i]->position.x << ", " << triangle->vertex[i]->position.y << ", " << triangle->vertex[i]->position.z << ") " << "vertex ID: " << triangle->vertexID[i] << std::endl; } } bool LodInputProvider::isDuplicateTriangle(LodData::Triangle* triangle, LodData::Triangle* triangle2) { for (int i = 0; i < 3; i++) { if (triangle->vertex[i] != triangle2->vertex[0] || triangle->vertex[i] != triangle2->vertex[1] || triangle->vertex[i] != triangle2->vertex[2]) { return false; } } return true; } LodData::Triangle* LodInputProvider::isDuplicateTriangle(LodData::Triangle* triangle) { // duplicate triangle detection (where all vertices has the same position) LodData::VTriangles::iterator itEnd = triangle->vertex[0]->triangles.end(); LodData::VTriangles::iterator it = triangle->vertex[0]->triangles.begin(); for (; it != itEnd; it++) { LodData::Triangle* t = *it; if (isDuplicateTriangle(triangle, t)) { return *it; } } return NULL; } void LodInputProvider::addTriangleToEdges(LodData* data, LodData::Triangle* triangle) { if(MESHLOD_QUALITY >= 3) { LodData::Triangle* duplicate = isDuplicateTriangle(triangle); if (duplicate != NULL) { #if OGRE_DEBUG_MODE stringstream str; str << "In " << data->mMeshName << " duplicate triangle found." << std::endl; str << "Triangle " << LodData::getVectorIDFromPointer(data->mTriangleList, triangle) << " positions:" << std::endl; printTriangle(triangle, str); str << "Triangle " << LodData::getVectorIDFromPointer(data->mTriangleList, duplicate) << " positions:" << std::endl; printTriangle(duplicate, str); str << "Triangle " << LodData::getVectorIDFromPointer(data->mTriangleList, triangle) << " will be excluded from Lod level calculations."; LogManager::getSingleton().stream() << str; #endif triangle->isRemoved = true; data->mIndexBufferInfoList[triangle->submeshID].indexCount -= 3; return; } } for (int i = 0; i < 3; i++) { triangle->vertex[i]->triangles.addNotExists(triangle); } for (int i = 0; i < 3; i++) { for (int n = 0; n < 3; n++) { if (i != n) { triangle->vertex[i]->addEdge(LodData::Edge(triangle->vertex[n])); } } } } }<commit_msg>Add as string to LogManager.<commit_after>/* * ----------------------------------------------------------------------------- * This source file is part of OGRE * (Object-oriented Graphics Rendering Engine) * For the latest info, see http://www.ogre3d.org/ * * Copyright (c) 2000-2013 Torus Knot Software Ltd * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * ----------------------------------------------------------------------------- */ #include "OgreLodInputProvider.h" #include "OgreLodData.h" #include "OgreLogManager.h" namespace Ogre { void LodInputProvider::printTriangle(LodData::Triangle* triangle, stringstream& str) { for (int i = 0; i < 3; i++) { str << (i + 1) << ". vertex position: (" << triangle->vertex[i]->position.x << ", " << triangle->vertex[i]->position.y << ", " << triangle->vertex[i]->position.z << ") " << "vertex ID: " << triangle->vertexID[i] << std::endl; } } bool LodInputProvider::isDuplicateTriangle(LodData::Triangle* triangle, LodData::Triangle* triangle2) { for (int i = 0; i < 3; i++) { if (triangle->vertex[i] != triangle2->vertex[0] || triangle->vertex[i] != triangle2->vertex[1] || triangle->vertex[i] != triangle2->vertex[2]) { return false; } } return true; } LodData::Triangle* LodInputProvider::isDuplicateTriangle(LodData::Triangle* triangle) { // duplicate triangle detection (where all vertices has the same position) LodData::VTriangles::iterator itEnd = triangle->vertex[0]->triangles.end(); LodData::VTriangles::iterator it = triangle->vertex[0]->triangles.begin(); for (; it != itEnd; it++) { LodData::Triangle* t = *it; if (isDuplicateTriangle(triangle, t)) { return *it; } } return NULL; } void LodInputProvider::addTriangleToEdges(LodData* data, LodData::Triangle* triangle) { if(MESHLOD_QUALITY >= 3) { LodData::Triangle* duplicate = isDuplicateTriangle(triangle); if (duplicate != NULL) { #if OGRE_DEBUG_MODE stringstream str; str << "In " << data->mMeshName << " duplicate triangle found." << std::endl; str << "Triangle " << LodData::getVectorIDFromPointer(data->mTriangleList, triangle) << " positions:" << std::endl; printTriangle(triangle, str); str << "Triangle " << LodData::getVectorIDFromPointer(data->mTriangleList, duplicate) << " positions:" << std::endl; printTriangle(duplicate, str); str << "Triangle " << LodData::getVectorIDFromPointer(data->mTriangleList, triangle) << " will be excluded from Lod level calculations."; LogManager::getSingleton().stream() << str.str(); #endif triangle->isRemoved = true; data->mIndexBufferInfoList[triangle->submeshID].indexCount -= 3; return; } } for (int i = 0; i < 3; i++) { triangle->vertex[i]->triangles.addNotExists(triangle); } for (int i = 0; i < 3; i++) { for (int n = 0; n < 3; n++) { if (i != n) { triangle->vertex[i]->addEdge(LodData::Edge(triangle->vertex[n])); } } } } }<|endoftext|>
<commit_before>/* Copyright (c) 2009, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions 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 the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_UTP_STREAM_HPP_INCLUDED #define TORRENT_UTP_STREAM_HPP_INCLUDED #include "libtorrent/connection_queue.hpp" #include "libtorrent/proxy_base.hpp" #include "libtorrent/udp_socket.hpp" #include "libtorrent/io.hpp" #include "libtorrent/packet_buffer.hpp" #include "libtorrent/error_code.hpp" #include <boost/bind.hpp> #include <boost/function/function1.hpp> #include <boost/function/function2.hpp> #define CCONTROL_TARGET 100 namespace libtorrent { struct utp_socket_manager; // the point of the bif_endian_int is two-fold // one purpuse is to not have any alignment requirements // so that any byffer received from the network can be cast // to it and read as an integer of various sizes without // triggering a bus error. The other purpose is to convert // from network byte order to host byte order when read and // written, to offer a convenient interface to both interpreting // and writing network packets template <class T> struct big_endian_int { big_endian_int& operator=(T v) { char* p = m_storage; detail::write_impl(v, p); return *this; } operator T() const { const char* p = m_storage; return detail::read_impl(p, detail::type<T>()); } private: char m_storage[sizeof(T)]; }; typedef big_endian_int<boost::uint64_t> be_uint64; typedef big_endian_int<boost::uint32_t> be_uint32; typedef big_endian_int<boost::uint16_t> be_uint16; typedef big_endian_int<boost::int64_t> be_int64; typedef big_endian_int<boost::int32_t> be_int32; typedef big_endian_int<boost::int16_t> be_int16; /* uTP header from BEP 29 0 4 8 16 24 32 +-------+-------+---------------+---------------+---------------+ | ver | type | extension | connection_id | +-------+-------+---------------+---------------+---------------+ | timestamp_microseconds | +---------------+---------------+---------------+---------------+ | timestamp_difference_microseconds | +---------------+---------------+---------------+---------------+ | wnd_size | +---------------+---------------+---------------+---------------+ | seq_nr | ack_nr | +---------------+---------------+---------------+---------------+ */ enum type { ST_DATA = 0, ST_FIN, ST_STATE, ST_RESET, ST_SYN, NUM_TYPES }; struct utp_header { unsigned char ver:4; unsigned char type:4; unsigned char extension; be_uint16 connection_id; be_uint32 timestamp_microseconds; be_uint32 timestamp_difference_microseconds; be_uint32 wnd_size; be_uint16 seq_nr; be_uint16 ack_nr; }; struct utp_socket_impl; utp_socket_impl* construct_utp_impl(boost::uint16_t recv_id , boost::uint16_t send_id, void* userdata , utp_socket_manager* sm); void detach_utp_impl(utp_socket_impl* s); void delete_utp_impl(utp_socket_impl* s); bool should_delete(utp_socket_impl* s); void tick_utp_impl(utp_socket_impl* s, ptime const& now); bool utp_incoming_packet(utp_socket_impl* s, char const* p , int size, udp::endpoint const& ep, ptime receive_time); bool utp_match(utp_socket_impl* s, udp::endpoint const& ep, boost::uint16_t id); udp::endpoint utp_remote_endpoint(utp_socket_impl* s); boost::uint16_t utp_receive_id(utp_socket_impl* s); int utp_socket_state(utp_socket_impl const* s); #if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING int socket_impl_size(); #endif // this is the user-level stream interface to utp sockets. // the reason why it's split up in a utp_stream class and // an implementation class is because the socket state has // to be able to out-live the user level socket. For instance // when sending data on a stream and then closing it, the // state holding the send buffer has to be kept around until // it has been flushed, which may be longer than the client // will keep the utp_stream object around for. // for more details, see utp_socket_impl, which is analogous // to the kernel state for a socket. It's defined in utp_stream.cpp class utp_stream { public: typedef stream_socket::endpoint_type endpoint_type; typedef stream_socket::protocol_type protocol_type; explicit utp_stream(asio::io_service& io_service); ~utp_stream(); // used for incoming connections void set_impl(utp_socket_impl* s); utp_socket_impl* get_impl(); #ifndef BOOST_NO_EXCEPTIONS template <class IO_Control_Command> void io_control(IO_Control_Command& ioc) {} #endif template <class IO_Control_Command> void io_control(IO_Control_Command& ioc, error_code& ec) {} #ifndef BOOST_NO_EXCEPTIONS void bind(endpoint_type const& endpoint) {} #endif void bind(endpoint_type const& endpoint, error_code& ec); #ifndef BOOST_NO_EXCEPTIONS template <class SettableSocketOption> void set_option(SettableSocketOption const& opt) {} #endif template <class SettableSocketOption> error_code set_option(SettableSocketOption const& opt, error_code& ec) { return ec; } void close(); void close(error_code const& ec) { close(); } bool is_open() const { return m_open; } int read_buffer_size() const; static void on_read(void* self, size_t bytes_transferred, error_code const& ec, bool kill); static void on_write(void* self, size_t bytes_transferred, error_code const& ec, bool kill); static void on_connect(void* self, error_code const& ec, bool kill); typedef void(*handler_t)(void*, size_t, error_code const&, bool); typedef void(*connect_handler_t)(void*, error_code const&, bool); void add_read_buffer(void* buf, size_t len); void set_read_handler(handler_t h); void add_write_buffer(void const* buf, size_t len); void set_write_handler(handler_t h); size_t read_some(bool clear_buffers); void do_connect(tcp::endpoint const& ep, connect_handler_t h); endpoint_type local_endpoint() const { error_code ec; return local_endpoint(ec); } endpoint_type local_endpoint(error_code& ec) const; endpoint_type remote_endpoint() const { error_code ec; return remote_endpoint(ec); } endpoint_type remote_endpoint(error_code& ec) const; std::size_t available() const; std::size_t available(error_code& ec) const { return available(); } asio::io_service& io_service() { return m_io_service; } template <class Handler> void async_connect(endpoint_type const& endpoint, Handler const& handler) { if (!endpoint.address().is_v4()) { error_code ec = asio::error::operation_not_supported; m_io_service.post(boost::bind<void>(handler, asio::error::operation_not_supported, 0)); return; } if (m_impl == 0) { m_io_service.post(boost::bind<void>(handler, asio::error::not_connected, 0)); return; } m_connect_handler = handler; do_connect(endpoint, &utp_stream::on_connect); } template <class Mutable_Buffers, class Handler> void async_read_some(Mutable_Buffers const& buffers, Handler const& handler) { if (m_impl == 0) { m_io_service.post(boost::bind<void>(handler, asio::error::not_connected, 0)); return; } TORRENT_ASSERT(!m_read_handler); if (m_read_handler) { m_io_service.post(boost::bind<void>(handler, asio::error::operation_not_supported, 0)); return; } for (typename Mutable_Buffers::const_iterator i = buffers.begin() , end(buffers.end()); i != end; ++i) { using asio::buffer_cast; using asio::buffer_size; add_read_buffer(buffer_cast<void*>(*i), buffer_size(*i)); } m_read_handler = handler; set_read_handler(&utp_stream::on_read); } void do_async_connect(endpoint_type const& ep , boost::function<void(error_code const&)> const& handler); template <class Protocol> void open(Protocol const& p, error_code& ec) { m_open = true; } template <class Protocol> void open(Protocol const& p) { m_open = true; } template <class Mutable_Buffers> std::size_t read_some(Mutable_Buffers const& buffers, error_code& ec) { TORRENT_ASSERT(!m_read_handler); if (m_impl == 0) { ec = asio::error::not_connected; return 0; } if (read_buffer_size() == 0) { ec = asio::error::would_block; return 0; } #ifndef NDEBUG int buf_size = 0; #endif for (typename Mutable_Buffers::const_iterator i = buffers.begin() , end(buffers.end()); i != end; ++i) { using asio::buffer_cast; using asio::buffer_size; add_read_buffer(buffer_cast<void*>(*i), buffer_size(*i)); #ifndef NDEBUG buf_size += buffer_size(*i); #endif } std::size_t ret = read_some(true); TORRENT_ASSERT(ret <= buf_size); return ret; } template <class Const_Buffers> std::size_t write_some(Const_Buffers const& buffers, error_code& ec) { // TODO: implement return 0; } template <class Const_Buffers, class Handler> void async_write_some(Const_Buffers const& buffers, Handler const& handler) { if (m_impl == 0) { m_io_service.post(boost::bind<void>(handler, asio::error::not_connected, 0)); return; } TORRENT_ASSERT(!m_write_handler); if (m_write_handler) { m_io_service.post(boost::bind<void>(handler, asio::error::operation_not_supported, 0)); return; } for (typename Const_Buffers::const_iterator i = buffers.begin() , end(buffers.end()); i != end; ++i) { using asio::buffer_cast; using asio::buffer_size; add_write_buffer((void*)buffer_cast<void const*>(*i), buffer_size(*i)); } m_write_handler = handler; set_write_handler(&utp_stream::on_write); } //private: void cancel_handlers(error_code const&); boost::function1<void, error_code const&> m_connect_handler; boost::function2<void, error_code const&, std::size_t> m_read_handler; boost::function2<void, error_code const&, std::size_t> m_write_handler; asio::io_service& m_io_service; utp_socket_impl* m_impl; bool m_open; }; } #endif <commit_msg>fixed minor utp typo<commit_after>/* Copyright (c) 2009, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions 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 the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_UTP_STREAM_HPP_INCLUDED #define TORRENT_UTP_STREAM_HPP_INCLUDED #include "libtorrent/connection_queue.hpp" #include "libtorrent/proxy_base.hpp" #include "libtorrent/udp_socket.hpp" #include "libtorrent/io.hpp" #include "libtorrent/packet_buffer.hpp" #include "libtorrent/error_code.hpp" #include <boost/bind.hpp> #include <boost/function/function1.hpp> #include <boost/function/function2.hpp> #define CCONTROL_TARGET 100 namespace libtorrent { struct utp_socket_manager; // the point of the bif_endian_int is two-fold // one purpuse is to not have any alignment requirements // so that any byffer received from the network can be cast // to it and read as an integer of various sizes without // triggering a bus error. The other purpose is to convert // from network byte order to host byte order when read and // written, to offer a convenient interface to both interpreting // and writing network packets template <class T> struct big_endian_int { big_endian_int& operator=(T v) { char* p = m_storage; detail::write_impl(v, p); return *this; } operator T() const { const char* p = m_storage; return detail::read_impl(p, detail::type<T>()); } private: char m_storage[sizeof(T)]; }; typedef big_endian_int<boost::uint64_t> be_uint64; typedef big_endian_int<boost::uint32_t> be_uint32; typedef big_endian_int<boost::uint16_t> be_uint16; typedef big_endian_int<boost::int64_t> be_int64; typedef big_endian_int<boost::int32_t> be_int32; typedef big_endian_int<boost::int16_t> be_int16; /* uTP header from BEP 29 0 4 8 16 24 32 +-------+-------+---------------+---------------+---------------+ | ver | type | extension | connection_id | +-------+-------+---------------+---------------+---------------+ | timestamp_microseconds | +---------------+---------------+---------------+---------------+ | timestamp_difference_microseconds | +---------------+---------------+---------------+---------------+ | wnd_size | +---------------+---------------+---------------+---------------+ | seq_nr | ack_nr | +---------------+---------------+---------------+---------------+ */ enum type { ST_DATA = 0, ST_FIN, ST_STATE, ST_RESET, ST_SYN, NUM_TYPES }; struct utp_header { unsigned char ver:4; unsigned char type:4; unsigned char extension; be_uint16 connection_id; be_uint32 timestamp_microseconds; be_uint32 timestamp_difference_microseconds; be_uint32 wnd_size; be_uint16 seq_nr; be_uint16 ack_nr; }; struct utp_socket_impl; utp_socket_impl* construct_utp_impl(boost::uint16_t recv_id , boost::uint16_t send_id, void* userdata , utp_socket_manager* sm); void detach_utp_impl(utp_socket_impl* s); void delete_utp_impl(utp_socket_impl* s); bool should_delete(utp_socket_impl* s); void tick_utp_impl(utp_socket_impl* s, ptime const& now); bool utp_incoming_packet(utp_socket_impl* s, char const* p , int size, udp::endpoint const& ep, ptime receive_time); bool utp_match(utp_socket_impl* s, udp::endpoint const& ep, boost::uint16_t id); udp::endpoint utp_remote_endpoint(utp_socket_impl* s); boost::uint16_t utp_receive_id(utp_socket_impl* s); int utp_socket_state(utp_socket_impl const* s); #if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING int socket_impl_size(); #endif // this is the user-level stream interface to utp sockets. // the reason why it's split up in a utp_stream class and // an implementation class is because the socket state has // to be able to out-live the user level socket. For instance // when sending data on a stream and then closing it, the // state holding the send buffer has to be kept around until // it has been flushed, which may be longer than the client // will keep the utp_stream object around for. // for more details, see utp_socket_impl, which is analogous // to the kernel state for a socket. It's defined in utp_stream.cpp class utp_stream { public: typedef stream_socket::endpoint_type endpoint_type; typedef stream_socket::protocol_type protocol_type; explicit utp_stream(asio::io_service& io_service); ~utp_stream(); // used for incoming connections void set_impl(utp_socket_impl* s); utp_socket_impl* get_impl(); #ifndef BOOST_NO_EXCEPTIONS template <class IO_Control_Command> void io_control(IO_Control_Command& ioc) {} #endif template <class IO_Control_Command> void io_control(IO_Control_Command& ioc, error_code& ec) {} #ifndef BOOST_NO_EXCEPTIONS void bind(endpoint_type const& endpoint) {} #endif void bind(endpoint_type const& endpoint, error_code& ec); #ifndef BOOST_NO_EXCEPTIONS template <class SettableSocketOption> void set_option(SettableSocketOption const& opt) {} #endif template <class SettableSocketOption> error_code set_option(SettableSocketOption const& opt, error_code& ec) { return ec; } void close(); void close(error_code const& ec) { close(); } bool is_open() const { return m_open; } int read_buffer_size() const; static void on_read(void* self, size_t bytes_transferred, error_code const& ec, bool kill); static void on_write(void* self, size_t bytes_transferred, error_code const& ec, bool kill); static void on_connect(void* self, error_code const& ec, bool kill); typedef void(*handler_t)(void*, size_t, error_code const&, bool); typedef void(*connect_handler_t)(void*, error_code const&, bool); void add_read_buffer(void* buf, size_t len); void set_read_handler(handler_t h); void add_write_buffer(void const* buf, size_t len); void set_write_handler(handler_t h); size_t read_some(bool clear_buffers); void do_connect(tcp::endpoint const& ep, connect_handler_t h); endpoint_type local_endpoint() const { error_code ec; return local_endpoint(ec); } endpoint_type local_endpoint(error_code& ec) const; endpoint_type remote_endpoint() const { error_code ec; return remote_endpoint(ec); } endpoint_type remote_endpoint(error_code& ec) const; std::size_t available() const; std::size_t available(error_code& ec) const { return available(); } asio::io_service& io_service() { return m_io_service; } template <class Handler> void async_connect(endpoint_type const& endpoint, Handler const& handler) { if (!endpoint.address().is_v4()) { error_code ec = asio::error::operation_not_supported; m_io_service.post(boost::bind<void>(handler, asio::error::operation_not_supported, 0)); return; } if (m_impl == 0) { m_io_service.post(boost::bind<void>(handler, asio::error::not_connected, 0)); return; } m_connect_handler = handler; do_connect(endpoint, &utp_stream::on_connect); } template <class Mutable_Buffers, class Handler> void async_read_some(Mutable_Buffers const& buffers, Handler const& handler) { if (m_impl == 0) { m_io_service.post(boost::bind<void>(handler, asio::error::not_connected, 0)); return; } TORRENT_ASSERT(!m_read_handler); if (m_read_handler) { m_io_service.post(boost::bind<void>(handler, asio::error::operation_not_supported, 0)); return; } for (typename Mutable_Buffers::const_iterator i = buffers.begin() , end(buffers.end()); i != end; ++i) { using asio::buffer_cast; using asio::buffer_size; add_read_buffer(buffer_cast<void*>(*i), buffer_size(*i)); } m_read_handler = handler; set_read_handler(&utp_stream::on_read); } void do_async_connect(endpoint_type const& ep , boost::function<void(error_code const&)> const& handler); template <class Protocol> void open(Protocol const& p, error_code& ec) { m_open = true; } template <class Protocol> void open(Protocol const& p) { m_open = true; } template <class Mutable_Buffers> std::size_t read_some(Mutable_Buffers const& buffers, error_code& ec) { TORRENT_ASSERT(!m_read_handler); if (m_impl == 0) { ec = asio::error::not_connected; return 0; } if (read_buffer_size() == 0) { ec = asio::error::would_block; return 0; } #ifdef TORRENT_DEBUG int buf_size = 0; #endif for (typename Mutable_Buffers::const_iterator i = buffers.begin() , end(buffers.end()); i != end; ++i) { using asio::buffer_cast; using asio::buffer_size; add_read_buffer(buffer_cast<void*>(*i), buffer_size(*i)); #ifdef TORRENT_DEBUG buf_size += buffer_size(*i); #endif } std::size_t ret = read_some(true); TORRENT_ASSERT(ret <= buf_size); return ret; } template <class Const_Buffers> std::size_t write_some(Const_Buffers const& buffers, error_code& ec) { // TODO: implement return 0; } template <class Const_Buffers, class Handler> void async_write_some(Const_Buffers const& buffers, Handler const& handler) { if (m_impl == 0) { m_io_service.post(boost::bind<void>(handler, asio::error::not_connected, 0)); return; } TORRENT_ASSERT(!m_write_handler); if (m_write_handler) { m_io_service.post(boost::bind<void>(handler, asio::error::operation_not_supported, 0)); return; } for (typename Const_Buffers::const_iterator i = buffers.begin() , end(buffers.end()); i != end; ++i) { using asio::buffer_cast; using asio::buffer_size; add_write_buffer((void*)buffer_cast<void const*>(*i), buffer_size(*i)); } m_write_handler = handler; set_write_handler(&utp_stream::on_write); } //private: void cancel_handlers(error_code const&); boost::function1<void, error_code const&> m_connect_handler; boost::function2<void, error_code const&, std::size_t> m_read_handler; boost::function2<void, error_code const&, std::size_t> m_write_handler; asio::io_service& m_io_service; utp_socket_impl* m_impl; bool m_open; }; } #endif <|endoftext|>
<commit_before>#include "core/tz.hpp" #include "core/vector.hpp" #include "core/matrix_transform.hpp" #include "gl/device.hpp" #include "gl/renderer.hpp" #include "gl/resource.hpp" #include "gl/input.hpp" #include "gl/shader.hpp" float get_aspect_ratio() { return tz::window().get_width() / tz::window().get_height(); } int main() { tz::initialise({"tz_triangle_demo", tz::Version{1, 0, 0}, tz::info()}); { tz::gl::DeviceBuilder device_builder; tz::gl::Device device{device_builder}; tz::gl::ShaderBuilder shader_builder; shader_builder.set_shader_file(tz::gl::ShaderType::VertexShader, ".\\demo\\gl\\triangle_demo.vertex.tzsl"); shader_builder.set_shader_file(tz::gl::ShaderType::FragmentShader, ".\\demo\\gl\\triangle_demo.fragment.tzsl"); tz::gl::Shader shader = device.create_shader(shader_builder); tz::gl::RendererBuilder renderer_builder; tz::gl::Mesh mesh; mesh.vertices = { tz::gl::Vertex{{-0.5f, -0.5f, 0.0f}, {1.0f, 0.0f}, {}, {}, {}}, tz::gl::Vertex{{0.5f, -0.5f, 0.0f}, {0.0f, 0.0f}, {}, {}, {}}, tz::gl::Vertex{{0.5f, 0.5f, 0.0f}, {0.0f, 1.0f}, {}, {}, {}} }; mesh.indices = {0, 1, 2}; tz::gl::MeshInput mesh_input{mesh}; // Note: Window is resizeable but we don't amend the aspect-ratio if it does. This is for simplicity's sake -- This is done properly in tz_dynamic_triangle_demo. tz::gl::BufferResource buf_res{tz::gl::BufferData::from_array<tz::Mat4> ({{ tz::model({0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, 0.0f}, {1.0f, 1.0f, 1.0f}), tz::view({0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f}), tz::perspective(1.27f, get_aspect_ratio(), 0.1f, 1000.0f) }})}; renderer_builder.add_input(mesh_input); renderer_builder.set_output(tz::window()); renderer_builder.add_resource(buf_res); renderer_builder.set_pass(tz::gl::RenderPassAttachment::Colour); renderer_builder.set_shader(shader); tz::gl::Renderer renderer = device.create_renderer(renderer_builder); renderer.set_clear_colour({0.1f, 0.2f, 0.4f, 1.0f}); while(!tz::window().is_close_requested()) { tz::window().update(); renderer.render(); } } tz::terminate(); }<commit_msg>* tz_triangle_demo is no longer resizeable<commit_after>#include "core/tz.hpp" #include "core/vector.hpp" #include "core/matrix_transform.hpp" #include "gl/device.hpp" #include "gl/renderer.hpp" #include "gl/resource.hpp" #include "gl/input.hpp" #include "gl/shader.hpp" float get_aspect_ratio() { return tz::window().get_width() / tz::window().get_height(); } int main() { tz::WindowInitArgs wargs = tz::default_args; wargs.resizeable = false; tz::initialise({"tz_triangle_demo", tz::Version{1, 0, 0}, tz::info()}, tz::ApplicationType::WindowApplication, wargs); { tz::gl::DeviceBuilder device_builder; tz::gl::Device device{device_builder}; tz::gl::ShaderBuilder shader_builder; shader_builder.set_shader_file(tz::gl::ShaderType::VertexShader, ".\\demo\\gl\\triangle_demo.vertex.tzsl"); shader_builder.set_shader_file(tz::gl::ShaderType::FragmentShader, ".\\demo\\gl\\triangle_demo.fragment.tzsl"); tz::gl::Shader shader = device.create_shader(shader_builder); tz::gl::RendererBuilder renderer_builder; tz::gl::Mesh mesh; mesh.vertices = { tz::gl::Vertex{{-0.5f, -0.5f, 0.0f}, {1.0f, 0.0f}, {}, {}, {}}, tz::gl::Vertex{{0.5f, -0.5f, 0.0f}, {0.0f, 0.0f}, {}, {}, {}}, tz::gl::Vertex{{0.5f, 0.5f, 0.0f}, {0.0f, 1.0f}, {}, {}, {}} }; mesh.indices = {0, 1, 2}; tz::gl::MeshInput mesh_input{mesh}; // Note: Window is resizeable but we don't amend the aspect-ratio if it does. This is for simplicity's sake -- This is done properly in tz_dynamic_triangle_demo. tz::gl::BufferResource buf_res{tz::gl::BufferData::from_array<tz::Mat4> ({{ tz::model({0.0f, 0.0f, -1.0f}, {0.0f, 0.0f, 0.0f}, {1.0f, 1.0f, 1.0f}), tz::view({0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f}), tz::perspective(1.27f, get_aspect_ratio(), 0.1f, 1000.0f) }})}; renderer_builder.add_input(mesh_input); renderer_builder.set_output(tz::window()); renderer_builder.add_resource(buf_res); renderer_builder.set_pass(tz::gl::RenderPassAttachment::Colour); renderer_builder.set_shader(shader); tz::gl::Renderer renderer = device.create_renderer(renderer_builder); renderer.set_clear_colour({0.1f, 0.2f, 0.4f, 1.0f}); while(!tz::window().is_close_requested()) { tz::window().update(); renderer.render(); } } tz::terminate(); }<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: invmerge.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: ihi $ $Date: 2006-11-14 15:57:39 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" #include <vcl/window.hxx> #include <tools/debug.hxx> #include "invmerge.hxx" //------------------------------------------------------------------ ScInvertMerger::ScInvertMerger( Window* pWindow ) : pWin( pWindow ), pRects( NULL ) { // both rectangles empty } ScInvertMerger::ScInvertMerger( ::std::vector< Rectangle >* pRectangles ) : pWin( NULL ), pRects( pRectangles ) { // collect rectangles instead of inverting } ScInvertMerger::~ScInvertMerger() { Flush(); } void ScInvertMerger::Flush() { FlushLine(); FlushTotal(); DBG_ASSERT( aLineRect.IsEmpty() && aTotalRect.IsEmpty(), "Flush: not empty" ); if ( pRects ) { // // also join vertically if there are non-adjacent columns involved // size_t nComparePos = 0; while ( nComparePos < pRects->size() ) { Rectangle aCompRect = (*pRects)[nComparePos]; sal_Int32 nBottom = aCompRect.Bottom(); size_t nOtherPos = nComparePos + 1; while ( nOtherPos < pRects->size() ) { Rectangle aOtherRect = (*pRects)[nOtherPos]; if ( aOtherRect.Top() > nBottom + 1 ) { // rectangles are sorted, so we can stop searching break; } if ( aOtherRect.Top() == nBottom + 1 && aOtherRect.Left() == aCompRect.Left() && aOtherRect.Right() == aCompRect.Right() ) { // extend first rectangle nBottom = aOtherRect.Bottom(); aCompRect.Bottom() = nBottom; (*pRects)[nComparePos].Bottom() = nBottom; // remove second rectangle pRects->erase( pRects->begin() + nOtherPos ); // continue at unmodified nOtherPos } else ++nOtherPos; } ++nComparePos; } } } void ScInvertMerger::FlushTotal() { if( aTotalRect.IsEmpty() ) return; // nothing to do if ( pWin ) pWin->Invert( aTotalRect, INVERT_HIGHLIGHT ); else if ( pRects ) pRects->push_back( aTotalRect ); aTotalRect.SetEmpty(); } void ScInvertMerger::FlushLine() { if( aLineRect.IsEmpty() ) return; // nothing to do if ( aTotalRect.IsEmpty() ) { aTotalRect = aLineRect; // start new total rect } else { if ( aLineRect.Left() == aTotalRect.Left() && aLineRect.Right() == aTotalRect.Right() && aLineRect.Top() == aTotalRect.Bottom() + 1 ) { // extend total rect aTotalRect.Bottom() = aLineRect.Bottom(); } else { FlushTotal(); // draw old total rect aTotalRect = aLineRect; // and start new one } } aLineRect.SetEmpty(); } void ScInvertMerger::AddRect( const Rectangle& rRect ) { if ( aLineRect.IsEmpty() ) { aLineRect = rRect; // start new line rect } else { Rectangle aJustified = rRect; if ( rRect.Left() > rRect.Right() ) // switch for RTL layout { aJustified.Left() = rRect.Right(); aJustified.Right() = rRect.Left(); } BOOL bDone = FALSE; if ( aJustified.Top() == aLineRect.Top() && aJustified.Bottom() == aLineRect.Bottom() ) { // try to extend line rect if ( aJustified.Left() == aLineRect.Right() + 1 ) { aLineRect.Right() = aJustified.Right(); bDone = TRUE; } else if ( aJustified.Right() + 1 == aLineRect.Left() ) // for RTL layout { aLineRect.Left() = aJustified.Left(); bDone = TRUE; } } if (!bDone) { FlushLine(); // use old line rect for total rect aLineRect = aJustified; // and start new one } } } <commit_msg>INTEGRATION: CWS calcselection (1.5.358); FILE MERGED 2008/02/13 13:56:00 nn 1.5.358.1: #i86069# transparent cell selection<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: invmerge.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2008-02-19 15:35:49 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" #include <vcl/window.hxx> #include <tools/debug.hxx> #include "invmerge.hxx" //------------------------------------------------------------------ ScInvertMerger::ScInvertMerger( Window* pWindow ) : pWin( pWindow ), pRects( NULL ) { // both rectangles empty } ScInvertMerger::ScInvertMerger( ::std::vector< Rectangle >* pRectangles ) : pWin( NULL ), pRects( pRectangles ) { // collect rectangles instead of inverting } ScInvertMerger::~ScInvertMerger() { Flush(); } void ScInvertMerger::Flush() { FlushLine(); FlushTotal(); DBG_ASSERT( aLineRect.IsEmpty() && aTotalRect.IsEmpty(), "Flush: not empty" ); if ( pRects ) { // // also join vertically if there are non-adjacent columns involved // size_t nComparePos = 0; while ( nComparePos < pRects->size() ) { Rectangle aCompRect = (*pRects)[nComparePos]; sal_Int32 nBottom = aCompRect.Bottom(); size_t nOtherPos = nComparePos + 1; while ( nOtherPos < pRects->size() ) { Rectangle aOtherRect = (*pRects)[nOtherPos]; if ( aOtherRect.Top() > nBottom + 1 ) { // rectangles are sorted, so we can stop searching break; } if ( aOtherRect.Top() == nBottom + 1 && aOtherRect.Left() == aCompRect.Left() && aOtherRect.Right() == aCompRect.Right() ) { // extend first rectangle nBottom = aOtherRect.Bottom(); aCompRect.Bottom() = nBottom; (*pRects)[nComparePos].Bottom() = nBottom; // remove second rectangle pRects->erase( pRects->begin() + nOtherPos ); // continue at unmodified nOtherPos } else ++nOtherPos; } ++nComparePos; } } } void ScInvertMerger::FlushTotal() { if( aTotalRect.IsEmpty() ) return; // nothing to do if ( pWin ) pWin->Invert( aTotalRect, INVERT_HIGHLIGHT ); else if ( pRects ) pRects->push_back( aTotalRect ); aTotalRect.SetEmpty(); } void ScInvertMerger::FlushLine() { if( aLineRect.IsEmpty() ) return; // nothing to do if ( aTotalRect.IsEmpty() ) { aTotalRect = aLineRect; // start new total rect } else { if ( aLineRect.Left() == aTotalRect.Left() && aLineRect.Right() == aTotalRect.Right() && aLineRect.Top() == aTotalRect.Bottom() + 1 ) { // extend total rect aTotalRect.Bottom() = aLineRect.Bottom(); } else { FlushTotal(); // draw old total rect aTotalRect = aLineRect; // and start new one } } aLineRect.SetEmpty(); } void ScInvertMerger::AddRect( const Rectangle& rRect ) { Rectangle aJustified = rRect; if ( rRect.Left() > rRect.Right() ) // switch for RTL layout { aJustified.Left() = rRect.Right(); aJustified.Right() = rRect.Left(); } if ( aLineRect.IsEmpty() ) { aLineRect = aJustified; // start new line rect } else { BOOL bDone = FALSE; if ( aJustified.Top() == aLineRect.Top() && aJustified.Bottom() == aLineRect.Bottom() ) { // try to extend line rect if ( aJustified.Left() == aLineRect.Right() + 1 ) { aLineRect.Right() = aJustified.Right(); bDone = TRUE; } else if ( aJustified.Right() + 1 == aLineRect.Left() ) // for RTL layout { aLineRect.Left() = aJustified.Left(); bDone = TRUE; } } if (!bDone) { FlushLine(); // use old line rect for total rect aLineRect = aJustified; // and start new one } } } <|endoftext|>
<commit_before>/* * CategoryStream.hh * * Copyright 2001, LifeLine Networks BV (www.lifeline.nl). All rights reserved. * Copyright 2001, Bastiaan Bakker. All rights reserved. * * See the COPYING file for the terms of usage and distribution. */ #ifndef _LOG4CPP_CATEGORYSTREAM_HH #define _LOG4CPP_CATEGORYSTREAM_HH #include <log4cpp/Portability.hh> #include <log4cpp/Priority.hh> #ifdef LOG4CPP_HAVE_SSTREAM #include <sstream> #endif namespace log4cpp { class LOG4CPP_EXPORT Category; /** * This class enables streaming simple types and objects to a category. * Use category.errorStream(), etc. to obtain a CategoryStream class. **/ class LOG4CPP_EXPORT CategoryStream { public: /** * Enumeration of special 'Separators'. Currently only contains the * 'ENDLINE' separator, which separates two log messages. **/ typedef enum { ENDLINE } Separator; /** * Construct a CategoryStream for given Category with given priority. * @param category The category this stream will send log messages to. * @param priority The priority the log messages will get or * Priority::NOTSET to silently discard any streamed in messages. **/ CategoryStream(Category& category, Priority::Value priority); /** * Destructor for CategoryStream **/ ~CategoryStream(); /** * Returns the destination Category for this stream. * @returns The Category. **/ inline Category& getCategory() const { return _category; }; /** * Returns the priority for this stream. * @returns The priority. **/ inline Priority::Value getPriority() const throw() { return _priority; }; /** * Streams in a Separator. If the separator equals * CategoryStream::ENDLINE it sends the contents of the stream buffer * to the Category with set priority and empties the buffer. * @param separator The Separator * @returns A reference to itself. **/ CategoryStream& operator<<(Separator separator); /** * Flush the contents of the stream buffer to the Category and * empties the buffer. **/ void flush(); /** * Stream in arbitrary types and objects. * @param t The value or object to stream in. * @returns A reference to itself. **/ template<typename T> CategoryStream& operator<<(const T& t) { if (getPriority() != Priority::NOTSET) { if (!_buffer) { if (!(_buffer = new std::ostringstream)) { // XXX help help help } } (*_buffer) << t; } return *this; } private: Category& _category; Priority::Value _priority; std::ostringstream* _buffer; }; } #endif // _LOG4CPP_CATEGORYSTREAM_HH <commit_msg>Add CategoryStream::width() member Add alias of EOL, eol as ENDOFLINE<commit_after>/* * CategoryStream.hh * * Copyright 2001, LifeLine Networks BV (www.lifeline.nl). All rights reserved. * Copyright 2001, Bastiaan Bakker. All rights reserved. * * See the COPYING file for the terms of usage and distribution. */ #ifndef _LOG4CPP_CATEGORYSTREAM_HH #define _LOG4CPP_CATEGORYSTREAM_HH #include <log4cpp/Portability.hh> #include <log4cpp/Priority.hh> #include <ios> #ifdef LOG4CPP_HAVE_SSTREAM #include <sstream> #endif namespace log4cpp { class LOG4CPP_EXPORT Category; /** * This class enables streaming simple types and objects to a category. * Use category.errorStream(), etc. to obtain a CategoryStream class. **/ class LOG4CPP_EXPORT CategoryStream { public: /** * Enumeration of special 'Separators'. Currently only contains the * 'ENDLINE' separator, which separates two log messages. **/ typedef enum { ENDLINE = 0, EOL = 0, eol = 0 } Separator; /** * Construct a CategoryStream for given Category with given priority. * @param category The category this stream will send log messages to. * @param priority The priority the log messages will get or * Priority::NOTSET to silently discard any streamed in messages. **/ CategoryStream(Category& category, Priority::Value priority); /** * Destructor for CategoryStream **/ ~CategoryStream(); /** * Returns the destination Category for this stream. * @returns The Category. **/ inline Category& getCategory() const { return _category; }; /** * Returns the priority for this stream. * @returns The priority. **/ inline Priority::Value getPriority() const throw() { return _priority; }; /** * Streams in a Separator. If the separator equals * CategoryStream::ENDLINE it sends the contents of the stream buffer * to the Category with set priority and empties the buffer. * @param separator The Separator * @returns A reference to itself. **/ CategoryStream& operator<<(Separator separator); /** * Flush the contents of the stream buffer to the Category and * empties the buffer. **/ void flush(); /** * Stream in arbitrary types and objects. * @param t The value or object to stream in. * @returns A reference to itself. **/ template<typename T> CategoryStream& operator<<(const T& t) { if (getPriority() != Priority::NOTSET) { if (!_buffer) { if (!(_buffer = new std::ostringstream)) { // XXX help help help } } (*_buffer) << t; } return *this; } std::streamsize width(std::streamsize wide ) { if (getPriority() != Priority::NOTSET) { if (!_buffer) { if (!(_buffer = new std::ostringstream)) { // XXX help help help } } } return _buffer->width(wide); } CategoryStream& left() { _buffer->setf(std::ios_base::left, std::ios_base::adjustfield); return *this; } private: Category& _category; Priority::Value _priority; std::ostringstream* _buffer; }; } #endif // _LOG4CPP_CATEGORYSTREAM_HH <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2014 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_MARKER_HELPERS_HPP #define MAPNIK_MARKER_HELPERS_HPP #include <mapnik/color.hpp> #include <mapnik/feature.hpp> #include <mapnik/geometry_impl.hpp> #include <mapnik/geometry_type.hpp> #include <mapnik/geometry_centroid.hpp> #include <mapnik/geom_util.hpp> #include <mapnik/symbolizer.hpp> #include <mapnik/expression_node.hpp> #include <mapnik/expression_evaluator.hpp> #include <mapnik/svg/svg_path_attributes.hpp> #include <mapnik/svg/svg_converter.hpp> #include <mapnik/marker.hpp> // for svg_storage_type #include <mapnik/markers_placement.hpp> #include <mapnik/attribute.hpp> #include <mapnik/box2d.hpp> #include <mapnik/vertex_converters.hpp> #include <mapnik/vertex_processor.hpp> #include <mapnik/label_collision_detector.hpp> #include <mapnik/renderer_common/apply_vertex_converter.hpp> // agg #include "agg_trans_affine.h" // boost #include <boost/optional.hpp> #include <boost/geometry/algorithms/centroid.hpp> // stl #include <memory> #include <type_traits> // remove_reference #include <cmath> namespace mapnik { struct clip_poly_tag; using svg_attribute_type = agg::pod_bvector<svg::path_attributes>; template <typename Detector> struct vector_markers_dispatch : util::noncopyable { vector_markers_dispatch(svg_path_ptr const& src, agg::trans_affine const& marker_trans, symbolizer_base const& sym, Detector & detector, double scale_factor, feature_impl & feature, attributes const& vars) : src_(src), marker_trans_(marker_trans), sym_(sym), detector_(detector), feature_(feature), vars_(vars), scale_factor_(scale_factor) {} virtual ~vector_markers_dispatch() {} template <typename T> void add_path(T & path) { marker_placement_enum placement_method = get<marker_placement_enum, keys::markers_placement_type>(sym_, feature_, vars_); value_bool ignore_placement = get<value_bool, keys::ignore_placement>(sym_, feature_, vars_); value_bool allow_overlap = get<value_bool, keys::allow_overlap>(sym_, feature_, vars_); value_bool avoid_edges = get<value_bool, keys::avoid_edges>(sym_, feature_, vars_); value_double opacity = get<value_double,keys::opacity>(sym_, feature_, vars_); value_double spacing = get<value_double, keys::spacing>(sym_, feature_, vars_); value_double max_error = get<value_double, keys::max_error>(sym_, feature_, vars_); coord2d center = src_->bounding_box().center(); agg::trans_affine_translation recenter(-center.x, -center.y); agg::trans_affine tr = recenter * marker_trans_; markers_placement_params params { src_->bounding_box(), tr, spacing * scale_factor_, max_error, allow_overlap, avoid_edges }; markers_placement_finder<T, Detector> placement_finder( placement_method, path, detector_, params); double x, y, angle = .0; while (placement_finder.get_point(x, y, angle, ignore_placement)) { agg::trans_affine matrix = tr; matrix.rotate(angle); matrix.translate(x, y); render_marker(matrix, opacity); } } virtual void render_marker(agg::trans_affine const& marker_tr, double opacity) = 0; protected: svg_path_ptr const& src_; agg::trans_affine const& marker_trans_; symbolizer_base const& sym_; Detector & detector_; feature_impl & feature_; attributes const& vars_; double scale_factor_; }; template <typename Detector> struct raster_markers_dispatch : util::noncopyable { raster_markers_dispatch(image_rgba8 const& src, agg::trans_affine const& marker_trans, symbolizer_base const& sym, Detector & detector, double scale_factor, feature_impl & feature, attributes const& vars) : src_(src), marker_trans_(marker_trans), sym_(sym), detector_(detector), feature_(feature), vars_(vars), scale_factor_(scale_factor) {} virtual ~raster_markers_dispatch() {} template <typename T> void add_path(T & path) { marker_placement_enum placement_method = get<marker_placement_enum, keys::markers_placement_type>(sym_, feature_, vars_); value_bool allow_overlap = get<value_bool, keys::allow_overlap>(sym_, feature_, vars_); value_bool avoid_edges = get<value_bool, keys::avoid_edges>(sym_, feature_, vars_); value_double opacity = get<value_double, keys::opacity>(sym_, feature_, vars_); value_bool ignore_placement = get<value_bool, keys::ignore_placement>(sym_, feature_, vars_); value_double spacing = get<value_double, keys::spacing>(sym_, feature_, vars_); value_double max_error = get<value_double, keys::max_error>(sym_, feature_, vars_); box2d<double> bbox(0,0, src_.width(),src_.height()); markers_placement_params params { bbox, marker_trans_, spacing * scale_factor_, max_error, allow_overlap, avoid_edges }; markers_placement_finder<T, label_collision_detector4> placement_finder( placement_method, path, detector_, params); double x, y, angle = .0; while (placement_finder.get_point(x, y, angle, ignore_placement)) { agg::trans_affine matrix = marker_trans_; matrix.rotate(angle); matrix.translate(x, y); render_marker(matrix, opacity); } } virtual void render_marker(agg::trans_affine const& marker_tr, double opacity) = 0; protected: image_rgba8 const& src_; agg::trans_affine const& marker_trans_; symbolizer_base const& sym_; Detector & detector_; feature_impl & feature_; attributes const& vars_; double scale_factor_; }; void build_ellipse(symbolizer_base const& sym, mapnik::feature_impl & feature, attributes const& vars, svg_storage_type & marker_ellipse, svg::svg_path_adapter & svg_path); bool push_explicit_style(svg_attribute_type const& src, svg_attribute_type & dst, symbolizer_base const& sym, feature_impl & feature, attributes const& vars); void setup_transform_scaling(agg::trans_affine & tr, double svg_width, double svg_height, mapnik::feature_impl & feature, attributes const& vars, symbolizer_base const& sym); // Apply markers to a feature with multiple geometries template <typename Converter> void apply_markers_multi(feature_impl const& feature, attributes const& vars, Converter & converter, symbolizer_base const& sym) { using vertex_converter_type = Converter; using apply_vertex_converter_type = detail::apply_vertex_converter<vertex_converter_type>; using vertex_processor_type = new_geometry::vertex_processor<apply_vertex_converter_type>; auto const& geom = feature.get_geometry(); new_geometry::geometry_types type = new_geometry::geometry_type(geom); if (type == new_geometry::geometry_types::Point || new_geometry::geometry_types::LineString || new_geometry::geometry_types::Polygon) { apply_vertex_converter_type apply(converter); mapnik::util::apply_visitor(vertex_processor_type(apply), geom); } else if (type != new_geometry::geometry_types::GeometryCollection) // multi geometries { marker_multi_policy_enum multi_policy = get<marker_multi_policy_enum, keys::markers_multipolicy>(sym, feature, vars); marker_placement_enum placement = get<marker_placement_enum, keys::markers_placement_type>(sym, feature, vars); if (placement == MARKER_POINT_PLACEMENT && multi_policy == MARKER_WHOLE_MULTI) { new_geometry::point pt; if (new_geometry::centroid(geom, pt)) { // unset any clipping since we're now dealing with a point converter.template unset<clip_poly_tag>(); new_geometry::point_vertex_adapter va(pt); converter.apply(va); } } else if ((placement == MARKER_POINT_PLACEMENT || placement == MARKER_INTERIOR_PLACEMENT) && multi_policy == MARKER_LARGEST_MULTI) { // Only apply to path with largest envelope area // TODO: consider using true area for polygon types if (type == new_geometry::geometry_types::MultiPolygon) { new_geometry::multi_polygon multi_poly = mapnik::util::get<new_geometry::multi_polygon>(geom); double maxarea = 0; new_geometry::polygon const* largest = 0; for (new_geometry::polygon const& poly : multi_poly) { box2d<double> bbox = new_geometry::envelope(poly); new_geometry::polygon_vertex_adapter va(poly); double area = bbox.width() * bbox.height(); if (area > maxarea) { maxarea = area; largest = &poly; } } if (largest) { new_geometry::polygon_vertex_adapter va(*largest); converter.apply(va); } } } else if (type == new_geometry::geometry_types::MultiPolygon) { if (multi_policy != MARKER_EACH_MULTI && placement != MARKER_POINT_PLACEMENT) { MAPNIK_LOG_WARN(marker_symbolizer) << "marker_multi_policy != 'each' has no effect with marker_placement != 'point'"; } new_geometry::multi_polygon multi_poly = mapnik::util::get<new_geometry::multi_polygon>(geom); for (auto const& poly : multi_poly) { new_geometry::polygon_vertex_adapter va(poly); converter.apply(va); } } } } } #endif //MAPNIK_MARKER_HELPERS_HPP <commit_msg>remove unused headers<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2014 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_MARKER_HELPERS_HPP #define MAPNIK_MARKER_HELPERS_HPP #include <mapnik/color.hpp> #include <mapnik/feature.hpp> #include <mapnik/geometry_impl.hpp> #include <mapnik/geometry_type.hpp> #include <mapnik/geometry_centroid.hpp> #include <mapnik/symbolizer.hpp> #include <mapnik/expression_node.hpp> #include <mapnik/expression_evaluator.hpp> #include <mapnik/svg/svg_path_attributes.hpp> #include <mapnik/svg/svg_converter.hpp> #include <mapnik/marker.hpp> // for svg_storage_type #include <mapnik/markers_placement.hpp> #include <mapnik/attribute.hpp> #include <mapnik/box2d.hpp> #include <mapnik/vertex_converters.hpp> #include <mapnik/vertex_processor.hpp> #include <mapnik/label_collision_detector.hpp> #include <mapnik/renderer_common/apply_vertex_converter.hpp> // agg #include "agg_trans_affine.h" // boost #include <boost/optional.hpp> // stl #include <memory> #include <type_traits> // remove_reference #include <cmath> namespace mapnik { struct clip_poly_tag; using svg_attribute_type = agg::pod_bvector<svg::path_attributes>; template <typename Detector> struct vector_markers_dispatch : util::noncopyable { vector_markers_dispatch(svg_path_ptr const& src, agg::trans_affine const& marker_trans, symbolizer_base const& sym, Detector & detector, double scale_factor, feature_impl & feature, attributes const& vars) : src_(src), marker_trans_(marker_trans), sym_(sym), detector_(detector), feature_(feature), vars_(vars), scale_factor_(scale_factor) {} virtual ~vector_markers_dispatch() {} template <typename T> void add_path(T & path) { marker_placement_enum placement_method = get<marker_placement_enum, keys::markers_placement_type>(sym_, feature_, vars_); value_bool ignore_placement = get<value_bool, keys::ignore_placement>(sym_, feature_, vars_); value_bool allow_overlap = get<value_bool, keys::allow_overlap>(sym_, feature_, vars_); value_bool avoid_edges = get<value_bool, keys::avoid_edges>(sym_, feature_, vars_); value_double opacity = get<value_double,keys::opacity>(sym_, feature_, vars_); value_double spacing = get<value_double, keys::spacing>(sym_, feature_, vars_); value_double max_error = get<value_double, keys::max_error>(sym_, feature_, vars_); coord2d center = src_->bounding_box().center(); agg::trans_affine_translation recenter(-center.x, -center.y); agg::trans_affine tr = recenter * marker_trans_; markers_placement_params params { src_->bounding_box(), tr, spacing * scale_factor_, max_error, allow_overlap, avoid_edges }; markers_placement_finder<T, Detector> placement_finder( placement_method, path, detector_, params); double x, y, angle = .0; while (placement_finder.get_point(x, y, angle, ignore_placement)) { agg::trans_affine matrix = tr; matrix.rotate(angle); matrix.translate(x, y); render_marker(matrix, opacity); } } virtual void render_marker(agg::trans_affine const& marker_tr, double opacity) = 0; protected: svg_path_ptr const& src_; agg::trans_affine const& marker_trans_; symbolizer_base const& sym_; Detector & detector_; feature_impl & feature_; attributes const& vars_; double scale_factor_; }; template <typename Detector> struct raster_markers_dispatch : util::noncopyable { raster_markers_dispatch(image_rgba8 const& src, agg::trans_affine const& marker_trans, symbolizer_base const& sym, Detector & detector, double scale_factor, feature_impl & feature, attributes const& vars) : src_(src), marker_trans_(marker_trans), sym_(sym), detector_(detector), feature_(feature), vars_(vars), scale_factor_(scale_factor) {} virtual ~raster_markers_dispatch() {} template <typename T> void add_path(T & path) { marker_placement_enum placement_method = get<marker_placement_enum, keys::markers_placement_type>(sym_, feature_, vars_); value_bool allow_overlap = get<value_bool, keys::allow_overlap>(sym_, feature_, vars_); value_bool avoid_edges = get<value_bool, keys::avoid_edges>(sym_, feature_, vars_); value_double opacity = get<value_double, keys::opacity>(sym_, feature_, vars_); value_bool ignore_placement = get<value_bool, keys::ignore_placement>(sym_, feature_, vars_); value_double spacing = get<value_double, keys::spacing>(sym_, feature_, vars_); value_double max_error = get<value_double, keys::max_error>(sym_, feature_, vars_); box2d<double> bbox(0,0, src_.width(),src_.height()); markers_placement_params params { bbox, marker_trans_, spacing * scale_factor_, max_error, allow_overlap, avoid_edges }; markers_placement_finder<T, label_collision_detector4> placement_finder( placement_method, path, detector_, params); double x, y, angle = .0; while (placement_finder.get_point(x, y, angle, ignore_placement)) { agg::trans_affine matrix = marker_trans_; matrix.rotate(angle); matrix.translate(x, y); render_marker(matrix, opacity); } } virtual void render_marker(agg::trans_affine const& marker_tr, double opacity) = 0; protected: image_rgba8 const& src_; agg::trans_affine const& marker_trans_; symbolizer_base const& sym_; Detector & detector_; feature_impl & feature_; attributes const& vars_; double scale_factor_; }; void build_ellipse(symbolizer_base const& sym, mapnik::feature_impl & feature, attributes const& vars, svg_storage_type & marker_ellipse, svg::svg_path_adapter & svg_path); bool push_explicit_style(svg_attribute_type const& src, svg_attribute_type & dst, symbolizer_base const& sym, feature_impl & feature, attributes const& vars); void setup_transform_scaling(agg::trans_affine & tr, double svg_width, double svg_height, mapnik::feature_impl & feature, attributes const& vars, symbolizer_base const& sym); // Apply markers to a feature with multiple geometries template <typename Converter> void apply_markers_multi(feature_impl const& feature, attributes const& vars, Converter & converter, symbolizer_base const& sym) { using vertex_converter_type = Converter; using apply_vertex_converter_type = detail::apply_vertex_converter<vertex_converter_type>; using vertex_processor_type = new_geometry::vertex_processor<apply_vertex_converter_type>; auto const& geom = feature.get_geometry(); new_geometry::geometry_types type = new_geometry::geometry_type(geom); if (type == new_geometry::geometry_types::Point || new_geometry::geometry_types::LineString || new_geometry::geometry_types::Polygon) { apply_vertex_converter_type apply(converter); mapnik::util::apply_visitor(vertex_processor_type(apply), geom); } else if (type != new_geometry::geometry_types::GeometryCollection) // multi geometries { marker_multi_policy_enum multi_policy = get<marker_multi_policy_enum, keys::markers_multipolicy>(sym, feature, vars); marker_placement_enum placement = get<marker_placement_enum, keys::markers_placement_type>(sym, feature, vars); if (placement == MARKER_POINT_PLACEMENT && multi_policy == MARKER_WHOLE_MULTI) { new_geometry::point pt; if (new_geometry::centroid(geom, pt)) { // unset any clipping since we're now dealing with a point converter.template unset<clip_poly_tag>(); new_geometry::point_vertex_adapter va(pt); converter.apply(va); } } else if ((placement == MARKER_POINT_PLACEMENT || placement == MARKER_INTERIOR_PLACEMENT) && multi_policy == MARKER_LARGEST_MULTI) { // Only apply to path with largest envelope area // TODO: consider using true area for polygon types if (type == new_geometry::geometry_types::MultiPolygon) { new_geometry::multi_polygon multi_poly = mapnik::util::get<new_geometry::multi_polygon>(geom); double maxarea = 0; new_geometry::polygon const* largest = 0; for (new_geometry::polygon const& poly : multi_poly) { box2d<double> bbox = new_geometry::envelope(poly); new_geometry::polygon_vertex_adapter va(poly); double area = bbox.width() * bbox.height(); if (area > maxarea) { maxarea = area; largest = &poly; } } if (largest) { new_geometry::polygon_vertex_adapter va(*largest); converter.apply(va); } } } else if (type == new_geometry::geometry_types::MultiPolygon) { if (multi_policy != MARKER_EACH_MULTI && placement != MARKER_POINT_PLACEMENT) { MAPNIK_LOG_WARN(marker_symbolizer) << "marker_multi_policy != 'each' has no effect with marker_placement != 'point'"; } new_geometry::multi_polygon multi_poly = mapnik::util::get<new_geometry::multi_polygon>(geom); for (auto const& poly : multi_poly) { new_geometry::polygon_vertex_adapter va(poly); converter.apply(va); } } } } } #endif //MAPNIK_MARKER_HELPERS_HPP <|endoftext|>
<commit_before>/* * This file is part of otf2xx (https://github.com/tud-zih-energy/otf2xx) * otf2xx - A wrapper for the Open Trace Format 2 library * * Copyright (c) 2013-2016, Technische Universität Dresden, Germany * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions 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 the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef INCLUDE_OTF2XX_CHRONO_CONVERT_HPP #define INCLUDE_OTF2XX_CHRONO_CONVERT_HPP #include <otf2xx/chrono/clock.hpp> #include <otf2xx/chrono/ticks.hpp> #include <otf2xx/chrono/time_point.hpp> #include <otf2xx/definition/clock_properties.hpp> #include <cassert> #include <cmath> #include <limits> namespace otf2 { namespace chrono { /** * \brief class to convert between ticks and time points * * This class can convert between ticks and time points. * For this, it needs the number of ticks per second. * * \note The time epoch is assumed to be equal between the time point and * time point represented with the number ticks given. */ class convert { static_assert(clock::period::num == 1, "Don't mess around with chrono!"); public: explicit convert(otf2::chrono::ticks ticks_per_second = otf2::chrono::ticks(otf2::chrono::clock::period::den), otf2::chrono::ticks offset = otf2::chrono::ticks(0)) : offset_(offset.count()), factor_(static_cast<double>(clock::period::den) / ticks_per_second.count()), inverse_factor_(ticks_per_second.count() / static_cast<double>(clock::period::den)) { // WARNING: Be careful, when changing clock::period::den. // You will have to think about every calculations twice, as there // might be narrowing and rounding anywhere. // We also assumed here, that we have nanoseconds or picoseconds resolution and the // input resolution is about nanoseconds or a few hundred // picoseconds. // These assumptions have to be double checked! assert(ticks_per_second.count() <= clock::period::den); } explicit convert(const otf2::definition::clock_properties& cp) : convert(cp.ticks_per_second(), cp.start_time()) { } convert(const convert&) = default; convert& operator=(const convert&) = default; convert(convert&&) = default; convert& operator=(convert&&) = default; /** * \brief converts from ticks to time point * * \param[in] ticks since epoch * \return time_point with a duration equal to the passed time * since the epoch. */ otf2::chrono::time_point operator()(otf2::chrono::ticks ticks) const { // VTTI please remember that those two inputs are uint64_t and then look at the next // line assert(ticks.count() >= offset_); auto tp = ticks.count() - offset_; assert(tp < static_cast<uint64_t>(std::numeric_limits<int64_t>::max()) / factor_); return time_point(otf2::chrono::duration(static_cast<int64_t>(tp * factor_))); } /** * \brief converts from time points to ticks * * \param[in] t a time point * \return number ticks equal to passed time of the duration of the time * point */ otf2::chrono::ticks operator()(time_point t) const { auto tp = t.time_since_epoch().count(); assert(tp < static_cast<uint64_t>(std::numeric_limits<int64_t>::max()) / inverse_factor_); // Note 1: Using ceil here has its origins in the observation that casting from double // to int in the other conversion above leads to an implicit round down. Thus, we // counter that here with an explicit round up. // Note 2: Using an multiplication with the inverse yields a better performance. Though, // there might be cases, where a different sequence of multiplication or division // operations would result in lower rounding errors. auto tpi = static_cast<uint64_t>(std::ceil(tp * inverse_factor_)); assert(tpi >= -offset_); return ticks(tpi + offset_); } private: uint64_t offset_; double factor_; double inverse_factor_; }; /** * \brief converts from std::chrono::timepoint to otf2::chrono::time_point * * \param[in] tp the std::chrono time point * \return the same time point as otf2::chrono::time_point */ template <typename Clock, typename Duration> otf2::chrono::time_point convert_time_point(std::chrono::time_point<Clock, Duration> tp) { return otf2::chrono::time_point( std::chrono::duration_cast<otf2::chrono::clock::duration>(tp.time_since_epoch())); } } // namespace chrono } // namespace otf2 #endif // INCLUDE_OTF2XX_CHRONO_CONVERT_HPP <commit_msg>Fixes assertion in convert<commit_after>/* * This file is part of otf2xx (https://github.com/tud-zih-energy/otf2xx) * otf2xx - A wrapper for the Open Trace Format 2 library * * Copyright (c) 2013-2016, Technische Universität Dresden, Germany * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions 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 the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef INCLUDE_OTF2XX_CHRONO_CONVERT_HPP #define INCLUDE_OTF2XX_CHRONO_CONVERT_HPP #include <otf2xx/chrono/clock.hpp> #include <otf2xx/chrono/ticks.hpp> #include <otf2xx/chrono/time_point.hpp> #include <otf2xx/definition/clock_properties.hpp> #include <cassert> #include <cmath> #include <limits> namespace otf2 { namespace chrono { /** * \brief class to convert between ticks and time points * * This class can convert between ticks and time points. * For this, it needs the number of ticks per second. * * \note The time epoch is assumed to be equal between the time point and * time point represented with the number ticks given. */ class convert { static_assert(clock::period::num == 1, "Don't mess around with chrono!"); public: explicit convert(otf2::chrono::ticks ticks_per_second = otf2::chrono::ticks(otf2::chrono::clock::period::den), otf2::chrono::ticks offset = otf2::chrono::ticks(0)) : offset_(offset.count()), factor_(static_cast<double>(clock::period::den) / ticks_per_second.count()), inverse_factor_(ticks_per_second.count() / static_cast<double>(clock::period::den)) { // WARNING: Be careful, when changing clock::period::den. // You will have to think about every calculations twice, as there // might be narrowing and rounding anywhere. // We also assumed here, that we have nanoseconds or picoseconds resolution and the // input resolution is about nanoseconds or a few hundred // picoseconds. // These assumptions have to be double checked! assert(ticks_per_second.count() <= clock::period::den); } explicit convert(const otf2::definition::clock_properties& cp) : convert(cp.ticks_per_second(), cp.start_time()) { } convert(const convert&) = default; convert& operator=(const convert&) = default; convert(convert&&) = default; convert& operator=(convert&&) = default; /** * \brief converts from ticks to time point * * \param[in] ticks since epoch * \return time_point with a duration equal to the passed time * since the epoch. */ otf2::chrono::time_point operator()(otf2::chrono::ticks ticks) const { // VTTI please remember that those two inputs are uint64_t and then look at the next // line assert(ticks.count() >= offset_); auto tp = ticks.count() - offset_; assert(tp < static_cast<uint64_t>(std::numeric_limits<int64_t>::max()) / factor_); return time_point(otf2::chrono::duration(static_cast<int64_t>(tp * factor_))); } /** * \brief converts from time points to ticks * * \param[in] t a time point * \return number ticks equal to passed time of the duration of the time * point */ otf2::chrono::ticks operator()(time_point t) const { auto tp = t.time_since_epoch().count(); assert(tp < static_cast<uint64_t>(std::numeric_limits<int64_t>::max()) / inverse_factor_); // Note 1: Using ceil here has its origins in the observation that casting from double // to int in the other conversion above leads to an implicit round down. Thus, we // counter that here with an explicit round up. // Note 2: Using an multiplication with the inverse yields a better performance. Though, // there might be cases, where a different sequence of multiplication or division // operations would result in lower rounding errors. auto tpi = static_cast<uint64_t>(std::ceil(tp * inverse_factor_)); assert(tpi <= std::numeric_limits<std::uint64_t>::max() - offset_); return ticks(tpi + offset_); } private: uint64_t offset_; double factor_; double inverse_factor_; }; /** * \brief converts from std::chrono::timepoint to otf2::chrono::time_point * * \param[in] tp the std::chrono time point * \return the same time point as otf2::chrono::time_point */ template <typename Clock, typename Duration> otf2::chrono::time_point convert_time_point(std::chrono::time_point<Clock, Duration> tp) { return otf2::chrono::time_point( std::chrono::duration_cast<otf2::chrono::clock::duration>(tp.time_since_epoch())); } } // namespace chrono } // namespace otf2 #endif // INCLUDE_OTF2XX_CHRONO_CONVERT_HPP <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** **************************************************************************/ #include "simulatorqtversion.h" #include "qt4projectmanagerconstants.h" #include <qtsupport/qtsupportconstants.h> #include <proparser/profileevaluator.h> #include <QCoreApplication> #include <QDir> #include <QFileInfoList> using namespace Qt4ProjectManager; using namespace Qt4ProjectManager::Internal; SimulatorQtVersion::SimulatorQtVersion() : QtSupport::BaseQtVersion() { } SimulatorQtVersion::SimulatorQtVersion(const Utils::FileName &path, bool isAutodetected, const QString &autodetectionSource) : QtSupport::BaseQtVersion(path, isAutodetected, autodetectionSource) { } SimulatorQtVersion::~SimulatorQtVersion() { } SimulatorQtVersion *SimulatorQtVersion::clone() const { return new SimulatorQtVersion(*this); } QString SimulatorQtVersion::type() const { return QLatin1String(QtSupport::Constants::SIMULATORQT); } QString SimulatorQtVersion::warningReason() const { if (qtAbis().count() == 1 && qtAbis().first().isNull()) return QCoreApplication::translate("QtVersion", "ABI detection failed: Make sure to use a matching tool chain when building."); if (qtVersion() >= QtSupport::QtVersionNumber(4, 7, 0) && qmlviewerCommand().isEmpty()) return QCoreApplication::translate("QtVersion", "No qmlviewer installed."); return QString(); } QList<ProjectExplorer::Abi> SimulatorQtVersion::detectQtAbis() const { ensureMkSpecParsed(); return qtAbisFromLibrary(qtCorePath(versionInfo(), qtVersionString())); } bool SimulatorQtVersion::supportsTargetId(const QString &id) const { return id == QLatin1String(Constants::QT_SIMULATOR_TARGET_ID); } QSet<QString> SimulatorQtVersion::supportedTargetIds() const { return QSet<QString>() << QLatin1String(Constants::QT_SIMULATOR_TARGET_ID); } QString SimulatorQtVersion::description() const { return QCoreApplication::translate("QtVersion", "Qt Simulator", "Qt Version is meant for Qt Simulator"); } Core::FeatureSet SimulatorQtVersion::availableFeatures() const { Core::FeatureSet features = QtSupport::BaseQtVersion::availableFeatures(); if (qtVersion() >= QtSupport::QtVersionNumber(4, 7, 4)) //no reliable test for components, yet. features |= Core::FeatureSet(QtSupport::Constants::FEATURE_QTQUICK_COMPONENTS_MEEGO) | Core::FeatureSet(QtSupport::Constants::FEATURE_QTQUICK_COMPONENTS_SYMBIAN); return features; } bool SimulatorQtVersion::supportsPlatform(const QString &platformName) const { return (platformName == QtSupport::Constants::SYMBIAN_PLATFORM || platformName == QtSupport::Constants::MEEGO_HARMATTAN_PLATFORM || platformName.isEmpty()); } <commit_msg>Wizards: The simulator is for mobile development<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** **************************************************************************/ #include "simulatorqtversion.h" #include "qt4projectmanagerconstants.h" #include <qtsupport/qtsupportconstants.h> #include <proparser/profileevaluator.h> #include <QCoreApplication> #include <QDir> #include <QFileInfoList> using namespace Qt4ProjectManager; using namespace Qt4ProjectManager::Internal; SimulatorQtVersion::SimulatorQtVersion() : QtSupport::BaseQtVersion() { } SimulatorQtVersion::SimulatorQtVersion(const Utils::FileName &path, bool isAutodetected, const QString &autodetectionSource) : QtSupport::BaseQtVersion(path, isAutodetected, autodetectionSource) { } SimulatorQtVersion::~SimulatorQtVersion() { } SimulatorQtVersion *SimulatorQtVersion::clone() const { return new SimulatorQtVersion(*this); } QString SimulatorQtVersion::type() const { return QLatin1String(QtSupport::Constants::SIMULATORQT); } QString SimulatorQtVersion::warningReason() const { if (qtAbis().count() == 1 && qtAbis().first().isNull()) return QCoreApplication::translate("QtVersion", "ABI detection failed: Make sure to use a matching tool chain when building."); if (qtVersion() >= QtSupport::QtVersionNumber(4, 7, 0) && qmlviewerCommand().isEmpty()) return QCoreApplication::translate("QtVersion", "No qmlviewer installed."); return QString(); } QList<ProjectExplorer::Abi> SimulatorQtVersion::detectQtAbis() const { ensureMkSpecParsed(); return qtAbisFromLibrary(qtCorePath(versionInfo(), qtVersionString())); } bool SimulatorQtVersion::supportsTargetId(const QString &id) const { return id == QLatin1String(Constants::QT_SIMULATOR_TARGET_ID); } QSet<QString> SimulatorQtVersion::supportedTargetIds() const { return QSet<QString>() << QLatin1String(Constants::QT_SIMULATOR_TARGET_ID); } QString SimulatorQtVersion::description() const { return QCoreApplication::translate("QtVersion", "Qt Simulator", "Qt Version is meant for Qt Simulator"); } Core::FeatureSet SimulatorQtVersion::availableFeatures() const { Core::FeatureSet features = QtSupport::BaseQtVersion::availableFeatures(); if (qtVersion() >= QtSupport::QtVersionNumber(4, 7, 4)) //no reliable test for components, yet. features |= Core::FeatureSet(QtSupport::Constants::FEATURE_QTQUICK_COMPONENTS_MEEGO) | Core::FeatureSet(QtSupport::Constants::FEATURE_QTQUICK_COMPONENTS_SYMBIAN); features |= Core::FeatureSet(QtSupport::Constants::FEATURE_MOBILE); return features; } bool SimulatorQtVersion::supportsPlatform(const QString &platformName) const { return (platformName == QtSupport::Constants::SYMBIAN_PLATFORM || platformName == QtSupport::Constants::MEEGO_HARMATTAN_PLATFORM || platformName.isEmpty()); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: AccessibleViewForwarder.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: af $ $Date: 2002-06-03 15:06:58 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SVX_ACCESSIBILITY_ACCESSIBLE_VIEW_FORWARDER_HXX #include "AccessibleViewForwarder.hxx" #endif #ifndef _SVDPNTV_HXX #include <svx/svdpntv.hxx> #endif #ifndef _SV_OUTDEV_HXX #include <vcl/outdev.hxx> #endif namespace accessibility { /** For the time beeing, the implementation of this class will not use the member mrDevice. Instead the device is retrieved from the view everytime it is used. This is necessary because the device has to stay up-to-date with the current view and the class has to stay compatible. May change in the future. */ AccessibleViewForwarder::AccessibleViewForwarder (SdrPaintView* pView, USHORT nWindowId) : mpView (pView), mnWindowId (nWindowId), mrDevice (*pView->GetWin(nWindowId)) { OSL_ASSERT (mpView != NULL); // empty } AccessibleViewForwarder::AccessibleViewForwarder (SdrPaintView* pView, OutputDevice& rDevice) : mpView (pView), mnWindowId (0), mrDevice (rDevice) { // Search the output device to determine its id. for (USHORT i=0; i<mpView->GetWinCount(); i++) if (mpView->GetWin(i) == &rDevice) { mnWindowId = i; break; } } AccessibleViewForwarder::~AccessibleViewForwarder (void) { // empty } void AccessibleViewForwarder::SetView (SdrPaintView* pView) { mpView = pView; OSL_ASSERT (mpView != NULL); } sal_Bool AccessibleViewForwarder::IsValid (void) const { return sal_True; } Rectangle AccessibleViewForwarder::GetVisibleArea (void) const { return mpView->GetVisibleArea (mnWindowId); } Point AccessibleViewForwarder::LogicToPixel (const Point& rPoint) const { OSL_ASSERT (mpView != NULL); OutputDevice* pDevice = mpView->GetWin(mnWindowId); Rectangle aBBox (static_cast<Window*>(pDevice)->GetWindowExtentsRelative(NULL)); return pDevice->LogicToPixel (rPoint) + aBBox.TopLeft(); } Size AccessibleViewForwarder::LogicToPixel (const Size& rSize) const { OSL_ASSERT (mpView != NULL); OutputDevice* pDevice = mpView->GetWin(mnWindowId); return pDevice->LogicToPixel (rSize); } Point AccessibleViewForwarder::PixelToLogic (const Point& rPoint) const { OSL_ASSERT (mpView != NULL); OutputDevice* pDevice = mpView->GetWin(mnWindowId); return pDevice->PixelToLogic (rPoint); } Size AccessibleViewForwarder::PixelToLogic (const Size& rSize) const { OSL_ASSERT (mpView != NULL); OutputDevice* pDevice = mpView->GetWin(mnWindowId); return pDevice->PixelToLogic (rSize); } } // end of namespace accessibility <commit_msg>#100559# Transformation of point coordinates into internal coordinates now takes care of absolute pixel coordinates.<commit_after>/************************************************************************* * * $RCSfile: AccessibleViewForwarder.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: af $ $Date: 2002-06-28 08:44:42 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SVX_ACCESSIBILITY_ACCESSIBLE_VIEW_FORWARDER_HXX #include "AccessibleViewForwarder.hxx" #endif #ifndef _SVDPNTV_HXX #include <svx/svdpntv.hxx> #endif #ifndef _SV_OUTDEV_HXX #include <vcl/outdev.hxx> #endif namespace accessibility { /** For the time beeing, the implementation of this class will not use the member mrDevice. Instead the device is retrieved from the view everytime it is used. This is necessary because the device has to stay up-to-date with the current view and the class has to stay compatible. May change in the future. */ AccessibleViewForwarder::AccessibleViewForwarder (SdrPaintView* pView, USHORT nWindowId) : mpView (pView), mnWindowId (nWindowId), mrDevice (*pView->GetWin(nWindowId)) { OSL_ASSERT (mpView != NULL); // empty } AccessibleViewForwarder::AccessibleViewForwarder (SdrPaintView* pView, OutputDevice& rDevice) : mpView (pView), mnWindowId (0), mrDevice (rDevice) { // Search the output device to determine its id. for (USHORT i=0; i<mpView->GetWinCount(); i++) if (mpView->GetWin(i) == &rDevice) { mnWindowId = i; break; } } AccessibleViewForwarder::~AccessibleViewForwarder (void) { // empty } void AccessibleViewForwarder::SetView (SdrPaintView* pView) { mpView = pView; OSL_ASSERT (mpView != NULL); } sal_Bool AccessibleViewForwarder::IsValid (void) const { return sal_True; } Rectangle AccessibleViewForwarder::GetVisibleArea (void) const { return mpView->GetVisibleArea (mnWindowId); } /** Tansform the given point into pixel coordiantes. After the the pixel coordiantes of the window origin are added to make the point coordinates absolute. */ Point AccessibleViewForwarder::LogicToPixel (const Point& rPoint) const { OSL_ASSERT (mpView != NULL); OutputDevice* pDevice = mpView->GetWin(mnWindowId); Rectangle aBBox (static_cast<Window*>(pDevice)->GetWindowExtentsRelative(NULL)); return pDevice->LogicToPixel (rPoint) + aBBox.TopLeft(); } Size AccessibleViewForwarder::LogicToPixel (const Size& rSize) const { OSL_ASSERT (mpView != NULL); OutputDevice* pDevice = mpView->GetWin(mnWindowId); return pDevice->LogicToPixel (rSize); } /** First subtract the window origin to make the point coordinates relative to the window and then transform them into internal coordinates. */ Point AccessibleViewForwarder::PixelToLogic (const Point& rPoint) const { OSL_ASSERT (mpView != NULL); OutputDevice* pDevice = mpView->GetWin(mnWindowId); Rectangle aBBox (static_cast<Window*>(pDevice)->GetWindowExtentsRelative(NULL)); return pDevice->PixelToLogic (rPoint - aBBox.TopLeft()); } Size AccessibleViewForwarder::PixelToLogic (const Size& rSize) const { OSL_ASSERT (mpView != NULL); OutputDevice* pDevice = mpView->GetWin(mnWindowId); return pDevice->PixelToLogic (rSize); } } // end of namespace accessibility <|endoftext|>
<commit_before>/** * @file clitest.cpp * @brief Brief description of file. * */ #include <pthread.h> #include <string> #include <map> #include <queue> #include "tcp.h" #include "messages.h" #include "data.h" #include "time.h" namespace diamondapparatus { /// this is the database the client writes stuff to from its thread static std::map<std::string,Topic *> topics; /// primary mutex static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; /// condition used in get-wait static pthread_cond_t getcond = PTHREAD_COND_INITIALIZER; static bool running=false; inline void lock(const char *n){ dprintf("+++Attemping to lock: %s\n",n); pthread_mutex_lock(&mutex); } inline void unlock(const char *n){ dprintf("---Unlocking: %s\n",n); pthread_mutex_unlock(&mutex); } // the states the client can be in enum ClientState { ST_IDLE, ST_AWAITACK }; class MyClient : public TCPClient { ClientState state; public: MyClient(const char *host,int port) : TCPClient(host,port){ state = ST_IDLE; } void setState(ClientState s){ dprintf("====> state = %d\n",s); state = s; } // the topic I'm waiting for in get(), if any. const char *waittopic; void notify(const char *d){ dprintf("notify at %p\n",d); const char *name = Topic::getNameFromMsg(d); if(topics.find(std::string(name)) == topics.end()){ fprintf(stderr,"Topic %s not in client set, ignoring\n",name); return; } Topic *t = topics[name]; t->fromMessage(d); t->state =Topic::Changed; t->timeLastSet = Time::now(); // if we were waiting for this, signal. if(waittopic && !strcmp(name,waittopic)){ pthread_cond_signal(&getcond); } } virtual void process(uint32_t packetsize,void *packet){ lock("msgrecv"); char *p = (char *)packet; SCAck *ack; uint32_t type = ntohl(*(uint32_t *)p); dprintf("Packet type %d at %p\n",type,packet); if(type == SC_KILLCLIENT){ fprintf(stderr,"force exit\n"); running=false; } switch(state){ case ST_IDLE: if(type == SC_NOTIFY){ notify(p); } break; case ST_AWAITACK: ack = (SCAck *)p; if(type != SC_ACK) throw "unexpected packet in awaiting ack"; else if(ack->code){ dprintf("Ack code %d: %s\n",ntohs(ack->code),ack->msg); throw "bad code from ack"; } else dprintf("Acknowledged\n"); setState(ST_IDLE); break; } unlock("msgrecv"); } void subscribe(const char *name){ lock("subscribe"); StrMsg p; p.type = htonl(CS_SUBSCRIBE); strcpy(p.msg,name); request(&p,sizeof(StrMsg)); //TODO - ADD TIMEOUT setState(ST_AWAITACK); unlock("subscribe"); } void publish(const char *name,Topic& d){ lock("publish"); int size; const char *p = d.toMessage(&size,CS_PUBLISH,name); request(p,size); //TODO - ADD TIMEOUT setState(ST_AWAITACK); free((void *)p); unlock("publish"); } void simpleMsg(int msg){ lock("smlmsg"); NoDataMsg p; p.type = htonl(msg); request(&p,sizeof(NoDataMsg)); unlock("smlmsg"); } bool isIdle(){ lock("isidle"); bool e = (state == ST_IDLE); dprintf("Is idle? state=%d, so %s\n",state,e?"true":"false"); unlock("isidle"); return e; } }; /* * * * Threading stuff * * */ static pthread_t thread; static MyClient *client; static void *threadfunc(void *parameter){ running = true; while(running){ // deal with requests if(!client->update())break; } dprintf("LOOP EXITING\n"); delete client; running = false; }; static void waitForIdle(){ while(running && !client->isIdle()){ usleep(100000); } dprintf("Wait done, running=%s, isidle=%s\n",running?"T":"F", client->isIdle()?"T":"F"); } /* * * * Interface code * * */ void init(){ // get environment data or defaults const char *hn = getenv("DIAMOND_HOST"); char *hostname = NULL; if(hn)hostname = strdup(hn); const char *pr = getenv("DIAMOND_PORT"); int port = pr?atoi(pr):DEFAULTPORT; client = new MyClient(hostname?hostname:"localhost",port); pthread_create(&thread,NULL,threadfunc,NULL); if(hostname)free(hostname); while(!running){} // wait for thread } void destroy(){ running=false;// assume atomic :) pthread_cond_destroy(&getcond); pthread_mutex_destroy(&mutex); } void subscribe(const char *n){ if(!running)throw DiamondException("not connected"); Topic *t = new Topic(); topics[n]=t; client->subscribe(n); waitForIdle(); // wait for the ack } void publish(const char *name,Topic& t){ if(!running)throw DiamondException("not connected"); client->publish(name,t); waitForIdle(); // wait for the ack } void killServer(){ if(!running)throw DiamondException("not connected"); client->simpleMsg(CS_KILLSERVER); } void clearServer(){ if(!running)throw DiamondException("not connected"); client->simpleMsg(CS_CLEARSERVER); } bool isRunning(){ return running; } Topic get(const char *n,int wait){ Topic rv; if(!running){ rv.state = Topic::NotConnected; return rv; } if(topics.find(n) == topics.end()){ // topic not subscribed to rv.state = Topic::NotFound; return rv; } // we are connected and subscribed to this topic lock("gettopic"); Topic *t = topics[n]; if(t->state == Topic::NoData){ // if WaitAny, wait for data if(wait == GetWaitAny){ dprintf("No data present : entering wait\n"); while(t->state == Topic::NoData){ client->waittopic = n; // stalls until new data arrives, but unlocks mutex pthread_cond_wait(&getcond,&mutex); dprintf("Data apparently arrived!\n"); } // should now have data and mutex locked again } else { rv.state = Topic::NotFound; return rv; } } if(wait == GetWaitNew){ while(t->state != Topic::Changed){ client->waittopic = n; // stalls until new data arrives, but unlocks mutex pthread_cond_wait(&getcond,&mutex); } // should now have data and mutex locked again } rv = *t; t->state = Topic::Unchanged; unlock("gettopic"); return rv; } } <commit_msg>waitcond cleared after data waited for received.<commit_after>/** * @file clitest.cpp * @brief Brief description of file. * */ #include <pthread.h> #include <string> #include <map> #include <queue> #include "tcp.h" #include "messages.h" #include "data.h" #include "time.h" namespace diamondapparatus { /// this is the database the client writes stuff to from its thread static std::map<std::string,Topic *> topics; /// primary mutex static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; /// condition used in get-wait static pthread_cond_t getcond = PTHREAD_COND_INITIALIZER; static bool running=false; inline void lock(const char *n){ dprintf("+++Attemping to lock: %s\n",n); pthread_mutex_lock(&mutex); } inline void unlock(const char *n){ dprintf("---Unlocking: %s\n",n); pthread_mutex_unlock(&mutex); } // the states the client can be in enum ClientState { ST_IDLE, ST_AWAITACK }; class MyClient : public TCPClient { ClientState state; public: MyClient(const char *host,int port) : TCPClient(host,port){ state = ST_IDLE; } void setState(ClientState s){ dprintf("====> state = %d\n",s); state = s; } // the topic I'm waiting for in get(), if any. const char *waittopic; void notify(const char *d){ dprintf("notify at %p\n",d); const char *name = Topic::getNameFromMsg(d); if(topics.find(std::string(name)) == topics.end()){ fprintf(stderr,"Topic %s not in client set, ignoring\n",name); return; } Topic *t = topics[name]; t->fromMessage(d); t->state =Topic::Changed; t->timeLastSet = Time::now(); // if we were waiting for this, signal. if(waittopic && !strcmp(name,waittopic)){ pthread_cond_signal(&getcond); waittopic=NULL; // and zero the wait topic. } } virtual void process(uint32_t packetsize,void *packet){ lock("msgrecv"); char *p = (char *)packet; SCAck *ack; uint32_t type = ntohl(*(uint32_t *)p); dprintf("Packet type %d at %p\n",type,packet); if(type == SC_KILLCLIENT){ fprintf(stderr,"force exit\n"); running=false; } switch(state){ case ST_IDLE: if(type == SC_NOTIFY){ notify(p); } break; case ST_AWAITACK: ack = (SCAck *)p; if(type != SC_ACK) throw "unexpected packet in awaiting ack"; else if(ack->code){ dprintf("Ack code %d: %s\n",ntohs(ack->code),ack->msg); throw "bad code from ack"; } else dprintf("Acknowledged\n"); setState(ST_IDLE); break; } unlock("msgrecv"); } void subscribe(const char *name){ lock("subscribe"); StrMsg p; p.type = htonl(CS_SUBSCRIBE); strcpy(p.msg,name); request(&p,sizeof(StrMsg)); //TODO - ADD TIMEOUT setState(ST_AWAITACK); unlock("subscribe"); } void publish(const char *name,Topic& d){ lock("publish"); int size; const char *p = d.toMessage(&size,CS_PUBLISH,name); request(p,size); //TODO - ADD TIMEOUT setState(ST_AWAITACK); free((void *)p); unlock("publish"); } void simpleMsg(int msg){ lock("smlmsg"); NoDataMsg p; p.type = htonl(msg); request(&p,sizeof(NoDataMsg)); unlock("smlmsg"); } bool isIdle(){ lock("isidle"); bool e = (state == ST_IDLE); dprintf("Is idle? state=%d, so %s\n",state,e?"true":"false"); unlock("isidle"); return e; } }; /* * * * Threading stuff * * */ static pthread_t thread; static MyClient *client; static void *threadfunc(void *parameter){ running = true; while(running){ // deal with requests if(!client->update())break; } dprintf("LOOP EXITING\n"); delete client; running = false; }; static void waitForIdle(){ while(running && !client->isIdle()){ usleep(100000); } dprintf("Wait done, running=%s, isidle=%s\n",running?"T":"F", client->isIdle()?"T":"F"); } /* * * * Interface code * * */ void init(){ // get environment data or defaults const char *hn = getenv("DIAMOND_HOST"); char *hostname = NULL; if(hn)hostname = strdup(hn); const char *pr = getenv("DIAMOND_PORT"); int port = pr?atoi(pr):DEFAULTPORT; client = new MyClient(hostname?hostname:"localhost",port); pthread_create(&thread,NULL,threadfunc,NULL); if(hostname)free(hostname); while(!running){} // wait for thread } void destroy(){ running=false;// assume atomic :) pthread_cond_destroy(&getcond); pthread_mutex_destroy(&mutex); } void subscribe(const char *n){ if(!running)throw DiamondException("not connected"); Topic *t = new Topic(); topics[n]=t; client->subscribe(n); waitForIdle(); // wait for the ack } void publish(const char *name,Topic& t){ if(!running)throw DiamondException("not connected"); client->publish(name,t); waitForIdle(); // wait for the ack } void killServer(){ if(!running)throw DiamondException("not connected"); client->simpleMsg(CS_KILLSERVER); } void clearServer(){ if(!running)throw DiamondException("not connected"); client->simpleMsg(CS_CLEARSERVER); } bool isRunning(){ return running; } Topic get(const char *n,int wait){ Topic rv; if(!running){ rv.state = Topic::NotConnected; return rv; } if(topics.find(n) == topics.end()){ // topic not subscribed to rv.state = Topic::NotFound; return rv; } // we are connected and subscribed to this topic lock("gettopic"); Topic *t = topics[n]; if(t->state == Topic::NoData){ // if WaitAny, wait for data if(wait == GetWaitAny){ dprintf("No data present : entering wait\n"); while(t->state == Topic::NoData){ client->waittopic = n; // stalls until new data arrives, but unlocks mutex pthread_cond_wait(&getcond,&mutex); dprintf("Data apparently arrived!\n"); } // should now have data and mutex locked again } else { rv.state = Topic::NotFound; return rv; } } if(wait == GetWaitNew){ while(t->state != Topic::Changed){ client->waittopic = n; // stalls until new data arrives, but unlocks mutex pthread_cond_wait(&getcond,&mutex); } // should now have data and mutex locked again } rv = *t; t->state = Topic::Unchanged; unlock("gettopic"); return rv; } } <|endoftext|>
<commit_before>#include "Model/Classes/NMR_KeyStoreResourceData.h" #include "Common/NMR_Exception.h" #include <memory> namespace NMR { CKeyStoreResourceData::CKeyStoreResourceData(std::string const & path) { m_sPath = path; m_EncryptionAlgorithm = eKeyStoreEncryptAlgorithm::Aes256Gcm; } CKeyStoreResourceData::CKeyStoreResourceData(std::string const & path, eKeyStoreEncryptAlgorithm const & ea, nfBool const & compression) { m_sPath = path; m_EncryptionAlgorithm = ea; m_bCompression = compression; } PKeyStoreDecryptRight CKeyStoreResourceData::addDecryptRight(PKeyStoreDecryptRight decryptRight) { if (!decryptRight->getConsumer().get()) throw CNMRException(NMR_ERROR_INVALIDPARAM); if (m_ConsumerDecryptRight.find(decryptRight->getConsumer()->getConsumerID()) != m_ConsumerDecryptRight.end()) { throw CNMRException(NMR_ERROR_DUPLICATE_KEYSTORECONSUMER); } m_DecryptRights.push_back(decryptRight); m_ConsumerDecryptRight[decryptRight->getConsumer()->getConsumerID()] = decryptRight; return decryptRight; } PKeyStoreDecryptRight CKeyStoreResourceData::addDecryptRight(NMR::PKeyStoreConsumer const& consumer, eKeyStoreEncryptAlgorithm const& encryptAlgorithm) { NMR::CIPHERVALUE value = { 0, 0, 0 }; return this->addDecryptRight(consumer, encryptAlgorithm, value); } PKeyStoreDecryptRight CKeyStoreResourceData::addDecryptRight(NMR::PKeyStoreConsumer const& consumer, eKeyStoreEncryptAlgorithm const& encryptAlgorithm, NMR::CIPHERVALUE const& cipherValue) { if (!consumer.get()) throw CNMRException(NMR_ERROR_INVALIDPARAM); if (m_ConsumerDecryptRight.find(consumer->getConsumerID()) != m_ConsumerDecryptRight.end()) { throw CNMRException(NMR_ERROR_DUPLICATE_KEYSTORECONSUMER); } PKeyStoreDecryptRight decryptRight = std::make_shared<CKeyStoreDecryptRight>(consumer, encryptAlgorithm, cipherValue); m_DecryptRights.push_back(decryptRight); m_ConsumerDecryptRight[consumer->getConsumerID()] = decryptRight; return decryptRight; } nfUint32 CKeyStoreResourceData::getDecryptRightCount() { return (uint32_t)m_DecryptRights.size(); } PKeyStoreDecryptRight CKeyStoreResourceData::getDecryptRight(nfUint32 index) const { return m_DecryptRights[index]; } PKeyStoreDecryptRight CKeyStoreResourceData::findDecryptRightByConsumer(NMR::PKeyStoreConsumer const& consumer) { if (!consumer.get()) throw CNMRException(NMR_ERROR_INVALIDPARAM); return m_ConsumerDecryptRight[consumer->getConsumerID()]; } void CKeyStoreResourceData::removeDecryptRight(NMR::PKeyStoreConsumer const& consumer) { if (!consumer.get()) throw CNMRException(NMR_ERROR_INVALIDPARAM); size_t n = m_ConsumerDecryptRight.erase(consumer->getConsumerID()); if (n > 0) { for (auto it = m_DecryptRights.begin(); it != m_DecryptRights.end(); it++) { if ((*it)->getConsumer()->getConsumerID() == consumer->getConsumerID()) { m_DecryptRights.erase(it); } } } } eKeyStoreEncryptAlgorithm CKeyStoreResourceData::getEncryptionAlgorithm() const { return m_EncryptionAlgorithm; } nfBool CKeyStoreResourceData::getCompression() const { return m_bCompression; } NMR::PPackageModelPath CKeyStoreResourceData::getPath() const { NMR::CResourceHandler * pResourceHandler = new NMR::CResourceHandler(); return pResourceHandler->makePackageModelPath(m_sPath); } nfBool CKeyStoreResourceData::empty() const { return m_DecryptRights.empty(); CIPHERVALUE CKeyStoreResourceData::getCipherValue() const { return m_sCipherValue; } void CKeyStoreResourceData::setCipherValue(CIPHERVALUE const & cv) { m_sCipherValue = cv; m_bOpen = true; } bool CKeyStoreResourceData::isOpen() const { return m_bOpen; } } <commit_msg>SW3DRAM-975 adding missing token<commit_after>#include "Model/Classes/NMR_KeyStoreResourceData.h" #include "Common/NMR_Exception.h" #include <memory> namespace NMR { CKeyStoreResourceData::CKeyStoreResourceData(std::string const & path) { m_sPath = path; m_EncryptionAlgorithm = eKeyStoreEncryptAlgorithm::Aes256Gcm; } CKeyStoreResourceData::CKeyStoreResourceData(std::string const & path, eKeyStoreEncryptAlgorithm const & ea, nfBool const & compression) { m_sPath = path; m_EncryptionAlgorithm = ea; m_bCompression = compression; } PKeyStoreDecryptRight CKeyStoreResourceData::addDecryptRight(PKeyStoreDecryptRight decryptRight) { if (!decryptRight->getConsumer().get()) throw CNMRException(NMR_ERROR_INVALIDPARAM); if (m_ConsumerDecryptRight.find(decryptRight->getConsumer()->getConsumerID()) != m_ConsumerDecryptRight.end()) { throw CNMRException(NMR_ERROR_DUPLICATE_KEYSTORECONSUMER); } m_DecryptRights.push_back(decryptRight); m_ConsumerDecryptRight[decryptRight->getConsumer()->getConsumerID()] = decryptRight; return decryptRight; } PKeyStoreDecryptRight CKeyStoreResourceData::addDecryptRight(NMR::PKeyStoreConsumer const& consumer, eKeyStoreEncryptAlgorithm const& encryptAlgorithm) { NMR::CIPHERVALUE value = { 0, 0, 0 }; return this->addDecryptRight(consumer, encryptAlgorithm, value); } PKeyStoreDecryptRight CKeyStoreResourceData::addDecryptRight(NMR::PKeyStoreConsumer const& consumer, eKeyStoreEncryptAlgorithm const& encryptAlgorithm, NMR::CIPHERVALUE const& cipherValue) { if (!consumer.get()) throw CNMRException(NMR_ERROR_INVALIDPARAM); if (m_ConsumerDecryptRight.find(consumer->getConsumerID()) != m_ConsumerDecryptRight.end()) { throw CNMRException(NMR_ERROR_DUPLICATE_KEYSTORECONSUMER); } PKeyStoreDecryptRight decryptRight = std::make_shared<CKeyStoreDecryptRight>(consumer, encryptAlgorithm, cipherValue); m_DecryptRights.push_back(decryptRight); m_ConsumerDecryptRight[consumer->getConsumerID()] = decryptRight; return decryptRight; } nfUint32 CKeyStoreResourceData::getDecryptRightCount() { return (uint32_t)m_DecryptRights.size(); } PKeyStoreDecryptRight CKeyStoreResourceData::getDecryptRight(nfUint32 index) const { return m_DecryptRights[index]; } PKeyStoreDecryptRight CKeyStoreResourceData::findDecryptRightByConsumer(NMR::PKeyStoreConsumer const& consumer) { if (!consumer.get()) throw CNMRException(NMR_ERROR_INVALIDPARAM); return m_ConsumerDecryptRight[consumer->getConsumerID()]; } void CKeyStoreResourceData::removeDecryptRight(NMR::PKeyStoreConsumer const& consumer) { if (!consumer.get()) throw CNMRException(NMR_ERROR_INVALIDPARAM); size_t n = m_ConsumerDecryptRight.erase(consumer->getConsumerID()); if (n > 0) { for (auto it = m_DecryptRights.begin(); it != m_DecryptRights.end(); it++) { if ((*it)->getConsumer()->getConsumerID() == consumer->getConsumerID()) { m_DecryptRights.erase(it); } } } } eKeyStoreEncryptAlgorithm CKeyStoreResourceData::getEncryptionAlgorithm() const { return m_EncryptionAlgorithm; } nfBool CKeyStoreResourceData::getCompression() const { return m_bCompression; } NMR::PPackageModelPath CKeyStoreResourceData::getPath() const { NMR::CResourceHandler * pResourceHandler = new NMR::CResourceHandler(); return pResourceHandler->makePackageModelPath(m_sPath); } nfBool CKeyStoreResourceData::empty() const { return m_DecryptRights.empty(); } CIPHERVALUE CKeyStoreResourceData::getCipherValue() const { return m_sCipherValue; } void CKeyStoreResourceData::setCipherValue(CIPHERVALUE const & cv) { m_sCipherValue = cv; m_bOpen = true; } bool CKeyStoreResourceData::isOpen() const { return m_bOpen; } } <|endoftext|>
<commit_before>// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "paddle/fluid/memory/allocation/buffered_allocator.h" #include <algorithm> #include <limits> #include <utility> namespace paddle { namespace memory { namespace allocation { BufferedAllocator::BufferedAllocator(std::unique_ptr<Allocator>&& allocator) { underlying_allocator_.reset( dynamic_cast<UnmanagedAllocator*>(allocator.release())); PADDLE_ENFORCE_NOT_NULL( underlying_allocator_, "Underlying allocator of BufferedAllocator must be unmanaged"); if (underlying_allocator_->IsAllocThreadSafe()) { mtx_.reset(new std::mutex()); } } BufferedAllocator::~BufferedAllocator() { FreeCache(-1UL); } std::unique_ptr<Allocation> BufferedAllocator::Allocate(size_t size, Allocator::Attr attr) { std::unique_ptr<Allocation> result; { platform::LockGuardPtr<std::mutex> guard(mtx_); auto it = allocations_.lower_bound(size); if (it != allocations_.end() && it->first < size * 2) { result = std::move(it->second); allocations_.erase(it); } } if (result) { return result; } try { return underlying_allocator_->Allocate(size, attr); } catch (BadAlloc&) { FreeCache(size); return underlying_allocator_->Allocate(size, attr); } } void BufferedAllocator::FreeCache(size_t size) { platform::LockGuardPtr<std::mutex> guard(mtx_); if (UNLIKELY(size == 0)) return; size_t cur = 0; while (!allocations_.empty()) { // free the largest auto it = --allocations_.end(); cur += it->second->size(); underlying_allocator_->FreeUniquePtr(std::move(it->second)); allocations_.erase(it); if (cur >= size) return; } } void BufferedAllocator::FreeUniquePtr(std::unique_ptr<Allocation> allocation) { platform::LockGuardPtr<std::mutex> guard(mtx_); allocations_.emplace(allocation->size(), std::move(allocation)); } bool BufferedAllocator::IsAllocThreadSafe() const { return this->underlying_allocator_->IsAllocThreadSafe(); } } // namespace allocation } // namespace memory } // namespace paddle <commit_msg>clean buffered_allocator<commit_after>// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "paddle/fluid/memory/allocation/buffered_allocator.h" #include <algorithm> #include <limits> #include <utility> namespace paddle { namespace memory { namespace allocation { BufferedAllocator::BufferedAllocator(std::unique_ptr<Allocator>&& allocator) { underlying_allocator_.reset( dynamic_cast<UnmanagedAllocator*>(allocator.release())); PADDLE_ENFORCE_NOT_NULL( underlying_allocator_, "Underlying allocator of BufferedAllocator must be unmanaged"); if (underlying_allocator_->IsAllocThreadSafe()) { mtx_.reset(new std::mutex()); } } BufferedAllocator::~BufferedAllocator() { FreeCache(-1UL); } std::unique_ptr<Allocation> BufferedAllocator::Allocate(size_t size, Allocator::Attr attr) { { platform::LockGuardPtr<std::mutex> guard(mtx_); auto it = allocations_.lower_bound(size); if (it != allocations_.end() && it->first < size * 2) { std::unique_ptr<Allocation> result(std::move(it->second)); allocations_.erase(it); return result; } } try { return underlying_allocator_->Allocate(size, attr); } catch (BadAlloc&) { FreeCache(size); return underlying_allocator_->Allocate(size, attr); } } void BufferedAllocator::FreeCache(size_t size) { platform::LockGuardPtr<std::mutex> guard(mtx_); if (UNLIKELY(size == 0)) return; size_t cur = 0; while (!allocations_.empty()) { // free the largest auto it = --allocations_.end(); cur += it->second->size(); underlying_allocator_->FreeUniquePtr(std::move(it->second)); allocations_.erase(it); if (cur >= size) return; } } void BufferedAllocator::FreeUniquePtr(std::unique_ptr<Allocation> allocation) { platform::LockGuardPtr<std::mutex> guard(mtx_); allocations_.emplace(allocation->size(), std::move(allocation)); } bool BufferedAllocator::IsAllocThreadSafe() const { return this->underlying_allocator_->IsAllocThreadSafe(); } } // namespace allocation } // namespace memory } // namespace paddle <|endoftext|>
<commit_before>// Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/MIRIAMUI/CQMiriamWidget.cpp,v $ // $Revision: 1.17 $ // $Name: $ // $Author: aekamal $ // $Date: 2009/09/28 14:53:30 $ // End CVS Header // Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. #include <QMessageBox> #include <QHeaderView> #include <QClipboard> #include "CQMiriamWidget.h" #include "copasi.h" #include "UI/qtUtilities.h" #include "MIRIAM/CModelMIRIAMInfo.h" #include "report/CCopasiRootContainer.h" #include "commandline/CConfigurationFile.h" /* * Constructs a CQMiriamWidget which is a child of 'parent', with the * name 'name'.' */ CQMiriamWidget::CQMiriamWidget(QWidget* parent, const char* name) : CopasiWidget(parent, name) { setupUi(this); // Create the MIRIAM Info mpMIRIAMInfo = new CMIRIAMInfo(); //Create Data Models for the 4 tables mpCreatorDM = new CQCreatorDM(mpMIRIAMInfo, this); mpReferenceDM = new CQReferenceDM(mpMIRIAMInfo, this); mpBiologicalDescriptionDM = new CQBiologicalDescriptionDM(mpMIRIAMInfo, this); mpModifiedDM = new CQModifiedDM(mpMIRIAMInfo, this); //Create Proxy Data Models for the 4 tables mpCreatorPDM = new CQSortFilterProxyModel(); mpReferencePDM = new CQSortFilterProxyModel(); mpBiologicalDescriptionPDM = new CQSortFilterProxyModel(); mpModifiedPDM = new CQSortFilterProxyModel(); //Create Required Delegates mpResourceDelegate1 = new CQComboDelegate(&mResources, this); mpTblReferences->setItemDelegateForColumn(COL_RESOURCE_REFERENCE, mpResourceDelegate1); mpResourceDelegate2 = new CQComboDelegate(&mReferences, this); mpTblDescription->setItemDelegateForColumn(COL_RESOURCE_BD, mpResourceDelegate2); mpPredicateDelegate = new CQComboDelegate(&mPredicates, this); mpTblDescription->setItemDelegateForColumn(COL_RELATIONSHIP, mpPredicateDelegate); mWidgets.push_back(mpTblAuthors); mDMs.push_back(mpCreatorDM); mProxyDMs.push_back(mpCreatorPDM); mWidgets.push_back(mpTblReferences); mDMs.push_back(mpReferenceDM); mProxyDMs.push_back(mpReferencePDM); mWidgets.push_back(mpTblDescription); mDMs.push_back(mpBiologicalDescriptionDM); mProxyDMs.push_back(mpBiologicalDescriptionPDM); mWidgets.push_back(mpTblModified); mDMs.push_back(mpModifiedDM); mProxyDMs.push_back(mpModifiedPDM); // Build the list of supported predicates mPredicates.push_back("-- select --"); mPredicates.push_back(FROM_UTF8(CRDFPredicate::getDisplayName(CRDFPredicate::copasi_encodes))); mPredicates.push_back(FROM_UTF8(CRDFPredicate::getDisplayName(CRDFPredicate::copasi_hasPart))); mPredicates.push_back(FROM_UTF8(CRDFPredicate::getDisplayName(CRDFPredicate::copasi_hasVersion))); mPredicates.push_back(FROM_UTF8(CRDFPredicate::getDisplayName(CRDFPredicate::copasi_is))); mPredicates.push_back(FROM_UTF8(CRDFPredicate::getDisplayName(CRDFPredicate::copasi_isEncodedBy))); mPredicates.push_back(FROM_UTF8(CRDFPredicate::getDisplayName(CRDFPredicate::copasi_isHomologTo))); mPredicates.push_back(FROM_UTF8(CRDFPredicate::getDisplayName(CRDFPredicate::copasi_isPartOf))); mPredicates.push_back(FROM_UTF8(CRDFPredicate::getDisplayName(CRDFPredicate::copasi_isVersionOf))); std::vector<QTableView*>::const_iterator it = mWidgets.begin(); std::vector<QTableView*>::const_iterator end = mWidgets.end(); std::vector<CQBaseDataModel*>::const_iterator itDM = mDMs.begin(); std::vector<CQBaseDataModel*>::const_iterator endDM = mDMs.end(); std::vector<CQSortFilterProxyModel*>::const_iterator itPDM = mProxyDMs.begin(); std::vector<CQSortFilterProxyModel*>::const_iterator endPDM = mProxyDMs.end(); for (; it != end && itDM != endDM && itPDM != endPDM; it++, itDM++, itPDM++) { //Set Proxy Data Model properties (*itPDM)->setDynamicSortFilter(true); (*itPDM)->setSortCaseSensitivity(Qt::CaseInsensitive); (*it)->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents); (*it)->verticalHeader()->hide(); (*it)->sortByColumn(COL_ROW_NUMBER, Qt::AscendingOrder); connect((*itDM), SIGNAL(notifyGUI(ListViews::ObjectType, ListViews::Action, const std::string)), this, SLOT(protectedNotify(ListViews::ObjectType, ListViews::Action, const std::string))); connect((*itDM), SIGNAL(dataChanged(const QModelIndex&, const QModelIndex&)), this, SLOT(dataChanged(const QModelIndex&, const QModelIndex&))); } // Build the list of known resources updateResourcesList(); } /* * Destroys the object and frees any allocated resources */ CQMiriamWidget::~CQMiriamWidget() { pdelete(mpCreatorPDM); pdelete(mpReferencePDM); pdelete(mpBiologicalDescriptionPDM); pdelete(mpModifiedPDM); pdelete(mpCreatorDM); pdelete(mpReferenceDM); pdelete(mpBiologicalDescriptionDM); pdelete(mpModifiedDM); pdelete(mpResourceDelegate1); pdelete(mpResourceDelegate2); pdelete(mpPredicateDelegate); pdelete(mpMIRIAMInfo); // no need to delete child widgets, Qt does it all for us } /* * Sets the strings of the subwidgets using the current * language. */ void CQMiriamWidget::languageChange() { retranslateUi(this); } void CQMiriamWidget::slotBtnDeleteClicked() { if (mpTblAuthors->hasFocus()) {deleteSelectedAuthors();} else if (mpTblReferences->hasFocus()) {deleteSelectedReferences();} else if (mpTblModified->hasFocus()) {deleteSelectedModifieds();} else if (mpTblDescription->hasFocus()) {deleteSelectedBiologicalDescriptions();} } void CQMiriamWidget::deleteSelectedAuthors() { QModelIndexList selRows = mpTblAuthors->selectionModel()->selectedRows(0); if (selRows.empty()) {return;} QModelIndexList mappedSelRows; QModelIndexList::const_iterator i; for (i = selRows.begin(); i != selRows.end(); ++i) {mappedSelRows.append(mpCreatorPDM->mapToSource(*i));} mpCreatorDM->removeRows(mappedSelRows); } void CQMiriamWidget::deleteSelectedReferences() { QModelIndexList selRows = mpTblReferences->selectionModel()->selectedRows(0); if (selRows.empty()) {return;} QModelIndexList mappedSelRows; QModelIndexList::const_iterator i; for (i = selRows.begin(); i != selRows.end(); ++i) {mappedSelRows.append(mpReferencePDM->mapToSource(*i));} mpReferenceDM->removeRows(mappedSelRows); } void CQMiriamWidget::deleteSelectedBiologicalDescriptions() { QModelIndexList selRows = mpTblDescription->selectionModel()->selectedRows(0); if (selRows.empty()) {return;} QModelIndexList mappedSelRows; QModelIndexList::const_iterator i; for (i = selRows.begin(); i != selRows.end(); ++i) {mappedSelRows.append(mpBiologicalDescriptionPDM->mapToSource(*i));} mpBiologicalDescriptionDM->removeRows(mappedSelRows); } void CQMiriamWidget::deleteSelectedModifieds() { QModelIndexList selRows = mpTblModified->selectionModel()->selectedRows(0); if (selRows.empty()) {return;} QModelIndexList mappedSelRows; QModelIndexList::const_iterator i; for (i = selRows.begin(); i != selRows.end(); ++i) {mappedSelRows.append(mpModifiedPDM->mapToSource(*i));} mpModifiedDM->removeRows(mappedSelRows); } void CQMiriamWidget::slotBtnClearClicked() { if (mpDTCreated->hasFocus()) { mpDTCreated->setDateTime(QDateTime::currentDateTime()); return; } if (mpTblAuthors->hasFocus()) { int ret = QMessageBox::question(this, tr("Confirm Delete"), "Delete all Creators?", QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (ret == QMessageBox::Yes) { mpCreatorDM->clear(); } } else if (mpTblReferences->hasFocus()) { int ret = QMessageBox::question(this, tr("Confirm Delete"), "Delete all References?", QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (ret == QMessageBox::Yes) { mpReferenceDM->clear(); } } else if (mpTblDescription->hasFocus()) { int ret = QMessageBox::question(this, tr("Confirm Delete"), "Delete all Descriptions?", QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (ret == QMessageBox::Yes) { mpBiologicalDescriptionDM->clear(); } } else if (mpTblModified->hasFocus()) { int ret = QMessageBox::question(this, tr("Confirm Delete"), "Delete all Date/Time Modifieds?", QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (ret == QMessageBox::Yes) { mpModifiedDM->clear(); } } } bool CQMiriamWidget::update(ListViews::ObjectType objectType, ListViews::Action C_UNUSED(action), const std::string & key) { if (getIgnoreUpdates()) return true; if (objectType != ListViews::MIRIAM) return true; if (key != mpMIRIAMInfo->getKey()) return true; bool success = true; mpMIRIAMInfo->load(key); if (mpMIRIAMInfo->getCreatedDT() != "") mpDTCreated->setDateTime(QDateTime::fromString(FROM_UTF8(mpMIRIAMInfo->getCreatedDT()), Qt::ISODate)); return success; } void CQMiriamWidget::slotCreatedDTChanged(QDateTime newDT) { //Now update. // Created at std::string DT = ""; if (newDT.isValid()) { DT = TO_UTF8(newDT.toString(Qt::ISODate)); DT += "Z"; if (DT != mpMIRIAMInfo->getCreatedDT()) { mpMIRIAMInfo->setCreatedDT(DT); } } } bool CQMiriamWidget::enterProtected() { mpMIRIAMInfo->load(mKey); //Set Models for the 4 TableViews std::vector<QTableView*>::const_iterator it = mWidgets.begin(); std::vector<QTableView*>::const_iterator end = mWidgets.end(); std::vector<CQBaseDataModel*>::const_iterator itDM = mDMs.begin(); std::vector<CQBaseDataModel*>::const_iterator endDM = mDMs.end(); std::vector<CQSortFilterProxyModel*>::const_iterator itPDM = mProxyDMs.begin(); std::vector<CQSortFilterProxyModel*>::const_iterator endPDM = mProxyDMs.end(); for (; it != end && itDM != endDM && itPDM != endPDM; it++, itDM++, itPDM++) { (*itPDM)->setSourceModel(*itDM); (*it)->setModel(NULL); (*it)->setModel(*itPDM); (*it)->resizeColumnsToContents(); } QDateTime DTCreated; if (mpMIRIAMInfo->getCreatedDT() != "") DTCreated = QDateTime::fromString(FROM_UTF8(mpMIRIAMInfo->getCreatedDT()), Qt::ISODate); if (DTCreated.isValid()) mpDTCreated->setDateTime(DTCreated); else { mpDTCreated->setDateTime(QDateTime::currentDateTime()); } return true; } bool CQMiriamWidget::leave() { mpMIRIAMInfo->save(); return true; } const CMIRIAMInfo & CQMiriamWidget::getMIRIAMInfo() const {return *mpMIRIAMInfo;} void CQMiriamWidget::updateResourcesList() { mResources.clear(); mReferences.clear(); // Build the list of known resources assert(CCopasiRootContainer::getDatamodelList()->size() > 0); const CMIRIAMResources * pResource = &CCopasiRootContainer::getConfiguration()->getRecentMIRIAMResources(); mResources.push_back("-- select --"); mReferences.push_back("-- select --"); unsigned C_INT32 i, imax = pResource->getResourceList().size(); for (i = 0; i < imax; i++) if (pResource->getMIRIAMResource(i).getMIRIAMCitation()) mResources.push_back(FROM_UTF8(pResource->getMIRIAMResource(i).getMIRIAMDisplayName())); else mReferences.push_back(FROM_UTF8(pResource->getMIRIAMResource(i).getMIRIAMDisplayName())); } void CQMiriamWidget::keyPressEvent(QKeyEvent* ev) { if (ev->key() == Qt::Key_Delete) slotBtnDeleteClicked(); else if (ev->key() == Qt::Key_C && ev->modifiers() & Qt::ControlModifier) slotCopyEvent(); } void CQMiriamWidget::dataChanged(const QModelIndex& C_UNUSED(topLeft), const QModelIndex& C_UNUSED(bottomRight)) { std::vector<QTableView*>::const_iterator it = mWidgets.begin(); std::vector<QTableView*>::const_iterator end = mWidgets.end(); for (; it != end; it++) (*it)->resizeColumnsToContents(); } void CQMiriamWidget::slotCopyEvent() { CQSortFilterProxyModel* pProxyModel = NULL; CQBaseDataModel* pBaseDM = NULL; QTableView* pTbl = NULL; if (mpTblAuthors->hasFocus()) { pProxyModel = mpCreatorPDM; pBaseDM = mpCreatorDM; pTbl = mpTblAuthors; } else if (mpTblReferences->hasFocus()) { pProxyModel = mpReferencePDM; pBaseDM = mpReferenceDM; pTbl = mpTblReferences; } else if (mpTblModified->hasFocus()) { pProxyModel = mpModifiedPDM; pBaseDM = mpModifiedDM; pTbl = mpTblModified; } else if (mpTblDescription->hasFocus()) { pProxyModel = mpBiologicalDescriptionPDM; pBaseDM = mpBiologicalDescriptionDM; pTbl = mpTblDescription; } QModelIndexList selRows = pTbl->selectionModel()->selectedRows(0); if (selRows.empty()) {return;} QString str; QModelIndexList::const_iterator i; for (i = selRows.begin(); i != selRows.end(); ++i) { for (int x = 0; x < pBaseDM->columnCount(); ++x) { if (!pTbl->isColumnHidden(x)) { if (!str.isEmpty()) str += "\t"; str += pBaseDM->index(pProxyModel->mapToSource(*i).row(), x).data().toString(); } } str += "\n"; } QApplication::clipboard()->setText(str); } <commit_msg>Fixed crash when creating a new table entry.<commit_after>// Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/MIRIAMUI/CQMiriamWidget.cpp,v $ // $Revision: 1.18 $ // $Name: $ // $Author: shoops $ // $Date: 2009/11/06 16:02:39 $ // End CVS Header // Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. #include <QMessageBox> #include <QHeaderView> #include <QClipboard> #include "CQMiriamWidget.h" #include "copasi.h" #include "UI/qtUtilities.h" #include "MIRIAM/CModelMIRIAMInfo.h" #include "report/CCopasiRootContainer.h" #include "commandline/CConfigurationFile.h" /* * Constructs a CQMiriamWidget which is a child of 'parent', with the * name 'name'.' */ CQMiriamWidget::CQMiriamWidget(QWidget* parent, const char* name) : CopasiWidget(parent, name) { setupUi(this); // Create the MIRIAM Info mpMIRIAMInfo = new CMIRIAMInfo(); //Create Data Models for the 4 tables mpCreatorDM = new CQCreatorDM(mpMIRIAMInfo, this); mpReferenceDM = new CQReferenceDM(mpMIRIAMInfo, this); mpBiologicalDescriptionDM = new CQBiologicalDescriptionDM(mpMIRIAMInfo, this); mpModifiedDM = new CQModifiedDM(mpMIRIAMInfo, this); //Create Proxy Data Models for the 4 tables mpCreatorPDM = new CQSortFilterProxyModel(); mpReferencePDM = new CQSortFilterProxyModel(); mpBiologicalDescriptionPDM = new CQSortFilterProxyModel(); mpModifiedPDM = new CQSortFilterProxyModel(); //Create Required Delegates mpResourceDelegate1 = new CQComboDelegate(&mResources, this); mpTblReferences->setItemDelegateForColumn(COL_RESOURCE_REFERENCE, mpResourceDelegate1); mpResourceDelegate2 = new CQComboDelegate(&mReferences, this); mpTblDescription->setItemDelegateForColumn(COL_RESOURCE_BD, mpResourceDelegate2); mpPredicateDelegate = new CQComboDelegate(&mPredicates, this); mpTblDescription->setItemDelegateForColumn(COL_RELATIONSHIP, mpPredicateDelegate); mWidgets.push_back(mpTblAuthors); mDMs.push_back(mpCreatorDM); mProxyDMs.push_back(mpCreatorPDM); mWidgets.push_back(mpTblReferences); mDMs.push_back(mpReferenceDM); mProxyDMs.push_back(mpReferencePDM); mWidgets.push_back(mpTblDescription); mDMs.push_back(mpBiologicalDescriptionDM); mProxyDMs.push_back(mpBiologicalDescriptionPDM); mWidgets.push_back(mpTblModified); mDMs.push_back(mpModifiedDM); mProxyDMs.push_back(mpModifiedPDM); // Build the list of supported predicates mPredicates.push_back("-- select --"); mPredicates.push_back(FROM_UTF8(CRDFPredicate::getDisplayName(CRDFPredicate::copasi_encodes))); mPredicates.push_back(FROM_UTF8(CRDFPredicate::getDisplayName(CRDFPredicate::copasi_hasPart))); mPredicates.push_back(FROM_UTF8(CRDFPredicate::getDisplayName(CRDFPredicate::copasi_hasVersion))); mPredicates.push_back(FROM_UTF8(CRDFPredicate::getDisplayName(CRDFPredicate::copasi_is))); mPredicates.push_back(FROM_UTF8(CRDFPredicate::getDisplayName(CRDFPredicate::copasi_isEncodedBy))); mPredicates.push_back(FROM_UTF8(CRDFPredicate::getDisplayName(CRDFPredicate::copasi_isHomologTo))); mPredicates.push_back(FROM_UTF8(CRDFPredicate::getDisplayName(CRDFPredicate::copasi_isPartOf))); mPredicates.push_back(FROM_UTF8(CRDFPredicate::getDisplayName(CRDFPredicate::copasi_isVersionOf))); std::vector<QTableView*>::const_iterator it = mWidgets.begin(); std::vector<QTableView*>::const_iterator end = mWidgets.end(); std::vector<CQBaseDataModel*>::const_iterator itDM = mDMs.begin(); std::vector<CQBaseDataModel*>::const_iterator endDM = mDMs.end(); std::vector<CQSortFilterProxyModel*>::const_iterator itPDM = mProxyDMs.begin(); std::vector<CQSortFilterProxyModel*>::const_iterator endPDM = mProxyDMs.end(); for (; it != end && itDM != endDM && itPDM != endPDM; it++, itDM++, itPDM++) { //Set Proxy Data Model properties (*itPDM)->setDynamicSortFilter(true); (*itPDM)->setSortCaseSensitivity(Qt::CaseInsensitive); (*it)->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents); (*it)->verticalHeader()->hide(); (*it)->sortByColumn(COL_ROW_NUMBER, Qt::AscendingOrder); connect((*itDM), SIGNAL(notifyGUI(ListViews::ObjectType, ListViews::Action, const std::string)), this, SLOT(protectedNotify(ListViews::ObjectType, ListViews::Action, const std::string))); connect((*itDM), SIGNAL(dataChanged(const QModelIndex&, const QModelIndex&)), this, SLOT(dataChanged(const QModelIndex&, const QModelIndex&))); } // Build the list of known resources updateResourcesList(); } /* * Destroys the object and frees any allocated resources */ CQMiriamWidget::~CQMiriamWidget() { pdelete(mpCreatorPDM); pdelete(mpReferencePDM); pdelete(mpBiologicalDescriptionPDM); pdelete(mpModifiedPDM); pdelete(mpCreatorDM); pdelete(mpReferenceDM); pdelete(mpBiologicalDescriptionDM); pdelete(mpModifiedDM); pdelete(mpResourceDelegate1); pdelete(mpResourceDelegate2); pdelete(mpPredicateDelegate); pdelete(mpMIRIAMInfo); // no need to delete child widgets, Qt does it all for us } /* * Sets the strings of the subwidgets using the current * language. */ void CQMiriamWidget::languageChange() { retranslateUi(this); } void CQMiriamWidget::slotBtnDeleteClicked() { if (mpTblAuthors->hasFocus()) {deleteSelectedAuthors();} else if (mpTblReferences->hasFocus()) {deleteSelectedReferences();} else if (mpTblModified->hasFocus()) {deleteSelectedModifieds();} else if (mpTblDescription->hasFocus()) {deleteSelectedBiologicalDescriptions();} } void CQMiriamWidget::deleteSelectedAuthors() { QModelIndexList selRows = mpTblAuthors->selectionModel()->selectedRows(0); if (selRows.empty()) {return;} QModelIndexList mappedSelRows; QModelIndexList::const_iterator i; for (i = selRows.begin(); i != selRows.end(); ++i) {mappedSelRows.append(mpCreatorPDM->mapToSource(*i));} mpCreatorDM->removeRows(mappedSelRows); } void CQMiriamWidget::deleteSelectedReferences() { QModelIndexList selRows = mpTblReferences->selectionModel()->selectedRows(0); if (selRows.empty()) {return;} QModelIndexList mappedSelRows; QModelIndexList::const_iterator i; for (i = selRows.begin(); i != selRows.end(); ++i) {mappedSelRows.append(mpReferencePDM->mapToSource(*i));} mpReferenceDM->removeRows(mappedSelRows); } void CQMiriamWidget::deleteSelectedBiologicalDescriptions() { QModelIndexList selRows = mpTblDescription->selectionModel()->selectedRows(0); if (selRows.empty()) {return;} QModelIndexList mappedSelRows; QModelIndexList::const_iterator i; for (i = selRows.begin(); i != selRows.end(); ++i) {mappedSelRows.append(mpBiologicalDescriptionPDM->mapToSource(*i));} mpBiologicalDescriptionDM->removeRows(mappedSelRows); } void CQMiriamWidget::deleteSelectedModifieds() { QModelIndexList selRows = mpTblModified->selectionModel()->selectedRows(0); if (selRows.empty()) {return;} QModelIndexList mappedSelRows; QModelIndexList::const_iterator i; for (i = selRows.begin(); i != selRows.end(); ++i) {mappedSelRows.append(mpModifiedPDM->mapToSource(*i));} mpModifiedDM->removeRows(mappedSelRows); } void CQMiriamWidget::slotBtnClearClicked() { if (mpDTCreated->hasFocus()) { mpDTCreated->setDateTime(QDateTime::currentDateTime()); return; } if (mpTblAuthors->hasFocus()) { int ret = QMessageBox::question(this, tr("Confirm Delete"), "Delete all Creators?", QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (ret == QMessageBox::Yes) { mpCreatorDM->clear(); } } else if (mpTblReferences->hasFocus()) { int ret = QMessageBox::question(this, tr("Confirm Delete"), "Delete all References?", QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (ret == QMessageBox::Yes) { mpReferenceDM->clear(); } } else if (mpTblDescription->hasFocus()) { int ret = QMessageBox::question(this, tr("Confirm Delete"), "Delete all Descriptions?", QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (ret == QMessageBox::Yes) { mpBiologicalDescriptionDM->clear(); } } else if (mpTblModified->hasFocus()) { int ret = QMessageBox::question(this, tr("Confirm Delete"), "Delete all Date/Time Modifieds?", QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (ret == QMessageBox::Yes) { mpModifiedDM->clear(); } } } bool CQMiriamWidget::update(ListViews::ObjectType objectType, ListViews::Action C_UNUSED(action), const std::string & key) { if (getIgnoreUpdates()) return true; if (objectType != ListViews::MIRIAM) return true; if (key == "" || key != mpMIRIAMInfo->getKey()) return true; bool success = true; mpMIRIAMInfo->load(key); if (mpMIRIAMInfo->getCreatedDT() != "") mpDTCreated->setDateTime(QDateTime::fromString(FROM_UTF8(mpMIRIAMInfo->getCreatedDT()), Qt::ISODate)); return success; } void CQMiriamWidget::slotCreatedDTChanged(QDateTime newDT) { //Now update. // Created at std::string DT = ""; if (newDT.isValid()) { DT = TO_UTF8(newDT.toString(Qt::ISODate)); DT += "Z"; if (DT != mpMIRIAMInfo->getCreatedDT()) { mpMIRIAMInfo->setCreatedDT(DT); } } } bool CQMiriamWidget::enterProtected() { mpMIRIAMInfo->load(mKey); //Set Models for the 4 TableViews std::vector<QTableView*>::const_iterator it = mWidgets.begin(); std::vector<QTableView*>::const_iterator end = mWidgets.end(); std::vector<CQBaseDataModel*>::const_iterator itDM = mDMs.begin(); std::vector<CQBaseDataModel*>::const_iterator endDM = mDMs.end(); std::vector<CQSortFilterProxyModel*>::const_iterator itPDM = mProxyDMs.begin(); std::vector<CQSortFilterProxyModel*>::const_iterator endPDM = mProxyDMs.end(); for (; it != end && itDM != endDM && itPDM != endPDM; it++, itDM++, itPDM++) { (*itPDM)->setSourceModel(*itDM); (*it)->setModel(NULL); (*it)->setModel(*itPDM); (*it)->resizeColumnsToContents(); } QDateTime DTCreated; if (mpMIRIAMInfo->getCreatedDT() != "") DTCreated = QDateTime::fromString(FROM_UTF8(mpMIRIAMInfo->getCreatedDT()), Qt::ISODate); if (DTCreated.isValid()) mpDTCreated->setDateTime(DTCreated); else { mpDTCreated->setDateTime(QDateTime::currentDateTime()); } return true; } bool CQMiriamWidget::leave() { mpMIRIAMInfo->save(); return true; } const CMIRIAMInfo & CQMiriamWidget::getMIRIAMInfo() const {return *mpMIRIAMInfo;} void CQMiriamWidget::updateResourcesList() { mResources.clear(); mReferences.clear(); // Build the list of known resources assert(CCopasiRootContainer::getDatamodelList()->size() > 0); const CMIRIAMResources * pResource = &CCopasiRootContainer::getConfiguration()->getRecentMIRIAMResources(); mResources.push_back("-- select --"); mReferences.push_back("-- select --"); unsigned C_INT32 i, imax = pResource->getResourceList().size(); for (i = 0; i < imax; i++) if (pResource->getMIRIAMResource(i).getMIRIAMCitation()) mResources.push_back(FROM_UTF8(pResource->getMIRIAMResource(i).getMIRIAMDisplayName())); else mReferences.push_back(FROM_UTF8(pResource->getMIRIAMResource(i).getMIRIAMDisplayName())); } void CQMiriamWidget::keyPressEvent(QKeyEvent* ev) { if (ev->key() == Qt::Key_Delete) slotBtnDeleteClicked(); else if (ev->key() == Qt::Key_C && ev->modifiers() & Qt::ControlModifier) slotCopyEvent(); } void CQMiriamWidget::dataChanged(const QModelIndex& C_UNUSED(topLeft), const QModelIndex& C_UNUSED(bottomRight)) { std::vector<QTableView*>::const_iterator it = mWidgets.begin(); std::vector<QTableView*>::const_iterator end = mWidgets.end(); for (; it != end; it++) (*it)->resizeColumnsToContents(); } void CQMiriamWidget::slotCopyEvent() { CQSortFilterProxyModel* pProxyModel = NULL; CQBaseDataModel* pBaseDM = NULL; QTableView* pTbl = NULL; if (mpTblAuthors->hasFocus()) { pProxyModel = mpCreatorPDM; pBaseDM = mpCreatorDM; pTbl = mpTblAuthors; } else if (mpTblReferences->hasFocus()) { pProxyModel = mpReferencePDM; pBaseDM = mpReferenceDM; pTbl = mpTblReferences; } else if (mpTblModified->hasFocus()) { pProxyModel = mpModifiedPDM; pBaseDM = mpModifiedDM; pTbl = mpTblModified; } else if (mpTblDescription->hasFocus()) { pProxyModel = mpBiologicalDescriptionPDM; pBaseDM = mpBiologicalDescriptionDM; pTbl = mpTblDescription; } QModelIndexList selRows = pTbl->selectionModel()->selectedRows(0); if (selRows.empty()) {return;} QString str; QModelIndexList::const_iterator i; for (i = selRows.begin(); i != selRows.end(); ++i) { for (int x = 0; x < pBaseDM->columnCount(); ++x) { if (!pTbl->isColumnHidden(x)) { if (!str.isEmpty()) str += "\t"; str += pBaseDM->index(pProxyModel->mapToSource(*i).row(), x).data().toString(); } } str += "\n"; } QApplication::clipboard()->setText(str); } <|endoftext|>
<commit_before>/* * Copyright (c) 2015 The Jackson Laboratory * * This software was developed by Gary Churchill's Lab at The Jackson * Laboratory (see http://research.jax.org/faculty/churchill). * * This is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software. If not, see <http://www.gnu.org/licenses/>. */ // // populase.cpp // // // Created by Glen Beane on 8/20/14. // // #include <iostream> #include <getopt.h> #include "alignment_incidence_matrix.h" #include "sample_allelic_expression.h" #include "python_interface.h" void print_help(); int main(int argc, char **argv) { clock_t t1, t2; float diff; int num_iterations; int max_iterations = 200; int read_length = 100; SampleAllelicExpression::model model = SampleAllelicExpression::MODEL_2; int m; std::string input_filename; std::string output_filename; std::string transcript_length_file; std::string extension = ".pcl.bz2"; //getopt related variables opterr = 0; int c; int option_index = 0; static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"model", required_argument, 0, 'm'}, {"output", required_argument, 0, 'o'}, {"read-length", required_argument, 0, 'k'}, {"transcript-lengths", required_argument, 0, 'l'}, {"max-iterations", required_argument, 0, 'i'}, {0, 0, 0, 0} }; while ((c = getopt_long(argc, argv, "hm:o:k:l:i:", long_options, &option_index)) != -1) { switch (c) { case 'h': print_help(); return 0; case 'm': m = std::stoi(optarg); if (m < 1 || m > 4) { std::cerr << "Invalid model number specified. Valid options: 1, 2, 3, 4\n"; } switch (m) { case 1: model = SampleAllelicExpression::MODEL_1; break; case 2: model = SampleAllelicExpression::MODEL_2; break; case 3: std::cerr << "Model 3 is currently unimplemented, please specify a different model\n"; return 1; case 4: model = SampleAllelicExpression::MODEL_4; break; } break; case 'o': output_filename = std::string(optarg); break; case 'k': read_length = std::stoi(optarg); break; case 'l': transcript_length_file = std::string(optarg); break; case 'i': max_iterations = std::stoi(optarg); } } input_filename = argv[optind]; if (extension.size() >= input_filename.size() || !std::equal(extension.rbegin(), extension.rend(), input_filename.rbegin())) { std::cerr << "Error, expected file with .pcl.bz2 extension. Input file should be prepared with bam_to_pcl.py script.\n"; return 1; } if (output_filename.empty()) { //use default, based on the input file name but placed in current working directdory output_filename = input_filename.substr(0, input_filename.size() - extension.size()).append(".stacksum.tsv"); //check to see if there was a path in the input file name. If so, trim it off std::size_t found = output_filename.rfind('/'); if (found != std::string::npos) { output_filename = output_filename.substr(found+1); } } PythonInterface pi = PythonInterface(); if (pi.init()){ std::cerr << "Error importing TranscriptHits Python module.\n"; std::cerr << '\t' << pi.getErrorString() << std::endl; return 1; } std::cout << "Loading " << input_filename << ". This may take a while..." << std::endl; AlignmentIncidenceMatrix *aim = pi.load(input_filename); if (!aim) { std::cerr << "Error loading pcl file\n"; std::cerr << '\t' << pi.getErrorString() << std::endl; return 1; } std::cout << "Loaded Pickled Alignment Incidence file " << input_filename << std::endl; std::vector<std::string> hap_names = aim->get_haplotype_names(); std::cout << "File had the following haplotype names:\n"; for (std::vector<std::string>::iterator it = hap_names.begin(); it != hap_names.end(); ++it) { std::cout << *it << "\t"; } std::cout << std::endl; std::cout << aim->num_reads() << " reads loaded\n"; std::cout << aim->num_transcripts() << " transcripts\n"; std::cout << std::endl; if (!transcript_length_file.empty()) { std::cout << "Loading Transcript Length File " << transcript_length_file << std::endl; aim->loadTranscriptLengths(transcript_length_file); } if (model != SampleAllelicExpression::MODEL_4 && !aim->has_gene_mappings()) { std::cerr << "File does not contain transcript to gene mapping information. Only normalization Model 4 can be used.\n"; return 1; } t1 = clock(); SampleAllelicExpression sae(aim, read_length); t2 = clock(); diff = ((float)t2-(float)t1)/CLOCKS_PER_SEC; std::cout << "Time for initializing stack sum = " << diff << "s" << std::endl; if (max_iterations > 0) { num_iterations = 0; std::cout << "Beginning EM Iterations" << std::endl; t1 = clock(); do { sae.update(model); } while (++num_iterations < max_iterations && !sae.converged()); t2 = clock(); diff = ((float)t2-(float)t1)/CLOCKS_PER_SEC; std::cout << "Time for " << num_iterations << " iterations = " << diff << "s\n"; std::cout << "Time per iteration " << diff/num_iterations << "s\n"; } std::cout << "Saving results to " << output_filename << std::endl; sae.saveStackSums(output_filename); std::cout << "Done.\n"; return 0; } void print_help() { std::cout << "EMASE Help\n\n" << "USAGE: emase [options] <alignment_incidence>\n\n" << "INPUT: Alignment Incidence file prepared with bam_to_pcl.py script\n\n" << "OPTIONS\n" << " --model (-m) : Specify normalization model (can be 1-4, default=2)\n" << " --output (-o) : Specify filename for output file (default is input_basename.stacksum.tsv)\n" << " --transcript-lengths (-l) : Filename for transcript length file. Format is \"transcript_id\tlength\"\n" << " --read-length (-k) : Specify read length for use when applying transcript length adjustment.\n" << " Ignored unless combined with --transcript-lengths. (Default 100)\n" << " --max-iterations (-i) : Specify the maximum number of EM iterations. (Default 200)\n" << " --help (-h) : Print this message and exit\n\n"; } <commit_msg>do some checking of args, avoid segfaulting if user does not pass filename!<commit_after>/* * Copyright (c) 2015 The Jackson Laboratory * * This software was developed by Gary Churchill's Lab at The Jackson * Laboratory (see http://research.jax.org/faculty/churchill). * * This is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software. If not, see <http://www.gnu.org/licenses/>. */ // // populase.cpp // // // Created by Glen Beane on 8/20/14. // // #include <iostream> #include <getopt.h> #include "alignment_incidence_matrix.h" #include "sample_allelic_expression.h" #include "python_interface.h" void print_help(); int main(int argc, char **argv) { clock_t t1, t2; float diff; int num_iterations; int max_iterations = 200; int read_length = 100; SampleAllelicExpression::model model = SampleAllelicExpression::MODEL_2; int m; std::string input_filename; std::string output_filename; std::string transcript_length_file; std::string extension = ".pcl.bz2"; //getopt related variables int c; int option_index = 0; int bad_args = 0; static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"model", required_argument, 0, 'm'}, {"output", required_argument, 0, 'o'}, {"read-length", required_argument, 0, 'k'}, {"transcript-lengths", required_argument, 0, 'l'}, {"max-iterations", required_argument, 0, 'i'}, {0, 0, 0, 0} }; while ((c = getopt_long(argc, argv, "hm:o:k:l:i:", long_options, &option_index)) != -1) { switch (c) { case 'h': print_help(); return 0; case 'm': m = std::stoi(optarg); if (m < 1 || m > 4) { std::cerr << "Invalid model number specified. Valid options: 1, 2, 3, 4\n"; } switch (m) { case 1: model = SampleAllelicExpression::MODEL_1; break; case 2: model = SampleAllelicExpression::MODEL_2; break; case 3: std::cerr << "Model 3 is currently unimplemented, please specify a different model\n"; return 1; case 4: model = SampleAllelicExpression::MODEL_4; break; } break; case 'o': output_filename = std::string(optarg); break; case 'k': read_length = std::stoi(optarg); break; case 'l': transcript_length_file = std::string(optarg); break; case 'i': max_iterations = std::stoi(optarg); break; case '?': bad_args++; } } if (bad_args) { print_help(); return 1; } if (argc - optind == 1) { input_filename = argv[optind]; } else { // TODO print error message. no print_help(); return 1; } if (extension.size() >= input_filename.size() || !std::equal(extension.rbegin(), extension.rend(), input_filename.rbegin())) { std::cerr << "Error, expected file with .pcl.bz2 extension. Input file should be prepared with bam_to_pcl.py script.\n"; return 1; } if (output_filename.empty()) { //use default, based on the input file name but placed in current working directdory output_filename = input_filename.substr(0, input_filename.size() - extension.size()).append(".stacksum.tsv"); //check to see if there was a path in the input file name. If so, trim it off std::size_t found = output_filename.rfind('/'); if (found != std::string::npos) { output_filename = output_filename.substr(found+1); } } PythonInterface pi = PythonInterface(); if (pi.init()){ std::cerr << "Error importing TranscriptHits Python module.\n"; std::cerr << '\t' << pi.getErrorString() << std::endl; return 1; } std::cout << "Loading " << input_filename << ". This may take a while..." << std::endl; AlignmentIncidenceMatrix *aim = pi.load(input_filename); if (!aim) { std::cerr << "Error loading pcl file\n"; std::cerr << '\t' << pi.getErrorString() << std::endl; return 1; } std::cout << "Loaded Pickled Alignment Incidence file " << input_filename << std::endl; std::vector<std::string> hap_names = aim->get_haplotype_names(); std::cout << "File had the following haplotype names:\n"; for (std::vector<std::string>::iterator it = hap_names.begin(); it != hap_names.end(); ++it) { std::cout << *it << "\t"; } std::cout << std::endl; std::cout << aim->num_reads() << " reads loaded\n"; std::cout << aim->num_transcripts() << " transcripts\n"; std::cout << std::endl; if (!transcript_length_file.empty()) { std::cout << "Loading Transcript Length File " << transcript_length_file << std::endl; aim->loadTranscriptLengths(transcript_length_file); } if (model != SampleAllelicExpression::MODEL_4 && !aim->has_gene_mappings()) { std::cerr << "File does not contain transcript to gene mapping information. Only normalization Model 4 can be used.\n"; return 1; } t1 = clock(); SampleAllelicExpression sae(aim, read_length); t2 = clock(); diff = ((float)t2-(float)t1)/CLOCKS_PER_SEC; std::cout << "Time for initializing stack sum = " << diff << "s" << std::endl; if (max_iterations > 0) { num_iterations = 0; std::cout << "Beginning EM Iterations" << std::endl; t1 = clock(); do { sae.update(model); } while (++num_iterations < max_iterations && !sae.converged()); t2 = clock(); diff = ((float)t2-(float)t1)/CLOCKS_PER_SEC; std::cout << "Time for " << num_iterations << " iterations = " << diff << "s\n"; std::cout << "Time per iteration " << diff/num_iterations << "s\n"; } std::cout << "Saving results to " << output_filename << std::endl; sae.saveStackSums(output_filename); std::cout << "Done.\n"; return 0; } void print_help() { std::cout << std::endl << std::endl << "EMASE Help\n" << "----------\n\n" << "USAGE: emase [options] <alignment_incidence>\n\n" << "INPUT: Alignment Incidence file prepared with bam_to_pcl.py script\n\n" << "OPTIONS\n" << " --model (-m) : Specify normalization model (can be 1-4, default=2)\n" << " --output (-o) : Specify filename for output file (default is input_basename.stacksum.tsv)\n" << " --transcript-lengths (-l) : Filename for transcript length file. Format is \"transcript_id\tlength\"\n" << " --read-length (-k) : Specify read length for use when applying transcript length adjustment.\n" << " Ignored unless combined with --transcript-lengths. (Default 100)\n" << " --max-iterations (-i) : Specify the maximum number of EM iterations. (Default 200)\n" << " --help (-h) : Print this message and exit\n\n"; } <|endoftext|>
<commit_before>/// @file moveAction.cpp /// @brief Implementation of the class for a move action. /// @author Enrico Fraccaroli /// @date Jul 14 2016 /// @copyright /// Copyright (c) 2016 Enrico Fraccaroli <[email protected]> /// Permission is hereby granted, free of charge, to any person obtaining a /// copy of this software and associated documentation files (the "Software"), /// to deal in the Software without restriction, including without limitation /// the rights to use, copy, modify, merge, publish, distribute, sublicense, /// and/or sell copies of the Software, and to permit persons to whom the /// Software is furnished to do so, subject to the following conditions: /// The above copyright notice and this permission notice shall be included /// in all copies or substantial portions of the Software. /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL /// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING /// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER /// DEALINGS IN THE SOFTWARE. #include "moveAction.hpp" #include "effectFactory.hpp" #include "character.hpp" #include "logger.hpp" #include "room.hpp" using namespace std::chrono; MoveAction::MoveAction(Character * _actor, Room * _destination, Direction _direction) : GeneralAction(_actor), destination(_destination), direction(_direction) { // Debugging message. Logger::log(LogLevel::Debug, "Created MoveAction."); // Reset the cooldown of the action. this->resetCooldown(MoveAction::getCooldown(_actor)); } MoveAction::~MoveAction() { Logger::log(LogLevel::Debug, "Deleted move action."); } bool MoveAction::check(std::string & error) const { if (!GeneralAction::check(error)) { return false; } if (this->destination == nullptr) { Logger::log(LogLevel::Error, "No destination has been set."); error = "You cannot reach the destination."; return false; } if (this->direction == Direction::None) { Logger::log(LogLevel::Error, "No direction has been set."); error = "You have lost your direction."; return false; } // Calculate the time needed to move. if ((actor->posture != CharacterPosture::Stand) && (actor->posture != CharacterPosture::Crouch) && (actor->posture != CharacterPosture::Prone)) { error = "You first need to stand up."; return false; } return true; } ActionType MoveAction::getType() const { return ActionType::Move; } std::string MoveAction::getDescription() const { return "moving"; } std::string MoveAction::stop() { return "You stop moving."; } ActionStatus MoveAction::perform() { // Check if the cooldown is ended. if (!this->checkElapsed()) { return ActionStatus::Running; } std::string error; if (!this->check(error)) { actor->sendMsg(error + "\n\n"); return ActionStatus::Error; } if (!MoveAction::canMoveTo(actor, direction, error, false)) { // Notify that the actor can't move because too tired. actor->sendMsg(error + "\n"); return ActionStatus::Error; } // Get the amount of required stamina. auto consumedStamina = this->getConsumedStamina(actor, actor->posture); // Consume the stamina. actor->remStamina(consumedStamina, true); // Check if the actor was aiming. if (actor->combatHandler.getAimedTarget() != nullptr) { actor->effects.forceAddEffect(EffectFactory::disturbedAim(actor, 1, -3)); } // Move character. actor->moveTo( destination, actor->getNameCapital() + " goes " + direction.toString() + ".\n", actor->getNameCapital() + " arrives from " + direction.getOpposite().toString() + ".\n"); return ActionStatus::Finished; } unsigned int MoveAction::getConsumedStamina(const Character * character, const CharacterPosture & posture) { auto multiplier = 1.0; if (posture == CharacterPosture::Crouch) { multiplier = 0.75; } else if (posture == CharacterPosture::Prone) { multiplier = 0.50; } // BASE [+1.0] // STRENGTH [-0.0 to -1.40] // WEIGHT [+1.6 to +2.51] // CARRIED [+0.0 to +2.48] unsigned int consumedStamina = 1; consumedStamina -= character->getAbilityLog(Ability::Strength, 0.0, 1.0); consumedStamina = SafeSum(consumedStamina, SafeLog10(character->weight)); consumedStamina = SafeSum(consumedStamina, SafeLog10(character->getCarryingWeight())); return static_cast<unsigned int>(consumedStamina * multiplier); } unsigned int MoveAction::getCooldown(const Character * character) { unsigned int cooldown = 2; if (character->posture == CharacterPosture::Crouch) { cooldown = 4; } else if (character->posture == CharacterPosture::Prone) { cooldown = 6; } return cooldown; } bool MoveAction::canMoveTo(Character * character, const Direction & direction, std::string & error, bool allowInCombat) { if ((character->getAction()->getType() == ActionType::Combat) && !allowInCombat) { // Check if the character is locked into close combat. bool lockedInCombat = false; // Check if he is in the same room of one of its aggressors. for (auto iterator : character->combatHandler) { if (iterator->aggressor != nullptr) { if (iterator->aggressor->room == character->room) { lockedInCombat = true; break; } } } // Check even the aimed character. if (character->combatHandler.getAimedTarget() != nullptr) { if (character->combatHandler.getAimedTarget()->room == character->room) { lockedInCombat = true; } } if (lockedInCombat) { error = "You cannot move while fighting in close combat."; } return !lockedInCombat; } // Check if the character is in a no-walk position. if ((character->posture != CharacterPosture::Stand) && (character->posture != CharacterPosture::Crouch) && (character->posture != CharacterPosture::Prone)) { error = "You first need to stand up."; return false; } // Find the exit to the destination. auto destExit = character->room->findExit(direction); if (destExit == nullptr) { error = "You cannot go that way."; return false; } // Check if the actor has enough stamina to execute the action. if (MoveAction::getConsumedStamina(character, character->posture) > character->getStamina()) { error = "You are too tired to move.\n"; return false; } // If the direction is upstairs, check if there is a stair. if (direction == Direction::Up) { if (!HasFlag(destExit->flags, ExitFlag::Stairs)) { error = "You can't go upstairs, there are no stairs."; return false; } } // Check if the destination is correct. if (destExit->destination == nullptr) { error = "That direction can't take you anywhere."; return false; } // Check if the destination is bocked by a door. auto door = destExit->destination->findDoor(); if (door != nullptr) { if (HasFlag(door->flags, ItemFlag::Closed)) { error = "Maybe you have to open that door first."; return false; } } // Check if the destination has a floor. std::shared_ptr<Exit> destDown = destExit->destination->findExit(Direction::Down); if (destDown != nullptr) { if (!HasFlag(destDown->flags, ExitFlag::Stairs)) { error = "Do you really want to fall in that pit?"; return false; } } // Check if the destination is forbidden for mobiles. return !(character->isMobile() && HasFlag(destExit->flags, ExitFlag::NoMob)); } <commit_msg>Remove 'using namespace' where not needed<commit_after>/// @file moveAction.cpp /// @brief Implementation of the class for a move action. /// @author Enrico Fraccaroli /// @date Jul 14 2016 /// @copyright /// Copyright (c) 2016 Enrico Fraccaroli <[email protected]> /// Permission is hereby granted, free of charge, to any person obtaining a /// copy of this software and associated documentation files (the "Software"), /// to deal in the Software without restriction, including without limitation /// the rights to use, copy, modify, merge, publish, distribute, sublicense, /// and/or sell copies of the Software, and to permit persons to whom the /// Software is furnished to do so, subject to the following conditions: /// The above copyright notice and this permission notice shall be included /// in all copies or substantial portions of the Software. /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL /// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING /// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER /// DEALINGS IN THE SOFTWARE. #include "moveAction.hpp" #include "effectFactory.hpp" #include "character.hpp" #include "logger.hpp" #include "room.hpp" MoveAction::MoveAction(Character * _actor, Room * _destination, Direction _direction) : GeneralAction(_actor), destination(_destination), direction(_direction) { // Debugging message. Logger::log(LogLevel::Debug, "Created MoveAction."); // Reset the cooldown of the action. this->resetCooldown(MoveAction::getCooldown(_actor)); } MoveAction::~MoveAction() { Logger::log(LogLevel::Debug, "Deleted move action."); } bool MoveAction::check(std::string & error) const { if (!GeneralAction::check(error)) { return false; } if (this->destination == nullptr) { Logger::log(LogLevel::Error, "No destination has been set."); error = "You cannot reach the destination."; return false; } if (this->direction == Direction::None) { Logger::log(LogLevel::Error, "No direction has been set."); error = "You have lost your direction."; return false; } // Calculate the time needed to move. if ((actor->posture != CharacterPosture::Stand) && (actor->posture != CharacterPosture::Crouch) && (actor->posture != CharacterPosture::Prone)) { error = "You first need to stand up."; return false; } return true; } ActionType MoveAction::getType() const { return ActionType::Move; } std::string MoveAction::getDescription() const { return "moving"; } std::string MoveAction::stop() { return "You stop moving."; } ActionStatus MoveAction::perform() { // Check if the cooldown is ended. if (!this->checkElapsed()) { return ActionStatus::Running; } std::string error; if (!this->check(error)) { actor->sendMsg(error + "\n\n"); return ActionStatus::Error; } if (!MoveAction::canMoveTo(actor, direction, error, false)) { // Notify that the actor can't move because too tired. actor->sendMsg(error + "\n"); return ActionStatus::Error; } // Get the amount of required stamina. auto consumedStamina = this->getConsumedStamina(actor, actor->posture); // Consume the stamina. actor->remStamina(consumedStamina, true); // Check if the actor was aiming. if (actor->combatHandler.getAimedTarget() != nullptr) { actor->effects.forceAddEffect(EffectFactory::disturbedAim(actor, 1, -3)); } // Move character. actor->moveTo( destination, actor->getNameCapital() + " goes " + direction.toString() + ".\n", actor->getNameCapital() + " arrives from " + direction.getOpposite().toString() + ".\n"); return ActionStatus::Finished; } unsigned int MoveAction::getConsumedStamina(const Character * character, const CharacterPosture & posture) { auto multiplier = 1.0; if (posture == CharacterPosture::Crouch) { multiplier = 0.75; } else if (posture == CharacterPosture::Prone) { multiplier = 0.50; } // BASE [+1.0] // STRENGTH [-0.0 to -1.40] // WEIGHT [+1.6 to +2.51] // CARRIED [+0.0 to +2.48] unsigned int consumedStamina = 1; consumedStamina -= character->getAbilityLog(Ability::Strength, 0.0, 1.0); consumedStamina = SafeSum(consumedStamina, SafeLog10(character->weight)); consumedStamina = SafeSum(consumedStamina, SafeLog10(character->getCarryingWeight())); return static_cast<unsigned int>(consumedStamina * multiplier); } unsigned int MoveAction::getCooldown(const Character * character) { unsigned int cooldown = 2; if (character->posture == CharacterPosture::Crouch) { cooldown = 4; } else if (character->posture == CharacterPosture::Prone) { cooldown = 6; } return cooldown; } bool MoveAction::canMoveTo(Character * character, const Direction & direction, std::string & error, bool allowInCombat) { if ((character->getAction()->getType() == ActionType::Combat) && !allowInCombat) { // Check if the character is locked into close combat. bool lockedInCombat = false; // Check if he is in the same room of one of its aggressors. for (auto iterator : character->combatHandler) { if (iterator->aggressor != nullptr) { if (iterator->aggressor->room == character->room) { lockedInCombat = true; break; } } } // Check even the aimed character. if (character->combatHandler.getAimedTarget() != nullptr) { if (character->combatHandler.getAimedTarget()->room == character->room) { lockedInCombat = true; } } if (lockedInCombat) { error = "You cannot move while fighting in close combat."; } return !lockedInCombat; } // Check if the character is in a no-walk position. if ((character->posture != CharacterPosture::Stand) && (character->posture != CharacterPosture::Crouch) && (character->posture != CharacterPosture::Prone)) { error = "You first need to stand up."; return false; } // Find the exit to the destination. auto destExit = character->room->findExit(direction); if (destExit == nullptr) { error = "You cannot go that way."; return false; } // Check if the actor has enough stamina to execute the action. if (MoveAction::getConsumedStamina(character, character->posture) > character->getStamina()) { error = "You are too tired to move.\n"; return false; } // If the direction is upstairs, check if there is a stair. if (direction == Direction::Up) { if (!HasFlag(destExit->flags, ExitFlag::Stairs)) { error = "You can't go upstairs, there are no stairs."; return false; } } // Check if the destination is correct. if (destExit->destination == nullptr) { error = "That direction can't take you anywhere."; return false; } // Check if the destination is bocked by a door. auto door = destExit->destination->findDoor(); if (door != nullptr) { if (HasFlag(door->flags, ItemFlag::Closed)) { error = "Maybe you have to open that door first."; return false; } } // Check if the destination has a floor. std::shared_ptr<Exit> destDown = destExit->destination->findExit(Direction::Down); if (destDown != nullptr) { if (!HasFlag(destDown->flags, ExitFlag::Stairs)) { error = "Do you really want to fall in that pit?"; return false; } } // Check if the destination is forbidden for mobiles. return !(character->isMobile() && HasFlag(destExit->flags, ExitFlag::NoMob)); } <|endoftext|>
<commit_before>#include <netdb.h> #include <unistd.h> #include "client.h" #include "duckchat.h" // Variables struct sockaddr_in client_addr; struct sockaddr_in server_addr; int client_socket; struct addrinfo *server_info; char *channel; // Prints an error message and exits the program. void Error(const char *msg) { std::cerr << msg << std::endl; exit(1); } // Connects to the server at a the given port. void Connect(char *domain, const char *port) { std::cout << "Connecting to " << domain << std::endl; struct addrinfo hints; struct addrinfo *server_info_tmp; int status; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = 0; if ((status = getaddrinfo(domain, port, &hints, &server_info_tmp)) != 0) { std::cerr << "client: unable to resolve address: " << gai_strerror(status) << std::endl; exit(1); } // getaddrinfo() returns a list of address structures into server_info_tmp. // Try each address until we successfully connect(). // If socket() (or connect()) fails, close the socket and try the next address. for (server_info = server_info_tmp; server_info != NULL; server_info = server_info->ai_next) { if ((client_socket = socket(server_info->ai_family, server_info->ai_socktype, server_info->ai_protocol)) < 0) { continue; } if (connect(client_socket, server_info->ai_addr, server_info->ai_addrlen) != -1) { break; // Success } close(client_socket); } if (server_info == NULL) { Error("client: all sockets failed to connect"); } } // Sends a message to all users in on the active channel. int RequestSay(const char *message) { struct request_say say; memset(&say, 0, sizeof(say)); say.req_type = REQ_SAY; strncpy(say.req_text, message, SAY_MAX); strncpy(say.req_channel, channel, CHANNEL_MAX); if (sendto(client_socket, &say, sizeof(say), 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to send message\n"); } return 0; } // Sends login requests to the server. int RequestLogin(char *username) { struct request_login login; memset(&login, 0, sizeof(login)); login.req_type = REQ_LOGIN; strncpy(login.req_username, username, USERNAME_MAX); size_t message_size = sizeof(struct request_login); if (sendto(client_socket, &login, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request login\n"); } return 0; } // Sends logout requests to the server. int RequestLogout() { struct request_logout logout; memset((char *) &logout, 0, sizeof(logout)); logout.req_type = REQ_LOGOUT; size_t message_size = sizeof(struct request_logout); if (sendto(client_socket, &logout, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request logout\n"); } return 0; } // Sends join requests to the server. int RequestJoin(char *channel) { struct request_join join; memset((char *) &join, 0, sizeof(join)); join.req_type = REQ_JOIN; strncpy(join.req_channel, channel, CHANNEL_MAX); size_t message_size = sizeof(struct request_join); if (sendto(client_socket, &join, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request join\n"); } return 0; } // Splits strings around spaces. std::vector<std::string> StringSplit(std::string input) { std::istringstream iss(input); std::vector<std::string> result{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}}; return result; } // Splits strings around spaces. std::vector<std::string> SplitString(std::string input, char delimiter) { std::vector<std::string> result; std::string word = ""; for (char c : input) { if (c != delimiter) { word += c; } else { result.push_back(word); word = ""; } } result.push_back(word); return result; } // Processes the input string to decide what type of command it is. bool ProcessInput(std::string input) { std::vector<std::string> inputs = StringSplit(input); bool result = true; if (inputs[0] == "/exit") { RequestLogout(); result = false; } else if (inputs[0] == "/list") { } else if (inputs[0] == "/join") { } else if (inputs[0] == "/leave") { } else if (inputs[0] == "/who") { } else if (inputs[0] == "/switch") { } else { std::cout << "Invalid command" << std::endl; } return result; } int main(int argc, char *argv[]) { char *domain; char *port_str; int port_num; char *username; std::string input; struct timeval timeout; fd_set read_set; int file_desc = 0; int result; char receive_buffer[SAY_MAX]; memset(&receive_buffer, 0, SAY_MAX); if (argc < 4) { Error("usage: client [server name] [port] [username]"); } domain = argv[1]; port_str = argv[2]; port_num = atoi(argv[2]); username = argv[3]; if (strlen(domain) > UNIX_PATH_MAX) { Error("client: server name must be less than 108 characters"); } if (port_num < 0 || port_num > 65535) { Error("client: port number must be between 0 and 65535"); } if (strlen(username) > USERNAME_MAX) { Error("client: username must be less than 32 characters"); } Connect(domain, port_str); RequestLogin(username); channel = (char *) "Common"; RequestJoin(channel); // TODO handle response from send while(1) { FD_ZERO(&read_set); FD_SET(file_desc, &read_set); timeout.tv_sec = 5; // TODO change time value? timeout.tv_usec = 0; // if ((result = select(file_desc + 1, &read_set, NULL, NULL, NULL)) < 0) { // continue; // } if ((result = select(file_desc + 1, &read_set, NULL, NULL, &timeout)) < 0) { Error("client: problem using select"); } // size_t size = sizeof(receive_buffer); std::cout << "past select, result: " << result << std::endl; if (result > 0) { if (FD_ISSET(file_desc, &read_set)) { // Socket has data result = recv(file_desc, receive_buffer, SAY_MAX, 0); } if (result == 0) { close(file_desc); } else { // TODO capture user input, store, clean input, then print buffer, afterward replace input std::cout << "[" << channel << "]" << "[" << username << "]: " << receive_buffer << std::endl; } } std::cout << "past check result" << std::endl; std::cout << "> "; getline(std::cin, input); if (input[0] == '/') { if (!ProcessInput(input)) { break; } } else { // Send chat messages RequestSay(input.c_str()); std::cout << "[" << channel << "]" << "[" << username << "]: " << input << std::endl; } // if (FD_ISSET(STDIN_FILENO, &read_set)) { // std::cout << "> "; // getline(std::cin, input); // // if (input[0] == '/') { // if (!ProcessInput(input)) { // break; // } // } else { // // Send chat messages // RequestSay(input.c_str()); // std::cout << "[" << channel << "]" << "[" << username << "]: " << input << std::endl; // } // } std::cout << "past getline" << std::endl; } return 0; }<commit_msg>test select again<commit_after>#include <netdb.h> #include <unistd.h> #include "client.h" #include "duckchat.h" // Variables struct sockaddr_in client_addr; struct sockaddr_in server_addr; int client_socket; struct addrinfo *server_info; char *channel; // Prints an error message and exits the program. void Error(const char *msg) { std::cerr << msg << std::endl; exit(1); } // Connects to the server at a the given port. void Connect(char *domain, const char *port) { std::cout << "Connecting to " << domain << std::endl; struct addrinfo hints; struct addrinfo *server_info_tmp; int status; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = 0; if ((status = getaddrinfo(domain, port, &hints, &server_info_tmp)) != 0) { std::cerr << "client: unable to resolve address: " << gai_strerror(status) << std::endl; exit(1); } // getaddrinfo() returns a list of address structures into server_info_tmp. // Try each address until we successfully connect(). // If socket() (or connect()) fails, close the socket and try the next address. for (server_info = server_info_tmp; server_info != NULL; server_info = server_info->ai_next) { if ((client_socket = socket(server_info->ai_family, server_info->ai_socktype, server_info->ai_protocol)) < 0) { continue; } if (connect(client_socket, server_info->ai_addr, server_info->ai_addrlen) != -1) { break; // Success } close(client_socket); } if (server_info == NULL) { Error("client: all sockets failed to connect"); } } // Sends a message to all users in on the active channel. int RequestSay(const char *message) { struct request_say say; memset(&say, 0, sizeof(say)); say.req_type = REQ_SAY; strncpy(say.req_text, message, SAY_MAX); strncpy(say.req_channel, channel, CHANNEL_MAX); if (sendto(client_socket, &say, sizeof(say), 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to send message\n"); } return 0; } // Sends login requests to the server. int RequestLogin(char *username) { struct request_login login; memset(&login, 0, sizeof(login)); login.req_type = REQ_LOGIN; strncpy(login.req_username, username, USERNAME_MAX); size_t message_size = sizeof(struct request_login); if (sendto(client_socket, &login, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request login\n"); } return 0; } // Sends logout requests to the server. int RequestLogout() { struct request_logout logout; memset((char *) &logout, 0, sizeof(logout)); logout.req_type = REQ_LOGOUT; size_t message_size = sizeof(struct request_logout); if (sendto(client_socket, &logout, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request logout\n"); } return 0; } // Sends join requests to the server. int RequestJoin(char *channel) { struct request_join join; memset((char *) &join, 0, sizeof(join)); join.req_type = REQ_JOIN; strncpy(join.req_channel, channel, CHANNEL_MAX); size_t message_size = sizeof(struct request_join); if (sendto(client_socket, &join, message_size, 0, server_info->ai_addr, server_info->ai_addrlen) < 0) { Error("client: failed to request join\n"); } return 0; } // Splits strings around spaces. std::vector<std::string> StringSplit(std::string input) { std::istringstream iss(input); std::vector<std::string> result{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}}; return result; } // Splits strings around spaces. std::vector<std::string> SplitString(std::string input, char delimiter) { std::vector<std::string> result; std::string word = ""; for (char c : input) { if (c != delimiter) { word += c; } else { result.push_back(word); word = ""; } } result.push_back(word); return result; } // Processes the input string to decide what type of command it is. bool ProcessInput(std::string input) { std::vector<std::string> inputs = StringSplit(input); bool result = true; if (inputs[0] == "/exit") { RequestLogout(); result = false; } else if (inputs[0] == "/list") { } else if (inputs[0] == "/join") { } else if (inputs[0] == "/leave") { } else if (inputs[0] == "/who") { } else if (inputs[0] == "/switch") { } else { std::cout << "Invalid command" << std::endl; } return result; } int main(int argc, char *argv[]) { char *domain; char *port_str; int port_num; char *username; std::string input; struct timeval timeout; fd_set read_set; int file_desc = 0; int result; char receive_buffer[SAY_MAX]; memset(&receive_buffer, 0, SAY_MAX); if (argc < 4) { Error("usage: client [server name] [port] [username]"); } domain = argv[1]; port_str = argv[2]; port_num = atoi(argv[2]); username = argv[3]; if (strlen(domain) > UNIX_PATH_MAX) { Error("client: server name must be less than 108 characters"); } if (port_num < 0 || port_num > 65535) { Error("client: port number must be between 0 and 65535"); } if (strlen(username) > USERNAME_MAX) { Error("client: username must be less than 32 characters"); } Connect(domain, port_str); RequestLogin(username); channel = (char *) "Common"; RequestJoin(channel); // TODO handle response from send while(1) { FD_ZERO(&read_set); FD_SET(file_desc, &read_set); timeout.tv_sec = 5; // TODO change time value? timeout.tv_usec = 0; // if ((result = select(file_desc + 1, &read_set, NULL, NULL, NULL)) < 0) { // continue; // } if ((result = select(file_desc + 1, &read_set, NULL, NULL, &timeout)) < 0) { Error("client: problem using select"); } // size_t size = sizeof(receive_buffer); // std::cout << "past select, result: " << result << std::endl; if (result > 0) { if (FD_ISSET(file_desc, &read_set)) { // Socket has data result = read(client_socket, receive_buffer, sizeof(receive_buffer)); } if (result == 0) { close(file_desc); } else { // TODO capture user input, store, clean input, then print buffer, afterward replace input std::cout << "[" << channel << "]" << "[" << username << "]: " << receive_buffer << std::endl; } } // std::cout << "past check result" << std::endl; std::cout << "> "; getline(std::cin, input); if (input[0] == '/') { if (!ProcessInput(input)) { break; } } else { // Send chat messages RequestSay(input.c_str()); std::cout << "[" << channel << "]" << "[" << username << "]: " << input << std::endl; } // if (FD_ISSET(STDIN_FILENO, &read_set)) { // std::cout << "> "; // getline(std::cin, input); // // if (input[0] == '/') { // if (!ProcessInput(input)) { // break; // } // } else { // // Send chat messages // RequestSay(input.c_str()); // std::cout << "[" << channel << "]" << "[" << username << "]: " << input << std::endl; // } // } // std::cout << "past getline" << std::endl; } return 0; }<|endoftext|>
<commit_before>/** * @file Special Purpose Strings Library: storage_password.hpp * @author Daniel Evers * @brief Storage implementation that wipes memory before free'ing it - for sensitive data * @license MIT */ #ifndef SPSL_STORAGE_PASSWORD_HPP_ #define SPSL_STORAGE_PASSWORD_HPP_ #include <limits> #include <stdexcept> #include <string> // for traits #include "spsl/pagealloc.hpp" #include "spsl/type_traits.hpp" namespace spsl { /** * Secure memset implementation that may not be optimized "away". * @param[in] ptr pointer to the memory area to clear * @param[in] size number of bytes to clear * @return @c ptr */ inline void* secure_memzero(void* ptr, size_t size) noexcept { // Note: We are *not* using SecureZeroMemory() here because this requires us to include the // Windows headers and then all hell breaks loose... // Also, the implementation is pretty much the same :) // For more info, start here: // http://stackoverflow.com/questions/9973260/what-is-the-correct-way-to-clear-sensitive-data-from-memory-in-ios volatile char* p = reinterpret_cast<char*>(ptr); while (size--) *p++ = 0; return ptr; } /** * Storage implementation that wipes all memory before free'ing it. It's therefore usable for * passwords and other sensitive data that shouldn't be "left behind" when releasing memory * back to the OS. * * The allocation strategy is simple: We always allocate a multiple of the block size, assuming * that passwords and other sensitive data is relatively static. We rely on an allocator type, * which defaults to std::allocator, so that we can swap out the allocator in the unit tests. * Only the allocate(), deallocate() and max_size() member functions of the allocator type are used. */ template <typename CharType, std::size_t BlockSize = 128, typename Allocator = SensitiveSegmentAllocator<CharType>> class StoragePassword : private Allocator { public: using size_type = std::size_t; using difference_type = ssize_t; using char_type = CharType; /// simple alias for the typing impaired :) using this_type = StoragePassword<char_type, BlockSize, Allocator>; using traits_type = typename std::char_traits<char_type>; using allocator = Allocator; static constexpr char_type nul() { return char_type(); } // size information functions size_type max_size() const { const allocator& a = *this; return a.max_size(); } constexpr static size_type block_size() { return BlockSize; } size_type capacity() const { return _l.m_capacity; } size_type length() const { return _l.m_length; } size_type size() const { return _l.m_length; } bool empty() const { return _l.m_length == 0; } // access to the underlying allocator allocator& getAllocator() noexcept { return *this; } const allocator& getAllocator() const noexcept { return *this; } // note: This function is *not* constexpr to stay compatible with C++11 static size_type _roundRequiredCapacityToBlockSize(size_type cap) { size_type numBlocks = cap / BlockSize; if (numBlocks * BlockSize < cap) ++numBlocks; return numBlocks * BlockSize; } void reserve(size_type new_cap = 0) { if (new_cap > max_size()) throw std::length_error("requested capacity exceeds maximum"); if (new_cap >= capacity()) { // need to realloc: We explicitly allocate a new block, copy all data and wipe the old new_cap = _roundRequiredCapacityToBlockSize(new_cap + 1); // allocate a new buffer (the allocator will throw in case of error) allocator& a = *this; char_type* newbuf = a.allocate(new_cap); // copy existing data (note: all data must fit because we're only growing) if (size()) traits_type::copy(newbuf, m_buffer, size() + 1); else newbuf[0] = nul(); // wipe all existing data if (m_buffer != _b) { _wipe(); a.deallocate(m_buffer, capacity()); } // now replace our data m_buffer = newbuf; _l.m_capacity = new_cap; } } // get rid of unnecessarily allocated data void shrink_to_fit() { // quick & dirty implementation: create a copy of this string and swap... if ((empty() && capacity()) || (capacity() - (size() + 1) >= BlockSize)) { this_type copy(*this); swap(copy); } } void _set_length(size_type n) { _l.m_length = n; traits_type::assign(m_buffer[n], nul()); } // default constructor StoragePassword(const allocator& alloc = allocator()) noexcept : allocator(alloc), m_buffer(_b) { _l.m_capacity = 0; _set_length(0); } // implement copy & move StoragePassword(const this_type& other) : StoragePassword(other.getAllocator()) { if (!other.empty()) assign(other.data(), other.size()); } StoragePassword(this_type&& other) noexcept : StoragePassword(other.getAllocator()) { swap(other); other.clear(); } StoragePassword& operator=(const this_type& other) { assign(other.data(), other.size()); return *this; } StoragePassword& operator=(this_type&& other) noexcept { swap(other); other.clear(); return *this; } // default destructor: wipe & release ~StoragePassword() { if (m_buffer != _b) { clear(); allocator& a = *this; a.deallocate(m_buffer, capacity()); } } // buffer access functions char_type* data() { return m_buffer; } const char_type* data() const { return m_buffer; } char_type& operator[](size_type pos) { return data()[pos]; } const char_type& operator[](size_type pos) const { return data()[pos]; } void assign(const char_type* s, size_type n) { reserve(n); traits_type::copy(m_buffer, s, n); _set_length(n); } void assign(size_type count, char_type ch) { reserve(count); traits_type::assign(m_buffer, count, ch); _set_length(count); } template <typename InputIt, typename = checkInputIter<InputIt>> void assign(InputIt first, InputIt last) { clear(); append(first, last); } void clear() { if (m_buffer != _b) { _wipe(); } _l.m_length = 0; } void push_back(char_type c) { reserve(size() + 1); traits_type::assign(m_buffer[_l.m_length++], c); traits_type::assign(m_buffer[_l.m_length], nul()); } void pop_back() { // the standard leaves it as "undefined" if size() == 0, but we'll just keep it sane if (size() != 0) _set_length(size() - 1); } void insert(size_type index, size_type count, char_type ch) { if (index > size()) throw std::out_of_range("index out of range"); reserve(size() + count); // move the existing data (including the terminating NUL) char_type* ptr = m_buffer + index; const size_type len = size() + 1 - index; traits_type::move(ptr + count, ptr, len); for (size_type i = 0; i < count; ++i) traits_type::assign(ptr[i], ch); _l.m_length += count; } void insert(size_type index, const char_type* s, size_type n) { if (index > size()) throw std::out_of_range("index out of range"); reserve(size() + n); // move the existing data (including the terminating NUL) char_type* ptr = m_buffer + index; const size_type len = size() + 1 - index; traits_type::move(ptr + n, ptr, len); traits_type::copy(ptr, s, n); _l.m_length += n; } template <typename InputIt, typename = checkInputIter<InputIt>> void insert(size_type index, InputIt first, InputIt last) { this_type tmp; tmp.assign(first, last); insert(index, tmp.data(), tmp.size()); } void erase(size_type index, size_type count) noexcept { // move all following characters here const size_type n = size() - index - count; traits_type::move(data() + index, data() + index + count, n); _l.m_length -= count; // wipe the rest _wipe(_l.m_length, n); } void append(size_type count, char_type ch) { reserve(size() + count); traits_type::assign(m_buffer + size(), count, ch); _set_length(size() + count); } void append(const char_type* s, size_type n) { reserve(size() + n); traits_type::copy(m_buffer + size(), s, n); _set_length(size() + n); } template <typename InputIt, typename = checkInputIter<InputIt>> void append(InputIt first, InputIt last) { while (first != last) { push_back(*first); ++first; } } void replace(size_type pos, size_type count, const char_type* cstr, size_type count2) { // lazy implementation: // - different length: build a new string and swap... // - same length: overwrite the part to replace // This is *not* the most efficient implementation, but it's easy and exception safe :) // TODO: avoid reallocations, fix this if (count == count2) { traits_type::copy(data() + pos, cstr, count2); } else { this_type tmp; tmp.reserve(size() - count + count2); // (1) copy the part before 'pos' if (pos != 0) tmp.assign(data(), pos); // (2) append the replacement string tmp.append(cstr, count2); // (3) append the rest after 'pos + count' size_type rest = pos + count; if (rest < size()) tmp.append(data() + rest, size() - rest); // (4) swap/move *this = std::move(tmp); } } void replace(size_type pos, size_type count, size_type count2, char_type ch) { // => same implementation as above // TODO: avoid reallocations, fix this if (count == count2) { traits_type::assign(data() + pos, count2, ch); } else { this_type tmp; tmp.reserve(size() - count + count2); // (1) copy the part before 'pos' if (pos != 0) tmp.assign(data(), pos); // (2) append the replacement string tmp.append(count2, ch); // (3) append the rest after 'pos + count' size_type rest = pos + count; if (rest < size()) tmp.append(data() + rest, size() - rest); // (4) swap/move *this = std::move(tmp); } } template <class InputIt> void replace(size_type pos, size_type count, InputIt first, InputIt last) { // => same implementation as above this_type tmp; tmp.assign(first, last); replace(pos, count, tmp.data(), tmp.size()); } void resize(size_type count, char_type ch) { if (count < size()) { // wipe the remaining content traits_type::assign(m_buffer + count, size() - count, nul()); } else if (count > size()) { reserve(count); traits_type::assign(m_buffer + size(), count, ch); } _set_length(count); } void swap(this_type& other) noexcept { std::swap(_l.m_length, other._l.m_length); std::swap(_l.m_capacity, other._l.m_capacity); // avoid swapping internal pointers... std::swap(m_buffer, other.m_buffer); if (other.m_buffer == _b) other.m_buffer = other._b; if (m_buffer == other._b) m_buffer = _b; std::swap(getAllocator(), other.getAllocator()); } protected: void _wipe(size_type index, size_type count) noexcept { secure_memzero(m_buffer + index, count * sizeof(char_type)); } void _wipe() noexcept { _wipe(0, capacity()); } protected: // we store length + capacity information in a union that we also use as empty string // representation (assumption: m_buffer == _b => m_length == m_capacity == 0) struct SizeInfo { /// number of bytes (*not* characters) in the buffer, not including the terminating NUL size_type m_length; /// number of bytes (*not* characters) allocated size_type m_capacity; }; union { SizeInfo _l; // actually _b[1] is sufficient, but triggers overflow warnings in GCC char_type _b[sizeof(SizeInfo)]; }; /// the underlying buffer char_type* m_buffer; }; } // namespace spsl #endif /* SPSL_STORAGE_PASSWORD_HPP_ */ <commit_msg>issue #24: format fix<commit_after>/** * @file Special Purpose Strings Library: storage_password.hpp * @author Daniel Evers * @brief Storage implementation that wipes memory before free'ing it - for sensitive data * @license MIT */ #ifndef SPSL_STORAGE_PASSWORD_HPP_ #define SPSL_STORAGE_PASSWORD_HPP_ #include <limits> #include <stdexcept> #include <string> // for traits #include "spsl/pagealloc.hpp" #include "spsl/type_traits.hpp" namespace spsl { /** * Secure memset implementation that may not be optimized "away". * @param[in] ptr pointer to the memory area to clear * @param[in] size number of bytes to clear * @return @c ptr */ inline void* secure_memzero(void* ptr, size_t size) noexcept { // Note: We are *not* using SecureZeroMemory() here because this requires us to include the // Windows headers and then all hell breaks loose... // Also, the implementation is pretty much the same :) // For more info, start here: // http://stackoverflow.com/questions/9973260/what-is-the-correct-way-to-clear-sensitive-data-from-memory-in-ios volatile char* p = reinterpret_cast<char*>(ptr); while (size--) *p++ = 0; return ptr; } /** * Storage implementation that wipes all memory before free'ing it. It's therefore usable for * passwords and other sensitive data that shouldn't be "left behind" when releasing memory * back to the OS. * * The allocation strategy is simple: We always allocate a multiple of the block size, assuming * that passwords and other sensitive data is relatively static. We rely on an allocator type, * which defaults to std::allocator, so that we can swap out the allocator in the unit tests. * Only the allocate(), deallocate() and max_size() member functions of the allocator type are used. */ template <typename CharType, std::size_t BlockSize = 128, typename Allocator = SensitiveSegmentAllocator<CharType>> class StoragePassword : private Allocator { public: using size_type = std::size_t; using difference_type = ssize_t; using char_type = CharType; /// simple alias for the typing impaired :) using this_type = StoragePassword<char_type, BlockSize, Allocator>; using traits_type = typename std::char_traits<char_type>; using allocator = Allocator; static constexpr char_type nul() { return char_type(); } // size information functions size_type max_size() const { const allocator& a = *this; return a.max_size(); } constexpr static size_type block_size() { return BlockSize; } size_type capacity() const { return _l.m_capacity; } size_type length() const { return _l.m_length; } size_type size() const { return _l.m_length; } bool empty() const { return _l.m_length == 0; } // access to the underlying allocator allocator& getAllocator() noexcept { return *this; } const allocator& getAllocator() const noexcept { return *this; } // note: This function is *not* constexpr to stay compatible with C++11 static size_type _roundRequiredCapacityToBlockSize(size_type cap) { size_type numBlocks = cap / BlockSize; if (numBlocks * BlockSize < cap) ++numBlocks; return numBlocks * BlockSize; } void reserve(size_type new_cap = 0) { if (new_cap > max_size()) throw std::length_error("requested capacity exceeds maximum"); if (new_cap >= capacity()) { // need to realloc: We explicitly allocate a new block, copy all data and wipe the old new_cap = _roundRequiredCapacityToBlockSize(new_cap + 1); // allocate a new buffer (the allocator will throw in case of error) allocator& a = *this; char_type* newbuf = a.allocate(new_cap); // copy existing data (note: all data must fit because we're only growing) if (size()) traits_type::copy(newbuf, m_buffer, size() + 1); else newbuf[0] = nul(); // wipe all existing data if (m_buffer != _b) { _wipe(); a.deallocate(m_buffer, capacity()); } // now replace our data m_buffer = newbuf; _l.m_capacity = new_cap; } } // get rid of unnecessarily allocated data void shrink_to_fit() { // quick & dirty implementation: create a copy of this string and swap... if ((empty() && capacity()) || (capacity() - (size() + 1) >= BlockSize)) { this_type copy(*this); swap(copy); } } void _set_length(size_type n) { _l.m_length = n; traits_type::assign(m_buffer[n], nul()); } // default constructor StoragePassword(const allocator& alloc = allocator()) noexcept : allocator(alloc), m_buffer(_b) { _l.m_capacity = 0; _set_length(0); } // implement copy & move StoragePassword(const this_type& other) : StoragePassword(other.getAllocator()) { if (!other.empty()) assign(other.data(), other.size()); } StoragePassword(this_type&& other) noexcept : StoragePassword(other.getAllocator()) { swap(other); other.clear(); } StoragePassword& operator=(const this_type& other) { assign(other.data(), other.size()); return *this; } StoragePassword& operator=(this_type&& other) noexcept { swap(other); other.clear(); return *this; } // default destructor: wipe & release ~StoragePassword() { if (m_buffer != _b) { clear(); allocator& a = *this; a.deallocate(m_buffer, capacity()); } } // buffer access functions char_type* data() { return m_buffer; } const char_type* data() const { return m_buffer; } char_type& operator[](size_type pos) { return data()[pos]; } const char_type& operator[](size_type pos) const { return data()[pos]; } void assign(const char_type* s, size_type n) { reserve(n); traits_type::copy(m_buffer, s, n); _set_length(n); } void assign(size_type count, char_type ch) { reserve(count); traits_type::assign(m_buffer, count, ch); _set_length(count); } template <typename InputIt, typename = checkInputIter<InputIt>> void assign(InputIt first, InputIt last) { clear(); append(first, last); } void clear() { if (m_buffer != _b) { _wipe(); } _l.m_length = 0; } void push_back(char_type c) { reserve(size() + 1); traits_type::assign(m_buffer[_l.m_length++], c); traits_type::assign(m_buffer[_l.m_length], nul()); } void pop_back() { // the standard leaves it as "undefined" if size() == 0, but we'll just keep it sane if (size() != 0) _set_length(size() - 1); } void insert(size_type index, size_type count, char_type ch) { if (index > size()) throw std::out_of_range("index out of range"); reserve(size() + count); // move the existing data (including the terminating NUL) char_type* ptr = m_buffer + index; const size_type len = size() + 1 - index; traits_type::move(ptr + count, ptr, len); for (size_type i = 0; i < count; ++i) traits_type::assign(ptr[i], ch); _l.m_length += count; } void insert(size_type index, const char_type* s, size_type n) { if (index > size()) throw std::out_of_range("index out of range"); reserve(size() + n); // move the existing data (including the terminating NUL) char_type* ptr = m_buffer + index; const size_type len = size() + 1 - index; traits_type::move(ptr + n, ptr, len); traits_type::copy(ptr, s, n); _l.m_length += n; } template <typename InputIt, typename = checkInputIter<InputIt>> void insert(size_type index, InputIt first, InputIt last) { this_type tmp; tmp.assign(first, last); insert(index, tmp.data(), tmp.size()); } void erase(size_type index, size_type count) noexcept { // move all following characters here const size_type n = size() - index - count; traits_type::move(data() + index, data() + index + count, n); _l.m_length -= count; // wipe the rest _wipe(_l.m_length, n); } void append(size_type count, char_type ch) { reserve(size() + count); traits_type::assign(m_buffer + size(), count, ch); _set_length(size() + count); } void append(const char_type* s, size_type n) { reserve(size() + n); traits_type::copy(m_buffer + size(), s, n); _set_length(size() + n); } template <typename InputIt, typename = checkInputIter<InputIt>> void append(InputIt first, InputIt last) { while (first != last) { push_back(*first); ++first; } } void replace(size_type pos, size_type count, const char_type* cstr, size_type count2) { // lazy implementation: // - different length: build a new string and swap... // - same length: overwrite the part to replace // This is *not* the most efficient implementation, but it's easy and exception safe :) // TODO: avoid reallocations, fix this if (count == count2) { traits_type::copy(data() + pos, cstr, count2); } else { this_type tmp; tmp.reserve(size() - count + count2); // (1) copy the part before 'pos' if (pos != 0) tmp.assign(data(), pos); // (2) append the replacement string tmp.append(cstr, count2); // (3) append the rest after 'pos + count' size_type rest = pos + count; if (rest < size()) tmp.append(data() + rest, size() - rest); // (4) swap/move *this = std::move(tmp); } } void replace(size_type pos, size_type count, size_type count2, char_type ch) { // => same implementation as above // TODO: avoid reallocations, fix this if (count == count2) { traits_type::assign(data() + pos, count2, ch); } else { this_type tmp; tmp.reserve(size() - count + count2); // (1) copy the part before 'pos' if (pos != 0) tmp.assign(data(), pos); // (2) append the replacement string tmp.append(count2, ch); // (3) append the rest after 'pos + count' size_type rest = pos + count; if (rest < size()) tmp.append(data() + rest, size() - rest); // (4) swap/move *this = std::move(tmp); } } template <class InputIt> void replace(size_type pos, size_type count, InputIt first, InputIt last) { // => same implementation as above this_type tmp; tmp.assign(first, last); replace(pos, count, tmp.data(), tmp.size()); } void resize(size_type count, char_type ch) { if (count < size()) { // wipe the remaining content traits_type::assign(m_buffer + count, size() - count, nul()); } else if (count > size()) { reserve(count); traits_type::assign(m_buffer + size(), count, ch); } _set_length(count); } void swap(this_type& other) noexcept { std::swap(_l.m_length, other._l.m_length); std::swap(_l.m_capacity, other._l.m_capacity); // avoid swapping internal pointers... std::swap(m_buffer, other.m_buffer); if (other.m_buffer == _b) other.m_buffer = other._b; if (m_buffer == other._b) m_buffer = _b; std::swap(getAllocator(), other.getAllocator()); } protected: void _wipe(size_type index, size_type count) noexcept { secure_memzero(m_buffer + index, count * sizeof(char_type)); } void _wipe() noexcept { _wipe(0, capacity()); } protected: // we store length + capacity information in a union that we also use as empty string // representation (assumption: m_buffer == _b => m_length == m_capacity == 0) struct SizeInfo { /// number of bytes (*not* characters) in the buffer, not including the terminating NUL size_type m_length; /// number of bytes (*not* characters) allocated size_type m_capacity; }; union { SizeInfo _l; // actually _b[1] is sufficient, but triggers overflow warnings in GCC char_type _b[sizeof(SizeInfo)]; }; /// the underlying buffer char_type* m_buffer; }; } // namespace spsl #endif /* SPSL_STORAGE_PASSWORD_HPP_ */ <|endoftext|>
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef __ISOLATOR_VOLUME_STATE_HPP__ #define __ISOLATOR_VOLUME_STATE_HPP__ // ONLY USEFUL AFTER RUNNING PROTOC. #include "slave/containerizer/mesos/isolators/docker/volume/state.pb.h" #endif // __ISOLATOR_VOLUME_STATE_HPP__ <commit_msg>Fixed ifndef guard naming for docker volume isolator state.<commit_after>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef __ISOLATOR_DOCKER_VOLUME_STATE_HPP__ #define __ISOLATOR_DOCKER_VOLUME_STATE_HPP__ // ONLY USEFUL AFTER RUNNING PROTOC. #include "slave/containerizer/mesos/isolators/docker/volume/state.pb.h" #endif // __ISOLATOR_DOCKER_VOLUME_STATE_HPP__ <|endoftext|>
<commit_before>// This code is based on Sabberstone project. // Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva // Hearthstone++ is hearthstone simulator using C++ with reinforcement learning. // Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon #include <Rosetta/Games/Game.hpp> #include <Rosetta/Tasks/SimpleTasks/IncludeTask.hpp> #include <stdexcept> namespace RosettaStone::SimpleTasks { TaskID IncludeTask::GetTaskID() const { return TaskID::INCLUDE; } std::vector<Entity*> IncludeTask::GetEntities(EntityType entityType, Player& player, Entity* source, Entity* target) { std::vector<Entity*> entities; switch (entityType) { case EntityType::SOURCE: entities.emplace_back(source); break; case EntityType::TARGET: entities.emplace_back(target); break; case EntityType::HERO: entities.emplace_back(player.GetHero()); break; case EntityType::FRIENDS: for (auto& minion : player.GetField().GetAllMinions()) { entities.emplace_back(minion); } entities.emplace_back(player.GetHero()); break; case EntityType::ENEMIES: for (auto& minion : player.GetOpponent().GetField().GetAllMinions()) { entities.emplace_back(minion); } entities.emplace_back(player.GetOpponent().GetHero()); break; case EntityType::ENEMY_HERO: entities.emplace_back(player.GetOpponent().GetHero()); break; case EntityType::WEAPON: if (player.GetHero()->weapon != nullptr) { entities.emplace_back(player.GetHero()->weapon); } break; case EntityType::ENEMY_WEAPON: if (player.GetOpponent().GetHero()->weapon != nullptr) { entities.emplace_back(player.GetOpponent().GetHero()->weapon); } break; case EntityType::ENEMY_FIELD: for (auto& minion : player.GetOpponent().GetField().GetAllMinions()) { entities.emplace_back(minion); } break; case EntityType::STACK: entities = player.GetGame()->taskStack; break; default: throw std::domain_error( "IncludeTask::GetEntities() - Invalid entity type"); } return entities; } TaskStatus IncludeTask::Impl(Player&) { return TaskStatus::COMPLETE; } } // namespace RosettaStone::SimpleTasks <commit_msg>refactor: Process case 'EntityType::ALL'<commit_after>// This code is based on Sabberstone project. // Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva // Hearthstone++ is hearthstone simulator using C++ with reinforcement learning. // Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon #include <Rosetta/Games/Game.hpp> #include <Rosetta/Tasks/SimpleTasks/IncludeTask.hpp> #include <stdexcept> namespace RosettaStone::SimpleTasks { TaskID IncludeTask::GetTaskID() const { return TaskID::INCLUDE; } std::vector<Entity*> IncludeTask::GetEntities(EntityType entityType, Player& player, Entity* source, Entity* target) { std::vector<Entity*> entities; switch (entityType) { case EntityType::SOURCE: entities.emplace_back(source); break; case EntityType::TARGET: entities.emplace_back(target); break; case EntityType::ALL: for (auto& minion : player.GetField().GetAllMinions()) { entities.emplace_back(minion); } entities.emplace_back(player.GetHero()); for (auto& minion : player.GetOpponent().GetField().GetAllMinions()) { entities.emplace_back(minion); } entities.emplace_back(player.GetOpponent().GetHero()); break; case EntityType::FRIENDS: for (auto& minion : player.GetField().GetAllMinions()) { entities.emplace_back(minion); } entities.emplace_back(player.GetHero()); break; case EntityType::ENEMIES: for (auto& minion : player.GetOpponent().GetField().GetAllMinions()) { entities.emplace_back(minion); } entities.emplace_back(player.GetOpponent().GetHero()); break; case EntityType::HERO: entities.emplace_back(player.GetHero()); break; case EntityType::ENEMY_HERO: entities.emplace_back(player.GetOpponent().GetHero()); break; case EntityType::WEAPON: if (player.GetHero()->weapon != nullptr) { entities.emplace_back(player.GetHero()->weapon); } break; case EntityType::ENEMY_WEAPON: if (player.GetOpponent().GetHero()->weapon != nullptr) { entities.emplace_back(player.GetOpponent().GetHero()->weapon); } break; case EntityType::ENEMY_FIELD: for (auto& minion : player.GetOpponent().GetField().GetAllMinions()) { entities.emplace_back(minion); } break; case EntityType::STACK: entities = player.GetGame()->taskStack; break; default: throw std::domain_error( "IncludeTask::GetEntities() - Invalid entity type"); } return entities; } TaskStatus IncludeTask::Impl(Player&) { return TaskStatus::COMPLETE; } } // namespace RosettaStone::SimpleTasks <|endoftext|>
<commit_before>//===-- PPCTargetMachine.cpp - Define TargetMachine for PowerPC -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Top-level implementation for the PowerPC target. // //===----------------------------------------------------------------------===// #include "PPCTargetMachine.h" #include "PPC.h" #include "llvm/CodeGen/Passes.h" #include "llvm/MC/MCStreamer.h" #include "llvm/PassManager.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FormattedStream.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Target/TargetOptions.h" using namespace llvm; static cl:: opt<bool> DisableCTRLoops("disable-ppc-ctrloops", cl::Hidden, cl::desc("Disable CTR loops for PPC")); extern "C" void LLVMInitializePowerPCTarget() { // Register the targets RegisterTargetMachine<PPC32TargetMachine> A(ThePPC32Target); RegisterTargetMachine<PPC64TargetMachine> B(ThePPC64Target); RegisterTargetMachine<PPC64TargetMachine> C(ThePPC64LETarget); } /// Return the datalayout string of a subtarget. static std::string getDataLayoutString(const PPCSubtarget &ST) { const Triple &T = ST.getTargetTriple(); // PPC is big endian. std::string Ret = "E"; Ret += DataLayout::getManglingComponent(T); // PPC32 has 32 bit pointers. The PS3 (OS Lv2) is a PPC64 machine with 32 bit // pointers. if (!ST.isPPC64() || T.getOS() == Triple::Lv2) Ret += "-p:32:32"; // Note, the alignment values for f64 and i64 on ppc64 in Darwin // documentation are wrong; these are correct (i.e. "what gcc does"). if (ST.isPPC64() || ST.isSVR4ABI()) Ret += "-i64:64"; else Ret += "-f64:32:64"; // PPC64 has 32 and 64 bit registers, PPC32 has only 32 bit ones. if (ST.isPPC64()) Ret += "-n32:64"; else Ret += "-n32"; return Ret; } PPCTargetMachine::PPCTargetMachine(const Target &T, StringRef TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOpt::Level OL, bool is64Bit) : LLVMTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL), Subtarget(TT, CPU, FS, is64Bit, OL), DL(getDataLayoutString(Subtarget)), InstrInfo(*this), FrameLowering(Subtarget), JITInfo(*this, is64Bit), TLInfo(*this), TSInfo(*this), InstrItins(Subtarget.getInstrItineraryData()) { initAsmInfo(); } void PPC32TargetMachine::anchor() { } PPC32TargetMachine::PPC32TargetMachine(const Target &T, StringRef TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOpt::Level OL) : PPCTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) { } void PPC64TargetMachine::anchor() { } PPC64TargetMachine::PPC64TargetMachine(const Target &T, StringRef TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOpt::Level OL) : PPCTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) { } //===----------------------------------------------------------------------===// // Pass Pipeline Configuration //===----------------------------------------------------------------------===// namespace { /// PPC Code Generator Pass Configuration Options. class PPCPassConfig : public TargetPassConfig { public: PPCPassConfig(PPCTargetMachine *TM, PassManagerBase &PM) : TargetPassConfig(TM, PM) {} PPCTargetMachine &getPPCTargetMachine() const { return getTM<PPCTargetMachine>(); } const PPCSubtarget &getPPCSubtarget() const { return *getPPCTargetMachine().getSubtargetImpl(); } virtual bool addPreISel(); virtual bool addILPOpts(); virtual bool addInstSelector(); virtual bool addPreSched2(); virtual bool addPreEmitPass(); }; } // namespace TargetPassConfig *PPCTargetMachine::createPassConfig(PassManagerBase &PM) { return new PPCPassConfig(this, PM); } bool PPCPassConfig::addPreISel() { if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None) addPass(createPPCCTRLoops(getPPCTargetMachine())); return false; } bool PPCPassConfig::addILPOpts() { if (getPPCSubtarget().hasISEL()) { addPass(&EarlyIfConverterID); return true; } return false; } bool PPCPassConfig::addInstSelector() { // Install an instruction selector. addPass(createPPCISelDag(getPPCTargetMachine())); #ifndef NDEBUG if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None) addPass(createPPCCTRLoopsVerify()); #endif return false; } bool PPCPassConfig::addPreSched2() { if (getOptLevel() != CodeGenOpt::None) addPass(&IfConverterID); return true; } bool PPCPassConfig::addPreEmitPass() { if (getOptLevel() != CodeGenOpt::None) addPass(createPPCEarlyReturnPass()); // Must run branch selection immediately preceding the asm printer. addPass(createPPCBranchSelectionPass()); return false; } bool PPCTargetMachine::addCodeEmitter(PassManagerBase &PM, JITCodeEmitter &JCE) { // Inform the subtarget that we are in JIT mode. FIXME: does this break macho // writing? Subtarget.SetJITMode(); // Machine code emitter pass for PowerPC. PM.add(createPPCJITCodeEmitterPass(*this, JCE)); return false; } void PPCTargetMachine::addAnalysisPasses(PassManagerBase &PM) { // Add first the target-independent BasicTTI pass, then our PPC pass. This // allows the PPC pass to delegate to the target independent layer when // appropriate. PM.add(createBasicTargetTransformInfoPass(this)); PM.add(createPPCTargetTransformInfoPass(this)); } <commit_msg>Update the datalayout string for ppc64LE.<commit_after>//===-- PPCTargetMachine.cpp - Define TargetMachine for PowerPC -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Top-level implementation for the PowerPC target. // //===----------------------------------------------------------------------===// #include "PPCTargetMachine.h" #include "PPC.h" #include "llvm/CodeGen/Passes.h" #include "llvm/MC/MCStreamer.h" #include "llvm/PassManager.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FormattedStream.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Target/TargetOptions.h" using namespace llvm; static cl:: opt<bool> DisableCTRLoops("disable-ppc-ctrloops", cl::Hidden, cl::desc("Disable CTR loops for PPC")); extern "C" void LLVMInitializePowerPCTarget() { // Register the targets RegisterTargetMachine<PPC32TargetMachine> A(ThePPC32Target); RegisterTargetMachine<PPC64TargetMachine> B(ThePPC64Target); RegisterTargetMachine<PPC64TargetMachine> C(ThePPC64LETarget); } /// Return the datalayout string of a subtarget. static std::string getDataLayoutString(const PPCSubtarget &ST) { const Triple &T = ST.getTargetTriple(); std::string Ret; // Most PPC* platforms are big endian, PPC64LE is little endian. if (ST.isLittleEndian()) Ret = "e"; else Ret = "E"; Ret += DataLayout::getManglingComponent(T); // PPC32 has 32 bit pointers. The PS3 (OS Lv2) is a PPC64 machine with 32 bit // pointers. if (!ST.isPPC64() || T.getOS() == Triple::Lv2) Ret += "-p:32:32"; // Note, the alignment values for f64 and i64 on ppc64 in Darwin // documentation are wrong; these are correct (i.e. "what gcc does"). if (ST.isPPC64() || ST.isSVR4ABI()) Ret += "-i64:64"; else Ret += "-f64:32:64"; // PPC64 has 32 and 64 bit registers, PPC32 has only 32 bit ones. if (ST.isPPC64()) Ret += "-n32:64"; else Ret += "-n32"; return Ret; } PPCTargetMachine::PPCTargetMachine(const Target &T, StringRef TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOpt::Level OL, bool is64Bit) : LLVMTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL), Subtarget(TT, CPU, FS, is64Bit, OL), DL(getDataLayoutString(Subtarget)), InstrInfo(*this), FrameLowering(Subtarget), JITInfo(*this, is64Bit), TLInfo(*this), TSInfo(*this), InstrItins(Subtarget.getInstrItineraryData()) { initAsmInfo(); } void PPC32TargetMachine::anchor() { } PPC32TargetMachine::PPC32TargetMachine(const Target &T, StringRef TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOpt::Level OL) : PPCTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) { } void PPC64TargetMachine::anchor() { } PPC64TargetMachine::PPC64TargetMachine(const Target &T, StringRef TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Reloc::Model RM, CodeModel::Model CM, CodeGenOpt::Level OL) : PPCTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) { } //===----------------------------------------------------------------------===// // Pass Pipeline Configuration //===----------------------------------------------------------------------===// namespace { /// PPC Code Generator Pass Configuration Options. class PPCPassConfig : public TargetPassConfig { public: PPCPassConfig(PPCTargetMachine *TM, PassManagerBase &PM) : TargetPassConfig(TM, PM) {} PPCTargetMachine &getPPCTargetMachine() const { return getTM<PPCTargetMachine>(); } const PPCSubtarget &getPPCSubtarget() const { return *getPPCTargetMachine().getSubtargetImpl(); } virtual bool addPreISel(); virtual bool addILPOpts(); virtual bool addInstSelector(); virtual bool addPreSched2(); virtual bool addPreEmitPass(); }; } // namespace TargetPassConfig *PPCTargetMachine::createPassConfig(PassManagerBase &PM) { return new PPCPassConfig(this, PM); } bool PPCPassConfig::addPreISel() { if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None) addPass(createPPCCTRLoops(getPPCTargetMachine())); return false; } bool PPCPassConfig::addILPOpts() { if (getPPCSubtarget().hasISEL()) { addPass(&EarlyIfConverterID); return true; } return false; } bool PPCPassConfig::addInstSelector() { // Install an instruction selector. addPass(createPPCISelDag(getPPCTargetMachine())); #ifndef NDEBUG if (!DisableCTRLoops && getOptLevel() != CodeGenOpt::None) addPass(createPPCCTRLoopsVerify()); #endif return false; } bool PPCPassConfig::addPreSched2() { if (getOptLevel() != CodeGenOpt::None) addPass(&IfConverterID); return true; } bool PPCPassConfig::addPreEmitPass() { if (getOptLevel() != CodeGenOpt::None) addPass(createPPCEarlyReturnPass()); // Must run branch selection immediately preceding the asm printer. addPass(createPPCBranchSelectionPass()); return false; } bool PPCTargetMachine::addCodeEmitter(PassManagerBase &PM, JITCodeEmitter &JCE) { // Inform the subtarget that we are in JIT mode. FIXME: does this break macho // writing? Subtarget.SetJITMode(); // Machine code emitter pass for PowerPC. PM.add(createPPCJITCodeEmitterPass(*this, JCE)); return false; } void PPCTargetMachine::addAnalysisPasses(PassManagerBase &PM) { // Add first the target-independent BasicTTI pass, then our PPC pass. This // allows the PPC pass to delegate to the target independent layer when // appropriate. PM.add(createBasicTargetTransformInfoPass(this)); PM.add(createPPCTargetTransformInfoPass(this)); } <|endoftext|>
<commit_before>#ifndef VSMC_INTERNAL_FORWARD_HPP #define VSMC_INTERNAL_FORWARD_HPP namespace vsmc { namespace internal { class WeightBase; template <typename> class Weight; template <typename, typename> class InitializeBase; template <typename, typename> class MoveBase; template <typename, typename> class MonitorEvalBase; template <typename, typename> class PathEvalBase; } // namespace vsmc::internal class NullTimer; class VBase {}; template <typename> class Sampler; template <typename> class Particle; template <typename> class Monitor; template <typename> class Path; template <unsigned, typename, typename> class StateBase; template <typename> class SingleParticle; template <typename> class ConstSingleParticle; template <unsigned, typename, typename T = NullTimer> class StateSeq; template <typename, typename D = VBase> class InitializeSeq; template <typename, typename D = VBase> class MoveSeq; template <typename, typename D = VBase> class MonitorEvalSeq; template <typename, typename D = VBase> class PathEvalSeq; template <unsigned, typename, typename T = NullTimer> class StateOMP; template <typename, typename D = VBase> class InitializeOMP; template <typename, typename D = VBase> class MoveOMP; template <typename, typename D = VBase> class MonitorEvalOMP; template <typename, typename D = VBase> class PathEvalOMP; template <unsigned, typename, typename T = NullTimer> class StateTBB; template <typename, typename D = VBase> class InitializeTBB; template <typename, typename D = VBase> class MoveTBB; template <typename, typename D = VBase> class MonitorEvalTBB; template <typename, typename D = VBase> class PathEvalTBB; template <unsigned, typename, typename P = NullTimer> class StateCL; template <typename> class InitializeCL; template <typename> class MoveCL; template <typename> class MonitorEvalCL; template <typename> class PathEvalCL; } // namesapce vsmc #endif // VSMC_INTERNAL_FORWARD_HPP <commit_msg>Remove VBase implementation<commit_after>#ifndef VSMC_INTERNAL_FORWARD_HPP #define VSMC_INTERNAL_FORWARD_HPP namespace vsmc { namespace internal { class WeightBase; template <typename> class Weight; template <typename, typename> class InitializeBase; template <typename, typename> class MoveBase; template <typename, typename> class MonitorEvalBase; template <typename, typename> class PathEvalBase; } // namespace vsmc::internal class NullTimer; class VBase; template <typename> class Sampler; template <typename> class Particle; template <typename> class Monitor; template <typename> class Path; template <unsigned, typename, typename> class StateBase; template <typename> class SingleParticle; template <typename> class ConstSingleParticle; template <unsigned, typename, typename T = NullTimer> class StateSeq; template <typename, typename D = VBase> class InitializeSeq; template <typename, typename D = VBase> class MoveSeq; template <typename, typename D = VBase> class MonitorEvalSeq; template <typename, typename D = VBase> class PathEvalSeq; template <unsigned, typename, typename T = NullTimer> class StateOMP; template <typename, typename D = VBase> class InitializeOMP; template <typename, typename D = VBase> class MoveOMP; template <typename, typename D = VBase> class MonitorEvalOMP; template <typename, typename D = VBase> class PathEvalOMP; template <unsigned, typename, typename T = NullTimer> class StateTBB; template <typename, typename D = VBase> class InitializeTBB; template <typename, typename D = VBase> class MoveTBB; template <typename, typename D = VBase> class MonitorEvalTBB; template <typename, typename D = VBase> class PathEvalTBB; template <unsigned, typename, typename P = NullTimer> class StateCL; template <typename> class InitializeCL; template <typename> class MoveCL; template <typename> class MonitorEvalCL; template <typename> class PathEvalCL; } // namesapce vsmc #endif // VSMC_INTERNAL_FORWARD_HPP <|endoftext|>
<commit_before>// Copyright (c) 2012 Plenluno All rights reserved. #include <libj/value.h> int main() { libj::Value v = 5; libj::Value* vp = &v; int* ip; libj::to<const int>(vp, &ip); return 0; } <commit_msg>fix a cpplint warning<commit_after>// Copyright (c) 2012 Plenluno All rights reserved. #include <libj/value.h> int main() { libj::Value v = 5; libj::Value* vp = &v; int* ip; libj::to<const int>(vp, &ip); return 0; } <|endoftext|>
<commit_before>/** * @file GoalSymbols.cpp * * @author <a href="mailto:[email protected]">Martin Martius</a> * Implementation of class GoalSymbols */ #include "GoalSymbols.h" void GoalSymbols::registerSymbols(xabsl::Engine& engine) { // a whole goal was seen engine.registerDecimalInputSymbol("goal.own.whole.time_since_seen", &getTimeSinceWholeOwnGoalSeen); engine.registerDecimalInputSymbol("goal.opp.whole.time_since_seen", &getTimeSinceWholeOppGoalSeen); // at least one goal post was seen engine.registerDecimalInputSymbol("goal.opp.time_since_seen", &getTimeSinceOpponentGoalSeen); engine.registerDecimalInputSymbol("goal.own.time_since_seen", &getTimeSinceOwnGoalSeen); //engine.registerDecimalInputSymbol("goal.opp.x", &getOpponentGoalX); //engine.registerDecimalInputSymbol("goal.opp.y", &getOpponentGoalY); //engine.registerDecimalInputSymbol("goal.opp.angle", &getAngleToOpponentGoal); //engine.registerDecimalInputSymbol("goal.opp.distance", &getDistanceToOpponentGoal); //engine.registerDecimalInputSymbol("goal.own.x", &getOwnGoalX); //engine.registerDecimalInputSymbol("goal.own.y", &getOwnGoalY); //engine.registerDecimalInputSymbol("goal.own.angle", &getAngleToOwnGoal); //engine.registerDecimalInputSymbol("goal.own.distance", &getDistanceToOwnGoal); // goal percept symbols engine.registerDecimalInputSymbol("goal.centroid.x", &getGoalCentroidX); engine.registerDecimalInputSymbol("goal.centroid.y", &getGoalCentroidY); engine.registerDecimalInputSymbol("goal.centroid.z", &getGoalCentroidZ); engine.registerBooleanInputSymbol("goal.opp.was_seen", &getOpponentGoalWasSeen); engine.registerBooleanInputSymbol("goal.own.was_seen", &getOwnGoalWasSeen); //to provide that the goal model is valid, when to clusters are build engine.registerBooleanInputSymbol("goal.opp.isValid", &localGoalModel.opponentGoalIsValid); // engine.registerDecimalInputSymbol("goal.opp.seen_angle", &getAngleToOpponentGoal); //engine.registerDecimalInputSymbol("goal.own.seen_angle", &getAngleToOwnGoal); engine.registerDecimalInputSymbol("goal.opp.seen_center.x", &localGoalModel.seen_center.x); engine.registerDecimalInputSymbol("goal.opp.seen_center.y", &localGoalModel.seen_center.y); }//end registerSymbols GoalSymbols* GoalSymbols::theInstance = NULL; void GoalSymbols::execute() { } double GoalSymbols::getTimeSinceWholeOwnGoalSeen() { const GoalModel::Goal& goal = theInstance->getSensingGoalModel().getOwnGoal(theInstance->compassDirection, theInstance->fieldInfo); return (double) theInstance->frameInfo.getTimeSince(goal.frameInfoWhenGoalLastSeen.getTime()); }//end getTimeSinceWholeOwnGoalSeen double GoalSymbols::getTimeSinceWholeOppGoalSeen() { const GoalModel::Goal& goal = theInstance->getSensingGoalModel().getOwnGoal(theInstance->compassDirection, theInstance->fieldInfo); return (double) theInstance->frameInfo.getTimeSince(goal.frameInfoWhenGoalLastSeen.getTime()); }//end getTimeSinceWholeOppGoalSeen double GoalSymbols::getOpponentGoalX() { return theInstance->localGoalModel.getOppGoal(theInstance->compassDirection, theInstance->fieldInfo).calculateCenter().x; }//end getOpponentGoalX double GoalSymbols::getOpponentGoalY() { return theInstance->localGoalModel.getOppGoal(theInstance->compassDirection, theInstance->fieldInfo).calculateCenter().y; }//end getOpponentGoalY double GoalSymbols::getAngleToOpponentGoal() { return Math::toDegrees(theInstance->localGoalModel.seen_angle); }//end getAngleToOpGoal double GoalSymbols::getDistanceToOpponentGoal() { return theInstance->localGoalModel.getOppGoal(theInstance->compassDirection, theInstance->fieldInfo).calculateCenter().abs(); }//end getDistanceToOpponentGoal double GoalSymbols::getTimeSinceOpponentGoalSeen() { return (double) theInstance->frameInfo.getTimeSince( theInstance->localGoalModel.frameWhenOpponentGoalWasSeen.getTime()); }//end getTimeSinceOpponentGoalSeen double GoalSymbols::getOwnGoalX() { return theInstance->localGoalModel.getOwnGoal(theInstance->compassDirection, theInstance->fieldInfo).calculateCenter().x; }//end getOwnGoalX double GoalSymbols::getOwnGoalY() { return theInstance->localGoalModel.getOwnGoal(theInstance->compassDirection, theInstance->fieldInfo).calculateCenter().y; }//end getOwnGoalY double GoalSymbols::getGoalCentroidX() { const GoalPercept& m = theInstance->goalPercept; return m.goalCentroid.x; }//end getGoalCentroidX double GoalSymbols::getGoalCentroidY() { const GoalPercept& m = theInstance->goalPercept; return m.goalCentroid.y; }//end getGoalCentroidY double GoalSymbols::getGoalCentroidZ() { const GoalPercept& m = theInstance->goalPercept; return m.goalCentroid.z; }//end getGoalCentroidZ double GoalSymbols::getAngleToOwnGoal() { double radAngle = theInstance->localGoalModel.getOwnGoal(theInstance->compassDirection, theInstance->fieldInfo).calculateCenter().angle(); return Math::toDegrees(radAngle); }//end getAngleToOwnGoal double GoalSymbols::getDistanceToOwnGoal() { return theInstance->localGoalModel.getOwnGoal(theInstance->compassDirection, theInstance->fieldInfo).calculateCenter().abs(); }//end getDistanceToOwnGoal double GoalSymbols::getTimeSinceOwnGoalSeen() { return (double) theInstance->frameInfo.getTimeSince( theInstance->localGoalModel.getOwnGoal(theInstance->compassDirection, theInstance->fieldInfo).frameInfoWhenGoalLastSeen.getTime()); }//end getTimeSinceOpponentGoalSeen //FIXME not via color decideable! bool GoalSymbols::getOpponentGoalWasSeen() { /* ColorClasses::Color goalColor = (theInstance->playerInfo.gameData.teamColor == GameData::blue)?ColorClasses::yellow:ColorClasses::skyblue; for(unsigned int i = 0; i < theInstance->goalPercept.getNumberOfSeenPosts(); i++) if(theInstance->goalPercept.getPost(i).color == goalColor && theInstance->goalPercept.getPost(i).positionReliable) return true; */ return theInstance->localGoalModel.opponentGoalIsValid && theInstance->localGoalModel.someGoalWasSeen; }//end getOpponentGoalWasSeen bool GoalSymbols::getOwnGoalWasSeen() { return theInstance->localGoalModel.ownGoalIsValid && theInstance->localGoalModel.someGoalWasSeen; }//end getOpponentGoalWasSeen <commit_msg>little clean<commit_after>/** * @file GoalSymbols.cpp * * @author <a href="mailto:[email protected]">Martin Martius</a> * Implementation of class GoalSymbols */ #include "GoalSymbols.h" void GoalSymbols::registerSymbols(xabsl::Engine& engine) { // a whole goal was seen engine.registerDecimalInputSymbol("goal.own.whole.time_since_seen", &getTimeSinceWholeOwnGoalSeen); engine.registerDecimalInputSymbol("goal.opp.whole.time_since_seen", &getTimeSinceWholeOppGoalSeen); // at least one goal post was seen engine.registerDecimalInputSymbol("goal.opp.time_since_seen", &getTimeSinceOpponentGoalSeen); engine.registerDecimalInputSymbol("goal.own.time_since_seen", &getTimeSinceOwnGoalSeen); //engine.registerDecimalInputSymbol("goal.opp.x", &getOpponentGoalX); //engine.registerDecimalInputSymbol("goal.opp.y", &getOpponentGoalY); //engine.registerDecimalInputSymbol("goal.opp.angle", &getAngleToOpponentGoal); //engine.registerDecimalInputSymbol("goal.opp.distance", &getDistanceToOpponentGoal); //engine.registerDecimalInputSymbol("goal.own.x", &getOwnGoalX); //engine.registerDecimalInputSymbol("goal.own.y", &getOwnGoalY); //engine.registerDecimalInputSymbol("goal.own.angle", &getAngleToOwnGoal); //engine.registerDecimalInputSymbol("goal.own.distance", &getDistanceToOwnGoal); // goal percept symbols engine.registerDecimalInputSymbol("goal.centroid.x", &getGoalCentroidX); engine.registerDecimalInputSymbol("goal.centroid.y", &getGoalCentroidY); engine.registerDecimalInputSymbol("goal.centroid.z", &getGoalCentroidZ); engine.registerBooleanInputSymbol("goal.opp.was_seen", &getOpponentGoalWasSeen); engine.registerBooleanInputSymbol("goal.own.was_seen", &getOwnGoalWasSeen); //to provide that the goal model is valid, when to clusters are build engine.registerBooleanInputSymbol("goal.opp.isValid", &localGoalModel.opponentGoalIsValid); // engine.registerDecimalInputSymbol("goal.opp.seen_angle", &getAngleToOpponentGoal); //engine.registerDecimalInputSymbol("goal.own.seen_angle", &getAngleToOwnGoal); engine.registerDecimalInputSymbol("goal.opp.seen_center.x", &localGoalModel.seen_center.x); engine.registerDecimalInputSymbol("goal.opp.seen_center.y", &localGoalModel.seen_center.y); }//end registerSymbols GoalSymbols* GoalSymbols::theInstance = NULL; void GoalSymbols::execute() { } double GoalSymbols::getTimeSinceWholeOwnGoalSeen() { const GoalModel::Goal& goal = theInstance->getSensingGoalModel().getOwnGoal(theInstance->compassDirection, theInstance->fieldInfo); return (double) theInstance->frameInfo.getTimeSince(goal.frameInfoWhenGoalLastSeen.getTime()); }//end getTimeSinceWholeOwnGoalSeen double GoalSymbols::getTimeSinceWholeOppGoalSeen() { const GoalModel::Goal& goal = theInstance->getSensingGoalModel().getOwnGoal(theInstance->compassDirection, theInstance->fieldInfo); return (double) theInstance->frameInfo.getTimeSince(goal.frameInfoWhenGoalLastSeen.getTime()); }//end getTimeSinceWholeOppGoalSeen double GoalSymbols::getOpponentGoalX() { return theInstance->localGoalModel.getOppGoal(theInstance->compassDirection, theInstance->fieldInfo).calculateCenter().x; }//end getOpponentGoalX double GoalSymbols::getOpponentGoalY() { return theInstance->localGoalModel.getOppGoal(theInstance->compassDirection, theInstance->fieldInfo).calculateCenter().y; }//end getOpponentGoalY double GoalSymbols::getAngleToOpponentGoal() { return Math::toDegrees(theInstance->localGoalModel.seen_angle); }//end getAngleToOpGoal double GoalSymbols::getDistanceToOpponentGoal() { return theInstance->localGoalModel.getOppGoal(theInstance->compassDirection, theInstance->fieldInfo).calculateCenter().abs(); }//end getDistanceToOpponentGoal double GoalSymbols::getTimeSinceOpponentGoalSeen() { return (double) theInstance->frameInfo.getTimeSince( theInstance->localGoalModel.frameWhenOpponentGoalWasSeen.getTime()); }//end getTimeSinceOpponentGoalSeen double GoalSymbols::getOwnGoalX() { return theInstance->localGoalModel.getOwnGoal(theInstance->compassDirection, theInstance->fieldInfo).calculateCenter().x; }//end getOwnGoalX double GoalSymbols::getOwnGoalY() { return theInstance->localGoalModel.getOwnGoal(theInstance->compassDirection, theInstance->fieldInfo).calculateCenter().y; }//end getOwnGoalY double GoalSymbols::getGoalCentroidX() { const GoalPercept& m = theInstance->goalPercept; return m.goalCentroid.x; }//end getGoalCentroidX double GoalSymbols::getGoalCentroidY() { const GoalPercept& m = theInstance->goalPercept; return m.goalCentroid.y; }//end getGoalCentroidY double GoalSymbols::getGoalCentroidZ() { const GoalPercept& m = theInstance->goalPercept; return m.goalCentroid.z; }//end getGoalCentroidZ double GoalSymbols::getAngleToOwnGoal() { double radAngle = theInstance->localGoalModel.getOwnGoal(theInstance->compassDirection, theInstance->fieldInfo).calculateCenter().angle(); return Math::toDegrees(radAngle); }//end getAngleToOwnGoal double GoalSymbols::getDistanceToOwnGoal() { return theInstance->localGoalModel.getOwnGoal(theInstance->compassDirection, theInstance->fieldInfo).calculateCenter().abs(); }//end getDistanceToOwnGoal double GoalSymbols::getTimeSinceOwnGoalSeen() { return (double) theInstance->frameInfo.getTimeSince( theInstance->localGoalModel.getOwnGoal(theInstance->compassDirection, theInstance->fieldInfo).frameInfoWhenGoalLastSeen.getTime()); }//end getTimeSinceOpponentGoalSeen bool GoalSymbols::getOpponentGoalWasSeen() { return theInstance->localGoalModel.opponentGoalIsValid && theInstance->localGoalModel.someGoalWasSeen; } bool GoalSymbols::getOwnGoalWasSeen() { return theInstance->localGoalModel.ownGoalIsValid && theInstance->localGoalModel.someGoalWasSeen; } <|endoftext|>
<commit_before>/** * Non-metric Space Library * * Authors: Bilegsaikhan Naidan (https://github.com/bileg), Leonid Boytsov (http://boytsov.info). * With contributions from Lawrence Cayton (http://lcayton.com/) and others. * * For the complete list of contributors and further details see: * https://github.com/searchivarius/NonMetricSpaceLib * * Copyright (c) 2014 * * This code is released under the * Apache License Version 2.0 http://www.apache.org/licenses/. * */ #include <unordered_map> #include <queue> #include "space.h" #include "knnquery.h" #include "method/simple_inverted_index.h" #include "falconn_heap_mod.h" #define SANITY_CHECKS namespace similarity { using namespace std; template <typename dist_t> void SimplInvIndex<dist_t>::Search(KNNQuery<dist_t>* query, IdType) const { vector<SparseVectElem<dist_t>> query_vect; const Object* o = query->QueryObject(); UnpackSparseElements(o->data(), o->datalength(), query_vect); #if 0 vector<IdType> postPos(query_vect.size()); vector<const PostList*> posts(query_vect.size()); for (size_t qi = 0; qi < query_vect.size(); ++qi) { auto it = index_.find(query_vect[qi].id_); if (it != index_.end()) { // There may be out-of-vocabulary words const PostList& pl = *it->second; posts[qi] = &pl; } } for (IdType did = 0;did < data_.size(); ++did) { float accum = 0; for (size_t qi = 0; qi < query_vect.size(); ++qi) { const PostList* pPostList = posts[qi]; if (pPostList == nullptr) continue; while (postPos[qi] < pPostList->qty_ && pPostList->entries_[postPos[qi]].doc_id_ < did) { postPos[qi]++; } if (postPos[qi] < pPostList->qty_ && pPostList->entries_[postPos[qi]].doc_id_ == did) { accum += query_vect[qi].val_ * pPostList->entries_[postPos[qi]].val_; } } if (accum > 0) query->CheckAndAddToResult(-accum, data_[did]); } #else size_t K = query->GetK(); FalconnHeapMod1<dist_t, IdType> tmpResQueue; FalconnHeapMod1<IdType, int32_t> postListQueue; vector<unique_ptr<PostListQueryState>> queryStates(query_vect.size()); size_t wordQty = 0; for (auto e : query_vect) { auto it = index_.find(e.id_); if (it != index_.end()) { // There may be out-of-vocabulary words const PostList& pl = *it->second; CHECK(pl.qty_ > 0); ++wordQty; } } // While some people expect the result set to always contain at least k entries, // it's not clear what we return here if (0 == wordQty) return; unsigned qsi = 0; for (auto eQuery : query_vect) { uint32_t wordId = eQuery.id_; auto it = index_.find(wordId); if (it != index_.end()) { // There may be out-of-vocabulary words #ifdef SANITY_CHECKS CHECK(it->second.get() != nullptr); #endif const PostList& pl = *it->second; CHECK(pl.qty_ > 0); queryStates[qsi].reset(new PostListQueryState(pl, eQuery.val_, eQuery.val_ * pl.entries_[0].val_)); postListQueue.push(-pl.entries_[0].doc_id_, qsi); ++wordQty; } ++qsi; } dist_t accum = 0; // while (!postListQueue.empty()) { IdType minDocIdNeg = postListQueue.top_key(); while (!postListQueue.empty() && postListQueue.top_key() == minDocIdNeg) { unsigned qsi = postListQueue.top_data(); PostListQueryState& queryState = *queryStates[qsi]; const PostList& pl = *queryState.post_; accum += queryState.qval_x_docval_; //accum += queryState.qval_ * pl.entries_[queryState.post_pos_].val_; queryState.post_pos_++; // This will update data inside queue /* * If we didn't reach the end of the posting list, we retrieve the next document id. * Then, we push this update element down the priority queue. * * On reaching the end of the posting list, we evict the entry from the priority queue. */ if (queryState.post_pos_ < pl.qty_) { const auto& eDoc = pl.entries_[queryState.post_pos_]; /* * Leo thinks it may be beneficial to access the posting list entry only once. * This access is used for two things * 1) obtain the next doc id * 2) compute the contribution of the current document to the overall dot product (val_ * qval_) */ postListQueue.replace_top_key(-eDoc.doc_id_); queryState.qval_x_docval_ = eDoc.val_ * queryState.qval_; } else postListQueue.pop(); } // tmpResQueue is a MAX-QUEUE (which is what we need, b/c we maximize the dot product dist_t negAccum = -accum; #if 1 // This one seems to be a bit faster if (tmpResQueue.size() < K || tmpResQueue.top_key() == negAccum) tmpResQueue.push(negAccum, -minDocIdNeg); else if (tmpResQueue.top_key() > negAccum) tmpResQueue.replace_top(-accum, -minDocIdNeg); #else query->CheckAndAddToResult(negAccum, data_[-minDocIdNeg]); #endif accum = 0; } while (!tmpResQueue.empty()) { #ifdef SANITY_CHECKS CHECK(tmpResQueue.top_data() >= 0); #endif #if 0 query->CheckAndAddToResult(-tmpResQueue.top_key(), data_[tmpResQueue.top_data()]); #else // This branch recomputes the distance, but it normally has a negligibly small effect on the run-time query->CheckAndAddToResult(data_[tmpResQueue.top_data()]); #endif tmpResQueue.pop(); } #endif } template <typename dist_t> void SimplInvIndex<dist_t>::CreateIndex(const AnyParams& IndexParams) { AnyParamManager pmgr(IndexParams); pmgr.CheckUnused(); // Always call ResetQueryTimeParams() to set query-time parameters to their default values this->ResetQueryTimeParams(); // Let's first calculate memory requirements unordered_map<unsigned, size_t> dict_qty; vector<SparseVectElem<dist_t>> tmp_vect; LOG(LIB_INFO) << "Collecting dictionary stat"; for (const Object* o : data_) { tmp_vect.clear(); UnpackSparseElements(o->data(), o->datalength(), tmp_vect); for (const auto& e : tmp_vect) dict_qty[e.id_] ++; } // Create posting-list place holders unordered_map<unsigned, size_t> post_pos; LOG(LIB_INFO) << "Actually creating the index"; for (const auto dictEntry : dict_qty) { unsigned wordId = dictEntry.first; size_t qty = dictEntry.second; post_pos.insert(make_pair(wordId, 0)); index_.insert(make_pair(wordId, unique_ptr<PostList>(new PostList(qty)))); } // Fill posting lists for (size_t did = 0; did < data_.size(); ++did) { tmp_vect.clear(); UnpackSparseElements(data_[did]->data(), data_[did]->datalength(), tmp_vect); for (const auto& e : tmp_vect) { const auto wordId = e.id_; auto itPost = index_.find(wordId); auto itPostPos = post_pos.find(wordId); #ifdef SANITY_CHECKS CHECK(itPost != index_.end()); CHECK(itPostPos != post_pos.end()); CHECK(itPost->second.get() != nullptr); #endif PostList& pl = *itPost->second; size_t curr_pos = itPostPos->second++;; CHECK(curr_pos < pl.qty_); pl.entries_[curr_pos] = PostEntry(did, e.val_); } } #ifdef SANITY_CHECKS // Sanity check LOG(LIB_INFO) << "Sanity check"; for (const auto dictEntry : dict_qty) { unsigned wordId = dictEntry.first; size_t qty = dictEntry.second; CHECK(qty == post_pos[wordId]); } #endif } template <typename dist_t> SimplInvIndex<dist_t>::~SimplInvIndex() { // nothing here yet } template <typename dist_t> void SimplInvIndex<dist_t>::SetQueryTimeParams(const AnyParams& QueryTimeParams) { // Check if a user specified extra parameters, which can be also misspelled variants of existing ones AnyParamManager pmgr(QueryTimeParams); int dummy; // Note that GetParamOptional() should always have a default value pmgr.GetParamOptional("dummyParam", dummy, -1); LOG(LIB_INFO) << "Set dummy = " << dummy; pmgr.CheckUnused(); } template class SimplInvIndex<float>; } <commit_msg>removing some dead code<commit_after>/** * Non-metric Space Library * * Authors: Bilegsaikhan Naidan (https://github.com/bileg), Leonid Boytsov (http://boytsov.info). * With contributions from Lawrence Cayton (http://lcayton.com/) and others. * * For the complete list of contributors and further details see: * https://github.com/searchivarius/NonMetricSpaceLib * * Copyright (c) 2014 * * This code is released under the * Apache License Version 2.0 http://www.apache.org/licenses/. * */ #include <unordered_map> #include <queue> #include "space.h" #include "knnquery.h" #include "method/simple_inverted_index.h" #include "falconn_heap_mod.h" #define SANITY_CHECKS namespace similarity { using namespace std; template <typename dist_t> void SimplInvIndex<dist_t>::Search(KNNQuery<dist_t>* query, IdType) const { vector<SparseVectElem<dist_t>> query_vect; const Object* o = query->QueryObject(); UnpackSparseElements(o->data(), o->datalength(), query_vect); size_t K = query->GetK(); FalconnHeapMod1<dist_t, IdType> tmpResQueue; FalconnHeapMod1<IdType, int32_t> postListQueue; vector<unique_ptr<PostListQueryState>> queryStates(query_vect.size()); size_t wordQty = 0; for (auto e : query_vect) { auto it = index_.find(e.id_); if (it != index_.end()) { // There may be out-of-vocabulary words const PostList& pl = *it->second; CHECK(pl.qty_ > 0); ++wordQty; } } // While some people expect the result set to always contain at least k entries, // it's not clear what we return here if (0 == wordQty) return; unsigned qsi = 0; for (auto eQuery : query_vect) { uint32_t wordId = eQuery.id_; auto it = index_.find(wordId); if (it != index_.end()) { // There may be out-of-vocabulary words #ifdef SANITY_CHECKS CHECK(it->second.get() != nullptr); #endif const PostList& pl = *it->second; CHECK(pl.qty_ > 0); queryStates[qsi].reset(new PostListQueryState(pl, eQuery.val_, eQuery.val_ * pl.entries_[0].val_)); postListQueue.push(-pl.entries_[0].doc_id_, qsi); ++wordQty; } ++qsi; } dist_t accum = 0; // while (!postListQueue.empty()) { IdType minDocIdNeg = postListQueue.top_key(); while (!postListQueue.empty() && postListQueue.top_key() == minDocIdNeg) { unsigned qsi = postListQueue.top_data(); PostListQueryState& queryState = *queryStates[qsi]; const PostList& pl = *queryState.post_; accum += queryState.qval_x_docval_; //accum += queryState.qval_ * pl.entries_[queryState.post_pos_].val_; queryState.post_pos_++; // This will update data inside queue /* * If we didn't reach the end of the posting list, we retrieve the next document id. * Then, we push this update element down the priority queue. * * On reaching the end of the posting list, we evict the entry from the priority queue. */ if (queryState.post_pos_ < pl.qty_) { const auto& eDoc = pl.entries_[queryState.post_pos_]; /* * Leo thinks it may be beneficial to access the posting list entry only once. * This access is used for two things * 1) obtain the next doc id * 2) compute the contribution of the current document to the overall dot product (val_ * qval_) */ postListQueue.replace_top_key(-eDoc.doc_id_); queryState.qval_x_docval_ = eDoc.val_ * queryState.qval_; } else postListQueue.pop(); } // tmpResQueue is a MAX-QUEUE (which is what we need, b/c we maximize the dot product dist_t negAccum = -accum; #if 1 // This one seems to be a bit faster if (tmpResQueue.size() < K || tmpResQueue.top_key() == negAccum) tmpResQueue.push(negAccum, -minDocIdNeg); else if (tmpResQueue.top_key() > negAccum) tmpResQueue.replace_top(-accum, -minDocIdNeg); #else query->CheckAndAddToResult(negAccum, data_[-minDocIdNeg]); #endif accum = 0; } while (!tmpResQueue.empty()) { #ifdef SANITY_CHECKS CHECK(tmpResQueue.top_data() >= 0); #endif #if 0 query->CheckAndAddToResult(-tmpResQueue.top_key(), data_[tmpResQueue.top_data()]); #else // This branch recomputes the distance, but it normally has a negligibly small effect on the run-time query->CheckAndAddToResult(data_[tmpResQueue.top_data()]); #endif tmpResQueue.pop(); } } template <typename dist_t> void SimplInvIndex<dist_t>::CreateIndex(const AnyParams& IndexParams) { AnyParamManager pmgr(IndexParams); pmgr.CheckUnused(); // Always call ResetQueryTimeParams() to set query-time parameters to their default values this->ResetQueryTimeParams(); // Let's first calculate memory requirements unordered_map<unsigned, size_t> dict_qty; vector<SparseVectElem<dist_t>> tmp_vect; LOG(LIB_INFO) << "Collecting dictionary stat"; for (const Object* o : data_) { tmp_vect.clear(); UnpackSparseElements(o->data(), o->datalength(), tmp_vect); for (const auto& e : tmp_vect) dict_qty[e.id_] ++; } // Create posting-list place holders unordered_map<unsigned, size_t> post_pos; LOG(LIB_INFO) << "Actually creating the index"; for (const auto dictEntry : dict_qty) { unsigned wordId = dictEntry.first; size_t qty = dictEntry.second; post_pos.insert(make_pair(wordId, 0)); index_.insert(make_pair(wordId, unique_ptr<PostList>(new PostList(qty)))); } // Fill posting lists for (size_t did = 0; did < data_.size(); ++did) { tmp_vect.clear(); UnpackSparseElements(data_[did]->data(), data_[did]->datalength(), tmp_vect); for (const auto& e : tmp_vect) { const auto wordId = e.id_; auto itPost = index_.find(wordId); auto itPostPos = post_pos.find(wordId); #ifdef SANITY_CHECKS CHECK(itPost != index_.end()); CHECK(itPostPos != post_pos.end()); CHECK(itPost->second.get() != nullptr); #endif PostList& pl = *itPost->second; size_t curr_pos = itPostPos->second++;; CHECK(curr_pos < pl.qty_); pl.entries_[curr_pos] = PostEntry(did, e.val_); } } #ifdef SANITY_CHECKS // Sanity check LOG(LIB_INFO) << "Sanity check"; for (const auto dictEntry : dict_qty) { unsigned wordId = dictEntry.first; size_t qty = dictEntry.second; CHECK(qty == post_pos[wordId]); } #endif } template <typename dist_t> SimplInvIndex<dist_t>::~SimplInvIndex() { // nothing here yet } template <typename dist_t> void SimplInvIndex<dist_t>::SetQueryTimeParams(const AnyParams& QueryTimeParams) { // Check if a user specified extra parameters, which can be also misspelled variants of existing ones AnyParamManager pmgr(QueryTimeParams); int dummy; // Note that GetParamOptional() should always have a default value pmgr.GetParamOptional("dummyParam", dummy, -1); LOG(LIB_INFO) << "Set dummy = " << dummy; pmgr.CheckUnused(); } template class SimplInvIndex<float>; } <|endoftext|>
<commit_before>#ifndef __ANY_VALUE_HPP_INCLUDED #define __ANY_VALUE_HPP_INCLUDED // Include standard headers #include <cmath> // NAN, std::isnan, std::pow #include <string> // std::string #include <stdint.h> // uint32_t etc. namespace model { class World; } namespace datatypes { enum datatype { UNKNOWN, BOOL, FLOAT, DOUBLE, INT32_T, UINT32_T, VOID_POINTER, WORLD_POINTER }; } typedef struct AnyValue { AnyValue() : type(datatypes::UNKNOWN), bool_value(false), float_value(NAN), double_value(NAN), int32_t_value(0), uint32_t_value(0), void_pointer(nullptr), world_pointer(nullptr) { // constructor. } AnyValue(bool bool_value) : type(datatypes::BOOL), bool_value(bool_value), float_value(NAN), double_value(NAN), int32_t_value(0), uint32_t_value(0), void_pointer(nullptr), world_pointer(nullptr) { // constructor. } AnyValue(float float_value) : type(datatypes::FLOAT), bool_value(false), float_value(float_value), double_value(NAN), int32_t_value(0), uint32_t_value(0), void_pointer(nullptr), world_pointer(nullptr) { // constructor. } AnyValue(double double_value) : type(datatypes::DOUBLE), bool_value(false), float_value(NAN), double_value(double_value), int32_t_value(0), uint32_t_value(0), void_pointer(nullptr), world_pointer(nullptr) { // constructor. } AnyValue(int32_t int32_t_value) : type(datatypes::INT32_T), bool_value(false), float_value(NAN), double_value(NAN), int32_t_value(int32_t_value), uint32_t_value(0), void_pointer(nullptr), world_pointer(nullptr) { // constructor. } AnyValue(uint32_t uint32_t_value) : type(datatypes::UINT32_T), bool_value(false), float_value(NAN), double_value(NAN), int32_t_value(0), uint32_t_value(uint32_t_value), void_pointer(nullptr), world_pointer(nullptr) { // constructor. } AnyValue(void* void_pointer) : type(datatypes::VOID_POINTER), bool_value(false), float_value(NAN), double_value(NAN), int32_t_value(0), uint32_t_value(uint32_t_value), void_pointer(void_pointer), world_pointer(nullptr) { // constructor. } AnyValue(model::World* world_pointer) : type(datatypes::WORLD_POINTER), bool_value(false), float_value(NAN), double_value(NAN), int32_t_value(0), uint32_t_value(uint32_t_value), void_pointer(nullptr), world_pointer(world_pointer) { // constructor. } int type; bool bool_value; float float_value; double double_value; int32_t int32_t_value; uint32_t uint32_t_value; void* void_pointer; model::World* world_pointer; } AnyValue; #endif <commit_msg>Debug output for pointer `AnyValue` objects' constructors.<commit_after>#ifndef __ANY_VALUE_HPP_INCLUDED #define __ANY_VALUE_HPP_INCLUDED // Include standard headers #include <cmath> // NAN, std::isnan, std::pow #include <iostream> // std::cout, std::cin, std::cerr #include <string> // std::string #include <stdint.h> // uint32_t etc. namespace model { class World; } namespace datatypes { enum datatype { UNKNOWN, BOOL, FLOAT, DOUBLE, INT32_T, UINT32_T, VOID_POINTER, WORLD_POINTER }; } typedef struct AnyValue { AnyValue() : type(datatypes::UNKNOWN), bool_value(false), float_value(NAN), double_value(NAN), int32_t_value(0), uint32_t_value(0), void_pointer(nullptr), world_pointer(nullptr) { // constructor. } AnyValue(bool bool_value) : type(datatypes::BOOL), bool_value(bool_value), float_value(NAN), double_value(NAN), int32_t_value(0), uint32_t_value(0), void_pointer(nullptr), world_pointer(nullptr) { // constructor. } AnyValue(float float_value) : type(datatypes::FLOAT), bool_value(false), float_value(float_value), double_value(NAN), int32_t_value(0), uint32_t_value(0), void_pointer(nullptr), world_pointer(nullptr) { // constructor. } AnyValue(double double_value) : type(datatypes::DOUBLE), bool_value(false), float_value(NAN), double_value(double_value), int32_t_value(0), uint32_t_value(0), void_pointer(nullptr), world_pointer(nullptr) { // constructor. } AnyValue(int32_t int32_t_value) : type(datatypes::INT32_T), bool_value(false), float_value(NAN), double_value(NAN), int32_t_value(int32_t_value), uint32_t_value(0), void_pointer(nullptr), world_pointer(nullptr) { // constructor. } AnyValue(uint32_t uint32_t_value) : type(datatypes::UINT32_T), bool_value(false), float_value(NAN), double_value(NAN), int32_t_value(0), uint32_t_value(uint32_t_value), void_pointer(nullptr), world_pointer(nullptr) { // constructor. } AnyValue(void* void_pointer) : type(datatypes::VOID_POINTER), bool_value(false), float_value(NAN), double_value(NAN), int32_t_value(0), uint32_t_value(uint32_t_value), void_pointer(void_pointer), world_pointer(nullptr) { // constructor. std::cout << "creating AnyValue with void* value.\n"; } AnyValue(model::World* world_pointer) : type(datatypes::WORLD_POINTER), bool_value(false), float_value(NAN), double_value(NAN), int32_t_value(0), uint32_t_value(uint32_t_value), void_pointer(nullptr), world_pointer(world_pointer) { // constructor. std::cout << "creating AnyValue with model::World* value.\n"; } int type; bool bool_value; float float_value; double double_value; int32_t int32_t_value; uint32_t uint32_t_value; void* void_pointer; model::World* world_pointer; } AnyValue; #endif <|endoftext|>