<commit_before>#include <cstdio>
#include <cstdlib>
#include <iostream>
#define  MAXSTRLEN  255                   // 用户可在255以内定义最大串长
typedef unsigned char SString[MAXSTRLEN+1];	// 0号单元存放串的长度

void get_next(SString T,int next[]){

	int i=1,j;
	next[1]=0;
	j=0;
	while(i<T[0]){

		if(j == 0 || T[i]==T[j]){
			++i;
			++j;

			if(T[i]!=T[j]){
				next[i]=j;
			}else{

				next[i]=next[j];
			}
		}

		else
			j=next[j];
	}
}

int Index_KMP(SString S,SString T,int pos){
// 算法4.6
// 利用模式串T的next函数求T在主串S中第pos个字符之后的位置
// KMP算法。请补全代码
	int i=pos,j=1;
	int next[T[0]];
	get_next(T,next);

	while(i<=S[0] &&j<=T[0]){

		if(j==0 || S[i] == T[i]){
			++i;
			++j;

		}else{

			j=next[j];
		}

	}
	if(j>T[0]) return  i-T[0];
	return 0
}
void main()
{
SString T,S;
 int i,j,n;
 char ch;
 int pos;
 scanf(“%d”,&n);    // 指定n对需进行模式匹配的字符串
ch=getchar();
for(j=1;j<=n;j++)
{
ch=getchar();
  for( i=1;i<=MAXSTRLEN&&(ch!='\n');i++)    // 录入主串
  {
S[i]=ch;
  ch=getchar();
}
S[0]=i-1;    // S[0]用于存储主串中字符个数
ch=getchar();
for( i=1;i<=MAXSTRLEN&&(ch!='\n');i++)    // 录入模式串
{
  T[i]=ch;
  ch=getchar();
}
T[0]=i-1;    // T[0]用于存储模式串中字符个数
pos=Index_KMP(S,T,1);    // 请填空
printf("%d\n",pos);
}
    }<commit_msg>update uoj8592<commit_after>#include <cstdio>
#include <cstdlib>
#include <iostream>
#define  MAXSTRLEN  255                   // 用户可在255以内定义最大串长
typedef unsigned char SString[MAXSTRLEN+1];	// 0号单元存放串的长度

void get_next(SString T,int next[]){

	int i=1,j;
	next[1]=0;
	j=0;
	while(i<T[0]){

		if(j == 0 || T[i]==T[j]){
			++i;
			++j;

			if(T[i]!=T[j]){
				next[i]=j;
			}else{

				next[i]=next[j];
			}
		}

		else
			j=next[j];
	}
}

int Index_KMP(SString S,SString T,int pos){
// 算法4.6
// 利用模式串T的next函数求T在主串S中第pos个字符之后的位置
// KMP算法。请补全代码
	int i=pos,j=1;
	int next[T[0]];
	get_next(T,next);

	while(i<=S[0] &&j<=T[0]){

		if(j==0 || S[i] == T[i]){
			++i;
			++j;

		}else{

			j=next[j];
		}

	}
	if(j>T[0]) return  i-T[0];
	return 0;
}
int main()
{
SString T,S;
 int i,j,n;
 char ch;
 int pos;
 scanf("%d",&n);    // 指定n对需进行模式匹配的字符串
ch=getchar();
for(j=1;j<=n;j++)
{
ch=getchar();
  for( i=1;i<=MAXSTRLEN&&(ch!='\n');i++)    // 录入主串
  {
S[i]=ch;
  ch=getchar();
}
S[0]=i-1;    // S[0]用于存储主串中字符个数
ch=getchar();
for( i=1;i<=MAXSTRLEN&&(ch!='\n');i++)    // 录入模式串
{
  T[i]=ch;
  ch=getchar();
}
T[0]=i-1;    // T[0]用于存储模式串中字符个数
pos=Index_KMP(S,T,1);    // 请填空
printf("%d\n",pos);
}
    }<|endoftext|>


<commit_before>#pragma once

#include "util.hh"
#include "queue.hh"

#include <avr/interrupt.h>
#include <util/delay.h>
#include <util/twi.h>

// See http://www.chrisherring.net/all/tutorial-interrupt-driven-twi-interface-for-avr-part1/

/*
enum TWIMode {
  TWIMaster,
  TWISlave
};
*/

class I2C {
public:
  enum TransferMode {
    kNoStop,        // Used to send repeated start in the subsequent transfer
    kSendStop
  };
};

template<class I2CPeriph, byte address>
class I2CDevice {
public:
  static void send(byte *const data, byte nBytes, I2C::TransferMode mode = I2C::kSendStop) {
    I2CPeriph::write(address, data, nBytes, mode);
  }
  static void receive(byte * data, byte nBytes, I2C::TransferMode mode = I2C::kSendStop) {
    I2CPeriph::read(address, data, nBytes, mode);
  }
};

class TWIMaster : public I2C {
public:
  static void setup(uint32_t clockFrequency = 100000ul) {
  	_state = kReady;
  	_errorCode = 0xFF;
  	_repStart = 0;
  	// Set prescaler (no prescaling) (TODO: set correct prescaler)
    // Note that no prescaler is necessary for 100kHz clock
  	TWSR = 0;
  	// Set bit rate
  	TWBR = ((F_CPU / clockFrequency) - 16) / 2;
  	// Enable TWI and interrupt
  	TWCR = (1 << TWIE) | (1 << TWEN);
  }

  static byte write(byte address, byte *const data, byte nBytes, TransferMode mode = kSendStop) {
    if (!isTWIReady()) return 0;
    _sla = (address << 1) | TW_WRITE;
    _mode = mode;
    _data = data;
    _dataLength = nBytes;
    TWISendStart();
  }

  static byte read(byte address, byte *data, byte nBytes, TransferMode mode = kSendStop) {
    _sla = (address << 1) | TW_READ;
    _mode = mode;
    _data = data;
    _dataLength = nBytes;
    TWISendStart();
  }

  static bool isReady(void) {
  	return (_state == kReady) || (_state == kRepeatedStartSent);
  }

  static bool onTWIInterrupt() {
    interruptImpl();
  }

private:

  enum State {
  	kReady,
  	kInitializing,
  	kRepeatedStartSent,
  	kTransmit,
  	kReceive
  };

  static byte    _sla;
  static State   _state;
  static byte    _errorCode;
  static TransmitMode    _mode;

  static byte   * _data;
  static byte   _dataLength; // The total number of bytes to transmit

  /************************ Helper methods ************************/

  // Send the START signal, enable interrupts and TWI, clear TWINT flag to resume transfer.
  static void TWISendStart() {
    TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN)|(1<<TWIE);
  }

  // Send the STOP signal, enable interrupts and TWI, clear TWINT flag.
  static void TWISendStop() {
    TWCR = (1<<TWINT)|(1<<TWSTO)|(1<<TWEN)|(1<<TWIE);
  }

  // Used to resume a transfer, clear TWINT and ensure that TWI and interrupts are enabled.
  static void TWISendTransmit()	{
    TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWIE);
  }

  // FOR MR mode. Resume a transfer, ensure that TWI and interrupts are enabled
  // and respond with an ACK if the device is addressed as a slave or after it receives a byte.
  static void TWISendACK() {
    TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWIE)|(1<<TWEA);
  }

  // FOR MR mode. Resume a transfer, ensure that TWI and interrupts are enabled
  // but DO NOT respond with an ACK if the device is addressed as a slave or after
  // it receives a byte.
  static void TWISendNACK() {
    TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWIE);
  }

  /********************* TWI state machine *********************/

  static void interruptImpl() {
  	switch (TW_STATUS)
  	{
      // ----\/ ---- START CONDITION ----\/ ----  //
      case TW_START: // Start condition has been transmitted
        TWDR = _sla;    // Transmit either SLA+W or SLA+R
        TWISendTransmit();
        break;
  		// ----\/ ---- MASTER TRANSMITTER ----\/ ----  //
  		case TW_MT_SLA_ACK: // SLA+W transmitted and ACK received
  		case TW_MT_DATA_ACK: // Data byte has been transmitted, ACK received
  			if (_dataLength > 0) // If there is more data to send
  			{
  				TWDR = *_data++; // Load data to transmit buffer
          _dataLength--;
  				_errorCode = TW_NO_INFO;
  				TWISendTransmit(); // Send the data
  			}
  			// All transmissions are complete, exit
  			else
  			{
  				_state = kReady;
  				_errorCode = 0xFF;
          if (_mode == kSendStop) {
    				TWISendStop();
          }
  			}
  			break;

  		// ----\/ ---- MASTER RECEIVER ----\/ ----  //

  		case TW_MR_SLA_ACK: // SLA+R has been transmitted, ACK has been received
  			// Switch to Master Receiver mode
  			_state = kReceive;
				_errorCode = TW_NO_INFO;
  			// If there is more than one byte to be read, receive data byte and return an ACK
  			if (_dataLength > 1)
  			{
  				TWISendACK();
  			}
  			// Otherwise when a data byte (the only data byte) is received, return NACK
  			else
  			{
  				TWISendNACK();
  			}
  			break;

  		case TW_MR_DATA_ACK: // Data has been received, ACK has been transmitted.
  			/// -- HANDLE DATA BYTE --- ///
  			*_data++ = TWDR;
        _dataLength--;
				_errorCode = TW_NO_INFO;
  			// If there is more than one byte to be read, receive data byte and return an ACK
  			if (_dataLength > 1)
  			{
  				TWISendACK();
  			}
  			// Otherwise when a data byte (the only data byte) is received, return NACK
  			else
  			{
  				TWISendNACK();
  			}
  			break;

  		case TW_MR_DATA_NACK: // Data byte has been received, NACK has been transmitted. End of transmission.

  			/// -- HANDLE DATA BYTE --- ///
  			*_data+++ = TWDR;
        _dataLength--;
  			// All transmissions are complete, exit
				_state = kReady;
				_errorCode = 0xFF;
        if (_mode == kSendStop) {
  				TWISendStop();
        }
  			break;

  		// ----\/ ---- MT and MR common ----\/ ---- //

  		case TW_MR_SLA_NACK: // SLA+R transmitted, NACK received
  		case TW_MT_SLA_NACK: // SLA+W transmitted, NACK received
  		case TW_MT_DATA_NACK: // Data byte has been transmitted, NACK received
  		case TW_MT_ARB_LOST: // Arbitration has been lost
      _state = kReady;
  			_errorCode = TW_STATUS;
  			TWISendStop();
  			break;
  		case TW_REP_START: // Repeated start has been transmitted
  			// Set the mode but DO NOT clear TWINT as the next data is not yet ready
  			_state = kRepeatedStartSent;
  			break;

  		// ----\/ ---- SLAVE RECEIVER ----\/ ----  //

  		// TODO  IMPLEMENT SLAVE RECEIVER FUNCTIONALITY

  		// ----\/ ---- SLAVE TRANSMITTER ----\/ ----  //

  		// TODO  IMPLEMENT SLAVE TRANSMITTER FUNCTIONALITY

  		// ----\/ ---- MISCELLANEOUS STATES ----\/ ----  //
  		case TW_NO_INFO:
        // It is not really possible to get into this ISR on this condition
  			// Rather, it is there to be manually set between operations
  			break;
  		case TW_BUS_ERROR: // Illegal START/STOP, abort and return error
  			_errorCode = TW_STATUS;
  			_state = kReady;
  			TWISendStop();
  			break;
  	}
  }
};
<commit_msg>Syntax error fix<commit_after>#pragma once

#include "util.hh"
#include "queue.hh"

#include <avr/interrupt.h>
#include <util/delay.h>
#include <util/twi.h>

// See http://www.chrisherring.net/all/tutorial-interrupt-driven-twi-interface-for-avr-part1/

/*
enum TWIMode {
  TWIMaster,
  TWISlave
};
*/

class I2C {
public:
  enum TransferMode {
    kNoStop,        // Used to send repeated start in the subsequent transfer
    kSendStop
  };
};

template<class I2CPeriph, byte address>
class I2CDevice {
public:
  static void send(byte *const data, byte nBytes, I2C::TransferMode mode = I2C::kSendStop) {
    I2CPeriph::write(address, data, nBytes, mode);
  }
  static void receive(byte * data, byte nBytes, I2C::TransferMode mode = I2C::kSendStop) {
    I2CPeriph::read(address, data, nBytes, mode);
  }
};

class TWIMaster : public I2C {
public:
  static void setup(uint32_t clockFrequency = 100000ul) {
  	_state = kReady;
  	_errorCode = 0xFF;
  	// Set prescaler (no prescaling) (TODO: set correct prescaler)
    // Note that no prescaler is necessary for 100kHz clock
  	TWSR = 0;
  	// Set bit rate
  	TWBR = ((F_CPU / clockFrequency) - 16) / 2;
  	// Enable TWI and interrupt
  	TWCR = (1 << TWIE) | (1 << TWEN);
  }

