text
stringlengths 54
60.6k
|
|---|
<commit_before>
#include <libclientserver.h>
Buffer::Buffer()
{
m_buffer_length = 8192;
m_chunk_size = 65535;
m_buffer_used = 0;
m_buffer = NULL;
m_max_size = 0;
}
Buffer::~Buffer()
{
free(m_buffer);
}
/**
* @Init
*
* One of the Init functions or overloads must be called before using any other function in the class
*/
int Buffer::Init()
{
m_buffer = (char *) malloc(m_buffer_length * sizeof(m_buffer));
if (!m_buffer)
return -ENOMEM;
return 0;
}
/**
* @Init
* @param[in] buflen This should be the initial size of memory allocated to the buffer
*
* One of the Init functions or overloads must be called before using any other function in the class
*/
int Buffer::Init(size_t buflen)
{
m_buffer_length = buflen;
return Init();
}
/**
* @Read
* @param[in] fd This should be the file descriptor to read from
*
* This function will attempt to read chunk size from the fd and populate the buffer contents with the data
* If the buffer is going to exceed the max size it will return -ENOMEM
* If the file has reached EOF -1 will be returned
* If there is an error reading from the fd the approiate error code will be returned to indicte what the problem was.
* In normal working cases without error's the length of the data read will be returned. This includes returning 0 if there was no data to read.
*/
int Buffer::Read(int fd)
{
if (GetFreeSpace() < m_chunk_size)
{
if (ReSize(m_buffer_length + m_chunk_size) == false)
{
return -ENOMEM;
}
}
int ret = read(fd, m_buffer + m_buffer_used, m_chunk_size);
if (ret < 0)
{
switch(errno)
{
case EAGAIN:
case EINTR:
return 0;
default:
return -errno;
}
}
if (ret == 0)
return -1;
m_buffer_used += ret;
return ret;
}
/**
* Write
* @param[in] fd The file descriptor to write to
*
* This function will attempt to write as much of the buffer as possible to the fd.
* If an error occurs it will will return the approate error code to indicate what the error was.
* If the function was able to write any data it will return the amount of data that was written to the fd
*/
int Buffer::Write(int fd)
{
if (m_buffer_used == 0)
return 0;
int ret = write(fd, m_buffer, m_buffer_used);
if (ret > 0)
{
Shift(ret);
return ret;
}
switch(errno)
{
case EAGAIN:
case EINTR:
return 0;
break;
default:
return -errno;
break;
}
return -1;
}
/**
* WriteBuffered
* @param[in] fd The file descriptor to write to
* @param[in] buf The data to write
* @param[in] length The amount of data to write from buf
*
* This functin will attempt to write as much data as it can to the file descriptor before it blocks.
* Once it starts blocking it will then write the remaining part of the data to the buffer which can be written by calling Write(fd) later
* If the initial write fails it will return the error that occured and will not attempt to write any data to either the fd or the buffer
* If the buffers required more memory it is posisble for this function to file is there is a maximum buffer limit set. In which case it will fail with -NOBUFS
* Under normal situations this function will always return the lgnth value passed
*/
int Buffer::WriteBuffered(int fd, const char *buf, size_t length)
{
int ret = write(fd, buf, length);
if (ret < 0)
{
switch(errno)
{
case EAGAIN:
case EINTR:
return PushData(buf, length);
default:
return -errno;
break;
}
}
size_t written = ret;
if (written == length)
return length;
//Not all of it went to the socket to buffer it and say success to the caller
ret = PushData(&buf[written], length - written);
if (ret < 0)
return ret;
if ((size_t) ret != length - written)
return -ENOBUFS;
return length;
}
/**
* PushData
* @param[in] buf The buffer to append the to the buffer contents
* @param[in] length The length of the data
*
* This function will append the data to the buffer
* It is possible to fail with eother a memory allocation issue or if the maxmimum buffer size is going to be exceeded
*/
int Buffer::PushData(const char *buf, size_t length)
{
if (GetFreeSpace() < length)
{
if (ReSize(m_buffer_length + length) == false)
{
return -ENOMEM;
}
}
memcpy(&m_buffer[m_buffer_used], buf, length);
m_buffer_used += length;
return length;
}
/**
* PullData
* @param[in] buf This will be populated by the data
* @param[in] length The size of the buffer buf
*
* This function will read data from the front of the buffer and populate as much as possible in buf
* If the passed buf is larger than the data stored in the buffer then the return value will indicate how much data was copied ot buf
*/
int Buffer::PullData(char *buf, size_t length)
{
int len = length;
if (m_buffer_used < length)
len = m_buffer_used;
memcpy(buf, m_buffer, len);
Shift(len);
return len;
}
/**
* Clear
*
* This function will mark the buffer as empty as if it has no data in it
*/
void Buffer::Clear()
{
m_buffer_used = 0;
}
/*
* GetLine
* @param[in] str This will be modified to contain the next line found in the buffer
*
* This function will attempt to scan the buffer and return the first line of text found in the buffer
* If it finds a line of text then true will be returned. It will return false if it the buffer does nto contain a full line
*/
bool Buffer::GetLine(std::string *str)
{
return GetLine(str, '\n');
}
/*
* GetLine
* @param[in] str This will be modified to contain the next line found in the buffer
* @param[in] term This will be used to specifiy the end of line marker to look for in the buffer
*
* This function will attempt to scan the buffer and return the first line of text found in the buffer
* If it finds a line of text then true will be returned. It will return false if it the buffer does nto contain a full line
*/
bool Buffer::GetLine(std::string *str, const char term)
{
if (GetDataLength() == 0)
return false;
char *lf = (char *) memchr(m_buffer, term, m_buffer_used);
if (lf == NULL)
return false;
*lf = 0; //Add NULL Terminator
*str = m_buffer;
size_t Offset = lf - m_buffer + 1;
Shift(Offset);
return true;
}
/*
* GetLine
* @param[in] str This will be modified to contain the next line found in the buffer
* @param[in] ending This will be used to specifiy the end of line marker to look for in the buffer
*
* This function will attempt to scan the buffer and return the first line of text found in the buffer
* If it finds a line of text then true will be returned. It will return false if it the buffer does nto contain a full line
*/
bool Buffer::GetLine(std::string *str, const std::string &ending)
{
return GetLine(str, ending.c_str());
}
/*
* GetLine
* @param[in] str This will be modified to contain the next line found in the buffer
* @param[in] ending This will be used to specifiy the end of line marker to look for in the buffer
*
* This function will attempt to scan the buffer and return the first line of text found in the buffer
* If it finds a line of text then true will be returned. It will return false if it the buffer does nto contain a full line
*/
bool Buffer::GetLine(std::string *str, const char *ending)
{
if (GetDataLength() == 0)
return false;
char *lf = (char *) memmem(m_buffer, m_buffer_used, ending, strlen(ending));
if (lf == NULL)
return false;
*lf = 0; //Add NULL Terminator
*str = m_buffer;
size_t Offset = lf - m_buffer + 1;
Shift(Offset);
return true;
}
/**
* Shift
* @param[in] size The amount of data to remove from the front of the buffer
*
* This will rmeove the size of bytes from the front of the buffer. If you attempt to remove more data that exists in the buffer abort will be called.
*/
void Buffer::Shift(size_t size)
{
if (size == 0)
return;
if (m_buffer_used == 0)
abort();
if (size > m_buffer_used)
abort();
if (size == m_buffer_used)
{
m_buffer_used = 0;
return;
}
memmove(m_buffer, m_buffer + size, m_buffer_used);
m_buffer_used -= size;
}
/**
* GetPtr
*
* This function return a raw value to a buffer. Beaware that calling other functions can invalidate this pointer as the memory block may be relocated to a different area.
*/
void *Buffer::GetPtr()
{
return m_buffer;
}
/**
* GetDataLength
*
* This function will return the number of bytes stored in the buffer
*/
size_t Buffer::GetDataLength()
{
return m_buffer_used;
}
/**
* GetFreeSpace
*
* This function will return the number of free bytes in the buffer before the buffer would need to be expanded to use more data
*/
size_t Buffer::GetFreeSpace()
{
return m_buffer_length - m_buffer_used;
}
/**
* GetTotalSpace
*
* This function returns the total space of the allocated buffer
*/
size_t Buffer::GetTotalSpace()
{
return m_buffer_length;
}
/**
* SetChunkSize
* @param[in] size Value to store
*
* After setting this value it will be used to perform io on the Read function when attempting to read data
*/
void Buffer::SetChunkSize(size_t size)
{
m_chunk_size = size;
}
/**
* GetChunkSize
*
* Opposite of SetChunkSize
*/
size_t Buffer::GetChunkSize()
{
return m_chunk_size;
}
/**
* SetMaxSize
* @param[in] size Set the maximum size of the buffer
*
* This will set the enforced limit of how big the buffer can grow.
* This function can fail if a limit is placed but there is currently data in the buffer bigger than the new limit
* Calling with a value of 0 will impose no limit on the buffer and no reallocation will be attempted
*/
int Buffer::SetMaxSize(size_t size)
{
if (size == 0)
m_max_size = 0;
if (m_buffer_length > size)
{
if (Shrink() == false)
{
return -1;
}
}
if (m_buffer_length > size)
{
return -1;
}
m_max_size = size;
return 0;
}
/**
* GetMaxSize
*
* This will return the maximum size the buffer can be.
* 0 imposes no limit
*/
size_t Buffer::GetMaxSize()
{
return m_max_size;
}
/**
* Shrink
*
* Cause the allocated memory to be shrunk to use the minimum amount of memory
*/
bool Buffer::Shrink()
{
return ReSize(m_buffer_used);
}
/**
* ReSize
* @param[in] size The new size for the block of allocated memory
*
* Cause the allocated buffer memory to be resized
*/
bool Buffer::ReSize(size_t newsize)
{
if (newsize < m_buffer_used)
abort();
if (m_max_size != 0 && newsize > m_max_size)
return false;
char *nbuf = (char *) realloc(m_buffer, newsize * sizeof(m_buffer));
if (!nbuf)
return false;
m_buffer = nbuf;
m_buffer_length = newsize;
return true;
}
<commit_msg>Missing pointer de-reference<commit_after>
#include <libclientserver.h>
Buffer::Buffer()
{
m_buffer_length = 8192;
m_chunk_size = 65535;
m_buffer_used = 0;
m_buffer = NULL;
m_max_size = 0;
}
Buffer::~Buffer()
{
free(m_buffer);
}
/**
* @Init
*
* One of the Init functions or overloads must be called before using any other function in the class
*/
int Buffer::Init()
{
m_buffer = (char *) malloc(m_buffer_length * sizeof(*m_buffer));
if (!m_buffer)
return -ENOMEM;
return 0;
}
/**
* @Init
* @param[in] buflen This should be the initial size of memory allocated to the buffer
*
* One of the Init functions or overloads must be called before using any other function in the class
*/
int Buffer::Init(size_t buflen)
{
m_buffer_length = buflen;
return Init();
}
/**
* @Read
* @param[in] fd This should be the file descriptor to read from
*
* This function will attempt to read chunk size from the fd and populate the buffer contents with the data
* If the buffer is going to exceed the max size it will return -ENOMEM
* If the file has reached EOF -1 will be returned
* If there is an error reading from the fd the approiate error code will be returned to indicte what the problem was.
* In normal working cases without error's the length of the data read will be returned. This includes returning 0 if there was no data to read.
*/
int Buffer::Read(int fd)
{
if (GetFreeSpace() < m_chunk_size)
{
if (ReSize(m_buffer_length + m_chunk_size) == false)
{
return -ENOMEM;
}
}
int ret = read(fd, m_buffer + m_buffer_used, m_chunk_size);
if (ret < 0)
{
switch(errno)
{
case EAGAIN:
case EINTR:
return 0;
default:
return -errno;
}
}
if (ret == 0)
return -1;
m_buffer_used += ret;
return ret;
}
/**
* Write
* @param[in] fd The file descriptor to write to
*
* This function will attempt to write as much of the buffer as possible to the fd.
* If an error occurs it will will return the approate error code to indicate what the error was.
* If the function was able to write any data it will return the amount of data that was written to the fd
*/
int Buffer::Write(int fd)
{
if (m_buffer_used == 0)
return 0;
int ret = write(fd, m_buffer, m_buffer_used);
if (ret > 0)
{
Shift(ret);
return ret;
}
switch(errno)
{
case EAGAIN:
case EINTR:
return 0;
break;
default:
return -errno;
break;
}
return -1;
}
/**
* WriteBuffered
* @param[in] fd The file descriptor to write to
* @param[in] buf The data to write
* @param[in] length The amount of data to write from buf
*
* This functin will attempt to write as much data as it can to the file descriptor before it blocks.
* Once it starts blocking it will then write the remaining part of the data to the buffer which can be written by calling Write(fd) later
* If the initial write fails it will return the error that occured and will not attempt to write any data to either the fd or the buffer
* If the buffers required more memory it is posisble for this function to file is there is a maximum buffer limit set. In which case it will fail with -NOBUFS
* Under normal situations this function will always return the lgnth value passed
*/
int Buffer::WriteBuffered(int fd, const char *buf, size_t length)
{
int ret = write(fd, buf, length);
if (ret < 0)
{
switch(errno)
{
case EAGAIN:
case EINTR:
return PushData(buf, length);
default:
return -errno;
break;
}
}
size_t written = ret;
if (written == length)
return length;
//Not all of it went to the socket to buffer it and say success to the caller
ret = PushData(&buf[written], length - written);
if (ret < 0)
return ret;
if ((size_t) ret != length - written)
return -ENOBUFS;
return length;
}
/**
* PushData
* @param[in] buf The buffer to append the to the buffer contents
* @param[in] length The length of the data
*
* This function will append the data to the buffer
* It is possible to fail with eother a memory allocation issue or if the maxmimum buffer size is going to be exceeded
*/
int Buffer::PushData(const char *buf, size_t length)
{
if (GetFreeSpace() < length)
{
if (ReSize(m_buffer_length + length) == false)
{
return -ENOMEM;
}
}
memcpy(&m_buffer[m_buffer_used], buf, length);
m_buffer_used += length;
return length;
}
/**
* PullData
* @param[in] buf This will be populated by the data
* @param[in] length The size of the buffer buf
*
* This function will read data from the front of the buffer and populate as much as possible in buf
* If the passed buf is larger than the data stored in the buffer then the return value will indicate how much data was copied ot buf
*/
int Buffer::PullData(char *buf, size_t length)
{
int len = length;
if (m_buffer_used < length)
len = m_buffer_used;
memcpy(buf, m_buffer, len);
Shift(len);
return len;
}
/**
* Clear
*
* This function will mark the buffer as empty as if it has no data in it
*/
void Buffer::Clear()
{
m_buffer_used = 0;
}
/*
* GetLine
* @param[in] str This will be modified to contain the next line found in the buffer
*
* This function will attempt to scan the buffer and return the first line of text found in the buffer
* If it finds a line of text then true will be returned. It will return false if it the buffer does nto contain a full line
*/
bool Buffer::GetLine(std::string *str)
{
return GetLine(str, '\n');
}
/*
* GetLine
* @param[in] str This will be modified to contain the next line found in the buffer
* @param[in] term This will be used to specifiy the end of line marker to look for in the buffer
*
* This function will attempt to scan the buffer and return the first line of text found in the buffer
* If it finds a line of text then true will be returned. It will return false if it the buffer does nto contain a full line
*/
bool Buffer::GetLine(std::string *str, const char term)
{
if (GetDataLength() == 0)
return false;
char *lf = (char *) memchr(m_buffer, term, m_buffer_used);
if (lf == NULL)
return false;
*lf = 0; //Add NULL Terminator
*str = m_buffer;
size_t Offset = lf - m_buffer + 1;
Shift(Offset);
return true;
}
/*
* GetLine
* @param[in] str This will be modified to contain the next line found in the buffer
* @param[in] ending This will be used to specifiy the end of line marker to look for in the buffer
*
* This function will attempt to scan the buffer and return the first line of text found in the buffer
* If it finds a line of text then true will be returned. It will return false if it the buffer does nto contain a full line
*/
bool Buffer::GetLine(std::string *str, const std::string &ending)
{
return GetLine(str, ending.c_str());
}
/*
* GetLine
* @param[in] str This will be modified to contain the next line found in the buffer
* @param[in] ending This will be used to specifiy the end of line marker to look for in the buffer
*
* This function will attempt to scan the buffer and return the first line of text found in the buffer
* If it finds a line of text then true will be returned. It will return false if it the buffer does nto contain a full line
*/
bool Buffer::GetLine(std::string *str, const char *ending)
{
if (GetDataLength() == 0)
return false;
char *lf = (char *) memmem(m_buffer, m_buffer_used, ending, strlen(ending));
if (lf == NULL)
return false;
*lf = 0; //Add NULL Terminator
*str = m_buffer;
size_t Offset = lf - m_buffer + 1;
Shift(Offset);
return true;
}
/**
* Shift
* @param[in] size The amount of data to remove from the front of the buffer
*
* This will rmeove the size of bytes from the front of the buffer. If you attempt to remove more data that exists in the buffer abort will be called.
*/
void Buffer::Shift(size_t size)
{
if (size == 0)
return;
if (m_buffer_used == 0)
abort();
if (size > m_buffer_used)
abort();
if (size == m_buffer_used)
{
m_buffer_used = 0;
return;
}
memmove(m_buffer, m_buffer + size, m_buffer_used);
m_buffer_used -= size;
}
/**
* GetPtr
*
* This function return a raw value to a buffer. Beaware that calling other functions can invalidate this pointer as the memory block may be relocated to a different area.
*/
void *Buffer::GetPtr()
{
return m_buffer;
}
/**
* GetDataLength
*
* This function will return the number of bytes stored in the buffer
*/
size_t Buffer::GetDataLength()
{
return m_buffer_used;
}
/**
* GetFreeSpace
*
* This function will return the number of free bytes in the buffer before the buffer would need to be expanded to use more data
*/
size_t Buffer::GetFreeSpace()
{
return m_buffer_length - m_buffer_used;
}
/**
* GetTotalSpace
*
* This function returns the total space of the allocated buffer
*/
size_t Buffer::GetTotalSpace()
{
return m_buffer_length;
}
/**
* SetChunkSize
* @param[in] size Value to store
*
* After setting this value it will be used to perform io on the Read function when attempting to read data
*/
void Buffer::SetChunkSize(size_t size)
{
m_chunk_size = size;
}
/**
* GetChunkSize
*
* Opposite of SetChunkSize
*/
size_t Buffer::GetChunkSize()
{
return m_chunk_size;
}
/**
* SetMaxSize
* @param[in] size Set the maximum size of the buffer
*
* This will set the enforced limit of how big the buffer can grow.
* This function can fail if a limit is placed but there is currently data in the buffer bigger than the new limit
* Calling with a value of 0 will impose no limit on the buffer and no reallocation will be attempted
*/
int Buffer::SetMaxSize(size_t size)
{
if (size == 0)
m_max_size = 0;
if (m_buffer_length > size)
{
if (Shrink() == false)
{
return -1;
}
}
if (m_buffer_length > size)
{
return -1;
}
m_max_size = size;
return 0;
}
/**
* GetMaxSize
*
* This will return the maximum size the buffer can be.
* 0 imposes no limit
*/
size_t Buffer::GetMaxSize()
{
return m_max_size;
}
/**
* Shrink
*
* Cause the allocated memory to be shrunk to use the minimum amount of memory
*/
bool Buffer::Shrink()
{
return ReSize(m_buffer_used);
}
/**
* ReSize
* @param[in] size The new size for the block of allocated memory
*
* Cause the allocated buffer memory to be resized
*/
bool Buffer::ReSize(size_t newsize)
{
if (newsize < m_buffer_used)
abort();
if (m_max_size != 0 && newsize > m_max_size)
return false;
char *nbuf = (char *) realloc(m_buffer, newsize * sizeof(*m_buffer));
if (!nbuf)
return false;
m_buffer = nbuf;
m_buffer_length = newsize;
return true;
}
<|endoftext|>
|
<commit_before>//
// MIT License
//
// Copyright 2018-2019
//
// 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 BOOST_TEST_MODULE cpu_test
#include <boost/test/unit_test.hpp>
#include <variant>
#include "decode.hh"
#include "disassemble.hh"
namespace jde = jones::decode;
namespace jdi = jones::disassemble;
namespace {
void check_instruction_invalid(const jde::instruction &instruction) {
BOOST_CHECK(instruction.decoded_opcode.type == opcode_type::INVALID);
BOOST_CHECK(instruction.decoded_opcode.value == 0);
BOOST_CHECK(instruction.decoded_operand.type == operand_type::INVALID);
BOOST_CHECK(std::get<uint8_t>(instruction.decoded_operand.value) == static_cast<uint8_t>(0x00));
}
void check_instruction_no_operand(const jde::instruction &instruction) {
BOOST_CHECK(instruction.decoded_operand.type == operand_type::NONE);
BOOST_CHECK(std::get<uint8_t>(instruction.decoded_operand.value) == static_cast<uint8_t>(0x00));
}
} // namespace
BOOST_AUTO_TEST_CASE(cpu_test) { BOOST_CHECK(true); }
BOOST_AUTO_TEST_CASE(disasemble_test_and_immediate) {
uint8_t and_immediate[] = {0x29, 0x2C};
const auto instructions = jdi::disassemble(and_immediate, sizeof(and_immediate));
BOOST_CHECK(instructions.instructions.size() == 1);
const auto &first_instruction = instructions.instructions[0];
BOOST_CHECK(first_instruction == "AND #$2C");
}
//
// Test: Decodes an instruction that is too small. In this case, an empty instruction.
//
BOOST_AUTO_TEST_CASE(decode_invalid_instruction_too_small) {
uint8_t empty_instruction[] = {};
const auto instruction = jde::decode(empty_instruction, sizeof(empty_instruction));
check_instruction_invalid(instruction);
}
//
// Test: Decodes opcode value 0x00.
//
BOOST_AUTO_TEST_CASE(decode_0x00_brk_instruction_valid) {
uint8_t brk_instruction[] = {0x00};
const auto instruction = jde::decode(brk_instruction, sizeof(brk_instruction));
BOOST_CHECK(instruction.decoded_opcode.type == opcode_type::BRK);
BOOST_CHECK(instruction.decoded_opcode.value == 0x00);
check_instruction_no_operand(instruction);
}
//
// Test: Decodes opcode value 0x01 with operand value set to 0xFF
//
BOOST_AUTO_TEST_CASE(decode_0x01_ora_instruction_valid) {
uint8_t ora_instruction[] = {0x01, 0xFF};
const auto instruction = jde::decode(ora_instruction, sizeof(ora_instruction));
BOOST_CHECK(instruction.decoded_opcode.type == opcode_type::ORA);
BOOST_CHECK(instruction.decoded_opcode.value == 0x01);
BOOST_CHECK(instruction.decoded_operand.type == operand_type::MEMORY);
BOOST_CHECK(std::get<uint8_t>(instruction.decoded_operand.value) == static_cast<uint8_t>(0xFF));
}
//
// Test: Decodes opcode value 0x01 with missing operand value.
//
BOOST_AUTO_TEST_CASE(decode_0x01_ora_instruction_invalid_too_small) {
uint8_t ora_instruction[] = {0x01};
const auto instruction = jde::decode(ora_instruction, sizeof(ora_instruction));
check_instruction_invalid(instruction);
}
//
// Test: Decodes opcode value 0x02.
//
BOOST_AUTO_TEST_CASE(decode_0x02_stp_instruction_valid) {
uint8_t stp_instruction[] = {0x02};
const auto instruction = jde::decode(stp_instruction, sizeof(stp_instruction));
BOOST_CHECK(instruction.decoded_opcode.type == opcode_type::STP);
BOOST_CHECK(instruction.decoded_opcode.value == 0x02);
check_instruction_no_operand(instruction);
}
//
// Test: Decodes opcode value 0x03 with operand value set to 0xFF.
//
BOOST_AUTO_TEST_CASE(decode_0x03_slo_instruction_valid) {
uint8_t slo_instruction[] = {0x03, 0xFF};
const auto instruction = jde::decode(slo_instruction, sizeof(slo_instruction));
BOOST_CHECK(instruction.decoded_opcode.type == opcode_type::SLO);
BOOST_CHECK(instruction.decoded_opcode.value == 0x03);
BOOST_CHECK(instruction.decoded_operand.type == operand_type::MEMORY);
BOOST_CHECK(std::get<uint8_t>(instruction.decoded_operand.value) == static_cast<uint8_t>(0xFF));
}
//
// Test: Decodes opcode value 0x03 with missing operand value.
//
BOOST_AUTO_TEST_CASE(decode_0x03_slo_instruction_invalid_too_small) {
uint8_t slo_instruction[] = {0x03};
const auto instruction = jde::decode(slo_instruction, sizeof(slo_instruction));
check_instruction_invalid(instruction);
}
//
// Test: Decodes opcode value 0x04 with operand value set to 0xFF.
//
BOOST_AUTO_TEST_CASE(decode_0x04_nop_instruction_valid) {
uint8_t nop_instruction[] = {0x04, 0xFF};
const auto instruction = jde::decode(nop_instruction, sizeof(nop_instruction));
BOOST_CHECK(instruction.decoded_opcode.type == opcode_type::NOP);
BOOST_CHECK(instruction.decoded_opcode.value == 0x04);
BOOST_CHECK(instruction.decoded_operand.type == operand_type::MEMORY);
BOOST_CHECK(std::get<uint8_t>(instruction.decoded_operand.value) == static_cast<uint8_t>(0xFF));
}
//
// Test: Decodes opcode value 0x04 with missing operand type.
//
BOOST_AUTO_TEST_CASE(decode_0x04_nop_instruction_invalid_too_small) {
uint8_t nop_instruction[] = {0x04};
const auto instruction = jde::decode(nop_instruction, sizeof(nop_instruction));
check_instruction_invalid(instruction);
}
//
// Test: Decodes opcode value 0x05 with operand value set to 0xFF
//
BOOST_AUTO_TEST_CASE(decode_0x05_ora_instruction_valid) {
uint8_t ora_instruction[] = {0x05, 0xFF};
const auto instruction = jde::decode(ora_instruction, sizeof(ora_instruction));
BOOST_CHECK(instruction.decoded_opcode.type == opcode_type::ORA);
BOOST_CHECK(instruction.decoded_opcode.value == 0x05);
BOOST_CHECK(instruction.decoded_operand.type == operand_type::MEMORY);
BOOST_CHECK(std::get<uint8_t>(instruction.decoded_operand.value) == static_cast<uint8_t>(0xFF));
}
//
// Test: Decodes opcode value 0x05 with missing operand value.
//
BOOST_AUTO_TEST_CASE(decode_0x05_ora_instruction_invalid_too_small) {
uint8_t ora_instruction[] = {0x05};
const auto instruction = jde::decode(ora_instruction, sizeof(ora_instruction));
check_instruction_invalid(instruction);
}
<commit_msg>adding more unit tests<commit_after>//
// MIT License
//
// Copyright 2018-2019
//
// 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 BOOST_TEST_MODULE cpu_test
#include <boost/test/unit_test.hpp>
#include <variant>
#include "decode.hh"
#include "disassemble.hh"
namespace jde = jones::decode;
namespace jdi = jones::disassemble;
namespace {
void check_instruction_invalid(const jde::instruction &instruction) {
BOOST_CHECK(instruction.decoded_opcode.type == opcode_type::INVALID);
BOOST_CHECK(instruction.decoded_opcode.value == 0);
BOOST_CHECK(instruction.decoded_operand.type == operand_type::INVALID);
BOOST_CHECK(std::get<uint8_t>(instruction.decoded_operand.value) == static_cast<uint8_t>(0x00));
}
void check_instruction_no_operand(const jde::instruction &instruction) {
BOOST_CHECK(instruction.decoded_operand.type == operand_type::NONE);
BOOST_CHECK(std::get<uint8_t>(instruction.decoded_operand.value) == static_cast<uint8_t>(0x00));
}
} // namespace
BOOST_AUTO_TEST_CASE(cpu_test) { BOOST_CHECK(true); }
BOOST_AUTO_TEST_CASE(disasemble_test_and_immediate) {
uint8_t and_immediate[] = {0x29, 0x2C};
const auto instructions = jdi::disassemble(and_immediate, sizeof(and_immediate));
BOOST_CHECK(instructions.instructions.size() == 1);
const auto &first_instruction = instructions.instructions[0];
BOOST_CHECK(first_instruction == "AND #$2C");
}
//
// Test: Decodes an instruction that is too small. In this case, an empty instruction.
//
BOOST_AUTO_TEST_CASE(decode_invalid_instruction_too_small) {
uint8_t empty_instruction[] = {};
const auto instruction = jde::decode(empty_instruction, sizeof(empty_instruction));
check_instruction_invalid(instruction);
}
//
// Test: Decodes opcode value 0x00.
//
BOOST_AUTO_TEST_CASE(decode_0x00_brk_instruction_valid) {
uint8_t brk_instruction[] = {0x00};
const auto instruction = jde::decode(brk_instruction, sizeof(brk_instruction));
BOOST_CHECK(instruction.decoded_opcode.type == opcode_type::BRK);
BOOST_CHECK(instruction.decoded_opcode.value == 0x00);
check_instruction_no_operand(instruction);
}
//
// Test: Decodes opcode value 0x01 with operand value set to 0xFF
//
BOOST_AUTO_TEST_CASE(decode_0x01_ora_instruction_valid) {
uint8_t ora_instruction[] = {0x01, 0xFF};
const auto instruction = jde::decode(ora_instruction, sizeof(ora_instruction));
BOOST_CHECK(instruction.decoded_opcode.type == opcode_type::ORA);
BOOST_CHECK(instruction.decoded_opcode.value == 0x01);
BOOST_CHECK(instruction.decoded_operand.type == operand_type::MEMORY);
BOOST_CHECK(std::get<uint8_t>(instruction.decoded_operand.value) == static_cast<uint8_t>(0xFF));
}
//
// Test: Decodes opcode value 0x01 with missing operand value.
//
BOOST_AUTO_TEST_CASE(decode_0x01_ora_instruction_invalid_too_small) {
uint8_t ora_instruction[] = {0x01};
const auto instruction = jde::decode(ora_instruction, sizeof(ora_instruction));
check_instruction_invalid(instruction);
}
//
// Test: Decodes opcode value 0x02.
//
BOOST_AUTO_TEST_CASE(decode_0x02_stp_instruction_valid) {
uint8_t stp_instruction[] = {0x02};
const auto instruction = jde::decode(stp_instruction, sizeof(stp_instruction));
BOOST_CHECK(instruction.decoded_opcode.type == opcode_type::STP);
BOOST_CHECK(instruction.decoded_opcode.value == 0x02);
check_instruction_no_operand(instruction);
}
//
// Test: Decodes opcode value 0x03 with operand value set to 0xFF.
//
BOOST_AUTO_TEST_CASE(decode_0x03_slo_instruction_valid) {
uint8_t slo_instruction[] = {0x03, 0xFF};
const auto instruction = jde::decode(slo_instruction, sizeof(slo_instruction));
BOOST_CHECK(instruction.decoded_opcode.type == opcode_type::SLO);
BOOST_CHECK(instruction.decoded_opcode.value == 0x03);
BOOST_CHECK(instruction.decoded_operand.type == operand_type::MEMORY);
BOOST_CHECK(std::get<uint8_t>(instruction.decoded_operand.value) == static_cast<uint8_t>(0xFF));
}
//
// Test: Decodes opcode value 0x03 with missing operand value.
//
BOOST_AUTO_TEST_CASE(decode_0x03_slo_instruction_invalid_too_small) {
uint8_t slo_instruction[] = {0x03};
const auto instruction = jde::decode(slo_instruction, sizeof(slo_instruction));
check_instruction_invalid(instruction);
}
//
// Test: Decodes opcode value 0x04 with operand value set to 0xFF.
//
BOOST_AUTO_TEST_CASE(decode_0x04_nop_instruction_valid) {
uint8_t nop_instruction[] = {0x04, 0xFF};
const auto instruction = jde::decode(nop_instruction, sizeof(nop_instruction));
BOOST_CHECK(instruction.decoded_opcode.type == opcode_type::NOP);
BOOST_CHECK(instruction.decoded_opcode.value == 0x04);
BOOST_CHECK(instruction.decoded_operand.type == operand_type::MEMORY);
BOOST_CHECK(std::get<uint8_t>(instruction.decoded_operand.value) == static_cast<uint8_t>(0xFF));
}
//
// Test: Decodes opcode value 0x04 with missing operand type.
//
BOOST_AUTO_TEST_CASE(decode_0x04_nop_instruction_invalid_too_small) {
uint8_t nop_instruction[] = {0x04};
const auto instruction = jde::decode(nop_instruction, sizeof(nop_instruction));
check_instruction_invalid(instruction);
}
//
// Test: Decodes opcode value 0x05 with operand value set to 0xFF
//
BOOST_AUTO_TEST_CASE(decode_0x05_ora_instruction_valid) {
uint8_t ora_instruction[] = {0x05, 0xFF};
const auto instruction = jde::decode(ora_instruction, sizeof(ora_instruction));
BOOST_CHECK(instruction.decoded_opcode.type == opcode_type::ORA);
BOOST_CHECK(instruction.decoded_opcode.value == 0x05);
BOOST_CHECK(instruction.decoded_operand.type == operand_type::MEMORY);
BOOST_CHECK(std::get<uint8_t>(instruction.decoded_operand.value) == static_cast<uint8_t>(0xFF));
}
//
// Test: Decodes opcode value 0x05 with missing operand value.
//
BOOST_AUTO_TEST_CASE(decode_0x05_ora_instruction_invalid_too_small) {
uint8_t ora_instruction[] = {0x05};
const auto instruction = jde::decode(ora_instruction, sizeof(ora_instruction));
check_instruction_invalid(instruction);
}
//
// Test: Decodes opcode value 0x06 with operand value set to 0xFF
//
BOOST_AUTO_TEST_CASE(decode_0x06_asl_instruction_valid) {
uint8_t asl_instruction[] = {0x06, 0xFF};
const auto instruction = jde::decode(asl_instruction, sizeof(asl_instruction));
BOOST_CHECK(instruction.decoded_opcode.type == opcode_type::ASL);
BOOST_CHECK(instruction.decoded_opcode.value == 0x06);
BOOST_CHECK(instruction.decoded_operand.type == operand_type::MEMORY);
BOOST_CHECK(std::get<uint8_t>(instruction.decoded_operand.value) == static_cast<uint8_t>(0xFF));
}
//
// Test: Decodes opcode value 0x06 with missing operand value.
//
BOOST_AUTO_TEST_CASE(decode_0x06_asl_instruction_invalid_too_small) {
uint8_t asl_instruction[] = {0x06};
const auto instruction = jde::decode(asl_instruction, sizeof(asl_instruction));
check_instruction_invalid(instruction);
}
//
// Test: Decodes opcode value 0x07 with operand value set to 0xFF
//
BOOST_AUTO_TEST_CASE(decode_0x07_slo_instruction_valid) {
uint8_t slo_instruction[] = {0x07, 0xFF};
const auto instruction = jde::decode(slo_instruction, sizeof(slo_instruction));
BOOST_CHECK(instruction.decoded_opcode.type == opcode_type::SLO);
BOOST_CHECK(instruction.decoded_opcode.value == 0x07);
BOOST_CHECK(instruction.decoded_operand.type == operand_type::MEMORY);
BOOST_CHECK(std::get<uint8_t>(instruction.decoded_operand.value) == static_cast<uint8_t>(0xFF));
}
//
// Test: Decodes opcode value 0x07 with missing operand value.
//
BOOST_AUTO_TEST_CASE(decode_0x07_slo_instruction_invalid_too_small) {
uint8_t slo_instruction[] = {0x07};
const auto instruction = jde::decode(slo_instruction, sizeof(slo_instruction));
check_instruction_invalid(instruction);
}
//
// Test: Decodes opcode value 0x08.
//
BOOST_AUTO_TEST_CASE(decode_0x08_php_instruction_valid) {
uint8_t php_instruction[] = {0x08, 0xFF};
const auto instruction = jde::decode(php_instruction, sizeof(php_instruction));
BOOST_CHECK(instruction.decoded_opcode.type == opcode_type::PHP);
BOOST_CHECK(instruction.decoded_opcode.value == 0x08);
check_instruction_no_operand(instruction);
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2011 Isaac W. Foraker, all rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. Neither the name of the Author nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE AND DOCUMENTATION IS PROVIDED BY THE AUTHOR AND
* CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "c_duck_type/duck_type.h"
#include "c_duck_type/nil_class.h"
#include "c_duck_type/string.h"
#include "c_duck_type/integer.h"
#include "c_duck_type/real.h"
#include "c_duck_type/boolean.h"
#include <sstream>
#include <cstring>
namespace CDuckType {
DuckType::DuckType()
{
value_ = &nil;
}
DuckType::DuckType(const DuckType &object)
{
}
DuckType::DuckType(const BaseType &object)
{
value_ = object.dup();
}
DuckType::~DuckType()
{
if (value_ && !value_->is_a<NilClass>())
delete value_;
}
DuckType &DuckType::swap(DuckType &value)
{
BaseType *v = value_;
value_ = value.value_;
value.value_ = v;
return *this;
}
DuckType &DuckType::operator=(const DuckType &value)
{
throw std::runtime_error("implement me");
return *this;
}
DuckType &DuckType::operator=(const BaseType &value)
{
throw std::runtime_error("implement me");
return *this;
}
DuckType &DuckType::operator=(const char* value)
{
if (value_ && value_->is_a<String>()) {
static_cast<String*>(value_)->assign(value);
}
else if (value_ && value_->equals(nil)) {
value_ = new String(value);
}
else {
delete value_;
value_ = new String(value);
}
return *this;
}
DuckType &DuckType::operator=(integer_type value)
{
if (value_ && value_->is_a<Integer>()) {
static_cast<Integer*>(value_)->assign(value);
}
else if (value_ && value_->equals(nil)) {
value_ = new Integer(value);
}
else {
delete value_;
value_ = new Integer(value);
}
return *this;
}
DuckType &DuckType::operator=(real_type value)
{
if (value_ && value_->is_a<Real>()) {
static_cast<Real*>(value_)->assign(value);
}
else if (value_ && value_->equals(nil)) {
value_ = new Real(value);
}
else {
delete value_;
value_ = new Real(value);
}
return *this;
}
DuckType &DuckType::operator=(bool value)
{
if (value_ && value_->is_a<Boolean>()) {
Boolean *b = static_cast<Boolean*>(value_);
b->assign(value);
}
else if (value_ && value_->equals(nil)) {
value_ = new Boolean(value);
}
else {
delete value_;
value_ = new Boolean(value);
}
return *this;
}
string_type DuckType::to_string() const
{
return value_->to_string();
}
integer_type DuckType::to_integer() const
{
return value_->to_integer();
}
real_type DuckType::to_real() const
{
return value_->to_real();
}
bool DuckType::is_a(const DuckType &object) const
{
if (value_)
return value_->is_a(*object.value_);
else
return false;
}
bool DuckType::is_a(const BaseType &object) const
{
if (value_)
return value_->is_a(object);
else
return false;
}
} // CDuckType
<commit_msg>Implemented more DuckType constructors.<commit_after>/*
* Copyright (c) 2011 Isaac W. Foraker, all rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. Neither the name of the Author nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE AND DOCUMENTATION IS PROVIDED BY THE AUTHOR AND
* CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "c_duck_type/duck_type.h"
#include "c_duck_type/nil_class.h"
#include "c_duck_type/string.h"
#include "c_duck_type/integer.h"
#include "c_duck_type/real.h"
#include "c_duck_type/boolean.h"
#include <sstream>
#include <cstring>
namespace CDuckType {
DuckType::DuckType()
{
value_ = &nil;
}
DuckType::DuckType(const DuckType &object)
{
value_ = object.value_->dup();
}
DuckType::DuckType(const BaseType &object)
{
value_ = object.dup();
}
DuckType::DuckType(const char *value)
{
value_ = new String(value);
}
DuckType::DuckType(integer_type value)
{
value_ = new Integer(value);
}
DuckType::DuckType(real_type value)
{
value_ = new Real(value);
}
DuckType::DuckType(bool value)
{
value_ = new Boolean(value);
}
DuckType::~DuckType()
{
if (value_ && value_ != &nil)
delete value_;
}
DuckType &DuckType::swap(DuckType &value)
{
BaseType *v = value_;
value_ = value.value_;
value.value_ = v;
return *this;
}
DuckType &DuckType::operator=(const DuckType &value)
{
throw std::runtime_error("implement me");
return *this;
}
DuckType &DuckType::operator=(const BaseType &value)
{
throw std::runtime_error("implement me");
return *this;
}
DuckType &DuckType::operator=(const char* value)
{
if (value_ && value_->is_a<String>()) {
static_cast<String*>(value_)->assign(value);
}
else if (value_ && value_->equals(nil)) {
value_ = new String(value);
}
else {
delete value_;
value_ = new String(value);
}
return *this;
}
DuckType &DuckType::operator=(integer_type value)
{
if (value_ && value_->is_a<Integer>()) {
static_cast<Integer*>(value_)->assign(value);
}
else if (value_ && value_->equals(nil)) {
value_ = new Integer(value);
}
else {
delete value_;
value_ = new Integer(value);
}
return *this;
}
DuckType &DuckType::operator=(real_type value)
{
if (value_ && value_->is_a<Real>()) {
static_cast<Real*>(value_)->assign(value);
}
else if (value_ && value_->equals(nil)) {
value_ = new Real(value);
}
else {
delete value_;
value_ = new Real(value);
}
return *this;
}
DuckType &DuckType::operator=(bool value)
{
if (value_ && value_->is_a<Boolean>()) {
Boolean *b = static_cast<Boolean*>(value_);
b->assign(value);
}
else if (value_ && value_->equals(nil)) {
value_ = new Boolean(value);
}
else {
delete value_;
value_ = new Boolean(value);
}
return *this;
}
string_type DuckType::to_string() const
{
return value_->to_string();
}
integer_type DuckType::to_integer() const
{
return value_->to_integer();
}
real_type DuckType::to_real() const
{
return value_->to_real();
}
bool DuckType::is_a(const DuckType &object) const
{
if (value_)
return value_->is_a(*object.value_);
else
return false;
}
bool DuckType::is_a(const BaseType &object) const
{
if (value_)
return value_->is_a(object);
else
return false;
}
} // CDuckType
<|endoftext|>
|
<commit_before>/*
The MIT License (MIT)
Copyright (c) 2013 rajendrauppal
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <iostream>
#include "Exceptions.h"
#include "GcdLcm.h"
using std::cout;
using std::cin;
using std::endl;
int GcdLcm::GCD_Euclidean_Iterative(int m, int n)
{
if ( (m < 0) || (n < 0) ) throw InvalidInputException();
if ( !m && !n ) throw InvalidInputException();
if ( m && !n ) return m;
if ( !m && n ) return n;
while ( n ) {
int temp = n;
n = m % n;
m = temp;
}
return m;
}
int GcdLcm::GCD_Euclidean_Recursive(int m, int n)
{
if ( (m < 0) || (n < 0) ) throw InvalidInputException();
if ( !m && !n ) throw InvalidInputException();
if ( m && !n ) return m;
if ( !m && n ) return n;
return GCD_Euclidean_Recursive(n, m % n);
}
int GcdLcm::GCD_AlternateEuclidean_Iterative(int m, int n)
{
if ( (m < 0) || (n < 0) ) throw InvalidInputException();
if ( !m && !n ) throw InvalidInputException();
if ( m && !n ) return m;
if ( !m && n ) return n;
while ( m != n ) {
if ( m > n )
m = m - n;
else
n = n - m;
}
return m;
}
int GcdLcm::GCD_AlternateEuclidean_Recursive(int m, int n)
{
if ( (m < 0) || (n < 0) ) throw InvalidInputException();
if ( !m && !n ) throw InvalidInputException();
if ( m && !n ) return m;
if ( !m && n ) return n;
if ( m == n ) return m;
if ( m > n )
return GCD_AlternateEuclidean_Recursive(m - n, n);
else
return GCD_AlternateEuclidean_Recursive(m, n - m);
}
int GcdLcm::GCD_Binary_Iterative(int m, int n)
{
return 0;
}
/* Binary GCD algorithm (Credit: en.wikipedia.org/wiki/Binary_GCD_algorithm)
-----------------------------------------------
m n gcd
-----------------------------------------------
even even 2 * gcd( m/2, n/2 )
even odd gcd( m/2, n )
odd even gcd( m, n/2 )
odd odd m >= n then gcd( (m - n)/2, n )
m < n then gcd( (n - m)/2, m )
-----------------------------------------------
*/
int GcdLcm::GCD_Binary_Recursive(int m, int n)
{
if ( (m < 0) || (n < 0) ) throw InvalidInputException();
if ( !m && !n ) throw InvalidInputException();
if ( m && !n ) return m;
if ( !m && n ) return n;
if ( m == n ) return m;
bool m_even = ~m & 1;
bool n_even = ~n & 1;
if ( m_even && n_even )
return GCD_Binary_Recursive( m >> 1, n >> 1 ) << 1;
if ( m_even && !n_even )
return GCD_Binary_Recursive( m >> 1, n );
if ( !m_even && n_even )
return GCD_Binary_Recursive( m, n >> 1 );
if ( m >= n )
return GCD_Binary_Recursive( (m - n) >> 1, n );
else
return GCD_Binary_Recursive( (n - m) >> 1, m );
}
int GcdLcm::LCM_Iterative(int m, int n)
{
return 0;
}
int GcdLcm::LCM_Recursive(int m, int n)
{
return 0;
}
int GcdLcm::GCD_UsingLCM(int m, int n)
{
return 0;
}
int main()
{
GcdLcm gcdlcm;
int nums[13][2] = {{0,1}, {1,0}, {0,0}, {1,1}, {-1,1}, {1,-1}, {-1,-1}, {1,1}, {2,3}, {10,10}, {121,11}, {24,60}, {36253652,183728732}};
for ( size_t i = 0; i < 13; ++i ) {
try
{
cout << gcdlcm.GCD_Euclidean_Iterative(nums[i][0], nums[i][1]) << endl;
cout << gcdlcm.GCD_Euclidean_Recursive(nums[i][0], nums[i][1]) << endl;
cout << gcdlcm.GCD_AlternateEuclidean_Iterative(nums[i][0], nums[i][1]) << endl;
cout << gcdlcm.GCD_AlternateEuclidean_Recursive(nums[i][0], nums[i][1]) << endl;
cout << gcdlcm.GCD_Binary_Recursive(nums[i][0], nums[i][1]) << endl;
}
catch (CPPExceptions& e)
{
cout << e.message() << endl;
}
}
cout << "Press Enter to continue..." << endl;
cin.get();
return 0;
}<commit_msg>Implemented Binary GCD algorithm<commit_after>/*
The MIT License (MIT)
Copyright (c) 2013 rajendrauppal
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <iostream>
#include "Exceptions.h"
#include "GcdLcm.h"
using std::cout;
using std::cin;
using std::endl;
int GcdLcm::GCD_Euclidean_Iterative(int m, int n)
{
if ( (m < 0) || (n < 0) ) throw InvalidInputException();
if ( !m && !n ) throw InvalidInputException();
if ( m && !n ) return m;
if ( !m && n ) return n;
while ( n ) {
int temp = n;
n = m % n;
m = temp;
}
return m;
}
int GcdLcm::GCD_Euclidean_Recursive(int m, int n)
{
if ( (m < 0) || (n < 0) ) throw InvalidInputException();
if ( !m && !n ) throw InvalidInputException();
if ( m && !n ) return m;
if ( !m && n ) return n;
return GCD_Euclidean_Recursive(n, m % n);
}
int GcdLcm::GCD_AlternateEuclidean_Iterative(int m, int n)
{
if ( (m < 0) || (n < 0) ) throw InvalidInputException();
if ( !m && !n ) throw InvalidInputException();
if ( m && !n ) return m;
if ( !m && n ) return n;
while ( m != n ) {
if ( m > n )
m = m - n;
else
n = n - m;
}
return m;
}
int GcdLcm::GCD_AlternateEuclidean_Recursive(int m, int n)
{
if ( (m < 0) || (n < 0) ) throw InvalidInputException();
if ( !m && !n ) throw InvalidInputException();
if ( m && !n ) return m;
if ( !m && n ) return n;
if ( m == n ) return m;
if ( m > n )
return GCD_AlternateEuclidean_Recursive(m - n, n);
else
return GCD_AlternateEuclidean_Recursive(m, n - m);
}
int GcdLcm::GCD_Binary_Iterative(int m, int n)
{
return 0;
}
/* Binary GCD algorithm (Credit: en.wikipedia.org/wiki/Binary_GCD_algorithm)
-----------------------------------------------
m n gcd
-----------------------------------------------
even even 2 * gcd( m/2, n/2 )
even odd gcd( m/2, n )
odd even gcd( m, n/2 )
odd odd m >= n then gcd( (m - n)/2, n )
m < n then gcd( (n - m)/2, m )
-----------------------------------------------
*/
int GcdLcm::GCD_Binary_Recursive(int m, int n)
{
if ( (m < 0) || (n < 0) ) throw InvalidInputException();
if ( !m && !n ) throw InvalidInputException();
if ( m && !n ) return m;
if ( !m && n ) return n;
if ( m == n ) return m;
bool m_even = ~m & 1;
bool n_even = ~n & 1;
if ( m_even && n_even )
return GCD_Binary_Recursive( m >> 1, n >> 1 ) << 1;
if ( m_even && !n_even )
return GCD_Binary_Recursive( m >> 1, n );
if ( !m_even && n_even )
return GCD_Binary_Recursive( m, n >> 1 );
if ( m >= n )
return GCD_Binary_Recursive( (m - n) >> 1, n );
else
return GCD_Binary_Recursive( (n - m) >> 1, m );
}
int GcdLcm::LCM_Iterative(int m, int n)
{
return 0;
}
int GcdLcm::LCM_Recursive(int m, int n)
{
return 0;
}
int GcdLcm::GCD_UsingLCM(int m, int n)
{
return 0;
}
int main()
{
GcdLcm gcdlcm;
int nums[13][2] = {{0,1}, {1,0}, {0,0}, {1,1}, {-1,1}, {1,-1}, {-1,-1}, {1,1}, {2,3}, {10,10}, {121,11}, {24,60}, {36253652,183728732}};
for ( size_t i = 0; i < 13; ++i ) {
try
{
cout << gcdlcm.GCD_Euclidean_Iterative(nums[i][0], nums[i][1]) << endl;
cout << gcdlcm.GCD_Euclidean_Recursive(nums[i][0], nums[i][1]) << endl;
cout << gcdlcm.GCD_AlternateEuclidean_Iterative(nums[i][0], nums[i][1]) << endl;
cout << gcdlcm.GCD_AlternateEuclidean_Recursive(nums[i][0], nums[i][1]) << endl;
cout << gcdlcm.GCD_Binary_Recursive(nums[i][0], nums[i][1]) << endl;
}
catch (CPPExceptions& e)
{
cout << e.message() << endl;
}
}
cout << "Press Enter to continue..." << endl;
cin.get();
return 0;
}<|endoftext|>
|
<commit_before>// Scintilla source code edit control
// @file LexAU3.cxx
// Lexer for AutoIt3 http://www.hiddensoft.com/autoit3
// by Jos van der Zande, jvdzande@yahoo.com
//
// Changes:
//
// Copyright for Scintilla: 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
// Scintilla source code edit control
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
static inline bool IsTypeCharacter(const int ch)
{
return ch == '$';
}
static inline bool IsAWordChar(const int ch)
{
return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_' || ch == '-');
}
static inline bool IsAWordStart(const int ch)
{
return (ch < 0x80) && (isalnum(ch) || ch == '_' || ch == '@' || ch == '#' || ch == '{' || ch == '+' || ch == '!' || ch == '#' || ch == '^');
}
static void ColouriseAU3Doc(unsigned int startPos,
int length, int initStyle,
WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &keywords3 = *keywordlists[2];
WordList &keywords4 = *keywordlists[3];
styler.StartAt(startPos);
StyleContext sc(startPos, length, initStyle, styler);
char si,sk;
si=0;
sk=0;
for (; sc.More(); sc.Forward()) {
char s[100];
sc.GetCurrentLowered(s, sizeof(s));
switch (sc.state)
{
case SCE_AU3_COMMENTBLOCK:
{
if (sc.ch == '#') {sc.SetState(SCE_AU3_DEFAULT);}
break;
}
case SCE_AU3_COMMENT:
{
if (sc.atLineEnd) {sc.SetState(SCE_AU3_DEFAULT);}
break;
}
case SCE_AU3_OPERATOR:
{
sc.SetState(SCE_AU3_DEFAULT);
break;
}
case SCE_AU3_KEYWORD:
{
if (!IsAWordChar(sc.ch))
{
if (!IsTypeCharacter(sc.ch))
{
if (strcmp(s, "#cs")==0 || strcmp(s, "#comments_start")==0)
{
sc.ChangeState(SCE_AU3_COMMENTBLOCK);
sc.SetState(SCE_AU3_COMMENTBLOCK);
}
else if (strcmp(s, "#ce")==0 || strcmp(s, "#comments_end")==0)
{
sc.ChangeState(SCE_AU3_COMMENTBLOCK);
sc.SetState(SCE_AU3_DEFAULT);
}
else if (keywords.InList(s)) {
sc.ChangeState(SCE_AU3_KEYWORD);
sc.SetState(SCE_AU3_DEFAULT);
//sc.SetState(SCE_AU3_KEYWORD);
}
else if (keywords2.InList(s)) {
sc.ChangeState(SCE_AU3_FUNCTION);
sc.SetState(SCE_AU3_DEFAULT);
//sc.SetState(SCE_AU3_FUNCTION);
}
else if (keywords3.InList(s)) {
sc.ChangeState(SCE_AU3_MACRO);
sc.SetState(SCE_AU3_DEFAULT);
}
else if (!IsAWordChar(sc.ch)) {
sc.ChangeState(SCE_AU3_DEFAULT);
sc.SetState(SCE_AU3_DEFAULT);
}
}
}
if (sc.atLineEnd) {sc.SetState(SCE_AU3_DEFAULT);}
break;
}
case SCE_AU3_NUMBER:
{
if (!IsAWordChar(sc.ch)) {sc.SetState(SCE_AU3_DEFAULT);}
break;
}
case SCE_AU3_VARIABLE:
{
if (!IsAWordChar(sc.ch)) {sc.SetState(SCE_AU3_DEFAULT);}
break;
}
case SCE_AU3_STRING:
{
sk = 0;
// check for " in and single qouted string
if (si == 1){
if (sc.ch == '\"'){sc.ForwardSetState(SCE_AU3_DEFAULT);}}
// check for ' in and double qouted string
if (si == 2){
if (sc.ch == '\''){sc.ForwardSetState(SCE_AU3_DEFAULT);}}
if (sc.atLineEnd) {sc.SetState(SCE_AU3_DEFAULT);}
// find Sendkeys in an STRING
if (sc.ch == '{') {sc.SetState(SCE_AU3_SENT);}
if (sc.ch == '+' && sc.chNext == '{') {sc.SetState(SCE_AU3_SENT);}
if (sc.ch == '!' && sc.chNext == '{') {sc.SetState(SCE_AU3_SENT);}
if (sc.ch == '^' && sc.chNext == '{') {sc.SetState(SCE_AU3_SENT);}
if (sc.ch == '#' && sc.chNext == '{') {sc.SetState(SCE_AU3_SENT);}
break;
}
case SCE_AU3_SENT:
{
// Sent key string ended
if (sk == 1)
{
// set color to SENTKEY when valid sentkey .. else set to comment to show its wrong
if (keywords4.InList(s))
{
sc.ChangeState(SCE_AU3_SENT);
}
else
{
sc.ChangeState(SCE_AU3_STRING);
}
sc.SetState(SCE_AU3_STRING);
sk=0;
}
// check if next portion is again a sentkey
if (sc.atLineEnd) {sc.SetState(SCE_AU3_DEFAULT);}
if (sc.ch == '{') {sc.SetState(SCE_AU3_SENT);}
if (sc.ch == '+' && sc.chNext == '{') {sc.SetState(SCE_AU3_SENT);}
if (sc.ch == '!' && sc.chNext == '{') {sc.SetState(SCE_AU3_SENT);}
if (sc.ch == '^' && sc.chNext == '{') {sc.SetState(SCE_AU3_SENT);}
if (sc.ch == '#' && sc.chNext == '{') {sc.SetState(SCE_AU3_SENT);}
// check to see if the string ended...
// check for " in and single qouted string
if (si == 1){
if (sc.ch == '\"'){sc.ForwardSetState(SCE_AU3_DEFAULT);}}
// check for ' in and double qouted string
if (si == 2){
if (sc.ch == '\''){sc.ForwardSetState(SCE_AU3_DEFAULT);}}
break;
}
} //switch (sc.state)
// Determine if a new state should be entered:
if (sc.state == SCE_AU3_SENT)
{
if (sc.ch == '}' && sc.chNext != '}')
{
sk = 1;
}
}
if (sc.state == SCE_AU3_DEFAULT)
{
if (sc.ch == ';') {sc.SetState(SCE_AU3_COMMENT);}
else if (sc.ch == '#') {sc.SetState(SCE_AU3_KEYWORD);}
else if (IsAWordStart(sc.ch)) {sc.SetState(SCE_AU3_KEYWORD);}
else if (sc.ch == '@') {sc.SetState(SCE_AU3_KEYWORD);}
else if (sc.ch == '\"') {
sc.SetState(SCE_AU3_STRING);
si = 1; }
else if (sc.ch == '\'') {
sc.SetState(SCE_AU3_STRING);
si = 2; }
else if (sc.ch == '$') {sc.SetState(SCE_AU3_VARIABLE);}
else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {sc.SetState(SCE_AU3_NUMBER);}
//else if (IsAWordStart(sc.ch)) {sc.SetState(SCE_AU3_KEYWORD);}
else if (isoperator(static_cast<char>(sc.ch)) || (sc.ch == '\\')) {sc.SetState(SCE_AU3_OPERATOR);}
else if (sc.atLineEnd) {sc.SetState(SCE_AU3_DEFAULT);}
}
} //for (; sc.More(); sc.Forward())
sc.Complete();
}
//
static const char * const AU3WordLists[] = {
"#autoit keywords",
"#autoit functions",
"#autoit macros",
"#autoit Sent keys",
0
};
LexerModule lmAU3(SCLEX_AU3, ColouriseAU3Doc, "au3", NULL , AU3WordLists);
<commit_msg>Folder added by Jos.<commit_after>// Scintilla source code edit control
// @file LexAU3.cxx
// Lexer for AutoIt3 http://www.hiddensoft.com/autoit3
// by Jos van der Zande, jvdzande@yahoo.com
//
// Changes:
//
// Copyright for Scintilla: 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
// Scintilla source code edit control
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
static bool IsAU3Comment(Accessor &styler, int pos, int len) {
return len>0 && styler[pos]==';';
}
static inline bool IsTypeCharacter(const int ch)
{
return ch == '$';
}
static inline bool IsAWordChar(const int ch)
{
return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_' || ch == '-');
}
static inline bool IsAWordStart(const int ch)
{
return (ch < 0x80) && (isalnum(ch) || ch == '_' || ch == '@' || ch == '#' || ch == '{' || ch == '+' || ch == '!' || ch == '#' || ch == '^');
}
static void ColouriseAU3Doc(unsigned int startPos,
int length, int initStyle,
WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &keywords3 = *keywordlists[2];
WordList &keywords4 = *keywordlists[3];
styler.StartAt(startPos);
StyleContext sc(startPos, length, initStyle, styler);
char si,sk;
si=0;
sk=0;
for (; sc.More(); sc.Forward()) {
char s[100];
sc.GetCurrentLowered(s, sizeof(s));
switch (sc.state)
{
case SCE_AU3_COMMENTBLOCK:
{
if (sc.ch == '#') {sc.SetState(SCE_AU3_DEFAULT);}
break;
}
case SCE_AU3_COMMENT:
{
if (sc.atLineEnd) {sc.SetState(SCE_AU3_DEFAULT);}
break;
}
case SCE_AU3_OPERATOR:
{
sc.SetState(SCE_AU3_DEFAULT);
break;
}
case SCE_AU3_KEYWORD:
{
if (!IsAWordChar(sc.ch))
{
if (!IsTypeCharacter(sc.ch))
{
if (strcmp(s, "#cs")==0 || strcmp(s, "#comments_start")==0)
{
sc.ChangeState(SCE_AU3_COMMENTBLOCK);
sc.SetState(SCE_AU3_COMMENTBLOCK);
}
else if (strcmp(s, "#ce")==0 || strcmp(s, "#comments_end")==0)
{
sc.ChangeState(SCE_AU3_COMMENTBLOCK);
sc.SetState(SCE_AU3_DEFAULT);
}
else if (keywords.InList(s)) {
sc.ChangeState(SCE_AU3_KEYWORD);
sc.SetState(SCE_AU3_DEFAULT);
//sc.SetState(SCE_AU3_KEYWORD);
}
else if (keywords2.InList(s)) {
sc.ChangeState(SCE_AU3_FUNCTION);
sc.SetState(SCE_AU3_DEFAULT);
//sc.SetState(SCE_AU3_FUNCTION);
}
else if (keywords3.InList(s)) {
sc.ChangeState(SCE_AU3_MACRO);
sc.SetState(SCE_AU3_DEFAULT);
}
else if (!IsAWordChar(sc.ch)) {
sc.ChangeState(SCE_AU3_DEFAULT);
sc.SetState(SCE_AU3_DEFAULT);
}
}
}
if (sc.atLineEnd) {sc.SetState(SCE_AU3_DEFAULT);}
break;
}
case SCE_AU3_NUMBER:
{
if (!IsAWordChar(sc.ch)) {sc.SetState(SCE_AU3_DEFAULT);}
break;
}
case SCE_AU3_VARIABLE:
{
if (!IsAWordChar(sc.ch)) {sc.SetState(SCE_AU3_DEFAULT);}
break;
}
case SCE_AU3_STRING:
{
sk = 0;
// check for " in and single qouted string
if (si == 1){
if (sc.ch == '\"'){sc.ForwardSetState(SCE_AU3_DEFAULT);}}
// check for ' in and double qouted string
if (si == 2){
if (sc.ch == '\''){sc.ForwardSetState(SCE_AU3_DEFAULT);}}
if (sc.atLineEnd) {sc.SetState(SCE_AU3_DEFAULT);}
// find Sendkeys in an STRING
if (sc.ch == '{') {sc.SetState(SCE_AU3_SENT);}
if (sc.ch == '+' && sc.chNext == '{') {sc.SetState(SCE_AU3_SENT);}
if (sc.ch == '!' && sc.chNext == '{') {sc.SetState(SCE_AU3_SENT);}
if (sc.ch == '^' && sc.chNext == '{') {sc.SetState(SCE_AU3_SENT);}
if (sc.ch == '#' && sc.chNext == '{') {sc.SetState(SCE_AU3_SENT);}
break;
}
case SCE_AU3_SENT:
{
// Sent key string ended
if (sk == 1)
{
// set color to SENTKEY when valid sentkey .. else set to comment to show its wrong
if (keywords4.InList(s))
{
sc.ChangeState(SCE_AU3_SENT);
}
else
{
sc.ChangeState(SCE_AU3_STRING);
}
sc.SetState(SCE_AU3_STRING);
sk=0;
}
// check if next portion is again a sentkey
if (sc.atLineEnd) {sc.SetState(SCE_AU3_DEFAULT);}
if (sc.ch == '{') {sc.SetState(SCE_AU3_SENT);}
if (sc.ch == '+' && sc.chNext == '{') {sc.SetState(SCE_AU3_SENT);}
if (sc.ch == '!' && sc.chNext == '{') {sc.SetState(SCE_AU3_SENT);}
if (sc.ch == '^' && sc.chNext == '{') {sc.SetState(SCE_AU3_SENT);}
if (sc.ch == '#' && sc.chNext == '{') {sc.SetState(SCE_AU3_SENT);}
// check to see if the string ended...
// check for " in and single qouted string
if (si == 1){
if (sc.ch == '\"'){sc.ForwardSetState(SCE_AU3_DEFAULT);}}
// check for ' in and double qouted string
if (si == 2){
if (sc.ch == '\''){sc.ForwardSetState(SCE_AU3_DEFAULT);}}
break;
}
} //switch (sc.state)
// Determine if a new state should be entered:
if (sc.state == SCE_AU3_SENT)
{
if (sc.ch == '}' && sc.chNext != '}')
{
sk = 1;
}
}
if (sc.state == SCE_AU3_DEFAULT)
{
if (sc.ch == ';') {sc.SetState(SCE_AU3_COMMENT);}
else if (sc.ch == '#') {sc.SetState(SCE_AU3_KEYWORD);}
else if (IsAWordStart(sc.ch)) {sc.SetState(SCE_AU3_KEYWORD);}
else if (sc.ch == '@') {sc.SetState(SCE_AU3_KEYWORD);}
else if (sc.ch == '\"') {
sc.SetState(SCE_AU3_STRING);
si = 1; }
else if (sc.ch == '\'') {
sc.SetState(SCE_AU3_STRING);
si = 2; }
else if (sc.ch == '$') {sc.SetState(SCE_AU3_VARIABLE);}
else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {sc.SetState(SCE_AU3_NUMBER);}
//else if (IsAWordStart(sc.ch)) {sc.SetState(SCE_AU3_KEYWORD);}
else if (isoperator(static_cast<char>(sc.ch)) || (sc.ch == '\\')) {sc.SetState(SCE_AU3_OPERATOR);}
else if (sc.atLineEnd) {sc.SetState(SCE_AU3_DEFAULT);}
}
} //for (; sc.More(); sc.Forward())
sc.Complete();
}
//
//
static void FoldAU3Doc(unsigned int startPos, int length, int, WordList *[], Accessor &styler)
{
int endPos = startPos + length;
// Backtrack to previous line in case need to fix its fold status
int lineCurrent = styler.GetLine(startPos);
if (startPos > 0) {
if (lineCurrent > 0) {
lineCurrent--;
startPos = styler.LineStart(lineCurrent);
}
}
int spaceFlags = 0;
int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, IsAU3Comment);
char chNext = styler[startPos];
for (int i = startPos; i < endPos; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
if ((ch == '\r' && chNext != '\n') || (ch == '\n') || (i == endPos)) {
int lev = indentCurrent;
int indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags, IsAU3Comment);
if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG)) {
// Only non whitespace lines can be headers
if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK)) {
lev |= SC_FOLDLEVELHEADERFLAG;
} else if (indentNext & SC_FOLDLEVELWHITEFLAG) {
// Line after is blank so check the next - maybe should continue further?
int spaceFlags2 = 0;
int indentNext2 = styler.IndentAmount(lineCurrent + 2, &spaceFlags2, IsAU3Comment);
if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext2 & SC_FOLDLEVELNUMBERMASK)) {
lev |= SC_FOLDLEVELHEADERFLAG;
}
}
}
indentCurrent = indentNext;
styler.SetLevel(lineCurrent, lev);
lineCurrent++;
}
}
}
//
static const char * const AU3WordLists[] = {
"#autoit keywords",
"#autoit functions",
"#autoit macros",
"#autoit Sent keys",
0
};
LexerModule lmAU3(SCLEX_AU3, ColouriseAU3Doc, "au3", FoldAU3Doc , AU3WordLists);
<|endoftext|>
|
<commit_before>/* -*- indent-tabs-mode: nil -*- */
#include "client/http_log_client.h"
#include "log/cert.h"
#include "proto/ct.pb.h"
#include "proto/serializer.h"
#include "util/json_wrapper.h"
#include "util/util.h"
#include <curlpp/cURLpp.hpp>
#include <curlpp/Easy.hpp>
#include <curlpp/Options.hpp>
#include <glog/logging.h>
#include <sstream>
using std::string;
using std::ostringstream;
using ct::Cert;
using ct::CertChain;
void HTTPLogClient::BaseUrl(ostringstream *url) {
*url << "http://" << server_ << "/ct/v1/";
}
static HTTPLogClient::Status SendRequest(ostringstream *response,
curlpp::Easy *request,
const ostringstream &url) {
request->setOpt(new curlpp::options::Url(url.str()));
try {
*response << *request;
} catch(curlpp::LibcurlRuntimeError &e) {
if (e.what() == string("couldn't connect to host"))
return HTTPLogClient::CONNECT_FAILED;
LOG(ERROR) << "Caught curlpp::LibcurlRuntimeError: " << e.what();
return HTTPLogClient::UNKNOWN_ERROR;
}
return HTTPLogClient::OK;
}
HTTPLogClient::Status
HTTPLogClient::UploadSubmission(const std::string &submission, bool pre,
ct::SignedCertificateTimestamp *sct) {
CertChain chain(submission);
if (!chain.IsLoaded())
return INVALID_INPUT;
JsonArray jchain;
for (size_t n = 0; n < chain.Length(); ++n) {
string cert;
CHECK_EQ(Cert::TRUE, chain.CertAt(n)->DerEncoding(&cert));
jchain.Add(json_object_new_string(ToBase64(cert).c_str()));
}
json_object *jsend = json_object_new_object();
json_object_object_add(jsend, "chain", jchain.Extract());
const char *jsoned = json_object_to_json_string(jsend);
ostringstream url;
BaseUrl(&url);
url << "add-";
if (pre)
url << "pre-";
url << "chain";
curlpp::Easy request;
request.setOpt(new curlpp::options::PostFields(jsoned));
std::ostringstream response;
Status ret = SendRequest(&response, &request, url);
LOG(INFO) << "request = " << url.str();
LOG(INFO) << "body = " << jsoned;
LOG(INFO) << "response = " << response.str();
json_object_put(jsend);
if (ret != OK)
return ret;
JsonObject jresponse(json_tokener_parse(response.str().c_str()));
jsoned = jresponse.ToJson();
if (!jresponse.IsType(json_type_object)) {
LOG(ERROR) << "Expected a JSON object, got: " << response.str();
return BAD_RESPONSE;
}
JsonString id(jresponse, "id");
if (!id.Ok())
return BAD_RESPONSE;
sct->mutable_id()->set_key_id(id.FromBase64());
JsonInt timestamp(jresponse, "timestamp");
if (!timestamp.Ok())
return BAD_RESPONSE;
sct->set_timestamp(timestamp.Value());
JsonString extensions(jresponse, "extensions");
if (!extensions.Ok())
return BAD_RESPONSE;
sct->set_extension(extensions.FromBase64());
JsonString signature(jresponse, "signature");
if (!signature.Ok())
return BAD_RESPONSE;
if (Deserializer::DeserializeDigitallySigned(signature.FromBase64(),
sct->mutable_signature())
!= Deserializer::OK)
return BAD_RESPONSE;
sct->set_version(ct::V1);
return OK;
}
HTTPLogClient::Status
HTTPLogClient::QueryAuditProof(const string &merkle_leaf_hash,
ct::MerkleAuditProof *proof) {
ostringstream url;
BaseUrl(&url);
url << "get-sth";
curlpp::Easy request;
std::ostringstream response;
Status ret = SendRequest(&response, &request, url);
LOG(INFO) << "request = " << url.str();
LOG(INFO) << "response = " << response.str();
if (ret != OK)
return ret;
JsonObject jresponse(response);
JsonInt tree_size(jresponse, "tree_size");
if (!tree_size.Ok())
return BAD_RESPONSE;
proof->set_tree_size(tree_size.Value());
JsonInt timestamp(jresponse, "timestamp");
if (!timestamp.Ok())
return BAD_RESPONSE;
proof->set_timestamp(timestamp.Value());
JsonString tree_head_signature(jresponse, "tree_head_signature");
if (!tree_head_signature.Ok())
return BAD_RESPONSE;
string decoded = tree_head_signature.FromBase64();
if (Deserializer::DeserializeDigitallySigned(decoded,
proof->mutable_tree_head_signature()) != Deserializer::OK)
return BAD_RESPONSE;
ostringstream url2;
BaseUrl(&url2);
url2 << "get-proof-by-hash?hash="
<< curlpp::escape(ToBase64(merkle_leaf_hash))
<< "&tree_size=" << tree_size.Value();
curlpp::Easy request2;
std::ostringstream response2;
ret = SendRequest(&response2, &request2, url2);
LOG(INFO) << "request = " << url2.str();
LOG(INFO) << "response = " << response2.str();
if (ret != OK)
return ret;
JsonObject jresponse2(response2);
JsonInt leaf_index(jresponse2, "leaf_index");
if (!leaf_index.Ok())
return BAD_RESPONSE;
proof->set_leaf_index(leaf_index.Value());
JsonArray audit_path(jresponse2, "audit_path");
if (!audit_path.Ok())
return BAD_RESPONSE;
for (int n = 0; n < audit_path.Length(); ++n) {
JsonString path_node(audit_path, n);
CHECK(path_node.Ok());
proof->add_path_node(path_node.FromBase64());
}
proof->set_version(ct::V1);
return OK;
}
HTTPLogClient::Status HTTPLogClient::GetEntries(int first, int last,
std::vector<LogEntry> *entries) {
ostringstream url;
BaseUrl(&url);
url << "get-entries?start=" << first << "&end=" << last;
curlpp::Easy request;
std::ostringstream response;
Status ret = SendRequest(&response, &request, url);
LOG(INFO) << "request = " << url.str();
LOG(INFO) << "response = " << response.str();
if (ret != OK)
return ret;
JsonObject jresponse(response);
if (!jresponse.Ok())
return BAD_RESPONSE;
JsonArray jentries(jresponse, "entries");
if (!jentries.Ok())
return BAD_RESPONSE;
for (int n = 0; n < jentries.Length(); ++n) {
JsonObject entry(jentries, n);
if (!entry.Ok())
return BAD_RESPONSE;
JsonString leaf_input(entry, "leaf_input");
if (!leaf_input.Ok())
return BAD_RESPONSE;
LogEntry log_entry;
if (Deserializer::DeserializeMerkleTreeLeaf(leaf_input.FromBase64(),
&log_entry.leaf)
!= Deserializer::OK)
return BAD_RESPONSE;
JsonString extra_data(entry, "extra_data");
if (!extra_data.Ok())
return BAD_RESPONSE;
if (log_entry.leaf.timestamped_entry().entry_type() == ct::X509_ENTRY)
Deserializer::DeserializeX509Chain(extra_data.FromBase64(),
log_entry.entry.mutable_x509_entry());
else if (log_entry.leaf.timestamped_entry().entry_type()
== ct::PRECERT_ENTRY)
Deserializer::DeserializePrecertChainEntry(extra_data.FromBase64(),
log_entry.entry.mutable_precert_entry());
else
LOG(FATAL) << "Don't understand entry type: "
<< log_entry.leaf.timestamped_entry().entry_type();
entries->push_back(log_entry);
}
return OK;
}
<commit_msg>Remove unnecessary call to ToJson.<commit_after>/* -*- indent-tabs-mode: nil -*- */
#include "client/http_log_client.h"
#include "log/cert.h"
#include "proto/ct.pb.h"
#include "proto/serializer.h"
#include "util/json_wrapper.h"
#include "util/util.h"
#include <curlpp/cURLpp.hpp>
#include <curlpp/Easy.hpp>
#include <curlpp/Options.hpp>
#include <glog/logging.h>
#include <sstream>
using std::string;
using std::ostringstream;
using ct::Cert;
using ct::CertChain;
void HTTPLogClient::BaseUrl(ostringstream *url) {
*url << "http://" << server_ << "/ct/v1/";
}
static HTTPLogClient::Status SendRequest(ostringstream *response,
curlpp::Easy *request,
const ostringstream &url) {
request->setOpt(new curlpp::options::Url(url.str()));
try {
*response << *request;
} catch(curlpp::LibcurlRuntimeError &e) {
if (e.what() == string("couldn't connect to host"))
return HTTPLogClient::CONNECT_FAILED;
LOG(ERROR) << "Caught curlpp::LibcurlRuntimeError: " << e.what();
return HTTPLogClient::UNKNOWN_ERROR;
}
return HTTPLogClient::OK;
}
HTTPLogClient::Status
HTTPLogClient::UploadSubmission(const std::string &submission, bool pre,
ct::SignedCertificateTimestamp *sct) {
CertChain chain(submission);
if (!chain.IsLoaded())
return INVALID_INPUT;
JsonArray jchain;
for (size_t n = 0; n < chain.Length(); ++n) {
string cert;
CHECK_EQ(Cert::TRUE, chain.CertAt(n)->DerEncoding(&cert));
jchain.Add(json_object_new_string(ToBase64(cert).c_str()));
}
json_object *jsend = json_object_new_object();
json_object_object_add(jsend, "chain", jchain.Extract());
const char *jsoned = json_object_to_json_string(jsend);
ostringstream url;
BaseUrl(&url);
url << "add-";
if (pre)
url << "pre-";
url << "chain";
curlpp::Easy request;
request.setOpt(new curlpp::options::PostFields(jsoned));
std::ostringstream response;
Status ret = SendRequest(&response, &request, url);
LOG(INFO) << "request = " << url.str();
LOG(INFO) << "body = " << jsoned;
LOG(INFO) << "response = " << response.str();
json_object_put(jsend);
if (ret != OK)
return ret;
JsonObject jresponse(json_tokener_parse(response.str().c_str()));
if (!jresponse.IsType(json_type_object)) {
LOG(ERROR) << "Expected a JSON object, got: " << response.str();
return BAD_RESPONSE;
}
JsonString id(jresponse, "id");
if (!id.Ok())
return BAD_RESPONSE;
sct->mutable_id()->set_key_id(id.FromBase64());
JsonInt timestamp(jresponse, "timestamp");
if (!timestamp.Ok())
return BAD_RESPONSE;
sct->set_timestamp(timestamp.Value());
JsonString extensions(jresponse, "extensions");
if (!extensions.Ok())
return BAD_RESPONSE;
sct->set_extension(extensions.FromBase64());
JsonString signature(jresponse, "signature");
if (!signature.Ok())
return BAD_RESPONSE;
if (Deserializer::DeserializeDigitallySigned(signature.FromBase64(),
sct->mutable_signature())
!= Deserializer::OK)
return BAD_RESPONSE;
sct->set_version(ct::V1);
return OK;
}
HTTPLogClient::Status
HTTPLogClient::QueryAuditProof(const string &merkle_leaf_hash,
ct::MerkleAuditProof *proof) {
ostringstream url;
BaseUrl(&url);
url << "get-sth";
curlpp::Easy request;
std::ostringstream response;
Status ret = SendRequest(&response, &request, url);
LOG(INFO) << "request = " << url.str();
LOG(INFO) << "response = " << response.str();
if (ret != OK)
return ret;
JsonObject jresponse(response);
JsonInt tree_size(jresponse, "tree_size");
if (!tree_size.Ok())
return BAD_RESPONSE;
proof->set_tree_size(tree_size.Value());
JsonInt timestamp(jresponse, "timestamp");
if (!timestamp.Ok())
return BAD_RESPONSE;
proof->set_timestamp(timestamp.Value());
JsonString tree_head_signature(jresponse, "tree_head_signature");
if (!tree_head_signature.Ok())
return BAD_RESPONSE;
string decoded = tree_head_signature.FromBase64();
if (Deserializer::DeserializeDigitallySigned(decoded,
proof->mutable_tree_head_signature()) != Deserializer::OK)
return BAD_RESPONSE;
ostringstream url2;
BaseUrl(&url2);
url2 << "get-proof-by-hash?hash="
<< curlpp::escape(ToBase64(merkle_leaf_hash))
<< "&tree_size=" << tree_size.Value();
curlpp::Easy request2;
std::ostringstream response2;
ret = SendRequest(&response2, &request2, url2);
LOG(INFO) << "request = " << url2.str();
LOG(INFO) << "response = " << response2.str();
if (ret != OK)
return ret;
JsonObject jresponse2(response2);
JsonInt leaf_index(jresponse2, "leaf_index");
if (!leaf_index.Ok())
return BAD_RESPONSE;
proof->set_leaf_index(leaf_index.Value());
JsonArray audit_path(jresponse2, "audit_path");
if (!audit_path.Ok())
return BAD_RESPONSE;
for (int n = 0; n < audit_path.Length(); ++n) {
JsonString path_node(audit_path, n);
CHECK(path_node.Ok());
proof->add_path_node(path_node.FromBase64());
}
proof->set_version(ct::V1);
return OK;
}
HTTPLogClient::Status HTTPLogClient::GetEntries(int first, int last,
std::vector<LogEntry> *entries) {
ostringstream url;
BaseUrl(&url);
url << "get-entries?start=" << first << "&end=" << last;
curlpp::Easy request;
std::ostringstream response;
Status ret = SendRequest(&response, &request, url);
LOG(INFO) << "request = " << url.str();
LOG(INFO) << "response = " << response.str();
if (ret != OK)
return ret;
JsonObject jresponse(response);
if (!jresponse.Ok())
return BAD_RESPONSE;
JsonArray jentries(jresponse, "entries");
if (!jentries.Ok())
return BAD_RESPONSE;
for (int n = 0; n < jentries.Length(); ++n) {
JsonObject entry(jentries, n);
if (!entry.Ok())
return BAD_RESPONSE;
JsonString leaf_input(entry, "leaf_input");
if (!leaf_input.Ok())
return BAD_RESPONSE;
LogEntry log_entry;
if (Deserializer::DeserializeMerkleTreeLeaf(leaf_input.FromBase64(),
&log_entry.leaf)
!= Deserializer::OK)
return BAD_RESPONSE;
JsonString extra_data(entry, "extra_data");
if (!extra_data.Ok())
return BAD_RESPONSE;
if (log_entry.leaf.timestamped_entry().entry_type() == ct::X509_ENTRY)
Deserializer::DeserializeX509Chain(extra_data.FromBase64(),
log_entry.entry.mutable_x509_entry());
else if (log_entry.leaf.timestamped_entry().entry_type()
== ct::PRECERT_ENTRY)
Deserializer::DeserializePrecertChainEntry(extra_data.FromBase64(),
log_entry.entry.mutable_precert_entry());
else
LOG(FATAL) << "Don't understand entry type: "
<< log_entry.leaf.timestamped_entry().entry_type();
entries->push_back(log_entry);
}
return OK;
}
<|endoftext|>
|
<commit_before>/* bzflag
* Copyright (c) 1993 - 2008 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* interface header */
#include "CommandManager.h"
/* system implementation headers */
#include <ctype.h>
#include <stdio.h>
#include <assert.h>
#include <string>
/* common implementation headers */
#include "TextUtils.h"
// initialize the singleton
template <>
CommandManager* Singleton<CommandManager>::_instance = (CommandManager*)0;
CommandManager::CommandManager()
{
// do nothing
}
CommandManager::~CommandManager()
{
// do nothing
}
void CommandManager::add(const std::string& name,
CommandFunction func,
const std::string& help)
{
commands.erase(name);
CmdInfo info;
info.func = func;
info.help = help;
commands.insert(std::make_pair(name, info));
}
void CommandManager::remove(const std::string& name)
{
commands.erase(name);
}
std::string CommandManager::getHelp(const std::string& name) const
{
// look up command
Commands::const_iterator index = commands.find(name);
if (index == commands.end())
return "";
// return help string
return index->second.help;
}
std::string CommandManager::run(const std::string& name,
const ArgList& args, bool* ret) const
{
// look up command
Commands::const_iterator index = commands.find(name);
if (index == commands.end()) {
if (ret)
*ret = false;
return TextUtils::format("Command %s not found", name.c_str());
}
if (ret)
*ret = true;
// run it
return (*index->second.func)(name, args,ret);
}
std::string CommandManager::run(const std::string& cmd,bool *ret) const
{
std::string result;
const char* scan = cmd.c_str();
scan = skipWhitespace(scan);
while (scan != NULL && *scan != '\0') {
std::string name;
ArgList args;
// parse command name
scan = skipWhitespace(scan);
scan = readValue(scan, &name);
if (scan != NULL)
scan = skipWhitespace(scan);
// parse arguments
while (scan != NULL && *scan != '\0' && *scan != ';') {
std::string value;
scan = readValue(scan, &value);
if (scan != NULL) {
scan = skipWhitespace(scan);
args.push_back(value);
}
}
// run it or report error
if (scan == NULL) {
if (ret)
*ret = false;
return std::string("Error parsing command");
} else if (name[0] != '#') {
result = run(name, args, ret);
}
// discard ; and empty commands
while (scan != NULL && *scan == ';') {
++scan;
scan = skipWhitespace(scan);
}
}
// return result of last command only
return result;
}
void CommandManager::iterate(Callback callback,
void* userData) const
{
assert(callback != NULL);
for (Commands::const_iterator index = commands.begin();
index != commands.end(); ++index)
(*callback)(index->first, userData);
}
const char* CommandManager::readValue(const char* string,
std::string* value)
{
if (*string == '\"')
return readQuoted(string + 1, value);
else if (*string != '\0')
return readUnquoted(string, value);
else
return string;
}
const char* CommandManager::readUnquoted(const char* string,
std::string* value)
{
// read up to next whitespace. escapes are not interpreted.
const char* start = string;
while (*string != '\0' && !isspace(*string) && *string != ';')
++string;
*value = std::string(start, string - start);
return string;
}
const char* CommandManager::readQuoted(const char* string,
std::string* value)
{
*value = "";
bool escaped = false;
for (; *string != '\0'; ++string) {
if (escaped) {
switch (*string) {
case 't': value->append("\t", 1); break;
case 'n': value->append("\n", 1); break;
case 'r': value->append("\r", 1); break;
case '\\': value->append("\\", 1); break;
case '\"': value->append("\"", 1); break;
default: value->append(string, 1); break;
}
escaped = false;
} else if (*string == '\\') {
escaped = true;
} else if (*string == '\"') {
return string + 1;
} else {
value->append(string, 1);
}
}
// closing quote is missing. if escaped is true the called may have
// wanted to continue the line but we don't allow that.
return NULL;
}
const char* CommandManager::skipWhitespace(const char* string)
{
while (*string != '\0' && isspace(*string))
++string;
return string;
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>make windows not choke on UTF8 sequences in the client config file. since we aren't actually doing anything with the characters this routine doesn't actually need to be multibyte-aware.<commit_after>/* bzflag
* Copyright (c) 1993 - 2008 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* interface header */
#include "CommandManager.h"
/* system implementation headers */
#include <ctype.h>
#include <wctype.h>
#include <stdio.h>
#include <assert.h>
#include <string>
/* common implementation headers */
#include "TextUtils.h"
// initialize the singleton
template <>
CommandManager* Singleton<CommandManager>::_instance = (CommandManager*)0;
CommandManager::CommandManager()
{
// do nothing
}
CommandManager::~CommandManager()
{
// do nothing
}
void CommandManager::add(const std::string& name,
CommandFunction func,
const std::string& help)
{
commands.erase(name);
CmdInfo info;
info.func = func;
info.help = help;
commands.insert(std::make_pair(name, info));
}
void CommandManager::remove(const std::string& name)
{
commands.erase(name);
}
std::string CommandManager::getHelp(const std::string& name) const
{
// look up command
Commands::const_iterator index = commands.find(name);
if (index == commands.end())
return "";
// return help string
return index->second.help;
}
std::string CommandManager::run(const std::string& name,
const ArgList& args, bool* ret) const
{
// look up command
Commands::const_iterator index = commands.find(name);
if (index == commands.end()) {
if (ret)
*ret = false;
return TextUtils::format("Command %s not found", name.c_str());
}
if (ret)
*ret = true;
// run it
return (*index->second.func)(name, args,ret);
}
std::string CommandManager::run(const std::string& cmd,bool *ret) const
{
std::string result;
const char* scan = cmd.c_str();
scan = skipWhitespace(scan);
while (scan != NULL && *scan != '\0') {
std::string name;
ArgList args;
// parse command name
scan = skipWhitespace(scan);
scan = readValue(scan, &name);
if (scan != NULL)
scan = skipWhitespace(scan);
// parse arguments
while (scan != NULL && *scan != '\0' && *scan != ';') {
std::string value;
scan = readValue(scan, &value);
if (scan != NULL) {
scan = skipWhitespace(scan);
args.push_back(value);
}
}
// run it or report error
if (scan == NULL) {
if (ret)
*ret = false;
return std::string("Error parsing command");
} else if (name[0] != '#') {
result = run(name, args, ret);
}
// discard ; and empty commands
while (scan != NULL && *scan == ';') {
++scan;
scan = skipWhitespace(scan);
}
}
// return result of last command only
return result;
}
void CommandManager::iterate(Callback callback,
void* userData) const
{
assert(callback != NULL);
for (Commands::const_iterator index = commands.begin();
index != commands.end(); ++index)
(*callback)(index->first, userData);
}
const char* CommandManager::readValue(const char* string,
std::string* value)
{
if (*string == '\"')
return readQuoted(string + 1, value);
else if (*string != '\0')
return readUnquoted(string, value);
else
return string;
}
const char* CommandManager::readUnquoted(const char* string,
std::string* value)
{
// read up to next whitespace. escapes are not interpreted.
const char* start = string;
while (*string != '\0' && !iswspace(*string) && *string != ';')
++string;
*value = std::string(start, string - start);
return string;
}
const char* CommandManager::readQuoted(const char* string,
std::string* value)
{
*value = "";
bool escaped = false;
for (; *string != '\0'; ++string) {
if (escaped) {
switch (*string) {
case 't': value->append("\t", 1); break;
case 'n': value->append("\n", 1); break;
case 'r': value->append("\r", 1); break;
case '\\': value->append("\\", 1); break;
case '\"': value->append("\"", 1); break;
default: value->append(string, 1); break;
}
escaped = false;
} else if (*string == '\\') {
escaped = true;
} else if (*string == '\"') {
return string + 1;
} else {
value->append(string, 1);
}
}
// closing quote is missing. if escaped is true the called may have
// wanted to continue the line but we don't allow that.
return NULL;
}
const char* CommandManager::skipWhitespace(const char* string)
{
while (*string != '\0' && isspace(*string))
++string;
return string;
}
// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>
|
<commit_before>#pragma once
#include "Application.hpp"
#include "common/NetworkManager.hpp"
#include "common/NetworkRequester.hpp"
#include "common/NetworkWorker.hpp"
#include "singletons/Paths.hpp"
#include <rapidjson/document.h>
#include <rapidjson/error/en.h>
#include <QCryptographicHash>
#include <QFile>
namespace chatterino {
static QJsonObject parseJSONFromData(const QByteArray &data)
{
QJsonDocument jsonDoc(QJsonDocument::fromJson(data));
if (jsonDoc.isNull()) {
return QJsonObject();
}
return jsonDoc.object();
}
static rapidjson::Document parseJSONFromData2(const QByteArray &data)
{
rapidjson::Document ret(rapidjson::kNullType);
rapidjson::ParseResult result = ret.Parse(data.data(), data.length());
if (result.Code() != rapidjson::kParseErrorNone) {
Log("JSON parse error: {} ({})", rapidjson::GetParseError_En(result.Code()),
result.Offset());
return ret;
}
return ret;
}
static rapidjson::Document parseJSONFromReply2(QNetworkReply *reply)
{
rapidjson::Document ret(rapidjson::kNullType);
if (reply->error() != QNetworkReply::NetworkError::NoError) {
return ret;
}
QByteArray data = reply->readAll();
rapidjson::ParseResult result = ret.Parse(data.data(), data.length());
if (result.Code() != rapidjson::kParseErrorNone) {
Log("JSON parse error: {} ({})", rapidjson::GetParseError_En(result.Code()),
result.Offset());
return ret;
}
return ret;
}
class NetworkRequest
{
public:
enum RequestType {
GetRequest,
PostRequest,
PutRequest,
DeleteRequest,
};
private:
struct Data {
QNetworkRequest request;
const QObject *caller = nullptr;
std::function<void(QNetworkReply *)> onReplyCreated;
int timeoutMS = -1;
bool useQuickLoadCache = false;
std::function<bool(int)> onError;
std::function<bool(const rapidjson::Document &)> onSuccess;
NetworkRequest::RequestType requestType;
QByteArray payload;
QString getHash()
{
if (this->hash.isEmpty()) {
QByteArray bytes;
bytes.append(this->request.url().toString());
for (const auto &header : this->request.rawHeaderList()) {
bytes.append(header);
}
QByteArray hashBytes(QCryptographicHash::hash(bytes, QCryptographicHash::Sha256));
this->hash = hashBytes.toHex();
}
return this->hash;
}
void writeToCache(const QByteArray &bytes);
private:
QString hash;
} data;
public:
NetworkRequest() = delete;
explicit NetworkRequest(const char *url);
explicit NetworkRequest(const std::string &url);
explicit NetworkRequest(const QString &url);
NetworkRequest(QUrl url);
void setRequestType(RequestType newRequestType);
template <typename Func>
void onError(Func cb)
{
this->data.onError = cb;
}
template <typename Func>
void onSuccess(Func cb)
{
this->data.onSuccess = cb;
}
void setPayload(const QByteArray &payload)
{
this->data.payload = payload;
}
void setUseQuickLoadCache(bool value);
void setCaller(const QObject *caller);
void setOnReplyCreated(std::function<void(QNetworkReply *)> f);
void setRawHeader(const char *headerName, const char *value);
void setRawHeader(const char *headerName, const QByteArray &value);
void setRawHeader(const char *headerName, const QString &value);
void setTimeout(int ms);
void makeAuthorizedV5(const QString &clientID, const QString &oauthToken = QString());
template <typename FinishedCallback>
void get(FinishedCallback onFinished)
{
if (this->data.useQuickLoadCache) {
auto app = getApp();
QFile cachedFile(app->paths->cacheDirectory + "/" + this->data.getHash());
if (cachedFile.exists()) {
if (cachedFile.open(QIODevice::ReadOnly)) {
QByteArray bytes = cachedFile.readAll();
// qDebug() << "Loaded cached resource" << this->data.request.url();
bool success = onFinished(bytes);
cachedFile.close();
if (!success) {
// The images were not successfully loaded from the file
// XXX: Invalidate the cache file so we don't attempt to load it again next
// time
}
}
}
}
QTimer *timer = nullptr;
if (this->data.timeoutMS > 0) {
timer = new QTimer;
}
NetworkRequester requester;
NetworkWorker *worker = new NetworkWorker;
worker->moveToThread(&NetworkManager::workerThread);
if (this->data.caller != nullptr) {
QObject::connect(worker, &NetworkWorker::doneUrl, this->data.caller,
[onFinished, data = this->data](auto reply) mutable {
if (reply->error() != QNetworkReply::NetworkError::NoError) {
if (data.onError) {
data.onError(reply->error());
}
return;
}
QByteArray readBytes = reply->readAll();
QByteArray bytes;
bytes.setRawData(readBytes.data(), readBytes.size());
data.writeToCache(bytes);
onFinished(bytes);
reply->deleteLater();
});
}
if (timer != nullptr) {
timer->start(this->data.timeoutMS);
}
QObject::connect(
&requester, &NetworkRequester::requestUrl, worker,
[timer, data = std::move(this->data), worker, onFinished{std::move(onFinished)}]() {
QNetworkReply *reply = NetworkManager::NaM.get(data.request);
if (timer != nullptr) {
QObject::connect(timer, &QTimer::timeout, worker, [reply, timer]() {
Log("Aborted!");
reply->abort();
timer->deleteLater();
});
}
if (data.onReplyCreated) {
data.onReplyCreated(reply);
}
QObject::connect(reply, &QNetworkReply::finished, worker,
[data = std::move(data), worker, reply,
onFinished = std::move(onFinished)]() mutable {
if (data.caller == nullptr) {
QByteArray bytes = reply->readAll();
data.writeToCache(bytes);
onFinished(bytes);
reply->deleteLater();
} else {
emit worker->doneUrl(reply);
}
delete worker;
});
});
emit requester.requestUrl();
}
template <typename FinishedCallback>
void getJSON(FinishedCallback onFinished)
{
this->get([onFinished{std::move(onFinished)}](const QByteArray &bytes) -> bool {
auto object = parseJSONFromData(bytes);
onFinished(object);
// XXX: Maybe return onFinished? For now I don't want to force onFinished to have a
// return value
return true;
});
}
void execute();
private:
void useCache();
void doRequest();
void executeGet();
void executePut();
void executeDelete();
};
} // namespace chatterino
<commit_msg>Remove unused parseJSONFromReply2 function<commit_after>#pragma once
#include "Application.hpp"
#include "common/NetworkManager.hpp"
#include "common/NetworkRequester.hpp"
#include "common/NetworkWorker.hpp"
#include "singletons/Paths.hpp"
#include <rapidjson/document.h>
#include <rapidjson/error/en.h>
#include <QCryptographicHash>
#include <QFile>
namespace chatterino {
static QJsonObject parseJSONFromData(const QByteArray &data)
{
QJsonDocument jsonDoc(QJsonDocument::fromJson(data));
if (jsonDoc.isNull()) {
return QJsonObject();
}
return jsonDoc.object();
}
static rapidjson::Document parseJSONFromData2(const QByteArray &data)
{
rapidjson::Document ret(rapidjson::kNullType);
rapidjson::ParseResult result = ret.Parse(data.data(), data.length());
if (result.Code() != rapidjson::kParseErrorNone) {
Log("JSON parse error: {} ({})", rapidjson::GetParseError_En(result.Code()),
result.Offset());
return ret;
}
return ret;
}
class NetworkRequest
{
public:
enum RequestType {
GetRequest,
PostRequest,
PutRequest,
DeleteRequest,
};
private:
struct Data {
QNetworkRequest request;
const QObject *caller = nullptr;
std::function<void(QNetworkReply *)> onReplyCreated;
int timeoutMS = -1;
bool useQuickLoadCache = false;
std::function<bool(int)> onError;
std::function<bool(const rapidjson::Document &)> onSuccess;
NetworkRequest::RequestType requestType;
QByteArray payload;
QString getHash()
{
if (this->hash.isEmpty()) {
QByteArray bytes;
bytes.append(this->request.url().toString());
for (const auto &header : this->request.rawHeaderList()) {
bytes.append(header);
}
QByteArray hashBytes(QCryptographicHash::hash(bytes, QCryptographicHash::Sha256));
this->hash = hashBytes.toHex();
}
return this->hash;
}
void writeToCache(const QByteArray &bytes);
private:
QString hash;
} data;
public:
NetworkRequest() = delete;
explicit NetworkRequest(const char *url);
explicit NetworkRequest(const std::string &url);
explicit NetworkRequest(const QString &url);
NetworkRequest(QUrl url);
void setRequestType(RequestType newRequestType);
template <typename Func>
void onError(Func cb)
{
this->data.onError = cb;
}
template <typename Func>
void onSuccess(Func cb)
{
this->data.onSuccess = cb;
}
void setPayload(const QByteArray &payload)
{
this->data.payload = payload;
}
void setUseQuickLoadCache(bool value);
void setCaller(const QObject *caller);
void setOnReplyCreated(std::function<void(QNetworkReply *)> f);
void setRawHeader(const char *headerName, const char *value);
void setRawHeader(const char *headerName, const QByteArray &value);
void setRawHeader(const char *headerName, const QString &value);
void setTimeout(int ms);
void makeAuthorizedV5(const QString &clientID, const QString &oauthToken = QString());
template <typename FinishedCallback>
void get(FinishedCallback onFinished)
{
if (this->data.useQuickLoadCache) {
auto app = getApp();
QFile cachedFile(app->paths->cacheDirectory + "/" + this->data.getHash());
if (cachedFile.exists()) {
if (cachedFile.open(QIODevice::ReadOnly)) {
QByteArray bytes = cachedFile.readAll();
// qDebug() << "Loaded cached resource" << this->data.request.url();
bool success = onFinished(bytes);
cachedFile.close();
if (!success) {
// The images were not successfully loaded from the file
// XXX: Invalidate the cache file so we don't attempt to load it again next
// time
}
}
}
}
QTimer *timer = nullptr;
if (this->data.timeoutMS > 0) {
timer = new QTimer;
}
NetworkRequester requester;
NetworkWorker *worker = new NetworkWorker;
worker->moveToThread(&NetworkManager::workerThread);
if (this->data.caller != nullptr) {
QObject::connect(worker, &NetworkWorker::doneUrl, this->data.caller,
[onFinished, data = this->data](auto reply) mutable {
if (reply->error() != QNetworkReply::NetworkError::NoError) {
if (data.onError) {
data.onError(reply->error());
}
return;
}
QByteArray readBytes = reply->readAll();
QByteArray bytes;
bytes.setRawData(readBytes.data(), readBytes.size());
data.writeToCache(bytes);
onFinished(bytes);
reply->deleteLater();
});
}
if (timer != nullptr) {
timer->start(this->data.timeoutMS);
}
QObject::connect(
&requester, &NetworkRequester::requestUrl, worker,
[timer, data = std::move(this->data), worker, onFinished{std::move(onFinished)}]() {
QNetworkReply *reply = NetworkManager::NaM.get(data.request);
if (timer != nullptr) {
QObject::connect(timer, &QTimer::timeout, worker, [reply, timer]() {
Log("Aborted!");
reply->abort();
timer->deleteLater();
});
}
if (data.onReplyCreated) {
data.onReplyCreated(reply);
}
QObject::connect(reply, &QNetworkReply::finished, worker,
[data = std::move(data), worker, reply,
onFinished = std::move(onFinished)]() mutable {
if (data.caller == nullptr) {
QByteArray bytes = reply->readAll();
data.writeToCache(bytes);
onFinished(bytes);
reply->deleteLater();
} else {
emit worker->doneUrl(reply);
}
delete worker;
});
});
emit requester.requestUrl();
}
template <typename FinishedCallback>
void getJSON(FinishedCallback onFinished)
{
this->get([onFinished{std::move(onFinished)}](const QByteArray &bytes) -> bool {
auto object = parseJSONFromData(bytes);
onFinished(object);
// XXX: Maybe return onFinished? For now I don't want to force onFinished to have a
// return value
return true;
});
}
void execute();
private:
void useCache();
void doRequest();
void executeGet();
void executePut();
void executeDelete();
};
} // namespace chatterino
<|endoftext|>
|
<commit_before>/*
* HyPerConnection.hpp
*
* Created on: Oct 21, 2008
* Author: rasmussn
*/
#ifndef HYPERCONN_HPP_
#define HYPERCONN_HPP_
#include "PVConnection.h"
#include "../columns/InterColComm.hpp"
#include "../include/pv_types.h"
#include "../io/PVParams.hpp"
#include "../layers/HyPerLayer.hpp"
#define PROTECTED_NUMBER 13
#define MAX_ARBOR_LIST (1+MAX_NEIGHBORS)
namespace PV {
class HyPerCol;
class HyPerLayer;
class ConnectionProbe;
/**
* A PVConnection identifies a connection between two layers
*/
typedef struct {
int delay; // current output delay in the associated f ring buffer (should equal fixed delay + varible delay for valid connection)
int fixDelay; // fixed output delay. TODO: should be float
int varDelayMin; // minimum variable conduction delay
int varDelayMax; // maximum variable conduction delay
int numDelay;
int isGraded; //==1, release is stochastic with prob = (activity <= 1), default is 0 (no graded release)
float vel; // conduction velocity in position units (pixels) per time step--added by GTK
float rmin; // minimum connection distance
float rmax; // maximum connection distance
} PVConnParams;
class HyPerConn {
friend class HyPerCol;
public:
HyPerConn();
HyPerConn(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post,
int channel);
HyPerConn(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post,
int channel, const char * filename);
virtual ~HyPerConn();
virtual int deliver(Publisher * pub, PVLayerCube * cube, int neighbor);
virtual int insertProbe(ConnectionProbe * p);
virtual int outputState(float time, bool last=false);
virtual int updateState(float time, float dt);
virtual int updateWeights(int axonId);
inline int numberOfAxonalArborLists() {return numAxonalArborLists;}
virtual int numWeightPatches(int arbor);
virtual int numDataPatches(int arbor);
virtual int writeWeights(float time, bool last=false);
virtual int writeWeights(PVPatch ** patches, int numPatches,
const char * filename, float time, bool last);
virtual int writeTextWeights(const char * filename, int k);
virtual int writePostSynapticWeights(float time, bool last=false);
int readWeights(const char * filename);
virtual PVPatch ** readWeights(PVPatch ** patches, int numPatches,
const char * filename);
virtual PVPatch * getWeights(int kPre, int arbor);
virtual PVPatch * getPlasticityIncrement(int k, int arbor);
inline PVLayerCube * getPlasticityDecrement() {return pDecr;}
inline PVPatch ** weights(int neighbor) {return wPatches[neighbor];}
inline const char * getName() {return name;}
inline int getDelay() {return params->delay;}
inline float minWeight() {return 0.0;}
inline float maxWeight() {return wMax;}
inline PVAxonalArbor * axonalArbor(int kPre, int neighbor)
{return &axonalArborList[neighbor][kPre];}
HyPerLayer * preSynapticLayer() {return pre;}
HyPerLayer * postSynapticLayer() {return post;}
int getConnectionId() {return connId;}
void setConnectionId(int id) {connId = id;}
int setParams(PVParams * params, PVConnParams * p);
PVPatch ** convertPreSynapticWeights(float time);
int preSynapticPatchHead(int kxPost, int kyPost, int kfPost, int * kxPre, int * kyPre);
int postSynapticPatchHead(int kPre,
int * kxPostOut, int * kyPostOut, int * kfPostOut,
int * dxOut, int * dyOut, int * nxpOut, int * nypOut);
int gauss2DCalcWeights(PVPatch * wp, int kPre, int noPost,
int numFlanks, float shift, float rotate, float aspect, float sigma,
float r2Max, float strength);
PVPatch ** normalizeWeights(PVPatch ** patches, int numPatches);
virtual int kernelIndexToPatchIndex(int kernelIndex);
virtual int patchIndexToKernelIndex(int patchIndex);
protected:
HyPerLayer * pre;
HyPerLayer * post;
HyPerCol * parent;
PVLayerCube * pDecr; // plasticity decrement variable (Mi) for pre-synaptic layer
PVPatch ** pIncr; // list of stdp patches Psij variable
PVPatch ** wPatches[MAX_ARBOR_LIST]; // list of weight patches, one set per neighbor
PVPatch ** wPostPatches; // post-synaptic linkage of weights
PVAxonalArbor * axonalArborList[MAX_ARBOR_LIST]; // list of axonal arbors for each neighbor
int channel; // which channel of the post to update (e.g. inhibit)
int connId; // connection id
char * name;
int nxp, nyp, nfp; // size of weight dimensions
int numParams;
PVConnParams * params;
int numAxonalArborLists; // number of axonal arbors (weight patches) for presynaptic layer
// STDP parameters for modifying weights
float ampLTP; // long term potentiation amplitude
float ampLTD; // long term depression amplitude
float tauLTP;
float tauLTD;
float dWMax;
float wMax;
float wMin;
int numProbes;
ConnectionProbe ** probes; // probes used to output data
bool stdpFlag; // presence of spike timing dependent plasticity
bool ioAppend; // controls opening of binary files
float wPostTime; // time of last conversion to wPostPatches
float writeTime; // time of next output
float writeStep; // output time interval
protected:
int setPatchSize(const char * filename);
int initialize(const char * name, HyPerCol * hc,
HyPerLayer * pre, HyPerLayer * post, int channel, const char * filename);
int initialize(const char * name, HyPerCol * hc,
HyPerLayer * pre, HyPerLayer * post, int channel);
int initialize_base();
int initialize(const char * filename);
int initializeSTDP();
virtual PVPatch ** initializeWeights(PVPatch ** patches, int numPatches,
const char * filename);
PVPatch ** initializeRandomWeights(PVPatch ** patches, int numPatches, int seed);
PVPatch ** initializeSmartWeights(PVPatch ** patches, int numPatches);
virtual PVPatch ** initializeDefaultWeights(PVPatch ** patches, int numPatches);
PVPatch ** initializeGaussianWeights(PVPatch ** patches, int numPatches);
virtual PVPatch ** createWeights(PVPatch ** patches, int nPatches, int nxPatch,
int nyPatch, int nfPatch);
PVPatch ** createWeights(PVPatch ** patches);
virtual PVPatch ** allocWeights(PVPatch ** patches, int nPatches, int nxPatch,
int nyPatch, int nfPatch);
PVPatch ** allocWeights(PVPatch ** patches);
int uniformWeights(PVPatch * wp, float wMin, float wMax, int * seed);
int gaussianWeights(PVPatch * wp, float mean, float stdev, int * seed);
int smartWeights(PVPatch * wp, int k);
virtual int checkPVPFileHeader(const PVLayerLoc * loc, int params[], int numParams);
virtual int checkWeightsHeader(const char * filename, int wgtParams[]);
virtual int deleteWeights();
virtual int createAxonalArbors();
// static member functions
public:
static PVPatch ** createPatches(int numBundles, int nx, int ny, int nf)
{
PVPatch ** patches = (PVPatch**) malloc(numBundles*sizeof(PVPatch*));
for (int i = 0; i < numBundles; i++) {
patches[i] = pvpatch_inplace_new(nx, ny, nf);
}
return patches;
}
static int deletePatches(int numBundles, PVPatch ** patches)
{
for (int i = 0; i < numBundles; i++) {
pvpatch_inplace_delete(patches[i]);
}
free(patches);
return 0;
}
};
} // namespace PV
#endif /* HYPERCONN_HPP_ */
<commit_msg>made methods wmin and mwax virtual to allow kernelConn subclass to override<commit_after>/*
* HyPerConnection.hpp
*
* Created on: Oct 21, 2008
* Author: rasmussn
*/
#ifndef HYPERCONN_HPP_
#define HYPERCONN_HPP_
#include "PVConnection.h"
#include "../columns/InterColComm.hpp"
#include "../include/pv_types.h"
#include "../io/PVParams.hpp"
#include "../layers/HyPerLayer.hpp"
#define PROTECTED_NUMBER 13
#define MAX_ARBOR_LIST (1+MAX_NEIGHBORS)
namespace PV {
class HyPerCol;
class HyPerLayer;
class ConnectionProbe;
/**
* A PVConnection identifies a connection between two layers
*/
typedef struct {
int delay; // current output delay in the associated f ring buffer (should equal fixed delay + varible delay for valid connection)
int fixDelay; // fixed output delay. TODO: should be float
int varDelayMin; // minimum variable conduction delay
int varDelayMax; // maximum variable conduction delay
int numDelay;
int isGraded; //==1, release is stochastic with prob = (activity <= 1), default is 0 (no graded release)
float vel; // conduction velocity in position units (pixels) per time step--added by GTK
float rmin; // minimum connection distance
float rmax; // maximum connection distance
} PVConnParams;
class HyPerConn {
friend class HyPerCol;
public:
HyPerConn();
HyPerConn(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post,
int channel);
HyPerConn(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post,
int channel, const char * filename);
virtual ~HyPerConn();
virtual int deliver(Publisher * pub, PVLayerCube * cube, int neighbor);
virtual int insertProbe(ConnectionProbe * p);
virtual int outputState(float time, bool last=false);
virtual int updateState(float time, float dt);
virtual int updateWeights(int axonId);
inline int numberOfAxonalArborLists() {return numAxonalArborLists;}
virtual int numWeightPatches(int arbor);
virtual int numDataPatches(int arbor);
virtual int writeWeights(float time, bool last=false);
virtual int writeWeights(PVPatch ** patches, int numPatches,
const char * filename, float time, bool last);
virtual int writeTextWeights(const char * filename, int k);
virtual int writePostSynapticWeights(float time, bool last=false);
int readWeights(const char * filename);
virtual PVPatch ** readWeights(PVPatch ** patches, int numPatches,
const char * filename);
virtual PVPatch * getWeights(int kPre, int arbor);
virtual PVPatch * getPlasticityIncrement(int k, int arbor);
inline PVLayerCube * getPlasticityDecrement() {return pDecr;}
inline PVPatch ** weights(int neighbor) {return wPatches[neighbor];}
inline const char * getName() {return name;}
inline int getDelay() {return params->delay;}
virtual float minWeight() {return 0.0;}
virtual float maxWeight() {return wMax;}
inline PVAxonalArbor * axonalArbor(int kPre, int neighbor)
{return &axonalArborList[neighbor][kPre];}
HyPerLayer * preSynapticLayer() {return pre;}
HyPerLayer * postSynapticLayer() {return post;}
int getConnectionId() {return connId;}
void setConnectionId(int id) {connId = id;}
int setParams(PVParams * params, PVConnParams * p);
PVPatch ** convertPreSynapticWeights(float time);
int preSynapticPatchHead(int kxPost, int kyPost, int kfPost, int * kxPre, int * kyPre);
int postSynapticPatchHead(int kPre,
int * kxPostOut, int * kyPostOut, int * kfPostOut,
int * dxOut, int * dyOut, int * nxpOut, int * nypOut);
int gauss2DCalcWeights(PVPatch * wp, int kPre, int noPost,
int numFlanks, float shift, float rotate, float aspect, float sigma,
float r2Max, float strength);
PVPatch ** normalizeWeights(PVPatch ** patches, int numPatches);
virtual int kernelIndexToPatchIndex(int kernelIndex);
virtual int patchIndexToKernelIndex(int patchIndex);
protected:
HyPerLayer * pre;
HyPerLayer * post;
HyPerCol * parent;
PVLayerCube * pDecr; // plasticity decrement variable (Mi) for pre-synaptic layer
PVPatch ** pIncr; // list of stdp patches Psij variable
PVPatch ** wPatches[MAX_ARBOR_LIST]; // list of weight patches, one set per neighbor
PVPatch ** wPostPatches; // post-synaptic linkage of weights
PVAxonalArbor * axonalArborList[MAX_ARBOR_LIST]; // list of axonal arbors for each neighbor
int channel; // which channel of the post to update (e.g. inhibit)
int connId; // connection id
char * name;
int nxp, nyp, nfp; // size of weight dimensions
int numParams;
PVConnParams * params;
int numAxonalArborLists; // number of axonal arbors (weight patches) for presynaptic layer
// STDP parameters for modifying weights
float ampLTP; // long term potentiation amplitude
float ampLTD; // long term depression amplitude
float tauLTP;
float tauLTD;
float dWMax;
float wMax;
float wMin;
int numProbes;
ConnectionProbe ** probes; // probes used to output data
bool stdpFlag; // presence of spike timing dependent plasticity
bool ioAppend; // controls opening of binary files
float wPostTime; // time of last conversion to wPostPatches
float writeTime; // time of next output
float writeStep; // output time interval
protected:
int setPatchSize(const char * filename);
int initialize(const char * name, HyPerCol * hc,
HyPerLayer * pre, HyPerLayer * post, int channel, const char * filename);
int initialize(const char * name, HyPerCol * hc,
HyPerLayer * pre, HyPerLayer * post, int channel);
int initialize_base();
int initialize(const char * filename);
int initializeSTDP();
virtual PVPatch ** initializeWeights(PVPatch ** patches, int numPatches,
const char * filename);
PVPatch ** initializeRandomWeights(PVPatch ** patches, int numPatches, int seed);
PVPatch ** initializeSmartWeights(PVPatch ** patches, int numPatches);
virtual PVPatch ** initializeDefaultWeights(PVPatch ** patches, int numPatches);
PVPatch ** initializeGaussianWeights(PVPatch ** patches, int numPatches);
virtual PVPatch ** createWeights(PVPatch ** patches, int nPatches, int nxPatch,
int nyPatch, int nfPatch);
PVPatch ** createWeights(PVPatch ** patches);
virtual PVPatch ** allocWeights(PVPatch ** patches, int nPatches, int nxPatch,
int nyPatch, int nfPatch);
PVPatch ** allocWeights(PVPatch ** patches);
int uniformWeights(PVPatch * wp, float wMin, float wMax, int * seed);
int gaussianWeights(PVPatch * wp, float mean, float stdev, int * seed);
int smartWeights(PVPatch * wp, int k);
virtual int checkPVPFileHeader(const PVLayerLoc * loc, int params[], int numParams);
virtual int checkWeightsHeader(const char * filename, int wgtParams[]);
virtual int deleteWeights();
virtual int createAxonalArbors();
// static member functions
public:
static PVPatch ** createPatches(int numBundles, int nx, int ny, int nf)
{
PVPatch ** patches = (PVPatch**) malloc(numBundles*sizeof(PVPatch*));
for (int i = 0; i < numBundles; i++) {
patches[i] = pvpatch_inplace_new(nx, ny, nf);
}
return patches;
}
static int deletePatches(int numBundles, PVPatch ** patches)
{
for (int i = 0; i < numBundles; i++) {
pvpatch_inplace_delete(patches[i]);
}
free(patches);
return 0;
}
};
} // namespace PV
#endif /* HYPERCONN_HPP_ */
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2003-2010 Sony Pictures Imageworks Inc., et al.
All Rights Reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Sony Pictures Imageworks nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <OpenColorIO/OpenColorIO.h>
#include "OpBuilders.h"
#include <cmath>
#include <cstring>
#include <iterator>
OCIO_NAMESPACE_ENTER
{
DisplayTransformRcPtr DisplayTransform::Create()
{
return DisplayTransformRcPtr(new DisplayTransform(), &deleter);
}
void DisplayTransform::deleter(DisplayTransform* t)
{
delete t;
}
class DisplayTransform::Impl
{
public:
TransformDirection dir_;
std::string inputColorSpaceName_;
TransformRcPtr linearCC_;
TransformRcPtr colorTimingCC_;
TransformRcPtr channelView_;
std::string displayColorSpaceName_;
Impl() :
dir_(TRANSFORM_DIR_FORWARD)
{ }
~Impl()
{ }
Impl& operator= (const Impl & rhs)
{
dir_ = rhs.dir_;
inputColorSpaceName_ = rhs.inputColorSpaceName_;
linearCC_ = rhs.linearCC_;
if(linearCC_) linearCC_ = linearCC_->createEditableCopy();
colorTimingCC_ = rhs.colorTimingCC_;
if(colorTimingCC_) colorTimingCC_ = colorTimingCC_->createEditableCopy();
channelView_ = rhs.channelView_;
if(channelView_) channelView_ = channelView_->createEditableCopy();
displayColorSpaceName_ = rhs.displayColorSpaceName_;
return *this;
}
};
///////////////////////////////////////////////////////////////////////////
DisplayTransform::DisplayTransform()
: m_impl(new DisplayTransform::Impl)
{
}
TransformRcPtr DisplayTransform::createEditableCopy() const
{
DisplayTransformRcPtr transform = DisplayTransform::Create();
*(transform->m_impl) = *m_impl;
return transform;
}
DisplayTransform::~DisplayTransform()
{
}
DisplayTransform& DisplayTransform::operator= (const DisplayTransform & rhs)
{
*m_impl = *rhs.m_impl;
return *this;
}
TransformDirection DisplayTransform::getDirection() const
{
return m_impl->dir_;
}
void DisplayTransform::setDirection(TransformDirection dir)
{
m_impl->dir_ = dir;
}
void DisplayTransform::setInputColorSpaceName(const char * name)
{
m_impl->inputColorSpaceName_ = name;
}
const char * DisplayTransform::getInputColorSpaceName() const
{
return m_impl->inputColorSpaceName_.c_str();
}
void DisplayTransform::setLinearCC(const ConstTransformRcPtr & cc)
{
m_impl->linearCC_ = cc->createEditableCopy();
}
ConstTransformRcPtr DisplayTransform::getLinearCC() const
{
return m_impl->linearCC_;
}
void DisplayTransform::setColorTimingCC(const ConstTransformRcPtr & cc)
{
m_impl->colorTimingCC_ = cc->createEditableCopy();
}
ConstTransformRcPtr DisplayTransform::getColorTimingCC() const
{
return m_impl->colorTimingCC_;
}
void DisplayTransform::setChannelView(const ConstTransformRcPtr & transform)
{
m_impl->channelView_ = transform->createEditableCopy();
}
ConstTransformRcPtr DisplayTransform::getChannelView() const
{
return m_impl->channelView_;
}
void DisplayTransform::setDisplayColorSpaceName(const char * name)
{
m_impl->displayColorSpaceName_ = name;
}
const char * DisplayTransform::getDisplayColorSpaceName() const
{
return m_impl->displayColorSpaceName_.c_str();
}
std::ostream& operator<< (std::ostream& os, const DisplayTransform& t)
{
os << "<DisplayTransform ";
os << "direction=" << TransformDirectionToString(t.getDirection()) << ", ";
os << ">\n";
return os;
}
///////////////////////////////////////////////////////////////////////////
void BuildDisplayOps(OpRcPtrVec & ops,
const Config & config,
const DisplayTransform & displayTransform,
TransformDirection dir)
{
TransformDirection combinedDir = CombineTransformDirections(dir,
displayTransform.getDirection());
if(combinedDir != TRANSFORM_DIR_FORWARD)
{
std::ostringstream os;
os << "DisplayTransform can only be applied in the forward direction.";
throw Exception(os.str().c_str());
}
std::string inputColorSpaceName = displayTransform.getInputColorSpaceName();
ConstColorSpaceRcPtr inputColorSpace = config.getColorSpace(inputColorSpaceName.c_str());
if(!inputColorSpace)
{
std::ostringstream os;
os << "DisplayTransform error.";
if(inputColorSpaceName.empty()) os << " InputColorSpaceName is unspecified.";
else os << " Cannot find inputColorSpace, named '" << inputColorSpaceName << "'.";
throw Exception(os.str().c_str());
}
std::string displayColorSpaceName = displayTransform.getDisplayColorSpaceName();
ConstColorSpaceRcPtr displayColorspace = config.getColorSpace(displayColorSpaceName.c_str());
if(!displayColorspace)
{
std::ostringstream os;
os << "DisplayTransform error.";
if(displayColorSpaceName.empty()) os << " displayColorspace is unspecified.";
else os << " Cannot find displayColorspace, named '" << displayColorSpaceName << "'.";
throw Exception(os.str().c_str());
}
bool skipColorSpaceConversions = (inputColorSpace->isData() || displayColorspace->isData());
ConstColorSpaceRcPtr currentColorspace = inputColorSpace;
// Apply a transform in ROLE_SCENE_LINEAR
ConstTransformRcPtr linearCC = displayTransform.getLinearCC();
if(linearCC)
{
// Put the new ops into a temp array, to see if it's a no-op
// If it is a no-op, dont bother doing the colorspace conversion.
OpRcPtrVec ccOps;
BuildOps(ccOps, config, linearCC, TRANSFORM_DIR_FORWARD);
if(!IsOpVecNoOp(ccOps))
{
ConstColorSpaceRcPtr targetColorSpace = config.getColorSpace(ROLE_SCENE_LINEAR);
if(!skipColorSpaceConversions)
{
BuildColorSpaceOps(ops, config,
currentColorspace,
targetColorSpace);
currentColorspace = targetColorSpace;
}
std::copy(ccOps.begin(), ccOps.end(), std::back_inserter(ops));
}
}
// Apply a color correction, in ROLE_COLOR_TIMING
ConstTransformRcPtr colorTimingCC = displayTransform.getColorTimingCC();
if(colorTimingCC)
{
// Put the new ops into a temp array, to see if it's a no-op
// If it is a no-op, dont bother doing the colorspace conversion.
OpRcPtrVec ccOps;
BuildOps(ccOps, config, colorTimingCC, TRANSFORM_DIR_FORWARD);
if(!IsOpVecNoOp(ccOps))
{
ConstColorSpaceRcPtr targetColorSpace = config.getColorSpace(ROLE_COLOR_TIMING);
if(!skipColorSpaceConversions)
{
BuildColorSpaceOps(ops, config,
currentColorspace,
targetColorSpace);
currentColorspace = targetColorSpace;
}
std::copy(ccOps.begin(), ccOps.end(), std::back_inserter(ops));
}
}
// Apply a channel view
ConstTransformRcPtr channelView = displayTransform.getChannelView();
if(channelView)
{
BuildOps(ops, config, channelView, TRANSFORM_DIR_FORWARD);
}
// Apply the conversion to the display color space
if(!skipColorSpaceConversions)
{
BuildColorSpaceOps(ops, config,
currentColorspace,
displayColorspace);
currentColorspace = displayColorspace;
}
}
}
OCIO_NAMESPACE_EXIT
<commit_msg>updated DisplayTransform to have better alpha handling<commit_after>/*
Copyright (c) 2003-2010 Sony Pictures Imageworks Inc., et al.
All Rights Reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Sony Pictures Imageworks nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <OpenColorIO/OpenColorIO.h>
#include "OpBuilders.h"
#include <cmath>
#include <cstring>
#include <iterator>
OCIO_NAMESPACE_ENTER
{
DisplayTransformRcPtr DisplayTransform::Create()
{
return DisplayTransformRcPtr(new DisplayTransform(), &deleter);
}
void DisplayTransform::deleter(DisplayTransform* t)
{
delete t;
}
class DisplayTransform::Impl
{
public:
TransformDirection dir_;
std::string inputColorSpaceName_;
TransformRcPtr linearCC_;
TransformRcPtr colorTimingCC_;
TransformRcPtr channelView_;
std::string displayColorSpaceName_;
Impl() :
dir_(TRANSFORM_DIR_FORWARD)
{ }
~Impl()
{ }
Impl& operator= (const Impl & rhs)
{
dir_ = rhs.dir_;
inputColorSpaceName_ = rhs.inputColorSpaceName_;
linearCC_ = rhs.linearCC_;
if(linearCC_) linearCC_ = linearCC_->createEditableCopy();
colorTimingCC_ = rhs.colorTimingCC_;
if(colorTimingCC_) colorTimingCC_ = colorTimingCC_->createEditableCopy();
channelView_ = rhs.channelView_;
if(channelView_) channelView_ = channelView_->createEditableCopy();
displayColorSpaceName_ = rhs.displayColorSpaceName_;
return *this;
}
};
///////////////////////////////////////////////////////////////////////////
DisplayTransform::DisplayTransform()
: m_impl(new DisplayTransform::Impl)
{
}
TransformRcPtr DisplayTransform::createEditableCopy() const
{
DisplayTransformRcPtr transform = DisplayTransform::Create();
*(transform->m_impl) = *m_impl;
return transform;
}
DisplayTransform::~DisplayTransform()
{
}
DisplayTransform& DisplayTransform::operator= (const DisplayTransform & rhs)
{
*m_impl = *rhs.m_impl;
return *this;
}
TransformDirection DisplayTransform::getDirection() const
{
return m_impl->dir_;
}
void DisplayTransform::setDirection(TransformDirection dir)
{
m_impl->dir_ = dir;
}
void DisplayTransform::setInputColorSpaceName(const char * name)
{
m_impl->inputColorSpaceName_ = name;
}
const char * DisplayTransform::getInputColorSpaceName() const
{
return m_impl->inputColorSpaceName_.c_str();
}
void DisplayTransform::setLinearCC(const ConstTransformRcPtr & cc)
{
m_impl->linearCC_ = cc->createEditableCopy();
}
ConstTransformRcPtr DisplayTransform::getLinearCC() const
{
return m_impl->linearCC_;
}
void DisplayTransform::setColorTimingCC(const ConstTransformRcPtr & cc)
{
m_impl->colorTimingCC_ = cc->createEditableCopy();
}
ConstTransformRcPtr DisplayTransform::getColorTimingCC() const
{
return m_impl->colorTimingCC_;
}
void DisplayTransform::setChannelView(const ConstTransformRcPtr & transform)
{
m_impl->channelView_ = transform->createEditableCopy();
}
ConstTransformRcPtr DisplayTransform::getChannelView() const
{
return m_impl->channelView_;
}
void DisplayTransform::setDisplayColorSpaceName(const char * name)
{
m_impl->displayColorSpaceName_ = name;
}
const char * DisplayTransform::getDisplayColorSpaceName() const
{
return m_impl->displayColorSpaceName_.c_str();
}
std::ostream& operator<< (std::ostream& os, const DisplayTransform& t)
{
os << "<DisplayTransform ";
os << "direction=" << TransformDirectionToString(t.getDirection()) << ", ";
os << ">\n";
return os;
}
///////////////////////////////////////////////////////////////////////////
void BuildDisplayOps(OpRcPtrVec & ops,
const Config & config,
const DisplayTransform & displayTransform,
TransformDirection dir)
{
TransformDirection combinedDir = CombineTransformDirections(dir,
displayTransform.getDirection());
if(combinedDir != TRANSFORM_DIR_FORWARD)
{
std::ostringstream os;
os << "DisplayTransform can only be applied in the forward direction.";
throw Exception(os.str().c_str());
}
std::string inputColorSpaceName = displayTransform.getInputColorSpaceName();
ConstColorSpaceRcPtr inputColorSpace = config.getColorSpace(inputColorSpaceName.c_str());
if(!inputColorSpace)
{
std::ostringstream os;
os << "DisplayTransform error.";
if(inputColorSpaceName.empty()) os << " InputColorSpaceName is unspecified.";
else os << " Cannot find inputColorSpace, named '" << inputColorSpaceName << "'.";
throw Exception(os.str().c_str());
}
std::string displayColorSpaceName = displayTransform.getDisplayColorSpaceName();
ConstColorSpaceRcPtr displayColorspace = config.getColorSpace(displayColorSpaceName.c_str());
if(!displayColorspace)
{
std::ostringstream os;
os << "DisplayTransform error.";
if(displayColorSpaceName.empty()) os << " displayColorspace is unspecified.";
else os << " Cannot find displayColorspace, named '" << displayColorSpaceName << "'.";
throw Exception(os.str().c_str());
}
bool skipColorSpaceConversions = (inputColorSpace->isData() || displayColorspace->isData());
// If we're viewing alpha, also skip all color space conversions.
// TODO: Should we enforce the use of a MatrixTransform at the API level?
ConstMatrixTransformRcPtr typedChannelView = DynamicPtrCast<const MatrixTransform>(
displayTransform.getChannelView());
if(typedChannelView)
{
float matrix44[16];
typedChannelView->getValue(matrix44, 0x0);
if((matrix44[3]>0.0f) || (matrix44[7]>0.0f) || (matrix44[11]>0.0f))
{
skipColorSpaceConversions = true;
}
}
ConstColorSpaceRcPtr currentColorspace = inputColorSpace;
// Apply a transform in ROLE_SCENE_LINEAR
ConstTransformRcPtr linearCC = displayTransform.getLinearCC();
if(linearCC)
{
// Put the new ops into a temp array, to see if it's a no-op
// If it is a no-op, dont bother doing the colorspace conversion.
OpRcPtrVec ccOps;
BuildOps(ccOps, config, linearCC, TRANSFORM_DIR_FORWARD);
if(!IsOpVecNoOp(ccOps))
{
ConstColorSpaceRcPtr targetColorSpace = config.getColorSpace(ROLE_SCENE_LINEAR);
if(!skipColorSpaceConversions)
{
BuildColorSpaceOps(ops, config,
currentColorspace,
targetColorSpace);
currentColorspace = targetColorSpace;
}
std::copy(ccOps.begin(), ccOps.end(), std::back_inserter(ops));
}
}
// Apply a color correction, in ROLE_COLOR_TIMING
ConstTransformRcPtr colorTimingCC = displayTransform.getColorTimingCC();
if(colorTimingCC)
{
// Put the new ops into a temp array, to see if it's a no-op
// If it is a no-op, dont bother doing the colorspace conversion.
OpRcPtrVec ccOps;
BuildOps(ccOps, config, colorTimingCC, TRANSFORM_DIR_FORWARD);
if(!IsOpVecNoOp(ccOps))
{
ConstColorSpaceRcPtr targetColorSpace = config.getColorSpace(ROLE_COLOR_TIMING);
if(!skipColorSpaceConversions)
{
BuildColorSpaceOps(ops, config,
currentColorspace,
targetColorSpace);
currentColorspace = targetColorSpace;
}
std::copy(ccOps.begin(), ccOps.end(), std::back_inserter(ops));
}
}
// Apply a channel view
ConstTransformRcPtr channelView = displayTransform.getChannelView();
if(channelView)
{
BuildOps(ops, config, channelView, TRANSFORM_DIR_FORWARD);
}
// Apply the conversion to the display color space
if(!skipColorSpaceConversions)
{
BuildColorSpaceOps(ops, config,
currentColorspace,
displayColorspace);
currentColorspace = displayColorspace;
}
}
}
OCIO_NAMESPACE_EXIT
<|endoftext|>
|
<commit_before>#ifndef CORE_ANIMATIONS_SLEEP_HPP_
#define CORE_ANIMATIONS_SLEEP_HPP_
#include <core/animation.hpp>
template <typename Value>
class Sleep: public Animation<Value>
{
public:
Sleep(int32_t initialTimeout):
m_initialTimeout(initialTimeout),
m_currenTimeout(initialTimeout)
{}
virtual Value nextValue(const int32_t deltaTime) override
{
return Value();
}
virtual Value getCurrentValue() const override
{
return Value();
}
virtual bool isFinished() const override
{
return false;
}
virtual void reset(const Value &value) override
{
}
private:
const int32_t m_initialTimeout;
int32_t m_currenTimeout;
};
#endif // CORE_ANIMATIONS_SLEEP_HPP_
<commit_msg>Implement sleep acroding to the specs<commit_after>#ifndef CORE_ANIMATIONS_SLEEP_HPP_
#define CORE_ANIMATIONS_SLEEP_HPP_
#include <algorithm>
#include <core/animation.hpp>
template <typename Value>
class Sleep: public Animation<Value>
{
public:
Sleep(int32_t initialTimeout):
m_initialTimeout(initialTimeout),
m_currentTimeout(initialTimeout),
m_currentValue()
{}
virtual Value nextValue(const int32_t deltaTime) override
{
m_currentTimeout = std::max(0, m_currentTimeout - deltaTime);
return m_currentValue;
}
virtual Value getCurrentValue() const override
{
return m_currentValue;
}
virtual bool isFinished() const override
{
return m_currentTimeout <= 0;
}
virtual void reset(const Value &value) override
{
m_currentValue = value;
m_currentTimeout = m_initialTimeout;
}
private:
const int32_t m_initialTimeout;
int32_t m_currentTimeout;
Value m_currentValue;
};
#endif // CORE_ANIMATIONS_SLEEP_HPP_
<|endoftext|>
|
<commit_before>/*
* CrashHandler.cpp
*
* Copyright (C) 2019 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/CrashHandler.hpp>
#include <sstream>
#include <core/FileUtils.hpp>
#include <core/Settings.hpp>
#include <core/StringUtils.hpp>
#include <core/system/System.hpp>
#include <core/system/Environment.hpp>
#ifndef _WIN32
#include <core/system/FileMode.hpp>
#endif
#include "config.h"
#ifndef RSTUDIO_CRASHPAD_ENABLED
namespace rstudio {
namespace core {
namespace crash_handler {
Error initialize(ProgramMode programMode)
{
return Success();
}
ConfigSource configSource()
{
return ConfigSource::Default;
}
bool isHandlerEnabled()
{
return false;
}
Error setUserHandlerEnabled(bool)
{
return Success();
}
} // namespace crash_handler
} // namespace core
} // namespace rstudio
#else
#include <crashpad/client/crashpad_client.h>
#include <crashpad/client/crash_report_database.h>
#include <crashpad/client/settings.h>
#define kCrashHandlingEnabled "crash-handling-enabled"
#define kCrashHandlingEnabledDefault false
#define kCrashDatabasePath "crash-db-path"
#define kCrashDatabasePathDefault ""
#define kUploadUrl "upload-url"
#define kUploadUrlDefault "https://sentry.io/api/1379214/minidump/?sentry_key=4e76b8d2cffb49419fec1b431e09247c"
#define kUploadDumps "uploads-enabled"
#define kUploadDumpsDefault true
#define kUploadProxy "upload-proxy"
#define kUploadProxyDefault ""
namespace rstudio {
namespace core {
namespace crash_handler {
namespace {
boost::shared_ptr<crashpad::CrashpadClient> s_crashpadClient;
boost::shared_ptr<Settings> s_settings;
ProgramMode s_programMode;
FilePath adminConfFile()
{
#ifndef _WIN32
return FilePath("/etc/rstudio/crash-handler.conf");
#else
return core::system::systemSettingsPath("RStudio", false).complete("crash-handler.conf");
#endif
}
FilePath userConfFile()
{
return core::system::userSettingsPath(core::system::userHomePath(),
"R",
false).complete("crash-handler.conf");
}
void readOptions()
{
s_settings.reset(new Settings());
FilePath optionsFile = adminConfFile();
if (s_programMode == ProgramMode::Desktop && !optionsFile.exists())
{
// admin-level file does not exist - check for existence of user file
// this is only done for desktop mode, as only the admin file should be
// respected in server mode
optionsFile = userConfFile();
// if the user options file does not explicitly exist, we will forcefully create it
// this is to ensure that there is an actual file backing for the settings
// as multiple user clients can update it simultaneously, so we need to have it
// backed to file as opposed to just hanging around in memory so that all clients
// can properly see the state at all times
if (!optionsFile.exists())
{
Error error = optionsFile.ensureFile();
if (error)
LOG_ERROR(error);
}
}
if (optionsFile.exists())
{
Error error = s_settings->initialize(optionsFile);
if (error)
LOG_ERROR(error);
}
}
base::FilePath googleFilePath(const std::string& str)
{
#ifdef _WIN32
std::string utf8Str = core::string_utils::systemToUtf8(str);
std::wstring wideStr = core::string_utils::utf8ToWide(utf8Str);
return base::FilePath(wideStr);
#else
return base::FilePath(str);
#endif
}
void logClientCreation(const base::FilePath& handlerPath,
const base::FilePath& databasePath,
const std::string& uploadUrl)
{
#ifdef _WIN32
std::wstringstream msg;
std::wstring uploadUrlStr = core::string_utils::utf8ToWide(uploadUrl);
#else
std::stringstream msg;
const std::string& uploadUrlStr = uploadUrl;
#endif
msg << "Initializing crashpad client:" <<
" handlerPath=" << handlerPath.value() <<
" databasePath=" << databasePath.value() <<
" uploadUrl=" << uploadUrlStr;
#ifdef _WIN32
std::string message = core::string_utils::wideToUtf8(msg.str());
#else
std::string message = msg.str();
#endif
LOG_INFO_MESSAGE(message);
}
FilePath permissionFile()
{
return core::system::userSettingsPath(core::system::userHomePath(),
"R",
false).complete("crash-handler-permission");
}
} // anonymous namespace
Error initialize(ProgramMode programMode)
{
#ifndef RSTUDIO_CRASHPAD_ENABLED
return Success();
#endif
s_programMode = programMode;
readOptions();
// if crash handling is explicitly disabled, exit out
bool crashHandlingEnabled = s_settings->getBool(kCrashHandlingEnabled, kCrashHandlingEnabledDefault);
if (!crashHandlingEnabled)
return Success();
// get the path to the crashpad database
std::string databasePathStr = s_settings->get(kCrashDatabasePath, kCrashDatabasePathDefault);
if (databasePathStr.empty())
{
#ifdef RSTUDIO_SERVER
if (s_programMode == ProgramMode::Server)
{
// server mode - default database path to default tmp location
FilePath tmpPath;
Error error = FilePath::tempFilePath(&tmpPath);
if (error)
return error;
FilePath databasePath = tmpPath.parent().childPath("crashpad_database");
// ensure that the database path exists
error = databasePath.ensureDirectory();
if (error)
return error;
// ensure that it is writeable by all users
// this is best case and we swallow the error because it is legitimately possible we
// lack the permissions to perform this (such as if we are an unprivileged rsession user)
core::system::changeFileMode(databasePath, core::system::EveryoneReadWriteExecuteMode);
databasePathStr = databasePath.absolutePath();
}
else
{
// desktop mode - default database path to user settings path
databasePathStr = core::system::userSettingsPath(core::system::userHomePath(),
"R",
true).childPath("crashpad_database").absolutePath();
}
#else
// desktop mode - default database path to user settings path
databasePathStr = core::system::userSettingsPath(core::system::userHomePath(),
"R",
true).childPath("crashpad_database").absolutePath();
#endif
}
base::FilePath databasePath = googleFilePath(databasePathStr);
// determine if dumps should be uploaded automatically
std::string uploadUrl = s_settings->get(kUploadUrl, kUploadUrlDefault);
bool uploadDumps = s_settings->getBool(kUploadDumps, kUploadDumpsDefault) && !uploadUrl.empty();
// get the path to the crashpad handler
FilePath exePath;
Error error = core::system::executablePath(nullptr, &exePath);
if (error)
return error;
// get the path for the crash handler - this may be overridden via env var
// for supporting development setups
base::FilePath handlerPath;
std::string crashHandlerPathEnv = core::system::getenv(kCrashHandlerEnvVar);
if (!crashHandlerPathEnv.empty())
{
handlerPath = googleFilePath(crashHandlerPathEnv);
}
else
{
#ifndef _WIN32
// for server, we use the crash handler proxy to ensure that the crashpad handler
// is run with the correct permissions (otherwise ptrace will not work if setuid is used)
#ifdef RSTUDIO_SERVER
if (s_programMode == ProgramMode::Server)
handlerPath = googleFilePath(exePath.parent().childPath("crash-handler-proxy").absolutePath());
else
handlerPath = googleFilePath(exePath.parent().childPath("crashpad_handler").absolutePath());
#else
handlerPath = googleFilePath(exePath.parent().childPath("crashpad_handler").absolutePath());
#endif
#else
handlerPath = googleFilePath(exePath.parent().childPath("crashpad_handler.exe").absolutePath());
#endif
}
// open the crashpad database
std::unique_ptr<crashpad::CrashReportDatabase> pDatabase =
crashpad::CrashReportDatabase::Initialize(databasePath);
// in server mode, attempt to give full access to the entire database for all users
// this is necessary so unprivileged processes can write crash dumps properly
// again, we swallow the errors here because unprivileged processes cannot change permissions
#ifdef RSTUDIO_SERVER
if (s_programMode == ProgramMode::Server)
{
std::vector<FilePath> dbFolders;
FilePath(databasePathStr).children(&dbFolders);
for (const FilePath& subPath : dbFolders)
core::system::changeFileMode(subPath, core::system::EveryoneReadWriteExecuteMode);
}
#endif
// ensure database is properly initialized
if (pDatabase != nullptr && pDatabase->GetSettings() != nullptr)
pDatabase->GetSettings()->SetUploadsEnabled(uploadDumps);
else
return systemError(boost::system::errc::no_such_file_or_directory, ERROR_LOCATION);
logClientCreation(handlerPath, databasePath, uploadUrl);
// initialize and start crashpad client
s_crashpadClient.reset(new crashpad::CrashpadClient());
std::map<std::string, std::string> annotations;
annotations["sentry[release]"] = RSTUDIO_VERSION;
std::vector<std::string> args {"--no-rate-limit"};
#ifdef __linux__
// export proxy environment variable if set
// if not set, the default (system-wide setting) or any existing proxy env var is used instead
// see https://curl.haxx.se/libcurl/c/CURLOPT_PROXY.html for more info
std::string proxy = s_settings->get(kUploadProxy, kUploadProxyDefault);
if (!proxy.empty())
core::system::setenv("ALL_PROXY", proxy);
bool success = s_crashpadClient->StartHandlerAtCrash(handlerPath,
databasePath,
base::FilePath(),
uploadUrl,
annotations,
args);
#else
bool success = s_crashpadClient->StartHandler(handlerPath,
databasePath,
base::FilePath(),
uploadUrl,
annotations,
args,
true,
false);
#endif
return success ? Success() : systemError(boost::system::errc::invalid_argument, ERROR_LOCATION);
}
ConfigSource configSource()
{
FilePath settingsPath = s_settings->filePath();
if (settingsPath.empty())
return ConfigSource::Default;
if (settingsPath == adminConfFile())
return ConfigSource::Admin;
else if (settingsPath == userConfFile())
return ConfigSource::User;
else
return ConfigSource::Default;
}
bool isHandlerEnabled()
{
return s_settings->getBool(kCrashHandlingEnabled, kCrashHandlingEnabledDefault);
}
Error setUserHandlerEnabled(bool handlerEnabled)
{
ConfigSource source = configSource();
if (source == ConfigSource::Admin)
{
// the admin setting is in effect so there's nothing to change
return Success();
}
if (source == ConfigSource::Default)
{
FilePath userFile = userConfFile();
Error error = userFile.ensureFile();
if (error)
return error;
Settings settings;
error = settings.initialize(userFile);
if (error)
return error;
settings.set(kCrashHandlingEnabled, handlerEnabled);
}
else
{
// we already have the user file open - simply update the settings directly
s_settings->set(kCrashHandlingEnabled, handlerEnabled);
}
return Success();
}
bool hasUserBeenPromptedForPermission()
{
if (!permissionFile().exists())
{
// if for some reason the parent directory is not writeable
// we will just treat the user as if they have been prompted
// to prevent indefinite repeated promptings
if (!file_utils::isDirectoryWriteable(permissionFile().parent()))
return true;
else
return false;
}
else
return true;
}
Error setUserHasBeenPromptedForPermission()
{
return permissionFile().ensureFile();
}
} // namespace crash_handler
} // namespace core
} // namespace rstudio
#endif
<commit_msg>Fix broken build<commit_after>/*
* CrashHandler.cpp
*
* Copyright (C) 2019 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/CrashHandler.hpp>
#include <sstream>
#include <core/FileUtils.hpp>
#include <core/Settings.hpp>
#include <core/StringUtils.hpp>
#include <core/system/System.hpp>
#include <core/system/Environment.hpp>
#ifndef _WIN32
#include <core/system/FileMode.hpp>
#endif
#include "config.h"
#ifndef RSTUDIO_CRASHPAD_ENABLED
namespace rstudio {
namespace core {
namespace crash_handler {
Error initialize(ProgramMode programMode)
{
return Success();
}
ConfigSource configSource()
{
return ConfigSource::Default;
}
bool isHandlerEnabled()
{
return false;
}
Error setUserHandlerEnabled(bool)
{
return Success();
}
bool hasUserBeenPromptedForPermission()
{
return true;
}
Error setUserHasBeenPromptedForPermission()
{
return Success();
}
} // namespace crash_handler
} // namespace core
} // namespace rstudio
#else
#include <crashpad/client/crashpad_client.h>
#include <crashpad/client/crash_report_database.h>
#include <crashpad/client/settings.h>
#define kCrashHandlingEnabled "crash-handling-enabled"
#define kCrashHandlingEnabledDefault false
#define kCrashDatabasePath "crash-db-path"
#define kCrashDatabasePathDefault ""
#define kUploadUrl "upload-url"
#define kUploadUrlDefault "https://sentry.io/api/1379214/minidump/?sentry_key=4e76b8d2cffb49419fec1b431e09247c"
#define kUploadDumps "uploads-enabled"
#define kUploadDumpsDefault true
#define kUploadProxy "upload-proxy"
#define kUploadProxyDefault ""
namespace rstudio {
namespace core {
namespace crash_handler {
namespace {
boost::shared_ptr<crashpad::CrashpadClient> s_crashpadClient;
boost::shared_ptr<Settings> s_settings;
ProgramMode s_programMode;
FilePath adminConfFile()
{
#ifndef _WIN32
return FilePath("/etc/rstudio/crash-handler.conf");
#else
return core::system::systemSettingsPath("RStudio", false).complete("crash-handler.conf");
#endif
}
FilePath userConfFile()
{
return core::system::userSettingsPath(core::system::userHomePath(),
"R",
false).complete("crash-handler.conf");
}
void readOptions()
{
s_settings.reset(new Settings());
FilePath optionsFile = adminConfFile();
if (s_programMode == ProgramMode::Desktop && !optionsFile.exists())
{
// admin-level file does not exist - check for existence of user file
// this is only done for desktop mode, as only the admin file should be
// respected in server mode
optionsFile = userConfFile();
// if the user options file does not explicitly exist, we will forcefully create it
// this is to ensure that there is an actual file backing for the settings
// as multiple user clients can update it simultaneously, so we need to have it
// backed to file as opposed to just hanging around in memory so that all clients
// can properly see the state at all times
if (!optionsFile.exists())
{
Error error = optionsFile.ensureFile();
if (error)
LOG_ERROR(error);
}
}
if (optionsFile.exists())
{
Error error = s_settings->initialize(optionsFile);
if (error)
LOG_ERROR(error);
}
}
base::FilePath googleFilePath(const std::string& str)
{
#ifdef _WIN32
std::string utf8Str = core::string_utils::systemToUtf8(str);
std::wstring wideStr = core::string_utils::utf8ToWide(utf8Str);
return base::FilePath(wideStr);
#else
return base::FilePath(str);
#endif
}
void logClientCreation(const base::FilePath& handlerPath,
const base::FilePath& databasePath,
const std::string& uploadUrl)
{
#ifdef _WIN32
std::wstringstream msg;
std::wstring uploadUrlStr = core::string_utils::utf8ToWide(uploadUrl);
#else
std::stringstream msg;
const std::string& uploadUrlStr = uploadUrl;
#endif
msg << "Initializing crashpad client:" <<
" handlerPath=" << handlerPath.value() <<
" databasePath=" << databasePath.value() <<
" uploadUrl=" << uploadUrlStr;
#ifdef _WIN32
std::string message = core::string_utils::wideToUtf8(msg.str());
#else
std::string message = msg.str();
#endif
LOG_INFO_MESSAGE(message);
}
FilePath permissionFile()
{
return core::system::userSettingsPath(core::system::userHomePath(),
"R",
false).complete("crash-handler-permission");
}
} // anonymous namespace
Error initialize(ProgramMode programMode)
{
#ifndef RSTUDIO_CRASHPAD_ENABLED
return Success();
#endif
s_programMode = programMode;
readOptions();
// if crash handling is explicitly disabled, exit out
bool crashHandlingEnabled = s_settings->getBool(kCrashHandlingEnabled, kCrashHandlingEnabledDefault);
if (!crashHandlingEnabled)
return Success();
// get the path to the crashpad database
std::string databasePathStr = s_settings->get(kCrashDatabasePath, kCrashDatabasePathDefault);
if (databasePathStr.empty())
{
#ifdef RSTUDIO_SERVER
if (s_programMode == ProgramMode::Server)
{
// server mode - default database path to default tmp location
FilePath tmpPath;
Error error = FilePath::tempFilePath(&tmpPath);
if (error)
return error;
FilePath databasePath = tmpPath.parent().childPath("crashpad_database");
// ensure that the database path exists
error = databasePath.ensureDirectory();
if (error)
return error;
// ensure that it is writeable by all users
// this is best case and we swallow the error because it is legitimately possible we
// lack the permissions to perform this (such as if we are an unprivileged rsession user)
core::system::changeFileMode(databasePath, core::system::EveryoneReadWriteExecuteMode);
databasePathStr = databasePath.absolutePath();
}
else
{
// desktop mode - default database path to user settings path
databasePathStr = core::system::userSettingsPath(core::system::userHomePath(),
"R",
true).childPath("crashpad_database").absolutePath();
}
#else
// desktop mode - default database path to user settings path
databasePathStr = core::system::userSettingsPath(core::system::userHomePath(),
"R",
true).childPath("crashpad_database").absolutePath();
#endif
}
base::FilePath databasePath = googleFilePath(databasePathStr);
// determine if dumps should be uploaded automatically
std::string uploadUrl = s_settings->get(kUploadUrl, kUploadUrlDefault);
bool uploadDumps = s_settings->getBool(kUploadDumps, kUploadDumpsDefault) && !uploadUrl.empty();
// get the path to the crashpad handler
FilePath exePath;
Error error = core::system::executablePath(nullptr, &exePath);
if (error)
return error;
// get the path for the crash handler - this may be overridden via env var
// for supporting development setups
base::FilePath handlerPath;
std::string crashHandlerPathEnv = core::system::getenv(kCrashHandlerEnvVar);
if (!crashHandlerPathEnv.empty())
{
handlerPath = googleFilePath(crashHandlerPathEnv);
}
else
{
#ifndef _WIN32
// for server, we use the crash handler proxy to ensure that the crashpad handler
// is run with the correct permissions (otherwise ptrace will not work if setuid is used)
#ifdef RSTUDIO_SERVER
if (s_programMode == ProgramMode::Server)
handlerPath = googleFilePath(exePath.parent().childPath("crash-handler-proxy").absolutePath());
else
handlerPath = googleFilePath(exePath.parent().childPath("crashpad_handler").absolutePath());
#else
handlerPath = googleFilePath(exePath.parent().childPath("crashpad_handler").absolutePath());
#endif
#else
handlerPath = googleFilePath(exePath.parent().childPath("crashpad_handler.exe").absolutePath());
#endif
}
// open the crashpad database
std::unique_ptr<crashpad::CrashReportDatabase> pDatabase =
crashpad::CrashReportDatabase::Initialize(databasePath);
// in server mode, attempt to give full access to the entire database for all users
// this is necessary so unprivileged processes can write crash dumps properly
// again, we swallow the errors here because unprivileged processes cannot change permissions
#ifdef RSTUDIO_SERVER
if (s_programMode == ProgramMode::Server)
{
std::vector<FilePath> dbFolders;
FilePath(databasePathStr).children(&dbFolders);
for (const FilePath& subPath : dbFolders)
core::system::changeFileMode(subPath, core::system::EveryoneReadWriteExecuteMode);
}
#endif
// ensure database is properly initialized
if (pDatabase != nullptr && pDatabase->GetSettings() != nullptr)
pDatabase->GetSettings()->SetUploadsEnabled(uploadDumps);
else
return systemError(boost::system::errc::no_such_file_or_directory, ERROR_LOCATION);
logClientCreation(handlerPath, databasePath, uploadUrl);
// initialize and start crashpad client
s_crashpadClient.reset(new crashpad::CrashpadClient());
std::map<std::string, std::string> annotations;
annotations["sentry[release]"] = RSTUDIO_VERSION;
std::vector<std::string> args {"--no-rate-limit"};
#ifdef __linux__
// export proxy environment variable if set
// if not set, the default (system-wide setting) or any existing proxy env var is used instead
// see https://curl.haxx.se/libcurl/c/CURLOPT_PROXY.html for more info
std::string proxy = s_settings->get(kUploadProxy, kUploadProxyDefault);
if (!proxy.empty())
core::system::setenv("ALL_PROXY", proxy);
bool success = s_crashpadClient->StartHandlerAtCrash(handlerPath,
databasePath,
base::FilePath(),
uploadUrl,
annotations,
args);
#else
bool success = s_crashpadClient->StartHandler(handlerPath,
databasePath,
base::FilePath(),
uploadUrl,
annotations,
args,
true,
false);
#endif
return success ? Success() : systemError(boost::system::errc::invalid_argument, ERROR_LOCATION);
}
ConfigSource configSource()
{
FilePath settingsPath = s_settings->filePath();
if (settingsPath.empty())
return ConfigSource::Default;
if (settingsPath == adminConfFile())
return ConfigSource::Admin;
else if (settingsPath == userConfFile())
return ConfigSource::User;
else
return ConfigSource::Default;
}
bool isHandlerEnabled()
{
return s_settings->getBool(kCrashHandlingEnabled, kCrashHandlingEnabledDefault);
}
Error setUserHandlerEnabled(bool handlerEnabled)
{
ConfigSource source = configSource();
if (source == ConfigSource::Admin)
{
// the admin setting is in effect so there's nothing to change
return Success();
}
if (source == ConfigSource::Default)
{
FilePath userFile = userConfFile();
Error error = userFile.ensureFile();
if (error)
return error;
Settings settings;
error = settings.initialize(userFile);
if (error)
return error;
settings.set(kCrashHandlingEnabled, handlerEnabled);
}
else
{
// we already have the user file open - simply update the settings directly
s_settings->set(kCrashHandlingEnabled, handlerEnabled);
}
return Success();
}
bool hasUserBeenPromptedForPermission()
{
if (!permissionFile().exists())
{
// if for some reason the parent directory is not writeable
// we will just treat the user as if they have been prompted
// to prevent indefinite repeated promptings
if (!file_utils::isDirectoryWriteable(permissionFile().parent()))
return true;
else
return false;
}
else
return true;
}
Error setUserHasBeenPromptedForPermission()
{
return permissionFile().ensureFile();
}
} // namespace crash_handler
} // namespace core
} // namespace rstudio
#endif
<|endoftext|>
|
<commit_before>#include <cppunit/XmlOutputterHook.h>
#if !defined(CPPUNIT_NO_TESTPLUGIN)
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/plugin/PlugInManager.h>
#include <cppunit/plugin/TestPlugIn.h>
#include <cppunit/plugin/DynamicLibraryManager.h>
CPPUNIT_NS_BEGIN
PlugInManager::PlugInManager()
{
}
PlugInManager::~PlugInManager()
{
for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
unload( *it );
}
void
PlugInManager::load( const std::string &libraryFileName,
const PlugInParameters ¶meters )
{
PlugInInfo info;
info.m_fileName = libraryFileName;
info.m_manager = new DynamicLibraryManager( libraryFileName );
TestPlugInSignature plug = (TestPlugInSignature)info.m_manager->findSymbol(
CPPUNIT_STRINGIZE( CPPUNIT_PLUGIN_EXPORTED_NAME ) );
info.m_interface = (*plug)();
m_plugIns.push_back( info );
info.m_interface->initialize( &TestFactoryRegistry::getRegistry(), parameters );
}
void
PlugInManager::unload( const std::string &libraryFileName )
{
for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
{
if ( it->m_fileName == libraryFileName )
{
unload( *it );
m_plugIns.erase( it );
break;
}
}
}
void
PlugInManager::addListener( TestResult *eventManager )
{
for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
it->m_interface->addListener( eventManager );
}
void
PlugInManager::removeListener( TestResult *eventManager )
{
for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
it->m_interface->removeListener( eventManager );
}
void
PlugInManager::unload( PlugInInfo &plugIn )
{
try
{
plugIn.m_interface->uninitialize( &TestFactoryRegistry::getRegistry() );
delete plugIn.m_manager;
}
catch (...)
{
delete plugIn.m_manager;
plugIn.m_manager = NULL;
throw;
}
}
void
PlugInManager::addXmlOutputterHooks( XmlOutputter *outputter )
{
for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
it->m_interface->addXmlOutputterHooks( outputter );
}
void
PlugInManager::removeXmlOutputterHooks()
{
for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
it->m_interface->removeXmlOutputterHooks();
}
CPPUNIT_NS_END
#endif // !defined(CPPUNIT_NO_TESTPLUGIN)
<commit_msg>dereferencing fix for SUN4<commit_after>#include <cppunit/XmlOutputterHook.h>
#if !defined(CPPUNIT_NO_TESTPLUGIN)
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/plugin/PlugInManager.h>
#include <cppunit/plugin/TestPlugIn.h>
#include <cppunit/plugin/DynamicLibraryManager.h>
CPPUNIT_NS_BEGIN
PlugInManager::PlugInManager()
{
}
PlugInManager::~PlugInManager()
{
for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
unload( *it );
}
void
PlugInManager::load( const std::string &libraryFileName,
const PlugInParameters ¶meters )
{
PlugInInfo info;
info.m_fileName = libraryFileName;
info.m_manager = new DynamicLibraryManager( libraryFileName );
TestPlugInSignature plug = (TestPlugInSignature)info.m_manager->findSymbol(
CPPUNIT_STRINGIZE( CPPUNIT_PLUGIN_EXPORTED_NAME ) );
info.m_interface = (*plug)();
m_plugIns.push_back( info );
info.m_interface->initialize( &TestFactoryRegistry::getRegistry(), parameters );
}
void
PlugInManager::unload( const std::string &libraryFileName )
{
for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
{
if ( (*it).m_fileName == libraryFileName )
{
unload( *it );
m_plugIns.erase( it );
break;
}
}
}
void
PlugInManager::addListener( TestResult *eventManager )
{
for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
(*it).m_interface->addListener( eventManager );
}
void
PlugInManager::removeListener( TestResult *eventManager )
{
for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
(*it).m_interface->removeListener( eventManager );
}
void
PlugInManager::unload( PlugInInfo &plugIn )
{
try
{
plugIn.m_interface->uninitialize( &TestFactoryRegistry::getRegistry() );
delete plugIn.m_manager;
}
catch (...)
{
delete plugIn.m_manager;
plugIn.m_manager = NULL;
throw;
}
}
void
PlugInManager::addXmlOutputterHooks( XmlOutputter *outputter )
{
for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
(*it).m_interface->addXmlOutputterHooks( outputter );
}
void
PlugInManager::removeXmlOutputterHooks()
{
for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
(*it).m_interface->removeXmlOutputterHooks();
}
CPPUNIT_NS_END
#endif // !defined(CPPUNIT_NO_TESTPLUGIN)
<|endoftext|>
|
<commit_before>#include "edge_orientation.h"
#include "indexing.h"
void EdgeOrientation::index_to_array(int index, vector<int> & arr)
{
Indexing::index_to_orientation_dependent(index, arr, 2);
}
void EdgeOrientation::apply_move(vector<int> & arr, int move)
{
if (move == 0)
{
permute_array(arr, 0, 3, 2, 1, 0); // U
}
else if (move == 1)
{
permute_array(arr, 8, 9, 10, 11, 0); // D
}
else if (move == 2)
{
permute_array(arr, 1, 6, 9, 5, 0); // R
}
else if (move == 3)
{
permute_array(arr, 3, 4, 11, 7, 0); // L
}
else if (move == 4)
{
permute_array(arr, 2, 7, 10, 6, 1); // F
}
else if (move == 5)
{
permute_array(arr, 0, 5, 8, 4, 1); // F
}
}
int EdgeOrientation::array_to_index(vector<int> const& arr)
{
return Indexing::orientation_to_index_dependent(arr, 2);
}
void EdgeOrientation::permute_array(vector<int> & arr, int idx1, int idx2, int idx3, int idx4, int increment)
{
int tmp = arr[idx1];
arr[idx1] = (arr[idx2] + increment) % 2;
arr[idx2] = (arr[idx3] + increment) % 2;
arr[idx3] = (arr[idx4] + increment) % 2;
arr[idx4] = (tmp + increment) % 2;
}
<commit_msg>Fix naming from F to B<commit_after>#include "edge_orientation.h"
#include "indexing.h"
void EdgeOrientation::index_to_array(int index, vector<int> & arr)
{
Indexing::index_to_orientation_dependent(index, arr, 2);
}
void EdgeOrientation::apply_move(vector<int> & arr, int move)
{
if (move == 0)
{
permute_array(arr, 0, 3, 2, 1, 0); // U
}
else if (move == 1)
{
permute_array(arr, 8, 9, 10, 11, 0); // D
}
else if (move == 2)
{
permute_array(arr, 1, 6, 9, 5, 0); // R
}
else if (move == 3)
{
permute_array(arr, 3, 4, 11, 7, 0); // L
}
else if (move == 4)
{
permute_array(arr, 2, 7, 10, 6, 1); // F
}
else if (move == 5)
{
permute_array(arr, 0, 5, 8, 4, 1); // B
}
}
int EdgeOrientation::array_to_index(vector<int> const& arr)
{
return Indexing::orientation_to_index_dependent(arr, 2);
}
void EdgeOrientation::permute_array(vector<int> & arr, int idx1, int idx2, int idx3, int idx4, int increment)
{
int tmp = arr[idx1];
arr[idx1] = (arr[idx2] + increment) % 2;
arr[idx2] = (arr[idx3] + increment) % 2;
arr[idx3] = (arr[idx4] + increment) % 2;
arr[idx4] = (tmp + increment) % 2;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2013, Alexey Ivanov
#include "stdafx.h"
#include "request_handler.h"
#include "../aimp/manager.h"
#include "../aimp/manager_impl_common.h"
#include "../http_server/reply.h"
#include "../http_server/request.h"
#include "../http_server/mime_types.h"
#include "utils/string_encoding.h"
#include "utils/util.h"
namespace UploadTrack
{
using namespace AIMPPlayer;
using namespace std;
namespace fs = boost::filesystem;
const wchar_t * const kPlaylistTitle = L"Control plugin";
void fill_reply_disabled(Http::Reply& rep);
bool RequestHandler::handle_request(const Http::Request& req, Http::Reply& rep)
{
using namespace Http;
if (!enabled_) {
fill_reply_disabled(rep);
return true;
}
try {
for (auto field_it : req.mpfd_parser.GetFieldsMap()) {
const MPFD::Field& field_const = *field_it.second;
MPFD::Field& field = const_cast<MPFD::Field&>(field_const);
const std::string filename = field.GetFileName();
const fs::wpath path = temp_dir_ / filename;
{ // save to temp dir.
std::ofstream out(path.native(), std::ios_base::out | std::ios_base::binary);
out.write(field.GetFileContent(), field.GetFileContentSize());
out.close();
}
aimp_manager_.addFileToPlaylist(path, getTargetPlaylist());
// we should not erase file since AIMP will use it.
//fs::remove(path);
}
rep = Reply::stock_reply(Reply::ok);
} catch (MPFD::Exception&) {
rep = Reply::stock_reply(Reply::bad_request);
} catch (std::exception&) {
rep = Reply::stock_reply(Reply::forbidden);
}
return true;
}
void fill_reply_disabled(Http::Reply& rep)
{
rep.status = Http::Reply::forbidden;
rep.content = "403 Forbidden<br/> Track upload is disabled in Control plugin settings.";
rep.headers.resize(2);
rep.headers[0].name = "Content-Length";
rep.headers[0].value = boost::lexical_cast<std::string>(rep.content.size());
rep.headers[1].name = "Content-Type";
rep.headers[1].value = "text/html";
}
bool getPlaylistByTitle(sqlite3* db, const char* title, PlaylistID* playlist_id);
int RequestHandler::getTargetPlaylist()
{
if (!target_playlist_id_created_) {
if (!getPlaylistByTitle(getPlaylistsDB(aimp_manager_),
StringEncoding::utf16_to_utf8(kPlaylistTitle).c_str(),
&target_playlist_id_)
)
{
target_playlist_id_ = aimp_manager_.createPlaylist(kPlaylistTitle);
}
target_playlist_id_created_ = true;
}
return target_playlist_id_;
}
bool getPlaylistByTitle(sqlite3* db, const char* title, PlaylistID* playlist_id)
{
using namespace Utilities;
std::ostringstream query;
query << "SELECT id FROM Playlists WHERE title = ?";
sqlite3_stmt* stmt = createStmt( db, query.str() );
ON_BLOCK_EXIT(&sqlite3_finalize, stmt);
int rc_db = sqlite3_bind_text(stmt, 1, title, strlen(title), SQLITE_STATIC);
if (SQLITE_OK != rc_db) {
const std::string msg = MakeString() << "sqlite3_bind_text16() error " << rc_db;
throw std::runtime_error(msg);
}
for(;;) {
rc_db = sqlite3_step(stmt);
if (SQLITE_ROW == rc_db) {
assert(sqlite3_column_count(stmt) == 1);
if (playlist_id) {
*playlist_id = sqlite3_column_int(stmt, 0);
}
return true;
} else if (SQLITE_DONE == rc_db) {
break;
} else {
const std::string msg = MakeString() << "sqlite3_step() error "
<< rc_db << ": " << sqlite3_errmsg(db)
<< ". Query: " << query.str();
throw std::runtime_error(msg);
}
}
return false;
}
} // namespace UploadTrack
<commit_msg>add ability to specify playlist to upload track to.<commit_after>// Copyright (c) 2013, Alexey Ivanov
#include "stdafx.h"
#include "request_handler.h"
#include "../aimp/manager.h"
#include "../aimp/manager_impl_common.h"
#include "../http_server/reply.h"
#include "../http_server/request.h"
#include "../http_server/mime_types.h"
#include "utils/string_encoding.h"
#include "utils/util.h"
namespace UploadTrack
{
using namespace AIMPPlayer;
using namespace std;
namespace fs = boost::filesystem;
void fill_reply_disabled(Http::Reply& rep);
PlaylistID getPlaylistID(const std::string& uri);
const std::string kPlaylistIDTag("/playlist_id/");
bool RequestHandler::handle_request(const Http::Request& req, Http::Reply& rep)
{
using namespace Http;
if (!enabled_) {
fill_reply_disabled(rep);
return true;
}
try {
const PlaylistID playlist_id = getPlaylistID(req.uri);
for (auto field_it : req.mpfd_parser.GetFieldsMap()) {
const MPFD::Field& field_const = *field_it.second;
MPFD::Field& field = const_cast<MPFD::Field&>(field_const);
const std::string filename = field.GetFileName();
const fs::wpath path = temp_dir_ / filename;
{ // save to temp dir.
std::ofstream out(path.native(), std::ios_base::out | std::ios_base::binary);
out.write(field.GetFileContent(), field.GetFileContentSize());
out.close();
}
aimp_manager_.addFileToPlaylist(path, playlist_id);
// we should not erase file since AIMP will use it.
//fs::remove(path);
}
rep = Reply::stock_reply(Reply::ok);
} catch (MPFD::Exception&) {
rep = Reply::stock_reply(Reply::bad_request);
} catch (std::exception&) {
rep = Reply::stock_reply(Reply::forbidden);
}
return true;
}
void fill_reply_disabled(Http::Reply& rep)
{
rep.status = Http::Reply::forbidden;
rep.content = "403 Forbidden<br/> Track upload is disabled in Control plugin settings.";
rep.headers.resize(2);
rep.headers[0].name = "Content-Length";
rep.headers[0].value = boost::lexical_cast<std::string>(rep.content.size());
rep.headers[1].name = "Content-Type";
rep.headers[1].value = "text/html";
}
PlaylistID getPlaylistID(const std::string& uri)
{
size_t start_index = uri.find(kPlaylistIDTag);
if (start_index == string::npos) {
throw std::runtime_error("can't find playlist id tag in uri");
}
start_index += kPlaylistIDTag.length();
const string id(uri.c_str(), start_index, uri.length() - start_index);
const PlaylistID playlist_id = boost::lexical_cast<PlaylistID>(id);
return playlist_id;
}
} // namespace UploadTrack
<|endoftext|>
|
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id$
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/framework/XMLBuffer.hpp>
#include <xercesc/validators/common/ContentSpecNode.hpp>
#include <xercesc/validators/schema/SchemaSymbols.hpp>
#include <xercesc/util/ValueStackOf.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// ContentSpecNode: Copy Constructor
//
// Note: this copy constructor has dependency on various get*() methods
// and shall be placed after those method's declaration.
// aka inline function compilation error on AIX 4.2, xlC 3 r ev.1
// ---------------------------------------------------------------------------
ContentSpecNode::ContentSpecNode(const ContentSpecNode& toCopy) :
XSerializable(toCopy)
, XMemory(toCopy)
, fMemoryManager(toCopy.fMemoryManager)
, fElement(0)
, fElementDecl(toCopy.fElementDecl)
, fFirst(0)
, fSecond(0)
, fType(toCopy.fType)
, fAdoptFirst(true)
, fAdoptSecond(true)
, fMinOccurs(toCopy.fMinOccurs)
, fMaxOccurs(toCopy.fMaxOccurs)
{
const QName* tempElement = toCopy.getElement();
if (tempElement)
fElement = new (fMemoryManager) QName(*tempElement);
const ContentSpecNode *tmp = toCopy.getFirst();
if (tmp)
fFirst = new (fMemoryManager) ContentSpecNode(*tmp);
tmp = toCopy.getSecond();
if (tmp)
fSecond = new (fMemoryManager) ContentSpecNode(*tmp);
}
ContentSpecNode::~ContentSpecNode()
{
// Delete our children, avoiding recursive cleanup
if (fAdoptFirst && fFirst) {
deleteChildNode(fFirst);
}
if (fAdoptSecond && fSecond) {
deleteChildNode(fSecond);
}
delete fElement;
}
void ContentSpecNode::deleteChildNode(ContentSpecNode* node)
{
ValueStackOf<ContentSpecNode*> toBeDeleted(10, fMemoryManager);
toBeDeleted.push(node);
while(!toBeDeleted.empty())
{
ContentSpecNode* node = toBeDeleted.pop();
if(node==0)
continue;
if(node->isFirstAdopted())
toBeDeleted.push(node->orphanFirst());
if(node->isSecondAdopted())
toBeDeleted.push(node->orphanSecond());
delete node;
}
}
class formatNodeHolder
{
public:
formatNodeHolder(const ContentSpecNode* n, const ContentSpecNode::NodeTypes p, XMLCh c) : node(n), parentType(p), character(c) {}
formatNodeHolder& operator =(const formatNodeHolder* other)
{
node=other->node;
parentType=other->parentType;
character=other->character;
}
const ContentSpecNode* node;
ContentSpecNode::NodeTypes parentType;
XMLCh character;
};
// ---------------------------------------------------------------------------
// Local methods
// ---------------------------------------------------------------------------
static void formatNode( const ContentSpecNode* const curNode
, XMLBuffer& bufToFill
, MemoryManager* const memMgr)
{
if (!curNode)
return;
ValueStackOf<formatNodeHolder> toBeProcessed(10, memMgr);
toBeProcessed.push(formatNodeHolder(curNode, ContentSpecNode::UnknownType, 0));
while(!toBeProcessed.empty())
{
formatNodeHolder item=toBeProcessed.pop();
if(item.character!=0)
{
bufToFill.append(item.character);
continue;
}
const ContentSpecNode* curNode = item.node;
if(!curNode)
continue;
const ContentSpecNode::NodeTypes parentType = item.parentType;
const ContentSpecNode* first = curNode->getFirst();
const ContentSpecNode* second = curNode->getSecond();
const ContentSpecNode::NodeTypes curType = curNode->getType();
// Get the type of the first node
const ContentSpecNode::NodeTypes firstType = first ?
first->getType() :
ContentSpecNode::Leaf;
// Calculate the parens flag for the rep nodes
bool doRepParens = false;
if (((firstType != ContentSpecNode::Leaf)
&& (parentType != ContentSpecNode::UnknownType))
|| ((firstType == ContentSpecNode::Leaf)
&& (parentType == ContentSpecNode::UnknownType)))
{
doRepParens = true;
}
// Now handle our type
switch(curType & 0x0f)
{
case ContentSpecNode::Leaf :
if (curNode->getElement()->getURI() == XMLElementDecl::fgPCDataElemId)
bufToFill.append(XMLElementDecl::fgPCDataElemName);
else
{
bufToFill.append(curNode->getElement()->getRawName());
// show the + and * modifiers also when we have a non-infinite number of repetitions
if(curNode->getMinOccurs()==0 && (curNode->getMaxOccurs()==-1 || curNode->getMaxOccurs()>1))
bufToFill.append(chAsterisk);
else if(curNode->getMinOccurs()==0 && curNode->getMaxOccurs()==1)
bufToFill.append(chQuestion);
else if(curNode->getMinOccurs()==1 && (curNode->getMaxOccurs()==-1 || curNode->getMaxOccurs()>1))
bufToFill.append(chPlus);
}
break;
case ContentSpecNode::ZeroOrOne :
if (doRepParens)
bufToFill.append(chOpenParen);
toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chQuestion));
if (doRepParens)
toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen));
toBeProcessed.push(formatNodeHolder(first, curType, 0));
break;
case ContentSpecNode::ZeroOrMore :
if (doRepParens)
bufToFill.append(chOpenParen);
toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chAsterisk));
if (doRepParens)
toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen));
toBeProcessed.push(formatNodeHolder(first, curType, 0));
break;
case ContentSpecNode::OneOrMore :
if (doRepParens)
bufToFill.append(chOpenParen);
toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chPlus));
if (doRepParens)
toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen));
toBeProcessed.push(formatNodeHolder(first, curType, 0));
break;
case ContentSpecNode::Choice :
if ((parentType & 0x0f) != (curType & 0x0f))
bufToFill.append(chOpenParen);
if ((parentType & 0x0f) != (curType & 0x0f))
toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen));
if(second!=NULL)
{
toBeProcessed.push(formatNodeHolder(second, curType, 0));
toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chPipe));
}
toBeProcessed.push(formatNodeHolder(first, curType, 0));
break;
case ContentSpecNode::Sequence :
if ((parentType & 0x0f) != (curType & 0x0f))
bufToFill.append(chOpenParen);
if ((parentType & 0x0f) != (curType & 0x0f))
toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen));
if(second!=NULL)
{
toBeProcessed.push(formatNodeHolder(second, curType, 0));
toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chComma));
}
toBeProcessed.push(formatNodeHolder(first, curType, 0));
break;
case ContentSpecNode::All :
if ((parentType & 0x0f) != (curType & 0x0f))
{
bufToFill.append(chLatin_A);
bufToFill.append(chLatin_l);
bufToFill.append(chLatin_l);
bufToFill.append(chOpenParen);
}
if ((parentType & 0x0f) != (curType & 0x0f))
toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen));
toBeProcessed.push(formatNodeHolder(second, curType, 0));
toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chComma));
toBeProcessed.push(formatNodeHolder(first, curType, 0));
break;
}
}
}
// ---------------------------------------------------------------------------
// ContentSpecNode: Miscellaneous
// ---------------------------------------------------------------------------
void ContentSpecNode::formatSpec(XMLBuffer& bufToFill) const
{
// Clean out the buffer first
bufToFill.reset();
if (fType == ContentSpecNode::Leaf)
bufToFill.append(chOpenParen);
formatNode
(
this
, bufToFill
, fMemoryManager
);
if (fType == ContentSpecNode::Leaf)
bufToFill.append(chCloseParen);
}
int ContentSpecNode::getMinTotalRange() const {
int min = fMinOccurs;
if ((fType & 0x0f) == ContentSpecNode::Sequence
|| fType == ContentSpecNode::All
|| (fType & 0x0f) == ContentSpecNode::Choice) {
int minFirst = fFirst->getMinTotalRange();
if (fSecond) {
int minSecond = fSecond->getMinTotalRange();
if ((fType & 0x0f) == ContentSpecNode::Choice) {
min = min * ((minFirst < minSecond)? minFirst : minSecond);
}
else {
min = min * (minFirst + minSecond);
}
}
else
min = min * minFirst;
}
return min;
}
int ContentSpecNode::getMaxTotalRange() const {
int max = fMaxOccurs;
if (max == SchemaSymbols::XSD_UNBOUNDED) {
return SchemaSymbols::XSD_UNBOUNDED;
}
if ((fType & 0x0f) == ContentSpecNode::Sequence
|| fType == ContentSpecNode::All
|| (fType & 0x0f) == ContentSpecNode::Choice) {
int maxFirst = fFirst->getMaxTotalRange();
if (maxFirst == SchemaSymbols::XSD_UNBOUNDED) {
return SchemaSymbols::XSD_UNBOUNDED;
}
if (fSecond) {
int maxSecond = fSecond->getMaxTotalRange();
if (maxSecond == SchemaSymbols::XSD_UNBOUNDED) {
return SchemaSymbols::XSD_UNBOUNDED;
}
else {
if ((fType & 0x0f) == ContentSpecNode::Choice) {
max = max * ((maxFirst > maxSecond) ? maxFirst : maxSecond);
}
else {
max = max * (maxFirst + maxSecond);
}
}
}
else {
max = max * maxFirst;
}
}
return max;
}
/***
* Support for Serialization/De-serialization
***/
IMPL_XSERIALIZABLE_TOCREATE(ContentSpecNode)
void ContentSpecNode::serialize(XSerializeEngine& serEng)
{
/***
* Since fElement, fFirst, fSecond are NOT created by the default
* constructor, we need to create them dynamically.
***/
if (serEng.isStoring())
{
serEng<<fElement;
XMLElementDecl::storeElementDecl(serEng, fElementDecl);
serEng<<fFirst;
serEng<<fSecond;
serEng<<(int)fType;
serEng<<fAdoptFirst;
serEng<<fAdoptSecond;
serEng<<fMinOccurs;
serEng<<fMaxOccurs;
}
else
{
serEng>>fElement;
fElementDecl = XMLElementDecl::loadElementDecl(serEng);
serEng>>fFirst;
serEng>>fSecond;
int type;
serEng>>type;
fType = (NodeTypes)type;
serEng>>fAdoptFirst;
serEng>>fAdoptSecond;
serEng>>fMinOccurs;
serEng>>fMaxOccurs;
}
}
XERCES_CPP_NAMESPACE_END
<commit_msg>Add return statement to copy constructor (XERCESC-2001)<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id$
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/framework/XMLBuffer.hpp>
#include <xercesc/validators/common/ContentSpecNode.hpp>
#include <xercesc/validators/schema/SchemaSymbols.hpp>
#include <xercesc/util/ValueStackOf.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// ContentSpecNode: Copy Constructor
//
// Note: this copy constructor has dependency on various get*() methods
// and shall be placed after those method's declaration.
// aka inline function compilation error on AIX 4.2, xlC 3 r ev.1
// ---------------------------------------------------------------------------
ContentSpecNode::ContentSpecNode(const ContentSpecNode& toCopy) :
XSerializable(toCopy)
, XMemory(toCopy)
, fMemoryManager(toCopy.fMemoryManager)
, fElement(0)
, fElementDecl(toCopy.fElementDecl)
, fFirst(0)
, fSecond(0)
, fType(toCopy.fType)
, fAdoptFirst(true)
, fAdoptSecond(true)
, fMinOccurs(toCopy.fMinOccurs)
, fMaxOccurs(toCopy.fMaxOccurs)
{
const QName* tempElement = toCopy.getElement();
if (tempElement)
fElement = new (fMemoryManager) QName(*tempElement);
const ContentSpecNode *tmp = toCopy.getFirst();
if (tmp)
fFirst = new (fMemoryManager) ContentSpecNode(*tmp);
tmp = toCopy.getSecond();
if (tmp)
fSecond = new (fMemoryManager) ContentSpecNode(*tmp);
}
ContentSpecNode::~ContentSpecNode()
{
// Delete our children, avoiding recursive cleanup
if (fAdoptFirst && fFirst) {
deleteChildNode(fFirst);
}
if (fAdoptSecond && fSecond) {
deleteChildNode(fSecond);
}
delete fElement;
}
void ContentSpecNode::deleteChildNode(ContentSpecNode* node)
{
ValueStackOf<ContentSpecNode*> toBeDeleted(10, fMemoryManager);
toBeDeleted.push(node);
while(!toBeDeleted.empty())
{
ContentSpecNode* node = toBeDeleted.pop();
if(node==0)
continue;
if(node->isFirstAdopted())
toBeDeleted.push(node->orphanFirst());
if(node->isSecondAdopted())
toBeDeleted.push(node->orphanSecond());
delete node;
}
}
class formatNodeHolder
{
public:
formatNodeHolder(const ContentSpecNode* n, const ContentSpecNode::NodeTypes p, XMLCh c) : node(n), parentType(p), character(c) {}
formatNodeHolder& operator =(const formatNodeHolder* other)
{
node=other->node;
parentType=other->parentType;
character=other->character;
return *this;
}
const ContentSpecNode* node;
ContentSpecNode::NodeTypes parentType;
XMLCh character;
};
// ---------------------------------------------------------------------------
// Local methods
// ---------------------------------------------------------------------------
static void formatNode( const ContentSpecNode* const curNode
, XMLBuffer& bufToFill
, MemoryManager* const memMgr)
{
if (!curNode)
return;
ValueStackOf<formatNodeHolder> toBeProcessed(10, memMgr);
toBeProcessed.push(formatNodeHolder(curNode, ContentSpecNode::UnknownType, 0));
while(!toBeProcessed.empty())
{
formatNodeHolder item=toBeProcessed.pop();
if(item.character!=0)
{
bufToFill.append(item.character);
continue;
}
const ContentSpecNode* curNode = item.node;
if(!curNode)
continue;
const ContentSpecNode::NodeTypes parentType = item.parentType;
const ContentSpecNode* first = curNode->getFirst();
const ContentSpecNode* second = curNode->getSecond();
const ContentSpecNode::NodeTypes curType = curNode->getType();
// Get the type of the first node
const ContentSpecNode::NodeTypes firstType = first ?
first->getType() :
ContentSpecNode::Leaf;
// Calculate the parens flag for the rep nodes
bool doRepParens = false;
if (((firstType != ContentSpecNode::Leaf)
&& (parentType != ContentSpecNode::UnknownType))
|| ((firstType == ContentSpecNode::Leaf)
&& (parentType == ContentSpecNode::UnknownType)))
{
doRepParens = true;
}
// Now handle our type
switch(curType & 0x0f)
{
case ContentSpecNode::Leaf :
if (curNode->getElement()->getURI() == XMLElementDecl::fgPCDataElemId)
bufToFill.append(XMLElementDecl::fgPCDataElemName);
else
{
bufToFill.append(curNode->getElement()->getRawName());
// show the + and * modifiers also when we have a non-infinite number of repetitions
if(curNode->getMinOccurs()==0 && (curNode->getMaxOccurs()==-1 || curNode->getMaxOccurs()>1))
bufToFill.append(chAsterisk);
else if(curNode->getMinOccurs()==0 && curNode->getMaxOccurs()==1)
bufToFill.append(chQuestion);
else if(curNode->getMinOccurs()==1 && (curNode->getMaxOccurs()==-1 || curNode->getMaxOccurs()>1))
bufToFill.append(chPlus);
}
break;
case ContentSpecNode::ZeroOrOne :
if (doRepParens)
bufToFill.append(chOpenParen);
toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chQuestion));
if (doRepParens)
toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen));
toBeProcessed.push(formatNodeHolder(first, curType, 0));
break;
case ContentSpecNode::ZeroOrMore :
if (doRepParens)
bufToFill.append(chOpenParen);
toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chAsterisk));
if (doRepParens)
toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen));
toBeProcessed.push(formatNodeHolder(first, curType, 0));
break;
case ContentSpecNode::OneOrMore :
if (doRepParens)
bufToFill.append(chOpenParen);
toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chPlus));
if (doRepParens)
toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen));
toBeProcessed.push(formatNodeHolder(first, curType, 0));
break;
case ContentSpecNode::Choice :
if ((parentType & 0x0f) != (curType & 0x0f))
bufToFill.append(chOpenParen);
if ((parentType & 0x0f) != (curType & 0x0f))
toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen));
if(second!=NULL)
{
toBeProcessed.push(formatNodeHolder(second, curType, 0));
toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chPipe));
}
toBeProcessed.push(formatNodeHolder(first, curType, 0));
break;
case ContentSpecNode::Sequence :
if ((parentType & 0x0f) != (curType & 0x0f))
bufToFill.append(chOpenParen);
if ((parentType & 0x0f) != (curType & 0x0f))
toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen));
if(second!=NULL)
{
toBeProcessed.push(formatNodeHolder(second, curType, 0));
toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chComma));
}
toBeProcessed.push(formatNodeHolder(first, curType, 0));
break;
case ContentSpecNode::All :
if ((parentType & 0x0f) != (curType & 0x0f))
{
bufToFill.append(chLatin_A);
bufToFill.append(chLatin_l);
bufToFill.append(chLatin_l);
bufToFill.append(chOpenParen);
}
if ((parentType & 0x0f) != (curType & 0x0f))
toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chCloseParen));
toBeProcessed.push(formatNodeHolder(second, curType, 0));
toBeProcessed.push(formatNodeHolder(0, ContentSpecNode::UnknownType, chComma));
toBeProcessed.push(formatNodeHolder(first, curType, 0));
break;
}
}
}
// ---------------------------------------------------------------------------
// ContentSpecNode: Miscellaneous
// ---------------------------------------------------------------------------
void ContentSpecNode::formatSpec(XMLBuffer& bufToFill) const
{
// Clean out the buffer first
bufToFill.reset();
if (fType == ContentSpecNode::Leaf)
bufToFill.append(chOpenParen);
formatNode
(
this
, bufToFill
, fMemoryManager
);
if (fType == ContentSpecNode::Leaf)
bufToFill.append(chCloseParen);
}
int ContentSpecNode::getMinTotalRange() const {
int min = fMinOccurs;
if ((fType & 0x0f) == ContentSpecNode::Sequence
|| fType == ContentSpecNode::All
|| (fType & 0x0f) == ContentSpecNode::Choice) {
int minFirst = fFirst->getMinTotalRange();
if (fSecond) {
int minSecond = fSecond->getMinTotalRange();
if ((fType & 0x0f) == ContentSpecNode::Choice) {
min = min * ((minFirst < minSecond)? minFirst : minSecond);
}
else {
min = min * (minFirst + minSecond);
}
}
else
min = min * minFirst;
}
return min;
}
int ContentSpecNode::getMaxTotalRange() const {
int max = fMaxOccurs;
if (max == SchemaSymbols::XSD_UNBOUNDED) {
return SchemaSymbols::XSD_UNBOUNDED;
}
if ((fType & 0x0f) == ContentSpecNode::Sequence
|| fType == ContentSpecNode::All
|| (fType & 0x0f) == ContentSpecNode::Choice) {
int maxFirst = fFirst->getMaxTotalRange();
if (maxFirst == SchemaSymbols::XSD_UNBOUNDED) {
return SchemaSymbols::XSD_UNBOUNDED;
}
if (fSecond) {
int maxSecond = fSecond->getMaxTotalRange();
if (maxSecond == SchemaSymbols::XSD_UNBOUNDED) {
return SchemaSymbols::XSD_UNBOUNDED;
}
else {
if ((fType & 0x0f) == ContentSpecNode::Choice) {
max = max * ((maxFirst > maxSecond) ? maxFirst : maxSecond);
}
else {
max = max * (maxFirst + maxSecond);
}
}
}
else {
max = max * maxFirst;
}
}
return max;
}
/***
* Support for Serialization/De-serialization
***/
IMPL_XSERIALIZABLE_TOCREATE(ContentSpecNode)
void ContentSpecNode::serialize(XSerializeEngine& serEng)
{
/***
* Since fElement, fFirst, fSecond are NOT created by the default
* constructor, we need to create them dynamically.
***/
if (serEng.isStoring())
{
serEng<<fElement;
XMLElementDecl::storeElementDecl(serEng, fElementDecl);
serEng<<fFirst;
serEng<<fSecond;
serEng<<(int)fType;
serEng<<fAdoptFirst;
serEng<<fAdoptSecond;
serEng<<fMinOccurs;
serEng<<fMaxOccurs;
}
else
{
serEng>>fElement;
fElementDecl = XMLElementDecl::loadElementDecl(serEng);
serEng>>fFirst;
serEng>>fSecond;
int type;
serEng>>type;
fType = (NodeTypes)type;
serEng>>fAdoptFirst;
serEng>>fAdoptSecond;
serEng>>fMinOccurs;
serEng>>fMaxOccurs;
}
}
XERCES_CPP_NAMESPACE_END
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012-2018 Daniele Bartolini and individual contributors.
* License: https://github.com/dbartolini/crown/blob/master/LICENSE
*/
#include "core/containers/hash_map.h"
#include "core/json/json_object.h"
#include "core/json/sjson.h"
#include "core/memory/temp_allocator.h"
#include "core/strings/string_id.h"
#include "core/strings/string_stream.h"
#include "device/console_server.h"
namespace crown
{
ConsoleServer::ConsoleServer(Allocator& a)
: _clients(a)
, _commands(a)
{
}
void ConsoleServer::listen(u16 port, bool wait)
{
_server.bind(port);
_server.listen(5);
if (wait)
{
AcceptResult ar;
TCPSocket client;
do
{
ar = _server.accept(client);
}
while (ar.error != AcceptResult::SUCCESS);
array::push_back(_clients, client);
}
}
void ConsoleServer::shutdown()
{
for (u32 i = 0; i < array::size(_clients); ++i)
_clients[i].close();
_server.close();
}
void ConsoleServer::send(TCPSocket client, const char* json)
{
u32 len = strlen32(json);
client.write(&len, 4);
client.write(json, len);
}
void ConsoleServer::error(TCPSocket client, const char* msg)
{
TempAllocator4096 ta;
StringStream ss(ta);
ss << "{\"type\":\"error\",\"message\":\"" << msg << "\"}";
send(client, string_stream::c_str(ss));
}
void ConsoleServer::log(LogSeverity::Enum sev, const char* system, const char* msg)
{
const char* severity_map[] = { "info", "warning", "error" };
CE_STATIC_ASSERT(countof(severity_map) == LogSeverity::COUNT);
TempAllocator4096 ta;
StringStream ss(ta);
ss << "{\"type\":\"message\",\"severity\":\"";
ss << severity_map[sev];
ss << "\",\"system\":\"";
ss << system;
ss << "\",\"message\":\"";
// Sanitize msg
const char* ch = msg;
for (; *ch; ch++)
{
if (*ch == '"' || *ch == '\\')
ss << "\\";
ss << *ch;
}
ss << "\"}";
send(string_stream::c_str(ss));
}
void ConsoleServer::send(const char* json)
{
for (u32 i = 0; i < array::size(_clients); ++i)
send(_clients[i], json);
}
void ConsoleServer::update()
{
TCPSocket client;
AcceptResult ar = _server.accept_nonblock(client);
if (ar.error == AcceptResult::SUCCESS)
array::push_back(_clients, client);
TempAllocator256 alloc;
Array<u32> to_remove(alloc);
// Update all clients
for (u32 i = 0; i < array::size(_clients); ++i)
{
for (;;)
{
u32 msg_len = 0;
ReadResult rr = _clients[i].read_nonblock(&msg_len, 4);
if (rr.error == ReadResult::WOULDBLOCK)
break;
if (rr.error != ReadResult::SUCCESS)
{
array::push_back(to_remove, i);
break;
}
// Read message
TempAllocator4096 ta;
Array<char> msg(ta);
array::resize(msg, msg_len + 1);
rr = _clients[i].read(array::begin(msg), msg_len);
array::push_back(msg, '\0');
if (rr.error != ReadResult::SUCCESS)
{
array::push_back(to_remove, i);
break;
}
// Process message
JsonObject obj(ta);
sjson::parse(array::begin(msg), obj);
Command cmd;
cmd.function = NULL;
cmd.user_data = NULL;
cmd = hash_map::get(_commands
, sjson::parse_string_id(obj["type"])
, cmd
);
if (cmd.function)
cmd.function(*this, _clients[i], array::begin(msg), cmd.user_data);
else
error(_clients[i], "Unknown command");
}
}
// Remove clients
for (u32 i = 0; i < array::size(to_remove); ++i)
{
const u32 last = array::size(_clients) - 1;
const u32 c = to_remove[i];
_clients[c].close();
_clients[c] = _clients[last];
array::pop_back(_clients);
}
}
void ConsoleServer::register_command(const char* type, CommandFunction function, void* user_data)
{
CE_ENSURE(NULL != type);
CE_ENSURE(NULL != function);
Command cmd;
cmd.function = function;
cmd.user_data = user_data;
hash_map::set(_commands, StringId32(type), cmd);
}
namespace console_server_globals
{
ConsoleServer* _console_server = NULL;
void init()
{
_console_server = CE_NEW(default_allocator(), ConsoleServer)(default_allocator());
}
void shutdown()
{
_console_server->shutdown();
CE_DELETE(default_allocator(), _console_server);
_console_server = NULL;
}
} // namespace console_server_globals
ConsoleServer* console_server()
{
return console_server_globals::_console_server;
}
} // namespace crown
<commit_msg>device: correctly terminate string buffer<commit_after>/*
* Copyright (c) 2012-2018 Daniele Bartolini and individual contributors.
* License: https://github.com/dbartolini/crown/blob/master/LICENSE
*/
#include "core/containers/hash_map.h"
#include "core/json/json_object.h"
#include "core/json/sjson.h"
#include "core/memory/temp_allocator.h"
#include "core/strings/string_id.h"
#include "core/strings/string_stream.h"
#include "device/console_server.h"
namespace crown
{
ConsoleServer::ConsoleServer(Allocator& a)
: _clients(a)
, _commands(a)
{
}
void ConsoleServer::listen(u16 port, bool wait)
{
_server.bind(port);
_server.listen(5);
if (wait)
{
AcceptResult ar;
TCPSocket client;
do
{
ar = _server.accept(client);
}
while (ar.error != AcceptResult::SUCCESS);
array::push_back(_clients, client);
}
}
void ConsoleServer::shutdown()
{
for (u32 i = 0; i < array::size(_clients); ++i)
_clients[i].close();
_server.close();
}
void ConsoleServer::send(TCPSocket client, const char* json)
{
u32 len = strlen32(json);
client.write(&len, 4);
client.write(json, len);
}
void ConsoleServer::error(TCPSocket client, const char* msg)
{
TempAllocator4096 ta;
StringStream ss(ta);
ss << "{\"type\":\"error\",\"message\":\"" << msg << "\"}";
send(client, string_stream::c_str(ss));
}
void ConsoleServer::log(LogSeverity::Enum sev, const char* system, const char* msg)
{
const char* severity_map[] = { "info", "warning", "error" };
CE_STATIC_ASSERT(countof(severity_map) == LogSeverity::COUNT);
TempAllocator4096 ta;
StringStream ss(ta);
ss << "{\"type\":\"message\",\"severity\":\"";
ss << severity_map[sev];
ss << "\",\"system\":\"";
ss << system;
ss << "\",\"message\":\"";
// Sanitize msg
const char* ch = msg;
for (; *ch; ch++)
{
if (*ch == '"' || *ch == '\\')
ss << "\\";
ss << *ch;
}
ss << "\"}";
send(string_stream::c_str(ss));
}
void ConsoleServer::send(const char* json)
{
for (u32 i = 0; i < array::size(_clients); ++i)
send(_clients[i], json);
}
void ConsoleServer::update()
{
TCPSocket client;
AcceptResult ar = _server.accept_nonblock(client);
if (ar.error == AcceptResult::SUCCESS)
array::push_back(_clients, client);
TempAllocator256 alloc;
Array<u32> to_remove(alloc);
// Update all clients
for (u32 i = 0; i < array::size(_clients); ++i)
{
for (;;)
{
u32 msg_len = 0;
ReadResult rr = _clients[i].read_nonblock(&msg_len, 4);
if (rr.error == ReadResult::WOULDBLOCK)
break;
if (rr.error != ReadResult::SUCCESS)
{
array::push_back(to_remove, i);
break;
}
// Read message
TempAllocator4096 ta;
Array<char> msg(ta);
array::resize(msg, msg_len + 1);
rr = _clients[i].read(array::begin(msg), msg_len);
msg[msg_len] = '\0';
if (rr.error != ReadResult::SUCCESS)
{
array::push_back(to_remove, i);
break;
}
// Process message
JsonObject obj(ta);
sjson::parse(array::begin(msg), obj);
Command cmd;
cmd.function = NULL;
cmd.user_data = NULL;
cmd = hash_map::get(_commands
, sjson::parse_string_id(obj["type"])
, cmd
);
if (cmd.function)
cmd.function(*this, _clients[i], array::begin(msg), cmd.user_data);
else
error(_clients[i], "Unknown command");
}
}
// Remove clients
for (u32 i = 0; i < array::size(to_remove); ++i)
{
const u32 last = array::size(_clients) - 1;
const u32 c = to_remove[i];
_clients[c].close();
_clients[c] = _clients[last];
array::pop_back(_clients);
}
}
void ConsoleServer::register_command(const char* type, CommandFunction function, void* user_data)
{
CE_ENSURE(NULL != type);
CE_ENSURE(NULL != function);
Command cmd;
cmd.function = function;
cmd.user_data = user_data;
hash_map::set(_commands, StringId32(type), cmd);
}
namespace console_server_globals
{
ConsoleServer* _console_server = NULL;
void init()
{
_console_server = CE_NEW(default_allocator(), ConsoleServer)(default_allocator());
}
void shutdown()
{
_console_server->shutdown();
CE_DELETE(default_allocator(), _console_server);
_console_server = NULL;
}
} // namespace console_server_globals
ConsoleServer* console_server()
{
return console_server_globals::_console_server;
}
} // namespace crown
<|endoftext|>
|
<commit_before>#include <PCU.h>
#include "phRestart.h"
#include <apf.h>
#include "phIO.h"
#include "ph.h"
#include <cstdlib>
#include <fstream>
#include <sstream>
#include <cassert>
namespace ph {
/* in_size is the number of dofs for the data array
and out_size is the number of dofs in the field.
they are unequal when we read a restart file
and want to add more dofs for the next restart files */
void attachField(
apf::Mesh* m,
const char* fieldname,
double* data,
int in_size,
int out_size)
{
if (!(in_size <= out_size))
fprintf(stderr, "field \"%s\" in_size %d out_size %d\n", fieldname, in_size, out_size);
assert(in_size <= out_size);
apf::Field* f = apf::createPackedField(m, fieldname, out_size);
size_t n = m->count(0);
apf::NewArray<double> c(out_size);
apf::MeshEntity* e;
size_t i = 0;
apf::MeshIterator* it = m->begin(0);
while ((e = m->iterate(it))) {
for (int j = 0; j < in_size; ++j)
c[j] = data[j * n + i];
apf::setComponents(f, e, 0, &c[0]);
++i;
}
m->end(it);
assert(i == n);
}
/* convenience wrapper, in most cases in_size=out_size */
void attachField(
apf::Mesh* m,
const char* fieldname,
double* data,
int size)
{
attachField(m, fieldname, data, size, size);
}
void detachField(
apf::Field* f,
double*& data,
int& size)
{
apf::Mesh* m = apf::getMesh(f);
size = apf::countComponents(f);
size_t n = m->count(0);
apf::NewArray<double> c(size);
data = (double*)malloc(sizeof(double) * size * m->count(0));
apf::MeshEntity* e;
size_t i = 0;
apf::MeshIterator* it = m->begin(0);
while ((e = m->iterate(it))) {
apf::getComponents(f, e, 0, &c[0]);
for (int j = 0; j < size; ++j)
data[j * n + i] = c[j];
++i;
}
m->end(it);
assert(i == n);
apf::destroyField(f);
}
void detachField(
apf::Mesh* m,
const char* fieldname,
double*& data,
int& size)
{
apf::Field* f = m->findField(fieldname);
assert(f);
detachField(f, data, size);
}
int readAndAttachField(
Input& in,
FILE* f,
apf::Mesh* m,
int swap)
{
double* data;
int nodes, vars, step;
char hname[1024];
const char* anyfield = "";
int ret = ph_read_field(f, anyfield, swap,
&data, &nodes, &vars, &step, hname);
/* no field was found or the field has an empty data block */
if(ret==0 || ret==1) return ret;
assert(nodes == static_cast<int>(m->count(0)));
assert(step == in.timeStepNumber);
int out_size = vars;
if ( std::string(hname) == std::string("solution") )
out_size = in.ensa_dof;
attachField(m, hname, data, vars, out_size);
free(data);
return 1;
}
void detachAndWriteField(
Input& in,
apf::Mesh* m,
FILE* f,
const char* fieldname)
{
double* data;
int size;
detachField(m, fieldname, data, size);
ph_write_field(f, fieldname, data, m->count(0), size, in.timeStepNumber);
free(data);
}
/* silliest darn fields I ever did see */
static double* buildMappingPartId(apf::Mesh* m)
{
int n = m->count(0);
/* malloc instead of new[] for consistency with ph_read_field */
double* data = (double*)malloc(sizeof(double) * n);
int self = PCU_Comm_Self();
for (int i = 0; i < n; ++i)
data[i] = self;
return data;
}
static double* buildMappingVtxId(apf::Mesh* m)
{
int n = m->count(0);
/* malloc instead of new[] for consistency with ph_read_field */
double* data = (double*)malloc(sizeof(double) * n);
for (int i = 0; i < n; ++i)
data[i] = i;
return data;
}
static std::string buildRestartFileName(std::string prefix, int step)
{
std::stringstream ss;
int rank = PCU_Comm_Self() + 1;
ss << prefix << '.' << step << '.' << rank;
return ss.str();
}
void readAndAttachFields(Input& in, apf::Mesh* m) {
double t0 = PCU_Time();
setupInputSubdir(in.restartFileName);
std::string filename = buildRestartFileName(in.restartFileName, in.timeStepNumber);
FILE* f = in.openfile_read(in, filename.c_str());
if (!f) {
fprintf(stderr,"failed to open \"%s\"!\n", filename.c_str());
abort();
}
int swap = ph_should_swap(f);
while( readAndAttachField(in,f,m,swap) ); /* inf loop?? */
fclose(f);
double t1 = PCU_Time();
if (!PCU_Comm_Self())
printf("fields read and attached in %f seconds\n", t1 - t0);
}
void buildMapping(apf::Mesh* m)
{
double* mapping = buildMappingPartId(m);
attachField(m, "mapping_partid", mapping, 1);
free(mapping);
mapping = buildMappingVtxId(m);
attachField(m, "mapping_vtxid", mapping, 1);
free(mapping);
}
void attachZeroSolution(Input& in, apf::Mesh* m)
{
int vars = in.ensa_dof;
int nodes = m->count(0);
double* data = new double[nodes * vars]();
attachField(m, "solution", data, vars);
delete [] data;
}
void detachAndWriteSolution(Input& in, Output& out, apf::Mesh* m, std::string path)
{
double t0 = PCU_Time();
path += buildRestartFileName("restart", in.timeStepNumber);
FILE* f = out.openfile_write(out, path.c_str());
if (!f) {
fprintf(stderr,"failed to open \"%s\"!\n", path.c_str());
abort();
}
ph_write_preamble(f);
int nodes = m->count(0);
ph_write_header(f, "number of modes", 0, 1, &nodes);
ph_write_header(f, "number of variables", 0, 1, &in.ensa_dof);
apf::Field* errField = m->findField("errors");
if (errField)
apf::destroyField(errField);
if (m->findField("solution"))
detachAndWriteField(in, m, f, "solution");
if (in.displacementMigration)
detachAndWriteField(in, m, f, "displacement");
if (in.dwalMigration)
detachAndWriteField(in, m, f, "dwal");
if (in.buildMapping) {
detachAndWriteField(in, m, f, "mapping_partid");
detachAndWriteField(in, m, f, "mapping_vtxid");
}
/* detach any remaining fields */
while(m->countFields())
apf::destroyField( m->getField(0) );
fclose(f);
double t1 = PCU_Time();
if (!PCU_Comm_Self())
printf("solution written in %f seconds\n", t1 - t0);
}
}
<commit_msg>try to ignore PHASTA array VOF solution<commit_after>#include <PCU.h>
#include "phRestart.h"
#include <apf.h>
#include "phIO.h"
#include "ph.h"
#include <cstdlib>
#include <fstream>
#include <sstream>
#include <cassert>
namespace ph {
/* in_size is the number of dofs for the data array
and out_size is the number of dofs in the field.
they are unequal when we read a restart file
and want to add more dofs for the next restart files */
void attachField(
apf::Mesh* m,
const char* fieldname,
double* data,
int in_size,
int out_size)
{
if (!(in_size <= out_size))
fprintf(stderr, "field \"%s\" in_size %d out_size %d\n", fieldname, in_size, out_size);
assert(in_size <= out_size);
apf::Field* f = apf::createPackedField(m, fieldname, out_size);
size_t n = m->count(0);
apf::NewArray<double> c(out_size);
apf::MeshEntity* e;
size_t i = 0;
apf::MeshIterator* it = m->begin(0);
while ((e = m->iterate(it))) {
for (int j = 0; j < in_size; ++j)
c[j] = data[j * n + i];
apf::setComponents(f, e, 0, &c[0]);
++i;
}
m->end(it);
assert(i == n);
}
/* convenience wrapper, in most cases in_size=out_size */
void attachField(
apf::Mesh* m,
const char* fieldname,
double* data,
int size)
{
attachField(m, fieldname, data, size, size);
}
void detachField(
apf::Field* f,
double*& data,
int& size)
{
apf::Mesh* m = apf::getMesh(f);
size = apf::countComponents(f);
size_t n = m->count(0);
apf::NewArray<double> c(size);
data = (double*)malloc(sizeof(double) * size * m->count(0));
apf::MeshEntity* e;
size_t i = 0;
apf::MeshIterator* it = m->begin(0);
while ((e = m->iterate(it))) {
apf::getComponents(f, e, 0, &c[0]);
for (int j = 0; j < size; ++j)
data[j * n + i] = c[j];
++i;
}
m->end(it);
assert(i == n);
apf::destroyField(f);
}
void detachField(
apf::Mesh* m,
const char* fieldname,
double*& data,
int& size)
{
apf::Field* f = m->findField(fieldname);
assert(f);
detachField(f, data, size);
}
int readAndAttachField(
Input& in,
FILE* f,
apf::Mesh* m,
int swap)
{
double* data;
int nodes, vars, step;
char hname[1024];
const char* anyfield = "";
int ret = ph_read_field(f, anyfield, swap,
&data, &nodes, &vars, &step, hname);
/* no field was found or the field has an empty data block */
if(ret==0 || ret==1)
return ret;
if ( std::string(hname) == std::string("VOF solution") )
return 1;
assert(nodes == static_cast<int>(m->count(0)));
assert(step == in.timeStepNumber);
int out_size = vars;
if ( std::string(hname) == std::string("solution") )
out_size = in.ensa_dof;
attachField(m, hname, data, vars, out_size);
free(data);
return 1;
}
void detachAndWriteField(
Input& in,
apf::Mesh* m,
FILE* f,
const char* fieldname)
{
double* data;
int size;
detachField(m, fieldname, data, size);
ph_write_field(f, fieldname, data, m->count(0), size, in.timeStepNumber);
free(data);
}
/* silliest darn fields I ever did see */
static double* buildMappingPartId(apf::Mesh* m)
{
int n = m->count(0);
/* malloc instead of new[] for consistency with ph_read_field */
double* data = (double*)malloc(sizeof(double) * n);
int self = PCU_Comm_Self();
for (int i = 0; i < n; ++i)
data[i] = self;
return data;
}
static double* buildMappingVtxId(apf::Mesh* m)
{
int n = m->count(0);
/* malloc instead of new[] for consistency with ph_read_field */
double* data = (double*)malloc(sizeof(double) * n);
for (int i = 0; i < n; ++i)
data[i] = i;
return data;
}
static std::string buildRestartFileName(std::string prefix, int step)
{
std::stringstream ss;
int rank = PCU_Comm_Self() + 1;
ss << prefix << '.' << step << '.' << rank;
return ss.str();
}
void readAndAttachFields(Input& in, apf::Mesh* m) {
double t0 = PCU_Time();
setupInputSubdir(in.restartFileName);
std::string filename = buildRestartFileName(in.restartFileName, in.timeStepNumber);
FILE* f = in.openfile_read(in, filename.c_str());
if (!f) {
fprintf(stderr,"failed to open \"%s\"!\n", filename.c_str());
abort();
}
int swap = ph_should_swap(f);
/* stops when ph_read_field returns 0 */
while( readAndAttachField(in,f,m,swap) );
fclose(f);
double t1 = PCU_Time();
if (!PCU_Comm_Self())
printf("fields read and attached in %f seconds\n", t1 - t0);
}
void buildMapping(apf::Mesh* m)
{
double* mapping = buildMappingPartId(m);
attachField(m, "mapping_partid", mapping, 1);
free(mapping);
mapping = buildMappingVtxId(m);
attachField(m, "mapping_vtxid", mapping, 1);
free(mapping);
}
void attachZeroSolution(Input& in, apf::Mesh* m)
{
int vars = in.ensa_dof;
int nodes = m->count(0);
double* data = new double[nodes * vars]();
attachField(m, "solution", data, vars);
delete [] data;
}
void detachAndWriteSolution(Input& in, Output& out, apf::Mesh* m, std::string path)
{
double t0 = PCU_Time();
path += buildRestartFileName("restart", in.timeStepNumber);
FILE* f = out.openfile_write(out, path.c_str());
if (!f) {
fprintf(stderr,"failed to open \"%s\"!\n", path.c_str());
abort();
}
ph_write_preamble(f);
int nodes = m->count(0);
ph_write_header(f, "number of modes", 0, 1, &nodes);
ph_write_header(f, "number of variables", 0, 1, &in.ensa_dof);
apf::Field* errField = m->findField("errors");
if (errField)
apf::destroyField(errField);
if (m->findField("solution"))
detachAndWriteField(in, m, f, "solution");
if (in.displacementMigration)
detachAndWriteField(in, m, f, "displacement");
if (in.dwalMigration)
detachAndWriteField(in, m, f, "dwal");
if (in.buildMapping) {
detachAndWriteField(in, m, f, "mapping_partid");
detachAndWriteField(in, m, f, "mapping_vtxid");
}
/* detach any remaining fields */
while(m->countFields())
apf::destroyField( m->getField(0) );
fclose(f);
double t1 = PCU_Time();
if (!PCU_Comm_Self())
printf("solution written in %f seconds\n", t1 - t0);
}
}
<|endoftext|>
|
<commit_before>#include "robotpath.h"
RobotPath::RobotPath(RobotGridMatrix *Maze, QList<QPoint> botOnePath, QList<QPoint> botTwoPath){
this->botOnePath = &botOnePath;
this->botTwoPath = &botTwoPath;
for(int r=0; r < 8; r++)
for(int c=0; c < 10; c++)
this->Maze[r][c] = Maze->Maze[r][c];
//this->Maze = Maze->Maze;
Robot bot1, bot2;
{
bot1.Pos = QPoint(9,0);
bot1.Dir = DOWN;
bot1.PrevDir = DEFAULT;
this->botOnePath->append(bot1.Pos);
qDebug("ACTUAL: Maze[%d][%d] {0}",bot1.Pos.x(),bot1.Pos.y());
}
{
bot2.Pos = QPoint(9,7);
bot2.Dir = UP;
bot2.PrevDir = DEFAULT;
this->botTwoPath->append(bot2.Pos);
}
int t=1;
while((bot1.Pos != QPoint(0,7))) {
this->FindDirection(bot1, 1);
this->MakeStep(bot1);
qDebug("ACTUAL: Maze[%d][%d] {%d}",bot1.Pos.x(),bot1.Pos.y(),t);
this->botOnePath->append(bot1.Pos);
if(t > 20) break;
t++;
}
/*
while((bot2.Pos != QPoint(0,0))) {
//for(int t; t < 10; t++) {
bot2.Dir = this->FindDirection(bot2, BOT2);
this->MakeStep(&bot2); qDebug("hire2 %d",t);
this->botTwoPath->append(bot2.Pos);
}*/
}
RobotPath::RobotPath(Map maze, QList<QPoint> botOnePath, QList<QPoint> botTwoPath) {
this->botOnePath = &botOnePath;
this->botTwoPath = &botTwoPath;
this->map = &maze;
Robot bot1, bot2;
{
bot1.ID = 1;
bot1.Pos = QPoint(9,0);
bot1.Dir = DOWN;
bot1.PrevDir = DEFAULT;
this->botOnePath->append(bot1.Pos);
qDebug("ACTUAL: Maze[%d][%d] {0}",bot1.Pos.x(),bot1.Pos.y());
}
{
bot2.ID = 2;
bot2.Pos = QPoint(9,7);
bot2.Dir = UP;
bot2.PrevDir = DEFAULT;
this->botTwoPath->append(bot2.Pos);
}
while((bot1.Pos != QPoint(0,7))) {
this->Movement(bot1);
this->botOnePath->append(bot1.Pos);
qDebug("ACTUAL: MAZE[%d][%d]",bot1.Pos.x(),bot1.Pos.y());
}
}
void RobotPath::Movement(Robot &bot) {
switch(bot.ID) {
case 1: {
if(this->map->popValue(QPoint_LEFT+bot.Pos) == bot.ID || this->map->popValue(QPoint_LEFT+bot.Pos) == SHARED) {
if(bot.PrevDir != RIGHT) {
bot.PrevDir = bot.Dir = LEFT;
bot.Pos += QPoint_LEFT;
return;
}
}
if(this->map->popValue(QPoint_DOWN+bot.Pos) == bot.ID || this->map->popValue(QPoint_DOWN+bot.Pos) == SHARED) {
if(bot.PrevDir != UP) {
bot.PrevDir = bot.Dir = DOWN;
bot.Pos += QPoint_DOWN;
return;
}
}
if(this->map->popValue(QPoint_UP+bot.Pos) == bot.ID || this->map->popValue(QPoint_UP+bot.Pos) == SHARED) {
if(bot.PrevDir != DOWN) {
bot.PrevDir = bot.Dir = UP;
bot.Pos += QPoint_UP;
return;
}
}
if(this->map->popValue(QPoint_RIGHT+bot.Pos) == bot.ID || this->map->popValue(QPoint_RIGHT+bot.Pos) == SHARED) {
if(bot.PrevDir != LEFT) {
bot.PrevDir = bot.Dir = RIGHT;
bot.Pos += QPoint_RIGHT;
return;
}
}
} break;
case 2: {
if(this->map->popValue(QPoint_LEFT+bot.Pos) == bot.ID || this->map->popValue(QPoint_LEFT+bot.Pos) == SHARED) {
if(bot.PrevDir != RIGHT) {
bot.PrevDir = bot.Dir = LEFT;
bot.Pos += QPoint_LEFT;
return;
}
}
if(this->map->popValue(QPoint_UP+bot.Pos) == bot.ID || this->map->popValue(QPoint_UP+bot.Pos) == SHARED) {
if(bot.PrevDir != DOWN) {
bot.PrevDir = bot.Dir = UP;
bot.Pos += QPoint_UP;
return;
}
}
if(this->map->popValue(QPoint_DOWN+bot.Pos) == bot.ID || this->map->popValue(QPoint_DOWN+bot.Pos) == SHARED) {
if(bot.PrevDir != UP) {
bot.PrevDir = bot.Dir = DOWN;
bot.Pos += QPoint_DOWN;
return;
}
}
if(this->map->popValue(QPoint_RIGHT+bot.Pos) == bot.ID || this->map->popValue(QPoint_RIGHT+bot.Pos) == SHARED) {
if(bot.PrevDir != LEFT) {
bot.PrevDir = bot.Dir = RIGHT;
bot.Pos += QPoint_RIGHT;
return;
}
}
} break;
}
}
RobotPath::~RobotPath(){}
void RobotPath::FindDirection(Robot& BOT, int Elem){
int x,y;
x = BOT.Pos.x(); // position swap
y = BOT.Pos.y(); // position swap
switch(Elem) {
case 1: {
if(this->Maze[x][y-1] == Elem || this->Maze[x][y-1] == SHARED) {
qDebug("LEFT: Maze[%d][%d] == %d",y-1,x,this->Maze[x][y-1]);
if(BOT.PrevDir != RIGHT) {
BOT.PrevDir = BOT.Dir;
BOT.Dir = LEFT;
return;
}
}
if(this->Maze[x+1][y] == Elem || this->Maze[x+1][y] == SHARED) {
qDebug("DOWN: Maze[%d][%d] == %d",y,x+1,this->Maze[x+1][y]);
if(BOT.PrevDir != UP) {
BOT.PrevDir = BOT.Dir;
BOT.Dir = DOWN;
return;
}
}
if(this->Maze[x-1][y] == Elem || this->Maze[x-1][y] == SHARED) {
qDebug("UP: Maze[%d][%d] == %d",x-1,y,this->Maze[x-1][y]);
if(BOT.PrevDir != DOWN) {
BOT.PrevDir = BOT.Dir;
BOT.Dir = UP;
return;
}
}
if(this->Maze[x][y+1] == Elem || this->Maze[x][y+1] == SHARED) {
qDebug("RIGHT: Maze[%d][%d] == %d",x,y+1,this->Maze[x][y+1]);
if(BOT.PrevDir != LEFT) {
BOT.PrevDir = BOT.Dir;
BOT.Dir = RIGHT;
return;
}
}
}
}
//BOT.Dir = LEFT;
}
void RobotPath::MakeStep(Robot& BOT){
switch(BOT.Dir){
case UP: BOT.Pos.rx()--; break;
case DOWN: BOT.Pos.rx()++; break;
case LEFT: BOT.Pos.ry()--; break;
case RIGHT: BOT.Pos.ry()++; break;
}
BOT.Dir = DEFAULT;
}
<commit_msg>added the save of second movement position<commit_after>#include "robotpath.h"
RobotPath::RobotPath(RobotGridMatrix *Maze, QList<QPoint> botOnePath, QList<QPoint> botTwoPath){
this->botOnePath = &botOnePath;
this->botTwoPath = &botTwoPath;
for(int r=0; r < 8; r++)
for(int c=0; c < 10; c++)
this->Maze[r][c] = Maze->Maze[r][c];
//this->Maze = Maze->Maze;
Robot bot1, bot2;
{
bot1.Pos = QPoint(9,0);
bot1.Dir = DOWN;
bot1.PrevDir = DEFAULT;
this->botOnePath->append(bot1.Pos);
qDebug("ACTUAL: Maze[%d][%d] {0}",bot1.Pos.x(),bot1.Pos.y());
}
{
bot2.Pos = QPoint(9,7);
bot2.Dir = UP;
bot2.PrevDir = DEFAULT;
this->botTwoPath->append(bot2.Pos);
}
int t=1;
while((bot1.Pos != QPoint(0,7))) {
this->FindDirection(bot1, 1);
this->MakeStep(bot1);
qDebug("ACTUAL: Maze[%d][%d] {%d}",bot1.Pos.x(),bot1.Pos.y(),t);
this->botOnePath->append(bot1.Pos);
if(t > 20) break;
t++;
}
/*
while((bot2.Pos != QPoint(0,0))) {
//for(int t; t < 10; t++) {
bot2.Dir = this->FindDirection(bot2, BOT2);
this->MakeStep(&bot2); qDebug("hire2 %d",t);
this->botTwoPath->append(bot2.Pos);
}*/
}
RobotPath::RobotPath(Map maze, QList<QPoint> botOnePath, QList<QPoint> botTwoPath) {
this->botOnePath = &botOnePath;
this->botTwoPath = &botTwoPath;
this->map = &maze;
Robot bot1, bot2;
{
bot1.ID = 1;
bot1.Pos = QPoint(9,0);
bot1.Dir = DOWN;
bot1.PrevDir = DEFAULT;
this->botOnePath->append(bot1.Pos);
qDebug("ACTUAL: Maze[%d][%d] {0}",bot1.Pos.x(),bot1.Pos.y());
}
{
bot2.ID = 2;
bot2.Pos = QPoint(9,7);
bot2.Dir = UP;
bot2.PrevDir = DEFAULT;
this->botTwoPath->append(bot2.Pos);
}
while((bot1.Pos != QPoint(0,7))) {
this->Movement(bot1);
this->botOnePath->append(bot1.Pos);
qDebug("ACTUAL: MAZE[%d][%d]",bot1.Pos.x(),bot1.Pos.y());
}
while((bot2.Pos != QPoint(0,0))) {
this->Movement(bot2);
this->botOnePath->append(bot2.Pos);
qDebug("ACTUAL2: MAZE[%d][%d]",bot2.Pos.x(),bot2.Pos.y());
}
}
void RobotPath::Movement(Robot &bot) {
switch(bot.ID) {
case 1: {
if(this->map->popValue(QPoint_LEFT+bot.Pos) == bot.ID || this->map->popValue(QPoint_LEFT+bot.Pos) == SHARED) {
if(bot.PrevDir != RIGHT) {
bot.PrevDir = bot.Dir = LEFT;
bot.Pos += QPoint_LEFT;
return;
}
}
if(this->map->popValue(QPoint_DOWN+bot.Pos) == bot.ID || this->map->popValue(QPoint_DOWN+bot.Pos) == SHARED) {
if(bot.PrevDir != UP) {
bot.PrevDir = bot.Dir = DOWN;
bot.Pos += QPoint_DOWN;
return;
}
}
if(this->map->popValue(QPoint_UP+bot.Pos) == bot.ID || this->map->popValue(QPoint_UP+bot.Pos) == SHARED) {
if(bot.PrevDir != DOWN) {
bot.PrevDir = bot.Dir = UP;
bot.Pos += QPoint_UP;
return;
}
}
if(this->map->popValue(QPoint_RIGHT+bot.Pos) == bot.ID || this->map->popValue(QPoint_RIGHT+bot.Pos) == SHARED) {
if(bot.PrevDir != LEFT) {
bot.PrevDir = bot.Dir = RIGHT;
bot.Pos += QPoint_RIGHT;
return;
}
}
} break;
case 2: {
if(this->map->popValue(QPoint_LEFT+bot.Pos) == bot.ID || this->map->popValue(QPoint_LEFT+bot.Pos) == SHARED) {
if(bot.PrevDir != RIGHT) {
bot.PrevDir = bot.Dir = LEFT;
bot.Pos += QPoint_LEFT;
return;
}
}
if(this->map->popValue(QPoint_UP+bot.Pos) == bot.ID || this->map->popValue(QPoint_UP+bot.Pos) == SHARED) {
if(bot.PrevDir != DOWN) {
bot.PrevDir = bot.Dir = UP;
bot.Pos += QPoint_UP;
return;
}
}
if(this->map->popValue(QPoint_DOWN+bot.Pos) == bot.ID || this->map->popValue(QPoint_DOWN+bot.Pos) == SHARED) {
if(bot.PrevDir != UP) {
bot.PrevDir = bot.Dir = DOWN;
bot.Pos += QPoint_DOWN;
return;
}
}
if(this->map->popValue(QPoint_RIGHT+bot.Pos) == bot.ID || this->map->popValue(QPoint_RIGHT+bot.Pos) == SHARED) {
if(bot.PrevDir != LEFT) {
bot.PrevDir = bot.Dir = RIGHT;
bot.Pos += QPoint_RIGHT;
return;
}
}
} break;
}
}
RobotPath::~RobotPath(){}
void RobotPath::FindDirection(Robot& BOT, int Elem){
int x,y;
x = BOT.Pos.x(); // position swap
y = BOT.Pos.y(); // position swap
switch(Elem) {
case 1: {
if(this->Maze[x][y-1] == Elem || this->Maze[x][y-1] == SHARED) {
qDebug("LEFT: Maze[%d][%d] == %d",y-1,x,this->Maze[x][y-1]);
if(BOT.PrevDir != RIGHT) {
BOT.PrevDir = BOT.Dir;
BOT.Dir = LEFT;
return;
}
}
if(this->Maze[x+1][y] == Elem || this->Maze[x+1][y] == SHARED) {
qDebug("DOWN: Maze[%d][%d] == %d",y,x+1,this->Maze[x+1][y]);
if(BOT.PrevDir != UP) {
BOT.PrevDir = BOT.Dir;
BOT.Dir = DOWN;
return;
}
}
if(this->Maze[x-1][y] == Elem || this->Maze[x-1][y] == SHARED) {
qDebug("UP: Maze[%d][%d] == %d",x-1,y,this->Maze[x-1][y]);
if(BOT.PrevDir != DOWN) {
BOT.PrevDir = BOT.Dir;
BOT.Dir = UP;
return;
}
}
if(this->Maze[x][y+1] == Elem || this->Maze[x][y+1] == SHARED) {
qDebug("RIGHT: Maze[%d][%d] == %d",x,y+1,this->Maze[x][y+1]);
if(BOT.PrevDir != LEFT) {
BOT.PrevDir = BOT.Dir;
BOT.Dir = RIGHT;
return;
}
}
}
}
//BOT.Dir = LEFT;
}
void RobotPath::MakeStep(Robot& BOT){
switch(BOT.Dir){
case UP: BOT.Pos.rx()--; break;
case DOWN: BOT.Pos.rx()++; break;
case LEFT: BOT.Pos.ry()--; break;
case RIGHT: BOT.Pos.ry()++; break;
}
BOT.Dir = DEFAULT;
}
<|endoftext|>
|
<commit_before>/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "InsertPropertyPanel.hxx"
#include "InsertPropertyPanel.hrc"
#include "sfx2/sidebar/CommandInfoProvider.hxx"
#include <sfx2/sidebar/Theme.hxx>
#include <sfx2/sidebar/Tools.hxx>
#include <sfx2/sidebar/ControlFactory.hxx>
#include <svx/dialmgr.hxx>
#include <svtools/miscopt.hxx>
#include <svtools/generictoolboxcontroller.hxx>
#include <vcl/toolbox.hxx>
#include <sfx2/tbxctrl.hxx>
#include <framework/sfxhelperfunctions.hxx>
#include <framework/imageproducer.hxx>
#include <comphelper/processfactory.hxx>
#include <cppuhelper/compbase1.hxx>
#include <cppuhelper/basemutex.hxx>
#include <com/sun/star/frame/XStatusListener.hpp>
using namespace css;
using namespace cssu;
using ::rtl::OUString;
namespace svx { namespace sidebar {
InsertPropertyPanel::InsertPropertyPanel (
Window* pParent,
const cssu::Reference<css::frame::XFrame>& rxFrame)
: Control(pParent, SVX_RES(RID_SIDEBAR_INSERT_PANEL)),
mpStandardShapesBackground(sfx2::sidebar::ControlFactory::CreateToolBoxBackground(this)),
mpStandardShapesToolBox(sfx2::sidebar::ControlFactory::CreateToolBox(
mpStandardShapesBackground.get(),
SVX_RES(TB_INSERT_STANDARD))),
mpCustomShapesBackground(sfx2::sidebar::ControlFactory::CreateToolBoxBackground(this)),
mpCustomShapesToolBox(sfx2::sidebar::ControlFactory::CreateToolBox(
mpCustomShapesBackground.get(),
SVX_RES(TB_INSERT_CUSTOM))),
maControllers(),
mxFrame(rxFrame)
{
SetupToolBox(*mpStandardShapesToolBox);
SetupToolBox(*mpCustomShapesToolBox);
FreeResource();
UpdateIcons();
mpStandardShapesToolBox->Show();
mpCustomShapesToolBox->Show();
// Listen to all tool box selection events.
Window* pTopWindow = pParent;
while (pTopWindow->GetParent() != NULL)
pTopWindow = pTopWindow->GetParent();
pTopWindow->AddChildEventListener(LINK(this, InsertPropertyPanel, WindowEventListener));
}
InsertPropertyPanel::~InsertPropertyPanel (void)
{
ControllerContainer aControllers;
aControllers.swap(maControllers);
for (ControllerContainer::iterator iController(aControllers.begin()), iEnd(aControllers.end());
iController!=iEnd;
++iController)
{
Reference<lang::XComponent> xComponent (iController->second.mxController, UNO_QUERY);
if (xComponent.is())
xComponent->dispose();
}
// Remove window child listener.
Window* pTopWindow = this;
while (pTopWindow->GetParent() != NULL)
pTopWindow = pTopWindow->GetParent();
pTopWindow->RemoveChildEventListener(LINK(this, InsertPropertyPanel, WindowEventListener));
mpStandardShapesToolBox.reset();
mpCustomShapesToolBox.reset();
mpStandardShapesBackground.reset();
mpCustomShapesBackground.reset();
}
void InsertPropertyPanel::SetupToolBox (ToolBox& rToolBox)
{
const sal_uInt16 nItemCount (rToolBox.GetItemCount());
for (sal_uInt16 nItemIndex=0; nItemIndex<nItemCount; ++nItemIndex)
CreateController(rToolBox.GetItemId(nItemIndex));
rToolBox.SetDropdownClickHdl(LINK(this, InsertPropertyPanel, DropDownClickHandler));
rToolBox.SetClickHdl(LINK(this, InsertPropertyPanel, ClickHandler));
rToolBox.SetDoubleClickHdl(LINK(this, InsertPropertyPanel, DoubleClickHandler));
rToolBox.SetSelectHdl(LINK(this, InsertPropertyPanel, SelectHandler));
rToolBox.SetActivateHdl(LINK(this, InsertPropertyPanel, ActivateToolBox));
rToolBox.SetDeactivateHdl(LINK(this, InsertPropertyPanel, DeactivateToolBox));
rToolBox.SetSizePixel(rToolBox.CalcWindowSizePixel());
}
IMPL_LINK(InsertPropertyPanel, DropDownClickHandler, ToolBox*, pToolBox)
{
if (pToolBox != NULL)
{
Reference<frame::XToolbarController> xController (GetControllerForItemId(pToolBox->GetCurItemId()));
if (xController.is())
{
Reference<awt::XWindow> xWindow = xController->createPopupWindow();
if (xWindow.is() )
xWindow->setFocus();
}
}
return 1;
}
IMPL_LINK(InsertPropertyPanel, ClickHandler, ToolBox*, pToolBox)
{
if (pToolBox == NULL)
return 0;
Reference<frame::XToolbarController> xController (GetControllerForItemId(pToolBox->GetCurItemId()));
if (xController.is())
xController->click();
return 1;
}
IMPL_LINK(InsertPropertyPanel, DoubleClickHandler, ToolBox*, pToolBox)
{
if (pToolBox == NULL)
return 0;
Reference<frame::XToolbarController> xController (GetControllerForItemId(pToolBox->GetCurItemId()));
if (xController.is())
xController->doubleClick();
return 1;
}
IMPL_LINK(InsertPropertyPanel, SelectHandler, ToolBox*, pToolBox)
{
if (pToolBox == NULL)
return 0;
Reference<frame::XToolbarController> xController (GetControllerForItemId(pToolBox->GetCurItemId()));
if (xController.is())
xController->execute((sal_Int16)pToolBox->GetModifier());
return 1;
}
IMPL_LINK(InsertPropertyPanel, WindowEventListener, VclSimpleEvent*, pEvent)
{
// We will be getting a lot of window events (well, basically all
// of them), so reject early everything that is not connected to
// toolbox selection.
if (pEvent == NULL)
return 1;
if ( ! pEvent->ISA(VclWindowEvent))
return 1;
if (pEvent->GetId() != VCLEVENT_TOOLBOX_SELECT)
return 1;
ToolBox* pToolBox = dynamic_cast<ToolBox*>(dynamic_cast<VclWindowEvent*>(pEvent)->GetWindow());
if (pToolBox == NULL)
return 1;
// Extract name of (sub)toolbar from help id.
OUString sToolbarName (rtl::OStringToOUString(pToolBox->GetHelpId(), RTL_TEXTENCODING_UTF8));
if (sToolbarName.getLength() == 0)
return 1;
const util::URL aURL (sfx2::sidebar::Tools::GetURL(sToolbarName));
if (aURL.Path.getLength() == 0)
return 1;
// Get item id.
sal_uInt16 nId = pToolBox->GetCurItemId();
if (nId == 0)
return 1;
// Get toolbar controller.
const sal_uInt16 nItemId (GetItemIdForSubToolbarName(aURL.Path));
Reference<frame::XSubToolbarController> xController (GetControllerForItemId(nItemId), UNO_QUERY);
if ( ! xController.is())
return 1;
const OUString sCommand (pToolBox->GetItemCommand(nId));
ControllerContainer::iterator iController (maControllers.find(nItemId));
if (iController != maControllers.end())
iController->second.msCurrentCommand = sCommand;
xController->functionSelected(sCommand);
const sal_Bool bBigImages (SvtMiscOptions().AreCurrentSymbolsLarge());
Image aImage (framework::GetImageFromURL(mxFrame, sCommand, bBigImages));
pToolBox->SetItemImage(iController->first, aImage);
return 1;
}
IMPL_LINK(InsertPropertyPanel, ActivateToolBox, ToolBox*, EMPTYARG)
{
return 1;
}
IMPL_LINK(InsertPropertyPanel, DeactivateToolBox, ToolBox*, EMPTYARG)
{
return 1;
}
void InsertPropertyPanel::CreateController (
const sal_uInt16 nItemId)
{
ToolBox* pToolBox = GetToolBoxForItemId(nItemId);
if (pToolBox != NULL)
{
ItemDescriptor aDescriptor;
const OUString sCommandName (pToolBox->GetItemCommand(nItemId));
// Create a controller for the new item.
aDescriptor.mxController.set(
static_cast<XWeak*>(::framework::CreateToolBoxController(
mxFrame,
pToolBox,
nItemId,
sCommandName)),
UNO_QUERY);
if ( ! aDescriptor.mxController.is())
aDescriptor.mxController.set(
static_cast<XWeak*>(new svt::GenericToolboxController(
::comphelper::getProcessServiceFactory(),
mxFrame,
pToolBox,
nItemId,
sCommandName)),
UNO_QUERY);
if ( ! aDescriptor.mxController.is())
return;
// Get dispatch object for the command.
aDescriptor.maURL = sfx2::sidebar::Tools::GetURL(sCommandName);
aDescriptor.msCurrentCommand = sCommandName;
aDescriptor.mxDispatch = sfx2::sidebar::Tools::GetDispatch(mxFrame, aDescriptor.maURL);
if ( ! aDescriptor.mxDispatch.is())
return;
// Initialize the controller with eg a service factory.
Reference<lang::XInitialization> xInitialization (aDescriptor.mxController, UNO_QUERY);
if (xInitialization.is())
{
beans::PropertyValue aPropValue;
std::vector<Any> aPropertyVector;
aPropValue.Name = A2S("Frame");
aPropValue.Value <<= mxFrame;
aPropertyVector.push_back(makeAny(aPropValue));
aPropValue.Name = A2S("ServiceManager");
aPropValue.Value <<= ::comphelper::getProcessServiceFactory();
aPropertyVector.push_back(makeAny(aPropValue));
aPropValue.Name = A2S("CommandURL");
aPropValue.Value <<= sCommandName;
aPropertyVector.push_back(makeAny(aPropValue));
Sequence<Any> aArgs (comphelper::containerToSequence(aPropertyVector));
xInitialization->initialize(aArgs);
}
Reference<util::XUpdatable> xUpdatable (aDescriptor.mxController, UNO_QUERY);
if (xUpdatable.is())
xUpdatable->update();
// Add label.
const OUString sLabel (sfx2::sidebar::CommandInfoProvider::Instance().GetLabelForCommand(
sCommandName,
mxFrame));
pToolBox->SetQuickHelpText(nItemId, sLabel);
// Add item to toolbox.
pToolBox->EnableItem(nItemId);
maControllers.insert(::std::make_pair(nItemId, aDescriptor));
}
}
ToolBox* InsertPropertyPanel::GetToolBoxForItemId (const sal_uInt16 nItemId) const
{
switch(nItemId)
{
case TBI_STANDARD_LINE:
case TBI_STANDARD_ARROW:
case TBI_STANDARD_RECTANGLE:
case TBI_STANDARD_ELLIPSE:
case TBI_STANDARD_TEXT:
case TBI_STANDARD_LINES:
case TBI_STANDARD_CONNECTORS:
case TBI_STANDARD_ARROWS:
return mpStandardShapesToolBox.get();
case TBI_CUSTOM_BASICS:
case TBI_CUSTOM_SYMBOLS:
case TBI_CUSTOM_ARROWS:
case TBI_CUSTOM_FLOWCHARTS:
case TBI_CUSTOM_CALLOUTS:
case TBI_CUSTOM_STARS:
return mpCustomShapesToolBox.get();
default:
return NULL;
}
}
Reference<frame::XToolbarController> InsertPropertyPanel::GetControllerForItemId (const sal_uInt16 nItemId) const
{
ControllerContainer::const_iterator iController (maControllers.find(nItemId));
if (iController != maControllers.end())
return iController->second.mxController;
else
return NULL;
}
sal_uInt16 InsertPropertyPanel::GetItemIdForSubToolbarName (const OUString& rsSubToolbarName) const
{
for (ControllerContainer::const_iterator iController(maControllers.begin()), iEnd(maControllers.end());
iController!=iEnd;
++iController)
{
Reference<frame::XSubToolbarController> xSubToolbarController (iController->second.mxController, UNO_QUERY);
if (xSubToolbarController.is())
if (xSubToolbarController->getSubToolbarName().equals(rsSubToolbarName))
return iController->first;
}
return 0;
}
void InsertPropertyPanel::UpdateIcons (void)
{
const sal_Bool bBigImages (SvtMiscOptions().AreCurrentSymbolsLarge());
for (ControllerContainer::iterator iController(maControllers.begin()), iEnd(maControllers.end());
iController!=iEnd;
++iController)
{
const ::rtl::OUString sCommandURL (iController->second.msCurrentCommand);
Image aImage (framework::GetImageFromURL(mxFrame, sCommandURL, bBigImages));
ToolBox* pToolBox = GetToolBoxForItemId(iController->first);
if (pToolBox != NULL)
pToolBox->SetItemImage(iController->first, aImage);
}
}
} } // end of namespace svx::sidebar
<commit_msg>getProcessServiceFactory->getProcessComponentContext<commit_after>/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "InsertPropertyPanel.hxx"
#include "InsertPropertyPanel.hrc"
#include "sfx2/sidebar/CommandInfoProvider.hxx"
#include <sfx2/sidebar/Theme.hxx>
#include <sfx2/sidebar/Tools.hxx>
#include <sfx2/sidebar/ControlFactory.hxx>
#include <svx/dialmgr.hxx>
#include <svtools/miscopt.hxx>
#include <svtools/generictoolboxcontroller.hxx>
#include <vcl/toolbox.hxx>
#include <sfx2/tbxctrl.hxx>
#include <framework/sfxhelperfunctions.hxx>
#include <framework/imageproducer.hxx>
#include <comphelper/processfactory.hxx>
#include <cppuhelper/compbase1.hxx>
#include <cppuhelper/basemutex.hxx>
#include <com/sun/star/frame/XStatusListener.hpp>
using namespace css;
using namespace cssu;
using ::rtl::OUString;
namespace svx { namespace sidebar {
InsertPropertyPanel::InsertPropertyPanel (
Window* pParent,
const cssu::Reference<css::frame::XFrame>& rxFrame)
: Control(pParent, SVX_RES(RID_SIDEBAR_INSERT_PANEL)),
mpStandardShapesBackground(sfx2::sidebar::ControlFactory::CreateToolBoxBackground(this)),
mpStandardShapesToolBox(sfx2::sidebar::ControlFactory::CreateToolBox(
mpStandardShapesBackground.get(),
SVX_RES(TB_INSERT_STANDARD))),
mpCustomShapesBackground(sfx2::sidebar::ControlFactory::CreateToolBoxBackground(this)),
mpCustomShapesToolBox(sfx2::sidebar::ControlFactory::CreateToolBox(
mpCustomShapesBackground.get(),
SVX_RES(TB_INSERT_CUSTOM))),
maControllers(),
mxFrame(rxFrame)
{
SetupToolBox(*mpStandardShapesToolBox);
SetupToolBox(*mpCustomShapesToolBox);
FreeResource();
UpdateIcons();
mpStandardShapesToolBox->Show();
mpCustomShapesToolBox->Show();
// Listen to all tool box selection events.
Window* pTopWindow = pParent;
while (pTopWindow->GetParent() != NULL)
pTopWindow = pTopWindow->GetParent();
pTopWindow->AddChildEventListener(LINK(this, InsertPropertyPanel, WindowEventListener));
}
InsertPropertyPanel::~InsertPropertyPanel (void)
{
ControllerContainer aControllers;
aControllers.swap(maControllers);
for (ControllerContainer::iterator iController(aControllers.begin()), iEnd(aControllers.end());
iController!=iEnd;
++iController)
{
Reference<lang::XComponent> xComponent (iController->second.mxController, UNO_QUERY);
if (xComponent.is())
xComponent->dispose();
}
// Remove window child listener.
Window* pTopWindow = this;
while (pTopWindow->GetParent() != NULL)
pTopWindow = pTopWindow->GetParent();
pTopWindow->RemoveChildEventListener(LINK(this, InsertPropertyPanel, WindowEventListener));
mpStandardShapesToolBox.reset();
mpCustomShapesToolBox.reset();
mpStandardShapesBackground.reset();
mpCustomShapesBackground.reset();
}
void InsertPropertyPanel::SetupToolBox (ToolBox& rToolBox)
{
const sal_uInt16 nItemCount (rToolBox.GetItemCount());
for (sal_uInt16 nItemIndex=0; nItemIndex<nItemCount; ++nItemIndex)
CreateController(rToolBox.GetItemId(nItemIndex));
rToolBox.SetDropdownClickHdl(LINK(this, InsertPropertyPanel, DropDownClickHandler));
rToolBox.SetClickHdl(LINK(this, InsertPropertyPanel, ClickHandler));
rToolBox.SetDoubleClickHdl(LINK(this, InsertPropertyPanel, DoubleClickHandler));
rToolBox.SetSelectHdl(LINK(this, InsertPropertyPanel, SelectHandler));
rToolBox.SetActivateHdl(LINK(this, InsertPropertyPanel, ActivateToolBox));
rToolBox.SetDeactivateHdl(LINK(this, InsertPropertyPanel, DeactivateToolBox));
rToolBox.SetSizePixel(rToolBox.CalcWindowSizePixel());
}
IMPL_LINK(InsertPropertyPanel, DropDownClickHandler, ToolBox*, pToolBox)
{
if (pToolBox != NULL)
{
Reference<frame::XToolbarController> xController (GetControllerForItemId(pToolBox->GetCurItemId()));
if (xController.is())
{
Reference<awt::XWindow> xWindow = xController->createPopupWindow();
if (xWindow.is() )
xWindow->setFocus();
}
}
return 1;
}
IMPL_LINK(InsertPropertyPanel, ClickHandler, ToolBox*, pToolBox)
{
if (pToolBox == NULL)
return 0;
Reference<frame::XToolbarController> xController (GetControllerForItemId(pToolBox->GetCurItemId()));
if (xController.is())
xController->click();
return 1;
}
IMPL_LINK(InsertPropertyPanel, DoubleClickHandler, ToolBox*, pToolBox)
{
if (pToolBox == NULL)
return 0;
Reference<frame::XToolbarController> xController (GetControllerForItemId(pToolBox->GetCurItemId()));
if (xController.is())
xController->doubleClick();
return 1;
}
IMPL_LINK(InsertPropertyPanel, SelectHandler, ToolBox*, pToolBox)
{
if (pToolBox == NULL)
return 0;
Reference<frame::XToolbarController> xController (GetControllerForItemId(pToolBox->GetCurItemId()));
if (xController.is())
xController->execute((sal_Int16)pToolBox->GetModifier());
return 1;
}
IMPL_LINK(InsertPropertyPanel, WindowEventListener, VclSimpleEvent*, pEvent)
{
// We will be getting a lot of window events (well, basically all
// of them), so reject early everything that is not connected to
// toolbox selection.
if (pEvent == NULL)
return 1;
if ( ! pEvent->ISA(VclWindowEvent))
return 1;
if (pEvent->GetId() != VCLEVENT_TOOLBOX_SELECT)
return 1;
ToolBox* pToolBox = dynamic_cast<ToolBox*>(dynamic_cast<VclWindowEvent*>(pEvent)->GetWindow());
if (pToolBox == NULL)
return 1;
// Extract name of (sub)toolbar from help id.
OUString sToolbarName (rtl::OStringToOUString(pToolBox->GetHelpId(), RTL_TEXTENCODING_UTF8));
if (sToolbarName.getLength() == 0)
return 1;
const util::URL aURL (sfx2::sidebar::Tools::GetURL(sToolbarName));
if (aURL.Path.getLength() == 0)
return 1;
// Get item id.
sal_uInt16 nId = pToolBox->GetCurItemId();
if (nId == 0)
return 1;
// Get toolbar controller.
const sal_uInt16 nItemId (GetItemIdForSubToolbarName(aURL.Path));
Reference<frame::XSubToolbarController> xController (GetControllerForItemId(nItemId), UNO_QUERY);
if ( ! xController.is())
return 1;
const OUString sCommand (pToolBox->GetItemCommand(nId));
ControllerContainer::iterator iController (maControllers.find(nItemId));
if (iController != maControllers.end())
iController->second.msCurrentCommand = sCommand;
xController->functionSelected(sCommand);
const sal_Bool bBigImages (SvtMiscOptions().AreCurrentSymbolsLarge());
Image aImage (framework::GetImageFromURL(mxFrame, sCommand, bBigImages));
pToolBox->SetItemImage(iController->first, aImage);
return 1;
}
IMPL_LINK(InsertPropertyPanel, ActivateToolBox, ToolBox*, EMPTYARG)
{
return 1;
}
IMPL_LINK(InsertPropertyPanel, DeactivateToolBox, ToolBox*, EMPTYARG)
{
return 1;
}
void InsertPropertyPanel::CreateController (
const sal_uInt16 nItemId)
{
ToolBox* pToolBox = GetToolBoxForItemId(nItemId);
if (pToolBox != NULL)
{
ItemDescriptor aDescriptor;
const OUString sCommandName (pToolBox->GetItemCommand(nItemId));
// Create a controller for the new item.
aDescriptor.mxController.set(
static_cast<XWeak*>(::framework::CreateToolBoxController(
mxFrame,
pToolBox,
nItemId,
sCommandName)),
UNO_QUERY);
if ( ! aDescriptor.mxController.is())
aDescriptor.mxController.set(
static_cast<XWeak*>(new svt::GenericToolboxController(
::comphelper::getProcessComponentContext(),
mxFrame,
pToolBox,
nItemId,
sCommandName)),
UNO_QUERY);
if ( ! aDescriptor.mxController.is())
return;
// Get dispatch object for the command.
aDescriptor.maURL = sfx2::sidebar::Tools::GetURL(sCommandName);
aDescriptor.msCurrentCommand = sCommandName;
aDescriptor.mxDispatch = sfx2::sidebar::Tools::GetDispatch(mxFrame, aDescriptor.maURL);
if ( ! aDescriptor.mxDispatch.is())
return;
// Initialize the controller with eg a service factory.
Reference<lang::XInitialization> xInitialization (aDescriptor.mxController, UNO_QUERY);
if (xInitialization.is())
{
beans::PropertyValue aPropValue;
std::vector<Any> aPropertyVector;
aPropValue.Name = A2S("Frame");
aPropValue.Value <<= mxFrame;
aPropertyVector.push_back(makeAny(aPropValue));
aPropValue.Name = A2S("ServiceManager");
aPropValue.Value <<= ::comphelper::getProcessServiceFactory();
aPropertyVector.push_back(makeAny(aPropValue));
aPropValue.Name = A2S("CommandURL");
aPropValue.Value <<= sCommandName;
aPropertyVector.push_back(makeAny(aPropValue));
Sequence<Any> aArgs (comphelper::containerToSequence(aPropertyVector));
xInitialization->initialize(aArgs);
}
Reference<util::XUpdatable> xUpdatable (aDescriptor.mxController, UNO_QUERY);
if (xUpdatable.is())
xUpdatable->update();
// Add label.
const OUString sLabel (sfx2::sidebar::CommandInfoProvider::Instance().GetLabelForCommand(
sCommandName,
mxFrame));
pToolBox->SetQuickHelpText(nItemId, sLabel);
// Add item to toolbox.
pToolBox->EnableItem(nItemId);
maControllers.insert(::std::make_pair(nItemId, aDescriptor));
}
}
ToolBox* InsertPropertyPanel::GetToolBoxForItemId (const sal_uInt16 nItemId) const
{
switch(nItemId)
{
case TBI_STANDARD_LINE:
case TBI_STANDARD_ARROW:
case TBI_STANDARD_RECTANGLE:
case TBI_STANDARD_ELLIPSE:
case TBI_STANDARD_TEXT:
case TBI_STANDARD_LINES:
case TBI_STANDARD_CONNECTORS:
case TBI_STANDARD_ARROWS:
return mpStandardShapesToolBox.get();
case TBI_CUSTOM_BASICS:
case TBI_CUSTOM_SYMBOLS:
case TBI_CUSTOM_ARROWS:
case TBI_CUSTOM_FLOWCHARTS:
case TBI_CUSTOM_CALLOUTS:
case TBI_CUSTOM_STARS:
return mpCustomShapesToolBox.get();
default:
return NULL;
}
}
Reference<frame::XToolbarController> InsertPropertyPanel::GetControllerForItemId (const sal_uInt16 nItemId) const
{
ControllerContainer::const_iterator iController (maControllers.find(nItemId));
if (iController != maControllers.end())
return iController->second.mxController;
else
return NULL;
}
sal_uInt16 InsertPropertyPanel::GetItemIdForSubToolbarName (const OUString& rsSubToolbarName) const
{
for (ControllerContainer::const_iterator iController(maControllers.begin()), iEnd(maControllers.end());
iController!=iEnd;
++iController)
{
Reference<frame::XSubToolbarController> xSubToolbarController (iController->second.mxController, UNO_QUERY);
if (xSubToolbarController.is())
if (xSubToolbarController->getSubToolbarName().equals(rsSubToolbarName))
return iController->first;
}
return 0;
}
void InsertPropertyPanel::UpdateIcons (void)
{
const sal_Bool bBigImages (SvtMiscOptions().AreCurrentSymbolsLarge());
for (ControllerContainer::iterator iController(maControllers.begin()), iEnd(maControllers.end());
iController!=iEnd;
++iController)
{
const ::rtl::OUString sCommandURL (iController->second.msCurrentCommand);
Image aImage (framework::GetImageFromURL(mxFrame, sCommandURL, bBigImages));
ToolBox* pToolBox = GetToolBoxForItemId(iController->first);
if (pToolBox != NULL)
pToolBox->SetItemImage(iController->first, aImage);
}
}
} } // end of namespace svx::sidebar
<|endoftext|>
|
<commit_before>/***************************************************************************
copyright : (C) 2013 by Lukas Krejci
email : krejclu6@fel.cvut.cz
***************************************************************************/
/***************************************************************************
* This library is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License version *
* 2.1 as published by the Free Software Foundation. *
* *
* This library is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA *
* 02110-1301 USA *
* *
* Alternatively, this file is available under the Mozilla Public *
* License Version 1.1. You may obtain a copy of the License at *
* http://www.mozilla.org/MPL/ *
***************************************************************************/
#include <tbytevectorlist.h>
#include <tpropertymap.h>
#include <tdebug.h>
#include "tableofcontentsframe.h"
using namespace TagLib;
using namespace ID3v2;
class TableOfContentsFrame::TableOfContentsFramePrivate
{
public:
TableOfContentsFramePrivate() :
tagHeader(0),
isTopLevel(false),
isOrdered(false)
{
embeddedFrameList.setAutoDelete(true);
}
const ID3v2::Header *tagHeader;
ByteVector elementID;
bool isTopLevel;
bool isOrdered;
ByteVectorList childElements;
FrameListMap embeddedFrameListMap;
FrameList embeddedFrameList;
};
namespace {
// These functions are needed to try to aim for backward compatibility with
// an API that previously (unreasonably) required null bytes to be appeneded
// at the end of identifiers explicitly by the API user.
// BIC: remove these
ByteVector &strip(ByteVector &b)
{
if(b.endsWith('\0'))
b.resize(b.size() - 1);
return b;
}
ByteVectorList &strip(ByteVectorList &l)
{
for(ByteVectorList::Iterator it = l.begin(); it != l.end(); ++it)
{
strip(*it);
}
return l;
}
}
////////////////////////////////////////////////////////////////////////////////
// public methods
////////////////////////////////////////////////////////////////////////////////
TableOfContentsFrame::TableOfContentsFrame(const ID3v2::Header *tagHeader, const ByteVector &data) :
ID3v2::Frame(data),
d(new TableOfContentsFramePrivate())
{
d->tagHeader = tagHeader;
setData(data);
}
TableOfContentsFrame::TableOfContentsFrame(const ByteVector &elementID,
const ByteVectorList &children,
const FrameList &embeddedFrames) :
ID3v2::Frame("CTOC"),
d(new TableOfContentsFramePrivate())
{
d->elementID = elementID;
strip(d->elementID);
d->childElements = children;
for(FrameList::ConstIterator it = embeddedFrames.begin(); it != embeddedFrames.end(); ++it)
addEmbeddedFrame(*it);
}
TableOfContentsFrame::~TableOfContentsFrame()
{
delete d;
}
ByteVector TableOfContentsFrame::elementID() const
{
return d->elementID;
}
bool TableOfContentsFrame::isTopLevel() const
{
return d->isTopLevel;
}
bool TableOfContentsFrame::isOrdered() const
{
return d->isOrdered;
}
unsigned int TableOfContentsFrame::entryCount() const
{
return d->childElements.size();
}
ByteVectorList TableOfContentsFrame::childElements() const
{
return d->childElements;
}
void TableOfContentsFrame::setElementID(const ByteVector &eID)
{
d->elementID = eID;
strip(d->elementID);
}
void TableOfContentsFrame::setIsTopLevel(const bool &t)
{
d->isTopLevel = t;
}
void TableOfContentsFrame::setIsOrdered(const bool &o)
{
d->isOrdered = o;
}
void TableOfContentsFrame::setChildElements(const ByteVectorList &l)
{
d->childElements = l;
strip(d->childElements);
}
void TableOfContentsFrame::addChildElement(const ByteVector &cE)
{
d->childElements.append(cE);
strip(d->childElements);
}
void TableOfContentsFrame::removeChildElement(const ByteVector &cE)
{
ByteVectorList::Iterator it = d->childElements.find(cE);
if(it == d->childElements.end())
it = d->childElements.find(cE + ByteVector("\0"));
d->childElements.erase(it);
}
const FrameListMap &TableOfContentsFrame::embeddedFrameListMap() const
{
return d->embeddedFrameListMap;
}
const FrameList &TableOfContentsFrame::embeddedFrameList() const
{
return d->embeddedFrameList;
}
const FrameList &TableOfContentsFrame::embeddedFrameList(const ByteVector &frameID) const
{
return d->embeddedFrameListMap[frameID];
}
void TableOfContentsFrame::addEmbeddedFrame(Frame *frame)
{
d->embeddedFrameList.append(frame);
d->embeddedFrameListMap[frame->frameID()].append(frame);
}
void TableOfContentsFrame::removeEmbeddedFrame(Frame *frame, bool del)
{
// remove the frame from the frame list
FrameList::Iterator it = d->embeddedFrameList.find(frame);
d->embeddedFrameList.erase(it);
// ...and from the frame list map
it = d->embeddedFrameListMap[frame->frameID()].find(frame);
d->embeddedFrameListMap[frame->frameID()].erase(it);
// ...and delete as desired
if(del)
delete frame;
}
void TableOfContentsFrame::removeEmbeddedFrames(const ByteVector &id)
{
FrameList l = d->embeddedFrameListMap[id];
for(FrameList::ConstIterator it = l.begin(); it != l.end(); ++it)
removeEmbeddedFrame(*it, true);
}
String TableOfContentsFrame::toString() const
{
return String();
}
PropertyMap TableOfContentsFrame::asProperties() const
{
PropertyMap map;
map.unsupportedData().append(frameID() + String("/") + d->elementID);
return map;
}
TableOfContentsFrame *TableOfContentsFrame::findByElementID(const ID3v2::Tag *tag,
const ByteVector &eID) // static
{
ID3v2::FrameList tablesOfContents = tag->frameList("CTOC");
for(ID3v2::FrameList::ConstIterator it = tablesOfContents.begin();
it != tablesOfContents.end();
++it)
{
TableOfContentsFrame *frame = dynamic_cast<TableOfContentsFrame *>(*it);
if(frame && frame->elementID() == eID)
return frame;
}
return 0;
}
TableOfContentsFrame *TableOfContentsFrame::findTopLevel(const ID3v2::Tag *tag) // static
{
ID3v2::FrameList tablesOfContents = tag->frameList("CTOC");
for(ID3v2::FrameList::ConstIterator it = tablesOfContents.begin();
it != tablesOfContents.end();
++it)
{
TableOfContentsFrame *frame = dynamic_cast<TableOfContentsFrame *>(*it);
if(frame && frame->isTopLevel() == true)
return frame;
}
return 0;
}
void TableOfContentsFrame::parseFields(const ByteVector &data)
{
unsigned int size = data.size();
if(size < 6) {
debug("A CTOC frame must contain at least 6 bytes (1 byte element ID terminated by "
"null, 1 byte flags, 1 byte entry count and 1 byte child element ID terminated "
"by null.");
return;
}
int pos = 0;
unsigned int embPos = 0;
d->elementID = readStringField(data, String::Latin1, &pos).data(String::Latin1);
d->isTopLevel = (data.at(pos) & 2) != 0;
d->isOrdered = (data.at(pos++) & 1) != 0;
unsigned int entryCount = static_cast<unsigned char>(data.at(pos++));
for(unsigned int i = 0; i < entryCount; i++) {
ByteVector childElementID = readStringField(data, String::Latin1, &pos).data(String::Latin1);
d->childElements.append(childElementID);
}
size -= pos;
if(size < header()->size())
return;
while(embPos < size - header()->size()) {
Frame *frame = FrameFactory::instance()->createFrame(data.mid(pos + embPos), (d->tagHeader != 0));
if(!frame)
return;
// Checks to make sure that frame parsed correctly.
if(frame->size() <= 0) {
delete frame;
return;
}
embPos += frame->size() + header()->size();
addEmbeddedFrame(frame);
}
}
ByteVector TableOfContentsFrame::renderFields() const
{
ByteVector data;
data.append(d->elementID);
data.append('\0');
char flags = 0;
if(d->isTopLevel)
flags += 2;
if(d->isOrdered)
flags += 1;
data.append(flags);
data.append((char)(entryCount()));
ByteVectorList::ConstIterator it = d->childElements.begin();
while(it != d->childElements.end()) {
data.append(*it);
data.append('\0');
it++;
}
FrameList l = d->embeddedFrameList;
for(FrameList::ConstIterator it = l.begin(); it != l.end(); ++it)
data.append((*it)->render());
return data;
}
TableOfContentsFrame::TableOfContentsFrame(const ID3v2::Header *tagHeader,
const ByteVector &data, Header *h) :
Frame(h),
d(new TableOfContentsFramePrivate())
{
d->tagHeader = tagHeader;
parseFields(fieldData(data));
}
<commit_msg>Fill `TableOfContentsFrame::toString()`. (#852)<commit_after>/***************************************************************************
copyright : (C) 2013 by Lukas Krejci
email : krejclu6@fel.cvut.cz
***************************************************************************/
/***************************************************************************
* This library is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License version *
* 2.1 as published by the Free Software Foundation. *
* *
* This library is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA *
* 02110-1301 USA *
* *
* Alternatively, this file is available under the Mozilla Public *
* License Version 1.1. You may obtain a copy of the License at *
* http://www.mozilla.org/MPL/ *
***************************************************************************/
#include <tbytevectorlist.h>
#include <tpropertymap.h>
#include <tdebug.h>
#include "tableofcontentsframe.h"
using namespace TagLib;
using namespace ID3v2;
class TableOfContentsFrame::TableOfContentsFramePrivate
{
public:
TableOfContentsFramePrivate() :
tagHeader(0),
isTopLevel(false),
isOrdered(false)
{
embeddedFrameList.setAutoDelete(true);
}
const ID3v2::Header *tagHeader;
ByteVector elementID;
bool isTopLevel;
bool isOrdered;
ByteVectorList childElements;
FrameListMap embeddedFrameListMap;
FrameList embeddedFrameList;
};
namespace {
// These functions are needed to try to aim for backward compatibility with
// an API that previously (unreasonably) required null bytes to be appeneded
// at the end of identifiers explicitly by the API user.
// BIC: remove these
ByteVector &strip(ByteVector &b)
{
if(b.endsWith('\0'))
b.resize(b.size() - 1);
return b;
}
ByteVectorList &strip(ByteVectorList &l)
{
for(ByteVectorList::Iterator it = l.begin(); it != l.end(); ++it)
{
strip(*it);
}
return l;
}
}
////////////////////////////////////////////////////////////////////////////////
// public methods
////////////////////////////////////////////////////////////////////////////////
TableOfContentsFrame::TableOfContentsFrame(const ID3v2::Header *tagHeader, const ByteVector &data) :
ID3v2::Frame(data),
d(new TableOfContentsFramePrivate())
{
d->tagHeader = tagHeader;
setData(data);
}
TableOfContentsFrame::TableOfContentsFrame(const ByteVector &elementID,
const ByteVectorList &children,
const FrameList &embeddedFrames) :
ID3v2::Frame("CTOC"),
d(new TableOfContentsFramePrivate())
{
d->elementID = elementID;
strip(d->elementID);
d->childElements = children;
for(FrameList::ConstIterator it = embeddedFrames.begin(); it != embeddedFrames.end(); ++it)
addEmbeddedFrame(*it);
}
TableOfContentsFrame::~TableOfContentsFrame()
{
delete d;
}
ByteVector TableOfContentsFrame::elementID() const
{
return d->elementID;
}
bool TableOfContentsFrame::isTopLevel() const
{
return d->isTopLevel;
}
bool TableOfContentsFrame::isOrdered() const
{
return d->isOrdered;
}
unsigned int TableOfContentsFrame::entryCount() const
{
return d->childElements.size();
}
ByteVectorList TableOfContentsFrame::childElements() const
{
return d->childElements;
}
void TableOfContentsFrame::setElementID(const ByteVector &eID)
{
d->elementID = eID;
strip(d->elementID);
}
void TableOfContentsFrame::setIsTopLevel(const bool &t)
{
d->isTopLevel = t;
}
void TableOfContentsFrame::setIsOrdered(const bool &o)
{
d->isOrdered = o;
}
void TableOfContentsFrame::setChildElements(const ByteVectorList &l)
{
d->childElements = l;
strip(d->childElements);
}
void TableOfContentsFrame::addChildElement(const ByteVector &cE)
{
d->childElements.append(cE);
strip(d->childElements);
}
void TableOfContentsFrame::removeChildElement(const ByteVector &cE)
{
ByteVectorList::Iterator it = d->childElements.find(cE);
if(it == d->childElements.end())
it = d->childElements.find(cE + ByteVector("\0"));
d->childElements.erase(it);
}
const FrameListMap &TableOfContentsFrame::embeddedFrameListMap() const
{
return d->embeddedFrameListMap;
}
const FrameList &TableOfContentsFrame::embeddedFrameList() const
{
return d->embeddedFrameList;
}
const FrameList &TableOfContentsFrame::embeddedFrameList(const ByteVector &frameID) const
{
return d->embeddedFrameListMap[frameID];
}
void TableOfContentsFrame::addEmbeddedFrame(Frame *frame)
{
d->embeddedFrameList.append(frame);
d->embeddedFrameListMap[frame->frameID()].append(frame);
}
void TableOfContentsFrame::removeEmbeddedFrame(Frame *frame, bool del)
{
// remove the frame from the frame list
FrameList::Iterator it = d->embeddedFrameList.find(frame);
d->embeddedFrameList.erase(it);
// ...and from the frame list map
it = d->embeddedFrameListMap[frame->frameID()].find(frame);
d->embeddedFrameListMap[frame->frameID()].erase(it);
// ...and delete as desired
if(del)
delete frame;
}
void TableOfContentsFrame::removeEmbeddedFrames(const ByteVector &id)
{
FrameList l = d->embeddedFrameListMap[id];
for(FrameList::ConstIterator it = l.begin(); it != l.end(); ++it)
removeEmbeddedFrame(*it, true);
}
String TableOfContentsFrame::toString() const
{
String s = String(d->elementID) +
": top level: " + (d->isTopLevel ? "true" : "false") +
", ordered: " + (d->isOrdered ? "true" : "false");
if(!d->childElements.isEmpty()) {
s+= ", chapters: [ " + String(d->childElements.toByteVector(", ")) + " ]";
}
if(!d->embeddedFrameList.isEmpty()) {
StringList frameIDs;
for(FrameList::ConstIterator it = d->embeddedFrameList.begin();
it != d->embeddedFrameList.end(); ++it)
frameIDs.append((*it)->frameID());
s += ", sub-frames: [ " + frameIDs.toString(", ") + " ]";
}
return s;
}
PropertyMap TableOfContentsFrame::asProperties() const
{
PropertyMap map;
map.unsupportedData().append(frameID() + String("/") + d->elementID);
return map;
}
TableOfContentsFrame *TableOfContentsFrame::findByElementID(const ID3v2::Tag *tag,
const ByteVector &eID) // static
{
ID3v2::FrameList tablesOfContents = tag->frameList("CTOC");
for(ID3v2::FrameList::ConstIterator it = tablesOfContents.begin();
it != tablesOfContents.end();
++it)
{
TableOfContentsFrame *frame = dynamic_cast<TableOfContentsFrame *>(*it);
if(frame && frame->elementID() == eID)
return frame;
}
return 0;
}
TableOfContentsFrame *TableOfContentsFrame::findTopLevel(const ID3v2::Tag *tag) // static
{
ID3v2::FrameList tablesOfContents = tag->frameList("CTOC");
for(ID3v2::FrameList::ConstIterator it = tablesOfContents.begin();
it != tablesOfContents.end();
++it)
{
TableOfContentsFrame *frame = dynamic_cast<TableOfContentsFrame *>(*it);
if(frame && frame->isTopLevel() == true)
return frame;
}
return 0;
}
void TableOfContentsFrame::parseFields(const ByteVector &data)
{
unsigned int size = data.size();
if(size < 6) {
debug("A CTOC frame must contain at least 6 bytes (1 byte element ID terminated by "
"null, 1 byte flags, 1 byte entry count and 1 byte child element ID terminated "
"by null.");
return;
}
int pos = 0;
unsigned int embPos = 0;
d->elementID = readStringField(data, String::Latin1, &pos).data(String::Latin1);
d->isTopLevel = (data.at(pos) & 2) != 0;
d->isOrdered = (data.at(pos++) & 1) != 0;
unsigned int entryCount = static_cast<unsigned char>(data.at(pos++));
for(unsigned int i = 0; i < entryCount; i++) {
ByteVector childElementID = readStringField(data, String::Latin1, &pos).data(String::Latin1);
d->childElements.append(childElementID);
}
size -= pos;
if(size < header()->size())
return;
while(embPos < size - header()->size()) {
Frame *frame = FrameFactory::instance()->createFrame(data.mid(pos + embPos), (d->tagHeader != 0));
if(!frame)
return;
// Checks to make sure that frame parsed correctly.
if(frame->size() <= 0) {
delete frame;
return;
}
embPos += frame->size() + header()->size();
addEmbeddedFrame(frame);
}
}
ByteVector TableOfContentsFrame::renderFields() const
{
ByteVector data;
data.append(d->elementID);
data.append('\0');
char flags = 0;
if(d->isTopLevel)
flags += 2;
if(d->isOrdered)
flags += 1;
data.append(flags);
data.append((char)(entryCount()));
ByteVectorList::ConstIterator it = d->childElements.begin();
while(it != d->childElements.end()) {
data.append(*it);
data.append('\0');
it++;
}
FrameList l = d->embeddedFrameList;
for(FrameList::ConstIterator it = l.begin(); it != l.end(); ++it)
data.append((*it)->render());
return data;
}
TableOfContentsFrame::TableOfContentsFrame(const ID3v2::Header *tagHeader,
const ByteVector &data, Header *h) :
Frame(h),
d(new TableOfContentsFramePrivate())
{
d->tagHeader = tagHeader;
parseFields(fieldData(data));
}
<|endoftext|>
|
<commit_before>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "jstreamsconfig.h"
#include "indexer.h"
#include "dummyindexwriter.h"
#include "streamindexer.h"
#include "indexerconfiguration.h"
#include "streamendanalyzer.h"
using namespace jstreams;
class FindIndexerConfiguration : public IndexerConfiguration {
public:
bool useFactory(StreamEndAnalyzerFactory* e) const {
return e->analyzesSubStreams();
}
bool useFactory(StreamThroughAnalyzerFactory*) const {return false;}
bool indexMore() const {return true;}
bool addMoreText() const {return false;}
};
void
printUsage(char** argv) {
fprintf(stderr, "Usage: %s [dir-or-file-to-find]\n", argv[0]);
}
bool
containsHelp(int argc, char **argv) {
for (int i=1; i<argc; ++i) {
if (strcmp(argv[i], "--help") == 0
|| strcmp(argv[i], "-h") == 0) return true;
}
return false;
}
int
main(int argc, char **argv) {
const char* path = ".";
if (containsHelp(argc, argv) || argc > 2) {
printUsage(argv);
return -1;
}
if (argc == 2) {
path = argv[1];
}
DummyIndexWriter writer(1);
FindIndexerConfiguration conf;
Indexer indexer(writer, conf);
indexer.index(path);
return 0;
}
<commit_msg>Add content and implement information function.<commit_after>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "jstreamsconfig.h"
#include "indexer.h"
#include "dummyindexwriter.h"
#include "streamindexer.h"
#include "indexerconfiguration.h"
#include "streamendanalyzer.h"
using namespace jstreams;
/**
* Special indexer that indexes only the filenames.
**/
class FindIndexerConfiguration : public IndexerConfiguration {
public:
bool useFactory(StreamEndAnalyzerFactory* e) const {
return e->analyzesSubStreams();
}
bool useFactory(StreamThroughAnalyzerFactory*) const {return false;}
bool indexMore() const {return true;}
bool addMoreText() const {return false;}
FieldType getIndexType(const cnstr& fieldname) const {
return None;
}
};
void
printUsage(char** argv) {
fprintf(stderr, "Usage: %s [dir-or-file-to-find]\n", argv[0]);
}
bool
containsHelp(int argc, char **argv) {
for (int i=1; i<argc; ++i) {
if (strcmp(argv[i], "--help") == 0
|| strcmp(argv[i], "-h") == 0) return true;
}
return false;
}
int
main(int argc, char **argv) {
const char* path = ".";
if (containsHelp(argc, argv) || argc > 2) {
printUsage(argv);
return -1;
}
if (argc == 2) {
path = argv[1];
}
DummyIndexWriter writer(1);
FindIndexerConfiguration conf;
Indexer indexer(writer, conf);
indexer.index(path);
return 0;
}
<|endoftext|>
|
<commit_before>#ifndef Rice__Hash__ipp_
#define Rice__Hash__ipp_
#include "protect.hpp"
#include "to_from_ruby.hpp"
#include "Builtin_Object.hpp"
#include "Exception.hpp"
#include "Builtin_Object.hpp"
#include <algorithm>
// TODO: Evil hack
struct st_table_entry {
unsigned int hash;
st_data_t key;
st_data_t record;
st_table_entry *next;
};
inline Rice::Hash::
Hash()
: Builtin_Object<RHash, T_HASH>(protect(rb_hash_new))
{
}
inline Rice::Hash::
Hash(Object v)
: Builtin_Object<RHash, T_HASH>(v)
{
}
inline size_t Rice::Hash::
size() const
{
return RHASH_TBL(*this)->num_entries;
}
inline Rice::Hash::Proxy::
Proxy(Hash hash, Object key)
: hash_(hash)
, key_(key)
{
}
/*
inline Rice::Hash::Proxy::
operator VALUE() const
{
return value();
}
*/
inline Rice::Hash::Proxy::
operator Rice::Object() const
{
return value();
}
inline VALUE Rice::Hash::Proxy::
value() const
{
return protect(rb_hash_aref, hash_, key_);
}
template<typename T>
inline Rice::Object Rice::Hash::Proxy::
operator=(T const & value)
{
return protect(rb_hash_aset, hash_, key_, to_ruby(value));
}
inline void Rice::Hash::Proxy::
swap(Proxy & proxy)
{
hash_.swap(proxy.hash_);
key_.swap(proxy.key_);
}
template<typename Key_T>
inline Rice::Hash::Proxy const Rice::Hash::
operator[](Key_T const & key) const
{
return Proxy(*this, to_ruby(key));
}
template<typename Key_T>
inline Rice::Hash::Proxy Rice::Hash::
operator[](Key_T const & key)
{
return Proxy(*this, to_ruby(key));
}
template<typename Value_T, typename Key_T>
inline Value_T Rice::Hash::
get(Key_T const & key)
{
Object ruby_key(to_ruby(key));
Object value = operator[](ruby_key);
try
{
return from_ruby<Value_T>(value);
}
catch(Exception const & ex)
{
String s_key(ruby_key.to_s());
throw Exception(
ex,
"%s while converting value for key %s",
ex.what(),
s_key.c_str());
}
}
inline Rice::Hash::Entry::
Entry(Hash hash, Object key)
: key(key)
, first(Hash::Entry::key)
, value(hash, key)
, second(Hash::Entry::value)
{
}
inline Rice::Hash::Entry::
Entry(Entry const & entry)
: key(entry.key)
, first(Hash::Entry::key)
, value(entry.value)
, second(Hash::Entry::value)
{
}
inline Rice::Hash::Entry & Rice::Hash::Entry::
operator=(Rice::Hash::Entry const & rhs)
{
Entry tmp(rhs);
swap(tmp);
return *this;
}
inline void Rice::Hash::Entry::
swap(Rice::Hash::Entry & entry)
{
const_cast<Object &>(key).swap(const_cast<Object &>(entry.key));
value.swap(entry.value);
}
template<typename Hash_Ref_T, typename Value_T>
inline Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
Iterator(Hash_Ref_T hash, size_t bin, st_table_entry * ptr)
: hash_(hash)
, tbl_(RHASH_TBL(hash.value()))
, bin_(bin)
, ptr_(ptr)
, tmp_(hash, Qnil)
{
// If we aren't already at the end, then use the increment operator to
// point to the first element
if(!ptr_ && bin_ < tbl_->num_bins)
{
operator++();
}
}
template<typename Hash_Ref_T, typename Value_T>
inline Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
Iterator(Iterator const & iterator)
: hash_(iterator.hash_.value())
, tbl_(iterator.tbl_)
, bin_(iterator.bin_)
, ptr_(iterator.ptr_)
, tmp_(iterator.hash_, Qnil)
{
}
template<typename Hash_Ref_T, typename Value_T>
template<typename Iterator_T>
inline Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
Iterator(Iterator_T const & iterator)
: hash_(iterator.hash_.value())
, tbl_(iterator.tbl_)
, bin_(iterator.bin_)
, ptr_(iterator.ptr_)
, tmp_(iterator.hash_, Qnil)
{
}
template<typename Hash_Ref_T, typename Value_T>
inline Rice::Hash::Iterator<Hash_Ref_T, Value_T> &
Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
operator=(Iterator const & iterator)
{
Iterator tmp(iterator);
this->swap(tmp);
return *this;
}
template<typename Hash_Ref_T, typename Value_T>
inline Rice::Hash::Iterator<Hash_Ref_T, Value_T> &
Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
operator++()
{
// Go to the next element in the bin; this will be a no-op if we were
// called from the constructor, because ptr_ will be 0 (and if its
// not, this function won't get called).
if(ptr_)
{
ptr_ = ptr_->next;
}
// If we've reached the end of the bin, then try the next bin until
// we have run out of bins
while(ptr_ == 0)
{
++bin_;
if(bin_ == tbl_->num_bins)
{
// At the end..
return *this;
}
ptr_ = tbl_->bins[bin_];
}
return *this;
}
template<typename Hash_Ref_T, typename Value_T>
inline Rice::Hash::Iterator<Hash_Ref_T, Value_T>
Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
operator++(int)
{
Iterator copy(*this);
++(*this);
return copy;
}
template<typename Hash_Ref_T, typename Value_T>
inline Value_T
Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
operator*()
{
return Value_T(hash_, ptr_->key);
}
template<typename Hash_Ref_T, typename Value_T>
inline Value_T *
Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
operator->()
{
Entry tmp(hash_, ptr_->key);
this->tmp_.swap(tmp);
return &tmp_;
}
template<typename Hash_Ref_T, typename Value_T>
inline bool Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
operator==(Iterator const & rhs) const
{
return hash_.value() == rhs.hash_.value()
&& tbl_ == rhs.tbl_
&& bin_ == rhs.bin_
&& ptr_ == rhs.ptr_;
}
template<typename Hash_Ref_T, typename Value_T>
inline bool Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
operator!=(Iterator const & rhs) const
{
return !(*this == rhs);
}
template<typename Hash_Ref_T, typename Value_T>
inline void
Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
swap(Iterator& iterator)
{
using namespace std;
hash_.swap(iterator.hash_);
swap(tbl_, iterator.tbl_);
swap(bin_, iterator.bin_);
swap(ptr_, iterator.ptr_);
}
inline Rice::Hash::iterator Rice::Hash::
begin()
{
st_table * tbl(RHASH_TBL(value()));
return iterator(*this, 0, tbl->bins[0]);
}
inline Rice::Hash::const_iterator Rice::Hash::
begin() const
{
st_table * tbl(RHASH_TBL(value()));
return const_iterator(*this, 0, tbl->bins[0]);
}
inline Rice::Hash::iterator Rice::Hash::
end()
{
st_table * tbl(RHASH_TBL(value()));
return iterator(*this, tbl->num_bins, 0);
}
inline Rice::Hash::const_iterator Rice::Hash::
end() const
{
st_table * tbl(RHASH_TBL(value()));
return const_iterator(*this, tbl->num_bins, 0);
}
inline bool Rice::
operator<(
Hash::Entry const & lhs, Hash::Entry const & rhs)
{
Object lhs_key(lhs.key);
Object rhs_key(rhs.key);
if(lhs_key < rhs_key)
{
return true;
}
else if(lhs_key > rhs_key)
{
return false;
}
else if(Object(lhs.value.value()) < Object(rhs.value.value()))
{
return true;
}
else
{
return false;
}
}
#endif // Rice__Hash__ipp_
<commit_msg>Fixed compile error where *this wasn't implicitly converted to a VALUE.<commit_after>#ifndef Rice__Hash__ipp_
#define Rice__Hash__ipp_
#include "protect.hpp"
#include "to_from_ruby.hpp"
#include "Builtin_Object.hpp"
#include "Exception.hpp"
#include "Builtin_Object.hpp"
#include <algorithm>
// TODO: Evil hack
struct st_table_entry {
unsigned int hash;
st_data_t key;
st_data_t record;
st_table_entry *next;
};
inline Rice::Hash::
Hash()
: Builtin_Object<RHash, T_HASH>(protect(rb_hash_new))
{
}
inline Rice::Hash::
Hash(Object v)
: Builtin_Object<RHash, T_HASH>(v)
{
}
inline size_t Rice::Hash::
size() const
{
return RHASH_TBL(this->value())->num_entries;
}
inline Rice::Hash::Proxy::
Proxy(Hash hash, Object key)
: hash_(hash)
, key_(key)
{
}
/*
inline Rice::Hash::Proxy::
operator VALUE() const
{
return value();
}
*/
inline Rice::Hash::Proxy::
operator Rice::Object() const
{
return value();
}
inline VALUE Rice::Hash::Proxy::
value() const
{
return protect(rb_hash_aref, hash_, key_);
}
template<typename T>
inline Rice::Object Rice::Hash::Proxy::
operator=(T const & value)
{
return protect(rb_hash_aset, hash_, key_, to_ruby(value));
}
inline void Rice::Hash::Proxy::
swap(Proxy & proxy)
{
hash_.swap(proxy.hash_);
key_.swap(proxy.key_);
}
template<typename Key_T>
inline Rice::Hash::Proxy const Rice::Hash::
operator[](Key_T const & key) const
{
return Proxy(*this, to_ruby(key));
}
template<typename Key_T>
inline Rice::Hash::Proxy Rice::Hash::
operator[](Key_T const & key)
{
return Proxy(*this, to_ruby(key));
}
template<typename Value_T, typename Key_T>
inline Value_T Rice::Hash::
get(Key_T const & key)
{
Object ruby_key(to_ruby(key));
Object value = operator[](ruby_key);
try
{
return from_ruby<Value_T>(value);
}
catch(Exception const & ex)
{
String s_key(ruby_key.to_s());
throw Exception(
ex,
"%s while converting value for key %s",
ex.what(),
s_key.c_str());
}
}
inline Rice::Hash::Entry::
Entry(Hash hash, Object key)
: key(key)
, first(Hash::Entry::key)
, value(hash, key)
, second(Hash::Entry::value)
{
}
inline Rice::Hash::Entry::
Entry(Entry const & entry)
: key(entry.key)
, first(Hash::Entry::key)
, value(entry.value)
, second(Hash::Entry::value)
{
}
inline Rice::Hash::Entry & Rice::Hash::Entry::
operator=(Rice::Hash::Entry const & rhs)
{
Entry tmp(rhs);
swap(tmp);
return *this;
}
inline void Rice::Hash::Entry::
swap(Rice::Hash::Entry & entry)
{
const_cast<Object &>(key).swap(const_cast<Object &>(entry.key));
value.swap(entry.value);
}
template<typename Hash_Ref_T, typename Value_T>
inline Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
Iterator(Hash_Ref_T hash, size_t bin, st_table_entry * ptr)
: hash_(hash)
, tbl_(RHASH_TBL(hash.value()))
, bin_(bin)
, ptr_(ptr)
, tmp_(hash, Qnil)
{
// If we aren't already at the end, then use the increment operator to
// point to the first element
if(!ptr_ && bin_ < tbl_->num_bins)
{
operator++();
}
}
template<typename Hash_Ref_T, typename Value_T>
inline Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
Iterator(Iterator const & iterator)
: hash_(iterator.hash_.value())
, tbl_(iterator.tbl_)
, bin_(iterator.bin_)
, ptr_(iterator.ptr_)
, tmp_(iterator.hash_, Qnil)
{
}
template<typename Hash_Ref_T, typename Value_T>
template<typename Iterator_T>
inline Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
Iterator(Iterator_T const & iterator)
: hash_(iterator.hash_.value())
, tbl_(iterator.tbl_)
, bin_(iterator.bin_)
, ptr_(iterator.ptr_)
, tmp_(iterator.hash_, Qnil)
{
}
template<typename Hash_Ref_T, typename Value_T>
inline Rice::Hash::Iterator<Hash_Ref_T, Value_T> &
Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
operator=(Iterator const & iterator)
{
Iterator tmp(iterator);
this->swap(tmp);
return *this;
}
template<typename Hash_Ref_T, typename Value_T>
inline Rice::Hash::Iterator<Hash_Ref_T, Value_T> &
Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
operator++()
{
// Go to the next element in the bin; this will be a no-op if we were
// called from the constructor, because ptr_ will be 0 (and if its
// not, this function won't get called).
if(ptr_)
{
ptr_ = ptr_->next;
}
// If we've reached the end of the bin, then try the next bin until
// we have run out of bins
while(ptr_ == 0)
{
++bin_;
if(bin_ == tbl_->num_bins)
{
// At the end..
return *this;
}
ptr_ = tbl_->bins[bin_];
}
return *this;
}
template<typename Hash_Ref_T, typename Value_T>
inline Rice::Hash::Iterator<Hash_Ref_T, Value_T>
Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
operator++(int)
{
Iterator copy(*this);
++(*this);
return copy;
}
template<typename Hash_Ref_T, typename Value_T>
inline Value_T
Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
operator*()
{
return Value_T(hash_, ptr_->key);
}
template<typename Hash_Ref_T, typename Value_T>
inline Value_T *
Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
operator->()
{
Entry tmp(hash_, ptr_->key);
this->tmp_.swap(tmp);
return &tmp_;
}
template<typename Hash_Ref_T, typename Value_T>
inline bool Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
operator==(Iterator const & rhs) const
{
return hash_.value() == rhs.hash_.value()
&& tbl_ == rhs.tbl_
&& bin_ == rhs.bin_
&& ptr_ == rhs.ptr_;
}
template<typename Hash_Ref_T, typename Value_T>
inline bool Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
operator!=(Iterator const & rhs) const
{
return !(*this == rhs);
}
template<typename Hash_Ref_T, typename Value_T>
inline void
Rice::Hash::Iterator<Hash_Ref_T, Value_T>::
swap(Iterator& iterator)
{
using namespace std;
hash_.swap(iterator.hash_);
swap(tbl_, iterator.tbl_);
swap(bin_, iterator.bin_);
swap(ptr_, iterator.ptr_);
}
inline Rice::Hash::iterator Rice::Hash::
begin()
{
st_table * tbl(RHASH_TBL(value()));
return iterator(*this, 0, tbl->bins[0]);
}
inline Rice::Hash::const_iterator Rice::Hash::
begin() const
{
st_table * tbl(RHASH_TBL(value()));
return const_iterator(*this, 0, tbl->bins[0]);
}
inline Rice::Hash::iterator Rice::Hash::
end()
{
st_table * tbl(RHASH_TBL(value()));
return iterator(*this, tbl->num_bins, 0);
}
inline Rice::Hash::const_iterator Rice::Hash::
end() const
{
st_table * tbl(RHASH_TBL(value()));
return const_iterator(*this, tbl->num_bins, 0);
}
inline bool Rice::
operator<(
Hash::Entry const & lhs, Hash::Entry const & rhs)
{
Object lhs_key(lhs.key);
Object rhs_key(rhs.key);
if(lhs_key < rhs_key)
{
return true;
}
else if(lhs_key > rhs_key)
{
return false;
}
else if(Object(lhs.value.value()) < Object(rhs.value.value()))
{
return true;
}
else
{
return false;
}
}
#endif // Rice__Hash__ipp_
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io>
* Authors:
* - Paul Asmuth <paul@eventql.io>
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License ("the license") as
* published by the Free Software Foundation, either version 3 of the License,
* or any later version.
*
* In accordance with Section 7(e) of the license, the licensing of the Program
* under the license does not imply a trademark license. Therefore any rights,
* title and interest in our trademarks remain entirely with us.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the license for more details.
*
* You can be released from the requirements of the license by purchasing a
* commercial license. Buying such a license is mandatory as soon as you develop
* commercial activities involving this program without disclosing the source
* code of your own applications
*/
#include <string>
#include <ctime>
#include <sys/time.h>
#include <sys/types.h>
#ifdef __MACH__
#include <mach/clock.h>
#include <mach/mach.h>
#endif
#include "eventql/util/wallclock.h"
#include "eventql/util/logging.h"
UnixTime WallClock::now() {
return UnixTime(WallClock::getUnixMicros());
}
uint64_t WallClock::unixSeconds() {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec;
}
uint64_t WallClock::getUnixMillis() {
return unixMillis();
}
uint64_t WallClock::unixMillis() {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec * 1000llu + tv.tv_usec / 1000llu;
}
uint64_t WallClock::getUnixMicros() {
return unixMicros();
}
uint64_t WallClock::unixMicros() {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec * 1000000llu + tv.tv_usec;
}
uint64_t MonotonicClock::now() {
#ifdef __MACH__
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);
clock_get_time(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);
return std::uint64_t(mts.tv_sec) * 1000000 + mts.tv_nsec / 1000;
#else
timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {
logFatal("clock_gettime(CLOCK_MONOTONIC) failed");
abort();
} else {
return std::uint64_t(ts.tv_sec) * 1000000 + ts.tv_nsec / 1000;
}
#endif
}
<commit_msg>fix invalid logFatal call<commit_after>/**
* Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io>
* Authors:
* - Paul Asmuth <paul@eventql.io>
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License ("the license") as
* published by the Free Software Foundation, either version 3 of the License,
* or any later version.
*
* In accordance with Section 7(e) of the license, the licensing of the Program
* under the license does not imply a trademark license. Therefore any rights,
* title and interest in our trademarks remain entirely with us.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the license for more details.
*
* You can be released from the requirements of the license by purchasing a
* commercial license. Buying such a license is mandatory as soon as you develop
* commercial activities involving this program without disclosing the source
* code of your own applications
*/
#include <string>
#include <ctime>
#include <sys/time.h>
#include <sys/types.h>
#ifdef __MACH__
#include <mach/clock.h>
#include <mach/mach.h>
#endif
#include "eventql/util/wallclock.h"
#include "eventql/util/logging.h"
UnixTime WallClock::now() {
return UnixTime(WallClock::getUnixMicros());
}
uint64_t WallClock::unixSeconds() {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec;
}
uint64_t WallClock::getUnixMillis() {
return unixMillis();
}
uint64_t WallClock::unixMillis() {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec * 1000llu + tv.tv_usec / 1000llu;
}
uint64_t WallClock::getUnixMicros() {
return unixMicros();
}
uint64_t WallClock::unixMicros() {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec * 1000000llu + tv.tv_usec;
}
uint64_t MonotonicClock::now() {
#ifdef __MACH__
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);
clock_get_time(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);
return std::uint64_t(mts.tv_sec) * 1000000 + mts.tv_nsec / 1000;
#else
timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {
logFatal("evqld", "clock_gettime(CLOCK_MONOTONIC) failed");
abort();
} else {
return std::uint64_t(ts.tv_sec) * 1000000 + ts.tv_nsec / 1000;
}
#endif
}
<|endoftext|>
|
<commit_before>409ad740-ad5a-11e7-8fcd-ac87a332f658<commit_msg>My Life for Auir<commit_after>410abed1-ad5a-11e7-b246-ac87a332f658<|endoftext|>
|
<commit_before>39e4ef05-2e4f-11e5-89bc-28cfe91dbc4b<commit_msg>39ee201c-2e4f-11e5-9a4e-28cfe91dbc4b<commit_after>39ee201c-2e4f-11e5-9a4e-28cfe91dbc4b<|endoftext|>
|
<commit_before>db9e9c9e-2e4e-11e5-b7c6-28cfe91dbc4b<commit_msg>dba54499-2e4e-11e5-83b5-28cfe91dbc4b<commit_after>dba54499-2e4e-11e5-83b5-28cfe91dbc4b<|endoftext|>
|
<commit_before>5bf673ff-2d16-11e5-af21-0401358ea401<commit_msg>5bf67400-2d16-11e5-af21-0401358ea401<commit_after>5bf67400-2d16-11e5-af21-0401358ea401<|endoftext|>
|
<commit_before>a336a06c-35ca-11e5-8079-6c40088e03e4<commit_msg>a33fc9f8-35ca-11e5-be28-6c40088e03e4<commit_after>a33fc9f8-35ca-11e5-be28-6c40088e03e4<|endoftext|>
|
<commit_before>471c730c-2748-11e6-9bba-e0f84713e7b8<commit_msg>lets try again<commit_after>47275075-2748-11e6-8282-e0f84713e7b8<|endoftext|>
|
<commit_before>e6bd4e78-2747-11e6-92d9-e0f84713e7b8<commit_msg>Deal with it<commit_after>e6cf1da8-2747-11e6-be1c-e0f84713e7b8<|endoftext|>
|
<commit_before>6fb82b6e-2d3e-11e5-95ed-c82a142b6f9b<commit_msg>702ea53a-2d3e-11e5-a40e-c82a142b6f9b<commit_after>702ea53a-2d3e-11e5-a40e-c82a142b6f9b<|endoftext|>
|
<commit_before>bf9cafc0-2d3d-11e5-a8dc-c82a142b6f9b<commit_msg>bffc1594-2d3d-11e5-a35a-c82a142b6f9b<commit_after>bffc1594-2d3d-11e5-a35a-c82a142b6f9b<|endoftext|>
|
<commit_before>d190a9a8-35ca-11e5-a3dd-6c40088e03e4<commit_msg>d1975988-35ca-11e5-b1ac-6c40088e03e4<commit_after>d1975988-35ca-11e5-b1ac-6c40088e03e4<|endoftext|>
|
<commit_before>b2f04480-ad5b-11e7-baf7-ac87a332f658<commit_msg>NO CHANGES<commit_after>b36db866-ad5b-11e7-a2ed-ac87a332f658<|endoftext|>
|
<commit_before>7c58de68-2e4f-11e5-9933-28cfe91dbc4b<commit_msg>7c61c5fa-2e4f-11e5-9181-28cfe91dbc4b<commit_after>7c61c5fa-2e4f-11e5-9181-28cfe91dbc4b<|endoftext|>
|
<commit_before>dd51cb05-2e4e-11e5-89f8-28cfe91dbc4b<commit_msg>dd596f63-2e4e-11e5-9cbf-28cfe91dbc4b<commit_after>dd596f63-2e4e-11e5-9cbf-28cfe91dbc4b<|endoftext|>
|
<commit_before>c3885c11-327f-11e5-9068-9cf387a8033e<commit_msg>c38eb0e6-327f-11e5-bcf8-9cf387a8033e<commit_after>c38eb0e6-327f-11e5-bcf8-9cf387a8033e<|endoftext|>
|
<commit_before>a4d5fb63-327f-11e5-b897-9cf387a8033e<commit_msg>a4dc183a-327f-11e5-8fdc-9cf387a8033e<commit_after>a4dc183a-327f-11e5-8fdc-9cf387a8033e<|endoftext|>
|
<commit_before>e4123eb8-2747-11e6-9413-e0f84713e7b8<commit_msg>My Life for Auir<commit_after>e421e997-2747-11e6-944a-e0f84713e7b8<|endoftext|>
|
<commit_before>76155412-2e3a-11e5-8f08-c03896053bdd<commit_msg>762471fe-2e3a-11e5-92a1-c03896053bdd<commit_after>762471fe-2e3a-11e5-92a1-c03896053bdd<|endoftext|>
|
<commit_before>17ea6191-2e4f-11e5-b43b-28cfe91dbc4b<commit_msg>17f132b0-2e4f-11e5-a5e7-28cfe91dbc4b<commit_after>17f132b0-2e4f-11e5-a5e7-28cfe91dbc4b<|endoftext|>
|
<commit_before>ddb7ab18-585a-11e5-9295-6c40088e03e4<commit_msg>ddbe452c-585a-11e5-90d1-6c40088e03e4<commit_after>ddbe452c-585a-11e5-90d1-6c40088e03e4<|endoftext|>
|
<commit_before>c8e407b3-2d3c-11e5-a246-c82a142b6f9b<commit_msg>c9480c63-2d3c-11e5-a76f-c82a142b6f9b<commit_after>c9480c63-2d3c-11e5-a76f-c82a142b6f9b<|endoftext|>
|
<commit_before>af0649bd-ad5b-11e7-bb36-ac87a332f658<commit_msg>Stuff changed<commit_after>af8a9fdc-ad5b-11e7-a7fb-ac87a332f658<|endoftext|>
|
<commit_before>641506fa-2749-11e6-acb3-e0f84713e7b8<commit_msg>testing<commit_after>6426442e-2749-11e6-943f-e0f84713e7b8<|endoftext|>
|
<commit_before>5aee97fa-2e3a-11e5-a24c-c03896053bdd<commit_msg>5afe5250-2e3a-11e5-b00c-c03896053bdd<commit_after>5afe5250-2e3a-11e5-b00c-c03896053bdd<|endoftext|>
|
<commit_before>d622f6a3-327f-11e5-a888-9cf387a8033e<commit_msg>d629739e-327f-11e5-881a-9cf387a8033e<commit_after>d629739e-327f-11e5-881a-9cf387a8033e<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Wapp6
** All rights reserved.
** Contact: Wapp6 (contact@wapp6.com)
**
** This file is part of OPR6Desktop application.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QCoreApplication>
#include <QCommandLineOption>
#include <QCommandLineParser>
#include <QStandardPaths>
#include <QDir>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlRecord>
#include <QSqlError>
#include <QDebug>
#include <QTextStream>
#include <QDateTime>
#include <iostream>
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
QString noteTable = "note";
QCoreApplication::setApplicationName("clignote");
QCoreApplication::setApplicationVersion("1.0");
QString storedNotes = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
if(!QDir(storedNotes).exists() && !QDir(storedNotes).mkpath(storedNotes)) {
std::cout << "unable to create directory, exiting...";
exit(-1);
}
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
QSqlQuery query;
QDir storage(storedNotes);
db.setDatabaseName(storage.absoluteFilePath("notes.db"));
if(!db.open()) {
qDebug() << "unable to open db";
std::cout << db.lastError().text().toStdString();
exit(-2);
} else {
query = QSqlQuery(db);
if(!db.tables().contains(noteTable)) {
qDebug() << "table note is not present, creating";
if(!query.exec(QString("CREATE TABLE %1(id INTEGER PRIMARY KEY, created_at DATETIME, text TEXT);").arg(noteTable))) {
qDebug() << query.lastQuery() << query.lastError() << db.lastError();
std::cout << "error creating database";
exit(-1);
}
}
}
QCommandLineParser parser;
parser.setApplicationDescription("Note helper");
parser.addHelpOption();
parser.addVersionOption();
parser.addPositionalArgument("command", QCoreApplication::translate("main", "what to do (list, add, delete)"));
parser.addPositionalArgument("content", QCoreApplication::translate("main", "note id or text"));
// Process the actual command line arguments given by the user
parser.process(app);
const QStringList args = parser.positionalArguments();
if(!args.length()) {
std::cout << "argument required, use --help";
exit(0);
}
// source is args.at(0), destination is args.at(1)
if(args.at(0) == "list") {
if(query.exec(QString("select * from %1").arg(noteTable))) {;
if(query.first()) {
QSqlRecord record;
std::cout << " id | creation date | note \n";
std::cout << QString("").fill('-',80).toStdString() << "\n";
do {
record = query.record();
std::cout << QString().fill(' ', 6-record.value(0).toString().length()).toStdString()
<< record.value(0).toString().toStdString()
<< " | "
<< record.value(1).toDateTime().toString(Qt::ISODate).toStdString()
<< " | "
<< record.value(2).toString().toStdString()
<< "\n";
} while(query.next());
} else {
std::cout << QCoreApplication::translate("main", "No note available\n").toStdString();
}
} else {
std::cout << "error querying database\n";
qDebug() << query.lastQuery() << query.lastError() << db.lastError();
}
exit(0);
}
if(args.at(0) == "add") {
if(args.length() < 2) {
std::cout << "no note to add...";
}
else {
qDebug() << args.mid(1).join(" ");
QString text = args.mid(1).join(" ");
query.prepare(QString("insert into %1 values(NULL, :currentDateTime, :text)").arg(noteTable));
query.bindValue(":currentDateTime", QDateTime::currentDateTime());
query.bindValue(":text", text);
if(query.exec()) {
std::cout << "note added\n";
} else {
std::cout << "error saving note to database\n";
qDebug() << query.lastQuery() << query.lastError() << db.lastError();
}
}
exit(0);
}
if(args.at(0) == "delete") {
if(args.length() < 2) {
std::cout << "no note to delete...\n";
}
else {
qInfo() << args.at(1);
QString intString = args.at(1);
int noteId = QVariant(intString).toInt();
if(noteId) {
query.prepare(QString("delete from %1 where id=:id").arg(noteTable));
query.bindValue(":id", noteId);
if(query.exec()) {
std::cout << "note deleted\n";
} else {
qDebug() << query.lastQuery() << query.lastError() << db.lastError();
std::cout << "error deleting note from database\n";
}
} else {
std::cout << "invalid note identifier\n";
}
}
exit(0);
}
return app.exec();
}
<commit_msg>remove licence header<commit_after>#include <QCoreApplication>
#include <QCommandLineOption>
#include <QCommandLineParser>
#include <QStandardPaths>
#include <QDir>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlRecord>
#include <QSqlError>
#include <QDebug>
#include <QTextStream>
#include <QDateTime>
#include <iostream>
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
QString noteTable = "note";
QCoreApplication::setApplicationName("clignote");
QCoreApplication::setApplicationVersion("1.0");
QString storedNotes = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
if(!QDir(storedNotes).exists() && !QDir(storedNotes).mkpath(storedNotes)) {
std::cout << "unable to create directory, exiting...";
exit(-1);
}
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
QSqlQuery query;
QDir storage(storedNotes);
db.setDatabaseName(storage.absoluteFilePath("notes.db"));
if(!db.open()) {
qDebug() << "unable to open db";
std::cout << db.lastError().text().toStdString();
exit(-2);
} else {
query = QSqlQuery(db);
if(!db.tables().contains(noteTable)) {
qDebug() << "table note is not present, creating";
if(!query.exec(QString("CREATE TABLE %1(id INTEGER PRIMARY KEY, created_at DATETIME, text TEXT);").arg(noteTable))) {
qDebug() << query.lastQuery() << query.lastError() << db.lastError();
std::cout << "error creating database";
exit(-1);
}
}
}
QCommandLineParser parser;
parser.setApplicationDescription("Note helper");
parser.addHelpOption();
parser.addVersionOption();
parser.addPositionalArgument("command", QCoreApplication::translate("main", "what to do (list, add, delete)"));
parser.addPositionalArgument("content", QCoreApplication::translate("main", "note id or text"));
// Process the actual command line arguments given by the user
parser.process(app);
const QStringList args = parser.positionalArguments();
if(!args.length()) {
std::cout << "argument required, use --help";
exit(0);
}
// source is args.at(0), destination is args.at(1)
if(args.at(0) == "list") {
if(query.exec(QString("select * from %1").arg(noteTable))) {;
if(query.first()) {
QSqlRecord record;
std::cout << " id | creation date | note \n";
std::cout << QString("").fill('-',80).toStdString() << "\n";
do {
record = query.record();
std::cout << QString().fill(' ', 6-record.value(0).toString().length()).toStdString()
<< record.value(0).toString().toStdString()
<< " | "
<< record.value(1).toDateTime().toString(Qt::ISODate).toStdString()
<< " | "
<< record.value(2).toString().toStdString()
<< "\n";
} while(query.next());
} else {
std::cout << QCoreApplication::translate("main", "No note available\n").toStdString();
}
} else {
std::cout << "error querying database\n";
qDebug() << query.lastQuery() << query.lastError() << db.lastError();
}
exit(0);
}
if(args.at(0) == "add") {
if(args.length() < 2) {
std::cout << "no note to add...";
}
else {
qDebug() << args.mid(1).join(" ");
QString text = args.mid(1).join(" ");
query.prepare(QString("insert into %1 values(NULL, :currentDateTime, :text)").arg(noteTable));
query.bindValue(":currentDateTime", QDateTime::currentDateTime());
query.bindValue(":text", text);
if(query.exec()) {
std::cout << "note added\n";
} else {
std::cout << "error saving note to database\n";
qDebug() << query.lastQuery() << query.lastError() << db.lastError();
}
}
exit(0);
}
if(args.at(0) == "delete") {
if(args.length() < 2) {
std::cout << "no note to delete...\n";
}
else {
qInfo() << args.at(1);
QString intString = args.at(1);
int noteId = QVariant(intString).toInt();
if(noteId) {
query.prepare(QString("delete from %1 where id=:id").arg(noteTable));
query.bindValue(":id", noteId);
if(query.exec()) {
std::cout << "note deleted\n";
} else {
qDebug() << query.lastQuery() << query.lastError() << db.lastError();
std::cout << "error deleting note from database\n";
}
} else {
std::cout << "invalid note identifier\n";
}
}
exit(0);
}
return app.exec();
}
<|endoftext|>
|
<commit_before>2dc2c214-2748-11e6-be5b-e0f84713e7b8<commit_msg>almost working<commit_after>2dd2bb4c-2748-11e6-800c-e0f84713e7b8<|endoftext|>
|
<commit_before>5e58949e-2d16-11e5-af21-0401358ea401<commit_msg>5e58949f-2d16-11e5-af21-0401358ea401<commit_after>5e58949f-2d16-11e5-af21-0401358ea401<|endoftext|>
|
<commit_before>6de91794-2fa5-11e5-83e1-00012e3d3f12<commit_msg>6deaec52-2fa5-11e5-a6f6-00012e3d3f12<commit_after>6deaec52-2fa5-11e5-a6f6-00012e3d3f12<|endoftext|>
|
<commit_before>97fce38c-35ca-11e5-ae63-6c40088e03e4<commit_msg>9804f37e-35ca-11e5-bbc3-6c40088e03e4<commit_after>9804f37e-35ca-11e5-bbc3-6c40088e03e4<|endoftext|>
|
<commit_before>1f268d4c-2e3a-11e5-980d-c03896053bdd<commit_msg>1f38ba9c-2e3a-11e5-864c-c03896053bdd<commit_after>1f38ba9c-2e3a-11e5-864c-c03896053bdd<|endoftext|>
|
<commit_before>229e99dc-2e4f-11e5-b9ad-28cfe91dbc4b<commit_msg>22a839d7-2e4f-11e5-86ea-28cfe91dbc4b<commit_after>22a839d7-2e4f-11e5-86ea-28cfe91dbc4b<|endoftext|>
|
<commit_before>0116afa1-2748-11e6-8c25-e0f84713e7b8<commit_msg>Deal with it<commit_after>013296f3-2748-11e6-ae91-e0f84713e7b8<|endoftext|>
|
<commit_before>4f64ef00-2748-11e6-8afc-e0f84713e7b8<commit_msg>That didn't fix it<commit_after>4f778847-2748-11e6-9f44-e0f84713e7b8<|endoftext|>
|
<commit_before>d55f7007-327f-11e5-80fc-9cf387a8033e<commit_msg>d5673eab-327f-11e5-98b6-9cf387a8033e<commit_after>d5673eab-327f-11e5-98b6-9cf387a8033e<|endoftext|>
|
<commit_before>69c02e64-2fa5-11e5-8edc-00012e3d3f12<commit_msg>69c1dc14-2fa5-11e5-99f2-00012e3d3f12<commit_after>69c1dc14-2fa5-11e5-99f2-00012e3d3f12<|endoftext|>
|
<commit_before>9699693d-327f-11e5-b824-9cf387a8033e<commit_msg>96a0caa6-327f-11e5-90e3-9cf387a8033e<commit_after>96a0caa6-327f-11e5-90e3-9cf387a8033e<|endoftext|>
|
<commit_before>9101ae2d-2d14-11e5-af21-0401358ea401<commit_msg>9101ae2e-2d14-11e5-af21-0401358ea401<commit_after>9101ae2e-2d14-11e5-af21-0401358ea401<|endoftext|>
|
<commit_before>2e23a76e-2e4f-11e5-8654-28cfe91dbc4b<commit_msg>2e2ab1fa-2e4f-11e5-9257-28cfe91dbc4b<commit_after>2e2ab1fa-2e4f-11e5-9257-28cfe91dbc4b<|endoftext|>
|
<commit_before>83000ea8-2d15-11e5-af21-0401358ea401<commit_msg>83000ea9-2d15-11e5-af21-0401358ea401<commit_after>83000ea9-2d15-11e5-af21-0401358ea401<|endoftext|>
|
<commit_before>aa84c266-4b02-11e5-8914-28cfe9171a43<commit_msg>master branch<commit_after>aa91f987-4b02-11e5-a5e4-28cfe9171a43<|endoftext|>
|
<commit_before>51e2dccc-ad59-11e7-916b-ac87a332f658<commit_msg>Hey we can now do a thing<commit_after>528d44a8-ad59-11e7-a450-ac87a332f658<|endoftext|>
|
<commit_before>a21d0638-2e4f-11e5-8f55-28cfe91dbc4b<commit_msg>a223bd73-2e4f-11e5-b205-28cfe91dbc4b<commit_after>a223bd73-2e4f-11e5-b205-28cfe91dbc4b<|endoftext|>
|
<commit_before>67c74494-2fa5-11e5-bd2e-00012e3d3f12<commit_msg>67c94064-2fa5-11e5-9b2b-00012e3d3f12<commit_after>67c94064-2fa5-11e5-9b2b-00012e3d3f12<|endoftext|>
|
<commit_before>7293325e-2e4f-11e5-83b3-28cfe91dbc4b<commit_msg>729beb7d-2e4f-11e5-90f4-28cfe91dbc4b<commit_after>729beb7d-2e4f-11e5-90f4-28cfe91dbc4b<|endoftext|>
|
<commit_before>abd49845-327f-11e5-a1e6-9cf387a8033e<commit_msg>abda5d19-327f-11e5-ad3c-9cf387a8033e<commit_after>abda5d19-327f-11e5-ad3c-9cf387a8033e<|endoftext|>
|
<commit_before>5ae7ec32-2d16-11e5-af21-0401358ea401<commit_msg>5ae7ec33-2d16-11e5-af21-0401358ea401<commit_after>5ae7ec33-2d16-11e5-af21-0401358ea401<|endoftext|>
|
<commit_before>c88ac048-35ca-11e5-8022-6c40088e03e4<commit_msg>c89165f4-35ca-11e5-974b-6c40088e03e4<commit_after>c89165f4-35ca-11e5-974b-6c40088e03e4<|endoftext|>
|
<commit_before>95d55c38-ad5a-11e7-914b-ac87a332f658<commit_msg>Long commit messages are not required<commit_after>966df27a-ad5a-11e7-bcbc-ac87a332f658<|endoftext|>
|
<commit_before>e6d0d308-585a-11e5-babb-6c40088e03e4<commit_msg>e6d80600-585a-11e5-a33b-6c40088e03e4<commit_after>e6d80600-585a-11e5-a33b-6c40088e03e4<|endoftext|>
|
<commit_before>3e415728-5216-11e5-89d9-6c40088e03e4<commit_msg>3e482848-5216-11e5-bf8a-6c40088e03e4<commit_after>3e482848-5216-11e5-bf8a-6c40088e03e4<|endoftext|>
|
<commit_before>053b4b4c-2e4f-11e5-a7cc-28cfe91dbc4b<commit_msg>0544f070-2e4f-11e5-902c-28cfe91dbc4b<commit_after>0544f070-2e4f-11e5-902c-28cfe91dbc4b<|endoftext|>
|
<commit_before>94c5472b-2e4f-11e5-9ca0-28cfe91dbc4b<commit_msg>94cd7226-2e4f-11e5-9088-28cfe91dbc4b<commit_after>94cd7226-2e4f-11e5-9088-28cfe91dbc4b<|endoftext|>
|
<commit_before>c9d24fee-327f-11e5-ab8a-9cf387a8033e<commit_msg>c9d874bd-327f-11e5-85bf-9cf387a8033e<commit_after>c9d874bd-327f-11e5-85bf-9cf387a8033e<|endoftext|>
|
<commit_before>2caffbf6-2e3a-11e5-8a79-c03896053bdd<commit_msg>2cbe5676-2e3a-11e5-9127-c03896053bdd<commit_after>2cbe5676-2e3a-11e5-9127-c03896053bdd<|endoftext|>
|
<commit_before>444cc23d-2e4f-11e5-b2f8-28cfe91dbc4b<commit_msg>44557230-2e4f-11e5-9155-28cfe91dbc4b<commit_after>44557230-2e4f-11e5-9155-28cfe91dbc4b<|endoftext|>
|
<commit_before>#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <stdio.h>
#include <string>
#include "include/logging/enumCvType.hpp"
#include "include/filters/selectMode.hpp"
#include "include/filters/gaussianBlurWindows.hpp"
#include "include/filters/hsvColorThresholdWindows.hpp"
#include "include/filters/dilateErodeWindows.hpp"
#include "include/filters/cannyEdgeDetectWindows.hpp"
#include "include/filters/laplacianSharpenWindows.hpp"
#include "include/filters/houghLinesWindows.hpp"
#include "include/filters/mergeFinalWindows.hpp"
#include "include/filters/depthDistanceWindows.hpp"
void drawBoundedRects(cv::Mat& src, int thresh)
{
cv::Mat threshold_output;
std::vector<std::vector<cv::Point> > contours;
std::vector<cv::Vec4i> hierarchy;
// Convert src to gray format
cv::cvtColor(src, threshold_output, CV_BGR2GRAY);
// Detect edges using Threshold
cv::threshold(threshold_output, threshold_output, thresh, 255, cv::THRESH_BINARY);
// Find contours
cv::findContours(threshold_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0));
// Get the moments
std::vector<cv::Moments> mu(contours.size() );
for( int i = 0; i < contours.size(); i++ )
{ mu[i] = moments( contours[i], false ); }
// Get the mass centers:
std::vector<cv::Point2f> mc( contours.size() );
for( int i = 0; i < contours.size(); i++ )
{ mc[i] = cv::Point2f( mu[i].m10/mu[i].m00 , mu[i].m01/mu[i].m00 ); }
// Approximate contours to rotated rectangles and ellipses
std::vector<cv::RotatedRect> minRect( contours.size());
for(int i = 0; i < contours.size(); i++)
{
minRect[i] = cv::minAreaRect(cv::Mat(contours[i]));
}
// Draw polygonal contour + bounding rects
cv::Mat drawing = cv::Mat::zeros(threshold_output.size(), CV_8UC3);
for(int i = 0; i < contours.size(); i++)
{
cv::Scalar color = cv::Scalar(0, 0, 255);
cv::drawContours(drawing, contours, i, color, 1, 8, std::vector<cv::Vec4i>(), 0, cv::Point());
cv::Point2f rect_points[4]; minRect[i].points(rect_points);
for(int j = 0; j < 4; j++)
{
cv::line(drawing, rect_points[j], rect_points[(j+1)%4], color, 1, 8);
}
}
// Calculate the area with the moments 00 and compare with the result of the OpenCV function
printf("\t Info: Area and Contour Length \n");
for( int i = 0; i< contours.size(); i++ )
{
printf(" * Contour[%2d] - Area (M_00) = %4.2f - Area OpenCV: %4.2f - Length: %4.2f\n", i, mu[i].m00, contourArea(contours[i]), arcLength( contours[i], true ) );
cv::Scalar color = cv::Scalar(0, 255, 0);
cv::drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, cv::Point() );
}
// Show in a window
cv::namedWindow("Contours", CV_WINDOW_AUTOSIZE);
cv::imshow("Contours", drawing);
}
int main( int argc, char *argv[])
{
// Parameters for selecting which filters to apply
int blur = 0;
int color = 0;
int dilate_erode = 0;
int edge = 0;
int laplacian = 0;
int hough = 0;
int depth_dist = 0;
int merge = 0;
// Parameters for applying filters even if windows are closed
int apply_blur = 1;
int apply_color = 1;
int apply_dilate_erode = 0;
int apply_edge = 1;
int apply_laplacian = 0;
int apply_hough = 0;
int apply_depth_dist = 0;
int apply_merge = 1;
// gaussianBlur parameters
int blur_ksize = 7;
int sigmaX = 10;
int sigmaY = 10;
// hsvColorThreshold parameters
int hMin = 130;
int hMax = 190;
int sMin = 10;
int sMax = 30;
int vMin = 85;
int vMax = 100;
int debugMode = 0; // 0 is none, 1 is debug mode
int bitAnd = 1; // 0 is none, 1 is bitAnd between h, s, and v
// dilateErode parameters
int holes = 0;
int noise = 0;
int size = 1;
cv::Mat element = cv::getStructuringElement(cv::MORPH_CROSS,
cv::Size(2 * size + 1, 2 * size + 1),
cv::Point(size, size) );
// cannyEdgeDetect parameters
int threshLow = 100;
int threshHigh = 300;
// laplacianSharpen parameters
int laplacian_ksize = 3;
int scale = 1; // optional scale value added to image
int delta = 0; // optional delta value added to image
int ddepth = CV_16S;
// houghLines parameters
int rho = 1;
int theta = 180;
int threshold = 50;
int lineMin = 50;
int maxGap = 10;
// mergeFinal parameters
int weight1 = 100; // decide weighted sums of original rgb feed to filtered rgb feed; values = out of 100
int weight2 = 100;
std::cout << "\n";
std::cout << " =========== FILTER LIST =========== " << "\n";
std::cout << "| |" << "\n";
std::cout << "| (0) No Filter |" << "\n";
std::cout << "| (1) Gaussian Blur Filter |" << "\n";
std::cout << "| (2) HSV Color Filter |" << "\n";
std::cout << "| (3) Dilate and Erode Filter |" << "\n";
std::cout << "| (4) Canny Edge Detection Filter |" << "\n";
std::cout << "| (5) Laplacian Sharpen Filter |" << "\n";
std::cout << "| (6) Hough Lines Filter |" << "\n";
std::cout << "| (7) Merge Final Outputs |" << "\n";
std::cout << "| |" << "\n";
std::cout << " =================================== " << "\n";
std::cout << "\n";
std::cout << "\n";
std::cout << " ============== NOTICE ============= " << "\n";
std::cout << "| |" << "\n";
std::cout << "| Press 'q' to quit without saving |" << "\n";
std::cout << "| Press ' ' to pause |" << "\n";
std::cout << "| |" << "\n";
std::cout << " =================================== " << "\n";
std::cout << "\n";
cv::VideoCapture camera(0);
if( !camera.isOpened() && (argc < 2) )
{
std::cout << "Error - Unable to open Camera at Port 0" << std::endl;
return -1;
}
// Matrices for holding image data
cv::Mat rgb, rgb_orig;
cv::Mat image;
char kill = ' '; // Press q to quit the program
int thresh = 120;
while ((kill != 'q') && (kill != 's'))
{
if (kill == ' ') // Press space to pause program, then any key to resume
{
cv::waitKey(0);
}
selectMode(blur, color, dilate_erode, edge, laplacian, hough, depth_dist, merge);
if (argc > 2) // Use images
{
rgb = cv::imread(argv[1]);
rgb_orig = rgb.clone(); // Clone rgb input in order to merge at end
if (!rgb.data || !rgb_orig.data) // No data
{
std::cout << "No image data" << std::endl;
return -1;
}
}
else
{
camera >> rgb;
rgb_orig = rgb.clone();
}
cv::imshow("BGR Feed", rgb);
rgb.copyTo(image);
cv::namedWindow("Source", CV_WINDOW_AUTOSIZE);
cv::createTrackbar("Threshold:", "Source", &thresh, 255);
// Filters are only applied if last parameter is true, otherwise their windows are destroyed
gaussianBlurWindows(image, blur_ksize, sigmaX, sigmaY, apply_blur, blur);
hsvColorThresholdWindows(image, hMin, hMax, sMin, sMax, vMin, vMax, debugMode, bitAnd, apply_color, color);
dilateErodeWindows(image, element, holes, noise, apply_dilate_erode, dilate_erode);
drawBoundedRects(image, thresh);
cannyEdgeDetectWindows(image, threshLow, threshHigh, apply_edge, edge);
laplacianSharpenWindows(image, ddepth, laplacian_ksize, scale, delta, apply_laplacian, laplacian);
#if 0
// List sizes of image
cv::Size imageSize = image.size();
std::cout << "Image: [" << imageSize.height << " x " << imageSize.width << "]" << "\n";
#endif
houghLinesWindows(image, rho, theta, threshold, lineMin, maxGap, apply_hough, hough);
#if 0
// List sizes of image
imageSize = image.size();
std::cout << "Image: [" << imageSize.height << " x " << imageSize.width << "]" << "\n";
#endif
mergeFinalWindows(rgb_orig, image, weight1, weight2, apply_merge, merge);
kill = cv::waitKey(5);
}
return 0;
}
<commit_msg>Add in distance calculation code<commit_after>#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <stdio.h>
#include <string>
#include <cmath>
#include "include/logging/enumCvType.hpp"
#include "include/filters/selectMode.hpp"
#include "include/filters/gaussianBlurWindows.hpp"
#include "include/filters/hsvColorThresholdWindows.hpp"
#include "include/filters/dilateErodeWindows.hpp"
#include "include/filters/cannyEdgeDetectWindows.hpp"
#include "include/filters/laplacianSharpenWindows.hpp"
#include "include/filters/houghLinesWindows.hpp"
#include "include/filters/mergeFinalWindows.hpp"
#include "include/filters/depthDistanceWindows.hpp"
void calculateDistance (cv::Mat& image, cv::RotatedRect& boundedRect);
double distance(cv::Point one, cv::Point two);
void drawBoundedRects(cv::Mat& src, int thresh)
{
cv::Mat threshold_output;
std::vector<std::vector<cv::Point> > contours;
std::vector<cv::Vec4i> hierarchy;
// Convert src to gray format
cv::cvtColor(src, threshold_output, CV_BGR2GRAY);
// Detect edges using Threshold
cv::threshold(threshold_output, threshold_output, thresh, 255, cv::THRESH_BINARY);
// Find contours
cv::findContours(threshold_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0));
// Get the moments
std::vector<cv::Moments> mu(contours.size() );
for( int i = 0; i < contours.size(); i++ )
{ mu[i] = moments( contours[i], false ); }
// Get the mass centers:
std::vector<cv::Point2f> mc( contours.size() );
for( int i = 0; i < contours.size(); i++ )
{ mc[i] = cv::Point2f( mu[i].m10/mu[i].m00 , mu[i].m01/mu[i].m00 ); }
// Approximate contours to rotated rectangles and ellipses
std::vector<cv::RotatedRect> minRect( contours.size());
for(int i = 0; i < contours.size(); i++)
{
minRect[i] = cv::minAreaRect(cv::Mat(contours[i]));
}
// Draw polygonal contour + bounding rects
cv::Mat drawing = cv::Mat::zeros(threshold_output.size(), CV_8UC3);
for(int i = 0; i < contours.size(); i++)
{
//cv::Scalar color = cv::Scalar(0, 255, 255);
//cv::drawContours(drawing, contours, i, color, 1, 8, std::vector<cv::Vec4i>(), 0, cv::Point());
cv::Point2f rect_points[4];
minRect[i].points(rect_points);
for(int j = 0; j < 4; j++)
{
//cv::line(drawing, rect_points[j], rect_points[(j+1)%4], color, 1, 8);
}
}
// Bounded rectangle is the one at the 0th index
if (minRect.size() > 0)
calculateDistance(drawing, minRect[0]);
// Calculate the area with the moments 00 and compare with the result of the OpenCV function
// printf("\t Info: Area and Contour Length \n");
for( int i = 0; i < contours.size(); i++ )
{
// printf(" * Contour[%2d] - Area (M_00) = %4.2f - Area OpenCV: %4.2f - Length: %4.2f\n", i, mu[i].m00, contourArea(contours[i]), arcLength( contours[i], true ) );
// printf("Contour[%2d] - Length: %4.2f\n", i, arcLength( contours[i], true ) );
//cv::Scalar color = cv::Scalar(0, 255, 0);
//cv::drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, cv::Point() );
}
// Show in a window
cv::namedWindow("Contours", CV_WINDOW_AUTOSIZE);
cv::imshow("Contours", drawing);
}
double distance(cv::Point one, cv::Point two)
{
return std::sqrt(std::pow(one.x - two.x, 2) + std::pow(one.y - two.y, 2));
}
void calculateDistance (cv::Mat& image, cv::RotatedRect& boundedRect)
{
double focalLen = 673.20;
// 20 inches real width
double wReal = 20;
double wPixel = 0;
double d = 204;
cv::Point2f vert[4];
boundedRect.points(vert);
cv::line(image, vert[0], vert[3], cv::Scalar (255, 0, 0));
wPixel = distance(vert[0], vert[3]);
// focalLen = (wPixel * d) / wReal;
d = (wReal * focalLen) / wPixel;
char str[50];
sprintf(str, "Line Length = %4.2f", wPixel);
cv::putText(image, str, cv::Point(10, 420), CV_FONT_HERSHEY_COMPLEX_SMALL, 0.75, cv::Scalar(255, 0, 0), 1, 8, false);
sprintf(str, "Focal Length = %4.2f", focalLen);
cv::putText(image, str, cv::Point(10, 440), CV_FONT_HERSHEY_COMPLEX_SMALL, 0.75, cv::Scalar(255, 0, 0), 1, 8, false);
sprintf(str, "Distance = %4.2f", d);
cv::putText(image, str, cv::Point(10, 460), CV_FONT_HERSHEY_COMPLEX_SMALL, 0.75, cv::Scalar(255, 0, 0), 1, 8, false);
}
int main( int argc, char *argv[])
{
// Parameters for selecting which filters to apply
int blur = 0;
int color = 0;
int dilate_erode = 0;
int edge = 0;
int laplacian = 0;
int hough = 0;
int depth_dist = 0;
int merge = 0;
// Parameters for applying filters even if windows are closed
int apply_blur = 1;
int apply_color = 1;
int apply_dilate_erode = 0;
int apply_edge = 1;
int apply_laplacian = 0;
int apply_hough = 0;
int apply_depth_dist = 0;
int apply_merge = 1;
// gaussianBlur parameters
int blur_ksize = 7;
int sigmaX = 10;
int sigmaY = 10;
// hsvColorThreshold parameters
int hMin = 130;
int hMax = 190;
int sMin = 10;
int sMax = 30;
int vMin = 85;
int vMax = 100;
int debugMode = 0; // 0 is none, 1 is debug mode
int bitAnd = 1; // 0 is none, 1 is bitAnd between h, s, and v
// dilateErode parameters
int holes = 0;
int noise = 0;
int size = 1;
cv::Mat element = cv::getStructuringElement(cv::MORPH_CROSS,
cv::Size(2 * size + 1, 2 * size + 1),
cv::Point(size, size) );
// cannyEdgeDetect parameters
int threshLow = 100;
int threshHigh = 300;
// laplacianSharpen parameters
int laplacian_ksize = 3;
int scale = 1; // optional scale value added to image
int delta = 0; // optional delta value added to image
int ddepth = CV_16S;
// houghLines parameters
int rho = 1;
int theta = 180;
int threshold = 50;
int lineMin = 50;
int maxGap = 10;
// mergeFinal parameters
int weight1 = 100; // decide weighted sums of original rgb feed to filtered rgb feed; values = out of 100
int weight2 = 100;
std::cout << "\n";
std::cout << " =========== FILTER LIST =========== " << "\n";
std::cout << "| |" << "\n";
std::cout << "| (0) No Filter |" << "\n";
std::cout << "| (1) Gaussian Blur Filter |" << "\n";
std::cout << "| (2) HSV Color Filter |" << "\n";
std::cout << "| (3) Dilate and Erode Filter |" << "\n";
std::cout << "| (4) Canny Edge Detection Filter |" << "\n";
std::cout << "| (5) Laplacian Sharpen Filter |" << "\n";
std::cout << "| (6) Hough Lines Filter |" << "\n";
std::cout << "| (7) Merge Final Outputs |" << "\n";
std::cout << "| |" << "\n";
std::cout << " =================================== " << "\n";
std::cout << "\n";
std::cout << "\n";
std::cout << " ============== NOTICE ============= " << "\n";
std::cout << "| |" << "\n";
std::cout << "| Press 'q' to quit without saving |" << "\n";
std::cout << "| Press ' ' to pause |" << "\n";
std::cout << "| |" << "\n";
std::cout << " =================================== " << "\n";
std::cout << "\n";
cv::VideoCapture camera(1);
if( !camera.isOpened() )
{
std::cout << "Error - Unable to open Camera at Port 0" << std::endl;
return -1;
}
// Matrices for holding image data
cv::Mat rgb, rgb_orig;
cv::Mat image;
char kill = ' '; // Press q to quit the program
int thresh = 120;
while ((kill != 'q') && (kill != 's'))
{
if (kill == ' ') // Press space to pause program, then any key to resume
{
cv::waitKey(0);
}
selectMode(blur, color, dilate_erode, edge, laplacian, hough, depth_dist, merge);
if (argc > 2) // Use images
{
rgb = cv::imread(argv[1]);
rgb_orig = rgb.clone(); // Clone rgb input in order to merge at end
if (!rgb.data || !rgb_orig.data) // No data
{
std::cout << "No image data" << std::endl;
return -1;
}
}
else
{
camera >> rgb;
rgb_orig = rgb.clone();
}
cv::imshow("BGR Feed", rgb);
rgb.copyTo(image);
cv::namedWindow("Source", CV_WINDOW_AUTOSIZE);
cv::createTrackbar("Threshold:", "Source", &thresh, 255);
// Filters are only applied if last parameter is true, otherwise their windows are destroyed
gaussianBlurWindows(image, blur_ksize, sigmaX, sigmaY, apply_blur, blur);
hsvColorThresholdWindows(image, hMin, hMax, sMin, sMax, vMin, vMax, debugMode, bitAnd, apply_color, color);
dilateErodeWindows(image, element, holes, noise, apply_dilate_erode, dilate_erode);
drawBoundedRects(image, thresh);
cannyEdgeDetectWindows(image, threshLow, threshHigh, apply_edge, edge);
laplacianSharpenWindows(image, ddepth, laplacian_ksize, scale, delta, apply_laplacian, laplacian);
#if 0
// List sizes of image
cv::Size imageSize = image.size();
std::cout << "Image: [" << imageSize.height << " x " << imageSize.width << "]" << "\n";
#endif
houghLinesWindows(image, rho, theta, threshold, lineMin, maxGap, apply_hough, hough);
#if 0
// List sizes of image
imageSize = image.size();
std::cout << "Image: [" << imageSize.height << " x " << imageSize.width << "]" << "\n";
#endif
mergeFinalWindows(rgb_orig, image, weight1, weight2, apply_merge, merge);
kill = cv::waitKey(5);
}
return 0;
}
<|endoftext|>
|
<commit_before>79638342-2d53-11e5-baeb-247703a38240<commit_msg>79640222-2d53-11e5-baeb-247703a38240<commit_after>79640222-2d53-11e5-baeb-247703a38240<|endoftext|>
|
<commit_before>00350b22-585b-11e5-93ac-6c40088e03e4<commit_msg>003c8e4a-585b-11e5-9209-6c40088e03e4<commit_after>003c8e4a-585b-11e5-9209-6c40088e03e4<|endoftext|>
|
<commit_before>d4c6286b-327f-11e5-ba74-9cf387a8033e<commit_msg>d4d053fa-327f-11e5-9429-9cf387a8033e<commit_after>d4d053fa-327f-11e5-9429-9cf387a8033e<|endoftext|>
|
<commit_before>8d6dfdb6-2d14-11e5-af21-0401358ea401<commit_msg>8d6dfdb7-2d14-11e5-af21-0401358ea401<commit_after>8d6dfdb7-2d14-11e5-af21-0401358ea401<|endoftext|>
|
<commit_before>b3891490-35ca-11e5-88b5-6c40088e03e4<commit_msg>b38fd336-35ca-11e5-a6db-6c40088e03e4<commit_after>b38fd336-35ca-11e5-a6db-6c40088e03e4<|endoftext|>
|
<commit_before>#include <QGuiApplication>
#include <QQuickView>
#include <QQmlContext>
#include <QQmlApplicationEngine>
#include <QObject>
#include "log.h"
#include "windowcontroller.h"
int main(int argc, char *argv[])
{
auto v1=QString(LVIEW_VERSION);
auto v2=QString(GIT_VERSION);
auto lview_version=v1+"-"+v2;
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
// auto ctx=engine.rootContext();
// ctx->setContextProperty("logfile", QVariant::fromValue(ll));
engine.load(QUrl(QLatin1String("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
auto ctx=engine.rootContext();
ctx->setContextProperty("lview_version", QVariant::fromValue(lview_version));
engine.load(QUrl(QLatin1String("qrc:/main.qml")));
QObject* rootObject=engine.rootObjects().first();
qDebug()<<"rootObject:"<<rootObject->objectName();
WindowController *wc=new WindowController(rootObject);
QObject::connect(rootObject, SIGNAL(updateAllSignal(QString)),
wc, SLOT(updateAllSlot(QString)));
QObject::connect(rootObject, SIGNAL(openFileSignal(QString)),
wc, SLOT(openFileSlot(QString)));
QObject::connect(rootObject, SIGNAL(closeFileSignal(QString)),
wc, SLOT(closeFileSlot(QString)));
QObject::connect(rootObject, SIGNAL(addHighlightedTextSignal(QString)),
wc, SLOT(addHighlightedTextSlot(QString)));
QObject::connect(rootObject, SIGNAL(clearHighlightedTextSignal()),
wc, SLOT(clearHighlightedTextSlot()));
return app.exec();
}
<commit_msg>!twice<commit_after>#include <QGuiApplication>
#include <QQuickView>
#include <QQmlContext>
#include <QQmlApplicationEngine>
#include <QObject>
#include "log.h"
#include "windowcontroller.h"
int main(int argc, char *argv[])
{
auto v1=QString(LVIEW_VERSION);
auto v2=QString(GIT_VERSION);
auto lview_version=v1+"-"+v2;
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
// auto ctx=engine.rootContext();
// ctx->setContextProperty("logfile", QVariant::fromValue(ll));
engine.load(QUrl(QLatin1String("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
auto ctx=engine.rootContext();
ctx->setContextProperty("lview_version", QVariant::fromValue(lview_version));
QObject* rootObject=engine.rootObjects().first();
qDebug()<<"rootObject:"<<rootObject->objectName();
WindowController *wc=new WindowController(rootObject);
QObject::connect(rootObject, SIGNAL(updateAllSignal(QString)),
wc, SLOT(updateAllSlot(QString)));
QObject::connect(rootObject, SIGNAL(openFileSignal(QString)),
wc, SLOT(openFileSlot(QString)));
QObject::connect(rootObject, SIGNAL(closeFileSignal(QString)),
wc, SLOT(closeFileSlot(QString)));
QObject::connect(rootObject, SIGNAL(addHighlightedTextSignal(QString)),
wc, SLOT(addHighlightedTextSlot(QString)));
QObject::connect(rootObject, SIGNAL(clearHighlightedTextSignal()),
wc, SLOT(clearHighlightedTextSlot()));
return app.exec();
}
<|endoftext|>
|
<commit_before>5d286642-2d16-11e5-af21-0401358ea401<commit_msg>5d286643-2d16-11e5-af21-0401358ea401<commit_after>5d286643-2d16-11e5-af21-0401358ea401<|endoftext|>
|
<commit_before>0c276c1e-585b-11e5-acd1-6c40088e03e4<commit_msg>0c2ecd88-585b-11e5-b514-6c40088e03e4<commit_after>0c2ecd88-585b-11e5-b514-6c40088e03e4<|endoftext|>
|
<commit_before>8431fc37-2d15-11e5-af21-0401358ea401<commit_msg>8431fc38-2d15-11e5-af21-0401358ea401<commit_after>8431fc38-2d15-11e5-af21-0401358ea401<|endoftext|>
|
<commit_before>ee7db75c-327f-11e5-9254-9cf387a8033e<commit_msg>ee83b9e8-327f-11e5-8456-9cf387a8033e<commit_after>ee83b9e8-327f-11e5-8456-9cf387a8033e<|endoftext|>
|
<commit_before>60056580-2e4f-11e5-82c9-28cfe91dbc4b<commit_msg>600c0611-2e4f-11e5-bf59-28cfe91dbc4b<commit_after>600c0611-2e4f-11e5-bf59-28cfe91dbc4b<|endoftext|>
|
<commit_before>c1c341a8-327f-11e5-ad4c-9cf387a8033e<commit_msg>c1c97bf5-327f-11e5-b1dc-9cf387a8033e<commit_after>c1c97bf5-327f-11e5-b1dc-9cf387a8033e<|endoftext|>
|
<commit_before>1f4b08f3-2748-11e6-ac3d-e0f84713e7b8<commit_msg>Finished?<commit_after>1f5c3885-2748-11e6-b5b1-e0f84713e7b8<|endoftext|>
|
<commit_before>c5eb3c0f-2e4e-11e5-b233-28cfe91dbc4b<commit_msg>c5f0b65c-2e4e-11e5-8dc4-28cfe91dbc4b<commit_after>c5f0b65c-2e4e-11e5-8dc4-28cfe91dbc4b<|endoftext|>
|
<commit_before>#include <iostream>
#include "ncurses.h"
using namespace std;
int main()
{
initscr();
printw("HI PEOPLE");
refresh();
getch();
endwin();
return 0;
}
<commit_msg>Changed a few things<commit_after>#include "ncurses.h"
int main()
{
initscr();
printw("HI PEOPLE"); //HI CODERS
refresh();
getch();
endwin();
return 0;
}
<|endoftext|>
|
<commit_before>#include "board.h"
#include "player.h"
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
void gameLoop(Board ¤t_game, Player &player1, Player &player2){
int winner = 0;
int move;
while((winner = current_game.win()) == 0){
if(player1.piece == "X"){
current_game.print();
current_game.getMoves();
cout << endl << "Player 1: Select move#: ";
cin >> move;
if (current_game.validateMove(move)){
current_game.insertMove(player1.team, move);
}
if((winner = current_game.win()) != 0)
break;
if(player2.ishuman){
current_game.print();
current_game.getMoves();
cout << endl << "Player 2: Select move#: ";
cin >> move;
if (current_game.validateMove(move)){
current_game.insertMove(player2.team, move);
}
}else{
//call ai move
}
}else{
if(player2.ishuman){
current_game.print();
current_game.getMoves();
cout << endl << "Player 2: Select move#: ";
cin >> move;
if (current_game.validateMove(move)){
current_game.insertMove(player2.team, move);
}
}else{
//call ai move
}
if((winner = current_game.win()) != 0)
break;
current_game.print();
current_game.getMoves();
cout << endl << "Player 1: Select move#: ";
cin >> move;
if (current_game.validateMove(move)){
current_game.insertMove(player1.team, move);
}
}
}
current_game.print();
cout << endl << winner << " won.";
}
string oppositePiece(string piece){
if(piece == "X"){
return "O";
}
return "X";
}
int main(){
int board_size = 3;
int humans = 1;
string player = "X";
cout << "Pick the size of the grid (default = 3): ";
cin >> board_size;
Board board(board_size); //initialize a new board
board.print();
cout << endl << "1 or 2 human players? ";
cin >> humans;
if(humans == 1){
cout << endl << "X or O (X moves first): ";
cin >> player;
player = toupper(player[0]);
Player human(player); //initializes human player to their piece
cout << "You are " << human.convertToPiece();
AI ai(oppositePiece(human.piece)); //initializes ai player to opposite piece
cout << endl << "AI is " << ai.piece;
gameLoop(board, human, ai); //game logic within the game is done here
}else if(humans == 2){
cout << endl << "Player 1: X or O (X moves first): ";
cin >> player;
player = toupper(player[0]);
Player human1(player); //initializes human player to their piece
Player human2(oppositePiece(human1.piece)); //initializes player 2 to opposite piece
cout << endl << "Player 1 is: " << human1.piece;
cout << endl << "Player 2 is: " << human2.piece;
gameLoop(board, human1, human2); //game logic within the game is done here
}
return 0;
}<commit_msg>Added player win output<commit_after>#include "board.h"
#include "player.h"
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
void gameLoop(Board ¤t_game, Player &player1, Player &player2){
int winner = 0;
int move;
while((winner = current_game.win()) == 0){
if(player1.piece == "X"){
current_game.print();
current_game.getMoves();
cout << endl << "Player 1: Select move#: ";
cin >> move;
if (current_game.validateMove(move)){
current_game.insertMove(player1.team, move);
}
if((winner = current_game.win()) != 0)
break;
if(player2.ishuman){
current_game.print();
current_game.getMoves();
cout << endl << "Player 2: Select move#: ";
cin >> move;
if (current_game.validateMove(move)){
current_game.insertMove(player2.team, move);
}
}else{
//call ai move
}
}else{
if(player2.ishuman){
current_game.print();
current_game.getMoves();
cout << endl << "Player 2: Select move#: ";
cin >> move;
if (current_game.validateMove(move)){
current_game.insertMove(player2.team, move);
}
}else{
//call ai move
}
if((winner = current_game.win()) != 0)
break;
current_game.print();
current_game.getMoves();
cout << endl << "Player 1: Select move#: ";
cin >> move;
if (current_game.validateMove(move)){
current_game.insertMove(player1.team, move);
}
}
}
current_game.print();
if(player1.team == winner){
cout << endl << "Player 1 won.";
}else{
cout << endl << "Player 2 won.";
}
}
string oppositePiece(string piece){
if(piece == "X"){
return "O";
}
return "X";
}
int main(){
int board_size = 3;
int humans = 1;
string player = "X";
cout << "Pick the size of the grid (default = 3): ";
cin >> board_size;
Board board(board_size); //initialize a new board
board.print();
cout << endl << "1 or 2 human players? ";
cin >> humans;
if(humans == 1){
cout << endl << "X or O (X moves first): ";
cin >> player;
player = toupper(player[0]);
Player human(player); //initializes human player to their piece
cout << "You are " << human.convertToPiece();
AI ai(oppositePiece(human.piece)); //initializes ai player to opposite piece
cout << endl << "AI is " << ai.piece;
gameLoop(board, human, ai); //game logic within the game is done here
}else if(humans == 2){
cout << endl << "Player 1: X or O (X moves first): ";
cin >> player;
player = toupper(player[0]);
Player human1(player); //initializes human player to their piece
Player human2(oppositePiece(human1.piece)); //initializes player 2 to opposite piece
cout << endl << "Player 1 is: " << human1.piece;
cout << endl << "Player 2 is: " << human2.piece;
gameLoop(board, human1, human2); //game logic within the game is done here
}
return 0;
}<|endoftext|>
|
<commit_before>4ad9952e-2e3a-11e5-9cdd-c03896053bdd<commit_msg>4ae8b324-2e3a-11e5-9aee-c03896053bdd<commit_after>4ae8b324-2e3a-11e5-9aee-c03896053bdd<|endoftext|>
|
<commit_before>cf62c68a-327f-11e5-8965-9cf387a8033e<commit_msg>cf68e0c5-327f-11e5-8ec9-9cf387a8033e<commit_after>cf68e0c5-327f-11e5-8ec9-9cf387a8033e<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include <map>
#include <eXosip2/eXosip.h>
using namespace std;
int main(int argc, char const *argv[])
{
struct eXosip_t *context_eXosip;
cout<<"Hello Stream Server"<<endl;
int ret = eXosip_init(context_eXosip);
if(ret!=0)
{
cout<<"inti eXosip error"<<endl;
}
return 0;
}
<commit_msg>test clock_gettime<commit_after>#include <iostream>
#include <string>
#include <map>
#include <eXosip2/eXosip.h>
#include <time.h>
using namespace std;
int main(int argc, char const *argv[])
{
struct eXosip_t *context_eXosip;
cout<<"Hello Stream Server"<<endl;
int ret = eXosip_init(context_eXosip);
if(ret!=0)
{
cout<<"inti eXosip error"<<endl;
}
timespec time1;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID,&time1);
return 0;
}
<|endoftext|>
|
<commit_before>758b40d4-2d53-11e5-baeb-247703a38240<commit_msg>758bc3e2-2d53-11e5-baeb-247703a38240<commit_after>758bc3e2-2d53-11e5-baeb-247703a38240<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.