blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
365e646409bb4cc413a758d947ebce54a552e53c
47ebaa434e78c396c4e6baa14f0b78073f08a549
/branches/NewDatabaseBackbone/server/src/network/asyncnetio.cpp
caae0303e17f031d6034b965e83ff50ffc1832a8
[]
no_license
BackupTheBerlios/wolfpack-svn
d0730dc59b6c78c6b517702e3825dd98410c2afd
4f738947dd076479af3db0251fb040cd665544d0
refs/heads/master
2021-10-13T13:52:36.548015
2013-11-01T01:16:57
2013-11-01T01:16:57
40,748,157
1
2
null
2021-09-30T04:28:19
2015-08-15T05:35:25
C++
UTF-8
C++
false
false
21,343
cpp
/* * Wolfpack Emu (WP) * UO Server Emulation Program * * Copyright 2001-2004 by holders identified in AUTHORS.txt * 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., 59 Temple Palace - Suite 330, Boston, MA 02111-1307, USA. * * In addition to that license, if you are running this program or modified * versions of it on a public system you HAVE TO make the complete source of * the version used by you available or provide people with a location to * download it. * * Wolfpack Homepage: http://developer.berlios.de/projects/wolfpack/ */ #include "asyncnetio.h" #include "uorxpackets.h" #include "uopacket.h" #include "../serverconfig.h" #include "../basics.h" // Library Includes #include <qsocketdevice.h> #include <qptrlist.h> #include <qmap.h> #include <algorithm> #undef CONST // Twofish #include "encryption.h" /*! \internal Table of packet lengths, automatically generated from Client Version: UO: LBR (Thrid Dawn) 3.0.8d 0xFFFF - Packet not used 0x0000 - Packet has dynamic length */ const Q_UINT16 packetLengths[256] = { 0x0068, 0x0005, 0x0007, 0x0000, 0x0002, 0x0005, 0x0005, 0x0007, // 0x00 0x000e, 0x0005, 0x0007, 0x010a, 0x0000, 0x0003, 0x0000, 0x003d, // 0x08 0x00d7, 0x0000, 0x0000, 0x000a, 0x0006, 0x0009, 0x0001, 0x0000, // 0x10 0x0000, 0x0000, 0x0000, 0x0025, 0x0000, 0x0005, 0x0004, 0x0008, // 0x18 0x0013, 0x0008, 0x0003, 0x001a, 0x0007, 0x0014, 0x0005, 0x0002, // 0x20 0x0005, 0x0001, 0x0005, 0x0002, 0x0002, 0x0011, 0x000f, 0x000a, // 0x28 0x0005, 0x0001, 0x0002, 0x0002, 0x000a, 0x028d, 0x0000, 0x0008, // 0x30 0x0007, 0x0009, 0x0000, 0x0000, 0x0000, 0x0002, 0x0025, 0x0000, // 0x38 0x00c9, 0x0000, 0x0000, 0x0229, 0x02c9, 0x0005, 0x0000, 0x000b, // 0x40 0x0049, 0x005d, 0x0005, 0x0009, 0x0000, 0x0000, 0x0006, 0x0002, // 0x48 0x0000, 0x0000, 0x0000, 0x0002, 0x000c, 0x0001, 0x000b, 0x006e, // 0x50 0x006a, 0x0000, 0x0000, 0x0004, 0x0002, 0x0049, 0x0000, 0x0031, // 0x58 0x0005, 0x0009, 0x000f, 0x000d, 0x0001, 0x0004, 0x0000, 0x0015, // 0x60 0x0000, 0x0000, 0x0003, 0x0009, 0x0013, 0x0003, 0x000e, 0x0000, // 0x68 0x001c, 0x0000, 0x0005, 0x0002, 0x0000, 0x0023, 0x0010, 0x0011, // 0x70 0x0000, 0x0009, 0x0000, 0x0002, 0x0000, 0x000d, 0x0002, 0x0000, // 0x78 0x003e, 0x0000, 0x0002, 0x0027, 0x0045, 0x0002, 0x0000, 0x0000, // 0x80 0x0042, 0x0000, 0x0000, 0x0000, 0x000b, 0x0000, 0x0000, 0x0000, // 0x88 0x0013, 0x0041, 0x0000, 0x0063, 0x0000, 0x0009, 0x0000, 0x0002, // 0x90 0x0000, 0x001a, 0x0000, 0x0102, 0x0135, 0x0033, 0x0000, 0x0000, // 0x98 0x0003, 0x0009, 0x0009, 0x0009, 0x0095, 0x0000, 0x0000, 0x0004, // 0xA0 0x0000, 0x0000, 0x0005, 0x0000, 0x0000, 0x0000, 0x0000, 0x000d, // 0xA8 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0040, 0x0009, 0x0000, // 0xB0 0x0000, 0x0003, 0x0006, 0x0009, 0x0003, 0x0000, 0x0000, 0x0000, // 0xB8 0x0024, 0x0000, 0x0000, 0x0000, 0x0006, 0x00cb, 0x0001, 0x0031, // 0xC0 0x0002, 0x0006, 0x0006, 0x0007, 0x0000, 0x0001, 0x0000, 0x004e, // 0xC8 0x0000, 0x0002, 0x0019, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, // 0xD0 0x0000, 0x010C, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, // 0xD8 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, // 0xE0 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, // 0xE8 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, // 0xF0 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF, // 0xF8 }; /***************************************************************************** cAsyncNetIOPrivate member functions *****************************************************************************/ enum eEncryption { E_NONE = 0, E_LOGIN, E_GAME }; #include <deque> class cAsyncNetIOPrivate { private: cAsyncNetIOPrivate( cAsyncNetIOPrivate& ); // Satisfy warning C4511 public: cAsyncNetIOPrivate(); ~cAsyncNetIOPrivate(); QSocketDevice* socket; // connection socket // ewba is the encrypted write buffer QPtrList<QByteArray> rba, wba, ewba; // list of read/write bufs Q_ULONG rsize, wsize; // read/write total buf size Q_ULONG rindex, windex; // read/write index QMutex wmutex; // write mutex bool skippedUOHeader; // Skip crypt key junk std::deque<cUOPacket*> packets; // Complete UOPackets QMutex packetsMutex; QMutex cryptMutex; int getch(); int ungetch( int ch ); Q_LONG readBlock( char* data, Q_ULONG maxlen ); Q_LONG writeBlock( const char* data, Q_ULONG len ); Q_LONG writeBlock( QByteArray data ); bool consumeWriteBuf( Q_ULONG nbytes ); bool consumeReadBuf( Q_ULONG nbytes, char* sink ); bool login; // false = GameServer Protocol, true = LoginServer Protocol Q_UINT32 seed; cClientEncryption* encryption; }; cAsyncNetIOPrivate::cAsyncNetIOPrivate() : socket( 0 ), rsize( 0 ), wsize( 0 ), rindex( 0 ), windex( 0 ), skippedUOHeader( false ), encryption( 0 ) { rba.setAutoDelete( TRUE ); wba.setAutoDelete( TRUE ); ewba.setAutoDelete( TRUE ); } cAsyncNetIOPrivate::~cAsyncNetIOPrivate() { for ( uint i = 0; i < packets.size(); ++i ) { /// QMutexLocker lock( &packetsMutex ); I think it's safe not to lock here. delete packets.front(); packets.pop_front(); } delete encryption; } /*! \internal Reads \a maxlen bytes from the socket into \a data and returns the number of bytes read. Returns -1 if an error occurred. */ Q_LONG cAsyncNetIOPrivate::readBlock( char* data, Q_ULONG maxlen ) { if ( data == 0 && maxlen != 0 ) { return -1; } if ( maxlen >= rsize ) maxlen = rsize; consumeReadBuf( maxlen, data ); return maxlen; } /*! \internal Writes \a len bytes to the socket from \a data and returns the number of bytes written. Returns -1 if an error occurred. */ Q_LONG cAsyncNetIOPrivate::writeBlock( const char* data, Q_ULONG len ) { // Invalid Socket -> Disconnected if ( !socket->isValid() ) { socket->close(); return 0; } if ( len == 0 ) return 0; QByteArray* a = wba.last(); if ( a && a->size() + len < 128 ) { // small buffer, resize int i = a->size(); a->resize( i + len ); memcpy( a->data() + i, data, len ); } else { // append new buffer a = new QByteArray( len ); memcpy( a->data(), data, len ); wba.append( a ); } wsize += len; return len; } /*! \internal Writes \a data and returns the number of bytes written. Returns -1 if an error occurred. */ Q_LONG cAsyncNetIOPrivate::writeBlock( QByteArray data ) { return writeBlock( data.data(), data.size() ); } /*! \internal Reads a single byte/character from the internal read buffer. Returns the byte/character read, or -1 if there is nothing to be read. \sa ungetch() */ int cAsyncNetIOPrivate::getch() { if ( rsize > 0 ) { uchar c; consumeReadBuf( 1, ( char * ) &c ); return c; } return -1; } /*! Prepends the character \a ch to the read buffer so that the next read returns this character as the first character of the output. \sa getch() */ int cAsyncNetIOPrivate::ungetch( int ch ) { if ( rba.isEmpty() || rindex == 0 ) { // we need a new QByteArray QByteArray* ba = new QByteArray( 1 ); rba.insert( 0, ba ); rsize++; ba->at( 0 ) = ch; } else { // we can reuse a place in the buffer QByteArray* ba = rba.first(); rindex--; rsize++; ba->at( rindex ) = ch; } return ch; } /*! \internal Removes from internal read buffer \a nbytes. Returns true if successful or false if there were not enough bytes in buffer to fulfill the request. */ bool cAsyncNetIOPrivate::consumeWriteBuf( Q_ULONG nbytes ) { if ( nbytes > wsize ) { wsize = 0; return false; } if ( nbytes <= 0 || nbytes > wsize ) return false; wsize -= nbytes; for ( ; ; ) { QByteArray* a = ewba.first(); if ( windex + nbytes >= a->size() ) { nbytes -= a->size() - windex; ewba.remove(); windex = 0; if ( nbytes == 0 ) break; } else { windex += nbytes; break; } } return false; } /*! \internal Reads and removes from internal read buffer \a nbytes and place then into \a sink. Returns true if successful or false if there were not enough bytes to fulfill the request. */ bool cAsyncNetIOPrivate::consumeReadBuf( Q_ULONG nbytes, char* sink ) { if ( nbytes <= 0 || nbytes > rsize ) return false; rsize -= nbytes; for ( ; ; ) { QByteArray* a = rba.first(); if ( rindex + nbytes >= a->size() ) { // Here we skip the whole byte array and get the next later int len = a->size() - rindex; if ( sink ) { memcpy( sink, a->data() + rindex, len ); sink += len; } nbytes -= len; rba.remove(); rindex = 0; if ( nbytes == 0 ) { // nothing more to skip break; } } else { // Here we skip only a part of the first byte array if ( sink ) memcpy( sink, a->data() + rindex, nbytes ); rindex += nbytes; break; } } return true; } /***************************************************************************** cAsyncNetIO member functions *****************************************************************************/ /*! \class cAsyncNetIO asyncnetio.h \brief The cAsyncNetIO class asyncronous low-level network handling, buffering, compressing, slicing and building higher level application packets. \ingroup network \ingroup mainclass \sa cUOPacket */ /*! Frees allocated buffer memory for the sockets */ cAsyncNetIO::~cAsyncNetIO() throw() { QMap<QSocketDevice*, cAsyncNetIOPrivate*>::iterator it = buffers.begin(); for ( ; it != buffers.end(); ++it ) delete it.data(); } /*! Registers a \a socket for asyncronous services. \a login determines whether the connection has been established to the login server or not. */ bool cAsyncNetIO::registerSocket( QSocketDevice* socket, bool login ) { QMutexLocker lock( &mapsMutex ); cAsyncNetIOPrivate* d = new cAsyncNetIOPrivate; d->login = login; d->socket = socket; buffers.insert( socket, d ); return true; } /*! Unregisters a \a socket for asyncronous services. The \a socket parameter is not modified in any way. */ bool cAsyncNetIO::unregisterSocket( QSocketDevice* socket ) { QMutexLocker lock( &mapsMutex ); iterator it = buffers.find( socket ); if ( it != buffers.end() ) { delete it.data(); buffers.remove( it ); } return true; } /*! \internal The thread's execution loop for AsyncNetIO */ void cAsyncNetIO::run() throw() { while ( !canceled() ) { mapsMutex.lock(); // do not disturb me here. for ( const_iterator it( buffers.begin() ); it != buffers.end(); ++it ) { // Read all avaliable data. char buf[4096]; cAsyncNetIOPrivate* d = it.data(); // Check if the socket is valid if ( !d->socket->isValid() ) continue; // Let it in the queue until it's taken out by the closed-collector // Try to get the UO Header somehow if ( !d->skippedUOHeader ) { int nread = d->socket->readBlock( buf, 4 - d->rsize ); if ( nread > 0 ) { QByteArray* a = new QByteArray( nread ); memcpy( a->data(), buf, nread ); d->rba.append( a ); d->rsize += nread; if ( d->rsize == 4 ) { char temp[4]; d->consumeReadBuf( 4, temp ); d->skippedUOHeader = true; wpCopyIn( d->seed, temp ); d->seed = B_BENDIAN_TO_HOST_INT32( d->seed ); // Only 0xFFFFFFFF seed allowed for !d->login if ( !d->login && d->seed != 0xFFFFFFFF ) { d->writeBlock( "\x82\x04", 2 ); flushWriteBuffer( d ); d->socket->close(); continue; } } } /*else if ( nread == 0 ) { d->socket->close(); }*/ } else { int nread = d->socket->readBlock( buf, sizeof( buf ) ); if ( nread > 0 ) { // If we have an encryption object already // then decrypt the buffer before storing it if ( d->encryption ) d->encryption->clientDecrypt( &buf[0], nread ); QByteArray* a = new QByteArray( nread ); memcpy( a->data(), buf, nread ); d->rba.append( a ); d->rsize += nread; // We need to use the read buffer as a temporary buffer // for encrypted data if we didn't receive all we need if ( !d->encryption ) { // Game server Encryption if ( !d->login && d->rsize >= 65 ) { // The 0x91 packet is 65 byte nread = d->rsize; d->consumeReadBuf( d->rsize, &buf[0] ); // This should be no encryption if ( buf[0] == '\x91' && buf[1] == '\xFF' && buf[2] == '\xFF' && buf[3] == '\xFF' && buf[4] == '\xFF' ) { // Is no Encryption allowed? if ( !Config::instance()->allowUnencryptedClients() ) { // Send a communication problem message to this socket d->writeBlock( "\x82\x04", 2 ); flushWriteBuffer( d ); d->socket->close(); continue; } d->encryption = new cNoEncryption; } else { cGameEncryption* crypt = new cGameEncryption; crypt->init( 0xFFFFFFFF ); d->encryption = crypt; } } // LoginServer Encryption else if ( d->login && d->rsize >= 62 ) { // The 0x80 packet is 62 byte, but we want to have everything nread = d->rsize; d->consumeReadBuf( d->rsize, &buf[0] ); // Check if it could be *not* encrypted if ( buf[0] == '\x80' && buf[30] == '\x00' && buf[60] == '\x00' ) { // Is no Encryption allowed? if ( !Config::instance()->allowUnencryptedClients() ) { // Send a communication problem message to this socket d->writeBlock( "\x82\x04", 2 ); flushWriteBuffer( d ); d->socket->close(); continue; } d->encryption = new cNoEncryption; } else { cLoginEncryption* crypt = new cLoginEncryption; if ( !crypt->init( d->seed, &buf[0], nread ) ) { delete crypt; // Send a communication problem message to this socket d->writeBlock( "\x82\x04", 2 ); flushWriteBuffer( d ); d->socket->close(); continue; } d->encryption = crypt; } // It gets a bit tricky now, try to decode it with all // possible keys } // If we found an encryption let's decrypt what we got in our buffer if ( d->encryption ) { d->encryption->clientDecrypt( &buf[0], nread ); QByteArray* a = new QByteArray( nread ); memcpy( a->data(), buf, nread ); d->rba.append( a ); d->rsize += nread; } } } else if ( nread == 0 ) { d->socket->close(); } buildUOPackets( d ); } // Write data to socket flushWriteBuffer( d ); } mapsMutex.unlock(); //if( buffers.empty() ) // Disconnecting doesn't work for now waitCondition.wait( 10 ); // let's rest for a while } } /*! Informs the amount of data avaliable into internal buffers */ Q_ULONG cAsyncNetIO::bytesAvailable( QSocketDevice* socket ) const { const_iterator it = buffers.find( socket ); return it.data()->rsize; } /*! \internal This method will check the buffer for the next packet ID and try to build it if it have already been fully received. If the packet have arrived incomplete it will leave the data in buffer. Built packets are queued for core's retrieve. */ void cAsyncNetIO::buildUOPackets( cAsyncNetIOPrivate* d ) { bool keepExtracting = d->rsize > 1; while ( keepExtracting ) { int packetID = d->getch(); if ( packetID != -1 ) { Q_UINT16 length = packetLengths[packetID]; if ( length != 0x0000 ) { // fixed size. d->ungetch( packetID ); if ( length == 0xFFFF ) { QByteArray packetData( d->rsize ); d->readBlock( packetData.data(), d->rsize ); qWarning( cUOPacket::dump( packetData ) ); continue; } if ( d->rsize >= length ) { QByteArray packetData( length ); d->readBlock( packetData.data(), length ); cUOPacket* packet = getUORxPacket( packetData ); if ( !packet ) d->socket->close(); QMutexLocker lock( &d->packetsMutex ); d->packets.push_back( packet ); } else keepExtracting = false; // we have to wait some more. } else { // variable length if ( d->rsize < 3 ) // Packet ID, size + 1 byte data. { keepExtracting = false; d->ungetch( packetID ); // byte was read, put back to buffer. continue; } Q_UINT16 length = 0; Q_UINT8* p = ( Q_UINT8* ) &length; *( p + 1 ) = ( Q_UINT8 ) d->getch(); *p = ( Q_UINT8 ) d->getch(); d->ungetch( *p ); d->ungetch( *( p + 1 ) ); d->ungetch( packetID ); length = B_LENDIAN_TO_HOST_INT32( length ); // Because we built as little if ( d->rsize < length ) { keepExtracting = false; continue; } QByteArray packetData( length ); d->readBlock( packetData.data(), length ); cUOPacket* packet = getUORxPacket( packetData ); if ( !packet ) d->socket->close(); QMutexLocker lock( &d->packetsMutex ); d->packets.push_back( packet ); } } else keepExtracting = false; // no more data in buffer. } } /*! \internal This method will check the buffer for data to be written and send it to socket. Lock is done in record level, should be safe to call from different threads. */ void cAsyncNetIO::flushWriteBuffer( cAsyncNetIOPrivate* d ) { bool osBufferFull = false; int consumed = 0; // Buffer has closed if ( !d->socket->isValid() || !d->socket->isWritable() ) return; // Before we continue, we should guarantee no one writes packets to the buffer. QMutexLocker lock( &d->wmutex ); // Encrypt new packets QByteArray *p = d->wba.first(); while ( p ) { // Encrypt the outgoing buffer if ( d->encryption ) d->encryption->serverEncrypt( p->data(), p->size() ); d->ewba.append( p ); p = d->wba.next(); } d->wba.setAutoDelete( FALSE ); d->wba.clear(); d->wba.setAutoDelete( TRUE ); while ( !osBufferFull && d->wsize > 0 ) { QByteArray* a = d->ewba.first(); if ( !a ) break; int nwritten; int i = 0; if ( ( int ) a->size() - d->windex < 1460 ) { // Concatenate many smaller blocks. the first may be // partial, but each subsequent block is copied entirely // or not at all. the sizes here are picked so that we // generally won't trigger nagle's algorithm in the tcp // implementation: we concatenate if we'd otherwise send // less than PMTU bytes (we assume PMTU is 1460 bytes), // and concatenate up to the largest payload TCP/IP can // carry. with these precautions, nagle's algorithm // should apply only when really appropriate. QByteArray out( 65536 ); int j = d->windex; int s = a->size() - j; while ( a && i + s < ( int ) out.size() ) { memcpy( out.data() + i, a->data() + j, s ); j = 0; i += s; a = d->ewba.next(); s = a ? a->size() : 0; } nwritten = d->socket->writeBlock( out.data(), i ); } else { // Big block, write it immediately i = a->size() - d->windex; nwritten = d->socket->writeBlock( a->data() + d->windex, i ); } if ( nwritten > 0 ) { if ( d->consumeWriteBuf( nwritten ) ) consumed += nwritten; } if ( nwritten < i ) osBufferFull = TRUE; } } /*! Tries to receive a cUOPacket from \a socket if one is avaliable. If no packet is avaliable at this time, the result will be 0. Packets retrieved from this method should be freed by the caller. */ cUOPacket* cAsyncNetIO::recvPacket( QSocketDevice* socket ) { iterator it = buffers.find( socket ); if ( it.data()->packets.size() ) { QMutexLocker lock( &( it.data()->packetsMutex ) ); cUOPacket* p = it.data()->packets.front(); it.data()->packets.pop_front(); return p; } else return 0; } /* Re-queues a packet to the front of the queue for a socket. */ void cAsyncNetIO::pushfrontPacket( QSocketDevice* socket, cUOPacket* packet ) { iterator it = buffers.find( socket ); if ( it != buffers.end() ) { QMutexLocker lock( &( it.data()->packetsMutex ) ); it.data()->packets.push_front( packet ); } } /*! Queues \a packet for sending to \a socket. UO Huffman compression will be applied if \a compress is true. */ void cAsyncNetIO::sendPacket( QSocketDevice* socket, cUOPacket* packet, bool compress ) { QByteArray data; if ( compress ) { data = packet->compressed(); } else { data = packet->uncompressed(); } iterator it = buffers.find( socket ); QMutexLocker lock( &it.data()->wmutex ); it.data()->writeBlock( data ); } /*! Sends to connected \a socket any packet writes still in buffer. This method is usually called prior to disconnection to ensure all data, including error messages have been sent. */ void cAsyncNetIO::flush( QSocketDevice* socket ) { iterator it = buffers.find( socket ); if ( it != buffers.end() ) flushWriteBuffer( it.data() ); }
[ "fkollmann@db57ef4e-4fe8-0310-84ee-c23f6f2f8b61" ]
fkollmann@db57ef4e-4fe8-0310-84ee-c23f6f2f8b61
e8401caba358f0588a3784fd234acd61c214eb76
8862c89bb5d575653a6d07f27f1b29bd118cb22c
/3rdparty/cereal/details/traits.hpp
23fab66f89072018d938c8ed4af22d107630c111
[ "CC-BY-4.0", "MIT", "BSD-3-Clause", "BSL-1.0" ]
permissive
simonspa/allpix-squared
c1e475e2ba9d6de83a5006a1e526ea6403fd5ca2
62242b5c5b39a418309b7d2efb6336ff47d1b4d2
refs/heads/master
2021-06-05T16:01:31.969564
2020-02-28T11:40:57
2020-02-28T11:40:57
104,188,159
7
4
MIT
2021-12-03T03:31:33
2017-09-20T08:30:26
C++
UTF-8
C++
false
false
101,390
hpp
/*! \file traits.hpp \brief Internal type trait support \ingroup Internal */ /* Copyright (c) 2014, Randolph Voorhies, Shane Grant 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 cereal 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 RANDOLPH VOORHIES OR SHANE GRANT 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 CEREAL_DETAILS_TRAITS_HPP_ #define CEREAL_DETAILS_TRAITS_HPP_ #ifndef __clang__ #if(__GNUC__ == 4 && __GNUC_MINOR__ <= 7) #define CEREAL_OLDER_GCC #endif // gcc 4.7 or earlier #endif // __clang__ #include <type_traits> #include <typeindex> #include "cereal/access.hpp" #include "cereal/macros.hpp" namespace cereal { namespace traits { using yes = std::true_type; using no = std::false_type; namespace detail { // ###################################################################### //! Used to delay a static_assert until template instantiation template <class T> struct delay_static_assert : std::false_type {}; // ###################################################################### // SFINAE Helpers #ifdef CEREAL_OLDER_GCC // when VS supports better SFINAE, we can use this as the default template <typename> struct Void { typedef void type; }; #endif // CEREAL_OLDER_GCC //! Return type for SFINAE Enablers enum class sfinae {}; // ###################################################################### // Helper functionality for boolean integral constants and Enable/DisableIf template <bool H, bool... T> struct meta_bool_and : std::integral_constant<bool, H && meta_bool_and<T...>::value> {}; template <bool B> struct meta_bool_and<B> : std::integral_constant<bool, B> {}; template <bool H, bool... T> struct meta_bool_or : std::integral_constant<bool, H || meta_bool_or<T...>::value> {}; template <bool B> struct meta_bool_or<B> : std::integral_constant<bool, B> {}; // workaround needed due to bug in MSVC 2013, see // http://connect.microsoft.com/VisualStudio/feedback/details/800231/c-11-alias-template-issue template <bool... Conditions> struct EnableIfHelper : std::enable_if<meta_bool_and<Conditions...>::value, sfinae> {}; template <bool... Conditions> struct DisableIfHelper : std::enable_if<!meta_bool_or<Conditions...>::value, sfinae> {}; } // namespace detail //! Used as the default value for EnableIf and DisableIf template parameters /*! @relates EnableIf @relates DisableIf */ static const detail::sfinae sfinae = {}; // ###################################################################### //! Provides a way to enable a function if conditions are met /*! This is intended to be used in a near identical fashion to std::enable_if while being significantly easier to read at the cost of not allowing for as complicated of a condition. This will compile (allow the function) if every condition evaluates to true. at compile time. This should be used with SFINAE to ensure that at least one other candidate function works when one fails due to an EnableIf. This should be used as the las template parameter to a function as an unnamed parameter with a default value of cereal::traits::sfinae: @code{cpp} // using by making the last template argument variadic template <class T, EnableIf<std::is_same<T, bool>::value> = sfinae> void func(T t ); @endcode Note that this performs a logical AND of all conditions, so you will need to construct more complicated requirements with this fact in mind. @relates DisableIf @relates sfinae @tparam Conditions The conditions which will be logically ANDed to enable the function. */ template <bool... Conditions> using EnableIf = typename detail::EnableIfHelper<Conditions...>::type; // ###################################################################### //! Provides a way to disable a function if conditions are met /*! This is intended to be used in a near identical fashion to std::enable_if while being significantly easier to read at the cost of not allowing for as complicated of a condition. This will compile (allow the function) if every condition evaluates to false. This should be used with SFINAE to ensure that at least one other candidate function works when one fails due to a DisableIf. This should be used as the las template parameter to a function as an unnamed parameter with a default value of cereal::traits::sfinae: @code{cpp} // using by making the last template argument variadic template <class T, DisableIf<std::is_same<T, bool>::value> = sfinae> void func(T t ); @endcode This is often used in conjunction with EnableIf to form an enable/disable pair of overloads. Note that this performs a logical AND of all conditions, so you will need to construct more complicated requirements with this fact in mind. If all conditions hold, the function will be disabled. @relates EnableIf @relates sfinae @tparam Conditions The conditions which will be logically ANDed to disable the function. */ template <bool... Conditions> using DisableIf = typename detail::DisableIfHelper<Conditions...>::type; // ###################################################################### namespace detail { template <class InputArchive> struct get_output_from_input : no { static_assert(detail::delay_static_assert<InputArchive>::value, "Could not find an associated output archive for input archive."); }; template <class OutputArchive> struct get_input_from_output : no { static_assert(detail::delay_static_assert<OutputArchive>::value, "Could not find an associated input archive for output archive."); }; } //! Sets up traits that relate an input archive to an output archive #define CEREAL_SETUP_ARCHIVE_TRAITS(InputArchive, OutputArchive) \ namespace cereal { \ namespace traits { \ namespace detail { \ template <> struct get_output_from_input<InputArchive> { using type = OutputArchive; }; \ template <> struct get_input_from_output<OutputArchive> { using type = InputArchive; }; \ } \ } \ } /* end namespaces */ // ###################################################################### //! Used to convert a MAKE_HAS_XXX macro into a versioned variant #define CEREAL_MAKE_VERSIONED_TEST , 0 // ###################################################################### //! Creates a test for whether a non const member function exists /*! This creates a class derived from std::integral_constant that will be true if the type has the proper member function for the given archive. @param name The name of the function to test for (e.g. serialize, load, save) @param test_name The name to give the test for the function being tested for (e.g. serialize, versioned_serialize) @param versioned Either blank or the macro CEREAL_MAKE_VERSIONED_TEST */ #ifdef CEREAL_OLDER_GCC #define CEREAL_MAKE_HAS_MEMBER_TEST(name, test_name, versioned) \ template <class T, class A, class SFINAE = void> struct has_member_##test_name : no {}; \ template <class T, class A> \ struct has_member_##test_name<T, \ A, \ typename detail::Void<decltype(cereal::access::member_##name( \ std::declval<A&>(), std::declval<T&>() versioned))>::type> : yes {} #else // NOT CEREAL_OLDER_GCC #define CEREAL_MAKE_HAS_MEMBER_TEST(name, test_name, versioned) \ namespace detail { \ template <class T, class A> struct has_member_##name##_##versioned##_impl { \ template <class TT, class AA> \ static auto test(int) \ -> decltype(cereal::access::member_##name(std::declval<AA&>(), std::declval<TT&>() versioned), yes()); \ template <class, class> static no test(...); \ static const bool value = std::is_same<decltype(test<T, A>(0)), yes>::value; \ }; \ } /* end namespace detail */ \ template <class T, class A> \ struct has_member_##test_name \ : std::integral_constant<bool, detail::has_member_##name##_##versioned##_impl<T, A>::value> {} #endif // NOT CEREAL_OLDER_GCC // ###################################################################### //! Creates a test for whether a non const non-member function exists /*! This creates a class derived from std::integral_constant that will be true if the type has the proper non-member function for the given archive. */ #define CEREAL_MAKE_HAS_NON_MEMBER_TEST(test_name, func, versioned) \ namespace detail { \ template <class T, class A> struct has_non_member_##test_name##_impl { \ template <class TT, class AA> \ static auto test(int) -> decltype(func(std::declval<AA&>(), std::declval<TT&>() versioned), yes()); \ template <class, class> static no test(...); \ static const bool value = std::is_same<decltype(test<T, A>(0)), yes>::value; \ }; \ } /* end namespace detail */ \ template <class T, class A> \ struct has_non_member_##test_name \ : std::integral_constant<bool, detail::has_non_member_##test_name##_impl<T, A>::value> {} // ###################################################################### // Member Serialize CEREAL_MAKE_HAS_MEMBER_TEST(serialize, serialize, ); // ###################################################################### // Member Serialize (versioned) CEREAL_MAKE_HAS_MEMBER_TEST(serialize, versioned_serialize, CEREAL_MAKE_VERSIONED_TEST); // ###################################################################### // Non Member Serialize CEREAL_MAKE_HAS_NON_MEMBER_TEST(serialize, CEREAL_SERIALIZE_FUNCTION_NAME, ); // ###################################################################### // Non Member Serialize (versioned) CEREAL_MAKE_HAS_NON_MEMBER_TEST(versioned_serialize, CEREAL_SERIALIZE_FUNCTION_NAME, CEREAL_MAKE_VERSIONED_TEST); // ###################################################################### // Member Load CEREAL_MAKE_HAS_MEMBER_TEST(load, load, ); // ###################################################################### // Member Load (versioned) CEREAL_MAKE_HAS_MEMBER_TEST(load, versioned_load, CEREAL_MAKE_VERSIONED_TEST); // ###################################################################### // Non Member Load CEREAL_MAKE_HAS_NON_MEMBER_TEST(load, CEREAL_LOAD_FUNCTION_NAME, ); // ###################################################################### // Non Member Load (versioned) CEREAL_MAKE_HAS_NON_MEMBER_TEST(versioned_load, CEREAL_LOAD_FUNCTION_NAME, CEREAL_MAKE_VERSIONED_TEST); // ###################################################################### #undef CEREAL_MAKE_HAS_NON_MEMBER_TEST #undef CEREAL_MAKE_HAS_MEMBER_TEST // ###################################################################### //! Creates a test for whether a member save function exists /*! This creates a class derived from std::integral_constant that will be true if the type has the proper member function for the given archive. @param test_name The name to give the test (e.g. save or versioned_save) @param versioned Either blank or the macro CEREAL_MAKE_VERSIONED_TEST */ #ifdef CEREAL_OLDER_GCC #define CEREAL_MAKE_HAS_MEMBER_SAVE_IMPL(test_name, versioned) \ namespace detail { \ template <class T, class A> struct has_member_##test_name##_impl { \ template <class TT, class AA, class SFINAE = void> struct test : no {}; \ template <class TT, class AA> \ struct test<TT, \ AA, \ typename detail::Void<decltype(cereal::access::member_save( \ std::declval<AA&>(), std::declval<TT const&>() versioned))>::type> : yes {}; \ static const bool value = test<T, A>(); \ \ template <class TT, class AA, class SFINAE = void> struct test2 : no {}; \ template <class TT, class AA> \ struct test2<TT, \ AA, \ typename detail::Void<decltype(cereal::access::member_save_non_const( \ std::declval<AA&>(), std::declval<typename std::remove_const<TT>::type&>() versioned))>::type> \ : yes {}; \ static const bool not_const_type = test2<T, A>(); \ }; \ } /* end namespace detail */ #else /* NOT CEREAL_OLDER_GCC =================================== */ #define CEREAL_MAKE_HAS_MEMBER_SAVE_IMPL(test_name, versioned) \ namespace detail { \ template <class T, class A> struct has_member_##test_name##_impl { \ template <class TT, class AA> \ static auto test(int) \ -> decltype(cereal::access::member_save(std::declval<AA&>(), std::declval<TT const&>() versioned), yes()); \ template <class, class> static no test(...); \ static const bool value = std::is_same<decltype(test<T, A>(0)), yes>::value; \ \ template <class TT, class AA> \ static auto test2(int) \ -> decltype(cereal::access::member_save_non_const(std::declval<AA&>(), \ std::declval<typename std::remove_const<TT>::type&>() \ versioned), \ yes()); \ template <class, class> static no test2(...); \ static const bool not_const_type = std::is_same<decltype(test2<T, A>(0)), yes>::value; \ }; \ } /* end namespace detail */ #endif /* NOT CEREAL_OLDER_GCC */ // ###################################################################### // Member Save CEREAL_MAKE_HAS_MEMBER_SAVE_IMPL(save, ) template <class T, class A> struct has_member_save : std::integral_constant<bool, detail::has_member_save_impl<T, A>::value> { typedef typename detail::has_member_save_impl<T, A> check; static_assert(check::value || !check::not_const_type, "cereal detected a non-const save. \n " "save member functions must always be const"); }; // ###################################################################### // Member Save (versioned) CEREAL_MAKE_HAS_MEMBER_SAVE_IMPL(versioned_save, CEREAL_MAKE_VERSIONED_TEST) template <class T, class A> struct has_member_versioned_save : std::integral_constant<bool, detail::has_member_versioned_save_impl<T, A>::value> { typedef typename detail::has_member_versioned_save_impl<T, A> check; static_assert(check::value || !check::not_const_type, "cereal detected a versioned non-const save. \n " "save member functions must always be const"); }; // ###################################################################### #undef CEREAL_MAKE_HAS_MEMBER_SAVE_IMPL // ###################################################################### //! Creates a test for whether a non-member save function exists /*! This creates a class derived from std::integral_constant that will be true if the type has the proper non-member function for the given archive. @param test_name The name to give the test (e.g. save or versioned_save) @param versioned Either blank or the macro CEREAL_MAKE_VERSIONED_TEST */ #define CEREAL_MAKE_HAS_NON_MEMBER_SAVE_TEST(test_name, versioned) \ namespace detail { \ template <class T, class A> struct has_non_member_##test_name##_impl { \ template <class TT, class AA> \ static auto test(int) \ -> decltype(CEREAL_SAVE_FUNCTION_NAME(std::declval<AA&>(), std::declval<TT const&>() versioned), yes()); \ template <class, class> static no test(...); \ static const bool value = std::is_same<decltype(test<T, A>(0)), yes>::value; \ \ template <class TT, class AA> \ static auto test2(int) \ -> decltype(CEREAL_SAVE_FUNCTION_NAME(std::declval<AA&>(), \ std::declval<typename std::remove_const<TT>::type&>() versioned), \ yes()); \ template <class, class> static no test2(...); \ static const bool not_const_type = std::is_same<decltype(test2<T, A>(0)), yes>::value; \ }; \ } /* end namespace detail */ \ \ template <class T, class A> \ struct has_non_member_##test_name \ : std::integral_constant<bool, detail::has_non_member_##test_name##_impl<T, A>::value> { \ using check = typename detail::has_non_member_##test_name##_impl<T, A>; \ static_assert(check::value || !check::not_const_type, \ "cereal detected a non-const type parameter in non-member " #test_name ". \n " #test_name \ " non-member functions must always pass their types as const"); \ }; // ###################################################################### // Non Member Save CEREAL_MAKE_HAS_NON_MEMBER_SAVE_TEST(save, ) // ###################################################################### // Non Member Save (versioned) CEREAL_MAKE_HAS_NON_MEMBER_SAVE_TEST(versioned_save, CEREAL_MAKE_VERSIONED_TEST) // ###################################################################### #undef CEREAL_MAKE_HAS_NON_MEMBER_SAVE_TEST // ###################################################################### // Minimal Utilities namespace detail { // Determines if the provided type is an std::string template <class> struct is_string : std::false_type {}; template <class CharT, class Traits, class Alloc> struct is_string<std::basic_string<CharT, Traits, Alloc>> : std::true_type {}; } // Determines if the type is valid for use with a minimal serialize function template <class T> struct is_minimal_type : std::integral_constant<bool, detail::is_string<T>::value || std::is_arithmetic<T>::value> { }; // ###################################################################### //! Creates implementation details for whether a member save_minimal function exists /*! This creates a class derived from std::integral_constant that will be true if the type has the proper member function for the given archive. @param test_name The name to give the test (e.g. save_minimal or versioned_save_minimal) @param versioned Either blank or the macro CEREAL_MAKE_VERSIONED_TEST */ #ifdef CEREAL_OLDER_GCC #define CEREAL_MAKE_HAS_MEMBER_SAVE_MINIMAL_IMPL(test_name, versioned) \ namespace detail { \ template <class T, class A> struct has_member_##test_name##_impl { \ template <class TT, class AA, class SFINAE = void> struct test : no {}; \ template <class TT, class AA> \ struct test<TT, \ AA, \ typename detail::Void<decltype(cereal::access::member_save_minimal( \ std::declval<AA const&>(), std::declval<TT const&>() versioned))>::type> : yes {}; \ \ static const bool value = test<T, A>(); \ \ template <class TT, class AA, class SFINAE = void> struct test2 : no {}; \ template <class TT, class AA> \ struct test2< \ TT, \ AA, \ typename detail::Void<decltype(cereal::access::member_save_minimal_non_const( \ std::declval<AA const&>(), std::declval<typename std::remove_const<TT>::type&>() versioned))>::type> \ : yes {}; \ static const bool not_const_type = test2<T, A>(); \ \ static const bool valid = value || !not_const_type; \ }; \ } /* end namespace detail */ #else /* NOT CEREAL_OLDER_GCC =================================== */ #define CEREAL_MAKE_HAS_MEMBER_SAVE_MINIMAL_IMPL(test_name, versioned) \ namespace detail { \ template <class T, class A> struct has_member_##test_name##_impl { \ template <class TT, class AA> \ static auto test(int) -> decltype(cereal::access::member_save_minimal(std::declval<AA const&>(), \ std::declval<TT const&>() versioned), \ yes()); \ template <class, class> static no test(...); \ static const bool value = std::is_same<decltype(test<T, A>(0)), yes>::value; \ \ template <class TT, class AA> \ static auto test2(int) -> decltype(cereal::access::member_save_minimal_non_const( \ std::declval<AA const&>(), \ std::declval<typename std::remove_const<TT>::type&>() versioned), \ yes()); \ template <class, class> static no test2(...); \ static const bool not_const_type = std::is_same<decltype(test2<T, A>(0)), yes>::value; \ \ static const bool valid = value || !not_const_type; \ }; \ } /* end namespace detail */ #endif // NOT CEREAL_OLDER_GCC // ###################################################################### //! Creates helpers for minimal save functions /*! The get_member_*_type structs allow access to the return type of a save_minimal, assuming that the function actually exists. If the function does not exist, the type will be void. @param test_name The name to give the test (e.g. save_minimal or versioned_save_minimal) @param versioned Either blank or the macro CEREAL_MAKE_VERSIONED_TEST */ #define CEREAL_MAKE_HAS_MEMBER_SAVE_MINIMAL_HELPERS_IMPL(test_name, versioned) \ namespace detail { \ template <class T, class A, bool Valid> struct get_member_##test_name##_type { using type = void; }; \ \ template <class T, class A> struct get_member_##test_name##_type<T, A, true> { \ using type = decltype( \ cereal::access::member_save_minimal(std::declval<A const&>(), std::declval<T const&>() versioned)); \ }; \ } /* end namespace detail */ // ###################################################################### //! Creates a test for whether a member save_minimal function exists /*! This creates a class derived from std::integral_constant that will be true if the type has the proper member function for the given archive. @param test_name The name to give the test (e.g. save_minimal or versioned_save_minimal) */ #define CEREAL_MAKE_HAS_MEMBER_SAVE_MINIMAL_TEST(test_name) \ template <class T, class A> \ struct has_member_##test_name : std::integral_constant<bool, detail::has_member_##test_name##_impl<T, A>::value> { \ using check = typename detail::has_member_##test_name##_impl<T, A>; \ static_assert(check::valid, \ "cereal detected a non-const member " #test_name ". \n " #test_name \ " member functions must always be const"); \ \ using type = typename detail::get_member_##test_name##_type<T, A, check::value>::type; \ static_assert((check::value && is_minimal_type<type>::value) || !check::value, \ "cereal detected a member " #test_name " with an invalid return type. \n " \ "return type must be arithmetic or string"); \ }; // ###################################################################### // Member Save Minimal CEREAL_MAKE_HAS_MEMBER_SAVE_MINIMAL_IMPL(save_minimal, ) CEREAL_MAKE_HAS_MEMBER_SAVE_MINIMAL_HELPERS_IMPL(save_minimal, ) CEREAL_MAKE_HAS_MEMBER_SAVE_MINIMAL_TEST(save_minimal) // ###################################################################### // Member Save Minimal (versioned) CEREAL_MAKE_HAS_MEMBER_SAVE_MINIMAL_IMPL(versioned_save_minimal, CEREAL_MAKE_VERSIONED_TEST) CEREAL_MAKE_HAS_MEMBER_SAVE_MINIMAL_HELPERS_IMPL(versioned_save_minimal, CEREAL_MAKE_VERSIONED_TEST) CEREAL_MAKE_HAS_MEMBER_SAVE_MINIMAL_TEST(versioned_save_minimal) // ###################################################################### #undef CEREAL_MAKE_HAS_MEMBER_SAVE_MINIMAL_IMPL #undef CEREAL_MAKE_HAS_MEMBER_SAVE_MINIMAL_HELPERS_IMPL #undef CEREAL_MAKE_HAS_MEMBER_SAVE_MINIMAL_TEST // ###################################################################### //! Creates a test for whether a non-member save_minimal function exists /*! This creates a class derived from std::integral_constant that will be true if the type has the proper member function for the given archive. @param test_name The name to give the test (e.g. save_minimal or versioned_save_minimal) @param versioned Either blank or the macro CEREAL_MAKE_VERSIONED_TEST */ #define CEREAL_MAKE_HAS_NON_MEMBER_SAVE_MINIMAL_TEST(test_name, versioned) \ namespace detail { \ template <class T, class A> struct has_non_member_##test_name##_impl { \ template <class TT, class AA> \ static auto test(int) -> decltype(CEREAL_SAVE_MINIMAL_FUNCTION_NAME(std::declval<AA const&>(), \ std::declval<TT const&>() versioned), \ yes()); \ template <class, class> static no test(...); \ static const bool value = std::is_same<decltype(test<T, A>(0)), yes>::value; \ \ template <class TT, class AA> \ static auto test2(int) \ -> decltype(CEREAL_SAVE_MINIMAL_FUNCTION_NAME(std::declval<AA const&>(), \ std::declval<typename std::remove_const<TT>::type&>() \ versioned), \ yes()); \ template <class, class> static no test2(...); \ static const bool not_const_type = std::is_same<decltype(test2<T, A>(0)), yes>::value; \ \ static const bool valid = value || !not_const_type; \ }; \ \ template <class T, class A, bool Valid> struct get_non_member_##test_name##_type { using type = void; }; \ \ template <class T, class A> struct get_non_member_##test_name##_type<T, A, true> { \ using type = \ decltype(CEREAL_SAVE_MINIMAL_FUNCTION_NAME(std::declval<A const&>(), std::declval<T const&>() versioned)); \ }; \ } /* end namespace detail */ \ \ template <class T, class A> \ struct has_non_member_##test_name \ : std::integral_constant<bool, detail::has_non_member_##test_name##_impl<T, A>::value> { \ using check = typename detail::has_non_member_##test_name##_impl<T, A>; \ static_assert(check::valid, \ "cereal detected a non-const type parameter in non-member " #test_name ". \n " #test_name \ " non-member functions must always pass their types as const"); \ \ using type = typename detail::get_non_member_##test_name##_type<T, A, check::value>::type; \ static_assert((check::value && is_minimal_type<type>::value) || !check::value, \ "cereal detected a non-member " #test_name " with an invalid return type. \n " \ "return type must be arithmetic or string"); \ }; // ###################################################################### // Non-Member Save Minimal CEREAL_MAKE_HAS_NON_MEMBER_SAVE_MINIMAL_TEST(save_minimal, ) // ###################################################################### // Non-Member Save Minimal (versioned) CEREAL_MAKE_HAS_NON_MEMBER_SAVE_MINIMAL_TEST(versioned_save_minimal, CEREAL_MAKE_VERSIONED_TEST) // ###################################################################### #undef CEREAL_MAKE_HAS_NON_MEMBER_SAVE_MINIMAL_TEST // ###################################################################### // Load Minimal Utilities namespace detail { //! Used to help strip away conversion wrappers /*! If someone writes a non-member load/save minimal function that accepts its parameter as some generic template type and needs to perform trait checks on that type, our NoConvert wrappers will interfere with this. Using the struct strip_minmal, users can strip away our wrappers to get to the underlying type, allowing traits to work properly */ struct NoConvertBase {}; //! A struct that prevents implicit conversion /*! Any type instantiated with this struct will be unable to implicitly convert to another type. Is designed to only allow conversion to Source const &. @tparam Source the type of the original source */ template <class Source> struct NoConvertConstRef : NoConvertBase { using type = Source; //!< Used to get underlying type easily template <class Dest, class = typename std::enable_if<std::is_same<Source, Dest>::value>::type> operator Dest() = delete; //! only allow conversion if the types are the same and we are converting into a const reference template <class Dest, class = typename std::enable_if<std::is_same<Source, Dest>::value>::type> operator Dest const&(); }; //! A struct that prevents implicit conversion /*! Any type instantiated with this struct will be unable to implicitly convert to another type. Is designed to only allow conversion to Source &. @tparam Source the type of the original source */ template <class Source> struct NoConvertRef : NoConvertBase { using type = Source; //!< Used to get underlying type easily template <class Dest, class = typename std::enable_if<std::is_same<Source, Dest>::value>::type> operator Dest() = delete; #ifdef __clang__ template <class Dest, class = typename std::enable_if<std::is_same<Source, Dest>::value>::type> operator Dest const&() = delete; #endif // __clang__ //! only allow conversion if the types are the same and we are converting into a const reference template <class Dest, class = typename std::enable_if<std::is_same<Source, Dest>::value>::type> operator Dest&(); }; //! A type that can implicitly convert to anything else struct AnyConvert { template <class Dest> operator Dest&(); template <class Dest> operator Dest const&() const; }; } // namespace detail // ###################################################################### //! Creates a test for whether a member load_minimal function exists /*! This creates a class derived from std::integral_constant that will be true if the type has the proper member function for the given archive. Our strategy here is to first check if a function matching the signature more or less exists (allow anything like load_minimal(xxx) using AnyConvert, and then secondly enforce that it has the correct signature using NoConvertConstRef @param test_name The name to give the test (e.g. load_minimal or versioned_load_minimal) @param versioned Either blank or the macro CEREAL_MAKE_VERSIONED_TEST */ #ifdef CEREAL_OLDER_GCC #define CEREAL_MAKE_HAS_MEMBER_LOAD_MINIMAL_IMPL(test_name, versioned) \ namespace detail { \ template <class T, class A, class SFINAE = void> struct has_member_##test_name##_impl : no {}; \ template <class T, class A> \ struct has_member_##test_name##_impl< \ T, \ A, \ typename detail::Void<decltype(cereal::access::member_load_minimal( \ std::declval<A const&>(), std::declval<T&>(), AnyConvert() versioned))>::type> : yes {}; \ \ template <class T, class A, class U, class SFINAE = void> struct has_member_##test_name##_type_impl : no {}; \ template <class T, class A, class U> \ struct has_member_##test_name##_type_impl< \ T, \ A, \ U, \ typename detail::Void<decltype(cereal::access::member_load_minimal( \ std::declval<A const&>(), std::declval<T&>(), NoConvertConstRef<U>() versioned))>::type> : yes {}; \ } /* end namespace detail */ #else /* NOT CEREAL_OLDER_GCC =================================== */ #define CEREAL_MAKE_HAS_MEMBER_LOAD_MINIMAL_IMPL(test_name, versioned) \ namespace detail { \ template <class T, class A> struct has_member_##test_name##_impl { \ template <class TT, class AA> \ static auto test(int) -> decltype(cereal::access::member_load_minimal(std::declval<AA const&>(), \ std::declval<TT&>(), \ AnyConvert() versioned), \ yes()); \ template <class, class> static no test(...); \ static const bool value = std::is_same<decltype(test<T, A>(0)), yes>::value; \ }; \ template <class T, class A, class U> struct has_member_##test_name##_type_impl { \ template <class TT, class AA, class UU> \ static auto test(int) -> decltype(cereal::access::member_load_minimal(std::declval<AA const&>(), \ std::declval<TT&>(), \ NoConvertConstRef<UU>() versioned), \ yes()); \ template <class, class, class> static no test(...); \ static const bool value = std::is_same<decltype(test<T, A, U>(0)), yes>::value; \ }; \ } /* end namespace detail */ #endif // NOT CEREAL_OLDER_GCC // ###################################################################### //! Creates helpers for minimal load functions /*! The has_member_*_wrapper structs ensure that the load and save types for the requested function type match appropriately. @param load_test_name The name to give the test (e.g. load_minimal or versioned_load_minimal) @param save_test_name The name to give the test (e.g. save_minimal or versioned_save_minimal, should match the load name. @param save_test_prefix The name to give the test (e.g. save_minimal or versioned_save_minimal, should match the load name, without the trailing "_minimal" (e.g. save or versioned_save). Needed because the preprocessor is an abomination. @param versioned Either blank or the macro CEREAL_MAKE_VERSIONED_TEST */ #define CEREAL_MAKE_HAS_MEMBER_LOAD_MINIMAL_HELPERS_IMPL(load_test_name, save_test_name, save_test_prefix, versioned) \ namespace detail { \ template <class T, class A, bool Valid> struct has_member_##load_test_name##_wrapper : std::false_type {}; \ \ template <class T, class A> struct has_member_##load_test_name##_wrapper<T, A, true> { \ using AOut = typename detail::get_output_from_input<A>::type; \ \ static_assert(has_member_##save_test_prefix##_minimal<T, AOut>::value, \ "cereal detected member " #load_test_name " but no valid member " #save_test_name ". \n " \ "cannot evaluate correctness of " #load_test_name " without valid " #save_test_name "."); \ \ using SaveType = typename detail::get_member_##save_test_prefix##_minimal_type<T, AOut, true>::type; \ const static bool value = has_member_##load_test_name##_impl<T, A>::value; \ const static bool valid = has_member_##load_test_name##_type_impl<T, A, SaveType>::value; \ \ static_assert(valid || !value, \ "cereal detected different or invalid types in corresponding member " #load_test_name \ " and " #save_test_name " functions. \n " \ "the paramater to " #load_test_name \ " must be a constant reference to the type that " #save_test_name " returns."); \ }; \ } /* end namespace detail */ // ###################################################################### //! Creates a test for whether a member load_minimal function exists /*! This creates a class derived from std::integral_constant that will be true if the type has the proper member function for the given archive. @param load_test_name The name to give the test (e.g. load_minimal or versioned_load_minimal) @param load_test_prefix The above parameter minus the trailing "_minimal" */ #define CEREAL_MAKE_HAS_MEMBER_LOAD_MINIMAL_TEST(load_test_name, load_test_prefix) \ template <class T, class A> \ struct has_member_##load_test_prefix##_minimal \ : std::integral_constant<bool, \ detail::has_member_##load_test_name##_wrapper< \ T, \ A, \ detail::has_member_##load_test_name##_impl<T, A>::value>::value> {}; // ###################################################################### // Member Load Minimal CEREAL_MAKE_HAS_MEMBER_LOAD_MINIMAL_IMPL(load_minimal, ) CEREAL_MAKE_HAS_MEMBER_LOAD_MINIMAL_HELPERS_IMPL(load_minimal, save_minimal, save, ) CEREAL_MAKE_HAS_MEMBER_LOAD_MINIMAL_TEST(load_minimal, load) // ###################################################################### // Member Load Minimal (versioned) CEREAL_MAKE_HAS_MEMBER_LOAD_MINIMAL_IMPL(versioned_load_minimal, CEREAL_MAKE_VERSIONED_TEST) CEREAL_MAKE_HAS_MEMBER_LOAD_MINIMAL_HELPERS_IMPL(versioned_load_minimal, versioned_save_minimal, versioned_save, CEREAL_MAKE_VERSIONED_TEST) CEREAL_MAKE_HAS_MEMBER_LOAD_MINIMAL_TEST(versioned_load_minimal, versioned_load) // ###################################################################### #undef CEREAL_MAKE_HAS_MEMBER_LOAD_MINIMAL_IMPL #undef CEREAL_MAKE_HAS_MEMBER_LOAD_MINIMAL_HELPERS_IMPL #undef CEREAL_MAKE_HAS_MEMBER_LOAD_MINIMAL_TEST // ###################################################################### // Non-Member Load Minimal namespace detail { #ifdef CEREAL_OLDER_GCC void CEREAL_LOAD_MINIMAL_FUNCTION_NAME(); // prevents nonsense complaining about not finding this void CEREAL_SAVE_MINIMAL_FUNCTION_NAME(); #endif // CEREAL_OLDER_GCC } // namespace detail // ###################################################################### //! Creates a test for whether a non-member load_minimal function exists /*! This creates a class derived from std::integral_constant that will be true if the type has the proper member function for the given archive. See notes from member load_minimal implementation. @param test_name The name to give the test (e.g. load_minimal or versioned_load_minimal) @param save_name The corresponding name the save test would have (e.g. save_minimal or versioned_save_minimal) @param versioned Either blank or the macro CEREAL_MAKE_VERSIONED_TEST */ #define CEREAL_MAKE_HAS_NON_MEMBER_LOAD_MINIMAL_TEST(test_name, save_name, versioned) \ namespace detail { \ template <class T, class A, class U = void> struct has_non_member_##test_name##_impl { \ template <class TT, class AA> \ static auto test(int) -> decltype(CEREAL_LOAD_MINIMAL_FUNCTION_NAME(std::declval<AA const&>(), \ std::declval<TT&>(), \ AnyConvert() versioned), \ yes()); \ template <class, class> static no test(...); \ static const bool exists = std::is_same<decltype(test<T, A>(0)), yes>::value; \ \ template <class TT, class AA, class UU> \ static auto test2(int) -> decltype(CEREAL_LOAD_MINIMAL_FUNCTION_NAME(std::declval<AA const&>(), \ std::declval<TT&>(), \ NoConvertConstRef<UU>() versioned), \ yes()); \ template <class, class, class> static no test2(...); \ static const bool valid = std::is_same<decltype(test2<T, A, U>(0)), yes>::value; \ \ template <class TT, class AA> \ static auto test3(int) -> decltype(CEREAL_LOAD_MINIMAL_FUNCTION_NAME(std::declval<AA const&>(), \ NoConvertRef<TT>(), \ AnyConvert() versioned), \ yes()); \ template <class, class> static no test3(...); \ static const bool const_valid = std::is_same<decltype(test3<T, A>(0)), yes>::value; \ }; \ \ template <class T, class A, bool Valid> struct has_non_member_##test_name##_wrapper : std::false_type {}; \ \ template <class T, class A> struct has_non_member_##test_name##_wrapper<T, A, true> { \ using AOut = typename detail::get_output_from_input<A>::type; \ \ static_assert(detail::has_non_member_##save_name##_impl<T, AOut>::valid, \ "cereal detected non-member " #test_name " but no valid non-member " #save_name ". \n " \ "cannot evaluate correctness of " #test_name " without valid " #save_name "."); \ \ using SaveType = typename detail::get_non_member_##save_name##_type<T, AOut, true>::type; \ using check = has_non_member_##test_name##_impl<T, A, SaveType>; \ static const bool value = check::exists; \ \ static_assert(check::valid || !check::exists, \ "cereal detected different types in corresponding non-member " #test_name " and " #save_name \ " functions. \n " \ "the paramater to " #test_name " must be a constant reference to the type that " #save_name \ " returns."); \ static_assert(check::const_valid || !check::exists, \ "cereal detected an invalid serialization type parameter in non-member " #test_name \ ". " #test_name \ " non-member functions must accept their serialization type by non-const reference"); \ }; \ } /* namespace detail */ \ \ template <class T, class A> \ struct has_non_member_##test_name \ : std::integral_constant< \ bool, \ detail::has_non_member_##test_name##_wrapper<T, A, detail::has_non_member_##test_name##_impl<T, A>::exists>:: \ value> {}; // ###################################################################### // Non-Member Load Minimal CEREAL_MAKE_HAS_NON_MEMBER_LOAD_MINIMAL_TEST(load_minimal, save_minimal, ) // ###################################################################### // Non-Member Load Minimal (versioned) CEREAL_MAKE_HAS_NON_MEMBER_LOAD_MINIMAL_TEST(versioned_load_minimal, versioned_save_minimal, CEREAL_MAKE_VERSIONED_TEST) // ###################################################################### #undef CEREAL_MAKE_HAS_NON_MEMBER_LOAD_MINIMAL_TEST // ###################################################################### //! Member load and construct check template <typename T, typename A> struct has_member_load_and_construct : std::integral_constant<bool, std::is_same<decltype(access::load_and_construct<T>( std::declval<A&>(), std::declval<::cereal::construct<T>&>())), void>::value> {}; // ###################################################################### //! Member load and construct check (versioned) template <typename T, typename A> struct has_member_versioned_load_and_construct : std::integral_constant<bool, std::is_same<decltype(access::load_and_construct<T>( std::declval<A&>(), std::declval<::cereal::construct<T>&>(), 0)), void>::value> {}; // ###################################################################### //! Creates a test for whether a non-member load_and_construct specialization exists /*! This creates a class derived from std::integral_constant that will be true if the type has the proper non-member function for the given archive. */ #define CEREAL_MAKE_HAS_NON_MEMBER_LOAD_AND_CONSTRUCT_TEST(test_name, versioned) \ namespace detail { \ template <class T, class A> struct has_non_member_##test_name##_impl { \ template <class TT, class AA> \ static auto test(int) \ -> decltype(LoadAndConstruct<TT>::load_and_construct(std::declval<AA&>(), \ std::declval<::cereal::construct<TT>&>() versioned), \ yes()); \ template <class, class> static no test(...); \ static const bool value = std::is_same<decltype(test<T, A>(0)), yes>::value; \ }; \ } /* end namespace detail */ \ template <class T, class A> \ struct has_non_member_##test_name \ : std::integral_constant<bool, detail::has_non_member_##test_name##_impl<T, A>::value> {}; // ###################################################################### //! Non member load and construct check CEREAL_MAKE_HAS_NON_MEMBER_LOAD_AND_CONSTRUCT_TEST(load_and_construct, ) // ###################################################################### //! Non member load and construct check (versioned) CEREAL_MAKE_HAS_NON_MEMBER_LOAD_AND_CONSTRUCT_TEST(versioned_load_and_construct, CEREAL_MAKE_VERSIONED_TEST) // ###################################################################### //! Has either a member or non member load and construct template <typename T, typename A> struct has_load_and_construct : std::integral_constant<bool, has_member_load_and_construct<T, A>::value || has_non_member_load_and_construct<T, A>::value || has_member_versioned_load_and_construct<T, A>::value || has_non_member_versioned_load_and_construct<T, A>::value> {}; // ###################################################################### #undef CEREAL_MAKE_HAS_NON_MEMBER_LOAD_AND_CONSTRUCT_TEST // ###################################################################### // End of serialization existence tests #undef CEREAL_MAKE_VERSIONED_TEST // ###################################################################### template <class T, class InputArchive, class OutputArchive> struct has_member_split : std::integral_constant<bool, (has_member_load<T, InputArchive>::value && has_member_save<T, OutputArchive>::value) || (has_member_versioned_load<T, InputArchive>::value && has_member_versioned_save<T, OutputArchive>::value)> {}; // ###################################################################### template <class T, class InputArchive, class OutputArchive> struct has_non_member_split : std::integral_constant<bool, (has_non_member_load<T, InputArchive>::value && has_non_member_save<T, OutputArchive>::value) || (has_non_member_versioned_load<T, InputArchive>::value && has_non_member_versioned_save<T, OutputArchive>::value)> { }; // ###################################################################### template <class T, class OutputArchive> struct has_invalid_output_versioning : std::integral_constant<bool, (has_member_versioned_save<T, OutputArchive>::value && has_member_save<T, OutputArchive>::value) || (has_non_member_versioned_save<T, OutputArchive>::value && has_non_member_save<T, OutputArchive>::value) || (has_member_versioned_serialize<T, OutputArchive>::value && has_member_serialize<T, OutputArchive>::value) || (has_non_member_versioned_serialize<T, OutputArchive>::value && has_non_member_serialize<T, OutputArchive>::value) || (has_member_versioned_save_minimal<T, OutputArchive>::value && has_member_save_minimal<T, OutputArchive>::value) || (has_non_member_versioned_save_minimal<T, OutputArchive>::value && has_non_member_save_minimal<T, OutputArchive>::value)> {}; // ###################################################################### template <class T, class InputArchive> struct has_invalid_input_versioning : std::integral_constant<bool, (has_member_versioned_load<T, InputArchive>::value && has_member_load<T, InputArchive>::value) || (has_non_member_versioned_load<T, InputArchive>::value && has_non_member_load<T, InputArchive>::value) || (has_member_versioned_serialize<T, InputArchive>::value && has_member_serialize<T, InputArchive>::value) || (has_non_member_versioned_serialize<T, InputArchive>::value && has_non_member_serialize<T, InputArchive>::value) || (has_member_versioned_load_minimal<T, InputArchive>::value && has_member_load_minimal<T, InputArchive>::value) || (has_non_member_versioned_load_minimal<T, InputArchive>::value && has_non_member_load_minimal<T, InputArchive>::value)> {}; // ###################################################################### namespace detail { //! Create a test for a cereal::specialization entry #define CEREAL_MAKE_IS_SPECIALIZED_IMPL(name) \ template <class T, class A> \ struct is_specialized_##name \ : std::integral_constant<bool, !std::is_base_of<std::false_type, specialize<A, T, specialization::name>>::value> {} CEREAL_MAKE_IS_SPECIALIZED_IMPL(member_serialize); CEREAL_MAKE_IS_SPECIALIZED_IMPL(member_load_save); CEREAL_MAKE_IS_SPECIALIZED_IMPL(member_load_save_minimal); CEREAL_MAKE_IS_SPECIALIZED_IMPL(non_member_serialize); CEREAL_MAKE_IS_SPECIALIZED_IMPL(non_member_load_save); CEREAL_MAKE_IS_SPECIALIZED_IMPL(non_member_load_save_minimal); #undef CEREAL_MAKE_IS_SPECIALIZED_IMPL //! Number of specializations detected template <class T, class A> struct count_specializations : std::integral_constant<int, is_specialized_member_serialize<T, A>::value + is_specialized_member_load_save<T, A>::value + is_specialized_member_load_save_minimal<T, A>::value + is_specialized_non_member_serialize<T, A>::value + is_specialized_non_member_load_save<T, A>::value + is_specialized_non_member_load_save_minimal<T, A>::value> {}; } // namespace detail //! Check if any specialization exists for a type template <class T, class A> struct is_specialized : std::integral_constant<bool, detail::is_specialized_member_serialize<T, A>::value || detail::is_specialized_member_load_save<T, A>::value || detail::is_specialized_member_load_save_minimal<T, A>::value || detail::is_specialized_non_member_serialize<T, A>::value || detail::is_specialized_non_member_load_save<T, A>::value || detail::is_specialized_non_member_load_save_minimal<T, A>::value> { static_assert(detail::count_specializations<T, A>::value <= 1, "More than one explicit specialization detected for type."); }; //! Create the static assertion for some specialization /*! This assertion will fail if the type is indeed specialized and does not have the appropriate type of serialization functions */ #define CEREAL_MAKE_IS_SPECIALIZED_ASSERT(name, versioned_name, print_name, spec_name) \ static_assert((is_specialized<T, A>::value && detail::is_specialized_##spec_name<T, A>::value && \ (has_##name<T, A>::value || has_##versioned_name<T, A>::value)) || \ !(is_specialized<T, A>::value && detail::is_specialized_##spec_name<T, A>::value), \ "cereal detected " #print_name " specialization but no " #print_name " serialize function") //! Generates a test for specialization for versioned and unversioned functions /*! This creates checks that can be queried to see if a given type of serialization function has been specialized for this type */ #define CEREAL_MAKE_IS_SPECIALIZED(name, versioned_name, spec_name) \ template <class T, class A> \ struct is_specialized_##name \ : std::integral_constant<bool, is_specialized<T, A>::value && detail::is_specialized_##spec_name<T, A>::value> { \ CEREAL_MAKE_IS_SPECIALIZED_ASSERT(name, versioned_name, name, spec_name); \ }; \ template <class T, class A> \ struct is_specialized_##versioned_name \ : std::integral_constant<bool, is_specialized<T, A>::value && detail::is_specialized_##spec_name<T, A>::value> { \ CEREAL_MAKE_IS_SPECIALIZED_ASSERT(name, versioned_name, versioned_name, spec_name); \ } CEREAL_MAKE_IS_SPECIALIZED(member_serialize, member_versioned_serialize, member_serialize); CEREAL_MAKE_IS_SPECIALIZED(non_member_serialize, non_member_versioned_serialize, non_member_serialize); CEREAL_MAKE_IS_SPECIALIZED(member_save, member_versioned_save, member_load_save); CEREAL_MAKE_IS_SPECIALIZED(non_member_save, non_member_versioned_save, non_member_load_save); CEREAL_MAKE_IS_SPECIALIZED(member_load, member_versioned_load, member_load_save); CEREAL_MAKE_IS_SPECIALIZED(non_member_load, non_member_versioned_load, non_member_load_save); CEREAL_MAKE_IS_SPECIALIZED(member_save_minimal, member_versioned_save_minimal, member_load_save_minimal); CEREAL_MAKE_IS_SPECIALIZED(non_member_save_minimal, non_member_versioned_save_minimal, non_member_load_save_minimal); CEREAL_MAKE_IS_SPECIALIZED(member_load_minimal, member_versioned_load_minimal, member_load_save_minimal); CEREAL_MAKE_IS_SPECIALIZED(non_member_load_minimal, non_member_versioned_load_minimal, non_member_load_save_minimal); #undef CEREAL_MAKE_IS_SPECIALIZED_ASSERT #undef CEREAL_MAKE_IS_SPECIALIZED // ###################################################################### // detects if a type has any active minimal output serialization template <class T, class OutputArchive> struct has_minimal_output_serialization : std::integral_constant<bool, is_specialized_member_save_minimal<T, OutputArchive>::value || ((has_member_save_minimal<T, OutputArchive>::value || has_non_member_save_minimal<T, OutputArchive>::value || has_member_versioned_save_minimal<T, OutputArchive>::value || has_non_member_versioned_save_minimal<T, OutputArchive>::value) && !(is_specialized_member_serialize<T, OutputArchive>::value || is_specialized_member_save<T, OutputArchive>::value))> {}; // ###################################################################### // detects if a type has any active minimal input serialization template <class T, class InputArchive> struct has_minimal_input_serialization : std::integral_constant<bool, is_specialized_member_load_minimal<T, InputArchive>::value || ((has_member_load_minimal<T, InputArchive>::value || has_non_member_load_minimal<T, InputArchive>::value || has_member_versioned_load_minimal<T, InputArchive>::value || has_non_member_versioned_load_minimal<T, InputArchive>::value) && !(is_specialized_member_serialize<T, InputArchive>::value || is_specialized_member_load<T, InputArchive>::value))> {}; // ###################################################################### namespace detail { //! The number of output serialization functions available /*! If specialization is being used, we'll count only those; otherwise we'll count everything */ template <class T, class OutputArchive> struct count_output_serializers : std::integral_constant<int, count_specializations<T, OutputArchive>::value ? count_specializations<T, OutputArchive>::value : has_member_save<T, OutputArchive>::value + has_non_member_save<T, OutputArchive>::value + has_member_serialize<T, OutputArchive>::value + has_non_member_serialize<T, OutputArchive>::value + has_member_save_minimal<T, OutputArchive>::value + has_non_member_save_minimal<T, OutputArchive>::value + /*-versioned---------------------------------------------------------*/ has_member_versioned_save<T, OutputArchive>::value + has_non_member_versioned_save<T, OutputArchive>::value + has_member_versioned_serialize<T, OutputArchive>::value + has_non_member_versioned_serialize<T, OutputArchive>::value + has_member_versioned_save_minimal<T, OutputArchive>::value + has_non_member_versioned_save_minimal<T, OutputArchive>::value> {}; } template <class T, class OutputArchive> struct is_output_serializable : std::integral_constant<bool, detail::count_output_serializers<T, OutputArchive>::value == 1> {}; // ###################################################################### namespace detail { //! The number of input serialization functions available /*! If specialization is being used, we'll count only those; otherwise we'll count everything */ template <class T, class InputArchive> struct count_input_serializers : std::integral_constant<int, count_specializations<T, InputArchive>::value ? count_specializations<T, InputArchive>::value : has_member_load<T, InputArchive>::value + has_non_member_load<T, InputArchive>::value + has_member_serialize<T, InputArchive>::value + has_non_member_serialize<T, InputArchive>::value + has_member_load_minimal<T, InputArchive>::value + has_non_member_load_minimal<T, InputArchive>::value + /*-versioned---------------------------------------------------------*/ has_member_versioned_load<T, InputArchive>::value + has_non_member_versioned_load<T, InputArchive>::value + has_member_versioned_serialize<T, InputArchive>::value + has_non_member_versioned_serialize<T, InputArchive>::value + has_member_versioned_load_minimal<T, InputArchive>::value + has_non_member_versioned_load_minimal<T, InputArchive>::value> {}; } template <class T, class InputArchive> struct is_input_serializable : std::integral_constant<bool, detail::count_input_serializers<T, InputArchive>::value == 1> {}; // ###################################################################### // Base Class Support namespace detail { struct base_class_id { template <class T> base_class_id(T const* const t) : type(typeid(T)), ptr(t), hash(std::hash<std::type_index>()(typeid(T)) ^ (std::hash<void const*>()(t) << 1)) {} bool operator==(base_class_id const& other) const { return (type == other.type) && (ptr == other.ptr); } std::type_index type; void const* ptr; size_t hash; }; struct base_class_id_hash { size_t operator()(base_class_id const& id) const { return id.hash; } }; } // namespace detail namespace detail { //! Common base type for base class casting struct BaseCastBase {}; template <class> struct get_base_class; template <template <typename> class Cast, class Base> struct get_base_class<Cast<Base>> { using type = Base; }; //! Base class cast, behave as the test template <class Cast, template <class, class> class Test, class Archive, bool IsBaseCast = std::is_base_of<BaseCastBase, Cast>::value> struct has_minimal_base_class_serialization_impl : Test<typename get_base_class<Cast>::type, Archive> {}; //! Not a base class cast template <class Cast, template <class, class> class Test, class Archive> struct has_minimal_base_class_serialization_impl<Cast, Test, Archive, false> : std::false_type {}; } //! Checks to see if the base class used in a cast has a minimal serialization /*! @tparam Cast Either base_class or virtual_base_class wrapped type @tparam Test A has_minimal test (for either input or output) @tparam Archive The archive to use with the test */ template <class Cast, template <class, class> class Test, class Archive> struct has_minimal_base_class_serialization : detail::has_minimal_base_class_serialization_impl<Cast, Test, Archive> {}; // ###################################################################### namespace detail { struct shared_from_this_wrapper { template <class U> static auto(check)(U const& t) -> decltype(::cereal::access::shared_from_this(t), std::true_type()); static auto(check)(...) -> decltype(std::false_type()); template <class U> static auto get(U const& t) -> decltype(t.shared_from_this()); }; } //! Determine if T or any base class of T has inherited from std::enable_shared_from_this template <class T> struct has_shared_from_this : decltype((detail::shared_from_this_wrapper::check)(std::declval<T>())) {}; //! Get the type of the base class of T which inherited from std::enable_shared_from_this template <class T> struct get_shared_from_this_base { private: using PtrType = decltype(detail::shared_from_this_wrapper::get(std::declval<T>())); public: //! The type of the base of T that inherited from std::enable_shared_from_this using type = typename std::decay<typename PtrType::element_type>::type; }; // ###################################################################### //! Extracts the true type from something possibly wrapped in a cereal NoConvert /*! Internally cereal uses some wrapper classes to test the validity of non-member minimal load and save functions. This can interfere with user type traits on templated load and save minimal functions. To get to the correct underlying type, users should use strip_minimal when performing any enable_if type type trait checks. See the enum serialization in types/common.hpp for an example of using this */ template <class T, bool IsCerealMinimalTrait = std::is_base_of<detail::NoConvertBase, T>::value> struct strip_minimal { using type = T; }; //! Specialization for types wrapped in a NoConvert template <class T> struct strip_minimal<T, true> { using type = typename T::type; }; // ###################################################################### //! Determines whether the class T can be default constructed by cereal::access template <class T> struct is_default_constructible { #ifdef CEREAL_OLDER_GCC template <class TT, class SFINAE = void> struct test : no {}; template <class TT> struct test<TT, typename detail::Void<decltype(cereal::access::construct<TT>())>::type> : yes {}; static const bool value = test<T>(); #else // NOT CEREAL_OLDER_GCC ========================================= template <class TT> static auto test(int) -> decltype(cereal::access::construct<TT>(), yes()); template <class> static no test(...); static const bool value = std::is_same<decltype(test<T>(0)), yes>::value; #endif // NOT CEREAL_OLDER_GCC }; // ###################################################################### namespace detail { //! Removes all qualifiers and minimal wrappers from an archive template <class A> using decay_archive = typename std::decay<typename strip_minimal<A>::type>::type; } //! Checks if the provided archive type is equal to some cereal archive type /*! This automatically does things such as std::decay and removing any other wrappers that may be on the Archive template parameter. Example use: @code{cpp} // example use to disable a serialization function template <class Archive, EnableIf<cereal::traits::is_same_archive<Archive, cereal::BinaryOutputArchive>::value> = sfinae> void save( Archive & ar, MyType const & mt ); @endcode */ template <class ArchiveT, class CerealArchiveT> struct is_same_archive : std::integral_constant<bool, std::is_same<detail::decay_archive<ArchiveT>, CerealArchiveT>::value> {}; // ###################################################################### //! A macro to use to restrict which types of archives your function will work for. /*! This requires you to have a template class parameter named Archive and replaces the void return type for your function. INTYPE refers to the input archive type you wish to restrict on. OUTTYPE refers to the output archive type you wish to restrict on. For example, if we want to limit a serialize to only work with binary serialization: @code{.cpp} template <class Archive> CEREAL_ARCHIVE_RESTRICT(BinaryInputArchive, BinaryOutputArchive) serialize( Archive & ar, MyCoolType & m ) { ar & m; } @endcode If you need to do more restrictions in your enable_if, you will need to do this by hand. */ #define CEREAL_ARCHIVE_RESTRICT(INTYPE, OUTTYPE) \ typename std::enable_if<cereal::traits::is_same_archive<Archive, INTYPE>::value || \ cereal::traits::is_same_archive<Archive, OUTTYPE>::value, \ void>::type //! Type traits only struct used to mark an archive as human readable (text based) /*! Archives that wish to identify as text based/human readable should inherit from this struct */ struct TextArchive {}; //! Checks if an archive is a text archive (human readable) template <class A> struct is_text_archive : std::integral_constant<bool, std::is_base_of<TextArchive, detail::decay_archive<A>>::value> {}; } // namespace traits // ###################################################################### namespace detail { template <class T, class A, bool Member = traits::has_member_load_and_construct<T, A>::value, bool MemberVersioned = traits::has_member_versioned_load_and_construct<T, A>::value, bool NonMember = traits::has_non_member_load_and_construct<T, A>::value, bool NonMemberVersioned = traits::has_non_member_versioned_load_and_construct<T, A>::value> struct Construct { static_assert(cereal::traits::detail::delay_static_assert<T>::value, "cereal found more than one compatible load_and_construct function for the provided type and " "archive combination. \n\n " "Types must either have a member load_and_construct function or a non-member specialization of " "LoadAndConstruct (you may not mix these). \n " "In addition, you may not mix versioned with non-versioned load_and_construct functions. \n\n "); static T* load_andor_construct(A& /*ar*/, construct<T>& /*construct*/) { return nullptr; } }; // no load and construct case template <class T, class A> struct Construct<T, A, false, false, false, false> { static_assert( ::cereal::traits::is_default_constructible<T>::value, "Trying to serialize a an object with no default constructor. \n\n " "Types must either be default constructible or define either a member or non member Construct function. \n " "Construct functions generally have the signature: \n\n " "template <class Archive> \n " "static void load_and_construct(Archive & ar, cereal::construct<T> & construct) \n " "{ \n " " var a; \n " " ar( a ) \n " " construct( a ); \n " "} \n\n"); static T* load_andor_construct() { return ::cereal::access::construct<T>(); } }; // member non-versioned template <class T, class A> struct Construct<T, A, true, false, false, false> { static void load_andor_construct(A& ar, construct<T>& construct) { access::load_and_construct<T>(ar, construct); } }; // member versioned template <class T, class A> struct Construct<T, A, false, true, false, false> { static void load_andor_construct(A& ar, construct<T>& construct) { const auto version = ar.template loadClassVersion<T>(); access::load_and_construct<T>(ar, construct, version); } }; // non-member non-versioned template <class T, class A> struct Construct<T, A, false, false, true, false> { static void load_andor_construct(A& ar, construct<T>& construct) { LoadAndConstruct<T>::load_and_construct(ar, construct); } }; // non-member versioned template <class T, class A> struct Construct<T, A, false, false, false, true> { static void load_andor_construct(A& ar, construct<T>& construct) { const auto version = ar.template loadClassVersion<T>(); LoadAndConstruct<T>::load_and_construct(ar, construct, version); } }; } // namespace detail } // namespace cereal #endif // CEREAL_DETAILS_TRAITS_HPP_
[ "simon.spannagel@cern.ch" ]
simon.spannagel@cern.ch
879f6b7c09a33c1890898e809992e2bb8b1f9346
47370bfab859b7c1db8cd1a942a464e82563ad31
/lookonemsg.cpp
da7fa6d1ae94b333cfa2091ccd6ad3d5ef2413da
[]
no_license
GreateCode/Message_Center
d348c7290ff648a0915876ac4175dab5335e030f
a9b9595cb7160609ca31d248058d76add2386c1f
refs/heads/master
2021-01-10T16:42:04.449502
2015-10-23T11:26:02
2015-10-23T11:26:02
44,858,942
0
0
null
null
null
null
UTF-8
C++
false
false
1,342
cpp
#include "lookonemsg.h" #include "ui_lookonemsg.h" #include <QDesktopWidget> #include <QPoint> LookOneMsg::LookOneMsg(QWidget *parent) : QWidget(parent), ui(new Ui::LookOneMsg) { ui->setupUi(this); setWindowFlags(Qt::FramelessWindowHint | Qt::Tool); setWindowTitle(tr ("Message")); initUI(); initConn(); QDesktopWidget desk; QPoint point = QPoint((desk.width() - width()) / 2, (desk.height() - height()) / 2); move(point); } LookOneMsg::~LookOneMsg() { delete ui; } void LookOneMsg::setTitle(const QString &title) { ui->titleLabel->setText(title); } void LookOneMsg::setBrowseText(const QString &text) { ui->textBrowser->setText(text); } void LookOneMsg::initUI() { ui->closeBtn->getIconPath(":/close"); } void LookOneMsg::initConn() { connect(ui->closeBtn, SIGNAL(clicked()), this, SLOT(hide())); } void LookOneMsg::mousePressEvent(QMouseEvent *event) { m_dPos = event->globalPos() - this->pos (); } void LookOneMsg::mouseMoveEvent(QMouseEvent *event) { move(event->globalPos() - m_dPos); } void LookOneMsg::paintEvent(QPaintEvent *) { QPainter painter(this); QPen pen; pen.setColor(QColor("#E0E0E0")); painter.setPen(pen); painter.setFont(QFont("Arial", 50)); painter.drawRect(QRect(0, 0, this->width() - 1, this->height() - 1)); }
[ "yanghongchao_it@163.com" ]
yanghongchao_it@163.com
fffeed0eaa36165a5fc619f4619fb1fa494276be
d99308722d63c38daf8697aac46e454db9004252
/prototypes/bob/src/columns/ScalarColumn.h
9191ae7109b076f36af99c10334127ac2aac67fc
[]
no_license
przemekpastuszka/Triss
5bf38011a328727c208dbb6183cf4e90fb2a6430
7087c71baaefbb1824f261267924a0c2d564a68a
refs/heads/master
2021-05-26T20:03:52.083043
2013-06-11T21:11:48
2013-06-11T21:11:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,935
h
/* * Copyright 2012 Przemysław Pastuszka */ #ifndef PROTOTYPES_BOB_SRC_COLUMNS_SCALARCOLUMN_H_ #define PROTOTYPES_BOB_SRC_COLUMNS_SCALARCOLUMN_H_ #include <algorithm> #include <vector> #include "TypedColumn.h" namespace Bob { template <class T> class ScalarColumn : public TypedColumn<T> { private: std::vector<Field<T> > fields; public: Field<T>* getField(unsigned int i) { return &fields[i]; } public: unsigned int getSize() const { return fields.size(); } void add(const Row& row, int nextFieldId) { Field<T> field; field.value = row.get<T>(this -> columnId); field.nextFieldId = nextFieldId; fields.push_back(field); } void sort() { std::sort(fields.begin(), fields.end()); } int lowerBound(const T& value) const { typename std::vector<Field<T> >::const_iterator it = std::lower_bound(fields.begin(), fields.end(), value); return int(it - fields.begin()); } int upperBound(const T& value) const { typename std::vector<Field<T> >::const_iterator it = std::upper_bound(fields.begin(), fields.end(), value); return int(it - fields.begin()) - 1; } int fillRowWithValueAndGetNextFieldId(int valueIndex, Row* row, ColumnQueryState* state, bool fill) const { if(state -> constraintRange.isInRange(valueIndex) == false) { return -1; } if(fill) { row -> set<T>(this -> columnId, fields[valueIndex].value); } return fields[valueIndex].nextFieldId; } ColumnQueryState* prepareColumnForQuery() const { return new TypedColumnQueryState<T>(); } }; } #endif /* PROTOTYPES_BOB_SRC_COLUMNS_SCALARCOLUMN_H_ */
[ "pastuszka.przemyslaw@gmail.com" ]
pastuszka.przemyslaw@gmail.com
aa594680967fb3b8cb290d6bfb58cd624accbb38
7d1e5677f1b00deb32be594a320c6ff9813e7f1c
/brdf/specularReflection.cpp
e42cb7fcc9991ad6506cd1409674368270f215c0
[]
no_license
vidarn/raytracer-experiment
1ab2b2dbe1441f8358dfc6ebe9b79b92b637c1d2
8f7db690f2f6bb8c8feea74ea7a6c2268648afd0
refs/heads/master
2021-01-02T22:58:53.602527
2015-02-10T18:39:42
2015-02-10T18:39:42
17,278,901
0
0
null
null
null
null
UTF-8
C++
false
false
781
cpp
#include "specularReflection.h" #include <cstdlib> void SpecularReflectionBRDF::extractNormal(const void *data, Vec3 *normal) const { struct SpecularParams *params = (struct SpecularParams *)data; } float SpecularReflectionBRDF::f(const Vec3 &in, const Vec3 &out, const void *data) const { return 0.0f; } float SpecularReflectionBRDF::sample_f(Vec3 &in, Vec3 *out, float *pdf, Sampler &sampler, const void *data) const { struct SpecularParams *params = (struct SpecularParams *)data; Vec3 normal(0.0f, 0.0f, 1.0f); *out = Vec3(-in[0],-in[1],in[2]); float eta1 = 1.0f; float eta2 = params->ior; float cosI = std::max(0.0f,in[2]); *pdf = 1.0f; float a = (*out)[2]; if(a > 0.001f){ return fresnel(cosI,eta1,eta2); } else return 0.0f; }
[ "vidar.nelson@gmail.com" ]
vidar.nelson@gmail.com
27159236755160e236bfd088f475a6e5ded90302
5e3854a39930f676bedc35bd01a0aebf3fb431c6
/algorithm/leetcode883_projection-area-of-3d-shapes.cpp
35e2d2d2c9c11883a066bb815d604df57c2212f6
[]
no_license
kobe24o/LeetCode
a6f17f71f456055b0f740e9f5a91626c5885212f
519145d4c27e60ff001154df8d0e258508a2039f
refs/heads/master
2022-08-04T12:44:33.841722
2022-07-30T06:55:47
2022-07-30T06:55:47
198,562,034
36
17
null
null
null
null
UTF-8
C++
false
false
814
cpp
class Solution { public: int projectionArea(vector<vector<int>>& grid) { int bot = 0, left = 0, front = 0, i, j; for(i = 0; i < grid.size(); ++i) { for(j = 0; j < grid[0].size(); ++j) { if(grid[i][j] != 0) ++bot; } } int max; for(i = 0; i < grid.size(); ++i) { max = 0; for(j = 0; j < grid[0].size(); ++j) { if(grid[i][j] > max) max = grid[i][j]; } left += max; } for(j = 0; j < grid[0].size(); ++j) { max = 0; for(i = 0; i < grid.size(); ++i) { if(grid[i][j] > max) max = grid[i][j]; } front += max; } return front+left+bot; } };
[ "mingmingchen1989@163.com" ]
mingmingchen1989@163.com
82caed702c6dc824bc711e560e758b3bb527fa5b
a14841811dc863a21e9f8cba742aaa73a41a05ba
/etc/cldx/Tar32/tar32_2/src/rpm.cpp
e98d7258f6ad7468185cca642a2ccd2cc5a870ef
[]
no_license
wkoiking/xyzzy
27968de07b6028cab1fbdfd3da5c48e8c2be77d9
afddf867027e2d386070314042e71087aa27cbf0
refs/heads/master
2022-12-25T08:26:34.545318
2022-12-11T02:48:49
2022-12-11T02:48:49
40,278,058
0
0
null
null
null
null
UTF-8
C++
false
false
3,435
cpp
#include "stdafx.h" #include "rpm.h" #include "fast_stl.h" /* Reference: lib/rpmlib.h of rpm package. */ struct rpmlead{ unsigned char magic[4]; unsigned char major; /* not supported ver1, only support 2,3 and lator */ unsigned char minor; short type; short archnum; char name[66]; short osnum; short signature_type; char reserved[16]; /* pad to 96 bytes -- 8 byte aligned */ int magic_check(){ return magic[0] == 0xed && magic[1] == 0xab && magic[2] == 0xee && magic[3] == 0xdb; }; short my_htons(short s){ unsigned char *p = (unsigned char*)&s; return (p[0] << 8) + (p[1]); }; void hton(){ type = my_htons(type); archnum = my_htons(archnum); osnum = my_htons(osnum); signature_type = my_htons(signature_type); }; }; /* Reference: lib/header.c of rpm package. */ struct rpm_entryInfo{ int tag; int type; int offset; /* Offset from beginning of data segment, only defined on disk */ int count; }; /* case: signature_type == RPMSIG_HEADERSIG */ struct rpmsig_headersig{ unsigned char magic[4]; int reserved; int index_len; /* count of index entries */ int data_len; /* number of bytes */ int magic_check(){ return magic[0] == 0x8e && magic[1] == 0xad && magic[2] == 0xe8 && magic[3]==0x01; }; int get_lostheaderlen(){ return index_len * sizeof(rpm_entryInfo) + data_len; }; long my_htonl(long s){ unsigned char *p = (unsigned char*)&s; return (p[0] << 24) + (p[1]<<16) + (p[2]<<8) + p[3]; }; void hton(){ index_len = my_htonl(index_len); data_len = my_htonl(data_len); }; }; /* Reference: lib/signature.h of rpm package */ #define RPMSIG_NONE 0 /* Do not change! */ /* The following types are no longer generated */ #define RPMSIG_PGP262_1024 1 /* No longer generated */ /* 256 byte */ /* These are the new-style signatures. They are Header structures. */ /* Inside them we can put any number of any type of signature we like. */ #define RPMSIG_HEADERSIG 5 /* New Header style signature */ size64 rpm_getheadersize(const char *arcfile) { rpmlead lead; rpmsig_headersig sigheader,header; //std::ifstream fs; fast_fstream fs; fs.open(arcfile, std::ios::in|std::ios::binary); if(fs.fail()){return false;} fs.read((char*)&lead, sizeof(lead)); if(fs.gcount() != sizeof(lead)){return -1;} if(! lead.magic_check()){return -1;} lead.hton(); if(lead.signature_type == RPMSIG_NONE){ ; }else if(lead.signature_type == RPMSIG_PGP262_1024){ fs.seekg(256, std::ios::cur); if(fs.fail()){return false;} }else if(lead.signature_type == RPMSIG_HEADERSIG){ fs.read((char*)&sigheader,sizeof(sigheader)); if(fs.gcount() != sizeof(sigheader)){return -1;} if(!sigheader.magic_check()){return -1;} sigheader.hton(); int siglen = sigheader.get_lostheaderlen(); fs.seekg(siglen, std::ios::cur); if(fs.fail()){return -1;} size64 pos = fs.tellg(); if(pos == -1){return -1;} if((pos%8) != 0){ /* 8 byte padding */ // int pad = pos - (pos/8)*8; size64 pad = (pos/8 + 1) * 8 - pos ; // fix by tsuneo 2001.05.14 fs.seekg(pad, std::ios::cur); if(fs.fail()){return -1;} } }else{ return -1; } fs.read((char*)&header, sizeof(header)); if(fs.gcount() != sizeof(header)){return -1;} if(!header.magic_check()){return -1;} header.hton(); int hdrlen = header.get_lostheaderlen(); if(hdrlen == -1){return -1;} fs.seekg(hdrlen, std::ios::cur); if(fs.fail()){return -1;} size64 size = fs.tellg(); return size; }
[ "fujinaga@signal.co.jp" ]
fujinaga@signal.co.jp
6a3ed792a86dc0f392e8a63b5ac7fb9460eacf4d
5e58df253d5dffbb8129c4c5ce42b0e9ff55c2e6
/cpp/controllers_py/pybind_utils.cc
5a16eb5b45e0f727926dd2d07132dd8109f9511a
[ "Apache-2.0" ]
permissive
Zhehui-Huang/dm_robotics
ceea7d5d5d92d7219952e13cc67b2e7bd958591f
a37c85c62326a24f090ddd592395229139411c16
refs/heads/main
2023-08-11T02:37:10.100980
2021-10-11T18:26:23
2021-10-12T14:31:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,774
cc
// Copyright 2020 DeepMind Technologies Limited. // // 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 // // https://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 "pybind_utils.h" // controller #include <dlfcn.h> #include <string> #include "dm_robotics/support/logging.h" #include "absl/strings/substitute.h" #include "dm_robotics/mujoco/mjlib.h" #include "pybind11/pybind11.h" // pybind namespace dm_robotics::internal { namespace { namespace py = pybind11; constexpr char kDmControlMjModelClassName[] = "MjModel"; constexpr char kDmControlMjDataClassName[] = "MjData"; // Returns a ctypes module for use through pybind. py::module GetCtypesModule() { static PyObject* const ctypes_module_ptr = []() -> PyObject* { py::module ctypes_module = py::module::import("ctypes"); PyObject* ctypes_module_ptr = ctypes_module.ptr(); Py_XINCREF(ctypes_module_ptr); return ctypes_module_ptr; }(); return py::reinterpret_borrow<py::module>(ctypes_module_ptr); } // Returns a pointer to the underlying object pointed to by `ctypes_obj`. // Note that does not increment the reference count. template <class T> T* GetPointer(py::handle ctypes_obj) { auto ctypes_module = GetCtypesModule(); return reinterpret_cast<T*>( ctypes_module.attr("addressof")(ctypes_obj.attr("contents")) .cast<std::uintptr_t>()); } // Returns a pointer to a MuJoCo mjModel or mjData from the dm_control wrappers // around these objects. The dm_control wrappers are such that the `ptr` // attributes return a ctypes object bound to underlying MuJoCo native type. // // Raises a `RuntimeError` exception in Python if the handle does not contain a // `ptr` attribute. template <class T> T* GetMujocoPointerFromDmControlWrapperHandle(py::handle dm_control_wrapper) { if (!py::hasattr(dm_control_wrapper, "ptr")) { RaiseRuntimeErrorWithMessage( "GetMujocoPointerFromDmControlWrapperHandle: handle does not have a " "`ptr` attribute. This function assumes that dm_control wrappers " "around mjModel and mjData contain a `ptr` attribute with the MuJoCo " "native type."); } return GetPointer<T>(dm_control_wrapper.attr("ptr")); } } // namespace void RaiseRuntimeErrorWithMessage(absl::string_view message) { PyErr_SetString(PyExc_RuntimeError, std::string(message).c_str()); throw py::error_already_set(); } const MjLib* LoadMjLibFromDmControl() { py::gil_scoped_acquire gil; // Get the path to the DSO. const py::module mjbindings( py::module::import("dm_control.mujoco.wrapper.mjbindings")); const std::string dso_path = mjbindings.attr("mjlib").attr("_name").cast<std::string>(); // Create the MjLib object by dlopen'ing the DSO. auto* mjlib = new MjLib(dso_path, RTLD_NOW); // Activate the MuJoCo library. const py::module mjutil(py::module::import("dm_control.mujoco.wrapper.util")); const std::string key_path = mjutil.attr("get_mjkey_path")().cast<std::string>(); CHECK_EQ(mjlib->mj_activate(key_path.c_str()), 1) << "Unable to activate MuJoCo with license located in: " << key_path; return mjlib; } // Helper function for getting an mjModel object from a py::handle. const mjModel* GetmjModelOrRaise(py::handle obj) { const std::string class_name = obj.attr("__class__").attr("__name__").cast<std::string>(); if (class_name != kDmControlMjModelClassName) { RaiseRuntimeErrorWithMessage(absl::Substitute( "GetmjModelOrRaise: the class name of the argument [$0] does not match " "the expected dm_control type name for mjModel [$1].", class_name, kDmControlMjModelClassName)); } return GetMujocoPointerFromDmControlWrapperHandle<mjModel>(obj); } // Helper function for getting an mjData object from a py::handle. const mjData* GetmjDataOrRaise(py::handle obj) { const std::string class_name = obj.attr("__class__").attr("__name__").cast<std::string>(); if (class_name != kDmControlMjDataClassName) { RaiseRuntimeErrorWithMessage(absl::Substitute( "GetmjDataOrRaise: the class name of the argument [$0] does not match " "the expected dm_control type name for mjData [$1].", class_name, kDmControlMjDataClassName)); } return GetMujocoPointerFromDmControlWrapperHandle<mjData>(obj); } } // namespace dm_robotics::internal
[ "akhilraju@google.com" ]
akhilraju@google.com
8ca43b0dc207377f537c5322f19c84bf890dae49
dd80a584130ef1a0333429ba76c1cee0eb40df73
/external/compiler-rt/lib/asan/lit_tests/TestCases/wait.cc
b5580dc88675a0964e846e39e79dc96b377af219
[ "MIT", "NCSA" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
C++
false
false
2,199
cc
// RUN: %clangxx_asan -DWAIT -O0 %s -o %t && not %t 2>&1 | FileCheck %s // RUN: %clangxx_asan -DWAIT -O3 %s -o %t && not %t 2>&1 | FileCheck %s // RUN: %clangxx_asan -DWAITPID -O0 %s -o %t && not %t 2>&1 | FileCheck %s // RUN: %clangxx_asan -DWAITPID -O3 %s -o %t && not %t 2>&1 | FileCheck %s // RUN: %clangxx_asan -DWAITID -O0 %s -o %t && not %t 2>&1 | FileCheck %s // RUN: %clangxx_asan -DWAITID -O3 %s -o %t && not %t 2>&1 | FileCheck %s // RUN: %clangxx_asan -DWAIT3 -O0 %s -o %t && not %t 2>&1 | FileCheck %s // RUN: %clangxx_asan -DWAIT3 -O3 %s -o %t && not %t 2>&1 | FileCheck %s // RUN: %clangxx_asan -DWAIT4 -O0 %s -o %t && not %t 2>&1 | FileCheck %s // RUN: %clangxx_asan -DWAIT4 -O3 %s -o %t && not %t 2>&1 | FileCheck %s // RUN: %clangxx_asan -DWAIT3_RUSAGE -O0 %s -o %t && not %t 2>&1 | FileCheck %s // RUN: %clangxx_asan -DWAIT3_RUSAGE -O3 %s -o %t && not %t 2>&1 | FileCheck %s // RUN: %clangxx_asan -DWAIT4_RUSAGE -O0 %s -o %t && not %t 2>&1 | FileCheck %s // RUN: %clangxx_asan -DWAIT4_RUSAGE -O3 %s -o %t && not %t 2>&1 | FileCheck %s #include <assert.h> #include <sys/wait.h> #include <unistd.h> int main(int argc, char **argv) { pid_t pid = fork(); if (pid) { // parent int x[3]; int *status = x + argc * 3; int res; #if defined(WAIT) res = wait(status); #elif defined(WAITPID) res = waitpid(pid, status, WNOHANG); #elif defined(WAITID) siginfo_t *si = (siginfo_t*)(x + argc * 3); res = waitid(P_ALL, 0, si, WEXITED | WNOHANG); #elif defined(WAIT3) res = wait3(status, WNOHANG, NULL); #elif defined(WAIT4) res = wait4(pid, status, WNOHANG, NULL); #elif defined(WAIT3_RUSAGE) || defined(WAIT4_RUSAGE) struct rusage *ru = (struct rusage*)(x + argc * 3); int good_status; # if defined(WAIT3_RUSAGE) res = wait3(&good_status, WNOHANG, ru); # elif defined(WAIT4_RUSAGE) res = wait4(pid, &good_status, WNOHANG, ru); # endif #endif // CHECK: stack-buffer-overflow // CHECK: {{WRITE of size .* at 0x.* thread T0}} // CHECK: {{in .*wait}} // CHECK: {{in main .*wait.cc:}} // CHECK: is located in stack of thread T0 at offset // CHECK: {{in main}} return res != -1; } // child return 0; }
[ "karun.matharu@gmail.com" ]
karun.matharu@gmail.com
d696282cdefc1d4c4e7d4fd4a0744fe8ba9b0251
0bf3e7e9784c00a72e774e84bb042ac0cf83fc36
/lab3_bliss/src/Controller.h
3c07cd8dd3703e79f2240da129831bc770c68900
[ "MIT" ]
permissive
tyr0525/Computer-Architecture-Projects
73762b36e010969ee62eda5e36bb2ceb6b94ec41
2ff1060f9e918f20a0672c187e1e47e047c0bb8d
refs/heads/master
2022-11-28T05:40:54.028342
2020-07-10T09:07:56
2020-07-10T09:07:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
50,582
h
#ifndef __CONTROLLER_H #define __CONTROLLER_H #include <cassert> #include <cstdio> #include <deque> #include <fstream> #include <list> #include <string> #include <vector> #include "Config.h" #include "DRAM.h" #include "Refresh.h" #include "Request.h" #include "Scheduler.h" #include "Statistics.h" #include "ALDRAM.h" #include "SALP.h" #include "TLDRAM.h" using namespace std; namespace ramulator { extern bool warmup_complete; template <typename T> class Controller { protected: // For counting bandwidth ScalarStat read_transaction_bytes; ScalarStat write_transaction_bytes; ScalarStat row_hits; ScalarStat row_misses; ScalarStat row_conflicts; VectorStat read_row_hits; VectorStat read_row_misses; VectorStat read_row_conflicts; VectorStat write_row_hits; VectorStat write_row_misses; VectorStat write_row_conflicts; ScalarStat useless_activates; ScalarStat read_latency_avg; ScalarStat read_latency_sum; ScalarStat req_queue_length_avg; ScalarStat req_queue_length_sum; ScalarStat read_req_queue_length_avg; ScalarStat read_req_queue_length_sum; ScalarStat write_req_queue_length_avg; ScalarStat write_req_queue_length_sum; #ifndef INTEGRATED_WITH_GEM5 VectorStat record_read_hits; VectorStat record_read_misses; VectorStat record_read_conflicts; VectorStat record_write_hits; VectorStat record_write_misses; VectorStat record_write_conflicts; #endif public: /* Member Variables */ long clk = 0; DRAM<T>* channel; Scheduler<T>* scheduler; // determines the highest priority request whose commands will be issued RowPolicy<T>* rowpolicy; // determines the row-policy (e.g., closed-row vs. open-row) RowTable<T>* rowtable; // tracks metadata about rows (e.g., which are open and for how long) Refresh<T>* refresh; struct Queue { list<Request> q; unsigned int max = 32; unsigned int size() {return q.size();} }; int MAX_SIZE = 32; int MAX_CYCLE = 10000; int resetCycleLeft = MAX_CYCLE; int MAX_REQUEST = 4; Queue readq; // queue for read requests Queue writeq; // queue for write requests Queue bliss_readq; Queue bliss_writeq; Queue actq; // read and write requests for which activate was issued are moved to // actq, which has higher priority than readq and writeq. // This is an optimization // for avoiding useless activations (i.e., PRECHARGE // after ACTIVATE w/o READ of WRITE command) map<int,bool> blacklist; Queue otherq; // queue for all "other" requests (e.g., refresh) map<int, int> counter; //counter consecutive requests deque<Request> pending; // read requests that are about to receive data from DRAM bool write_mode = false; // whether write requests should be prioritized over reads bool bliss_mode = false; // whether schedule requests from blacklist float wr_high_watermark = 0.8f; // threshold for switching to write mode float wr_low_watermark = 0.2f; // threshold for switching back to read mode //long refreshed = 0; // last time refresh requests were generated /* Command trace for DRAMPower 3.1 */ string cmd_trace_prefix = "cmd-trace-"; vector<ofstream> cmd_trace_files; bool record_cmd_trace = false; /* Commands to stdout */ bool print_cmd_trace = false; /* Constructor */ Controller(const Config& configs, DRAM<T>* channel) : channel(channel), scheduler(new Scheduler<T>(this)), rowpolicy(new RowPolicy<T>(this)), rowtable(new RowTable<T>(this)), refresh(new Refresh<T>(this)), cmd_trace_files(channel->children.size()) { record_cmd_trace = configs.record_cmd_trace(); print_cmd_trace = configs.print_cmd_trace(); if (record_cmd_trace){ if (configs["cmd_trace_prefix"] != "") { cmd_trace_prefix = configs["cmd_trace_prefix"]; } string prefix = cmd_trace_prefix + "chan-" + to_string(channel->id) + "-rank-"; string suffix = ".cmdtrace"; for (unsigned int i = 0; i < channel->children.size(); i++) cmd_trace_files[i].open(prefix + to_string(i) + suffix); } // regStats row_hits .name("row_hits_channel_"+to_string(channel->id) + "_core") .desc("Number of row hits per channel per core") .precision(0) ; row_misses .name("row_misses_channel_"+to_string(channel->id) + "_core") .desc("Number of row misses per channel per core") .precision(0) ; row_conflicts .name("row_conflicts_channel_"+to_string(channel->id) + "_core") .desc("Number of row conflicts per channel per core") .precision(0) ; read_row_hits .init(configs.get_core_num()) .name("read_row_hits_channel_"+to_string(channel->id) + "_core") .desc("Number of row hits for read requests per channel per core") .precision(0) ; read_row_misses .init(configs.get_core_num()) .name("read_row_misses_channel_"+to_string(channel->id) + "_core") .desc("Number of row misses for read requests per channel per core") .precision(0) ; read_row_conflicts .init(configs.get_core_num()) .name("read_row_conflicts_channel_"+to_string(channel->id) + "_core") .desc("Number of row conflicts for read requests per channel per core") .precision(0) ; write_row_hits .init(configs.get_core_num()) .name("write_row_hits_channel_"+to_string(channel->id) + "_core") .desc("Number of row hits for write requests per channel per core") .precision(0) ; write_row_misses .init(configs.get_core_num()) .name("write_row_misses_channel_"+to_string(channel->id) + "_core") .desc("Number of row misses for write requests per channel per core") .precision(0) ; write_row_conflicts .init(configs.get_core_num()) .name("write_row_conflicts_channel_"+to_string(channel->id) + "_core") .desc("Number of row conflicts for write requests per channel per core") .precision(0) ; useless_activates .name("useless_activates_"+to_string(channel->id)+ "_core") .desc("Number of useless activations. E.g, ACT -> PRE w/o RD or WR") .precision(0) ; read_transaction_bytes .name("read_transaction_bytes_"+to_string(channel->id)) .desc("The total byte of read transaction per channel") .precision(0) ; write_transaction_bytes .name("write_transaction_bytes_"+to_string(channel->id)) .desc("The total byte of write transaction per channel") .precision(0) ; read_latency_sum .name("read_latency_sum_"+to_string(channel->id)) .desc("The memory latency cycles (in memory time domain) sum for all read requests in this channel") .precision(0) ; read_latency_avg .name("read_latency_avg_"+to_string(channel->id)) .desc("The average memory latency cycles (in memory time domain) per request for all read requests in this channel") .precision(6) ; req_queue_length_sum .name("req_queue_length_sum_"+to_string(channel->id)) .desc("Sum of read and write queue length per memory cycle per channel.") .precision(0) ; req_queue_length_avg .name("req_queue_length_avg_"+to_string(channel->id)) .desc("Average of read and write queue length per memory cycle per channel.") .precision(6) ; read_req_queue_length_sum .name("read_req_queue_length_sum_"+to_string(channel->id)) .desc("Read queue length sum per memory cycle per channel.") .precision(0) ; read_req_queue_length_avg .name("read_req_queue_length_avg_"+to_string(channel->id)) .desc("Read queue length average per memory cycle per channel.") .precision(6) ; write_req_queue_length_sum .name("write_req_queue_length_sum_"+to_string(channel->id)) .desc("Write queue length sum per memory cycle per channel.") .precision(0) ; write_req_queue_length_avg .name("write_req_queue_length_avg_"+to_string(channel->id)) .desc("Write queue length average per memory cycle per channel.") .precision(6) ; #ifndef INTEGRATED_WITH_GEM5 record_read_hits .init(configs.get_core_num()) .name("record_read_hits") .desc("record read hit count for this core when it reaches request limit or to the end") ; record_read_misses .init(configs.get_core_num()) .name("record_read_misses") .desc("record_read_miss count for this core when it reaches request limit or to the end") ; record_read_conflicts .init(configs.get_core_num()) .name("record_read_conflicts") .desc("record read conflict count for this core when it reaches request limit or to the end") ; record_write_hits .init(configs.get_core_num()) .name("record_write_hits") .desc("record write hit count for this core when it reaches request limit or to the end") ; record_write_misses .init(configs.get_core_num()) .name("record_write_misses") .desc("record write miss count for this core when it reaches request limit or to the end") ; record_write_conflicts .init(configs.get_core_num()) .name("record_write_conflicts") .desc("record write conflict for this core when it reaches request limit or to the end") ; #endif } ~Controller(){ delete scheduler; delete rowpolicy; delete rowtable; delete channel; delete refresh; for (auto& file : cmd_trace_files) file.close(); cmd_trace_files.clear(); } void reset_blacklist(){ blacklist.clear(); readq.q.splice(readq.q.end(),bliss_readq.q); writeq.q.splice(writeq.q.end(),bliss_writeq.q); resetCycleLeft = MAX_CYCLE; } void check_interference(int pid ){ map<int,int>::iterator it = counter.find(pid); if(it == counter.end()){ counter.insert(pair<int,int>(pid,0)); }else if (it->second < MAX_REQUEST) { counter[pid]++; }else if (it->second == MAX_REQUEST){ blacklist.insert(pair<int,bool>(pid, true)); blacklist[pid] = true; } } void finish(long read_req, long dram_cycles) { read_latency_avg = read_latency_sum.value() / read_req; req_queue_length_avg = req_queue_length_sum.value() / dram_cycles; read_req_queue_length_avg = read_req_queue_length_sum.value() / dram_cycles; write_req_queue_length_avg = write_req_queue_length_sum.value() / dram_cycles; // call finish function of each channel channel->finish(dram_cycles); } /* Member Functions */ Queue& get_queue(Request::Type type,bool blacklist) { if(blacklist){ switch (int(type)) { case int(Request::Type::READ): return bliss_readq; case int(Request::Type::WRITE): return bliss_writeq; default: return otherq; } }else{ switch (int(type)) { case int(Request::Type::READ): return readq; case int(Request::Type::WRITE): return writeq; default: return otherq; } } } bool enqueue(Request& req) { if(req.type == Request::Type::REFRESH){ return true; } bool blacklist_stat = false; map<int,bool>::iterator it = blacklist.find(req.pid); if(it != blacklist.end()){ blacklist_stat = true; } Queue& queue = get_queue(req.type,blacklist_stat); if (MAX_SIZE == readq.size()+bliss_readq.size()) return false; if (MAX_SIZE == writeq.size()+bliss_writeq.size()) return false; req.arrive = clk; queue.q.push_back(req); // shortcut for read requests, if a write to same addr exists // necessary for coherence if (!blacklist_stat && req.type == Request::Type::READ && find_if(writeq.q.begin(), writeq.q.end(), [req](Request& wreq){ return req.addr == wreq.addr;}) != writeq.q.end()){ req.depart = clk + 1; pending.push_back(req); readq.q.pop_back(); } // still push back to pending, no difference, since memory not involved in this case; if (blacklist_stat && req.type == Request::Type::READ && find_if(bliss_writeq.q.begin(), bliss_writeq.q.end(), [req](Request& wreq){ return req.addr == wreq.addr;}) != bliss_writeq.q.end()){ req.depart = clk + 1; pending.push_back(req); bliss_readq.q.pop_back(); } return true; } void tick() { clk++; resetCycleLeft--; if(resetCycleLeft == 0) reset_blacklist(); req_queue_length_sum += readq.size() + writeq.size() + pending.size(); read_req_queue_length_sum += readq.size() + pending.size(); write_req_queue_length_sum += writeq.size(); /*** 1. Serve completed reads ***/ if (pending.size()) { Request& req = pending[0]; if (req.depart <= clk) { if (req.depart - req.arrive > 1) { // this request really accessed a row read_latency_sum += req.depart - req.arrive; channel->update_serving_requests( req.addr_vec.data(), -1, clk); } req.callback(req); pending.pop_front(); } } /*** 2. Refresh scheduler ***/ refresh->tick_ref(); /*** 3. Should we schedule writes? ***/ if(!bliss_mode){ if(readq.size()==0 && writeq.size() == 0){ bliss_mode = true; } }else{ if(readq.size()!=0 || writeq.size() != 0){ bliss_mode = false; } } Queue* Swriteq = bliss_mode ? &bliss_writeq : &writeq; Queue* Sreadq = bliss_mode ? &bliss_readq : &readq; if (!write_mode) { // yes -- write queue is almost full or read queue is empty if ((*Swriteq).size() > int(wr_high_watermark * (*Swriteq).max) || (*Sreadq).size() == 0) write_mode = true; } else { // no -- write queue is almost empty and read queue is not empty if ((*Swriteq).size() < int(wr_low_watermark * (*Swriteq).max) && (*Sreadq).size() != 0) write_mode = false; } /*** 4. Find the best command to schedule, if any ***/ // First check the actq (which has higher priority) to see if there // are requests available to service in this cycle Queue* queue = &actq; auto req = scheduler->get_head(queue->q); if ((req == queue->q.end() || !is_ready(req)) && actq.size()==0 ) { if(bliss_mode){ queue = !write_mode ? &bliss_readq : &bliss_writeq; }else{ queue = !write_mode ? &readq : &writeq; } if (otherq.size()) queue = &otherq; // "other" requests are rare, so we give them precedence over reads/writes req = scheduler->get_head(queue->q); } if (req == queue->q.end() || !is_ready(req)) { // we couldn't find a command to schedule -- let's try to be speculative auto cmd = T::Command::PRE; vector<int> victim = rowpolicy->get_victim(cmd); if (!victim.empty()){ issue_cmd(cmd, victim); } return; // nothing more to be done this cycle } if (req->is_first_command) { req->is_first_command = false; int coreid = req->coreid; if (req->type == Request::Type::READ || req->type == Request::Type::WRITE) { channel->update_serving_requests(req->addr_vec.data(), 1, clk); } int tx = (channel->spec->prefetch_size * channel->spec->channel_width / 8); if (req->type == Request::Type::READ) { if (is_row_hit(req)) { ++read_row_hits[coreid]; ++row_hits; } else if (is_row_open(req)) { ++read_row_conflicts[coreid]; ++row_conflicts; } else { ++read_row_misses[coreid]; ++row_misses; } read_transaction_bytes += tx; } else if (req->type == Request::Type::WRITE) { if (is_row_hit(req)) { ++write_row_hits[coreid]; ++row_hits; } else if (is_row_open(req)) { ++write_row_conflicts[coreid]; ++row_conflicts; } else { ++write_row_misses[coreid]; ++row_misses; } write_transaction_bytes += tx; } } // issue command on behalf of request auto cmd = get_first_cmd(req); issue_cmd(cmd, get_addr_vec(cmd, req)); // check whether this is the last command (which finishes the request) //if (cmd != channel->spec->translate[int(req->type)]){ if (!(channel->spec->is_accessing(cmd) || channel->spec->is_refreshing(cmd))) { if(channel->spec->is_opening(cmd)) { // promote the request that caused issuing activation to actq actq.q.push_back(*req); queue->q.erase(req); } return; } // set a future completion time for read requests if (req->type == Request::Type::READ) { req->depart = clk + channel->spec->read_latency; pending.push_back(*req); } if (req->type == Request::Type::WRITE) { channel->update_serving_requests(req->addr_vec.data(), -1, clk); req->callback(*req); } // remove request from queue queue->q.erase(req); check_interference(req->pid); } bool is_ready(list<Request>::iterator req) { typename T::Command cmd = get_first_cmd(req); return channel->check(cmd, req->addr_vec.data(), clk); } bool is_ready(typename T::Command cmd, const vector<int>& addr_vec) { return channel->check(cmd, addr_vec.data(), clk); } bool is_row_hit(list<Request>::iterator req) { // cmd must be decided by the request type, not the first cmd typename T::Command cmd = channel->spec->translate[int(req->type)]; return channel->check_row_hit(cmd, req->addr_vec.data()); } bool is_row_hit(typename T::Command cmd, const vector<int>& addr_vec) { return channel->check_row_hit(cmd, addr_vec.data()); } bool is_row_open(list<Request>::iterator req) { // cmd must be decided by the request type, not the first cmd typename T::Command cmd = channel->spec->translate[int(req->type)]; return channel->check_row_open(cmd, req->addr_vec.data()); } bool is_row_open(typename T::Command cmd, const vector<int>& addr_vec) { return channel->check_row_open(cmd, addr_vec.data()); } void update_temp(ALDRAM::Temp current_temperature) { } // For telling whether this channel is busying in processing read or write bool is_active() { return (channel->cur_serving_requests > 0); } // For telling whether this channel is under refresh bool is_refresh() { return clk <= channel->end_of_refreshing; } void set_high_writeq_watermark(const float watermark) { wr_high_watermark = watermark; } void set_low_writeq_watermark(const float watermark) { wr_low_watermark = watermark; } void record_core(int coreid) { #ifndef INTEGRATED_WITH_GEM5 record_read_hits[coreid] = read_row_hits[coreid]; record_read_misses[coreid] = read_row_misses[coreid]; record_read_conflicts[coreid] = read_row_conflicts[coreid]; record_write_hits[coreid] = write_row_hits[coreid]; record_write_misses[coreid] = write_row_misses[coreid]; record_write_conflicts[coreid] = write_row_conflicts[coreid]; #endif } private: typename T::Command get_first_cmd(list<Request>::iterator req) { typename T::Command cmd = channel->spec->translate[int(req->type)]; return channel->decode(cmd, req->addr_vec.data()); } // upgrade to an autoprecharge command void cmd_issue_autoprecharge(typename T::Command& cmd, const vector<int>& addr_vec) { // currently, autoprecharge is only used with closed row policy if(channel->spec->is_accessing(cmd) && rowpolicy->type == RowPolicy<T>::Type::ClosedAP) { // check if it is the last request to the opened row Queue* queue = write_mode ? &writeq : &readq; auto begin = addr_vec.begin(); vector<int> rowgroup(begin, begin + int(T::Level::Row) + 1); int num_row_hits = 0; for (auto itr = queue->q.begin(); itr != queue->q.end(); ++itr) { if (is_row_hit(itr)) { auto begin2 = itr->addr_vec.begin(); vector<int> rowgroup2(begin2, begin2 + int(T::Level::Row) + 1); if(rowgroup == rowgroup2) num_row_hits++; } } if(num_row_hits == 0) { Queue* queue = &actq; for (auto itr = queue->q.begin(); itr != queue->q.end(); ++itr) { if (is_row_hit(itr)) { auto begin2 = itr->addr_vec.begin(); vector<int> rowgroup2(begin2, begin2 + int(T::Level::Row) + 1); if(rowgroup == rowgroup2) num_row_hits++; } } } assert(num_row_hits > 0); // The current request should be a hit, // so there should be at least one request // that hits in the current open row if(num_row_hits == 1) { if(cmd == T::Command::RD) cmd = T::Command::RDA; else if (cmd == T::Command::WR) cmd = T::Command::WRA; else assert(false && "Unimplemented command type."); } } } void issue_cmd(typename T::Command cmd, const vector<int>& addr_vec) { cmd_issue_autoprecharge(cmd, addr_vec); assert(is_ready(cmd, addr_vec)); channel->update(cmd, addr_vec.data(), clk); if(cmd == T::Command::PRE){ if(rowtable->get_hits(addr_vec, true) == 0){ useless_activates++; } } rowtable->update(cmd, addr_vec, clk); if (record_cmd_trace){ // select rank auto& file = cmd_trace_files[addr_vec[1]]; string& cmd_name = channel->spec->command_name[int(cmd)]; file<<clk<<','<<cmd_name; // TODO bad coding here if (cmd_name == "PREA" || cmd_name == "REF") file<<endl; else{ int bank_id = addr_vec[int(T::Level::Bank)]; if (channel->spec->standard_name == "DDR4" || channel->spec->standard_name == "GDDR5") bank_id += addr_vec[int(T::Level::Bank) - 1] * channel->spec->org_entry.count[int(T::Level::Bank)]; file<<','<<bank_id<<endl; } } if (print_cmd_trace){ printf("%5s %10ld:", channel->spec->command_name[int(cmd)].c_str(), clk); for (int lev = 0; lev < int(T::Level::MAX); lev++) printf(" %5d", addr_vec[lev]); printf("\n"); } } vector<int> get_addr_vec(typename T::Command cmd, list<Request>::iterator req){ return req->addr_vec; } }; template <> vector<int> Controller<SALP>::get_addr_vec( SALP::Command cmd, list<Request>::iterator req); template <> bool Controller<SALP>::is_ready(list<Request>::iterator req); template <> void Controller<ALDRAM>::update_temp(ALDRAM::Temp current_temperature); template <> void Controller<TLDRAM>::tick(); template <> void Controller<TLDRAM>::cmd_issue_autoprecharge(typename TLDRAM::Command& cmd, const vector<int>& addr_vec); } /*namespace ramulator*/ #endif /*__CONTROLLER_H*/ //============================================================================== // #ifndef __CONTROLLER_H // #define __CONTROLLER_H // #include <cassert> // #include <cstdio> // #include <deque> // #include <fstream> // #include <list> // #include <string> // #include <vector> // #include "Config.h" // #include "DRAM.h" // #include "Refresh.h" // #include "Request.h" // #include "Scheduler.h" // #include "Statistics.h" // #include "ALDRAM.h" // #include "SALP.h" // #include "TLDRAM.h" // using namespace std; // namespace ramulator // { // extern bool warmup_complete; // template <typename T> // class Controller // { // protected: // // For counting bandwidth // ScalarStat read_transaction_bytes; // ScalarStat write_transaction_bytes; // ScalarStat row_hits; // ScalarStat row_misses; // ScalarStat row_conflicts; // VectorStat read_row_hits; // VectorStat read_row_misses; // VectorStat read_row_conflicts; // VectorStat write_row_hits; // VectorStat write_row_misses; // VectorStat write_row_conflicts; // ScalarStat useless_activates; // ScalarStat read_latency_avg; // ScalarStat read_latency_sum; // ScalarStat req_queue_length_avg; // ScalarStat req_queue_length_sum; // ScalarStat read_req_queue_length_avg; // ScalarStat read_req_queue_length_sum; // ScalarStat write_req_queue_length_avg; // ScalarStat write_req_queue_length_sum; // #ifndef INTEGRATED_WITH_GEM5 // VectorStat record_read_hits; // VectorStat record_read_misses; // VectorStat record_read_conflicts; // VectorStat record_write_hits; // VectorStat record_write_misses; // VectorStat record_write_conflicts; // #endif // public: // /* Member Variables */ // long clk = 0; // DRAM<T>* channel; // Scheduler<T>* scheduler; // determines the highest priority request whose commands will be issued // RowPolicy<T>* rowpolicy; // determines the row-policy (e.g., closed-row vs. open-row) // RowTable<T>* rowtable; // tracks metadata about rows (e.g., which are open and for how long) // Refresh<T>* refresh; // struct Queue { // list<Request> q; // unsigned int max = 32; // unsigned int size() {return q.size();} // }; // Queue readq; // queue for read requests // Queue writeq; // queue for write requests // Queue actq; // read and write requests for which activate was issued are moved to // // actq, which has higher priority than readq and writeq. // // This is an optimization // // for avoiding useless activations (i.e., PRECHARGE // // after ACTIVATE w/o READ of WRITE command) // Queue otherq; // queue for all "other" requests (e.g., refresh) // deque<Request> pending; // read requests that are about to receive data from DRAM // bool write_mode = false; // whether write requests should be prioritized over reads // float wr_high_watermark = 0.8f; // threshold for switching to write mode // float wr_low_watermark = 0.2f; // threshold for switching back to read mode // //long refreshed = 0; // last time refresh requests were generated // /* Command trace for DRAMPower 3.1 */ // string cmd_trace_prefix = "cmd-trace-"; // vector<ofstream> cmd_trace_files; // bool record_cmd_trace = false; // /* Commands to stdout */ // bool print_cmd_trace = false; // /* Constructor */ // Controller(const Config& configs, DRAM<T>* channel) : // channel(channel), // scheduler(new Scheduler<T>(this)), // rowpolicy(new RowPolicy<T>(this)), // rowtable(new RowTable<T>(this)), // refresh(new Refresh<T>(this)), // cmd_trace_files(channel->children.size()) // { // record_cmd_trace = configs.record_cmd_trace(); // print_cmd_trace = configs.print_cmd_trace(); // if (record_cmd_trace){ // if (configs["cmd_trace_prefix"] != "") { // cmd_trace_prefix = configs["cmd_trace_prefix"]; // } // string prefix = cmd_trace_prefix + "chan-" + to_string(channel->id) + "-rank-"; // string suffix = ".cmdtrace"; // for (unsigned int i = 0; i < channel->children.size(); i++) // cmd_trace_files[i].open(prefix + to_string(i) + suffix); // } // // regStats // row_hits // .name("row_hits_channel_"+to_string(channel->id) + "_core") // .desc("Number of row hits per channel per core") // .precision(0) // ; // row_misses // .name("row_misses_channel_"+to_string(channel->id) + "_core") // .desc("Number of row misses per channel per core") // .precision(0) // ; // row_conflicts // .name("row_conflicts_channel_"+to_string(channel->id) + "_core") // .desc("Number of row conflicts per channel per core") // .precision(0) // ; // read_row_hits // .init(configs.get_core_num()) // .name("read_row_hits_channel_"+to_string(channel->id) + "_core") // .desc("Number of row hits for read requests per channel per core") // .precision(0) // ; // read_row_misses // .init(configs.get_core_num()) // .name("read_row_misses_channel_"+to_string(channel->id) + "_core") // .desc("Number of row misses for read requests per channel per core") // .precision(0) // ; // read_row_conflicts // .init(configs.get_core_num()) // .name("read_row_conflicts_channel_"+to_string(channel->id) + "_core") // .desc("Number of row conflicts for read requests per channel per core") // .precision(0) // ; // write_row_hits // .init(configs.get_core_num()) // .name("write_row_hits_channel_"+to_string(channel->id) + "_core") // .desc("Number of row hits for write requests per channel per core") // .precision(0) // ; // write_row_misses // .init(configs.get_core_num()) // .name("write_row_misses_channel_"+to_string(channel->id) + "_core") // .desc("Number of row misses for write requests per channel per core") // .precision(0) // ; // write_row_conflicts // .init(configs.get_core_num()) // .name("write_row_conflicts_channel_"+to_string(channel->id) + "_core") // .desc("Number of row conflicts for write requests per channel per core") // .precision(0) // ; // useless_activates // .name("useless_activates_"+to_string(channel->id)+ "_core") // .desc("Number of useless activations. E.g, ACT -> PRE w/o RD or WR") // .precision(0) // ; // read_transaction_bytes // .name("read_transaction_bytes_"+to_string(channel->id)) // .desc("The total byte of read transaction per channel") // .precision(0) // ; // write_transaction_bytes // .name("write_transaction_bytes_"+to_string(channel->id)) // .desc("The total byte of write transaction per channel") // .precision(0) // ; // read_latency_sum // .name("read_latency_sum_"+to_string(channel->id)) // .desc("The memory latency cycles (in memory time domain) sum for all read requests in this channel") // .precision(0) // ; // read_latency_avg // .name("read_latency_avg_"+to_string(channel->id)) // .desc("The average memory latency cycles (in memory time domain) per request for all read requests in this channel") // .precision(6) // ; // req_queue_length_sum // .name("req_queue_length_sum_"+to_string(channel->id)) // .desc("Sum of read and write queue length per memory cycle per channel.") // .precision(0) // ; // req_queue_length_avg // .name("req_queue_length_avg_"+to_string(channel->id)) // .desc("Average of read and write queue length per memory cycle per channel.") // .precision(6) // ; // read_req_queue_length_sum // .name("read_req_queue_length_sum_"+to_string(channel->id)) // .desc("Read queue length sum per memory cycle per channel.") // .precision(0) // ; // read_req_queue_length_avg // .name("read_req_queue_length_avg_"+to_string(channel->id)) // .desc("Read queue length average per memory cycle per channel.") // .precision(6) // ; // write_req_queue_length_sum // .name("write_req_queue_length_sum_"+to_string(channel->id)) // .desc("Write queue length sum per memory cycle per channel.") // .precision(0) // ; // write_req_queue_length_avg // .name("write_req_queue_length_avg_"+to_string(channel->id)) // .desc("Write queue length average per memory cycle per channel.") // .precision(6) // ; // #ifndef INTEGRATED_WITH_GEM5 // record_read_hits // .init(configs.get_core_num()) // .name("record_read_hits") // .desc("record read hit count for this core when it reaches request limit or to the end") // ; // record_read_misses // .init(configs.get_core_num()) // .name("record_read_misses") // .desc("record_read_miss count for this core when it reaches request limit or to the end") // ; // record_read_conflicts // .init(configs.get_core_num()) // .name("record_read_conflicts") // .desc("record read conflict count for this core when it reaches request limit or to the end") // ; // record_write_hits // .init(configs.get_core_num()) // .name("record_write_hits") // .desc("record write hit count for this core when it reaches request limit or to the end") // ; // record_write_misses // .init(configs.get_core_num()) // .name("record_write_misses") // .desc("record write miss count for this core when it reaches request limit or to the end") // ; // record_write_conflicts // .init(configs.get_core_num()) // .name("record_write_conflicts") // .desc("record write conflict for this core when it reaches request limit or to the end") // ; // #endif // } // ~Controller(){ // delete scheduler; // delete rowpolicy; // delete rowtable; // delete channel; // delete refresh; // for (auto& file : cmd_trace_files) // file.close(); // cmd_trace_files.clear(); // } // void finish(long read_req, long dram_cycles) { // read_latency_avg = read_latency_sum.value() / read_req; // req_queue_length_avg = req_queue_length_sum.value() / dram_cycles; // read_req_queue_length_avg = read_req_queue_length_sum.value() / dram_cycles; // write_req_queue_length_avg = write_req_queue_length_sum.value() / dram_cycles; // // call finish function of each channel // channel->finish(dram_cycles); // } // /* Member Functions */ // Queue& get_queue(Request::Type type) // { // switch (int(type)) { // case int(Request::Type::READ): return readq; // case int(Request::Type::WRITE): return writeq; // default: return otherq; // } // } // bool enqueue(Request& req) // { // Queue& queue = get_queue(req.type); // if (queue.max == queue.size()) // return false; // req.arrive = clk; // queue.q.push_back(req); // // shortcut for read requests, if a write to same addr exists // // necessary for coherence // if (req.type == Request::Type::READ && find_if(writeq.q.begin(), writeq.q.end(), // [req](Request& wreq){ return req.addr == wreq.addr;}) != writeq.q.end()){ // req.depart = clk + 1; // pending.push_back(req); // readq.q.pop_back(); // } // return true; // } // void tick() // { // clk++; // req_queue_length_sum += readq.size() + writeq.size() + pending.size(); // read_req_queue_length_sum += readq.size() + pending.size(); // write_req_queue_length_sum += writeq.size(); // /*** 1. Serve completed reads ***/ // if (pending.size()) { // Request& req = pending[0]; // if (req.depart <= clk) { // if (req.depart - req.arrive > 1) { // this request really accessed a row // read_latency_sum += req.depart - req.arrive; // channel->update_serving_requests( // req.addr_vec.data(), -1, clk); // } // req.callback(req); // pending.pop_front(); // } // } // /*** 2. Refresh scheduler ***/ // refresh->tick_ref(); // /*** 3. Should we schedule writes? ***/ // if (!write_mode) { // // yes -- write queue is almost full or read queue is empty // if (writeq.size() > int(wr_high_watermark * writeq.max) || readq.size() == 0) // write_mode = true; // } // else { // // no -- write queue is almost empty and read queue is not empty // if (writeq.size() < int(wr_low_watermark * writeq.max) && readq.size() != 0) // write_mode = false; // } // /*** 4. Find the best command to schedule, if any ***/ // // First check the actq (which has higher priority) to see if there // // are requests available to service in this cycle // Queue* queue = &actq; // auto req = scheduler->get_head(queue->q); // if ((req == queue->q.end() || !is_ready(req)) && actq.size()==0 ) { // queue = !write_mode ? &readq : &writeq; // if (otherq.size()) // queue = &otherq; // "other" requests are rare, so we give them precedence over reads/writes // req = scheduler->get_head(queue->q); // } // if (req == queue->q.end() || !is_ready(req)) { // // we couldn't find a command to schedule -- let's try to be speculative // auto cmd = T::Command::PRE; // vector<int> victim = rowpolicy->get_victim(cmd); // if (!victim.empty()){ // issue_cmd(cmd, victim); // } // return; // nothing more to be done this cycle // } // if (req->is_first_command) { // req->is_first_command = false; // int coreid = req->coreid; // if (req->type == Request::Type::READ || req->type == Request::Type::WRITE) { // channel->update_serving_requests(req->addr_vec.data(), 1, clk); // } // int tx = (channel->spec->prefetch_size * channel->spec->channel_width / 8); // if (req->type == Request::Type::READ) { // if (is_row_hit(req)) { // ++read_row_hits[coreid]; // ++row_hits; // } else if (is_row_open(req)) { // ++read_row_conflicts[coreid]; // ++row_conflicts; // } else { // ++read_row_misses[coreid]; // ++row_misses; // } // read_transaction_bytes += tx; // } else if (req->type == Request::Type::WRITE) { // if (is_row_hit(req)) { // ++write_row_hits[coreid]; // ++row_hits; // } else if (is_row_open(req)) { // ++write_row_conflicts[coreid]; // ++row_conflicts; // } else { // ++write_row_misses[coreid]; // ++row_misses; // } // write_transaction_bytes += tx; // } // } // // issue command on behalf of request // auto cmd = get_first_cmd(req); // issue_cmd(cmd, get_addr_vec(cmd, req)); // // check whether this is the last command (which finishes the request) // //if (cmd != channel->spec->translate[int(req->type)]){ // if (!(channel->spec->is_accessing(cmd) || channel->spec->is_refreshing(cmd))) { // if(channel->spec->is_opening(cmd)) { // // promote the request that caused issuing activation to actq // actq.q.push_back(*req); // queue->q.erase(req); // } // return; // } // // set a future completion time for read requests // if (req->type == Request::Type::READ) { // req->depart = clk + channel->spec->read_latency; // pending.push_back(*req); // } // if (req->type == Request::Type::WRITE) { // channel->update_serving_requests(req->addr_vec.data(), -1, clk); // req->callback(*req); // } // // remove request from queue // queue->q.erase(req); // } // bool is_ready(list<Request>::iterator req) // { // typename T::Command cmd = get_first_cmd(req); // return channel->check(cmd, req->addr_vec.data(), clk); // } // bool is_ready(typename T::Command cmd, const vector<int>& addr_vec) // { // return channel->check(cmd, addr_vec.data(), clk); // } // bool is_row_hit(list<Request>::iterator req) // { // // cmd must be decided by the request type, not the first cmd // typename T::Command cmd = channel->spec->translate[int(req->type)]; // return channel->check_row_hit(cmd, req->addr_vec.data()); // } // bool is_row_hit(typename T::Command cmd, const vector<int>& addr_vec) // { // return channel->check_row_hit(cmd, addr_vec.data()); // } // bool is_row_open(list<Request>::iterator req) // { // // cmd must be decided by the request type, not the first cmd // typename T::Command cmd = channel->spec->translate[int(req->type)]; // return channel->check_row_open(cmd, req->addr_vec.data()); // } // bool is_row_open(typename T::Command cmd, const vector<int>& addr_vec) // { // return channel->check_row_open(cmd, addr_vec.data()); // } // void update_temp(ALDRAM::Temp current_temperature) // { // } // // For telling whether this channel is busying in processing read or write // bool is_active() { // return (channel->cur_serving_requests > 0); // } // // For telling whether this channel is under refresh // bool is_refresh() { // return clk <= channel->end_of_refreshing; // } // void set_high_writeq_watermark(const float watermark) { // wr_high_watermark = watermark; // } // void set_low_writeq_watermark(const float watermark) { // wr_low_watermark = watermark; // } // void record_core(int coreid) { // #ifndef INTEGRATED_WITH_GEM5 // record_read_hits[coreid] = read_row_hits[coreid]; // record_read_misses[coreid] = read_row_misses[coreid]; // record_read_conflicts[coreid] = read_row_conflicts[coreid]; // record_write_hits[coreid] = write_row_hits[coreid]; // record_write_misses[coreid] = write_row_misses[coreid]; // record_write_conflicts[coreid] = write_row_conflicts[coreid]; // #endif // } // private: // typename T::Command get_first_cmd(list<Request>::iterator req) // { // typename T::Command cmd = channel->spec->translate[int(req->type)]; // return channel->decode(cmd, req->addr_vec.data()); // } // // upgrade to an autoprecharge command // void cmd_issue_autoprecharge(typename T::Command& cmd, // const vector<int>& addr_vec) { // // currently, autoprecharge is only used with closed row policy // if(channel->spec->is_accessing(cmd) && rowpolicy->type == RowPolicy<T>::Type::ClosedAP) { // // check if it is the last request to the opened row // Queue* queue = write_mode ? &writeq : &readq; // auto begin = addr_vec.begin(); // vector<int> rowgroup(begin, begin + int(T::Level::Row) + 1); // int num_row_hits = 0; // for (auto itr = queue->q.begin(); itr != queue->q.end(); ++itr) { // if (is_row_hit(itr)) { // auto begin2 = itr->addr_vec.begin(); // vector<int> rowgroup2(begin2, begin2 + int(T::Level::Row) + 1); // if(rowgroup == rowgroup2) // num_row_hits++; // } // } // if(num_row_hits == 0) { // Queue* queue = &actq; // for (auto itr = queue->q.begin(); itr != queue->q.end(); ++itr) { // if (is_row_hit(itr)) { // auto begin2 = itr->addr_vec.begin(); // vector<int> rowgroup2(begin2, begin2 + int(T::Level::Row) + 1); // if(rowgroup == rowgroup2) // num_row_hits++; // } // } // } // assert(num_row_hits > 0); // The current request should be a hit, // // so there should be at least one request // // that hits in the current open row // if(num_row_hits == 1) { // if(cmd == T::Command::RD) // cmd = T::Command::RDA; // else if (cmd == T::Command::WR) // cmd = T::Command::WRA; // else // assert(false && "Unimplemented command type."); // } // } // } // void issue_cmd(typename T::Command cmd, const vector<int>& addr_vec) // { // cmd_issue_autoprecharge(cmd, addr_vec); // assert(is_ready(cmd, addr_vec)); // channel->update(cmd, addr_vec.data(), clk); // if(cmd == T::Command::PRE){ // if(rowtable->get_hits(addr_vec, true) == 0){ // useless_activates++; // } // } // rowtable->update(cmd, addr_vec, clk); // if (record_cmd_trace){ // // select rank // auto& file = cmd_trace_files[addr_vec[1]]; // string& cmd_name = channel->spec->command_name[int(cmd)]; // file<<clk<<','<<cmd_name; // // TODO bad coding here // if (cmd_name == "PREA" || cmd_name == "REF") // file<<endl; // else{ // int bank_id = addr_vec[int(T::Level::Bank)]; // if (channel->spec->standard_name == "DDR4" || channel->spec->standard_name == "GDDR5") // bank_id += addr_vec[int(T::Level::Bank) - 1] * channel->spec->org_entry.count[int(T::Level::Bank)]; // file<<','<<bank_id<<endl; // } // } // if (print_cmd_trace){ // printf("%5s %10ld:", channel->spec->command_name[int(cmd)].c_str(), clk); // for (int lev = 0; lev < int(T::Level::MAX); lev++) // printf(" %5d", addr_vec[lev]); // printf("\n"); // } // } // vector<int> get_addr_vec(typename T::Command cmd, list<Request>::iterator req){ // return req->addr_vec; // } // }; // template <> // vector<int> Controller<SALP>::get_addr_vec( // SALP::Command cmd, list<Request>::iterator req); // template <> // bool Controller<SALP>::is_ready(list<Request>::iterator req); // template <> // void Controller<ALDRAM>::update_temp(ALDRAM::Temp current_temperature); // template <> // void Controller<TLDRAM>::tick(); // template <> // void Controller<TLDRAM>::cmd_issue_autoprecharge(typename TLDRAM::Command& cmd, // const vector<int>& addr_vec); // } /*namespace ramulator*/ // #endif /*__CONTROLLER_H*/
[ "u3533156@hku.hk" ]
u3533156@hku.hk
5bd1db63d4f90a837f17fc6ccd54dbaece65eeaa
fb78f3ba1e3092b76759148b057aecb84dc2cebd
/1436.旅行终点站.cpp
fdf369dfc431098774ab2703a05a79f13a0845d2
[]
no_license
zpeng1997/leetcode
5c1813486264d012620567771544d784870a634e
ddac58f299c8dff7e2ff307a69d6a1ddbcc5f1fb
refs/heads/master
2022-09-17T13:52:14.450935
2020-05-21T03:18:52
2020-05-21T03:18:52
263,941,812
0
0
null
null
null
null
UTF-8
C++
false
false
2,417
cpp
/* * @lc app=leetcode.cn id=1436 lang=cpp * * [1436] 旅行终点站 * * https://leetcode-cn.com/problems/destination-city/description/ * * algorithms * Easy (81.18%) * Likes: 2 * Dislikes: 0 * Total Accepted: 3.9K * Total Submissions: 4.7K * Testcase Example: '[["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]]' * * 给你一份旅游线路图,该线路图中的旅行线路用数组 paths 表示,其中 paths[i] = [cityAi, cityBi] 表示该线路将会从 * cityAi 直接前往 cityBi 。请你找出这次旅行的终点站,即没有任何可以通往其他城市的线路的城市。 * * 题目数据保证线路图会形成一条不存在循环的线路,因此只会有一个旅行终点站。 * * * * 示例 1: * * 输入:paths = [["London","New York"],["New York","Lima"],["Lima","Sao Paulo"]] * 输出:"Sao Paulo" * 解释:从 "London" 出发,最后抵达终点站 "Sao Paulo" 。本次旅行的路线是 "London" -> "New York" -> * "Lima" -> "Sao Paulo" 。 * * * 示例 2: * * 输入:paths = [["B","C"],["D","B"],["C","A"]] * 输出:"A" * 解释:所有可能的线路是: * "D" -> "B" -> "C" -> "A".  * "B" -> "C" -> "A".  * "C" -> "A".  * "A".  * 显然,旅行终点站是 "A" 。 * * * 示例 3: * * 输入:paths = [["A","Z"]] * 输出:"Z" * * * * * 提示: * * * 1 <= paths.length <= 100 * paths[i].length == 2 * 1 <= cityAi.length, cityBi.length <= 10 * cityAi != cityBi * 所有字符串均由大小写英文字母和空格字符组成。 * * */ // @lc code=start class Solution { public: string destCity(vector<vector<string>>& paths) { // 拓扑排序 map<string, int> hash; map<string, string> ha; for(auto path : paths){ hash[path[0]] = 0; if(hash.find(path[1]) != hash.end()){ hash[path[1]] += 1; } ha[path[0]] = path[1]; } string res; for(auto it = hash.begin(); it != hash.end(); it ++){ if(it->second == 0){ res = it->first; break; } } while(ha.find(res) != ha.end()){ res = ha.find(res)->second; } return res; } }; // @lc code=end
[ "zpeng1997@gmail.com" ]
zpeng1997@gmail.com
576b5178ed14f866923bfb59969e69808995f5d4
f400eba120d81a65699ebcef37ec5a494d85c18f
/curve_editor/Surface.cpp
4c2fb80a473a9fc284b37cb9a117e8d80dfe64ea
[]
no_license
x1jiang-Saki/MIT6.837_2004Fall
a81dab4adb2df6e60633f42c997b516c1369b448
a4443cf655f1c05603f8eeea38055c44f4a43bbb
refs/heads/master
2022-09-16T03:27:41.465222
2020-05-27T08:22:00
2020-05-27T08:22:00
264,628,054
1
0
null
null
null
null
UTF-8
C++
false
false
3,299
cpp
#include "Surface.h" #include <GL/gl.h> #include "_matrix.h" void SurfaceOfRevolution::Paint(ArgParser* args) { curve->Paint(args); } TriangleMesh* SurfaceOfRevolution::OutputTriangles(ArgParser* args) { return curve->OutputTriangles(args); } void SurfaceOfRevolution::OutputBSpline(FILE* file) { curve->OutputBSpline(file); } void SurfaceOfRevolution::moveControlPoint(int selectedPoint, float x, float y) { curve->moveControlPoint(selectedPoint, x, y); } void SurfaceOfRevolution::addControlPoint(int selectedPoint, float x, float y) { curve->addControlPoint(selectedPoint, x, y); } void SurfaceOfRevolution::deleteControlPoint(int selectedPoint) { curve->deleteControlPoint(selectedPoint); } void BezierPatch::Paint(ArgParser* args) { glLineWidth(5); glColor3f(0, 0, 1); glBegin(GL_LINE_STRIP); for (Vec3f& v : vertices) glVertex3f(v.x(), v.y(), v.z()); glEnd(); glLineWidth(3); glColor3f(0, 1, 0); glBegin(GL_POINTS); int patch_tessellation = args->patch_tessellation; float d = 1.0f / patch_tessellation; vector<Matrix> G(4); for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { G[i].Set(j, 0, vertices[i * 4 + j].x()); G[i].Set(j, 1, vertices[i * 4 + j].y()); G[i].Set(j, 2, vertices[i * 4 + j].z()); } } for (int i = 0; i <= patch_tessellation; ++i) { float t = i * d; float t2 = t * t; float t3 = t2 * t; Matrix G_new; for (int j = 0; j < 4; ++j) { Vec4f T(t3, t2, t, 1); Bezier_Matrix.Transform(T); G[j].Transform(T); G_new.Set(j, 0, T.x()); G_new.Set(j, 1, T.y()); G_new.Set(j, 2, T.z()); } for (int j = 0; j <= patch_tessellation; ++j) { float s = j * d; float s2 = s * s; float s3 = s2 * s; Vec4f S(s3, s2, s, 1); Bezier_Matrix.Transform(S); G_new.Transform(S); glVertex3f(S.x(), S.y(), S.z()); } } glEnd(); glPointSize(5); glColor3f(1, 0, 0); for (int i = 0; i < 16; i += 4) { glBegin(GL_POINTS); glVertex3f(vertices[i].x(), vertices[i].y(), vertices[i].z()); glVertex3f(vertices[i + 1].x(), vertices[i + 1].y(), vertices[i + 1].z()); glVertex3f(vertices[i + 2].x(), vertices[i + 2].y(), vertices[i + 2].z()); glVertex3f(vertices[i + 3].x(), vertices[i + 3].y(), vertices[i + 3].z()); glEnd(); } } TriangleMesh* BezierPatch::OutputTriangles(ArgParser* args) { int patch_tessellation = args->patch_tessellation; float d = 1.0f / patch_tessellation; TriangleNet* triangleNet = new TriangleNet(patch_tessellation, patch_tessellation); vector<Matrix> G(4); for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { G[i].Set(j, 0, vertices[i * 4 + j].x()); G[i].Set(j, 1, vertices[i * 4 + j].y()); G[i].Set(j, 2, vertices[i * 4 + j].z()); } } for (int i = 0; i <= patch_tessellation; ++i) { float t = i * d; float t2 = t * t; float t3 = t2 * t; Matrix G_new; for (int j = 0; j < 4; ++j) { Vec4f T(t3, t2, t, 1); Bezier_Matrix.Transform(T); G[j].Transform(T); G_new.Set(j, 0, T.x()); G_new.Set(j, 1, T.y()); G_new.Set(j, 2, T.z()); } for (int j = 0; j <= patch_tessellation; ++j) { float s = j * d; float s2 = s * s; float s3 = s2 * s; Vec4f S(s3, s2, s, 1); Bezier_Matrix.Transform(S); G_new.Transform(S); triangleNet->SetVertex(i, j, Vec3f(S.x(), S.y(), S.z())); } } return triangleNet; }
[ "bethouloski@gmail.com" ]
bethouloski@gmail.com
fd18d12dca001a87f3a2c4f6e8a915e21f7522ed
b3f1515c3ad3e1d5d1b5f5e2d8db5fb95d5370a2
/FMap_PNG_datasets/FMapRequestManager.cpp
59543a23bb377bd4772383a115793e47fd41f9a0
[]
no_license
HPDRC/FMap
e69b8b5c19a320528df3a2d5c9897dfc8054af4f
9a7a81516ff6cc23137a21d464ae27aecd7d291e
refs/heads/master
2020-04-12T00:05:09.665566
2018-12-17T20:54:04
2018-12-17T20:54:04
162,188,324
0
0
null
null
null
null
UTF-8
C++
false
false
19,075
cpp
#include "FMapRequestManager.h" #include "fmap.h" CFMapRequestManager::CFMapRequestManager(void) { isXML = false; isUTM = false; isKMLReq = false; isGMLReq = false; isAtlasReq = false; isKMLUTMReq = false; isGMLUTMReq = false; isAtlasUTMReq = false; isTransGIF = false; isGIF = false; isTransPNG = false; isPNG = false; isHighlight = false; isTxt = false; //isNorthernHemisphere = true; } CFMapRequestManager::~CFMapRequestManager(void) { } //CFMapRequestManager::CalReqRect() //{ // //} std::string CFMapRequestManager::InitFilledAreaReq(std::string strAreaReq, bool* pHasFilledArea) { ASSERT(strAreaReq != ""); Overlays reqOverlays(strAreaReq); std::string strOverlay = reqOverlays.getNextOverlay(); std::string strFillArea; std::string strBlankLayer = "blanklayer"; while(strOverlay != "") { int iDot = (int) (strOverlay.find('.')); if(iDot != std::string::npos) { std::string strAreaSuffix = strOverlay.substr(iDot+1); int nLASuffix = (int)(strAreaSuffix.size()); if( FILLEDAREAREQ_LENGTH == nLASuffix ) { strFillArea = strOverlay; int nFillAreaPos = (int)(strAreaReq.find(strFillArea)); int nFillAreaLen = (int)(strFillArea.size()); strAreaReq.replace(nFillAreaPos, nFillAreaLen, strBlankLayer); strAreaReq.insert(0,"+"); strAreaReq.insert(0,strFillArea); *pHasFilledArea = true; } } strOverlay = reqOverlays.getNextOverlay(); } return strAreaReq; } //std::string CFMapRequestManager::DoubleToString(double d) //{ // /*std::ostringstream ostr; // if (!(ostr << d)) // { // return "ERROR"; // } // return ostr.str();*/ // // char temp[30] = {0}; // sprintf_s(temp, "%f", d); // // return temp; // //} double CFMapRequestManager::GetLatLongExt(double d, double doffset, bool isBigger) { if(isBigger) { if( d >= 0 ) { d = d*(1 + doffset); } else { d = d*(1 - doffset); } } else { if( d >= 0 ) { d = d*(1 - doffset); } else { d = d*(1 + doffset); } } return d; } bool CFMapRequestManager::GetLatLongExtByPixel(double* dlong, double* dlat, int nlevel, bool isUpLeft, int nPixelOffset) { /*int nPX = 0, nPY = 0; this->transformer.LatLongToPixelXY( *dlat, *dlong, nlevel, &nPX, &nPY, 0, 0 ); if(isUpLeft) { nPX = nPX - nPixelOffset; nPY = nPY - nPixelOffset; if(nPX <= 0) { nPX = 0; } if(nPY <= 0) { nPY = 0; } } else { nPX = nPX + nPixelOffset; nPY = nPY + nPixelOffset; } this->transformer.PixelXYToLatLong(nPX, nPY, nlevel, dlat, dlong);*/ return true; } bool CFMapRequestManager::HasFilledAreaReq(std::string strAreaReq, bool hasFilledAreaReq) { ASSERT(strAreaReq != ""); Overlays reqOverlays(strAreaReq); std::string strOverlay = reqOverlays.getNextOverlay(); //std::string strFillArea; //std::string strBlankLayer = "blanklayer"; while(strOverlay != "") { int iDot = (int) (strOverlay.find('.')); if(iDot != std::string::npos) { std::string strAreaSuffix = strOverlay.substr(iDot+1); int nLASuffix = (int)(strAreaSuffix.size()); if( (FILLEDAREAREQ_LENGTH == nLASuffix) || (HIGHLIGHTCENTER_LENGTH == nLASuffix) || (AREA_COLOR_LENGTH == nLASuffix)) { //strFillArea = strOverlay; //int nFillAreaPos = (int)(strAreaReq.find(strFillArea)); //int nFillAreaLen = (int)(strFillArea.size()); //strAreaReq.replace(nFillAreaPos, nFillAreaLen, strBlankLayer); //strAreaReq.insert(0,"+"); //strAreaReq.insert(0,strFillArea); hasFilledAreaReq = true; } } strOverlay = reqOverlays.getNextOverlay(); } return hasFilledAreaReq; } bool CFMapRequestManager::HasXML(CString strTarImaType) { if( ("KML" == strTarImaType.MakeUpper()) || ("KML_GDC" == strTarImaType.MakeUpper()) || ("GML" == strTarImaType.MakeUpper()) || ("GML_GDC" == strTarImaType.MakeUpper()) || ("XML" == strTarImaType.MakeUpper()) || ("XML_GDC" == strTarImaType.MakeUpper()) || ("KML_UTM" == strTarImaType.MakeUpper()) || ("GML_UTM" == strTarImaType.MakeUpper()) || ("XML_UTM" == strTarImaType.MakeUpper()) || ("TXT" == strTarImaType.MakeUpper()) ) { isXML = true; } return isXML; } bool CFMapRequestManager::HasUTM(CString strTarImaType) { if( ("KML_UTM" == strTarImaType.MakeUpper()) || ("GML_UTM" == strTarImaType.MakeUpper()) || ("XML_UTM" == strTarImaType.MakeUpper()) ) { isUTM = true; } return isUTM; } bool CFMapRequestManager::HasKMLReq(CString strTarImaType) { if( ("KML" == strTarImaType.MakeUpper()) || ("KML_GDC" == strTarImaType.MakeUpper()) ) { isKMLReq = true; } return isKMLReq; } bool CFMapRequestManager::HasKMLUTMReq(CString strTarImaType) { if( "KML_UTM" == strTarImaType.MakeUpper() ) { isKMLUTMReq = true; } return isKMLUTMReq; } bool CFMapRequestManager::HasGMLReq(CString strTarImaType) { if( ("GML" == strTarImaType.MakeUpper()) || ("GML_GDC" == strTarImaType.MakeUpper()) ) { isGMLReq = true; } return isGMLReq; } bool CFMapRequestManager::HasGMLUTMReq(CString strTarImaType) { if( "GML_UTM" == strTarImaType.MakeUpper() ) { isGMLUTMReq = true; } return isGMLUTMReq; } bool CFMapRequestManager::HasAtlasReq(CString strTarImaType) { if( ("XML" == strTarImaType.MakeUpper()) || ("XML_GDC" == strTarImaType.MakeUpper()) ) { isAtlasReq = true; } return isAtlasReq; } bool CFMapRequestManager::HasAtlasUTMReq(CString strTarImaType) { if( "XML_UTM" == strTarImaType.MakeUpper() ) { isAtlasUTMReq = true; } return isAtlasUTMReq; } std::string CFMapRequestManager::RefactLayer( bool hasGIF, bool hasPNG, std::string strReq, bool *pHasTransCanvas, TransInfo *ptransInfo ) { //std::basic_string <char>::size_type all = strReq.find ( "all" ); //std::basic_string <char>::size_type ramb = strReq.find ( "ramb" ); std::string newall = ""; std::string newramb = ""; std::string newseas = ""; std::string newpoints = ""; std::string info; std::string newsamotrails = ""; std::string strBlankLayer = "blanklayer"; std::string strnewsamotrails = ""; Overlays overlays(strReq); std::string strOverlay = overlays.getNextOverlay(); while(strOverlay != "") { int iDot = (int) (strOverlay.find('.')); if(iDot != std::string::npos) { //here just for seas layer, need the transinfo info from request info = strOverlay.substr(iDot+1); strOverlay = strOverlay.substr(0, iDot); } if( "all" == strOverlay ) { //newall = "+gnis2+fire+schools+llfr+mulr+bwpoints+dos+incorpp+metrop+resr"; newall = "+gnis2+fire+schools"; strReq.append( newall.c_str() ); } if( "ramb" == strOverlay ) { newramb = "+comn+re1n+re2n+rinn+rldn+rntn+busn+cldn"; strReq.append( newramb.c_str() ); } /*if( "points2" == strOverlay ) { newpoints = "+points"; strReq.append( newpoints.c_str() ); }*/ if( ( "seas" == strOverlay ) && (!hasGIF) && (!hasPNG) ) { *pHasTransCanvas = false; //here just for seas layer, need the transinfo info from request ptransInfo->type = TransInfo::area; ptransInfo->values[0] = ptransInfo->char2int(info[0]); ptransInfo->values[1] = ptransInfo->char2int(info[1]); ptransInfo->values[2] = ptransInfo->char2int(info[2]); //always set as sea.000, then replace seas to sea, in order to discard seas newseas = "+newsea.000"; strReq.append( newseas.c_str() ); } if( "samotrails" == strOverlay ) { strnewsamotrails = strOverlay; int nsamotrailsPos = (int)(strReq.find(strnewsamotrails)); int nsamotrailsLen = (int)(strnewsamotrails.size()) + 3;//lenth(".ln") = 3 strnewsamotrails = strReq.substr(nsamotrailsPos, nsamotrailsLen); strReq.replace(nsamotrailsPos, nsamotrailsLen, strBlankLayer); newsamotrails = strnewsamotrails + "+"; strReq.insert(0, newsamotrails); } strOverlay = overlays.getNextOverlay(); } //std::string newall = ""; //std::string newramb = ""; //if( (all != std::string::npos)||(all1 != std::string::npos) ) //{ // //newall = "+gnis2+fire+schools+llfr+mulr+bwpoints+dos+incorpp+metrop+resr"; // newall = "+gnis2+fire+schools"; //} //strReq.append( newall.c_str() ); //if( (ramb != std::string::npos)||( ramb1 != std::string::npos) ) //{ // newramb = "+comn+re1n+re2n+rinn+rldn+rntn+busn+cldn"; //} //strReq.append( newramb.c_str() ); return strReq; } CString CFMapRequestManager::InitRequest(CString strReq) { strReq.Replace("%2C", ","); strReq.Replace("%2c", ","); strReq.Replace("%24", "$"); strReq.Replace("%20", " "); strReq.Replace("%40", "@"); strReq.Replace("%2f", "|"); strReq.Replace("/" , "|"); strReq.Replace("%7c", "|"); strReq.Replace("%7C", "|"); strReq.Replace("%3A", ":"); strReq.Replace("%3a", ":"); return strReq; } bool CFMapRequestManager::HasTransGIF( CString strTarImaType ) { if( "GIF" == strTarImaType.MakeUpper() ) { isTransGIF = true; } return isTransGIF; } bool CFMapRequestManager::hasGIFOutput( CString strTarImaType ) { if( ("GIF_OP" == strTarImaType.MakeUpper()) || ("GIF" == strTarImaType.MakeUpper()) ) { isGIF = true; } return isGIF; } bool CFMapRequestManager::HasTransPNG( CString strTarImaType ) { if( ("PNG" == strTarImaType.MakeUpper()) ) { isTransPNG = true; } return isTransPNG; } bool CFMapRequestManager::hasPNGOutput( CString strTarImaType ) { if( ("PNG_OP" == strTarImaType.MakeUpper()) || ("PNG" == strTarImaType.MakeUpper()) ) { isPNG = true; } return isPNG; } bool CFMapRequestManager::makeResVisible(std::string overlay, std::pair<double, double> range, Overlays& overlays, double res) { Rule reqRule( overlay, make_pair(range.first, range.second) ); CompositeRule comRule; comRule.add( reqRule ); comRule.apply( overlays, res ); return true; } bool CFMapRequestManager::HasHighlight( CString strHigh ) { if( "" != strHigh ) { isHighlight = true; } return isHighlight; } bool CFMapRequestManager::HasHighlightCenter( CString strHL ) { if( "CENTER" == strHL.MakeUpper() ) { return true; } return false; } bool CFMapRequestManager::HasTxt( CString strTxt ) { if( "TXT" == strTxt.MakeUpper() ) { isTxt = true; } return isTxt; } bool CFMapRequestManager::HasLatLongReq(std::string lat1, std::string long1, std::string lat2, std::string long2, std::string level) { /*if( ("" != lat1) || ("" != long1) || ("" != lat2) || ("" != long2) ) { return true; } else { return false; }*/ if( ("" != lat1) && ("" != long1) && ("" != lat2) && ("" != long2) && ("" != level)) { return true; } else { return false; } } bool CFMapRequestManager::HasLatLongReqinUTM(std::string lat1, std::string long1, std::string lat2, std::string long2, std::string prj, std::string reqwidth, std::string reqheight) { if( ("" != lat1) && ("" != long1) && ("" != lat2) && ("" != long2) && ("" != prj ) && ("" != reqwidth) && ("" != reqheight) ) { return true; } else { return false; } } std::string CFMapRequestManager::GetLatLongFiles(std::string str_filename) { if( "" == str_filename ) { return str_filename; } //string str_file = "e:\\degree\\latlong\\" + str_filename + ".qix"; //string str_file = DISK_LOCATION_LATLONG + str_filename + ".qix"; #ifdef TERRA_NODE string str_file = DISK_LOCATION_LATLONG + str_filename + ".qix"; #else string str_file = DISK_LOCATION_LATLONG_LOCAL + str_filename + ".qix"; #endif return str_file; } int CFMapRequestManager::GetLayerType(CString layer) { if( "" == layer) { return -1; } int idot = layer.Find('.'); if(-1 == idot) { return -1; } int nlength = layer.GetLength() - idot - 1; switch(nlength) { case AREA_COLOR_LENGTH: return ShapeUtility::polygon; case LINE_COLOR_LENGTH: return ShapeUtility::arc; case POINT_ICON_LENGTH: return ShapeUtility::point; default: return -1; } } CString CFMapRequestManager::GetTableName(CString name) { if( "" == name ) { return ""; } int idot = name.Find('.'); if(-1 == idot) { return name; } return name.Left(idot); } CString CFMapRequestManager::GetFieldName(CString str, CString tablename) { logObj.writeToLog(_INFO, (char*)str.GetString()); int icurPos = 0, ifield = 0; CString resToken, str_fieldname; str_fieldname = ""; resToken = str.Tokenize(";",icurPos); while (resToken != "") { ifield = resToken.Find(tablename); if( -1 != ifield ) { str_fieldname = resToken.Right( resToken.GetLength() - tablename.GetLength() - 1); return str_fieldname; } resToken = str.Tokenize(";",icurPos); } logObj.writeToLog(_INFO, (char*)str_fieldname.GetString()); if( "" == str_fieldname ) { str_fieldname = "labelname"; } return str_fieldname; } //bool CFMapRequestManager::GetPolygonColor(OverridedColor* color, CString str, CMapStringToPtr* color_table) bool CFMapRequestManager::GetPolygonColor(OverridedColor* color, CString str, CMapColorTable* color_table) { if( "" == str ) { color->line = ""; color->area = ""; color->label = ""; return false; } int idot = str.Find('.'); if(-1 == idot) { color->line = ""; color->area = ""; color->label = ""; return false; } str = str.Right(str.GetLength() - idot -1); /*if( AREA_COLOR_LENGTH != str.GetLength() ) { color->line = ""; color->area = ""; color->label = ""; return false; }*/ if( AREA_COLOR_LENGTH == str.GetLength() || (AREA_COLOR_LENGTH+1) == str.GetLength() ) { Gdiplus::Color pixel; CColorManager colormanager; color->line = str.Mid(3,8).GetString(); pixel = pixel.MakeARGB( (BYTE) strtol(color->line.substr(0,2).c_str(), NULL, 16), (BYTE) strtol(color->line.substr(2,2).c_str(), NULL, 16), (BYTE) strtol(color->line.substr(4,2).c_str(), NULL, 16), (BYTE) strtol(color->line.substr(6,2).c_str(), NULL, 16) ); color_table->SetAt(colormanager.GetPNGColorTableIndex(pixel), pixel); //save color only, ignore the alpha //color_table->SetAt(str.Mid(5,6).MakeUpper(), pixel); color->area = str.Mid(11,8).GetString(); pixel = pixel.MakeARGB( (BYTE) strtol(color->area.substr(0,2).c_str(), NULL, 16), (BYTE) strtol(color->area.substr(2,2).c_str(), NULL, 16), (BYTE) strtol(color->area.substr(4,2).c_str(), NULL, 16), (BYTE) strtol(color->area.substr(6,2).c_str(), NULL, 16) ); color_table->SetAt(colormanager.GetPNGColorTableIndex(pixel), pixel); //save color only, ignore the alpha //color_table->SetAt(str.Mid(13,6).MakeUpper(), pixel); color->label = str.Mid(19,8).GetString(); pixel = pixel.MakeARGB( (BYTE) strtol(color->label.substr(0,2).c_str(), NULL, 16), (BYTE) strtol(color->label.substr(2,2).c_str(), NULL, 16), (BYTE) strtol(color->label.substr(4,2).c_str(), NULL, 16), (BYTE) strtol(color->label.substr(6,2).c_str(), NULL, 16) ); color_table->SetAt(colormanager.GetPNGColorTableIndex(pixel), pixel); //save color only, ignore the alpha //color_table->SetAt(str.Mid(21,6).MakeUpper(), pixel); } else { color->line = ""; color->area = ""; color->label = ""; return false; } return true; } bool CFMapRequestManager::GetLineStringColor(OverridedColor* color, CString str, CMapColorTable* color_table) { if( "" == str ) { color->line = ""; color->area = ""; color->label = ""; return false; } int idot = str.Find('.'); if(-1 == idot) { color->line = ""; color->area = ""; color->label = ""; return false; } str = str.Right(str.GetLength() - idot -1); /*if( AREA_COLOR_LENGTH != str.GetLength() ) { color->line = ""; color->area = ""; color->label = ""; return false; }*/ if( LINE_COLOR_LENGTH == str.GetLength() ) { Gdiplus::Color pixel; CColorManager colormanager; color->line = str.Mid(2,8).GetString(); pixel = pixel.MakeARGB( (BYTE) strtol(color->line.substr(0,2).c_str(), NULL, 16), (BYTE) strtol(color->line.substr(2,2).c_str(), NULL, 16), (BYTE) strtol(color->line.substr(4,2).c_str(), NULL, 16), (BYTE) strtol(color->line.substr(6,2).c_str(), NULL, 16) ); color_table->SetAt(colormanager.GetPNGColorTableIndex(pixel), pixel); color->area = ""; color->label = ""; } else { color->line = ""; color->area = ""; color->label = ""; return false; } return true; } bool GetPolygonLabelSize(int* pnsize, CString str) { int idot = str.Find('.'); if(-1 == idot) { return false; } str = str.Right(str.GetLength() - idot -1); if( (AREA_COLOR_LENGTH+1) == str.GetLength() ) { *pnsize = atoi(str.Right(1).GetString()); } else { return false; } return true; } bool CFMapRequestManager::HasPointLable(CString str) { if( "" == str ) { return false; } int idot = str.Find('.'); if(-1 == idot) { return false; } if( ('l' == str.GetAt(idot+1)) || ('L' == str.GetAt(idot+1)) || ('f' == str.GetAt(idot+1)) || ('F' == str.GetAt(idot+1)) ) { return true; } else { return false; } } bool CFMapRequestManager::HasPointIcon(CString str) { if( "" == str ) { return false; } int idot = str.Find('.'); if(-1 == idot) { return false; } if( ('i' == str.GetAt(idot+1)) || ('I' == str.GetAt(idot+1)) || ('f' == str.GetAt(idot+1)) || ('F' == str.GetAt(idot+1))) { return true; } else { return false; } } bool CFMapRequestManager::HasLineStringLable(CString str) { if( "" == str ) { return false; } int idot = str.Find('.'); if(-1 == idot) { return false; } if( ('L' == str.GetAt(idot+1)) || ('l' == str.GetAt(idot+1)) ) { return true; } else { return false; } } bool CFMapRequestManager::HasLineStringShape(CString str) { if( "" == str ) { return false; } int idot = str.Find('.'); if(-1 == idot) { return false; } if( ('n' == str.GetAt(idot+2)) || ('N' == str.GetAt(idot+2)) ) { return true; } else { return false; } } bool CFMapRequestManager::HasPolygonFill(CString str) { if( "" == str ) { return false; } int idot = str.Find('.'); if(-1 == idot) { return false; } if( '0' == str.GetAt(idot+2) ) { return false; } else { return true; } } bool CFMapRequestManager::HasPolygonBoundary(CString str) { if( "" == str ) { return false; } int idot = str.Find('.'); if(-1 == idot) { return false; } if( '0' == str.GetAt(idot+1) ) { return false; } else { return true; } } bool CFMapRequestManager::HasPolygonLable(CString str) { if( "" == str ) { return false; } int idot = str.Find('.'); if(-1 == idot) { return false; } if( '0' == str.GetAt(idot+3) ) { return false; } else { return true; } } bool CFMapRequestManager::HasLODData(int ndatatype) { if( (ndatatype == ShapeUtility::polygon)|| (ndatatype == ShapeUtility::arc) ) { return true; } else if( ndatatype == ShapeUtility::point ) { return false; } else { //should be return log error return false; } } bool CFMapRequestManager::HasNorthernHemisphere(double lat1) { if( lat1 >= 0 ) { return true; } else { return false; } } bool CFMapRequestManager::HasNorthUTM(int utm) { if( utm >= 0 ) { return true; } else { return false; } }
[ "liadeng@cs.fiu.edu" ]
liadeng@cs.fiu.edu
3e32ac289d863f673609ac9d7313ec3e799ec092
73d12ee91ff28cf126259e5c0dc054672874a18c
/principal.cpp
c2cebaebb82fa35e31c0da18349898021730415f
[]
no_license
MayolZazueta/ejemplo1
e7124b9aa1af12e729db35707e40cb2da8a02624
defc8369b86f9ca170683a87146b1d2742e056ad
refs/heads/master
2021-01-19T16:21:21.224329
2017-08-22T05:58:30
2017-08-22T05:58:30
101,003,970
0
0
null
null
null
null
UTF-8
C++
false
false
531
cpp
#include <cstdlib> #include <iostream> #include <string> #include "lexico.h" using namespace std; int main(int argc, char *argv[]){ Lexico lexico; lexico.entrada("+-+"); cout << "Resultado del Analisis Lexico" << endl << endl; cout << "Simbolo\t\tTipo" << endl; while ( lexico.simbolo.compare("$") != 0 ){ lexico.sigSimbolo(); cout << lexico.simbolo << "\t\t" << lexico.tipoAcad(lexico.tipo) << endl; } cin.get(); return 0; }
[ "emayolzazueta@gmail.com" ]
emayolzazueta@gmail.com
97e4eb1a11671f5864cb4f1bbf35c0c14acbeb28
44d212e4b92b39a24b3fc9356c28bddd513f1f54
/UVa Online Judge/00555. Bridge Hands.cpp
1923600d498927667962395864899af58900723f
[ "MIT" ]
permissive
nicoelayda/competitive-programming
e946d4eeac5fadcae58d44dd3d9b6fb3d86983a4
5b5452d8d2865a1a5f1e3d2fece011749722e8c4
refs/heads/master
2020-04-23T09:42:46.697943
2019-02-18T16:29:27
2019-02-18T16:29:33
171,078,251
0
0
null
null
null
null
UTF-8
C++
false
false
1,216
cpp
#include <iostream> #include <algorithm> #include <vector> using namespace std; const string dealers = "SWNE"; const string suits = "CDSH"; const string values = "23456789TJQKA"; bool comparator(pair<char, char> card1, pair<char, char> card2) { if (suits.find(card1.first) == suits.find(card2.first)) return values.find(card1.second) < values.find(card2.second); return suits.find(card1.first) < suits.find(card2.first); } int main() { char dealer; while (cin >> dealer && dealer != '#') { vector< vector< pair<char, char> > > hands(4, vector< pair<char, char> >()); for (int i = 0, p = (dealers.find(dealer) + 1) % 4; i < 52; i++, p = (p + 1) % 4) { pair<char, char> card; cin >> card.first; cin >> card.second; hands[p].push_back(card); } for (int i = 0; i < 4; i++) { sort(hands[i].begin(), hands[i].end(), comparator); cout << dealers[i] << ":"; for (int c = 0; c < 13; c++) { cout << " " << hands[i][c].first << hands[i][c].second; } cout << endl; } } return 0; }
[ "nico@elayda.com" ]
nico@elayda.com
7397edf823ca89fa8f2b5b7918d41c12ae108f6b
a28d70e5a7c6949cf34d03b6267d7cfc1e72726e
/Laserharp/Laserharp.ino
293e7f0902661589fd96dfbb70a155f3fb19f7cc
[]
no_license
Esmay1/ipmedt5
eb885c5c02afd7bd4189323e4067a929eaa6083a
9d8e89ff042445951895b1af73e573206ea3c727
refs/heads/master
2021-01-21T02:27:33.167273
2015-08-19T09:23:34
2015-08-19T09:23:34
35,487,978
0
0
null
null
null
null
UTF-8
C++
false
false
2,878
ino
int noteON = 144;//144 = 10010000 in binair, dit is het 'note on' commando void setup() { // MIDI baud rate: Serial.begin(31250); // Gebruik het harpgeluid in plaats van het standaard pianogeluid. programChange(0xc0, 46); } // Deze loop wordt achter elkaar door afgespeeld. void loop() { // Deze loop zorgt ervoor dat de chip blijft checken of een snaar wordt gespeeld. while(1) { int velocity = 127; int note; // Dit if statement checkt de eerste snaar (de sensoren zijn aangesloten op A poorten). // if (PINA & (1<<PA0)) // { // // Als de poort een 0 is, dan speelt er een toon af. // // note = 48; // // MIDImessage(noteON, note, velocity); // do // { // delay(1); // } // while (PINA & (1<<PA0)); // // MIDImessage(noteON, note, 0); // // } // if (PINA & (1<<PA1)) { note = 50; MIDImessage(noteON, note, velocity); do { delay(1); } while (PINA & (1<<PA1)); MIDImessage(noteON, note, 0); } if (PINA & (1<<PA2)) { note = 52; MIDImessage(noteON, note, velocity); do { delay(1); } while (PINA & (1<<PA2)); MIDImessage(noteON, note, 0); } if (PINA & (1<<PA3)) { note = 53; MIDImessage(noteON, note, velocity); do { delay(1); } while (PINA & (1<<PA3)); MIDImessage(noteON, note, 0); } if (PINA & (1<<PA4)) { note = 55; MIDImessage(noteON, note, velocity); do { delay(1); } while (PINA & (1<<PA4)); MIDImessage(noteON, note, 0); } if (PINA & (1<<PA5)) { note = 57; MIDImessage(noteON, note, velocity); do { delay(1); } while (PINA & (1<<PA5)); MIDImessage(noteON, note, 0); } // // if (PINA & (1<<PA6)) // { // note = 59; // MIDImessage(noteON, note, velocity); // do // { // delay(1); // } // while (PINA & (1<<PA6)); // // MIDImessage(noteON, note, 0); // } // if (PINA & (1<<PA7)) { note = 60; MIDImessage(noteON, note, velocity); do { delay(1); } while (PINA & (1<<PA7)); MIDImessage(noteON, note, 0); } } } // Methode om het harpgeluid te gebruiken in plaats van het standaard pianogeluid. void programChange(char ProgramCommand, char Tone) { Serial.write(ProgramCommand); Serial.write(Tone); } // Methode om een bericht te sturen naar het MIDI device. void MIDImessage(int command, int MIDInote, int MIDIvelocity) { Serial.write(command);//send note on or note off command Serial.write(MIDInote);//send pitch data Serial.write(MIDIvelocity);//send velocity data }
[ "esmay.timmermans@hotmail.com" ]
esmay.timmermans@hotmail.com
037395e0e626e927380a9ecf12611c5d1e11c373
1b3aa93dea32e1b16b1fac45342f188dc69ecf63
/node/src/PortServerAcceptor.hpp
5f95a24225269d62f1f6b9f3ee2afb2cec0c8867
[]
no_license
edgarinformaticamodular/mtx-transactional-monitor
fcd567db4cd74d06ed10492e3058d370fe617c96
7a4e27421a97ca263cfa397e66677dbe7369e44c
refs/heads/master
2016-09-13T15:05:07.996572
2013-05-20T09:18:34
2013-05-20T09:18:34
56,486,856
0
0
null
null
null
null
UTF-8
C++
false
false
315
hpp
#ifndef ECC_PORT_SERVER_ACCEPTOR_HPP #define ECC_PORT_SERVER_ACCEPTOR_HPP #include "PortServer.hpp" using ecc::PortServer; /** * */ namespace ecc { class PortServerAcceptor : public virtual PortServer { public: PortServerAcceptor(string,string, int); void push(Message* a_message); };// }// #endif
[ "edgar@treeknowledge.com" ]
edgar@treeknowledge.com
563f501bcef6551b15a939050545dafb92e0c4ff
3b07d392f0d3077dacac4661b478e0cce4a49d7c
/ViewModel.h
fb37dc6d681f99eba89b8628b1e3ef826b3c436a
[ "BSD-3-Clause" ]
permissive
yacoxy/ViewModel
c2a8c05b004f18bc70bf1d67fd95f44385d8e7d1
4ad0a8cea28d4fd8c8e6a1bbfea4b23078c419e7
refs/heads/master
2021-06-14T05:49:36.920908
2021-05-20T08:39:03
2021-05-20T08:39:03
201,380,687
3
0
null
null
null
null
UTF-8
C++
false
false
1,614
h
#ifndef VIEWMODEL_H #define VIEWMODEL_H #include <QMainWindow> #include "SceneModelGloabl.h" namespace Ui { class ViewModel; } class BaseItem; class PointItem; class ShapeItem; class ImageItem; class HistogramItem; class SceneModel; class ViewModel : public QMainWindow { Q_OBJECT public: explicit ViewModel(QWidget *parent = 0); ~ViewModel(); public slots: /**************ImageItem slots*********************/ void loadImage(); void imageItemParamChanged(); void imagePosChanged(); void imageSpinChanged(QPointF spinCenter,double spinAngle); /***************ShapeItem slots********************/ void switchShapeItem(int type); void shapeDataChanged_FromWidget(QList<double> &data); void shapeDataChanged_FromItem(); /***************PointItem slots********************/ void addPoint(QPointF point = QPointF(100,100)); void delPoint(); void pointItemPosChanged(PointID id,QPointF pos); void posValueChangedFromWidget(int,int); void selectionChangedFromItem(); void selectionChangedFromWidget(); /***************ScenModel slots********************/ void mousePoschanged(QPointF mousePos,QRgb rgb,bool hasRgb); private: void imageItemUIOperation(bool enable); private: Ui::ViewModel *ui; SceneModel *m_sceneModel; //Scene ImageItem *m_bgImageItem; //Backgroud image item ImageItem *m_opImageItem; //Image item for operation ShapeItem *m_shapeItem; //ShapeItem QList<PointItem *> m_pointItemList; //PointItem list }; #endif // VIEWMODEL_H
[ "704662720@qq.com" ]
704662720@qq.com
d48eab864410c35db311b3df22c2838db0554f02
e57a6db62b9e80a3fbbe06830a9eb3658173ac87
/perceptron/main.cpp
b7fb6f1e7f7e45a4e9db08183a272c9b4e9b70d2
[]
no_license
Matus942/Perceptron
e33d0a62c358ac0c958f24ae79372c97fb82ad84
39cdcf6ee834f05655b23fcb77c2d6e1f2cfa2e1
refs/heads/main
2023-02-22T01:02:58.916513
2021-02-01T06:23:36
2021-02-01T06:23:36
334,851,683
0
0
null
null
null
null
UTF-8
C++
false
false
132
cpp
#include <iostream> #include "klasa.h" using namespace std; int main() { klasa l; l.sprawdz(); return 0; }
[ "noreply@github.com" ]
noreply@github.com
a7cf9379c2881a45d9874dddc0356b2866c7267e
32e75227c997c45a4274c880051001f6f8ffd948
/Beginner Set/1012.cpp
35c803a1689f2a85cacc4da91f7ff6b4590e3c70
[]
no_license
Xsardas665/URI_SOLUTIONS
098b83e818cd11a1493b1b3889160525d2e93a01
44295de57fb1c074066e9025c9431d23c3b46272
refs/heads/main
2023-01-06T14:52:14.066197
2020-11-06T10:02:19
2020-11-06T10:02:19
308,400,279
0
0
null
null
null
null
UTF-8
C++
false
false
337
cpp
#include <iostream> using namespace std; int main() { double a,b,c; scanf("%lf %lf %lf",&a,&b,&c); printf("TRIANGULO: %.3lf\n",(.5)*(a*c)); printf("CIRCULO: %.3lf\n",(3.14159)*(c*c)); printf("TRAPEZIO: %.3lf\n",(.5)*(a+b)*c); printf("QUADRADO: %.3lf\n",(b*b)); printf("RETANGULO: %.3lf\n",(a*b)); return 0; }
[ "Xsardas665@gmail.com" ]
Xsardas665@gmail.com
58770fb797e3ffcb50f6b9831fd2c11bd5e7b08d
fbc447467fe42185d926b71682731eb14e2ed8b6
/GUI/VideoPlayer/VideoWidget.cpp
2b11f0303018fafd0efd076534682e5cf8fe81ce
[]
no_license
yvatyan/Diploma
609c1927c74dda9890db6126e62bc0a5c6efbf50
bba2e9cb3ba2009fbad439c2a46400a5ef0cf50e
refs/heads/master
2021-01-21T06:27:08.233745
2017-06-29T16:45:48
2017-06-29T16:45:48
83,235,137
0
0
null
null
null
null
UTF-8
C++
false
false
6,373
cpp
#include "GUI/VideoPlayer/VideoWidget.h" #include <QVideoSurfaceFormat> #include <QPainter> #include <QDebug> #include "GUI/VideoPlayer/CoverWidget.h" ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////// VideoSurface /////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// VideoSurface::VideoSurface(QWidget* widget, QObject* parent) : QAbstractVideoSurface(parent) , videoWidget(widget) , imageFormat(QImage::Format_Invalid) { videoProcessor = Q_NULLPTR; coverWidget = Q_NULLPTR; } QList<QVideoFrame::PixelFormat> VideoSurface::supportedPixelFormats( QAbstractVideoBuffer::HandleType handleType) const { if (handleType == QAbstractVideoBuffer::NoHandle) { return QList<QVideoFrame::PixelFormat>() << QVideoFrame::Format_RGB32 << QVideoFrame::Format_ARGB32 << QVideoFrame::Format_ARGB32_Premultiplied << QVideoFrame::Format_RGB565 << QVideoFrame::Format_RGB555; } else { return QList<QVideoFrame::PixelFormat>(); } } bool VideoSurface::isFormatSupported( const QVideoSurfaceFormat& format, QVideoSurfaceFormat* similar) const { Q_UNUSED(similar); const QImage::Format imageFormat = QVideoFrame::imageFormatFromPixelFormat(format.pixelFormat()); const QSize size = format.frameSize(); return imageFormat != QImage::Format_Invalid && !size.isEmpty() && format.handleType() == QAbstractVideoBuffer::NoHandle; } void VideoSurface::SetVideoFrameProcessor(VideoFrameProcessor* vfProcessor) { videoProcessor = vfProcessor; } void VideoSurface::SetCoverWidget(QWidget* widget) { coverWidget = widget; } bool VideoSurface::start(const QVideoSurfaceFormat& format) { if (isFormatSupported(format, NULL)) { imageFormat = QVideoFrame::imageFormatFromPixelFormat(format.pixelFormat()); QAbstractVideoSurface::start(format); videoWidget->updateGeometry(); updateVideoRect(); clippedRectRegion = QRect(QPoint(0, 0), displayableRectRegion.size()); frameNumber = 0; return true; } else { return false; } } void VideoSurface::stop() { currentFrame = QVideoFrame(); displayableRectRegion = QRect(); clippedRectRegion = QRect(); QAbstractVideoSurface::stop(); videoWidget->update(); if(coverWidget) { static_cast<CoverWidget*>(coverWidget)->ResetRegions(); static_cast<CoverWidget*>(coverWidget)->ResetPoints(); } } bool VideoSurface::present(const QVideoFrame& frame) { frameNumber ++; if (surfaceFormat().pixelFormat() != frame.pixelFormat() || surfaceFormat().frameSize() != frame.size()) { setError(IncorrectFormatError); stop(); return false; } else { currentFrame = frame; if (currentFrame.map(QAbstractVideoBuffer::ReadOnly)) { currentFrame.unmap(); if(videoProcessor && videoProcessor->HasFreeTask()) { if(!coverWidget) { videoProcessor->Process( VideoFrameData( ImageData(new QVideoFrame(currentFrame)), NULL, frameNumber ) ); } else { videoProcessor->Process( VideoFrameData( ImageData(new QVideoFrame(currentFrame)), NULL, frameNumber, static_cast<CoverWidget*>(coverWidget)->GetAnnoRectRegions() ) ); } } videoWidget->repaint(displayableRectRegion); return true; } } } void VideoSurface::updateVideoRect() { QSize size = surfaceFormat().sizeHint(); size.scale(videoWidget->size().boundedTo(size), Qt::KeepAspectRatio); displayableRectRegion = QRect(QPoint(0, 0), size); displayableRectRegion.moveCenter(videoWidget->rect().center()); coverWidget->setGeometry(displayableRectRegion); coverWidget->update(); } void VideoSurface::paint(QPainter* painter) { bool showOriginFrame = true; if (videoProcessor && videoProcessor->HasCompleteTask()) { const VideoFrameData* data = videoProcessor->GetResultDataPointer(); if(data->ContainsTransformationResult()) { painter->drawImage(displayableRectRegion, data->GetImageData().GetQImage(), clippedRectRegion); showOriginFrame = false; } if(data->ContainsRegionResult()) { if(coverWidget) { static_cast<CoverWidget*>(coverWidget)->SetAnnoRectRegions(data->GetObjectRegions()); } } if(data->ContainsPointedResult()) { if(coverWidget) { static_cast<CoverWidget*>(coverWidget)->SetAnnoCrossPoints(data->GetObjectPoints()); } } } if(showOriginFrame) { if (currentFrame.map(QAbstractVideoBuffer::ReadOnly)) { QImage image( currentFrame.bits(), currentFrame.width(), currentFrame.height(), currentFrame.bytesPerLine(), imageFormat ); painter->drawImage(displayableRectRegion, image, clippedRectRegion); currentFrame.unmap(); } } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////// VideoWidget //////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// VideoWidget::VideoWidget(QWidget *parent) : QWidget(parent) , surface(0) { surface = new VideoSurface(this); } VideoWidget::~VideoWidget() { delete surface; } QSize VideoWidget::sizeHint() const { return surface->surfaceFormat().sizeHint(); } void VideoWidget::paintEvent(QPaintEvent* event) { Q_UNUSED(event); QPainter painter(this); surface->paint(&painter); } void VideoWidget::resizeEvent(QResizeEvent* event) { QWidget::resizeEvent(event); surface->updateVideoRect(); } QAbstractVideoSurface* VideoWidget::videoSurface() const { return surface; } void VideoWidget::SetVideoFrameProcessor(VideoFrameProcessor* vfProcessor) { surface->SetVideoFrameProcessor(vfProcessor); } void VideoWidget::SetCoverWidget(QWidget* widget) { surface->SetCoverWidget(widget); }
[ "Юрий Ватьян" ]
Юрий Ватьян
b5184f0c6a037b0c157b33ca6d4279ac99d5b18d
547c6e2dc56a05e1272400369af37cf4d50c617a
/Source/ARDemo3/AsteroidFactory.cpp
a2caf90f908e45cc4749ab68148936ee202ad740
[]
no_license
coltonomous/ARsteroids
7a23a25a5016bf5220e7d5a1071e41d7186bc687
df8624a8db3cd927aaae34221db0b1c774033f5b
refs/heads/master
2020-04-29T19:27:47.671195
2019-03-26T00:40:05
2019-03-26T00:40:05
175,607,386
0
0
null
null
null
null
UTF-8
C++
false
false
1,225
cpp
#include "AsteroidFactory.h" #include "Asteroid.h" // Sets default values AAsteroidFactory::AAsteroidFactory() { bodiesToSpawn = 250; minRadius = 2000.f; maxRadius = 15000.f; } // Called when the game starts or when spawned void AAsteroidFactory::BeginPlay() { Super::BeginPlay(); SpawnBodies(this->bodiesToSpawn); } // Spawns additional asteroids void AAsteroidFactory::SpawnBodies(int bodies) { for(int i = 0; i < bodies; i++){ SpawnSingleBody(); } } // Spawns a single asteroid at a random location within the spawn zone void AAsteroidFactory::SpawnSingleBody() { float degrees = FMath::RandRange(0.f, 359.f); float spawnZone = FMath::RandRange(this->minRadius, this->maxRadius); float sinDegrees = FMath::Sin(degrees); float cosDegrees = FMath::Cos(degrees); float xRange = cosDegrees * spawnZone; float yRange = sinDegrees * spawnZone; float zRange = FMath::RandRange(-20000.f, 20000.f); FVector spawnLocation = FVector(xRange, yRange, zRange); FRotator spawnRotation = FRotator(0.f, 0.f, 0.f); FActorSpawnParameters spawnInfo; GetWorld()->SpawnActor<AAsteroid>(spawnLocation, spawnRotation, spawnInfo); }
[ "noreply@github.com" ]
noreply@github.com
b04e2af477696665a83ae9628cea174b13f0c402
c97098b838ef5968431c716bd13f4f063412002e
/old.misc/vbmod/base64com/src/Base64.h
977e913897f11a182e7127f1a30ce5d70ae39609
[]
no_license
hackerlank/usnap
9cc6f2969639c529cd81a4f4662e81850dd80465
2ab43c81c85ddb3d3aa23a15905d965d14710c2b
refs/heads/master
2020-06-11T00:14:53.268772
2012-10-15T09:51:46
2012-10-15T09:51:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,102
h
// Base64.h : Declaration of the CBase64 #ifndef __BASE64_H_ #define __BASE64_H_ #include "resource.h" // main symbols ///////////////////////////////////////////////////////////////////////////// // CBase64 class ATL_NO_VTABLE CBase64 : public CComObjectRootEx<CComSingleThreadModel>, public CComCoClass<CBase64, &CLSID_Base64>, public IDispatchImpl<IBase64, &IID_IBase64, &LIBID_BinariesLib> { public: CBase64() { } DECLARE_REGISTRY_RESOURCEID(IDR_BASE64) DECLARE_PROTECT_FINAL_CONSTRUCT() BEGIN_COM_MAP(CBase64) COM_INTERFACE_ENTRY(IBase64) COM_INTERFACE_ENTRY(IDispatch) END_COM_MAP() // IBase64 public: STDMETHOD(DecodeFile)(/*[in]*/BSTR base64, /*[in]*/BSTR outputFileName); STDMETHOD(EncodeFile)(/*[in]*/BSTR fileName, /*[out, retval]*/BSTR *ret); STDMETHOD(DecodeData)(/*[in]*/BSTR base64, /*[out, retval]*/VARIANT *data); STDMETHOD(EncodeData)(/*[in]*/VARIANT *data, /*[out]*/BSTR *ret); STDMETHOD(DecodeString)(/*[in]*/BSTR base64, /*[out, retval]*/BSTR *ret); STDMETHOD(EncodeString)(/*[in]*/BSTR string, /*[out, retval]*/BSTR *ret); }; #endif //__BASE64_H_
[ "pub.lenik@bodz.net" ]
pub.lenik@bodz.net
8af0935edf0eba4cb4adc5c8b4881d565a0fd4eb
331426c3acb53224f923275fd16d1937dc28de4d
/GeeksForGeeks/BitMagic/14.MaximumSubsetXor.cpp
b20f77c25d64e6be86807f68c17965d235023550
[]
no_license
ag-richa-13/Competitive-Coding
63cc875b1afe2c5fde230e78880ebaaca1274707
2b2dcc75013a4f31f7ed5ae32bb02b7f58e43083
refs/heads/master
2023-04-05T12:54:16.340639
2021-03-28T09:15:20
2021-03-28T09:15:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,520
cpp
// Maximum Subset XOR // Question: // Given a set of positive integers. The task is to complete the function maxSubarrayXOR which returns an integer // denoting the maximum XOR subset value in the given set. // Input Format: // The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each test // case contains two lines. The first line of input contains an integer N denoting the size of the array A[]. Then // in the next line are N space separated values of the array. // Output Format: // For each test case in a new line output will be the maximum XOR subset value in the given set. // Your Task: // You need to complete the function maxSubarrayXOR. // Example: // Input: // 2 // 3 // 2 4 5 // 3 // 9 8 5 // Output: // 7 // 13 // Solution: // maxSubarrayXOR(A,n): return XOR(A,0,n,0) // XOR(A,a,n,i): // if(i == n) return a // else return max(XOR(s,a^s[i],n,i+1), XOR(s,a,n,i+1)) (i.e maximum of including ith element and not including it) #include <iostream> using namespace std; #define INT_BITS 32 int maxSubarrayXOR(int [], int n); int main() { int t; cin>>t; while(t--) { int n; cin>>n; int a[n]; for(int i=0;i<n;i++) cin>>a[i]; cout<<maxSubarrayXOR(a,n)<<endl; } } int XOR(int s[],int a,int n,int i){ if(i==n) return a; else return max(XOR(s,a^s[i],n,i+1), XOR(s,a,n,i+1)); } int maxSubarrayXOR(int A[], int n) { return XOR(A,0,n,0); }
[ "krishna.gavas@gmail.com" ]
krishna.gavas@gmail.com
6a805f0783c50841e426282e4b632ae7fca28ab2
368f3cb41bc3761ca28e351df702f7c72dafc6cc
/CrazyMarble3DCLion/GUI/LevelEditorMenu/LvlEditorMapButton.h
fc8b029742ca0bd4fa34af4cd59d768a4a4bfddf
[]
no_license
Dramelac/CrazyMarbles
580c45faa2b663fabbd5fd099918acb039bf9e18
aea6905050c62dab8dbfffa41fa3e59f994bfd2b
refs/heads/master
2021-01-19T05:18:32.641920
2017-10-01T12:33:44
2017-10-01T12:33:44
48,296,156
1
0
null
null
null
null
UTF-8
C++
false
false
577
h
// // Created by mathieu on 15/05/16. // #ifndef CRAZYMARBLE3D_LVLEDITORMAPBUTTON_H #define CRAZYMARBLE3D_LVLEDITORMAPBUTTON_H #include "../MapMenu/MapButton.h" using namespace video; class LvlEditorMapButton { private: IGUIButton* removeButton; MapButton* mapButton; public: LvlEditorMapButton(IGUIEnvironment* gui, IVideoDriver* driver, const path &map, u16 nPos); virtual ~LvlEditorMapButton(); bool checkRemove(); bool checkChange(); void setupPos(u16 nPos); void setMapName(path map); }; #endif //CRAZYMARBLE3D_LVLEDITORMAPBUTTON_H
[ "mathieu.calemard@hotmail.fr" ]
mathieu.calemard@hotmail.fr
d6a7bead65dada79f40b9e8216d3dbf0949cc515
46a7ff3fd79a56085593b69c0ab344c34ed12c08
/src/Launcher/Code/Turbo_DB/Turbo_DB.hpp
d0a8e6a5db4e49c9187d4794e488009be6f6972a
[ "MIT" ]
permissive
cs0x7f/aff3ct
ec6a2f486ef92f5308b0eae19aa8de3687bcbb59
0c23f39d39989fddb83e5c1e5dca9bc2d760f670
refs/heads/master
2020-03-31T17:08:33.977314
2018-10-10T11:21:40
2018-10-10T11:21:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
559
hpp
#ifndef LAUNCHER_TURBO_DB_HPP_ #define LAUNCHER_TURBO_DB_HPP_ #include "Factory/Module/Codec/Turbo_DB/Codec_turbo_DB.hpp" namespace aff3ct { namespace launcher { template <class L, typename B = int, typename R = float, typename Q = R> class Turbo_DB : public L { protected: factory::Codec_turbo_DB::parameters *params_cdc; public: Turbo_DB(const int argc, const char **argv, std::ostream &stream = std::cout); virtual ~Turbo_DB(); protected: virtual void get_description_args(); virtual void store_args(); }; } } #endif /* LAUNCHER_TURBO_DB_HPP_ */
[ "adrien.cassagne@inria.fr" ]
adrien.cassagne@inria.fr
00aeb4e2458ee3f34d12be4f7f7f29de4c0666bf
409ced85714ad6f46b0b13f1f5c23e0fe157bd37
/_wildcard_search_.h
8fd2645260b43a7c7382773652552a8b4044a3d2
[ "MIT" ]
permissive
bb33bb/cpp-utils
281325ea4c1bf88b5ced101a6d12a1ac35ed15af
f870929b72021e42890d5cd1cf6d0c8614e49995
refs/heads/master
2023-06-07T19:34:41.903870
2018-01-20T20:18:53
2018-01-20T20:18:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,572
h
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // _wildcard_search_.h - header file for a simple wildcard // string search class, with just two wildcards: * and ?. // * means 'match 0 or more of any characters', and ? means // 'match exactly one - any - character'. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #ifndef __wildcard_search_already_included_vasya__ #define __wildcard_search_already_included_vasya__ #include "_common_.h" namespace soige { class _wildcard_search_ { public: static bool wildcardPatternMatch( LPCTSTR pattern, long pat_len, LPCTSTR search_str, long str_len, bool case_sensitive ); _wildcard_search_(); _wildcard_search_(const _wildcard_search_& other); _wildcard_search_(LPCTSTR pattern, bool caseSensitive = true, bool matchWholeWord = false, bool matchEntireString = false); virtual ~_wildcard_search_(); virtual _wildcard_search_& operator=(const _wildcard_search_& other); void clear(); void initPattern(LPCTSTR pattern, bool caseSensitive = true, bool matchWholeWord = false, bool matchEntireString = false); bool match (LPCTSTR pString, long stringLen, long* pMatchStart = NULL, long* pMatchLength = NULL); private: LPTSTR _pattern; bool _caseSensitive; bool _wholeWord; // does the match have to be delimited by word boundaries? bool _entireString; // does entire string have to be matched by the pattern? }; }; // namespace soige #endif // __wildcard_search_already_included_vasya__
[ "noreply@github.com" ]
noreply@github.com
3354086c618f4bbeffbceaf30b7232afd9e9580e
f5262ca267eacc7cccd2b6a627ea014f27806a7b
/Classes/Scene/BasePopupBox.cpp
ca60a3c4d48f942b878deeda79cbf57f0f38a79c
[]
no_license
daxingyou/dzpkV3.2
deba8d2a7d8ef3c547e36b6bd2b54eab0fe3129a
275bff1762ff6becc03ef98ef6349450988c86e4
refs/heads/master
2022-02-03T13:05:09.507725
2015-06-15T06:01:32
2015-06-15T06:01:32
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
495
cpp
#include "BasePopupBox.h" bool BasePopupBox::init(){ if(!Layer::init()){ return false; } //ÆÁ±Î´¥Ãþ²ã auto listener = EventListenerTouchOneByOne::create(); listener->onTouchBegan = [](Touch* t, Event* e){ return true; }; listener->setSwallowTouches(true); Director::getInstance()->getEventDispatcher()->setPriority(listener, -128); Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this); return true; }
[ "1015406529@qq.com" ]
1015406529@qq.com
45f4a7f2dd739dbde172b9faeae93c49fbdd8dc5
fc4eeda20f26ae4112bfd12f6837fdb7339be183
/lib/sip_parse/src/sip_via.cpp
89c568be8c0334dc7a414bccb1d948d8899e8060
[]
no_license
swhors/simpson_sip_library
8b7a64220a46e10059b020ba5c51f54208d9659e
87d69dc0cdea49e6662e2c768697a6f58bc80f57
refs/heads/main
2023-03-14T00:05:12.604722
2021-03-01T07:47:17
2021-03-01T07:47:17
343,330,488
0
0
null
null
null
null
UTF-8
C++
false
false
6,001
cpp
#include <stdio.h> #ifdef LINUX #include <strings.h> #endif #include <iostream> #include <string> using namespace std; #include <stdlib.h> #include <string.h> #include <memory.h> #include <malloc.h> #include "host_addr.h" #include "skytool.h" #include "SIpFieldBase.h" #include "debug.h" #include "sip_tool.h" #include "sip_info.h" #include "sip_answer_code.h" #include "sip_method.h" #include "sip_uri.h" #include "sip_via.h" extern int err; int parse_via_intenal(PBYTE inStr,PVOID _pVia) { PSIPVIA pVia=(PSIPVIA)_pVia; if( pVia ) return (pVia->parse(inStr)?1:0); return 0; } VOID print_via(IN PVOID _pBuff,OUT PBYTE outBuf) { PSIPVIA pVia = (PSIPVIA)_pBuff; if( pVia <= NULL ) return; pVia->print(outBuf); } sip_via_t::sip_via_t() { ttl=-1; hidden=0; } sip_via_t::~sip_via_t() { this->free(); } int sip_via_t::build(SIPINF &inf,hostaddr_t &host,char *sBranch,char *sReceived,char *sMaddr) { this->sipInf = inf; this->host = host; if( sBranch ) this->branch = sBranch; if( sReceived ) this->received = sReceived; if( sMaddr ) this->maddr = sMaddr; return 1; } int sip_via_t::build(protocol_type_e protoType, BYTE highVer, BYTE lowVer, char *szAddress, int port, char *sBranch, char *sReceived, char *sMaddr) { SIPINF sipInf; hostaddr_t cmHost; sipInf.build(protoType,highVer,lowVer); cmHost.type = ip; cmHost.hostAddr = szAddress; cmHost.port = port; return build(sipInf,cmHost,sBranch,sReceived,sMaddr); } #include "peg_def.h" #include "peg_xsip.h" using namespace peg_templ; VOID sip_via_t::free() { //host.free(); if( branch.size() > 0 ) branch.erase(branch.begin(), branch.end()); if( received.size() > 0 ) received.erase(received.begin(), received.end()); if( maddr.size() > 0 ) maddr.erase(maddr.begin(), maddr.end()); ttl = -1; rport = -1; hidden = 0; } PBYTE sip_via_t::parse(IN PBYTE inStr) { C c; PBYTE tmp0,tmp1,start; typedef And<CHAR_H,CHAR_I,CHAR_D,CHAR_D, CHAR_E,CHAR_N > hidden; typedef Or<unreserved , Char< '.' > , Char<'+'> > branchStr; typedef And<CHAR_B,CHAR_R,CHAR_A,CHAR_N, CHAR_C,CHAR_H,Char<'='>, PlusRepeat< branchStr> > branch; typedef And<CHAR_R,CHAR_E,CHAR_C,CHAR_E, CHAR_I,CHAR_V,CHAR_E,CHAR_D, Char<'='>,hostaddr > received; typedef And<CHAR_R,CHAR_P,CHAR_O,CHAR_R,CHAR_T > p_rport; typedef And<CHAR_M,CHAR_A,CHAR_D,CHAR_D, CHAR_R,Char<'='>, hostaddr > maddr; typedef And<CHAR_T,CHAR_T,CHAR_L, Char<'='>,PlusRepeat<AllNum> > ttl; typedef FindRepeat<hidden > is_hidden; typedef FindRepeat<branch > is_branch; typedef FindRepeat<received > is_recv; typedef FindRepeat<ttl > is_ttl; typedef FindRepeat<maddr > is_maddr; typedef FindRepeat<hostaddr > is_sentby; typedef FindRepeat<p_rport > is_rport; tmp0 = inStr; while(*tmp0==' ')tmp0++; tmp1 = parse_sipinfo(tmp0, &sipInf); if( tmp1 ) tmp0 = tmp1; if( is_sentby::Matches(tmp0, &c,start)) { parse_siphost(start,&host); } tmp1 = tmp0; // hidden if( is_hidden::Matches(tmp1, &c, start)) { this->hidden = 1; } tmp1 = tmp0; // ttl if( is_ttl::Matches(tmp1, &c, start)) { this->ttl = atoi((char*)(start+4)); } tmp1 = tmp0; // maddr if( is_maddr::Matches(tmp1, &c, start )) { this->maddr.assign((char*)(start+6),(int)(tmp1-start-6)); //this->maddr.insert((char*)(start+6),(int)(tmp1-start-6)); //sprintf(this->maddr, "%s", //this->maddr.CopyStr((char*)(start+6),(int)(tmp1-start-6)); } tmp1 = tmp0; // received if( is_recv::Matches(tmp1, &c, start)) { this->received.assign((char*)(start+9),(int)(tmp1-start-9)); //this->received.CopyStr((char*)(start+9),(int)(tmp1-start-9)); } tmp1 = tmp0; if( is_rport::Matches(tmp1, &c, start )) { if( *tmp1 == ';' || *tmp1 == ' ' || *tmp1 == '\r' || *tmp1 == 'n') rport = 0; else rport = atoi((char*)tmp1); } tmp1 = tmp0; // branch if( is_branch::Matches(tmp1, &c,start)) { this->branch.assign((char*)(start+7),(int)(tmp1-start-7)); //this->branch.CopyStr((char*)(start+7),(int)(tmp1-start-7)); } return tmp1; } int sip_via_t::print(OUT PBYTE outStr) { if( outStr <= NULL ) { return 0; } else { char addr[256]; char info[64]; int bOkHost=0; memset(addr, 0, 256); memset(info, 0, 64); print_sipinfo(&sipInf,(PBYTE)&info); sprintf((char*)outStr, "Via: %s", info); if( host.type == ip ) { if( host.port > 0 ) sprintf_s(addr,256, " %s:%d",(host.hostAddr.empty()?"127.0.0.1":(char*)host.hostAddr.data()),host.port); else sprintf_s(addr,256, " %s",(host.hostAddr.empty()?"127.0.0.1":(char*)host.hostAddr.data())); strcat((char*)outStr,addr); bOkHost = 1; } // hidden if( hidden ) strcat((char*)outStr,";hidden"); // ttl if( ttl >= 0 ) strcatfm((char*)outStr,";ttl=%d",ttl); // maddr if( !maddr.empty() ) strcatfm((char*)outStr,";maddr=%s",maddr.data()); // received if( !received.empty()) strcatfm((char*)outStr,";received=%s",received.data()); if( rport == 0 ) strcatfm((char*)outStr,";rport"); else if( rport > 0 ) strcatfm((char*)outStr,";rport=",rport); //branch if( !branch.empty()) strcatfm((char*)outStr,";branch=%s",branch.data()); strcat((char*)outStr,"\r\n"); } return 1; } CSipFieldBase &sip_via_t::operator =(const CSipFieldBase &cFieldBase) { sip_via_t *pSipVia = (sip_via_t *)&cFieldBase; *this = *pSipVia; return *this; } sip_via_t &sip_via_t::operator =(const sip_via_t &v) { sipInf = v.sipInf; host = v.host; branch = v.branch; received = v.received; maddr = v.maddr; ttl = v.ttl; hidden = v.hidden; rport = v.rport; return *this; } ////////////
[ "swhors@gmail.com" ]
swhors@gmail.com
fde3b4930d640695b6ba18fb36b671f1b2dbf343
eaf81457a7663b9a4ef22afc483450ce9710ab3b
/dbc/dbcfile.h
683b0dd6004139b5f3d39307489fada45d1d6b13
[]
no_license
Herman-H/wow_db_editor
b8f9b4bf87b2dc4db2e5a5efbe4e959374540ea1
88dfcd75ee905cd1653d6383152c36d013adefa2
refs/heads/master
2021-01-17T14:09:00.709835
2016-07-24T01:03:04
2016-07-24T01:03:04
42,594,502
0
0
null
null
null
null
UTF-8
C++
false
false
10,602
h
#ifndef DBCFILE_H #define DBCFILE_H #include <string> #include <vector> #include <inttypes.h> #include <cstdint> #include <cstring> #include "dbctmp.h" enum class fieldtype { STRING, INT, UINT, FLOAT, LOCALE, INTPTR }; template <fieldtype F> struct fieldreturntype { typedef uint32_t type; }; template <> struct fieldreturntype<fieldtype::STRING> { typedef char * type; }; template <> struct fieldreturntype<fieldtype::LOCALE> { typedef char * type; }; template <> struct fieldreturntype<fieldtype::INT> { typedef int32_t type; }; template <> struct fieldreturntype<fieldtype::FLOAT> { typedef float type; }; template <> struct fieldreturntype<fieldtype::INTPTR> { typedef int* type; }; enum class recordid { creature_type, creature_family, map, areatable, faction, factiontemplate, modelinfo, modeldata, spell, spellitemenchant, emote, creaturespells, skillline, itemextendedcost, item, itemset, itemdisplay, itemclass, itemsubclass, itemsubclassmask, itemrandomproperties, itemrandomsuffix, gemproperties, title, language, totemcategory, lock, locktype }; template <recordid ID> struct get_dbc_filename_ { static const char * name(){ return ""; } }; template <> struct get_dbc_filename_<recordid::creature_type> { static const char * name(){ return "CreatureType.dbc"; } }; template <> struct get_dbc_filename_<recordid::map> { static const char * name(){ return "Map.dbc"; } }; template <> struct get_dbc_filename_<recordid::areatable> { static const char * name(){ return "AreaTable.dbc"; } }; template <> struct get_dbc_filename_<recordid::creature_family> { static const char * name(){ return "CreatureFamily.dbc"; } }; template <> struct get_dbc_filename_<recordid::faction> { static const char * name(){ return "Faction.dbc"; } }; template <> struct get_dbc_filename_<recordid::factiontemplate> { static const char * name(){ return "FactionTemplate.dbc"; } }; template <> struct get_dbc_filename_<recordid::modelinfo> { static const char * name(){ return "CreatureDisplayInfo.dbc"; } }; template <> struct get_dbc_filename_<recordid::modeldata> { static const char * name(){ return "CreatureModelData.dbc"; } }; template <> struct get_dbc_filename_<recordid::spell> { static const char * name(){ return "Spell.dbc"; } }; template <> struct get_dbc_filename_<recordid::emote> { static const char * name(){ return "Emotes.dbc"; } }; template <> struct get_dbc_filename_<recordid::creaturespells> { static const char * name(){ return "CreatureSpellData.dbc"; } }; template <> struct get_dbc_filename_<recordid::skillline> { static const char * name(){ return "SkillLine.dbc"; } }; template <> struct get_dbc_filename_<recordid::itemextendedcost> { static const char * name(){ return "ItemExtendedCost.dbc"; } }; template <> struct get_dbc_filename_<recordid::item> { static const char * name(){ return "Item.dbc"; } }; template <> struct get_dbc_filename_<recordid::itemset> { static const char * name(){ return "ItemSet.dbc"; } }; template <> struct get_dbc_filename_<recordid::itemdisplay> { static const char * name(){ return "ItemDisplayInfo.dbc"; } }; template <> struct get_dbc_filename_<recordid::itemclass> { static const char * name(){ return "ItemClass.dbc"; } }; template <> struct get_dbc_filename_<recordid::itemsubclass> { static const char * name(){ return "ItemSubClass.dbc"; } }; template <> struct get_dbc_filename_<recordid::itemsubclassmask> { static const char * name(){ return "ItemSubClassMask.dbc"; } }; template <> struct get_dbc_filename_<recordid::itemrandomproperties> { static const char * name(){ return "ItemRandomProperties.dbc"; } }; template <> struct get_dbc_filename_<recordid::itemrandomsuffix> { static const char * name(){ return "ItemRandomSuffix.dbc"; } }; template <> struct get_dbc_filename_<recordid::gemproperties> { static const char * name(){ return "GemProperties.dbc"; } }; template <> struct get_dbc_filename_<recordid::title> { static const char * name(){ return "CharTitles.dbc"; } }; template <> struct get_dbc_filename_<recordid::spellitemenchant> { static const char * name(){ return "SpellItemEnchantment.dbc"; } }; template <> struct get_dbc_filename_<recordid::language> { static const char * name(){ return "Languages.dbc"; } }; template <> struct get_dbc_filename_<recordid::totemcategory> { static const char * name(){ return "TotemCategory.dbc"; } }; template <> struct get_dbc_filename_<recordid::lock> { static const char * name(){ return "Lock.dbc"; } }; template <> struct get_dbc_filename_<recordid::locktype> { static const char * name(){ return "LockType.dbc"; } }; template <size_t BYTES, fieldtype T> struct dbcfield; template <typename FIELD> struct fieldsizepredicate; template <template <size_t,fieldtype> class F, size_t BYTES, fieldtype T> struct fieldsizepredicate<F<BYTES,T>> { enum { value = BYTES }; }; template <typename FIELD> struct getfieldtype; template <template <size_t,fieldtype> class F, size_t BYTES, fieldtype T> struct getfieldtype<F<BYTES,T>> { static const fieldtype type = T; }; template <typename FIELD> struct singlefield; template <size_t BYTES, fieldtype T> struct singlefield<dbcfield<BYTES,T>> { enum { size = BYTES }; uint32_t data[BYTES/4]; }; template <typename ... FIELDS> struct fieldstore : inherit_all<tuple_t<singlefield<FIELDS>...>> { }; template <recordid ID, typename ... FIELDS> struct dbcrecord { public: fieldstore<FIELDS...> record; private: typedef fieldstore<FIELDS...> recordtype; template <size_t I, typename ... FS> struct parse; template <size_t I> struct parse<I> { static void field(char * p, recordtype &r) { p=p;r=r; // lines should be optimised away, but removes warnings that parameters are not in use } }; template <size_t I, typename F, typename ... FS> struct parse<I, F, FS...> : parse<I+1, FS...> { static void field(char * p, recordtype &r) { memcpy(r.template get<I>()->data, p, r.template get<I>()->size); parse<I+1,FS...>::field(p + r.template get<I>()->size, r); } }; public: enum { record_size = accumulate<fieldsizepredicate,tuple_t<FIELDS...>>::value }; template <size_t S> struct field { static const fieldtype type = getfieldtype<typename return_Nth<S, tuple_t<FIELDS...>>::type>::type; enum { offset = accumulate<fieldsizepredicate, typename return_N_first<S,FIELDS...>::type>::value }; }; dbcrecord(char * p) { parse<0, FIELDS...>::field(p,record); p+=record_size; } }; template <typename P> struct indexIsntInRecord; template <recordid RID, typename ... FIELDS, size_t INDEX> struct indexIsntInRecord<pair_tv<dbcrecord<RID,FIELDS...>, INDEX>> { enum { value = (INDEX >= sizeof...(FIELDS)) }; }; template <typename PAIR> struct gettypeoffieldpredicate; template <recordid RID, typename ... FIELDS, size_t INDEX> struct gettypeoffieldpredicate<pair_tv<dbcrecord<RID,FIELDS...>, INDEX>> { typedef integral_type< static_cast<size_t>(getfieldtype<typename return_Nth<INDEX, tuple_t<FIELDS...>>::type>::type) > type; }; template <typename PAIR> struct getrecordidpredicate; template <recordid RID, typename ... FIELDS, size_t INDEX> struct getrecordidpredicate<pair_tv<dbcrecord<RID,FIELDS...>,INDEX>> { typedef integral_type<static_cast<size_t>(RID)> type; }; /* Each pair should consist of a dbcrecord and a field index * (1) Ensure that index is in range of its paired record * (2) Ensure that all indices of the records are of the same fieldtype * (3) Ensure that all records have unique IDs */ template <typename ... PAIRS> struct fields_match { /*(1)*/static_assert(accumulate<indexIsntInRecord, tuple_t<PAIRS...>>::value == 0, "Index is out of range!\n"); /*(2)*/static_assert(count_tuple< typename make_set< typename accumulate_types<gettypeoffieldpredicate, tuple_t<PAIRS...>>::type >::type >::value == 1, "Types of the provided fields do not match!\n"); /*(3)*/static_assert(count_tuple< typename make_set< typename accumulate_types<getrecordidpredicate, tuple_t<PAIRS...>>::type >::type >::value == sizeof...(PAIRS), "Provided records are not distinct!\n"); }; template <recordid RID, typename ... FIELDS, size_t INDEX> struct fields_match<pair_tv<dbcrecord<RID, FIELDS...>,INDEX>> { }; /* Any dbc entity has a label, of type recordfield */ template < typename L, /* and a database id, of type dbcfield, associated with it */ typename ID, /* all other entries should hold the dbc id which should all match */ typename ... MATCHING_PAIRS> struct dbcentity; template < recordid LRID, typename ... LFIELDS, size_t LINDEX, size_t LMATCH, recordid IDID, typename ... IDFIELDS, size_t IDINDEX, size_t IDMATCH, typename ... MATCHING_PAIRS> struct dbcentity< triple_tvv<dbcrecord<LRID,LFIELDS...>,LINDEX,LMATCH>, triple_tvv<dbcrecord<IDID,IDFIELDS...>,IDINDEX,IDMATCH>, MATCHING_PAIRS...> { static_assert(LINDEX < sizeof...(LFIELDS), "Label index out of range!\n"); static_assert(LMATCH < sizeof...(LFIELDS), "Label match index out of range!\n"); static_assert(IDINDEX < sizeof...(IDFIELDS), "Id index out of range!\n"); static_assert(IDMATCH < sizeof...(IDFIELDS), "Id match index out of range!\n"); static const recordid label_recordid = LRID; // The label's DBC-file static const recordid ref_recordid = IDID; // The reference's DBC-file static const size_t label_id = LMATCH; // The label's ID across all DBC-files static const size_t ref_id = IDMATCH; // The reference's ID across all DBC-files enum { label_index = LINDEX }; // The column of the DBC-file where the label-data is stored enum { ref_index = IDINDEX }; // The column of the DBC-file where the references-data is stored typedef fields_match<MATCHING_PAIRS...> matches; }; struct dbcheader { uint32_t wdbc; uint32_t record_count; uint32_t field_count; uint32_t record_size; uint32_t string_block_size; }; #endif // DBCFILE_H
[ "hermanh@student.chalmers.se" ]
hermanh@student.chalmers.se
45f5cd05e8d8f615bd141044013f437703f21db2
024179f67155e02af85fdb294a664d3115e191c0
/week1/1-3-2.cpp
085d1799622d72050ccfe0fa8a98dbe1615c7612
[]
no_license
Acretock/Yellow-Belt
c23340eaab7f9f4fd14b8ee49aeebcfc8a5cc673
414c1d8fd189a3e8f1a93ad9bb392d522db3d428
refs/heads/main
2023-05-11T03:19:03.629409
2021-05-27T13:21:18
2021-05-27T13:21:18
371,343,258
1
0
null
null
null
null
UTF-8
C++
false
false
505
cpp
#include <map> #include <string> #include <iostream> #include <exception> using namespace std; template <typename Key,typename Value> Value& GetRefStrict(map<Key, Value>&m, Key k) { if (m.count(k) == 0) { throw runtime_error{"No such key exist \n"}; } else { return m.at(k); } } int main() { map<int, string> m = { {0,"value"} }; try { string& item = GetRefStrict(m, 1); item = "new_value"; cout << m[0] << endl; } catch (exception& e) { cout<< e.what(); } }
[ "noreply@github.com" ]
noreply@github.com
db506b62fc556a5431ca28b6592c63f0af6572a7
0145e31eacc96ebb810bf66c1d9a17f317f1601b
/testing/module_test/test_threadmem/test.cpp
7239eb2f3ed19993ba3a03f5a2b3fe5d52746f2f
[]
no_license
huypn12/distributed_crackpass
1ab0571de9be220198e4fcd07cbf409d931a3562
fc540e40c26af2da58d0963d31679a521a66e074
refs/heads/master
2020-06-23T14:12:14.962711
2019-07-24T14:23:08
2019-07-24T14:23:08
198,645,789
0
0
null
2019-11-02T16:19:46
2019-07-24T13:54:52
C
UTF-8
C++
false
false
597
cpp
#include <iostream> #include <vector> class MyObject{ public: int x; MyObject* next; MyObject(){ x = 0; next = NULL;}; }; int main(int argc, char const* argv[]) { std::vector<MyObject*> mo; MyObject* mo1 = new MyObject(); mo.push_back(mo1); // this works for (auto it = mo.begin(); it != mo.end(); ++it){ std::cout << "element x " << (*it)->x << std::endl; } // adding this line is ok std::vector<MyObject *> MO(0); auto min = MO.begin(); // adding this line is not ok std::cout << (*min)->x << std::endl; return 0; }
[ "huy.phung1292@gmail.com" ]
huy.phung1292@gmail.com
0f3732099a8efb80a0d5708edf546869060bdb1c
3d2f73cd73ce032c82ac74127c34627b17f44349
/AboutCode Project/main.cpp
b384284db9bd1678902ed79655a273fb0412e0d6
[]
no_license
googleplexplex/AboutCode
b7e42dfb4d4fd26c5e9c610325f533c3abb5037b
58f4b686fbf7d316ef457bc651407449ef95e0e1
refs/heads/master
2022-11-19T09:17:45.476421
2020-07-06T19:31:31
2020-07-06T19:31:31
277,535,067
0
0
null
null
null
null
UTF-8
C++
false
false
3,596
cpp
#include <iostream> #include <string> #include <iostream> #include <fstream> #include <regex> using namespace std; void outputFile(string path) { string line; ifstream myfile(path); if (myfile.is_open()) { while (!myfile.eof()) { getline(myfile, line); cout << line << endl; } myfile.close(); } } string copyFileInHeap(string path) { string result; string line; ifstream myfile(path); if (myfile.is_open()) { while (!myfile.eof()) { getline(myfile, line); result += line; if (!myfile.eof()) result += '\n'; } myfile.close(); } return result; } string getStructsNames(string searchIn) { smatch m; regex structNamesRegex("struct[\n ]+([a-zA-Z][a-zA-Z0-9]*)"); string result; while (regex_search(searchIn, m, structNamesRegex)) { result += m[1].str() + ' '; searchIn = m.suffix().str(); } return result; } string getClassesNames(string searchIn) { smatch m; regex structNamesRegex("class[\n ]+([a-zA-Z][a-zA-Z0-9]*)"); string result; while (regex_search(searchIn, m, structNamesRegex)) { result += m[1].str() + ' '; searchIn = m.suffix().str(); } return result; } string getNamespaces(string searchIn) { smatch m; regex structNamesRegex("namespace[\n ]+([a-zA-Z][a-zA-Z0-9]*)[\n ]*\\{"); string result; while (regex_search(searchIn, m, structNamesRegex)) { result += m[1].str() + ' '; searchIn = m.suffix().str(); } return result; } string getStructContent(string searchIn, string structName) { smatch m; string regexStr("struct " + structName + "[\s\S]*?(\\{\n?([\s\S]*?)\\})\;"); regex structNamesRegex(regexStr); string result; while (regex_search(searchIn, m, structNamesRegex)) { result += m[1].str() + ' '; searchIn = m.suffix().str(); } return result; } string getClassContent(string searchIn, string className) { smatch m; regex structNamesRegex("class " + className + "[\s\S]*?\\{[ \n]*([\s\S]*?)\\};"); string result; while (regex_search(searchIn, m, structNamesRegex)) { result += m[1].str() + ' '; searchIn = m.suffix().str(); } return result; } string getNamespaceContent(string searchIn, string namespaceName) { smatch m; regex structNamesRegex("namespace " + namespaceName + "[\s\S]*?\\{[ \n]*([\s\S]*?)\\};"); string result; while (regex_search(searchIn, m, structNamesRegex)) { result += m[1].str() + ' '; searchIn = m.suffix().str(); } return result; } struct A { void a_method() { cout << "Called method from A struct!"; } }; class B { public: void b_method() { cout << "Called method from B class!"; } }; namespace C { void c_method() { cout << "Called method from C namespace!" << endl; } } int main(void) { string fileContent = copyFileInHeap(__FILE__); cout << "Detected structeres: " << getStructsNames(fileContent) << endl; cout << "Detected classes: " << getClassesNames(fileContent) << endl; cout << "Detected namespaces: " << getNamespaces(fileContent) << endl; cout << "Content of A struct: " << getStructContent(fileContent, "A") << endl; cout << "Content of B class: " << getClassContent(fileContent, "B") << endl; cout << "Content of C namespace: " << getNamespaceContent(fileContent, "C") << endl; return 0; }
[ "iambagger10@gmail.com" ]
iambagger10@gmail.com
5c915a9784898f9a5fe74fcb97439edf1150c5cb
3e3fd47e5955d98f9657dc52ced1ec6aa1571a03
/worker/deps/libwebrtc/libwebrtc/modules/bitrate_controller/loss_based_bandwidth_estimation.cc
b434510b994b4a7912c393099afe36b436a5b5a3
[ "ISC", "BSD-3-Clause" ]
permissive
versatica/mediasoup
f9de556f16d81694e6d776ec2ed9c7d6633c6fee
d6d5fcc9f98a42a5e2f38bd4faaafcbd77960df7
refs/heads/v3
2023-09-01T17:39:26.877961
2023-08-30T17:24:33
2023-08-30T17:24:33
27,918,697
5,654
1,141
ISC
2023-09-14T15:32:28
2014-12-12T12:00:36
C++
UTF-8
C++
false
false
9,380
cc
/* * 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 "modules/bitrate_controller/loss_based_bandwidth_estimation.h" #include "api/units/data_rate.h" #include "api/units/time_delta.h" #include "system_wrappers/source/field_trial.h" #include <algorithm> #include <string> #include <vector> namespace webrtc { namespace { const char kBweLossBasedControl[] = "WebRTC-Bwe-LossBasedControl"; // Increase slower when RTT is high. double GetIncreaseFactor(const LossBasedControlConfig& config, TimeDelta rtt) { // Clamp the RTT if (rtt < config.increase_low_rtt) { rtt = config.increase_low_rtt; } else if (rtt > config.increase_high_rtt) { rtt = config.increase_high_rtt; } auto rtt_range = config.increase_high_rtt.Get() - config.increase_low_rtt; if (rtt_range <= TimeDelta::Zero()) { // RTC_DCHECK(false); // Only on misconfiguration. return config.min_increase_factor; } auto rtt_offset = rtt - config.increase_low_rtt; auto relative_offset = std::max(0.0, std::min(rtt_offset / rtt_range, 1.0)); auto factor_range = config.max_increase_factor - config.min_increase_factor; return config.min_increase_factor + (1 - relative_offset) * factor_range; } double LossFromBitrate(DataRate bitrate, DataRate loss_bandwidth_balance, double exponent) { if (loss_bandwidth_balance >= bitrate) return 1.0; return pow(loss_bandwidth_balance / bitrate, exponent); } DataRate BitrateFromLoss(double loss, DataRate loss_bandwidth_balance, double exponent) { if (exponent <= 0) { // RTC_DCHECK(false); return DataRate::Infinity(); } if (loss < 1e-5) return DataRate::Infinity(); return loss_bandwidth_balance * pow(loss, -1.0 / exponent); } double ExponentialUpdate(TimeDelta window, TimeDelta interval) { // Use the convention that exponential window length (which is really // infinite) is the time it takes to dampen to 1/e. if (window <= TimeDelta::Zero()) { // RTC_DCHECK(false); return 1.0f; } return 1.0f - exp(interval / window * -1.0); } } // namespace LossBasedControlConfig::LossBasedControlConfig() : enabled(field_trial::IsEnabled(kBweLossBasedControl)), min_increase_factor("min_incr", 1.02), max_increase_factor("max_incr", 1.08), increase_low_rtt("incr_low_rtt", TimeDelta::ms(200)), increase_high_rtt("incr_high_rtt", TimeDelta::ms(800)), decrease_factor("decr", 0.99), loss_window("loss_win", TimeDelta::ms(800)), loss_max_window("loss_max_win", TimeDelta::ms(800)), acknowledged_rate_max_window("ackrate_max_win", TimeDelta::ms(800)), increase_offset("incr_offset", DataRate::bps(1000)), loss_bandwidth_balance_increase("balance_incr", DataRate::kbps(0.5)), loss_bandwidth_balance_decrease("balance_decr", DataRate::kbps(4)), loss_bandwidth_balance_exponent("exponent", 0.5), allow_resets("resets", false), decrease_interval("decr_intvl", TimeDelta::ms(300)), loss_report_timeout("timeout", TimeDelta::ms(6000)) { std::string trial_string = field_trial::FindFullName(kBweLossBasedControl); ParseFieldTrial( {&min_increase_factor, &max_increase_factor, &increase_low_rtt, &increase_high_rtt, &decrease_factor, &loss_window, &loss_max_window, &acknowledged_rate_max_window, &increase_offset, &loss_bandwidth_balance_increase, &loss_bandwidth_balance_decrease, &loss_bandwidth_balance_exponent, &allow_resets, &decrease_interval, &loss_report_timeout}, trial_string); } LossBasedControlConfig::LossBasedControlConfig(const LossBasedControlConfig&) = default; LossBasedControlConfig::~LossBasedControlConfig() = default; LossBasedBandwidthEstimation::LossBasedBandwidthEstimation() : config_(LossBasedControlConfig()), average_loss_(0), average_loss_max_(0), loss_based_bitrate_(DataRate::Zero()), acknowledged_bitrate_max_(DataRate::Zero()), acknowledged_bitrate_last_update_(Timestamp::MinusInfinity()), time_last_decrease_(Timestamp::MinusInfinity()), has_decreased_since_last_loss_report_(false), last_loss_packet_report_(Timestamp::MinusInfinity()), last_loss_ratio_(0) {} void LossBasedBandwidthEstimation::UpdateLossStatistics( const std::vector<PacketResult>& packet_results, Timestamp at_time) { if (packet_results.empty()) { // RTC_DCHECK(false); return; } int loss_count = 0; for (const auto& pkt : packet_results) { loss_count += pkt.receive_time.IsInfinite() ? 1 : 0; } last_loss_ratio_ = static_cast<double>(loss_count) / packet_results.size(); const TimeDelta time_passed = last_loss_packet_report_.IsFinite() ? at_time - last_loss_packet_report_ : TimeDelta::seconds(1); last_loss_packet_report_ = at_time; has_decreased_since_last_loss_report_ = false; average_loss_ += ExponentialUpdate(config_.loss_window, time_passed) * (last_loss_ratio_ - average_loss_); if (average_loss_ > average_loss_max_) { average_loss_max_ = average_loss_; } else { average_loss_max_ += ExponentialUpdate(config_.loss_max_window, time_passed) * (average_loss_ - average_loss_max_); } } void LossBasedBandwidthEstimation::UpdateAcknowledgedBitrate( DataRate acknowledged_bitrate, Timestamp at_time) { const TimeDelta time_passed = acknowledged_bitrate_last_update_.IsFinite() ? at_time - acknowledged_bitrate_last_update_ : TimeDelta::seconds(1); acknowledged_bitrate_last_update_ = at_time; if (acknowledged_bitrate > acknowledged_bitrate_max_) { acknowledged_bitrate_max_ = acknowledged_bitrate; } else { acknowledged_bitrate_max_ -= ExponentialUpdate(config_.acknowledged_rate_max_window, time_passed) * (acknowledged_bitrate_max_ - acknowledged_bitrate); } } void LossBasedBandwidthEstimation::Update(Timestamp at_time, DataRate min_bitrate, TimeDelta last_round_trip_time) { // Only increase if loss has been low for some time. const double loss_estimate_for_increase = average_loss_max_; // Avoid multiple decreases from averaging over one loss spike. const double loss_estimate_for_decrease = std::min(average_loss_, last_loss_ratio_); const bool allow_decrease = !has_decreased_since_last_loss_report_ && (at_time - time_last_decrease_ >= last_round_trip_time + config_.decrease_interval); if (loss_estimate_for_increase < loss_increase_threshold()) { // Increase bitrate by RTT-adaptive ratio. DataRate new_increased_bitrate = min_bitrate * GetIncreaseFactor(config_, last_round_trip_time) + config_.increase_offset; // The bitrate that would make the loss "just high enough". const DataRate new_increased_bitrate_cap = BitrateFromLoss( loss_estimate_for_increase, config_.loss_bandwidth_balance_increase, config_.loss_bandwidth_balance_exponent); new_increased_bitrate = std::min(new_increased_bitrate, new_increased_bitrate_cap); loss_based_bitrate_ = std::max(new_increased_bitrate, loss_based_bitrate_); } else if (loss_estimate_for_decrease > loss_decrease_threshold() && allow_decrease) { // The bitrate that would make the loss "just acceptable". const DataRate new_decreased_bitrate_floor = BitrateFromLoss( loss_estimate_for_decrease, config_.loss_bandwidth_balance_decrease, config_.loss_bandwidth_balance_exponent); DataRate new_decreased_bitrate = std::max(decreased_bitrate(), new_decreased_bitrate_floor); if (new_decreased_bitrate < loss_based_bitrate_) { time_last_decrease_ = at_time; has_decreased_since_last_loss_report_ = true; loss_based_bitrate_ = new_decreased_bitrate; } } } void LossBasedBandwidthEstimation::Reset(DataRate bitrate) { loss_based_bitrate_ = bitrate; average_loss_ = 0; average_loss_max_ = 0; } double LossBasedBandwidthEstimation::loss_increase_threshold() const { return LossFromBitrate(loss_based_bitrate_, config_.loss_bandwidth_balance_increase, config_.loss_bandwidth_balance_exponent); } double LossBasedBandwidthEstimation::loss_decrease_threshold() const { return LossFromBitrate(loss_based_bitrate_, config_.loss_bandwidth_balance_decrease, config_.loss_bandwidth_balance_exponent); } DataRate LossBasedBandwidthEstimation::decreased_bitrate() const { return config_.decrease_factor * acknowledged_bitrate_max_; } void LossBasedBandwidthEstimation::MaybeReset(DataRate bitrate) { if (config_.allow_resets) Reset(bitrate); } void LossBasedBandwidthEstimation::SetInitialBitrate(DataRate bitrate) { Reset(bitrate); } } // namespace webrtc
[ "jmillan@aliax.net" ]
jmillan@aliax.net
1cfe53f1c069789a15e08b217a22476a56f41f82
9a3fc0a5abe3bf504a63a643e6501a2f3452ba6d
/tju/594.cpp
2e3363a076837132f0eb695ded8529fc5d3fd56b
[]
no_license
rodolfo15625/algorithms
7034f856487c69553205198700211d7afb885d4c
9e198ff0c117512373ca2d9d706015009dac1d65
refs/heads/master
2021-01-18T08:30:19.777193
2014-10-20T13:15:09
2014-10-20T13:15:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,187
cpp
#include <vector> #include <list> #include <map> #include <set> #include <queue> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #include <cstring> #define all(v) (v).begin(),(v).end() #define rall(v) (v).rbegin(),(v).rend() #define sz size() #define fill(x,i) memset(x,i,sizeof(x)) #define cpresent(V,e) (find(all(V),(e))!=(V).end()) #define foreach(c,it) for(__typeof((c).begin()) it=(c).begin();it!=(c).end();it++) #define GI ({int _t; scanf("%d", &_t); _t;}) using namespace std; long long toi(string s){istringstream is(s);long long x;is>>x;return x;} string tos(long long t){stringstream st; st<<t;return st.str();} long converts(long a){ int res=0; for(int i=0;i<4;i++){ res<<=8; res += a&255; a>>=8; } return res; } int main(){ freopen("in.txt","r",stdin); freopen("out.txt","w",stdout); long in; while(scanf("%ld",&in)==1){ cout << in << " converts to " << converts(in) << endl; } return 0; }
[ "winftc@gmail.com" ]
winftc@gmail.com
07f671f1a658033bb6470500d532cbb37055b452
c0a6f68a03879dcd19d9fc7ab04af917f6044633
/src/qt/notificator.h
a48e61770116bff846f82bc23c7f8e4d4b6f5439
[ "MIT" ]
permissive
zzcasper/Joash-Coin-Sources
6738671b5777c4a1a868dc01ecfe736c5c3fbe83
f01c1dfe9659245d4ccebb4fa57177911f0e2aae
refs/heads/master
2020-04-27T02:38:01.151118
2019-03-06T18:44:38
2019-03-06T18:44:38
174,000,842
0
0
null
null
null
null
UTF-8
C++
false
false
2,880
h
// Copyright (c) 2011-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_QT_NOTIFICATOR_H #define BITCOIN_QT_NOTIFICATOR_H #if defined(HAVE_CONFIG_H) #include "config/joashcoin-config.h" #endif #include <QIcon> #include <QObject> QT_BEGIN_NAMESPACE class QSystemTrayIcon; #ifdef USE_DBUS class QDBusInterface; #endif QT_END_NAMESPACE /** Cross-platform desktop notification client. */ class Notificator: public QObject { Q_OBJECT public: /** Create a new notificator. @note Ownership of trayIcon is not transferred to this object. */ Notificator(const QString &programName, QSystemTrayIcon *trayIcon, QWidget *parent); ~Notificator(); // Message class enum Class { Information, /**< Informational message */ Warning, /**< Notify user of potential problem */ Critical /**< An error occurred */ }; public Q_SLOTS: /** Show notification message. @param[in] cls general message class @param[in] title title shown with message @param[in] text message content @param[in] icon optional icon to show with message @param[in] millisTimeout notification timeout in milliseconds (defaults to 10 seconds) @note Platform implementations are free to ignore any of the provided fields except for \a text. */ void notify(Class cls, const QString &title, const QString &text, const QIcon &icon = QIcon(), int millisTimeout = 10000); private: QWidget *parent; enum Mode { None, /**< Ignore informational notifications, and show a modal pop-up dialog for Critical notifications. */ Freedesktop, /**< Use DBus org.freedesktop.Notifications */ QSystemTray, /**< Use QSystemTray::showMessage */ Growl12, /**< Use the Growl 1.2 notification system (Mac only) */ Growl13, /**< Use the Growl 1.3 notification system (Mac only) */ UserNotificationCenter /**< Use the 10.8+ User Notification Center (Mac only) */ }; QString programName; Mode mode; QSystemTrayIcon *trayIcon; #ifdef USE_DBUS QDBusInterface *interface; void notifyDBus(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout); #endif void notifySystray(Class cls, const QString &title, const QString &text, const QIcon &icon, int millisTimeout); #ifdef Q_OS_MAC void notifyGrowl(Class cls, const QString &title, const QString &text, const QIcon &icon); void notifyMacUserNotificationCenter(Class cls, const QString &title, const QString &text, const QIcon &icon); #endif }; #endif // BITCOIN_QT_NOTIFICATOR_H
[ "ibo.casper@gmail.com" ]
ibo.casper@gmail.com
a05c34566ab7b932503aa7cae9bac22c0add8235
da4d8e4510012a849349fc9c943d43dbf55b18ff
/OPTRE_Modules/CfgFactionClasses.hpp
10436190f5332a1d5bdc9e41824d3fe74e123af8
[]
no_license
thedog88/OPTRE_DEV
fd02f59dded7958cf2b8f19c90ef818f695fa139
6ba99bbe1b76191abd0414cc017304435ceb2bde
refs/heads/master
2021-01-09T20:59:10.634187
2017-06-06T23:43:46
2017-06-06T23:43:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
561
hpp
class CfgFactionClasses { class OPTRE_Zeus { displayName = "OPTRE ZEUS"; priority = 8; side = 7; }; class OPTRE_HUD { displayName = "OPTRE HUD"; priority = 8; side = 7; }; class OPTRE_HEV { displayName = "OPTRE HEV"; priority = 8; side = 7; }; class OPTRE_Frigate { displayName = "OPTRE UNSC Frigate"; priority = 8; side = 7; }; class OPTRE_EditorSupport { displayName = "OPTRE Support Events"; priority = 8; side = 7; }; class OPTRE_ZeusReSup { displayName = "Resupply"; priority = 8; side = 7; }; };
[ "misterhipster052@gmail.com" ]
misterhipster052@gmail.com
ac2221f4d210aeaeb3ca66ee3c5b48b719eb6eb8
29e0d1a5601ce6ba68c79f8d28b536b44be1afd7
/datatest.cpp
8f33b6680c7ab2d5c477950be7a4746805790298
[ "BSL-1.0", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
J08nY/cryptopp
62eb705812ce86564d48f744e5259d31b13d1ac4
b208c8c1b460005639559ccc718cebe0d139a0ae
refs/heads/master
2022-01-25T04:59:56.527357
2017-12-05T12:16:34
2017-12-05T12:16:34
113,182,947
2
0
null
2017-12-05T13:03:33
2017-12-05T13:03:33
null
UTF-8
C++
false
false
28,791
cpp
// datatest.cpp - originally written and placed in the public domain by Wei Dai // CryptoPP::Test namespace added by JW in February 2017 #define CRYPTOPP_DEFAULT_NO_DLL #define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1 #include "cryptlib.h" #include "factory.h" #include "integer.h" #include "filters.h" #include "hex.h" #include "randpool.h" #include "files.h" #include "trunhash.h" #include "queue.h" #include "smartptr.h" #include "validate.h" #include "hkdf.h" #include "stdcpp.h" #include <iostream> #include <sstream> // Aggressive stack checking with VS2005 SP1 and above. #if (_MSC_FULL_VER >= 140050727) # pragma strict_gs_check (on) #endif #if CRYPTOPP_MSC_VERSION # pragma warning(disable: 4505 4355) #endif NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(Test) typedef std::map<std::string, std::string> TestData; static bool s_thorough = false; class TestFailure : public Exception { public: TestFailure() : Exception(OTHER_ERROR, "Validation test failed") {} }; static const TestData *s_currentTestData = NULLPTR; static void OutputTestData(const TestData &v) { for (TestData::const_iterator i = v.begin(); i != v.end(); ++i) { std::cerr << i->first << ": " << i->second << std::endl; } } static void SignalTestFailure() { OutputTestData(*s_currentTestData); throw TestFailure(); } static void SignalUnknownAlgorithmError(const std::string& algType) { OutputTestData(*s_currentTestData); throw Exception(Exception::OTHER_ERROR, "Unknown algorithm " + algType + " during validation test"); } static void SignalTestError() { OutputTestData(*s_currentTestData); throw Exception(Exception::OTHER_ERROR, "Unexpected error during validation test"); } bool DataExists(const TestData &data, const char *name) { TestData::const_iterator i = data.find(name); return (i != data.end()); } const std::string & GetRequiredDatum(const TestData &data, const char *name) { TestData::const_iterator i = data.find(name); if (i == data.end()) SignalTestError(); return i->second; } void RandomizedTransfer(BufferedTransformation &source, BufferedTransformation &target, bool finish, const std::string &channel=DEFAULT_CHANNEL) { while (source.MaxRetrievable() > (finish ? 0 : 4096)) { byte buf[4096+64]; size_t start = Test::GlobalRNG().GenerateWord32(0, 63); size_t len = Test::GlobalRNG().GenerateWord32(1, UnsignedMin(4096U, 3*source.MaxRetrievable()/2)); len = source.Get(buf+start, len); target.ChannelPut(channel, buf+start, len); } } void PutDecodedDatumInto(const TestData &data, const char *name, BufferedTransformation &target) { std::string s1 = GetRequiredDatum(data, name), s2; ByteQueue q; while (!s1.empty()) { while (s1[0] == ' ') { s1 = s1.substr(1); if (s1.empty()) goto end; // avoid invalid read if s1 is empty } int repeat = 1; if (s1[0] == 'r') { repeat = ::atoi(s1.c_str()+1); s1 = s1.substr(s1.find(' ')+1); } // Convert word32 or word64 to little endian order. Some algorithm test vectors are // presented in the format. We probably should have named them word32le and word64le. if (s1.length() >= 6 && (s1.substr(0,6) == "word32" || s1.substr(0,6) == "word64")) { std::istringstream iss(s1.substr(6)); if (s1.substr(0,6) == "word64") { word64 value; while (iss >> std::skipws >> std::hex >> value) { value = ConditionalByteReverse(LITTLE_ENDIAN_ORDER, value); q.Put((const byte *)&value, 8); } } else { word32 value; while (iss >> std::skipws >> std::hex >> value) { value = ConditionalByteReverse(LITTLE_ENDIAN_ORDER, value); q.Put((const byte *)&value, 4); } } goto end; } s2.clear(); if (s1[0] == '\"') { s2 = s1.substr(1, s1.find('\"', 1)-1); s1 = s1.substr(s2.length() + 2); } else if (s1.substr(0, 2) == "0x") { StringSource(s1.substr(2, s1.find(' ')), true, new HexDecoder(new StringSink(s2))); s1 = s1.substr(STDMIN(s1.find(' '), s1.length())); } else { StringSource(s1.substr(0, s1.find(' ')), true, new HexDecoder(new StringSink(s2))); s1 = s1.substr(STDMIN(s1.find(' '), s1.length())); } while (repeat--) { q.Put((const byte *)s2.data(), s2.size()); RandomizedTransfer(q, target, false); } } end: RandomizedTransfer(q, target, true); } std::string GetDecodedDatum(const TestData &data, const char *name) { std::string s; PutDecodedDatumInto(data, name, StringSink(s).Ref()); return s; } std::string GetOptionalDecodedDatum(const TestData &data, const char *name) { std::string s; if (DataExists(data, name)) PutDecodedDatumInto(data, name, StringSink(s).Ref()); return s; } class TestDataNameValuePairs : public NameValuePairs { public: TestDataNameValuePairs(const TestData &data) : m_data(data) {} virtual bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const { TestData::const_iterator i = m_data.find(name); if (i == m_data.end()) { if (std::string(name) == Name::DigestSize() && valueType == typeid(int)) { i = m_data.find("MAC"); if (i == m_data.end()) i = m_data.find("Digest"); if (i == m_data.end()) return false; m_temp.clear(); PutDecodedDatumInto(m_data, i->first.c_str(), StringSink(m_temp).Ref()); *reinterpret_cast<int *>(pValue) = (int)m_temp.size(); return true; } else return false; } const std::string &value = i->second; if (valueType == typeid(int)) *reinterpret_cast<int *>(pValue) = atoi(value.c_str()); else if (valueType == typeid(Integer)) *reinterpret_cast<Integer *>(pValue) = Integer((std::string(value) + "h").c_str()); else if (valueType == typeid(ConstByteArrayParameter)) { m_temp.clear(); PutDecodedDatumInto(m_data, name, StringSink(m_temp).Ref()); reinterpret_cast<ConstByteArrayParameter *>(pValue)->Assign((const byte *)m_temp.data(), m_temp.size(), false); } else throw ValueTypeMismatch(name, typeid(std::string), valueType); return true; } private: const TestData &m_data; mutable std::string m_temp; }; void TestKeyPairValidAndConsistent(CryptoMaterial &pub, const CryptoMaterial &priv) { // "!!" converts between bool <-> integral. if (!pub.Validate(Test::GlobalRNG(), 2U+!!s_thorough)) SignalTestFailure(); if (!priv.Validate(Test::GlobalRNG(), 2U+!!s_thorough)) SignalTestFailure(); ByteQueue bq1, bq2; pub.Save(bq1); pub.AssignFrom(priv); pub.Save(bq2); if (bq1 != bq2) SignalTestFailure(); } void TestSignatureScheme(TestData &v) { std::string name = GetRequiredDatum(v, "Name"); std::string test = GetRequiredDatum(v, "Test"); member_ptr<PK_Signer> signer(ObjectFactoryRegistry<PK_Signer>::Registry().CreateObject(name.c_str())); member_ptr<PK_Verifier> verifier(ObjectFactoryRegistry<PK_Verifier>::Registry().CreateObject(name.c_str())); TestDataNameValuePairs pairs(v); if (test == "GenerateKey") { signer->AccessPrivateKey().GenerateRandom(Test::GlobalRNG(), pairs); verifier->AccessPublicKey().AssignFrom(signer->AccessPrivateKey()); } else { std::string keyFormat = GetRequiredDatum(v, "KeyFormat"); if (keyFormat == "DER") verifier->AccessMaterial().Load(StringStore(GetDecodedDatum(v, "PublicKey")).Ref()); else if (keyFormat == "Component") verifier->AccessMaterial().AssignFrom(pairs); if (test == "Verify" || test == "NotVerify") { SignatureVerificationFilter verifierFilter(*verifier, NULLPTR, SignatureVerificationFilter::SIGNATURE_AT_BEGIN); PutDecodedDatumInto(v, "Signature", verifierFilter); PutDecodedDatumInto(v, "Message", verifierFilter); verifierFilter.MessageEnd(); if (verifierFilter.GetLastResult() == (test == "NotVerify")) SignalTestFailure(); return; } else if (test == "PublicKeyValid") { if (!verifier->GetMaterial().Validate(Test::GlobalRNG(), 3)) SignalTestFailure(); return; } if (keyFormat == "DER") signer->AccessMaterial().Load(StringStore(GetDecodedDatum(v, "PrivateKey")).Ref()); else if (keyFormat == "Component") signer->AccessMaterial().AssignFrom(pairs); } if (test == "GenerateKey" || test == "KeyPairValidAndConsistent") { TestKeyPairValidAndConsistent(verifier->AccessMaterial(), signer->GetMaterial()); SignatureVerificationFilter verifierFilter(*verifier, NULLPTR, SignatureVerificationFilter::THROW_EXCEPTION); verifierFilter.Put((const byte *)"abc", 3); StringSource ss("abc", true, new SignerFilter(Test::GlobalRNG(), *signer, new Redirector(verifierFilter))); } else if (test == "Sign") { SignerFilter f(Test::GlobalRNG(), *signer, new HexEncoder(new FileSink(std::cout))); StringSource ss(GetDecodedDatum(v, "Message"), true, new Redirector(f)); SignalTestFailure(); } else if (test == "DeterministicSign") { // This test is specialized for RFC 6979. The RFC is a drop-in replacement // for DSA and ECDSA, and access to the seed or secret is not needed. If // additional determinsitic signatures are added, then the test harness will // likely need to be extended. std::string signature; SignerFilter f(Test::GlobalRNG(), *signer, new StringSink(signature)); StringSource ss(GetDecodedDatum(v, "Message"), true, new Redirector(f)); if (GetDecodedDatum(v, "Signature") != signature) SignalTestFailure(); return; } else if (test == "RandomSign") { SignalTestError(); CRYPTOPP_ASSERT(false); // TODO: implement } else { SignalTestError(); CRYPTOPP_ASSERT(false); } } void TestAsymmetricCipher(TestData &v) { std::string name = GetRequiredDatum(v, "Name"); std::string test = GetRequiredDatum(v, "Test"); member_ptr<PK_Encryptor> encryptor(ObjectFactoryRegistry<PK_Encryptor>::Registry().CreateObject(name.c_str())); member_ptr<PK_Decryptor> decryptor(ObjectFactoryRegistry<PK_Decryptor>::Registry().CreateObject(name.c_str())); std::string keyFormat = GetRequiredDatum(v, "KeyFormat"); if (keyFormat == "DER") { decryptor->AccessMaterial().Load(StringStore(GetDecodedDatum(v, "PrivateKey")).Ref()); encryptor->AccessMaterial().Load(StringStore(GetDecodedDatum(v, "PublicKey")).Ref()); } else if (keyFormat == "Component") { TestDataNameValuePairs pairs(v); decryptor->AccessMaterial().AssignFrom(pairs); encryptor->AccessMaterial().AssignFrom(pairs); } if (test == "DecryptMatch") { std::string decrypted, expected = GetDecodedDatum(v, "Plaintext"); StringSource ss(GetDecodedDatum(v, "Ciphertext"), true, new PK_DecryptorFilter(Test::GlobalRNG(), *decryptor, new StringSink(decrypted))); if (decrypted != expected) SignalTestFailure(); } else if (test == "KeyPairValidAndConsistent") { TestKeyPairValidAndConsistent(encryptor->AccessMaterial(), decryptor->GetMaterial()); } else { SignalTestError(); CRYPTOPP_ASSERT(false); } } void TestSymmetricCipher(TestData &v, const NameValuePairs &overrideParameters) { std::string name = GetRequiredDatum(v, "Name"); std::string test = GetRequiredDatum(v, "Test"); std::string key = GetDecodedDatum(v, "Key"); std::string plaintext = GetDecodedDatum(v, "Plaintext"); TestDataNameValuePairs testDataPairs(v); CombinedNameValuePairs pairs(overrideParameters, testDataPairs); if (test == "Encrypt" || test == "EncryptXorDigest" || test == "Resync" || test == "EncryptionMCT" || test == "DecryptionMCT") { static member_ptr<SymmetricCipher> encryptor, decryptor; static std::string lastName; if (name != lastName) { encryptor.reset(ObjectFactoryRegistry<SymmetricCipher, ENCRYPTION>::Registry().CreateObject(name.c_str())); decryptor.reset(ObjectFactoryRegistry<SymmetricCipher, DECRYPTION>::Registry().CreateObject(name.c_str())); lastName = name; } // Most block ciphers don't specify BlockSize. Kalyna and Threefish use it. int blockSize = pairs.GetIntValueWithDefault(Name::BlockSize(), 0); // Most block ciphers don't specify BlockPaddingScheme. Kalyna uses it in test vectors. // 0 is NoPadding, 1 is ZerosPadding, 2 is PkcsPadding, 3 is OneAndZerosPadding, etc // Note: The machinery is wired such that paddingScheme is effectively latched. An // old paddingScheme may be unintentionally used in a subsequent test. int paddingScheme = pairs.GetIntValueWithDefault(Name::BlockPaddingScheme(), 0); ConstByteArrayParameter iv; if (pairs.GetValue(Name::IV(), iv) && iv.size() != encryptor->IVSize() && (int)iv.size() != blockSize) SignalTestFailure(); if (test == "Resync") { encryptor->Resynchronize(iv.begin(), (int)iv.size()); decryptor->Resynchronize(iv.begin(), (int)iv.size()); } else { encryptor->SetKey((const byte *)key.data(), key.size(), pairs); decryptor->SetKey((const byte *)key.data(), key.size(), pairs); } int seek = pairs.GetIntValueWithDefault("Seek", 0); if (seek) { encryptor->Seek(seek); decryptor->Seek(seek); } // If a per-test vector parameter was set for a test, like BlockPadding, BlockSize or Tweak, // then it becomes latched in testDataPairs. The old value is used in subsequent tests, and // it could cause a self test failure in the next test. The behavior surfaced under Kalyna // and Threefish. The Kalyna test vectors use NO_PADDING for all tests excpet one. For // Threefish, using (and not using) a Tweak caused problems as we marched through test // vectors. For BlockPadding, BlockSize or Tweak, unlatch them now, after the key has been // set and NameValuePairs have been processed. Also note we only unlatch from testDataPairs. // If overrideParameters are specified, the caller is responsible for managing the parameter. v.erase("Tweak"); v.erase("BlockSize"); v.erase("BlockPaddingScheme"); std::string encrypted, xorDigest, ciphertext, ciphertextXorDigest; if (test == "EncryptionMCT" || test == "DecryptionMCT") { SymmetricCipher *cipher = encryptor.get(); SecByteBlock buf((byte *)plaintext.data(), plaintext.size()), keybuf((byte *)key.data(), key.size()); if (test == "DecryptionMCT") { cipher = decryptor.get(); ciphertext = GetDecodedDatum(v, "Ciphertext"); buf.Assign((byte *)ciphertext.data(), ciphertext.size()); } for (int i=0; i<400; i++) { encrypted.reserve(10000 * plaintext.size()); for (int j=0; j<10000; j++) { cipher->ProcessString(buf.begin(), buf.size()); encrypted.append((char *)buf.begin(), buf.size()); } encrypted.erase(0, encrypted.size() - keybuf.size()); xorbuf(keybuf.begin(), (const byte *)encrypted.data(), keybuf.size()); cipher->SetKey(keybuf, keybuf.size()); } encrypted.assign((char *)buf.begin(), buf.size()); ciphertext = GetDecodedDatum(v, test == "EncryptionMCT" ? "Ciphertext" : "Plaintext"); if (encrypted != ciphertext) { std::cout << "\nincorrectly encrypted: "; StringSource xx(encrypted, false, new HexEncoder(new FileSink(std::cout))); xx.Pump(256); xx.Flush(false); std::cout << "\n"; SignalTestFailure(); } return; } StreamTransformationFilter encFilter(*encryptor, new StringSink(encrypted), static_cast<BlockPaddingSchemeDef::BlockPaddingScheme>(paddingScheme)); RandomizedTransfer(StringStore(plaintext).Ref(), encFilter, true); encFilter.MessageEnd(); if (test != "EncryptXorDigest") ciphertext = GetDecodedDatum(v, "Ciphertext"); else { ciphertextXorDigest = GetDecodedDatum(v, "CiphertextXorDigest"); xorDigest.append(encrypted, 0, 64); for (size_t i=64; i<encrypted.size(); i++) xorDigest[i%64] ^= encrypted[i]; } if (test != "EncryptXorDigest" ? encrypted != ciphertext : xorDigest != ciphertextXorDigest) { std::cout << "\nincorrectly encrypted: "; StringSource xx(encrypted, false, new HexEncoder(new FileSink(std::cout))); xx.Pump(2048); xx.Flush(false); std::cout << "\n"; SignalTestFailure(); } std::string decrypted; StreamTransformationFilter decFilter(*decryptor, new StringSink(decrypted), static_cast<BlockPaddingSchemeDef::BlockPaddingScheme>(paddingScheme)); RandomizedTransfer(StringStore(encrypted).Ref(), decFilter, true); decFilter.MessageEnd(); if (decrypted != plaintext) { std::cout << "\nincorrectly decrypted: "; StringSource xx(decrypted, false, new HexEncoder(new FileSink(std::cout))); xx.Pump(256); xx.Flush(false); std::cout << "\n"; SignalTestFailure(); } } else { std::cout << "\nunexpected test name\n"; SignalTestError(); } } void TestAuthenticatedSymmetricCipher(TestData &v, const NameValuePairs &overrideParameters) { std::string type = GetRequiredDatum(v, "AlgorithmType"); std::string name = GetRequiredDatum(v, "Name"); std::string test = GetRequiredDatum(v, "Test"); std::string key = GetDecodedDatum(v, "Key"); std::string plaintext = GetOptionalDecodedDatum(v, "Plaintext"); std::string ciphertext = GetOptionalDecodedDatum(v, "Ciphertext"); std::string header = GetOptionalDecodedDatum(v, "Header"); std::string footer = GetOptionalDecodedDatum(v, "Footer"); std::string mac = GetOptionalDecodedDatum(v, "MAC"); TestDataNameValuePairs testDataPairs(v); CombinedNameValuePairs pairs(overrideParameters, testDataPairs); if (test == "Encrypt" || test == "EncryptXorDigest" || test == "NotVerify") { member_ptr<AuthenticatedSymmetricCipher> asc1, asc2; asc1.reset(ObjectFactoryRegistry<AuthenticatedSymmetricCipher, ENCRYPTION>::Registry().CreateObject(name.c_str())); asc2.reset(ObjectFactoryRegistry<AuthenticatedSymmetricCipher, DECRYPTION>::Registry().CreateObject(name.c_str())); asc1->SetKey((const byte *)key.data(), key.size(), pairs); asc2->SetKey((const byte *)key.data(), key.size(), pairs); std::string encrypted, decrypted; AuthenticatedEncryptionFilter ef(*asc1, new StringSink(encrypted)); bool macAtBegin = !mac.empty() && !Test::GlobalRNG().GenerateBit(); // test both ways randomly AuthenticatedDecryptionFilter df(*asc2, new StringSink(decrypted), macAtBegin ? AuthenticatedDecryptionFilter::MAC_AT_BEGIN : 0); if (asc1->NeedsPrespecifiedDataLengths()) { asc1->SpecifyDataLengths(header.size(), plaintext.size(), footer.size()); asc2->SpecifyDataLengths(header.size(), plaintext.size(), footer.size()); } StringStore sh(header), sp(plaintext), sc(ciphertext), sf(footer), sm(mac); if (macAtBegin) RandomizedTransfer(sm, df, true); sh.CopyTo(df, LWORD_MAX, AAD_CHANNEL); RandomizedTransfer(sc, df, true); sf.CopyTo(df, LWORD_MAX, AAD_CHANNEL); if (!macAtBegin) RandomizedTransfer(sm, df, true); df.MessageEnd(); RandomizedTransfer(sh, ef, true, AAD_CHANNEL); RandomizedTransfer(sp, ef, true); RandomizedTransfer(sf, ef, true, AAD_CHANNEL); ef.MessageEnd(); if (test == "Encrypt" && encrypted != ciphertext+mac) { std::cout << "\nincorrectly encrypted: "; StringSource xx(encrypted, false, new HexEncoder(new FileSink(std::cout))); xx.Pump(2048); xx.Flush(false); std::cout << "\n"; SignalTestFailure(); } if (test == "Encrypt" && decrypted != plaintext) { std::cout << "\nincorrectly decrypted: "; StringSource xx(decrypted, false, new HexEncoder(new FileSink(std::cout))); xx.Pump(256); xx.Flush(false); std::cout << "\n"; SignalTestFailure(); } if (ciphertext.size()+mac.size()-plaintext.size() != asc1->DigestSize()) { std::cout << "\nbad MAC size\n"; SignalTestFailure(); } if (df.GetLastResult() != (test == "Encrypt")) { std::cout << "\nMAC incorrectly verified\n"; SignalTestFailure(); } } else { std::cout << "\nunexpected test name\n"; SignalTestError(); } } void TestDigestOrMAC(TestData &v, bool testDigest) { std::string name = GetRequiredDatum(v, "Name"); std::string test = GetRequiredDatum(v, "Test"); const char *digestName = testDigest ? "Digest" : "MAC"; member_ptr<MessageAuthenticationCode> mac; member_ptr<HashTransformation> hash; HashTransformation *pHash = NULLPTR; TestDataNameValuePairs pairs(v); if (testDigest) { hash.reset(ObjectFactoryRegistry<HashTransformation>::Registry().CreateObject(name.c_str())); pHash = hash.get(); } else { mac.reset(ObjectFactoryRegistry<MessageAuthenticationCode>::Registry().CreateObject(name.c_str())); pHash = mac.get(); std::string key = GetDecodedDatum(v, "Key"); mac->SetKey((const byte *)key.c_str(), key.size(), pairs); } if (test == "Verify" || test == "VerifyTruncated" || test == "NotVerify") { int digestSize = -1; if (test == "VerifyTruncated") digestSize = pairs.GetIntValueWithDefault(Name::DigestSize(), digestSize); HashVerificationFilter verifierFilter(*pHash, NULLPTR, HashVerificationFilter::HASH_AT_BEGIN, digestSize); PutDecodedDatumInto(v, digestName, verifierFilter); PutDecodedDatumInto(v, "Message", verifierFilter); verifierFilter.MessageEnd(); if (verifierFilter.GetLastResult() == (test == "NotVerify")) SignalTestFailure(); } else { SignalTestError(); CRYPTOPP_ASSERT(false); } } void TestKeyDerivationFunction(TestData &v) { std::string name = GetRequiredDatum(v, "Name"); std::string test = GetRequiredDatum(v, "Test"); if(test == "Skip") return; CRYPTOPP_ASSERT(test == "Verify"); std::string key = GetDecodedDatum(v, "Key"); std::string salt = GetDecodedDatum(v, "Salt"); std::string info = GetDecodedDatum(v, "Info"); std::string derived = GetDecodedDatum(v, "DerivedKey"); std::string t = GetDecodedDatum(v, "DerivedKeyLength"); TestDataNameValuePairs pairs(v); unsigned int length = pairs.GetIntValueWithDefault(Name::DerivedKeyLength(), (int)derived.size()); member_ptr<KeyDerivationFunction> kdf; kdf.reset(ObjectFactoryRegistry<KeyDerivationFunction>::Registry().CreateObject(name.c_str())); std::string calc; calc.resize(length); unsigned int ret = kdf->DeriveKey(reinterpret_cast<byte*>(&calc[0]), calc.size(), reinterpret_cast<const byte*>(key.data()), key.size(), reinterpret_cast<const byte*>(salt.data()), salt.size(), reinterpret_cast<const byte*>(info.data()), info.size()); if(calc != derived || ret != length) SignalTestFailure(); } // GetField parses the name/value pairs. The tricky part is the insertion operator // because Unix&Linux uses LF, OS X uses CR, and Windows uses CRLF. If this function // is modified, then run 'cryptest.exe tv rsa_pkcs1_1_5' as a test. Its the parser // file from hell. If it can be parsed without error, then things are likely OK. bool GetField(std::istream &is, std::string &name, std::string &value) { // ***** Name ***** name.clear(); is >> name; if (name.empty()) return false; if (name[name.size()-1] != ':') { char c; is >> std::skipws >> c; if (c != ':') SignalTestError(); } else name.erase(name.size()-1); while (is.peek() == ' ') is.ignore(1); // ***** Value ***** value.clear(); std::string line; bool continueLine = true; while (continueLine && std::getline(is, line)) { // Unix and Linux may have a stray \r because of Windows if (!line.empty() && (line[line.size() - 1] == '\r' || line[line.size() - 1] == '\n')) { line.erase(line.size()-1); } continueLine = false; if (!line.empty()) { // Early out for immediate line continuation if (line[0] == '\\') { continueLine = true; continue; } // Check end of line. It must be last character if (line[line.size() - 1] == '\\') { continueLine = true; } // Check for comment. It can be first character if (line[0] == '#') { continue; } } // Leading and trailing position. The leading position moves right, and // trailing position moves left. The sub-string in the middle is the value // for the name. We leave one space when line continuation is in effect. // The value can be an empty string. One Plaintext value is often empty // for algorithm testing. std::string::size_type l=0, t=std::string::npos; const std::string whitespace = "\t \r\n"; l = line.find_first_not_of(whitespace, l); if (l == std::string::npos) { l = 0; } t = line.find('#', l); if (t != std::string::npos) { t--; } t = line.find_last_not_of(whitespace+"\\", t); if (t != std::string::npos) { t++; } CRYPTOPP_ASSERT(t >= l); value += line.substr(l, t - l); if (continueLine) value += ' '; } return true; } void OutputPair(const NameValuePairs &v, const char *name) { Integer x; bool b = v.GetValue(name, x); CRYPTOPP_UNUSED(b); CRYPTOPP_ASSERT(b); std::cout << name << ": \\\n "; x.Encode(HexEncoder(new FileSink(std::cout), false, 64, "\\\n ").Ref(), x.MinEncodedSize()); std::cout << std::endl; } void OutputNameValuePairs(const NameValuePairs &v) { std::string names = v.GetValueNames(); std::string::size_type i = 0; while (i < names.size()) { std::string::size_type j = names.find_first_of (';', i); if (j == std::string::npos) return; else { std::string name = names.substr(i, j-i); if (name.find(':') == std::string::npos) OutputPair(v, name.c_str()); } i = j + 1; } } void TestDataFile(std::string filename, const NameValuePairs &overrideParameters, unsigned int &totalTests, unsigned int &failedTests) { static const std::string dataDirectory(CRYPTOPP_DATA_DIR); if (!dataDirectory.empty()) { if(dataDirectory != filename.substr(0, dataDirectory.length())) filename.insert(0, dataDirectory); } std::ifstream file(filename.c_str()); if (!file.good()) throw Exception(Exception::OTHER_ERROR, "Can not open file " + filename + " for reading"); TestData v; s_currentTestData = &v; std::string name, value, lastAlgName; while (file) { while (file.peek() == '#') file.ignore((std::numeric_limits<std::streamsize>::max)(), '\n'); if (file.peek() == '\n' || file.peek() == '\r') v.clear(); if (!GetField(file, name, value)) break; // Can't assert value. Plaintext is sometimes empty. // CRYPTOPP_ASSERT(!value.empty()); v[name] = value; if (name == "Test" && (s_thorough || v["SlowTest"] != "1")) { bool failed = true; std::string algType = GetRequiredDatum(v, "AlgorithmType"); if (lastAlgName != GetRequiredDatum(v, "Name")) { lastAlgName = GetRequiredDatum(v, "Name"); std::cout << "\nTesting " << algType.c_str() << " algorithm " << lastAlgName.c_str() << ".\n"; } try { if (algType == "Signature") TestSignatureScheme(v); else if (algType == "SymmetricCipher") TestSymmetricCipher(v, overrideParameters); else if (algType == "AuthenticatedSymmetricCipher") TestAuthenticatedSymmetricCipher(v, overrideParameters); else if (algType == "AsymmetricCipher") TestAsymmetricCipher(v); else if (algType == "MessageDigest") TestDigestOrMAC(v, true); else if (algType == "MAC") TestDigestOrMAC(v, false); else if (algType == "KDF") TestKeyDerivationFunction(v); else if (algType == "FileList") TestDataFile(GetRequiredDatum(v, "Test"), g_nullNameValuePairs, totalTests, failedTests); else SignalUnknownAlgorithmError(algType); failed = false; } catch (const TestFailure &) { std::cout << "\nTest failed.\n"; } catch (const CryptoPP::Exception &e) { std::cout << "\nCryptoPP::Exception caught: " << e.what() << std::endl; } catch (const std::exception &e) { std::cout << "\nstd::exception caught: " << e.what() << std::endl; } if (failed) { std::cout << "Skipping to next test.\n"; failedTests++; } else std::cout << "." << std::flush; totalTests++; } } } bool RunTestDataFile(const char *filename, const NameValuePairs &overrideParameters, bool thorough) { s_thorough = thorough; unsigned int totalTests = 0, failedTests = 0; TestDataFile((filename ? filename : ""), overrideParameters, totalTests, failedTests); std::cout << std::dec << "\nTests complete. Total tests = " << totalTests << ". Failed tests = " << failedTests << "." << std::endl; if (failedTests != 0) std::cout << "SOME TESTS FAILED!\n"; return failedTests == 0; } NAMESPACE_END // Test NAMESPACE_END // CryptoPP
[ "noloader@gmail.com" ]
noloader@gmail.com
28788e5d86881ecf18ac6c6df87dfe06d37786cb
2d4ef74dd77fef6e3c2ebfff46fb37ce310da9d8
/chap08/networkinformation/networkinformation.h
29a36a09d02289dbeece751ca935314a942015ae
[]
no_license
0000duck/Linux.Windows.Programming.With.Qt
288d8188dbcc5c0f8839e5cf5cc3787f5d8ee63d
11d5de0c9c43177fdafb9bc68c59f78e87c61279
refs/heads/master
2022-06-08T13:26:55.976565
2020-05-09T09:29:09
2020-05-09T09:29:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
628
h
#ifndef NETWORKINFORMATION_H #define NETWORKINFORMATION_H #include <QLineEdit> #include <QLabel> #include <QPushButton> #include <QDialog> #include <QtNetwork> class NetworkInformation : public QDialog // network information dialogs widget { Q_OBJECT public: NetworkInformation( QWidget *parent=0, Qt::WindowFlags f=0 ); ~NetworkInformation(); public: QLabel* LabelLocalHostName; QLineEdit* LineEditLocalHostName; QLabel* LabelAddress; QLineEdit* LineEditAddress; QPushButton* PushButtonDetail; public: void getHostInformation(); public slots: void slotDetail(); }; #endif // NETWORKINFORMATION_H
[ "hexu_1985@sina.com" ]
hexu_1985@sina.com
49c77d9bd94fa9c3d652b8c927bbf0353a9b7509
8b480f76b5c251d7dea5736777493095eea52aae
/3rdparty/protobuf/src/google/protobuf/compiler/java/java_lazy_message_field.cc
7c655c344231a2a0342a9ebbec4ee62139710aba
[ "LicenseRef-scancode-protobuf" ]
permissive
xinxu/LaluneCommon
e9e3bdf736b65db91a26b224ff8fc73ca813da29
c38dd2279c04d6538f476a01d4766e51df07f18a
refs/heads/master
2021-01-18T08:32:56.723698
2015-02-04T03:56:49
2015-02-04T03:56:49
23,908,903
0
0
null
null
null
null
UTF-8
C++
false
false
28,709
cc
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://code.google.com/p/protobuf/ // // 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. // Author: niwasaki@google.com (Naoki Iwasaki) // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. #include <google/protobuf/compiler/java/java_context.h> #include <google/protobuf/compiler/java/java_lazy_message_field.h> #include <google/protobuf/compiler/java/java_doc_comment.h> #include <google/protobuf/compiler/java/java_helpers.h> #include <google/protobuf/io/printer.h> namespace google_lalune { namespace protobuf { namespace compiler { namespace java { ImmutableLazyMessageFieldGenerator:: ImmutableLazyMessageFieldGenerator( const FieldDescriptor* descriptor, int messageBitIndex, int builderBitIndex, Context* context) : ImmutableMessageFieldGenerator( descriptor, messageBitIndex, builderBitIndex, context) { } ImmutableLazyMessageFieldGenerator::~ImmutableLazyMessageFieldGenerator() {} void ImmutableLazyMessageFieldGenerator:: GenerateMembers(io::Printer* printer) const { printer->Print(variables_, "private com.google.protobuf.LazyFieldLite $name$_ =\n" " new com.google.protobuf.LazyFieldLite();\n"); PrintExtraFieldInfo(variables_, printer); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, "$deprecation$public boolean has$capitalized_name$() {\n" " return $get_has_field_bit_message$;\n" "}\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, "$deprecation$public $type$ get$capitalized_name$() {\n" " return ($type$) $name$_.getValue($type$.getDefaultInstance());\n" "}\n"); if (HasNestedBuilders(descriptor_->containing_type())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, "$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder() {\n" " return $name$_;\n" "}\n"); } } void ImmutableLazyMessageFieldGenerator:: GenerateBuilderMembers(io::Printer* printer) const { // When using nested-builders, the code initially works just like the // non-nested builder case. It only creates a nested builder lazily on // demand and then forever delegates to it after creation. printer->Print(variables_, "private com.google.protobuf.LazyFieldLite $name$_ =\n" " new com.google.protobuf.LazyFieldLite();\n"); if (HasNestedBuilders(descriptor_->containing_type())) { printer->Print(variables_, // If this builder is non-null, it is used and the other fields are // ignored. "private com.google.protobuf.SingleFieldBuilder<\n" " $type$, $type$.Builder, $type$OrBuilder> $name$Builder_;" "\n"); } // The comments above the methods below are based on a hypothetical // field of type "Field" called "Field". // boolean hasField() WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, "$deprecation$public boolean has$capitalized_name$() {\n" " return $get_has_field_bit_builder$;\n" "}\n"); printer->Print(variables_, "$deprecation$public $type$ get$capitalized_name$() {\n" " return ($type$) $name$_.getValue($type$.getDefaultInstance());\n" "}\n"); // Field.Builder setField(Field value) WriteFieldDocComment(printer, descriptor_); PrintNestedBuilderFunction(printer, "$deprecation$public Builder set$capitalized_name$($type$ value)", "if (value == null) {\n" " throw new NullPointerException();\n" "}\n" "$name$_.setValue(value);\n" "$on_changed$\n", NULL, // Lazy fields are supported only for lite-runtime. "$set_has_field_bit_builder$;\n" "return this;\n"); // Field.Builder setField(Field.Builder builderForValue) WriteFieldDocComment(printer, descriptor_); PrintNestedBuilderFunction(printer, "$deprecation$public Builder set$capitalized_name$(\n" " $type$.Builder builderForValue)", "$name$_.setValue(builderForValue.build());\n" "$on_changed$\n", NULL, "$set_has_field_bit_builder$;\n" "return this;\n"); // Field.Builder mergeField(Field value) WriteFieldDocComment(printer, descriptor_); PrintNestedBuilderFunction(printer, "$deprecation$public Builder merge$capitalized_name$($type$ value)", "if ($get_has_field_bit_builder$ &&\n" " !$name$_.containsDefaultInstance()) {\n" " $name$_.setValue(\n" " $type$.newBuilder(\n" " get$capitalized_name$()).mergeFrom(value).buildPartial());\n" "} else {\n" " $name$_.setValue(value);\n" "}\n" "$on_changed$\n", NULL, "$set_has_field_bit_builder$;\n" "return this;\n"); // Field.Builder clearField() WriteFieldDocComment(printer, descriptor_); PrintNestedBuilderFunction(printer, "$deprecation$public Builder clear$capitalized_name$()", "$name$_.clear();\n" "$on_changed$\n", NULL, "$clear_has_field_bit_builder$;\n" "return this;\n"); if (HasNestedBuilders(descriptor_->containing_type())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, "$deprecation$public $type$.Builder get$capitalized_name$Builder() {\n" " $set_has_field_bit_builder$;\n" " $on_changed$\n" " return get$capitalized_name$FieldBuilder().getBuilder();\n" "}\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, "$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder() {\n" " if ($name$Builder_ != null) {\n" " return $name$Builder_.getMessageOrBuilder();\n" " } else {\n" " return $name$_;\n" " }\n" "}\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, "private com.google.protobuf.SingleFieldBuilder<\n" " $type$, $type$.Builder, $type$OrBuilder> \n" " get$capitalized_name$FieldBuilder() {\n" " if ($name$Builder_ == null) {\n" " $name$Builder_ = new com.google.protobuf.SingleFieldBuilder<\n" " $type$, $type$.Builder, $type$OrBuilder>(\n" " $name$_,\n" " getParentForChildren(),\n" " isClean());\n" " $name$_ = null;\n" " }\n" " return $name$Builder_;\n" "}\n"); } } void ImmutableLazyMessageFieldGenerator:: GenerateInitializationCode(io::Printer* printer) const { printer->Print(variables_, "$name$_.clear();\n"); } void ImmutableLazyMessageFieldGenerator:: GenerateBuilderClearCode(io::Printer* printer) const { printer->Print(variables_, "$name$_.clear();\n"); printer->Print(variables_, "$clear_has_field_bit_builder$;\n"); } void ImmutableLazyMessageFieldGenerator:: GenerateMergingCode(io::Printer* printer) const { printer->Print(variables_, "if (other.has$capitalized_name$()) {\n" " $name$_.merge(other.$name$_);\n" " $set_has_field_bit_builder$;\n" "}\n"); } void ImmutableLazyMessageFieldGenerator:: GenerateBuildingCode(io::Printer* printer) const { printer->Print(variables_, "if ($get_has_field_bit_from_local$) {\n" " $set_has_field_bit_to_local$;\n" "}\n"); printer->Print(variables_, "result.$name$_.setByteString(\n" " $name$_.toByteString(),\n" " $name$_.getExtensionRegistry());\n"); } void ImmutableLazyMessageFieldGenerator:: GenerateParsingCode(io::Printer* printer) const { printer->Print(variables_, "$name$_.setByteString(input.readBytes(), extensionRegistry);\n"); printer->Print(variables_, "$set_has_field_bit_message$;\n"); } void ImmutableLazyMessageFieldGenerator:: GenerateSerializationCode(io::Printer* printer) const { // Do not de-serialize lazy fields. printer->Print(variables_, "if ($get_has_field_bit_message$) {\n" " output.writeBytes($number$, $name$_.toByteString());\n" "}\n"); } void ImmutableLazyMessageFieldGenerator:: GenerateSerializedSizeCode(io::Printer* printer) const { printer->Print(variables_, "if ($get_has_field_bit_message$) {\n" " size += com.google.protobuf.CodedOutputStream\n" " .computeLazyFieldSize($number$, $name$_);\n" "}\n"); } // =================================================================== ImmutableLazyMessageOneofFieldGenerator:: ImmutableLazyMessageOneofFieldGenerator(const FieldDescriptor* descriptor, int messageBitIndex, int builderBitIndex, Context* context) : ImmutableLazyMessageFieldGenerator( descriptor, messageBitIndex, builderBitIndex, context) { const OneofGeneratorInfo* info = context->GetOneofGeneratorInfo(descriptor->containing_oneof()); SetCommonOneofVariables(descriptor, info, &variables_); variables_["lazy_type"] = "com.google.protobuf.LazyFieldLite"; } ImmutableLazyMessageOneofFieldGenerator:: ~ImmutableLazyMessageOneofFieldGenerator() {} void ImmutableLazyMessageOneofFieldGenerator:: GenerateMembers(io::Printer* printer) const { PrintExtraFieldInfo(variables_, printer); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, "$deprecation$public boolean has$capitalized_name$() {\n" " return $has_oneof_case_message$;\n" "}\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, "$deprecation$public $type$ get$capitalized_name$() {\n" " if ($has_oneof_case_message$) {\n" " return ($type$) (($lazy_type$) $oneof_name$_).getValue(\n" " $type$.getDefaultInstance());\n" " }\n" " return $type$.getDefaultInstance();\n" "}\n"); } void ImmutableLazyMessageOneofFieldGenerator:: GenerateBuilderMembers(io::Printer* printer) const { // boolean hasField() WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, "$deprecation$public boolean has$capitalized_name$() {\n" " return $has_oneof_case_message$;\n" "}\n"); printer->Print(variables_, "$deprecation$public $type$ get$capitalized_name$() {\n" " if ($has_oneof_case_message$) {\n" " return ($type$) (($lazy_type$) $oneof_name$_).getValue(\n" " $type$.getDefaultInstance());\n" " }\n" " return $type$.getDefaultInstance();\n" "}\n"); // Field.Builder setField(Field value) WriteFieldDocComment(printer, descriptor_); PrintNestedBuilderFunction(printer, "$deprecation$public Builder set$capitalized_name$($type$ value)", "if (value == null) {\n" " throw new NullPointerException();\n" "}\n" "if (!($has_oneof_case_message$)) {\n" " $oneof_name$_ = new $lazy_type$();\n" " $set_oneof_case_message$;\n" "}\n" "(($lazy_type$) $oneof_name$_).setValue(value);\n" "$on_changed$\n", NULL, // Lazy fields are supported only for lite-runtime. "return this;\n"); // Field.Builder setField(Field.Builder builderForValue) WriteFieldDocComment(printer, descriptor_); PrintNestedBuilderFunction(printer, "$deprecation$public Builder set$capitalized_name$(\n" " $type$.Builder builderForValue)", "if (!($has_oneof_case_message$)) {\n" " $oneof_name$_ = new $lazy_type$();\n" " $set_oneof_case_message$;\n" "}\n" "(($lazy_type$) $oneof_name$_).setValue(builderForValue.build());\n" "$on_changed$\n", NULL, "return this;\n"); // Field.Builder mergeField(Field value) WriteFieldDocComment(printer, descriptor_); PrintNestedBuilderFunction(printer, "$deprecation$public Builder merge$capitalized_name$($type$ value)", "if ($has_oneof_case_message$ &&\n" " !(($lazy_type$) $oneof_name$_).containsDefaultInstance()) {\n" " (($lazy_type$) $oneof_name$_).setValue(\n" " $type$.newBuilder(\n" " get$capitalized_name$()).mergeFrom(value).buildPartial());\n" "} else {\n" " if (!($has_oneof_case_message$)) {\n" " $oneof_name$_ = new $lazy_type$();\n" " $set_oneof_case_message$;\n" " }\n" " (($lazy_type$) $oneof_name$_).setValue(value);\n" "}\n" "$on_changed$\n", NULL, "return this;\n"); // Field.Builder clearField() WriteFieldDocComment(printer, descriptor_); PrintNestedBuilderFunction(printer, "$deprecation$public Builder clear$capitalized_name$()", "if ($has_oneof_case_message$) {\n" " $clear_oneof_case_message$;\n" " $oneof_name$_ = null;\n" " $on_changed$\n" "}\n", NULL, "return this;\n"); } void ImmutableLazyMessageOneofFieldGenerator:: GenerateMergingCode(io::Printer* printer) const { printer->Print(variables_, "if (!($has_oneof_case_message$)) {\n" " $oneof_name$_ = new $lazy_type$();\n" "}\n" "(($lazy_type$) $oneof_name$_).merge(\n" " ($lazy_type$) other.$oneof_name$_);\n" "$set_oneof_case_message$;\n"); } void ImmutableLazyMessageOneofFieldGenerator:: GenerateBuildingCode(io::Printer* printer) const { printer->Print(variables_, "if ($has_oneof_case_message$) {\n"); printer->Indent(); printer->Print(variables_, "result.$oneof_name$_ = new $lazy_type$();\n" "(($lazy_type$) result.$oneof_name$_).setByteString(\n" " (($lazy_type$) $oneof_name$_).toByteString(),\n" " (($lazy_type$) $oneof_name$_).getExtensionRegistry());\n"); printer->Outdent(); printer->Print("}\n"); } void ImmutableLazyMessageOneofFieldGenerator:: GenerateParsingCode(io::Printer* printer) const { printer->Print(variables_, "if (!($has_oneof_case_message$)) {\n" " $oneof_name$_ = new $lazy_type$();\n" "}\n" "(($lazy_type$) $oneof_name$_).setByteString(\n" " input.readBytes(), extensionRegistry);\n" "$set_oneof_case_message$;\n"); } void ImmutableLazyMessageOneofFieldGenerator:: GenerateSerializationCode(io::Printer* printer) const { // Do not de-serialize lazy fields. printer->Print(variables_, "if ($has_oneof_case_message$) {\n" " output.writeBytes(\n" " $number$, (($lazy_type$) $oneof_name$_).toByteString());\n" "}\n"); } void ImmutableLazyMessageOneofFieldGenerator:: GenerateSerializedSizeCode(io::Printer* printer) const { printer->Print(variables_, "if ($has_oneof_case_message$) {\n" " size += com.google.protobuf.CodedOutputStream\n" " .computeLazyFieldSize($number$, ($lazy_type$) $oneof_name$_);\n" "}\n"); } // =================================================================== RepeatedImmutableLazyMessageFieldGenerator:: RepeatedImmutableLazyMessageFieldGenerator( const FieldDescriptor* descriptor, int messageBitIndex, int builderBitIndex, Context* context) : RepeatedImmutableMessageFieldGenerator( descriptor, messageBitIndex, builderBitIndex, context) { } RepeatedImmutableLazyMessageFieldGenerator:: ~RepeatedImmutableLazyMessageFieldGenerator() {} void RepeatedImmutableLazyMessageFieldGenerator:: GenerateMembers(io::Printer* printer) const { printer->Print(variables_, "private java.util.List<com.google.protobuf.LazyFieldLite> $name$_;\n"); PrintExtraFieldInfo(variables_, printer); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, "$deprecation$public java.util.List<$type$>\n" " get$capitalized_name$List() {\n" " java.util.List<$type$> list =\n" " new java.util.ArrayList<$type$>($name$_.size());\n" " for (com.google.protobuf.LazyFieldLite lf : $name$_) {\n" " list.add(($type$) lf.getValue($type$.getDefaultInstance()));\n" " }\n" " return list;\n" "}\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, "$deprecation$public java.util.List<? extends $type$OrBuilder>\n" " get$capitalized_name$OrBuilderList() {\n" " return get$capitalized_name$List();\n" "}\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, "$deprecation$public int get$capitalized_name$Count() {\n" " return $name$_.size();\n" "}\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, "$deprecation$public $type$ get$capitalized_name$(int index) {\n" " return ($type$)\n" " $name$_.get(index).getValue($type$.getDefaultInstance());\n" "}\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, "$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder(\n" " int index) {\n" " return ($type$OrBuilder)\n" " $name$_.get(index).getValue($type$.getDefaultInstance());\n" "}\n"); } void RepeatedImmutableLazyMessageFieldGenerator:: GenerateBuilderMembers(io::Printer* printer) const { // When using nested-builders, the code initially works just like the // non-nested builder case. It only creates a nested builder lazily on // demand and then forever delegates to it after creation. printer->Print(variables_, "private java.util.List<com.google.protobuf.LazyFieldLite> $name$_ =\n" " java.util.Collections.emptyList();\n" "private void ensure$capitalized_name$IsMutable() {\n" " if (!$get_mutable_bit_builder$) {\n" " $name$_ =\n" " new java.util.ArrayList<com.google.protobuf.LazyFieldLite>(\n" " $name$_);\n" " $set_mutable_bit_builder$;\n" " }\n" "}\n" "\n"); if (HasNestedBuilders(descriptor_->containing_type())) { printer->Print(variables_, // If this builder is non-null, it is used and the other fields are // ignored. "private com.google.protobuf.RepeatedFieldBuilder<\n" " $type$, $type$.Builder, $type$OrBuilder> $name$Builder_;\n" "\n"); } // The comments above the methods below are based on a hypothetical // repeated field of type "Field" called "RepeatedField". // List<Field> getRepeatedFieldList() WriteFieldDocComment(printer, descriptor_); PrintNestedBuilderFunction(printer, "$deprecation$public java.util.List<$type$> get$capitalized_name$List()", "java.util.List<$type$> list =\n" " new java.util.ArrayList<$type$>($name$_.size());\n" "for (com.google.protobuf.LazyFieldLite lf : $name$_) {\n" " list.add(($type$) lf.getValue($type$.getDefaultInstance()));\n" "}\n" "return java.util.Collections.unmodifiableList(list);\n", "return $name$Builder_.getMessageList();\n", NULL); // int getRepeatedFieldCount() WriteFieldDocComment(printer, descriptor_); PrintNestedBuilderFunction(printer, "$deprecation$public int get$capitalized_name$Count()", "return $name$_.size();\n", "return $name$Builder_.getCount();\n", NULL); // Field getRepeatedField(int index) WriteFieldDocComment(printer, descriptor_); PrintNestedBuilderFunction(printer, "$deprecation$public $type$ get$capitalized_name$(int index)", "return ($type$) $name$_.get(index).getValue(\n" " $type$.getDefaultInstance());\n", "return $name$Builder_.getMessage(index);\n", NULL); // Builder setRepeatedField(int index, Field value) WriteFieldDocComment(printer, descriptor_); PrintNestedBuilderFunction(printer, "$deprecation$public Builder set$capitalized_name$(\n" " int index, $type$ value)", "if (value == null) {\n" " throw new NullPointerException();\n" "}\n" "ensure$capitalized_name$IsMutable();\n" "$name$_.set(index, com.google.protobuf.LazyFieldLite.fromValue(value));\n" "$on_changed$\n", "$name$Builder_.setMessage(index, value);\n", "return this;\n"); // Builder setRepeatedField(int index, Field.Builder builderForValue) WriteFieldDocComment(printer, descriptor_); PrintNestedBuilderFunction(printer, "$deprecation$public Builder set$capitalized_name$(\n" " int index, $type$.Builder builderForValue)", "ensure$capitalized_name$IsMutable();\n" "$name$_.set(index, com.google.protobuf.LazyFieldLite.fromValue(\n" " builderForValue.build()));\n" "$on_changed$\n", "$name$Builder_.setMessage(index, builderForValue.build());\n", "return this;\n"); // Builder addRepeatedField(Field value) WriteFieldDocComment(printer, descriptor_); PrintNestedBuilderFunction(printer, "$deprecation$public Builder add$capitalized_name$($type$ value)", "if (value == null) {\n" " throw new NullPointerException();\n" "}\n" "ensure$capitalized_name$IsMutable();\n" "$name$_.add(com.google.protobuf.LazyFieldLite.fromValue(value));\n" "$on_changed$\n", "$name$Builder_.addMessage(value);\n", "return this;\n"); // Builder addRepeatedField(int index, Field value) WriteFieldDocComment(printer, descriptor_); PrintNestedBuilderFunction(printer, "$deprecation$public Builder add$capitalized_name$(\n" " int index, $type$ value)", "if (value == null) {\n" " throw new NullPointerException();\n" "}\n" "ensure$capitalized_name$IsMutable();\n" "$name$_.add(index, com.google.protobuf.LazyFieldLite.fromValue(value));\n" "$on_changed$\n", "$name$Builder_.addMessage(index, value);\n", "return this;\n"); // Builder addRepeatedField(Field.Builder builderForValue) WriteFieldDocComment(printer, descriptor_); PrintNestedBuilderFunction(printer, "$deprecation$public Builder add$capitalized_name$(\n" " $type$.Builder builderForValue)", "ensure$capitalized_name$IsMutable();\n" "$name$_.add(com.google.protobuf.LazyFieldLite.fromValue(\n" " builderForValue.build()));\n" "$on_changed$\n", "$name$Builder_.addMessage(builderForValue.build());\n", "return this;\n"); // Builder addRepeatedField(int index, Field.Builder builderForValue) WriteFieldDocComment(printer, descriptor_); PrintNestedBuilderFunction(printer, "$deprecation$public Builder add$capitalized_name$(\n" " int index, $type$.Builder builderForValue)", "ensure$capitalized_name$IsMutable();\n" "$name$_.add(index, com.google.protobuf.LazyFieldLite.fromValue(\n" " builderForValue.build()));\n" "$on_changed$\n", "$name$Builder_.addMessage(index, builderForValue.build());\n", "return this;\n"); // Builder addAllRepeatedField(Iterable<Field> values) WriteFieldDocComment(printer, descriptor_); PrintNestedBuilderFunction(printer, "$deprecation$public Builder addAll$capitalized_name$(\n" " java.lang.Iterable<? extends $type$> values)", "ensure$capitalized_name$IsMutable();\n" "for (com.google.protobuf.MessageLite v : values) {\n" " $name$_.add(com.google.protobuf.LazyFieldLite.fromValue(v));\n" "}\n" "$on_changed$\n", "$name$Builder_.addAllMessages(values);\n", "return this;\n"); // Builder clearAllRepeatedField() WriteFieldDocComment(printer, descriptor_); PrintNestedBuilderFunction(printer, "$deprecation$public Builder clear$capitalized_name$()", "$name$_ = java.util.Collections.emptyList();\n" "$clear_mutable_bit_builder$;\n" "$on_changed$\n", "$name$Builder_.clear();\n", "return this;\n"); // Builder removeRepeatedField(int index) WriteFieldDocComment(printer, descriptor_); PrintNestedBuilderFunction(printer, "$deprecation$public Builder remove$capitalized_name$(int index)", "ensure$capitalized_name$IsMutable();\n" "$name$_.remove(index);\n" "$on_changed$\n", "$name$Builder_.remove(index);\n", "return this;\n"); if (HasNestedBuilders(descriptor_->containing_type())) { WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, "$deprecation$public $type$.Builder get$capitalized_name$Builder(\n" " int index) {\n" " return get$capitalized_name$FieldBuilder().getBuilder(index);\n" "}\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, "$deprecation$public $type$OrBuilder get$capitalized_name$OrBuilder(\n" " int index) {\n" " if ($name$Builder_ == null) {\n" " return $name$_.get(index);" " } else {\n" " return $name$Builder_.getMessageOrBuilder(index);\n" " }\n" "}\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, "$deprecation$public java.util.List<? extends $type$OrBuilder> \n" " get$capitalized_name$OrBuilderList() {\n" " if ($name$Builder_ != null) {\n" " return $name$Builder_.getMessageOrBuilderList();\n" " } else {\n" " return java.util.Collections.unmodifiableList($name$_);\n" " }\n" "}\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, "$deprecation$public $type$.Builder add$capitalized_name$Builder() {\n" " return get$capitalized_name$FieldBuilder().addBuilder(\n" " $type$.getDefaultInstance());\n" "}\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, "$deprecation$public $type$.Builder add$capitalized_name$Builder(\n" " int index) {\n" " return get$capitalized_name$FieldBuilder().addBuilder(\n" " index, $type$.getDefaultInstance());\n" "}\n"); WriteFieldDocComment(printer, descriptor_); printer->Print(variables_, "$deprecation$public java.util.List<$type$.Builder> \n" " get$capitalized_name$BuilderList() {\n" " return get$capitalized_name$FieldBuilder().getBuilderList();\n" "}\n" "private com.google.protobuf.RepeatedFieldBuilder<\n" " $type$, $type$.Builder, $type$OrBuilder> \n" " get$capitalized_name$FieldBuilder() {\n" " if ($name$Builder_ == null) {\n" " $name$Builder_ = new com.google.protobuf.RepeatedFieldBuilder<\n" " $type$, $type$.Builder, $type$OrBuilder>(\n" " $name$_,\n" " $get_mutable_bit_builder$,\n" " getParentForChildren(),\n" " isClean());\n" " $name$_ = null;\n" " }\n" " return $name$Builder_;\n" "}\n"); } } void RepeatedImmutableLazyMessageFieldGenerator:: GenerateParsingCode(io::Printer* printer) const { printer->Print(variables_, "if (!$get_mutable_bit_parser$) {\n" " $name$_ =\n" " new java.util.ArrayList<com.google.protobuf.LazyFieldLite>();\n" " $set_mutable_bit_parser$;\n" "}\n" "$name$_.add(new com.google.protobuf.LazyFieldLite(\n" " extensionRegistry, input.readBytes()));\n"); } void RepeatedImmutableLazyMessageFieldGenerator:: GenerateSerializationCode(io::Printer* printer) const { printer->Print(variables_, "for (int i = 0; i < $name$_.size(); i++) {\n" " output.writeBytes($number$, $name$_.get(i).toByteString());\n" "}\n"); } void RepeatedImmutableLazyMessageFieldGenerator:: GenerateSerializedSizeCode(io::Printer* printer) const { printer->Print(variables_, "for (int i = 0; i < $name$_.size(); i++) {\n" " size += com.google.protobuf.CodedOutputStream\n" " .computeLazyFieldSize($number$, $name$_.get(i));\n" "}\n"); } } // namespace java } // namespace compiler } // namespace protobuf } // namespace google
[ "weiyuemin@163.com" ]
weiyuemin@163.com
52fc9e10000a4d42968f48ea16c078a25efe0a50
efb87e4ac44f9cc98eab0dc162266fa1b99b7e5a
/UVA/UVA 836.cpp
edc94e466a7043e2ea737137450f1a65f328bedd
[]
no_license
farmerboy95/CompetitiveProgramming
fe4eef85540d3e91c42ff6ec265a3262e5b97d1f
1998d5ae764d47293f2cd71020bec1dbf5b470aa
refs/heads/master
2023-08-29T16:42:28.109183
2023-08-24T07:00:19
2023-08-24T07:00:19
206,353,615
12
1
null
null
null
null
UTF-8
C++
false
false
4,616
cpp
/* Author: Nguyen Tan Bao Status: AC Idea: - Fix 2 rows, find the largest segment of 1s */ #include <bits/stdc++.h> #define FI first #define SE second #define ALL(a) a.begin(), a.end() #define SZ(a) int((a).size()) #define MS(s, n) memset(s, n, sizeof(s)) #define FOR(i,a,b) for (int i = (a); i <= (b); i++) #define FORE(i,a,b) for (int i = (a); i >= (b); i--) #define FORALL(it, a) for (__typeof((a).begin()) it = (a).begin(); it != (a).end(); it++) #define TRAV(x, a) for (auto &x : a) using namespace std; using ll = long long; using ld = double; using pi = pair<int, int>; using pl = pair<ll, ll>; using pd = pair<ld, ld>; using cd = complex<ld>; using vcd = vector<cd>; using vi = vector<int>; using vl = vector<ll>; using vd = vector<ld>; using vs = vector<string>; using vpi = vector<pi>; using vpl = vector<pl>; using vpd = vector<pd>; // vector<pair> template<class T> using min_pq = priority_queue<T, vector<T>, greater<T> >; template<class T> inline int ckmin(T& a, const T& val) { return val < a ? a = val, 1 : 0; } template<class T> inline int ckmax(T& a, const T& val) { return a < val ? a = val, 1 : 0; } template<class T> void remDup(vector<T>& v) { sort(ALL(v)); v.erase(unique(ALL(v)), end(v)); } constexpr int pct(int x) { return __builtin_popcount(x); } // # of bits set constexpr int bits(int x) { return x == 0 ? 0 : 31-__builtin_clz(x); } // floor(log2(x)) constexpr int p2(int x) { return 1<<x; } constexpr int msk2(int x) { return p2(x)-1; } ll ceilDiv(ll a, ll b) { return a / b + ((a ^ b) > 0 && a % b); } // divide a by b rounded up ll floorDiv(ll a, ll b) { return a / b - ((a ^ b) < 0 && a % b); } // divide a by b rounded down void setPrec(int x) { cout << fixed << setprecision(x); } // TO_STRING #define ts to_string string ts(char c) { return string(1, c); } string ts(const char* s) { return (string) s; } string ts(string s) { return s; } string ts(bool b) { return ts((int)b); } template<class T> string ts(complex<T> c) { stringstream ss; ss << c; return ss.str(); } template<class T> using V = vector<T>; string ts(V<bool> v) {string res = "{"; FOR(i,0,SZ(v)-1) res += char('0'+v[i]); res += "}"; return res; } template<size_t sz> string ts(bitset<sz> b) { string res = ""; FOR(i,0,SZ(b)-1) res += char('0'+b[i]); return res; } template<class T, class U> string ts(pair<T,U> p); template<class T> string ts(T v) { // containers with begin(), end() bool fst = 1; string res = ""; for (const auto& x: v) { if (!fst) res += " "; fst = 0; res += ts(x); } return res; } template<class T, class U> string ts(pair<T,U> p) { return "("+ts(p.FI)+", "+ts(p.SE)+")"; } // OUTPUT template<class T> void pr(T x) { cout << ts(x); } template<class T, class ...U> void pr(const T& t, const U&... u) { pr(t); pr(u...); } void ps() { pr("\n"); } // print w/ spaces template<class T, class ...U> void ps(const T& t, const U&... u) { pr(t); if (sizeof...(u)) pr(" "); ps(u...); } // DEBUG void DBG() { cerr << "]" << endl; } template<class T, class ...U> void DBG(const T& t, const U&... u) { cerr << ts(t); if (sizeof...(u)) cerr << ", "; DBG(u...); } #define dbg(...) cerr << "Line(" << __LINE__ << ") -> [" << #__VA_ARGS__ << "]: [", DBG(__VA_ARGS__) #define chk(...) if (!(__VA_ARGS__)) cerr << "Line(" << __LINE__ << ") -> function(" \ << __FUNCTION__ << ") -> CHK FAILED: (" << #__VA_ARGS__ << ")" << "\n", exit(0); const ld PI = acos(-1.0); const int dx[4] = {1,0,-1,0}, dy[4] = {0,1,0,-1}; const ld EPS = 1e-9; const ll MODBASE = 1000000007LL; const int INF = 0x3f3f3f3f; const int MAXN = 110; const int MAXM = 1000; const int MAXK = 16; const int MAXQ = 200010; int n, a[MAXN][MAXN], b[MAXN]; string s[MAXN]; int main() { ios::sync_with_stdio(0); cin.tie(nullptr); int te; cin >> te; FOR(o,1,te) { if (o > 1) cout << "\n"; cin >> s[1]; n = SZ(s[1]); s[1] = " " + s[1]; FOR(i,2,n) { cin >> s[i]; s[i] = " " + s[i]; } FOR(i,1,n) FOR(j,1,n) { a[i][j] = (s[i][j] == '1'); a[i][j] += a[i-1][j]; } int res = -INF; FOR(l,1,n) FOR(r,l,n) { FOR(j,1,n) b[j] = (a[r][j] - a[l-1][j] == r - l + 1); int Max = 0, cnt = 0; FOR(j,1,n) if (b[j]) { cnt++; ckmax(Max, cnt); } else { cnt = 0; } ckmax(res, (r-l+1) * Max); } cout << res << "\n"; } return 0; }
[ "jerry.stone.manutd@gmail.com" ]
jerry.stone.manutd@gmail.com
3a50bbcac275e43dbe513fafaddccf6d48695a88
a71d1a81b385495e32c29061ae72a4516b3382ec
/WinGUI/OptionsDlg.h
35e18d70ed6fcbf274da6e68f2586a60879fa896
[]
no_license
liuhaoXD/KeePass-Archive
dacf27b3b8abf9a96d96a29009c5e040726527b8
d5aae3fa58c4a8cf8f57b3ebe1a7563c3b3b1f74
refs/heads/master
2020-07-01T21:17:51.866046
2020-02-03T05:51:24
2020-02-03T05:51:24
201,302,837
0
0
null
null
null
null
UTF-8
C++
false
false
4,843
h
/* KeePass Password Safe - The Open-Source Password Manager Copyright (C) 2003-2020 Dominik Reichl <dominik.reichl@t-online.de> 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef AFX_OPTIONSDLG_H__97A7BE00_1851_11D8_BF16_0050BF14F5CC__INCLUDED_ #define AFX_OPTIONSDLG_H__97A7BE00_1851_11D8_BF16_0050BF14F5CC__INCLUDED_ #include <afxwin.h> #include "NewGUI/KCSideBannerWnd.h" #include "NewGUI/WindowGroups.h" #include "NewGUI/ColourPickerXP.h" #include "NewGUI/XPStyleButtonST.h" #include "NewGUI/OptionsList.h" #include "PwSafeDlg.h" #define OPTGRP_SECURITY 0 #define OPTGRP_GUI 1 #define OPTGRP_FILES 2 #define OPTGRP_MEMORY 3 #define OPTGRP_SETUP 4 #define OPTGRP_ADVANCED 5 // No _T, will be TRL-ed #define OPTSZ_FILES "Files" #define OPTSZ_MEMORY "Memory" #define OPTSZ_GUI "Interface (GUI)" #define OPTSZ_SECURITY "Security" #define OPTSZ_SETUP "Setup" #define OPTSZ_ADVANCED "Advanced" ///////////////////////////////////////////////////////////////////////////// class COptionsDlg : public CDialog { public: COptionsDlg(CWnd* pParent = NULL); CPwSafeDlg *m_pParentDlg; CKCSideBannerWnd m_banner; CString m_strFontSpec; CString m_strNotesFontSpec; CString m_strPasswordFontSpec; CWindowGroups m_wndgrp; CImageList m_ilIcons; CImageList m_ilOptionIcons; COLORREF m_rgbRowHighlight; DWORD m_dwATHotKey; CString m_strDefaultAutoTypeSequence; BOOL m_bAutoTypeIEFix; BOOL m_bAutoTypeSameKL; BOOL m_bSortAutoTypeSelItems; private: void AddTcItem(LPCTSTR lpName, int iImageIndex); void _ChangeFont(CString& rSpec, const LOGFONT* plfOverride); public: BOOL m_bRememberLast; BOOL m_bAutoSave; BOOL m_bOpenLastDb; BOOL m_bStartMinimized; BOOL m_bAutoShowExpired; BOOL m_bAutoShowExpiredSoon; BOOL m_bStartWithWindows; BOOL m_bBackupEntries; BOOL m_bSingleInstance; BOOL m_bSingleClickTrayIcon; BOOL m_bShowTrayOnlyIfTrayed; BOOL m_bQuickFindInPasswords; BOOL m_bQuickFindIncBackup; BOOL m_bQuickFindIncExpired; BOOL m_bMinimizeBeforeAT; BOOL m_bDeleteBackupsOnSave; BOOL m_bShowFullPath; BOOL m_bDisableAutoType; BOOL m_bCopyURLs; BOOL m_bExitInsteadOfLockAT; BOOL m_bAllowSaveIfModifiedOnly; BOOL m_bCheckForUpdate; BOOL m_bMinimizeOnLock; BOOL m_bLockOnWinLock; BOOL m_bEnableRemoteCtrl; BOOL m_bUseLocalTimeFormat; BOOL m_bRegisterRestoreHotKey; BOOL m_bFocusResAfterQuickFind; BOOL m_bAlwaysAllowIpc; BOOL m_bDropToBackOnCopy; BOOL m_bDeleteTANsAfterUse; BOOL m_bUseTransactedFileWrites; BOOL m_bRememberKeySources; //{{AFX_DATA(COptionsDlg) enum { IDD = IDD_OPTIONS_DLG }; COptionsList m_olAdvanced; CButton m_btnDeleteAssoc; CButton m_btnCreateAssoc; CColourPickerXP m_btnColorRowHighlight; CTabCtrl m_tabMenu; CXPStyleButtonST m_btSelFont; CXPStyleButtonST m_btSelNotesFont; CXPStyleButtonST m_btSelPwFont; CXPStyleButtonST m_btCancel; CXPStyleButtonST m_btOK; CXPStyleButtonST m_btnAutoType; int m_nNewlineSequence; UINT m_uClipboardSeconds; BOOL m_bClearClipOnDbClose; BOOL m_bClipNoPersist; BOOL m_bImgButtons; BOOL m_bEntryGrid; BOOL m_bLockOnMinimize; BOOL m_bMinimizeToTray; BOOL m_bLockAfterTime; UINT m_nLockAfter; BOOL m_bColAutoSize; BOOL m_bCloseMinimizes; BOOL m_bDisableUnsafe; BOOL m_bUsePuttyForURLs; BOOL m_bSaveOnLATMod; int m_nClipboardMethod; BOOL m_bSecureEdits; BOOL m_bDefaultExpire; DWORD m_dwDefaultExpire; //}}AFX_DATA //{{AFX_VIRTUAL(COptionsDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); //}}AFX_VIRTUAL protected: //{{AFX_MSG(COptionsDlg) virtual BOOL OnInitDialog(); virtual void OnOK(); virtual void OnCancel(); afx_msg void OnBtnSelFont(); afx_msg void OnBtnSelNotesFont(); afx_msg void OnBtnSelPasswordFont(); afx_msg void OnSelChangeTabMenu(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnBtnCreateAssoc(); afx_msg void OnBtnDeleteAssoc(); afx_msg void OnRadioClipMethodSecure(); afx_msg void OnRadioClipMethodTimed(); afx_msg void OnCheckDefaultExpire(); afx_msg void OnCheckLockAfterTime(); afx_msg void OnBtnAutoType(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} #endif // AFX_OPTIONSDLG_H__97A7BE00_1851_11D8_BF16_0050BF14F5CC__INCLUDED_
[ "liuhao.x64@gmail.com" ]
liuhao.x64@gmail.com
e35c86cf581f069911696a6beec6388f7d80b99b
381238e5762373ca5f0debc531be6897bcd1afb8
/Broken/TreeNode.cpp
8484f59bb41c03380ec4eefcca13f563b655548d
[]
no_license
voidTM/FinishedGroupProject
cef38f3de168c082d5d4f883b691f363e35e3739
7590ce0c301cc3238544c0559e1fdd77d3c072e3
refs/heads/master
2021-01-23T02:35:30.623286
2014-11-30T22:39:45
2014-11-30T22:39:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
114
cpp
/* * File: TreeNode.cpp * Author: kim * * Created on November 9, 2014, 5:43 PM */ #include "TreeNode.h"
[ "samsong974@gmail.com" ]
samsong974@gmail.com
beebaf990ccd7d2a915069328ab61ed376976118
bc39b43f556c8bf78872662522af2ee311637b43
/chrome/browser/ui/webui/settings/site_settings_handler.h
f763dcd4a5aa8eef6fd2f9e70e5643cc11a1bbad
[ "BSD-3-Clause" ]
permissive
shahzadlone/chromium
a0b3cb45909a6232e4f94557d7c41668b4ae9a21
cd1c297873cd93013b043744950ad0ac121ad351
refs/heads/master
2023-01-01T13:40:42.049827
2019-01-21T00:01:26
2019-01-21T00:01:26
166,625,000
0
0
NOASSERTION
2019-01-20T05:01:40
2019-01-20T05:01:40
null
UTF-8
C++
false
false
11,999
h
// Copyright 2016 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. #ifndef CHROME_BROWSER_UI_WEBUI_SETTINGS_SITE_SETTINGS_HANDLER_H_ #define CHROME_BROWSER_UI_WEBUI_SETTINGS_SITE_SETTINGS_HANDLER_H_ #include <list> #include <map> #include <memory> #include <set> #include <string> #include <vector> #include "base/scoped_observer.h" #include "chrome/browser/browsing_data/cookies_tree_model.h" #include "chrome/browser/permissions/chooser_context_base.h" #include "chrome/browser/storage/storage_info_fetcher.h" #include "chrome/browser/ui/webui/settings/settings_page_ui_handler.h" #include "components/content_settings/core/browser/content_settings_observer.h" #include "content/public/browser/host_zoom_map.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" #include "ppapi/buildflags/buildflags.h" #include "third_party/blink/public/mojom/quota/quota_types.mojom.h" class HostContentSettingsMap; class Profile; class PrefChangeRegistrar; namespace base { class ListValue; } namespace settings { // Chrome "ContentSettings" settings page UI handler. class SiteSettingsHandler : public SettingsPageUIHandler, public content_settings::Observer, public content::NotificationObserver, public ChooserContextBase::PermissionObserver, public CookiesTreeModel::Observer { public: explicit SiteSettingsHandler(Profile* profile); ~SiteSettingsHandler() override; // SettingsPageUIHandler: void RegisterMessages() override; void OnJavascriptAllowed() override; void OnJavascriptDisallowed() override; // Usage info. void OnGetUsageInfo(const storage::UsageInfoEntries& entries); void OnStorageCleared(base::OnceClosure callback, blink::mojom::QuotaStatusCode code); void OnUsageCleared(); // CookiesTreeModel::Observer: // TODO(https://crbug.com/835712): Listen for backend data changes and notify // WebUI void TreeNodesAdded(ui::TreeModel* model, ui::TreeModelNode* parent, int start, int count) override; void TreeNodesRemoved(ui::TreeModel* model, ui::TreeModelNode* parent, int start, int count) override; void TreeNodeChanged(ui::TreeModel* model, ui::TreeModelNode* node) override; void TreeModelEndBatch(CookiesTreeModel* model) override; #if defined(OS_CHROMEOS) // Alert the Javascript that the |kEnableDRM| pref has changed. void OnPrefEnableDrmChanged(); #endif // content_settings::Observer: void OnContentSettingChanged(const ContentSettingsPattern& primary_pattern, const ContentSettingsPattern& secondary_pattern, ContentSettingsType content_type, const std::string& resource_identifier) override; // content::NotificationObserver: void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) override; // ChooserContextBase::PermissionObserver implementation: void OnChooserObjectPermissionChanged( ContentSettingsType guard_content_settings_type, ContentSettingsType data_content_settings_type) override; // content::HostZoomMap subscription. void OnZoomLevelChanged(const content::HostZoomMap::ZoomLevelChange& change); private: friend class SiteSettingsHandlerChooserExceptionTest; friend class SiteSettingsHandlerInfobarTest; friend class SiteSettingsHandlerTest; FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerChooserExceptionTest, HandleGetChooserExceptionListForUsb); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerChooserExceptionTest, HandleResetChooserExceptionForSiteForUsb); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerInfobarTest, SettingPermissionsTriggersInfobar); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, BlockAutoplay_SendOnRequest); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, BlockAutoplay_Update); #if BUILDFLAG(ENABLE_PLUGINS) FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, ChangingFlashSettingForSiteIsRemembered); #endif FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, DefaultSettingSource); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, ExceptionHelpers); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, ExtensionDisplayName); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, GetAllSites); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, OnStorageFetched); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, GetAndSetDefault); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, GetAndSetForInvalidURLs); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, GetAndSetOriginPermissions); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, Incognito); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, Origins); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, Patterns); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, PatternsAndContentType); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, SessionOnlyException); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, ZoomLevels); FRIEND_TEST_ALL_PREFIXES(SiteSettingsHandlerTest, HandleClearEtldPlus1DataAndCookies); // Creates the CookiesTreeModel if necessary. void EnsureCookiesTreeModelCreated(); // Add this class as an observer for content settings and chooser contexts. void ObserveSources(); // Calculates the data storage that has been used for each origin, and // stores the information in the |all_sites_map| and |origin_size_map|. void GetOriginStorage( std::map<std::string, std::set<std::string>>* all_sites_map, std::map<std::string, int>* origin_size_map); // Calculates the number of cookies for each etld+1 and each origin, and // stores the information in the |all_sites_map| and |origin_cookie_map|. void GetOriginCookies( std::map<std::string, std::set<std::string>>* all_sites_map, std::map<std::string, int>* origin_cookie_map); // Asynchronously fetches the usage for a given origin. Replies back with // OnGetUsageInfo above. void HandleFetchUsageTotal(const base::ListValue* args); // Deletes the storage being used for a given host. void HandleClearUsage(const base::ListValue* args); // Handles the request for a list of all USB devices. void HandleFetchUsbDevices(const base::ListValue* args); // Removes a particular USB device permission. void HandleRemoveUsbDevice(const base::ListValue* args); // Gets and sets the default value for a particular content settings type. void HandleSetDefaultValueForContentType(const base::ListValue* args); void HandleGetDefaultValueForContentType(const base::ListValue* args); // Returns a list of sites with permissions settings, grouped by their // eTLD+1. Recreates the cookies tree model to fetch the cookie and usage // data, which will send the list of sites with cookies or usage data to // the front end when fetching finished. void HandleGetAllSites(const base::ListValue* args); // Called when the list of origins using storage has been fetched, and sends // this list back to the front end. void OnStorageFetched(); // Returns a list of sites, grouped by their effective top level domain plus // 1, with their cookies number and data usage information. This method will // only be called after HandleGetAllSites is called. base::Value PopulateCookiesAndUsageData(Profile* profile); // Converts a given number of bytes into a human-readable format, with data // units. void HandleGetFormattedBytes(const base::ListValue* args); // Returns the list of site exceptions for a given content settings type. void HandleGetExceptionList(const base::ListValue* args); // Returns the list of chooser exceptions for a given chooser type. void HandleGetChooserExceptionList(const base::ListValue* args); // Gets and sets a list of ContentSettingTypes for an origin. // TODO(https://crbug.com/739241): Investigate replacing the // '*CategoryPermissionForPattern' equivalents below with these methods. void HandleGetOriginPermissions(const base::ListValue* args); void HandleSetOriginPermissions(const base::ListValue* args); // Clears the Flash data setting used to remember if the user has changed the // Flash permission for an origin. void HandleClearFlashPref(const base::ListValue* args); // Handles setting and resetting an origin permission. void HandleResetCategoryPermissionForPattern(const base::ListValue* args); void HandleSetCategoryPermissionForPattern(const base::ListValue* args); // Handles resetting a chooser exception for the given site. void HandleResetChooserExceptionForSite(const base::ListValue* args); // Returns whether a given string is a valid origin. void HandleIsOriginValid(const base::ListValue* args); // Returns whether the pattern is valid given the type. void HandleIsPatternValidForType(const base::ListValue* args); // Looks up whether an incognito session is active. void HandleUpdateIncognitoStatus(const base::ListValue* args); // Notifies the JS side whether incognito is enabled. void SendIncognitoStatus(Profile* profile, bool was_destroyed); // Handles the request for a list of all zoom levels. void HandleFetchZoomLevels(const base::ListValue* args); // Sends the zoom level list down to the web ui. void SendZoomLevels(); // Removes a particular zoom level for a given host. void HandleRemoveZoomLevel(const base::ListValue* args); // Handles the request to send block autoplay state. void HandleFetchBlockAutoplayStatus(const base::ListValue* args); // Notifies the JS side about the state of the block autoplay toggle. void SendBlockAutoplayStatus(); // Updates the block autoplay enabled pref when the UI is toggled. void HandleSetBlockAutoplayEnabled(const base::ListValue* args); BrowsingDataLocalStorageHelper* GetLocalStorageHelper(); // Clear web storage data and cookies from cookies tree model for an ETLD+1. void HandleClearEtldPlus1DataAndCookies(const base::ListValue* args); void SetCookiesTreeModelForTesting( std::unique_ptr<CookiesTreeModel> cookies_tree_model); void ClearAllSitesMapForTesting(); Profile* profile_; content::NotificationRegistrar notification_registrar_; // Keeps track of events related to zooming. std::unique_ptr<content::HostZoomMap::Subscription> host_zoom_map_subscription_; // The host for which to fetch usage. std::string usage_host_; // The origin for which to clear usage. std::string clearing_origin_; // Change observer for content settings. ScopedObserver<HostContentSettingsMap, content_settings::Observer> observer_; // Change observer for chooser permissions. ScopedObserver<ChooserContextBase, ChooserContextBase::PermissionObserver> chooser_observer_; // Change observer for prefs. std::unique_ptr<PrefChangeRegistrar> pref_change_registrar_; scoped_refptr<BrowsingDataLocalStorageHelper> local_storage_helper_; std::unique_ptr<CookiesTreeModel> cookies_tree_model_; // Whether to send all sites list on cookie tree model update. bool should_send_list_ = false; // Populated every time the user reloads the All Sites page. std::map<std::string, std::set<std::string>> all_sites_map_; // Store the origins that has permission settings. std::set<std::string> origin_permission_set_; DISALLOW_COPY_AND_ASSIGN(SiteSettingsHandler); }; } // namespace settings #endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_SITE_SETTINGS_HANDLER_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
f345b388d9645d4bda550766679cfe5a17b419d5
20d81296aa9f2b4daebdc6725ba40cb4f91de088
/misc/springsystem/include/inviwo/springsystem/utils/springsystemutils.h
754f2ed34eefd798414b57e053df0332e66101a1
[ "BSD-2-Clause" ]
permissive
Robin-cloud276/modules
9f09c1decb66075654a7ab8af6212d1806a480da
3bef6362f58b1ef59fdfadbc2339488c1998c46b
refs/heads/master
2023-03-19T22:23:49.080714
2021-03-08T14:27:02
2021-03-08T14:27:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,397
h
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2016-2021 Inviwo Foundation * All rights reserved. * * 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 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. * *********************************************************************************/ #pragma once #include <inviwo/springsystem/springsystemmoduledefine.h> #include <inviwo/springsystem/datastructures/springsystem.h> #include <inviwo/core/common/inviwo.h> namespace inviwo { namespace springmass { template <size_t N, typename ComponentType = double> struct Grid { std::vector<glm::vec<N, ComponentType>> positions; std::vector<std::pair<std::size_t, std::size_t>> springs; std::vector<bool> locked; }; template <size_t N, typename ComponentType = double> auto createLineGrid(std::size_t numNodes, ComponentType deltaDist) -> Grid<N, ComponentType>; template <size_t N, typename ComponentType = double> auto createRectangularGrid(size2_t gridDim, glm::vec<N, ComponentType> origin, glm::vec<N, ComponentType> deltaDist) -> Grid<N, ComponentType>; template <size_t N, typename ComponentType = double> auto createDiagonalGridDiagonal(size2_t gridDim, glm::vec<N, ComponentType> origin, glm::vec<N, ComponentType> deltaDist) -> Grid<N, ComponentType>; template <size_t N, typename ComponentType = double> auto createHexagonalGrid(size2_t gridDim, glm::vec<N, ComponentType> origin, glm::vec<N, ComponentType> deltaDist) -> Grid<N, ComponentType>; // implementations template <size_t N, typename ComponentType> auto createLineGrid(std::size_t numNodes, ComponentType deltaDist) -> Grid<N, ComponentType> { using Vector = glm::vec<N, ComponentType>; static_assert(N >= 1, ""); if (numNodes < 2) numNodes = 2; Grid<2, double> res{std::vector<Vector>(numNodes, Vector{0}), std::vector<std::pair<std::size_t, std::size_t>>(numNodes - 1), std::vector<bool>(numNodes, false)}; // add nodes placed equidistantly const ComponentType origin((numNodes - 1) * deltaDist * 0.5); for (std::size_t i = 0; i < numNodes; ++i) { res.positions[i].x = -origin + deltaDist * i; } // add springs in between nodes for (std::size_t i = 0; i < numNodes - 1; ++i) { res.springs[i] = {i, i + 1}; } // mark first node as anchor point res.locked[0] = true; return res; } template <size_t N, typename ComponentType> auto createRectangularGrid(size2_t gridDim, glm::vec<N, ComponentType> origin, glm::vec<N, ComponentType> deltaDist) -> Grid<N, ComponentType> { static_assert(N >= 2, ""); using Vector = glm::vec<N, ComponentType>; gridDim = glm::max(size2_t(2, 2), gridDim); const std::size_t numNodes = gridDim.x * gridDim.y; const std::size_t numSprings = (gridDim.x - 1) * gridDim.y + gridDim.x * (gridDim.y - 1); Grid<2, double> res{std::vector<Vector>(numNodes, Vector{0}), std::vector<std::pair<std::size_t, std::size_t>>(numSprings), std::vector<bool>(numNodes, false)}; // add nodes placed equidistantly for (std::size_t j = 0; j < gridDim.y; ++j) { for (std::size_t i = 0; i < gridDim.x; ++i) { Vector pos{}; pos.x = deltaDist.x * i; pos.y = -deltaDist.y * j; res.positions[i + gridDim.x * j] = origin + pos; } } // add springs in between nodes // horizontal springs size_t count = 0; for (std::size_t j = 0; j < gridDim.y; ++j) { for (std::size_t i = 0; i < gridDim.x - 1; ++i) { auto rowIndex = j * gridDim.x; res.springs[count] = {i + rowIndex, i + 1 + rowIndex}; ++count; } } // vertical springs for (std::size_t i = 0; i < gridDim.x; ++i) { for (std::size_t j = 0; j < gridDim.y - 1; ++j) { res.springs[count] = {i + j * gridDim.x, i + (j + 1) * gridDim.x}; ++count; } } // mark first and last node of top line as anchor res.locked[0] = true; res.locked[gridDim.x - 1] = true; return res; } template <size_t N, typename ComponentType> auto createDiagonalGridDiagonal(size2_t gridDim, glm::vec<N, ComponentType> origin, glm::vec<N, ComponentType> deltaDist) -> Grid<N, ComponentType> { static_assert(N >= 2, ""); using Vector = glm::vec<N, ComponentType>; gridDim = glm::max(size2_t(2, 2), gridDim); const std::size_t numNodes = gridDim.x * gridDim.y; const std::size_t numSprings = (gridDim.x - 1) * gridDim.y + gridDim.x * (gridDim.y - 1) + 2 * (gridDim.x - 1) * (gridDim.y - 1); Grid<2, double> res{std::vector<Vector>(numNodes, Vector{0}), std::vector<std::pair<std::size_t, std::size_t>>(numSprings), std::vector<bool>(numNodes, false)}; // add nodes placed equidistantly for (std::size_t j = 0; j < gridDim.y; ++j) { for (std::size_t i = 0; i < gridDim.x; ++i) { Vector pos{}; pos.x = deltaDist.x * i; pos.y = -deltaDist.y * j; res.positions[i + gridDim.x * j] = origin + pos; } } // add springs in between nodes // horizontal springs for (std::size_t j = 0; j < gridDim.y; ++j) { for (std::size_t i = 0; i < gridDim.x - 1; ++i) { auto rowIndex = j * gridDim.x; res.springs.push_back({i + rowIndex, i + 1 + rowIndex}); } } // vertical springs size_t count = 0; for (std::size_t i = 0; i < gridDim.x; ++i) { for (std::size_t j = 0; j < gridDim.y - 1; ++j) { res.springs[count] = {i + j * gridDim.x, i + (j + 1) * gridDim.x}; ++count; } } // add diagonals for (std::size_t j = 0; j < gridDim.y - 1; ++j) { for (std::size_t i = 0; i < gridDim.x - 1; ++i) { res.springs[count] = {i + j * gridDim.x, i + 1 + (j + 1) * gridDim.x}; ++count; res.springs[count] = {i + (j + 1) * gridDim.x, i + 1 + j * gridDim.x}; ++count; } } // mark first and last node of top line as anchor res.locked[0] = true; res.locked[gridDim.x - 1] = true; return res; } template <size_t N, typename ComponentType> auto createHexagonalGrid(size2_t gridDim, glm::vec<N, ComponentType> origin, glm::vec<N, ComponentType> deltaDist) -> Grid<N, ComponentType> { static_assert(N >= 2, ""); using Vector = glm::vec<N, ComponentType>; gridDim = glm::max(size2_t(2, 3), gridDim); if ((gridDim.y & 1) == 0) { // make sure, y dimension is odd gridDim.y += 1; } const std::size_t nodesPerLine = gridDim.x + 1; const std::size_t nodesPerCol = gridDim.y + 1; const std::size_t numNodes = (2 * (nodesPerCol - 1)) * (nodesPerLine - 1) + nodesPerCol; const std::size_t numBorderSprings = 2 * gridDim.x + 2 * (gridDim.y / 2); const std::size_t numSprings = nodesPerCol / 2 * nodesPerLine + 5 * (gridDim.y / 2) * (nodesPerLine - 1) + numBorderSprings; using Vec = glm::vec<2, ComponentType>; Grid<2, double> res{std::vector<Vector>(), std::vector<std::pair<std::size_t, std::size_t>>(), std::vector<bool>(numNodes, false)}; res.positions.reserve(numNodes); res.springs.reserve(numSprings); // hexagon defined by width and its height = w * 2 / sqrt(3) const auto width = deltaDist.x; const auto height = 2.0f / glm::sqrt(3.0f) * width; // first line - nodes are 2*w apart for (std::size_t i = 0; i < nodesPerLine; ++i) { res.positions.push_back(origin + Vec(width * i, 0)); if (i > 0) { res.springs.push_back({i - 1, i}); } } // loop over 0 < i < 4*(m - 1), four cases std::size_t line = 1; ComponentType verticalLinePos = 0.0f; for (std::size_t l = 1; l < (nodesPerCol - 1) * 2; ++l, ++line) { const auto lineIndex = res.positions.size(); if (line == 1) { // first case, n nodes, connected vertically down verticalLinePos -= static_cast<ComponentType>(0.5) * height; for (std::size_t i = 0; i < nodesPerLine; ++i) { res.positions.push_back(origin + Vec(width * i, verticalLinePos)); res.springs.push_back({lineIndex - nodesPerLine + i, lineIndex + i}); } } else if (line == 2) { verticalLinePos -= static_cast<ComponentType>(0.25) * height; for (std::size_t i = 0; i < nodesPerLine - 1; ++i) { res.positions.push_back(origin + Vec(width * i + 0.5f * width, verticalLinePos)); res.springs.push_back({lineIndex + i, lineIndex - nodesPerLine + i}); res.springs.push_back({lineIndex + i, lineIndex - nodesPerLine + i + 1}); } } else if (line == 3) { verticalLinePos -= static_cast<ComponentType>(0.5) * height; for (std::size_t i = 0; i < nodesPerLine - 1; ++i) { res.positions.push_back(origin + Vec(width * i + 0.5f * width, verticalLinePos)); res.springs.push_back({lineIndex - (nodesPerLine - 1) + i, lineIndex + i}); } } else { // fourth case verticalLinePos -= static_cast<ComponentType>(0.25) * height; for (std::size_t i = 0; i < nodesPerLine; ++i) { res.positions.push_back(origin + Vec(width * i, verticalLinePos)); if (i == 0) { // spring at the outer-left edge res.springs.push_back({lineIndex, lineIndex - 3 * nodesPerLine + 2}); } if (i + 1 == nodesPerLine) { // spring at the outer-right edge res.springs.push_back({lineIndex + i, lineIndex - 3 * nodesPerLine + 2 + i}); } if (i > 0) { // spring to lower left neighbor res.springs.push_back({lineIndex + i, lineIndex - nodesPerLine + i}); } if (i + 1 < nodesPerLine) { // spring to lower right neighbor res.springs.push_back({lineIndex + i, lineIndex - (nodesPerLine - 1) + i}); } } line -= 4; } } // springs last line for (std::size_t i = 1; i < nodesPerLine; ++i) { res.springs.push_back({numNodes - nodesPerLine + i - 1, numNodes - nodesPerLine + i}); } ivwAssert(res.positions.size() == numNodes, "number of positions not equal to numNodes"); ivwAssert(res.springs.size() == numSprings, "number of springs mismatch"); // mark first and last node as anchor res.locked[0] = true; res.locked[nodesPerLine - 1] = true; return res; } } // namespace springmass } // namespace inviwo
[ "peter@steneteg.se" ]
peter@steneteg.se
67bdc7a9906d386b0d73c0ffb2cdf335fd72ee45
20a1d1074ebfb3442267aaba30c39d41cc4d8a18
/src/Psyzl2TileManager.cpp
244be834b10da732b09594e9d1a929644bf7cb4c
[]
no_license
Kalz00708/CPP_CW2016_1
3bc0621a5ca8156508ff2bb58b50d545750507f5
1a902967e146a87a99ce15ffa06da358fbfaea5c
refs/heads/master
2021-01-19T13:23:25.208418
2017-07-10T08:31:28
2017-07-10T08:31:28
88,078,941
0
0
null
null
null
null
UTF-8
C++
false
false
620
cpp
#include "header.h" #include "Psyzl2TileManager.h" Psyzl2TileManager::Psyzl2TileManager() :TileManager(20, 20) { } Psyzl2TileManager::~Psyzl2TileManager() { } void Psyzl2TileManager::DrawTileAt( BaseEngine* pEngine, SDL_Surface* pSurface, int iMapX, int iMapY, int iStartPositionScreenX, int iStartPositionScreenY) const { // Base class implementation just draws some grey tiles pEngine->DrawRectangle( iStartPositionScreenX, iStartPositionScreenY, iStartPositionScreenX + GetTileWidth() - 1, iStartPositionScreenY + GetTileHeight() - 1, pEngine->GetColour(GetValue(iMapX, iMapY)), pSurface); }
[ "psyzl2@nottingham.ac.uk" ]
psyzl2@nottingham.ac.uk
3b8436dc6d4624b6b226ba975f00137fa04fbf59
74ead99ba0b976212f72cbe9d0c7c988f8fb6d5d
/CommonFunction.cpp
58ee8af27fe64c9323ee9288422a6d4eb2b12442
[]
no_license
vanhai28/Hockey_console
59b1ae32109d1bee8ac721dc5e0533c34c9c382d
37079057a88b81cc2a7874d3294aef848f05b001
refs/heads/master
2020-09-13T02:24:58.087063
2019-12-27T10:42:14
2019-12-27T10:42:14
222,632,585
0
0
null
2019-12-15T11:06:22
2019-11-19T07:15:18
C++
UTF-8
C++
false
false
523
cpp
#include "CommonFunction.h" #include <random> int randomRange(int start, int end) { if (start > end || start < 0) return 0; //tao gia tri ngau nhien std::random_device rd; std::mt19937 mt(rd()); std::uniform_int_distribution<int> dist(start, end); return dist(mt); } int tryParseInt(string line) { int result; try { result = stoi(line); } catch (exception ex) { result = 0; } return result; } void gotoXY(int x, int y, HANDLE& h) { COORD c; c.X = x; c.Y = y; SetConsoleCursorPosition(h, c); }
[ "48937890+vanhai28@users.noreply.github.com" ]
48937890+vanhai28@users.noreply.github.com
da28005350e3c1d6604085c728f7ecb49e672215
835934c3035770bd2fb0cea752bbe5c93b8ddc83
/VTKHeaders/vtkStructuredPointsToPolyDataFilter.h
9e66a11f73c883751241cc3ac6b9aeeb1875b09f
[ "MIT" ]
permissive
jmah/OsiriX-Quad-Buffered-Stereo
d257c9fc1e9be01340fe652f5bf9d63f5c84cde1
096491358a5d4d8a0928dc03d7183ec129720c56
refs/heads/master
2016-09-05T11:08:48.274221
2007-05-02T15:06:45
2007-05-02T15:06:45
3,008,660
2
0
null
null
null
null
UTF-8
C++
false
false
1,951
h
/*========================================================================= Program: Visualization Toolkit Module: $RCSfile: vtkStructuredPointsToPolyDataFilter.h,v $ 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. =========================================================================*/ // .NAME vtkStructuredPointsToPolyDataFilter - abstract filter class // .SECTION Description // vtkStructuredPointsToPolyDataFilter is an abstract filter class whose // subclasses take on input structured points and generate polygonal // data on output. // .SECTION See Also // vtkDividingCubes vtkMarchingCubes vtkMarchingSquares // vtkRecursiveDividingCubes vtkImageDataGeometryFilter #ifndef __vtkStructuredPointsToPolyDataFilter_h #define __vtkStructuredPointsToPolyDataFilter_h #include "vtkPolyDataSource.h" class vtkImageData; class VTK_FILTERING_EXPORT vtkStructuredPointsToPolyDataFilter : public vtkPolyDataSource { public: vtkTypeRevisionMacro(vtkStructuredPointsToPolyDataFilter,vtkPolyDataSource); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Set / get the input data or filter. virtual void SetInput(vtkImageData *input); vtkImageData *GetInput(); protected: vtkStructuredPointsToPolyDataFilter(); ~vtkStructuredPointsToPolyDataFilter(); void ComputeInputUpdateExtents(vtkDataObject *output); virtual int FillInputPortInformation(int, vtkInformation*); private: vtkStructuredPointsToPolyDataFilter(const vtkStructuredPointsToPolyDataFilter&); // Not implemented. void operator=(const vtkStructuredPointsToPolyDataFilter&); // Not implemented. }; #endif
[ "me@JonathonMah.com" ]
me@JonathonMah.com
c8289a01ebe53e7e31d7c30aec7618284281655b
612325535126eaddebc230d8c27af095c8e5cc2f
/src/base/system_monitor/system_monitor_unittest.cc
0e8ffc72343b58d4f2da5eb317f2533d5a8e25ff
[ "BSD-3-Clause" ]
permissive
TrellixVulnTeam/proto-quic_1V94
1a3a03ac7a08a494b3d4e9857b24bb8f2c2cd673
feee14d96ee95313f236e0f0e3ff7719246c84f7
refs/heads/master
2023-04-01T14:36:53.888576
2019-10-17T02:23:04
2019-10-17T02:23:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,618
cc
// Copyright (c) 2012 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. #include "base/system_monitor/system_monitor.h" #include "base/macros.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/test/mock_devices_changed_observer.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace base { namespace { class SystemMonitorTest : public testing::Test { protected: SystemMonitorTest() { system_monitor_.reset(new SystemMonitor); } MessageLoop message_loop_; std::unique_ptr<SystemMonitor> system_monitor_; private: DISALLOW_COPY_AND_ASSIGN(SystemMonitorTest); }; TEST_F(SystemMonitorTest, DeviceChangeNotifications) { const int kObservers = 5; testing::Sequence mock_sequencer[kObservers]; MockDevicesChangedObserver observers[kObservers]; for (int index = 0; index < kObservers; ++index) { system_monitor_->AddDevicesChangedObserver(&observers[index]); EXPECT_CALL(observers[index], OnDevicesChanged(SystemMonitor::DEVTYPE_UNKNOWN)) .Times(3) .InSequence(mock_sequencer[index]); } system_monitor_->ProcessDevicesChanged(SystemMonitor::DEVTYPE_UNKNOWN); RunLoop().RunUntilIdle(); system_monitor_->ProcessDevicesChanged(SystemMonitor::DEVTYPE_UNKNOWN); system_monitor_->ProcessDevicesChanged(SystemMonitor::DEVTYPE_UNKNOWN); RunLoop().RunUntilIdle(); } } // namespace } // namespace base
[ "2100639007@qq.com" ]
2100639007@qq.com
064b93d665b4c1235f9cc09d38e9b8105a4043e2
8e168361894837d8bab79d2e57107ced24307d51
/tesla/net/Endian.hpp
5a445300ea014781f63f371b1f4f7df6bb284f22
[ "MIT" ]
permissive
liuheng/tesla
d65c5fa88f1980b17bffb0f2f2dfb6b645b43229
da406aa9744618314a3dab99d8eb698b32234cbd
refs/heads/master
2021-03-12T22:40:14.706937
2014-07-12T05:02:06
2014-07-12T05:02:06
40,073,132
0
0
null
null
null
null
UTF-8
C++
false
false
1,300
hpp
/* * * Author: * Thomas Liu * Date: * 4/17/2014 * Description: * * * * Licensed under the Apache License, Version 2.0 * */ #ifndef TESLA_NET_ENDIAN_HPP #define TESLA_NET_ENDIAN_HPP #include <stdint.h> #include <endian.h> namespace tesla { namespace net { // the inline assembler code makes type blur, // so we disable warnings for a while. #if defined(__clang__) || __GNUC_MINOR__ >= 6 #pragma GCC diagnostic push #endif #pragma GCC diagnostic ignored "-Wconversion" #pragma GCC diagnostic ignored "-Wold-style-cast" inline uint64_t hostToNetwork64(uint64_t host64) { return htobe64(host64); } inline uint32_t hostToNetwork32(uint32_t host32) { return htobe32(host32); } inline uint16_t hostToNetwork16(uint16_t host16) { return htobe16(host16); } inline uint64_t networkToHost64(uint64_t net64) { return be64toh(net64); } inline uint32_t networkToHost32(uint32_t net32) { return be32toh(net32); } inline uint16_t networkToHost16(uint16_t net16) { return be16toh(net16); } #if defined(__clang__) || __GNUC_MINOR__ >= 6 #pragma GCC diagnostic pop #else #pragma GCC diagnostic warning "-Wconversion" #pragma GCC diagnostic warning "-Wold-style-cast" #endif // __clang__ } // namespace net } // namespace tesla #endif // TESLA_NET_ENDIAN_HPP
[ "thomas@zhihu.com" ]
thomas@zhihu.com
697e779209b006d8b01381ffb09bdda31c342a01
c25c3177e7ff002605179d15d5dec380268e304b
/src/lib/schwa/utils/enums.h
07fc54bcb469595d508d21960eddf2a99f099050
[ "MIT" ]
permissive
schwa-lab/libschwa
659851eca7849cbde08545804c8afb4bb62c782b
4812d10ad3919629beedb08e406fcdaf4290e3ba
refs/heads/master
2020-05-19T18:55:23.312854
2014-09-05T01:00:14
2014-09-05T01:00:14
17,270,174
7
1
null
null
null
null
UTF-8
C++
false
false
653
h
/* -*- Mode: C++; indent-tabs-mode: nil -*- */ #ifndef SCHWA_UTILS_ENUMS_H_ #define SCHWA_UTILS_ENUMS_H_ #include <type_traits> namespace schwa { template <typename E> inline constexpr E from_underlying(const typename std::underlying_type<E>::type e) { static_assert(std::is_enum<E>::value, "must be used with an enum"); return static_cast<E>(e); } template <typename E> inline constexpr typename std::underlying_type<E>::type to_underlying(E e) { static_assert(std::is_enum<E>::value, "must be used with an enum"); return static_cast<typename std::underlying_type<E>::type>(e); } } #endif // SCHWA_UTILS_ENUMS_H_
[ "tim.dawborn@gmail.com" ]
tim.dawborn@gmail.com
0dc1bcfd2d4131c280feba96959c14b3e7f4f469
5856e2cd49a1571110bf9d4e408541c4d5a622fe
/blingfirecompile.library/inc/FAMealyDfa.h
243bedcbbb50265711b631ed5b21d8ff2e8cf35e
[ "LicenseRef-scancode-generic-cla", "MIT" ]
permissive
tgarciai/BlingFire
c888828af472dd272f3e877b5f251a4d388e04af
afc8fdc7d2c789bb7a28c99cfb30f6a8e66f861c
refs/heads/master
2022-04-18T16:57:40.148163
2020-04-17T21:17:27
2020-04-17T21:17:27
257,096,571
1
0
MIT
2020-04-19T20:33:48
2020-04-19T20:33:48
null
UTF-8
C++
false
false
990
h
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ #ifndef _FA_MEALYDFA_H_ #define _FA_MEALYDFA_H_ #include "FAConfig.h" #include "FAMealyDfaA.h" #include "FAEncoder_pref.h" #include "FAChain2Num_hash.h" class FARSDfaCA; /// /// FSM-compile-time interafece for Mealy DFA sigma function. /// class FAMealyDfa : public FAMealyDfaA { public: FAMealyDfa (FAAllocatorA * pAlloc); virtual ~FAMealyDfa (); public: // NOTE: does not return destination state if FARSDfaCA was not setup const int GetDestOw (const int State, const int Iw, int * pOw) const; const int GetOw (const int Src, const int Iw) const; void SetOw (const int Src, const int Iw, const int Ow); void Prepare (); void Clear (); public: void SetRsDfa (const FARSDfaCA * pRsDfa); private: const FARSDfaCA * m_pRsDfa; FAEncoder_pref m_enc; FAChain2Num_hash m_arc2ow; }; #endif
[ "jiamguo@microsoft.com" ]
jiamguo@microsoft.com
bbdfb3573401d01d4666c03fc9463290ab9b72b0
0cd9dd3b0897a7eb9c9cdc14f2d3ac02727efea3
/libdvblinkremote/src/stream_request.cpp
f3a93f7a1142b8c9ac1c2b9370f063d7cb9f183f
[ "MIT" ]
permissive
avdleeuw/dvblinkremote
40fd5b7409d4d79873546b512cb04d950ecee136
18886ee67705feef7efd0a1b6cef10cb0a214ac7
refs/heads/master
2021-01-16T20:56:14.696211
2012-09-27T10:17:28
2012-09-27T10:17:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,997
cpp
/*************************************************************************** * Copyright (C) 2012 Marcus Efraimsson. * * 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 "request.h" using namespace dvblinkremote; StreamRequest::StreamRequest(const std::string& serverAddress, const long dvbLinkChannelId, const std::string& clientId, const std::string& streamType) : m_serverAddress(serverAddress), m_dvbLinkChannelId(dvbLinkChannelId), m_clientId(clientId), m_streamType(streamType) { Duration = -1; } StreamRequest::~StreamRequest() { } std::string& StreamRequest::GetServerAddress() { return m_serverAddress; } long StreamRequest::GetDVBLinkChannelID() { return m_dvbLinkChannelId; } std::string& StreamRequest::GetClientID() { return m_clientId; } std::string& StreamRequest::GetStreamType() { return m_streamType; }
[ "marcus.efraimsson@gmail.com" ]
marcus.efraimsson@gmail.com
75e921859214deca1d374dab0d1cd8ac47ddc886
e2e0bce316c5192d82e33a6ddcf2c96a9b2295d6
/5º Período/LPA/TP05/AdjacencyMatrix.cpp
e9035b1bf79721804f290ffdbb3caff770189269
[]
no_license
viniciusfdasilva/PUCMG
134a32d530929c11b911f48fa50d9f309c94c380
b4dca634856856eee2672aabd88436fc5ee453f4
refs/heads/master
2022-03-28T21:20:59.392675
2019-12-12T12:31:35
2019-12-12T12:31:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,910
cpp
#ifndef _A_M #define _A_M #include "AdjacencyMatrix.h" using namespace std; namespace Graph { AdjacencyMatrix::AdjacencyMatrix() { this->num_vertices = 5; this->matrix = (vertice*) malloc(25 * sizeof(vertice)); } AdjacencyMatrix::AdjacencyMatrix(int num_vertices) { this->num_vertices = num_vertices; this->matrix = (vertice*) malloc((num_vertices * num_vertices) * sizeof(vertice)); } inline bool AdjacencyMatrix::hasEdge(int v1, int v2) { return this->matrix[v1 * this->num_vertices + v2].edge; } bool AdjacencyMatrix::isComplete() { if(isDirectioned()) return false; int sum = 0; for(int i = 0; i< this->num_vertices; i++) { for(int j = i+1; j < this->num_vertices; j++) { sum += this->matrix[i*num_vertices+j].edge; } } return sum == (num_vertices * num_vertices-1)/2; } bool AdjacencyMatrix::isRegular() { int degrees[this->num_vertices]; bool resp = true; for(int i = 0; i< this->num_vertices; i++) { degrees[i] = this->getDegree(i); } for(int i = 1; (i< this->num_vertices) && resp; i++) { resp = degrees[i] == degrees[i-1]; } return resp; } bool AdjacencyMatrix::isNullGraph() { bool resp = true; int degrees[this->num_vertices]; for(int i = 0; i< this->num_vertices; i++) { degrees[i] = this->getDegree(i); } for(int i = 0; (i< this->num_vertices) && resp; i++) { resp = degrees[i] == 0; } return resp; } inline void AdjacencyMatrix::addEdge(int x, int y, int val) { this->matrix[x * this->num_vertices + y].edge = EDGE; this->matrix[x * this->num_vertices + y].value = val; } inline void AdjacencyMatrix::delEdge(int x, int y) { this->matrix[x * this->num_vertices + y].edge = EMPTY; this->matrix[x * this->num_vertices + y].value = 0; } inline int AdjacencyMatrix::getEdge(int x, int y) { return this->matrix[x * this->num_vertices + y].edge; } int AdjacencyMatrix::getValue(int x, int y) { return this->matrix[x * this->num_vertices + y].value; } void AdjacencyMatrix::addVertice() { ++num_vertices; vertice *aux = (vertice*) malloc( num_vertices * num_vertices * sizeof(vertice)); for(int i = 0; i< num_vertices-1; i++) { for(int j = 0; j< num_vertices-1; j++) { aux[i*num_vertices+j] = this->matrix[i*(num_vertices-1)+j]; } } this->matrix = aux; aux = NULL; free(aux); } void AdjacencyMatrix::delVertice() { --num_vertices; vertice *aux = (vertice*) malloc( num_vertices * num_vertices * sizeof(vertice)); for(int i = 0; i< num_vertices; i++) { for(int j = 0; j< num_vertices; j++) { aux[i*num_vertices+j] = this->matrix[i*(num_vertices+1)+j]; } } this->matrix = aux; aux = NULL; free(aux); } inline int AdjacencyMatrix::getDegree(int vertice) { int resp = -1; if(!isDirectioned()) resp = getEnterDegree(vertice) + getOutDegree(vertice); return resp; } int AdjacencyMatrix::getOutDegree(int vertice) { int resp = 0; for(int i = 0; i< num_vertices; i++) { resp += matrix[vertice * num_vertices + i].edge; } return resp; } int AdjacencyMatrix::getEnterDegree(int vertice) { int resp = 0; for(int i = 0; i< num_vertices; i++) { resp += matrix[i * num_vertices + vertice].edge; } return resp; } bool AdjacencyMatrix::hasLoops() { bool resp = false; for(int i = 0; i<num_vertices; i++) { resp = resp || (matrix[i * num_vertices + i].edge == 1); } return resp; } bool AdjacencyMatrix::isBipartite() { int colors[this->num_vertices]; memset(colors, 0, num_vertices*sizeof(int)); colors[0] = 1; queue <int> vertices_to_visit; vertices_to_visit.push(0); while(!vertices_to_visit.empty()) { int current_vertice = vertices_to_visit.front(); vertices_to_visit.pop(); for(int j = 0; j < num_vertices; j++) { if(matrix[current_vertice * num_vertices + j].edge == 1) { if(colors[j] == 0) { colors[j] = colors[current_vertice] == 1? 2:1; vertices_to_visit.push(j); }else if(colors[j] == colors[current_vertice]) { return false; } } } } return true; } bool AdjacencyMatrix::isDirectioned() { bool resp = true; for(int i = 0; i< num_vertices; i++) { for(int j = i+1; j< num_vertices; j++) { resp = resp && (matrix[i * num_vertices + j].edge == matrix[j * num_vertices + i].edge); } } return !resp; } bool AdjacencyMatrix::isConnect() { bool resp = true; short *visited_vertices = (short*) malloc(num_vertices * sizeof(short)); int val = 0; for(int i = 0; i< num_vertices; i++) { if(visited_vertices[i] == 0) { val++; visit_conex(i, val, visited_vertices); } } for(int i = 0; (i< num_vertices) && resp; i++) resp = (1 == visited_vertices[i]); visited_vertices = NULL; free(visited_vertices); return resp; } AdjacencyMatrix* AdjacencyMatrix::getComplement() { AdjacencyMatrix* resp = new AdjacencyMatrix(this->num_vertices); for(int i = 0; i< this->num_vertices; i++) { for(int j = 0; j < this->num_vertices; j++) { int aux = this->getEdge(i,j) == 1? 0:1; if (aux == 1) resp->addEdge(i,j,1); } } for(int i = 0; i< this->num_vertices; i++) resp->delEdge(i,i); return resp; } int AdjacencyMatrix::getNComponents() { short *visited_vertices = (short*) malloc(num_vertices * sizeof(short)); int val = 0; for(int i = 0; i< num_vertices; i++) { if(visited_vertices[i] == 0) { val++; visit_conex(i, val, visited_vertices); } } visited_vertices = NULL; free(visited_vertices); return val; } void AdjacencyMatrix::visit_conex(int vertice, int val, short* visited_vertice) { for(int i = 0; i< num_vertices; i++) { if(visited_vertice[i] == 0 && matrix[vertice * num_vertices + i].edge == 1) { visited_vertice[i] = val; visit_conex(i, val, visited_vertice); } } } bool AdjacencyMatrix::isEulerGraph() { bool resp = true; int degrees[this->num_vertices]; for(int i = 0; i< this->num_vertices; i++) { degrees[i] = this->getDegree(i) % 2; } for(int i = 0; i< this->num_vertices && resp; i++) { resp = degrees[i] == 0; } return resp; } bool AdjacencyMatrix::isUnicursal() { int val = 0; int degrees[this->num_vertices]; for(int i = 0; i< this->num_vertices; i++) { degrees[i] = this->getDegree(i) % 2; } for(int i = 0; i< this->num_vertices; i++) { val += degrees[i]; } return val == 2; } bool AdjacencyMatrix::isCircuit(int list[], int n) { bool resp = this->isClosePath(list, n); int frequency[this->num_vertices]; for(int i = 0; i< n && resp; i++) { frequency[list[i]]++; } for(int i = 0; i< this->num_vertices-1 && resp; i++) { resp = frequency[i] == 1; } return resp; } inline bool AdjacencyMatrix::isLonelyVertice(int vertice) { return getDegree(vertice) == 0; } inline bool AdjacencyMatrix::isPendingVertice(int vertice) { return (!isDirectioned() && (getDegree(vertice) == 1)); } bool AdjacencyMatrix::isPath(int list[], int n) { bool resp = true; for(int i = 1; (i < n) && resp; i++) { resp = (getEdge(i-1, i) == 1); } return resp; } bool AdjacencyMatrix::isOpenPath(int list[], int n) { return (this->isPath(list, n)) && (list[0] != list[n-1]); } bool AdjacencyMatrix::isClosePath(int list[], int n) { return (this->isPath(list, n)) && (list[0] == list[n-1]); } void AdjacencyMatrix::print() { int i,j; printf("\n "); for(i = 0; i< this->num_vertices; i++) { if(i < 10) printf(" 0%d", i); else printf(" %d", i); } printf("\n"); printf(" "); for(i = 0; i< this->num_vertices*3; i++) printf("-"); printf("-\n"); for(i = 0; i< this->num_vertices; i++) { if(i<10) printf("0%d|",i); else printf("%d|",i); for(j = 0; j < this->num_vertices; j++) { printf(" %d", this->matrix[i * this->num_vertices + j].edge); } printf("\n"); } } void AdjacencyMatrix::transpose() { if(isDirectioned()) { for(int i = 0; i < num_vertices; i++) { for(int j = 1; j < num_vertices; j++) { const short tmp = matrix[i * num_vertices + j].edge; matrix[i * num_vertices + j].edge = matrix[j * num_vertices + i].edge; matrix[j * num_vertices + i].edge = tmp; } } } } void AdjacencyMatrix::BFS() { short visited_vertices[num_vertices]; for(int i = 0; i< num_vertices; i++) visited_vertices[i] = 0; for(int i = 0; i< num_vertices; i++) { if(visited_vertices[i] == 0) { visited_vertices[i] = 1; queue <int> vertices_to_visit; vertices_to_visit.push(i); while(!vertices_to_visit.empty()) { int current_vertice = vertices_to_visit.front(); vertices_to_visit.pop(); for(int j = 0; j < num_vertices; j++) { if(matrix[current_vertice * num_vertices + j].edge == 1 && visited_vertices[j] == 0) { visited_vertices[j] = 1; vertices_to_visit.push(j); } } visited_vertices[current_vertice] = 2; printf("%d\n", current_vertice); } } } for(int i = 0; i< num_vertices; i++) printf("%d", visited_vertices[i]); } void AdjacencyMatrix::DFS() { short *visited_vertices = (short*) malloc(num_vertices * sizeof(short)); for(int i = 0; i< num_vertices; i++) { if(visited_vertices[i] == 0) { visit(i, visited_vertices); } } visited_vertices = NULL; free(visited_vertices); } void AdjacencyMatrix::visit(int vertice, short* visited_vertice) { visited_vertice[vertice] = 1; for(int i = 0; i< num_vertices; i++) { if(visited_vertice[i] == 0 && matrix[vertice * num_vertices + i].edge == 1) { visit(i, visited_vertice); } } visited_vertice[vertice] = 2; printf("%d\n",vertice); } void AdjacencyMatrix::topologicalOrder() { AdjacencyMatrix aux (num_vertices); bool hasGraph = false; for(int i = 0; i< num_vertices; i++) { for(int j = 0; j< num_vertices; j++) { if(this->getEdge(i,j)) aux.addEdge(i,j,1); hasGraph = hasGraph || aux.getEdge(i,j); } } while(hasGraph) { for(int i = 0; i < num_vertices; i++) { if(aux.getEnterDegree(i) == 0) { for(int j = 0; j < num_vertices; j++) { aux.delEdge(i,j); aux.delEdge(j,i); } } } bool tmp = false; for(int i = 0; i< num_vertices; i++) { for(int j = 0; j< num_vertices; j++) { tmp = tmp || aux.getEdge(i,j); } } hasGraph = hasGraph && tmp; } } AdjacencyMatrix::~AdjacencyMatrix() { matrix = NULL; free(matrix); } } #endif
[ "gabrielluciano26@gmail.com" ]
gabrielluciano26@gmail.com
8c34709ca847c5c50ee61c763c97547e9d257f09
86d2546f8409a5263aabe94aef8716ef431c68af
/CleverApplication/MeetingCommandReceiver.h
34cb5cba557a3ad22d81746c2eaccca8ea33b882
[]
no_license
sucong0826/CppWorld
016977e486e94623c3589a2415517c2134696b05
6d5fe955409edcfd4caacf660caef07274baf773
refs/heads/master
2022-10-04T01:23:38.320061
2022-09-30T12:57:17
2022-09-30T12:57:17
226,373,619
0
0
null
null
null
null
UTF-8
C++
false
false
397
h
#pragma once #include "IMeetingCommandReceiver.h" #include "IMeetingCommandExecutor.h" class MeetingCommandReceiver : public IMeetingCommandReceiver { public: MeetingCommandReceiver(IMeetingCommandExecutor* commandExecutor); virtual ~MeetingCommandReceiver(); virtual void ReceiveCommand(int command, MeetingCommandArgument& argument); private: IMeetingCommandExecutor* pCommandExecutor; };
[ "clever.su@zoom.us" ]
clever.su@zoom.us
4fdb3107571abfb58de5d5bf673eb2fe1dc944ee
5253aec20af21fe348f25ef7830a4a6d95726f10
/history/EmbedHistoryListener.h
46f17e336ac657a7af5fbffb2c55fddc420dda64
[]
no_license
veskuh/embedlite-components
0eee8d0b22af5cc7c27eb5d13939111cd90d63b3
73bbe3d4f7c986187525f2245f471bd807baca84
refs/heads/master
2021-01-15T16:37:19.381870
2014-05-21T06:50:23
2014-05-21T06:50:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,658
h
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef EmbedHistoryListener_H_ #define EmbedHistoryListener_H_ #include "mozilla/IHistory.h" #include "nsDataHashtable.h" #include "nsTPriorityQueue.h" #include "nsThreadUtils.h" #include "nsIEmbedAppService.h" #include "nsServiceManagerUtils.h" #include "nsIObserver.h" #define NS_EMBEDLITEHISTORY_CID \ { 0xec7cf1e2, \ 0x6e88, \ 0x11e2, \ { 0xa7, 0x9a, 0xfb, 0x19, 0xfe, 0x29, 0x97 }} class EmbedHistoryListener : public mozilla::IHistory , public nsIRunnable , public nsIObserver { public: NS_DECL_ISUPPORTS NS_DECL_IHISTORY NS_DECL_NSIRUNNABLE NS_DECL_NSIOBSERVER nsresult Init() { return NS_OK; } /** * Obtains a pointer that has had AddRef called on it. Used by the service * manager only. */ static EmbedHistoryListener* GetSingleton(); EmbedHistoryListener(); private: nsIEmbedAppService* GetService(); static EmbedHistoryListener* sHistory; nsDataHashtable<nsCStringHashKey, nsTArray<mozilla::dom::Link*> *> mListeners; nsTPriorityQueue<nsCString> mPendingURIs; nsCOMPtr<nsIEmbedAppService> mService; }; #define NS_EMBED_HISTORY_CONTRACTID "@mozilla.org/embed-history-component;1" #define NS_EMBED_HISTORY_SERVICE_CLASSNAME "Embed History Listener Component" #define NS_EMBED_HISTORY_SERVICE_CID NS_EMBEDLITEHISTORY_CID #endif /*EmbedHistoryListener_H_*/
[ "tanya.meshkova@gmail.com" ]
tanya.meshkova@gmail.com
221d4e3aa954514d11eca3343eb2a659454bbf41
2521147fa7c8ffee76057da6cc759501b29caff7
/main.ino
257b5a94d2c924b4d28c126286789bbd7c533e91
[ "LicenseRef-scancode-public-domain" ]
permissive
suppachailao/PongGame_IOT_Class
b1f16dc1992dcc3d429ce4f66e0a19708be7fab2
90594e89ff3f9c6ba32fa194907d1a9ef78369ea
refs/heads/master
2021-04-28T11:11:11.471713
2018-02-20T13:53:25
2018-02-20T13:53:25
122,085,908
0
0
null
null
null
null
UTF-8
C++
false
false
2,470
ino
/* PongGame Suppachai IOT_Class by Ajahn Piti, */ #include "PongGame.h" #include "LEDMatrix.h" #include "HC595.h" using namespace std; using namespace hw4; LEDMatrix ledMat(2,3,4,5); //HC595 shreg(2, 3, 4, 5); #define leftUpBut 8 #define leftDownBut 9 #define rightUpBut 11 #define rightDownBut 12 #define resetBut 13 // shift 14 connect to D2 // shift 13 connect to GND // shift 12 connect to D4 // shift 11 connect to D3 // shift 10 connect to D5 const int nrow = 8; const int ncol = 8; PongGame pongGame(nrow, ncol); int* buffer = new int[nrow*ncol]; void setup(){ Serial.begin(9600); pongGame.start(millis()); pinMode(leftUpBut, INPUT_PULLUP); pinMode(leftDownBut, INPUT_PULLUP); pinMode(rightUpBut, INPUT_PULLUP); pinMode(rightDownBut, INPUT_PULLUP); pinMode(resetBut, INPUT_PULLUP); } void processInput(unsigned long tick){ //You will need to change this if ((digitalRead(leftUpBut)==LOW)){ pongGame.movePad(Player::PLAYER_TWO, PadDirection::UP); delay(50); } else if ((digitalRead(leftDownBut)==LOW)){ pongGame.movePad(Player::PLAYER_TWO, PadDirection::DOWN); delay(50); } else if ((digitalRead(resetBut)==LOW)){ pongGame.reset(); pongGame.start(tick); // Serial.println(digitalRead(resetBut)); } else if ((digitalRead(rightUpBut)==LOW)){ pongGame.movePad(Player::PLAYER_ONE, PadDirection::UP); delay(50); } else if ((digitalRead(rightDownBut)==LOW)){ pongGame.movePad(Player::PLAYER_ONE, PadDirection::DOWN); delay(50); } // } } byte BoolArrayToByte(bool boolArray[8]){ byte result = 0; for(int i = 0; i < 8; i++) { if(boolArray[i]) { result = result | (1 << i); } } return result; } void drawScreen(int* buffer){ bool rowArray[8]; for(int irow=0; irow<nrow; irow++){ for(int icol=0; icol<ncol; icol++){ rowArray[icol] = buffer[irow*ncol + icol]; } byte rowByte = BoolArrayToByte(rowArray); ledMat.writeRow(irow, rowByte); // ledMat.update(); } } void loop(){ const unsigned long tick = millis(); processInput(tick); pongGame.update(tick); if(pongGame.isDirty()){ pongGame.paint(buffer); drawScreen(buffer); } else{ drawScreen(buffer); } }
[ "noreply@github.com" ]
noreply@github.com
a4ae827ff9b6e705839a45c102025e2033b5ecc5
fa0c642ba67143982d3381f66c029690b6d2bd17
/Source/Engine/Platform/ios/Controller/iosControllerManager.h
6eb1a1cb5bb569e6c4f4df9ff088c5425332ee9d
[ "MIT" ]
permissive
blockspacer/EasyGameEngine
3f605fb2d5747ab250ef8929b0b60e5a41cf6966
da0b0667138573948cbd2e90e56ece5c42cb0392
refs/heads/master
2023-05-05T20:01:31.532452
2021-06-01T13:35:54
2021-06-01T13:35:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
828
h
//! @file iosControllerManager.h //! @author LiCode //! @version 1.1.0.621 //! @date 2011/01/17 //! Copyright 2009-2010 LiCode's Union. #pragma once namespace EGE { //---------------------------------------------------------------------------- // iosControllerManager //---------------------------------------------------------------------------- class iosControllerManager : public TControllerManager< IControllerManager > { public: iosControllerManager( ); virtual ~iosControllerManager( ); // IControllerManager Interface public: virtual _ubool Initialize( IViewBasedApp* application ) override; virtual _void Pause( ) override; virtual _void Resume( ) override; virtual _dword GetJoystickNumber( ) const override; virtual IJoystickRef GetJoystickByIndex( _dword index ) const override; }; }
[ "zopenge@126.com" ]
zopenge@126.com
d222c54484a887ae32bf297b250193b26a8b4828
48179ca220a805d4ebd6dc1fdfa9c7fdae04ddc6
/tasks/standard-task.hh
d55859db7bc9a43b43a1b771eb97ded52ae24a05
[ "Apache-2.0" ]
permissive
lukas-ke/faint-graphics-editor
45093d777acc097fd0d963b13718e08368e12908
c475123c03311042877740d018f314cd667d10d5
refs/heads/master
2022-11-11T09:32:33.184403
2022-11-06T11:24:18
2022-11-06T11:24:18
15,910,961
12
1
null
null
null
null
UTF-8
C++
false
false
1,375
hh
// -*- coding: us-ascii-unix -*- // Copyright 2014 Lukas Kemmer // // 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. #ifndef FAINT_STANDARD_TASK_HH #define FAINT_STANDARD_TASK_HH #include "tasks/task.hh" namespace faint { class StandardTask : public Task{ // Base class for tasks with some default behavior. public: void Activate() override; TaskResult Char(const KeyInfo&) override; TaskResult DoubleClick(const PosInfo&) override; bool EatsSettings() const override; Optional<const faint::HistoryContext&> HistoryContext() const override; bool RefreshOnMouseOut() const override; Optional<const faint::SelectionContext&> SelectionContext() const override; void SelectionChange() override; void SetLayer(Layer) override; Optional<const faint::TextContext&> TextContext() const override; void UpdateSettings() override; }; } // namespace #endif
[ "lukas.kemmer@gmail.com" ]
lukas.kemmer@gmail.com
ccff170f248cc21fd093db03372870bb27e9dff0
2f9200469b14b83135dbe0cd5fb3e10b152e31d2
/MFC/20160307(序列化)代码及作业/SankCAD/SankCAD.cpp
ccc8b6778dc74784faffd59dbaa22c5e435059bc
[]
no_license
Hi10086/CR22-2
9fb56e81dd1572deda740958efbad6d15eafffba
e7e53d76bd16d2ccaae930b017944a9b38783002
refs/heads/master
2016-09-12T22:00:43.833014
2016-04-17T08:49:56
2016-04-17T08:49:56
56,426,037
1
0
null
null
null
null
UTF-8
C++
false
false
4,073
cpp
// SankCAD.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "SankCAD.h" #include "MainFrm.h" #include "SankCADDoc.h" #include "SankCADView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CSankCADApp BEGIN_MESSAGE_MAP(CSankCADApp, CWinApp) //{{AFX_MSG_MAP(CSankCADApp) ON_COMMAND(ID_APP_ABOUT, OnAppAbout) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG_MAP // Standard file based document commands ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew) ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen) // Standard print setup command ON_COMMAND(ID_FILE_PRINT_SETUP, CWinApp::OnFilePrintSetup) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CSankCADApp construction CSankCADApp::CSankCADApp() { // TODO: add construction code here, // Place all significant initialization in InitInstance } ///////////////////////////////////////////////////////////////////////////// // The one and only CSankCADApp object CSankCADApp theApp; ///////////////////////////////////////////////////////////////////////////// // CSankCADApp initialization BOOL CSankCADApp::InitInstance() { AfxEnableControlContainer(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need. #ifdef _AFXDLL Enable3dControls(); // Call this when using MFC in a shared DLL #else Enable3dControlsStatic(); // Call this when linking to MFC statically #endif // Change the registry key under which our settings are stored. // TODO: You should modify this string to be something appropriate // such as the name of your company or organization. SetRegistryKey(_T("Local AppWizard-Generated Applications")); LoadStdProfileSettings(); // Load standard INI file options (including MRU) // Register the application's document templates. Document templates // serve as the connection between documents, frame windows and views. CSingleDocTemplate* pDocTemplate; pDocTemplate = new CSingleDocTemplate( IDR_MAINFRAME, RUNTIME_CLASS(CSankCADDoc), RUNTIME_CLASS(CMainFrame), // main SDI frame window RUNTIME_CLASS(CSankCADView)); AddDocTemplate(pDocTemplate); // Parse command line for standard shell commands, DDE, file open CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); // Dispatch commands specified on the command line if (!ProcessShellCommand(cmdInfo)) return FALSE; // The one and only window has been initialized, so show and update it. m_pMainWnd->ShowWindow(SW_SHOW); m_pMainWnd->UpdateWindow(); return TRUE; } ///////////////////////////////////////////////////////////////////////////// // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data //{{AFX_DATA(CAboutDlg) enum { IDD = IDD_ABOUTBOX }; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAboutDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: //{{AFX_MSG(CAboutDlg) // No message handlers //}}AFX_MSG DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { //{{AFX_DATA_INIT(CAboutDlg) //}}AFX_DATA_INIT } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CAboutDlg) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) //{{AFX_MSG_MAP(CAboutDlg) // No message handlers //}}AFX_MSG_MAP END_MESSAGE_MAP() // App command to run the dialog void CSankCADApp::OnAppAbout() { CAboutDlg aboutDlg; aboutDlg.DoModal(); } ///////////////////////////////////////////////////////////////////////////// // CSankCADApp message handlers
[ "373650433@qq.com" ]
373650433@qq.com
87edb20802acf1a433a65a413956916c961231f1
47c9c2957c6b67fe6cb51e76e76aed5e0f0bd71d
/Include/10.0.19041.0/um/encdec.h
0c37ba97e9400ba7ec84e4cb64292d9cf975a2db
[]
no_license
ojdkbuild/tools_toolchain_sdk10_19041
7f7aeee00c53f2d342f2dd2fef0db58c966fe411
dff0034d9b9afb29e5c9f39b31734be5ba187d0f
refs/heads/master
2023-08-16T07:32:15.062980
2021-09-19T13:29:48
2021-09-19T13:29:48
408,134,287
1
0
null
null
null
null
UTF-8
C++
false
false
77,055
h
/* this ALWAYS GENERATED file contains the definitions for the interfaces */ /* File created by MIDL compiler version 8.01.0622 */ /* @@MIDL_FILE_HEADING( ) */ /* verify that the <rpcndr.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCNDR_H_VERSION__ #define __REQUIRED_RPCNDR_H_VERSION__ 500 #endif /* verify that the <rpcsal.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCSAL_H_VERSION__ #define __REQUIRED_RPCSAL_H_VERSION__ 100 #endif #include "rpc.h" #include "rpcndr.h" #ifndef __RPCNDR_H_VERSION__ #error this stub requires an updated version of <rpcndr.h> #endif /* __RPCNDR_H_VERSION__ */ #ifndef COM_NO_WINDOWS_H #include "windows.h" #include "ole2.h" #endif /*COM_NO_WINDOWS_H*/ #ifndef __encdec_h__ #define __encdec_h__ #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif /* Forward Declarations */ #ifndef __IETFilterConfig_FWD_DEFINED__ #define __IETFilterConfig_FWD_DEFINED__ typedef interface IETFilterConfig IETFilterConfig; #endif /* __IETFilterConfig_FWD_DEFINED__ */ #ifndef __IDTFilterConfig_FWD_DEFINED__ #define __IDTFilterConfig_FWD_DEFINED__ typedef interface IDTFilterConfig IDTFilterConfig; #endif /* __IDTFilterConfig_FWD_DEFINED__ */ #ifndef __IXDSCodecConfig_FWD_DEFINED__ #define __IXDSCodecConfig_FWD_DEFINED__ typedef interface IXDSCodecConfig IXDSCodecConfig; #endif /* __IXDSCodecConfig_FWD_DEFINED__ */ #ifndef __IDTFilterLicenseRenewal_FWD_DEFINED__ #define __IDTFilterLicenseRenewal_FWD_DEFINED__ typedef interface IDTFilterLicenseRenewal IDTFilterLicenseRenewal; #endif /* __IDTFilterLicenseRenewal_FWD_DEFINED__ */ #ifndef __IPTFilterLicenseRenewal_FWD_DEFINED__ #define __IPTFilterLicenseRenewal_FWD_DEFINED__ typedef interface IPTFilterLicenseRenewal IPTFilterLicenseRenewal; #endif /* __IPTFilterLicenseRenewal_FWD_DEFINED__ */ #ifndef __IMceBurnerControl_FWD_DEFINED__ #define __IMceBurnerControl_FWD_DEFINED__ typedef interface IMceBurnerControl IMceBurnerControl; #endif /* __IMceBurnerControl_FWD_DEFINED__ */ #ifndef __IETFilter_FWD_DEFINED__ #define __IETFilter_FWD_DEFINED__ typedef interface IETFilter IETFilter; #endif /* __IETFilter_FWD_DEFINED__ */ #ifndef __IETFilterEvents_FWD_DEFINED__ #define __IETFilterEvents_FWD_DEFINED__ typedef interface IETFilterEvents IETFilterEvents; #endif /* __IETFilterEvents_FWD_DEFINED__ */ #ifndef __ETFilter_FWD_DEFINED__ #define __ETFilter_FWD_DEFINED__ #ifdef __cplusplus typedef class ETFilter ETFilter; #else typedef struct ETFilter ETFilter; #endif /* __cplusplus */ #endif /* __ETFilter_FWD_DEFINED__ */ #ifndef __IDTFilter_FWD_DEFINED__ #define __IDTFilter_FWD_DEFINED__ typedef interface IDTFilter IDTFilter; #endif /* __IDTFilter_FWD_DEFINED__ */ #ifndef __IDTFilter2_FWD_DEFINED__ #define __IDTFilter2_FWD_DEFINED__ typedef interface IDTFilter2 IDTFilter2; #endif /* __IDTFilter2_FWD_DEFINED__ */ #ifndef __IDTFilter3_FWD_DEFINED__ #define __IDTFilter3_FWD_DEFINED__ typedef interface IDTFilter3 IDTFilter3; #endif /* __IDTFilter3_FWD_DEFINED__ */ #ifndef __IDTFilterEvents_FWD_DEFINED__ #define __IDTFilterEvents_FWD_DEFINED__ typedef interface IDTFilterEvents IDTFilterEvents; #endif /* __IDTFilterEvents_FWD_DEFINED__ */ #ifndef __DTFilter_FWD_DEFINED__ #define __DTFilter_FWD_DEFINED__ #ifdef __cplusplus typedef class DTFilter DTFilter; #else typedef struct DTFilter DTFilter; #endif /* __cplusplus */ #endif /* __DTFilter_FWD_DEFINED__ */ #ifndef __IXDSCodec_FWD_DEFINED__ #define __IXDSCodec_FWD_DEFINED__ typedef interface IXDSCodec IXDSCodec; #endif /* __IXDSCodec_FWD_DEFINED__ */ #ifndef __IXDSCodecEvents_FWD_DEFINED__ #define __IXDSCodecEvents_FWD_DEFINED__ typedef interface IXDSCodecEvents IXDSCodecEvents; #endif /* __IXDSCodecEvents_FWD_DEFINED__ */ #ifndef __XDSCodec_FWD_DEFINED__ #define __XDSCodec_FWD_DEFINED__ #ifdef __cplusplus typedef class XDSCodec XDSCodec; #else typedef struct XDSCodec XDSCodec; #endif /* __cplusplus */ #endif /* __XDSCodec_FWD_DEFINED__ */ #ifndef __CXDSData_FWD_DEFINED__ #define __CXDSData_FWD_DEFINED__ #ifdef __cplusplus typedef class CXDSData CXDSData; #else typedef struct CXDSData CXDSData; #endif /* __cplusplus */ #endif /* __CXDSData_FWD_DEFINED__ */ /* header files for imported files */ #include "oaidl.h" #include "ocidl.h" #ifdef __cplusplus extern "C"{ #endif /* interface __MIDL_itf_encdec_0000_0000 */ /* [local] */ //+------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 2002. // //-------------------------------------------------------------------------- #pragma once #include <winapifamily.h> #pragma region Desktop Family #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) #pragma warning(push) #pragma warning(disable:4001) #pragma once #pragma warning(push) #pragma warning(disable:4001) #pragma once #pragma warning(pop) #pragma warning(pop) #pragma region Desktop Family #pragma region Desktop Family #pragma endregion typedef enum EnTvRat_System { MPAA = 0, US_TV = 1, Canadian_English = 2, Canadian_French = 3, Reserved4 = 4, System5 = 5, System6 = 6, Reserved7 = 7, PBDA = 8, AgeBased = 9, TvRat_kSystems = 10, TvRat_SystemDontKnow = 255 } EnTvRat_System; typedef enum EnTvRat_GenericLevel { TvRat_0 = 0, TvRat_1 = 1, TvRat_2 = 2, TvRat_3 = 3, TvRat_4 = 4, TvRat_5 = 5, TvRat_6 = 6, TvRat_7 = 7, TvRat_8 = 8, TvRat_9 = 9, TvRat_10 = 10, TvRat_11 = 11, TvRat_12 = 12, TvRat_13 = 13, TvRat_14 = 14, TvRat_15 = 15, TvRat_16 = 16, TvRat_17 = 17, TvRat_18 = 18, TvRat_19 = 19, TvRat_20 = 20, TvRat_21 = 21, TvRat_kLevels = 22, TvRat_Unblock = -1, TvRat_LevelDontKnow = 255 } EnTvRat_GenericLevel; typedef enum EnTvRat_MPAA { MPAA_NotApplicable = TvRat_0, MPAA_G = TvRat_1, MPAA_PG = TvRat_2, MPAA_PG13 = TvRat_3, MPAA_R = TvRat_4, MPAA_NC17 = TvRat_5, MPAA_X = TvRat_6, MPAA_NotRated = TvRat_7 } EnTvRat_MPAA; typedef enum EnTvRat_US_TV { US_TV_None = TvRat_0, US_TV_Y = TvRat_1, US_TV_Y7 = TvRat_2, US_TV_G = TvRat_3, US_TV_PG = TvRat_4, US_TV_14 = TvRat_5, US_TV_MA = TvRat_6, US_TV_None7 = TvRat_7 } EnTvRat_US_TV; typedef enum EnTvRat_CAE_TV { CAE_TV_Exempt = TvRat_0, CAE_TV_C = TvRat_1, CAE_TV_C8 = TvRat_2, CAE_TV_G = TvRat_3, CAE_TV_PG = TvRat_4, CAE_TV_14 = TvRat_5, CAE_TV_18 = TvRat_6, CAE_TV_Reserved = TvRat_7 } EnTvRat_CAE_TV; typedef enum EnTvRat_CAF_TV { CAF_TV_Exempt = TvRat_0, CAF_TV_G = TvRat_1, CAF_TV_8 = TvRat_2, CAF_TV_13 = TvRat_3, CAF_TV_16 = TvRat_4, CAF_TV_18 = TvRat_5, CAF_TV_Reserved6 = TvRat_6, CAF_TV_Reserved = TvRat_7 } EnTvRat_CAF_TV; typedef enum BfEnTvRat_GenericAttributes { BfAttrNone = 0, BfIsBlocked = 1, BfIsAttr_1 = 2, BfIsAttr_2 = 4, BfIsAttr_3 = 8, BfIsAttr_4 = 16, BfIsAttr_5 = 32, BfIsAttr_6 = 64, BfIsAttr_7 = 128, BfValidAttrSubmask = 255 } BfEnTvRat_GenericAttributes; typedef enum BfEnTvRat_Attributes_US_TV { US_TV_IsBlocked = BfIsBlocked, US_TV_IsViolent = BfIsAttr_1, US_TV_IsSexualSituation = BfIsAttr_2, US_TV_IsAdultLanguage = BfIsAttr_3, US_TV_IsSexuallySuggestiveDialog = BfIsAttr_4, US_TV_ValidAttrSubmask = 31 } BfEnTvRat_Attributes_US_TV; typedef enum BfEnTvRat_Attributes_MPAA { MPAA_IsBlocked = BfIsBlocked, MPAA_ValidAttrSubmask = 1 } BfEnTvRat_Attributes_MPAA; typedef enum BfEnTvRat_Attributes_CAE_TV { CAE_IsBlocked = BfIsBlocked, CAE_ValidAttrSubmask = 1 } BfEnTvRat_Attributes_CAE_TV; typedef enum BfEnTvRat_Attributes_CAF_TV { CAF_IsBlocked = BfIsBlocked, CAF_ValidAttrSubmask = 1 } BfEnTvRat_Attributes_CAF_TV; #pragma region Desktop Family #pragma endregion #pragma endregion // {C4C4C4C4-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(SID_DRMSecureServiceChannel, 0xC4C4C4C4, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C481-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(CLSID_ETFilterEncProperties, 0xC4C4C481, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C491-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(CLSID_ETFilterTagProperties, 0xC4C4C491, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {9CD31617-B303-4f96-8330-2EB173EA4DC6} DEFINE_GUID(CLSID_PTFilter, 0x9cd31617, 0xb303, 0x4f96, 0x83, 0x30, 0x2e, 0xb1, 0x73, 0xea, 0x4d, 0xc6); // {C4C4C482-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(CLSID_DTFilterEncProperties, 0xC4C4C482, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C492-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(CLSID_DTFilterTagProperties, 0xC4C4C492, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C483-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(CLSID_XDSCodecProperties, 0xC4C4C483, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C493-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(CLSID_XDSCodecTagProperties, 0xC4C4C493, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C4FC-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(CLSID_CPCAFiltersCategory, 0xC4C4C4FC, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C4E0-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(EVENTID_XDSCodecNewXDSRating, 0xC4C4C4E0, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C4DF-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(EVENTID_XDSCodecDuplicateXDSRating, 0xC4C4C4DF, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C4E1-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(EVENTID_XDSCodecNewXDSPacket, 0xC4C4C4E1, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C4E2-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(EVENTID_DTFilterRatingChange, 0xC4C4C4E2, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C4E3-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(EVENTID_DTFilterRatingsBlock, 0xC4C4C4E3, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C4E4-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(EVENTID_DTFilterRatingsUnblock, 0xC4C4C4E4, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C4E5-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(EVENTID_DTFilterXDSPacket, 0xC4C4C4E5, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C4E6-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(EVENTID_ETFilterEncryptionOn, 0xC4C4C4E6, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C4E7-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(EVENTID_ETFilterEncryptionOff, 0xC4C4C4E7, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C4E8-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(EVENTID_DTFilterCOPPUnblock, 0xC4C4C4E8, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C4E9-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(EVENTID_EncDecFilterError, 0xC4C4C4E9, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C4EA-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(EVENTID_DTFilterCOPPBlock , 0xC4C4C4EA, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C4EB-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(EVENTID_ETFilterCopyOnce, 0xC4C4C4EB, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C4F0-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(EVENTID_ETFilterCopyNever, 0xC4C4C4F0, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C4EC-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(EVENTID_DTFilterDataFormatOK, 0xC4C4C4EC, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C4ED-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(EVENTID_DTFilterDataFormatFailure, 0xC4C4C4ED, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C4EE-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(EVENTID_ETDTFilterLicenseOK, 0xC4C4C4EE, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C4EF-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(EVENTID_ETDTFilterLicenseFailure, 0xC4C4C4EF, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C4D0-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(MEDIASUBTYPE_ETDTFilter_Tagged, 0xC4C4C4D0, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {C4C4C4D1-0049-4E2B-98FB-9537F6CE516D} DEFINE_GUID(FORMATTYPE_ETDTFilter_Tagged, 0xC4C4C4D1, 0x0049, 0x4E2B, 0x98, 0xFB, 0x95, 0x37, 0xF6, 0xCE, 0x51, 0x6D); // {46adbd28-6fd0-4796-93b2-155c51dc048d} DEFINE_GUID( MEDIASUBTYPE_CPFilters_Processed, 0x46adbd28, 0x6fd0, 0x4796, 0x93, 0xb2, 0x15, 0x5c, 0x51, 0xdc, 0x4, 0x8d ); // {6739b36f-1d5f-4ac2-8192-28bb0e73d16a} DEFINE_GUID( FORMATTYPE_CPFilters_Processed, 0x6739b36f, 0x1d5f, 0x4ac2, 0x81, 0x92, 0x28, 0xbb, 0xe, 0x73, 0xd1, 0x6a ); // {4A1B465B-0FB9-4159-AFBD-E33006A0F9F4} DEFINE_GUID(EVENTID_EncDecFilterEvent, 0x4a1b465b, 0xfb9, 0x4159, 0xaf, 0xbd, 0xe3, 0x30, 0x6, 0xa0, 0xf9, 0xf4); enum FormatNotSupportedEvents { FORMATNOTSUPPORTED_CLEAR = 0, FORMATNOTSUPPORTED_NOTSUPPORTED = 1 } ; // {24B2280A-B2AA-4777-BF65-63F35E7B024A} DEFINE_GUID(EVENTID_FormatNotSupportedEvent, 0x24b2280a, 0xb2aa, 0x4777, 0xbf, 0x65, 0x63, 0xf3, 0x5e, 0x7b, 0x2, 0x4a); // {16155770-AED5-475c-BB98-95A33070DF0C} DEFINE_GUID(EVENTID_DemultiplexerFilterDiscontinuity, 0x16155770, 0xaed5, 0x475c, 0xbb, 0x98, 0x95, 0xa3, 0x30, 0x70, 0xdf, 0xc); // {40749583-6b9d-4eec-b43c-67a1801e1a9b} DEFINE_GUID( DSATTRIB_WMDRMProtectionInfo, 0x40749583, 0x6b9d, 0x4eec, 0xb4, 0x3c, 0x67, 0xa1, 0x80, 0x1e, 0x1a, 0x9b ); // {e4846dda-5838-42b4-b897-6f7e5faa2f2f} DEFINE_GUID( DSATTRIB_BadSampleInfo, 0xe4846dda, 0x5838, 0x42b4, 0xb8, 0x97, 0x6f, 0x7e, 0x5f, 0xaa, 0x2f, 0x2f ); #pragma pack(push, 1) typedef /* [public] */ struct __MIDL___MIDL_itf_encdec_0000_0000_0001 { unsigned short wszKID[ 25 ]; unsigned __int64 qwCounter; unsigned __int64 qwIndex; unsigned char bOffset; } WMDRMProtectionInfo; typedef /* [public] */ struct __MIDL___MIDL_itf_encdec_0000_0000_0002 { HRESULT hrReason; } BadSampleInfo; #pragma pack(pop) typedef LONGLONG REFERENCE_TIME; typedef LONG PackedTvRating; #pragma region Desktop Family #pragma region Desktop Family #pragma endregion typedef /* [v1_enum][uuid] */ DECLSPEC_UUID("25AEE876-3D61-4486-917E-7C0CB3D9983C") enum ProtType { PROT_COPY_FREE = 1, PROT_COPY_ONCE = 2, PROT_COPY_NEVER = 3, PROT_COPY_NEVER_REALLY = 4, PROT_COPY_NO_MORE = 5, PROT_COPY_FREE_CIT = 6, PROT_COPY_BF = 7, PROT_COPY_CN_RECORDING_STOP = 8, PROT_COPY_FREE_SECURE = 9, PROT_COPY_INVALID = 50 } ProtType; typedef /* [v1_enum] */ enum EncDecEvents { ENCDEC_CPEVENT = 0, ENCDEC_RECORDING_STATUS = ( ENCDEC_CPEVENT + 1 ) } EncDecEvents; typedef /* [v1_enum] */ enum CPRecordingStatus { RECORDING_STOPPED = 0, RECORDING_STARTED = 1 } CPRecordingStatus; typedef /* [v1_enum] */ enum CPEventBitShift { CPEVENT_BITSHIFT_RATINGS = 0, CPEVENT_BITSHIFT_COPP = ( CPEVENT_BITSHIFT_RATINGS + 1 ) , CPEVENT_BITSHIFT_LICENSE = ( CPEVENT_BITSHIFT_COPP + 1 ) , CPEVENT_BITSHIFT_ROLLBACK = ( CPEVENT_BITSHIFT_LICENSE + 1 ) , CPEVENT_BITSHIFT_SAC = ( CPEVENT_BITSHIFT_ROLLBACK + 1 ) , CPEVENT_BITSHIFT_DOWNRES = ( CPEVENT_BITSHIFT_SAC + 1 ) , CPEVENT_BITSHIFT_STUBLIB = ( CPEVENT_BITSHIFT_DOWNRES + 1 ) , CPEVENT_BITSHIFT_UNTRUSTEDGRAPH = ( CPEVENT_BITSHIFT_STUBLIB + 1 ) , CPEVENT_BITSHIFT_PENDING_CERTIFICATE = ( CPEVENT_BITSHIFT_UNTRUSTEDGRAPH + 1 ) , CPEVENT_BITSHIFT_NO_PLAYREADY = ( CPEVENT_BITSHIFT_PENDING_CERTIFICATE + 1 ) } CPEventBitShift; typedef /* [v1_enum] */ enum CPEvents { CPEVENT_NONE = 0, CPEVENT_RATINGS = ( CPEVENT_NONE + 1 ) , CPEVENT_COPP = ( CPEVENT_RATINGS + 1 ) , CPEVENT_LICENSE = ( CPEVENT_COPP + 1 ) , CPEVENT_ROLLBACK = ( CPEVENT_LICENSE + 1 ) , CPEVENT_SAC = ( CPEVENT_ROLLBACK + 1 ) , CPEVENT_DOWNRES = ( CPEVENT_SAC + 1 ) , CPEVENT_STUBLIB = ( CPEVENT_DOWNRES + 1 ) , CPEVENT_UNTRUSTEDGRAPH = ( CPEVENT_STUBLIB + 1 ) , CPEVENT_PROTECTWINDOWED = ( CPEVENT_UNTRUSTEDGRAPH + 1 ) } CPEvents; typedef /* [v1_enum] */ enum RevokedComponent { REVOKED_COPP = 0, REVOKED_SAC = ( REVOKED_COPP + 1 ) , REVOKED_APP_STUB = ( REVOKED_SAC + 1 ) , REVOKED_SECURE_PIPELINE = ( REVOKED_APP_STUB + 1 ) , REVOKED_MAX_TYPES = ( REVOKED_SECURE_PIPELINE + 1 ) } RevokedComponent; typedef /* [v1_enum] */ enum EnTag_Mode { EnTag_Remove = 0, EnTag_Once = 0x1, EnTag_Repeat = 0x2 } EnTag_Mode; typedef /* [v1_enum][uuid] */ DECLSPEC_UUID("6F8C2442-2BFB-4180-9EE5-EA1FB47AE35C") enum COPPEventBlockReason { COPP_Unknown = -1, COPP_BadDriver = 0, COPP_NoCardHDCPSupport = 1, COPP_NoMonitorHDCPSupport = 2, COPP_BadCertificate = 3, COPP_InvalidBusProtection = 4, COPP_AeroGlassOff = 5, COPP_RogueApp = 6, COPP_ForbiddenVideo = 7, COPP_Activate = 8, COPP_DigitalAudioUnprotected = 9 } COPPEventBlockReason; typedef /* [v1_enum][uuid] */ DECLSPEC_UUID("57BCA1BE-DF7A-434e-8B89-26D6A0541FDA") enum LicenseEventBlockReason { LIC_BadLicense = 0, LIC_NeedIndiv = 1, LIC_Expired = 2, LIC_NeedActivation = 3, LIC_ExtenderBlocked = 4 } LicenseEventBlockReason; typedef /* [v1_enum][uuid] */ DECLSPEC_UUID("D5CC1CDC-EF31-48dc-95B8-AFD34C08036B") enum DownResEventParam { DOWNRES_Always = 0, DOWNRES_InWindowOnly = 1, DOWNRES_Undefined = 2 } DownResEventParam; #pragma region Desktop Family #pragma endregion #pragma endregion extern RPC_IF_HANDLE __MIDL_itf_encdec_0000_0000_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_encdec_0000_0000_v0_0_s_ifspec; #ifndef __IETFilterConfig_INTERFACE_DEFINED__ #define __IETFilterConfig_INTERFACE_DEFINED__ /* interface IETFilterConfig */ /* [unique][helpstring][uuid][object][restricted] */ EXTERN_C const IID IID_IETFilterConfig; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("C4C4C4D1-0049-4E2B-98FB-9537F6CE516D") IETFilterConfig : public IUnknown { public: virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE InitLicense( /* [in] */ int LicenseId) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetSecureChannelObject( /* [out] */ __RPC__deref_out_opt IUnknown **ppUnkDRMSecureChannel) = 0; }; #else /* C style interface */ typedef struct IETFilterConfigVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IETFilterConfig * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IETFilterConfig * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IETFilterConfig * This); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *InitLicense )( __RPC__in IETFilterConfig * This, /* [in] */ int LicenseId); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetSecureChannelObject )( __RPC__in IETFilterConfig * This, /* [out] */ __RPC__deref_out_opt IUnknown **ppUnkDRMSecureChannel); END_INTERFACE } IETFilterConfigVtbl; interface IETFilterConfig { CONST_VTBL struct IETFilterConfigVtbl *lpVtbl; }; #ifdef COBJMACROS #define IETFilterConfig_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IETFilterConfig_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IETFilterConfig_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IETFilterConfig_InitLicense(This,LicenseId) \ ( (This)->lpVtbl -> InitLicense(This,LicenseId) ) #define IETFilterConfig_GetSecureChannelObject(This,ppUnkDRMSecureChannel) \ ( (This)->lpVtbl -> GetSecureChannelObject(This,ppUnkDRMSecureChannel) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IETFilterConfig_INTERFACE_DEFINED__ */ #ifndef __IDTFilterConfig_INTERFACE_DEFINED__ #define __IDTFilterConfig_INTERFACE_DEFINED__ /* interface IDTFilterConfig */ /* [unique][helpstring][uuid][object][restricted] */ EXTERN_C const IID IID_IDTFilterConfig; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("C4C4C4D2-0049-4E2B-98FB-9537F6CE516D") IDTFilterConfig : public IUnknown { public: virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetSecureChannelObject( /* [out] */ __RPC__deref_out_opt IUnknown **ppUnkDRMSecureChannel) = 0; }; #else /* C style interface */ typedef struct IDTFilterConfigVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IDTFilterConfig * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IDTFilterConfig * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IDTFilterConfig * This); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetSecureChannelObject )( __RPC__in IDTFilterConfig * This, /* [out] */ __RPC__deref_out_opt IUnknown **ppUnkDRMSecureChannel); END_INTERFACE } IDTFilterConfigVtbl; interface IDTFilterConfig { CONST_VTBL struct IDTFilterConfigVtbl *lpVtbl; }; #ifdef COBJMACROS #define IDTFilterConfig_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IDTFilterConfig_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IDTFilterConfig_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IDTFilterConfig_GetSecureChannelObject(This,ppUnkDRMSecureChannel) \ ( (This)->lpVtbl -> GetSecureChannelObject(This,ppUnkDRMSecureChannel) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IDTFilterConfig_INTERFACE_DEFINED__ */ #ifndef __IXDSCodecConfig_INTERFACE_DEFINED__ #define __IXDSCodecConfig_INTERFACE_DEFINED__ /* interface IXDSCodecConfig */ /* [unique][helpstring][uuid][object] */ EXTERN_C const IID IID_IXDSCodecConfig; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("C4C4C4D3-0049-4E2B-98FB-9537F6CE516D") IXDSCodecConfig : public IUnknown { public: virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetSecureChannelObject( /* [out] */ __RPC__deref_out_opt IUnknown **ppUnkDRMSecureChannel) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE SetPauseBufferTime( /* [in] */ DWORD dwPauseBufferTime) = 0; }; #else /* C style interface */ typedef struct IXDSCodecConfigVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IXDSCodecConfig * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IXDSCodecConfig * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IXDSCodecConfig * This); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetSecureChannelObject )( __RPC__in IXDSCodecConfig * This, /* [out] */ __RPC__deref_out_opt IUnknown **ppUnkDRMSecureChannel); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetPauseBufferTime )( __RPC__in IXDSCodecConfig * This, /* [in] */ DWORD dwPauseBufferTime); END_INTERFACE } IXDSCodecConfigVtbl; interface IXDSCodecConfig { CONST_VTBL struct IXDSCodecConfigVtbl *lpVtbl; }; #ifdef COBJMACROS #define IXDSCodecConfig_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IXDSCodecConfig_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IXDSCodecConfig_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IXDSCodecConfig_GetSecureChannelObject(This,ppUnkDRMSecureChannel) \ ( (This)->lpVtbl -> GetSecureChannelObject(This,ppUnkDRMSecureChannel) ) #define IXDSCodecConfig_SetPauseBufferTime(This,dwPauseBufferTime) \ ( (This)->lpVtbl -> SetPauseBufferTime(This,dwPauseBufferTime) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IXDSCodecConfig_INTERFACE_DEFINED__ */ #ifndef __IDTFilterLicenseRenewal_INTERFACE_DEFINED__ #define __IDTFilterLicenseRenewal_INTERFACE_DEFINED__ /* interface IDTFilterLicenseRenewal */ /* [unique][helpstring][uuid][object] */ EXTERN_C const IID IID_IDTFilterLicenseRenewal; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("8A78B317-E405-4a43-994A-620D8F5CE25E") IDTFilterLicenseRenewal : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE GetLicenseRenewalData( /* [out] */ __RPC__deref_out_opt LPWSTR *ppwszFileName, /* [out] */ __RPC__deref_out_opt LPWSTR *ppwszExpiredKid, /* [out] */ __RPC__deref_out_opt LPWSTR *ppwszTunerId) = 0; }; #else /* C style interface */ typedef struct IDTFilterLicenseRenewalVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IDTFilterLicenseRenewal * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IDTFilterLicenseRenewal * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IDTFilterLicenseRenewal * This); HRESULT ( STDMETHODCALLTYPE *GetLicenseRenewalData )( __RPC__in IDTFilterLicenseRenewal * This, /* [out] */ __RPC__deref_out_opt LPWSTR *ppwszFileName, /* [out] */ __RPC__deref_out_opt LPWSTR *ppwszExpiredKid, /* [out] */ __RPC__deref_out_opt LPWSTR *ppwszTunerId); END_INTERFACE } IDTFilterLicenseRenewalVtbl; interface IDTFilterLicenseRenewal { CONST_VTBL struct IDTFilterLicenseRenewalVtbl *lpVtbl; }; #ifdef COBJMACROS #define IDTFilterLicenseRenewal_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IDTFilterLicenseRenewal_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IDTFilterLicenseRenewal_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IDTFilterLicenseRenewal_GetLicenseRenewalData(This,ppwszFileName,ppwszExpiredKid,ppwszTunerId) \ ( (This)->lpVtbl -> GetLicenseRenewalData(This,ppwszFileName,ppwszExpiredKid,ppwszTunerId) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IDTFilterLicenseRenewal_INTERFACE_DEFINED__ */ #ifndef __IPTFilterLicenseRenewal_INTERFACE_DEFINED__ #define __IPTFilterLicenseRenewal_INTERFACE_DEFINED__ /* interface IPTFilterLicenseRenewal */ /* [unique][helpstring][uuid][object] */ EXTERN_C const IID IID_IPTFilterLicenseRenewal; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("26D836A5-0C15-44c7-AC59-B0DA8728F240") IPTFilterLicenseRenewal : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE RenewLicenses( /* [in] */ __RPC__in WCHAR *wszFileName, /* [in] */ __RPC__in WCHAR *wszExpiredKid, /* [in] */ DWORD dwCallersId, /* [in] */ BOOL bHighPriority) = 0; virtual HRESULT STDMETHODCALLTYPE CancelLicenseRenewal( void) = 0; }; #else /* C style interface */ typedef struct IPTFilterLicenseRenewalVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IPTFilterLicenseRenewal * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IPTFilterLicenseRenewal * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IPTFilterLicenseRenewal * This); HRESULT ( STDMETHODCALLTYPE *RenewLicenses )( __RPC__in IPTFilterLicenseRenewal * This, /* [in] */ __RPC__in WCHAR *wszFileName, /* [in] */ __RPC__in WCHAR *wszExpiredKid, /* [in] */ DWORD dwCallersId, /* [in] */ BOOL bHighPriority); HRESULT ( STDMETHODCALLTYPE *CancelLicenseRenewal )( __RPC__in IPTFilterLicenseRenewal * This); END_INTERFACE } IPTFilterLicenseRenewalVtbl; interface IPTFilterLicenseRenewal { CONST_VTBL struct IPTFilterLicenseRenewalVtbl *lpVtbl; }; #ifdef COBJMACROS #define IPTFilterLicenseRenewal_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IPTFilterLicenseRenewal_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IPTFilterLicenseRenewal_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IPTFilterLicenseRenewal_RenewLicenses(This,wszFileName,wszExpiredKid,dwCallersId,bHighPriority) \ ( (This)->lpVtbl -> RenewLicenses(This,wszFileName,wszExpiredKid,dwCallersId,bHighPriority) ) #define IPTFilterLicenseRenewal_CancelLicenseRenewal(This) \ ( (This)->lpVtbl -> CancelLicenseRenewal(This) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IPTFilterLicenseRenewal_INTERFACE_DEFINED__ */ #ifndef __IMceBurnerControl_INTERFACE_DEFINED__ #define __IMceBurnerControl_INTERFACE_DEFINED__ /* interface IMceBurnerControl */ /* [unique][helpstring][uuid][object] */ EXTERN_C const IID IID_IMceBurnerControl; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("5A86B91A-E71E-46c1-88A9-9BB338710552") IMceBurnerControl : public IUnknown { public: virtual HRESULT STDMETHODCALLTYPE GetBurnerNoDecryption( void) = 0; }; #else /* C style interface */ typedef struct IMceBurnerControlVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IMceBurnerControl * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IMceBurnerControl * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IMceBurnerControl * This); HRESULT ( STDMETHODCALLTYPE *GetBurnerNoDecryption )( __RPC__in IMceBurnerControl * This); END_INTERFACE } IMceBurnerControlVtbl; interface IMceBurnerControl { CONST_VTBL struct IMceBurnerControlVtbl *lpVtbl; }; #ifdef COBJMACROS #define IMceBurnerControl_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IMceBurnerControl_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IMceBurnerControl_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IMceBurnerControl_GetBurnerNoDecryption(This) \ ( (This)->lpVtbl -> GetBurnerNoDecryption(This) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IMceBurnerControl_INTERFACE_DEFINED__ */ #ifndef __EncDec_LIBRARY_DEFINED__ #define __EncDec_LIBRARY_DEFINED__ /* library EncDec */ /* [helpstring][version][uuid] */ EXTERN_C const IID LIBID_EncDec; #ifndef __IETFilter_INTERFACE_DEFINED__ #define __IETFilter_INTERFACE_DEFINED__ /* interface IETFilter */ /* [unique][helpstring][uuid][object] */ EXTERN_C const IID IID_IETFilter; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("C4C4C4B1-0049-4E2B-98FB-9537F6CE516D") IETFilter : public IUnknown { public: virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_EvalRatObjOK( /* [retval][out] */ __RPC__out HRESULT *pHrCoCreateRetVal) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetCurrRating( /* [out] */ __RPC__out EnTvRat_System *pEnSystem, /* [out] */ __RPC__out EnTvRat_GenericLevel *pEnRating, /* [out] */ __RPC__out LONG *plbfEnAttr) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetCurrLicenseExpDate( /* [in] */ __RPC__in ProtType *protType, /* [out] */ __RPC__out long *lpDateTime) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetLastErrorCode( void) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE SetRecordingOn( BOOL fRecState) = 0; }; #else /* C style interface */ typedef struct IETFilterVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IETFilter * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IETFilter * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IETFilter * This); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_EvalRatObjOK )( __RPC__in IETFilter * This, /* [retval][out] */ __RPC__out HRESULT *pHrCoCreateRetVal); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetCurrRating )( __RPC__in IETFilter * This, /* [out] */ __RPC__out EnTvRat_System *pEnSystem, /* [out] */ __RPC__out EnTvRat_GenericLevel *pEnRating, /* [out] */ __RPC__out LONG *plbfEnAttr); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetCurrLicenseExpDate )( __RPC__in IETFilter * This, /* [in] */ __RPC__in ProtType *protType, /* [out] */ __RPC__out long *lpDateTime); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetLastErrorCode )( __RPC__in IETFilter * This); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetRecordingOn )( __RPC__in IETFilter * This, BOOL fRecState); END_INTERFACE } IETFilterVtbl; interface IETFilter { CONST_VTBL struct IETFilterVtbl *lpVtbl; }; #ifdef COBJMACROS #define IETFilter_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IETFilter_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IETFilter_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IETFilter_get_EvalRatObjOK(This,pHrCoCreateRetVal) \ ( (This)->lpVtbl -> get_EvalRatObjOK(This,pHrCoCreateRetVal) ) #define IETFilter_GetCurrRating(This,pEnSystem,pEnRating,plbfEnAttr) \ ( (This)->lpVtbl -> GetCurrRating(This,pEnSystem,pEnRating,plbfEnAttr) ) #define IETFilter_GetCurrLicenseExpDate(This,protType,lpDateTime) \ ( (This)->lpVtbl -> GetCurrLicenseExpDate(This,protType,lpDateTime) ) #define IETFilter_GetLastErrorCode(This) \ ( (This)->lpVtbl -> GetLastErrorCode(This) ) #define IETFilter_SetRecordingOn(This,fRecState) \ ( (This)->lpVtbl -> SetRecordingOn(This,fRecState) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IETFilter_INTERFACE_DEFINED__ */ #ifndef __IETFilterEvents_DISPINTERFACE_DEFINED__ #define __IETFilterEvents_DISPINTERFACE_DEFINED__ /* dispinterface IETFilterEvents */ /* [helpstring][uuid] */ EXTERN_C const IID DIID_IETFilterEvents; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("C4C4C4C1-0049-4E2B-98FB-9537F6CE516D") IETFilterEvents : public IDispatch { }; #else /* C style interface */ typedef struct IETFilterEventsVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IETFilterEvents * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IETFilterEvents * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IETFilterEvents * This); HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( __RPC__in IETFilterEvents * This, /* [out] */ __RPC__out UINT *pctinfo); HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( __RPC__in IETFilterEvents * This, /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ __RPC__deref_out_opt ITypeInfo **ppTInfo); HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( __RPC__in IETFilterEvents * This, /* [in] */ __RPC__in REFIID riid, /* [size_is][in] */ __RPC__in_ecount_full(cNames) LPOLESTR *rgszNames, /* [range][in] */ __RPC__in_range(0,16384) UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ __RPC__out_ecount_full(cNames) DISPID *rgDispId); /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( IETFilterEvents * This, /* [annotation][in] */ _In_ DISPID dispIdMember, /* [annotation][in] */ _In_ REFIID riid, /* [annotation][in] */ _In_ LCID lcid, /* [annotation][in] */ _In_ WORD wFlags, /* [annotation][out][in] */ _In_ DISPPARAMS *pDispParams, /* [annotation][out] */ _Out_opt_ VARIANT *pVarResult, /* [annotation][out] */ _Out_opt_ EXCEPINFO *pExcepInfo, /* [annotation][out] */ _Out_opt_ UINT *puArgErr); END_INTERFACE } IETFilterEventsVtbl; interface IETFilterEvents { CONST_VTBL struct IETFilterEventsVtbl *lpVtbl; }; #ifdef COBJMACROS #define IETFilterEvents_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IETFilterEvents_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IETFilterEvents_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IETFilterEvents_GetTypeInfoCount(This,pctinfo) \ ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define IETFilterEvents_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define IETFilterEvents_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define IETFilterEvents_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IETFilterEvents_DISPINTERFACE_DEFINED__ */ EXTERN_C const CLSID CLSID_ETFilter; #ifdef __cplusplus class DECLSPEC_UUID("C4C4C4F1-0049-4E2B-98FB-9537F6CE516D") ETFilter; #endif #ifndef __IDTFilter_INTERFACE_DEFINED__ #define __IDTFilter_INTERFACE_DEFINED__ /* interface IDTFilter */ /* [unique][helpstring][uuid][object] */ EXTERN_C const IID IID_IDTFilter; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("C4C4C4B2-0049-4E2B-98FB-9537F6CE516D") IDTFilter : public IUnknown { public: virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_EvalRatObjOK( /* [retval][out] */ __RPC__out HRESULT *pHrCoCreateRetVal) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetCurrRating( /* [out] */ __RPC__out EnTvRat_System *pEnSystem, /* [out] */ __RPC__out EnTvRat_GenericLevel *pEnRating, /* [out] */ __RPC__out LONG *plbfEnAttr) = 0; virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_BlockedRatingAttributes( /* [in] */ EnTvRat_System enSystem, /* [in] */ EnTvRat_GenericLevel enLevel, /* [retval][out] */ __RPC__out LONG *plbfEnAttr) = 0; virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_BlockedRatingAttributes( /* [in] */ EnTvRat_System enSystem, /* [in] */ EnTvRat_GenericLevel enLevel, /* [in] */ LONG lbfAttrs) = 0; virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_BlockUnRated( /* [retval][out] */ __RPC__out BOOL *pfBlockUnRatedShows) = 0; virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_BlockUnRated( /* [in] */ BOOL fBlockUnRatedShows) = 0; virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_BlockUnRatedDelay( /* [retval][out] */ __RPC__out LONG *pmsecsDelayBeforeBlock) = 0; virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_BlockUnRatedDelay( /* [in] */ LONG msecsDelayBeforeBlock) = 0; }; #else /* C style interface */ typedef struct IDTFilterVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IDTFilter * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IDTFilter * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IDTFilter * This); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_EvalRatObjOK )( __RPC__in IDTFilter * This, /* [retval][out] */ __RPC__out HRESULT *pHrCoCreateRetVal); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetCurrRating )( __RPC__in IDTFilter * This, /* [out] */ __RPC__out EnTvRat_System *pEnSystem, /* [out] */ __RPC__out EnTvRat_GenericLevel *pEnRating, /* [out] */ __RPC__out LONG *plbfEnAttr); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_BlockedRatingAttributes )( __RPC__in IDTFilter * This, /* [in] */ EnTvRat_System enSystem, /* [in] */ EnTvRat_GenericLevel enLevel, /* [retval][out] */ __RPC__out LONG *plbfEnAttr); /* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_BlockedRatingAttributes )( __RPC__in IDTFilter * This, /* [in] */ EnTvRat_System enSystem, /* [in] */ EnTvRat_GenericLevel enLevel, /* [in] */ LONG lbfAttrs); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_BlockUnRated )( __RPC__in IDTFilter * This, /* [retval][out] */ __RPC__out BOOL *pfBlockUnRatedShows); /* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_BlockUnRated )( __RPC__in IDTFilter * This, /* [in] */ BOOL fBlockUnRatedShows); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_BlockUnRatedDelay )( __RPC__in IDTFilter * This, /* [retval][out] */ __RPC__out LONG *pmsecsDelayBeforeBlock); /* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_BlockUnRatedDelay )( __RPC__in IDTFilter * This, /* [in] */ LONG msecsDelayBeforeBlock); END_INTERFACE } IDTFilterVtbl; interface IDTFilter { CONST_VTBL struct IDTFilterVtbl *lpVtbl; }; #ifdef COBJMACROS #define IDTFilter_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IDTFilter_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IDTFilter_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IDTFilter_get_EvalRatObjOK(This,pHrCoCreateRetVal) \ ( (This)->lpVtbl -> get_EvalRatObjOK(This,pHrCoCreateRetVal) ) #define IDTFilter_GetCurrRating(This,pEnSystem,pEnRating,plbfEnAttr) \ ( (This)->lpVtbl -> GetCurrRating(This,pEnSystem,pEnRating,plbfEnAttr) ) #define IDTFilter_get_BlockedRatingAttributes(This,enSystem,enLevel,plbfEnAttr) \ ( (This)->lpVtbl -> get_BlockedRatingAttributes(This,enSystem,enLevel,plbfEnAttr) ) #define IDTFilter_put_BlockedRatingAttributes(This,enSystem,enLevel,lbfAttrs) \ ( (This)->lpVtbl -> put_BlockedRatingAttributes(This,enSystem,enLevel,lbfAttrs) ) #define IDTFilter_get_BlockUnRated(This,pfBlockUnRatedShows) \ ( (This)->lpVtbl -> get_BlockUnRated(This,pfBlockUnRatedShows) ) #define IDTFilter_put_BlockUnRated(This,fBlockUnRatedShows) \ ( (This)->lpVtbl -> put_BlockUnRated(This,fBlockUnRatedShows) ) #define IDTFilter_get_BlockUnRatedDelay(This,pmsecsDelayBeforeBlock) \ ( (This)->lpVtbl -> get_BlockUnRatedDelay(This,pmsecsDelayBeforeBlock) ) #define IDTFilter_put_BlockUnRatedDelay(This,msecsDelayBeforeBlock) \ ( (This)->lpVtbl -> put_BlockUnRatedDelay(This,msecsDelayBeforeBlock) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IDTFilter_INTERFACE_DEFINED__ */ #ifndef __IDTFilter2_INTERFACE_DEFINED__ #define __IDTFilter2_INTERFACE_DEFINED__ /* interface IDTFilter2 */ /* [unique][helpstring][uuid][object] */ EXTERN_C const IID IID_IDTFilter2; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("C4C4C4B4-0049-4E2B-98FB-9537F6CE516D") IDTFilter2 : public IDTFilter { public: virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_ChallengeUrl( /* [out] */ __RPC__deref_out_opt BSTR *pbstrChallengeUrl) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetCurrLicenseExpDate( /* [in] */ __RPC__in ProtType *protType, /* [out] */ __RPC__out long *lpDateTime) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetLastErrorCode( void) = 0; }; #else /* C style interface */ typedef struct IDTFilter2Vtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IDTFilter2 * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IDTFilter2 * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IDTFilter2 * This); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_EvalRatObjOK )( __RPC__in IDTFilter2 * This, /* [retval][out] */ __RPC__out HRESULT *pHrCoCreateRetVal); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetCurrRating )( __RPC__in IDTFilter2 * This, /* [out] */ __RPC__out EnTvRat_System *pEnSystem, /* [out] */ __RPC__out EnTvRat_GenericLevel *pEnRating, /* [out] */ __RPC__out LONG *plbfEnAttr); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_BlockedRatingAttributes )( __RPC__in IDTFilter2 * This, /* [in] */ EnTvRat_System enSystem, /* [in] */ EnTvRat_GenericLevel enLevel, /* [retval][out] */ __RPC__out LONG *plbfEnAttr); /* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_BlockedRatingAttributes )( __RPC__in IDTFilter2 * This, /* [in] */ EnTvRat_System enSystem, /* [in] */ EnTvRat_GenericLevel enLevel, /* [in] */ LONG lbfAttrs); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_BlockUnRated )( __RPC__in IDTFilter2 * This, /* [retval][out] */ __RPC__out BOOL *pfBlockUnRatedShows); /* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_BlockUnRated )( __RPC__in IDTFilter2 * This, /* [in] */ BOOL fBlockUnRatedShows); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_BlockUnRatedDelay )( __RPC__in IDTFilter2 * This, /* [retval][out] */ __RPC__out LONG *pmsecsDelayBeforeBlock); /* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_BlockUnRatedDelay )( __RPC__in IDTFilter2 * This, /* [in] */ LONG msecsDelayBeforeBlock); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_ChallengeUrl )( __RPC__in IDTFilter2 * This, /* [out] */ __RPC__deref_out_opt BSTR *pbstrChallengeUrl); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetCurrLicenseExpDate )( __RPC__in IDTFilter2 * This, /* [in] */ __RPC__in ProtType *protType, /* [out] */ __RPC__out long *lpDateTime); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetLastErrorCode )( __RPC__in IDTFilter2 * This); END_INTERFACE } IDTFilter2Vtbl; interface IDTFilter2 { CONST_VTBL struct IDTFilter2Vtbl *lpVtbl; }; #ifdef COBJMACROS #define IDTFilter2_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IDTFilter2_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IDTFilter2_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IDTFilter2_get_EvalRatObjOK(This,pHrCoCreateRetVal) \ ( (This)->lpVtbl -> get_EvalRatObjOK(This,pHrCoCreateRetVal) ) #define IDTFilter2_GetCurrRating(This,pEnSystem,pEnRating,plbfEnAttr) \ ( (This)->lpVtbl -> GetCurrRating(This,pEnSystem,pEnRating,plbfEnAttr) ) #define IDTFilter2_get_BlockedRatingAttributes(This,enSystem,enLevel,plbfEnAttr) \ ( (This)->lpVtbl -> get_BlockedRatingAttributes(This,enSystem,enLevel,plbfEnAttr) ) #define IDTFilter2_put_BlockedRatingAttributes(This,enSystem,enLevel,lbfAttrs) \ ( (This)->lpVtbl -> put_BlockedRatingAttributes(This,enSystem,enLevel,lbfAttrs) ) #define IDTFilter2_get_BlockUnRated(This,pfBlockUnRatedShows) \ ( (This)->lpVtbl -> get_BlockUnRated(This,pfBlockUnRatedShows) ) #define IDTFilter2_put_BlockUnRated(This,fBlockUnRatedShows) \ ( (This)->lpVtbl -> put_BlockUnRated(This,fBlockUnRatedShows) ) #define IDTFilter2_get_BlockUnRatedDelay(This,pmsecsDelayBeforeBlock) \ ( (This)->lpVtbl -> get_BlockUnRatedDelay(This,pmsecsDelayBeforeBlock) ) #define IDTFilter2_put_BlockUnRatedDelay(This,msecsDelayBeforeBlock) \ ( (This)->lpVtbl -> put_BlockUnRatedDelay(This,msecsDelayBeforeBlock) ) #define IDTFilter2_get_ChallengeUrl(This,pbstrChallengeUrl) \ ( (This)->lpVtbl -> get_ChallengeUrl(This,pbstrChallengeUrl) ) #define IDTFilter2_GetCurrLicenseExpDate(This,protType,lpDateTime) \ ( (This)->lpVtbl -> GetCurrLicenseExpDate(This,protType,lpDateTime) ) #define IDTFilter2_GetLastErrorCode(This) \ ( (This)->lpVtbl -> GetLastErrorCode(This) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IDTFilter2_INTERFACE_DEFINED__ */ #ifndef __IDTFilter3_INTERFACE_DEFINED__ #define __IDTFilter3_INTERFACE_DEFINED__ /* interface IDTFilter3 */ /* [unique][helpstring][uuid][object] */ EXTERN_C const IID IID_IDTFilter3; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("513998cc-e929-4cdf-9fbd-bad1e0314866") IDTFilter3 : public IDTFilter2 { public: virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetProtectionType( /* [out] */ __RPC__out ProtType *pProtectionType) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE LicenseHasExpirationDate( /* [out] */ __RPC__out BOOL *pfLicenseHasExpirationDate) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE SetRights( /* [in] */ __RPC__in BSTR bstrRights) = 0; }; #else /* C style interface */ typedef struct IDTFilter3Vtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IDTFilter3 * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IDTFilter3 * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IDTFilter3 * This); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_EvalRatObjOK )( __RPC__in IDTFilter3 * This, /* [retval][out] */ __RPC__out HRESULT *pHrCoCreateRetVal); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetCurrRating )( __RPC__in IDTFilter3 * This, /* [out] */ __RPC__out EnTvRat_System *pEnSystem, /* [out] */ __RPC__out EnTvRat_GenericLevel *pEnRating, /* [out] */ __RPC__out LONG *plbfEnAttr); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_BlockedRatingAttributes )( __RPC__in IDTFilter3 * This, /* [in] */ EnTvRat_System enSystem, /* [in] */ EnTvRat_GenericLevel enLevel, /* [retval][out] */ __RPC__out LONG *plbfEnAttr); /* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_BlockedRatingAttributes )( __RPC__in IDTFilter3 * This, /* [in] */ EnTvRat_System enSystem, /* [in] */ EnTvRat_GenericLevel enLevel, /* [in] */ LONG lbfAttrs); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_BlockUnRated )( __RPC__in IDTFilter3 * This, /* [retval][out] */ __RPC__out BOOL *pfBlockUnRatedShows); /* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_BlockUnRated )( __RPC__in IDTFilter3 * This, /* [in] */ BOOL fBlockUnRatedShows); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_BlockUnRatedDelay )( __RPC__in IDTFilter3 * This, /* [retval][out] */ __RPC__out LONG *pmsecsDelayBeforeBlock); /* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_BlockUnRatedDelay )( __RPC__in IDTFilter3 * This, /* [in] */ LONG msecsDelayBeforeBlock); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_ChallengeUrl )( __RPC__in IDTFilter3 * This, /* [out] */ __RPC__deref_out_opt BSTR *pbstrChallengeUrl); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetCurrLicenseExpDate )( __RPC__in IDTFilter3 * This, /* [in] */ __RPC__in ProtType *protType, /* [out] */ __RPC__out long *lpDateTime); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetLastErrorCode )( __RPC__in IDTFilter3 * This); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetProtectionType )( __RPC__in IDTFilter3 * This, /* [out] */ __RPC__out ProtType *pProtectionType); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *LicenseHasExpirationDate )( __RPC__in IDTFilter3 * This, /* [out] */ __RPC__out BOOL *pfLicenseHasExpirationDate); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetRights )( __RPC__in IDTFilter3 * This, /* [in] */ __RPC__in BSTR bstrRights); END_INTERFACE } IDTFilter3Vtbl; interface IDTFilter3 { CONST_VTBL struct IDTFilter3Vtbl *lpVtbl; }; #ifdef COBJMACROS #define IDTFilter3_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IDTFilter3_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IDTFilter3_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IDTFilter3_get_EvalRatObjOK(This,pHrCoCreateRetVal) \ ( (This)->lpVtbl -> get_EvalRatObjOK(This,pHrCoCreateRetVal) ) #define IDTFilter3_GetCurrRating(This,pEnSystem,pEnRating,plbfEnAttr) \ ( (This)->lpVtbl -> GetCurrRating(This,pEnSystem,pEnRating,plbfEnAttr) ) #define IDTFilter3_get_BlockedRatingAttributes(This,enSystem,enLevel,plbfEnAttr) \ ( (This)->lpVtbl -> get_BlockedRatingAttributes(This,enSystem,enLevel,plbfEnAttr) ) #define IDTFilter3_put_BlockedRatingAttributes(This,enSystem,enLevel,lbfAttrs) \ ( (This)->lpVtbl -> put_BlockedRatingAttributes(This,enSystem,enLevel,lbfAttrs) ) #define IDTFilter3_get_BlockUnRated(This,pfBlockUnRatedShows) \ ( (This)->lpVtbl -> get_BlockUnRated(This,pfBlockUnRatedShows) ) #define IDTFilter3_put_BlockUnRated(This,fBlockUnRatedShows) \ ( (This)->lpVtbl -> put_BlockUnRated(This,fBlockUnRatedShows) ) #define IDTFilter3_get_BlockUnRatedDelay(This,pmsecsDelayBeforeBlock) \ ( (This)->lpVtbl -> get_BlockUnRatedDelay(This,pmsecsDelayBeforeBlock) ) #define IDTFilter3_put_BlockUnRatedDelay(This,msecsDelayBeforeBlock) \ ( (This)->lpVtbl -> put_BlockUnRatedDelay(This,msecsDelayBeforeBlock) ) #define IDTFilter3_get_ChallengeUrl(This,pbstrChallengeUrl) \ ( (This)->lpVtbl -> get_ChallengeUrl(This,pbstrChallengeUrl) ) #define IDTFilter3_GetCurrLicenseExpDate(This,protType,lpDateTime) \ ( (This)->lpVtbl -> GetCurrLicenseExpDate(This,protType,lpDateTime) ) #define IDTFilter3_GetLastErrorCode(This) \ ( (This)->lpVtbl -> GetLastErrorCode(This) ) #define IDTFilter3_GetProtectionType(This,pProtectionType) \ ( (This)->lpVtbl -> GetProtectionType(This,pProtectionType) ) #define IDTFilter3_LicenseHasExpirationDate(This,pfLicenseHasExpirationDate) \ ( (This)->lpVtbl -> LicenseHasExpirationDate(This,pfLicenseHasExpirationDate) ) #define IDTFilter3_SetRights(This,bstrRights) \ ( (This)->lpVtbl -> SetRights(This,bstrRights) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IDTFilter3_INTERFACE_DEFINED__ */ #ifndef __IDTFilterEvents_DISPINTERFACE_DEFINED__ #define __IDTFilterEvents_DISPINTERFACE_DEFINED__ /* dispinterface IDTFilterEvents */ /* [helpstring][uuid] */ EXTERN_C const IID DIID_IDTFilterEvents; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("C4C4C4C2-0049-4E2B-98FB-9537F6CE516D") IDTFilterEvents : public IDispatch { }; #else /* C style interface */ typedef struct IDTFilterEventsVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IDTFilterEvents * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IDTFilterEvents * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IDTFilterEvents * This); HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( __RPC__in IDTFilterEvents * This, /* [out] */ __RPC__out UINT *pctinfo); HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( __RPC__in IDTFilterEvents * This, /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ __RPC__deref_out_opt ITypeInfo **ppTInfo); HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( __RPC__in IDTFilterEvents * This, /* [in] */ __RPC__in REFIID riid, /* [size_is][in] */ __RPC__in_ecount_full(cNames) LPOLESTR *rgszNames, /* [range][in] */ __RPC__in_range(0,16384) UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ __RPC__out_ecount_full(cNames) DISPID *rgDispId); /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( IDTFilterEvents * This, /* [annotation][in] */ _In_ DISPID dispIdMember, /* [annotation][in] */ _In_ REFIID riid, /* [annotation][in] */ _In_ LCID lcid, /* [annotation][in] */ _In_ WORD wFlags, /* [annotation][out][in] */ _In_ DISPPARAMS *pDispParams, /* [annotation][out] */ _Out_opt_ VARIANT *pVarResult, /* [annotation][out] */ _Out_opt_ EXCEPINFO *pExcepInfo, /* [annotation][out] */ _Out_opt_ UINT *puArgErr); END_INTERFACE } IDTFilterEventsVtbl; interface IDTFilterEvents { CONST_VTBL struct IDTFilterEventsVtbl *lpVtbl; }; #ifdef COBJMACROS #define IDTFilterEvents_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IDTFilterEvents_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IDTFilterEvents_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IDTFilterEvents_GetTypeInfoCount(This,pctinfo) \ ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define IDTFilterEvents_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define IDTFilterEvents_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define IDTFilterEvents_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IDTFilterEvents_DISPINTERFACE_DEFINED__ */ EXTERN_C const CLSID CLSID_DTFilter; #ifdef __cplusplus class DECLSPEC_UUID("C4C4C4F2-0049-4E2B-98FB-9537F6CE516D") DTFilter; #endif #ifndef __IXDSCodec_INTERFACE_DEFINED__ #define __IXDSCodec_INTERFACE_DEFINED__ /* interface IXDSCodec */ /* [unique][helpstring][uuid][object] */ EXTERN_C const IID IID_IXDSCodec; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("C4C4C4B3-0049-4E2B-98FB-9537F6CE516D") IXDSCodec : public IUnknown { public: virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_XDSToRatObjOK( /* [retval][out] */ __RPC__out HRESULT *pHrCoCreateRetVal) = 0; virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_CCSubstreamService( /* [in] */ long SubstreamMask) = 0; virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_CCSubstreamService( /* [retval][out] */ __RPC__out long *pSubstreamMask) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetContentAdvisoryRating( /* [out] */ __RPC__out PackedTvRating *pRat, /* [out] */ __RPC__out long *pPktSeqID, /* [out] */ __RPC__out long *pCallSeqID, /* [out] */ __RPC__out REFERENCE_TIME *pTimeStart, /* [out] */ __RPC__out REFERENCE_TIME *pTimeEnd) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetXDSPacket( /* [out] */ __RPC__out long *pXDSClassPkt, /* [out] */ __RPC__out long *pXDSTypePkt, /* [out] */ __RPC__deref_out_opt BSTR *pBstrXDSPkt, /* [out] */ __RPC__out long *pPktSeqID, /* [out] */ __RPC__out long *pCallSeqID, /* [out] */ __RPC__out REFERENCE_TIME *pTimeStart, /* [out] */ __RPC__out REFERENCE_TIME *pTimeEnd) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetCurrLicenseExpDate( /* [in] */ __RPC__in ProtType *protType, /* [out] */ __RPC__out long *lpDateTime) = 0; virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetLastErrorCode( void) = 0; }; #else /* C style interface */ typedef struct IXDSCodecVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IXDSCodec * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IXDSCodec * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IXDSCodec * This); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_XDSToRatObjOK )( __RPC__in IXDSCodec * This, /* [retval][out] */ __RPC__out HRESULT *pHrCoCreateRetVal); /* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_CCSubstreamService )( __RPC__in IXDSCodec * This, /* [in] */ long SubstreamMask); /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_CCSubstreamService )( __RPC__in IXDSCodec * This, /* [retval][out] */ __RPC__out long *pSubstreamMask); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetContentAdvisoryRating )( __RPC__in IXDSCodec * This, /* [out] */ __RPC__out PackedTvRating *pRat, /* [out] */ __RPC__out long *pPktSeqID, /* [out] */ __RPC__out long *pCallSeqID, /* [out] */ __RPC__out REFERENCE_TIME *pTimeStart, /* [out] */ __RPC__out REFERENCE_TIME *pTimeEnd); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetXDSPacket )( __RPC__in IXDSCodec * This, /* [out] */ __RPC__out long *pXDSClassPkt, /* [out] */ __RPC__out long *pXDSTypePkt, /* [out] */ __RPC__deref_out_opt BSTR *pBstrXDSPkt, /* [out] */ __RPC__out long *pPktSeqID, /* [out] */ __RPC__out long *pCallSeqID, /* [out] */ __RPC__out REFERENCE_TIME *pTimeStart, /* [out] */ __RPC__out REFERENCE_TIME *pTimeEnd); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetCurrLicenseExpDate )( __RPC__in IXDSCodec * This, /* [in] */ __RPC__in ProtType *protType, /* [out] */ __RPC__out long *lpDateTime); /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetLastErrorCode )( __RPC__in IXDSCodec * This); END_INTERFACE } IXDSCodecVtbl; interface IXDSCodec { CONST_VTBL struct IXDSCodecVtbl *lpVtbl; }; #ifdef COBJMACROS #define IXDSCodec_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IXDSCodec_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IXDSCodec_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IXDSCodec_get_XDSToRatObjOK(This,pHrCoCreateRetVal) \ ( (This)->lpVtbl -> get_XDSToRatObjOK(This,pHrCoCreateRetVal) ) #define IXDSCodec_put_CCSubstreamService(This,SubstreamMask) \ ( (This)->lpVtbl -> put_CCSubstreamService(This,SubstreamMask) ) #define IXDSCodec_get_CCSubstreamService(This,pSubstreamMask) \ ( (This)->lpVtbl -> get_CCSubstreamService(This,pSubstreamMask) ) #define IXDSCodec_GetContentAdvisoryRating(This,pRat,pPktSeqID,pCallSeqID,pTimeStart,pTimeEnd) \ ( (This)->lpVtbl -> GetContentAdvisoryRating(This,pRat,pPktSeqID,pCallSeqID,pTimeStart,pTimeEnd) ) #define IXDSCodec_GetXDSPacket(This,pXDSClassPkt,pXDSTypePkt,pBstrXDSPkt,pPktSeqID,pCallSeqID,pTimeStart,pTimeEnd) \ ( (This)->lpVtbl -> GetXDSPacket(This,pXDSClassPkt,pXDSTypePkt,pBstrXDSPkt,pPktSeqID,pCallSeqID,pTimeStart,pTimeEnd) ) #define IXDSCodec_GetCurrLicenseExpDate(This,protType,lpDateTime) \ ( (This)->lpVtbl -> GetCurrLicenseExpDate(This,protType,lpDateTime) ) #define IXDSCodec_GetLastErrorCode(This) \ ( (This)->lpVtbl -> GetLastErrorCode(This) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IXDSCodec_INTERFACE_DEFINED__ */ #ifndef __IXDSCodecEvents_DISPINTERFACE_DEFINED__ #define __IXDSCodecEvents_DISPINTERFACE_DEFINED__ /* dispinterface IXDSCodecEvents */ /* [helpstring][uuid] */ EXTERN_C const IID DIID_IXDSCodecEvents; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("C4C4C4C3-0049-4E2B-98FB-9537F6CE516D") IXDSCodecEvents : public IDispatch { }; #else /* C style interface */ typedef struct IXDSCodecEventsVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( __RPC__in IXDSCodecEvents * This, /* [in] */ __RPC__in REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( __RPC__in IXDSCodecEvents * This); ULONG ( STDMETHODCALLTYPE *Release )( __RPC__in IXDSCodecEvents * This); HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( __RPC__in IXDSCodecEvents * This, /* [out] */ __RPC__out UINT *pctinfo); HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( __RPC__in IXDSCodecEvents * This, /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ __RPC__deref_out_opt ITypeInfo **ppTInfo); HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( __RPC__in IXDSCodecEvents * This, /* [in] */ __RPC__in REFIID riid, /* [size_is][in] */ __RPC__in_ecount_full(cNames) LPOLESTR *rgszNames, /* [range][in] */ __RPC__in_range(0,16384) UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ __RPC__out_ecount_full(cNames) DISPID *rgDispId); /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( IXDSCodecEvents * This, /* [annotation][in] */ _In_ DISPID dispIdMember, /* [annotation][in] */ _In_ REFIID riid, /* [annotation][in] */ _In_ LCID lcid, /* [annotation][in] */ _In_ WORD wFlags, /* [annotation][out][in] */ _In_ DISPPARAMS *pDispParams, /* [annotation][out] */ _Out_opt_ VARIANT *pVarResult, /* [annotation][out] */ _Out_opt_ EXCEPINFO *pExcepInfo, /* [annotation][out] */ _Out_opt_ UINT *puArgErr); END_INTERFACE } IXDSCodecEventsVtbl; interface IXDSCodecEvents { CONST_VTBL struct IXDSCodecEventsVtbl *lpVtbl; }; #ifdef COBJMACROS #define IXDSCodecEvents_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IXDSCodecEvents_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IXDSCodecEvents_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IXDSCodecEvents_GetTypeInfoCount(This,pctinfo) \ ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define IXDSCodecEvents_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define IXDSCodecEvents_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define IXDSCodecEvents_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IXDSCodecEvents_DISPINTERFACE_DEFINED__ */ EXTERN_C const CLSID CLSID_XDSCodec; #ifdef __cplusplus class DECLSPEC_UUID("C4C4C4F3-0049-4E2B-98FB-9537F6CE516D") XDSCodec; #endif EXTERN_C const CLSID CLSID_CXDSData; #ifdef __cplusplus class DECLSPEC_UUID("C4C4C4F4-0049-4E2B-98FB-9537F6CE516D") CXDSData; #endif #endif /* __EncDec_LIBRARY_DEFINED__ */ /* interface __MIDL_itf_encdec_0000_0007 */ /* [local] */ #endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) */ #pragma endregion extern RPC_IF_HANDLE __MIDL_itf_encdec_0000_0007_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_encdec_0000_0007_v0_0_s_ifspec; /* Additional Prototypes for ALL interfaces */ /* end of Additional Prototypes */ #ifdef __cplusplus } #endif #endif
[ "akashche@redhat.com" ]
akashche@redhat.com
7736b7bda61ef2cd64366bec8116b6ca0efba1e4
b2a1312f9cb13a84de95e34183dd67b0116e9bf9
/src/components.cpp
6824c5997bb5c07fd24a21c3c9712fadad51541e
[]
no_license
rpoisel/esp8266-pir-mqtt
4127618f4dd3a02ba9461c926e66a7ac2a12a936
55983043921a11083a408df98cac622db40ca68a
refs/heads/master
2021-06-22T15:57:41.521243
2020-12-13T15:54:37
2020-12-13T17:36:04
155,123,071
1
0
null
null
null
null
UTF-8
C++
false
false
75
cpp
#include "components.h" namespace Components { } // namespace Components
[ "rainer.poisel@gmail.com" ]
rainer.poisel@gmail.com
fae90d251fcefac3db89d8d69b84ba05a7255dd8
35f322c6a61a1bf1bc4bd69559ac73100f3f8ea3
/ComplexNumbers/ComplexClass.cpp
4a820c9138ec84feba104d9b0420a4fe236ed294
[]
no_license
abelzis/-Complex-Number-Class
3a0266cd3ba506aa2a02f1e51524d406e33b325d
374df754fb6a3d11d6478c5e8667922f52791162
refs/heads/master
2020-05-07T17:16:07.498065
2019-04-11T05:43:19
2019-04-11T05:43:19
180,722,167
0
0
null
null
null
null
UTF-8
C++
false
false
1,395
cpp
#include "ComplexClass.h" Complex Complex::operator+=(const Complex& a) { re_ += a.re_; im_ += a.im_; return *this; } Complex Complex::operator-=(const Complex& a) { re_ -= a.re_; im_ -= a.im_; return *this; } Complex& Complex::operator*=(const Complex& a) { double temp_re, temp_im; temp_re = (this->re_ * a.re_) - (this->im_ * a.im_); temp_im = (this->re_ * a.im_) + (this->im_ * a.re_); this->re_ = temp_re; this->im_ = temp_im; return *this; } Complex& Complex::operator/=(const Complex& a) { double temp_re, temp_im; temp_re = ((this->re_ * a.re_) + (this->im_ * a.im_)) / (a.re_*a.re_ + a.im_*a.im_); temp_im = ((this->im_ * a.re_) - (this->re_ * a.im_)) / (a.re_*a.re_ + a.im_*a.im_); this->re_ = temp_re; this->im_ = temp_im; return *this; } std::ostream& operator<<(std::ostream& out, const Complex& a) { if (a.im_ > 0 && a.re_ != 0) out << a.re_ << " + " << a.im_ << "i"; if (a.im_ < 0 && a.re_ != 0) out << a.re_ << " - " << abs(a.im_) << "i"; if (a.im_ == 0 && a.re_ != 0) out << a.re_; if (a.re_ == 0 && a.im_ != 0) out << a.im_ << "i"; if (a.re_ == 0 && a.im_ == 0) out << 0; return out; } std::istream& operator>>(std::istream & in, Complex & a) { std::cout << "Please input real value: "; in >> a.re_; std::cout << "Please input imaginary value: "; in >> a.im_; return in; }
[ "noreply@github.com" ]
noreply@github.com
abde02069c77c16515cce5666f599e980bab2d0b
5f58803edab530bc585e2b3a6d5d877e1e4215dc
/MonopolAdventureEditor/dialogEdition/widgetsEditeurs/LoyerServiceEditWidget.cpp
f1da2caf3022b25e9f58ffef5881795827793db4
[]
no_license
Vinorcola/MonopolAdventure
b96ae259a644498fb89969facd01b142121f66f6
7a15358fdaa261ec718f470a81b9b40307f6fcec
HEAD
2016-09-06T03:26:09.768549
2013-09-08T18:36:53
2013-09-08T18:36:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,196
cpp
#include "LoyerServiceEditWidget.hpp" LoyerServiceEditWidget::LoyerServiceEditWidget(Service* const service, const int nombreServices) : SauvegardeInterface(), m_service(service), m_champsLoyer() { /* Configuration des champs. */ for (int i(1); i <= nombreServices; ++i) { QSpinBox* champ(new QSpinBox); champ->setSingleStep(10); champ->setMaximum(MONTANT_MAX_EDITEUR); champ->setValue(service->getLoyer(i)); m_champsLoyer.append(champ); } /* Mise en forme du widget. */ QFormLayout* layout = new QFormLayout; layout->addRow(tr("Loyer si le propriétaire ne possède que ce service"), m_champsLoyer.first()); for (int i(1); i < nombreServices; ++i) { layout->addRow(tr("Loyer si le propriétaire possède") + " " + QString::number(i + 1) + " " + tr("services"), m_champsLoyer.at(i)); } setLayout(layout); } void LoyerServiceEditWidget::sauvegarde() { for (int i(0), iEnd(m_champsLoyer.count()); i < iEnd; ++i) { m_service->editLoyer(i + 1, m_champsLoyer.at(i)->value()); } }
[ "vinorcola@gmail.com" ]
vinorcola@gmail.com
aa6b1479c221a5b45d2cea4c7305326fcc1cbc89
b1fd9ac117297e23595ec878a017eef7a4b93cdb
/Graph/Shortest Path/Dijkstra/P4779_Dijkstra_STL.cpp
9d87392a36d7ef2f0339caec3359321baed3e268
[]
no_license
beliefy/luogu
298f3d9c617d7d01ae803642c3f1c7af76af51df
4f4a1ae4454ccfb065e94bfb2d929ecc68416f62
refs/heads/master
2022-12-16T13:13:15.712644
2020-08-28T02:50:37
2020-08-28T02:50:37
287,544,050
0
0
null
null
null
null
UTF-8
C++
false
false
1,159
cpp
#include <bits/stdc++.h> #define N 100001 #define M 200001 #define INF 0x7fffffff using namespace std; int n, m, s, head[N], to[M], w[M], nxt[M], dis[N], cnt; bool visit[N]; struct da { int u, s; bool operator<(const da &a) const { return s > a.s; } } now; priority_queue<da> q; void adde(int u, int v, int wi) { cnt++; to[cnt] = v; w[cnt] = wi; nxt[cnt] = head[u]; head[u] = cnt; } void dijkstra() { memset(dis, 127, sizeof(dis)); q.push((da){s, 0}); while (!q.empty()) { now = q.top(); q.pop(); if (visit[now.u]) continue; visit[now.u] = true; dis[now.u] = now.s; for (int i = head[now.u]; i; i = nxt[i]) { if (!visit[to[i]] && now.s + w[i] < dis[to[i]]) { q.push((da){to[i], now.s + w[i]}); } } } } int main() { cin >> n >> m >> s; for (int i = 1; i <= m; i++) { int u, v, w; cin >> u >> v >> w; adde(u, v, w); } dijkstra(); for (int i = 1; i <= n; i++) { cout << dis[i] << " "; } return 0; }
[ "2464304829@qq.com" ]
2464304829@qq.com
86c69b3e8c0b9c4d9ffa1129550c3d4208a0194f
0ca1306b1872037d406a553ddda682d006b50189
/src/qt/privacydialog.cpp
6f5717de6fdce463c4341a4ff4ab6840e7c2fdc0
[ "MIT" ]
permissive
SubmanjiLabs/AGORACoin
595073363bccd89c6de8969c269173c416ffddf7
e91ebea154092baf152f278cd54e2f5545128371
refs/heads/master
2020-06-19T02:50:48.260419
2019-07-11T19:54:15
2019-07-11T19:54:15
196,538,219
0
0
null
2019-07-12T08:15:09
2019-07-12T08:15:08
null
UTF-8
C++
false
false
34,989
cpp
// Copyright (c) 2017-2018 The PIVX developers // Copyright (c) 2019 The AGORA developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "privacydialog.h" #include "ui_privacydialog.h" #include "addressbookpage.h" #include "addresstablemodel.h" #include "bitcoinunits.h" #include "coincontroldialog.h" #include "libzerocoin/Denominations.h" #include "optionsmodel.h" #include "sendcoinsentry.h" #include "walletmodel.h" #include "coincontrol.h" #include "zagorcontroldialog.h" #include "spork.h" #include "askpassphrasedialog.h" #include <QClipboard> #include <QSettings> #include <utilmoneystr.h> #include <QtWidgets> #include <primitives/deterministicmint.h> #include <accumulators.h> PrivacyDialog::PrivacyDialog(QWidget* parent) : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint | Qt::WindowCloseButtonHint), ui(new Ui::PrivacyDialog), walletModel(0), currentBalance(-1), fDenomsMinimized(true) { nDisplayUnit = 0; // just make sure it's not unitialized ui->setupUi(this); // "Spending 999999 zAGOR ought to be enough for anybody." - Bill Gates, 2017 ui->zAGORpayAmount->setValidator( new QDoubleValidator(0.0, 21000000.0, 20, this) ); ui->labelMintAmountValue->setValidator( new QIntValidator(0, 999999, this) ); // Default texts for (mini-) coincontrol ui->labelCoinControlQuantity->setText (tr("Coins automatically selected")); ui->labelCoinControlAmount->setText (tr("Coins automatically selected")); ui->labelzAGORSyncStatus->setText("(" + tr("out of sync") + ")"); // Sunken frame for minting messages ui->TEMintStatus->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken); ui->TEMintStatus->setLineWidth (2); ui->TEMintStatus->setMidLineWidth (2); ui->TEMintStatus->setPlainText(tr("Mint Status: Okay")); // Coin Control signals connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked())); // Coin Control: clipboard actions QAction* clipboardQuantityAction = new QAction(tr("Copy quantity"), this); QAction* clipboardAmountAction = new QAction(tr("Copy amount"), this); connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity())); connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount())); ui->labelCoinControlQuantity->addAction(clipboardQuantityAction); ui->labelCoinControlAmount->addAction(clipboardAmountAction); // Denomination labels ui->labelzDenom1Text->setText(tr("Denom. with value <b>1</b>:")); ui->labelzDenom2Text->setText(tr("Denom. with value <b>5</b>:")); ui->labelzDenom3Text->setText(tr("Denom. with value <b>10</b>:")); ui->labelzDenom4Text->setText(tr("Denom. with value <b>50</b>:")); ui->labelzDenom5Text->setText(tr("Denom. with value <b>100</b>:")); ui->labelzDenom6Text->setText(tr("Denom. with value <b>500</b>:")); ui->labelzDenom7Text->setText(tr("Denom. with value <b>1000</b>:")); ui->labelzDenom8Text->setText(tr("Denom. with value <b>5000</b>:")); // AutoMint status ui->label_AutoMintStatus->setText(tr("AutoMint Status:")); // Global Supply labels ui->labelZsupplyText1->setText(tr("Denom. <b>1</b>:")); ui->labelZsupplyText5->setText(tr("Denom. <b>5</b>:")); ui->labelZsupplyText10->setText(tr("Denom. <b>10</b>:")); ui->labelZsupplyText50->setText(tr("Denom. <b>50</b>:")); ui->labelZsupplyText100->setText(tr("Denom. <b>100</b>:")); ui->labelZsupplyText500->setText(tr("Denom. <b>500</b>:")); ui->labelZsupplyText1000->setText(tr("Denom. <b>1000</b>:")); ui->labelZsupplyText5000->setText(tr("Denom. <b>5000</b>:")); // AGORA settings QSettings settings; if (!settings.contains("nSecurityLevel")){ nSecurityLevel = 42; settings.setValue("nSecurityLevel", nSecurityLevel); } else{ nSecurityLevel = settings.value("nSecurityLevel").toInt(); } if (!settings.contains("fMinimizeChange")){ fMinimizeChange = false; settings.setValue("fMinimizeChange", fMinimizeChange); } else{ fMinimizeChange = settings.value("fMinimizeChange").toBool(); } ui->checkBoxMinimizeChange->setChecked(fMinimizeChange); // Start with displaying the "out of sync" warnings showOutOfSyncWarning(true); // Hide those placeholder elements needed for CoinControl interaction ui->WarningLabel->hide(); // Explanatory text visible in QT-Creator ui->dummyHideWidget->hide(); // Dummy widget with elements to hide // Set labels/buttons depending on SPORK_16 status updateSPORK16Status(); // init Denoms section if(!settings.contains("fDenomsSectionMinimized")) settings.setValue("fDenomsSectionMinimized", true); minimizeDenomsSection(settings.value("fDenomsSectionMinimized").toBool()); } PrivacyDialog::~PrivacyDialog() { QSettings settings; settings.setValue("fDenomsSectionMinimized", fDenomsMinimized); delete ui; } void PrivacyDialog::setModel(WalletModel* walletModel) { this->walletModel = walletModel; if (walletModel && walletModel->getOptionsModel()) { // Keep up to date with wallet setBalance(walletModel->getBalance(), walletModel->getUnconfirmedBalance(), walletModel->getImmatureBalance(), walletModel->getZerocoinBalance(), walletModel->getUnconfirmedZerocoinBalance(), walletModel->getImmatureZerocoinBalance(), walletModel->getWatchBalance(), walletModel->getWatchUnconfirmedBalance(), walletModel->getWatchImmatureBalance()); connect(walletModel, SIGNAL(balanceChanged(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount)), this, SLOT(setBalance(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount))); ui->securityLevel->setValue(nSecurityLevel); } } void PrivacyDialog::on_pasteButton_clicked() { // Paste text from clipboard into recipient field ui->payTo->setText(QApplication::clipboard()->text()); } void PrivacyDialog::on_addressBookButton_clicked() { if (!walletModel || !walletModel->getOptionsModel()) return; AddressBookPage dlg(AddressBookPage::ForSelection, AddressBookPage::SendingTab, this); dlg.setModel(walletModel->getAddressTableModel()); if (dlg.exec()) { ui->payTo->setText(dlg.getReturnValue()); ui->zAGORpayAmount->setFocus(); } } void PrivacyDialog::on_pushButtonMintzAGOR_clicked() { if (!walletModel || !walletModel->getOptionsModel()) return; if(GetAdjustedTime() > GetSporkValue(SPORK_16_ZEROCOIN_MAINTENANCE_MODE)) { QMessageBox::information(this, tr("Mint Zerocoin"), tr("zAGOR is currently undergoing maintenance."), QMessageBox::Ok, QMessageBox::Ok); return; } // Reset message text ui->TEMintStatus->setPlainText(tr("Mint Status: Okay")); // Request unlock if wallet was locked or unlocked for mixing: WalletModel::EncryptionStatus encStatus = walletModel->getEncryptionStatus(); if (encStatus == walletModel->Locked) { WalletModel::UnlockContext ctx(walletModel->requestUnlock(AskPassphraseDialog::Context::Mint_zAGOR, true)); if (!ctx.isValid()) { // Unlock wallet was cancelled ui->TEMintStatus->setPlainText(tr("Error: Your wallet is locked. Please enter the wallet passphrase first.")); return; } } QString sAmount = ui->labelMintAmountValue->text(); CAmount nAmount = sAmount.toInt() * COIN; // Minting amount must be > 0 if(nAmount <= 0){ ui->TEMintStatus->setPlainText(tr("Message: Enter an amount > 0.")); return; } ui->TEMintStatus->setPlainText(tr("Minting ") + ui->labelMintAmountValue->text() + " zAGOR..."); ui->TEMintStatus->repaint (); int64_t nTime = GetTimeMillis(); CWalletTx wtx; vector<CDeterministicMint> vMints; string strError = pwalletMain->MintZerocoin(nAmount, wtx, vMints, CoinControlDialog::coinControl); // Return if something went wrong during minting if (strError != ""){ ui->TEMintStatus->setPlainText(QString::fromStdString(strError)); return; } double fDuration = (double)(GetTimeMillis() - nTime)/1000.0; // Minting successfully finished. Show some stats for entertainment. QString strStatsHeader = tr("Successfully minted ") + ui->labelMintAmountValue->text() + tr(" zAGOR in ") + QString::number(fDuration) + tr(" sec. Used denominations:\n"); // Clear amount to avoid double spending when accidentally clicking twice ui->labelMintAmountValue->setText ("0"); QString strStats = ""; ui->TEMintStatus->setPlainText(strStatsHeader); for (CDeterministicMint dMint : vMints) { boost::this_thread::sleep(boost::posix_time::milliseconds(100)); strStats = strStats + QString::number(dMint.GetDenomination()) + " "; ui->TEMintStatus->setPlainText(strStatsHeader + strStats); ui->TEMintStatus->repaint (); } ui->TEMintStatus->verticalScrollBar()->setValue(ui->TEMintStatus->verticalScrollBar()->maximum()); // Automatically scroll to end of text // Available balance isn't always updated, so force it. setBalance(walletModel->getBalance(), walletModel->getUnconfirmedBalance(), walletModel->getImmatureBalance(), walletModel->getZerocoinBalance(), walletModel->getUnconfirmedZerocoinBalance(), walletModel->getImmatureZerocoinBalance(), walletModel->getWatchBalance(), walletModel->getWatchUnconfirmedBalance(), walletModel->getWatchImmatureBalance()); coinControlUpdateLabels(); return; } void PrivacyDialog::on_pushButtonMintReset_clicked() { ui->TEMintStatus->setPlainText(tr("Starting ResetMintZerocoin: rescanning complete blockchain, this will need up to 30 minutes depending on your hardware.\nPlease be patient...")); ui->TEMintStatus->repaint (); int64_t nTime = GetTimeMillis(); string strResetMintResult = pwalletMain->ResetMintZerocoin(); double fDuration = (double)(GetTimeMillis() - nTime)/1000.0; ui->TEMintStatus->setPlainText(QString::fromStdString(strResetMintResult) + tr("Duration: ") + QString::number(fDuration) + tr(" sec.\n")); ui->TEMintStatus->repaint (); ui->TEMintStatus->verticalScrollBar()->setValue(ui->TEMintStatus->verticalScrollBar()->maximum()); // Automatically scroll to end of text return; } void PrivacyDialog::on_pushButtonSpentReset_clicked() { ui->TEMintStatus->setPlainText(tr("Starting ResetSpentZerocoin: ")); ui->TEMintStatus->repaint (); int64_t nTime = GetTimeMillis(); string strResetSpentResult = pwalletMain->ResetSpentZerocoin(); double fDuration = (double)(GetTimeMillis() - nTime)/1000.0; ui->TEMintStatus->setPlainText(QString::fromStdString(strResetSpentResult) + tr("Duration: ") + QString::number(fDuration) + tr(" sec.\n")); ui->TEMintStatus->repaint (); ui->TEMintStatus->verticalScrollBar()->setValue(ui->TEMintStatus->verticalScrollBar()->maximum()); // Automatically scroll to end of text return; } void PrivacyDialog::on_pushButtonSpendzAGOR_clicked() { if (!walletModel || !walletModel->getOptionsModel() || !pwalletMain) return; if(GetAdjustedTime() > GetSporkValue(SPORK_16_ZEROCOIN_MAINTENANCE_MODE)) { QMessageBox::information(this, tr("Mint Zerocoin"), tr("zAGOR is currently undergoing maintenance."), QMessageBox::Ok, QMessageBox::Ok); return; } // Request unlock if wallet was locked or unlocked for mixing: WalletModel::EncryptionStatus encStatus = walletModel->getEncryptionStatus(); if (encStatus == walletModel->Locked || encStatus == walletModel->UnlockedForAnonymizationOnly) { WalletModel::UnlockContext ctx(walletModel->requestUnlock(AskPassphraseDialog::Context::Send_zAGOR, true)); if (!ctx.isValid()) { // Unlock wallet was cancelled return; } // Wallet is unlocked now, sedn zAGOR sendzAGOR(); return; } // Wallet already unlocked or not encrypted at all, send zAGOR sendzAGOR(); } void PrivacyDialog::on_pushButtonZAgorControl_clicked() { if (!walletModel || !walletModel->getOptionsModel()) return; ZAgorControlDialog* zAgorControl = new ZAgorControlDialog(this); zAgorControl->setModel(walletModel); zAgorControl->exec(); } void PrivacyDialog::setZAgorControlLabels(int64_t nAmount, int nQuantity) { ui->labelzAgorSelected_int->setText(QString::number(nAmount)); ui->labelQuantitySelected_int->setText(QString::number(nQuantity)); } static inline int64_t roundint64(double d) { return (int64_t)(d > 0 ? d + 0.5 : d - 0.5); } void PrivacyDialog::sendzAGOR() { QSettings settings; // Handle 'Pay To' address options CBitcoinAddress address(ui->payTo->text().toStdString()); if(ui->payTo->text().isEmpty()){ QMessageBox::information(this, tr("Spend Zerocoin"), tr("No 'Pay To' address provided, creating local payment"), QMessageBox::Ok, QMessageBox::Ok); } else{ if (!address.IsValid()) { QMessageBox::warning(this, tr("Spend Zerocoin"), tr("Invalid AGORA Address"), QMessageBox::Ok, QMessageBox::Ok); ui->payTo->setFocus(); return; } } // Double is allowed now double dAmount = ui->zAGORpayAmount->text().toDouble(); CAmount nAmount = roundint64(dAmount* COIN); // Check amount validity if (!MoneyRange(nAmount) || nAmount <= 0.0) { QMessageBox::warning(this, tr("Spend Zerocoin"), tr("Invalid Send Amount"), QMessageBox::Ok, QMessageBox::Ok); ui->zAGORpayAmount->setFocus(); return; } // Convert change to zAGOR bool fMintChange = ui->checkBoxMintChange->isChecked(); // Persist minimize change setting fMinimizeChange = ui->checkBoxMinimizeChange->isChecked(); settings.setValue("fMinimizeChange", fMinimizeChange); // Warn for additional fees if amount is not an integer and change as zAGOR is requested bool fWholeNumber = floor(dAmount) == dAmount; double dzFee = 0.0; if(!fWholeNumber) dzFee = 1.0 - (dAmount - floor(dAmount)); if(!fWholeNumber && fMintChange){ QString strFeeWarning = "You've entered an amount with fractional digits and want the change to be converted to Zerocoin.<br /><br /><b>"; strFeeWarning += QString::number(dzFee, 'f', 8) + " AGOR </b>will be added to the standard transaction fees!<br />"; QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm additional Fees"), strFeeWarning, QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel); if (retval != QMessageBox::Yes) { // Sending canceled ui->zAGORpayAmount->setFocus(); return; } } // Persist Security Level for next start nSecurityLevel = ui->securityLevel->value(); settings.setValue("nSecurityLevel", nSecurityLevel); // Spend confirmation message box // Add address info if available QString strAddressLabel = ""; if(!ui->payTo->text().isEmpty() && !ui->addAsLabel->text().isEmpty()){ strAddressLabel = "<br />(" + ui->addAsLabel->text() + ") "; } // General info QString strQuestionString = tr("Are you sure you want to send?<br /><br />"); QString strAmount = "<b>" + QString::number(dAmount, 'f', 8) + " zAGOR</b>"; QString strAddress = tr(" to address ") + QString::fromStdString(address.ToString()) + strAddressLabel + " <br />"; if(ui->payTo->text().isEmpty()){ // No address provided => send to local address strAddress = tr(" to a newly generated (unused and therefore anonymous) local address <br />"); } QString strSecurityLevel = tr("with Security Level ") + ui->securityLevel->text() + " ?"; strQuestionString += strAmount + strAddress + strSecurityLevel; // Display message box QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"), strQuestionString, QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel); if (retval != QMessageBox::Yes) { // Sending canceled return; } int64_t nTime = GetTimeMillis(); ui->TEMintStatus->setPlainText(tr("Spending Zerocoin.\nComputationally expensive, might need several minutes depending on the selected Security Level and your hardware.\nPlease be patient...")); ui->TEMintStatus->repaint(); // use mints from zAGOR selector if applicable vector<CMintMeta> vMintsToFetch; vector<CZerocoinMint> vMintsSelected; if (!ZAgorControlDialog::setSelectedMints.empty()) { vMintsToFetch = ZAgorControlDialog::GetSelectedMints(); for (auto& meta : vMintsToFetch) { if (meta.nVersion < libzerocoin::PrivateCoin::PUBKEY_VERSION) { //version 1 coins have to use full security level to successfully spend. if (nSecurityLevel < 100) { QMessageBox::warning(this, tr("Spend Zerocoin"), tr("Version 1 zAGOR require a security level of 100 to successfully spend."), QMessageBox::Ok, QMessageBox::Ok); ui->TEMintStatus->setPlainText(tr("Failed to spend zAGOR")); ui->TEMintStatus->repaint(); return; } } CZerocoinMint mint; if (!pwalletMain->GetMint(meta.hashSerial, mint)) { ui->TEMintStatus->setPlainText(tr("Failed to fetch mint associated with serial hash")); ui->TEMintStatus->repaint(); return; } vMintsSelected.emplace_back(mint); } } // Spend zAGOR CWalletTx wtxNew; CZerocoinSpendReceipt receipt; bool fSuccess = false; if(ui->payTo->text().isEmpty()){ // Spend to newly generated local address fSuccess = pwalletMain->SpendZerocoin(nAmount, nSecurityLevel, wtxNew, receipt, vMintsSelected, fMintChange, fMinimizeChange); } else { // Spend to supplied destination address fSuccess = pwalletMain->SpendZerocoin(nAmount, nSecurityLevel, wtxNew, receipt, vMintsSelected, fMintChange, fMinimizeChange, &address); } // Display errors during spend if (!fSuccess) { if (receipt.GetStatus() == ZAGOR_SPEND_V1_SEC_LEVEL) { QMessageBox::warning(this, tr("Spend Zerocoin"), tr("Version 1 zAGOR require a security level of 100 to successfully spend."), QMessageBox::Ok, QMessageBox::Ok); ui->TEMintStatus->setPlainText(tr("Failed to spend zAGOR")); ui->TEMintStatus->repaint(); return; } int nNeededSpends = receipt.GetNeededSpends(); // Number of spends we would need for this transaction const int nMaxSpends = Params().Zerocoin_MaxSpendsPerTransaction(); // Maximum possible spends for one zAGOR transaction if (nNeededSpends > nMaxSpends) { QString strStatusMessage = tr("Too much inputs (") + QString::number(nNeededSpends, 10) + tr(") needed.\nMaximum allowed: ") + QString::number(nMaxSpends, 10); strStatusMessage += tr("\nEither mint higher denominations (so fewer inputs are needed) or reduce the amount to spend."); QMessageBox::warning(this, tr("Spend Zerocoin"), strStatusMessage.toStdString().c_str(), QMessageBox::Ok, QMessageBox::Ok); ui->TEMintStatus->setPlainText(tr("Spend Zerocoin failed with status = ") +QString::number(receipt.GetStatus(), 10) + "\n" + "Message: " + QString::fromStdString(strStatusMessage.toStdString())); } else { QMessageBox::warning(this, tr("Spend Zerocoin"), receipt.GetStatusMessage().c_str(), QMessageBox::Ok, QMessageBox::Ok); ui->TEMintStatus->setPlainText(tr("Spend Zerocoin failed with status = ") +QString::number(receipt.GetStatus(), 10) + "\n" + "Message: " + QString::fromStdString(receipt.GetStatusMessage())); } ui->zAGORpayAmount->setFocus(); ui->TEMintStatus->repaint(); ui->TEMintStatus->verticalScrollBar()->setValue(ui->TEMintStatus->verticalScrollBar()->maximum()); // Automatically scroll to end of text return; } if (walletModel && walletModel->getAddressTableModel()) { // If zAGOR was spent successfully update the addressbook with the label std::string labelText = ui->addAsLabel->text().toStdString(); if (!labelText.empty()) walletModel->updateAddressBookLabels(address.Get(), labelText, "send"); else walletModel->updateAddressBookLabels(address.Get(), "(no label)", "send"); } // Clear zagor selector in case it was used ZAgorControlDialog::setSelectedMints.clear(); ui->labelzAgorSelected_int->setText(QString("0")); ui->labelQuantitySelected_int->setText(QString("0")); // Some statistics for entertainment QString strStats = ""; CAmount nValueIn = 0; int nCount = 0; for (CZerocoinSpend spend : receipt.GetSpends()) { strStats += tr("zAGOR Spend #: ") + QString::number(nCount) + ", "; strStats += tr("denomination: ") + QString::number(spend.GetDenomination()) + ", "; strStats += tr("serial: ") + spend.GetSerial().ToString().c_str() + "\n"; strStats += tr("Spend is 1 of : ") + QString::number(spend.GetMintCount()) + " mints in the accumulator\n"; nValueIn += libzerocoin::ZerocoinDenominationToAmount(spend.GetDenomination()); ++nCount; } CAmount nValueOut = 0; for (const CTxOut& txout: wtxNew.vout) { strStats += tr("value out: ") + FormatMoney(txout.nValue).c_str() + " Agor, "; nValueOut += txout.nValue; strStats += tr("address: "); CTxDestination dest; if(txout.scriptPubKey.IsZerocoinMint()) strStats += tr("zAGOR Mint"); else if(ExtractDestination(txout.scriptPubKey, dest)) strStats += tr(CBitcoinAddress(dest).ToString().c_str()); strStats += "\n"; } double fDuration = (double)(GetTimeMillis() - nTime)/1000.0; strStats += tr("Duration: ") + QString::number(fDuration) + tr(" sec.\n"); strStats += tr("Sending successful, return code: ") + QString::number(receipt.GetStatus()) + "\n"; QString strReturn; strReturn += tr("txid: ") + wtxNew.GetHash().ToString().c_str() + "\n"; strReturn += tr("fee: ") + QString::fromStdString(FormatMoney(nValueIn-nValueOut)) + "\n"; strReturn += strStats; // Clear amount to avoid double spending when accidentally clicking twice ui->zAGORpayAmount->setText ("0"); ui->TEMintStatus->setPlainText(strReturn); ui->TEMintStatus->repaint(); ui->TEMintStatus->verticalScrollBar()->setValue(ui->TEMintStatus->verticalScrollBar()->maximum()); // Automatically scroll to end of text } void PrivacyDialog::on_payTo_textChanged(const QString& address) { updateLabel(address); } // Coin Control: copy label "Quantity" to clipboard void PrivacyDialog::coinControlClipboardQuantity() { GUIUtil::setClipboard(ui->labelCoinControlQuantity->text()); } // Coin Control: copy label "Amount" to clipboard void PrivacyDialog::coinControlClipboardAmount() { GUIUtil::setClipboard(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" "))); } // Coin Control: button inputs -> show actual coin control dialog void PrivacyDialog::coinControlButtonClicked() { if (!walletModel || !walletModel->getOptionsModel()) return; CoinControlDialog dlg; dlg.setModel(walletModel); dlg.exec(); coinControlUpdateLabels(); } // Coin Control: update labels void PrivacyDialog::coinControlUpdateLabels() { if (!walletModel || !walletModel->getOptionsModel() || !walletModel->getOptionsModel()->getCoinControlFeatures()) return; // set pay amounts CoinControlDialog::payAmounts.clear(); if (CoinControlDialog::coinControl->HasSelected()) { // Actual coin control calculation CoinControlDialog::updateLabels(walletModel, this); } else { ui->labelCoinControlQuantity->setText (tr("Coins automatically selected")); ui->labelCoinControlAmount->setText (tr("Coins automatically selected")); } } void PrivacyDialog::on_pushButtonShowDenoms_clicked() { minimizeDenomsSection(false); } void PrivacyDialog::on_pushButtonHideDenoms_clicked() { minimizeDenomsSection(true); } void PrivacyDialog::minimizeDenomsSection(bool fMinimize) { if (fMinimize) { ui->balanceSupplyFrame->show(); ui->verticalFrameRight->hide(); } else { ui->balanceSupplyFrame->hide(); ui->verticalFrameRight->show(); } fDenomsMinimized = fMinimize; } bool PrivacyDialog::updateLabel(const QString& address) { if (!walletModel) return false; // Fill in label from address book, if address has an associated label QString associatedLabel = walletModel->getAddressTableModel()->labelForAddress(address); if (!associatedLabel.isEmpty()) { ui->addAsLabel->setText(associatedLabel); return true; } return false; } void PrivacyDialog::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, const CAmount& zerocoinBalance, const CAmount& unconfirmedZerocoinBalance, const CAmount& immatureZerocoinBalance, const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance) { currentBalance = balance; currentUnconfirmedBalance = unconfirmedBalance; currentImmatureBalance = immatureBalance; currentZerocoinBalance = zerocoinBalance; currentUnconfirmedZerocoinBalance = unconfirmedZerocoinBalance; currentImmatureZerocoinBalance = immatureZerocoinBalance; currentWatchOnlyBalance = watchOnlyBalance; currentWatchUnconfBalance = watchUnconfBalance; currentWatchImmatureBalance = watchImmatureBalance; std::map<libzerocoin::CoinDenomination, CAmount> mapDenomBalances; std::map<libzerocoin::CoinDenomination, int> mapUnconfirmed; std::map<libzerocoin::CoinDenomination, int> mapImmature; for (const auto& denom : libzerocoin::zerocoinDenomList){ mapDenomBalances.insert(make_pair(denom, 0)); mapUnconfirmed.insert(make_pair(denom, 0)); mapImmature.insert(make_pair(denom, 0)); } std::vector<CMintMeta> vMints = pwalletMain->zagorTracker->GetMints(false); map<libzerocoin::CoinDenomination, int> mapMaturityHeights = GetMintMaturityHeight(); for (auto& meta : vMints){ // All denominations mapDenomBalances.at(meta.denom)++; if (!meta.nHeight || chainActive.Height() - meta.nHeight <= Params().Zerocoin_MintRequiredConfirmations()) { // All unconfirmed denominations mapUnconfirmed.at(meta.denom)++; } else { if (meta.denom == libzerocoin::CoinDenomination::ZQ_ERROR) { mapImmature.at(meta.denom)++; } else if (meta.nHeight >= mapMaturityHeights.at(meta.denom)) { mapImmature.at(meta.denom)++; } } } int64_t nCoins = 0; int64_t nSumPerCoin = 0; int64_t nUnconfirmed = 0; int64_t nImmature = 0; QString strDenomStats, strUnconfirmed = ""; for (const auto& denom : libzerocoin::zerocoinDenomList) { nCoins = libzerocoin::ZerocoinDenominationToInt(denom); nSumPerCoin = nCoins * mapDenomBalances.at(denom); nUnconfirmed = mapUnconfirmed.at(denom); nImmature = mapImmature.at(denom); strUnconfirmed = ""; if (nUnconfirmed) { strUnconfirmed += QString::number(nUnconfirmed) + QString(" unconf. "); } if(nImmature) { strUnconfirmed += QString::number(nImmature) + QString(" immature "); } if(nImmature || nUnconfirmed) { strUnconfirmed = QString("( ") + strUnconfirmed + QString(") "); } strDenomStats = strUnconfirmed + QString::number(mapDenomBalances.at(denom)) + " x " + QString::number(nCoins) + " = <b>" + QString::number(nSumPerCoin) + " zAGOR </b>"; switch (nCoins) { case libzerocoin::CoinDenomination::ZQ_ONE: ui->labelzDenom1Amount->setText(strDenomStats); break; case libzerocoin::CoinDenomination::ZQ_FIVE: ui->labelzDenom2Amount->setText(strDenomStats); break; case libzerocoin::CoinDenomination::ZQ_TEN: ui->labelzDenom3Amount->setText(strDenomStats); break; case libzerocoin::CoinDenomination::ZQ_FIFTY: ui->labelzDenom4Amount->setText(strDenomStats); break; case libzerocoin::CoinDenomination::ZQ_ONE_HUNDRED: ui->labelzDenom5Amount->setText(strDenomStats); break; case libzerocoin::CoinDenomination::ZQ_FIVE_HUNDRED: ui->labelzDenom6Amount->setText(strDenomStats); break; case libzerocoin::CoinDenomination::ZQ_ONE_THOUSAND: ui->labelzDenom7Amount->setText(strDenomStats); break; case libzerocoin::CoinDenomination::ZQ_FIVE_THOUSAND: ui->labelzDenom8Amount->setText(strDenomStats); break; default: // Error Case: don't update display break; } } CAmount matureZerocoinBalance = zerocoinBalance - unconfirmedZerocoinBalance - immatureZerocoinBalance; CAmount nLockedBalance = 0; if (walletModel) { nLockedBalance = walletModel->getLockedBalance(); } ui->labelzAvailableAmount->setText(QString::number(zerocoinBalance/COIN) + QString(" zAGOR ")); ui->labelzAvailableAmount_2->setText(QString::number(matureZerocoinBalance/COIN) + QString(" zAGOR ")); ui->labelzAvailableAmount_4->setText(QString::number(zerocoinBalance/COIN) + QString(" zAGOR ")); ui->labelzAGORAmountValue->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, balance - immatureBalance - nLockedBalance, false, BitcoinUnits::separatorAlways)); // Update/enable labels and buttons depending on the current SPORK_16 status updateSPORK16Status(); // Display global supply ui->labelZsupplyAmount->setText(QString::number(chainActive.Tip()->GetZerocoinSupply()/COIN) + QString(" <b>zAGOR </b> ")); ui->labelZsupplyAmount_2->setText(QString::number(chainActive.Tip()->GetZerocoinSupply()/COIN) + QString(" <b>zAGOR </b> ")); for (auto denom : libzerocoin::zerocoinDenomList) { int64_t nSupply = chainActive.Tip()->mapZerocoinSupply.at(denom); QString strSupply = QString::number(nSupply) + " x " + QString::number(denom) + " = <b>" + QString::number(nSupply*denom) + " zAGOR </b> "; switch (denom) { case libzerocoin::CoinDenomination::ZQ_ONE: ui->labelZsupplyAmount1->setText(strSupply); break; case libzerocoin::CoinDenomination::ZQ_FIVE: ui->labelZsupplyAmount5->setText(strSupply); break; case libzerocoin::CoinDenomination::ZQ_TEN: ui->labelZsupplyAmount10->setText(strSupply); break; case libzerocoin::CoinDenomination::ZQ_FIFTY: ui->labelZsupplyAmount50->setText(strSupply); break; case libzerocoin::CoinDenomination::ZQ_ONE_HUNDRED: ui->labelZsupplyAmount100->setText(strSupply); break; case libzerocoin::CoinDenomination::ZQ_FIVE_HUNDRED: ui->labelZsupplyAmount500->setText(strSupply); break; case libzerocoin::CoinDenomination::ZQ_ONE_THOUSAND: ui->labelZsupplyAmount1000->setText(strSupply); break; case libzerocoin::CoinDenomination::ZQ_FIVE_THOUSAND: ui->labelZsupplyAmount5000->setText(strSupply); break; default: // Error Case: don't update display break; } } } void PrivacyDialog::updateDisplayUnit() { if (walletModel && walletModel->getOptionsModel()) { nDisplayUnit = walletModel->getOptionsModel()->getDisplayUnit(); if (currentBalance != -1) setBalance(currentBalance, currentUnconfirmedBalance, currentImmatureBalance, currentZerocoinBalance, currentUnconfirmedZerocoinBalance, currentImmatureZerocoinBalance, currentWatchOnlyBalance, currentWatchUnconfBalance, currentWatchImmatureBalance); } } void PrivacyDialog::showOutOfSyncWarning(bool fShow) { ui->labelzAGORSyncStatus->setVisible(fShow); } void PrivacyDialog::keyPressEvent(QKeyEvent* event) { if (event->key() != Qt::Key_Escape) // press esc -> ignore { this->QDialog::keyPressEvent(event); } else { event->ignore(); } } void PrivacyDialog::updateSPORK16Status() { // Update/enable labels, buttons and tooltips depending on the current SPORK_16 status bool fButtonsEnabled = ui->pushButtonMintzAGOR->isEnabled(); bool fMaintenanceMode = GetAdjustedTime() > GetSporkValue(SPORK_16_ZEROCOIN_MAINTENANCE_MODE); if (fMaintenanceMode && fButtonsEnabled) { // Mint zAGOR ui->pushButtonMintzAGOR->setEnabled(false); ui->pushButtonMintzAGOR->setToolTip(tr("zAGOR is currently disabled due to maintenance.")); // Spend zAGOR ui->pushButtonSpendzAGOR->setEnabled(false); ui->pushButtonSpendzAGOR->setToolTip(tr("zAGOR is currently disabled due to maintenance.")); } else if (!fMaintenanceMode && !fButtonsEnabled) { // Mint zAGOR ui->pushButtonMintzAGOR->setEnabled(true); ui->pushButtonMintzAGOR->setToolTip(tr("PrivacyDialog", "Enter an amount of AGOR to convert to zAGOR", 0)); // Spend zAGOR ui->pushButtonSpendzAGOR->setEnabled(true); ui->pushButtonSpendzAGOR->setToolTip(tr("Spend Zerocoin. Without 'Pay To:' address creates payments to yourself.")); } }
[ "52382794+AGORACoinDeveloper@users.noreply.github.com" ]
52382794+AGORACoinDeveloper@users.noreply.github.com
4ca43429de0be5eb0d00f41fde16b9dafc06c508
96c2fe5f82e839604de435128876b7ec23994108
/boj/p12764/main.cc
8d5a3ffd5e6169fccd047b658289aeca8be208d4
[ "MIT" ]
permissive
suhwanhwang/problem-solving
d9ed5521fdd670c4793d187116f489a82ee4a90d
cf71bd9545d13959462713bd6eabee05e88f40f3
refs/heads/master
2023-08-31T15:29:46.164871
2023-08-28T23:12:26
2023-08-28T23:12:26
199,259,343
0
0
null
null
null
null
UTF-8
C++
false
false
1,667
cc
#include <iostream> #include <algorithm> #include <vector> #include <numeric> #include <unordered_map> #include <set> #include <functional> #include <queue> #include <cstdlib> #include <ctime> using namespace std; typedef long long ll; void solve(vector<pair<int, int>> &users) { sort(users.begin(), users.end()); priority_queue<pair<int, int>, vector<pair<int,int>>, greater<pair<int,int>>> user_pq; //end time, pc num; priority_queue<int, vector<int>, greater<int>> empty_pq; vector<int> count; int max_pc = 0; for (int i = 0; i < (int)users.size(); ++i) { int start = users[i].first; int end = users[i].second; // check finished user while(!user_pq.empty()) { auto p = user_pq.top(); if (p.first > start) { break; } empty_pq.push(p.second); user_pq.pop(); } // find next empty pc int next; if (empty_pq.empty()) { next = user_pq.size() + 1; max_pc = max(max_pc, next); } else { next = empty_pq.top(); empty_pq.pop(); } if (next > count.size()) { count.push_back(0); } count[next - 1]++; user_pq.push({end, next}); } cout << max_pc << endl; for (int used : count) { cout << used << " "; } cout << endl; } int main(void) { ios_base::sync_with_stdio(false); int n; cin >> n; vector<pair<int, int>> users(n); for (int i = 0; i < n; ++i) { cin >> users[i].first >> users[i].second; } solve(users); return 0; }
[ "suhwanh7@gmail.com" ]
suhwanh7@gmail.com
15994b8f58575f09364ce83fca10e68514078848
95f50fea669c1e6885a924ba864a7d7f5e926260
/hw4_v2/src/CartPole.cpp
7e56b8199278815d6331a563c777f6b7dfff2957
[]
no_license
danielsamfdo/RL_CS687
e20fdc2aff4d5318ba0fcedf7512bd6280f6708e
c2479a18f9ceafcf1292a2ebee6ab2505ed65310
refs/heads/master
2021-03-30T15:46:00.277180
2019-09-04T21:49:46
2019-09-04T21:49:46
107,219,539
1
0
null
null
null
null
UTF-8
C++
false
false
3,054
cpp
#include <stdafx.hpp> using namespace Eigen; using namespace std; CartPole::CartPole() { theta = 0; omega = 0; theta = 0; v = 0; x = 0; t = 0; } CartPole::~CartPole() {} VectorXd CartPole::getState() { VectorXd result(4); result[0] = x; result[1] = v; result[2] = theta; result[3] = omega; return result; } // Returns an integer that is +1, 0, or -1 static int sign(double x) { return (x > 0) - (x < 0); } // Bound x between min and max static double bound(const double & x, const double & minValue, const double & maxValue) { return std::min<double>(maxValue, std::max<double>(minValue, x)); } static double Mod(const double & x, const double & y) { if (0. == y) return x; double m = x - y * (double)std::floor(x / y); // handle boundary cases resulted from floating-point cut off: if (y > 0) { if (m >= y) return 0; if (m < 0) { if (y + m == y) return 0; else return (y + m); } } else { if (m <= y) return 0; if (m > 0) { if (y + m == y) return 0; else return (y + m); } } return m; } // wrap [rad] angle to [-PI..PI) static double wrapPosNegPI(const double & theta) { return Mod((double)theta + M_PI, (double)2.0*M_PI) - (double)M_PI; } double CartPole::update(int action) { double F = action*uMax + (action - 1)*uMax; // Run simSteps short steps, each using a forward Euler approximation of // the dynamics. double omegaDot, vDot, subDt = dt / (double)simSteps; for (int i = 0; i < simSteps; i++) { // Update once with timestep subDt // First compute the time derivatives (inserted the cos(theta) at the // beginning) omegaDot = (g*sin(theta) + cos(theta)*(muc*sign(v) - F - m*l*omega*omega*sin(theta)) / (m + mc) - mup*omega / (m*l)) / (l*(4.0 / 3.0 - m / (m + mc)*cos(theta)*cos(theta))); vDot = (F + m*l*(omega*omega*sin(theta) - omegaDot*cos(theta)) - muc*sign(v)) / (m + mc); // Update by adding the derivatives theta += subDt*omega; omega += subDt*omegaDot; x += subDt*v; v += subDt*vDot; // Keep in a nice range (-pi to pi so we can do the check below) theta = wrapPosNegPI(theta); t += subDt; } bound(x, -2.4, 2.4); if (inTerminalState()) return -1; else return 1; } bool CartPole::inTerminalState() { // This t bound is from getDesc, suggestedMaxT return ((fabs(theta) > M_PI / 15.0) || (fabs(x) >= 2.4) || (t >= 20.0 + 10 * dt)); } void CartPole::newEpisode() { theta = 0; omega = 0; theta = 0; v = 0; x = 0; t = 0; } int CartPole::getStateDim() { return 4; } int CartPole::getNumActions() { return 2; } VectorXd CartPole::getMinState() { VectorXd result(4); result[0] = -2.4; result[1] = -6; result[2] = -12 * M_PI / 180.0; result[3] = -6; return result; } VectorXd CartPole::getMaxState() { VectorXd result(4); result[0] = 2.4; result[1] = 6; result[2] = 12 * M_PI / 180.0; result[3] = 6; return result; } double CartPole::getGamma() { return 1.0; }
[ "danielsamfdo@gmail.com" ]
danielsamfdo@gmail.com
afda84a406679ae5a646cc4cc45dc17996aa6291
9bb65fa7a3e6008a85d94fe6724d6f721deff87a
/Ques 1.cpp
2f706a120d9e2d4c5a253dc5fc754f17541565ad
[]
no_license
AdMoSa/Assignment-3
23c5e170bb22fe650291d660aed5550d5f7c23fd
dfc818d9d12509eef113f8031b5cd074f10697ca
refs/heads/master
2021-01-23T05:09:46.900609
2017-11-17T18:34:51
2017-11-17T18:34:51
102,461,268
0
0
null
null
null
null
UTF-8
C++
false
false
223
cpp
#include <iostream> using namespace std; main() { float x,y,max; cout << "Enter 1st number: "; cin >> x; cout << "Enter 2nd number: "; cin >> y; if(x>=y) max=x; else max=y; cout << "Maximum is: "<< max; }
[ "noreply@github.com" ]
noreply@github.com
358aeab93b056144ffe180a8018f3cefcab00eb8
ddf6df9af794d182cf65ca76cbcc0b017280dcbe
/experiment/InterDLLSerialization/main.cpp
853f54133bfd904bae7cc1576c2062124c9b8832
[]
no_license
i-saint/atomic
088fcaf94be219f5c6739408051802fed0d321f6
2f6ed3c631fcea078f32941d250cef9c9cef2f1c
refs/heads/master
2020-04-21T23:40:18.364649
2014-09-01T08:02:38
2014-09-01T08:02:38
5,468,783
7
4
null
null
null
null
UTF-8
C++
false
false
603
cpp
#include "interface.h" BOOST_CLASS_EXPORT(IHoge) void serialize() { printf("serialize()\n"); IHoge *hoge = CreateHoge(); hoge->doSomething(); std::ofstream fs("hoge.bin", std::ios::binary); boost::archive::binary_oarchive ar(fs); ar << hoge; } void deserialzie() { printf("deserialzie()\n"); IHoge *hoge = nullptr; std::ifstream fs("hoge.bin", std::ios::binary); boost::archive::binary_iarchive ar(fs); ar >> hoge; hoge->doSomething(); } int main(int argc, char *argv[]) { serialize(); deserialzie(); }
[ "saint.skr@gmail.com" ]
saint.skr@gmail.com
046885343d0302da58bc63526ee6446434f3cf8b
00cc5c536b9af91d044fc9859d559e04c84778c3
/examples/space_region_3d.cpp
48a5834c73c00eeaa54498e51fae60d43a080a3e
[ "MIT" ]
permissive
adelbennaceur/cilantro
a76909feecd027cc1ee4557539e2f62df7ea187d
ef24b3534b4cdaf0bb3a11ffb629da6fda463773
refs/heads/master
2023-09-05T20:00:14.429435
2021-11-23T13:30:22
2021-11-23T13:30:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,922
cpp
#include <cilantro/visualization.hpp> #include <cilantro/spatial/space_region.hpp> #include <cilantro/utilities/point_cloud.hpp> #include <cilantro/utilities/timer.hpp> void callback(cilantro::Visualizer &viz, int key) { if (key == 'a') { viz.toggleVisibility("hull1"); } else if (key == 's') { viz.toggleVisibility("hull2"); } } int main(int argc, char* argv[]) { if (argc < 2) { std::cout << "Please provide path to PLY file." << std::endl; return 0; } cilantro::PointCloud3f cloud1(argv[1]); if (cloud1.isEmpty()) { std::cout << "Input cloud is empty!" << std::endl; return 0; } // Shift to the right cilantro::PointCloud3f cloud2(cloud1); cloud2.points.colwise() += Eigen::Vector3f(1,0,0); // Compute convex hulls as SpaceRegion objects // bool flags enable topology computation (for visualization) cilantro::SpaceRegion3f sr1(cloud1.points, true, true); cilantro::SpaceRegion3f sr2(cloud2.points, true, true); // Compute a spatial expression cilantro::Timer timer; timer.start(); // cilantro::SpaceRegion3f sr = sr1.relativeComplement(sr2, true, true); // cilantro::SpaceRegion3f sr = sr1.intersectionWith(sr2, true, true); // cilantro::SpaceRegion3f sr = sr1.intersectionWith(sr2).complement(true, true); cilantro::SpaceRegion3f sr = sr1.complement().unionWith(sr2.complement()).complement(true, true); timer.stop(); std::cout << "Build time: " << timer.getElapsedTime() << "ms" << std::endl; std::cout << "Number of polytopes in union: " << sr.getConvexPolytopes().size() << std::endl; // Find the points of the concatenation of the clouds that satisfy the spatial expression cilantro::PointCloud3f interior_cloud(cloud1); interior_cloud.append(cloud2); interior_cloud = cilantro::PointCloud3f(interior_cloud, sr.getInteriorPointIndices(interior_cloud.points, 0.005f)); // Visualize results const std::string window_name = "SpaceRegion3D example"; pangolin::CreateWindowAndBind(window_name, 640, 480); cilantro::Visualizer viz(window_name, "disp"); viz.registerKeyboardCallback('a', std::bind(callback, std::ref(viz), 'a')); viz.registerKeyboardCallback('s', std::bind(callback, std::ref(viz), 's')); viz.addObject<cilantro::PointCloudRenderable>("cloud1", cloud1, cilantro::RenderingProperties().setOpacity(0.3)); viz.addObject<cilantro::PointCloudRenderable>("cloud2", cloud2, cilantro::RenderingProperties().setOpacity(0.3)); viz.addObject<cilantro::PointCloudRenderable>("interior_cloud", interior_cloud, cilantro::RenderingProperties().setOpacity(1.0).setPointSize(2.5f).setPointColor(0.8,0.8,0.8)); const cilantro::ConvexPolytope3f& cp1(sr1.getConvexPolytopes()[0]); const cilantro::ConvexPolytope3f& cp2(sr2.getConvexPolytopes()[0]); viz.addObject<cilantro::TriangleMeshRenderable>("hull1", cp1.getVertices(), cp1.getFacetVertexIndices(), cilantro::RenderingProperties().setPointColor(1,0,0).setDrawWireframe(true).setUseFaceNormals(true).setLineWidth(2.0)); viz.addObject<cilantro::TriangleMeshRenderable>("hull2", cp2.getVertices(), cp2.getFacetVertexIndices(), cilantro::RenderingProperties().setPointColor(0,0,1).setDrawWireframe(true).setUseFaceNormals(true).setLineWidth(2.0)); const auto& polys(sr.getConvexPolytopes()); for (size_t i = 0; i < polys.size(); i++) { viz.addObject<cilantro::TriangleMeshRenderable>("sr_" + std::to_string(i), polys[i].getVertices(), polys[i].getFacetVertexIndices(), cilantro::RenderingProperties().setOpacity(0.9).setUseFaceNormals(true).setLineWidth(2.0).setPointColor(0.8,0.8,0.8)); } std::cout << "Press 'a' or 's' to toggle visibility of original hulls" << std::endl; std::cout << "Press 'w' to toggle wireframe" << std::endl; while (!viz.wasStopped()) { viz.spinOnce(); } return 0; }
[ "kzampog@gmail.com" ]
kzampog@gmail.com
4a71b3622f5fedff734ee30d2c23e756a6de6ce9
92e4dfa385c22913df0d11e0a7ca8844a2897638
/BalancedBraces/BalancedBraces/stdafx.cpp
95b27ec68f80f4c439b2f106a41d4eb8f9fb2b50
[]
no_license
vinod3114/Test-Practice
f3ef8350904cc03cd74b71eaf2f3da9cf248fbd6
b27850a30c0327c515f3ad9bc9b8b780dc3895d6
refs/heads/master
2021-04-27T03:47:10.821544
2018-02-24T21:54:10
2018-02-24T21:54:10
122,720,016
0
0
null
null
null
null
UTF-8
C++
false
false
293
cpp
// stdafx.cpp : source file that includes just the standard includes // BalancedBraces.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "vinod.sonatakke@gmail.com" ]
vinod.sonatakke@gmail.com
507a31dd1c05aebec168c078ac94a28e750da87a
59b6d5314fe3e866e7f6d5267ea8dba40e4bea41
/tests/Unit/HC/hc_atomic_sub_local.cpp
4e8c86fbf8aa9e84af7eaf20e379ba9f8cb93c6c
[ "LicenseRef-scancode-unknown-license-reference", "NCSA" ]
permissive
scchan/hcc
5534d4fe896b8a5dd3fc3272259af8ac959a588d
33e60e8635c58e772d2aa51d57b853f2bc1e1e5d
refs/heads/master
2021-01-19T15:47:55.209519
2016-07-15T16:48:56
2016-07-15T16:48:56
54,526,106
1
0
null
2016-11-25T21:06:43
2016-03-23T02:55:00
C++
UTF-8
C++
false
false
1,323
cpp
// XFAIL: Linux // RUN: %hc %s -o %t.out && %t.out #include <hc.hpp> #include <stdlib.h> #include <iostream> using namespace hc; template<typename T> bool test() { const int vecSize = 100; const int tile_size = 10; // Alloc & init input data extent<2> e_a(vecSize, vecSize); std::vector<T> va(vecSize * vecSize); for(int i = 0; i < vecSize * vecSize; ++i) { va[i] = 0; } array_view<T, 2> av_a(e_a, va); extent<2> compute_domain(e_a); parallel_for_each(compute_domain.tile(tile_size, tile_size), [=] (tiled_index<2> tidx) [[hc]] { index<2> localIdx = tidx.local; index<2> globalIdx = tidx.global; tile_static T localA[tile_size][tile_size]; localA[localIdx[0]][localIdx[1]] = T(tile_size * tile_size); tidx.barrier.wait(); for(int i = 0; i < tile_size; ++i) { for(int j = 0; j < tile_size; ++j) { atomic_fetch_sub(&(localA[i][j]), T(1)); } } tidx.barrier.wait(); av_a[globalIdx[0]][globalIdx[1]] = localA[localIdx[0]][localIdx[1]]; }); bool ret = true; for(int i = 0; i < vecSize; ++i) { for(int j = 0; j < vecSize; ++j) { if(av_a(i, j) != T(0)) { ret = false; } } } return ret; } int main() { bool ret = true; ret &= test<unsigned int>(); ret &= test<int>(); return !(ret == true); }
[ "jack@multicorewareinc.com" ]
jack@multicorewareinc.com
281cec2b72ff10e1b8bbff8d122f4b9d32377a1a
1a77b5eac40055032b72e27e720ac5d43451bbd6
/フォーム対応/VisualC++/MFC/Chap9/Rei66/Rei66/stdafx.cpp
ed16a23ca02ca7c9e5352c8019b0ee0f5fdffb57
[]
no_license
motonobu-t/algorithm
8c8d360ebb982a0262069bb968022fe79f2c84c2
ca7b29d53860eb06a357eb268f44f47ec9cb63f7
refs/heads/master
2021-01-22T21:38:34.195001
2017-05-15T12:00:51
2017-05-15T12:01:00
85,451,237
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
260
cpp
// stdafx.cpp : 標準インクルード Rei66.pch のみを // 含むソース ファイルは、プリコンパイル済みヘッダーになります。 // stdafx.obj にはプリコンパイルされた型情報が含まれます。 #include "stdafx.h"
[ "rx_78_bd@yahoo.co.jp" ]
rx_78_bd@yahoo.co.jp
375200a8d97bca8063693991af6460d4e34e7e3a
40f55fc2bc18b41d445f7ff8bd2c007e561d6572
/teensyTouchSensor.ino
608951c8d96adafff520dd4f6ea4b721a7ad4e3a
[]
no_license
mjkoehle/TeensyTouchSensor
da7fc7810a496652c7ce8984786c816f84ffb3a0
8945132c55e8c3df01a627b4ce461fff9c1856db
refs/heads/master
2020-05-23T07:59:31.773084
2017-02-24T16:09:06
2017-02-24T16:09:06
80,480,367
0
0
null
null
null
null
UTF-8
C++
false
false
11,756
ino
/* Michael Koehle 01.30.2017 Send json packet whenever state of one of the two touch sensors is changed. Sensors are filtered using moving average. An initial calibration sets a threshold for each sensor. This is equal to sensorMax + thresholdScale * (sensorMax-sensorMin) ThresholdScale is a user set value, 1 for each sensor. 1 is left. 2 ir right. */ /*user variables*/ double thresholdScale1 = .4; // see above, threshold for button 1 double thresholdScale2 = .4; // button 2 int calTime = 5000; //calibraton time on startup int beatDelay = 30000; //interval between sending beat packets, in millisenconds #include <SPI.h> #include <Ethernet.h> //#include <ArduinoJson.h> //need arduinoJson library here: https://github.com/bblanchon/ArduinoJson #include "mac.h" //local import #define s0 17 #define s1 16 #define s2 15 #define s3 14 /*network variables*/ const unsigned int resetPin = 9; //Ethernet Reset Pin //extern uint8_t mac[6]; //byte macB[] = {0x04, 0xE9, 0xE5, 0x03, 0x5F, 0x44}; //04:E9:E5:03:5F:10 [Teensy A] //04:E9:E5:03:5F:44 [Teensy B] //IPAddress localIp(192, 168, 0, sourceIP); IPAddress remoteIp(192, 168, 0 , 3); unsigned int serverPort = 3333; / unsigned int localPort = 7777; EthernetUDP udp; IPAddress localCheck; EthernetClient client; /* PANEL */ int currentModule; /*packet variables*/ String jsonString1 = ""; String jsonString2 = ""; String touchStart = "start_touch"; String touchStop = "end_touch"; String touchBeat = "touch_beat"; String flavor1 = touchBeat; String flavor2 = touchBeat; String choice1 = "left"; // color for pin1 String choice2 = "right"; //color for pin2 /*led variables*/ int redPin = 19; //red is 19 int greenPin = 20; //green is 20 int bluePin = 21; byte redValue = LOW; byte greenValue = LOW; byte blueValue = LOW; /*moving average variables*/ const int numReadings = 5; // Number of samples to average double readings1[numReadings]; // the readings from the analog input double readings2[numReadings]; int readIndex = 0; // the index of the current reading double total1 = 0; // the running total double average1 = 0; // averaged readings double total2 = 0; double average2 = 0; int inputPin1 = A8; // touch sensor1 int inputPin2 = A9; // touch sensor2 /* messaging logic variables*/ int triggerTime1 = 0; int triggerTime2 = 0; int currentBeat = 0; boolean trigger1 = false; boolean trigger2 = false; boolean sendMsg1 = false; boolean sendMsg2 = false; double thresholds[2]; double threshold1 = 0; double threshold2 = 0; boolean udpConnected = 0; void setup() { delay(1000); //wait to power up // initialize all the readings to 0: for (int thisReading = 0; thisReading < numReadings; thisReading++) { readings1[thisReading] = 0; readings2[thisReading] = 0; } Serial.begin(38400); // while (!Serial) { // ; // wait for serial port to connect. Needed for native USB port only // } pinMode(redPin, OUTPUT); pinMode(greenPin, OUTPUT); pinMode(bluePin, OUTPUT); digitalWrite(redPin, 1); // turn the LED on during calibration digitalWrite(greenPin, 1); calibrate(&thresholds[0]); //calibrate digitalWrite(redPin, 0); // turn the LED off after calibration digitalWrite(greenPin, 0); //connection: currentModule = readDIPAddress(); //Read address from DIP IPAddress localIp = IPAddress(192, 168, 0, currentModule + 100); //101-103 are touch sensor. 104-1011 ceiling getMAC(); //assigns MAC address to variable mac //Reset Ethernet Module resetEthernet(); Ethernet.begin(mac, localIp); udpConnected = udp.begin(localPort); //client.connect(remoteIp, serverPort); //MK this is for testing connection to a specific IP. Is there a check for just ethernet connection? //client.connected //.maintain Serial.println(udpConnected); Serial.println(localIp); threshold1 = thresholds[0]; threshold2 = thresholds[1]; delay(1000); } void loop() { /* Moving Average*/ // subtract the last reading: total1 = total1 - readings1[readIndex]; total2 = total2 - readings2[readIndex]; // read from the sensor: readings1[readIndex] = touchRead(inputPin1); readings2[readIndex] = touchRead(inputPin2); // add the reading to the total: total1 = total1 + readings1[readIndex]; total2 = total2 + readings2[readIndex]; // advance to the next position in the array: readIndex = readIndex + 1; // if we're at the end of the array... if (readIndex >= numReadings) { // ...wrap around to the beginning: readIndex = 0; } // calculate the average: average1 = total1 / numReadings; average2 = total2 / numReadings; /*Message Triggering*/ sendMsg1 = false; if (average1 >= threshold1) { if (trigger1 == false) { //if trigger1 is going from false to true, send msg to server sendMsg1 = true; redValue = HIGH; triggerTime1 = triggerTime1 + 1; trigger1 = true; //trigger1 is on flavor1 = touchStart; } } else { if (trigger1 == true) {//if trigger1 is going from true to false, send msg to server sendMsg1 = true; redValue = LOW; triggerTime1 = 0; trigger1 = false; flavor1 = touchStop; } } sendMsg2 = false; if (average2 >= threshold2) { if (trigger2 == false) { //if trigger2 is going from false to true, send msg to server sendMsg2 = true; greenValue = HIGH; triggerTime2 = triggerTime2 + 1; trigger2 = true; //trigger1 is on flavor2 = touchStart; } } else { if (trigger2 == true) { sendMsg2 = true; greenValue = LOW; triggerTime2 = 0; trigger2 = false; flavor2 = touchStop; } } if (millis() - currentBeat > beatDelay) { sendMsg1 = true; sendMsg2 = true; flavor1 = touchBeat; flavor2 = touchBeat; currentBeat = millis(); } /*visualization*/ Serial.print(touchRead(inputPin1)); Serial.print("\t"); Serial.print(average1); Serial.print("\t"); Serial.print(threshold1); Serial.print(touchRead(inputPin2)); Serial.print("\t"); Serial.print(average2); Serial.print("\t"); Serial.println(threshold2); /* Json messaging */ if (sendMsg1) { /*send packet*/ // DynamicJsonBuffer jsonBuffer3; char jsonChar1[100]; jsonString1 = "{\"source\": \"" + String(100+currentModule) + "\",\"flavor\" :\"" + flavor1 + "\",\"choice\" :\"" + choice1 + "\"}"; jsonString1.toCharArray(jsonChar1, 100); if (currentModule > 0) { //if dip is set to 0, don't try to send udp.beginPacket(remoteIp, serverPort); udp.write(jsonChar1); udp.println(); udp.endPacket(); } else { //else if dip (currentModule) is 0, change colors /*write color*/ digitalWrite(redPin, redValue); digitalWrite(bluePin, blueValue); digitalWrite(greenPin, greenValue); } } if (sendMsg2) { /*send packet*/ char jsonChar2[100]; jsonString2 = "{\"source\": \"" + String(100+currentModule) + "\",\"flavor\" :\"" + flavor2 + "\",\"choice\" :\"" + choice2 + "\"}"; jsonString2.toCharArray(jsonChar2, 100); if (currentModule > 0) { //if dip is set to 0, don't try to send udp.beginPacket(remoteIp, serverPort); udp.write(jsonChar2); udp.println(); udp.endPacket(); } else { //else if dip (currentModule) is 0, change colors /*write color*/ digitalWrite(redPin, redValue); digitalWrite(bluePin, blueValue); digitalWrite(greenPin, greenValue); } } delay(1); } /*end Loop*/ /*CALIBRATION*/ void calibrate(double *thresholds) { /*cal variables*/ int touchTime = 1000; //calibration for touching both sensors int sensorValue1 = 0; // the sensor value int sensorMin1 = 100000; // minimum sensor value int sensorMax1 = 0; // maximum sensor value int touchMax1 = 0; int sensorValue2 = 0; // the sensor value int sensorMin2 = 100000; // minimum sensor value int sensorMax2 = 0; // maximum sensor value int touchMax2 = 0; double idle1 = 0; //touch calibration variable. idle is halfway between max and min during not touched double idle2 = 0; double threshold1 = 0; double threshold2 = 0; int minTimer1 = 0; int counter = 0; int flagMe = 1; int debugOn = 1; while (millis() < calTime + touchTime) { counter = counter + 1; /* Moving Average*/ // subtract the last reading: total1 = total1 - readings1[readIndex]; total2 = total2 - readings2[readIndex]; // read from the sensor: readings1[readIndex] = touchRead(inputPin1); readings2[readIndex] = touchRead(inputPin2); // add the reading to the total: total1 = total1 + readings1[readIndex]; total2 = total2 + readings2[readIndex]; // advance to the next position in the array: readIndex = readIndex + 1; // if we're at the end of the array... if (readIndex >= numReadings) { // ...wrap around to the beginning: readIndex = 0; } // calculate the average: average1 = total1 / numReadings; average2 = total2 / numReadings; /*calculate min/maxes*/ if (counter > numReadings * 2 && millis() < calTime) { //give it some for moving average to take affect // record the maximum sensor value if ( average1 > sensorMax1) { sensorMax1 = average1; } // record the minimum sensor value if ( average1 < sensorMin1) { sensorMin1 = average1; } // record the maximum sensor value if ( average2 > sensorMax2) { sensorMax2 = average2; } // record the minimum sensor value if (average2 < sensorMin2) { sensorMin2 = average2; } } else if (millis() > calTime) { //only used for touch calibration // record the maximum sensor value if ( average1 > touchMax1) { touchMax1 = average1; } // record the maximum sensor value if ( average2 > touchMax2) { touchMax2 = average2; } } } /*method 1, if calibration includes a touch*/ idle1 = (sensorMax1 + sensorMin1) / 2; idle2 = (sensorMax2 + sensorMin2) / 2; thresholds[0] = idle1 + .5 * (touchMax1 - idle1); //calculate a threshold for trigger thresholds[1] = idle2 + .5 * (touchMax2 - idle2); //calculate a threshold for trigger /*method2: for calibration without touching sensor. */ thresholds[0] = sensorMax1 + thresholdScale1 * (sensorMax1 - sensorMin1); //calculate a threshold for trigger thresholds[1] = sensorMax2 + thresholdScale2 * (sensorMax2 - sensorMin2); //calculate a threshold for trigger // delay(1); } void getMAC() { delay(1000); Serial.println("Reading MAC from hardware..."); read_mac(); Serial.print("MAC: "); print_mac(); Serial.println(); Serial.println("Finished."); } //Reset Ethernet Module void resetEthernet() { pinMode(resetPin, OUTPUT); digitalWrite(resetPin, LOW); delayMicroseconds(10); //delay(1000); pinMode(resetPin, INPUT); Serial.println("Reset Done"); delay(1000); } int readDIPAddress() { int address; // State of each switch (0 or 1) int s0state; int s1state; int s2state; int s3state; pinMode(s0, INPUT_PULLUP); pinMode(s1, INPUT_PULLUP); pinMode(s2, INPUT_PULLUP); pinMode(s3, INPUT_PULLUP); delay(20); s0state = digitalReadFast(s0); s1state = digitalReadFast(s1); s2state = digitalReadFast(s2); s3state = digitalReadFast(s3); bitWrite(address, 0, !s0state); bitWrite(address, 1, !s1state); bitWrite(address, 2, !s2state); bitWrite(address, 3, !s3state); Serial.print("DIP Address => "); Serial.println(address); //delay(2000); // Serial.println(muxValue); return address; }
[ "mjkoehle@gmail.com" ]
mjkoehle@gmail.com
6d0dfa05bf9b0e89eeec206b2b4a0309a8b7c095
f7a2c96acedbe65f537229d7c52bfc978a28fdc4
/BuildFactory/YabScrollView.h
5de32525714fc2c3ded3a2f46498c80278489701
[]
no_license
lorglas/yab-1.0
23fcf708983b12a9e82dcc75cea2293a0670cffc
c5c4e926abdbd5d48be80e1ae2b01510b6f96c21
refs/heads/master
2022-04-24T09:40:53.139498
2020-04-30T07:42:39
2020-04-30T07:42:39
258,479,303
0
0
null
null
null
null
UTF-8
C++
false
false
651
h
#ifndef YABSCROLLVIEW_H #define YABSCROLLVIEW_H #include <ScrollView.h> class YabScrollView : public BScrollView { public: YabScrollView(const char *name,BView *target,uint32 resizeMask = B_FOLLOW_LEFT | B_FOLLOW_TOP,uint32 flags = 0,bool horizontal = false,bool vertical = false, border_style border = B_FANCY_BORDER); virtual void MouseMoved(BPoint pt, uint32 code, const BMessage *msg); virtual void MouseUp(BPoint pt); virtual void MouseDown(BPoint pt); int mouseMovedInfo; int mouseStateInfo; int mouseX; int mouseY; uint mouseLButton; uint mouseMButton; uint mouseRButton; private: int prevMouseStateInfo; }; #endif
[ "noreply@github.com" ]
noreply@github.com
0aa7d3897b48e6d333697c49bac1a7d628e370f5
37b6b22452bfcebbcb87672027851284bf104b8a
/source/net/io_stage.h
d0d56bbb553d88766e38ff725558ffe98c7fe2bf
[]
no_license
fanfeixiang/minotaur
7478a71325b7e7d18ff16e94e72b5cddc1b2e80f
477f5aaa5bf8f54684d8e1ffb46d1ea8791e1884
refs/heads/master
2020-12-11T06:12:00.664021
2015-04-07T09:44:44
2015-04-07T09:44:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
389
h
#ifndef _MINOTAUR_IO_STAGE_H_ #define _MINOTAUR_IO_STAGE_H_ /** * @file io_stage.h * @author Wolfhead */ #include "../stage.h" namespace minotaur { class IOStage : public Stage { protected: virtual uint32_t HashMessage(EventMessage) { return IODescriptorFactory::GetVersion(message.descriptor_id) % worker_count } }; } //namespace minotaur #endif // _MINOTAUR_IO_STAGE_H_
[ "wolfhead87@gmail.com" ]
wolfhead87@gmail.com
f5dda3b842019571d9ac0050adcf70034d494972
3c6ed046eda83e35ab754883a59dcb7099233b39
/media/base/android/media_codec_bridge_impl.cc
83cf68a74fceb40128f647cfe31cce71420085ef
[ "BSD-3-Clause" ]
permissive
ssln2014/chromium
66c5021c8893313dee78b963082cbdf948bd2d6a
4bad77148cc4a36373e40cf985444bc649c0eeff
refs/heads/master
2023-03-06T03:21:39.801883
2019-06-08T16:11:10
2019-06-08T16:11:10
190,914,348
1
0
BSD-3-Clause
2019-06-08T17:08:38
2019-06-08T17:08:38
null
UTF-8
C++
false
false
23,655
cc
// Copyright (c) 2013 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. #include "media/base/android/media_codec_bridge_impl.h" #include <algorithm> #include <limits> #include <memory> #include <utility> #include "base/android/build_info.h" #include "base/android/jni_android.h" #include "base/android/jni_array.h" #include "base/android/jni_string.h" #include "base/logging.h" #include "base/memory/ptr_util.h" #include "base/numerics/safe_conversions.h" #include "base/strings/string_util.h" #include "jni/MediaCodecBridgeBuilder_jni.h" #include "jni/MediaCodecBridge_jni.h" #include "media/base/android/jni_hdr_metadata.h" #include "media/base/android/media_codec_util.h" #include "media/base/audio_codecs.h" #include "media/base/bit_reader.h" #include "media/base/subsample_entry.h" #include "media/base/video_codecs.h" using base::android::AttachCurrentThread; using base::android::ConvertJavaStringToUTF8; using base::android::ConvertUTF8ToJavaString; using base::android::JavaIntArrayToIntVector; using base::android::JavaRef; using base::android::ScopedJavaGlobalRef; using base::android::ScopedJavaLocalRef; using base::android::ToJavaByteArray; #define RETURN_ON_ERROR(condition) \ do { \ if (!(condition)) { \ LOG(ERROR) << "Unable to parse AAC header: " #condition; \ return false; \ } \ } while (0) namespace media { namespace { enum { kBufferFlagSyncFrame = 1, // BUFFER_FLAG_SYNC_FRAME kBufferFlagEndOfStream = 4, // BUFFER_FLAG_END_OF_STREAM kConfigureFlagEncode = 1, // CONFIGURE_FLAG_ENCODE }; using CodecSpecificData = std::vector<uint8_t>; // Parses |extra_data| to get info to be added to a Java MediaFormat. bool GetCodecSpecificDataForAudio(AudioCodec codec, const uint8_t* extra_data, size_t extra_data_size, int64_t codec_delay_ns, int64_t seek_preroll_ns, CodecSpecificData* output_csd0, CodecSpecificData* output_csd1, CodecSpecificData* output_csd2, bool* output_frame_has_adts_header) { *output_frame_has_adts_header = false; if (extra_data_size == 0 && codec != kCodecOpus) return true; switch (codec) { case kCodecVorbis: { if (extra_data[0] != 2) { LOG(ERROR) << "Invalid number of vorbis headers before the codec " << "header: " << extra_data[0]; return false; } size_t header_length[2]; // |total_length| keeps track of the total number of bytes before the last // header. size_t total_length = 1; const uint8_t* current_pos = extra_data; // Calculate the length of the first 2 headers. for (int i = 0; i < 2; ++i) { header_length[i] = 0; while (total_length < extra_data_size) { size_t size = *(++current_pos); total_length += 1 + size; if (total_length > 0x80000000) { LOG(ERROR) << "Vorbis header size too large"; return false; } header_length[i] += size; if (size < 0xFF) break; } if (total_length >= extra_data_size) { LOG(ERROR) << "Invalid vorbis header size in the extra data"; return false; } } current_pos++; // The first header is the identification header. output_csd0->assign(current_pos, current_pos + header_length[0]); // The last header is the codec header. output_csd1->assign(extra_data + total_length, extra_data + extra_data_size); break; } case kCodecAAC: { media::BitReader reader(extra_data, extra_data_size); // The following code is copied from aac.cc // TODO(qinmin): refactor the code in aac.cc to make it more reusable. uint8_t profile = 0; uint8_t frequency_index = 0; uint8_t channel_config = 0; RETURN_ON_ERROR(reader.ReadBits(5, &profile)); RETURN_ON_ERROR(reader.ReadBits(4, &frequency_index)); if (0xf == frequency_index) RETURN_ON_ERROR(reader.SkipBits(24)); RETURN_ON_ERROR(reader.ReadBits(4, &channel_config)); if (profile == 5 || profile == 29) { // Read extension config. uint8_t ext_frequency_index = 0; RETURN_ON_ERROR(reader.ReadBits(4, &ext_frequency_index)); if (ext_frequency_index == 0xf) RETURN_ON_ERROR(reader.SkipBits(24)); RETURN_ON_ERROR(reader.ReadBits(5, &profile)); } if (profile < 1 || profile > 4 || frequency_index == 0xf || channel_config > 7) { LOG(ERROR) << "Invalid AAC header"; return false; } output_csd0->push_back(profile << 3 | frequency_index >> 1); output_csd0->push_back((frequency_index & 0x01) << 7 | channel_config << 3); *output_frame_has_adts_header = true; break; } case kCodecOpus: { if (!extra_data || extra_data_size == 0 || codec_delay_ns < 0 || seek_preroll_ns < 0) { LOG(ERROR) << "Invalid Opus Header"; return false; } // csd0 - Opus Header output_csd0->assign(extra_data, extra_data + extra_data_size); // csd1 - Codec Delay const uint8_t* codec_delay_ns_ptr = reinterpret_cast<const uint8_t*>(&codec_delay_ns); output_csd1->assign(codec_delay_ns_ptr, codec_delay_ns_ptr + sizeof(int64_t)); // csd2 - Seek Preroll const uint8_t* seek_preroll_ns_ptr = reinterpret_cast<const uint8_t*>(&seek_preroll_ns); output_csd2->assign(seek_preroll_ns_ptr, seek_preroll_ns_ptr + sizeof(int64_t)); break; } default: LOG(ERROR) << "Invalid header encountered for codec: " << GetCodecName(codec); return false; } return true; } } // namespace // static std::unique_ptr<MediaCodecBridge> MediaCodecBridgeImpl::CreateAudioDecoder( const AudioDecoderConfig& config, const JavaRef<jobject>& media_crypto, base::RepeatingClosure on_buffers_available_cb) { DVLOG(2) << __func__ << ": " << config.AsHumanReadableString() << " media_crypto:" << media_crypto.obj(); if (!MediaCodecUtil::IsMediaCodecAvailable()) return nullptr; const std::string mime = MediaCodecUtil::CodecToAndroidMimeType(config.codec()); if (mime.empty()) return nullptr; JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jstring> j_mime = ConvertUTF8ToJavaString(env, mime); const int channel_count = ChannelLayoutToChannelCount(config.channel_layout()); // It's important that the multiplication is first in this calculation to // reduce the precision loss due to integer truncation. const int64_t codec_delay_ns = base::Time::kNanosecondsPerSecond * config.codec_delay() / config.samples_per_second(); const int64_t seek_preroll_ns = config.seek_preroll().InMicroseconds() * base::Time::kNanosecondsPerMicrosecond; CodecSpecificData csd0, csd1, csd2; bool output_frame_has_adts_header; if (!GetCodecSpecificDataForAudio(config.codec(), config.extra_data().data(), config.extra_data().size(), codec_delay_ns, seek_preroll_ns, &csd0, &csd1, &csd2, &output_frame_has_adts_header)) { return nullptr; } ScopedJavaLocalRef<jbyteArray> j_csd0 = ToJavaByteArray(env, csd0); ScopedJavaLocalRef<jbyteArray> j_csd1 = ToJavaByteArray(env, csd1); ScopedJavaLocalRef<jbyteArray> j_csd2 = ToJavaByteArray(env, csd2); ScopedJavaGlobalRef<jobject> j_bridge( Java_MediaCodecBridgeBuilder_createAudioDecoder( env, j_mime, media_crypto, config.samples_per_second(), channel_count, j_csd0, j_csd1, j_csd2, output_frame_has_adts_header, !!on_buffers_available_cb)); if (j_bridge.is_null()) return nullptr; return base::WrapUnique(new MediaCodecBridgeImpl( std::move(j_bridge), std::move(on_buffers_available_cb))); } // static std::unique_ptr<MediaCodecBridge> MediaCodecBridgeImpl::CreateVideoDecoder( VideoCodec codec, CodecType codec_type, const gfx::Size& size, const JavaRef<jobject>& surface, const JavaRef<jobject>& media_crypto, const CodecSpecificData& csd0, const CodecSpecificData& csd1, const VideoColorSpace& color_space, const base::Optional<HDRMetadata>& hdr_metadata, bool allow_adaptive_playback, base::RepeatingClosure on_buffers_available_cb) { if (!MediaCodecUtil::IsMediaCodecAvailable()) return nullptr; const std::string mime = MediaCodecUtil::CodecToAndroidMimeType(codec); if (mime.empty()) return nullptr; JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jstring> j_mime = ConvertUTF8ToJavaString(env, mime); ScopedJavaLocalRef<jbyteArray> j_csd0 = ToJavaByteArray(env, csd0.data(), csd0.size()); ScopedJavaLocalRef<jbyteArray> j_csd1 = ToJavaByteArray(env, csd1.data(), csd1.size()); std::unique_ptr<JniHdrMetadata> jni_hdr_metadata; if (hdr_metadata.has_value()) { jni_hdr_metadata.reset( new JniHdrMetadata(color_space, hdr_metadata.value())); } ScopedJavaLocalRef<jobject> j_hdr_metadata( jni_hdr_metadata ? jni_hdr_metadata->obj() : nullptr); ScopedJavaGlobalRef<jobject> j_bridge( Java_MediaCodecBridgeBuilder_createVideoDecoder( env, j_mime, static_cast<int>(codec_type), media_crypto, size.width(), size.height(), surface, j_csd0, j_csd1, j_hdr_metadata, allow_adaptive_playback, !!on_buffers_available_cb)); if (j_bridge.is_null()) return nullptr; return base::WrapUnique(new MediaCodecBridgeImpl( std::move(j_bridge), std::move(on_buffers_available_cb))); } // static std::unique_ptr<MediaCodecBridge> MediaCodecBridgeImpl::CreateVideoEncoder( VideoCodec codec, const gfx::Size& size, int bit_rate, int frame_rate, int i_frame_interval, int color_format) { if (!MediaCodecUtil::IsMediaCodecAvailable()) return nullptr; const std::string mime = MediaCodecUtil::CodecToAndroidMimeType(codec); if (mime.empty()) return nullptr; JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jstring> j_mime = ConvertUTF8ToJavaString(env, mime); ScopedJavaGlobalRef<jobject> j_bridge( Java_MediaCodecBridgeBuilder_createVideoEncoder( env, j_mime, size.width(), size.height(), bit_rate, frame_rate, i_frame_interval, color_format)); if (j_bridge.is_null()) return nullptr; return base::WrapUnique(new MediaCodecBridgeImpl(std::move(j_bridge))); } // static void MediaCodecBridgeImpl::SetupCallbackHandlerForTesting() { // Callback APIs are only available on M+, so do nothing if below that. if (base::android::BuildInfo::GetInstance()->sdk_int() < base::android::SDK_VERSION_MARSHMALLOW) { return; } JNIEnv* env = AttachCurrentThread(); Java_MediaCodecBridge_createCallbackHandlerForTesting(env); } MediaCodecBridgeImpl::MediaCodecBridgeImpl( ScopedJavaGlobalRef<jobject> j_bridge, base::RepeatingClosure on_buffers_available_cb) : on_buffers_available_cb_(std::move(on_buffers_available_cb)), j_bridge_(std::move(j_bridge)) { DCHECK(!j_bridge_.is_null()); if (!on_buffers_available_cb_) return; DCHECK_GE(base::android::BuildInfo::GetInstance()->sdk_int(), base::android::SDK_VERSION_MARSHMALLOW); // Note this should be done last since setBuffersAvailableListener() may // immediately invoke the callback if buffers came in during construction. Java_MediaCodecBridge_setBuffersAvailableListener( AttachCurrentThread(), j_bridge_, reinterpret_cast<intptr_t>(this)); } MediaCodecBridgeImpl::~MediaCodecBridgeImpl() { JNIEnv* env = AttachCurrentThread(); if (j_bridge_.obj()) Java_MediaCodecBridge_release(env, j_bridge_); } void MediaCodecBridgeImpl::Stop() { JNIEnv* env = AttachCurrentThread(); Java_MediaCodecBridge_stop(env, j_bridge_); } MediaCodecStatus MediaCodecBridgeImpl::Flush() { JNIEnv* env = AttachCurrentThread(); return static_cast<MediaCodecStatus>( Java_MediaCodecBridge_flush(env, j_bridge_)); } MediaCodecStatus MediaCodecBridgeImpl::GetOutputSize(gfx::Size* size) { JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jobject> result = Java_MediaCodecBridge_getOutputFormat(env, j_bridge_); MediaCodecStatus status = static_cast<MediaCodecStatus>( Java_GetOutputFormatResult_status(env, result)); if (status == MEDIA_CODEC_OK) { size->SetSize(Java_GetOutputFormatResult_width(env, result), Java_GetOutputFormatResult_height(env, result)); } return status; } MediaCodecStatus MediaCodecBridgeImpl::GetOutputSamplingRate( int* sampling_rate) { JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jobject> result = Java_MediaCodecBridge_getOutputFormat(env, j_bridge_); MediaCodecStatus status = static_cast<MediaCodecStatus>( Java_GetOutputFormatResult_status(env, result)); if (status == MEDIA_CODEC_OK) *sampling_rate = Java_GetOutputFormatResult_sampleRate(env, result); return status; } MediaCodecStatus MediaCodecBridgeImpl::GetOutputChannelCount( int* channel_count) { JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jobject> result = Java_MediaCodecBridge_getOutputFormat(env, j_bridge_); MediaCodecStatus status = static_cast<MediaCodecStatus>( Java_GetOutputFormatResult_status(env, result)); if (status == MEDIA_CODEC_OK) *channel_count = Java_GetOutputFormatResult_channelCount(env, result); return status; } MediaCodecStatus MediaCodecBridgeImpl::QueueInputBuffer( int index, const uint8_t* data, size_t data_size, base::TimeDelta presentation_time) { DVLOG(3) << __func__ << " " << index << ": " << data_size; if (data_size > base::checked_cast<size_t>(std::numeric_limits<int32_t>::max())) { return MEDIA_CODEC_ERROR; } if (data && !FillInputBuffer(index, data, data_size)) return MEDIA_CODEC_ERROR; JNIEnv* env = AttachCurrentThread(); return static_cast<MediaCodecStatus>(Java_MediaCodecBridge_queueInputBuffer( env, j_bridge_, index, 0, data_size, presentation_time.InMicroseconds(), 0)); } MediaCodecStatus MediaCodecBridgeImpl::QueueSecureInputBuffer( int index, const uint8_t* data, size_t data_size, const std::string& key_id, const std::string& iv, const std::vector<SubsampleEntry>& subsamples, const EncryptionScheme& encryption_scheme, base::TimeDelta presentation_time) { DVLOG(3) << __func__ << " " << index << ": " << data_size; if (data_size > base::checked_cast<size_t>(std::numeric_limits<int32_t>::max())) { return MEDIA_CODEC_ERROR; } if (data && !FillInputBuffer(index, data, data_size)) return MEDIA_CODEC_ERROR; JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jbyteArray> j_key_id = ToJavaByteArray( env, reinterpret_cast<const uint8_t*>(key_id.data()), key_id.size()); ScopedJavaLocalRef<jbyteArray> j_iv = ToJavaByteArray( env, reinterpret_cast<const uint8_t*>(iv.data()), iv.size()); // The MediaCodec.CryptoInfo documentation says to pass NULL for |clear_array| // to indicate that all data is encrypted. But it doesn't specify what // |cypher_array| and |subsamples_size| should be in that case. We pass // one subsample here just to be on the safe side. int num_subsamples = std::max(static_cast<size_t>(1), subsamples.size()); std::unique_ptr<jint[]> native_clear_array(new jint[num_subsamples]); std::unique_ptr<jint[]> native_cypher_array(new jint[num_subsamples]); if (subsamples.empty()) { native_clear_array[0] = 0; native_cypher_array[0] = data_size; } else { for (size_t i = 0; i < subsamples.size(); ++i) { DCHECK(subsamples[i].clear_bytes <= std::numeric_limits<uint16_t>::max()); if (subsamples[i].cypher_bytes > static_cast<uint32_t>(std::numeric_limits<jint>::max())) { return MEDIA_CODEC_ERROR; } native_clear_array[i] = subsamples[i].clear_bytes; native_cypher_array[i] = subsamples[i].cypher_bytes; } } ScopedJavaLocalRef<jintArray> clear_array = base::android::ToJavaIntArray( env, native_clear_array.get(), num_subsamples); ScopedJavaLocalRef<jintArray> cypher_array = base::android::ToJavaIntArray( env, native_cypher_array.get(), num_subsamples); return static_cast<MediaCodecStatus>( Java_MediaCodecBridge_queueSecureInputBuffer( env, j_bridge_, index, 0, j_iv, j_key_id, clear_array, cypher_array, num_subsamples, static_cast<int>(encryption_scheme.mode()), static_cast<int>(encryption_scheme.pattern().crypt_byte_block()), static_cast<int>(encryption_scheme.pattern().skip_byte_block()), presentation_time.InMicroseconds())); } void MediaCodecBridgeImpl::QueueEOS(int input_buffer_index) { DVLOG(3) << __func__ << ": " << input_buffer_index; JNIEnv* env = AttachCurrentThread(); Java_MediaCodecBridge_queueInputBuffer(env, j_bridge_, input_buffer_index, 0, 0, 0, kBufferFlagEndOfStream); } MediaCodecStatus MediaCodecBridgeImpl::DequeueInputBuffer( base::TimeDelta timeout, int* index) { JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jobject> result = Java_MediaCodecBridge_dequeueInputBuffer( env, j_bridge_, timeout.InMicroseconds()); *index = Java_DequeueInputResult_index(env, result); MediaCodecStatus status = static_cast<MediaCodecStatus>( Java_DequeueInputResult_status(env, result)); DVLOG(3) << __func__ << ": status: " << status << ", index: " << *index; return status; } MediaCodecStatus MediaCodecBridgeImpl::DequeueOutputBuffer( base::TimeDelta timeout, int* index, size_t* offset, size_t* size, base::TimeDelta* presentation_time, bool* end_of_stream, bool* key_frame) { JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jobject> result = Java_MediaCodecBridge_dequeueOutputBuffer(env, j_bridge_, timeout.InMicroseconds()); *index = Java_DequeueOutputResult_index(env, result); *offset = base::checked_cast<size_t>(Java_DequeueOutputResult_offset(env, result)); *size = base::checked_cast<size_t>( Java_DequeueOutputResult_numBytes(env, result)); if (presentation_time) { *presentation_time = base::TimeDelta::FromMicroseconds( Java_DequeueOutputResult_presentationTimeMicroseconds(env, result)); } int flags = Java_DequeueOutputResult_flags(env, result); if (end_of_stream) *end_of_stream = flags & kBufferFlagEndOfStream; if (key_frame) *key_frame = flags & kBufferFlagSyncFrame; MediaCodecStatus status = static_cast<MediaCodecStatus>( Java_DequeueOutputResult_status(env, result)); DVLOG(3) << __func__ << ": status: " << status << ", index: " << *index << ", offset: " << *offset << ", size: " << *size << ", flags: " << flags; return status; } void MediaCodecBridgeImpl::ReleaseOutputBuffer(int index, bool render) { DVLOG(3) << __func__ << ": " << index; JNIEnv* env = AttachCurrentThread(); Java_MediaCodecBridge_releaseOutputBuffer(env, j_bridge_, index, render); } MediaCodecStatus MediaCodecBridgeImpl::GetInputBuffer(int input_buffer_index, uint8_t** data, size_t* capacity) { JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jobject> j_buffer( Java_MediaCodecBridge_getInputBuffer(env, j_bridge_, input_buffer_index)); if (j_buffer.is_null()) return MEDIA_CODEC_ERROR; *data = static_cast<uint8_t*>(env->GetDirectBufferAddress(j_buffer.obj())); *capacity = base::checked_cast<size_t>(env->GetDirectBufferCapacity(j_buffer.obj())); return MEDIA_CODEC_OK; } MediaCodecStatus MediaCodecBridgeImpl::CopyFromOutputBuffer(int index, size_t offset, void* dst, size_t num) { const uint8_t* src_data = nullptr; size_t src_capacity = 0; MediaCodecStatus status = GetOutputBufferAddress(index, offset, &src_data, &src_capacity); if (status == MEDIA_CODEC_OK) { CHECK_GE(src_capacity, num); memcpy(dst, src_data, num); } return status; } MediaCodecStatus MediaCodecBridgeImpl::GetOutputBufferAddress( int index, size_t offset, const uint8_t** addr, size_t* capacity) { JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jobject> j_buffer( Java_MediaCodecBridge_getOutputBuffer(env, j_bridge_, index)); if (j_buffer.is_null()) return MEDIA_CODEC_ERROR; const size_t total_capacity = env->GetDirectBufferCapacity(j_buffer.obj()); CHECK_GE(total_capacity, offset); *addr = reinterpret_cast<const uint8_t*>( env->GetDirectBufferAddress(j_buffer.obj())) + offset; *capacity = total_capacity - offset; return MEDIA_CODEC_OK; } void MediaCodecBridgeImpl::OnBuffersAvailable( JNIEnv* /* env */, const base::android::JavaParamRef<jobject>& /* obj */) { on_buffers_available_cb_.Run(); } std::string MediaCodecBridgeImpl::GetName() { if (base::android::BuildInfo::GetInstance()->sdk_int() < base::android::SDK_VERSION_JELLY_BEAN_MR2) return ""; JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jstring> j_name = Java_MediaCodecBridge_getName(env, j_bridge_); return ConvertJavaStringToUTF8(env, j_name); } bool MediaCodecBridgeImpl::SetSurface(const JavaRef<jobject>& surface) { DCHECK_GE(base::android::BuildInfo::GetInstance()->sdk_int(), base::android::SDK_VERSION_MARSHMALLOW); JNIEnv* env = AttachCurrentThread(); return Java_MediaCodecBridge_setSurface(env, j_bridge_, surface); } void MediaCodecBridgeImpl::SetVideoBitrate(int bps, int frame_rate) { JNIEnv* env = AttachCurrentThread(); Java_MediaCodecBridge_setVideoBitrate(env, j_bridge_, bps, frame_rate); } void MediaCodecBridgeImpl::RequestKeyFrameSoon() { JNIEnv* env = AttachCurrentThread(); Java_MediaCodecBridge_requestKeyFrameSoon(env, j_bridge_); } bool MediaCodecBridgeImpl::FillInputBuffer(int index, const uint8_t* data, size_t size) { uint8_t* dst = nullptr; size_t capacity = 0; if (GetInputBuffer(index, &dst, &capacity) != MEDIA_CODEC_OK) { LOG(ERROR) << "GetInputBuffer failed"; return false; } CHECK(dst); if (size > capacity) { LOG(ERROR) << "Input buffer size " << size << " exceeds MediaCodec input buffer capacity: " << capacity; return false; } memcpy(dst, data, size); return true; } } // namespace media
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
ad183c5e6f893daa35290e054546ac4648a41a9a
2482d7f225d0e2a30fd86fc884d1b09f0f709a67
/source/fen/FEN.cpp
6338fb03b7bc7b8de27ee9b920443123d37be304
[]
no_license
EduardGomezEscandell/ConsoleChess
0f194683b6e6aad16d562077bbf9b132c999d639
bc2a2ef7e262b320633f4120b2ec0a8597f55b93
refs/heads/master
2023-04-27T13:13:18.258816
2021-05-10T17:01:38
2021-05-10T17:01:38
356,655,820
0
0
null
null
null
null
UTF-8
C++
false
false
7,648
cpp
#include "FEN.h" #include "../defines.h" #include "regex" namespace ConsoleChess { std::tuple<PieceSet, Colour> GetPieceFromFEN(char c) { Colour col = Colour::UNDEFINED; if(c >= 'a' && c <= 'z') { col = Colour::BLACK; c += 'A' - 'a'; // Capitalizing } else if(c >= 'A' && c <= 'Z') { col = Colour::WHITE; } PieceSet piece; switch (c) { case 'P': piece = PieceSet::PAWN; break; case 'R': piece = PieceSet::ROOK; break; case 'B': piece = PieceSet::BISHOP; break; case 'Q': piece = PieceSet::QUEEN; break; case 'K': piece = PieceSet::KING; break; case 'N': piece = PieceSet::KNIGHT; break; default: piece = PieceSet::NONE; } return std::tie(piece, col); } bool FEN::Validator(const char * str) { static const std::regex regex(R"((([rnbqkpRNBQKP1-8]{1,8}|[1-8])\/){7}([rnbqkpRNBQKP1-8]{1,8}|[1-8])( [wb] ((K{0,1}Q{0,1}k{0,1}q{0,1})|-) (-|[a-h][36]) [0-9]+ [0-9]+){0,1})"); bool valid = std::regex_match(str, regex); if(!valid) return false; // Ensuring all ranks have 8 files unsigned int counter = 0; for(const char * ptr = str; *ptr != '\0'; ptr++) { const char c = *ptr; if(c==' ') break; // End of block if(c=='/') { if(counter != 8) return false; counter=0; } else if(c > '0' && c<'9') { counter += static_cast<unsigned int>(c - '0'); } else { counter++; } } if(counter != 8) return false; // Last rank check return true; } /** * @brief Returns a board from a string containing Forsyth–Edwards Notation (FEN) * * @param str: The FEN string * @returns The board generated */ Board FEN::Reader(const char * str) { Board board; if(!FEN::Validator(str)) CHESS_THROW << "Invalid FEN : \n <" << str << ">\n"; const char * it = str-1; // Reading position block { unsigned int file = 0; unsigned int rank = 7; while(*(++it) != ' ') // Iterating chars until spacebar is reached { const char c = *it; if(c=='\0') return board; // Short notation if(c=='/') // End of rank { file = 0; rank--; } else if(c >= '0' && c <= '9') // Empty squares { file += (c - '0'); } else { Colour col; PieceSet piece_type; std::tie(piece_type, col) = GetPieceFromFEN(c); if(piece_type == PieceSet::NONE) { CHESS_THROW << "Unexpected character when reading FEN : " << c; } board.CreatePieceInLocation(piece_type, rank, file, col); file++; } } } // Active colour it++; if(*it == 'b') { board.SetColourToMove(Colour::BLACK); } else { board.SetColourToMove(Colour::WHITE); } it++; // Castling { bool WhiteLong = false; bool WhiteShort = false; bool BlackLong = false; bool BlackShort = false; while(*(++it) != ' ') // Iterating chars until spacebar is reached { switch (*it) { case 'K': WhiteShort = true; break; case 'Q': WhiteLong = true; break; case 'k': BlackShort = true; break; case 'q': BlackLong = true; break; case '-': break; } } if(!WhiteLong) { Piece * rook = board.pGetSquareContent(0,0); if(rook && rook->GetColour()==Colour::WHITE) rook->RemoveCastlingRights(); } if(!WhiteShort) { Piece * rook = board.pGetSquareContent(0,7); if(rook && rook->GetColour()==Colour::WHITE) rook->RemoveCastlingRights(); } if(!BlackLong) { Piece * rook = board.pGetSquareContent(7,0); if(rook && rook->GetColour()==Colour::BLACK) rook->RemoveCastlingRights(); } if(!BlackShort) { Piece * rook = board.pGetSquareContent(7,7); if(rook && rook->GetColour()==Colour::BLACK) rook->RemoveCastlingRights(); } } // En Passant target square it++; if(*it != '-') { const unsigned int file = *it - 'a'; it++; const unsigned int rank = *it - '1'; it++; board.SetEnPassantTarget(rank, file); } else { it++; } // Halfmove clock while(*(++it) != ' ') // Iterating chars until spacebar is reached; { // TODO } // Move counter it++; board.SetMoveCounter(atoi(it)); return board; } bool RookCanCastle(const Board & rBoard, const int rank, const int file, Colour colour) { const Piece * corner_piece = rBoard.pGetSquareContent(rank, file); if(!corner_piece) return false; // Square is empty if(corner_piece->GetPieceType() != PieceSet::ROOK) return false; // Square is occupied by another piece type if(corner_piece->GetColour() != colour) return false; // Rook is enemy rook return corner_piece->HasCastlingRights(); } std::string FEN::Writer(const Board & rBoard) { std::stringstream output; // Board state for(int r=7; r>=0; r--) { unsigned int count = 0; for(int f=0; f<8; f++) { const Square & square = rBoard.GetSquare(r,f); if(square.IsEmpty()) { count++; } else // There is a piece { if(count > 0) { output << count; count = 0; } output << square.pGetContent()->GetPieceCharacter(); } } // End of rank if(count > 0) { output << count; } if(r != 0) { output << '/'; } } output << ' '; // Active colour output << (rBoard.WhoMoves() == Colour::WHITE ? 'w' : 'b') << ' '; // Castling bool no_castling = true; if(rBoard.GetKing(Colour::WHITE) && rBoard.GetKing(Colour::WHITE)->HasCastlingRights()) { if(RookCanCastle(rBoard, 0, 7, Colour::WHITE)) { output << 'K'; no_castling=false; } if(RookCanCastle(rBoard, 0, 0, Colour::WHITE)) { output << 'Q'; no_castling=false; } } if(rBoard.GetKing(Colour::BLACK) && rBoard.GetKing(Colour::BLACK)->HasCastlingRights()) { if(RookCanCastle(rBoard, 7, 7, Colour::BLACK)) { output << 'k'; no_castling=false; } if(RookCanCastle(rBoard, 7, 0, Colour::BLACK)) { output << 'q'; no_castling=false; } } if(no_castling) { output << '-'; } output << ' '; // En passant: const Square * en_passant_square = rBoard.GetEnPassantSquare(); if(en_passant_square) { output << en_passant_square->GetName() << ' '; } else { output << "- "; } // Halfmove clock: TODO output << "0 "; // Fullmove clock output << rBoard.GetMoveCount(); return output.str(); } }
[ "eduard.gomez.escandell@gmail.com" ]
eduard.gomez.escandell@gmail.com
27572017d59e33eab3e315f37ce702512efd2614
ab1d32763fc98fdf206440ed1db02ae43a6d7f1c
/monitor/opmap/rectangle.h
f732a910fcf22d10f32ccafaac792c51daac3e08
[]
no_license
FeiMaXiao/git
1e8d215071fb9949dc15326f7f19706bbcc74719
705877fa6eef82ad7f991fd5f87bc126361450e2
refs/heads/master
2021-01-20T01:35:16.449443
2017-04-24T14:33:27
2017-04-24T14:33:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,155
h
/** ****************************************************************************** * * @file rectangle.h * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2012. * @brief * @see The GNU Public License (GPL) Version 3 * @defgroup OPMapWidget * @{ * *****************************************************************************/ /* * 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 3 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., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef RECTANGLE_H #define RECTANGLE_H // #include <point.h> #include "size.h" #include "math.h" using namespace core; namespace internals { struct Rectangle { friend uint qHash(Rectangle const & rect); friend bool operator==(Rectangle const & lhs, Rectangle const & rhs); public: static Rectangle Empty; static Rectangle FromLTRB(int left, int top, int right, int bottom); Rectangle() { x = 0; y = 0; width = 0; height = 0; }; Rectangle(int x, int y, int width, int height) { this->x = x; this->y = y; this->width = width; this->height = height; } Rectangle(core::Point location, core::Size size) { this->x = location.X(); this->y = location.Y(); this->width = size.Width(); this->height = size.Height(); } core::Point GetLocation() { return core::Point(x, y); } void SetLocation(const core::Point &value) { x = value.X(); y = value.Y(); } int X() { return x; } int Y() { return y; } void SetX(const int &value) { x = value; } void SetY(const int &value) { y = value; } int Width() { return width; } void SetWidth(const int &value) { width = value; } int Height() { return height; } void SetHeight(const int &value) { height = value; } int Left() { return x; } int Top() { return y; } int Right() { return x + width; } int Bottom() { return y + height; } bool IsEmpty() { return height == 0 && width == 0 && x == 0 && y == 0; } bool operator==(const Rectangle &cSource) { return cSource.x == x && cSource.y == y && cSource.width == width && cSource.height == height; } bool operator!=(const Rectangle &cSource) { return !(*this == cSource); } bool Contains(const int &x, const int &y) { return this->x <= x && x < this->x + this->width && this->y <= y && y < this->y + this->height; } bool Contains(const core::Point &pt) { return Contains(pt.X(), pt.Y()); } bool Contains(const Rectangle &rect) { return (this->x <= rect.x) && ((rect.x + rect.width) <= (this->x + this->width)) && (this->y <= rect.y) && ((rect.y + rect.height) <= (this->y + this->height)); } void Inflate(const int &width, const int &height) { this->x -= width; this->y -= height; this->width += 2 * width; this->height += 2 * height; } void Inflate(Size &size) { Inflate(size.Width(), size.Height()); } static Rectangle Inflate(Rectangle rect, int x, int y); void Intersect(const Rectangle &rect) { Rectangle result = Rectangle::Intersect(rect, *this); this->x = result.X(); this->y = result.Y(); this->width = result.Width(); this->height = result.Height(); } static Rectangle Intersect(Rectangle a, Rectangle b); bool IntersectsWith(const Rectangle &rect) { return (rect.x < this->x + this->width) && (this->x < (rect.x + rect.width)) && (rect.y < this->y + this->height) && (this->y < rect.y + rect.height); } static Rectangle Union(const Rectangle &a, const Rectangle &b); void Offset(const core::Point &pos) { Offset(pos.X(), pos.Y()); } void Offset(const int &x, const int &y) { this->x += x; this->y += y; } QString ToString() { return "{X=" + QString::number(x) + ",Y=" + QString::number(y) + ",Width=" + QString::number(width) + ",Height=" + QString::number(height) + "}"; } private: int x; int y; int width; int height; }; } #endif // RECTANGLE_H
[ "419358583@qq.com" ]
419358583@qq.com
62b099c644c4eea6775a58f9b3db484e3e18949a
c26e9d3f92d95f7ce9d0fd5ef2c18dd95ec209a5
/summer_2k15_coding/codeforces/prime.cpp
eab22d93826c9398139794002dd48bd226d0eb9f
[]
no_license
crystal95/Competetive-Programming-at-different-platforms
c9ad1684f6258539309d07960ed6abfa7d1a16d0
92d283171b0ae0307e9ded473c6eea16f62cb60e
refs/heads/master
2021-01-09T21:44:28.175506
2016-03-27T21:26:26
2016-03-27T21:26:26
54,848,617
0
0
null
null
null
null
UTF-8
C++
false
false
301
cpp
#include<iostream> #include<math.h> using namespace std; int main() { int i,j,k,l,flag,count=0; for(i=2;i<=100005;i++) { flag=0; for(j=2;j<=sqrt(i);j++) { if(i%j==0) { flag=1; break; } } if(flag==0) { cout<<i<<", "; count++; } } cout<<count; return 0; }
[ "dsodhi95@gmail.com" ]
dsodhi95@gmail.com
7fcd96f2f4b62e7b068bc776c3678bbaef683f61
d16ee63414cb9b64540e7b6fe8657c42c2028c88
/module05/ex03/Bureaucrat.cpp
778c8ff07e8593e1bdaa522f66a45f9573511914
[]
no_license
borispeeters/cpp
79a7cb3e58c17c06ef7b7ee1120635cb78a7dfb5
25c41a046ffa5d8c8a3bd9a2be8004afcb09e141
refs/heads/master
2022-11-29T06:20:50.253031
2020-07-30T18:14:00
2020-07-30T18:14:00
269,397,656
1
0
null
null
null
null
UTF-8
C++
false
false
3,138
cpp
/* ************************************************************************** */ /* */ /* :::::::: */ /* Bureaucrat.cpp :+: :+: */ /* +:+ */ /* By: bpeeters <bpeeters@student.codam.nl> +#+ */ /* +#+ */ /* Created: 2020/06/18 16:29:59 by bpeeters #+# #+# */ /* Updated: 2020/07/27 11:11:05 by bpeeters ######## odam.nl */ /* */ /* ************************************************************************** */ #include <iostream> #include "Bureaucrat.hpp" #include "Form.hpp" Bureaucrat::GradeTooHighException::GradeTooHighException(): runtime_error("grade is too high") { } Bureaucrat::GradeTooHighException::~GradeTooHighException() throw() { } Bureaucrat::GradeTooLowException::GradeTooLowException(): runtime_error("grade is too low") { } Bureaucrat::GradeTooLowException::~GradeTooLowException() throw() { } Bureaucrat::Bureaucrat() { } Bureaucrat::Bureaucrat(std::string const & name, int grade): m_name(name), m_grade(grade) { if (m_grade < 1) throw Bureaucrat::GradeTooHighException(); if (m_grade > 150) throw Bureaucrat::GradeTooLowException(); } Bureaucrat::~Bureaucrat() { } Bureaucrat::Bureaucrat(Bureaucrat const & bureaucrat): m_name(bureaucrat.getName()), m_grade(bureaucrat.getGrade()) { if (m_grade < 1) throw Bureaucrat::GradeTooHighException(); if (m_grade > 150) throw Bureaucrat::GradeTooLowException(); } Bureaucrat& Bureaucrat::operator=(Bureaucrat const & bureaucrat) { if (&bureaucrat != this) { m_grade = bureaucrat.getGrade(); } return *this; } void Bureaucrat::signForm(Form & form) { try { form.beSigned(*this); std::cout << getName() << " signs " << form.getName() << '\n'; } catch(const std::exception& e) { std::cout << getName() << " cannot sign " << form.getName() << " because " << e.what() << '\n'; } } std::string const & Bureaucrat::getName() const { return m_name; } int Bureaucrat::getGrade() const { return m_grade; } void Bureaucrat::incrementGrade() { --m_grade; if (m_grade < 1) throw Bureaucrat::GradeTooHighException(); } void Bureaucrat::decrementGrade() { ++m_grade; if (m_grade > 150) throw Bureaucrat::GradeTooLowException(); } void Bureaucrat::executeForm(Form const & form) const { try { form.execute(*this); std::cout << this->getName() << " executes " << form.getName() << ".\n"; } catch(const std::exception& e) { std::cerr << this->getName() << " cannot execute form " << form.getName() << " because " << e.what() << '\n'; } } std::ostream& operator<<(std::ostream & out, const Bureaucrat & bureaucrat) { out << bureaucrat.getName() << ", bureaucrat grade " << bureaucrat.getGrade() << "."; return out; }
[ "borispeeters.bp@gmail.com" ]
borispeeters.bp@gmail.com
c38af71c7ed453e76a9fb02427d7075a0b419c88
751d0d0f0225706c13c18cbe3cc98cd3696af1a2
/tests/log.cpp
549ccd2348df56bbfe7ff6aca40774ca8b6e5630
[ "Apache-2.0" ]
permissive
mwlazlo/slugger
1d10feac006a38666ff4f7dd603f44109063e6f8
a3d267e723683edcd86bc6d10a5b07106b86bae4
refs/heads/master
2020-03-20T12:58:14.961521
2018-06-22T23:19:06
2018-06-22T23:19:06
137,445,203
0
0
null
null
null
null
UTF-8
C++
false
false
5,957
cpp
#include <iostream> #include <algorithm> #include <sstream> #include <iterator> #include <slugger/slugger.h> #include <time.h> #include <unistd.h> namespace log = slugger; void use_streams(const std::string& prefix="") { log::debug << prefix << "Hello debug" << std::endl; log::info << prefix << "Hello info" << std::endl; log::notice << prefix << "Hello notice" << std::endl; log::warning << prefix << "Hello warning" << std::endl; log::err << prefix << "Hello err" << std::endl; log::crit << prefix << "Hello crit" << std::endl; log::alert << prefix << "Hello alert" << std::endl; log::emerg << prefix << "Hello emerg" << std::endl; } void fork_use_streams() { if(!fork()) { log::debug << "Hello (forked) debug" << std::endl; log::info << "Hello (forked) info" << std::endl; log::notice << "Hello (forked) notice" << std::endl; log::warning << "Hello (forked) warning" << std::endl; log::err << "Hello (forked) err" << std::endl; log::crit << "Hello (forked) crit" << std::endl; log::alert << "Hello (forked) alert" << std::endl; log::emerg << "Hello (forked) emerg" << std::endl; } } void test_file() { log::destination::pointer f = log::stream::file::create("test.txt"); log::register_stream(f); use_streams(); } void test_null() { log::destination::pointer f = log::stream::null::create(); log::register_stream(f); use_streams(); } void test_std_err() { log::destination::pointer f = log::stream::std_err::create(); log::register_stream(f); use_streams(); } void test_std_out() { log::destination::pointer f = log::stream::std_out::create(); log::register_stream(f); use_streams(); } void test_sys_log() { log::destination::pointer f = log::stream::sys_log::create(); log::register_stream(f); log::set_program_name("logging test"); use_streams(); fork_use_streams(); } void test_tee() { log::destination::pointer rhs = log::stream::file::create("tee.txt"); log::destination::pointer lhs = log::stream::std_err::create(); log::destination::pointer f = log::stream::tee::create(lhs, rhs); log::register_stream(f); use_streams(); } void test_level() { std::cerr << "Setting log level to \"warning_t\"" << std::endl; log::set_logging_level(log::warning_t); use_streams(); } extern "C" { void* logger_thread(void*); } // need to mix things up a bit void rand_sleep() { struct timespec sleepTime; struct timespec remainingSleepTime; sleepTime.tv_sec=0; sleepTime.tv_nsec=10000; nanosleep(&sleepTime,&remainingSleepTime); } void* logger_thread(void* param) { unsigned int id = *(static_cast<unsigned int*>(param)); log::logging_level l = log::debug_t; switch(id) { case 0: l = log::debug_t; break; case 1: l = log::info_t; break; case 2: l = log::notice_t; break; case 3: l = log::err_t; break; case 4: l = log::alert_t; break; default: l = log::debug_t; break; } rand_sleep(); log::notice << "Hello, this is thread " << id << ". My log level is " << log::level_to_string(l) << std::endl; rand_sleep(); log::set_logging_level(l); rand_sleep(); log::debug << id << std::endl; rand_sleep(); log::info << id << std::endl; rand_sleep(); log::notice << id << std::endl; rand_sleep(); log::warning << id << std::endl; rand_sleep(); log::err << id << std::endl; rand_sleep(); log::crit << id << std::endl; rand_sleep(); log::alert << id << std::endl; rand_sleep(); log::emerg << id << std::endl; rand_sleep(); log::notice << "Bye, this is thread " << id << std::endl; return 0; } void test_thread() { static const int nthreads = 5; pthread_t threads[nthreads]; unsigned int ids[nthreads]; // storage for thread ids log::destination::pointer rhs = log::stream::sys_log::create(); log::destination::pointer lhs = log::stream::std_err::create(); log::destination::pointer f = log::stream::tee::create(lhs, rhs); log::register_stream(f); log::set_program_name("logging test"); std::cerr << "Starting " << nthreads << " logging threads, output to syslog AND stderr" << std::endl; for(int i = 0; i < nthreads; i++) { ids[i] = i; pthread_create(&threads[i], NULL, &logger_thread, static_cast<void*>(&ids[i])); } for(int i = 0; i < nthreads; i++) pthread_join(threads[i], NULL); } typedef void(*func)(); struct table_t { std::string name; func fun; bool operator==(const std::string &str) { return name == str; } }; std::ostream& operator<<(std::ostream& o, const table_t& t) { o << t.name; return o; } int main(int argc, char **argv) { table_t table[] = { { "file", &test_file }, { "null", &test_null }, { "std_err", &test_std_err }, { "std_out", &test_std_out }, { "sys_log", &test_sys_log }, { "tee", &test_tee }, { "level", &test_level }, { "thread", &test_thread }, { "", NULL } }; table_t* table_end = table + ((sizeof(table) / sizeof(table[0])) - 1); func fun = 0; if(argc == 2) { table_t* t = std::find(table, table_end, argv[1]); fun = t->fun; } if(!fun) { // concat options std::stringstream stream; std::copy(table, table_end, std::ostream_iterator<table_t>(stream, " | ")); std::string help = stream.str(); help.erase(help.length() - 2); std::cout << "Usage: " << argv[0] << ": " << help << std::endl; return 1; } fun(); return 0; } // vim: set ts=4 sw=4 et :
[ "matt.wlazlo@team.telstra.com" ]
matt.wlazlo@team.telstra.com
9284445225aa6fa98ce455025337b28e390dc18e
c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64
/Engine/Source/Runtime/Online/ICMP/Public/Icmp.h
e064baa5b9334959c308a90ca3cc8a35a83a722f
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
windystrife/UnrealEngine_NVIDIAGameWorks
c3c7863083653caf1bc67d3ef104fb4b9f302e2a
b50e6338a7c5b26374d66306ebc7807541ff815e
refs/heads/4.18-GameWorks
2023-03-11T02:50:08.471040
2022-01-13T20:50:29
2022-01-13T20:50:29
124,100,479
262
179
MIT
2022-12-16T05:36:38
2018-03-06T15:44:09
C++
UTF-8
C++
false
false
4,962
h
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" enum class EIcmpResponseStatus { /** We did receive a valid Echo reply back from the target host */ Success, /** We did not receive any results within the time limit */ Timeout, /** We got an unreachable error from another node on the way */ Unreachable, /** We could not resolve the target address to a valid IP address */ Unresolvable, /** Some internal error happened during setting up or sending the ping packet */ InternalError, /** not implemented - used to indicate we haven't implemented ICMP ping on this platform */ NotImplemented, }; struct FIcmpEchoResult { /** Status of the final response */ EIcmpResponseStatus Status; /** Addressed resolved by GetHostName */ FString ResolvedAddress; /** Reply received from this address */ FString ReplyFrom; /** Total round trip time */ float Time; FIcmpEchoResult() : Status(EIcmpResponseStatus::InternalError) , ResolvedAddress() , ReplyFrom() , Time(-1) {} FIcmpEchoResult(const FIcmpEchoResult& Other) : Status(Other.Status) , ResolvedAddress(Other.ResolvedAddress) , ReplyFrom(Other.ReplyFrom) , Time(Other.Time) {} }; typedef TFunction<void(FIcmpEchoResult)> FIcmpEchoResultCallback; DECLARE_DELEGATE_OneParam(FIcmpEchoResultDelegate, FIcmpEchoResult); // Simple ping interface that sends an ICMP packet to the given address and returns timing info for the reply if reachable class ICMP_API FIcmp { public: /** Send an ICMP echo packet and wait for a reply. * * The name resolution and ping send/receive will happen on a separate thread. * The third argument is a callback function that will be invoked on the game thread after the * a reply has been received from the target address, the timeout has expired, or if there * was an error resolving the address or delivering the ICMP message to it. * * Multiple pings can be issued concurrently and this function will ensure they're executed in * turn in order not to mix ping replies from different nodes. * * @param TargetAddress the target address to ping * @param Timeout max time to wait for a reply * @param HandleResult a callback function that will be called when the result is ready */ static void IcmpEcho(const FString& TargetAddress, float Timeout, FIcmpEchoResultCallback HandleResult); /** Send an ICMP echo packet and wait for a reply. * * This is a wrapper around the above function, taking a delegate instead of a function argument. * * @param TargetAddress the target address to ping * @param Timeout max time to wait for a reply * @param ResultDelegate a delegate that will be called when the result is ready */ static void IcmpEcho(const FString& TargetAddress, float Timeout, FIcmpEchoResultDelegate ResultDelegate) { IcmpEcho(TargetAddress, Timeout, [ResultDelegate](FIcmpEchoResult Result) { ResultDelegate.ExecuteIfBound(Result); }); } }; // Simple ping interface that sends an ICMP packet over UDP to the given address and returns timing info for the reply if reachable class ICMP_API FUDPPing { public: /** Send an ICMP echo packet and wait for a reply. * * The name resolution and ping send/receive will happen on a separate thread. * The third argument is a callback function that will be invoked on the game thread after the * a reply has been received from the target address, the timeout has expired, or if there * was an error resolving the address or delivering the ICMP message to it. * * Multiple pings can be issued concurrently and this function will ensure they're executed in * turn in order not to mix ping replies from different nodes. * * @param TargetAddress the target address to ping * @param Timeout max time to wait for a reply * @param HandleResult a callback function that will be called when the result is ready */ static void UDPEcho(const FString& TargetAddress, float Timeout, FIcmpEchoResultCallback HandleResult); /** Send an ICMP echo packet and wait for a reply. * * This is a wrapper around the above function, taking a delegate instead of a function argument. * * @param TargetAddress the target address to ping * @param Timeout max time to wait for a reply * @param ResultDelegate a delegate that will be called when the result is ready */ static void UDPEcho(const FString& TargetAddress, float Timeout, FIcmpEchoResultDelegate ResultDelegate) { UDPEcho(TargetAddress, Timeout, [ResultDelegate](FIcmpEchoResult Result) { ResultDelegate.ExecuteIfBound(Result); }); } }; #define EnumCase(Name) case EIcmpResponseStatus::Name : return TEXT(#Name) static const TCHAR* ToString(EIcmpResponseStatus Status) { switch (Status) { EnumCase(Success); EnumCase(Timeout); EnumCase(Unreachable); EnumCase(Unresolvable); EnumCase(InternalError); EnumCase(NotImplemented); default: return TEXT("Unknown"); } } #undef EnumCase
[ "tungnt.rec@gmail.com" ]
tungnt.rec@gmail.com
596c241d7c5e7d9b42b3915610a8a101d268fa6c
903eb9e5351671ac3691df243f15329303181bce
/TBB/Hello.cpp
815295f36b37f4c4768023c5cf7bd1041710e2de
[]
no_license
ramyasree9/Parallel-programming
9f128999a1c3d0a247786df9b5e10a99a3f2886e
8ec409714531694ef6fcd78743853859b2dfd50e
refs/heads/master
2021-01-10T05:38:48.290629
2016-02-10T19:23:00
2016-02-10T19:23:00
51,423,384
1
0
null
null
null
null
UTF-8
C++
false
false
798
cpp
#include<iostream> #include "tbb/task_scheduler_init.h" #include<tbb/parallel_for.h> #include<tbb/blocked_range.h> #include<math.h> using namespace std; using namespace tbb; class Hello { private: char *str; public: Hello(char s[]) :str(s){ } void operator () (const blocked_range<int> &r) const { for(int i=r.begin();i!=r.end();i++) { cout<<str<<" "<<GetCurrentThreadId()<<" "<<i<<endl; } } }; int main(int argc, char* argv[]) { int nthread; if(argc!=3) { cout<<"provide sufficient args <loop length> <no of threads>"; exit(-1); } nthread = strtol(argv[1], 0, 0); int num =atoi(argv[2]); task_scheduler_init init(num); char a[]="hello"; parallel_for(blocked_range<int>(0,nthread,1000),Hello(a)); if( nthread >= 1) init.terminate(); return 0; }
[ "ramyasusanth@gmail.com" ]
ramyasusanth@gmail.com
40b95932a6d1b799b844bfffe700452784e64cc8
8209f14e1949031e0023a04ab366bb49817237a6
/src/board/wheel.h
c38dee0698f5b4739ee7e8b09f83af0f54e3686e
[ "MIT" ]
permissive
WilliamLewww/Thane
3fdb6220c603c4dd3b65ceaad77ef2e922427049
c9fc1ea7780e51e78e3362670a08b1764843ed7e
refs/heads/master
2021-01-20T07:15:37.438212
2019-02-08T04:35:06
2019-02-08T04:35:06
101,527,318
0
0
MIT
2018-08-30T18:16:27
2017-08-27T03:27:00
C++
UTF-8
C++
false
false
3,773
h
#pragma once enum { LIP_SQUARE = 1, LIP_ROUND = 2 }; class Wheel { protected: std::string name; float width, height; int durometer; int lipID; int strength; int price; float currentHeightPercent; bool hasSkin; int color[3]; inline void setColor(int r, int g, int b) { color[0] = r; color[1] = g; color[2] = b; }; public: inline Wheel() { }; inline Wheel(std::string name, float width, float height, int durometer, int strength, int lipID, bool hasSkin) { this->name = name; this->width = width; this->height = height; this->durometer = durometer; this->strength = strength; this->lipID = lipID; this->hasSkin = hasSkin; }; inline std::string getName() { return name; }; inline int* getColor() { return color; }; inline float getWidth() { return width; }; inline float getHeight() { return height; }; inline float getCurrentHeightPercent() { return currentHeightPercent; }; inline int getDurometer() { return durometer; }; inline int getStrength() { return strength; }; inline int getPrice() { return price; }; inline int getLipID() { return lipID; }; inline bool getHasSkin() { return hasSkin; }; inline void decayWheel(float elapsedTimeSeconds, float angleDifference, float speed, bool shutdownSlide) { float rate = 0.00; if (shutdownSlide) { rate = (angleDifference * speed * 0.0001 * ((100.0 - (strength * (9.0 / 10.0))) / 100)) * elapsedTimeSeconds; } else { rate = (angleDifference * speed * 0.0001 * ((100.0 - strength) / 100)) * elapsedTimeSeconds; } if (currentHeightPercent - rate < 0) { currentHeightPercent = 0.00; } else { currentHeightPercent -= rate; } if (currentHeightPercent < 0.98 && hasSkin == true) { hasSkin = false; } if (currentHeightPercent < 0.89 && lipID == LIP_SQUARE) { lipID = LIP_ROUND; } }; inline float getTraction() { if (getCurrentHeightPercent() == 0) { return 4.0; } float traction = 0.00; float multiplier = 2.00; traction += ((durometer - 70.0) / 20.0); traction += ((60.0 - width) / 60.0) * 0.55; traction += ((75.0 - height) / 75.0) * 0.25; traction += (1.00 - currentHeightPercent) * 0.01; if (hasSkin == true) { multiplier -= 0.25; } if (lipID == LIP_SQUARE) { multiplier -= 0.12; } traction *= multiplier; return traction; }; inline float getRollSpeed() { if (getCurrentHeightPercent() == 0) { return 0.25; } float speed = 0.00; float multiplier = 2.00; speed += ((width - 40) / 40.0) * 0.27; speed += ((height + 8 - 60.0) / 15.0) * 0.38; speed += ((durometer - 70.0) / 30) * 0.17; speed += (currentHeightPercent) * 0.11; if (hasSkin == true) { multiplier += 0.16; } if (lipID == LIP_SQUARE) { multiplier -= 0.08; } speed *= multiplier; return speed; }; }; #include "wheel_presets.h" enum { WHEEL_MIDS = 1, WHEEL_BUTTERBALLS = 2, WHEEL_EXPERIMENTALS = 3, WHEEL_SNAKES = 4, WHEEL_STIMULUS = 5, WHEEL_ZIGZAGS = 6, WHEEL_COUNT = 6 }; static int getWheelCount() { return WHEEL_COUNT; } static std::string getWheelLipProfile(int lipID) { std::string lipProfile; switch (lipID) { case 1: lipProfile = "Square"; break; case 2: lipProfile = "Round"; break; } return lipProfile; }; static std::string getWheelHasSkin(bool hasSkin) { std::string skin; switch (hasSkin) { case true: skin = "True"; break; case false: skin = "False"; break; } return skin; } static Wheel getWheel(int wheelID) { Wheel wheel; switch (wheelID) { case WHEEL_MIDS: wheel = Mids(1); break; case WHEEL_BUTTERBALLS: wheel = Butterballs(1); break; case WHEEL_EXPERIMENTALS: wheel = Experimentals(1); break; case WHEEL_SNAKES: wheel = Snakes(1); break; case WHEEL_STIMULUS: wheel = Stimulus(1); break; case WHEEL_ZIGZAGS: wheel = ZigZags(1); break; } return wheel; };
[ "WilliamMilesLew@gmail.com" ]
WilliamMilesLew@gmail.com
b146fac6a6b18cd2c85777a4b322451b0fdb4327
dee6f95745a197055eadd35690c211b0b98eb8b6
/FaceDectector/FaceDectector/main.cpp
88538f9e903e38b5bf4f58cf534a4f4fe7c215db
[]
no_license
bsg16/FaceDetector
640677889e4c0a979d9838c2d52dd547dec765d5
6c26b0c95e1db6ec2591fc428c57416c2d1187bb
refs/heads/master
2020-06-02T22:33:05.522872
2019-06-11T08:48:49
2019-06-11T08:48:49
null
0
0
null
null
null
null
GB18030
C++
false
false
3,784
cpp
#include"detect.h" #include <opencv2/features2d.hpp> //#include "opencv2/features2d/features2d.hpp" Mat *spcm; //所有样本 Mat *intg; //积分图 int posnum; //正样本数 int negnum; //负样本数 int num; //总样本数 float *spcmweight; //每个样本的权重 vector<haarclassifier> haarcfs; //单个haar特征的分类器 vector<haarclassifier>weakcfs; //挑选出的最优弱分类器,与haar分类器是同一类 vector<strongclassifier>strongcfs; //级联分类器,由一组强分类器组成,一个强分类器由一组弱分类器线性组合 int weakcfnum =300; //挑选的弱分类器个数 int **weakoutput; //弱分类器对样本的预测值 int **haarcfoutput; int main() { GetLocalTime(&sys); printf("%02d:%02d:%02d \n", sys.wHour, sys.wMinute, sys.wSecond); cout << "训练开始弱分类器!!!\n"; readpic(spcm, posnum, num); negnum = num - posnum; intg = new Mat[num]; for (int i = 0; i < num; i++) integral(spcm[i], intg[i], CV_32SC1); /*getallclassifier(haarcfs,num,posnum); trainweakclassifier(haarcfs, weakcfs, num, posnum, weakcfnum,spcmweight,intg); cout << "最优弱分类器个数:" << weakcfs.size() << endl; float sumweight = 0; for (int i = 0; i < num; i++) sumweight += spcmweight[i]; cout << "样本权重之和" << sumweight; 获取弱分类器的输出 getweakclassifieroutput(weakcfs, num, intg, weakoutput); 写回分类器 writeweakclissfier(weakcfs, haarcfs, weakoutput, num, spcmweight); GetLocalTime(&sys); printf("\n%02d:%02d:%02d \n", sys.wHour, sys.wMinute, sys.wSecond); cout << "弱分类器训练结束!!!\n";*/ weakcfs.clear(); //读取分类器 readweakclissfier(weakcfs, weakcfnum, weakoutput, num); cout << "最优弱分类器个数:" << weakcfs.size() << endl; getweakclassifieroutput(weakcfs, num, intg, weakoutput); float tpr = 1.0; float fpr = 1.0; float neededfpr = 0.0000001; float neededtpr = 0.5; trainstrongclassifier(weakcfs, strongcfs, num, posnum,tpr,fpr,neededtpr,neededfpr, spcmweight, weakoutput); cout << "\n理论总正确率:" << tpr<<endl; cout << "理论总误报率:" << fpr << endl; GetLocalTime(&sys); printf("\n%02d:%02d:%02d \n", sys.wHour, sys.wMinute, sys.wSecond); cout << "训练结束!!!\n"; long long head1, tail1, freq; // timers QueryPerformanceFrequency((LARGE_INTEGER *)&freq); // QueryPerformanceCounter((LARGE_INTEGER *)&head1); // start time //Mat src = imread("faces_test/image_0042.jpg"); Mat src = imread("dong.jpg"); //src = imread("faces_test/image_0011.jpg"); //src = imread("dong.jpg"); vector<Rect> recs; vector<float> winweight; //窗口权重 Mat gray; Mat in; cvtColor(src, gray, CV_BGR2GRAY); integral(gray, in, CV_32SC1); detect(weakcfs, strongcfs, in, recs, winweight); //合并重叠的窗口 vector<Rect>win; emergewindow(recs, win, winweight); for (int i = 0; i < recs.size(); i++) rectangle(src, recs[i], Scalar(0, 255, 0), 2*winweight[i], 1, 0); /*for (int i = 0; i < win.size(); i++) { rectangle(src, win[i], Scalar(0, 255, 0), 1, 1, 0); }*/ /*for (int i = 0; i < recs.size(); i++) cout << recs[i].x<<" "<< recs[i].y<<" "<< recs[i].width<<" "<< winweight[i] << endl; cout <<"窗口数量:"<< recs.size();*/ QueryPerformanceCounter((LARGE_INTEGER *)&tail1); // end time double t = (tail1 - head1) * 1000.0 / freq; cout << "耗时:" << t << "ms" << endl; imshow("detectedfaces", src); Mat rst = src; mask(rst, win); imshow("mosaic", src); cv::waitKey(0); return 0; }
[ "noreply@github.com" ]
noreply@github.com
ec0f700d35d0ad61c564afd6966485c00b8f6672
9030ce2789a58888904d0c50c21591632eddffd7
/SDK/ARKSurvivalEvolved_PrimalItemSkin_SummerSwimShirt_Base_functions.cpp
d51cef8285c4e131246dc8a8f3bd5edf54d7e4aa
[ "MIT" ]
permissive
2bite/ARK-SDK
8ce93f504b2e3bd4f8e7ced184980b13f127b7bf
ce1f4906ccf82ed38518558c0163c4f92f5f7b14
refs/heads/master
2022-09-19T06:28:20.076298
2022-09-03T17:21:00
2022-09-03T17:21:00
232,411,353
14
5
null
null
null
null
UTF-8
C++
false
false
1,214
cpp
// ARKSurvivalEvolved (332.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_PrimalItemSkin_SummerSwimShirt_Base_parameters.hpp" namespace sdk { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function PrimalItemSkin_SummerSwimShirt_Base.PrimalItemSkin_SummerSwimShirt_Base_C.ExecuteUbergraph_PrimalItemSkin_SummerSwimShirt_Base // () // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void UPrimalItemSkin_SummerSwimShirt_Base_C::ExecuteUbergraph_PrimalItemSkin_SummerSwimShirt_Base(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function PrimalItemSkin_SummerSwimShirt_Base.PrimalItemSkin_SummerSwimShirt_Base_C.ExecuteUbergraph_PrimalItemSkin_SummerSwimShirt_Base"); UPrimalItemSkin_SummerSwimShirt_Base_C_ExecuteUbergraph_PrimalItemSkin_SummerSwimShirt_Base_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "sergey.2bite@gmail.com" ]
sergey.2bite@gmail.com
cab6477c812b56af639684a514aab315442fb5ff
95e6ab1436de9ba5fcf936639b9bbea0ab5282b5
/src/Inventory.h
26d3b06972efc0797d9bdbec57e80e840285bd03
[]
no_license
Justice-/ia
c46f3536ad8e80d7a24f69d8921aa3a049c8c177
78b7e5d063bef5c1defee7366feb2e2f2a409fbf
refs/heads/master
2021-01-16T22:50:27.890916
2013-06-16T14:50:36
2013-06-16T14:50:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,596
h
#ifndef INVENTORY_H #define INVENTORY_H #include <vector> #include <string> #include <iostream> #include "ItemData.h" #include "Item.h" using namespace std; class Engine; enum SlotTypes_t { slot_wielded, slot_wieldedAlt, slot_missiles, slot_armorBody //slot_cloak, //slot_ringLeft, //slot_ringRight, //slot_amulet }; struct InventorySlot { InventorySlot() : allowWieldedWeapon(false), allowMissile(false), allowArmor(false), allowCloak(false), allowAmulet(false), allowRing(false), item(NULL) { } bool allowWieldedWeapon, allowMissile, allowArmor, allowCloak, allowAmulet, allowRing; string interfaceName; SlotTypes_t id; Item* item; }; class Engine; class Inventory { public: Inventory(bool humanoid); ~Inventory() { for(unsigned int i = 0; i < slots_.size(); i++) if(slots_.at(i).item != NULL) delete slots_.at(i).item; for(unsigned int i = 0; i < general_.size(); i++) delete general_.at(i); for(unsigned int i = 0; i < intrinsics_.size(); i++) delete intrinsics_.at(i); } void dropAllNonIntrinsic(const coord pos, const bool ROLL_FOR_DESTRUCTION, Engine* const engine); bool hasItemInSlot(SlotTypes_t slotName) const; void putItemInSlot(SlotTypes_t slotName, Item* item, bool putInGeneral_ifOccupied = true, bool putInGeneral_ifSlotNotFound = true); void putItemInGeneral(Item* item); int getElementToStackItem(Item* item) const; void putItemInIntrinsics(Item* item); bool moveItemToGeneral(InventorySlot* inventorySlot); void moveItemFromGeneralToIntrinsics(const unsigned int GENERAL_INV_ELEMENT); void moveItemToSlot(InventorySlot* inventoryslot, const unsigned int GENERAL_INV_ELEMENT); void equipGeneralItemAndPossiblyEndTurn(const unsigned int GENERAL_INV_ELEMENT, const SlotTypes_t slotToEquip, Engine* const engine); // void equipGeneralItemToAltAndPossiblyEndTurn(const unsigned int GENERAL_INV_ELEMENT, Engine* const engine); void swapWieldedAndPrepared(const bool END_TURN, Engine* const engine); bool hasAmmoForFirearmInInventory(); int getElementWithItemType(const ItemId_t itemId) const; Item* getItemInSlot(SlotTypes_t slotName) const; Item* getItemInElement(const int GLOBAL_ELEMENT_NR) const; void removeItemInElementWithoutDeletingInstance(const int GLOBAL_ELEMENT); void decreaseItemInSlot(SlotTypes_t slotName); void decreaseItemInGeneral(unsigned element); void decreaseItemTypeInGeneral(const ItemId_t itemId); void deleteItemInGeneralWithElement(const unsigned ELEMENT); void removetemInGeneralWithPointer(Item* const item, const bool DELETE_ITEM); int getIntrinsicsSize() const { return intrinsics_.size(); } Item* getIntrinsicInElement(const int ELEMENT) const; Item* getLastItemInGeneral(); bool hasItemInGeneral(const ItemId_t id) const; int getItemStackSizeInGeneral(const ItemId_t id) const; bool hasDynamiteInGeneral() const; void decreaseDynamiteInGeneral(); //bool hasFirstAidInGeneral(); //void decreaseFirstAidInGeneral(); InventorySlot* getSlot(SlotTypes_t slotName); void sortGeneralInventory(Engine* const engine); vector<InventorySlot>* getSlots() { return &slots_; } vector<Item*>* getGeneral() { return &general_; } int getTotalItemWeight() const; void addSaveLines(vector<string>& lines) const; void setParametersFromSaveLines(vector<string>& lines, Engine* const engine); private: vector<InventorySlot> slots_; vector<Item*> general_; vector<Item*> intrinsics_; }; #endif
[ "m.tornq@gmail.com" ]
m.tornq@gmail.com
3bd4dbd7a473f5154d49a1f68738ed77e5309b39
20b9a508844f79eb4670fe33f87db2897f5bae7f
/Unreal/Plugins/AirSim/Source/Car/CarWheelFront.cpp
b29d4ddfb2e7f37bd3734d3ffa6bd739b591c1c2
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
jelaredulla/thesis
2f5714c013552c1775ad3b36274c0929fb0bc18c
dc348652cc0bd0a35e5d7506144d641510c2483b
refs/heads/master
2021-05-15T04:12:38.795907
2017-11-21T01:33:47
2017-11-21T01:33:47
105,950,956
0
0
null
null
null
null
UTF-8
C++
false
false
710
cpp
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "CarWheelFront.h" #include "TireConfig.h" #include "UObject/ConstructorHelpers.h" UCarWheelFront::UCarWheelFront() { ShapeRadius = 18.f; ShapeWidth = 15.0f; bAffectedByHandbrake = false; SteerAngle = 40.f; // Setup suspension forces SuspensionForceOffset = -4.0f; SuspensionMaxRaise = 8.0f; SuspensionMaxDrop = 12.0f; SuspensionNaturalFrequency = 9.0f; SuspensionDampingRatio = 1.05f; // Find the tire object and set the data for it static ConstructorHelpers::FObjectFinder<UTireConfig> TireData(TEXT("/AirSim/VehicleAdv/Vehicle/WheelData/Vehicle_FrontTireConfig.Vehicle_FrontTireConfig")); TireConfig = TireData.Object; }
[ "s4284683@eait.uq.edu.au" ]
s4284683@eait.uq.edu.au
2c63924c943404607f0fbca9d0118a4e7e7b6be5
c01dea2e9304eeb71a7144e17e68424b488af854
/C++/class 3/Session03/Student.h
f4df4a3f390e746ca8d599677567186e3a78589e
[]
no_license
sschatz1997/CS230
ab40230d15e5a08cf20290424bd54ad9b3613949
acdeca54b5f2379e4384f859067006d6d067b895
refs/heads/master
2020-07-25T03:03:14.092954
2020-06-08T22:44:54
2020-06-08T22:44:54
208,144,454
0
0
null
null
null
null
UTF-8
C++
false
false
712
h
//Student.h #include<iostream> #include<string> using namespace std; class Student{ public: //constructor Student(); Student(string first, string last); Student(string first, string last, string i, double g); //accessors void print() const; string getName() const; string getID() const; double getGPA() const; //mutators void setName(string first, string last); void setGPA(double); void setID(string); private: string first_name; string last_name; string id; double gpa; };
[ "s.schatz1997@gmail.com" ]
s.schatz1997@gmail.com
a9ce31e13fe6cfc68e3ab09ccd6da5fe0b08f87f
dbc5fd6f0b741d07aca08cff31fe88d2f62e8483
/lib/IR/Attributes.cpp
30216bcde6808a06dd9d759fd53a6de7955662fb
[ "LicenseRef-scancode-unknown-license-reference", "NCSA" ]
permissive
yrnkrn/zapcc
647246a2ed860f73adb49fa1bd21333d972ff76b
c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50
refs/heads/master
2023-03-08T22:55:12.842122
2020-07-21T10:21:59
2020-07-21T10:21:59
137,340,494
1,255
88
NOASSERTION
2020-07-21T10:22:01
2018-06-14T10:00:31
C++
UTF-8
C++
false
false
54,249
cpp
//===- Attributes.cpp - Implement AttributesList --------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // \file // \brief This file implements the Attribute, AttributeImpl, AttrBuilder, // AttributeListImpl, and AttributeList classes. // //===----------------------------------------------------------------------===// #include "llvm/IR/Attributes.h" #include "AttributeImpl.h" #include "LLVMContextImpl.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/FoldingSet.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Twine.h" #include "llvm/IR/Function.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Type.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> #include <cassert> #include <climits> #include <cstddef> #include <cstdint> #include <limits> #include <map> #include <string> #include <tuple> #include <utility> using namespace llvm; //===----------------------------------------------------------------------===// // Attribute Construction Methods //===----------------------------------------------------------------------===// // allocsize has two integer arguments, but because they're both 32 bits, we can // pack them into one 64-bit value, at the cost of making said value // nonsensical. // // In order to do this, we need to reserve one value of the second (optional) // allocsize argument to signify "not present." static const unsigned AllocSizeNumElemsNotPresent = -1; static uint64_t packAllocSizeArgs(unsigned ElemSizeArg, const Optional<unsigned> &NumElemsArg) { assert((!NumElemsArg.hasValue() || *NumElemsArg != AllocSizeNumElemsNotPresent) && "Attempting to pack a reserved value"); return uint64_t(ElemSizeArg) << 32 | NumElemsArg.getValueOr(AllocSizeNumElemsNotPresent); } static std::pair<unsigned, Optional<unsigned>> unpackAllocSizeArgs(uint64_t Num) { unsigned NumElems = Num & std::numeric_limits<unsigned>::max(); unsigned ElemSizeArg = Num >> 32; Optional<unsigned> NumElemsArg; if (NumElems != AllocSizeNumElemsNotPresent) NumElemsArg = NumElems; return std::make_pair(ElemSizeArg, NumElemsArg); } Attribute Attribute::get(LLVMContext &Context, Attribute::AttrKind Kind, uint64_t Val) { LLVMContextImpl *pImpl = Context.pImpl; FoldingSetNodeID ID; ID.AddInteger(Kind); if (Val) ID.AddInteger(Val); void *InsertPoint; AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint); if (!PA) { // If we didn't find any existing attributes of the same shape then create a // new one and insert it. if (!Val) PA = new EnumAttributeImpl(Kind); else PA = new IntAttributeImpl(Kind, Val); pImpl->AttrsSet.InsertNode(PA, InsertPoint); } // Return the Attribute that we found or created. return Attribute(PA); } Attribute Attribute::get(LLVMContext &Context, StringRef Kind, StringRef Val) { LLVMContextImpl *pImpl = Context.pImpl; FoldingSetNodeID ID; ID.AddString(Kind); if (!Val.empty()) ID.AddString(Val); void *InsertPoint; AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint); if (!PA) { // If we didn't find any existing attributes of the same shape then create a // new one and insert it. PA = new StringAttributeImpl(Kind, Val); pImpl->AttrsSet.InsertNode(PA, InsertPoint); } // Return the Attribute that we found or created. return Attribute(PA); } Attribute Attribute::getWithAlignment(LLVMContext &Context, uint64_t Align) { assert(isPowerOf2_32(Align) && "Alignment must be a power of two."); assert(Align <= 0x40000000 && "Alignment too large."); return get(Context, Alignment, Align); } Attribute Attribute::getWithStackAlignment(LLVMContext &Context, uint64_t Align) { assert(isPowerOf2_32(Align) && "Alignment must be a power of two."); assert(Align <= 0x100 && "Alignment too large."); return get(Context, StackAlignment, Align); } Attribute Attribute::getWithDereferenceableBytes(LLVMContext &Context, uint64_t Bytes) { assert(Bytes && "Bytes must be non-zero."); return get(Context, Dereferenceable, Bytes); } Attribute Attribute::getWithDereferenceableOrNullBytes(LLVMContext &Context, uint64_t Bytes) { assert(Bytes && "Bytes must be non-zero."); return get(Context, DereferenceableOrNull, Bytes); } Attribute Attribute::getWithAllocSizeArgs(LLVMContext &Context, unsigned ElemSizeArg, const Optional<unsigned> &NumElemsArg) { assert(!(ElemSizeArg == 0 && NumElemsArg && *NumElemsArg == 0) && "Invalid allocsize arguments -- given allocsize(0, 0)"); return get(Context, AllocSize, packAllocSizeArgs(ElemSizeArg, NumElemsArg)); } //===----------------------------------------------------------------------===// // Attribute Accessor Methods //===----------------------------------------------------------------------===// bool Attribute::isEnumAttribute() const { return pImpl && pImpl->isEnumAttribute(); } bool Attribute::isIntAttribute() const { return pImpl && pImpl->isIntAttribute(); } bool Attribute::isStringAttribute() const { return pImpl && pImpl->isStringAttribute(); } Attribute::AttrKind Attribute::getKindAsEnum() const { if (!pImpl) return None; assert((isEnumAttribute() || isIntAttribute()) && "Invalid attribute type to get the kind as an enum!"); return pImpl->getKindAsEnum(); } uint64_t Attribute::getValueAsInt() const { if (!pImpl) return 0; assert(isIntAttribute() && "Expected the attribute to be an integer attribute!"); return pImpl->getValueAsInt(); } StringRef Attribute::getKindAsString() const { if (!pImpl) return StringRef(); assert(isStringAttribute() && "Invalid attribute type to get the kind as a string!"); return pImpl->getKindAsString(); } StringRef Attribute::getValueAsString() const { if (!pImpl) return StringRef(); assert(isStringAttribute() && "Invalid attribute type to get the value as a string!"); return pImpl->getValueAsString(); } bool Attribute::hasAttribute(AttrKind Kind) const { return (pImpl && pImpl->hasAttribute(Kind)) || (!pImpl && Kind == None); } bool Attribute::hasAttribute(StringRef Kind) const { if (!isStringAttribute()) return false; return pImpl && pImpl->hasAttribute(Kind); } unsigned Attribute::getAlignment() const { assert(hasAttribute(Attribute::Alignment) && "Trying to get alignment from non-alignment attribute!"); return pImpl->getValueAsInt(); } unsigned Attribute::getStackAlignment() const { assert(hasAttribute(Attribute::StackAlignment) && "Trying to get alignment from non-alignment attribute!"); return pImpl->getValueAsInt(); } uint64_t Attribute::getDereferenceableBytes() const { assert(hasAttribute(Attribute::Dereferenceable) && "Trying to get dereferenceable bytes from " "non-dereferenceable attribute!"); return pImpl->getValueAsInt(); } uint64_t Attribute::getDereferenceableOrNullBytes() const { assert(hasAttribute(Attribute::DereferenceableOrNull) && "Trying to get dereferenceable bytes from " "non-dereferenceable attribute!"); return pImpl->getValueAsInt(); } std::pair<unsigned, Optional<unsigned>> Attribute::getAllocSizeArgs() const { assert(hasAttribute(Attribute::AllocSize) && "Trying to get allocsize args from non-allocsize attribute"); return unpackAllocSizeArgs(pImpl->getValueAsInt()); } std::string Attribute::getAsString(bool InAttrGrp) const { if (!pImpl) return ""; if (hasAttribute(Attribute::SanitizeAddress)) return "sanitize_address"; if (hasAttribute(Attribute::SanitizeHWAddress)) return "sanitize_hwaddress"; if (hasAttribute(Attribute::AlwaysInline)) return "alwaysinline"; if (hasAttribute(Attribute::ArgMemOnly)) return "argmemonly"; if (hasAttribute(Attribute::Builtin)) return "builtin"; if (hasAttribute(Attribute::ByVal)) return "byval"; if (hasAttribute(Attribute::Convergent)) return "convergent"; if (hasAttribute(Attribute::SwiftError)) return "swifterror"; if (hasAttribute(Attribute::SwiftSelf)) return "swiftself"; if (hasAttribute(Attribute::InaccessibleMemOnly)) return "inaccessiblememonly"; if (hasAttribute(Attribute::InaccessibleMemOrArgMemOnly)) return "inaccessiblemem_or_argmemonly"; if (hasAttribute(Attribute::InAlloca)) return "inalloca"; if (hasAttribute(Attribute::InlineHint)) return "inlinehint"; if (hasAttribute(Attribute::InReg)) return "inreg"; if (hasAttribute(Attribute::JumpTable)) return "jumptable"; if (hasAttribute(Attribute::MinSize)) return "minsize"; if (hasAttribute(Attribute::Naked)) return "naked"; if (hasAttribute(Attribute::Nest)) return "nest"; if (hasAttribute(Attribute::NoAlias)) return "noalias"; if (hasAttribute(Attribute::NoBuiltin)) return "nobuiltin"; if (hasAttribute(Attribute::NoCapture)) return "nocapture"; if (hasAttribute(Attribute::NoDuplicate)) return "noduplicate"; if (hasAttribute(Attribute::NoImplicitFloat)) return "noimplicitfloat"; if (hasAttribute(Attribute::NoInline)) return "noinline"; if (hasAttribute(Attribute::NonLazyBind)) return "nonlazybind"; if (hasAttribute(Attribute::NonNull)) return "nonnull"; if (hasAttribute(Attribute::NoRedZone)) return "noredzone"; if (hasAttribute(Attribute::NoReturn)) return "noreturn"; if (hasAttribute(Attribute::NoRecurse)) return "norecurse"; if (hasAttribute(Attribute::NoUnwind)) return "nounwind"; if (hasAttribute(Attribute::OptimizeNone)) return "optnone"; if (hasAttribute(Attribute::OptimizeForSize)) return "optsize"; if (hasAttribute(Attribute::ReadNone)) return "readnone"; if (hasAttribute(Attribute::ReadOnly)) return "readonly"; if (hasAttribute(Attribute::WriteOnly)) return "writeonly"; if (hasAttribute(Attribute::Returned)) return "returned"; if (hasAttribute(Attribute::ReturnsTwice)) return "returns_twice"; if (hasAttribute(Attribute::SExt)) return "signext"; if (hasAttribute(Attribute::Speculatable)) return "speculatable"; if (hasAttribute(Attribute::StackProtect)) return "ssp"; if (hasAttribute(Attribute::StackProtectReq)) return "sspreq"; if (hasAttribute(Attribute::StackProtectStrong)) return "sspstrong"; if (hasAttribute(Attribute::SafeStack)) return "safestack"; if (hasAttribute(Attribute::StrictFP)) return "strictfp"; if (hasAttribute(Attribute::StructRet)) return "sret"; if (hasAttribute(Attribute::SanitizeThread)) return "sanitize_thread"; if (hasAttribute(Attribute::SanitizeMemory)) return "sanitize_memory"; if (hasAttribute(Attribute::UWTable)) return "uwtable"; if (hasAttribute(Attribute::ZExt)) return "zeroext"; if (hasAttribute(Attribute::Cold)) return "cold"; // FIXME: These should be output like this: // // align=4 // alignstack=8 // if (hasAttribute(Attribute::Alignment)) { std::string Result; Result += "align"; Result += (InAttrGrp) ? "=" : " "; Result += utostr(getValueAsInt()); return Result; } auto AttrWithBytesToString = [&](const char *Name) { std::string Result; Result += Name; if (InAttrGrp) { Result += "="; Result += utostr(getValueAsInt()); } else { Result += "("; Result += utostr(getValueAsInt()); Result += ")"; } return Result; }; if (hasAttribute(Attribute::StackAlignment)) return AttrWithBytesToString("alignstack"); if (hasAttribute(Attribute::Dereferenceable)) return AttrWithBytesToString("dereferenceable"); if (hasAttribute(Attribute::DereferenceableOrNull)) return AttrWithBytesToString("dereferenceable_or_null"); if (hasAttribute(Attribute::AllocSize)) { unsigned ElemSize; Optional<unsigned> NumElems; std::tie(ElemSize, NumElems) = getAllocSizeArgs(); std::string Result = "allocsize("; Result += utostr(ElemSize); if (NumElems.hasValue()) { Result += ','; Result += utostr(*NumElems); } Result += ')'; return Result; } // Convert target-dependent attributes to strings of the form: // // "kind" // "kind" = "value" // if (isStringAttribute()) { std::string Result; Result += (Twine('"') + getKindAsString() + Twine('"')).str(); std::string AttrVal = pImpl->getValueAsString(); if (AttrVal.empty()) return Result; // Since some attribute strings contain special characters that cannot be // printable, those have to be escaped to make the attribute value printable // as is. e.g. "\01__gnu_mcount_nc" { raw_string_ostream OS(Result); OS << "=\""; PrintEscapedString(AttrVal, OS); OS << "\""; } return Result; } llvm_unreachable("Unknown attribute"); } bool Attribute::operator<(Attribute A) const { if (!pImpl && !A.pImpl) return false; if (!pImpl) return true; if (!A.pImpl) return false; return *pImpl < *A.pImpl; } //===----------------------------------------------------------------------===// // AttributeImpl Definition //===----------------------------------------------------------------------===// // Pin the vtables to this file. AttributeImpl::~AttributeImpl() = default; void EnumAttributeImpl::anchor() {} void IntAttributeImpl::anchor() {} void StringAttributeImpl::anchor() {} bool AttributeImpl::hasAttribute(Attribute::AttrKind A) const { if (isStringAttribute()) return false; return getKindAsEnum() == A; } bool AttributeImpl::hasAttribute(StringRef Kind) const { if (!isStringAttribute()) return false; return getKindAsString() == Kind; } Attribute::AttrKind AttributeImpl::getKindAsEnum() const { assert(isEnumAttribute() || isIntAttribute()); return static_cast<const EnumAttributeImpl *>(this)->getEnumKind(); } uint64_t AttributeImpl::getValueAsInt() const { assert(isIntAttribute()); return static_cast<const IntAttributeImpl *>(this)->getValue(); } StringRef AttributeImpl::getKindAsString() const { assert(isStringAttribute()); return static_cast<const StringAttributeImpl *>(this)->getStringKind(); } StringRef AttributeImpl::getValueAsString() const { assert(isStringAttribute()); return static_cast<const StringAttributeImpl *>(this)->getStringValue(); } bool AttributeImpl::operator<(const AttributeImpl &AI) const { // This sorts the attributes with Attribute::AttrKinds coming first (sorted // relative to their enum value) and then strings. if (isEnumAttribute()) { if (AI.isEnumAttribute()) return getKindAsEnum() < AI.getKindAsEnum(); if (AI.isIntAttribute()) return true; if (AI.isStringAttribute()) return true; } if (isIntAttribute()) { if (AI.isEnumAttribute()) return false; if (AI.isIntAttribute()) { if (getKindAsEnum() == AI.getKindAsEnum()) return getValueAsInt() < AI.getValueAsInt(); return getKindAsEnum() < AI.getKindAsEnum(); } if (AI.isStringAttribute()) return true; } if (AI.isEnumAttribute()) return false; if (AI.isIntAttribute()) return false; if (getKindAsString() == AI.getKindAsString()) return getValueAsString() < AI.getValueAsString(); return getKindAsString() < AI.getKindAsString(); } //===----------------------------------------------------------------------===// // AttributeSet Definition //===----------------------------------------------------------------------===// AttributeSet AttributeSet::get(LLVMContext &C, const AttrBuilder &B) { return AttributeSet(AttributeSetNode::get(C, B)); } AttributeSet AttributeSet::get(LLVMContext &C, ArrayRef<Attribute> Attrs) { return AttributeSet(AttributeSetNode::get(C, Attrs)); } AttributeSet AttributeSet::addAttribute(LLVMContext &C, Attribute::AttrKind Kind) const { if (hasAttribute(Kind)) return *this; AttrBuilder B; B.addAttribute(Kind); return addAttributes(C, AttributeSet::get(C, B)); } AttributeSet AttributeSet::addAttribute(LLVMContext &C, StringRef Kind, StringRef Value) const { AttrBuilder B; B.addAttribute(Kind, Value); return addAttributes(C, AttributeSet::get(C, B)); } AttributeSet AttributeSet::addAttributes(LLVMContext &C, const AttributeSet AS) const { if (!hasAttributes()) return AS; if (!AS.hasAttributes()) return *this; AttrBuilder B(AS); for (Attribute I : *this) B.addAttribute(I); return get(C, B); } AttributeSet AttributeSet::removeAttribute(LLVMContext &C, Attribute::AttrKind Kind) const { if (!hasAttribute(Kind)) return *this; AttrBuilder B(*this); B.removeAttribute(Kind); return get(C, B); } AttributeSet AttributeSet::removeAttribute(LLVMContext &C, StringRef Kind) const { if (!hasAttribute(Kind)) return *this; AttrBuilder B(*this); B.removeAttribute(Kind); return get(C, B); } AttributeSet AttributeSet::removeAttributes(LLVMContext &C, const AttrBuilder &Attrs) const { AttrBuilder B(*this); B.remove(Attrs); return get(C, B); } unsigned AttributeSet::getNumAttributes() const { return SetNode ? SetNode->getNumAttributes() : 0; } bool AttributeSet::hasAttribute(Attribute::AttrKind Kind) const { return SetNode ? SetNode->hasAttribute(Kind) : false; } bool AttributeSet::hasAttribute(StringRef Kind) const { return SetNode ? SetNode->hasAttribute(Kind) : false; } Attribute AttributeSet::getAttribute(Attribute::AttrKind Kind) const { return SetNode ? SetNode->getAttribute(Kind) : Attribute(); } Attribute AttributeSet::getAttribute(StringRef Kind) const { return SetNode ? SetNode->getAttribute(Kind) : Attribute(); } unsigned AttributeSet::getAlignment() const { return SetNode ? SetNode->getAlignment() : 0; } unsigned AttributeSet::getStackAlignment() const { return SetNode ? SetNode->getStackAlignment() : 0; } uint64_t AttributeSet::getDereferenceableBytes() const { return SetNode ? SetNode->getDereferenceableBytes() : 0; } uint64_t AttributeSet::getDereferenceableOrNullBytes() const { return SetNode ? SetNode->getDereferenceableOrNullBytes() : 0; } std::pair<unsigned, Optional<unsigned>> AttributeSet::getAllocSizeArgs() const { return SetNode ? SetNode->getAllocSizeArgs() : std::pair<unsigned, Optional<unsigned>>(0, 0); } std::string AttributeSet::getAsString(bool InAttrGrp) const { return SetNode ? SetNode->getAsString(InAttrGrp) : ""; } AttributeSet::iterator AttributeSet::begin() const { return SetNode ? SetNode->begin() : nullptr; } AttributeSet::iterator AttributeSet::end() const { return SetNode ? SetNode->end() : nullptr; } #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) LLVM_DUMP_METHOD void AttributeSet::dump() const { dbgs() << "AS =\n"; dbgs() << " { "; dbgs() << getAsString(true) << " }\n"; } #endif //===----------------------------------------------------------------------===// // AttributeSetNode Definition //===----------------------------------------------------------------------===// AttributeSetNode::AttributeSetNode(ArrayRef<Attribute> Attrs) : AvailableAttrs(0), NumAttrs(Attrs.size()) { // There's memory after the node where we can store the entries in. std::copy(Attrs.begin(), Attrs.end(), getTrailingObjects<Attribute>()); for (Attribute I : *this) { if (!I.isStringAttribute()) { AvailableAttrs |= ((uint64_t)1) << I.getKindAsEnum(); } } } AttributeSetNode *AttributeSetNode::get(LLVMContext &C, ArrayRef<Attribute> Attrs) { if (Attrs.empty()) return nullptr; // Otherwise, build a key to look up the existing attributes. LLVMContextImpl *pImpl = C.pImpl; FoldingSetNodeID ID; SmallVector<Attribute, 8> SortedAttrs(Attrs.begin(), Attrs.end()); std::sort(SortedAttrs.begin(), SortedAttrs.end()); for (Attribute Attr : SortedAttrs) Attr.Profile(ID); void *InsertPoint; AttributeSetNode *PA = pImpl->AttrsSetNodes.FindNodeOrInsertPos(ID, InsertPoint); // If we didn't find any existing attributes of the same shape then create a // new one and insert it. if (!PA) { // Coallocate entries after the AttributeSetNode itself. void *Mem = ::operator new(totalSizeToAlloc<Attribute>(SortedAttrs.size())); PA = new (Mem) AttributeSetNode(SortedAttrs); pImpl->AttrsSetNodes.InsertNode(PA, InsertPoint); } // Return the AttributeSetNode that we found or created. return PA; } AttributeSetNode *AttributeSetNode::get(LLVMContext &C, const AttrBuilder &B) { // Add target-independent attributes. SmallVector<Attribute, 8> Attrs; for (Attribute::AttrKind Kind = Attribute::None; Kind != Attribute::EndAttrKinds; Kind = Attribute::AttrKind(Kind + 1)) { if (!B.contains(Kind)) continue; Attribute Attr; switch (Kind) { case Attribute::Alignment: Attr = Attribute::getWithAlignment(C, B.getAlignment()); break; case Attribute::StackAlignment: Attr = Attribute::getWithStackAlignment(C, B.getStackAlignment()); break; case Attribute::Dereferenceable: Attr = Attribute::getWithDereferenceableBytes( C, B.getDereferenceableBytes()); break; case Attribute::DereferenceableOrNull: Attr = Attribute::getWithDereferenceableOrNullBytes( C, B.getDereferenceableOrNullBytes()); break; case Attribute::AllocSize: { auto A = B.getAllocSizeArgs(); Attr = Attribute::getWithAllocSizeArgs(C, A.first, A.second); break; } default: Attr = Attribute::get(C, Kind); } Attrs.push_back(Attr); } // Add target-dependent (string) attributes. for (const auto &TDA : B.td_attrs()) Attrs.emplace_back(Attribute::get(C, TDA.first, TDA.second)); return get(C, Attrs); } bool AttributeSetNode::hasAttribute(StringRef Kind) const { for (Attribute I : *this) if (I.hasAttribute(Kind)) return true; return false; } Attribute AttributeSetNode::getAttribute(Attribute::AttrKind Kind) const { if (hasAttribute(Kind)) { for (Attribute I : *this) if (I.hasAttribute(Kind)) return I; } return Attribute(); } Attribute AttributeSetNode::getAttribute(StringRef Kind) const { for (Attribute I : *this) if (I.hasAttribute(Kind)) return I; return Attribute(); } unsigned AttributeSetNode::getAlignment() const { for (Attribute I : *this) if (I.hasAttribute(Attribute::Alignment)) return I.getAlignment(); return 0; } unsigned AttributeSetNode::getStackAlignment() const { for (Attribute I : *this) if (I.hasAttribute(Attribute::StackAlignment)) return I.getStackAlignment(); return 0; } uint64_t AttributeSetNode::getDereferenceableBytes() const { for (Attribute I : *this) if (I.hasAttribute(Attribute::Dereferenceable)) return I.getDereferenceableBytes(); return 0; } uint64_t AttributeSetNode::getDereferenceableOrNullBytes() const { for (Attribute I : *this) if (I.hasAttribute(Attribute::DereferenceableOrNull)) return I.getDereferenceableOrNullBytes(); return 0; } std::pair<unsigned, Optional<unsigned>> AttributeSetNode::getAllocSizeArgs() const { for (Attribute I : *this) if (I.hasAttribute(Attribute::AllocSize)) return I.getAllocSizeArgs(); return std::make_pair(0, 0); } std::string AttributeSetNode::getAsString(bool InAttrGrp) const { std::string Str; for (iterator I = begin(), E = end(); I != E; ++I) { if (I != begin()) Str += ' '; Str += I->getAsString(InAttrGrp); } return Str; } //===----------------------------------------------------------------------===// // AttributeListImpl Definition //===----------------------------------------------------------------------===// /// Map from AttributeList index to the internal array index. Adding one happens /// to work, but it relies on unsigned integer wrapping. MSVC warns about /// unsigned wrapping in constexpr functions, so write out the conditional. LLVM /// folds it to add anyway. static constexpr unsigned attrIdxToArrayIdx(unsigned Index) { return Index == AttributeList::FunctionIndex ? 0 : Index + 1; } AttributeListImpl::AttributeListImpl(LLVMContext &C, ArrayRef<AttributeSet> Sets) : AvailableFunctionAttrs(0), Context(C), NumAttrSets(Sets.size()) { assert(!Sets.empty() && "pointless AttributeListImpl"); // There's memory after the node where we can store the entries in. std::copy(Sets.begin(), Sets.end(), getTrailingObjects<AttributeSet>()); // Initialize AvailableFunctionAttrs summary bitset. static_assert(Attribute::EndAttrKinds <= sizeof(AvailableFunctionAttrs) * CHAR_BIT, "Too many attributes"); static_assert(attrIdxToArrayIdx(AttributeList::FunctionIndex) == 0U, "function should be stored in slot 0"); for (Attribute I : Sets[0]) { if (!I.isStringAttribute()) AvailableFunctionAttrs |= 1ULL << I.getKindAsEnum(); } } void AttributeListImpl::Profile(FoldingSetNodeID &ID) const { Profile(ID, makeArrayRef(begin(), end())); } void AttributeListImpl::Profile(FoldingSetNodeID &ID, ArrayRef<AttributeSet> Sets) { for (const auto &Set : Sets) ID.AddPointer(Set.SetNode); } #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) LLVM_DUMP_METHOD void AttributeListImpl::dump() const { AttributeList(const_cast<AttributeListImpl *>(this)).dump(); } #endif //===----------------------------------------------------------------------===// // AttributeList Construction and Mutation Methods //===----------------------------------------------------------------------===// AttributeList AttributeList::getImpl(LLVMContext &C, ArrayRef<AttributeSet> AttrSets) { assert(!AttrSets.empty() && "pointless AttributeListImpl"); LLVMContextImpl *pImpl = C.pImpl; FoldingSetNodeID ID; AttributeListImpl::Profile(ID, AttrSets); void *InsertPoint; AttributeListImpl *PA = pImpl->AttrsLists.FindNodeOrInsertPos(ID, InsertPoint); // If we didn't find any existing attributes of the same shape then // create a new one and insert it. if (!PA) { // Coallocate entries after the AttributeListImpl itself. void *Mem = ::operator new( AttributeListImpl::totalSizeToAlloc<AttributeSet>(AttrSets.size())); PA = new (Mem) AttributeListImpl(C, AttrSets); pImpl->AttrsLists.InsertNode(PA, InsertPoint); } // Return the AttributesList that we found or created. return AttributeList(PA); } AttributeList AttributeList::get(LLVMContext &C, ArrayRef<std::pair<unsigned, Attribute>> Attrs) { // If there are no attributes then return a null AttributesList pointer. if (Attrs.empty()) return AttributeList(); assert(std::is_sorted(Attrs.begin(), Attrs.end(), [](const std::pair<unsigned, Attribute> &LHS, const std::pair<unsigned, Attribute> &RHS) { return LHS.first < RHS.first; }) && "Misordered Attributes list!"); assert(none_of(Attrs, [](const std::pair<unsigned, Attribute> &Pair) { return Pair.second.hasAttribute(Attribute::None); }) && "Pointless attribute!"); // Create a vector if (unsigned, AttributeSetNode*) pairs from the attributes // list. SmallVector<std::pair<unsigned, AttributeSet>, 8> AttrPairVec; for (ArrayRef<std::pair<unsigned, Attribute>>::iterator I = Attrs.begin(), E = Attrs.end(); I != E; ) { unsigned Index = I->first; SmallVector<Attribute, 4> AttrVec; while (I != E && I->first == Index) { AttrVec.push_back(I->second); ++I; } AttrPairVec.emplace_back(Index, AttributeSet::get(C, AttrVec)); } return get(C, AttrPairVec); } AttributeList AttributeList::get(LLVMContext &C, ArrayRef<std::pair<unsigned, AttributeSet>> Attrs) { // If there are no attributes then return a null AttributesList pointer. if (Attrs.empty()) return AttributeList(); assert(std::is_sorted(Attrs.begin(), Attrs.end(), [](const std::pair<unsigned, AttributeSet> &LHS, const std::pair<unsigned, AttributeSet> &RHS) { return LHS.first < RHS.first; }) && "Misordered Attributes list!"); assert(none_of(Attrs, [](const std::pair<unsigned, AttributeSet> &Pair) { return !Pair.second.hasAttributes(); }) && "Pointless attribute!"); unsigned MaxIndex = Attrs.back().first; SmallVector<AttributeSet, 4> AttrVec(attrIdxToArrayIdx(MaxIndex) + 1); for (auto Pair : Attrs) AttrVec[attrIdxToArrayIdx(Pair.first)] = Pair.second; return getImpl(C, AttrVec); } AttributeList AttributeList::get(LLVMContext &C, AttributeSet FnAttrs, AttributeSet RetAttrs, ArrayRef<AttributeSet> ArgAttrs) { // Scan from the end to find the last argument with attributes. Most // arguments don't have attributes, so it's nice if we can have fewer unique // AttributeListImpls by dropping empty attribute sets at the end of the list. unsigned NumSets = 0; for (size_t I = ArgAttrs.size(); I != 0; --I) { if (ArgAttrs[I - 1].hasAttributes()) { NumSets = I + 2; break; } } if (NumSets == 0) { // Check function and return attributes if we didn't have argument // attributes. if (RetAttrs.hasAttributes()) NumSets = 2; else if (FnAttrs.hasAttributes()) NumSets = 1; } // If all attribute sets were empty, we can use the empty attribute list. if (NumSets == 0) return AttributeList(); SmallVector<AttributeSet, 8> AttrSets; AttrSets.reserve(NumSets); // If we have any attributes, we always have function attributes. AttrSets.push_back(FnAttrs); if (NumSets > 1) AttrSets.push_back(RetAttrs); if (NumSets > 2) { // Drop the empty argument attribute sets at the end. ArgAttrs = ArgAttrs.take_front(NumSets - 2); AttrSets.insert(AttrSets.end(), ArgAttrs.begin(), ArgAttrs.end()); } return getImpl(C, AttrSets); } AttributeList AttributeList::get(LLVMContext &C, unsigned Index, const AttrBuilder &B) { if (!B.hasAttributes()) return AttributeList(); Index = attrIdxToArrayIdx(Index); SmallVector<AttributeSet, 8> AttrSets(Index + 1); AttrSets[Index] = AttributeSet::get(C, B); return getImpl(C, AttrSets); } AttributeList AttributeList::get(LLVMContext &C, unsigned Index, ArrayRef<Attribute::AttrKind> Kinds) { SmallVector<std::pair<unsigned, Attribute>, 8> Attrs; for (Attribute::AttrKind K : Kinds) Attrs.emplace_back(Index, Attribute::get(C, K)); return get(C, Attrs); } AttributeList AttributeList::get(LLVMContext &C, unsigned Index, ArrayRef<StringRef> Kinds) { SmallVector<std::pair<unsigned, Attribute>, 8> Attrs; for (StringRef K : Kinds) Attrs.emplace_back(Index, Attribute::get(C, K)); return get(C, Attrs); } AttributeList AttributeList::get(LLVMContext &C, ArrayRef<AttributeList> Attrs) { if (Attrs.empty()) return AttributeList(); if (Attrs.size() == 1) return Attrs[0]; unsigned MaxSize = 0; for (AttributeList List : Attrs) MaxSize = std::max(MaxSize, List.getNumAttrSets()); // If every list was empty, there is no point in merging the lists. if (MaxSize == 0) return AttributeList(); SmallVector<AttributeSet, 8> NewAttrSets(MaxSize); for (unsigned I = 0; I < MaxSize; ++I) { AttrBuilder CurBuilder; for (AttributeList List : Attrs) CurBuilder.merge(List.getAttributes(I - 1)); NewAttrSets[I] = AttributeSet::get(C, CurBuilder); } return getImpl(C, NewAttrSets); } AttributeList AttributeList::addAttribute(LLVMContext &C, unsigned Index, Attribute::AttrKind Kind) const { if (hasAttribute(Index, Kind)) return *this; AttrBuilder B; B.addAttribute(Kind); return addAttributes(C, Index, B); } AttributeList AttributeList::addAttribute(LLVMContext &C, unsigned Index, StringRef Kind, StringRef Value) const { AttrBuilder B; B.addAttribute(Kind, Value); return addAttributes(C, Index, B); } AttributeList AttributeList::addAttribute(LLVMContext &C, unsigned Index, Attribute A) const { AttrBuilder B; B.addAttribute(A); return addAttributes(C, Index, B); } AttributeList AttributeList::addAttributes(LLVMContext &C, unsigned Index, const AttrBuilder &B) const { if (!B.hasAttributes()) return *this; if (!pImpl) return AttributeList::get(C, {{Index, AttributeSet::get(C, B)}}); #ifndef NDEBUG // FIXME it is not obvious how this should work for alignment. For now, say // we can't change a known alignment. unsigned OldAlign = getAttributes(Index).getAlignment(); unsigned NewAlign = B.getAlignment(); assert((!OldAlign || !NewAlign || OldAlign == NewAlign) && "Attempt to change alignment!"); #endif Index = attrIdxToArrayIdx(Index); SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end()); if (Index >= AttrSets.size()) AttrSets.resize(Index + 1); AttrBuilder Merged(AttrSets[Index]); Merged.merge(B); AttrSets[Index] = AttributeSet::get(C, Merged); return getImpl(C, AttrSets); } AttributeList AttributeList::addParamAttribute(LLVMContext &C, ArrayRef<unsigned> ArgNos, Attribute A) const { assert(std::is_sorted(ArgNos.begin(), ArgNos.end())); SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end()); unsigned MaxIndex = attrIdxToArrayIdx(ArgNos.back() + FirstArgIndex); if (MaxIndex >= AttrSets.size()) AttrSets.resize(MaxIndex + 1); for (unsigned ArgNo : ArgNos) { unsigned Index = attrIdxToArrayIdx(ArgNo + FirstArgIndex); AttrBuilder B(AttrSets[Index]); B.addAttribute(A); AttrSets[Index] = AttributeSet::get(C, B); } return getImpl(C, AttrSets); } AttributeList AttributeList::removeAttribute(LLVMContext &C, unsigned Index, Attribute::AttrKind Kind) const { if (!hasAttribute(Index, Kind)) return *this; Index = attrIdxToArrayIdx(Index); SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end()); assert(Index < AttrSets.size()); AttrSets[Index] = AttrSets[Index].removeAttribute(C, Kind); return getImpl(C, AttrSets); } AttributeList AttributeList::removeAttribute(LLVMContext &C, unsigned Index, StringRef Kind) const { if (!hasAttribute(Index, Kind)) return *this; Index = attrIdxToArrayIdx(Index); SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end()); assert(Index < AttrSets.size()); AttrSets[Index] = AttrSets[Index].removeAttribute(C, Kind); return getImpl(C, AttrSets); } AttributeList AttributeList::removeAttributes(LLVMContext &C, unsigned Index, const AttrBuilder &AttrsToRemove) const { if (!pImpl) return AttributeList(); Index = attrIdxToArrayIdx(Index); SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end()); if (Index >= AttrSets.size()) AttrSets.resize(Index + 1); AttrSets[Index] = AttrSets[Index].removeAttributes(C, AttrsToRemove); return getImpl(C, AttrSets); } AttributeList AttributeList::removeAttributes(LLVMContext &C, unsigned WithoutIndex) const { if (!pImpl) return AttributeList(); WithoutIndex = attrIdxToArrayIdx(WithoutIndex); if (WithoutIndex >= getNumAttrSets()) return *this; SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end()); AttrSets[WithoutIndex] = AttributeSet(); return getImpl(C, AttrSets); } AttributeList AttributeList::addDereferenceableAttr(LLVMContext &C, unsigned Index, uint64_t Bytes) const { AttrBuilder B; B.addDereferenceableAttr(Bytes); return addAttributes(C, Index, B); } AttributeList AttributeList::addDereferenceableOrNullAttr(LLVMContext &C, unsigned Index, uint64_t Bytes) const { AttrBuilder B; B.addDereferenceableOrNullAttr(Bytes); return addAttributes(C, Index, B); } AttributeList AttributeList::addAllocSizeAttr(LLVMContext &C, unsigned Index, unsigned ElemSizeArg, const Optional<unsigned> &NumElemsArg) { AttrBuilder B; B.addAllocSizeAttr(ElemSizeArg, NumElemsArg); return addAttributes(C, Index, B); } //===----------------------------------------------------------------------===// // AttributeList Accessor Methods //===----------------------------------------------------------------------===// LLVMContext &AttributeList::getContext() const { return pImpl->getContext(); } AttributeSet AttributeList::getParamAttributes(unsigned ArgNo) const { return getAttributes(ArgNo + FirstArgIndex); } AttributeSet AttributeList::getRetAttributes() const { return getAttributes(ReturnIndex); } AttributeSet AttributeList::getFnAttributes() const { return getAttributes(FunctionIndex); } bool AttributeList::hasAttribute(unsigned Index, Attribute::AttrKind Kind) const { return getAttributes(Index).hasAttribute(Kind); } bool AttributeList::hasAttribute(unsigned Index, StringRef Kind) const { return getAttributes(Index).hasAttribute(Kind); } bool AttributeList::hasAttributes(unsigned Index) const { return getAttributes(Index).hasAttributes(); } bool AttributeList::hasFnAttribute(Attribute::AttrKind Kind) const { return pImpl && pImpl->hasFnAttribute(Kind); } bool AttributeList::hasFnAttribute(StringRef Kind) const { return hasAttribute(AttributeList::FunctionIndex, Kind); } bool AttributeList::hasParamAttribute(unsigned ArgNo, Attribute::AttrKind Kind) const { return hasAttribute(ArgNo + FirstArgIndex, Kind); } bool AttributeList::hasAttrSomewhere(Attribute::AttrKind Attr, unsigned *Index) const { if (!pImpl) return false; for (unsigned I = index_begin(), E = index_end(); I != E; ++I) { if (hasAttribute(I, Attr)) { if (Index) *Index = I; return true; } } return false; } Attribute AttributeList::getAttribute(unsigned Index, Attribute::AttrKind Kind) const { return getAttributes(Index).getAttribute(Kind); } Attribute AttributeList::getAttribute(unsigned Index, StringRef Kind) const { return getAttributes(Index).getAttribute(Kind); } unsigned AttributeList::getRetAlignment() const { return getAttributes(ReturnIndex).getAlignment(); } unsigned AttributeList::getParamAlignment(unsigned ArgNo) const { return getAttributes(ArgNo + FirstArgIndex).getAlignment(); } unsigned AttributeList::getStackAlignment(unsigned Index) const { return getAttributes(Index).getStackAlignment(); } uint64_t AttributeList::getDereferenceableBytes(unsigned Index) const { return getAttributes(Index).getDereferenceableBytes(); } uint64_t AttributeList::getDereferenceableOrNullBytes(unsigned Index) const { return getAttributes(Index).getDereferenceableOrNullBytes(); } std::pair<unsigned, Optional<unsigned>> AttributeList::getAllocSizeArgs(unsigned Index) const { return getAttributes(Index).getAllocSizeArgs(); } std::string AttributeList::getAsString(unsigned Index, bool InAttrGrp) const { return getAttributes(Index).getAsString(InAttrGrp); } AttributeSet AttributeList::getAttributes(unsigned Index) const { Index = attrIdxToArrayIdx(Index); if (!pImpl || Index >= getNumAttrSets()) return AttributeSet(); return pImpl->begin()[Index]; } AttributeList::iterator AttributeList::begin() const { return pImpl ? pImpl->begin() : nullptr; } AttributeList::iterator AttributeList::end() const { return pImpl ? pImpl->end() : nullptr; } //===----------------------------------------------------------------------===// // AttributeList Introspection Methods //===----------------------------------------------------------------------===// unsigned AttributeList::getNumAttrSets() const { return pImpl ? pImpl->NumAttrSets : 0; } #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) LLVM_DUMP_METHOD void AttributeList::dump() const { dbgs() << "PAL[\n"; for (unsigned i = index_begin(), e = index_end(); i != e; ++i) { if (getAttributes(i).hasAttributes()) dbgs() << " { " << i << " => " << getAsString(i) << " }\n"; } dbgs() << "]\n"; } #endif //===----------------------------------------------------------------------===// // AttrBuilder Method Implementations //===----------------------------------------------------------------------===// // FIXME: Remove this ctor, use AttributeSet. AttrBuilder::AttrBuilder(AttributeList AL, unsigned Index) { AttributeSet AS = AL.getAttributes(Index); for (const Attribute &A : AS) addAttribute(A); } AttrBuilder::AttrBuilder(AttributeSet AS) { for (const Attribute &A : AS) addAttribute(A); } void AttrBuilder::clear() { Attrs.reset(); TargetDepAttrs.clear(); Alignment = StackAlignment = DerefBytes = DerefOrNullBytes = 0; AllocSizeArgs = 0; } AttrBuilder &AttrBuilder::addAttribute(Attribute::AttrKind Val) { assert((unsigned)Val < Attribute::EndAttrKinds && "Attribute out of range!"); assert(Val != Attribute::Alignment && Val != Attribute::StackAlignment && Val != Attribute::Dereferenceable && Val != Attribute::AllocSize && "Adding integer attribute without adding a value!"); Attrs[Val] = true; return *this; } AttrBuilder &AttrBuilder::addAttribute(Attribute Attr) { if (Attr.isStringAttribute()) { addAttribute(Attr.getKindAsString(), Attr.getValueAsString()); return *this; } Attribute::AttrKind Kind = Attr.getKindAsEnum(); Attrs[Kind] = true; if (Kind == Attribute::Alignment) Alignment = Attr.getAlignment(); else if (Kind == Attribute::StackAlignment) StackAlignment = Attr.getStackAlignment(); else if (Kind == Attribute::Dereferenceable) DerefBytes = Attr.getDereferenceableBytes(); else if (Kind == Attribute::DereferenceableOrNull) DerefOrNullBytes = Attr.getDereferenceableOrNullBytes(); else if (Kind == Attribute::AllocSize) AllocSizeArgs = Attr.getValueAsInt(); return *this; } AttrBuilder &AttrBuilder::addAttribute(StringRef A, StringRef V) { TargetDepAttrs[A] = V; return *this; } AttrBuilder &AttrBuilder::removeAttribute(Attribute::AttrKind Val) { assert((unsigned)Val < Attribute::EndAttrKinds && "Attribute out of range!"); Attrs[Val] = false; if (Val == Attribute::Alignment) Alignment = 0; else if (Val == Attribute::StackAlignment) StackAlignment = 0; else if (Val == Attribute::Dereferenceable) DerefBytes = 0; else if (Val == Attribute::DereferenceableOrNull) DerefOrNullBytes = 0; else if (Val == Attribute::AllocSize) AllocSizeArgs = 0; return *this; } AttrBuilder &AttrBuilder::removeAttributes(AttributeList A, uint64_t Index) { remove(A.getAttributes(Index)); return *this; } AttrBuilder &AttrBuilder::removeAttribute(StringRef A) { std::map<std::string, std::string>::iterator I = TargetDepAttrs.find(A); if (I != TargetDepAttrs.end()) TargetDepAttrs.erase(I); return *this; } std::pair<unsigned, Optional<unsigned>> AttrBuilder::getAllocSizeArgs() const { return unpackAllocSizeArgs(AllocSizeArgs); } AttrBuilder &AttrBuilder::addAlignmentAttr(unsigned Align) { if (Align == 0) return *this; assert(isPowerOf2_32(Align) && "Alignment must be a power of two."); assert(Align <= 0x40000000 && "Alignment too large."); Attrs[Attribute::Alignment] = true; Alignment = Align; return *this; } AttrBuilder &AttrBuilder::addStackAlignmentAttr(unsigned Align) { // Default alignment, allow the target to define how to align it. if (Align == 0) return *this; assert(isPowerOf2_32(Align) && "Alignment must be a power of two."); assert(Align <= 0x100 && "Alignment too large."); Attrs[Attribute::StackAlignment] = true; StackAlignment = Align; return *this; } AttrBuilder &AttrBuilder::addDereferenceableAttr(uint64_t Bytes) { if (Bytes == 0) return *this; Attrs[Attribute::Dereferenceable] = true; DerefBytes = Bytes; return *this; } AttrBuilder &AttrBuilder::addDereferenceableOrNullAttr(uint64_t Bytes) { if (Bytes == 0) return *this; Attrs[Attribute::DereferenceableOrNull] = true; DerefOrNullBytes = Bytes; return *this; } AttrBuilder &AttrBuilder::addAllocSizeAttr(unsigned ElemSize, const Optional<unsigned> &NumElems) { return addAllocSizeAttrFromRawRepr(packAllocSizeArgs(ElemSize, NumElems)); } AttrBuilder &AttrBuilder::addAllocSizeAttrFromRawRepr(uint64_t RawArgs) { // (0, 0) is our "not present" value, so we need to check for it here. assert(RawArgs && "Invalid allocsize arguments -- given allocsize(0, 0)"); Attrs[Attribute::AllocSize] = true; // Reuse existing machinery to store this as a single 64-bit integer so we can // save a few bytes over using a pair<unsigned, Optional<unsigned>>. AllocSizeArgs = RawArgs; return *this; } AttrBuilder &AttrBuilder::merge(const AttrBuilder &B) { // FIXME: What if both have alignments, but they don't match?! if (!Alignment) Alignment = B.Alignment; if (!StackAlignment) StackAlignment = B.StackAlignment; if (!DerefBytes) DerefBytes = B.DerefBytes; if (!DerefOrNullBytes) DerefOrNullBytes = B.DerefOrNullBytes; if (!AllocSizeArgs) AllocSizeArgs = B.AllocSizeArgs; Attrs |= B.Attrs; for (auto I : B.td_attrs()) TargetDepAttrs[I.first] = I.second; return *this; } AttrBuilder &AttrBuilder::remove(const AttrBuilder &B) { // FIXME: What if both have alignments, but they don't match?! if (B.Alignment) Alignment = 0; if (B.StackAlignment) StackAlignment = 0; if (B.DerefBytes) DerefBytes = 0; if (B.DerefOrNullBytes) DerefOrNullBytes = 0; if (B.AllocSizeArgs) AllocSizeArgs = 0; Attrs &= ~B.Attrs; for (auto I : B.td_attrs()) TargetDepAttrs.erase(I.first); return *this; } bool AttrBuilder::overlaps(const AttrBuilder &B) const { // First check if any of the target independent attributes overlap. if ((Attrs & B.Attrs).any()) return true; // Then check if any target dependent ones do. for (const auto &I : td_attrs()) if (B.contains(I.first)) return true; return false; } bool AttrBuilder::contains(StringRef A) const { return TargetDepAttrs.find(A) != TargetDepAttrs.end(); } bool AttrBuilder::hasAttributes() const { return !Attrs.none() || !TargetDepAttrs.empty(); } bool AttrBuilder::hasAttributes(AttributeList AL, uint64_t Index) const { AttributeSet AS = AL.getAttributes(Index); for (Attribute Attr : AS) { if (Attr.isEnumAttribute() || Attr.isIntAttribute()) { if (contains(Attr.getKindAsEnum())) return true; } else { assert(Attr.isStringAttribute() && "Invalid attribute kind!"); return contains(Attr.getKindAsString()); } } return false; } bool AttrBuilder::hasAlignmentAttr() const { return Alignment != 0; } bool AttrBuilder::operator==(const AttrBuilder &B) { if (Attrs != B.Attrs) return false; for (td_const_iterator I = TargetDepAttrs.begin(), E = TargetDepAttrs.end(); I != E; ++I) if (B.TargetDepAttrs.find(I->first) == B.TargetDepAttrs.end()) return false; return Alignment == B.Alignment && StackAlignment == B.StackAlignment && DerefBytes == B.DerefBytes; } //===----------------------------------------------------------------------===// // AttributeFuncs Function Defintions //===----------------------------------------------------------------------===// /// \brief Which attributes cannot be applied to a type. AttrBuilder AttributeFuncs::typeIncompatible(Type *Ty) { AttrBuilder Incompatible; if (!Ty->isIntegerTy()) // Attribute that only apply to integers. Incompatible.addAttribute(Attribute::SExt) .addAttribute(Attribute::ZExt); if (!Ty->isPointerTy()) // Attribute that only apply to pointers. Incompatible.addAttribute(Attribute::ByVal) .addAttribute(Attribute::Nest) .addAttribute(Attribute::NoAlias) .addAttribute(Attribute::NoCapture) .addAttribute(Attribute::NonNull) .addDereferenceableAttr(1) // the int here is ignored .addDereferenceableOrNullAttr(1) // the int here is ignored .addAttribute(Attribute::ReadNone) .addAttribute(Attribute::ReadOnly) .addAttribute(Attribute::StructRet) .addAttribute(Attribute::InAlloca); return Incompatible; } template<typename AttrClass> static bool isEqual(const Function &Caller, const Function &Callee) { return Caller.getFnAttribute(AttrClass::getKind()) == Callee.getFnAttribute(AttrClass::getKind()); } /// \brief Compute the logical AND of the attributes of the caller and the /// callee. /// /// This function sets the caller's attribute to false if the callee's attribute /// is false. template<typename AttrClass> static void setAND(Function &Caller, const Function &Callee) { if (AttrClass::isSet(Caller, AttrClass::getKind()) && !AttrClass::isSet(Callee, AttrClass::getKind())) AttrClass::set(Caller, AttrClass::getKind(), false); } /// \brief Compute the logical OR of the attributes of the caller and the /// callee. /// /// This function sets the caller's attribute to true if the callee's attribute /// is true. template<typename AttrClass> static void setOR(Function &Caller, const Function &Callee) { if (!AttrClass::isSet(Caller, AttrClass::getKind()) && AttrClass::isSet(Callee, AttrClass::getKind())) AttrClass::set(Caller, AttrClass::getKind(), true); } /// \brief If the inlined function had a higher stack protection level than the /// calling function, then bump up the caller's stack protection level. static void adjustCallerSSPLevel(Function &Caller, const Function &Callee) { // If upgrading the SSP attribute, clear out the old SSP Attributes first. // Having multiple SSP attributes doesn't actually hurt, but it adds useless // clutter to the IR. AttrBuilder OldSSPAttr; OldSSPAttr.addAttribute(Attribute::StackProtect) .addAttribute(Attribute::StackProtectStrong) .addAttribute(Attribute::StackProtectReq); if (Callee.hasFnAttribute(Attribute::StackProtectReq)) { Caller.removeAttributes(AttributeList::FunctionIndex, OldSSPAttr); Caller.addFnAttr(Attribute::StackProtectReq); } else if (Callee.hasFnAttribute(Attribute::StackProtectStrong) && !Caller.hasFnAttribute(Attribute::StackProtectReq)) { Caller.removeAttributes(AttributeList::FunctionIndex, OldSSPAttr); Caller.addFnAttr(Attribute::StackProtectStrong); } else if (Callee.hasFnAttribute(Attribute::StackProtect) && !Caller.hasFnAttribute(Attribute::StackProtectReq) && !Caller.hasFnAttribute(Attribute::StackProtectStrong)) Caller.addFnAttr(Attribute::StackProtect); } /// \brief If the inlined function required stack probes, then ensure that /// the calling function has those too. static void adjustCallerStackProbes(Function &Caller, const Function &Callee) { if (!Caller.hasFnAttribute("probe-stack") && Callee.hasFnAttribute("probe-stack")) { Caller.addFnAttr(Callee.getFnAttribute("probe-stack")); } } /// \brief If the inlined function defines the size of guard region /// on the stack, then ensure that the calling function defines a guard region /// that is no larger. static void adjustCallerStackProbeSize(Function &Caller, const Function &Callee) { if (Callee.hasFnAttribute("stack-probe-size")) { uint64_t CalleeStackProbeSize; Callee.getFnAttribute("stack-probe-size") .getValueAsString() .getAsInteger(0, CalleeStackProbeSize); if (Caller.hasFnAttribute("stack-probe-size")) { uint64_t CallerStackProbeSize; Caller.getFnAttribute("stack-probe-size") .getValueAsString() .getAsInteger(0, CallerStackProbeSize); if (CallerStackProbeSize > CalleeStackProbeSize) { Caller.addFnAttr(Callee.getFnAttribute("stack-probe-size")); } } else { Caller.addFnAttr(Callee.getFnAttribute("stack-probe-size")); } } } #define GET_ATTR_COMPAT_FUNC #include "AttributesCompatFunc.inc" bool AttributeFuncs::areInlineCompatible(const Function &Caller, const Function &Callee) { return hasCompatibleFnAttrs(Caller, Callee); } void AttributeFuncs::mergeAttributesForInlining(Function &Caller, const Function &Callee) { mergeFnAttrs(Caller, Callee); }
[ "yaron.keren@gmail.com" ]
yaron.keren@gmail.com
5ad78609c6daadf95e79a0f9770c70a125d93269
c08a26d662bd1df1b2beaa36a36d0e9fecc1ebac
/commonuisupport/uikon/coreinc/eikamnt.h
292e4575fb1b0902b61e44a0db7dd0baaf83aed9
[]
no_license
SymbianSource/oss.FCL.sf.mw.classicui
9c2e2c31023256126bb2e502e49225d5c58017fe
dcea899751dfa099dcca7a5508cf32eab64afa7a
refs/heads/master
2021-01-11T02:38:59.198728
2010-10-08T14:24:02
2010-10-08T14:24:02
70,943,916
1
0
null
null
null
null
UTF-8
C++
false
false
2,237
h
// Copyright (c) 1997-2009 Nokia Corporation and/or its subsidiary(-ies). // All rights reserved. // This component and the accompanying materials are made available // under the terms of "Eclipse Public License v1.0" // which accompanies this distribution, and is available // at the URL "http://www.eclipse.org/legal/epl-v10.html". // // Initial Contributors: // Nokia Corporation - initial contribution. // // Contributors: // // Description: // #ifndef __EIKAMNT_H__ #define __EIKAMNT_H__ #include <e32base.h> #ifndef SYMBIAN_ENABLE_SPLIT_HEADERS #include <uikon/eikautomenutitlearray.h> #endif class CGulIcon; class MEikAutoMenuObserver; /** A menu title that will be added to a standard resource-constructed menu bar. If added to the CEikAutoMenuTitleArray stored by CEikonEnv during standard application start up, the menu pane specified will appear in all applications. The menu observer passed in is notified of any events on such menu panes in preference to the usual observer (C<MyApp>AppUi). @publishedAll @released */ NONSHARABLE_CLASS(CEikAutoMenuTitle) : public CBase { public: /** Specifies the position of a menu title in a menu. If an array of menu titles holds more than one menu title that is specified for the start or end of a menu, the menu titles are placed in the same order as that in which they appear in the array. This means the first menu title specified with EStart in an array will be the first on a menu bar and the last EEnd will be the last on a menu bar. */ enum TTitlePos { /** The menu title is placed first in a menu. */ EStart, /** The menu title is placed last in a menu. */ EEnd }; enum { ENominalTextLength=40 }; public: IMPORT_C static CEikAutoMenuTitle* NewLC(TTitlePos aPos, const TDesC& aText, MEikAutoMenuObserver& aMenuObserver, TInt aMenuPaneResourceId = 0, CGulIcon* aIcon = NULL); IMPORT_C ~CEikAutoMenuTitle(); private: CEikAutoMenuTitle(TTitlePos aPos, const TDesC& aText, MEikAutoMenuObserver& aMenuObserver, TInt aMenuPaneResourceId, CGulIcon* aIcon); public: TTitlePos iPos; TBuf<ENominalTextLength> iText; MEikAutoMenuObserver& iMenuObserver; TInt iMenuPaneResourceId; CGulIcon* iIcon; }; #endif // __EIKAMNT_H__
[ "kirill.dremov@nokia.com" ]
kirill.dremov@nokia.com
1bb3fc152adb85754d1558e86fd47b501de98d8c
83238bc55ff594c4c6b645638127cbcf19983733
/tests/cross-channel/post_task.cc
1dd05b0f1e91faea9d1a54f8e84ae52da5fd3fb2
[ "BSD-3-Clause" ]
permissive
ordavid90/ibverbs-tests
3651f52dabba0b1f844cae7975df0b00e5139081
59747f6ac6171c0ca16ca86468703fbaa9b5e622
refs/heads/master
2023-08-13T15:37:14.248444
2021-10-05T17:08:10
2021-10-05T17:13:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,390
cc
/** * Copyright (C) 2015-2016 Mellanox Technologies Ltd. All rights reserved. * * 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. * 3. 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. */ #include "cc_classes.h" #define SEND_POST_COUNT 10 /* verbs_post_task: [TI.1] Correct */ TEST_F(tc_verbs_post_task, ti_1){ #ifdef HAVE_CROSS_CHANNEL_TASK int rc = EOK; __init_test(IBV_QP_CREATE_CROSS_CHANNEL | IBV_QP_CREATE_MANAGED_SEND); /* * Use the created QP for communication operations. */ { struct ibv_task task[2]; struct ibv_task *task_bad; struct ibv_send_wr wr_tsk0[SEND_POST_COUNT]; struct ibv_send_wr wr_tsk1[4]; int i = 0; EXPECT_TRUE(SEND_POST_COUNT >= 10); /* create TASK(SEND) for qp */ memset(task, 0, sizeof(*task) * 2); memset(wr_tsk0, 0, sizeof(*wr_tsk0) * SEND_POST_COUNT); for (i = 0; i < SEND_POST_COUNT; i++) { wr_tsk0[i].wr_id = i; wr_tsk0[i].next = ( i < (SEND_POST_COUNT - 1) ? &wr_tsk0[i + 1] : NULL); wr_tsk0[i].sg_list = NULL; wr_tsk0[i].num_sge = 0; wr_tsk0[i].opcode = IBV_WR_SEND; wr_tsk0[i].send_flags = IBV_SEND_SIGNALED; wr_tsk0[i].imm_data = 0; } task[0].task_type = IBV_TASK_SEND; task[0].item.qp = ctx->qp; task[0].item.send_wr = wr_tsk0; task[0].next = &task[1]; /* create TASK(WAIT) for mqp */ memset(wr_tsk1, 0, sizeof(*wr_tsk1) * 4); /* SEND_EN(QP,1) */ wr_tsk1[0].wr_id = 0; wr_tsk1[0].next = &wr_tsk1[1]; wr_tsk1[0].sg_list = NULL; wr_tsk1[0].num_sge = 0; wr_tsk1[0].opcode = IBV_WR_SEND_ENABLE; wr_tsk1[0].send_flags = IBV_SEND_SIGNALED; wr_tsk1[0].imm_data = 0; wr_tsk1[0].task.wqe_enable.qp = ctx->qp; wr_tsk1[0].task.wqe_enable.wqe_count = 1; /* WAIT(QP,1) */ wr_tsk1[1].wr_id = 1; wr_tsk1[1].next = &wr_tsk1[2]; wr_tsk1[1].sg_list = NULL; wr_tsk1[1].num_sge = 0; wr_tsk1[1].opcode = IBV_WR_CQE_WAIT; wr_tsk1[1].send_flags = IBV_SEND_SIGNALED; wr_tsk1[1].imm_data = 0; wr_tsk1[1].task.cqe_wait.cq = ctx->mcq; wr_tsk1[1].task.cqe_wait.cq_count = 1; /* SEND_EN(QP,ALL) */ wr_tsk1[2].wr_id = 2; wr_tsk1[2].next = &wr_tsk1[3]; wr_tsk1[2].sg_list = NULL; wr_tsk1[2].num_sge = 0; wr_tsk1[2].opcode = IBV_WR_SEND_ENABLE; wr_tsk1[2].send_flags = 0; wr_tsk1[2].imm_data = 0; wr_tsk1[2].task.wqe_enable.qp = ctx->qp; wr_tsk1[2].task.wqe_enable.wqe_count = 0; /* WAIT(QP,SEND_POST_COUNT) */ wr_tsk1[3].wr_id = 3; wr_tsk1[3].next = NULL; wr_tsk1[3].sg_list = NULL; wr_tsk1[3].num_sge = 0; wr_tsk1[3].opcode = IBV_WR_CQE_WAIT; wr_tsk1[3].send_flags = IBV_SEND_SIGNALED | IBV_SEND_WAIT_EN_LAST; wr_tsk1[3].imm_data = 0; wr_tsk1[3].task.cqe_wait.cq = ctx->rcq; wr_tsk1[3].task.cqe_wait.cq_count = SEND_POST_COUNT; task[1].task_type = IBV_TASK_SEND; task[1].item.qp = ctx->mqp; task[1].item.send_wr = wr_tsk1; task[1].next = NULL; rc = ibv_post_task(ibv_ctx, task, &task_bad); ASSERT_EQ(EOK, rc); __poll_cq(ctx->scq, ctx->cq_tx_depth, ctx->wc, SEND_POST_COUNT); __poll_cq(ctx->rcq, ctx->cq_rx_depth, ctx->wc, SEND_POST_COUNT); __poll_cq(ctx->mcq, 0x10, ctx->wc, 3); EXPECT_EQ((uint64_t)0, ctx->wc[0].wr_id); EXPECT_EQ((uint64_t)1, ctx->wc[1].wr_id); EXPECT_EQ((uint64_t)3, ctx->wc[2].wr_id); } #endif } /* verbs_post_task: [TI.2] Bad case * Expected bad_task = task[1] */ TEST_F(tc_verbs_post_task, ti_2) { #ifdef HAVE_CROSS_CHANNEL_TASK int rc = EOK; __init_test(); /* * Use the created QP for communication operations. */ { struct ibv_task task[2]; struct ibv_task *task_bad; struct ibv_send_wr wr_tsk0[SEND_POST_COUNT]; struct ibv_send_wr wr_tsk1; int i = 0; EXPECT_TRUE(SEND_POST_COUNT >= 10); /* create TASK(SEND) for qp */ memset(task, 0, sizeof(*task) * 2); memset(wr_tsk0, 0, sizeof(*wr_tsk0) * SEND_POST_COUNT); for (i = 0; i < SEND_POST_COUNT; i++) { wr_tsk0[i].wr_id = i; wr_tsk0[i].next = ( i < (SEND_POST_COUNT - 1) ? &wr_tsk0[i + 1] : NULL); wr_tsk0[i].sg_list = NULL; wr_tsk0[i].num_sge = 0; wr_tsk0[i].opcode = IBV_WR_SEND; wr_tsk0[i].send_flags = IBV_SEND_SIGNALED; wr_tsk0[i].imm_data = 0; } task[0].task_type = IBV_TASK_SEND; task[0].item.qp = ctx->qp; task[0].item.send_wr = wr_tsk0; task[0].next = &task[1]; /* create TASK(WAIT) for mqp */ memset(&wr_tsk1, 0, sizeof(wr_tsk1)); /* SEND_EN(QP,1) */ wr_tsk1.wr_id = 0; wr_tsk1.next = NULL; wr_tsk1.sg_list = NULL; wr_tsk1.num_sge = 0; wr_tsk1.opcode = IBV_WR_SEND_ENABLE; wr_tsk1.send_flags = IBV_SEND_SIGNALED | IBV_SEND_WAIT_EN_LAST; wr_tsk1.imm_data = 0; wr_tsk1.task.wqe_enable.qp = ctx->qp; wr_tsk1.task.wqe_enable.wqe_count = 1; task[1].task_type = IBV_TASK_SEND; task[1].item.qp = ctx->qp; task[1].item.send_wr = &wr_tsk1; task[1].next = NULL; rc = ibv_post_task(ibv_ctx, task, &task_bad); ASSERT_NE(EOK, rc); ASSERT_EQ(task_bad, &task[1]); __poll_cq(ctx->scq, ctx->cq_tx_depth, ctx->wc, SEND_POST_COUNT); __poll_cq(ctx->rcq, ctx->cq_rx_depth, ctx->wc, SEND_POST_COUNT); } #endif }
[ "leonro@mellanox.com" ]
leonro@mellanox.com
75fc21c60d28b83530ef0a16f04170091961ea26
e410f3831a7132e4c8a12c0b02bee93a840e5bef
/evenNums.cpp
97768105964c6ef56558a91d6a6a63ee156c8995
[]
no_license
Brian-wKicheu/Summarry-of-cpp-basics
87e245a0887b4578692fbfa1346a6b2f7b7116de
f7b77610a91bfca74e253e65bcc17236626468e3
refs/heads/main
2023-04-23T06:37:02.866001
2021-05-04T08:54:37
2021-05-04T08:54:37
364,195,155
0
0
null
null
null
null
UTF-8
C++
false
false
312
cpp
#include <iostream> using namespace std; int main() { // Odd nums cout << "Odd numbers.\n"; for (int i = 1; i <= 10; i = i+2) { cout << i << "\n"; } // Even nums cout << "Even numbers.\n"; for (int j = 0; j <= 10; j = j+2) { cout << j << "\n"; } return 0; }
[ "noreply@github.com" ]
noreply@github.com
e150b003a22e1e87d0351242a94923656f3f2434
0632887651e550127a6482729b1a6fa43e2f4fd7
/ue03/tictoc/txc2.cc
298dfc2f37a6bd7bcc85687267eb1023bdcb35cc
[]
no_license
miri64/MPAS
85eef3ab845813d45048efe984b8d74b985a46ed
9036ea9f4ff870b41dc574549f41f8c20a9b1df1
refs/heads/master
2020-04-09T14:58:34.205016
2013-07-11T09:07:58
2013-07-11T09:07:58
9,389,907
0
1
null
null
null
null
UTF-8
C++
false
false
1,176
cc
// // This file is part of an OMNeT++/OMNEST simulation example. // // Copyright (C) 2003 Ahmet Sekercioglu // Copyright (C) 2003-2008 Andras Varga // // This file is distributed WITHOUT ANY WARRANTY. See the file // `license' for details on this and other legal matters. // #include <string.h> #include <omnetpp.h> /** * In this class we add some debug messages to Txc1. When you run the * simulation in the OMNeT++ GUI Tkenv, the output will appear in * the main text window, and you can also open separate output windows * for `tic' and `toc'. */ class Txc2 : public cSimpleModule { protected: virtual void initialize(); virtual void handleMessage(cMessage *msg); }; Define_Module(Txc2); void Txc2::initialize() { if (strcmp("tic", getName()) == 0) { // The `ev' object works like `cout' in C++. EV << "Here we go\n"; cMessage *msg = new cMessage("trololol"); send(msg, "out"); } } void Txc2::handleMessage(cMessage *msg) { // msg->getName() is name of the msg object, here it will be "tictocMsg". EV << "Received message `" << msg->getName() << "', aaaaand ... its gone\n"; send(msg, "out"); }
[ "nehls@mi.fu-berlin.de" ]
nehls@mi.fu-berlin.de
48593cc4be9cc0fb30d6f8bf719d5bf2c01256a9
29beb3c98fad090c283de4d96415e2328dd0e990
/vis/src/receiver_node.cpp
e071ec5ba2dd04321ef291ea490f05dcc07406bc
[]
no_license
matt769/Hexapod
b7cc89f78147b4aabbb548946ad8876118218a55
e4064dcc379492f24fca351a017ebbd79cc9f172
refs/heads/master
2023-06-16T13:59:20.034770
2021-07-03T11:21:25
2021-07-03T11:21:25
261,607,139
2
1
null
2021-05-29T14:45:02
2020-05-05T23:41:53
C++
UTF-8
C++
false
false
1,202
cpp
#include "ros_receiver.h" #include "build_from_urdf.h" #include "hexapod.h" #include "build_hexapod.h" #include "kinematics_support.h" #include "transformations.h" #include "visualisation.h" #include <geometry_msgs/TransformStamped.h> #include <ros/ros.h> #include <sensor_msgs/JointState.h> #include <std_msgs/Int32.h> #include <tf2/LinearMath/Quaternion.h> #include <tf2/LinearMath/Transform.h> #include <tf2/convert.h> #include <tf2_geometry_msgs/tf2_geometry_msgs.h> #include <tf2_ros/transform_broadcaster.h> #include <tf2_ros/transform_listener.h> using namespace hexapod_vis; using namespace hexapod; int main(int argc, char **argv) { ros::init(argc, argv, "receiver_node"); ros::NodeHandle nh; // Hexapod hexapod = buildDefaultHexapod(); // Hexapod hexapod = buildDefaultHexapod2(); // Hexapod hexapod = buildDefaultOctapod(); // Hexapod hexapod = buildFromURDF(); // Hexapod hexapod = buildPhantomX(); Hexapod hexapod = buildPhantomXForVis(); Vis visualiser(nh, &hexapod); RosReceiver receiver(nh, &hexapod); ros::Rate loop_rate(50); while (ros::ok()) { hexapod.update(); visualiser.update(); ros::spinOnce(); loop_rate.sleep(); } return 0; }
[ "matthedley@hotmail.co.uk" ]
matthedley@hotmail.co.uk
0785489e790444e105f05a39d005ff7defc9144f
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/cc/blink/scrollbar_impl.h
4e4bdaedc25e7a5e2e304a71280cb06c61b7ebd1
[ "BSD-3-Clause" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
1,650
h
// Copyright 2014 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. #ifndef CC_BLINK_SCROLLBAR_IMPL_H_ #define CC_BLINK_SCROLLBAR_IMPL_H_ #include <memory> #include "base/macros.h" #include "cc/input/scrollbar.h" #include "third_party/WebKit/public/platform/WebScrollbarThemePainter.h" namespace blink { class WebScrollbar; class WebScrollbarThemeGeometry; } namespace cc_blink { class ScrollbarImpl : public cc::Scrollbar { public: ScrollbarImpl(std::unique_ptr<blink::WebScrollbar> scrollbar, blink::WebScrollbarThemePainter painter, std::unique_ptr<blink::WebScrollbarThemeGeometry> geometry); ~ScrollbarImpl() override; // cc::Scrollbar implementation. cc::ScrollbarOrientation Orientation() const override; bool IsLeftSideVerticalScrollbar() const override; bool HasThumb() const override; bool IsOverlay() const override; gfx::Point Location() const override; int ThumbThickness() const override; int ThumbLength() const override; gfx::Rect TrackRect() const override; float ThumbOpacity() const override; bool NeedsPaintPart(cc::ScrollbarPart part) const override; void PaintPart(SkCanvas* canvas, cc::ScrollbarPart part, const gfx::Rect& content_rect) override; private: std::unique_ptr<blink::WebScrollbar> scrollbar_; blink::WebScrollbarThemePainter painter_; std::unique_ptr<blink::WebScrollbarThemeGeometry> geometry_; DISALLOW_COPY_AND_ASSIGN(ScrollbarImpl); }; } // namespace cc_blink #endif // CC_BLINK_SCROLLBAR_IMPL_H_
[ "enrico.weigelt@gr13.net" ]
enrico.weigelt@gr13.net
2710eabfe6d5b9f4a583bfea93c4f07424406a3a
33fd5786ddde55a705d74ce2ce909017e2535065
/build/iOS/Debug/include/_root.RubricBlack.h
41e764d1285581b13e632fc585bf9cfe9c1925ec
[]
no_license
frpaulas/iphodfuse
04cee30add8b50ea134eb5a83e355dce886a5d5a
e8886638c4466b3b0c6299da24156d4ee81c9112
refs/heads/master
2021-01-23T00:48:31.195577
2017-06-01T12:33:13
2017-06-01T12:33:13
92,842,106
3
3
null
2017-05-30T17:43:28
2017-05-30T14:33:26
C++
UTF-8
C++
false
false
1,198
h
// This file was generated based on '.uno/ux11/RubricBlack.g.uno'. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <_root.Rubric.h> #include <Fuse.Animations.IResize.h> #include <Fuse.Binding.h> #include <Fuse.IActualPlacement.h> #include <Fuse.INotifyUnrooted.h> #include <Fuse.IProperties.h> #include <Fuse.Node.h> #include <Fuse.Scripting.IScriptObject.h> #include <Fuse.Triggers.Actions.IHide.h> #include <Fuse.Triggers.Actions.IShow.h> #include <Fuse.Triggers.Actions-ea70af1f.h> #include <Fuse.Triggers.IValue-1.h> #include <Uno.Collections.ICollection-1.h> #include <Uno.Collections.IEnumerable-1.h> #include <Uno.Collections.IList-1.h> #include <Uno.String.h> #include <Uno.UX.IPropertyListener.h> namespace g{struct RubricBlack;} namespace g{ // public partial sealed class RubricBlack :2 // { ::g::Fuse::Controls::TextControl_type* RubricBlack_typeof(); void RubricBlack__ctor_11_fn(RubricBlack* __this); void RubricBlack__InitializeUX4_fn(RubricBlack* __this); void RubricBlack__New7_fn(RubricBlack** __retval); struct RubricBlack : ::g::Rubric { void ctor_11(); void InitializeUX4(); static RubricBlack* New7(); }; // } } // ::g
[ "frpaulas@gmail.com" ]
frpaulas@gmail.com
aa482453d5f90527258d26bce44c6d6862edd342
a79141629270d8eeed398ea985eaf84a1b4679ff
/Last digit of Fibonacci Number/Last digit of Fibonacci Number/main.cpp
0d1d6519599607c202f7f3da49542c91de58ab68
[]
no_license
LegendreXu/DataStructure
2e25f077b0799536dde63f46abed2dc267970c57
d7b35616ca301ffbe6979d6498b1c85b859ebb51
refs/heads/master
2020-03-31T12:34:25.030269
2018-10-09T09:24:10
2018-10-09T09:24:10
152,221,130
0
0
null
null
null
null
UTF-8
C++
false
false
690
cpp
// // main.cpp // Last digit of Fibonacci Number // // Created by 许国嵩 on 17/9/7. // Copyright © 2017年 许国嵩. All rights reserved. // #include <iostream> using namespace std; int main() { int n; int m [60]={0,1,1,2,3,5,8,3,1,4,5,9,4,3,7,0,7,7,4,1,5,6,1,7,8,5,3,8,1,9,0,9,9,8,7,5,2,7,9,6,5,1,6,7,3,0,3,3,6,9,5,4,9,3,2,5,7,2,9,1}; for(int i = 0;i < 60;i++){ if(i == 0){ m[0] = 0; } else if(i == 1){ m[1] = 1; } else{ m[i] = (m[i - 1]+m[i - 2]) % 10; } } while(cin>>n){ n %= 60; cout<<m[n]<<endl; } return 0; }
[ "noreply@github.com" ]
noreply@github.com