  static byte write(byte address, byte *const data, byte nBytes, TransferMode mode = kSendStop) {
    if (!isReady()) return 0;
    _sla = (address << 1) | TW_WRITE;
    _mode = mode;
    _data = data;
    _dataLength = nBytes;
    TWISendStart();
  }

  static byte read(byte address, byte *data, byte nBytes, TransferMode mode = kSendStop) {
    _sla = (address << 1) | TW_READ;
    _mode = mode;
    _data = data;
    _dataLength = nBytes;
    TWISendStart();
  }

  static bool isReady(void) {
  	return (_state == kReady) || (_state == kRepeatedStartSent);
  }

  static bool onTWIInterrupt() {
    interruptImpl();
  }

private:

  enum State {
  	kReady,
  	kInitializing,
  	kRepeatedStartSent,
  	kTransmit,
  	kReceive
  };

  static byte    _sla;
  static State   _state;
  static byte    _errorCode;
  static TransferMode    _mode;

  static byte   * _data;
  static byte   _dataLength; // The total number of bytes to transmit

  /************************ Helper methods ************************/

  // Send the START signal, enable interrupts and TWI, clear TWINT flag to resume transfer.
  static void TWISendStart() {
    TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN)|(1<<TWIE);
  }

  // Send the STOP signal, enable interrupts and TWI, clear TWINT flag.
  static void TWISendStop() {
    TWCR = (1<<TWINT)|(1<<TWSTO)|(1<<TWEN)|(1<<TWIE);
  }

  // Used to resume a transfer, clear TWINT and ensure that TWI and interrupts are enabled.
  static void TWISendTransmit()	{
    TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWIE);
  }

  // FOR MR mode. Resume a transfer, ensure that TWI and interrupts are enabled
  // and respond with an ACK if the device is addressed as a slave or after it receives a byte.
  static void TWISendACK() {
    TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWIE)|(1<<TWEA);
  }

  // FOR MR mode. Resume a transfer, ensure that TWI and interrupts are enabled
  // but DO NOT respond with an ACK if the device is addressed as a slave or after
  // it receives a byte.
  static void TWISendNACK() {
    TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWIE);
  }

  /********************* TWI state machine *********************/

  static void interruptImpl() {
  	switch (TW_STATUS)
  	{
      // ----\/ ---- START CONDITION ----\/ ----  //
      case TW_START: // Start condition has been transmitted
        TWDR = _sla;    // Transmit either SLA+W or SLA+R
        TWISendTransmit();
        break;
  		// ----\/ ---- MASTER TRANSMITTER ----\/ ----  //
  		case TW_MT_SLA_ACK: // SLA+W transmitted and ACK received
  		case TW_MT_DATA_ACK: // Data byte has been transmitted, ACK received
  			if (_dataLength > 0) // If there is more data to send
  			{
  				TWDR = *_data++; // Load data to transmit buffer
          _dataLength--;
  				_errorCode = TW_NO_INFO;
  				TWISendTransmit(); // Send the data
  			}
  			// All transmissions are complete, exit
  			else
  			{
  				_state = kReady;
  				_errorCode = 0xFF;
          if (_mode == kSendStop) {
    				TWISendStop();
          }
  			}
  			break;

  		// ----\/ ---- MASTER RECEIVER ----\/ ----  //

  		case TW_MR_SLA_ACK: // SLA+R has been transmitted, ACK has been received
  			// Switch to Master Receiver mode
  			_state = kReceive;
				_errorCode = TW_NO_INFO;
  			// If there is more than one byte to be read, receive data byte and return an ACK
  			if (_dataLength > 1)
  			{
  				TWISendACK();
  			}
  			// Otherwise when a data byte (the only data byte) is received, return NACK
  			else
  			{
  				TWISendNACK();
  			}
  			break;

  		case TW_MR_DATA_ACK: // Data has been received, ACK has been transmitted.
  			/// -- HANDLE DATA BYTE --- ///
  			*_data++ = TWDR;
        _dataLength--;
				_errorCode = TW_NO_INFO;
  			// If there is more than one byte to be read, receive data byte and return an ACK
  			if (_dataLength > 1)
  			{
  				TWISendACK();
  			}
  			// Otherwise when a data byte (the only data byte) is received, return NACK
  			else
  			{
  				TWISendNACK();
  			}
  			break;

  		case TW_MR_DATA_NACK: // Data byte has been received, NACK has been transmitted. End of transmission.

  			/// -- HANDLE DATA BYTE --- ///
  			*_data++ = TWDR;
        _dataLength--;
  			// All transmissions are complete, exit
				_state = kReady;
				_errorCode = 0xFF;
        if (_mode == kSendStop) {
  				TWISendStop();
        }
  			break;

  		// ----\/ ---- MT and MR common ----\/ ---- //

  		case TW_MR_SLA_NACK: // SLA+R transmitted, NACK received
  		case TW_MT_SLA_NACK: // SLA+W transmitted, NACK received
  		case TW_MT_DATA_NACK: // Data byte has been transmitted, NACK received
  		case TW_MT_ARB_LOST: // Arbitration has been lost
      _state = kReady;
  			_errorCode = TW_STATUS;
  			TWISendStop();
  			break;
  		case TW_REP_START: // Repeated start has been transmitted
  			// Set the mode but DO NOT clear TWINT as the next data is not yet ready
  			_state = kRepeatedStartSent;
  			break;

  		// ----\/ ---- SLAVE RECEIVER ----\/ ----  //

  		// TODO  IMPLEMENT SLAVE RECEIVER FUNCTIONALITY

  		// ----\/ ---- SLAVE TRANSMITTER ----\/ ----  //

  		// TODO  IMPLEMENT SLAVE TRANSMITTER FUNCTIONALITY

  		// ----\/ ---- MISCELLANEOUS STATES ----\/ ----  //
  		case TW_NO_INFO:
        // It is not really possible to get into this ISR on this condition
  			// Rather, it is there to be manually set between operations
  			break;
  		case TW_BUS_ERROR: // Illegal START/STOP, abort and return error
  			_errorCode = TW_STATUS;
  			_state = kReady;
  			TWISendStop();
  			break;
  	}
  }
};
<|endoftext|>


<commit_before>/*
 * Copyright 2014–2015 The SmartSqlite contributors (see NOTICE.txt)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "smartsqlite/version.h"

#include <cstring>

#include "smartsqlite/sqlite3.h"

namespace SmartSqlite {

namespace {
const auto SMARTSQLITE_VERSION_CODE = int{4};
const auto SMARTSQLITE_VERSION_STRING = std::string{"v4"};
}

std::string version()
{
    return SMARTSQLITE_VERSION_STRING;
}

int versionCode()
{
    return SMARTSQLITE_VERSION_CODE;
}

std::string sqliteVersion()
{
    return sqlite3_libversion();
}

bool checkSqliteVersion()
{
    return
            (sqlite3_libversion_number() == SQLITE_VERSION_NUMBER) &&
            (std::strcmp(sqlite3_sourceid(), SQLITE_SOURCE_ID) == 0) &&
            (std::strcmp(sqlite3_libversion(), SQLITE_VERSION) == 0);
}

}
<commit_msg>Make failing version check more verbose<commit_after>/*
 * Copyright 2014–2015 The SmartSqlite contributors (see NOTICE.txt)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "smartsqlite/version.h"

#include <cstring>
#include <iostream>

#include "smartsqlite/sqlite3.h"

namespace SmartSqlite {

namespace {
const auto SMARTSQLITE_VERSION_CODE = int{4};
const auto SMARTSQLITE_VERSION_STRING = std::string{"v4"};
}

std::string version()
{
    return SMARTSQLITE_VERSION_STRING;
}

int versionCode()
{
    return SMARTSQLITE_VERSION_CODE;
}

std::string sqliteVersion()
{
    return sqlite3_libversion();
}

bool checkSqliteVersion()
{
    auto logPrefix = "SmartSqlite version check failed: ";
    bool success = true;

    if (sqlite3_libversion_number() != SQLITE_VERSION_NUMBER)
    {
        success = false;
        std::cerr << logPrefix
                  << "sqlite3_libversion_number()==" << sqlite3_libversion_number()
                  << ", SQLITE_VERSION_NUMBER==" << SQLITE_VERSION_NUMBER
                  << std::endl;
    }

    if (std::strcmp(sqlite3_sourceid(), SQLITE_SOURCE_ID))
    {
        success = false;
        std::cerr << logPrefix
                  << "sqlite3_sourceid()==" << sqlite3_sourceid()
                  << ", SQLITE_SOURCE_ID==" << SQLITE_SOURCE_ID
                  << std::endl;
    }

    if (std::strcmp(sqlite3_libversion(), SQLITE_VERSION))
    {
        success = false;
        std::cerr << logPrefix
                  << "sqlite3_libversion()==" << sqlite3_libversion()
                  << ", SQLITE_VERSION==" << SQLITE_VERSION
                  << std::endl;
    }

    return success;
}

}
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>

#include "version.h"

// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("MintCoin");

// Client version number
#define CLIENT_VERSION_SUFFIX   ""

// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
//   generated by the build environment, possibly containing the output
//   of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
//   be defined (automatically using the export-subst git attribute), and
//   GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
//   * if BUILD_DESC is defined, use that literally (output of git-describe)
//   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
//   * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added

// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#    include "build.h"
#endif

// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
#    define GIT_COMMIT_ID ""
#    define GIT_COMMIT_DATE "$Format:%cD"
#endif

#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "" commit

#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) ""

#ifndef BUILD_DESC
#    ifdef GIT_COMMIT_ID
#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID)
#    else
#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD)
#    endif
#endif

#ifndef BUILD_DATE
#    ifdef GIT_COMMIT_DATE
#        define BUILD_DATE GIT_COMMIT_DATE
#    else
#        define BUILD_DATE __DATE__ ", " __TIME__
#    endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<commit_msg>Better version string formatting<commit_after>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "version.h"

#include <string>

// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("MintCoin");

// Client version number
#define CLIENT_VERSION_SUFFIX   ""

// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
//   generated by the build environment, possibly containing the output
//   of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
//   be defined (automatically using the export-subst git attribute), and
//   GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
//   * if BUILD_DESC is defined, use that literally (output of git-describe)
//   * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
//   * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added

// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#    include "build.h"
#endif

// git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$
#ifdef GIT_ARCHIVE
#    define GIT_COMMIT_ID "$Format:%h$"
#    define GIT_COMMIT_DATE "$Format:%cD$"
#endif

#define BUILD_DESC_WITH_SUFFIX(maj,min,rev,build,suffix) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" DO_STRINGIZE(suffix)

#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit

#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
    "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"

#ifndef BUILD_DESC
#    ifdef BUILD_SUFFIX
#        define BUILD_DESC BUILD_DESC_WITH_SUFFIX(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, BUILD_SUFFIX)
#    elif defined(GIT_COMMIT_ID)
#        define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#    else
#        define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#    endif
#endif

#ifndef BUILD_DATE
#    ifdef GIT_COMMIT_DATE
#        define BUILD_DATE GIT_COMMIT_DATE
#    else
#        define BUILD_DATE __DATE__ ", " __TIME__
#    endif
#endif

const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<|endoftext|>


<commit_before>#include <BinaryTree.hpp>
#include <catch.hpp>

SCENARIO ("init", "[init]")
{
  BinaryTree<int> obj;
  REQUIRE(obj.root_() == nullptr);
}

SCENARIO("insert", "[insert]")
{
  BinaryTree<int> obj;
  obj.insert_node(3);
  REQUIRE(obj.find_node(3, obj.root_())->data == 3);
}

SCENARIO("find_node", "[find_node]")
{
  BinaryTree<int> obj;
  obj.insert_node(2);
  REQUIRE(obj.find_node(2, obj.root_()) != nullptr);
  REQUIRE(obj.find_node(2, obj.root_())->data == 2);
}

SCENARIO("get root", "[get root]")
{
  BinaryTree<int> obj;
  obj.insert_node(4);
  REQUIRE(obj.root_() != 0);
}

SCENARIO ("reading", "[reading]")
{
   BinaryTree<int> obj;
   obj.reading("file1.txt");
   REQUIRE(obj.search_result(1) == 1);
}
<commit_msg>Update init.cpp<commit_after>#include <BinaryTree.hpp>
#include <catch.hpp>

SCENARIO ("init", "[init]")
{
  BinaryTree<int> obj;
  REQUIRE(obj.root_() == nullptr);
}

SCENARIO("insert", "[insert]")
{
  BinaryTree<int> obj;
  obj.insert_node(3);
  REQUIRE(obj.find_node(3, obj.root_())->data == 3);
}

SCENARIO("find_node", "[find_node]")
{
  BinaryTree<int> obj;
  obj.insert_node(2);
  REQUIRE(obj.find_node(2, obj.root_()) != nullptr);
  REQUIRE(obj.find_node(2, obj.root_())->data == 2);
}

SCENARIO("get root", "[get root]")
{
  BinaryTree<int> obj;
  obj.insert_node(4);
  REQUIRE(obj.root_() != 0);
}

SCENARIO ("reading", "[init]")
{
   BinaryTree<int> obj;
   obj.reading("file2.txt");
   REQUIRE(obj.search_result(1) == 1))
}
<|endoftext|>


<commit_before>#include <binary_search_tree.hpp>
#include <catch.hpp>

SCENARIO("default constructor")
{
	BinarySearchTree<int> bst;
	REQUIRE(bst.root() == nullptr);
	REQUIRE(bst.count() == 0);
}

SCENARIO("insertElement")
{
	BinarySearchTree<int> bst;
	bst.insert(7);
	REQUIRE(bst.findElement() == 7);
	REQUIRE(bst.count() == 1);
}
<commit_msg>Update init.cpp<commit_after>#include <binary_search_tree.hpp>
#include <catch.hpp>

SCENARIO("default constructor")
{
	BinarySearchTree<int> bst;
	REQUIRE(bst.root() == nullptr);
	REQUIRE(bst.count() == 0);
}

SCENARIO("insertElement")
{
	BinarySearchTree<int> bst;
	bst.insertElement(7);
	REQUIRE(bst.findElement() == 7);
	REQUIRE(bst.count() == 1);
}
<|endoftext|>


<commit_before>#include <matrix.hpp>
#include <catch.hpp>

SCENARIO("matrix init without parametrs", "[init wp]") {
	Matrix matrix;
	REQUIRE(matrix.rows() == 4);
	REQUIRE(matrix.columns() == 4);

	for (int i=0;i<matrix.rows(); i++) {
		for (int j = 0; j<matrix.columns();j++) {
			REQUIRE(matrix.Element(i,j) == 0);
		}
	}
}

SCENARIO("matrix init with parametrs", "[init withp]") {
	Matrix matrix(6,6);
	REQUIRE(matrix.rows() == 6);
	REQUIRE(matrix.columns() == 6);

	for (int i=0;i<matrix.rows(); i++) {
		for (int j = 0; j<matrix.columns();j++) {
			REQUIRE(matrix.Element(i,j) == 0);
		}
	}
}

SCENARIO("matrix init copy", "[init copy]") {
	Matrix matrix(6,6);
	Matrix matrix1(matrix);
	REQUIRE(matrix1.rows() == matrix.rows());
	REQUIRE(matrix1.columns() == matrix.columns());

	for (int i=0;i<matrix.rows(); i++) {
		for (int j = 0; j<matrix.columns();j++) {
			REQUIRE(matrix.Element(i,j) == matrix1.Element(i,j));
		}
	}
}

SCENARIO("matrix fill", "[fill]") {
	Matrix matrix(2,2);
	ofstream test1("test1.txt");
	test1 << "1 2 3 4";
	test1.close();
	matrix.fill("test1.txt");
	REQUIRE(matrix.Element(0,0) == 1);
	REQUIRE(matrix.Element(0,1) == 2);
	REQUIRE(matrix.Element(1,0) == 3);
	REQUIRE(matrix.Element(1,1) == 4);
}

SCENARIO("matrix sum", "[sum]") {
	Matrix matrix(2,2);
	Matrix matrix1(2,2);
	Matrix sum(2,2);

	ofstream test1("test1.txt");
	test1 << "1 2 3 4";
	test1.close();

	matrix.fill("test1.txt");
	matrix1.fill("test1.txt");
	//ofstream sumfile("sumfile.txt");
	//sumfile << "2 4 6 8";
	//sum.fill("sumfile.txt");
	//sumfile.close();
	REQUIRE(matrix.Element(0,0) + matrix1.Element(0,0) == 2);
	REQUIRE(matrix.Element(0,1) + matrix1.Element(0,1) == 4);
	REQUIRE(matrix.Element(1,0) + matrix1.Element(1,0) == 6);
	REQUIRE(matrix.Element(1,1) + matrix1.Element(1,1) == 8);

}

<commit_msg>Update init.cpp<commit_after>#include <matrix.hpp>
#include <catch.hpp>

SCENARIO("matrix init without parametrs", "[init wp]") {
	Matrix matrix;
	REQUIRE(matrix.rows() == 4);
	REQUIRE(matrix.columns() == 4);

	for (int i=0;i<matrix.rows(); i++) {
		for (int j = 0; j<matrix.columns();j++) {
			REQUIRE(matrix.Element(i,j) == 0);
		}
	}
}

SCENARIO("matrix init with parametrs", "[init withp]") {
	Matrix matrix(6,6);
	REQUIRE(matrix.rows() == 6);
	REQUIRE(matrix.columns() == 6);

	for (int i=0;i<matrix.rows(); i++) {
		for (int j = 0; j<matrix.columns();j++) {
			REQUIRE(matrix.Element(i,j) == 0);
		}
	}
}

SCENARIO("matrix init copy", "[init copy]") {
	Matrix matrix(6,6);
	Matrix matrix1(matrix);
	REQUIRE(matrix1.rows() == matrix.rows());
	REQUIRE(matrix1.columns() == matrix.columns());

	for (int i=0;i<matrix.rows(); i++) {
		for (int j = 0; j<matrix.columns();j++) {
			REQUIRE(matrix.Element(i,j) == matrix1.Element(i,j));
		}
	}
}

SCENARIO("matrix fill", "[fill]") {
	Matrix matrix(2,2);
	ofstream test1("test1.txt");
	test1 << "1 2 3 4";
	test1.close();
	matrix.fill("test1.txt");
	REQUIRE(matrix.Element(0,0) == 1);
	REQUIRE(matrix.Element(0,1) == 2);
	REQUIRE(matrix.Element(1,0) == 3);
	REQUIRE(matrix.Element(1,1) == 4);
}

SCENARIO("matrix sum", "[sum]") {
	Matrix matrix(2,2);
	Matrix matrix1(2,2);
	Matrix sum(2,2);

	ofstream test1("test1.txt");
	test1 << "1 2 3 4";
	test1.close();

	matrix.fill("test1.txt");
	matrix1.fill("test1.txt");
	//ofstream sumfile("sumfile.txt");
	//sumfile << "2 4 6 8";
	//sum.fill("sumfile.txt");
	//sumfile.close();
	REQUIRE(matrix.Element(0,0) + matrix1.Element(0,0) == 2);
	REQUIRE(matrix.Element(0,1) + matrix1.Element(0,1) == 4);
	REQUIRE(matrix.Element(1,0) + matrix1.Element(1,0) == 6);
	REQUIRE(matrix.Element(1,1) + matrix1.Element(1,1) == 8);

}

SCENARIO("matrix Proizv", "[Pro]") {
	Matrix matrix(2,2);
	Matrix matrix1(2,2);
	Matrix Pro(2,2);

	ofstream test1("test1.txt");
	test1 << "1 2 3 4";
	test1.close();

	matrix.fill("test1.txt");
	matrix1.fill("test1.txt");
	//ofstream sumfile("sumfile.txt");
	//sumfile << "2 4 6 8";
	//sum.fill("sumfile.txt");
	//sumfile.close();
	REQUIRE(matrix[0][0] * matrix1[0][0] + matrix[0][1] * matrix[1][0] == 7);
	REQUIRE(matrix[0][0] * matrix1[1][0] + matrix[0][1] * matrix[1][1] == 10);
	REQUIRE(matrix[0][1] * matrix1[0][0] + matrix[1][1] * matrix[0][1] == 15);
	REQUIRE(matrix[0][1] * matrix1[1][0] + matrix[1][1] * matrix[1][1] == 22);

}

<|endoftext|>


<commit_before>#define CATCH_CONFIG_RUNNER
#include <catch.hpp>
#include "sphere.cpp"
#include "box.hpp"

#include <glm/vec3.hpp>

TEST_CASE("get volume of sphere", "[volume]") {
	Sphere sphere;
	REQUIRE(sphere.volume() == Approx(4.1888));
}

TEST_CASE("get area of sphere", "[area]") {
	Sphere sphere;
	REQUIRE(sphere.area() == Approx(12.5664));
}

TEST_CASE("get radius of sphere", "[radius]") {
	Sphere sphere;
	REQUIRE(sphere.radius() == 1);
}

TEST_CASE("get center of sphere", "[center]") {
	Sphere sphere;
	glm::vec3 tmp{0,0,0};
	REQUIRE(sphere.center() == tmp);
}

TEST_CASE("constructors of sphere", "[constructors]") {
	Sphere s1;
	Sphere s2{{0,0,0},1};
	REQUIRE(s1.center() == s2.center());
	REQUIRE(s1.radius() == s2.radius());
	REQUIRE(s1.area() == s2.area());
	REQUIRE(s1.volume() == s2.volume());
}

TEST_CASE("constructors for box", "[constructors]") {
	Box b1;
	glm::vec3 tmp{0,0,0};
	REQUIRE(b1.min() == tmp);
	tmp = {1,1,1};
	REQUIRE(b1.max() == tmp);
	Box b2{{1,1,3},{3,2,2}};
	tmp = {1,1,2};
	REQUIRE(b2.min() == tmp);
	tmp = {3,2,3};
	REQUIRE(b2.max() == tmp);
}

int main(int argc, char *argv[]) {
  return Catch::Session().run(argc, argv);
}
<commit_msg>Add mehtod tests for box<commit_after>#define CATCH_CONFIG_RUNNER
#include <catch.hpp>
#include "sphere.cpp"
#include "box.hpp"

#include <glm/vec3.hpp>

TEST_CASE("get volume of sphere", "[volume]") {
	Sphere sphere;
	REQUIRE(sphere.volume() == Approx(4.1888));
}

TEST_CASE("get area of sphere", "[area]") {
	Sphere sphere;
	REQUIRE(sphere.area() == Approx(12.5664));
}

TEST_CASE("get radius of sphere", "[radius]") {
	Sphere sphere;
	REQUIRE(sphere.radius() == 1);
}

TEST_CASE("get center of sphere", "[center]") {
	Sphere sphere;
	glm::vec3 tmp{0,0,0};
	REQUIRE(sphere.center() == tmp);
}

TEST_CASE("constructors of sphere", "[constructors]") {
	Sphere s1;
	Sphere s2{{0,0,0},1};
	REQUIRE(s1.center() == s2.center());
	REQUIRE(s1.radius() == s2.radius());
	REQUIRE(s1.area() == s2.area());
	REQUIRE(s1.volume() == s2.volume());
}

TEST_CASE("constructors for box", "[constructors]") {
	Box b1;
	glm::vec3 tmp{0,0,0};
	REQUIRE(b1.min() == tmp);
	tmp = {1,1,1};
	REQUIRE(b1.max() == tmp);
	Box b2{{1,1,3},{3,2,2}};
	tmp = {1,1,2};
	REQUIRE(b2.min() == tmp);
	tmp = {3,2,3};
	REQUIRE(b2.max() == tmp);
}

TEST_CASE("get area of box", "[area]") {
	Box box;
	REQUIRE(box.area() == 6);
}

TEST_CASE("get volume of box", "[area]") {
	Box box;
	REQUIRE(box.volume() == 1);
}

int main(int argc, char *argv[]) {
  return Catch::Session().run(argc, argv);
}

//Tests for Box<|endoftext|>


<commit_before>#include <gtest\gtest.h>
#include <BufferedReader.h>

TEST(BufferedReader, OpenClose) {
	BufferedReader reader(1024);

	EXPECT_FALSE(reader.Close());
	EXPECT_FALSE(reader.Open(nullptr));
	EXPECT_FALSE(reader.Open(L"C:/temp/cwd/zbot"));
	EXPECT_TRUE(reader.Open(L"file"));
	EXPECT_TRUE(reader.Close());
	EXPECT_FALSE(reader.Close());
	EXPECT_FALSE(reader.Open(nullptr));

}

TEST(BufferedReader, InvalidRead) {
	BufferedReader reader(256);
	BYTE buffer[8192] = {};

	EXPECT_EQ(0, reader.Read(nullptr, 0));
	EXPECT_EQ(0, reader.Read(buffer, 0));
	EXPECT_EQ(0, reader.Read(nullptr, 128));
	EXPECT_EQ(0, reader.Read(buffer, 128));
	EXPECT_EQ(0, reader.Read(nullptr, 512));
	EXPECT_EQ(0, reader.Read(buffer, 512));
}

TEST(BufferedReader, Read) {
	BufferedReader reader(256);
	HANDLE hFile;
	DWORD readSize1, readSize2;
	BYTE buffer1[8192] = {}, buffer2[8192] = {};

	hFile = CreateFile(L"file", GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
	if (hFile == INVALID_HANDLE_VALUE)
		return;

	EXPECT_TRUE(reader.Open(L"file"));
	EXPECT_EQ(0, reader.Read(buffer1, 0));

	readSize1 = reader.Read(buffer1, 128);
	ReadFile(hFile, buffer2, 128, &readSize2, nullptr);
	EXPECT_EQ(readSize2, readSize1);
	EXPECT_EQ(0, memcmp(buffer1, buffer2, readSize1));
	readSize1 = reader.Read(buffer1, 512);
	ReadFile(hFile, buffer2, 512, &readSize2, nullptr);
	EXPECT_EQ(readSize2, readSize1);
	EXPECT_EQ(0, memcmp(buffer1, buffer2, readSize1));
	readSize1 = reader.Read(buffer1, 2048);
	ReadFile(hFile, buffer2, 2048, &readSize2, nullptr);
	EXPECT_EQ(readSize2, readSize1);
	EXPECT_EQ(0, memcmp(buffer1, buffer2, readSize1));

	SetFilePointer(hFile, 0, nullptr, SEEK_SET);
	readSize1 = reader.Read(0, buffer1, 128);
	ReadFile(hFile, buffer2, 128, &readSize2, nullptr);
	EXPECT_EQ(readSize2, readSize1);
	EXPECT_EQ(0, memcmp(buffer1, buffer2, readSize1));

	SetFilePointer(hFile, 0, nullptr, SEEK_SET);
	readSize1 = reader.Read(0, buffer1, 256);
	ReadFile(hFile, buffer2, 256, &readSize2, nullptr);
	EXPECT_EQ(readSize2, readSize1);
	EXPECT_EQ(0, memcmp(buffer1, buffer2, readSize1));

	SetFilePointer(hFile, 0, nullptr, SEEK_SET);
	readSize1 = reader.Read(0, buffer1, 2048);
	ReadFile(hFile, buffer2, 2048, &readSize2, nullptr);
	EXPECT_EQ(readSize2, readSize1);
	EXPECT_EQ(0, memcmp(buffer1, buffer2, readSize1));

	SetFilePointer(hFile, 0x100, nullptr, SEEK_SET);
	readSize1 = reader.Read(0x100, buffer1, 2048);
	ReadFile(hFile, buffer2, 2048, &readSize2, nullptr);
	EXPECT_EQ(readSize2, readSize1);
	EXPECT_EQ(0, memcmp(buffer1, buffer2, readSize1));
}

int main(int argc, char *argv[]) {
	::testing::InitGoogleTest(&argc, argv);
	return RUN_ALL_TESTS();
}<commit_msg>add test<commit_after>#include <gtest\gtest.h>
#include <BufferedReader.h>

TEST(BufferedReader, OpenClose) {
	BufferedReader reader(1024);

	EXPECT_FALSE(reader.Close());
	EXPECT_FALSE(reader.Open(nullptr));
	EXPECT_FALSE(reader.Open(L"C:/temp/cwd/zbot"));
	EXPECT_TRUE(reader.Open(L"file"));
	EXPECT_TRUE(reader.Close());
	EXPECT_FALSE(reader.Close());
	EXPECT_FALSE(reader.Open(nullptr));

}

TEST(BufferedReader, InvalidRead) {
	BufferedReader reader(256);
	BYTE buffer[8192] = {};

	EXPECT_EQ(0, reader.Read(nullptr, 0));
	EXPECT_EQ(0, reader.Read(buffer, 0));
	EXPECT_EQ(0, reader.Read(nullptr, 128));
	EXPECT_EQ(0, reader.Read(buffer, 128));
	EXPECT_EQ(0, reader.Read(nullptr, 512));
	EXPECT_EQ(0, reader.Read(buffer, 512));
}

TEST(BufferedReader, Read) {
	BufferedReader reader(256);
	HANDLE hFile;
	DWORD readSize1, readSize2;
	BYTE buffer1[8192] = {}, buffer2[8192] = {};

	hFile = CreateFile(L"file", GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
	if (hFile == INVALID_HANDLE_VALUE)
		return;

	EXPECT_TRUE(reader.Open(L"file"));
	EXPECT_EQ(0, reader.Read(buffer1, 0));

	readSize1 = reader.Read(buffer1, 128);
	ReadFile(hFile, buffer2, 128, &readSize2, nullptr);
	EXPECT_EQ(readSize2, readSize1);
	EXPECT_EQ(0, memcmp(buffer1, buffer2, readSize1));
	readSize1 = reader.Read(buffer1, 512);
	ReadFile(hFile, buffer2, 512, &readSize2, nullptr);
	EXPECT_EQ(readSize2, readSize1);
	EXPECT_EQ(0, memcmp(buffer1, buffer2, readSize1));
	readSize1 = reader.Read(buffer1, 2048);
	ReadFile(hFile, buffer2, 2048, &readSize2, nullptr);
	EXPECT_EQ(readSize2, readSize1);
	EXPECT_EQ(0, memcmp(buffer1, buffer2, readSize1));

	SetFilePointer(hFile, 0, nullptr, SEEK_SET);
	readSize1 = reader.Read(0, buffer1, 128);
	ReadFile(hFile, buffer2, 128, &readSize2, nullptr);
	EXPECT_EQ(readSize2, readSize1);
	EXPECT_EQ(0, memcmp(buffer1, buffer2, readSize1));

	SetFilePointer(hFile, 0, nullptr, SEEK_SET);
	readSize1 = reader.Read(0, buffer1, 256);
	ReadFile(hFile, buffer2, 256, &readSize2, nullptr);
	EXPECT_EQ(readSize2, readSize1);
	EXPECT_EQ(0, memcmp(buffer1, buffer2, readSize1));

	SetFilePointer(hFile, 0, nullptr, SEEK_SET);
	readSize1 = reader.Read(0, buffer1, 2048);
	ReadFile(hFile, buffer2, 2048, &readSize2, nullptr);
	EXPECT_EQ(readSize2, readSize1);
	EXPECT_EQ(0, memcmp(buffer1, buffer2, readSize1));

	SetFilePointer(hFile, 0x100, nullptr, SEEK_SET);
	readSize1 = reader.Read(0x100, buffer1, 2048);
	ReadFile(hFile, buffer2, 2048, &readSize2, nullptr);
	EXPECT_EQ(readSize2, readSize1);
	EXPECT_EQ(0, memcmp(buffer1, buffer2, readSize1));

	for (DWORD i = 0; i < 256; ++i) {
		SetFilePointer(hFile, i, nullptr, SEEK_SET);
		readSize1 = reader.Read(i, buffer1, 128);
		ReadFile(hFile, buffer2, 128, &readSize2, nullptr);
		EXPECT_EQ(readSize2, readSize1);
		EXPECT_EQ(0, memcmp(buffer1, buffer2, readSize1));
	}
}

int main(int argc, char *argv[]) {
	::testing::InitGoogleTest(&argc, argv);
	return RUN_ALL_TESTS();
}<|endoftext|>


<commit_before>/*****************************************************************************************
 *                                                                                *
 * OpenSpace                                                                             *
 *                                                                                *
 * Copyright (c) 2014-2020                                                               *
 *                                                                                *
 * 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.                                         *
 ****************************************************************************************/

#define CATCH_CONFIG_RUNNER
#include "catch2/catch.hpp"

#include <openspace/engine/configuration.h>
#include <openspace/engine/globals.h>
#include <openspace/engine/openspaceengine.h>
#include <openspace/engine/windowdelegate.h>
#include <openspace/util/factorymanager.h>
#include <openspace/util/spicemanager.h>
#include <openspace/util/time.h>
#include <ghoul/filesystem/file.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/logging/logmanager.h>
#include <ghoul/lua/ghoul_lua.h>
#include <ghoul/misc/dictionary.h>
#include <ghoul/ghoul.h>
#include <iostream>

int main(int argc, char** argv) {
    using namespace openspace;
    ghoul::initialize();

    // Register the path of the executable,
    // to make it possible to find other files in the same directory.
    FileSys.registerPathToken(
        "${BIN}",
        ghoul::filesystem::File(absPath(argv[0])).directoryName(),
        ghoul::filesystem::FileSystem::Override::Yes
    );

    std::string configFile = configuration::findConfiguration();
    *global::configuration = configuration::loadConfigurationFromFile(configFile);
    global::openSpaceEngine->registerPathTokens();
    global::openSpaceEngine->initialize();

    FileSys.registerPathToken("${TESTDIR}", "${BASE}/tests");

    // All of the relevant tests initialize the SpiceManager
    openspace::SpiceManager::deinitialize();

    int result = Catch::Session().run(argc, argv);

    // And the deinitialization needs the SpiceManager to be initialized
    openspace::SpiceManager::initialize();
    global::openSpaceEngine->deinitialize();
    return result;
}
<commit_msg>Restored missing global::create call to tests app<commit_after>/*****************************************************************************************
 *                                                                                *
 * OpenSpace                                                                             *
 *                                                                                *
 * Copyright (c) 2014-2020                                                               *
 *                                                                                *
 * 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.                                         *
 ****************************************************************************************/

#define CATCH_CONFIG_RUNNER
#include "catch2/catch.hpp"

#include <openspace/engine/configuration.h>
#include <openspace/engine/globals.h>
#include <openspace/engine/openspaceengine.h>
#include <openspace/engine/windowdelegate.h>
#include <openspace/util/factorymanager.h>
#include <openspace/util/spicemanager.h>
#include <openspace/util/time.h>
#include <ghoul/filesystem/file.h>
#include <ghoul/filesystem/filesystem.h>
#include <ghoul/logging/logmanager.h>
#include <ghoul/lua/ghoul_lua.h>
#include <ghoul/misc/dictionary.h>
#include <ghoul/ghoul.h>
#include <iostream>

int main(int argc, char** argv) {
    using namespace openspace;
    ghoul::initialize();
    global::create();

    // Register the path of the executable,
    // to make it possible to find other files in the same directory.
    FileSys.registerPathToken(
        "${BIN}",
        ghoul::filesystem::File(absPath(argv[0])).directoryName(),
        ghoul::filesystem::FileSystem::Override::Yes
    );

    std::string configFile = configuration::findConfiguration();
    *global::configuration = configuration::loadConfigurationFromFile(configFile);
    global::openSpaceEngine->registerPathTokens();
    global::openSpaceEngine->initialize();

    FileSys.registerPathToken("${TESTDIR}", "${BASE}/tests");

    // All of the relevant tests initialize the SpiceManager
    openspace::SpiceManager::deinitialize();

    int result = Catch::Session().run(argc, argv);

    // And the deinitialization needs the SpiceManager to be initialized
    openspace::SpiceManager::initialize();
    global::openSpaceEngine->deinitialize();
    return result;
}
<|endoftext|>


<commit_before>/* code_completion_service.cpp */

#include "code_completion_service.h"
#include "io/resource_loader.h"
#include "globals.h"

#ifdef GDSCRIPT_ENABLED
#include "modules/gdscript/gd_script.h"
#endif

static bool _is_symbol(CharType c) {

	return c!='_' && ((c>='!' && c<='/') || (c>=':' && c<='@') || (c>='[' && c<='`') || (c>='{' && c<='~') || c=='\t');
}

static bool _is_completable(CharType c) {

	return !_is_symbol(c) || c=='"' || c=='\'';
}

CodeCompletionService::Result CodeCompletionService::obtain_suggestions(const Request& p_request) {

	#ifdef GDSCRIPT_ENABLED
	Result result(true);

	String path = Globals::get_singleton()->localize_path(p_request.script_path);

	if (path == "res://" || !path.begins_with("res://"))
		return Result();

	Ref<Script> script = ResourceLoader::load(path);

	if (!script.is_valid() || !script->cast_to<GDScript>())
		return Result();

	String script_text = p_request.script_text;

	if (script_text.empty()) {
		ERR_FAIL_COND_V(!script->has_source_code(), result);
		script_text = script->get_source_code();
	}

	Node *base = get_tree()->get_edited_scene_root();
	if (base) {
		base = _find_node_for_script(base,base,script);
	}

	String current_line = _get_text_for_completion(p_request, script_text);

	List<String> options;
	script->get_language()->complete_code(script_text, script->get_path().get_base_dir(), base, &options, result.hint);

	if (options.size() > 0) {
		result.prefix = _filter_completion_candidates(p_request.column, current_line, options, result.suggestions);
	}

	return result;
	#else
	return Result();
	#endif
}

String CodeCompletionService::_get_text_for_completion(const Request& p_request, String& r_text) {

	Vector<String> substrings = r_text.replace("\r","").split("\n");
	r_text.clear();

	int len = substrings.size();

	for (int i=0;i<len;i++) {
		if (i==p_request.row) {
			r_text+=substrings[i].substr(0,p_request.column);
			r_text+=String::chr(0xFFFF); //not unicode, represents the cursor
			r_text+=substrings[i].substr(p_request.column,substrings[i].size());
		} else {
			r_text+=substrings[i];
		}

		if (i!=len-1)
			r_text+="\n";
	}

	return substrings[p_request.row];
}

Node* CodeCompletionService::_find_node_for_script(Node* p_base, Node* p_current, const Ref<Script>& p_script) {

	if (p_current->get_owner()!=p_base && p_base!=p_current)
		return NULL;
	Ref<Script> c = p_current->get_script();
	if (c==p_script)
		return p_current;
	for(int i=0;i<p_current->get_child_count();i++) {
		Node *found = _find_node_for_script(p_base,p_current->get_child(i),p_script);
		if (found)
			return found;
	}

	return NULL;
}

String CodeCompletionService::_filter_completion_candidates(int p_col, const String& p_line, const List<String>& p_options, Vector<String> &r_suggestions) {

	int cofs = CLAMP(p_col,0,p_line.length());

	//look for keywords first

	bool inquote=false;
	int first_quote=-1;

	int c=cofs-1;
	while(c>=0) {
		if (p_line[c]=='"' || p_line[c]=='\'') {
			inquote=!inquote;
			if (first_quote==-1)
				first_quote=c;
		}
		c--;
	}

	String prefix;

	bool pre_keyword=false;
	bool cancel=false;

	if (!inquote && first_quote==cofs-1) {

		cancel=true;

	} if (inquote && first_quote!=-1) {

		prefix=p_line.substr(first_quote,cofs-first_quote);

	} else if (cofs>0 && p_line[cofs-1]==' ') {
		int kofs=cofs-1;
		String kw;
		while (kofs>=0 && p_line[kofs]==' ')
			kofs--;

		while(kofs>=0 && p_line[kofs]>32 && _is_completable(p_line[kofs])) {
			kw=String::chr(p_line[kofs])+kw;
			kofs--;
		}

		pre_keyword=type_keywords.find(kw) || language_keywords.find(kw);

	} else {

		while(cofs>0 && p_line[cofs-1]>32 && _is_completable(p_line[cofs-1])) {
			prefix=String::chr(p_line[cofs-1])+prefix;
			if (p_line[cofs-1]=='\'' || p_line[cofs-1]=='"')
				break;

			cofs--;
		}
	}

	if (cancel || (!pre_keyword && prefix=="" && (cofs==0 || !completion_prefixes.has(String::chr(p_line[cofs-1])))))
		return String();

	for (const List<String>::Element *E=p_options.front();E;E=E->next()) {
		if (E->get().begins_with(prefix)) {
			r_suggestions.push_back(E->get());
		}
	}

	return prefix;
}

CodeCompletionService::CodeCompletionService() {

	completion_prefixes.insert(".");
	completion_prefixes.insert(",");
	completion_prefixes.insert("(");

	type_keywords.push_back("Vector2");
	type_keywords.push_back("Vector3");
	type_keywords.push_back("Plane");
	type_keywords.push_back("Quat");
	type_keywords.push_back("AABB");
	type_keywords.push_back("Matrix3");
	type_keywords.push_back("Transform");
	type_keywords.push_back("Color");
	type_keywords.push_back("Image");
	type_keywords.push_back("InputEvent");

	ObjectTypeDB::get_type_list(&type_keywords);

	#ifdef GDSCRIPT_ENABLED
	GDScriptLanguage::get_singleton()->get_reserved_words(&language_keywords);
	#endif
}

CodeCompletionService::~CodeCompletionService() {
}
<commit_msg>Fix wrong return<commit_after>/* code_completion_service.cpp */

#include "code_completion_service.h"
#include "io/resource_loader.h"
#include "globals.h"

#ifdef GDSCRIPT_ENABLED
#include "modules/gdscript/gd_script.h"
#endif

static bool _is_symbol(CharType c) {

	return c!='_' && ((c>='!' && c<='/') || (c>=':' && c<='@') || (c>='[' && c<='`') || (c>='{' && c<='~') || c=='\t');
}

static bool _is_completable(CharType c) {

	return !_is_symbol(c) || c=='"' || c=='\'';
}

CodeCompletionService::Result CodeCompletionService::obtain_suggestions(const Request& p_request) {

	#ifdef GDSCRIPT_ENABLED
	Result result(true);

	String path = Globals::get_singleton()->localize_path(p_request.script_path);

	if (path == "res://" || !path.begins_with("res://"))
		return Result();

	Ref<Script> script = ResourceLoader::load(path);

	if (!script.is_valid() || !script->cast_to<GDScript>())
		return Result();

	String script_text = p_request.script_text;

	if (script_text.empty()) {
		ERR_FAIL_COND_V(!script->has_source_code(), Result());
		script_text = script->get_source_code();
	}

	Node *base = get_tree()->get_edited_scene_root();
	if (base) {
		base = _find_node_for_script(base,base,script);
	}

	String current_line = _get_text_for_completion(p_request, script_text);

	List<String> options;
	script->get_language()->complete_code(script_text, script->get_path().get_base_dir(), base, &options, result.hint);

	if (options.size() > 0) {
		result.prefix = _filter_completion_candidates(p_request.column, current_line, options, result.suggestions);
	}

	return result;
	#else
	return Result();
	#endif
}

String CodeCompletionService::_get_text_for_completion(const Request& p_request, String& r_text) {

	Vector<String> substrings = r_text.replace("\r","").split("\n");
	r_text.clear();

	int len = substrings.size();

	for (int i=0;i<len;i++) {
		if (i==p_request.row) {
			r_text+=substrings[i].substr(0,p_request.column);
			r_text+=String::chr(0xFFFF); //not unicode, represents the cursor
			r_text+=substrings[i].substr(p_request.column,substrings[i].size());
		} else {
			r_text+=substrings[i];
		}

		if (i!=len-1)
			r_text+="\n";
	}

	return substrings[p_request.row];
}

Node* CodeCompletionService::_find_node_for_script(Node* p_base, Node* p_current, const Ref<Script>& p_script) {

	if (p_current->get_owner()!=p_base && p_base!=p_current)
		return NULL;
	Ref<Script> c = p_current->get_script();
	if (c==p_script)
		return p_current;
	for(int i=0;i<p_current->get_child_count();i++) {
		Node *found = _find_node_for_script(p_base,p_current->get_child(i),p_script);
		if (found)
			return found;
	}

	return NULL;
}

String CodeCompletionService::_filter_completion_candidates(int p_col, const String& p_line, const List<String>& p_options, Vector<String> &r_suggestions) {

	int cofs = CLAMP(p_col,0,p_line.length());

	//look for keywords first

	bool inquote=false;
	int first_quote=-1;

	int c=cofs-1;
	while(c>=0) {
		if (p_line[c]=='"' || p_line[c]=='\'') {
			inquote=!inquote;
			if (first_quote==-1)
				first_quote=c;
		}
		c--;
	}

	String prefix;

	bool pre_keyword=false;
	bool cancel=false;

	if (!inquote && first_quote==cofs-1) {

		cancel=true;

	} if (inquote && first_quote!=-1) {

		prefix=p_line.substr(first_quote,cofs-first_quote);

	} else if (cofs>0 && p_line[cofs-1]==' ') {
		int kofs=cofs-1;
		String kw;
		while (kofs>=0 && p_line[kofs]==' ')
			kofs--;

		while(kofs>=0 && p_line[kofs]>32 && _is_completable(p_line[kofs])) {
			kw=String::chr(p_line[kofs])+kw;
			kofs--;
		}

		pre_keyword=type_keywords.find(kw) || language_keywords.find(kw);

	} else {

		while(cofs>0 && p_line[cofs-1]>32 && _is_completable(p_line[cofs-1])) {
			prefix=String::chr(p_line[cofs-1])+prefix;
			if (p_line[cofs-1]=='\'' || p_line[cofs-1]=='"')
				break;

			cofs--;
		}
	}

	if (cancel || (!pre_keyword && prefix=="" && (cofs==0 || !completion_prefixes.has(String::chr(p_line[cofs-1])))))
		return String();

	for (const List<String>::Element *E=p_options.front();E;E=E->next()) {
		if (E->get().begins_with(prefix)) {
			r_suggestions.push_back(E->get());
		}
	}

	return prefix;
}

CodeCompletionService::CodeCompletionService() {

	completion_prefixes.insert(".");
	completion_prefixes.insert(",");
	completion_prefixes.insert("(");

	type_keywords.push_back("Vector2");
	type_keywords.push_back("Vector3");
	type_keywords.push_back("Plane");
	type_keywords.push_back("Quat");
	type_keywords.push_back("AABB");
	type_keywords.push_back("Matrix3");
	type_keywords.push_back("Transform");
	type_keywords.push_back("Color");
	type_keywords.push_back("Image");
	type_keywords.push_back("InputEvent");

	ObjectTypeDB::get_type_list(&type_keywords);

	#ifdef GDSCRIPT_ENABLED
	GDScriptLanguage::get_singleton()->get_reserved_words(&language_keywords);
	#endif
}

CodeCompletionService::~CodeCompletionService() {
}
<|endoftext|>


<commit_before>// you can use includes, for example:
#include <algorithm>

// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;

int findMin(vector<int> &P) {
    int minP(P[0]);
    for(unsigned int i=0; i<P.size(); ++i) {
        if( P[i]<minP )
            minP = P[i];
    }
    return minP;
}

int findMax(vector<int> &Q) {
    int maxQ(Q[0]);
    for(unsigned int i=0; i<Q.size(); ++i) {
        if( Q[i]>maxQ )
            maxQ = Q[i];
    }
    return maxQ;
}

bool isPrime(int number) {
    int a = floor(sqrt(number));
    for(unsigned int i=a; i>1; --i) {
        if( number%i==0 )
            return false;
    }
    return true;
}

vector<int> findPrimes(int first, int last) {
    vector<int> primes;
    for(unsigned int i=first; i<=last; ++i) {
        if( isPrime(i) ) {
            primes.push_back(i);
            // cout << i << endl;
        }
    }
    return primes;
}

vector<int> findSemiPrimes(vector<int> &primes, int first, int last) {
    vector<int> semiPrimes;
    for(unsigned int i=0; i<primes.size(); ++i) {
        for(unsigned int j=0; j<primes.size(); ++j) {
            if( primes[i]<=primes[j] ) {
                int semiPrime = primes[i]*primes[j];
                if( semiPrime>=first && semiPrime<=last ) {
                    semiPrimes.push_back( semiPrime );
                    // cout << semiPrime << endl;
                }
            }
        }
    }
    return semiPrimes;
}

int countSemiPrimes(vector<int> &semiPrimes, int first, int last) {
    int count(0);
    for(unsigned int i=0; i<semiPrimes.size(); ++i) {
        // cout << semiPrimes[i] << endl;
        if( semiPrimes[i]>=first && semiPrimes[i]<=last )
            count++;
    }
    return count;
}

vector<int> solution(int N, vector<int> &P, vector<int> &Q) {
    // write your code in C++11
    int minP = findMin(P);
    int maxQ = findMax(Q);
    // cout << minP << " " << maxQ << endl;

    vector<int> primes = findPrimes(2,maxQ);
    // cout << endl;
    vector<int> semiPrimes = findSemiPrimes(primes,minP,maxQ);

    vector<int> counts(P.size(),0);
    for(unsigned int i=0; i<P.size(); ++i) {
        counts[i] = countSemiPrimes(semiPrimes,P[i],Q[i]);
    }

    return counts;
}
<commit_msg>Update solution.cpp<commit_after>// you can use includes, for example:
#include <algorithm>

// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;

// Correctness 100%
// Performance 20%
// Task score 55%
// Detected time complexity:
// O(M * N ** (3/2)) or O(N * log(log(N)) + M * N) or O(M * N**3)

int findMin(vector<int> &P) {
    int minP(P[0]);
    for(unsigned int i=0; i<P.size(); ++i) {
        if( P[i]<minP )
            minP = P[i];
    }
    return minP;
}

int findMax(vector<int> &Q) {
    int maxQ(Q[0]);
    for(unsigned int i=0; i<Q.size(); ++i) {
        if( Q[i]>maxQ )
            maxQ = Q[i];
    }
    return maxQ;
}

bool isPrime(int number) {
    int a = floor(sqrt(number));
    for(unsigned int i=a; i>1; --i) {
        if( number%i==0 )
            return false;
    }
    return true;
}

vector<int> findPrimes(int first, int last) {
    vector<int> primes;
    for(unsigned int i=first; i<=last; ++i) {
        if( isPrime(i) ) {
            primes.push_back(i);
            // cout << i << endl;
        }
    }
    return primes;
}

vector<int> findSemiPrimes(vector<int> &primes, int first, int last) {
    vector<int> semiPrimes;
    for(unsigned int i=0; i<primes.size(); ++i) {
        for(unsigned int j=0; j<primes.size(); ++j) {
            if( primes[i]<=primes[j] ) {
                int semiPrime = primes[i]*primes[j];
                if( semiPrime>=first && semiPrime<=last ) {
                    semiPrimes.push_back( semiPrime );
                    // cout << semiPrime << endl;
                }
            }
        }
    }
    return semiPrimes;
}

int countSemiPrimes(vector<int> &semiPrimes, int first, int last) {
    int count(0);
    for(unsigned int i=0; i<semiPrimes.size(); ++i) {
        // cout << semiPrimes[i] << endl;
        if( semiPrimes[i]>=first && semiPrimes[i]<=last )
            count++;
    }
    return count;
}

vector<int> solution(int N, vector<int> &P, vector<int> &Q) {
    // write your code in C++11
    int minP = findMin(P);
    int maxQ = findMax(Q);
    // cout << minP << " " << maxQ << endl;

    vector<int> primes = findPrimes(2,maxQ);
    // cout << endl;
    vector<int> semiPrimes = findSemiPrimes(primes,minP,maxQ);

    vector<int> counts(P.size(),0);
    for(unsigned int i=0; i<P.size(); ++i) {
        counts[i] = countSemiPrimes(semiPrimes,P[i],Q[i]);
    }

    return counts;
}
<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2015.  All rights reserved
 */
#ifndef _Stroika_Foundation_Streams_OutputStream_inl_
#define _Stroika_Foundation_Streams_OutputStream_inl_  1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */
#include    <mutex>

#include    "../Debug/Assertions.h"
#include    "../Memory/BLOB.h"

namespace   Stroika {
    namespace   Foundation {
        namespace   Streams {

            /*
             ********************************************************************************
             **************************** OutputStream<ELEMENT_TYPE> ************************
             ********************************************************************************
             */
            template    <typename ELEMENT_TYPE>
            inline  OutputStream<ELEMENT_TYPE>::OutputStream (const _SharedIRep& rep)
                : inherited (rep)
            {
            }
            template    <typename ELEMENT_TYPE>
            inline  OutputStream<ELEMENT_TYPE>::OutputStream (nullptr_t)
                : inherited (nullptr)
            {
            }
            template    <typename ELEMENT_TYPE>
            inline  auto    OutputStream<ELEMENT_TYPE>::_GetRep () const -> _SharedIRep
            {
                return dynamic_pointer_cast<_IRep> (inherited::_GetRep ());
            }
            template    <typename ELEMENT_TYPE>
            inline  OutputStream<ELEMENT_TYPE>  OutputStream<ELEMENT_TYPE>::Synchronized () const
            {
                struct   SyncRep_ : public OutputStream<ELEMENT_TYPE>::_IRep {
                public:
                    SyncRep_ (const OutputStream<ELEMENT_TYPE>& realIn)
                        : OutputStream<ELEMENT_TYPE>::_IRep ()
                        , fCriticalSection_ ()
                        , fRealIn_ (realIn)
                    {
                    }
                    virtual bool    IsSeekable () const override
                    {
                        using   Execution::make_unique_lock;
                        // @todo implement 'offset' support
#if     qCompilerAndStdLib_make_unique_lock_IsSlow
                        MACRO_LOCK_GUARD_CONTEXT (fCriticalSection_);
#else
                        auto    critSec { make_unique_lock (fCriticalSection_) };
#endif
                        return fRealIn_.IsSeekable ();
                    }
                    virtual SeekOffsetType  GetWriteOffset () const override
                    {
                        using   Execution::make_unique_lock;
                        // @todo implement 'offset' support
#if     qCompilerAndStdLib_make_unique_lock_IsSlow
                        MACRO_LOCK_GUARD_CONTEXT (fCriticalSection_);
#else
                        auto    critSec { make_unique_lock (fCriticalSection_) };
#endif
                        return fRealIn_.GetWriteOffset ();
                    }
                    virtual SeekOffsetType  SeekWrite (Whence whence, SignedSeekOffsetType offset) override
                    {
                        using   Execution::make_unique_lock;
                        // @todo implement 'offset' support
#if     qCompilerAndStdLib_make_unique_lock_IsSlow
                        MACRO_LOCK_GUARD_CONTEXT (fCriticalSection_);
#else
                        auto    critSec { make_unique_lock (fCriticalSection_) };
#endif
                        return fRealIn_.SeekWrite (whence, offset);
                    }
                    virtual size_t  Write (ELEMENT_TYPE* intoStart, ELEMENT_TYPE* intoEnd) override
                    {
                        using   Execution::make_unique_lock;
                        // @todo implement 'offset' support
#if     qCompilerAndStdLib_make_unique_lock_IsSlow
                        MACRO_LOCK_GUARD_CONTEXT (fCriticalSection_);
#else
                        auto    critSec { make_unique_lock (fCriticalSection_) };
#endif
                        return fRealIn_.Write (intoStart, intoEnd);
                    }

                private:
                    mutable mutex               fCriticalSection_;
                    OutputStream<ELEMENT_TYPE>  fRealIn_;
                };
                return OutputStream<ELEMENT_TYPE> (make_shared<SyncRep_> (*this));
            }
            template    <typename ELEMENT_TYPE>
            inline  SeekOffsetType  OutputStream<ELEMENT_TYPE>::GetOffset () const
            {
                return _GetRep ()->GetWriteOffset ();
            }
            template    <typename ELEMENT_TYPE>
            SeekOffsetType  OutputStream<ELEMENT_TYPE>::GetOffsetToEndOfStream () const
            {
                SeekOffsetType  savedReadFrom = GetOffset ();
                SeekOffsetType  size =  Seek (Whence::eFromEnd, 0);
                Seek (Whence::eFromStart, savedReadFrom);
                Assert (size >= savedReadFrom);
                size -= savedReadFrom;
                return size;
            }
            template    <typename ELEMENT_TYPE>
            inline  SeekOffsetType    OutputStream<ELEMENT_TYPE>::Seek (SignedSeekOffsetType offset) const
            {
                return _GetRep ()->SeekWrite (Whence::eFromStart, offset);
            }
            template    <typename ELEMENT_TYPE>
            inline  SeekOffsetType    OutputStream<ELEMENT_TYPE>::Seek (Whence whence, SignedSeekOffsetType offset) const
            {
                return _GetRep ()->SeekWrite (whence, offset);
            }
            template    <typename ELEMENT_TYPE>
            inline  void    OutputStream<ELEMENT_TYPE>::Write (const ElementType* start, const ElementType* end) const
            {
                Require (start <= end);
                Require (start != nullptr or start == end);
                Require (end != nullptr or start == end);
                if (start != end) {
                    _GetRep ()->Write (start, end);
                }
            }
            template    <typename ELEMENT_TYPE>
            template    <typename TEST_TYPE, typename ENABLE_IF_TEST>
            inline  void    OutputStream<ELEMENT_TYPE>::Write (const Memory::BLOB& blob) const
            {
                Write (blob.begin (), blob.end ());
            }
            template    <typename ELEMENT_TYPE>
            template    <typename TEST_TYPE, typename ENABLE_IF_TEST>
            inline  void    OutputStream<ELEMENT_TYPE>::Write (const wchar_t* cStr) const
            {
                Write (cStr, cStr + ::wcslen (cStr));
            }
            template    <typename ELEMENT_TYPE>
            inline  void    OutputStream<ELEMENT_TYPE>::Flush () const
            {
                _GetRep ()->Flush ();
            }
            template    <>
            template    <>
            inline  const OutputStream<Characters::Character>& OutputStream<Characters::Character>::operator<< (const Characters::String& write2TextStream) const
            {
                Write (write2TextStream);
                return *this;
            }
            template    <>
            template    <>
            inline  const OutputStream<Characters::Character>& OutputStream<Characters::Character>::operator<< (const wchar_t* write2TextStream) const
            {
                Write (write2TextStream);
                return *this;
            }

        }
    }
}
#endif  /*_Stroika_Foundation_Streams_OutputStream_inl_*/
<commit_msg>#include String.h in Streams/OutputStream.inl to avoid gcc compile failure. Would be nice to detangle these dependencies more<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2015.  All rights reserved
 */
#ifndef _Stroika_Foundation_Streams_OutputStream_inl_
#define _Stroika_Foundation_Streams_OutputStream_inl_  1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */
#include    <mutex>

#include    "../Characters/String.h"
#include    "../Debug/Assertions.h"
#include    "../Memory/BLOB.h"

namespace   Stroika {
    namespace   Foundation {
        namespace   Streams {

            /*
             ********************************************************************************
             **************************** OutputStream<ELEMENT_TYPE> ************************
             ********************************************************************************
             */
            template    <typename ELEMENT_TYPE>
            inline  OutputStream<ELEMENT_TYPE>::OutputStream (const _SharedIRep& rep)
                : inherited (rep)
            {
            }
            template    <typename ELEMENT_TYPE>
            inline  OutputStream<ELEMENT_TYPE>::OutputStream (nullptr_t)
                : inherited (nullptr)
            {
            }
            template    <typename ELEMENT_TYPE>
            inline  auto    OutputStream<ELEMENT_TYPE>::_GetRep () const -> _SharedIRep
            {
                return dynamic_pointer_cast<_IRep> (inherited::_GetRep ());
            }
            template    <typename ELEMENT_TYPE>
            inline  OutputStream<ELEMENT_TYPE>  OutputStream<ELEMENT_TYPE>::Synchronized () const
            {
                struct   SyncRep_ : public OutputStream<ELEMENT_TYPE>::_IRep {
                public:
                    SyncRep_ (const OutputStream<ELEMENT_TYPE>& realIn)
                        : OutputStream<ELEMENT_TYPE>::_IRep ()
                        , fCriticalSection_ ()
                        , fRealIn_ (realIn)
                    {
                    }
                    virtual bool    IsSeekable () const override
                    {
                        using   Execution::make_unique_lock;
                        // @todo implement 'offset' support
#if     qCompilerAndStdLib_make_unique_lock_IsSlow
                        MACRO_LOCK_GUARD_CONTEXT (fCriticalSection_);
#else
                        auto    critSec { make_unique_lock (fCriticalSection_) };
#endif
                        return fRealIn_.IsSeekable ();
                    }
                    virtual SeekOffsetType  GetWriteOffset () const override
                    {
                        using   Execution::make_unique_lock;
                        // @todo implement 'offset' support
#if     qCompilerAndStdLib_make_unique_lock_IsSlow
                        MACRO_LOCK_GUARD_CONTEXT (fCriticalSection_);
#else
                        auto    critSec { make_unique_lock (fCriticalSection_) };
#endif
                        return fRealIn_.GetWriteOffset ();
                    }
                    virtual SeekOffsetType  SeekWrite (Whence whence, SignedSeekOffsetType offset) override
                    {
                        using   Execution::make_unique_lock;
                        // @todo implement 'offset' support
#if     qCompilerAndStdLib_make_unique_lock_IsSlow
                        MACRO_LOCK_GUARD_CONTEXT (fCriticalSection_);
#else
                        auto    critSec { make_unique_lock (fCriticalSection_) };
#endif
                        return fRealIn_.SeekWrite (whence, offset);
                    }
                    virtual size_t  Write (ELEMENT_TYPE* intoStart, ELEMENT_TYPE* intoEnd) override
                    {
                        using   Execution::make_unique_lock;
                        // @todo implement 'offset' support
#if     qCompilerAndStdLib_make_unique_lock_IsSlow
                        MACRO_LOCK_GUARD_CONTEXT (fCriticalSection_);
#else
                        auto    critSec { make_unique_lock (fCriticalSection_) };
#endif
                        return fRealIn_.Write (intoStart, intoEnd);
                    }

                private:
                    mutable mutex               fCriticalSection_;
                    OutputStream<ELEMENT_TYPE>  fRealIn_;
                };
                return OutputStream<ELEMENT_TYPE> (make_shared<SyncRep_> (*this));
            }
            template    <typename ELEMENT_TYPE>
            inline  SeekOffsetType  OutputStream<ELEMENT_TYPE>::GetOffset () const
            {
                return _GetRep ()->GetWriteOffset ();
            }
            template    <typename ELEMENT_TYPE>
            SeekOffsetType  OutputStream<ELEMENT_TYPE>::GetOffsetToEndOfStream () const
            {
                SeekOffsetType  savedReadFrom = GetOffset ();
                SeekOffsetType  size =  Seek (Whence::eFromEnd, 0);
                Seek (Whence::eFromStart, savedReadFrom);
                Assert (size >= savedReadFrom);
                size -= savedReadFrom;
                return size;
            }
            template    <typename ELEMENT_TYPE>
            inline  SeekOffsetType    OutputStream<ELEMENT_TYPE>::Seek (SignedSeekOffsetType offset) const
            {
                return _GetRep ()->SeekWrite (Whence::eFromStart, offset);
            }
            template    <typename ELEMENT_TYPE>
            inline  SeekOffsetType    OutputStream<ELEMENT_TYPE>::Seek (Whence whence, SignedSeekOffsetType offset) const
            {
                return _GetRep ()->SeekWrite (whence, offset);
            }
            template    <typename ELEMENT_TYPE>
            inline  void    OutputStream<ELEMENT_TYPE>::Write (const ElementType* start, const ElementType* end) const
            {
                Require (start <= end);
                Require (start != nullptr or start == end);
                Require (end != nullptr or start == end);
                if (start != end) {
                    _GetRep ()->Write (start, end);
                }
            }
            template    <typename ELEMENT_TYPE>
            template    <typename TEST_TYPE, typename ENABLE_IF_TEST>
            inline  void    OutputStream<ELEMENT_TYPE>::Write (const Memory::BLOB& blob) const
            {
                Write (blob.begin (), blob.end ());
            }
            template    <typename ELEMENT_TYPE>
            template    <typename TEST_TYPE, typename ENABLE_IF_TEST>
            inline  void    OutputStream<ELEMENT_TYPE>::Write (const wchar_t* cStr) const
            {
                Write (cStr, cStr + ::wcslen (cStr));
            }
            template    <typename ELEMENT_TYPE>
            inline  void    OutputStream<ELEMENT_TYPE>::Flush () const
            {
                _GetRep ()->Flush ();
            }
            template    <>
            template    <>
            inline  const OutputStream<Characters::Character>& OutputStream<Characters::Character>::operator<< (const Characters::String& write2TextStream) const
            {
                Write (write2TextStream);
                return *this;
            }
            template    <>
            template    <>
            inline  const OutputStream<Characters::Character>& OutputStream<Characters::Character>::operator<< (const wchar_t* write2TextStream) const
            {
                Write (write2TextStream);
                return *this;
            }

        }
    }
}
#endif  /*_Stroika_Foundation_Streams_OutputStream_inl_*/
<|endoftext|>


<commit_before>#include <tiramisu/tiramisu.h>

#include <string.h>

#include "baryon_wrapper.h"

using namespace tiramisu;

/* Implementation log:
    - Sum: 7h 35mn.
 */

/*
 * The goal is to generate code that implements the reference.
 * baryon_ref.cpp
 */
void generate_function(std::string name)
{
    tiramisu::init(name);

    var n("n", 0, Nsrc),
	iCprime("iCprime", 0, Nc),
	iSprime("iSprime", 0, Ns),
	jCprime("jCprime", 0, Nc),
	jSprime("jSprime", 0, Ns),
	kCprime("kCprime", 0, Nc),
	kSprime("kSprime", 0, Ns),
	lCprime("lCprime", 0, Nc),
	lSprime("lSprime", 0, Ns),
	x("x", 0, Vsnk),
	x2("x2", 0, Vsnk),
	t("t", 0, Lt),
	wnum("wnum", 0, Nw),
	y("y", 0, Vsrc),
	tri("tri", 0, Nq);

    input Blocal_r("Blocal_r", {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t}, p_float64);
    input Blocal_i("Blocal_i", {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t}, p_float64);
    input   prop_r("prop_r",   {tri, iCprime, iSprime, jCprime, jSprime, x, t, y}, p_float64);
    input   prop_i("prop_i",   {tri, iCprime, iSprime, jCprime, jSprime, x, t, y}, p_float64);
    input  weights("weights",  {wnum}, p_float64);
    input    psi_r("psi_r",    {n, y}, p_float64);
    input    psi_i("psi_i",    {n, y}, p_float64);
    input    color_weights("color_weights",    {wnum, tri}, p_int32);
    input    spin_weights("spin_weights",    {wnum, tri}, p_int32);

    computation Blocal_r_init("Blocal_r_init", {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t}, expr((double) 0));
    computation Blocal_i_init("Blocal_i_init", {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t}, expr((double) 0));

    computation iC("iC", {wnum}, color_weights(wnum, 0));
    computation iS("iS", {wnum}, spin_weights(wnum, 0));
    computation jC("jC", {wnum}, color_weights(wnum, 1));
    computation jS("jS", {wnum}, spin_weights(wnum, 1));
    computation kC("kC", {wnum}, color_weights(wnum, 2));
    computation kS("kS", {wnum}, spin_weights(wnum, 2));

    computation Blocal_r_update("Blocal_r_update", {wnum, n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t, y}, p_float64);
    Blocal_r_update.set_expression(Blocal_r_init(n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t) + weights(wnum) * psi_r(n, y) * (prop_r(0, iCprime, iSprime, iC(wnum), iS(wnum), x, t, y) * prop_r(2, kCprime, kSprime, kC(wnum), kS(wnum), x, t, y) - prop_r(0, kCprime, kSprime, iC(wnum), iS(wnum), x, t, y) * prop_r(2, iCprime, iSprime, kC(wnum), kS(wnum), x, t, y)) * prop_r(1, jCprime, jSprime, jC(wnum), jS(wnum), x, t, y));

    computation Blocal_i_update("Blocal_i_update", {wnum, n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t, y}, p_float64);
    Blocal_i_update.set_expression(Blocal_i_init(n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t) + weights(wnum) * psi_i(n, y) * (prop_i(0, iCprime, iSprime, iC(wnum), iS(wnum), x, t, y) * prop_i(2, kCprime, kSprime, kC(wnum), kS(wnum), x, t, y) - prop_i(0, kCprime, kSprime, iC(wnum), iS(wnum), x, t, y) * prop_i(2, iCprime, iSprime, kC(wnum), kS(wnum), x, t, y)) * prop_i(1, jCprime, jSprime, jC(wnum), jS(wnum), x, t, y));

    computation Q_r_init("Q_r_init", {n, iCprime, iSprime, kCprime, kSprime, jCprime, jSprime, x, t, y}, expr((double) 0));
    computation Q_i_init("Q_i_init", {n, iCprime, iSprime, kCprime, kSprime, jCprime, jSprime, x, t, y}, expr((double) 0));

    computation Bsingle_r_init("Bsingle_r_init", {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, x2, t}, expr((double) 0));
    computation Bsingle_i_init("Bsingle_i_init", {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, x2, t}, expr((double) 0));

    computation iC2("iC2", {wnum}, color_weights(wnum, 0));
    computation iS2("iS2", {wnum}, spin_weights(wnum, 0));
    computation jC2("jC2", {wnum}, color_weights(wnum, 1));
    computation jS2("jS2", {wnum}, spin_weights(wnum, 1));
    computation kC2("kC2", {wnum}, color_weights(wnum, 2));
    computation kS2("kS2", {wnum}, spin_weights(wnum, 2));

    computation Q_r_update("Q_r_update", {wnum, n, iCprime, iSprime, kCprime, kSprime, jCprime, jSprime, x, t, y},
			Q_r_init(n, iCprime, iSprime, kCprime, kSprime, jCprime, jSprime, x, t, y) + weights(wnum));
			//* psi_r(n, y) * (prop_r(0, iCprime, iSprime, iC2(wnum), iS2(wnum), x, t, y) * prop_r(2, kCprime, kSprime, kC2(wnum), kS2(wnum), x, t, y) - prop_r(0, kCprime, kSprime, iC2(wnum), iS2(wnum), x, t, y) * prop_r(2, iCprime, iSprime, kC2(wnum), kS2(wnum), x, t, y))));
    Q_r_update.add_predicate((jCprime == jC2(wnum)) && (jSprime == jS2(wnum)));

    computation Q_i_update("Q_i_update", {wnum, n, iCprime, iSprime, kCprime, kSprime, jCprime, jSprime, x, t, y},
			Q_i_init(n, iCprime, iSprime, kCprime, kSprime, jC2(wnum), jS2(wnum), x, t, y) + weights(wnum));
		        //* psi_i(n, y) * (prop_i(0, iCprime, iSprime, iC2(wnum), iS2(wnum), x, t, y) * prop_i(2, kCprime, kSprime, kC2(wnum), kS2(wnum), x, t, y) - prop_i(0, kCprime, kSprime, iC2(wnum), iS2(wnum), x, t, y) * prop_i(2, iCprime, iSprime, kC2(wnum), kS2(wnum), x, t, y)));

    computation Bsingle_r_update("Bsingle_r_update", {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, lCprime, lSprime, x, x2, t, y},
	    Bsingle_r_init(n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, x2, t) + Q_r_update(0, n, iCprime, iSprime, kCprime, kSprime, lCprime, lSprime, x, t, y));
            // * prop_r(1, jCprime, jSprime, lCprime, lSprime, x2, t, y));

    computation Bsingle_i_update("Bsingle_i_update", {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, lCprime, lSprime, x, x2, t, y},
	    Bsingle_i_init(n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, x2, t) + Q_i_update(0, n, iCprime, iSprime, kCprime, kSprime, lCprime, lSprime, x, t, y));
	    // * prop_i(1, jCprime, jSprime, lCprime, lSprime, x2, t, y));

    // -------------------------------------------------------
    // Layer II
    // -------------------------------------------------------
    Blocal_r_init.then(Blocal_i_init, t)
		 .then(Q_r_init, computation::root)
		 .then(Q_i_init, y)
		 .then(Bsingle_r_init, computation::root)
		 .then(Bsingle_i_init, t)
	         .then(iC, computation::root)
		 .then(iS, wnum)
		 .then(jC, wnum)
		 .then(jS, wnum)
		 .then(kC, wnum)
		 .then(kS, wnum)
		 .then(Blocal_r_update, wnum)
		 .then(Blocal_i_update, y)
	         .then(iC2, computation::root)
		 .then(iS2, wnum)
		 .then(jC2, wnum)
		 .then(jS2, wnum)
		 .then(kC2, wnum)
		 .then(kS2, wnum)
		 .then(Q_r_update, wnum)
		 .then(Q_i_update, y)
		 .then(Bsingle_r_update, computation::root)
		 .then(Bsingle_i_update, y);

    //Blocal_r_update.tag_parallel_level(n);
    Blocal_r_update.vectorize(t, Lt);
    //Blocal_r_update.unroll(y, Vsrc);
    //Blocal_r_update.unroll(x, Vsnk);

    // -------------------------------------------------------
    // Layer III
    // -------------------------------------------------------
    buffer buf_Blocal_r("buf_Blocal_r", {Nsrc, Nc, Ns, Nc, Ns, Nc, Ns, Vsnk, Lt}, p_float64, a_output);
    buffer buf_Blocal_i("buf_Blocal_i", {Nsrc, Nc, Ns, Nc, Ns, Nc, Ns, Vsnk, Lt}, p_float64, a_output);
    buffer buf_Q_r("buf_Q_r", {Nsrc, Nc, Ns, Nc, Ns, Nc, Ns, Vsnk, Lt, Vsnk}, p_float64, a_temporary);
    buffer buf_Q_i("buf_Q_i", {Nsrc, Nc, Ns, Nc, Ns, Nc, Ns, Vsnk, Lt, Vsnk}, p_float64, a_temporary);
    buffer buf_Bsingle_r("buf_Bsingle_r", {Nsrc, Nc, Ns, Nc, Ns, Nc, Ns, Vsnk, Vsnk, Lt}, p_float64, a_output);
    buffer buf_Bsingle_i("buf_Bsingle_i", {Nsrc, Nc, Ns, Nc, Ns, Nc, Ns, Vsnk, Vsnk, Lt}, p_float64, a_output);

    Blocal_r.store_in(&buf_Blocal_r);
    Blocal_i.store_in(&buf_Blocal_i);
    Blocal_r_init.store_in(&buf_Blocal_r);
    Blocal_i_init.store_in(&buf_Blocal_i);
    Blocal_r_update.store_in(&buf_Blocal_r, {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t});
    Blocal_i_update.store_in(&buf_Blocal_i, {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t});

    Q_r_init.store_in(&buf_Q_r);
    Q_i_init.store_in(&buf_Q_i);

    Q_r_update.store_in(&buf_Q_r, {n, iCprime, iSprime, kCprime, kSprime, jCprime, jSprime, x, t, y});
    Q_i_update.store_in(&buf_Q_i, {n, iCprime, iSprime, kCprime, kSprime, jCprime, jSprime, x, t, y});

    Bsingle_r_init.store_in(&buf_Bsingle_r);
    Bsingle_i_init.store_in(&buf_Bsingle_i);

    Bsingle_r_update.store_in(&buf_Bsingle_r, {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, x2, t});
    Bsingle_i_update.store_in(&buf_Bsingle_i, {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, x2, t});

    // -------------------------------------------------------
    // Code Generation
    // -------------------------------------------------------
    tiramisu::codegen({&buf_Blocal_r, &buf_Blocal_i, prop_r.get_buffer(), prop_i.get_buffer(), weights.get_buffer(), psi_r.get_buffer(), psi_i.get_buffer(), color_weights.get_buffer(), spin_weights.get_buffer(), Bsingle_r_update.get_buffer(), Bsingle_i_update.get_buffer()}, "generated_baryon.o");
}

int main(int argc, char **argv)
{
    generate_function("tiramisu_generated_code");

    return 0;
}
<commit_msg>dibaryon: add optimizations<commit_after>#include <tiramisu/tiramisu.h>

#include <string.h>

#include "baryon_wrapper.h"

using namespace tiramisu;

/*
 * The goal is to generate code that implements the reference.
 * baryon_ref.cpp
 */
void generate_function(std::string name)
{
    tiramisu::init(name);

    var n("n", 0, Nsrc),
	iCprime("iCprime", 0, Nc),
	iSprime("iSprime", 0, Ns),
	jCprime("jCprime", 0, Nc),
	jSprime("jSprime", 0, Ns),
	kCprime("kCprime", 0, Nc),
	kSprime("kSprime", 0, Ns),
	lCprime("lCprime", 0, Nc),
	lSprime("lSprime", 0, Ns),
	x("x", 0, Vsnk),
	x2("x2", 0, Vsnk),
	t("t", 0, Lt),
	wnum("wnum", 0, Nw),
	y("y", 0, Vsrc),
	tri("tri", 0, Nq);

    input Blocal_r("Blocal_r", {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t}, p_float64);
    input Blocal_i("Blocal_i", {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t}, p_float64);
    input   prop_r("prop_r",   {tri, iCprime, iSprime, jCprime, jSprime, x, t, y}, p_float64);
    input   prop_i("prop_i",   {tri, iCprime, iSprime, jCprime, jSprime, x, t, y}, p_float64);
    input  weights("weights",  {wnum}, p_float64);
    input    psi_r("psi_r",    {n, y}, p_float64);
    input    psi_i("psi_i",    {n, y}, p_float64);
    input    color_weights("color_weights",    {wnum, tri}, p_int32);
    input    spin_weights("spin_weights",    {wnum, tri}, p_int32);

    computation Blocal_r_init("Blocal_r_init", {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t}, expr((double) 0));
    computation Blocal_i_init("Blocal_i_init", {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t}, expr((double) 0));

    computation iC("iC", {wnum}, color_weights(wnum, 0));
    computation iS("iS", {wnum}, spin_weights(wnum, 0));
    computation jC("jC", {wnum}, color_weights(wnum, 1));
    computation jS("jS", {wnum}, spin_weights(wnum, 1));
    computation kC("kC", {wnum}, color_weights(wnum, 2));
    computation kS("kS", {wnum}, spin_weights(wnum, 2));

    computation Blocal_r_update("Blocal_r_update", {wnum, n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t, y}, p_float64);
    Blocal_r_update.set_expression(Blocal_r_init(n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t) + weights(wnum) * psi_r(n, y) * (prop_r(0, iCprime, iSprime, iC(wnum), iS(wnum), x, t, y) * prop_r(2, kCprime, kSprime, kC(wnum), kS(wnum), x, t, y) - prop_r(0, kCprime, kSprime, iC(wnum), iS(wnum), x, t, y) * prop_r(2, iCprime, iSprime, kC(wnum), kS(wnum), x, t, y)) * prop_r(1, jCprime, jSprime, jC(wnum), jS(wnum), x, t, y));

    computation Blocal_i_update("Blocal_i_update", {wnum, n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t, y}, p_float64);
    Blocal_i_update.set_expression(Blocal_i_init(n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t) + weights(wnum) * psi_i(n, y) * (prop_i(0, iCprime, iSprime, iC(wnum), iS(wnum), x, t, y) * prop_i(2, kCprime, kSprime, kC(wnum), kS(wnum), x, t, y) - prop_i(0, kCprime, kSprime, iC(wnum), iS(wnum), x, t, y) * prop_i(2, iCprime, iSprime, kC(wnum), kS(wnum), x, t, y)) * prop_i(1, jCprime, jSprime, jC(wnum), jS(wnum), x, t, y));

    computation Q_r_init("Q_r_init", {n, iCprime, iSprime, kCprime, kSprime, jCprime, jSprime, x, t, y}, expr((double) 0));
    computation Q_i_init("Q_i_init", {n, iCprime, iSprime, kCprime, kSprime, jCprime, jSprime, x, t, y}, expr((double) 0));

    computation Bsingle_r_init("Bsingle_r_init", {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, x2, t}, expr((double) 0));
    computation Bsingle_i_init("Bsingle_i_init", {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, x2, t}, expr((double) 0));

    computation iC2("iC2", {wnum}, color_weights(wnum, 0));
    computation iS2("iS2", {wnum}, spin_weights(wnum, 0));
    computation jC2("jC2", {wnum}, color_weights(wnum, 1));
    computation jS2("jS2", {wnum}, spin_weights(wnum, 1));
    computation kC2("kC2", {wnum}, color_weights(wnum, 2));
    computation kS2("kS2", {wnum}, spin_weights(wnum, 2));

    computation Q_r_update("Q_r_update", {wnum, n, iCprime, iSprime, kCprime, kSprime, jCprime, jSprime, x, t, y},
			Q_r_init(n, iCprime, iSprime, kCprime, kSprime, jCprime, jSprime, x, t, y) + weights(wnum));
			//* psi_r(n, y) * (prop_r(0, iCprime, iSprime, iC2(wnum), iS2(wnum), x, t, y) * prop_r(2, kCprime, kSprime, kC2(wnum), kS2(wnum), x, t, y) - prop_r(0, kCprime, kSprime, iC2(wnum), iS2(wnum), x, t, y) * prop_r(2, iCprime, iSprime, kC2(wnum), kS2(wnum), x, t, y))));
    Q_r_update.add_predicate((jCprime == jC2(wnum)) && (jSprime == jS2(wnum)));

    computation Q_i_update("Q_i_update", {wnum, n, iCprime, iSprime, kCprime, kSprime, jCprime, jSprime, x, t, y},
			Q_i_init(n, iCprime, iSprime, kCprime, kSprime, jC2(wnum), jS2(wnum), x, t, y) + weights(wnum));
		        //* psi_i(n, y) * (prop_i(0, iCprime, iSprime, iC2(wnum), iS2(wnum), x, t, y) * prop_i(2, kCprime, kSprime, kC2(wnum), kS2(wnum), x, t, y) - prop_i(0, kCprime, kSprime, iC2(wnum), iS2(wnum), x, t, y) * prop_i(2, iCprime, iSprime, kC2(wnum), kS2(wnum), x, t, y)));
    Q_i_update.add_predicate((jCprime == jC2(wnum)) && (jSprime == jS2(wnum)));

    computation Bsingle_r_update("Bsingle_r_update", {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, lCprime, lSprime, x, x2, t, y},
	    Bsingle_r_init(n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, x2, t) + Q_r_update(0, n, iCprime, iSprime, kCprime, kSprime, lCprime, lSprime, x, t, y));
            // * prop_r(1, jCprime, jSprime, lCprime, lSprime, x2, t, y));

    computation Bsingle_i_update("Bsingle_i_update", {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, lCprime, lSprime, x, x2, t, y},
	    Bsingle_i_init(n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, x2, t) + Q_i_update(0, n, iCprime, iSprime, kCprime, kSprime, lCprime, lSprime, x, t, y));
	    // * prop_i(1, jCprime, jSprime, lCprime, lSprime, x2, t, y));

    // -------------------------------------------------------
    // Layer II
    // -------------------------------------------------------
    Blocal_r_init.then(Blocal_i_init, t)
		 .then(Q_r_init, computation::root)
		 .then(Q_i_init, y)
		 .then(Bsingle_r_init, computation::root)
		 .then(Bsingle_i_init, t)
	         .then(iC, computation::root)
		 .then(iS, wnum)
		 .then(jC, wnum)
		 .then(jS, wnum)
		 .then(kC, wnum)
		 .then(kS, wnum)
		 .then(Blocal_r_update, wnum)
		 .then(Blocal_i_update, y)
	         .then(iC2, computation::root)
		 .then(iS2, wnum)
		 .then(jC2, wnum)
		 .then(jS2, wnum)
		 .then(kC2, wnum)
		 .then(kS2, wnum)
		 .then(Q_r_update, wnum)
		 .then(Q_i_update, y)
		 .then(Bsingle_r_update, computation::root)
		 .then(Bsingle_i_update, y);

    //Blocal_r_update.tag_parallel_level(n);
    Blocal_r_init.vectorize(t, Lt);
    Blocal_r_update.vectorize(t, Lt);
    //Blocal_r_update.unroll(y, Vsrc);
    //Blocal_r_update.unroll(x, Vsnk);

    Q_r_init.vectorize(y, Vsrc);

    Bsingle_r_init.vectorize(t, Lt);

    Q_r_update.vectorize(y, Vsrc);

    //Bsingle_r_update.tag_parallel_level(n);
    Bsingle_r_update.vectorize(t, Lt);

    // -------------------------------------------------------
    // Layer III
    // -------------------------------------------------------
    buffer buf_Blocal_r("buf_Blocal_r", {Nsrc, Nc, Ns, Nc, Ns, Nc, Ns, Vsnk, Lt}, p_float64, a_output);
    buffer buf_Blocal_i("buf_Blocal_i", {Nsrc, Nc, Ns, Nc, Ns, Nc, Ns, Vsnk, Lt}, p_float64, a_output);
    buffer buf_Q_r("buf_Q_r", {Nsrc, Nc, Ns, Nc, Ns, Nc, Ns, Vsnk, Lt, Vsnk}, p_float64, a_temporary);
    buffer buf_Q_i("buf_Q_i", {Nsrc, Nc, Ns, Nc, Ns, Nc, Ns, Vsnk, Lt, Vsnk}, p_float64, a_temporary);
    buffer buf_Bsingle_r("buf_Bsingle_r", {Nsrc, Nc, Ns, Nc, Ns, Nc, Ns, Vsnk, Vsnk, Lt}, p_float64, a_output);
    buffer buf_Bsingle_i("buf_Bsingle_i", {Nsrc, Nc, Ns, Nc, Ns, Nc, Ns, Vsnk, Vsnk, Lt}, p_float64, a_output);

    Blocal_r.store_in(&buf_Blocal_r);
    Blocal_i.store_in(&buf_Blocal_i);
    Blocal_r_init.store_in(&buf_Blocal_r);
    Blocal_i_init.store_in(&buf_Blocal_i);
    Blocal_r_update.store_in(&buf_Blocal_r, {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t});
    Blocal_i_update.store_in(&buf_Blocal_i, {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t});

    Q_r_init.store_in(&buf_Q_r);
    Q_i_init.store_in(&buf_Q_i);

    Q_r_update.store_in(&buf_Q_r, {n, iCprime, iSprime, kCprime, kSprime, jCprime, jSprime, x, t, y});
    Q_i_update.store_in(&buf_Q_i, {n, iCprime, iSprime, kCprime, kSprime, jCprime, jSprime, x, t, y});

    Bsingle_r_init.store_in(&buf_Bsingle_r);
    Bsingle_i_init.store_in(&buf_Bsingle_i);

    Bsingle_r_update.store_in(&buf_Bsingle_r, {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, x2, t});
    Bsingle_i_update.store_in(&buf_Bsingle_i, {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, x2, t});

    // -------------------------------------------------------
    // Code Generation
    // -------------------------------------------------------
    tiramisu::codegen({&buf_Blocal_r, &buf_Blocal_i, prop_r.get_buffer(), prop_i.get_buffer(), weights.get_buffer(), psi_r.get_buffer(), psi_i.get_buffer(), color_weights.get_buffer(), spin_weights.get_buffer(), Bsingle_r_update.get_buffer(), Bsingle_i_update.get_buffer()}, "generated_baryon.o");
}

int main(int argc, char **argv)
{
    generate_function("tiramisu_generated_code");

    return 0;
}
<|endoftext|>


<commit_before>#include "catch.hpp"
#include <type_traits>
#include <compile_time.hpp>
#include <string>

namespace myspace
{
REGISTER_TYPE_BEGIN()
REGISTER_TYPE(int)
REGISTER_TYPE(float)
REGISTER_TYPE(double)
REGISTER_TYPE_END()
}

TEST_CASE("", "")
{
}
<commit_msg>Add unit tests for the case of registering no types. 	modified:   tests/test_compile_time1.cpp<commit_after>#include "catch.hpp"
#include <type_traits>
#include <compile_time.hpp>
#include <string>

namespace refl_space_1
{
REGISTER_TYPE_BEGIN()
REGISTER_TYPE_END()
}

TEST_CASE("No types registered", "[REGISTER_TYPE]")
{
    constexpr auto range_len =
        metamusil::int_seq::length_v<refl_space_1::type_line_range>;

    constexpr auto compile_time_infos_len = metamusil::t_list::length_v<
        refl_space_1::instantiated_compile_time_infos>;

    constexpr auto type_len =
        metamusil::t_list::length_v<refl_space_1::type_universe>;

    REQUIRE(range_len == 0);
    REQUIRE(compile_time_infos_len == 0);
    REQUIRE(refl_space_1::type_name_array_holder::value == nullptr);
    REQUIRE(refl_space_1::type_info_array_holder::value == nullptr);
    REQUIRE(type_len == 0);
}
<|endoftext|>