text
stringlengths
8
6.88M
#ifndef SHOC_HASH_SHA1_H #define SHOC_HASH_SHA1_H #include "shoc/util.h" namespace shoc { struct Sha1 : Eater<Sha1> { static constexpr size_t SIZE = 20; static constexpr size_t STATE_SIZE = 5; // In words static constexpr size_t BLOCK_SIZE = 64; // In bytes public: void init(); void feed(const void *in, size_t len); void stop(byte *out); private: void pad(); void step(); private: using word = uint32_t; private: word length_low; word length_high; word state[STATE_SIZE]; byte block[BLOCK_SIZE]; byte block_idx; }; inline void Sha1::init() { state[0] = 0x67452301u; state[1] = 0xefcdab89u; state[2] = 0x98badcfeu; state[3] = 0x10325476u; state[4] = 0xc3d2e1f0u; block_idx = length_high = length_low = 0; } inline void Sha1::feed(const void *in, size_t len) { assert(in || !len); auto p = static_cast<const byte*>(in); while (len--) { block[block_idx++] = *p++; if ((length_low += 8) == 0) length_high += 1; if (block_idx == BLOCK_SIZE) step(); } } inline void Sha1::stop(byte *out) { assert(out); pad(); for (size_t i = 0, j = 0; i < STATE_SIZE; ++i, j += 4) { out[j + 0] = state[i] >> 24; out[j + 1] = state[i] >> 16; out[j + 2] = state[i] >> 8; out[j + 3] = state[i] >> 0; } zero(this, sizeof(*this)); } inline void Sha1::pad() { static constexpr size_t pad_start = BLOCK_SIZE - 8; block[block_idx++] = 0x80; if (block_idx > pad_start) { fill(block + block_idx, 0, BLOCK_SIZE - block_idx); step(); } fill(block + block_idx, 0, pad_start - block_idx); for (size_t i = 0, j = 0; i < 4; ++i, j += 8) { block[BLOCK_SIZE - 1 - i] = length_low >> j; block[BLOCK_SIZE - 5 - i] = length_high >> j; } step(); } inline void Sha1::step() { enum { a, b, c, d, e }; word w[80]; word var[STATE_SIZE]; copy(var, state, sizeof(state)); for (size_t t = 0; t < 16; ++t) { w[t] = block[t * 4] << 24; w[t] |= block[t * 4 + 1] << 16; w[t] |= block[t * 4 + 2] << 8; w[t] |= block[t * 4 + 3]; } for (size_t t = 16; t < 80; ++t) w[t] = rol(w[t-3] ^ w[t-8] ^ w[t-14] ^ w[t-16], 1); #define SHA_1_ROUND(start, end, K, ...) \ for (size_t t = start; t < end; ++t) { \ word tmp = rol(var[a], 5) + var[e] + w[t] + K + (__VA_ARGS__); \ var[e] = var[d]; \ var[d] = var[c]; \ var[c] = rol(var[b], 30); \ var[b] = var[a]; \ var[a] = tmp; \ } SHA_1_ROUND(0, 20, 0x5a827999, ch(var[b], var[c], var[d])) SHA_1_ROUND(20, 40, 0x6ed9eba1, parity(var[b], var[c], var[d])) SHA_1_ROUND(40, 60, 0x8f1bbcdc, maj(var[b], var[c], var[d])) SHA_1_ROUND(60, 80, 0xca62c1d6, parity(var[b], var[c], var[d])) #undef SHA_1_ROUND for (size_t i = 0; i < STATE_SIZE; ++i) state[i] += var[i]; block_idx = 0; } } #endif
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <sstream> #include "ros/ros.h" #include "sensor_msgs/NavSatFix.h" //gps conversion tools #include "./gps_conv.h" void convert_and_pub(char *data,ros::Publisher &publisher){ sensor_msgs::NavSatFix msgNav; msgNav.header.stamp = ros::Time::now(); msgNav.header.frame_id="/ardrone/gps_antenna"; degreesMinutesToDegrees(81.1); GeoPoint position = analyseGpsGga(data); //msgNav.status ? // Latitude [degrees]. Positive is north of equator; negative is south. msgNav.latitude = position.latitude; // Longitude [degrees]. Positive is east of prime meridian; negative is west. msgNav.longitude = position.longitude; // Altitude [m]. Positive is above the WGS 84 ellipsoid // (quiet NaN if no altitude is available). //msgNav.altitude; // Position covariance [m^2] defined relative to a tangential plane // through the reported position. The components are East, North, and // Up (ENU), in row-major order. // // Beware: this coordinate system exhibits singularities at the poles. //msgNav.position_covariance; // If the covariance of the fix is known, fill it in completely. If the // GPS receiver provides the variance of each measurement, put them // along the diagonal. If only Dilution of Precision is available, // estimate an approximate covariance from that. msgNav.position_covariance_type=msgNav.COVARIANCE_TYPE_UNKNOWN; publisher.publish(msgNav); return; } int main(int argc, char *argv[]) { int sockfd, portno, n=0; struct sockaddr_in serv_addr; struct hostent *server; ros::init(argc,argv,"gps_remote_driver"); ros::NodeHandle nh; ros::Publisher navdataPub= nh.advertise<sensor_msgs::NavSatFix>("gps",10); char buffer[256]; char buffer2[256*4]; if (argc < 3) { ROS_ERROR("usage %s hostname port\n", argv[0]); exit(0); } portno = atoi(argv[2]); sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) ROS_ERROR("ERROR opening socket"); server = gethostbyname(argv[1]); if (server == NULL) { ROS_ERROR("ERROR, no such host\n"); exit(0); } bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length); serv_addr.sin_port = htons(portno); if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) ROS_ERROR("ERROR connecting"); //printf("Please enter the message: "); //bzero(buffer,256); //fgets(buffer,255,stdin); //n = write(sockfd,buffer,strlen(buffer)); int i=0,i2=0; while(ros::ok()){ bzero(buffer,256); n = read(sockfd,buffer,255); if (n < 0) { ROS_ERROR("ERROR reading from socket"); break; }else if(n==0){ ROS_WARN("nothing received"); } i=0; ROS_INFO("\t\treceived %s",buffer); while((buffer[i]!='\0') && (i<static_cast<int>(sizeof(buffer)))){ //put char in buffer2 buffer2[i2]=buffer[i]; if((buffer2[i2]=='\n') || (i2>=static_cast<int>(sizeof(buffer2))-1)){ //we received an entire NMEA frame, go converting it buffer[i2+1]='\0'; ROS_INFO(buffer2); if ( std::string(buffer2).find("$GPGGA") == 0){ convert_and_pub(buffer2,navdataPub); } bzero(buffer2,256*4); i2=-1; } i++; i2++; } } close(sockfd); return 0; }
class Solution { public: bool isPerfectSquare(int num) { long left = 0; long right = num; while(left <= right){ long mid = left + (right-left)/2; long cur = mid*mid; if(cur == num){ return true; }else if(cur > num){ right = mid - 1; }else{ left = mid + 1; } } return false; } };
#ifndef BUTTON_H #define BUTTON_H #include <QPushButton> class Button : public QPushButton { Q_OBJECT public: Button(qint8 keyId, QPushButton *parent = nullptr); ~Button(); qint8 getKeyId() const; public slots: void slotEventPressed(); signals: void signalEventPressed(); private: qint8 m_keyId; }; #endif // BUTTON_H
#include "Snake.h" const int BODY_SIZE = 32; using namespace sf; Snake::Snake() { RectangleShape head; head.setFillColor(Color::Green); head.setOutlineThickness(-4.f); head.setOutlineColor(Color::Blue); head.setSize(Vector2f(BODY_SIZE, BODY_SIZE)); head.setPosition(640 / 2 - BODY_SIZE / 2, 480 / 2 - BODY_SIZE / 2); m_snakeParts.push_back(head); m_direction = DIR_UP; } Snake::~Snake() { } void Snake::Move() { Vector2f dir(0.f, 0.f); switch (m_direction) { case DIR_LEFT: dir.x = -1; break; case DIR_RIGHT: dir.x = 1; break; case DIR_UP: dir.y = -1; break; case DIR_DOWN: dir.y = 1; break; default: exit(-1); break; } Vector2f prevPos = m_snakeParts[0].getPosition(); Vector2f offset(dir.x * BODY_SIZE, dir.y * BODY_SIZE); m_snakeParts[0].move(offset); for (int i = 1;i < m_snakeParts.size(); i++) { Vector2f tmp = m_snakeParts[i].getPosition(); m_snakeParts[i].setPosition(prevPos); prevPos = tmp; } } void Snake::ChangeDirection(Direction dir) { if (std::abs(dir - m_direction) > 1) { m_direction = dir; } } void Snake::AddBodyPart() { RectangleShape bodyPart(Vector2f(BODY_SIZE, BODY_SIZE)); bodyPart.setFillColor(Color::Transparent); bodyPart.setOutlineThickness(-4.f); bodyPart.setOutlineColor(Color(123,321,132)); bodyPart.setSize(Vector2f(BODY_SIZE, BODY_SIZE)); bodyPart.setPosition(-100,-100); m_snakeParts.push_back(bodyPart); } bool Snake::IsSelfBitting() { FloatRect *head = &m_snakeParts[0].getGlobalBounds(); FloatRect *body; for (int i = 1;i < m_snakeParts.size();i++) { body = &m_snakeParts[i].getGlobalBounds(); if (head->intersects(*body)) // CollsionChecker::IsCollsion(head, body) { return true; } } return false; } FloatRect& Snake::GetHeadFloatRect() const { return m_snakeParts[0].getGlobalBounds(); } void Snake::draw(RenderTarget & target, RenderStates states) const { for (int i = 0;i < m_snakeParts.size(); i++) { target.draw(m_snakeParts[i]); } }
/* =========================================================================== Copyright (C) 2017 waYne (CAM) =========================================================================== */ #pragma once #ifndef ELYSIUM_GRAPHICS_GRAPHICSINSTANCE #define ELYSIUM_GRAPHICS_GRAPHICSINSTANCE #endif #ifndef ELYSIUM_CORE_OBJECT #include "../../../Core/01-Shared/Elysium.Core/Object.hpp" #endif #ifndef ELYSIUM_GRAPHICS_RENDERING_IWRAPPEDGRAPHICSINSTANCE #include "IWrappedGraphicsInstance.hpp" #endif #ifndef ELYSIUM_GRAPHICS_GRAPHICSDEVICE #include "GraphicsDevice.hpp" #endif using namespace Elysium::Core; using namespace Elysium::Graphics::Rendering; namespace Elysium { namespace Graphics { class EXPORT GraphicsInstance : public Object { friend class Game; public: // constructors & destructor GraphicsInstance(IWrappedGraphicsInstance* WrappedGraphicsInstance); ~GraphicsInstance(); // properties List<GraphicsDevice*>* GetGraphicsDevices(); private: // fields IWrappedGraphicsInstance* _WrappedGraphicsInstance = nullptr; List<GraphicsDevice*> _GraphicsDevices; }; } }
/* ***** BEGIN LICENSE BLOCK ***** * FW4SPL - Copyright (C) IRCAD, 2012-2013. * Distributed under the terms of the GNU Lesser General Public License (LGPL) as * published by the Free Software Foundation. * ****** END LICENSE BLOCK ****** */ // gdcmIO #include "gdcmIO/writer/DicomSRWriterManager.hpp" #include "gdcmIO/writer/DicomSRWriter.hpp" namespace gdcmIO { namespace writer { //------------------------------------------------------------------------------ DicomSRWriterManager::DicomSRWriterManager() { SLM_TRACE_FUNC(); } //------------------------------------------------------------------------------ DicomSRWriterManager::~DicomSRWriterManager() { SLM_TRACE_FUNC(); } //------------------------------------------------------------------------------ void DicomSRWriterManager::write(::gdcm::DataSet & a_gDs, const ::boost::filesystem::path & a_path) { ::fwData::Image::sptr image = this->getConcreteObject(); SLM_ASSERT("fwData::Image not instanced", image); SLM_ASSERT("gdcmIO::DicomInstance not set",this->getDicomInstance().get()) //***** Handle SR document *****// DicomSRWriter docSRWriter; docSRWriter.setObject( image ); docSRWriter.setFile( a_path.string() + "/docSR" ); //***** Set instance and the referenced instances *****// docSRWriter.setDicomInstance( this->getDicomInstance() ); docSRWriter.setDataSet(a_gDs); docSRWriter.write(); } } // namespace writer } // namespace gdcmIO
#include <iostream> using namespace std; int main() { double tank_volume = 300 * 200 * 100; int max_cups = 0; double cup_volume = 0, cup_radius = 0, cup_height = 0; cout << "Please enter the cup radius in cm" << endl; cin >> cup_radius; cout << "Please enter the cup height in cm" << endl; cin >> cup_height; cup_volume = (22 / 7) * cup_height * cup_radius * cup_radius; max_cups = tank_volume / cup_volume; cout << "Max cups = " << max_cups << endl; return 0; }
#include"Treasure.h" Treasure::Treasure(int x, int y, char display, std::string type, int numGold) : Item(x, y, display, type) { this->numGold = numGold; } int Treasure::getNumGold() { return this->numGold; } GoldPile::GoldPile(int x, int y) : Treasure(x, y, '$', "GoldPile", 10) { } DragonHoard::DragonHoard(int x, int y) : Treasure(x, y, '$', "DragonHoard", 50) { this->canBePickedUp = false; } bool DragonHoard::getCanBePickedUp() { return this->canBePickedUp; } void DragonHoard::setCanBePickedUp(bool canBePickedUp) { this->canBePickedUp = canBePickedUp; }
/******************************************************************************* The MIT License (MIT) Copyright (c) 2015 Dmitry "Dima" Korolev <dmitry.korolev@gmail.com> 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 "optionally_owned.h" #include <string> #include <thread> #include <atomic> #include "../../Bricks/3party/gtest/gtest-main.h" using std::string; using std::thread; using std::this_thread::sleep_for; using std::chrono::milliseconds; using std::atomic_bool; using sherlock::OptionallyOwned; struct Foo { string& s_; Foo(string& s) : s_(s) { s_ += "+"; } ~Foo() { s_ += "-"; } Foo(Foo&&) = default; void Use() { s_ += "U"; } }; TEST(OptionallyOwned, DoesNotOwnByReference) { string s; ASSERT_EQ("", s); { Foo bar(s); ASSERT_EQ("+", s); { OptionallyOwned<Foo> owner(bar); ASSERT_TRUE(owner.IsValid()); ASSERT_FALSE(owner.IsDetachable()); ASSERT_EQ("+", owner->s_); } ASSERT_EQ("+", s); // The destructor of `bar` will only be called when its gets out of scope. } ASSERT_EQ("+-", s); } TEST(OptionallyOwned, DoesOwnByUniquePointer) { string s; ASSERT_EQ("", s); { std::unique_ptr<Foo> baz(new Foo(s)); ASSERT_EQ("+", s); { OptionallyOwned<Foo> owner(std::move(baz)); ASSERT_TRUE(owner.IsValid()); ASSERT_TRUE(owner.IsDetachable()); ASSERT_EQ("+", owner->s_); } ASSERT_EQ("+-", s); // Since `owner` owned `baz`, it has been destructed as `owner` left the scope. } ASSERT_EQ("+-", s); } TEST(OptionallyOwned, ByUniquePointerOwnershipTransfers) { string s; ASSERT_EQ("", s); { std::unique_ptr<Foo> meh(new Foo(s)); ASSERT_EQ("+", s); { OptionallyOwned<Foo> owner(std::move(meh)); ASSERT_TRUE(owner.IsValid()); ASSERT_TRUE(owner.IsDetachable()); ASSERT_EQ("+", owner->s_); { OptionallyOwned<Foo> new_owner(std::move(owner)); ASSERT_TRUE(new_owner.IsValid()); ASSERT_EQ("+", new_owner->s_); ASSERT_FALSE(owner.IsValid()); string tmp; ASSERT_THROW(tmp = owner->s_, std::logic_error); } // Since `owner` has transferred ownership of `meh` to `new_owner`, which went out of scope, // `meh` has been destroyed as the scope ending on the previous line has exited. ASSERT_EQ("+-", s); } ASSERT_EQ("+-", s); // Since `owner` owned `meh`, it has been destructed as `owner` left the scope. } ASSERT_EQ("+-", s); } inline void UseFoo(OptionallyOwned<Foo> foo) { foo->Use(); } TEST(OptionallyOwned, ByUniquePointerOwnershipCanBePassedOnToAnotherFunction) { string s; ASSERT_EQ("", s); { std::unique_ptr<Foo> woo(new Foo(s)); ASSERT_EQ("+", s); { OptionallyOwned<Foo> owner(std::move(woo)); ASSERT_TRUE(owner.IsValid()); ASSERT_TRUE(owner.IsDetachable()); ASSERT_EQ("+", owner->s_); UseFoo(std::move(owner)); ASSERT_FALSE(owner.IsValid()); string tmp; ASSERT_THROW(tmp = owner->s_, std::logic_error); ASSERT_EQ("+U-", s); } ASSERT_EQ("+U-", s); } ASSERT_EQ("+U-", s); } TEST(OptionallyOwned, ByUniquePointerOwnershipCanBePassedOnToAnotherThread) { string s; ASSERT_EQ("", s); atomic_bool kill(false); atomic_bool done(false); std::unique_ptr<Foo> whoa(new Foo(s)); ASSERT_EQ("+", s); { OptionallyOwned<Foo> owner(std::move(whoa)); ASSERT_TRUE(owner.IsValid()); ASSERT_TRUE(owner.IsDetachable()); thread([&kill, &done](OptionallyOwned<Foo> inner_owned) { sleep_for(milliseconds(1)); while (!kill) { ; // Spin lock; } sleep_for(milliseconds(1)); { OptionallyOwned<Foo> inner_owned_and_let_go(std::move(inner_owned)); } sleep_for(milliseconds(1)); done = true; }, std::move(owner)).detach(); ASSERT_FALSE(owner.IsValid()); string tmp; ASSERT_THROW(tmp = owner->s_, std::logic_error); ASSERT_EQ("+", s); } sleep_for(milliseconds(1)); ASSERT_EQ("+", s); // An instance of `whoa` should still be alive in the thread. kill = true; while (!done) { ; // Spin lock; } ASSERT_EQ("+-", s); // An instance of `whoa` is now gone since the thread has released it. }
/*! * @file GeneratorElfX86.hpp * @brief x86 ELF binary generator * @author koturn */ #ifndef GENERATOR_ELF_X86_HPP #define GENERATOR_ELF_X86_HPP #include <iostream> #include "BinaryGenerator.hpp" #include "util/elfsubset.h" /*! * @brief x86 ELF binary generator */ class GeneratorElfX86 : public BinaryGenerator<GeneratorElfX86> { private: friend class CodeGenerator<GeneratorElfX86>; //! Address of .text section static const Elf32_Addr kBaseAddr = 0x04048000; //! Address of .bss section static const Elf32_Addr kBssAddr = 0x04248000; //! Number of program headers static const Elf32_Half kNProgramHeaders = 2; //! Number of section headers static const Elf32_Half kNSectionHeaders = 4; //! Program header size static const Elf32_Off kHeaderSize = static_cast<Elf32_Off>(sizeof(Elf32_Ehdr) + sizeof(Elf32_Phdr) * kNProgramHeaders); //! Program footer size static const Elf32_Off kFooterSize = static_cast<Elf32_Off>(sizeof(Elf32_Shdr) * kNSectionHeaders); public: explicit GeneratorElfX86(std::ostream& oStream) CODE_GENERATOR_NOEXCEPT : BinaryGenerator<GeneratorElfX86>(oStream) {} private: void emitHeaderImpl() CODE_GENERATOR_NOEXCEPT { // skip header skip(sizeof(Elf32_Ehdr) + sizeof(Elf32_Phdr) * kNProgramHeaders); // - - - - - The start of program body - - - - - // // mov ecx, {kBssAddr} u8 opcode1[] = {0xb9}; write(opcode1); write(static_cast<u32>(kBssAddr)); // mov edx, 0x01 u8 opcode2[] = {0xba}; write(opcode2); write(static_cast<u32>(0x01)); } void emitFooterImpl() CODE_GENERATOR_NOEXCEPT { // Emit newline emitAssignImpl('\n'); emitPutcharImpl(); // mov eax, 0x01 u8 opcode1[] = {0xb8}; write(opcode1); write(static_cast<u32>(0x01)); // xor ebx, ebx u8 opcode2[] = {0x31, 0xdb}; write(opcode2); // int 0x80 u8 opcode3[] = {0xcd, 0x80}; write(opcode3); // - - - - - The end of program body - - - - - // Elf32_Off codeSize = static_cast<Elf32_Off>(oStream.tellp()) - kHeaderSize; // - - - - - Program footer - - - - - // // Section string table (22bytes) const char kShStrTbl[] = "\0.text\0.shstrtbl\0.bss"; write(kShStrTbl); // First section header Elf32_Shdr shdr; shdr.sh_name = 0; shdr.sh_type = SHT_NULL; shdr.sh_flags = 0x00000000; shdr.sh_addr = 0x00000000; shdr.sh_offset = 0x00000000; shdr.sh_size = 0x00000000; shdr.sh_link = 0x00000000; shdr.sh_info = 0x00000000; shdr.sh_addralign = 0x00000000; shdr.sh_entsize = 0x00000000; write(shdr); // Second section header (.shstrtbl) shdr.sh_name = 7; shdr.sh_type = SHT_STRTAB; shdr.sh_flags = 0x00000000; shdr.sh_addr = 0x00000000; shdr.sh_offset = kHeaderSize + codeSize; shdr.sh_size = sizeof(kShStrTbl); shdr.sh_link = 0x00000000; shdr.sh_info = 0x00000000; shdr.sh_addralign = 0x00000001; shdr.sh_entsize = 0x00000000; write(shdr); // Third section header (.text) shdr.sh_name = 1; shdr.sh_type = SHT_PROGBITS; shdr.sh_flags = SHF_EXECINSTR | SHF_ALLOC; shdr.sh_addr = kBaseAddr + kHeaderSize; shdr.sh_offset = kHeaderSize; shdr.sh_size = codeSize; shdr.sh_link = 0x00000000; shdr.sh_info = 0x00000000; shdr.sh_addralign = 0x00000004; shdr.sh_entsize = 0x00000000; write(shdr); // Fourth section header (.bss) shdr.sh_name = 17; shdr.sh_type = SHT_NOBITS; shdr.sh_flags = SHF_ALLOC | SHF_WRITE; shdr.sh_addr = kBssAddr; shdr.sh_offset = 0x00001000; shdr.sh_size = 0x00010000; // 65536 cells shdr.sh_link = 0x00000000; shdr.sh_info = 0x00000000; shdr.sh_addralign = 0x00000010; shdr.sh_entsize = 0x00000000; write(shdr); // - - - - - Program header - - - - - // oStream.seekp(0, std::ios_base::beg); // ELF header Elf32_Ehdr ehdr; std::fill_n(ehdr.e_ident, sizeof(ehdr.e_ident), 0x00); ehdr.e_ident[EI_MAG0] = ELFMAG0; ehdr.e_ident[EI_MAG1] = ELFMAG1; ehdr.e_ident[EI_MAG2] = ELFMAG2; ehdr.e_ident[EI_MAG3] = ELFMAG3; ehdr.e_ident[EI_CLASS] = ELFCLASS32; ehdr.e_ident[EI_DATA] = ELFDATA2LSB; ehdr.e_ident[EI_VERSION] = EV_CURRENT; ehdr.e_ident[EI_OSABI] = ELFOSABI_LINUX; ehdr.e_ident[EI_ABIVERSION] = 0x00; ehdr.e_ident[EI_PAD] = 0x00; ehdr.e_type = ET_EXEC; ehdr.e_machine = EM_386; ehdr.e_version = EV_CURRENT; ehdr.e_entry = kBaseAddr + kHeaderSize; ehdr.e_phoff = sizeof(Elf32_Ehdr); ehdr.e_shoff = static_cast<Elf32_Off>(kHeaderSize + sizeof(kShStrTbl) + codeSize); ehdr.e_flags = 0x00000000; ehdr.e_ehsize = sizeof(Elf32_Ehdr); ehdr.e_phentsize = sizeof(Elf32_Phdr); ehdr.e_phnum = kNProgramHeaders; ehdr.e_shentsize = sizeof(Elf32_Shdr); ehdr.e_shnum = kNSectionHeaders; ehdr.e_shstrndx = 1; write(ehdr); // Program header Elf32_Phdr phdr; phdr.p_type = PT_LOAD; phdr.p_flags = PF_R | PF_X; phdr.p_offset = 0x00000000; phdr.p_vaddr = kBaseAddr; phdr.p_paddr = kBaseAddr; phdr.p_filesz = static_cast<Elf32_Word>(kHeaderSize + sizeof(kShStrTbl) + kFooterSize + codeSize); phdr.p_memsz = static_cast<Elf32_Word>(kHeaderSize + sizeof(kShStrTbl) + kFooterSize + codeSize); phdr.p_align = 0x00001000; write(phdr); // Program header for .bss (56 bytes) phdr.p_type = PT_LOAD; phdr.p_flags = PF_R | PF_W; phdr.p_offset = 0x00000000; phdr.p_vaddr = kBssAddr; phdr.p_paddr = kBssAddr; phdr.p_filesz = 0x00000000; phdr.p_memsz = 0x00010000; phdr.p_align = 0x00001000; write(phdr); oStream.seekp(0, std::ios_base::end); } void emitMovePointerImpl(int op1) CODE_GENERATOR_NOEXCEPT { if (op1 > 0) { if (op1 > 127) { // add ecx, {op1} u8 opcode[] = {0x81, 0xc1}; write(opcode); write(op1); } else if (op1 > 1) { // add ecx, {op1} u8 opcode[] = {0x83, 0xc1}; write(opcode); write(static_cast<u8>(op1)); } else { // inc ecx u8 opcode[] = {0x41}; write(opcode); } } else { if (op1 < -127) { // sub ecx, {-op1} u8 opcode[] = {0x81, 0xe9}; write(opcode); write(-op1); } else if (op1 < -1) { // sub ecx, {-op1} u8 opcode[] = {0x83, 0xe9}; write(opcode); write(static_cast<u8>(-op1)); } else { // dec ecx u8 opcode[] = {0x49}; write(opcode); } } } void emitAddImpl(int op1) CODE_GENERATOR_NOEXCEPT { if (op1 > 0) { if (op1 > 1) { // add byte ptr [ecx], {op1} u8 opcode[] = {0x80, 0x01}; write(opcode); write(static_cast<u8>(op1)); } else { // inc byte ptr [ecx] u8 opcode[] = {0xfe, 0x01}; write(opcode); } } else { if (op1 < -1) { // sub byte ptr [ecx], {op1} u8 opcode[] = {0x80, 0x29}; write(opcode); write(static_cast<u8>(-op1)); } else { // dec byte ptr [ecx] u8 opcode[] = {0xfe, 0x09}; write(opcode); } } } void emitPutcharImpl() CODE_GENERATOR_NOEXCEPT { // mov eax, 0x04 u8 opcode1[] = {0xb8}; write(opcode1); write(static_cast<u32>(0x04)); // mov ebx, 0x01 u8 opcode2[] = {0xbb}; write(opcode2); write(static_cast<u32>(0x01)); // int 0x80 u8 opcode3[] = {0xcd, 0x80}; write(opcode3); } void emitGetcharImpl() CODE_GENERATOR_NOEXCEPT { // mov eax, 0x03 u8 opcode1[] = {0xb8}; write(opcode1); write(static_cast<u32>(0x03)); // xor ebx, ebx u8 opcode2[] = {0x31, 0xdb}; write(opcode2); // int 0x80 u8 opcode3[] = {0xcd, 0x80}; write(opcode3); } void emitLoopStartImpl() CODE_GENERATOR_NOEXCEPT { loopStack.push(oStream.tellp()); // cmp byte ptr [ecx], 0x00 u8 opcode1[] = {0x80, 0x39}; write(opcode1); write(static_cast<u8>(0x00)); // je 0x******** u8 opcode2[] = {0x0f, 0x84}; write(opcode2); write(static_cast<u32>(0x00000000)); } void emitLoopEndImpl() CODE_GENERATOR_NOEXCEPT { std::ostream::pos_type pos = loopStack.top(); int offset = static_cast<int>(pos - oStream.tellp()) - 1; if (offset - static_cast<int>(sizeof(u8)) < -128) { // jmp {offset} (near jump) u8 opcode = {0xe9}; write(opcode); write(offset - sizeof(u32)); } else { // jmp {offset} (short jump) u8 opcode = {0xeb}; write(opcode); write(static_cast<u8>(offset - sizeof(u8))); } // fill loop start std::ostream::pos_type curPos = oStream.tellp(); oStream.seekp(pos + static_cast<std::ostream::pos_type>(5), std::ios_base::beg); write(static_cast<u32>(curPos - oStream.tellp() - sizeof(u32))); oStream.seekp(curPos, std::ios_base::beg); loopStack.pop(); } void emitEndIfImpl() CODE_GENERATOR_NOEXCEPT { // fill if jump std::ostream::pos_type pos = loopStack.top(); std::ostream::pos_type curPos = oStream.tellp(); oStream.seekp(pos + static_cast<std::ostream::pos_type>(5), std::ios_base::beg); write(static_cast<u32>(curPos - oStream.tellp() - sizeof(u32))); oStream.seekp(curPos, std::ios_base::beg); loopStack.pop(); } void emitAssignImpl(int op1) CODE_GENERATOR_NOEXCEPT { // mov byte ptr [ecx], {op1} u8 opcode[] = {0xc6, 0x01}; write(opcode); write(static_cast<u8>(op1)); } void emitAddVarImpl(int op1) CODE_GENERATOR_NOEXCEPT { // mov al, byte ptr [ecx] u8 opcode1[] = {0x8a, 0x01}; write(opcode1); // add byte ptr [ecx + {op1}], al if (op1 < -128 || 127 < op1) { u8 opcode2[] = {0x00, 0x81}; write(opcode2); write(static_cast<u32>(op1)); } else { u8 opcode2[] = {0x00, 0x41}; write(opcode2); write(static_cast<u8>(op1)); } } void emitSubVarImpl(int op1) CODE_GENERATOR_NOEXCEPT { // mov al, byte ptr [ecx] u8 opcode1[] = {0x8a, 0x01}; write(opcode1); // sub byte ptr [rbx + {op1}], al if (op1 < -128 || 127 < op1) { u8 opcode2[] = {0x28, 0x81}; write(opcode2); write(static_cast<u32>(op1)); } else { u8 opcode2[] = {0x28, 0x41}; write(opcode2); write(static_cast<u8>(op1)); } } void emitAddCMulVarImpl(int op1, int op2) CODE_GENERATOR_NOEXCEPT { if (op2 > 0) { // mov al, {op2} u8 opcode1[] = {0xb0}; write(opcode1); write(static_cast<u8>(op2)); // mul byte ptr [ecx] u8 opcode2[] = {0xf6, 0x21}; write(opcode2); // add byte ptr [ecx + {op1}], al if (op1 < -128 || 127 < op1) { u8 opcode3[] = {0x00, 0x81}; write(opcode3); write(static_cast<u32>(op1)); } else { u8 opcode3[] = {0x00, 0x41}; write(opcode3); write(static_cast<u8>(op1)); } } else { // mov al, {-op2} u8 opcode1[] = {0xb0}; write(opcode1); write(static_cast<u8>(-op2)); // mul byte ptr [ecx] u8 opcode2[] = {0xf6, 0x21}; write(opcode2); // sub byte ptr [ecx], al if (op1 < -128 || 127 < op1) { u8 opcode3[] = {0x28, 0x81}; write(opcode3); write(static_cast<u32>(op1)); } else { u8 opcode3[] = {0x28, 0x41}; write(opcode3); write(static_cast<u8>(op1)); } } } void emitInfLoopImpl() CODE_GENERATOR_NOEXCEPT { emitIfImpl(); // jmp {offset} (near jump) u8 opcode = {0xeb}; write(opcode); write(static_cast<u8>(-2)); emitEndIfImpl(); } void emitBreakPointImpl() CODE_GENERATOR_NOEXCEPT { write<u8>(0xcc); } }; // class GeneratorElfX86 #endif // GENERATOR_ELF_X86_HPP
/* 基于先序序列和中序序列重建而建二叉树 /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) { if(pre.size() == 0 || vin.size() == 0){ return NULL; } TreeNode* root = new TreeNode(pre[0]); // root->val = pre[0]; int i; for(i = 0; i < vin.size(); i++){ if(vin[i] == pre[0]){ break; } } int leftLength = i, rightLength = vin.size()-leftLength-1; // left child tree vector<int> leftPre(pre.begin()+1, pre.begin()+leftLength+1); vector<int> leftIn(vin.begin(), vin.begin()+leftLength); root->left = reConstructBinaryTree(leftPre, leftIn); // right child tree vector<int> rightPre(pre.begin()+leftLength+1, pre.end()); vector<int> rightIn(vin.begin()+leftLength+1, vin.end()); root->right = reConstructBinaryTree(rightPre, rightIn); return root; } };
#include "../../gl_framework.h" using namespace glmock; extern "C" { #undef glEnableVertexAttribArray void CALL_CONV glEnableVertexAttribArray(GLuint en) { } PFNGLENABLEVERTEXATTRIBARRAYPROC __glewEnableVertexAttribArray = &glEnableVertexAttribArray; }
#include "basicValues.h" #include "value.h" namespace json { template<typename T> class AllocOnFirstAccess: public RefCntPtr<IValue> { public: AllocOnFirstAccess():RefCntPtr<IValue>(new T) {} }; template<bool v> class StaticBool : public BoolValue { public: virtual bool getBool() const override { return v; } }; class StaticZeroNumber : public AbstractNumberValue { public: virtual double getNumber() const override { return 0.0; } virtual Int getInt() const override { return 0; } virtual UInt getUInt() const override {return 0;} virtual LongInt getIntLong() const override { return 0; } virtual ULongInt getUIntLong() const override {return 0;} virtual ValueTypeFlags flags() const override { return numberUnsignedInteger|numberInteger; } }; class StaticEmptyStringValue : public AbstractStringValue { public: virtual StringView<char> getString() const override { return StringView<char>(); } }; class StaticEmptyArrayValue : public AbstractArrayValue { public: virtual std::size_t size() const override { return 0; } virtual const IValue *itemAtIndex(std::size_t ) const override { return AbstractValue::getUndefined(); } virtual bool enumItems(const IEnumFn &) const override { return true; } }; class StaticEmptyObjectValue : public AbstractObjectValue { public: virtual std::size_t size() const override { return 0; } virtual const IValue *itemAtIndex(std::size_t ) const override { return getUndefined(); } virtual const IValue *member(const StringView<char> &) const override { return getUndefined(); } virtual bool enumItems(const IEnumFn &) const override { return true; } }; const IValue *NullValue::getNull() { static AllocOnFirstAccess<NullValue> staticNull; return staticNull; } const IValue * BoolValue::getBool(bool v) { static AllocOnFirstAccess< StaticBool<false> >boolFalse; static AllocOnFirstAccess< StaticBool<true> >boolTrue; if (v) return boolTrue; else return boolFalse; } const IValue * AbstractNumberValue::getZero() { static AllocOnFirstAccess<StaticZeroNumber>zero; return zero; } const IValue * AbstractStringValue::getEmptyString() { static AllocOnFirstAccess<StaticEmptyStringValue> emptyStr; return emptyStr; } const IValue * AbstractArrayValue::getEmptyArray() { static AllocOnFirstAccess<StaticEmptyArrayValue> emptyArray; return emptyArray; } const IValue * AbstractObjectValue::getEmptyObject() { static AllocOnFirstAccess<StaticEmptyObjectValue> emptyObject; return emptyObject; } template class NumberValueT<UInt, numberUnsignedInteger>; template class NumberValueT<Int, numberInteger>; template class NumberValueT<ULongInt, numberUnsignedInteger | longInt>; template class NumberValueT<LongInt, numberInteger | longInt>; template class NumberValueT<double,0>; bool NullValue::equal(const IValue* other) const { return other->type() == null; } bool BoolValue::equal(const IValue* other) const { return other->type() == boolean && getBool() == other->getBool(); } bool AbstractNumberValue::equal(const IValue* other) const { return other->type() == number && getNumber() == other->getNumber(); } bool AbstractStringValue::equal(const IValue* other) const { return other->type() == string && getString() == other->getString(); } bool AbstractArrayValue::equal(const IValue* other) const { if (other->type() == array && other->size() == size()) { std::size_t cnt = size(); for (std::size_t i = 0; i < cnt; i++) { const IValue *a = itemAtIndex(i); const IValue *b = other->itemAtIndex(i); if (a != b && !a->equal(b)) return false; } return true; } return false; } bool AbstractObjectValue::equal(const IValue *other) const { if (other->type() == object && other->size() == size()) { std::size_t cnt = size(); for (std::size_t i = 0; i < cnt; i++) { const IValue *a = itemAtIndex(i); const IValue *b = other->itemAtIndex(i); if (a != b && (a->getMemberName() != b->getMemberName() || !a->equal(b))) return false; } return true; } return false; } }
#pragma once struct Direction { enum Type { NORTH, NORTHWEST, NORTHEAST, SOUTH, SOUTHWEST, SOUTHEAST, EAST, WEST }; Type t_; Direction(Type t) : t_(t) {} operator Type () const { return t_; } private: //prevent automatic conversion for any other built-in types such as bool, int, etc template<typename T> operator T () const; };
// For ECE2031 project // Written by Michael Reilly #ifndef CONFIG_HPP #define CONFIG_HPP #include <cstdint> #include <cstdlib> #include <cstddef> #include <cstring> #include <cmath> #include <tuple> #include <memory> #include <functional> #include <algorithm> #include <iostream> #include <initializer_list> #include <exception> #include <stdexcept> #include <atomic> #include <string> #include <locale> namespace TFC { // Really common std namespace includes, and replacements for std libraries // that don't provide them using std::cout; using std::cin; using std::endl; using std::size_t; using std::string; using std::stringstream; using std::ifstream; using std::swap; using std::move; using std::unique_ptr; using std::shared_ptr; using std::weak_ptr; using std::make_shared; using std::make_unique; using std::static_pointer_cast; using std::dynamic_pointer_cast; using std::const_pointer_cast; using std::enable_shared_from_this; using std::pair; using std::make_pair; using std::tuple; using std::make_tuple; using std::tuple_element; using std::get; using std::tie; using std::ignore; using std::initializer_list; using std::min; using std::max; using std::bind; using std::function; using std::forward; using std::mem_fn; using std::ref; using std::cref; using namespace std::placeholders; using std::atomic; using std::atomic_flag; using std::atomic_load; using std::atomic_store; #ifndef NDEBUG #define TFC_DEBUG 1 constexpr bool DebugEnabled = true; #else constexpr bool DebugEnabled = false; #endif // A version of string::npos that's used in general to mean "not a position" // and is the largest value for size_t. size_t const NPos = (size_t)(-1); // Convenient way to purposefully mark a variable as unused to avoid warning #define _unused(x) ((void)x) #define TFC_CLASS(ClassName)\ class ClassName; \ typedef std::shared_ptr<ClassName> ClassName ## Ptr; \ typedef std::shared_ptr<const ClassName> ClassName ## ConstPtr; \ typedef std::weak_ptr<ClassName> ClassName ## WeakPtr; \ typedef std::weak_ptr<const ClassName> ClassName ## ConstWeakPtr; \ typedef std::unique_ptr<ClassName> ClassName ## UPtr; \ typedef std::unique_ptr<const ClassName> ClassName ## ConstUPtr #define TFC_STRUCT(StructName)\ struct StructName; \ typedef std::shared_ptr<StructName> StructName ## Ptr; \ typedef std::shared_ptr<const StructName> StructName ## ConstPtr; \ typedef std::weak_ptr<StructName> StructName ## WeakPtr; \ typedef std::weak_ptr<const StructName> StructName ## ConstWeakPtr; \ typedef std::unique_ptr<StructName> StructName ## UPtr; \ typedef std::unique_ptr<const StructName> StructName ## ConstUPtr } #endif
#include <iostream> #include <cmath> int convertDec(int num,int mPow,int system, int newNum = 0) { if(mPow < 0) { return newNum; } std::cout << "num:\t" << num << std::endl; int include = pow(system,mPow); std::cout << "Includ:\t" << include << std::endl; int count = num/include; std::cout << "count:\t" << count << std::endl; if(count > 0) { newNum = newNum*10+count; } else { newNum = newNum*10; } std::cout << "newNum:\t" << newNum << std::endl; int remain = num - include*count; std::cout << "remain:\t" << remain << std::endl; convertDec(remain, mPow - 1, system, newNum); } int main() { int number; int nSystem; std::cout << "Enter number:\t" << std::endl; std::cin >> number; std::cout << "Enter system:\t" << std::endl; std::cin >> nSystem; int maxPower; for(int i = 0; i < 32; i++) { if(number < pow(nSystem,i)) { maxPower = i-1; break; } } std::cout << "Maxp:\t" << maxPower << std::endl; std::cout << convertDec(number, maxPower, nSystem) << std::endl; return 0; }
/* Departamento de ComputaŤ‹o ComputaŤ‹o Gr‡fica 2017.1 Prof: Laurindo de Sousa Antonio Fabricio Almeida e Silva Editor Gr‡fico - Trabalho 04 */ #ifdef __APPLE__ #include <GLUT/glut.h> #else #include <GL/glut.h> #endif // Biblioteca com funcoes matematicas #include <cmath> #include <cstdio> #include <cstdlib> // Variaveis Globais //clicks do mouse necessarios para criar as formas bool click1 = false, click2 = false, click3 = false; //booleano de cada forma geometrica usado para saber qual deseja desenhar bool linha = false, quadrilatero = false, triangulo = false,poligono = false, circulo = false; //booleanos para saber quando fechar o poligono e o raio do circulo bool fechaPoligono = false, pegaRaio = false; double x_1,y_1,x_2,y_2,x_3,y_3; double raio; double escalaX = 1, escalaY = 1, translacaoX, translacaoY, fatorCisalhamento = 1, anguloRotacao; int width = 512, height = 512; //Largura e altura da janela // Estrututa de dados para o armazenamento dinamico dos pontos // selecionados pelos algoritmos de rasterizacao struct ponto{ int x; int y; ponto * prox; }; //Estrutura para armazenar todos os pontos, para fazer operaŤ›es struct coordenadasArmazenadas{ int x1; int y1; int x2; int y2; coordenadasArmazenadas *prox; }; // Lista encadeada de pontos // indica o primeiro elemento da lista ponto * pontos = NULL; ponto * temp = NULL; //Lista de coordenadas coordenadasArmazenadas *listaCoord; coordenadasArmazenadas * storeCoordenada(int x1, int y1, int x2, int y2){ coordenadasArmazenadas *coordArmaz; coordenadasArmazenadas *coordAux; coordArmaz = new coordenadasArmazenadas; int ym; if(y1<y2){ ym = y1; }else{ ym = y2; } int yp; coordArmaz->x1 = x1; coordArmaz->y1 = y1; coordArmaz->x2 = x2; coordArmaz->y2 = y2; if (listaCoord != NULL){ if(listaCoord->y1 < listaCoord->y2){ yp = listaCoord->y1; }else{ yp = listaCoord->y2; } } if ((listaCoord == NULL) || (ym<=yp)) { coordArmaz->prox = listaCoord; listaCoord = coordArmaz; return coordArmaz; } else { if (listaCoord->prox == NULL) { coordArmaz->prox = NULL; listaCoord->prox = coordArmaz; return listaCoord; } else { coordAux = listaCoord; if(coordAux->prox->y1 < coordAux->prox->y2){ yp = coordArmaz->prox->y1; }else{ yp = coordAux->prox->y2; } while ((yp < ym) && (coordAux->prox != NULL)) { coordAux = coordAux->prox; if (coordAux->prox != NULL){ if(coordAux->prox->y1 < coordAux->prox->y2){ yp = coordAux->prox->y1; }else{ yp = coordAux->prox->y2; } } } coordArmaz->prox = coordAux->prox; coordAux->prox = coordArmaz; return listaCoord; } } } // Funcao para armazenar um ponto na lista // Armazena como uma Pilha (empilha) ponto * pushPonto(int x, int y){ ponto * pnt; pnt = new ponto; pnt->x = x; pnt->y = y; pnt->prox = pontos; pontos = pnt; return pnt; } // Funcao para desarmazenar um ponto na lista // Desarmazena como uma Pilha (desempilha) ponto * popPonto(){ ponto * pnt; pnt = NULL; if(pontos != NULL){ pnt = pontos->prox; delete pontos; pontos = pnt; } return pnt; } // Declaracoes forward das funcoes utilizadas void init(void); void reshape(int w, int h); void display(void); void keyboard(unsigned char key, int x, int y); void mouse(int button, int state, int x, int y); void menuOpcoes(int value); void infos(); void limpaTela(); // Funcao que implementa o Algoritmo Imediato para rasterizacao de retas void retaImediata(double x1,double y1,double x2,double y2); void bresenham(double x1,double y1,double x2,double y2); void desenhaQuadrilatero(double x1,double y1,double x2,double y2); void desenhaTriangulo(double x1,double y1,double x2,double y2,double x3,double y3); void desenhaCirculo(double x1,double y1, double r); void escala(); void cisalhamentoEmX(); void cisalhamentoEmY(); // Funcao que percorre a lista de pontos desenhando-os na tela void drawPontos(); // Funcao Principal do C int main(int argc, char** argv){ glutInit(&argc, argv); // Passagens de parametro C para o glut glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB); // Selecao do Modo do Display e do Sistema de cor utilizado glutInitWindowSize (width, height); // Tamanho da janela do OpenGL glutInitWindowPosition (100, 100); //Posicao inicial da janela do OpenGL glutCreateWindow ("Paint CG"); // Da nome para uma janela OpenGL init(); // Chama funcao init(); glutReshapeFunc(reshape); //funcao callback para redesenhar a tela glutKeyboardFunc(keyboard); //funcao callback do teclado glutMouseFunc(mouse); //funcao callback do mouse glutDisplayFunc(display); //funcao callback de desenho glutCreateMenu(menuOpcoes); glutAddMenuEntry("Desenhar Linha", 0); glutAddMenuEntry("Desenhar Quadrilatero", 1); glutAddMenuEntry("Desenhar Triangulo", 2); glutAddMenuEntry("Desenhar Poligono", 3); glutAddMenuEntry("Desenhar Circunferencia", 4); glutAddMenuEntry("Escala", 5); glutAddMenuEntry("TranslaŤ‹o", 6); glutAddMenuEntry("RotaŤ‹o", 7); glutAddMenuEntry("Cisalhamento em X", 8); glutAddMenuEntry("Cisalhamento em Y", 9); glutAddMenuEntry("Limpar a tela", 10); glutAddMenuEntry("Sair", 11); glutAttachMenu(GLUT_RIGHT_BUTTON); glutMainLoop(); // executa o loop do OpenGL return 0; // retorna 0 para o tipo inteiro da funcao main(); } // Funcao com alguns comandos para a inicializacao do OpenGL; void init(void){ glClearColor(1.0, 1.0, 1.0, 1.0); //Limpa a tela com a cor branca; infos(); } void reshape(int w, int h){ // Definindo o Viewport para o tamanho da janela glViewport(0, 0, w, h); // Reinicializa o sistema de coordenadas glMatrixMode(GL_PROJECTION); glLoadIdentity(); width = w; height = h; glOrtho (0, w, 0, h, -1 ,1); // muda para o modo GL_MODELVIEW (n‹o pretendemos alterar a projecŤ‹o // quando estivermos a desenhar na tela) glMatrixMode(GL_MODELVIEW); glLoadIdentity(); click1 = true; //Para redesenhar os pixels selecionados click2 = true; if (triangulo) click3 = true; } // Funcao usada na funcao callback para utilizacao das teclas normais do teclado void keyboard(unsigned char key, int x, int y){ switch (key) { // key - variavel que possui valor ASCII da tecla precionada case 27: // codigo ASCII da tecla ESC exit(0); // comando pra finalizacao do programa break; //recebe os pontos do poligono case 102: //ao apertar a tecla F, o poligono e fechado ligando o ultimo ponto ao ponto inicial if (poligono && fechaPoligono) { fechaPoligono = false; x_2 = x_1; y_2 = y_1; x_1 = x_3; y_1 = y_3; //printf("x y (%.0f,%.0f)\n",x_1,y_1); glutPostRedisplay(); } break; } } //Funcao usada na funcao callback para a utilizacao do mouse void mouse(int button, int state, int x, int y){ switch (button) { case GLUT_LEFT_BUTTON: if (state == GLUT_DOWN) { if (triangulo == true || linha == true || quadrilatero == true){ if(triangulo && click2) { click3 = true; x_3 = x; y_3 = height - y; //printf("x3y3(%.0f,%.0f)\n",x_3,y_3); glutPostRedisplay(); } else if(click1){ click2 = true; x_2 = x; y_2 = height - y; //printf("x2y2(%.0f,%.0f)\n",x_2,y_2); if (triangulo == false){ glutPostRedisplay(); } }else{ click1 = true; x_1 = x; y_1 = height - y; //printf("x1y1(%.0f,%.0f)\n",x_1,y_1); } } else if (poligono) { //Letra E) if (fechaPoligono) { x_2 = x_1; y_2 = y_1; x_1 = x; y_1 = height - y; //printf("x y (%.0f,%.0f)\n",x_1,y_1); glutPostRedisplay(); } else { fechaPoligono = true; x_1 = x; y_1 = height - y; x_3 = x_1; y_3 = y_1; //printf("x1y1(%.0f,%.0f)\n",x_1,y_1); } } else if (circulo) { if(click1){ double xAux, yAux; pegaRaio = true; x_2 = x; y_2 = height - y; //printf("x2y2(%.0f,%.0f)\n", x_2, y_2); xAux = abs(x_2) - abs(x_1); yAux = abs(y_2) - abs(y_1); raio = sqrt(pow(xAux,2) + pow(yAux,2)); //printf("\nraio %.0f\n", raio); glutPostRedisplay(); }else{ click1 = true; x_1 = x; y_1 = height - y; //printf("x1y1(%.0f,%.0f)\n",x_1,y_1); } } } break; /* case GLUT_MIDDLE_BUTTON: if (state == GLUT_DOWN) { glutPostRedisplay(); } break; */ default: break; } } // Funcao usada na funcao callback para desenhar na tela void display(void){ glClear(GL_COLOR_BUFFER_BIT); //Limpa o Buffer de Cores glColor3f (0.0, 0.0, 0.0); // Seleciona a cor default como preto if (triangulo == true || linha == true || quadrilatero == true){ if(triangulo){ if(click1 && click2 && click3) { desenhaTriangulo(x_1,y_1,x_2,y_2,x_3,y_3); drawPontos(); click1 = false; click2 = false; click3 = false; } }else if(click1 && click2){ //retaImediata(x_1,y_1,x_2,y_2); if (linha) bresenham(x_1,y_1,x_2,y_2); else desenhaQuadrilatero(x_1,y_1,x_2,y_2); drawPontos(); //listaCoord(); //retirar depois click1 = false; click2 = false; } } else if (poligono) { //Letra E) bresenham(x_1,y_1,x_2,y_2); drawPontos(); if (!fechaPoligono) { bresenham(x_1,y_1,x_3,y_3); drawPontos(); } } else if (circulo && pegaRaio) { desenhaCirculo(x_1, y_1, raio); drawPontos(); pegaRaio = false; click1 = false; click2 = false; } glutSwapBuffers(); // manda o OpenGl renderizar as primitivas } //Funcao que desenha os pontos contidos em uma lista de pontos void drawPontos(){ ponto * pnt; pnt = pontos; glBegin(GL_POINTS); // Seleciona a primitiva GL_POINTS para desenhar while(pnt != NULL){ glVertex2i(pnt->x,pnt->y); pnt = pnt->prox; } glEnd(); // indica o fim do desenho } //Funcao callback para inicializar a forma geometrica escolhida no menu //os cicks e as formas restantes sao inicializadas como false em cada escolha void menuOpcoes(int value){ switch(value){ case 0: //desenhar linha linha = true; triangulo = false; quadrilatero = false; poligono = false; circulo = false; click1 = false; click2 = false; break; case 1://desenhar quadrilatero linha = false; quadrilatero = true; triangulo = false; poligono = false; circulo = false; click1 = false; click2 = false; break; case 2://desenhar triangulo linha = false; quadrilatero = false; triangulo = true; poligono = false; circulo = false; click1 = false; click2 = false; click3 = false; break; case 3://desenhar poligono linha = false; quadrilatero = false; triangulo = false; poligono = true; circulo = false; click1 = false; click2 = false; click3 = false; break; case 4://desenhar circunferencia triangulo = false; linha = false; quadrilatero = false; poligono = false; circulo = true; click1 = false; click2 = false; break; case 5: //Escala triangulo = false; linha = false; quadrilatero = false; poligono = false; circulo = false; system("cls"); printf("\n Digite o valor de escala em X: "); scanf("%lf", &escalaX); printf("\n Digite o valor de escala em Y: "); scanf("%lf", &escalaY); escala(); glutPostRedisplay(); break; case 6://Translacao triangulo = false; linha = false; quadrilatero = false; poligono = false; circulo = false; system("cls"); printf("\n Digite o valor de Translacao em X: "); scanf("%lf", &translacaoX); printf("\n Digite o valor de Translacao em Y: "); scanf("%lf", &translacaoY); glutPostRedisplay(); break; case 8://cisalhamento em X triangulo = false; linha = false; quadrilatero = false; poligono = false; circulo = false; system("cls"); printf("\n Digite o valor de cisalhamento: "); scanf("%lf", &fatorCisalhamento); cisalhamentoEmX(); glutPostRedisplay(); break; case 9://cisalhamento em Y triangulo = false; linha = false; quadrilatero = false; poligono = false; circulo = false; system("cls"); printf("\n Digite o valor de cisalhamento: "); scanf("%lf", &fatorCisalhamento); cisalhamentoEmY(); glutPostRedisplay(); break; case 10: limpaTela(); break; case 11: exit(0); break; } /* Manda o redesenhar a tela quando o menu for desativado */ glutPostRedisplay(); } void infos() { system("cls"); printf("Infos adicionais\nPressione o botao direito na tela para escolher as opcoes de desenho!\n"); } //FunŤ‹o para limpar a tela a qualquer momento caso o usuario desejar void limpaTela(){ glClearColor(1.0,1.0,1.0,1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); while(pontos != NULL){ temp = pontos; pontos = temp->prox; free(pontos); } } //Algoritmo de Bresenham para rasterizacao de retas(Letra 'A') void bresenham(double x1,double y1,double x2,double y2){ double aux1, aux2; double d, incE, incNE; double dx, dy; //delta X e delta Y bool sim = false, dec = false; listaCoord = storeCoordenada((int) x1, (int) y1, (int) x2, (int) y2); dx = x2 - x1; dy = y2 - y1; pontos = pushPonto((int)x1,(int)y1); pontos = pushPonto((int)x2,(int)y2); //Algoritmo para reducao ao primeiro octanto para rasterizacao de retas //necessarios para que possa desenhar as formas geometricas por toda a tela //Letra 'B' if ((dx * dy)<0) { y1 = y1*(-1); y2 = y2*(-1); dy = y2 - y1; sim = true; } if (abs(dx)<abs(dy)) { aux1 = y1; y1 = x1; x1 = aux1; aux2 = y2; y2 = x2; x2 = aux2; dx = x2 - x1; dy = y2 - y1; dec = true; } if (x1 > x2) { aux1 = x1; x1 = x2; x2 = aux1; aux2 = y1; y1 = y2; y2 = aux2; dx = x2 - x1; dy = y2 - y1; } //Continuacao do algoritmo de bresenham apos a reducao d = (2 * dy) - dx; incE = 2 * dy; incNE = 2 * (dy - dx); while (x1 < x2) { if (d <= 0) { aux1 = x1 + 1; aux2 = y1; d += incE; } else { aux1 = x1 + 1; aux2 = y1 + 1; d += incNE; } x1 = aux1; y1 = aux2; if (dec) { aux1 = y1; aux2 = x1; } if (sim) { aux2 = aux2 * (-1); } pontos = pushPonto((int)aux1,(int)aux2); } } //Ao receber dois pontos, utiliza o algoritmo de bresenham para desenhar o quadrilatero //Letra 'C' void desenhaQuadrilatero(double x1,double y1,double x2,double y2) { bresenham(x1, y1, x1, y2); bresenham(x1, y2, x2, y2); bresenham(x2, y2, x2, y1); bresenham(x2, y1, x1, y1); } //Ao receber 3 coordenadas na tela, um triangulo e desenhado, utilizando o algoritmo de bresenham //Letra 'D' void desenhaTriangulo(double x1,double y1,double x2,double y2,double x3,double y3) { bresenham(x1, y1, x2, y2); bresenham(x2, y2, x3, y3); bresenham(x3, y3, x1, y1); } //Algoritmo para desenhar um circulo a partir do raio dado //Letra 'G' void desenhaCirculo(double x,double y, double r){ double d = 1 - r; double deltaE = 3.0; double deltaSE = (-2*r) + 5; double x_aux = 0; double y_aux = r; //insere em struct de Coordenadas para operaŤ›es posteriores //coord = insCoord((int) x1, (int) y1, 0, 0, (int) r); pontos = pushPonto((int)(x),(int)(r + y)); //ponto superior da circunferencia (positivo) pontos = pushPonto((int)(x),(int)(-r + y)); //ponto inferior da circunferencia (negativo) pontos = pushPonto((int)(r + x),(int)(y)); //ponto extremo direito da circunferencia (positivo) pontos = pushPonto((int)(-r + x),(int)(y)); ////ponto extremo esquerdo da circunferencia (negativo) x_aux += 1; while(y_aux > x_aux) { if (d < 0) { d += deltaE; deltaE += 2; deltaSE += 2; } else if(d >= 0){ d += deltaSE; deltaE += 2; deltaSE = deltaSE + 4; y_aux--; } //marcando os 8 pixeis da circunferencia coorespondente as coordenadas pontos = pushPonto((int)(x_aux + x),(int)(y_aux + y)); pontos = pushPonto((int)(-x_aux + x),(int)(y_aux + y)); pontos = pushPonto((int)(-x_aux + x),(int)(-y_aux + y)); pontos = pushPonto((int)(x_aux + x),(int)(-y_aux + y)); pontos = pushPonto((int)(y_aux + x),(int)(x_aux + y)); pontos = pushPonto((int)(-y_aux + x),(int)(x_aux + y)); pontos = pushPonto((int)(-y_aux + x),(int)(-x_aux + y)); pontos = pushPonto((int)(y_aux + x),(int)(-x_aux + y)); x_aux++; } } void escala() { coordenadasArmazenadas *coordArmazenadas; coordArmazenadas = listaCoord; listaCoord = NULL; while(coordArmazenadas != NULL) { coordArmazenadas->x1 *= escalaX; coordArmazenadas->y1 *= escalaY; coordArmazenadas->x2 *= escalaX; coordArmazenadas->y2 *= escalaY; bresenham(coordArmazenadas->x1, coordArmazenadas->y1, coordArmazenadas->x2, coordArmazenadas->y2); drawPontos(); coordArmazenadas = coordArmazenadas->prox; } escalaX = 1; escalaY = 1; } void cisalhamentoEmX() { coordenadasArmazenadas *coordArmazenadas; coordArmazenadas = listaCoord; listaCoord = NULL; while(coordArmazenadas != NULL) { coordArmazenadas->x1 += (fatorCisalhamento * coordArmazenadas->y1); coordArmazenadas->x2 += (fatorCisalhamento * coordArmazenadas->y2); bresenham(coordArmazenadas->x1, coordArmazenadas->y1, coordArmazenadas->x2, coordArmazenadas->y2); drawPontos(); coordArmazenadas = coordArmazenadas->prox; } fatorCisalhamento = 1; } void cisalhamentoEmY() { coordenadasArmazenadas *coordArmazenadas; coordArmazenadas = listaCoord; listaCoord = NULL; while(coordArmazenadas != NULL) { coordArmazenadas->y1 += (fatorCisalhamento * coordArmazenadas->x1); coordArmazenadas->y2 += (fatorCisalhamento * coordArmazenadas->x2); bresenham(coordArmazenadas->x1, coordArmazenadas->y1, coordArmazenadas->x2, coordArmazenadas->y2); drawPontos(); coordArmazenadas = coordArmazenadas->prox; } fatorCisalhamento = 1; }
#pragma once class GameCamera2D :public GameObject { public: ~GameCamera2D(); bool Start(); void Update(); private: };
// Created on: 1997-01-03 // Created by: Christian CAILLET // Copyright (c) 1997-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // 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, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _StepData_FreeFormEntity_HeaderFile #define _StepData_FreeFormEntity_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <StepData_HArray1OfField.hxx> #include <Standard_Transient.hxx> #include <Standard_CString.hxx> #include <TColStd_HSequenceOfAsciiString.hxx> #include <Standard_Integer.hxx> class StepData_Field; class StepData_FreeFormEntity; DEFINE_STANDARD_HANDLE(StepData_FreeFormEntity, Standard_Transient) //! A Free Form Entity allows to record any kind of STEP //! parameters, in any way of typing //! It is implemented with an array of fields //! A Complex entity can be defined, as a chain of FreeFormEntity //! (see Next and As) class StepData_FreeFormEntity : public Standard_Transient { public: //! Creates a FreeFormEntity, with no field, no type Standard_EXPORT StepData_FreeFormEntity(); //! Sets the type of an entity //! For a complex one, the type of this member Standard_EXPORT void SetStepType (const Standard_CString typenam); //! Returns the recorded StepType //! For a complex one, the type of this member Standard_EXPORT Standard_CString StepType() const; //! Sets a next member, in order to define or complete a Complex //! entity //! If <last> is True (D), this next will be set as last of list //! Else, it is inserted just as next of <me> //! If <next> is Null, Next is cleared Standard_EXPORT void SetNext (const Handle(StepData_FreeFormEntity)& next, const Standard_Boolean last = Standard_True); //! Returns the next member of a Complex entity //! (remark : the last member has none) Standard_EXPORT Handle(StepData_FreeFormEntity) Next() const; //! Returns True if a FreeFormEntity is Complex (i.e. has Next) Standard_EXPORT Standard_Boolean IsComplex() const; //! Returns the member of a FreeFormEntity of which the type name //! is given (exact match, no sub-type) Standard_EXPORT Handle(StepData_FreeFormEntity) Typed (const Standard_CString typenam) const; //! Returns the list of types (one type for a simple entity), //! as is (non reordered) Standard_EXPORT Handle(TColStd_HSequenceOfAsciiString) TypeList() const; //! Reorders a Complex entity if required, i.e. if member types //! are not in alphabetic order //! Returns False if nothing done (order was OK or simple entity), //! True plus modified <ent> if <ent> has been reordered Standard_EXPORT static Standard_Boolean Reorder (Handle(StepData_FreeFormEntity)& ent); //! Sets a count of Fields, from scratch Standard_EXPORT void SetNbFields (const Standard_Integer nb); //! Returns the count of fields Standard_EXPORT Standard_Integer NbFields() const; //! Returns a field from its rank, for read-only use Standard_EXPORT const StepData_Field& Field (const Standard_Integer num) const; //! Returns a field from its rank, in order to modify it Standard_EXPORT StepData_Field& CField (const Standard_Integer num); DEFINE_STANDARD_RTTIEXT(StepData_FreeFormEntity,Standard_Transient) protected: private: TCollection_AsciiString thetype; Handle(StepData_HArray1OfField) thefields; Handle(StepData_FreeFormEntity) thenext; }; #endif // _StepData_FreeFormEntity_HeaderFile
#ifndef TOOLS_SHELL_SHELLCONTEXT #define TOOLS_SHELL_SHELLCONTEXT #include <map> #include <string> #include <boost/utility.hpp> #include <boost/shared_ptr.hpp> #include "DB.h" #include "DBClientProxy.h" class ShellState; class ShellContext : private boost::noncopyable { public: void changeState(ShellState * pState); void stop(void); bool ParseInput(void); void connect(void); void get(const std::string & db, const std::string & key); void put(const std::string & db, const std::string & key, const std::string & value); void scan(const std::string & db, const std::string & start_key, const std::string & end_key, const std::string & limit); void create(const std::string & db); void run(void); ShellContext(int argc, char ** argv); private: ShellState * pShellState_; bool exit_; int argc_; char ** argv_; int port_; boost::shared_ptr<rocksdb::DBClientProxy> clientProxy_; }; #endif
#ifndef NETMSGBUS_REQ2RECEIVER_MGR_H #define NETMSGBUS_REQ2RECEIVER_MGR_H #include "msgbus_def.h" #include "NetMsgBusServerConnMgr.hpp" #include "msgbus_handlerbase.hpp" #include "condition.hpp" #include "threadpool.h" #include "NetMsgBusUtility.hpp" #include "EventLoopPool.h" #include "SelectWaiter.h" #include "TcpSock.h" #include "SimpleLogger.h" #include "TcpClientPool.h" #include "NetMsgBusFuture.hpp" #include <errno.h> #include <pthread.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <map> #include <boost/unordered_map.hpp> #include <string> #include <netinet/in.h> #include <time.h> #include <arpa/inet.h> #include <sys/time.h> #include <boost/shared_array.hpp> #include <boost/bind.hpp> using std::string; using namespace core::net; #define TIMEOUT_SHORT 5 #define TIMEOUT_LONG 15 #define MAX_SENDMSG_CLIENT_NUM 1024 #define CLIENT_POOL_SIZE 4 namespace NetMsgBus { // client host info, all data with local byte order. typedef struct S_LocalHostInfo { S_LocalHostInfo(const std::string& ip, unsigned short int port) :host_ip(ip), host_port(port) { } S_LocalHostInfo() :host_ip(""), host_port(0) { } std::string host_ip; unsigned short int host_port; } LocalHostInfo; struct Req2ReceiverTask { Req2ReceiverTask() :clientname(""), sync(false), retry(false), timeout(TIMEOUT_LONG*4) { } std::string clientname; bool sync; uint32_t future_id; // note: 0 is reserved for non-future rsp need. bool retry; uint32_t data_len; boost::shared_array<char> data; int32_t timeout; LocalHostInfo dest_client; }; class Req2ReceiverMgr : public MsgHandler<Req2ReceiverMgr> { protected: Req2ReceiverMgr() :m_server_connmgr(NULL), m_req2receiver_running(false), m_req2receiver_terminate(false) { } public: friend class MsgHandlerMgr; static std::string ClassName() { return "Req2ReceiverMgr"; } void InitMsgHandler() { } void SetServerConnMgr(ServerConnMgr* pmgr) { m_server_connmgr = pmgr; } //void DisConnectFromClient(const std::string& name) //{ // LocalHostInfo destclient; // bool cache_exist = safe_get_cached_host_info(name, destclient); // if(!cache_exist) // { // return; // } // if(EventLoopPool::GetEventLoop("postmsg_event_loop")) // { // // find dest host in event loop, if success , we reuse the tcp connect. // TcpSockSmartPtr sptcp = m_postmsg_client_conn_pool.GetTcpSockByDestHost(destclient.host_ip, destclient.host_port); // if(sptcp) // { // sptcp->DisAllowSend(); // } // } //} bool SendMsgDirectToClient(const std::string& dest_ip, unsigned short dest_port, uint32_t data_len, boost::shared_array<char> data, string& rsp_content, int32_t timeout) { if(dest_ip.empty() || !m_req2receiver_running ) return false; Req2ReceiverTask task; task.data_len = data_len; task.data = data; task.sync = true; task.retry = false; task.timeout = timeout; task.dest_client.host_ip = dest_ip; task.dest_client.host_port = dest_port; std::pair<uint32_t, boost::shared_ptr<NetFuture> > future = future_mgr_.safe_insert_future(); task.future_id = future.first; // sync sendmsg will not retry to update client info if failed to send message. return ProcessReqToReceiver(task, rsp_content); } bool SendMsgDirectToClient(const std::string& clientname, uint32_t data_len, boost::shared_array<char> data, string& rsp_content, int32_t timeout) { if(clientname == "" || !m_req2receiver_running ) return false; LocalHostInfo destclient; bool cache_exist = safe_get_cached_host_info(clientname, destclient); if(!cache_exist) { if(m_server_connmgr && m_server_connmgr->ReqReceiverInfo(clientname, destclient.host_ip, destclient.host_port)) { // core::common::locker_guard guard(m_cached_receiver_locker); m_cached_client_info[clientname] = destclient; } else return false; } // sync sendmsg will not retry to update client info if failed to send message. return SendMsgDirectToClient(destclient.host_ip, destclient.host_port, data_len, data, rsp_content, timeout); } boost::shared_ptr<NetFuture> PostMsgDirectToClient(const std::string& dest_ip, unsigned short dest_port, uint32_t data_len, boost::shared_array<char> data, NetFuture::futureCB callback = NULL) { boost::shared_ptr<NetFuture> ret_future; if( !m_req2receiver_running ) { LOG(g_log, lv_debug, "req2receiver not running when post message to receiver."); return ret_future; } if(dest_ip.empty()) return ret_future; Req2ReceiverTask rtask; rtask.data = data; rtask.data_len = data_len; // send by ip , no retry need. rtask.retry = false; rtask.dest_client.host_ip = dest_ip; rtask.dest_client.host_port = dest_port; std::pair<uint32_t, boost::shared_ptr<NetFuture> > future = future_mgr_.safe_insert_future(callback); rtask.future_id = future.first; if(!QueueReqTaskToReceiver(rtask)) return boost::shared_ptr<NetFuture>(); return future.second; } boost::shared_ptr<NetFuture> PostMsgDirectToClient(const std::string& clientname, uint32_t data_len, boost::shared_array<char> data, NetFuture::futureCB callback = NULL) { if( !m_req2receiver_running ) { LOG(g_log, lv_debug, "req2receiver not running when post message to receiver."); return boost::shared_ptr<NetFuture>(); } Req2ReceiverTask rtask; rtask.clientname = clientname; rtask.data = data; rtask.data_len = data_len; rtask.retry = true; std::pair<uint32_t, boost::shared_ptr<NetFuture> > future = future_mgr_.safe_insert_future(callback); rtask.future_id = future.first; if(!QueueReqTaskToReceiver(rtask)) return boost::shared_ptr<NetFuture>(); return future.second; } bool Start() { if( m_req2receiver_running ) return true; m_req2receiver_terminate = false; m_req2receiver_tid = 0; if(0 != pthread_create(&m_req2receiver_tid, NULL, ProcessReq2ReceiverThreadFunc, this)) { perror("fatal error! req2receiver thread create failed\n"); m_req2receiver_tid = 0; return false; } //AddHandler("netmsgbus.server.getclient", &Req2ReceiverMgr::HandleRspGetClient, 0); while(!m_req2receiver_running) { usleep(100); } return true; } void Stop() { future_mgr_.safe_clear_bad_future(); m_req2receiver_terminate = true; { core::common::locker_guard guard(m_reqtoreceiver_locker); m_reqtoreceiver_cond.notify_all(); } if(m_req2receiver_tid) { pthread_join(m_req2receiver_tid, NULL); } RemoveAllHandlers(); EventLoopPool::TerminateLoop("postmsg_event_loop"); } private: void HandleRspGetClient(const NetFuture& futuredata) { MsgBusGetClientRsp rsp; std::string rspdata; if(!futuredata.get(rspdata) || futuredata.has_err()) return; try { rsp.UnPackBody(rspdata.data(), rspdata.size()); } catch(...) { LOG(g_log, lv_warn, "unpack get client rsp error."); return; } std::string clientname(rsp.dest_name); // remove all the pending task belong the rsp client name. Req2ReceiverTaskContainerT pendingtasks; { core::common::locker_guard guard(m_waitingtask_locker); WaitingReq2ReceiverTaskT::iterator it = m_wait2send_task_container.find(clientname); if(it != m_wait2send_task_container.end()) { pendingtasks = it->second; // clear all waiting tasks. it->second.clear(); m_wait2send_task_container.erase(it); } else { LOG(g_log, lv_info, "pending task %zu, but no pending task in client %s.", m_wait2send_task_container.size(), clientname.c_str()); } } Req2ReceiverTaskContainerT::iterator taskit = pendingtasks.begin(); if(rsp.ret_code == 0) { LocalHostInfo hostinfo; hostinfo.host_ip = rsp.dest_host.ip(); hostinfo.host_port = rsp.dest_host.port(); LOG(g_log, lv_debug, "get client info returned. ret name : %s, ip:port : %s:%d", clientname.c_str(), hostinfo.host_ip.c_str(), hostinfo.host_port); { core::common::locker_guard guard(m_cached_receiver_locker); m_cached_client_info[clientname] = hostinfo; } while(taskit != pendingtasks.end()) { // the client info has just update, so do not retry to update again. taskit->retry = false; QueueReqTaskToReceiver(*taskit); ++taskit; } } else { //PostMsg("netmsgbus.server.getclient.error", CustomType2Param(std::string(rsp.dest_name))); LOG(g_log, lv_warn, "server return error while query client info, ret_code: %d.", rsp.ret_code); while(taskit != pendingtasks.end()) { taskit->retry = false; future_mgr_.safe_remove_future(taskit->future_id); ++taskit; } } } bool QueueReqTaskToReceiver(const Req2ReceiverTask& req_task) { core::common::locker_guard guard(m_reqtoreceiver_locker); m_reqtoreceiver_task_container.push_back(req_task); // set a condition to inform new request. m_reqtoreceiver_cond.notify_one(); return true; } // 处理同步发送消息的响应数据 size_t Req2Receiver_onRead(TcpSockSmartPtr sp_tcp, const char* pdata, size_t size) { size_t readedlen = 0; while(true) { size_t needlen; uint32_t future_sid; uint32_t data_len; needlen = sizeof(future_sid) + sizeof(data_len); if(size < needlen) return readedlen; future_sid = ntohl(*((uint32_t*)pdata)); pdata += sizeof(future_sid); data_len = ntohl(*((uint32_t*)pdata)); pdata += sizeof(data_len); needlen += data_len; if(size < needlen) return readedlen; boost::shared_ptr<NetFuture> ready_sendmsg_rsp = future_mgr_.safe_get_future(future_sid, true); //g_log.Log(lv_debug, "receiver future data returned to client:%lld, sid:%u, fd:%d\n", (int64_t)core::utility::GetTickCount(), future_sid, sp_tcp->GetFD()); if(ready_sendmsg_rsp) { ready_sendmsg_rsp->set_result(pdata, data_len); } size -= needlen; readedlen += needlen; pdata += data_len; } } bool Req2Receiver_onSend(TcpSockSmartPtr sp_tcp) { return true; } void Req2Receiver_onClose(TcpSockSmartPtr sp_tcp) { //printf("req2receiver tcp disconnected.\n"); m_sendmsg_client_conn_pool.RemoveTcpSock(sp_tcp); m_postmsg_client_conn_pool.RemoveTcpSock(sp_tcp); future_mgr_.safe_clear_bad_future(); } void Req2Receiver_onError(TcpSockSmartPtr sp_tcp) { // you can notify the high level to handle the error, retry or just ignore. LOG(g_log, lv_error, "client %d , error happened, time:%lld.\n", sp_tcp->GetFD(), (int64_t)utility::GetTickCount()); m_sendmsg_client_conn_pool.RemoveTcpSock(sp_tcp); m_postmsg_client_conn_pool.RemoveTcpSock(sp_tcp); future_mgr_.safe_clear_bad_future(); } bool IdentiySelfToReceiver(TcpSockSmartPtr sp_tcp) { Req2ReceiverTask identifytask; identifytask.sync = 0; string sendername; if(m_server_connmgr) { sendername = m_server_connmgr->GetClientName(); } MsgBusParam netmsg_param; GenerateNetMsgContent("", netmsg_param, sendername, netmsg_param); identifytask.future_id = 0; identifytask.data = netmsg_param.paramdata; identifytask.data_len = netmsg_param.paramlen; string rsp; return WriteTaskDataToReceiver(sp_tcp, identifytask, rsp); } bool WriteTaskDataToReceiver(TcpSockSmartPtr sp_tcp, const Req2ReceiverTask& task, string& rsp_content) { char syncflag = 0; uint32_t waiting_futureid = task.future_id; boost::shared_ptr<NetFuture> cur_sendmsg_rsp; if(task.sync) { syncflag = 1; cur_sendmsg_rsp = future_mgr_.safe_get_future(waiting_futureid); } //g_log.Log(lv_debug, "begin send data to receiver:%lld, sid:%u, datalen:%d, fd:%d", (int64_t)core::utility::GetTickCount(), // task.future_id, 9 + task.data_len, sp_tcp->GetFD()); uint32_t write_len = sizeof(syncflag) + sizeof(waiting_futureid) + sizeof(task.data_len) + task.data_len; boost::shared_array<char> writedata(new char[write_len]); memcpy(writedata.get(), &syncflag, sizeof(syncflag)); uint32_t waiting_futureid_n = htonl(waiting_futureid); uint32_t data_len_n = htonl(task.data_len); memcpy(writedata.get() + sizeof(syncflag), &waiting_futureid_n, sizeof(waiting_futureid_n)); memcpy(writedata.get() + sizeof(syncflag) + sizeof(waiting_futureid), (char*)&data_len_n, sizeof(data_len_n)); memcpy(writedata.get() + sizeof(syncflag) + sizeof(waiting_futureid) + sizeof(task.data_len), task.data.get(), task.data_len); if(!sp_tcp->SendData(writedata.get(), write_len)) { LOG(g_log, lv_warn, "send msg to other client failed."); rsp_content = "send data failed."; future_mgr_.safe_remove_future(waiting_futureid); return false; } // 如果要求同步发送, 则等待 bool result = true; if(task.sync) { if(!cur_sendmsg_rsp) { LOG(g_log, lv_warn, "get future session failed: %u.", waiting_futureid); result = false; } else result = cur_sendmsg_rsp->get(task.timeout, rsp_content); //g_log.Log(lv_debug, "end send sync data to client:%lld, sid:%u\n", (int64_t)core::utility::GetTickCount(), waiting_futureid); // future will erase in on-read event. //core::common::locker_guard guard(m_rsp_sendmsg_lock); //m_sendmsg_rsp_container.erase(waiting_futureid); } return result; } // 处理特定的到某个客户端的请求,retry stand for if failed to send the data , whether to update the client host info and resend the data. bool ProcessReqToReceiver(const Req2ReceiverTask& task, string& rsp_content) { LocalHostInfo destclient; if(task.clientname.empty()) { assert(!task.dest_client.host_ip.empty()); destclient = task.dest_client; } else { bool cache_exist = safe_get_cached_host_info(task.clientname, destclient); if(!cache_exist) { // 缓存中没有该客户端信息,先将该任务放入等待列表中, // 然后向服务器获取客户端主机信息 // 一旦收到服务器回来的客户端信息,会处理对应客户端的等待的任务 if(task.retry) { safe_queue_waiting_task(task); if(m_server_connmgr) m_server_connmgr->ReqReceiverInfo(task.clientname, boost::bind(&Req2ReceiverMgr::HandleRspGetClient, this, _1)); } else { LOG(g_log, lv_warn, "error send data to client, no cached client info."); future_mgr_.safe_remove_future(task.future_id); return false; } return true; } } TcpSockSmartPtr newtcp; TcpClientPool* pclient_conn_pool = &m_postmsg_client_conn_pool; // changed: do not use tcp fd to seperate different sync request, use a future_sessionid_ instead, // so we can reuse the old tcp connection. if(task.sync) { pclient_conn_pool = &m_sendmsg_client_conn_pool; } newtcp = pclient_conn_pool->GetTcpSockByDestHost(destclient.host_ip, destclient.host_port); if( !newtcp ) { SockHandler callback; // both sync sendmsg and postmsg need a onRead callback to get the future rsp data. callback.onRead = boost::bind(&Req2ReceiverMgr::Req2Receiver_onRead, this, _1, _2, _3); callback.onSend = boost::bind(&Req2ReceiverMgr::Req2Receiver_onSend, this, _1); callback.onClose = boost::bind(&Req2ReceiverMgr::Req2Receiver_onClose, this, _1); callback.onError = boost::bind(&Req2ReceiverMgr::Req2Receiver_onError, this, _1); std::string loopname; if(task.sync) { g_log.Log(lv_info, "NULL event waiter. use the default netmsgbus eventloop in the pool."); loopname = NETMSGBUS_EVLOOP_NAME; } else { loopname = "postmsg_event_loop"; } // first identify me to the receiver. //IdentiySelfToReceiver(newtcp); bool ret; ret = pclient_conn_pool->CreateTcpSock(loopname, destclient.host_ip, destclient.host_port, CLIENT_POOL_SIZE, task.timeout, callback, boost::bind(&Req2ReceiverMgr::IdentiySelfToReceiver, this, _1)); if(!ret) { // 连接失败很可能是缓存的信息已经失效,因此我们把它加到等待列表中,并向服务器请求新的信息 if(task.retry) { safe_queue_waiting_task(task); safe_remove_cached_host_info(task.clientname); if(m_server_connmgr) m_server_connmgr->ReqReceiverInfo(task.clientname, boost::bind(&Req2ReceiverMgr::HandleRspGetClient, this, _1)); } else { perror("error connect to receiver client.\n"); PostMsg("netmsgbus.client.connectreceiver.failed", CustomType2Param(task.clientname)); future_mgr_.safe_remove_future(task.future_id); return false; } return true; } newtcp = pclient_conn_pool->GetTcpSockByDestHost(destclient.host_ip, destclient.host_port); if(!newtcp) { future_mgr_.safe_remove_future(task.future_id); return false; } } if(WriteTaskDataToReceiver(newtcp, task, rsp_content)) { return true; } future_mgr_.safe_remove_future(task.future_id); return false; } // 不关心返回值的处理到客户端请求 void ProcessReqToReceiver(const Req2ReceiverTask& task) { std::string tmp; ProcessReqToReceiver(task, tmp); } // 专门用于处理向其它客户端异步的发送消息 static void * ProcessReq2ReceiverThreadFunc(void * param) { Req2ReceiverMgr * req2recv_mgr = (Req2ReceiverMgr*)param; if( req2recv_mgr == NULL ) { assert(0); return 0; } req2recv_mgr->m_req2receiver_running = true; EventLoopPool::CreateEventLoop("postmsg_event_loop"); while(true) { Req2ReceiverTaskContainerT rtask_list; { // lock core::common::locker_guard guard(req2recv_mgr->m_reqtoreceiver_locker); while (req2recv_mgr->m_reqtoreceiver_task_container.empty()) { // even if the msgbus server is down, we can still use the cached info to sendmsg to receiver. if( req2recv_mgr->m_req2receiver_terminate) { req2recv_mgr->m_req2receiver_running = false; return 0; } // wait request event. //printf("waiting the request task to client.\n"); req2recv_mgr->m_reqtoreceiver_cond.wait(req2recv_mgr->m_reqtoreceiver_locker); } rtask_list.swap( req2recv_mgr->m_reqtoreceiver_task_container ); } while(!rtask_list.empty()) { Req2ReceiverTask& rtask = rtask_list.front(); std::string thread_name; if(rtask.clientname.size() <= 2) { thread_name = "byip"; } else { thread_name = rtask.clientname.substr(rtask.clientname.size() - 2); } // in order to make sure the order of sendmsg , we should use the same thread to process the same client name sendmsg. threadpool::queue_work_task_to_named_thread(boost::bind(&Req2ReceiverMgr::ProcessReqToReceiver, req2recv_mgr, rtask), "ProcessReqToReceiver" + thread_name); rtask_list.pop_front(); } } req2recv_mgr->m_req2receiver_running = false; return 0; } private: bool safe_queue_waiting_task(const Req2ReceiverTask& req_task) { core::common::locker_guard guard(m_waitingtask_locker); m_wait2send_task_container[req_task.clientname].push_back(req_task); return true; } bool safe_get_cached_host_info(const std::string& clientname, LocalHostInfo& hostinfo) { core::common::locker_guard guard(m_cached_receiver_locker); LocalHostContainerT::const_iterator cit = m_cached_client_info.find(clientname); if(cit != m_cached_client_info.end()) { hostinfo = cit->second; return true; } return false; } void safe_remove_cached_host_info(const std::string& clientname) { core::common::locker_guard guard(m_cached_receiver_locker); m_cached_client_info.erase(clientname); } pthread_t m_req2receiver_tid; typedef std::deque< Req2ReceiverTask > Req2ReceiverTaskContainerT; Req2ReceiverTaskContainerT m_reqtoreceiver_task_container; core::common::condition m_reqtoreceiver_cond; core::common::locker m_reqtoreceiver_locker; typedef boost::unordered_map< std::string, LocalHostInfo > LocalHostContainerT; typedef boost::unordered_map< std::string, Req2ReceiverTaskContainerT > WaitingReq2ReceiverTaskT; // 一些等待客户端IP信息返回的任务队列,GetClient返回后一起发出去 WaitingReq2ReceiverTaskT m_wait2send_task_container; LocalHostContainerT m_cached_client_info; core::common::locker m_cached_receiver_locker; core::common::locker m_waitingtask_locker; FutureMgr future_mgr_; ServerConnMgr* m_server_connmgr; volatile bool m_req2receiver_running; volatile bool m_req2receiver_terminate; TcpClientPool m_sendmsg_client_conn_pool; TcpClientPool m_postmsg_client_conn_pool; }; DECLARE_SP_PTR(Req2ReceiverMgr); } #endif // end of NETMSGBUS_REQ2RECEIVER_MGR_H
// // Created by 钟奇龙 on 2019-05-10. // #include <iostream> #include <vector> #include <string> using namespace std; vector<vector<int>> getDP(string s){ vector<vector<int>> dp(s.size(),vector<int>(s.size(),0)); for(int j=1; j<s.size(); ++j){ for(int i=0; i<j; ++i){ if(i == j-1){ if(s[i] == s[j]){ dp[i][j] = 0; }else{ dp[i][j] = 1; } }else{ if(s[i] == s[j]){ dp[i][j] = dp[i+1][j-1]; }else{ dp[i][j] = min(dp[i+1][j],dp[i][j-1]) + 1; } } } } return dp; } string getPalindrome(string s){ if(s.size() == 0) return ""; vector<vector<int> > dp = getDP(s); string res(s.size() + dp[0][s.size()-1],' '); int left = 0; int right = res.size() -1; int i = 0; int j = s.size()-1; while(i <= j){ if(s[i] == s[j]){ res[left++] = s[i++]; res[right--] = s[j--]; }else{ if(dp[i+1][j] < dp[i][j-1]){ res[left++] = s[i]; res[right--] = s[i++]; }else{ res[left++] = s[j]; res[right--] = s[j--]; } } } return res; } int main(){ cout<<getPalindrome("ab")<<endl; return 0; }
class Solution { public: int search(vector<int>& nums, int target) { int n = nums.size(); if(!n) return -1; int low = 0, high = n-1; while(low < high){ int mid = (low + high)/2; if(nums[mid] > nums[high]) low = mid+1; else high = mid; } int pivot = low; low = 0; high = n-1; while(low <= high){ int mid = (low + high)/2; int realmid = (mid+pivot)%n; if(nums[realmid] == target) return realmid; if(nums[realmid] > target) high = mid-1; else low = mid+1; } return -1; } };
// Wed Aug 24 15:46:50 EDT 2016 // Evan S Weinberg // Include file for GCR #ifndef ESW_INVERTER_GCR #define ESW_INVERTER_GCR #include <string> #include <complex> using std::complex; #include "inverter_struct.h" #include "verbosity.h" // Solves lhs = A^(-1) rhs using generalized conjugate residual // Makes no assumptions about the matrix. inversion_info minv_vector_gcr(double *phi, double *phi0, int size, int max_iter, double res, void (*matrix_vector)(double*,double*,void*), void* extra_info, inversion_verbose_struct* verbosity = 0); inversion_info minv_vector_gcr(complex<double> *phi, complex<double> *phi0, int size, int max_iter, double res, void (*matrix_vector)(complex<double>*,complex<double>*,void*), void* extra_info, inversion_verbose_struct* verbosity = 0); // Solves lhs = A^(-1) with GCR(m), where m is restart_freq. inversion_info minv_vector_gcr_restart(double *phi, double *phi0, int size, int max_iter, double res, int restart_freq, void (*matrix_vector)(double*,double*,void*), void* extra_info, inversion_verbose_struct* verbosity = 0); inversion_info minv_vector_gcr_restart(complex<double> *phi, complex<double> *phi0, int size, int max_iter, double res, int restart_freq, void (*matrix_vector)(complex<double>*,complex<double>*,void*), void* extra_info, inversion_verbose_struct* verbosity = 0); #endif
#ifndef __DXRENDER_H__ #define __DXRENDER_H__ #include "UISprite.h" class CubeDynamicTeapot; class Skybox; class CubeEnvTeapot; class MyTeapot; class Water; class MSDwarf; class MSPlane; class MyMesh; class Light; class TripleWindMill_Two; class Windmill; class Star; class Shield; class Tree; class Object; class Map; class Camera; class Axis; class Grid; class DXRender { private: bool m_bGridRender; bool m_bAxisRender; bool m_bOrtho; bool m_bHelp; bool m_bCapture; public: bool m_bEndboxRender; // 마우스 위치 얻기 private: POINT m_MousePos; // 기본 함수 public: enINITERROR DataLoding(void); void SystemUpdate(void); // void RenderScene(void); void DataRelease(void); // void CaptureMap(void); // 렌더타겟 LPDIRECT3DTEXTURE9 m_pRenderTargetTexture; LPDIRECT3DSURFACE9 m_pRenderTargetSurface; LPDIRECT3DSURFACE9 m_pRenderTargetDepthSurface; LPDIRECT3DSURFACE9 m_pOrgSurface; LPDIRECT3DSURFACE9 m_pOrgDepthSurface; bool m_bUseRenderTargetRender; UISprite* m_RenderTargetUI; LPDIRECT3DTEXTURE9 m_pRenderTargetTextureGreen; LPDIRECT3DSURFACE9 m_pRenderTargetSurfaceGreen; LPDIRECT3DSURFACE9 m_pRenderTargetDepthSurfaceGreen; bool m_bGreenMode; UISprite* m_RenderTargetGreenUI; void GreateRenderTarget(void); void GeneralRender(float dTime, bool capture=false); void RenderTargetRender(float dTime); void RenderTargetLState(float dTime); void ReleaseRenderTarget(void); protected: void _HelpText(void); void _PutFPS(int _x, int _y); public: DXRender(void); virtual ~DXRender(void); ////////////////////////////////////////////////////////////////////////// // 스카이 박스 관련 Skybox* m_pSkybox; void InitSkybox(void); void RenderSkybox(void); void ReleaseSkybox(void); ////////////////////////////////////////////////////////////////////////// // UI 관련 UISprite m_UISprite[UI_MAX]; int m_YesButtonNum; int m_NoButtonNum; void InitUI(void); void UpdateUI(float dTime); // 일단, 종료박스만 적용 void RenderUI(void); ////////////////////////////////////////////////////////////////////////// // Sampling void Sampling(void); ////////////////////////////////////////////////////////////////////////// // 카메라 관련 private: Camera* m_pCamera; void CameraInit(void); void CameraUpdate( float dTime ); void CameraCubeRender(float dTime); D3DXMATRIX D3DUtil_GetCubeMapViewMatrix( DWORD dwFace ); ////////////////////////////////////////////////////////////////////////// // 그리드 관련 private: Grid* m_pGrid; enINITERROR InitGrid(void); void RenderGrid(void); void ReleaseGrid(void); ////////////////////////////////////////////////////////////////////////// // 좌표축 관련 Axis* m_pAxis; enINITERROR InitAxis(void); void RenderAxis(void); void UpdateAxis(float dTime); void ReleaseAxis(void); ////////////////////////////////////////////////////////////////////////// // 맵 관련 Map* m_pMap; enINITERROR InitMap(void); void UpdateMap(float dTime); void RenderMap(void); void ReleaseMap(void); ////////////////////////////////////////////////////////////////////////// // 히어로 관련 Object* m_pHero; enINITERROR InitHero(void); void UpdateHero(float dTime); void RenderHero(void); void ReleaseHero(void); ////////////////////////////////////////////////////////////////////////// // 나무 관련 Tree* m_pTree; enINITERROR InitTree(void); void UpdateTree(float dTime); void RenderTree(void); void ReleaseTree(void); ////////////////////////////////////////////////////////////////////////// // 나름방패(?) 관련 Shield* m_pShield; enINITERROR InitShield(void); void UpdateShield(float dTime); void RenderShield(void); void ReleaseShield(void); ////////////////////////////////////////////////////////////////////////// // 별 관련 Star* m_pStar; enINITERROR InitStar(void); void UpdateStar(float dTime); void RenderStar(void); void ReleaseStar(void); ////////////////////////////////////////////////////////////////////////// // 풍차 관련 Windmill* m_pWindmill; Windmill* m_pTripleWindmill; TripleWindMill_Two* m_pTripleWindmill_Two; enINITERROR InitWindmill(void); void UpdateWindmill(float dTime); void RenderWindmill(void); void ReleaseWindmill(void); ////////////////////////////////////////////////////////////////////////// // 라이트 관련 Light* m_pLight; void InitLight(void); void UpdateLight(float dTime); void ReleaseLight(void); D3DXCOLOR m_BackColor; int m_LState; char* m_strState[4]; ////////////////////////////////////////////////////////////////////////// // 메쉬 파일관련(비행기) MyMesh* m_pMesh; // 메쉬 파일 정보 MSPlane* m_pPlane; // 실제 비행기 정보 void InitMSPlane(void); void UpdateMSPlane(float dTime); void RenderMSPlane(float dTime); void ReleaseMSPlane(void); ////////////////////////////////////////////////////////////////////////// // 메쉬 파일관련(드워프) MyMesh* m_pMeshDwarf; MSDwarf* m_pDwarf; // 실제 비행기 정보 void InitMSDwarf(void); void UpdateMSDwarf(float dTime); void RenderMSDwarf(float dTime); void ReleaseMSDwarf(void); ////////////////////////////////////////////////////////////////////////// // 주전자 MyTeapot* m_pTeapot; void InitTeapot(void); void UpdateTeapot(float dTime); void RenderTeapot(void); void ReleaseTeapot(void); ////////////////////////////////////////////////////////////////////////// // 큐브맵 주전자 CubeEnvTeapot* m_pCubeTeapot; void InitCubeTeapot(void); void UpdateCubeTeapot(float dTime); void RenderCubeTeapot(void); void ReleaseCubeTeapot(void); ////////////////////////////////////////////////////////////////////////// // 안개 D3DXCOLOR m_FogColor; // 포그 색상 float m_fDensity; void VertexFogOn(void); void PixelFogOn(void); void FogOff(void); ////////////////////////////////////////////////////////////////////////// // 워터(스텐실) Water* m_pWater; enINITERROR InitWater(void); void UpdateWater(float dTime); void RenderWater(void); void ReleaseWater(void); void StencilObjectOn(void); void StencilObjectOff(void); ////////////////////////////////////////////////////////////////////////// // 그림자(스텐실) void ShadowStencilOn(void); void ShadowStenciloff(void); ////////////////////////////////////////////////////////////////////////// // 동적큐브맵 CubeDynamicTeapot* m_pCubeDynamicTeapot; void InitCDTeapot(void); void UpdateCDTeapot(float dTime); void RenderCDTeapot(void); void ReleaseCDTeapot(void); }; #endif
#ifndef _BASE_VECTOR_3 #define _BASE_VECTOR_3 #ifdef _PSP_VER #include <libgum.h> #else #include <D3dx9math.h> #endif class BaseVector3 { protected: BaseVector3(void) {} public: virtual ~BaseVector3(void) {} public: #ifdef _PSP_VER ScePspFVector3& GetVector(void) { return _vec; } const ScePspFVector3& GetVector(void) const { return _vec; } protected: ScePspFVector3 _vec; #else D3DXVECTOR3& GetVector(void) { return _vec; } const D3DXVECTOR3& GetVector(void) const { return _vec; } protected: D3DXVECTOR3 _vec; #endif }; #endif
class ItemAPSI_DZE : ItemCore { scope = 2; displayName = $STR_EQUIP_APSI; picture = "\dayz_epoch_c\icons\tools\ItemAPSI.paa"; descriptionShort = $STR_EQUIP_APSI_DESC; }; class ItemAPSIBroken_DZE : ItemCore { scope = 2; displayName = $STR_EQUIP_APSI_BROKEN; descriptionShort = $STR_EQUIP_APSI_BROKEN_DESC; picture = "\dayz_epoch_c\icons\tools\ItemAPSIBroken.paa"; };
#include <iostream> #include <vector> #include <algorithm> #include <string> int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(0); std::cout.tie(0); int n, m, ans = std::numeric_limits<int>::max(); std::cin >> n >> m; std::vector<std::string> board(n); for (int i = 0; i < n; ++i) { std::cin >> board[i]; } auto func = [&board](int x, int y, bool isWhite) { int cnt{}; char c[2] = {isWhite ? 'W' : 'B', isWhite ? 'B' : 'W'}; for (int i = y; i < y + 8; ++i) { for (int j = x; j < x + 8; ++j) { cnt += board[i][j] != c[(i + j) % 2]; } } return cnt; }; for (int i = 0; i + 7 < n; ++i) { for (int j = 0; j + 7 < m; ++j) { ans = std::min(ans, std::min(func(j, i, true), func(j, i, false))); } } std::cout << ans << '\n'; return 0; }
#include "InfiniteGrid.hpp" InfiniteGrid::InfiniteGrid(sf::Vector2u window_size) { //Init settings. mWindowSize = window_size; mCellSize = 16; mPosition = {0, 0}; //Init constants. mLineColor = sf::Color::Black; //Init vertex arrays. mGridLines.setPrimitiveType(sf::Lines); mGridCells.setPrimitiveType(sf::Quads); init(); } void InfiniteGrid::updateWindowSize(sf::Vector2u new_size) { mWindowSize = new_size; update(); } void InfiniteGrid::draw(sf::RenderTarget& target, sf::RenderStates states) const { target.draw(mGridCells, states); states.transform *= mGridLineTransform; target.draw(mGridLines, states); } void InfiniteGrid::init() { //Initialize the base grid lines. initLines(); //Update the lines & cells. update(); } void InfiniteGrid::initLines() { mGridLines.clear(); /* We draw grid lines to fill up the screen as if the user had set the cell size to virtually 0. We can use mGridLineTransform to scale the grid later in updateLines(). */ //Lines to draw outside the window, to prevent empty spots where lines should be. const int buffer = 10; //For every vertical line. for (int x = -buffer; x < (signed)mWindowSize.x + buffer; x++) { //Append... mGridLines.append(sf::Vertex( sf::Vector2f(x, -buffer), mLineColor)); mGridLines.append(sf::Vertex( sf::Vector2f(x, mWindowSize.y + buffer), mLineColor)); } //For every horizontal line. for (int y = -buffer; y < (signed)mWindowSize.y + buffer; y++) { //Append... mGridLines.append(sf::Vertex( sf::Vector2f(-buffer, y), mLineColor)); mGridLines.append(sf::Vertex( sf::Vector2f(mWindowSize.x + buffer, y), mLineColor)); } } void InfiniteGrid::update() { //Update everything. updateLines(); updateCells(); } void InfiniteGrid::updateLines() { mGridLineTransform = sf::Transform::Identity; //Shift over by the position modulo the cell size, divided by the cell size. mGridLineTransform.translate( (int)(mPosition.x * mCellSize) % mCellSize, (int)(mPosition.y * mCellSize) % mCellSize); //Zoom in by the CellSize mGridLineTransform.scale(mCellSize, mCellSize); } void InfiniteGrid::updateCells() { mGridCells.clear(); //Iterate over all cells. for (auto& cell : mCells) { //The actual position of the cell is cell.pos + mPosition sf::Vector2f pos = sf::Vector2f(cell.pos) + mPosition; //Ignore if we're out of bounds. sf::FloatRect bounds(-5, -5, mWindowSize.x / mCellSize + 5, mWindowSize.y / mCellSize + 5); if (!bounds.contains(pos)) { continue; } pos.x *= mCellSize; pos.y *= mCellSize; pos.x = std::floor(pos.x); pos.y = std::floor(pos.y); //Create a quad at the given position mGridCells.append(sf::Vertex( pos, cell.col)); mGridCells.append(sf::Vertex( sf::Vector2f(pos.x + mCellSize, pos.y), cell.col)); mGridCells.append(sf::Vertex( sf::Vector2f(pos.x + mCellSize, pos.y + mCellSize), cell.col)); mGridCells.append(sf::Vertex( sf::Vector2f(pos.x, pos.y + mCellSize), cell.col)); } } void InfiniteGrid::setPosition(sf::Vector2f newPos) { mPosition = newPos; update(); } sf::Vector2f InfiniteGrid::getPosition() { return mPosition; } //CELL MANIP void InfiniteGrid::setCellSize(int newSize) { mCellSize = newSize; //Constrain the cell size. if (mCellSize < 1) { mCellSize = 1; } else if (mCellSize > 500) { mCellSize = 500; } update(); } int InfiniteGrid::getCellSize() { return mCellSize; } void InfiniteGrid::setCell(Cell c) { //Check for a cell already at c.pos. If there is none, push to mCells. if (!isCell(c.pos)) { mCells.push_back(c); } else { //If this boilerplate gets excessive i'll refactor it //otherwise, shush. I don't wanna return a pointer from getCell(). *(std::find_if(mCells.begin(), mCells.end(), [c](Cell& x) { return x.pos == c.pos; })) = c; } update(); } bool InfiniteGrid::isCell(sf::Vector2i pos) { //Try to find the cell. auto found = std::find_if(mCells.begin(), mCells.end(), [pos](Cell& c) { return c.pos == pos; }); //Return if it was found or not. return (found != mCells.end()); } InfiniteGrid::Cell InfiniteGrid::getCell(sf::Vector2i pos) { //If there isn't a cell, return a white cell @ 0,0 as a placeholder. if (!isCell(pos)) { return {.pos = {0, 0}, .col = sf::Color::White}; } return *(std::find_if(mCells.begin(), mCells.end(), [pos](Cell& x) { return x.pos == pos; })); } void InfiniteGrid::clearCell(sf::Vector2i pos) { //Remove the cell with the given position. for (auto i = mCells.begin(); i != mCells.end(); ++i) { if (i->pos == pos) { mCells.erase(i); update(); return; } } } void InfiniteGrid::clear() { mCells.clear(); update(); }
// This file is for a basic string library so I do not have to use <cstring> int getStringLength(char *str) { int resultLength = 0; // loop until you find the null ending term for(int i = 0; str[i]; i++) { ++resultLength; } return resultLength; } void clearTempStringsToNull(char *str) { int length = getStringLength(str); for(int i = 0; i < length; i++) { str[i] = 0; } } //TODO: make another compreString that is case insensitive int compareString(char *fString, char *sString) // first/second String { int firstStringLength = getStringLength(fString); if(firstStringLength != getStringLength(sString)) { return 0; } for(int index = 0; index <= firstStringLength; index++) { if(fString[index] == sString[index]) { } else { return 0; } } return 1; } //NOTE(Dustin): You will have to free this memory if you use this function char* CopyString(char *strToCopy) { char *result = (char*)calloc(getStringLength(strToCopy)+1, sizeof(char)); //clearTempStringsToNull(result); for (int i = 0; strToCopy[i]; i++) { result[i] = strToCopy[i]; } return result; } // if the end user knows the length they can pass it instead of my getting it char* CopyString(char *strToCopy, int lengthOfStrToCopy) { char *result = (char*)calloc(lengthOfStrToCopy+1,sizeof(char)); //clearTempStringsToNull(result); for (int i = 0; strToCopy[i]; i++) { result[i] = strToCopy[i]; } return result; } //NOTE(Dustin): Overloaded function, the calle defines were the copy gets placed void CopyString(char *strToCopy, char *placeToPutCopiedString) { for (int i = 0; strToCopy[i]; i++) { placeToPutCopiedString[i] = strToCopy[i]; } } //NOTE(Dustin): Enduser needs to free the resultstring char* CatString(char *originString, char *strToCat) { int originLength = getStringLength(originString); int catStrLength = getStringLength(strToCat); int outstringLength = (originLength + catStrLength); int catStrIndex = 0; char *resultString = ((char*)calloc(outstringLength+1, sizeof(char))); //clearTempStringsToNull(resultString); for(int index = 0; index < outstringLength; index++) { if(index < originLength) { resultString[index] = originString[index]; } else { resultString[index] = strToCat[catStrIndex]; catStrIndex++; } } return resultString; } //Lets the enduser mangage the memory for the outputstring void CatString(char *originString, char *strToCat, char *outputString) { int originLength = getStringLength(originString); int catStrLength = getStringLength(strToCat); int outstringLength = (originLength + catStrLength); int catStrIndex = 0; for(int index = 0; index < outstringLength; index++) { if(index < originLength) { outputString[index] = originString[index]; } else { if (index < catStrLength) { outputString[index] =strToCat[catStrIndex]; catStrLength++; } else { // How did you get here } } } } //Lets the enduser pass in the lengths if he has them from something prior char* CatString(char *originString, int originLength, char *strToCat, int catStrLength) { int catStrIndex = 0; char *resultString = ((char*)calloc((originLength + catStrLength) + 1, sizeof(char))); //clearTempStringsToNull(resultString); for(int index = 0; index <= (originLength + catStrLength); index++) { if(index <= originLength) { resultString[index] = originString[index]; } if (index <= catStrLength) { resultString[index] = strToCat[catStrIndex]; catStrLength++; } } return resultString; } //TODO: create a overload of this that lets user mangage all the mermory allocs char* SplitString(char *inputString, char strDelim, char *savePlace) { //char *resultToken = ((char*)malloc(getStringLength(inputString)+1)); char *tempParsingString = ((char*)calloc(getStringLength(inputString)+1, sizeof(char))); //clearTempStringsToNull(tempParsingString); bool isParsingStringToDelim = true; int index = 0; int resultIndex = 0; if(inputString) // see if null so we know to use the savePlace as the start { CopyString(inputString, tempParsingString); clearTempStringsToNull(savePlace); } else { CopyString(savePlace, tempParsingString); } while (isParsingStringToDelim) { //TODO: make this take multiple possible delim characters if(tempParsingString[index] == strDelim) { isParsingStringToDelim = false; index++; for(int i = 0; tempParsingString[(index)]; i++) { savePlace[i] = tempParsingString[index]; index++; } } else if(tempParsingString[index]) { resultIndex++; index++; } } if(resultIndex) { char *resultToken = ((char*)calloc(resultIndex+1, sizeof(char))); //clearTempStringsToNull(resultToken); for(int i = 0; i < resultIndex; i++) { //resultToken is a pointer on the heap resultToken[i] = tempParsingString[i]; } free(tempParsingString); return resultToken; } else { free(tempParsingString); return NULL; } } void SplitString(char *inputString, char *outputString ,char strDelim, char *savePlace) { //char *resultToken = ((char*)calloc(getStringLength(inputString)+1)); char *tempParsingString = ((char*)calloc(getStringLength(inputString)+1, sizeof(char))); //clearTempStringsToNull(tempParsingString); bool isParsingStringToDelim = true; int index = 0; int resultIndex = 0; if(inputString) // see if null so we know to use the savePlace as the start { CopyString(inputString, tempParsingString); } else { CopyString(savePlace, tempParsingString); } while (isParsingStringToDelim) { //TODO: make this take multiple possible delim characters if(tempParsingString[index] == strDelim) { isParsingStringToDelim = false; index++; for(int i = 0; tempParsingString[(index)]; i++) { savePlace[i] = tempParsingString[index]; index++; } } else if(tempParsingString[index]) { resultIndex++; index++; } } if(resultIndex) { for(int i = 0; i < resultIndex; i++) { outputString[i] = tempParsingString[i]; } free(tempParsingString); } else { free(tempParsingString); } }
/* BEGIN LICENSE */ /***************************************************************************** * SKCore : the SK core library * Copyright (C) 1995-2005 IDM <skcontact @at@ idm .dot. fr> * $Id: stringlist.h,v 1.3.4.3 2005/02/17 15:29:20 krys Exp $ * * Authors: Christopher Gautier <krys @at@ idm .dot. fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Alternatively you can contact IDM <skcontact @at@ idm> for other license * contracts concerning parts of the code owned by IDM. * *****************************************************************************/ /* END LICENSE */ #ifndef __SKC_STRINGLIST_H_ #define __SKC_STRINGLIST_H_ class SKAPI SKStringList : public SKFile { public: SK_REFCOUNT_INTF_DEFAULT(SKStringList) SKStringList(); ~SKStringList(); PRUint32 GetCount(); SKERR SetFileName(const char *pszFileName, const char *pszDefaultFileName = NULL); SKERR SetListWithOneWord(const char *pszWord); SKERR IsPresent(char* pszUTF8Word, PRBool *pbResult); private: PRUint32 m_iNbWords; char* m_pszWordString; char** m_pWordList; PRBool m_bInitialized; }; #else // __SKC_STRINGLIST_H_ #error "Multiple inclusions of stringlist.h" #endif // __SKC_STRINGLIST_H_
// Colton Sellers // 20 Oct 2019 // BST class // Creates a BST to store values // Uses Node which holds the Data // Uses templates to store any type of Data // binarysearchtreee.cpp file is included at the bottom of the .h file // binarysearchtreee.cpp is part of the template, cannot be compiled separately #ifndef BST_HPP #define BST_HPP #include <algorithm> #include <cmath> #include <iomanip> #include <iostream> #include <queue> #include <sstream> #include <string> using namespace std; template<class T> class BST { // display BST tree in a human-readable format friend ostream &operator<<(ostream &out, const BST &bst) { bst.printSideways(out, bst.Root); out << endl; bst.printVertical(out, bst.Root); return out; } private: // Node for BST struct Node { T Data; struct Node *Left; struct Node *Right; }; // refer to Data type "struct Node" as Node using Node = struct Node; // root of the tree Node *Root{nullptr}; // height of a Node, nullptr is 0, Root is 1, static, no access to 'this' static int getHeight(const Node *n) { if (n == NULL) return 0; return max((getHeight(n->Left) + 1), getHeight(n->Right) + 1); } /** * print tree sideways with root on left 6 2 5 0 4 1 3 */ static ostream &printSideways(ostream &out, const Node *curr, int level = 0) { const static char sp = ' '; const static int readabilitySpaces = 4; if (!curr) return out; printSideways(out, curr->Right, ++level); out << setfill(sp) << setw(level * readabilitySpaces) << sp; out << curr->Data << endl; printSideways(out, curr->Left, level); return out; } static ostream &centeredPrint(ostream &out, int space, const string &str, char fillChar = ' ') { auto strL = static_cast<int>(str.length()); int extra = (space - strL) / 2; if (extra > 0) { out << setfill(fillChar) << setw(extra + strL) << str; out << setfill(fillChar) << setw(space - extra - strL) << fillChar; } else { out << setfill(fillChar) << setw(space) << str; } return out; } /** * print tree with the root at top * _____0______ __1___ __2___ 3 4 5 6 * **/ static ostream &printTreeLevel(ostream &out, queue<const Node *> &q, int width, int depth, int maxDepth) { const static char sp = ' '; const static char und = '_'; int nodes = 0; int maxN = pow(2, depth - 1); // NOLINT int SpaceForEachItem = width * pow(2, maxDepth - 1) / maxN; // NOLINT string bigSpace = string(static_cast<uint64_t>(SpaceForEachItem / 4), sp); // NOLINT while (nodes++ < maxN) { const Node *tp = q.front(); Node *tpL = nullptr; Node *tpR = nullptr; q.pop(); string label = "N"; if (tp) { stringstream ss; ss << tp->Data; label = ss.str(); tpL = tp->Left; tpR = tp->Right; } char filler = depth == maxDepth ? sp : und; if (depth == maxDepth) { centeredPrint(out, SpaceForEachItem, label, filler); } else { out << bigSpace; centeredPrint(out, SpaceForEachItem / 2, label, filler); out << bigSpace; q.push(tpL); q.push(tpR); } } out << endl; return out; } // helper function for displaying tree sideways, works recursively static ostream &printVertical(ostream &out, Node *curr) { const static int width = 6; // must be even if (!curr) return out << "[__]"; // figure out the maximum depth which determines how wide the tree is int maxDepth = getHeight(curr); queue<const Node *> q; q.push(curr); for (int depth = 1; depth <= maxDepth; ++depth) { printTreeLevel(out, q, width, depth, maxDepth); } return out; } // Recursively copies the tree Node *copyTree(Node *root) const { if (root == NULL) return NULL; Node *temp = new Node; temp->Data = root->Data; temp->Left = copyTree(root->Left); temp->Right = copyTree(root->Right); return temp; } // Recursively empties the tree Node *makeEmpty(Node *root) const { if (root == NULL) return NULL; { makeEmpty(root->Left); makeEmpty(root->Right); delete root; } return NULL; } // recursive helper function for counting the nodes int recursiveCount(Node *root) const { if (root == NULL) return 0; return recursiveCount(root->Left) + recursiveCount(root->Right) + 1; } // traverses the tree inOrder string inOrder(Node *p) const { string result; if (p != NULL) { if (p->Left) result += inOrder(p->Left); result += p->Data; if (p->Right) result += inOrder(p->Right); } return result; } // traverses the tree preOrder string preOrder(Node *p) const { string result; if (p != NULL) { result += p->Data; if (p->Left) result += preOrder(p->Left); if (p->Right) result += preOrder(p->Right); } return result; } // traverses the tree postOrder string postOrder(Node *p) const { string result; if (p != NULL) { if (p->Left) result += postOrder(p->Left); if (p->Right) result += postOrder(p->Right); result += p->Data; } return result; } // compare the trees and return false if they are different bool compare(Node *root) const { return recursiveCompare(Root, root); } // recursive helper for comparing all nodes bool recursiveCompare(Node *node1, Node *node2) const { bool result; if (node1 == NULL && node2 == NULL) return true; if (node2 == NULL || node1 == NULL) return false; if (node1->Data != node2->Data) return false; result = recursiveCompare(node1->Left, node2->Left) && recursiveCompare(node1->Right, node2->Right); return result; } // read the current tree of nodes to an array void readToArray(Node *node, Node *array, int index) { if (node == NULL) return; readToArray(node->Left, array, index); array[index++] = *node; readToArray(node->Right, array, index); } //Recursive function to rebalance the tree Node *recursiveRebalance(Node *nodes, int start, int end) { if (start > end) return NULL; //Make mid the root int mid = (start + end) / 2; Node *newNode = new Node; newNode->Left = NULL; newNode->Right = NULL; newNode->Data = nodes[mid].Data; // Construct inOrder newNode->Left = recursiveRebalance(nodes, start, mid - 1); newNode->Right = recursiveRebalance(nodes, mid + 1, end); return newNode; } // Recursive helper for removing a node Node *recursiveRemove(Node *root, T item) { //base case if (root == NULL) return root; // if smaller go left if (item < root->Data) root->Left = recursiveRemove(root->Left, item); // if greater go right else if (item > root->Data) root->Right = recursiveRemove(root->Right, item); // they are the same value meaning delete this one else { // if only one child on left if (root->Left == NULL) { Node *temp = root->Right; return temp; } // if only one child on right else if (root->Right == NULL) { Node *temp = root->Left; return temp; } // if two children get the smallest on right Node *temp = findMin(root->Right); // copy the new root to this node root->Data = temp->Data; // Delete its old location root->Right = recursiveRemove(root->Right, temp->Data); } return root; } // Used to find the smallest value in a tree Node *findMin(Node *root) { Node *current = root; while (current && current->Left != NULL) current = current->Left; return current; } public: // Empty constructor BST() = default; // Construct tree with root explicit BST(const T &rootItem) { add(rootItem); } // Construct tree from array BST(const T arr[], int n) { for (int i = 0; i < n; i++) { add(arr[i]); } rebalance(); } // Copy constructor BST(const BST<T> &bst) { Root = copyTree(bst.Root); } // Destructor virtual ~BST() { makeEmpty(Root); } // Returns true if no nodes in BST bool isEmpty() const { return (Root == NULL); } // Returns height of tree int getHeight() const { return getHeight(Root); } // Number of nodes in BST int numberOfNodes() const { return recursiveCount(Root); } // Add a new item, return true if successful bool add(const T &item) { // Create the new node Node *newNode = new Node; newNode->Left = NULL; newNode->Right = NULL; newNode->Data = item; // Pointers for current and parent Node *current; Node *parent = NULL; current = Root; // If the root is null make the new node the root if (current == NULL) { Root = newNode; return true; } // Find the appropriate parent while (current != NULL) { parent = current; if (newNode->Data > current->Data) current = current->Right; else current = current->Left; } // Place it in the appropriate leaf spot if (newNode->Data < parent->Data) parent->Left = newNode; else parent->Right = newNode; return true; } // Remove item, return true if successful bool remove(const T &item) { recursiveRemove(Root, item); return !contains(item); } // true if item is in BST bool contains(const T &item) const { if (isEmpty()) { return false; } Node *curr; curr = Root; while (curr != NULL) { if (curr->Data == item) return true; if (item > curr->Data) curr = curr->Right; else curr = curr->Left; } return false; } // inOrder traversal: Left-root-Right void inOrderTraverse(void visit(const T &item)) const { visit(inOrder(Root)); } // preOrder traversal: root-Left-Right void preOrderTraverse(void visit(const T &item)) const { visit(preOrder(Root)); } // postOrder traversal: Left-Right-root void postOrderTraverse(void visit(const T &item)) const { visit(postOrder(Root)); } // Rebalances the tree void rebalance() { // make dynamic array that is the size of the tree int size = numberOfNodes(); Node *nodes; nodes = new Node[size]; // read to the array readToArray(Root, nodes, 0); // empty the old tree clear(); // build the new one Root = recursiveRebalance(nodes, 0, size - 1); delete[] nodes; } // delete all nodes in tree void clear() { Root = makeEmpty(Root); } // trees are equal if they have the same structure // AND the same item values at all the nodes bool operator==(const BST<T> &other) const { return compare(other.Root); } // not == to each other bool operator!=(const BST<T> &other) const { return !compare(other.Root); } }; #endif //BST_HPP
#pragma once class memes { public: memes(); ~memes(); };
#include "../Cheat.h" HFont F::Meme; HFont F::ESP; HFont F::Watermark; HFont F::Build; HFont F::Revue; HFont F::Icon; HFont F::MenuTab; void D::SetupFonts() { //"Courier New", 14, 450, 0, 0, FONTFLAG_OUTLINE, 0, 0); <- STYLES FONT I::Surface->SetFontGlyphSet(F::Revue = I::Surface->Create_Font(), charenc("Revue"), 24, FW_DONTCARE, NULL, NULL, FONTFLAG_ANTIALIAS); I::Surface->SetFontGlyphSet(F::Meme = I::Surface->Create_Font(), charenc("MS Sans Serif"), 10, FW_DONTCARE, NULL, NULL, FONTFLAG_ANTIALIAS); I::Surface->SetFontGlyphSet(F::ESP = I::Surface->Create_Font(), charenc("Verdana"), 12, 800, NULL, NULL, FONTFLAG_ANTIALIAS | FONTFLAG_OUTLINE); I::Surface->SetFontGlyphSet(F::Watermark = I::Surface->Create_Font(), charenc("MS Sans Serif"), 12, 800, FW_DONTCARE, NULL, NULL, FONTFLAG_OUTLINE); I::Surface->SetFontGlyphSet(F::Build = I::Surface->Create_Font(), charenc("MS Sans Serif"), 12,800, FW_DONTCARE, NULL, NULL, FONTFLAG_OUTLINE); I::Surface->SetFontGlyphSet(F::MenuTab = I::Surface->Create_Font(), charenc("badcache"), 10, 500, FW_DONTCARE, NULL, NULL, FONTFLAG_DROPSHADOW | FONTFLAG_OUTLINE); } void D::DrawString( HFont font, int x, int y, Color color, DWORD alignment, const char* msg, ... ) { va_list va_alist; char buf[1024]; va_start( va_alist, msg ); _vsnprintf( buf, sizeof( buf ), msg, va_alist ); va_end( va_alist ); wchar_t wbuf[1024]; MultiByteToWideChar( CP_UTF8, 0, buf, 256, wbuf, 256 ); int r = 255, g = 255, b = 255, a = 255; color.GetColor( r, g, b, a ); int width, height; I::Surface->GetTextSize( font, wbuf, width, height ); if( alignment & FONT_RIGHT ) x -= width; if( alignment & FONT_CENTER ) x -= width / 2; I::Surface->DrawSetTextFont( font ); I::Surface->DrawSetTextColor( r, g, b, a ); I::Surface->DrawSetTextPos( x, y - height / 2 ); I::Surface->DrawPrintText( wbuf, wcslen( wbuf ) ); } void D::DrawStringUnicode( HFont font, int x, int y, Color color, bool bCenter, const wchar_t* msg, ... ) { int r = 255, g = 255, b = 255, a = 255; color.GetColor( r, g, b, a ); int iWidth, iHeight; I::Surface->GetTextSize( font, msg, iWidth, iHeight ); I::Surface->DrawSetTextFont( font ); I::Surface->DrawSetTextColor( r, g, b, a ); I::Surface->DrawSetTextPos( !bCenter ? x : x - iWidth / 2, y - iHeight / 2 ); I::Surface->DrawPrintText( msg, wcslen( msg ) ); } void D::DrawRect( int x, int y, int w, int h, Color col ) { I::Surface->DrawSetColor( col ); I::Surface->DrawFilledRect( x, y, x + w, y + h ); } void D::Rectangle(float x, float y, float w, float h, float px, Color col) { DrawRect(x, (y + h - px), w, px, col); DrawRect(x, y, px, h, col); DrawRect(x, y, w, px, col); DrawRect((x + w - px), y, px, h, col); } void D::Border(int x, int y, int w, int h, int line, Color col) { DrawRect(x, y, w, line, col); DrawRect(x, y, line, h, col); DrawRect((x + w), y, line, h, col); DrawRect(x, (y + h), (w + line), line, col); } void D::DrawRectRainbow( int x, int y, int width, int height, float flSpeed, float &flRainbow ) { Color colColor( 0, 0, 0 ); flRainbow += flSpeed; if ( flRainbow > 1.f ) flRainbow = 0.f; for ( int i = 0; i < width; i++ ) { float hue = ( 1.f / ( float ) width ) * i; hue -= flRainbow; if ( hue < 0.f ) hue += 1.f; Color colRainbow = colColor.FromHSB( hue, 1.f, 1.f ); D::DrawRect( x + i, y, 1, height, colRainbow ); } } void D::DrawRectGradientHorizontal( int x, int y, int width, int height, Color color1, Color color2 ) { float flDifferenceR = ( float ) ( color2.r( ) - color1.r( ) ) / ( float ) width; float flDifferenceG = ( float ) ( color2.g( ) - color1.g( ) ) / ( float ) width; float flDifferenceB = ( float ) ( color2.b( ) - color1.b( ) ) / ( float ) width; for ( float i = 0.f; i < width; i++ ) { Color colGradient = Color( color1.r( ) + ( flDifferenceR * i ), color1.g( ) + ( flDifferenceG * i ), color1.b( ) + ( flDifferenceB * i ), color1.a( ) ); D::DrawRect( x + i, y, 1, height, colGradient ); } } void D::DrawLine2(int x1, int y1, int x2, int y2, Color col) { int width = 0; int height = 0; I::Engine->GetScreenSize(width, height); if (!(x1 < width && x1 > 0 && y1 < height && y1 > 0) || !(x2 < width && x2 > 0 && y2 < height && y2 > 0)) return; I::Surface->DrawSetColor(col); I::Surface->DrawLine(x1, y1, x2, y2); } void D::DrawPixel( int x, int y, Color col ) { I::Surface->DrawSetColor( col ); I::Surface->DrawFilledRect( x, y, x + 1, y + 1 ); } void D::DrawOutlinedRect( int x, int y, int w, int h, Color col ) { I::Surface->DrawSetColor( col ); I::Surface->DrawOutlinedRect( x, y, x + w, y + h ); } void D::DrawOutlinedCircle( int x, int y, int r, Color col ) { I::Surface->DrawSetColor( col ); I::Surface->DrawOutlinedCircle( x, y, r, 1 ); } void D::DrawLine( int x0, int y0, int x1, int y1, Color col ) { I::Surface->DrawSetColor( col ); I::Surface->DrawLine( x0, y0, x1, y1 ); } void D::DrawCorner( int iX, int iY, int iWidth, int iHeight, bool bRight, bool bDown, Color colDraw ) { int iRealX = bRight ? iX - iWidth : iX; int iRealY = bDown ? iY - iHeight : iY; if ( bDown && bRight ) iWidth = iWidth + 1; D::DrawRect( iRealX, iY, iWidth, 1, colDraw ); D::DrawRect( iX, iRealY, 1, iHeight, colDraw ); D::DrawRect( iRealX, bDown ? iY + 1 : iY - 1, !bDown && bRight ? iWidth + 1 : iWidth, 1, Color( 0, 0, 0, 255 ) ); D::DrawRect( bRight ? iX + 1 : iX - 1, bDown ? iRealY : iRealY - 1, 1, bDown ? iHeight + 2 : iHeight + 1, Color( 0, 0, 0, 255 ) ); } void D::DrawPolygon( int count, Vertex_t* Vertexs, Color color ) { static int Texture = I::Surface->CreateNewTextureID( true ); unsigned char buffer[4] = { 255, 255, 255, 255 }; I::Surface->DrawSetTextureRGBA( Texture, buffer, 1, 1 ); I::Surface->DrawSetColor( color ); I::Surface->DrawSetTexture( Texture ); I::Surface->DrawTexturedPolygon( count, Vertexs ); } void D::DrawBox(int x, int y, int w, int h, Color color) { // top DrawRect(x, y, w, 1, color); // right DrawRect(x, y + 1, 1, h - 1, color); // left DrawRect(x + w - 1, y + 1, 1, h - 1, color); // bottom DrawRect(x, y + h - 1, w - 1, 1, color); } void D::DrawRoundedBox( int x, int y, int w, int h, int r, int v, Color col ) { std::vector<Vertex_t> p; for ( int _i = 0; _i < 3; _i++ ) { int _x = x + ( _i < 2 && r || w - r ); int _y = y + ( _i % 3 > 0 && r || h - r ); for ( int i = 0; i < v; i++ ) { int a = RAD2DEG( ( i / v ) * -90 - _i * 90 ); p.push_back( Vertex_t( Vector2D( _x + sin( a ) * r, _y + cos( a ) * r ) ) ); } } D::DrawPolygon( 4 * ( v + 1 ), &p[0], col ); /* function DrawRoundedBox(x, y, w, h, r, v, col) local p = {}; for _i = 0, 3 do local _x = x + (_i < 2 && r || w - r) local _y = y + (_i%3 > 0 && r || h - r) for i = 0, v do local a = math.rad((i / v) * - 90 - _i * 90) table.insert(p, {x = _x + math.sin(a) * r, y = _y + math.cos(a) * r}) end end surface.SetDrawColor(col.r, col.g, col.b, 255) draw.NoTexture() surface.DrawPoly(p) end */ // Notes: amount of vertexes is 4(v + 1) where v is the number of vertices on each corner bit. // I did it in lua cause I have no idea how the vertex_t struct works and i'm still aids at C++ } bool D::ScreenTransform( const Vector &point, Vector &screen ) // tots not pasted { float w; const VMatrix &worldToScreen = I::Engine->WorldToScreenMatrix( ); screen.x = worldToScreen[0][0] * point[0] + worldToScreen[0][1] * point[1] + worldToScreen[0][2] * point[2] + worldToScreen[0][3]; screen.y = worldToScreen[1][0] * point[0] + worldToScreen[1][1] * point[1] + worldToScreen[1][2] * point[2] + worldToScreen[1][3]; w = worldToScreen[3][0] * point[0] + worldToScreen[3][1] * point[1] + worldToScreen[3][2] * point[2] + worldToScreen[3][3]; screen.z = 0.0f; bool behind = false; if ( w < 0.001f ) { behind = true; screen.x *= 100000; screen.y *= 100000; } else { behind = false; float invw = 1.0f / w; screen.x *= invw; screen.y *= invw; } return behind; } bool D::WorldToScreen( const Vector &origin, Vector &screen ) { if ( !ScreenTransform( origin, screen ) ) { int ScreenWidth, ScreenHeight; I::Engine->GetScreenSize( ScreenWidth, ScreenHeight ); float x = ScreenWidth / 2; float y = ScreenHeight / 2; x += 0.5 * screen.x * ScreenWidth + 0.5; y -= 0.5 * screen.y * ScreenHeight + 0.5; screen.x = x; screen.y = y; return true; } return false; } RECT D::GetViewport() { RECT Viewport = { 0, 0, 0, 0 }; int w, h; I::Engine->GetScreenSize(w, h); Viewport.right = w; Viewport.bottom = h; return Viewport; } int D::GetStringWidth( HFont font, const char* msg, ... ) { va_list va_alist; char buf[1024]; va_start( va_alist, msg ); _vsnprintf( buf, sizeof( buf ), msg, va_alist ); va_end( va_alist ); wchar_t wbuf[1024]; MultiByteToWideChar( CP_UTF8, 0, buf, 256, wbuf, 256 ); int iWidth, iHeight; I::Surface->GetTextSize( font, wbuf, iWidth, iHeight ); return iWidth; } RECT D::GetTextSize( HFont font, const char* text) { size_t origsize = strlen(text) + 1; const size_t newsize = 100; size_t convertedChars = 0; wchar_t wcstring[newsize]; mbstowcs_s(&convertedChars, wcstring, origsize, text, _TRUNCATE); RECT rect; int x, y; I::Surface->GetTextSize(font, wcstring, x, y); rect.left = x; rect.bottom = y; rect.right = x; return rect; } void D::Draw3DBox( Vector* boxVectors, Color color ) { Vector boxVectors0, boxVectors1, boxVectors2, boxVectors3, boxVectors4, boxVectors5, boxVectors6, boxVectors7; if( D::WorldToScreen( boxVectors[ 0 ], boxVectors0 ) && D::WorldToScreen( boxVectors[ 1 ], boxVectors1 ) && D::WorldToScreen( boxVectors[ 2 ], boxVectors2 ) && D::WorldToScreen( boxVectors[ 3 ], boxVectors3 ) && D::WorldToScreen( boxVectors[ 4 ], boxVectors4 ) && D::WorldToScreen( boxVectors[ 5 ], boxVectors5 ) && D::WorldToScreen( boxVectors[ 6 ], boxVectors6 ) && D::WorldToScreen( boxVectors[ 7 ], boxVectors7 ) ) { /* .+--5---+ .8 4 6'| +--7---+' 11 9 | 10 | | ,+--|3--+ |.0 | 2' +--1---+' */ Vector2D lines[ 12 ][ 2 ]; //bottom of box lines[ 0 ][ 0 ] = { boxVectors0.x, boxVectors0.y }; lines[ 0 ][ 1 ] = { boxVectors1.x, boxVectors1.y }; lines[ 1 ][ 0 ] = { boxVectors1.x, boxVectors1.y }; lines[ 1 ][ 1 ] = { boxVectors2.x, boxVectors2.y }; lines[ 2 ][ 0 ] = { boxVectors2.x, boxVectors2.y }; lines[ 2 ][ 1 ] = { boxVectors3.x, boxVectors3.y }; lines[ 3 ][ 0 ] = { boxVectors3.x, boxVectors3.y }; lines[ 3 ][ 1 ] = { boxVectors0.x, boxVectors0.y }; lines[ 4 ][ 0 ] = { boxVectors0.x, boxVectors0.y }; lines[ 4 ][ 1 ] = { boxVectors6.x, boxVectors6.y }; // top of box lines[ 5 ][ 0 ] = { boxVectors6.x, boxVectors6.y }; lines[ 5 ][ 1 ] = { boxVectors5.x, boxVectors5.y }; lines[ 6 ][ 0 ] = { boxVectors5.x, boxVectors5.y }; lines[ 6 ][ 1 ] = { boxVectors4.x, boxVectors4.y }; lines[ 7 ][ 0 ] = { boxVectors4.x, boxVectors4.y }; lines[ 7 ][ 1 ] = { boxVectors7.x, boxVectors7.y }; lines[ 8 ][ 0 ] = { boxVectors7.x, boxVectors7.y }; lines[ 8 ][ 1 ] = { boxVectors6.x, boxVectors6.y }; lines[ 9 ][ 0 ] = { boxVectors5.x, boxVectors5.y }; lines[ 9 ][ 1 ] = { boxVectors1.x, boxVectors1.y }; lines[ 10 ][ 0 ] = { boxVectors4.x, boxVectors4.y }; lines[ 10 ][ 1 ] = { boxVectors2.x, boxVectors2.y }; lines[ 11 ][ 0 ] = { boxVectors7.x, boxVectors7.y }; lines[ 11 ][ 1 ] = { boxVectors3.x, boxVectors3.y }; for( int i = 0; i < 12; i++ ) { D::DrawLine( lines[ i ][ 0 ].x, lines[ i ][ 0 ].y, lines[ i ][ 1 ].x, lines[ i ][ 1 ].y, color ); } } } void D::DrawCircle( float x, float y, float r, float s, Color color ) { float Step = M_PI * 2.0 / s; for( float a = 0; a < ( M_PI*2.0 ); a += Step ) { float x1 = r * cos( a ) + x; float y1 = r * sin( a ) + y; float x2 = r * cos( a + Step ) + x; float y2 = r * sin( a + Step ) + y; DrawLine( x1, y1, x2, y2, color ); } } void D::ShowRadar(float X, float Y, float Size) { /*DrawOutlinedRect(X - Size / 2 - 1, Y - 1, Size + 2, Size + 2, Color(23, 23, 23, 255)); DrawOutlinedRect(X - Size / 2, Y, Size, Size, Color(90, 90, 90, 255)); DrawLine(X - Size / 2, Y + Size / 2, X + Size / 2, Y + Size / 2, Color(90, 90, 90, 255)); DrawLine(X, Y, X, Y + Size, Color(90, 90, 90, 255));*/ int centerx = X + (Size / 2); int centery = Y + (Size / 2); auto mColor = Vars.g_fBColor; auto tColor = Vars.g_fTColor; DrawRect(centerx, centery - Size, 1, 2 * Size, Color(mColor[0] * 255.0f, mColor[1] * 255.0f, mColor[2] * 255.0f, 255)); DrawRect(centerx - Size, centery, 2 * Size, 1, Color(mColor[0] * 255.0f, mColor[1] * 255.0f, mColor[2] * 255.0f, 255)); Border(centerx - Size - 6, centery - Size - 6, 2 * Size + 6, 2 * Size + 6, 6, Color(mColor[0] * 255.0f, mColor[1] * 255.0f, mColor[2] * 255.0f, 255)); //all border DrawRect(centerx - Size, centery - Size, 2 * Size, 2 * Size, Color(50, 50, 50, 220)); DrawRect(centerx, centery - Size, 1, 2 * Size, Color(mColor[0] * 255.0f, mColor[1] * 255.0f, mColor[2] * 255.0f, 255)); DrawRect(centerx - Size, centery, 2 * Size, 1, Color(mColor[0] * 255.0f, mColor[1] * 255.0f, mColor[2] * 255.0f, 255)); DrawRect(centerx - Size - 6, centery - Size - 22, 2 * Size - (Size / 235) + 12, 25, Color(mColor[0] * 255.0f, mColor[1] * 255.0f, mColor[2] * 255.0f, 255)); //upper line DrawString(F::ESP,centerx - Size + 15, centery - Size - 7, Color(tColor[0] * 255.0f, tColor[1] * 255.0f, tColor[2] * 255.0f, 255), FONT_CENTER, "Radar"); Border(centerx - Size - 6, centery - Size - 22, 2 * Size + 11, 2 * Size + 28, 1, Color(mColor[0] * 255.0f, mColor[1] * 255.0f, mColor[2] * 255.0f, 255)); Rectangle(X + (Size / 2) - 2, Y + (Size / 2) - 2, 5, 5, 1, Color(mColor[0] * 255.0f, mColor[1] * 255.0f, mColor[2] * 255.0f, 255)); DrawRect(X + (Size / 2) - 1, Y + (Size / 2) - 1, 3, 3, Color(255, 255, 255, 255)); } void D::DrawRadarEntity(float X, float Y, float RadarSize, Color _Color, Vector RadarX, Vector RadarY, QAngle Angle, int HP, bool IsFriend) { float dx = RadarX.x - RadarY.x; float dy = RadarX.y - RadarY.y; float flAngle = Angle.y + 180; float yaw = flAngle * (M_PI / 180.0); float mainViewAngles_CosYaw = cos(yaw); float mainViewAngles_SinYaw = sin(yaw); float x = dy*(-mainViewAngles_CosYaw) + dx*mainViewAngles_SinYaw; float y = dx*(-mainViewAngles_CosYaw) - dy*mainViewAngles_SinYaw; float range = RadarSize * Vars.Visuals.Radar.range; if (fabs(x)>range || fabs(y)>range) { if (y>x) { if (y>-x) { x = range*x / y; y = range; } else { y = -range*y / x; x = -range; } } else { if (y>-x) { y = range*y / x; x = range; } else { x = -range*x / y; y = -range; } } } int ScreenX = X + (RadarSize / 2) + int(x / range*float(RadarSize)); int ScreenY = Y + (RadarSize / 2) + int(y / range*float(RadarSize)); DrawRect(ScreenX - 2, ScreenY - 2, 4, 4, Color(200, 130, 0, 255)); DrawOutlinedRect(ScreenX - 4, ScreenY + 4, HP * 8 / 100, 2, _Color); }
#ifndef HPREDUCER_H #define HPREDUCER_H class HPReducer { public: HPReducer(int _HPReduce = 1); int getHPReduce() const; protected: int _HPReduce; }; #endif // HPREDUCER_H
#include<bits/stdc++.h> using namespace std; int main(){ int numOne = 0, numTwo = 1, numThree; int input = 50; cout<<"Fibonacci Series = "<<endl; cout<<numOne<<endl; cout<<numTwo<<endl; for(int i = 2; i < input; ++i){ numThree = numOne + numTwo; cout<<numThree<<endl; numOne = numTwo; numTwo = numThree; } return 0; }
#include <iostream> using namespace std; int main() { int n; cin >> n; int i = 0; int number; int max =INT8_MIN; int min = INT8_MAX; while (i < n) { cin >> number; if (number>max) { max = number; }if(number<min) { min = number; } i++; } cout << min << " " << max << endl; }
// // Created by 杨殿生 on 2020/7/30. // #include <jni.h> #include <string> #include <logutil.h> // 八种基本数据类型 从 Java 到 JNI 的类型转换操作 // JNI 的基础数据类型在 Java 的基础类型上加了一个 j // 查看源码,JNI 的基础数据类型就是在 C/C++ 基础之上,通过 typedef 声明的别名 ///* Primitive types that match up with Java equivalents. */ //typedef uint8_t jboolean; /* unsigned 8 bits */ //typedef int8_t jbyte; /* signed 8 bits */ //typedef uint16_t jchar; /* unsigned 16 bits */ //typedef int16_t jshort; /* signed 16 bits */ //typedef int32_t jint; /* signed 32 bits */ //typedef int64_t jlong; /* signed 64 bits */ //typedef float jfloat; /* 32-bit IEEE 754 */ //typedef double jdouble; /* 64-bit IEEE 754 */ extern "C" JNIEXPORT jint JNICALL Java_com_yangdainsheng_operations_JNIBasicType_callNativeInt(JNIEnv *env, jobject thiz,jint num) { LOGD("java int value is %d", num); int c_num = num * 2; return c_num; } extern "C" JNIEXPORT jbyte JNICALL Java_com_yangdainsheng_operations_JNIBasicType_callNativeByte(JNIEnv *env, jobject thiz, jbyte b) { LOGD("java byte value is %d", b); jbyte c_byte = b + (jbyte) 10; return c_byte; } extern "C" JNIEXPORT jchar JNICALL Java_com_yangdainsheng_operations_JNIBasicType_callNativeChar(JNIEnv *env, jobject thiz, jchar a) { LOGD("java char value is %c", a); jchar c_char = a + (jchar) 3; return c_char; } extern "C" JNIEXPORT jshort JNICALL Java_com_yangdainsheng_operations_JNIBasicType_callNativeShort(JNIEnv *env, jobject thiz, jshort s) { LOGD("java char value is %d", s); jshort c_short = s + (jshort) 10; return c_short; } extern "C" JNIEXPORT jlong JNICALL Java_com_yangdainsheng_operations_JNIBasicType_callNativeLong(JNIEnv *env, jobject thiz, jlong l) { LOGD("java long value is %lld", l); jlong c_long = l + 100; return c_long; } extern "C" JNIEXPORT jfloat JNICALL Java_com_yangdainsheng_operations_JNIBasicType_callNativeFloat(JNIEnv *env, jobject thiz, jfloat f) { LOGD("java float value is %f", f); jfloat c_float = f + (jfloat) 10.0; return c_float; } extern "C" JNIEXPORT jdouble JNICALL Java_com_yangdainsheng_operations_JNIBasicType_callNativeDouble(JNIEnv *env, jobject thiz, jdouble d) { LOGD("java double value is %f", d); jdouble c_double = d + 20.0; return c_double; } extern "C" JNIEXPORT jboolean JNICALL Java_com_yangdainsheng_operations_JNIBasicType_callNativeBoolean(JNIEnv *env, jobject thiz, jboolean b) { LOGD("java boolean value is %d", b); jboolean c_bool = (jboolean) !b; return c_bool; }
#include <iostream> using namespace std; //s(n)=1*2*3*...*n int dequi(int n) { if(n==1) { return 1; } return n*dequi(n-1); } int khudequi(int n) { int tong=1; for(int i=2;i<=n;i++) { tong*=i; } return tong; } int dequiduoi(int n,int x=1) { if(n==1) { return x; } return dequiduoi(n-1,x*n); } int main() { int i=5; cout<<"\n de qui ="<<dequi(i); cout<<"\n khu de qui ="<<khudequi(i); cout<<"\n de qui duoi ="<<dequiduoi(i); return 0; }
#include <iostream> #include <string> #include <vector> #include "utils.h" using namespace std; //请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。 // 例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。 // 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。 // 数字的一般形式 [+/-] .A/B./A.B/A [e/E][+/-]C // A,B,C只包含数字,[]内的是可选部分 , /表示左右二者选其一即可 class Solution { public: bool isNumeric(char* ss) { string str(ss); bool is_float = false; // true: 第一次出现小数点, false: 尚未出现小数点 bool is_science = false; // true : 第一次出现了e, false: 尚未出现e bool have_digits = false; // true: 第一次出现数字部分, false 尚未数字部分 int i = (str[0] == '-' || str[0] == '+') ? 1 : 0; for ( ; i < str.size(); ++i) { if ('0' <= str[i] && str[i] <= '9') { have_digits = true; } else if (str[i] == '.') { if (!is_float && !is_science) is_float = true; // 确保小数点不出现了e后面 else return false; // 小数点出现了多次 或 e后面出现了小数点 } else if (str[i] == 'e' || str[i] == 'E') { if (!have_digits) { // 处理形如 "e123"的边界 return false; } else if (!is_science) { // 确保e第一次出现 is_science = true; if (i < str.size() - 1) { // 处理e后面的符号位 if (str[i + 1] == '-' || str[i + 1] == '+') i++; } } else { // e出现了多次 return false; } } else { // 出现非法字符 return false; } } return !(str.back() == 'E' || str.back() == 'e'); // 处理形如 "123e"的边界 } }; int main() { auto xxd = Solution(); char* test_cases[] = {"+100", "5e2", "5e+122", "-123", "3.141596", "-1E-19", "12e", "12E", "1e+3.4", "e12", "1.2.2", ".123", "12e+5.4", "12e12e12"}; for (int i = 0; i < 14; ++i) { cout << test_cases[i] << " ==> " << xxd.isNumeric(test_cases[i]) << endl; } return 0; }
/** funtion check (a^s)*d paramater: uint64_t x return (s,d) */ pair<ll, ll > factor(ll x){ ll s=0; while((x&1)==0){ s++; x>>=1; } return {s, x}; } /** funtion pow(a,d,n) paramater: uint64_t -> a,d,n return (a^d)%n */ ll Pow(ll a, ll d, ll n){ ll res=1; a%=n; while(d){ if(d&1) res=res*a%n; a=a*a%n; d>>=1; } return res; } bool miller_check(ll s, ll d, ll n, ll a){ if(n==a) return true; ll p = Pow(a,d,n); if(p==1) return true; while(s--){ if(p==n-1) return true; p=p*p%n; } return false; } bool miller(ll n){ if(n<2) return false; if(n%2==0) return n==2; ll s,d; tie(s,d) = factor(n-1); return miller_check(s,d,n,2)&&miller_check(s,d,n,3) && miller_check(s,d,n,7) && miller_check(s,d,n,41) && miller_check(s,d,n,61); }
/*******************************************************************\ Module: Assembler -> Goto Author: Daniel Kroening, kroening@kroening.com \*******************************************************************/ #include <ansi-c/string_constant.h> #include "goto_convert_class.h" /*******************************************************************\ Function: goto_convertt::convert_asm Inputs: Outputs: Purpose: \*******************************************************************/ void goto_convertt::convert_asm(const codet &code, goto_programt &dest) { if(code.get(ID_flavor)==ID_gcc) { const irep_idt &i_str= to_string_constant(code.op0()).get_value(); std::istringstream str(i_str.as_string()); goto_programt tmp_dest; bool unknown=false; std::string line; while(std::getline(str, line)) { // remove comments std::string::size_type c=line.find("#"); if(c!=std::string::npos) line.resize(c); // remove leading whitespace c=line.find_first_not_of(" \t"); if(c!=std::string::npos) line.erase(0, c); // remove trailing whitespace c=line.find_last_not_of(" \t"); if(c!=std::string::npos) line.resize(c+1); if(line.empty()) continue; if(line=="mfence") // x86 { goto_programt::targett t=tmp_dest.add_instruction(OTHER); t->location=code.location(); t->code=codet(ID_fence); t->code.location()=code.location(); t->code.set(ID_WWfence, true); t->code.set(ID_RRfence, true); t->code.set(ID_RWfence, true); t->code.set(ID_WRfence, true); } else if(line=="sync") // Power { goto_programt::targett t=tmp_dest.add_instruction(OTHER); t->location=code.location(); t->code=codet(ID_fence); t->code.location()=code.location(); t->code.set(ID_WWfence, true); t->code.set(ID_RRfence, true); t->code.set(ID_RWfence, true); t->code.set(ID_WRfence, true); t->code.set(ID_WWcumul, true); t->code.set(ID_RWcumul, true); t->code.set(ID_RRcumul, true); t->code.set(ID_WRcumul, true); } else if(line=="lwsync") // Power { goto_programt::targett t=tmp_dest.add_instruction(OTHER); t->location=code.location(); t->code=codet(ID_fence); t->code.location()=code.location(); t->code.set(ID_WWfence, true); t->code.set(ID_RRfence, true); t->code.set(ID_RWfence, true); t->code.set(ID_WWcumul, true); t->code.set(ID_RWcumul, true); t->code.set(ID_RRcumul, true); } else if(line=="isync") // Power { goto_programt::targett t=tmp_dest.add_instruction(OTHER); t->location=code.location(); t->code=codet(ID_fence); t->code.location()=code.location(); // doesn't do anything by itself, // needs to be combined with branch } else if(line=="dmb" || line=="dsb") // ARM { goto_programt::targett t=tmp_dest.add_instruction(OTHER); t->location=code.location(); t->code=codet(ID_fence); t->code.location()=code.location(); t->code.set(ID_WWfence, true); t->code.set(ID_RRfence, true); t->code.set(ID_RWfence, true); t->code.set(ID_WRfence, true); t->code.set(ID_WWcumul, true); t->code.set(ID_RWcumul, true); t->code.set(ID_RRcumul, true); t->code.set(ID_WRcumul, true); } else if(line=="isb") // ARM { goto_programt::targett t=tmp_dest.add_instruction(OTHER); t->location=code.location(); t->code=codet(ID_fence); t->code.location()=code.location(); // doesn't do anything by itself, // needs to be combined with branch } else unknown=true; // give up } if(unknown) copy(code, OTHER, dest); else dest.destructive_append(tmp_dest); } else { // give up and copy as OTHER copy(code, OTHER, dest); } }
#include "connbas_dbox.h" #include <memory.h> #include <string.h> #include <stdio.h> #include "_syslog.h" #include "trace_memory.h" #include <time.h> #include <stdio.h> #include <sys/types.h> #include <sys/timeb.h> #include <string.h> //-------------------------------------------------------------------- // CConnbas_dbox // char *CConnbas_dbox::sql_insertIdx = "INSERT INTO idx (record_id, kword_id, iw, xpath_id, hitstart, hitlen) VALUES (?, ?, ?, ?, ?, ?)"; // char *CConnbas_dbox::sql_selectKword = "SELECT kword_id FROM kword WHERE keyword=?"; // char *CConnbas_dbox::sql_insertKword = "INSERT INTO kword (kword_id, keyword) VALUES (?, ?)"; // char *CConnbas_dbox::sql_selectXPath = "SELECT xpath_id FROM xpath WHERE xpath=?"; // char *CConnbas_dbox::sql_insertXPath = "INSERT INTO xpath (xpath_id, xpath) VALUES (?, ?)"; // char *CConnbas_dbox::sql_updateUids = "UPDATE uids SET uid=uid+? WHERE name=?"; // char *CConnbas_dbox::sql_selectUid = "SELECT uid FROM uids WHERE name=?"; // char *CConnbas_dbox::sql_insertTHit = "INSERT INTO thit (record_id, xpath_id, name, value, hitstart, hitlen) VALUES (?, ?, ?, ?, ?, ?)"; // char *CConnbas_dbox::sql_insertProp = "INSERT INTO prop (record_id, xpath_id, name, value) VALUES (?, ?, ?, ?)"; //char *CConnbas_dbox::sql_updateRecord_lock = "UPDATE record SET status=status & ~2 WHERE record_id=?"; //char *CConnbas_dbox::sql_updateRecord_unlock = "UPDATE record SET status=status | 2 WHERE record_id=?"; // extern bool scanningRecords; extern bool running; CConnbas_dbox::CConnbas_dbox(unsigned int sbas_id, const char *host, const char *user, const char *passwd, const char *szDB, unsigned int port) { this->sbas_id = sbas_id; this->open(host, user, passwd, szDB, port); this->cstmt_setRecordsToReindexTh2 = NULL; this->cstmt_updatePref_cterms = NULL; this->cstmt_selectPref_moddates = NULL; this->cstmt_insertKword = NULL; this->cstmt_selectKword = NULL; this->cstmt_insertIdx = NULL; this->cstmt_selectXPath = NULL; this->cstmt_insertXPath = NULL; this->cstmt_updateUids = NULL; this->cstmt_selectUid = NULL; this->cstmt_selectPrefs = NULL; this->cstmt_selectCterms = NULL; this->cstmt_selectKwords = NULL; this->cstmt_selectXPaths = NULL; this->cstmt_selectRecords = NULL; this->struct_buffer = NULL; this->struct_buffer_size = 0; this->thesaurus_buffer = NULL; this->thesaurus_buffer_size = 0; this->cterms_buffer = NULL; this->cterms_buffer_size = 0; this->cterms_buffer2 = NULL; this->cterms_buffer2_size = 0; this->xml_buffer = NULL; this->xml_buffer_size = 0; this->cstmt_insertTHit = NULL; this->cstmt_insertProp = NULL; this->cstmt_updateRecord_lock = NULL; this->cstmt_updateRecord_unlock = NULL; this->cstmt_needReindex = NULL; } CConnbas_dbox::~CConnbas_dbox() { this->close(); } // --------------------------------------------------------------- // UPDATE record SET status=status & ~2 WHERE record_id IN (?) // --------------------------------------------------------------- int CConnbas_dbox::setRecordsToReindexTh2(char *lrid, unsigned long lrid_len) { int ret = -1; unsigned long lencpy; if(!this->cstmt_setRecordsToReindexTh2) { if( (this->cstmt_setRecordsToReindexTh2 = this->newStmt("UPDATE record SET status=status & ~2 WHERE record_id IN (?)", 1, 0)) ) { this->cstmt_setRecordsToReindexTh2->bindi[0].buffer_type = MYSQL_TYPE_STRING; } } if(this->cstmt_setRecordsToReindexTh2) { this->cstmt_setRecordsToReindexTh2->bindi[0].buffer = (void *)(lrid); this->cstmt_setRecordsToReindexTh2->bindi[0].buffer_length = lencpy = lrid_len; this->cstmt_setRecordsToReindexTh2->bindi[0].length = &lencpy; if (this->cstmt_setRecordsToReindexTh2->bind_param() == 0) { if(this->cstmt_setRecordsToReindexTh2->execute() == 0) { // status ar updated ret = 0; } } } return(ret); } // --------------------------------------------------------------- // DELETE FROM idx WHERE record_id IN (?) // DELETE FROM prop WHERE record_id IN (?) // DELETE FROM thit WHERE record_id IN (?) // --------------------------------------------------------------- int CConnbas_dbox::delRecRefs2(char *lrid, unsigned long lrid_len) { char *sql; if( (sql = (char *)(_MALLOC_WHY(37 + lrid_len + 1 + 1, "connbas_dbox.cpp:delRecRefs2:sql")) ) ) { memcpy(sql, "DELETE FROM idx WHERE record_id IN (", 37); memcpy(sql+37, lrid, lrid_len); sql[37+lrid_len] = ')'; sql[37+lrid_len+1] = '\0'; this->execute(sql, 37+lrid_len+1); memcpy(sql+12, "prop", 4); this->execute(sql, 37+lrid_len+1); memcpy(sql+12, "thit", 4); this->execute(sql, 37+lrid_len+1); _FREE(sql); } return(0); } // --------------------------------------------------------------- // UPDATE record SET status=status & ~4 WHERE record_id IN (?) // --------------------------------------------------------------- int CConnbas_dbox::updateRecord_lock2(char *lrid, unsigned long lrid_len) { char *sql; if( (sql = (char *)(_MALLOC_WHY(57 + lrid_len + 1 + 1, "connbas_dbox.cpp:updateRecord_lock2:sql")) ) ) { memcpy(sql, "UPDATE record SET status=status & ~4 WHERE record_id IN (", 57); memcpy(sql+56, lrid, lrid_len); sql[57+lrid_len] = ')'; sql[57+lrid_len+1] = '\0'; this->execute(sql, 57+lrid_len+1); _FREE(sql); } return(0); } // --------------------------------------------------------------- // UPDATE record SET status=status | 7 WHERE record_id IN (?) // --------------------------------------------------------------- int CConnbas_dbox::updateRecord_unlock2(char *lrid, unsigned long lrid_len) { char *sql; if( (sql = (char *)(_MALLOC_WHY(56 + lrid_len + 1 + 1, "connbas_dbox.cpp:updateRecord_unlock2:sql")) ) ) { memcpy(sql, "UPDATE record SET status=status | 7 WHERE record_id IN (", 56); memcpy(sql+56, lrid, lrid_len); sql[56+lrid_len] = ')'; sql[56+lrid_len+1] = '\0'; this->execute(sql, 56+lrid_len+1); _FREE(sql); } return(0); } // --------------------------------------------------------------- // UPDATE pref SET value=?, updated_on=? WHERE prop='cterms ' // --------------------------------------------------------------- int CConnbas_dbox::updatePref_cterms(char *cterms, unsigned long cterms_size, char *moddate ) { int ret = 0; if(!this->cstmt_updatePref_cterms) { if( (this->cstmt_updatePref_cterms = this->newStmt("UPDATE pref SET value=?, updated_on=? WHERE prop='cterms'", 2, 0) ) ) { this->cstmt_updatePref_cterms->bindi[0].buffer_type = MYSQL_TYPE_STRING; this->cstmt_updatePref_cterms->bindi[1].buffer_type = MYSQL_TYPE_STRING; } else { // newStmt error ret = -3; } } if(this->cstmt_updatePref_cterms) { unsigned long l_cterms_size = cterms_size; this->cstmt_updatePref_cterms->bindi[0].buffer = (void *)cterms; this->cstmt_updatePref_cterms->bindi[0].length = &l_cterms_size; unsigned long l_moddate_size = 14; this->cstmt_updatePref_cterms->bindi[1].buffer = (void *)moddate; this->cstmt_updatePref_cterms->bindi[1].length = &l_moddate_size; if (this->cstmt_updatePref_cterms->bind_param() == 0) { if(this->cstmt_updatePref_cterms->execute() != 0) { // mysql_stmt_execute error // printf("%s\n", mysql_stmt_error(this->stmt_updatePref_cterms) ); ret = -1; } } else { // mysql_stmt_bind_param error ret = -2; } } return(ret); } // --------------------------------------------------------------- // SELECT CAST(value AS UNSIGNED), updated_on<created_on AS k FROM pref WHERE prop='indexes' LIMIT 1 // --------------------------------------------------------------- int CConnbas_dbox::selectPrefsIndexes(int *value, int *toReindex) { int ret = 0; if(this->cstmt_needReindex == NULL) { if( (this->cstmt_needReindex = this->newStmt("SELECT CAST(value AS UNSIGNED), updated_on<created_on AS k FROM pref WHERE prop='indexes' LIMIT 1", 0, 2) ) ) { this->cstmt_needReindex->bindo[0].buffer_type = MYSQL_TYPE_LONG; this->cstmt_needReindex->bindo[1].buffer_type = MYSQL_TYPE_LONG; } else { // newStmt error ret = -3; } } if(this->cstmt_needReindex) { this->cstmt_needReindex->bindo[0].buffer = value; this->cstmt_needReindex->bindo[1].buffer = toReindex; if(this->cstmt_needReindex->bind_result() == 0) { if(this->cstmt_needReindex->execute() == 0) { if(this->cstmt_needReindex->store_result() == 0) { if(this->cstmt_needReindex->fetch() == 0) { ret = 0; } this->cstmt_needReindex->free_result(); } else { ret = -7; } } else { ret = -6; } } else { ret = -5; } } else { ret = -4; } return(ret); } // --------------------------------------------------------------- // SELECT prop, UNIX_TIMESTAMP(updated_on) FROM pref WHERE prop IN('structure', 'cterms', 'thesaurus') // --------------------------------------------------------------- int CConnbas_dbox::selectPref_moddates(time_t *struct_moddate, time_t *thesaurus_moddate, time_t *cterms_moddate) { int ret = 0; if(this->cstmt_selectPref_moddates == NULL) { if( (this->cstmt_selectPref_moddates = this->newStmt("SELECT prop, UNIX_TIMESTAMP(updated_on) FROM pref WHERE prop IN('structure', 'cterms', 'thesaurus')", 0, 2)) ) { this->cstmt_selectPref_moddates->bindo[0].buffer_type = MYSQL_TYPE_STRING; this->cstmt_selectPref_moddates->bindo[1].buffer_type = MYSQL_TYPE_LONG; } else { // newStmt error ret = -3; } } if(this->cstmt_selectPref_moddates) { int my_supdated_on; char prop[65]; unsigned long prop_length; this->cstmt_selectPref_moddates->bindo[0].buffer = (void *)(prop); this->cstmt_selectPref_moddates->bindo[0].buffer_length = 64; this->cstmt_selectPref_moddates->bindo[0].length = &prop_length; this->cstmt_selectPref_moddates->bindo[0].is_null = (my_bool*)0; // data is always not null this->cstmt_selectPref_moddates->bindo[1].buffer = (void *)&my_supdated_on; if(this->cstmt_selectPref_moddates->bind_result() == 0) { if(this->cstmt_selectPref_moddates->execute() == 0) { if(this->cstmt_selectPref_moddates->store_result() == 0) { while(this->cstmt_selectPref_moddates->fetch() == 0) { //printf("%s : %ld \n", prop, my_supdated_on); if(strcmp(prop, "structure")==0) { *struct_moddate = (time_t)my_supdated_on; } else if(strcmp(prop, "thesaurus")==0) { *thesaurus_moddate = (time_t)my_supdated_on; } else if(strcmp(prop, "cterms")==0) { *cterms_moddate = (time_t)my_supdated_on; } ret = 0; } this->cstmt_selectPref_moddates->free_result(); } else { ret = -7; } } else { ret = -6; } } else { ret = -5; } } else { ret = -4; } return(ret); } // --------------------------------------------------------------- // INSERT INTO kword (kword_id, k2, lng, keyword, lng) VALUES (? , ? , ? , ?) // --------------------------------------------------------------- int CConnbas_dbox::insertKword(char *keyword, unsigned long len, char *lng, unsigned int *kword_id ) { int ret = -1; unsigned long lencpy; unsigned long lenk2; unsigned long lenlng; if(!this->cstmt_insertKword) { if( (this->cstmt_insertKword = this->newStmt("INSERT INTO kword (kword_id, k2, keyword, lng) VALUES (?, ?, ?, ?)", 4, 0)) ) { this->cstmt_insertKword->bindi[0].buffer_type = MYSQL_TYPE_LONG; this->cstmt_insertKword->bindi[1].buffer_type = MYSQL_TYPE_STRING; this->cstmt_insertKword->bindi[2].buffer_type = MYSQL_TYPE_STRING; this->cstmt_insertKword->bindi[3].buffer_type = MYSQL_TYPE_STRING; } } if(!this->cstmt_selectKword) { if( (this->cstmt_selectKword = this->newStmt("SELECT kword_id FROM kword WHERE keyword=? AND lng=?", 2, 1)) ) { this->cstmt_selectKword->bindi[0].buffer_type = MYSQL_TYPE_STRING; this->cstmt_selectKword->bindi[1].buffer_type = MYSQL_TYPE_STRING; this->cstmt_selectKword->bindo[0].buffer_type = MYSQL_TYPE_LONG; } } if( (this->cstmt_insertKword && this->cstmt_selectKword) ) { this->cstmt_insertKword->bindi[0].buffer = (void *)(kword_id); if((lenk2=len) > 2) lenk2 = 2; if((lencpy=len) > 64) lencpy = 64; if((lenlng=strlen(lng)) > 4) lenlng = 4; this->cstmt_insertKword->bindi[1].buffer = (void *)(keyword); this->cstmt_insertKword->bindi[1].buffer_length = lenk2; this->cstmt_insertKword->bindi[1].length = &lenk2; this->cstmt_insertKword->bindi[2].buffer = (void *)(keyword); this->cstmt_insertKword->bindi[2].buffer_length = lencpy; this->cstmt_insertKword->bindi[2].length = &lencpy; this->cstmt_insertKword->bindi[3].buffer = (void *)(lng); this->cstmt_insertKword->bindi[3].buffer_length = lenlng; this->cstmt_insertKword->bindi[3].length = &lenlng; if (this->cstmt_insertKword->bind_param() == 0) { if(this->cstmt_insertKword->execute() == 0) { // the kword has been created ret = 0; } else { // the insert failed : the kword (OR THE kword_id !) must already exists int r = this->cstmt_insertKword->errNo(); if(r==ER_DUP_KEY || r==ER_DUP_ENTRY) { // change his id if((lencpy=len) > 64) lencpy = 64; if((lenlng=strlen(lng)) > 4) lenlng = 4; this->cstmt_selectKword->bindi[0].buffer = (void *)(keyword); this->cstmt_selectKword->bindi[0].buffer_length = lencpy; this->cstmt_selectKword->bindi[0].length = &lencpy; this->cstmt_selectKword->bindi[1].buffer = (void *)(lng); this->cstmt_selectKword->bindi[1].buffer_length = lenlng; this->cstmt_selectKword->bindi[1].length = &lenlng; unsigned int kid; this->cstmt_selectKword->bindo[0].buffer = (void *)(&kid); if (this->cstmt_selectKword->bind_param() == 0) { if(this->cstmt_selectKword->bind_result() == 0) { if(this->cstmt_selectKword->execute() == 0) { if(this->cstmt_selectKword->store_result() == 0) { if(this->cstmt_selectKword->fetch() == 0) { *kword_id = kid; ret = 0; } this->cstmt_selectKword->free_result(); } } } } } } } } return(ret); } // --------------------------------------------------------------- // INSERT INTO idx (record_id, kword_id, iw, xpath_id, hitstart, hitlen) VALUES (?, ?, ?, ?, ?, ?) // --------------------------------------------------------------- int CConnbas_dbox::insertIdx(unsigned int record_id, unsigned int kword_id, unsigned int iw, unsigned int xpath_id, unsigned int hitstart, unsigned int hitlen, bool business) { int ret = -1; if(!this->cstmt_insertIdx) { if( (this->cstmt_insertIdx = this->newStmt("INSERT INTO idx (record_id, kword_id, iw, xpath_id, hitstart, hitlen, business) VALUES (?, ?, ?, ?, ?, ?, ?)", 7, 0)) ) { this->cstmt_insertIdx->bindi[0].buffer_type = MYSQL_TYPE_LONG; this->cstmt_insertIdx->bindi[1].buffer_type = MYSQL_TYPE_LONG; this->cstmt_insertIdx->bindi[2].buffer_type = MYSQL_TYPE_LONG; this->cstmt_insertIdx->bindi[3].buffer_type = MYSQL_TYPE_LONG; this->cstmt_insertIdx->bindi[4].buffer_type = MYSQL_TYPE_LONG; this->cstmt_insertIdx->bindi[5].buffer_type = MYSQL_TYPE_LONG; this->cstmt_insertIdx->bindi[6].buffer_type = MYSQL_TYPE_TINY; } } if(this->cstmt_insertIdx) { this->cstmt_insertIdx->bindi[0].buffer = (void *)(&record_id); this->cstmt_insertIdx->bindi[1].buffer = (void *)(&kword_id); this->cstmt_insertIdx->bindi[2].buffer = (void *)(&iw); this->cstmt_insertIdx->bindi[3].buffer = (void *)(&xpath_id); this->cstmt_insertIdx->bindi[4].buffer = (void *)(&hitstart); this->cstmt_insertIdx->bindi[5].buffer = (void *)(&hitlen); this->cstmt_insertIdx->bindi[6].buffer = (void *)(&business); if (this->cstmt_insertIdx->bind_param() == 0) { if(this->cstmt_insertIdx->execute() == 0) { ret = 0; } } } return(ret); } // --------------------------------------------------------------- // INSERT INTO xpath (xpath_id, xpath) VALUES (? , ?) // --------------------------------------------------------------- int CConnbas_dbox::insertXPath(char *xpath, unsigned int *xpath_id ) { int ret = -1; size_t len = strlen(xpath); unsigned long lencpy; if(!this->cstmt_insertXPath) { if( (this->cstmt_insertXPath = this->newStmt("INSERT INTO xpath (xpath_id, xpath) VALUES (? , ?)", 2, 0)) ) { this->cstmt_insertXPath->bindi[0].buffer_type = MYSQL_TYPE_LONG; this->cstmt_insertXPath->bindi[1].buffer_type = MYSQL_TYPE_STRING; } } if(!this->cstmt_selectXPath) { if( (this->cstmt_selectXPath = this->newStmt("SELECT xpath_id FROM xpath WHERE xpath=?", 1, 1)) ) { this->cstmt_selectXPath->bindi[0].buffer_type = MYSQL_TYPE_STRING; this->cstmt_selectXPath->bindo[0].buffer_type = MYSQL_TYPE_LONG; } } if(this->cstmt_insertXPath && this->cstmt_selectXPath) { this->cstmt_insertXPath->bindi[0].buffer = (void *)(xpath_id); if((lencpy=len) > 150) lencpy = 150; this->cstmt_insertXPath->bindi[1].buffer = (void *)(xpath); this->cstmt_insertXPath->bindi[1].buffer_length = lencpy; this->cstmt_insertXPath->bindi[1].length = &lencpy; if (this->cstmt_insertXPath->bind_param() == 0) { //printf("-------- insertXPath='", xpath); //for(unsigned int zz=0; zz<lencpy; zz++) // putchar(xpath[zz]); //printf("' -----------", xpath); if(this->cstmt_insertXPath->execute() == 0) { // thee xpath has been created ret = 0; //printf("--- ret %d -----------\n", 0); } else { // the insert has failed : the xpath must already exists int r = this->cstmt_insertXPath->errNo(); //printf("--- ret %d -----------\n", r); if(r==ER_DUP_KEY || r==ER_DUP_ENTRY) { // get his id if((lencpy=len) > 150) lencpy = 150; this->cstmt_selectXPath->bindi[0].buffer = (void *)(xpath); this->cstmt_selectXPath->bindi[0].buffer_length = lencpy; this->cstmt_selectXPath->bindi[0].length = &lencpy; int xpid; this->cstmt_selectXPath->bindo[0].buffer = (void *)(&xpid); if (this->cstmt_selectXPath->bind_param() == 0) { if(this->cstmt_selectXPath->bind_result() == 0) { if(this->cstmt_selectXPath->execute() == 0) { if(this->cstmt_selectXPath->store_result() == 0) { if(this->cstmt_selectXPath->fetch() == 0) { *xpath_id = xpid; ret = 0; } this->cstmt_selectXPath->free_result(); } } } } } } } } return(ret); } unsigned int CConnbas_dbox::getID(const char *name, unsigned int n ) { unsigned int ret = 0; size_t len = strlen(name); unsigned long lencpy; if(!this->cstmt_updateUids) { if( (this->cstmt_updateUids = this->newStmt("UPDATE uids SET uid=uid+? WHERE name=?", 2, 0)) ) { this->cstmt_updateUids->bindi[0].buffer_type = MYSQL_TYPE_LONG; this->cstmt_updateUids->bindi[1].buffer_type = MYSQL_TYPE_STRING; } } if(!this->cstmt_selectUid) { if( (this->cstmt_selectUid = this->newStmt("SELECT uid FROM uids WHERE name=?", 1, 1)) ) { this->cstmt_selectUid->bindi[0].buffer_type = MYSQL_TYPE_STRING; this->cstmt_selectUid->bindo[0].buffer_type = MYSQL_TYPE_LONG; } } if(this->cstmt_updateUids && this->cstmt_selectUid) { this->cstmt_updateUids->bindi[0].buffer = (void *)(&n); if((lencpy=len) > 16) lencpy = 16; this->cstmt_updateUids->bindi[1].buffer = (void *)(name); this->cstmt_updateUids->bindi[1].buffer_length = lencpy; this->cstmt_updateUids->bindi[1].length = &lencpy; if (this->cstmt_updateUids->bind_param() == 0) { if(mysql_query(this->mysqlCnx, "LOCK TABLES uids WRITE") == 0) { if(this->cstmt_updateUids->execute() == 0) { if((lencpy=len) > 16) lencpy = 16; this->cstmt_selectUid->bindi[0].buffer = (void *)(name); this->cstmt_selectUid->bindi[0].buffer_length = lencpy; this->cstmt_selectUid->bindi[0].length = &lencpy; unsigned int uid; this->cstmt_selectUid->bindo[0].buffer = (void *)(&uid); if (this->cstmt_selectUid->bind_param() == 0) { if(this->cstmt_selectUid->bind_result() == 0) { if(this->cstmt_selectUid->execute() == 0) { if(this->cstmt_selectUid->store_result() == 0) { if(this->cstmt_selectUid->fetch() == 0) { ret = (uid-n)+1; } this->cstmt_selectUid->free_result(); } } } } } mysql_query(this->mysqlCnx, "UNLOCK TABLES"); } } } return(ret); } void CConnbas_dbox::reindexAll() { startChrono(this->reindexChrono); this->execute((char*)"TRUNCATE idx", sizeof("TRUNCATE idx")); this->execute((char*)"TRUNCATE kword", sizeof("TRUNCATE kword")); this->execute((char*)"TRUNCATE prop", sizeof("TRUNCATE prop")); this->execute((char*)"TRUNCATE thit", sizeof("TRUNCATE thit")); this->execute((char*)"TRUNCATE xpath", sizeof("TRUNCATE xpath")); this->execute((char*)"UPDATE uids SET uid=1 WHERE name IN('KEYWORDS','XPATH')", sizeof("UPDATE uids SET uid=1 WHERE name IN('KEYWORDS','XPATH')")); this->execute((char*)"UPDATE record SET status=(status|12)&~3", sizeof("UPDATE record SET status=(status|12)&~3")); // ----------------------- load cterms char *xmlcterms; unsigned long xmlcterms_length; // if(this->selectPrefs(NULL, NULL, NULL, NULL, &xmlcterms, &xmlcterms_length) == 0) if(this->selectCterms(&xmlcterms, &xmlcterms_length) == 0) { // we have the cterms, load in libxml xmlDocPtr DocCterms; // cterms libxml xmlXPathContextPtr XPathCtx_cterms; // cterms xpath xmlKeepBlanksDefault(0); DocCterms = xmlParseMemory(xmlcterms, xmlcterms_length); if(DocCterms != NULL) { // Create xpath evaluation context XPathCtx_cterms = xmlXPathNewContext(DocCterms); if(XPathCtx_cterms != NULL) { xmlXPathObjectPtr xpathObj_cterms = NULL; xpathObj_cterms = xmlXPathEvalExpression((const xmlChar*)("/cterms/te/te[starts-with(@id,'C')]"), XPathCtx_cterms); if(xpathObj_cterms) { if(xpathObj_cterms->nodesetval) { xmlNodeSetPtr nodes_cterms = xpathObj_cterms->nodesetval; for(int i=0; i<nodes_cterms->nodeNr; i++) { xmlUnlinkNode(nodes_cterms->nodeTab[i]); xmlFreeNode(nodes_cterms->nodeTab[i]); } char moddate[16]; time_t atimer; time(&atimer); struct tm *today; today = localtime(&atimer); strftime((char *)moddate, 15, "%Y%m%d%H%M%S", today); xmlSetProp(DocCterms->children, (const xmlChar*)"modification_date", (const xmlChar *)moddate ); xmlChar *out; int outsize; xmlDocDumpFormatMemory(DocCterms, &out, &outsize, 1); this->updatePref_cterms((char *)out, outsize, moddate ); xmlFree(out); } xmlXPathFreeObject(xpathObj_cterms); } } } } this->execute((char*)"UPDATE pref SET updated_on=NOW() WHERE prop='indexes'", sizeof("UPDATE pref SET updated_on=NOW() WHERE prop='indexes'")); } // --------------------------------------------------------------- // SELECT struct,thesaurus,cterms FROM ( // (SELECT value as struct from pref where prop='structure') as t1, // (SELECT value as thesaurus from pref where prop='thesaurus') as t2, // (SELECT value as cterms from pref where prop='cterms') as t3 ) // --------------------------------------------------------------- int CConnbas_dbox::selectPrefs(char **pstruct, unsigned long *struct_length, char **pthesaurus, unsigned long *thesaurus_length, char **pcterms, unsigned long *cterms_length) { int ret = -1; char micro_buffer[3][1]; unsigned long micro_length[3]; if(!this->cstmt_selectPrefs) { if( (this->cstmt_selectPrefs = this->newStmt("SELECT p1.value AS struct, p2.value AS thesaurus, p3.value AS cterms" " FROM pref p1, pref p2, pref p3" " WHERE p1.prop='structure' AND p2.prop='thesaurus' AND p3.prop='cterms'", 0, 3)) ) { this->cstmt_selectPrefs->bindo[0].buffer_type = MYSQL_TYPE_STRING; this->cstmt_selectPrefs->bindo[1].buffer_type = MYSQL_TYPE_STRING; this->cstmt_selectPrefs->bindo[2].buffer_type = MYSQL_TYPE_STRING; } } if(this->cstmt_selectPrefs) { // ------ binding of field 'struct' if(pstruct) { // we ask for fied 'struct' : let's bind within fuction args *pstruct = NULL; *struct_length = 0; if(this->struct_buffer == NULL) { if( (this->struct_buffer = (char *)(_MALLOC_WHY(this->struct_buffer_size = 1024, "connbas_dbox.cpp:selectPrefs:struct_buffer"))) == NULL) { // malloc error return(-2); } } this->cstmt_selectPrefs->bindo[0].buffer = (void *)(this->struct_buffer); this->cstmt_selectPrefs->bindo[0].buffer_length = this->struct_buffer_size; this->cstmt_selectPrefs->bindo[0].length = struct_length; } else { // we DONT ask 'struct' : let's bind to a micro buffer this->cstmt_selectPrefs->bindo[0].buffer = (void *)(micro_buffer+0); this->cstmt_selectPrefs->bindo[0].buffer_length = 1; this->cstmt_selectPrefs->bindo[0].length = micro_length+0; } // ------ binding of field 'thesaurus' if(pthesaurus) { *pthesaurus = NULL; *thesaurus_length = 0; if(this->thesaurus_buffer == NULL) { if( (this->thesaurus_buffer = (char *)(_MALLOC_WHY(this->thesaurus_buffer_size = 4096, "connbas_dbox.cpp:selectPrefs:thesaurus_buffer"))) == NULL) { // malloc error return(-2); } } this->cstmt_selectPrefs->bindo[1].buffer = (void *)(this->thesaurus_buffer); this->cstmt_selectPrefs->bindo[1].buffer_length = this->thesaurus_buffer_size; this->cstmt_selectPrefs->bindo[1].length = thesaurus_length; } else { this->cstmt_selectPrefs->bindo[1].buffer = (void *)(micro_buffer+1); this->cstmt_selectPrefs->bindo[1].buffer_length = 1; this->cstmt_selectPrefs->bindo[1].length = micro_length+1; } // ------ binding of field 'cterms' if(pcterms) { *pcterms = NULL; *cterms_length = 0; if(this->cterms_buffer == NULL) { if( (this->cterms_buffer = (char *)(_MALLOC_WHY(this->cterms_buffer_size = 4096, "connbas_dbox.cpp:selectPrefs:cterms_buffer"))) == NULL) { // malloc error return(2); } } this->cstmt_selectPrefs->bindo[2].buffer = (void *)(this->cterms_buffer); this->cstmt_selectPrefs->bindo[2].buffer_length = this->cterms_buffer_size; this->cstmt_selectPrefs->bindo[2].length = cterms_length; } else { this->cstmt_selectPrefs->bindo[2].buffer = (void *)(micro_buffer+2); this->cstmt_selectPrefs->bindo[2].buffer_length = 1; this->cstmt_selectPrefs->bindo[2].length = micro_length+2; } if(this->cstmt_selectPrefs->execute() == 0) { if(this->cstmt_selectPrefs->store_result() == 0) { int row_count = 0; ret = 0; while(ret==0) { if(this->cstmt_selectPrefs->bind_result() != 0) { ret = 3; // bind error break; } if((ret = this->cstmt_selectPrefs->fetch()) == MYSQL_NO_DATA) { ret = 0; // normal end break; } #ifdef MYSQL_DATA_TRUNCATED if(ret == MYSQL_DATA_TRUNCATED) ret = 0; // will be catched comparing buffer sizes #endif if(ret==0) { if(pstruct && *struct_length > this->struct_buffer_size+1) { // buffer too small, realloc if( (this->struct_buffer = (char *)_REALLOC((void *)(this->struct_buffer), this->struct_buffer_size = *struct_length+1)) ) { this->cstmt_selectPrefs->bindo[0].buffer = (void *)(this->struct_buffer); this->cstmt_selectPrefs->bindo[0].buffer_length = this->struct_buffer_size; ret = this->cstmt_selectPrefs->fetchColumn(0); } else { ret = CR_OUT_OF_MEMORY; } } if(ret==0 && pthesaurus && *thesaurus_length > this->thesaurus_buffer_size+1) { // buffer too small, realloc if( (this->thesaurus_buffer = (char *)_REALLOC((void *)(this->thesaurus_buffer), this->thesaurus_buffer_size = *thesaurus_length+1)) ) { this->cstmt_selectPrefs->bindo[1].buffer = (void *)(this->thesaurus_buffer); this->cstmt_selectPrefs->bindo[1].buffer_length = this->thesaurus_buffer_size; ret = this->cstmt_selectPrefs->fetchColumn(1); } else { ret = CR_OUT_OF_MEMORY; } } if(ret==0 && pcterms && *cterms_length > this->cterms_buffer_size+1) { // buffer too small, realloc if( (this->cterms_buffer = (char *)_REALLOC((void *)(this->cterms_buffer), this->cterms_buffer_size = *cterms_length+1)) ) { this->cstmt_selectPrefs->bindo[2].buffer = (void *)(this->cterms_buffer); this->cstmt_selectPrefs->bindo[2].buffer_length = this->cterms_buffer_size; ret = this->cstmt_selectPrefs->fetchColumn(2); } else { ret = CR_OUT_OF_MEMORY; } } if(ret == 0) { if(pstruct) *pstruct = this->struct_buffer; if(pthesaurus) *pthesaurus = this->thesaurus_buffer; if(pcterms) *pcterms = this->cterms_buffer; row_count++; } } } this->cstmt_selectPrefs->free_result(); } } } return(ret); } // --------------------------------------------------------------- // SELECT value FROM pref WHERE prop='cterms' // --------------------------------------------------------------- int CConnbas_dbox::selectCterms(char **pcterms, unsigned long *cterms_length) { int ret; if(!this->cstmt_selectCterms) { if( (this->cstmt_selectCterms = this->newStmt("SELECT value FROM pref WHERE prop='cterms' LIMIT 1", 0, 1)) ) { this->cstmt_selectCterms->bindo[0].buffer_type = MYSQL_TYPE_STRING; } } if(this->cstmt_selectCterms) { *pcterms = NULL; *cterms_length = 0; if(this->cterms_buffer == NULL) { if( (this->cterms_buffer2 = (char *)(_MALLOC_WHY(this->cterms_buffer2_size = 4096, "connbas_dbox.cpp:selectCterms:cterms_buffer2"))) == NULL) { // malloc error return(CR_OUT_OF_MEMORY); } } this->cstmt_selectCterms->bindo[0].buffer = (void *)(this->cterms_buffer2); this->cstmt_selectCterms->bindo[0].buffer_length = this->cterms_buffer2_size; this->cstmt_selectCterms->bindo[0].length = cterms_length; if(this->cstmt_selectCterms->execute() == 0) { if(this->cstmt_selectCterms->store_result() == 0) { ret = 0; if(this->cstmt_selectCterms->bind_result() == 0) { if( this->cstmt_selectCterms->fetch() == 0 ) { if( *cterms_length > this->cterms_buffer2_size+1 ) { if( (this->cterms_buffer2 = (char *)_REALLOC((void *)(this->cterms_buffer2), this->cterms_buffer2_size = *cterms_length+1)) ) { this->cstmt_selectCterms->bindo[0].buffer = (void *)(this->cterms_buffer2); this->cstmt_selectCterms->bindo[0].buffer_length = this->cterms_buffer2_size; ret = this->cstmt_selectCterms->fetchColumn(0); } else { ret = CR_OUT_OF_MEMORY; } } if(ret == 0) { *pcterms = this->cterms_buffer2; } this->cstmt_selectCterms->free_result(); } else { ret = 2; // fetch error } } else { ret = 3; // bind error } } } } return(ret); } // --------------------------------------------------------------- // LOCK TABLE pref WRITE, thit WRITE // --------------------------------------------------------------- int CConnbas_dbox::lockPref() { int ret = 0; extern CSyslog zSyslog; if(mysql_real_query(this->mysqlCnx, "LOCK TABLES pref WRITE, thit WRITE", 34) != 0) { ret = -1; zSyslog._log(CSyslog::LOGL_ERR, CSyslog::LOGC_SQLERR, "%s", mysql_error(this->mysqlCnx)); } return(ret); } // --------------------------------------------------------------- // UNLOCK TABLES // --------------------------------------------------------------- int CConnbas_dbox::unlockTables() { return(mysql_real_query(this->mysqlCnx, "UNLOCK TABLES", 13)==0 ? 0 : -1); } // --------------------------------------------------------------- // SELECT kword_id, keyword FROM kword // --------------------------------------------------------------- int CConnbas_dbox::scanKwords(void ( *callBack)(CConnbas_dbox *connbas, unsigned int kword_id, char *keyword, unsigned long keyword_len, char *lng, unsigned long lng_len) ) { int ret = -1; unsigned int kword_id; char keyword[65]; unsigned long keyword_length; char lng[5]; unsigned long lng_length; if(!this->cstmt_selectKwords) { if( (this->cstmt_selectKwords = this->newStmt("SELECT kword_id, keyword, lng FROM kword", 0, 3)) ) { this->cstmt_selectKwords->bindo[0].buffer_type = MYSQL_TYPE_LONG; this->cstmt_selectKwords->bindo[1].buffer_type = MYSQL_TYPE_STRING; this->cstmt_selectKwords->bindo[2].buffer_type = MYSQL_TYPE_STRING; } } if(this->cstmt_selectKwords) { this->cstmt_selectKwords->bindo[0].buffer = (void *)(&kword_id); this->cstmt_selectKwords->bindo[1].buffer = (void *)(&keyword); this->cstmt_selectKwords->bindo[1].buffer_length = 64; this->cstmt_selectKwords->bindo[1].length = &keyword_length; this->cstmt_selectKwords->bindo[2].buffer = (void *)(&lng); this->cstmt_selectKwords->bindo[2].buffer_length = 4; this->cstmt_selectKwords->bindo[2].length = &lng_length; // Bind the result buffers if(this->cstmt_selectKwords->bind_result() == 0) { if(this->cstmt_selectKwords->execute() == 0) { if(this->cstmt_selectKwords->store_result() == 0) { ret = 0; // we will return the number of fetched kwords (WARNING : possible int overflow) while(this->cstmt_selectKwords->fetch() == 0) { if(keyword_length > 64) keyword_length = 64; keyword[keyword_length] = '\0'; if(lng_length > 4) lng_length = 4; lng[lng_length] = '\0'; (*callBack)(this, kword_id, keyword, keyword_length, lng, lng_length); ret++; } this->cstmt_selectKwords->free_result(); } } } } return(ret); } // --------------------------------------------------------------- // SELECT xpath_id, xpath FROM xpath // --------------------------------------------------------------- int CConnbas_dbox::scanXPaths(void ( *callBack)(CConnbas_dbox *connbas, unsigned int xpath_id, char *xpath, unsigned long xpath_len) ) { int ret = -1; unsigned int xpath_id; char xpath[151]; unsigned long xpath_length; if(!this->cstmt_selectXPaths) { if( (this->cstmt_selectXPaths = this->newStmt("SELECT xpath_id, xpath FROM xpath", 0, 2)) ) { this->cstmt_selectXPaths->bindo[0].buffer_type = MYSQL_TYPE_LONG; this->cstmt_selectXPaths->bindo[1].buffer_type = MYSQL_TYPE_STRING; } } if(this->cstmt_selectXPaths) { this->cstmt_selectXPaths->bindo[0].buffer = (void *)(&xpath_id); this->cstmt_selectXPaths->bindo[1].buffer = (void *)(&xpath); this->cstmt_selectXPaths->bindo[1].buffer_length = 150; this->cstmt_selectXPaths->bindo[1].length = &xpath_length; // Bind the result buffers if(this->cstmt_selectXPaths->bind_result() == 0) { if(this->cstmt_selectXPaths->execute() == 0) { if(this->cstmt_selectXPaths->store_result() == 0) { ret = 0; // we will return the number of fetched xpath (WARNING : possible int overflow) while(this->cstmt_selectXPaths->fetch() == 0) { if(xpath_length > 150) xpath_length = 150; xpath[xpath_length] = '\0'; (*callBack)(this, xpath_id, xpath, xpath_length); ret++; } this->cstmt_selectXPaths->free_result(); } } } } return(ret); } // --------------------------------------------------------------- // SELECT record_id, xml FROM record ORDER BY record_id // --------------------------------------------------------------- int CConnbas_dbox::scanRecords(void (*callBack)(CConnbas_dbox *connbas, unsigned int record_id, char *xml, unsigned long len), SBAS_STATUS *sbas_status ) { int ret = -1; unsigned long xml_length; unsigned int record_id; int prefsIndexes_value = 1; int prefsIndexes_toReindex = 0; //printf("-- 1\n"); if(!this->cstmt_selectRecords) { //printf("-- 1-2\n"); if( (this->cstmt_selectRecords = this->newStmt("SELECT record_id, xml FROM record WHERE (status & 7) IN (4,5,6) ORDER BY record_id ASC", 0, 2)) ) { //printf("-- 1-3\n"); this->cstmt_selectRecords->bindo[0].buffer_type = MYSQL_TYPE_LONG; this->cstmt_selectRecords->bindo[1].buffer_type = MYSQL_TYPE_STRING; } } if(this->cstmt_selectRecords) { // ------ bind 'record_id' this->cstmt_selectRecords->bindo[0].buffer = (void *)(&record_id); // ------ bind 'xml' if(this->xml_buffer == NULL) { if( (this->xml_buffer = (char *)(_MALLOC_WHY(this->xml_buffer_size = 4096, "connbas_dbox.cpp:scanRecords:xml"))) == NULL) { // malloc error return(-2); } } this->cstmt_selectRecords->bindo[1].buffer = (void *)(this->xml_buffer); this->cstmt_selectRecords->bindo[1].buffer_length = this->xml_buffer_size; this->cstmt_selectRecords->bindo[1].length = &xml_length; if(this->cstmt_selectRecords->execute() == 0) { if(this->cstmt_selectRecords->store_result() == 0) { int row_count = 0; ret = 0; int checkReindexN = 0; while(ret==0 && this->cstmt_selectRecords->bind_result() == 0 && this->cstmt_selectRecords->fetch() == 0) { if(*sbas_status == SBAS_STATUS_TOSTOP ) // if the thread must stop, no more callback continue; // but fetch() till the end // check prefs 'indexes' every 20 records if(prefsIndexes_toReindex == 0 && prefsIndexes_value>0 && checkReindexN++ > 20) { this->selectPrefsIndexes(&prefsIndexes_value, &prefsIndexes_toReindex); checkReindexN = 0; } if(prefsIndexes_toReindex > 0 || prefsIndexes_value==0) // if the whole base has been asked to reindex, or indexation suspended { // no more callback continue; // but fetch() till the end } if(xml_length > this->xml_buffer_size+1) { if( (this->xml_buffer = (char *)_REALLOC((void *)(this->xml_buffer), this->xml_buffer_size = xml_length+1)) ) { this->cstmt_selectRecords->bindo[1].buffer = (void *)(this->xml_buffer); this->cstmt_selectRecords->bindo[1].buffer_length = this->xml_buffer_size; // printf("buffer reallocated to %ld\n", xmlbuffer_length); ret = this->cstmt_selectRecords->fetchColumn(1); } else { // malloc error ret = CR_OUT_OF_MEMORY; } } if(ret == 0) { (*callBack)(this, record_id, this->xml_buffer, xml_length); row_count++; } } this->cstmt_selectRecords->free_result(); } } } return(ret); } // --------------------------------------------------------------- // INSERT INTO thit (record_id, xpath_id, name, value, hitstart, hitlen) VALUES (?, ?, ?, ?, ?, ?) // --------------------------------------------------------------- int CConnbas_dbox::insertTHit(unsigned int record_id, unsigned int xpath_id, char *name, char *value, unsigned int hitstart, unsigned int hitlen, bool business ) { int ret = -1; if(!this->cstmt_insertTHit) { if( (this->cstmt_insertTHit = this->newStmt("INSERT INTO thit (record_id, xpath_id, name, value, hitstart, hitlen, business) VALUES (?, ?, ?, ?, ?, ?, ?)", 7, 0)) ) { this->cstmt_insertTHit->bindi[0].buffer_type = MYSQL_TYPE_LONG; this->cstmt_insertTHit->bindi[1].buffer_type = MYSQL_TYPE_LONG; this->cstmt_insertTHit->bindi[2].buffer_type = MYSQL_TYPE_STRING; this->cstmt_insertTHit->bindi[3].buffer_type = MYSQL_TYPE_STRING; this->cstmt_insertTHit->bindi[4].buffer_type = MYSQL_TYPE_LONG; this->cstmt_insertTHit->bindi[5].buffer_type = MYSQL_TYPE_LONG; this->cstmt_insertTHit->bindi[6].buffer_type = MYSQL_TYPE_TINY; } } if(this->cstmt_insertTHit) { this->cstmt_insertTHit->bindi[0].buffer = (void *)(&record_id); this->cstmt_insertTHit->bindi[1].buffer = (void *)(&xpath_id); unsigned long len_name = strlen((char *)name); if(len_name > 32) len_name = 32; this->cstmt_insertTHit->bindi[2].buffer = (void *)(name); this->cstmt_insertTHit->bindi[2].buffer_length = len_name; this->cstmt_insertTHit->bindi[2].length = &len_name; unsigned long len_value = strlen((char *)value); if(len_value > 100) len_value = 100; this->cstmt_insertTHit->bindi[3].buffer = (void *)(value); this->cstmt_insertTHit->bindi[3].buffer_length = len_value; this->cstmt_insertTHit->bindi[3].length = &len_value; this->cstmt_insertTHit->bindi[4].buffer = (void *)(&hitstart); this->cstmt_insertTHit->bindi[5].buffer = (void *)(&hitlen); this->cstmt_insertTHit->bindi[6].buffer = (void *)(&business); if (this->cstmt_insertTHit->bind_param() == 0) { if(this->cstmt_insertTHit->execute() == 0) { // the thit has been created ret = 0; } } } return(ret); } // --------------------------------------------------------------- // INSERT INTO prop (record_id, xpath_id, name, value, type, business) VALUES (?, ?, ?, ?, ?, ?) // --------------------------------------------------------------- int CConnbas_dbox::insertProp(unsigned int record_id, unsigned int xpath_id, char *name, char *value, int type, bool business) { int ret = -1; if(!this->cstmt_insertProp) { if( (this->cstmt_insertProp = this->newStmt("INSERT INTO prop (record_id, xpath_id, name, value, type, business) VALUES (?, ?, ?, ?, ?, ?)", 6, 0)) ) { this->cstmt_insertProp->bindi[0].buffer_type = MYSQL_TYPE_LONG; this->cstmt_insertProp->bindi[1].buffer_type = MYSQL_TYPE_LONG; this->cstmt_insertProp->bindi[2].buffer_type = MYSQL_TYPE_STRING; this->cstmt_insertProp->bindi[3].buffer_type = MYSQL_TYPE_STRING; this->cstmt_insertProp->bindi[4].buffer_type = MYSQL_TYPE_LONG; this->cstmt_insertProp->bindi[5].buffer_type = MYSQL_TYPE_TINY; } } if(this->cstmt_insertProp) { this->cstmt_insertProp->bindi[0].buffer = (void *)(&record_id); this->cstmt_insertProp->bindi[1].buffer = (void *)(&xpath_id); unsigned long len_name = strlen(name); if(len_name > 32) len_name = 32; this->cstmt_insertProp->bindi[2].buffer = (void *)(name); this->cstmt_insertProp->bindi[2].buffer_length = len_name; this->cstmt_insertProp->bindi[2].length = &len_name; unsigned long len_value = strlen(value); if(len_value > 100) len_value = 100; this->cstmt_insertProp->bindi[3].buffer = (void *)(value); this->cstmt_insertProp->bindi[3].buffer_length = len_value; this->cstmt_insertProp->bindi[3].length = &len_value; this->cstmt_insertProp->bindi[4].buffer = (void *)(&type); this->cstmt_insertProp->bindi[5].buffer = (void *)(&business); if (this->cstmt_insertProp->bind_param() == 0) { if(this->cstmt_insertProp->execute() == 0) { ret = 0; } } } return(ret); } // --------------------------------------------------------------- // UPDATE record SET status=status & ~4 WHERE record_id=? // --------------------------------------------------------------- int CConnbas_dbox::updateRecord_lock(unsigned int record_id) { int ret = -1; if(!this->cstmt_updateRecord_lock) { if( (this->cstmt_updateRecord_lock = this->newStmt("UPDATE record SET status=status & ~4 WHERE record_id=?", 1, 0)) ) { this->cstmt_updateRecord_lock->bindi[0].buffer_type = MYSQL_TYPE_LONG; } } if(this->cstmt_updateRecord_lock) { this->cstmt_updateRecord_lock->bindi[0].buffer = (void *)(&record_id); if (this->cstmt_updateRecord_lock->bind_param() == 0) { if(this->cstmt_updateRecord_lock->execute() == 0) { ret = 0; } } } return(ret); } // --------------------------------------------------------------- // UPDATE record SET status=status | 4 WHERE record_id=? // --------------------------------------------------------------- int CConnbas_dbox::updateRecord_unlock(unsigned int record_id) { int ret = -1; if(!this->cstmt_updateRecord_unlock) { if( (this->cstmt_updateRecord_unlock = this->newStmt("UPDATE record SET status=status | 4 WHERE record_id=?", 1, 0)) ) { this->cstmt_updateRecord_unlock->bindi[0].buffer_type = MYSQL_TYPE_LONG; } } if(this->cstmt_updateRecord_unlock) { this->cstmt_updateRecord_unlock->bindi[0].buffer = (void *)(&record_id); if (this->cstmt_updateRecord_unlock->bind_param() == 0) { if(this->cstmt_updateRecord_unlock->execute() == 0) { ret = 0; } } } return(ret); } void CConnbas_dbox::close() { this->isok = false; if(this->struct_buffer) { _FREE(this->struct_buffer); this->struct_buffer = NULL; this->struct_buffer_size = 0; } if(this->thesaurus_buffer) { _FREE(this->thesaurus_buffer); this->thesaurus_buffer = NULL; this->thesaurus_buffer_size = 0; } if(this->cterms_buffer) { _FREE(this->cterms_buffer); this->cterms_buffer = NULL; this->cterms_buffer_size = 0; } if(this->xml_buffer) { _FREE(this->xml_buffer); this->xml_buffer = NULL; this->xml_buffer_size = 0; } CConnbas::close(); }
// // Created by roy on 12/27/18. // #ifndef PROJECTPART1_EQUALCOMMAND_H #define PROJECTPART1_EQUALCOMMAND_H #include "Command.h" #include "DataReaderServer.h" #include "DataSender.h" #include "Utilities.h" #include "SmallLexer.h" /** * This command is the "assign" command which receives a variable and * a value (represented by an expression or variables), and puts the calculated * value in fitting symbol with the symbol map. */ #define EQUAL_COMMAND_JUMP 3 #define SECOND_CHAR 1 #define LAST_CHAR 2 #define BUFFER_SIZE 256 class EqualCommand : public Command { string expressionString, varName; DataReaderServer *dataReaderServer; DataSender *dataSender; Utilities util; SmallLexer smallLexer; public: EqualCommand(DataReaderServer *dataReaderServer, DataSender *dataSender, string varName, string expressionString, SymbolTable *symbolTable); virtual int execute(); }; #endif //PROJECTPART1_EQUALCOMMAND_H
/* *@author: profgrammer *@date: 09-01-2019 */ #include <bits/stdc++.h> using namespace std; int ncr(int n, int r){ if(n < r || n < 0 || r < 0) return 0; if(n == r || r == 0) return 1; return ncr(n-1,r) + ncr(n-1, r-1); } int main() { int n; cin>>n; for(int i = 0;i <= n;i++){ for(int j = 0;j <= i;j++) cout<<ncr(i,j)<<" "; cout<<endl; } }
/* Copyright 2021 University of Manchester Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http: // www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once namespace orkhestrafs::dbmstodspi::query_acceleration_constants { /// How much data can fit the datapath concurrently in the same cycle. const int kDatapathWidth = 16; /// How many cycles of data the datapath fits. const int kDatapathLength = 32; /// How many integers are transfered with a DDR burst. const int kDdrBurstSize = 512; /// How many integers are transferred in a single clock cycle. const int kDdrSizePerCycle = 4; /// What is the limit for the amount of records that can be transferred. const int kMaxRecordsPerDDRBurst = 32; /// How much memory space is required for a single module. const int kModuleSize = 1024 * 1024; /// How many IO streams can there be concurrently. const int kMaxIOStreamCount = 16; /// Which vector contains what information for query node I/O stream params. const struct StreamParamDefinition { int kStreamParamCount = 4; int kProjectionOffset = 0; int kDataTypesOffset = 1; int kDataSizesOffset = 2; int kChunkCountOffset = 3; } kIOStreamParamDefs; } // namespace orkhestrafs::dbmstodspi::query_acceleration_constants
/* -*-C++-*- */ /* * Copyright 2016 EU Project ASAP 619706. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef INCLUDED_ASAP_WORD_BANK_H #define INCLUDED_ASAP_WORD_BANK_H #include <sys/stat.h> #include <sys/mman.h> #include <fcntl.h> #include <string> #include <list> #include <map> #include <utility> #include <memory> #include "asap/traits.h" #include "asap/hashtable.h" #include "asap/hashindex.h" namespace asap { template<typename Container> typename std::enable_if< !is_specialization_of<hash_table, Container>::value && !is_specialization_of<hash_index, Container>::value && !is_specialization_of<std::vector, Container>::value>::type reserve_space( Container & c, size_t s ) { } template<typename Container, typename = typename std::enable_if< is_specialization_of<hash_table, Container>::value || is_specialization_of<hash_index, Container>::value>::type> void reserve_space( Container & c, size_t s ) { size_t s2 = s; size_t m = 1; while( (s2 & (s2-1)) != 0 ) { s2 &= ~m; m <<= 1; } c.rehash( s2<<1 ); } template<typename Container, typename std::enable_if< is_specialization_of<std::vector, Container>::value>::type* = nullptr> void reserve_space( Container & c, size_t s ) { c.reserve( s ); } class word_bank_base { // list of all chunks of text std::list<std::shared_ptr<char>> m_store; public: word_bank_base() { } word_bank_base( const word_bank_base & wb ) : m_store( wb.m_store ) { } word_bank_base( word_bank_base && wb ) : m_store( std::move(wb.m_store) ) { } word_bank_base & operator = ( const word_bank_base & wb ) { m_store = wb.m_store; return *this; } word_bank_base & operator = ( word_bank_base && wb ) { m_store = std::move( wb.m_store ); return *this; } ~word_bank_base() { clear(); } void swap( word_bank_base & wb ) { m_store.swap( wb.m_store ); } void clear( const char * ) { } void clear() { // if( m_store.size() > 0 ) // std::cerr << "Unlinking " << m_store.size() << " chunks of text\n"; // Delete chunks of data held in word_bank m_store.clear(); } void copy( const word_bank_base & rhs ) { // This creates shared_ptr<>'s pointing to the same blocks // as the rhs container m_store.insert( m_store.end(), rhs.m_store.cbegin(), rhs.m_store.cend() ); } void copy( word_bank_base && rhs ) { // unued? // This creates shared_ptr<>'s pointing to the same blocks // as the rhs container m_store.splice( m_store.end(), std::move(rhs.m_store) ); } void move( word_bank_base & rhs ) { m_store.splice( m_store.end(), rhs.m_store ); } void reduce( word_bank_base & rhs ) { // Move all chunks over from rhs to lhs // Using a list will be more efficient for this operation. m_store.splice( m_store.end(), rhs.m_store ); } void enregister( std::shared_ptr<char> & buf ) { m_store.push_back( buf ); } protected: char * push_chunk( size_t size ) { return push_chunk( new char[size] ); } char * push_chunk( char * chunk ) { std::shared_ptr<char> sp( chunk, std::default_delete<char[]>() ); m_store.push_back( sp ); return chunk; } }; class word_bank_managed : public word_bank_base { public: static const bool is_managed = true; static const bool is_allocated = false; private: const size_t m_chunk; size_t m_avail; char * m_next; public: word_bank_managed( size_t chunk = 4096 ) : m_chunk( chunk ), m_avail( 0 ), m_next( nullptr ) { } word_bank_managed( const word_bank_managed & wb ) : word_bank_base( wb ), m_chunk( wb.m_chunk ), m_avail( 0 ), m_next( nullptr ) { } word_bank_managed( word_bank_managed && wb ) : word_bank_base( std::move((word_bank_base&&)wb) ), m_chunk( std::move(wb.m_chunk) ), m_avail( std::move(wb.m_avail) ), m_next( std::move(wb.m_next) ) { wb.m_avail = 0; wb.m_next = nullptr; } word_bank_managed & operator = ( const word_bank_managed & wb ) { word_bank_base::operator = ( wb ); return *this; } word_bank_managed & operator = ( word_bank_managed && wb ) { word_bank_base::operator = ( std::move(wb) ); return *this; } ~word_bank_managed() { clear(); } void clear( const char * ) { } void clear() { word_bank_base::clear(); m_avail = 0; m_next = nullptr; } // Push len characters starting at p and '\0' delimit it const char * store( const char * p, size_t len ) { // Doesn't deal with fragmentation if( m_avail < len+1 ) push_chunk( std::max( len+1, m_chunk ) ); char * where = m_next; strncpy( where, p, len ); where[len] = '\0'; m_avail -= len + 1; m_next += len + 1; return where; } // Build up a string const char * append( const char * start, const char * str, size_t len ) { // Erase prior string terminator if( start ) { --m_next; ++m_avail; } // Make sure there is enough space // Doesn't deal with fragmentation if( m_avail < len+1 ) { char * was_next = m_next; push_chunk( std::max( start ? was_next-start+len+1 : len+1, m_chunk ) ); // copy what we had so we can extend it if( start ) { start = store( start, was_next - start ); --m_next; ++m_avail; } } // Store the string but return original pointer, unless if it is the // start of the word const char * where = store( str, len ); return start ? start : where; } // Note: this is dangerous to use... void erase( const char * w ) { char * ww = const_cast<char *>( w ); m_avail += m_next - ww; m_next = ww; } private: void push_chunk( size_t len ) { m_next = word_bank_base::push_chunk( len ); m_avail = len; } }; class word_bank_malloc : public word_bank_base { public: static const bool is_managed = true; static const bool is_allocated = true; word_bank_malloc() { } word_bank_malloc( const word_bank_malloc & wb ) { } word_bank_malloc( word_bank_malloc && wb ) { } word_bank_malloc & operator = ( const word_bank_malloc & wb ) { return *this; } word_bank_malloc & operator = ( word_bank_malloc && wb ) { return *this; } ~word_bank_malloc() { } void clear( const char * p ) { // std::cerr << "clear " << (void*)p << ": -" << p << "-\n"; delete[] p; } void clear() { } // Push len characters starting at p and '\0' delimit it const char * store( const char * p, size_t len ) { char * s = new char[len+1]; strncpy( s, p, len ); s[len] = '\0'; // std::cerr << "store " << (void*)s << ": -" << s << "-\n"; return s; } // Build up a string const char * append( const char * start, const char * str, size_t len ) { assert( 0 ); return 0; } // Note: this is dangerous to use... void erase( const char * w ) { // std::cerr << "erase " << (void*)w << ": -" << w << "-\n"; delete[] w; } }; // A word bank with all words taken from a pre-defined block of text. // The block of text is modified with '\0' to indicate end of string. class word_bank_pre_alloc : public word_bank_base { public: static const bool is_managed = false; static const bool is_allocated = false; public: word_bank_pre_alloc( char * store = 0 ) { if( store ) push_chunk( store ); } word_bank_pre_alloc( const word_bank_pre_alloc & wb ) : word_bank_base( wb ) { } word_bank_pre_alloc( word_bank_pre_alloc && wb ) : word_bank_base( std::move( (word_bank_base&&)wb ) ) { } word_bank_pre_alloc & operator = ( const word_bank_pre_alloc & wb ) { word_bank_base::operator = ( wb ); return *this; } word_bank_pre_alloc & operator = ( word_bank_pre_alloc && ) = delete; ~word_bank_pre_alloc() { clear(); } void clear( const char * ) { } void clear() { // Parent class has ownership over m_store chunk word_bank_base::clear(); } // Push len characters starting at p and '\0' delimit it const char * store( char * p, size_t len ) { p[len] = '\0'; return p; } // Build up a string const char * append( const char * start, const char * str, size_t len ) { assert( 0 ); return 0; } void erase( const char * w ) { } }; template<typename IndexTy, typename WordBankTy> class word_map; template<typename IndexTy, typename WordBankTy> class word_container { public: typedef IndexTy index_type; typedef WordBankTy word_bank_type; protected: index_type m_words; word_bank_type m_storage; public: word_container() { } // Try to avoid use of the copy constructor word_container( const word_container & wc ) : m_words( wc.m_words ), m_storage( wc.m_storage ) { } word_container( word_container && wc ) : m_words( std::move(wc.m_words) ), m_storage( std::move(wc.m_storage) ) { } ~word_container() { clear(); } // template<typename... Args> // word_container( Args... args ) : m_storage( args... ) { } const word_bank_type & storage() const { return m_storage; } word_bank_type & storage() { return m_storage; } size_t size() const { return m_words.size(); } bool empty() const { return m_words.empty(); } void clear() { m_storage.clear(); m_words.clear(); } void swap( word_container & wb ) { m_words.swap( wb.m_words ); m_storage.swap( wb.m_storage ); } void enregister( std::shared_ptr<char> & buf ) { m_storage.enregister( buf ); } // Build up a string const char * append( const char * start, const char * str, size_t len ) { return m_storage.append( start, str, len ); } void erase( const char * w ) { m_storage.erase( w ); } }; template<typename Type> struct value_cmp { bool operator () ( const Type & v1, const Type & v2 ) const { return v1 < v2; } }; template<> struct value_cmp<const char *> { bool operator () ( const char * v1, const char * v2 ) const { return strcmp( v1, v2 ) < 0; } }; // TODO: make parameter for word_list/merge/reduce operator template<typename ValueTyL, typename ValueTyR> struct word_cmp { bool operator () ( const ValueTyL & v1, const ValueTyR & v2 ) const { return value_cmp<ValueTyL>( v1, v2 ); } }; template<typename ValueTyL, typename ValueTyR> struct pair_cmp { bool operator () ( const ValueTyL & v1, const ValueTyR & v2 ) const { return value_cmp<decltype(v1.first)>()( v1.first, v2.first ); // return strcmp( v1.first, v2.first ) < 0; } }; template<typename ValueTyL, typename ValueTyR> struct pair_add_reducer { void operator () ( ValueTyL & v1, const ValueTyR & v2 ) const { v1.second += v2.second; } }; template<typename ValueTyL, typename ValueTyR> struct pair_nonzero_reducer { void operator () ( ValueTyL & v1, const ValueTyR & v2 ) const { v1.second += ( v2.second > 0 ); } }; // IndexTy is sequential container such std::vector, std::deque, std::list // Assumed is that IndexTy::value_type is const char * template<typename IndexTy, typename WordBankTy> class word_list : public word_container<IndexTy,WordBankTy> { typedef word_container<IndexTy,WordBankTy> base_type; public: typedef IndexTy index_type; typedef WordBankTy word_bank_type; typedef typename index_type::value_type value_type; typedef typename index_type::const_iterator const_iterator; typedef typename index_type::iterator iterator; static const bool is_managed = word_bank_type::is_managed; static const bool is_allocated = word_bank_type::is_allocated; private: template<typename OtherIndexTy> struct is_compatible : std::integral_constant< bool, std::is_same<typename OtherIndexTy::key_type, typename value_type::first_type>::value && std::is_same<typename OtherIndexTy::mapped_type, typename value_type::second_type>::value> { }; public: word_list() { } template<typename... Args> word_list( Args... args ) : base_type( args... ) { } ~word_list() { clear(); } void clear() { // std::cerr << "clearing word_container...\n"; if( is_allocated ) { for( typename index_type::const_iterator I=this->m_words.cbegin(), E=this->m_words.cend(); I != E; ++I ) { this->m_storage.clear( *I ); } } word_container<index_type, word_bank_type>::clear(); } void mark_clear() { this->m_words.clear(); } // Memorize the word, but do not store it in the word list const char * memorize( char * p, size_t len ) { return this->m_storage.store( p, len ); } // Memorize the word and store it in the word list as well const char * index( char * p, size_t len ) { const char * w = this->m_storage.store( p, len ); this->m_words.push_back( w ); return w; } // Only store in index void index_only( const char * w ) { this->m_words.push_back( w ); } void resize( size_t sz ) { this->m_words.resize( sz ); } void reserve( size_t sz ) { this->m_words.reserve( sz ); } // Retrieve n-th word. // Depends on pure list (like in directory list - single word) // or used as associative container (key-value pairs). // Need to differentiate word_list from word_value_list... auto operator[] ( size_t n ) const -> decltype(this->m_words[n]) { return this->m_words[n]; } iterator begin() { return this->m_words.begin(); } iterator end() { return this->m_words.end(); } const_iterator cbegin() const { return this->m_words.cbegin(); } const_iterator cend() const { return this->m_words.cend(); } const_iterator find( const char * w ) const { value_type val = std::make_pair( w, typename value_type::second_type() ); pair_cmp<value_type,value_type> cmp; for( const_iterator I=cbegin(), E=cend(); I != E; ++I ) if( !cmp( *I, val ) && !cmp( val, *I ) ) return I; return cend(); } const_iterator binary_search( const char * w ) const { value_type val = std::make_pair( w, typename value_type::second_type() ); // val.first = w; // only if std::pair std::pair<const_iterator,bool> ret = binary_search( cbegin(), cend(), this->size(), val, pair_cmp<value_type,value_type>() ); return ret.second ? ret.first : cend(); } #if 0 // TODO: this is imprecise: // + Not clear if range [I,E) is all of wb, or only part of it // + As such, copying over all of wb may be too much // + Ideally want to translate all strings into existing word bank // At the moment, this is used only with *this initially empty, so this // is ok. template<typename InputIterator> void insert( InputIterator I, InputIterator E, const word_bank_base & wb ) { std::for_each( I, E, [&]( typename index_type::value_type & val ) { this->m_words.push_back( val ); } ); // this->m_words.insert( I, E ); this->m_storage.copy( wb ); wc.mark_clear(); } template<typename OtherIndexTy, typename OtherWordBankTy> typename std::enable_if<is_compatible<OtherIndexTy>::value>::type insert( const word_map<OtherIndexTy,OtherWordBankTy> & wc ) { this->m_words.insert( this->m_words.end(), wc.cbegin(), wc.cend() ); this->m_storage.copy( wc.storage() ); wc.mark_clear(); } template<typename OtherIndexTy, typename OtherWordBankTy> typename std::enable_if<is_compatible<OtherIndexTy>::value>::type insert( word_map<OtherIndexTy,OtherWordBankTy> && wc ) { this->m_words.insert( this->m_words.end(), std::make_move_iterator(wc.begin()), std::make_move_iterator(wc.end()) ); this->m_storage.copy( std::move(wc.storage()) ); wc.mark_clear(); } #endif // 0 // Add in all contents from rhs into lhs (*this) and clear rhs // Assumes both *this and rhs are sorted by key (whatever sorting function // is used ...) void reduce( word_list & rhs ) { // TODO: consider parallel merge (std::experimental::parallel_merge) // TODO: Better with move iterators? core_reduce( rhs.begin(), rhs.end(), rhs.size(), rhs.storage(), word_cmp<value_type,value_type>() ); rhs.clear(); } private: template<class InputIt, class Compare> void core_reduce(InputIt first2, InputIt last2, size_t size2, const word_bank_base & storage, Compare cmp) { this->m_words.reserve( this->m_words.size() + size2 ); std::copy( first2, last2, this->m_words.end() ); this->m_storage.copy( std::move(storage) ); } template<class InputIt, class OutputIt, class Compare, class Reduce> OutputIt core_merge(iterator first1, iterator last1, InputIt first2, InputIt last2, OutputIt d_first, Compare cmp, Reduce reduce) { for (; first1 != last1; ++d_first) { if (first2 == last2) { return std::copy(first1, last1, d_first); } if( !cmp(*first1, *first2) ) { if( !cmp(*first2, *first1) ) { // equal auto val = *first1; reduce( val, *first2 ); *d_first = val; ++first1; } else { *d_first = *first2; } ++first2; } else { *d_first = *first1; ++first1; } } return std::copy(first2, last2, d_first); } // iterator is a RandomAccess iterator // n == std::distance( I, E ); template<typename InputIt, typename Compare> std::pair<InputIt,bool> binary_search( InputIt I, InputIt E, size_t n, const value_type & val, Compare cmp ) const { if( n == 0 ) return std::make_pair( E, false ); else if( n == 1 ) return std::make_pair( I, !cmp( *I, val ) && !cmp( val, *I ) ); size_t l = n/2; InputIt M = std::next( I, l ); if( cmp( *M, val ) ) // *M < val, search right sub-range return binary_search( M, E, n-l, val, cmp ); else if( cmp( val, *M ) ) // val < *M search left sub-range return binary_search( I, M, l, val, cmp ); else // val == *M return std::make_pair( M, true ); } }; // IndexTy is sequential container such std::vector, std::deque, std::list // Assumed is that IndexTy::value_type is const char * template<typename IndexTy, typename WordBankTy> class kv_list : public word_container<IndexTy,WordBankTy> { typedef word_container<IndexTy,WordBankTy> base_type; public: typedef IndexTy index_type; typedef WordBankTy word_bank_type; typedef typename index_type::value_type value_type; typedef typename value_type::first_type key_type; typedef typename value_type::second_type mapped_type; typedef typename index_type::const_iterator const_iterator; typedef typename index_type::iterator iterator; static const bool is_managed = word_bank_type::is_managed; static const bool is_allocated = word_bank_type::is_allocated; static const bool can_sort = true; static const bool always_sorted = false; private: template<typename OtherIndexTy> struct is_compatible : std::integral_constant< bool, std::is_same<typename OtherIndexTy::key_type, key_type>::value && std::is_same<typename OtherIndexTy::mapped_type, mapped_type>::value> { }; public: kv_list() { } template<typename... Args> kv_list( Args... args ) : base_type( args... ) { } ~kv_list() { clear(); } void clear() { // std::cerr << "clearing word_container...\n"; if( is_allocated ) { for( typename index_type::const_iterator I=this->m_words.cbegin(), E=this->m_words.cend(); I != E; ++I ) { this->m_storage.clear( I->first ); } } word_container<index_type, word_bank_type>::clear(); } void mark_clear() { this->m_words.clear(); } // Memorize the word, but do not store it in the word list const char * memorize( char * p, size_t len ) { return this->m_storage.store( p, len ); } // Memorize the word and store it in the word list as well const char * index( char * p, size_t len ) { const char * w = this->m_storage.store( p, len ); this->m_words.push_back( w ); return w; } // Only store in index void index_only( const char * w ) { this->m_words.push_back( w ); } void resize( size_t sz ) { this->m_words.resize( sz ); } void reserve( size_t sz ) { this->m_words.reserve( sz ); } // Retrieve n-th word item in the container. const value_type & operator[] ( size_t n ) const { return this->m_words[n]; } iterator begin() { return this->m_words.begin(); } iterator end() { return this->m_words.end(); } const_iterator cbegin() const { return this->m_words.cbegin(); } const_iterator cend() const { return this->m_words.cend(); } const_iterator find( const char * w ) const { value_type val = std::make_pair( w, typename value_type::second_type() ); pair_cmp<value_type,value_type> cmp; for( const_iterator I=cbegin(), E=cend(); I != E; ++I ) if( !cmp( *I, val ) && !cmp( val, *I ) ) return I; return cend(); } const_iterator binary_search( const char * w ) const { value_type val = std::make_pair( w, typename value_type::second_type() ); // val.first = w; // only if std::pair std::pair<const_iterator,bool> ret = binary_search( cbegin(), cend(), this->size(), val, pair_cmp<value_type,value_type>() ); return ret.second ? ret.first : cend(); } // TODO: this is imprecise: // + Not clear if range [I,E) is all of wb, or only part of it // + As such, copying over all of wb may be too much // + Ideally want to translate all strings into existing word bank // At the moment, this is used only with *this initially empty, so this // is ok. #if 0 // to find out where called from, if at all template<typename InputIterator> void insert( InputIterator I, InputIterator E, const word_bank_base & wb ) { assert( this->m_words.empty() ); std::for_each( I, E, [&]( typename index_type::value_type & val ) { this->m_words.push_back( val ); } ); // this->m_words.insert( I, E ); this->m_storage.copy( wb ); wc.mark_clear(); } #endif template<typename OtherIndexTy, typename OtherWordBankTy> typename std::enable_if<is_compatible<OtherIndexTy>::value>::type insert( word_map<OtherIndexTy,OtherWordBankTy> && wc ) { assert( this->m_words.empty() ); this->m_words.insert( this->m_words.end(), wc.cbegin(), wc.cend() ); this->m_storage.move( wc.storage() ); wc.mark_clear(); } /* template<typename OtherIndexTy, typename OtherWordBankTy> typename std::enable_if<is_compatible<OtherIndexTy>::value>::type insert( word_map<OtherIndexTy,OtherWordBankTy> && wc ) { assert( this->m_words.empty() ); this->m_words.insert( this->m_words.end(), wc.begin(), wc.end() ); // std::make_move_iterator(wc.begin()), // std::make_move_iterator(wc.end()) ); this->m_storage.copy( std::move(wc.storage()) ); wc.clear(); } */ template<typename OtherIndexTy, typename OtherWordBankTy> void count_presence( const word_map<OtherIndexTy,OtherWordBankTy> & rhs ) { typedef typename word_map<OtherIndexTy,OtherWordBankTy>::value_type other_value_type; core_reduce( rhs.cbegin(), rhs.cend(), rhs.size(), pair_cmp<value_type,value_type>(), pair_nonzero_reducer<value_type,other_value_type>() ); if( !is_managed ) this->m_storage.copy( rhs.storage() ); } template<typename OtherIndexTy, typename OtherWordBankTy> void count_presence( const kv_list<OtherIndexTy,OtherWordBankTy> & rhs ) { typedef typename kv_list<OtherIndexTy,OtherWordBankTy>::value_type ::second_type other_value_type; core_reduce( rhs.cbegin(), rhs.cend(), rhs.size(), pair_cmp<value_type,value_type>(), pair_nonzero_reducer<value_type,other_value_type>() ); if( !is_managed ) this->m_storage.copy( rhs.storage() ); } // Add in all contents from rhs into lhs (*this) and clear rhs // Assumes both *this and rhs are sorted by key (whatever sorting function // is used ...) void reduce( kv_list & rhs ) { // TODO: consider parallel merge (std::experimental::parallel_merge) // TODO: Better with move iterators? core_reduce( rhs.begin(), rhs.end(), rhs.size(), pair_cmp<value_type,value_type>(), pair_add_reducer<value_type,value_type>() ); this->m_storage.move( rhs.storage() ); rhs.clear(); } private: template<class InputIt, class Compare, class Reduce> void core_reduce(InputIt first2, InputIt last2, size_t size2, Compare cmp, Reduce reduce) { index_type joint; joint.reserve( this->size() + size2 ); // worst case core_merge( this->begin(), this->end(), first2, last2, std::back_inserter(joint), pair_cmp<value_type,value_type>(), pair_add_reducer<value_type,value_type>() ); this->m_words.swap( joint ); } template<class InputIt, class OutputIt, class Compare, class Reduce> OutputIt core_merge(iterator first1, iterator last1, InputIt first2, InputIt last2, OutputIt d_first, Compare cmp, Reduce reduce) { for (; first1 != last1; ++d_first) { if (first2 == last2) { return std::copy(first1, last1, d_first); } if( !cmp(*first1, *first2) ) { if( !cmp(*first2, *first1) ) { // equal auto val = *first1; reduce( val, *first2 ); *d_first = val; ++first1; } else { // take element from first2, need to duplicate string if( word_bank_type::is_managed ) { // record new copy size_t len = strlen( first2->first ); key_type w = memorize( (char*)first2->first, len ); *d_first = value_type( w, first2->second ); } else { *d_first = *first2; } } ++first2; } else { *d_first = *first1; ++first1; } } // take elements from first2, need to duplicate strings for( ; first2 != last2; ++first2, ++d_first ) { if( word_bank_type::is_managed ) { // record new copy size_t len = strlen( first2->first ); key_type w = memorize( (char*)first2->first, len ); *d_first = value_type( w, first2->second ); } else { *d_first = *first2; } } return d_first; } // iterator is a RandomAccess iterator // n == std::distance( I, E ); template<typename InputIt, typename Compare> std::pair<InputIt,bool> binary_search( InputIt I, InputIt E, size_t n, const value_type & val, Compare cmp ) const { if( n == 0 ) return std::make_pair( E, false ); else if( n == 1 ) return std::make_pair( I, !cmp( *I, val ) && !cmp( val, *I ) ); size_t l = n/2; InputIt M = std::next( I, l ); if( cmp( *M, val ) ) // *M < val, search right sub-range return binary_search( M, E, n-l, val, cmp ); else if( cmp( val, *M ) ) // val < *M search left sub-range return binary_search( I, M, l, val, cmp ); else // val == *M return std::make_pair( M, true ); } }; // class kv_list template<typename ValueTyL, typename ValueTyR> struct mapped_add_reducer { void operator () ( ValueTyL & v1, const ValueTyR & v2 ) { v1 += v2; } }; template<typename ValueTyL, typename ValueTyR> struct mapped_nonzero_reducer { void operator () ( ValueTyL & v1, const ValueTyR & v2 ) { v1 += ( v2 > 0 ); } }; // IndexTy is a map such as std::map, std::unordered_map where the mapped_type // is an integral type, or any type supporting: // - default constructor // - operator ++ () // - operator += () template<typename IndexTy, typename WordBankTy> class word_map : public word_container<IndexTy,WordBankTy> { typedef word_container<IndexTy,WordBankTy> base_type; public: typedef IndexTy index_type; typedef WordBankTy word_bank_type; typedef typename index_type::key_type key_type; typedef typename index_type::mapped_type mapped_type; typedef typename index_type::value_type value_type; typedef typename index_type::const_iterator const_iterator; typedef typename index_type::iterator iterator; static const bool is_managed = word_bank_type::is_managed; static const bool is_allocated = word_bank_type::is_allocated; static const bool can_sort = false; static const bool always_sorted = is_specialization_of<std::map, index_type>::value; template<typename OtherIndexTy, typename OtherWordBankTy> friend class word_map; private: template<typename OtherIndexTy> struct is_compatible : std::integral_constant< bool, std::is_same<typename OtherIndexTy::key_type, key_type>::value && std::is_same<typename OtherIndexTy::mapped_type, mapped_type>::value> { }; template<typename OtherIndexTy> struct is_compatible_kv : std::integral_constant< bool, std::is_same<typename OtherIndexTy::value_type::first_type, key_type>::value && std::is_same<typename OtherIndexTy::value_type::second_type, mapped_type>::value> { }; public: word_map() { } word_map( const word_map & wm ) : base_type( *static_cast<const base_type *>( &wm ) ) { } word_map( word_map && wm ) : base_type( std::move(wm) ) { } // template<typename... Args> // word_map( Args... args ) : base_type( args... ) { } ~word_map() { clear(); } void clear() { // std::cerr << "clearing word_container...\n"; if( is_allocated ) { for( typename index_type::const_iterator I=this->m_words.cbegin(), E=this->m_words.cend(); I != E; ++I ) { this->m_storage.clear( I->first ); } } word_container<index_type,word_bank_type>::clear(); } void mark_clear() { this->m_words.clear(); } // Memorize the word, but do not store it in the word list const char * memorize( char * p, size_t len ) { return this->m_storage.store( p, len ); } // Memorize the word and store it in the word list as well const char * index( char * p, size_t len ) { const char * w = this->m_storage.store( p, len ); iterator found = this->m_words.find( w ); if( found != this->m_words.end() ) { ++found->second; this->m_storage.erase( w ); } else { ++ (this->m_words[w]); } return w; } // Build up a string std::pair<const char *, char *> build( const std::pair<const char *, char *> & where, const char * str ) { return this->m_storage.build( str ); } // Retrieve the n-th word. Linear time complexity // Note: used in output. const char * operator[] ( size_t n ) const { return std::next( cbegin(), n )->first; } iterator begin() { return this->m_words.begin(); } iterator end() { return this->m_words.end(); } const_iterator cbegin() const { return this->m_words.cbegin(); } const_iterator cend() const { return this->m_words.cend(); } void reserve( size_t n ) { reserve_space( this->m_words, n ); } iterator find( const key_type & w ) { return this->m_words.find( w ); } const_iterator find( const key_type & w ) const { return this->m_words.find( w ); } // For reference and ease of substituting types in templates iterator binary_search( const key_type & w ) { return find( w ); } const_iterator binary_search( const key_type & w ) const { return find( w ); } template<typename OtherIndexTy, typename OtherWordBankTy> void count_presence( const word_map<OtherIndexTy,OtherWordBankTy> & rhs ) { typedef typename word_map<OtherIndexTy,OtherWordBankTy>::mapped_type other_mapped_type; core_reduce( rhs.cbegin(), rhs.cend(), rhs.storage(), mapped_nonzero_reducer<mapped_type,other_mapped_type>() ); if( !is_managed ) this->m_storage.copy( rhs.storage() ); } template<typename OtherIndexTy, typename OtherWordBankTy> void count_presence( const kv_list<OtherIndexTy,OtherWordBankTy> & rhs ) { typedef typename word_list<OtherIndexTy,OtherWordBankTy>::value_type ::second_type other_mapped_type; core_reduce( rhs.cbegin(), rhs.cend(), rhs.storage(), mapped_nonzero_reducer<mapped_type,other_mapped_type>() ); if( !is_managed ) this->m_storage.copy( rhs.storage() ); } template<typename OtherIndexTy, typename OtherWordBankTy> typename std::enable_if<is_compatible<OtherIndexTy>::value>::type insert( word_map<OtherIndexTy,OtherWordBankTy> && wc ) { this->m_words.insert( wc.cbegin(), wc.cend() ); this->m_storage.move( wc.storage() ); wc.mark_clear(); } /* template<typename OtherIndexTy, typename OtherWordBankTy> typename std::enable_if<is_compatible<OtherIndexTy>::value>::type insert( word_map<OtherIndexTy,OtherWordBankTy> && wc ) { // std::make_move_iterator on wc.begin() and end() segfaults // if wc is a asap::hashtable this->m_words.insert( wc.begin(), wc.end() ); this->m_storage.copy( std::move(wc.storage()) ); wc.clear(); } */ /* template<typename OtherIndexTy, typename OtherWordBankTy> typename std::enable_if<is_compatible_kv<OtherIndexTy>::value>::type insert( const kv_list<OtherIndexTy,OtherWordBankTy> & wc ) { this->m_words.insert( wc.cbegin(), wc.cend() ); this->m_storage.move( wc.storage() ); wc.mark_clear(); } */ template<typename OtherIndexTy, typename OtherWordBankTy> typename std::enable_if<is_compatible_kv<OtherIndexTy>::value>::type insert( kv_list<OtherIndexTy,OtherWordBankTy> && wc ) { this->m_words.insert( wc.begin(), wc.end() ); this->m_storage.move( wc.storage() ); wc.mark_clear(); } // Add in all contents from rhs into lhs and clear rhs void reduce( word_map<index_type, word_bank_type> & rhs ) { // Assumes Reducer is commutative -- results in errors. Why? // if( this->size() < rhs.size() ) // this->swap( rhs ); core_reduce( rhs.cbegin(), rhs.cend(), rhs.storage(), mapped_add_reducer<mapped_type,mapped_type>() ); rhs.mark_clear(); } private: // Copy in all contents from rhs into *this. // Retains rhs. Shares word storage. template<typename InputIterator, typename Reducer> void core_reduce( InputIterator Is, InputIterator E, const word_bank_base & storage, Reducer reducer_fn ) { bool any_word_new = false; #if 1 // This version is good for the pre_alloc word bank, but not for // the managed one as we struggle with translating strings. for( InputIterator I=Is; I != E; ++I ) { // Speculatively map word into our own word bank. This is necessary // only if the word was not present yet. In case of pre_alloc // word bank, this is unnecessary anyway (no-op). // The reason hereto is that we cannot overwrite the key // once the element has been inserted. Unless if we force it // with a const_cast... key_type w = I->first; if( word_bank_type::is_managed ) { // record new copy of word size_t len = strlen( I->first ); w = memorize( (char*)I->first, len ); } // Note: reconstruct value_type from key and mapped_type as // we may call this function with different mapped_types value_type keyval( w, mapped_type(0) ); reducer_fn( keyval.second, I->second ); // Lookup translated word and std::pair<iterator,bool> ret = this->m_words.insert( keyval ); if( ret.second ) { // Value was freshly inserted. Now remap the string. // Unseen words need to be stored into container of LHS // unless if we retain all files in memory, then do it // en bloc and skip the storage step (no-op but for strlen). any_word_new = true; // const char * w = I->first; // if( word_bank_type::is_managed ) // record new copy of word // ret.first->first = memorize( (char*)w, len ); // strlen( w ) ); } else { // Not inserted - key already occurred reducer_fn( ret.first->second, I->second ); if( word_bank_type::is_managed ) // erase redundant copy of word this->erase( w ); // TODO: consider dropping the old word and setting I->first // to ret.first->first; also need to push the appropriate // parts of storage onto I's storage. This is hard // (appropriate parts) and we currently don't have the // container. Reason to do this is so we can reduce // memory footprint. } } #elif 0 iterator hint = this->m_words.begin(); typename index_type::key_compare cmp = this->m_words.key_comp(); for( other_const_iterator I=rhs.cbegin(), E=rhs.cend(); I != E; ++I ) { iterator L = this->m_words.lower_bound( I->first ); // Found with equal keys? if( L != this->m_words.end() && !cmp( L->first, I->first ) && !cmp( I->first, L->first ) ) reducer_fn( L->second, I->second ); else { iterator where = L; if( where == this->m_words.end() ) where = hint; // Unseen words need to be stored into container of LHS // unless if we retain all files in memory, then do it // en bloc and skip the storage step (no-op but for strlen). any_word_new = true; const char * w = I->first; if( word_bank_type::is_managed ) // record new copy of word w = memorize( (char*)w, strlen( w ) ); // ++this->m_words[w]; // count word (set to 1) value_type keyval( w, mapped_type(0) ); reducer_fn( keyval.second, I->second ); hint = this->m_words.insert( where, keyval ); } } #else for( other_const_iterator I=rhs.cbegin(), E=rhs.cend(); I != E; ++I ) { iterator L = this->m_words.find( I->first ); if( L != this->m_words.end() ) { reducer_fn( L->second, I->second ); } else { // Unseen words need to be stored into container of LHS // unless if we retain all files in memory, then do it // en bloc and skip the storage step (no-op but for strlen). any_word_new = true; const char * w = I->first; if( word_bank_type::is_managed ) // record new copy of word w = memorize( (char*)w, strlen( w ) ); // ++this->m_words[w]; // count word (set to 1) value_type keyval( w, mapped_type(0) ); reducer_fn( keyval.second, I->second ); this->m_words.insert( keyval ); } } #endif // TODO: measure how frequently this happens and its impact on // overall memory footprint // if( !any_word_new ) // std::cerr << "All words in right argument also in left argument\n"; if( !word_bank_type::is_managed && any_word_new ) this->m_storage.copy( storage ); } }; template<typename WordContainerTy> class word_container_reducer { typedef WordContainerTy type; struct Monoid : cilk::monoid_base<type> { static void reduce( type * left, type * right ) { left->reduce( *right ); } static void identity( type * p ) { // Initialize to useful default size depending on chunk size new (p) type(); // TODO: p->private_reserve(1<<16); } }; private: cilk::reducer<Monoid> imp_; public: word_container_reducer() : imp_() { } void swap( type & c ) { imp_.view().swap( c ); } /* mapped_type & operator [] ( const key_type & key ) { return imp_.view()[key]; } const mapped_type & operator [] const ( const key_type & key ) { return imp_.view()[key]; } */ template<typename OtherIndexTy, typename OtherWordBankTy> void count_presence( const word_map<OtherIndexTy,OtherWordBankTy> & rhs ) { imp_.view().count_presence( rhs ); } template<typename OtherIndexTy, typename OtherWordBankTy> void count_presence( const kv_list<OtherIndexTy,OtherWordBankTy> & rhs ) { imp_.view().count_presence( rhs ); } type & get_value() { return imp_.view(); } }; template<typename WordContainerTy> class word_container_file_builder { public: typedef WordContainerTy word_container_type; private: word_container_type & m_container; // word container, with storage std::shared_ptr<char> m_buf; // file contents size_t m_size; // file size public: word_container_file_builder( const std::string & filename, word_container_type & container ) : m_container( container ) { open_file( filename ); } ~word_container_file_builder() { } void swap( word_container_file_builder & w ) { std::swap( m_container, w.m_container ); std::swap( m_buf, w.m_buf ); std::swap( m_size, w.m_size ); } size_t size() const { return m_container.size(); } char * get_buffer() const { return m_buf.get(); } char * get_buffer_end() const { return m_buf.get()+m_size; } const word_container_type & get_word_list() const { return m_container; } word_container_type & get_word_list() { return m_container; } const char * memorize( char * p, size_t len ) { return m_container.record( p, len ); } const char * index( char * p, size_t len ) { return m_container.push_back( p, len ); } private: // Read the file into memory. // TODO: replace mmap( PROT_READ | PROT_WRITE, MAP_PRIVATE ); void open_file( const std::string & filename ) { struct stat finfo; int fd; const char * fname = filename.c_str(); if( (fd = open( fname, O_RDONLY )) < 0 ) fatale( "open", fname ); if( fstat( fd, &finfo ) < 0 ) fatale( "fstat", fname ); #if 0 char * buf = (char*)mmap(0, finfo.st_size + 1, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_POPULATE, fd, 0); #else char * buf = new char[finfo.st_size+1]; uint64_t r = 0; while( r < (uint64_t)finfo.st_size ) { uint64_t rr = pread( fd, buf + r, finfo.st_size - r, r ); if( rr == (uint64_t)-1 ) fatale( "pread", fname ); r += rr; } #endif buf[finfo.st_size] = '\0'; close( fd ); m_size = finfo.st_size; std::shared_ptr<char> sp( buf, std::default_delete<char[]>() ); m_buf = sp; if( !word_container_type::is_managed ) m_container.enregister( sp ); } }; } // namespace asap #endif // INCLUDED_ASAP_WORD_BANK_H
#include "jni.h" #include "iberbar\Base\FileUtils.h" #include "iberbar\Base\Platform\Android\JNIEnvHelper.h" #include "iberbar\Base\LogText.h" #include "android\log.h" #include "Java_FileUtil.h" bool iberbar::FileUtilsFindData::attrib_is_sub() const { return false; } const TCHAR* iberbar::CFileUtils::sm_DefaultFileFilter = _tstr( "*.*" ); iberbar::CFileUtils::CFileUtils( void ) : m_strOriginWorkPath( _tstr( "" ) ) { } iberbar::CFileUtils::~CFileUtils() { } bool iberbar::CFileUtils::getFullPath( const TCHAR* pzRelPath, TCHAR* pzAbsPath, int nSizeInWords ) { int lc_lenWorkPath = strlen( m_strOriginWorkPath.c_str() ); int lc_lenCopy = (lc_lenWorkPath > nSizeInWords ) ? nSizeInWords : lc_lenWorkPath; int lc_lenLeave = nSizeInWords - lc_lenCopy; int lc_lenRel = strlen( pzRelPath ); if ( lc_lenLeave <= lc_lenRel ) return false; strncpy( pzAbsPath, m_strOriginWorkPath.c_str(), lc_lenCopy ); pzAbsPath += lc_lenCopy; strncpy( pzAbsPath, pzRelPath, lc_lenRel ); pzAbsPath += lc_lenRel; pzAbsPath[ 0 ] = 0; return false; } bool iberbar::CFileUtils::getWorkPath( TCHAR* pzPath, int nSizeInWords ) { return false; } bool iberbar::CFileUtils::setWorkPath( const TCHAR* pzPath ) { return false; } bool iberbar::CFileUtils::foreachFile( const TCHAR* strFileFilter, CUnknown* pHandleObject, PFileForeach1 pHandleFunction ) { return false; } bool iberbar::CFileUtils::foreachFile( const TCHAR* strFileFilter, PFileForeach2 pHandleFunction ) { return false; } void iberbar::CFileUtils::init() { // JNIEnv* lc_env = JNIEnvHelper::GetEnv(); // jclass lc_cls = lc_env->FindClass( "com/iberbar/engine/lib/FileUtil" ); // jmethodID lc_method = lc_env->GetStaticMethodID( lc_cls, "GetSdcardRootPath", "()Ljava/lang/String;" ); // if ( lc_method == 0 ) // { // return ; // } // jstring lc_s = (jstring)lc_env->CallStaticObjectMethod( lc_cls, lc_method ); // jstring_to_stdstring( lc_env, lc_s, &m_strOriginWorkPath ); JavaFileUtil::GetSdcardRootPath( &m_strOriginWorkPath ); GetLogConsole()->debug( "iberbarEngine", m_strOriginWorkPath.c_str() ); }
#include <stdio.h> #include "pageLib.h" typedef int PageID; typedef struct { FILE *file_ptr; int page_size; } Heapfile; typedef struct { int page_id; int slot; } RecordID; typedef struct { int page_offset; int freespace; } DirEntry; void init_heapfile(Heapfile *heapfile, int page_size, FILE *file); PageID alloc_page(Heapfile *heapfile); void read_page(Heapfile *heapfile, PageID pid, Page *page); void write_page(Page *page, Heapfile *heapfile, PageID pid); PageID getPageForInsertion(Heapfile *heapfile); // Helper functions void writeDirectoryPage(FILE *file, int page_size); void findEntryInDirectory(Page *page, Heapfile *heapfile, PageID pid, void (*applyAction)(Heapfile *heapfile, Page *page, DirEntry *dirEntry, int pid)); void _read_page(Heapfile *heapfile, Page *page, DirEntry *dirEntry, int pid); void _write_page(Heapfile *heapfile, Page *page, DirEntry *dirEntry, int pid); PageID _alloc_or_get_page(Heapfile *heapfile, bool allocateNew); class RecordIterator { Heapfile *currHeapfile; char *currDir; DirEntry *currDirEntry; Page *currPage; Record currRecord; Record currRecordCopy; int currPageSlot; int currPageMaxSlots; int dirEntryPtr, recordPtr, maxDirEntries; public: RecordIterator(Heapfile *heapfile); Record next(); bool hasNext(); void forceFree(); private: void cleanup(); void readPageFromDirectory(); };
#include <vector> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <list> #include <algorithm> #include <sstream> #include <set> #include <cmath> #include <map> #include <stack> #include <queue> #include <cstdio> #include <cstdlib> #include <cstring> #include <numeric> #include <bitset> #include <deque> const long long LINF = (5e18); const int INF = (1<<29); #define EPS 1e-6 const int MOD = 1000000007; using namespace std; class ArithmeticProgression { public: int calc(int a0, vector<int> &seq, long double d, bool &isMatch) { int res = 0; long double k = a0; for (int v: seq) { k += d; long long a = floor(k); if (a < v) res = -1; else if (a > v) res = 1; } if (res == 0) isMatch = true; return res == 0 ? 1 : res; } double minCommonDifference(int a0, vector <int> seq) { double lb = 0.0, ub = 1e12; bool isMatch = false; for (int i=0; i<400; ++i) { double md = (lb+ub)/2.0; int res = calc(a0, seq, md, isMatch); if (res == -1) lb = md; else if (res == 1) ub = md; } return isMatch ? lb : -1; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const double &Expected, const double &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arg0 = 0; int Arr1[] = {6, 13, 20, 27}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); double Arg2 = 6.75; verify_case(0, Arg2, minCommonDifference(Arg0, Arg1)); } void test_case_1() { int Arg0 = 1; int Arr1[] = {2, 3, 4, 5, 6}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); double Arg2 = 1.0; verify_case(1, Arg2, minCommonDifference(Arg0, Arg1)); } void test_case_2() { int Arg0 = 3; int Arr1[] = {}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); double Arg2 = 0.0; verify_case(2, Arg2, minCommonDifference(Arg0, Arg1)); } void test_case_3() { int Arg0 = 3; int Arr1[] = {3, 3, 3, 3, 4}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); double Arg2 = 0.2; verify_case(3, Arg2, minCommonDifference(Arg0, Arg1)); } void test_case_4() { int Arg0 = 1; int Arr1[] = {-3}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); double Arg2 = -1.0; verify_case(4, Arg2, minCommonDifference(Arg0, Arg1)); } void test_case_5() { int Arg0 = -10; int Arr1[] = {-8, -7}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); double Arg2 = -1.0; verify_case(5, Arg2, minCommonDifference(Arg0, Arg1)); } // END CUT HERE }; // BEGIN CUT HERE int main() { ArithmeticProgression ___test; ___test.run_test(5); } // END CUT HERE
// GMP class // Generalized movement primitive. // #include <gmp_lib/GMP/GMP.h> namespace as64_ { namespace gmp_ { // =================================== // ======= Public Functions ======== // =================================== GMP::GMP(unsigned N_kernels, double D, double K, double kernels_std_scaling) { #ifdef GMP_DEBUG_ try{ #endif this->D = D; this->K = K; this->wsog.reset(new WSoG(N_kernels, kernels_std_scaling)); this->setY0(0); this->setGoal(1); this->y_dot = 0; this->z_dot = 0; #ifdef GMP_DEBUG_ }catch(std::exception &e) { throw std::runtime_error(std::string("[GMP::GMP]: ") + e.what()); } #endif } void GMP::train(const std::string &train_method, const arma::rowvec &Time, const arma::rowvec &yd_data, double *train_error) { #ifdef GMP_DEBUG_ try{ #endif int i_end = Time.size()-1; arma::rowvec x = Time / Time(i_end); this->wsog->train(train_method, x, yd_data, train_error); #ifdef GMP_DEBUG_ }catch(std::exception &e) { throw std::runtime_error(std::string("[GMP::train]: ") + e.what()); } #endif } void GMP::update(const gmp_::Phase &s, double y, double z, double y_c, double z_c) { #ifdef GMP_DEBUG_ try{ #endif this->z_dot = ( this->goalAttractor(y, z) + this->shapeAttractor(s) + z_c); this->y_dot = z + y_c; #ifdef GMP_DEBUG_ }catch(std::exception &e) { throw std::runtime_error(std::string("[GMP::update]: ") + e.what()); } #endif } void GMP::updateWeights(const std::vector<gmp_::Phase> &s, const arma::rowvec &z, const std::vector<gmp_::UPDATE_TYPE> &type, const arma::rowvec &z_var_) { #ifdef GMP_DEBUG_ try{ #endif int n = s.size(); arma::rowvec z_var = z_var_; if (z_var_.size()==1) z_var = z_var(0)*arma::rowvec().ones(n); int k = this->numOfKernels(); arma::mat H(n, k); arma::rowvec z_hat(n); arma::rowvec Hi; for (int i=0; i<n; i++) { if (type[i] == gmp_::UPDATE_TYPE::POS) { Hi = this->wsog->regressVec(s[i].x).t(); z_hat(i) = this->wsog->output(s[i].x); } else if (type[i] == gmp_::UPDATE_TYPE::VEL) { Hi = this->wsog->regressVecDot(s[i].x, s[i].x_dot).t(); z_hat(i) = this->wsog->outputDot(s[i].x, s[i].x_dot); } else if (type[i] == gmp_::UPDATE_TYPE::ACCEL) { Hi = this->wsog->regressVecDDot(s[i].x, s[i].x_dot, s[i].x_ddot).t(); z_hat(i) = this->wsog->outputDDot(s[i].x, s[i].x_dot, s[i].x_ddot); } H.row(i) = Hi; } arma::vec e = (z - z_hat).t(); this->wsog->updateWeights(H, e, arma::diagmat(z_var)); #ifdef GMP_DEBUG_ }catch(std::exception &e) { throw std::runtime_error(std::string("[GMP::updateWeights]: ") + e.what()); } #endif } double GMP::getYdot() const { return this->y_dot; } double GMP::getZdot() const { return this->z_dot; } double GMP::getYddot(double yc_dot) const { #ifdef GMP_DEBUG_ try{ #endif double y_ddot = this->getZdot() + yc_dot; return y_ddot; #ifdef GMP_DEBUG_ }catch(std::exception &e) { throw std::runtime_error(std::string("[GMP::getYddot]: ") + e.what()); } #endif } double GMP::calcYddot(const gmp_::Phase &s, double y, double y_dot, double yc, double zc, double yc_dot) const { #ifdef GMP_DEBUG_ try{ #endif double z = y_dot - yc; double z_dot = ( this->goalAttractor(y, z) + this->shapeAttractor(s) + zc); double y_ddot = (z_dot + yc_dot); return y_ddot; #ifdef GMP_DEBUG_ }catch(std::exception &e) { throw std::runtime_error(std::string("[GMP::calcYddot]: ") + e.what()); } #endif } int GMP::numOfKernels() const { #ifdef GMP_DEBUG_ try{ #endif return this->wsog->numOfKernels(); #ifdef GMP_DEBUG_ }catch(std::exception &e) { throw std::runtime_error(std::string("[GMP::numOfKernels]: ") + e.what()); } #endif } void GMP::setY0(double y0) { #ifdef GMP_DEBUG_ try{ #endif this->wsog->setStartValue(y0); #ifdef GMP_DEBUG_ }catch(std::exception &e) { throw std::runtime_error(std::string("[GMP::setY0]: ") + e.what()); } #endif } void GMP::setGoal(double g) { #ifdef GMP_DEBUG_ try{ #endif this->g = g; this->wsog->setFinalValue(g); #ifdef GMP_DEBUG_ }catch(std::exception &e) { throw std::runtime_error(std::string("[GMP::setGoal]: ") + e.what()); } #endif } double GMP::getYd(double x) const { #ifdef GMP_DEBUG_ try{ #endif return this->wsog->output(x); #ifdef GMP_DEBUG_ }catch(std::exception &e) { throw std::runtime_error(std::string("[GMP::getYd]: ") + e.what()); } #endif } double GMP::getYdDot(double x, double x_dot) const { #ifdef GMP_DEBUG_ try{ #endif return this->wsog->outputDot(x, x_dot); #ifdef GMP_DEBUG_ }catch(std::exception &e) { throw std::runtime_error(std::string("[GMP::getYdDot]: ") + e.what()); } #endif } double GMP::getYdDDot(double x, double x_dot, double x_ddot) const { #ifdef GMP_DEBUG_ try{ #endif return this->wsog->outputDDot(x, x_dot, x_ddot); #ifdef GMP_DEBUG_ }catch(std::exception &e) { throw std::runtime_error(std::string("[GMP::getYdDDot]: ") + e.what()); } #endif } // ====================================== // ======= Protected Functions ======== // ====================================== double GMP::goalAttractor(double y, double z) const { #ifdef GMP_DEBUG_ try{ #endif double goal_attr = this->K*(this->g-y)- this->D*z; return goal_attr; #ifdef GMP_DEBUG_ }catch(std::exception &e) { throw std::runtime_error(std::string("[GMP::goalAttractor]: ") + e.what()); } #endif } double GMP::shapeAttractor(const gmp_::Phase &s) const { #ifdef GMP_DEBUG_ try{ #endif double x = s.x; double x_dot = s.x_dot; double x_ddot = s.x_ddot; double yd = this->wsog->output(x); double yd_dot = this->wsog->outputDot(x, x_dot); double yd_ddot = this->wsog->outputDDot(x, x_dot, x_ddot); double f = yd_ddot + this->D*yd_dot + this->K*(yd - this->g); double sAttrGat = 1; double shape_attr = sAttrGat * f; return shape_attr; #ifdef GMP_DEBUG_ }catch(std::exception &e) { throw std::runtime_error(std::string("[GMP::shapeAttractor]: ") + e.what()); } #endif } void GMP::exportToFile(const std::string &filename) const { FileIO fid(filename, FileIO::out | FileIO::trunc); writeToFile(fid, ""); } std::shared_ptr<GMP> GMP::importFromFile(const std::string &filename) { std::shared_ptr<GMP> gmp( new gmp_::GMP(2, 1, 1, 1) ); FileIO fid(filename, FileIO::in); gmp->readFromFile(fid, ""); return gmp; } void GMP::writeToFile(FileIO &fid, const std::string &prefix) const { fid.write(prefix+"D", this->D); fid.write(prefix+"K", this->K); fid.write(prefix+"N_kernels", this->wsog->N_kernels); fid.write(prefix+"w", this->wsog->w); fid.write(prefix+"c", this->wsog->c); fid.write(prefix+"h", this->wsog->h); } void GMP::readFromFile(FileIO &fid, const std::string &prefix) { fid.read(prefix+"D", this->D); fid.read(prefix+"K", this->K); fid.read(prefix+"N_kernels", this->wsog->N_kernels); fid.read(prefix+"w", this->wsog->w); fid.read(prefix+"c", this->wsog->c); fid.read(prefix+"h", this->wsog->h); this->wsog->f0_d = arma::dot(this->wsog->regressVec(0),this->wsog->w); this->wsog->fg_d = arma::dot(this->wsog->regressVec(1),this->wsog->w); this->wsog->setStartValue(this->wsog->f0_d); this->wsog->setFinalValue(this->wsog->fg_d); } } // namespace gmp_ } // namespace as64_
/* * File: main.cpp * Author: Elijah De Vera * Created on January 14, 2021, 12:36 PM * Purpose: Conditionals and if statements */ //System Libraries #include <iostream> //Input/Output Library #include <iomanip> using namespace std; //User Libraries //Global Constants, no Global Variables are allowed //Math/Physics/Conversions/Higher Dimensions - i.e. PI, e, etc... //Function Prototypes //Execution Begins Here! int main(int argc, char** argv) { cout << "Book Worm Points" << endl; //Set the random number seed //Declare Variables int books, points; //Initialize or input i.e. set variable values cout << "Input the number of books purchased this month." << endl; // getting input from User cin >> books; //Map inputs -> outputs if ( books == 0 ) { points = 0; } else if ( books == 1 ) { points = 1; } else if ( books == 2 ) { points = 15; } else if ( books == 3 ) { points = 30; } else if ( books > 4 ) { points = 60; } //Display the outputs cout << "Books purchased = " << setw(2) << right << books << endl; cout << "Points earned = " << setw(2) << right << points; //Exit stage right or left! return 0; }
#include <iostream> #include <fstream> #include "Stack.h" #include "Queue.h" using namespace std; struct NodeItem{ int row; int col; int weight; // weight = abs(x-root.row) + abs(y-root.y) NodeItem* parent; // used in shortest-path NodeItem(int r, int c, int d):row(r),col(c),weight(d),parent(0){} NodeItem operator=(NodeItem* n) { this->row = n->row; this->col = n->col; this->weight = n->weight; this->parent = n->parent; return *this; } }; class Robot{ private: NodeItem* root; int num_node; int row, col, battery; int** map; // map to store where has been visited bool** mapSP; // original bool map bool** mapcopy; // used in BFS_ShortestPath int** partial; // an array to store the # of zeros on a path stack<NodeItem*> track;// a stack to store the last step queue<NodeItem*> step; // the path itself NodeItem*** path; public: //constructor; initinalize map, battery life, num_node and root node Robot(int r, int c, int b, char** input):row(r),col(c),battery(b){ // construct map and all the other tools map = new int*[r]; mapSP = new bool*[r]; mapcopy = new bool*[r]; partial = new int*[r]; for(int i =0; i < r; i++) { map[i] = new int[c]; mapSP[i] = new bool[c]; mapcopy[i] = new bool[c]; partial[i] = new int[c]; } // mapping input & map and count nodes num_node =0; for(int i = 0; i < r; i++) { for(int j = 0; j < c; j++) { if(input[i][j]=='R') { map[i][j] = 1; mapSP[i][j] = true; partial[i][j] = 0; root = new NodeItem(i, j, 0); track.push(root); // initialize the position step.push(root); // first step is root } else if(input[i][j]=='1'){ map[i][j] = 2; mapSP[i][j] = false; } else{ map[i][j] = 0; partial[i][j] = 0; num_node++; // count zeros mapSP[i][j] = true; } } } ShortestPath_SpanningMap(root); /* 1 1 1 1 2 2 2 2 1 0 0 1 ===> 2 0 0 2 ===> num_node = 4, not including root 1 1 0 1 2 2 0 2 1 0 R 1 2 0 1 2 */ } int get_num_node() {return num_node;}; void mapCopyInit(); bool AllClean(); void Move(); void Move_Large(); void PrintStep(); void PrintMap(); NodeItem*** ShortestPath_SpanningMap(NodeItem* root); NodeItem* ShortestPath_from_to(NodeItem* from, NodeItem* to); bool Deadend(NodeItem* top); bool isValidStep(NodeItem*,int); void bestTravelInit(); void countStepsInit(); NodeItem* bestTravel(NodeItem* current); int countZeros(int i, int j); int countSteps_to_from(NodeItem* check, NodeItem* from, NodeItem* to); int countSteps(int i , int j); void pushSteps(NodeItem* path, NodeItem* from); void pushSteps_toRoot(NodeItem* temp, NodeItem* from); int steps() { return step.size()-1; } void outStep(ofstream&); }; bool Robot::Deadend(NodeItem* top) { int count = 0; int r = top->row; int c = top->col; if(r-1 >= 0 && map[r-1][c] == 0) count++; if(r+1 <= row-1 && map[r+1][c] == 0 ) count++; if(c-1 >= 0 && map[r][c-1] == 0 ) count++; if(c+1 <= col-1 && map[r][c+1] == 0) count++; if(count) return false; else return true; } // shortest but also record it //return a linked-list NodeItem*** Robot::ShortestPath_SpanningMap(NodeItem* from) { mapCopyInit(); path = new NodeItem**[row]; for(int i = 0; i < row; i++) { path[i] = new NodeItem*[col]; } for(int i = 0; i < row; i++) { for(int j = 0; j < col; j++) { path[i][j] = NULL; } } path[root->row][root->col] = root; path[root->row][root->col]->weight = 0; queue<NodeItem*> bfs; stack<NodeItem*> s; bfs.push(from); while(!bfs.empty()) { NodeItem* current = bfs.front(); int r = current->row; int c = current->col; mapcopy[r][c] = false; bfs.pop(); //cout<<"mapcopy[r-1][c]: "<<mapcopy[r-1][c]<<endl; if(r-1 >= 0 && mapcopy[r-1][c] == true ) { NodeItem* up = new NodeItem(r-1, c, current->weight+1); mapcopy[r-1][c] =false; up->parent = current; path[r-1][c] = up; bfs.push(up); } if(r+1 <= row-1 && mapcopy[r+1][c] == true) { NodeItem* down = new NodeItem(r+1, c, current->weight+1); mapcopy[r+1][c] = false; down->parent = current; path[r+1][c] = down; bfs.push(down);} if(c-1 >= 0 && mapcopy[r][c-1] == true ) { NodeItem* left = new NodeItem(r, c-1, current->weight+1); mapcopy[r][c-1] = false; left->parent = current; path[r][c-1] = left; bfs.push(left);} if(c+1 <= col-1 && mapcopy[r][c+1] == true) { NodeItem* right = new NodeItem(r, c+1, current->weight+1); mapcopy[r][c+1] = false; right->parent = current; path[r][c+1] = right; bfs.push(right);} } return path; } void Robot::mapCopyInit() { for(int i = 0; i < row; i++) { for(int j = 0; j < col; j++) { mapcopy[i][j] = mapSP[i][j]; } } } NodeItem* Robot::ShortestPath_from_to(NodeItem* from, NodeItem* to) { mapCopyInit(); queue<NodeItem*> bfs; stack<NodeItem*> s; bfs.push(from); NodeItem* ans = NULL; while(!bfs.empty()) { NodeItem* current = bfs.front(); int r = current->row; int c = current->col; mapcopy[r][c] = false; bfs.pop(); // case 0 : from == to if(r == to->row && c == to->col) { ans = current; break;} int weightUp = 0; int weightDown = 0; int weightLeft = 0; int weightRight = 0; if(r-1 >= 0 && mapcopy[r-1][c] == true ) { NodeItem* up = new NodeItem(r-1, c, weightUp); mapcopy[r-1][c] =false; up->parent = current; bfs.push(up); if(r-1 == to->row && c == to->col) {ans = up; break;}} if(r+1 <= row-1 && mapcopy[r+1][c] == true) { NodeItem* down = new NodeItem(r+1, c, weightDown); mapcopy[r+1][c] = false; down->parent = current; bfs.push(down);;if(r+1 == to->row && c == to->col) {ans = down; break;}} if(c-1 >= 0 && mapcopy[r][c-1] == true ) { NodeItem* left = new NodeItem(r, c-1, weightLeft); mapcopy[r][c-1] = false; left->parent = current; bfs.push(left); if(r == to->row && c-1 == to->col) {ans = left; break;}} if(c+1 <= col-1 && mapcopy[r][c+1] == true) { NodeItem* right = new NodeItem(r, c+1, weightRight); mapcopy[r][c+1] = false; right->parent = current; bfs.push(right); if(r == to->row && c+1 == to->col){ans = right; break;}} } cout<<endl; return ans; } int Robot::countZeros(int i, int j) { int num_of_zero = 0; int r = 0; int c = 0; NodeItem* temp = path[i][j]; while(temp!= root) { r = temp->row; c = temp->col; if (map[r][c] == 0) { num_of_zero++; } temp = temp->parent; } return num_of_zero; } int Robot::countSteps(int i , int j) { return path[i][j]->weight; } int Robot::countSteps_to_from(NodeItem* check, NodeItem* from, NodeItem* to) { int steps = 0; NodeItem* tmp = check; int r = 0; int c = 0; while(tmp != from) { tmp = tmp->parent; steps++; } return steps; } NodeItem* Robot::bestTravel(NodeItem* current) { // return the best option int best = 0; int x = root->row; int y = root->col; if( num_node <= 700000) { for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (map[i][j] == 0 ) { // cout<<"comparing"<<endl; partial[i][j] = countZeros(i,j); // cout<<partial[i][j]<<endl; if(partial[i][j] > best ) { best = partial[i][j]; x = i; y = j; } } } } } else { for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (map[i][j] == 0 ) { x = i; y = j; } } } } NodeItem* bestoption = new NodeItem(x,y,0); //cout<<"how many zeros on path: "<<best<<endl; return bestoption; } bool Robot::AllClean() { for(int i = 0; i < row; i++) { for(int j = 0; j < col; j++) { if(map[i][j] == 0) return false; } } return true; } bool Robot::isValidStep(NodeItem* now, int b) { stack<NodeItem*> stk; int r = now->row; int c = now->col; int w = now->weight; NodeItem* next; // Move Up Valid if(r-1 >= 0 && map[r-1][c] == 0 ) { int toRoot = path[r-1][c]->weight; if(b-toRoot >0)return true; } // Move Down Valid else if(r+1 <= row-1 && map[r+1][c] == 0 ) { int toRoot = path[r+1][c]->weight; if(b-toRoot >0)return true; } //Move Left Valid else if(c-1 >= 0 && map[r][c-1] == 0 ) { int toRoot = path[r][c-1]->weight; if(b-toRoot >0)return true; } //Move Right Valid else if(c+1 <= col-1 && map[r][c+1] == 0 ) { int toRoot = path[r][c+1]->weight; if(b-toRoot >0)return true; } return false; } void Robot::pushSteps(NodeItem* temp, NodeItem* from) { stack<NodeItem*> s; while (!s.empty()) {s.pop();} int r = 0; int c = 0; while(temp != from) { s.push(temp); temp = temp->parent; } while (!s.empty()) { step.push(s.top()); r = s.top()->row; c = s.top()->col; map[r][c] = 1; track.push(s.top()); //cout<<"[ "<< s.top()->row<<", "<<s.top()->col<<" ]"<<endl; s.pop(); } } void Robot::pushSteps_toRoot(NodeItem* temp, NodeItem* from) { stack<NodeItem*> s; while (!s.empty()) {s.pop();} int r = 0; int c = 0; while(temp != from) { temp = temp->parent; r= temp->row; c = temp->col; step.push(temp); map[r][c] = 1; //cout<<"[ "<< r<<", "<<c<<" ]"<<endl; } } void Robot::Move() { stack<NodeItem*> s3; int batterylife = battery; while(!AllClean()) { if(batterylife < 0) { cout<<"Invalid test case"<<endl; break;} //cout<<"Energy now: "<<batterylife<<endl; NodeItem* now = track.top(); //cout<<"Now position: "<<"[ "<< now->row<<", "<<now->col<<" ]"<<endl; int r = now->row; int c = now->col; int w = now->weight; // Special case addressing if(track.size()==1 && step.size()>1) { int x,y; for(int i = 0; i < row; i++) { for(int j = 0; j < col; j++) { if(map[i][j] == 0) { x = i; y = j; break; } } } NodeItem* temp = path[x][y]; pushSteps(temp,root); } // Normal situation: battery is still enough else if (isValidStep(now, batterylife) ) { //cout<<"GO! "<<endl; NodeItem* newnode; // Moving up if(r-1 >= 0 && map[r-1][c] == 0 ) { //visiting newnode = path[r-1][c]; map[r-1][c] = 1; track.push(newnode); step.push(newnode); batterylife--; } // Moving down else if(r+1 <= row-1 && map[r+1][c] == 0 ) { //visiting newnode = path[r+1][c]; map[r+1][c] = 1; track.push(newnode); step.push(newnode); batterylife--; } // Moving Left else if(c-1 >= 0 && map[r][c-1] == 0 ) { //visiting newnode = path[r][c-1]; map[r][c-1] = 1; track.push(newnode); step.push(newnode); batterylife--; } // Moving Right else if(c+1 <= col-1 && map[r][c+1] == 0 ) { //visiting newnode = path[r][c+1]; map[r][c+1] = 1; track.push(newnode); step.push(newnode); batterylife--; } } // Dead-End: 1. Search for the node that has unvisited adjancey node(s) else if ( Deadend(track.top()) ) { //cout<<"DeadEnd Occurs"<<endl; NodeItem* from = track.top(); //cout<<"From the dead-end node: "<<"[ "<< from->row<<", "<<from->col<<" ]"<<endl; while(Deadend(track.top())&& track.size()>1) { track.pop(); } NodeItem* to = track.top(); //cout<<"Back to the node with unvisited adjancey nodes: "<<"[ "<< to->row<<", "<<to->col<<" ]"<<endl; //cout<<endl; NodeItem* temp = ShortestPath_from_to(from, to); int counts = countSteps_to_from(temp, from,to); //cout<<"counts: "<<counts<<endl; cout<<endl; // if (to == root) then goRoot->parent == NULLs int counting = path[to->row][to->col]->weight; // it is safe to go if((batterylife - counts - counting -2) >= 0) { //cout<<"Safe to go!"<<endl; pushSteps(temp, from); batterylife -= counts; } // need to recharge first else { //cout<<"\nRecharge: "<<(counts+counting)<<" >= "<<batterylife<<endl; /*Recharge*/ // NodeItem*tempss = ShortestPath_to_R_BFS(from, root); pushSteps_toRoot(path[from->row][from->col], root); batterylife = battery; /*go to the best path*/ NodeItem* best = bestTravel(root); //cout<<"go to the best node after recharge: "<<"[ "<< best->row<<", "<<best->col<<" ]"<<endl; //NodeItem* newplace = ShortestPath_to_R_BFS(root, best); int steps = countSteps(best->row,best->col); pushSteps(path[best->row][best->col], root); track.push(best); batterylife -= steps; } } // Rechrge time: else { //cout<<"Recharge time!"<<endl; /* Calculate the shortest path from now to root */ //NodeItem* check = ShortestPath_to_R_BFS(now, root); pushSteps_toRoot(path[now->row][now->col], root); batterylife = battery; //cout<<"Now at: "<<"[ "<<track.top()->row<<", "<<track.top()->col<<" ]"<<endl; //cout<<"energy: "<<batterylife<<endl; NodeItem* best = bestTravel(track.top()); //cout<<"go to the best node after recharge: "<<"[ "<< best->row<<", "<<best->col<<" ]"<<endl; //NodeItem*temp = ShortestPath_to_R_BFS(track.top(), best); int steps = countSteps(best->row, best->col); // top == root pushSteps(path[best->row][best->col], root); batterylife -= steps; } // PrintMap(); // cout<<"step: "<<step.size()-1<<endl; // cout<<endl; } /* After all cleaned, walk shortestPath back to root */ cout<<"Timetogohome! now at position: "<<"[ "<< track.top()->row<<", "<<track.top()->col<<" ]"<<endl; pushSteps_toRoot(path[track.top()->row][track.top()->col], root); cout<<"Total: "<<steps()<<endl; } void Robot::Move_Large() { int batterylife = battery; int rx, ry; // cout<<"( "<<path[1][12]->row<<","<<path[1][12]->col<<" )"<<endl; // go to the furthest for(int i = 0; i < row; i++) { for(int j = 0; j < col; j++) { if(map[i][j] == 0) { // int count = countSteps(pathlookup[i*col+j],root,root); //cout<<"Go"<<endl; NodeItem* temp = path[i][j]; pushSteps(temp,root); // step_to_root[i][j] = countSteps(pathlookup[i*col+j],root,0); int s = path[i][j]->weight; batterylife -= s; int x = i; int y = j; while(batterylife - s >= 2) { // cout<<"batterylife: "<<batterylife<<endl; // cout<<"Wander"<<endl; if(map[x+1][y] == 0) {batterylife--; step.push(path[x+1][y]); map[x+1][y] = 1; x++;} else if(map[x][y+1] == 0) { batterylife--; step.push(path[x][y+1]);map[x][y+1] = 1;y++;} else if(map[x-1][y] == 0) { batterylife--; step.push(path[x-1][y]);map[x-1][y] = 1;x--;} else if(map[x][y-1] == 0) {batterylife--; step.push(path[x][y-1]);map[x][y-1] = 1; y--;} else {cout<<"DeadEnd"<<endl; break;} s = path[x][y]->weight; //cout<<"( "<<path[x][y]->row<<","<<path[x][y]->col<<" )"<<endl; // PrintMap(); // cout<<endl; } //cout<<"Recharge"<<endl; NodeItem* temps = path[x][y]; pushSteps_toRoot(temps,root); batterylife = battery; } } } cout<<"All Cleaned"<<endl; } void Robot::outStep(ofstream& outFile) { while(!step.empty()) { outFile<<step.front()->row<<" "<<step.front()->col<<" "<<endl; step.pop(); } } void Robot::PrintMap(){ for(int i = 0; i < row; i++) { for(int j = 0; j < col;j++) { cout<<map[i][j]; } cout<<endl; } } int main() { ifstream file("floor.data"); int r,c,b; file>>r>>c>>b; char** input = new char*[r]; for(int i = 0; i < r; i++) { input[i] = new char[c]; } for(int i = 0; i < r; i++) { for(int j = 0; j < c;j++) { file>>input[i][j]; } } Robot robot(r,c,b,input); int flag = robot.get_num_node(); // if(flag == 851585) { // cout<<"\nLarge"<<endl; // robot.Move_Large(); // } // else{ robot.Move(); // } cout<<"num_of_node: "<<flag<<endl; ofstream outFile("final.path", ios::out); outFile<<robot.steps()<<endl; // robot.PrintMap(); robot.outStep(outFile); }
#include "dfAnimator.h" #include "../Entity/Entity.h" dfAnimator::dfAnimator() { } dfAnimator::~dfAnimator(void) { } void dfAnimator::Setup(wchar_t* animFilename) { currentAnimIndex = 0; currentFrame = 0; playing = true; timer = 0.f; LoadAnimJSON(animFilename); } void dfAnimator::Setup(std::string name, float spd, int frames) { AnimationInfo info; for(int i = 0; i < frames; i++) info.frames.push_back(i); info.framesPerSecond = spd; info.loopbackFrame = 0; info.looping = true; info.name = name; } void dfAnimator::Setup(std::vector<AnimationInfo> animationList) { currentAnimIndex = 0; currentFrame = 0; playing = true; timer = 0.f; anims = animationList; } void dfAnimator::Init() { dfComponent::Init(); render = entity->GetComponent<Renderer>(); } void dfAnimator::Update() { dfComponent::Update(); timer += dfDeltaTime; if(playing) { if(timer > 1.f / anims[currentAnimIndex].framesPerSecond) { timer = 0.f; currentFrame++; if(currentFrame > anims[currentAnimIndex].frames[anims[currentAnimIndex].frames.size() - 1]) currentFrame = anims[currentAnimIndex].frames[0]; SetFrame(currentFrame); } } } void dfAnimator::SetFrame(int n) { render->SetAtlasLocation(n); } void dfAnimator::Play() { playing = true; } void dfAnimator::Play(std::string animName) { for(int i = 0; i < anims.size(); i++) { if(dfStrCmp(animName.c_str(), anims[i].name.c_str()) && currentAnimIndex != i) { currentAnimIndex = i; currentFrame = anims[i].frames[0]; Play(); SetFrame(currentFrame); } } } void dfAnimator::Pause() { playing = false; } void dfAnimator::LoadAnimJSON(wchar_t* animFilename) { JsonObject jsonObj = JsonObject(); std::string str = assMan.GetTextFile((const wchar_t*)animFilename); if(!jsonObj.parse(str.c_str(), str.length(), &jsonObj)) { // json load failed... dfAssert(false); } //animations JsonObject animListObj = jsonObj.getChild("animations"); for(int i = 0; i < animListObj.numChildren(); i++) { AnimationInfo animInfo; JsonKeyValue animObj = animListObj.getObjectChild(i); animInfo.name = animObj.key; animInfo.framesPerSecond = animObj.value.getChild("fps").asFloat(); std::string frameInfoStr = animObj.value.getChild("frames").asString(); animInfo.looping = true; std::string currentNumStr = ""; int lastNum = -1; for(int i = 0; i < frameInfoStr.length(); i++) { char c = frameInfoStr[i]; if(c == '-' || c == ':') { int currentNum = dfStringToInt(currentNumStr.c_str(), currentNumStr.length()); currentNumStr = ""; if(lastNum != -1) { if(currentNum > lastNum) for(int index = lastNum; index < currentNum + 1; index++) animInfo.frames.push_back(index); else for(int index = currentNum; index >= lastNum; index--) animInfo.frames.push_back(index); } lastNum = currentNum; } else if(c ==',') { int currentNum = dfStringToInt(currentNumStr.c_str(), currentNumStr.length()); currentNumStr = ""; if(lastNum != -1) { if(currentNum > lastNum) for(int index = lastNum; index < currentNum + 1; index++) animInfo.frames.push_back(index); else for(int index = currentNum; index >= lastNum; index--) animInfo.frames.push_back(index); } else { animInfo.frames.push_back(currentNum); } lastNum = -1; } else if(c =='0' || c =='1' || c =='2' || c =='3' || c =='4' || c =='5' || c =='6' || c =='7' || c =='8' || c =='9') { currentNumStr += c; } } // do it a final time int currentNum = dfStringToInt(currentNumStr.c_str(), currentNumStr.length()); currentNumStr = ""; if(lastNum != -1) { if(currentNum > lastNum) for(int index = lastNum; index < currentNum + 1; index++) animInfo.frames.push_back(index); else for(int index = currentNum; index >= lastNum; index--) animInfo.frames.push_back(index); } else { animInfo.frames.push_back(currentNum); } if(animInfo.frames.size() > 0) animInfo.loopbackFrame = animInfo.frames[0]; anims.push_back(animInfo); } }
#include <iostream> using namespace std; //Bubble – Sort (sortarea prin interschimbare) int main() { int a[100],i,j,aux,n; cout<<"n="; cin>>n; for(i=1; i<=n; i++) { cout<<"a["<<i<<"]="; cin>>a[i]; } cout<<"Sirul original arata de forma:"<<endl; for(i=1; i<=n; i++) cout<<a[i]<<" "; cout<<endl; for(j=2; j<n; j++) for(i=n; i>=j; i--) if(a[i-1]>a[i]) { aux=a[i-1]; a[i-1]=a[i]; a[i]=aux; for(i=1; i<=n; i++) cout<<a[i]<<" "; cout<<endl; } cout<<endl; cout<<"Sirul ordonat arata de forma:"<<endl; for(i=1; i<=n; i++) cout<<a[i]<<" "; return 0; }
# include <iostream> //# include <iomanip> using namespace std; int main () { float lowerLimit, higherLimit, stepSize, temperature; cout << "Please give in a lower limit, limit >= 0: "; cin >> lowerLimit; cout << "Please give in a higher limit, 10 > limit <= 50000: "; cin >> higherLimit; cout << "Please give in a step, 0 < step <= 10: "; cin >> stepSize; cout << endl; cout << "Celsius" << " " << "Fahrenheit" << endl; cout << "-------" << " " << "----------" <<endl; // cout << fixed << setprecision(6) << lowerLimit << endl; // printf("%.6lf\n", lowerLimit); printf("%.6lf ", lowerLimit); float fahrenheit = lowerLimit * 9 / 5 + 32; printf("%.6lf\n", fahrenheit); while((lowerLimit + stepSize) < higherLimit) { lowerLimit = lowerLimit + stepSize; fahrenheit = lowerLimit * 9 / 5 + 32; //cout << fixed << setprecision(6) << lowerLimit << endl; // printf("%.6lf\n", lowerLimit); printf("%.6lf ", lowerLimit); printf("%.6lf\n", fahrenheit); } cout << endl; system("pause"); return 0; }
#include "Socket.h" namespace chatty { namespace net { Socket::Socket(int fd) : fd_(fd) {} } // namespace net } // namespace chatty
// typedef int cod; // bool eq(cod a, cod b){ return (a==b); } #define vp vector<point> typedef ld cod; bool eq(cod a, cod b){ return fabs(a - b) <= EPS; } struct point { cod x, y, z; point(cod x=0, cod y=0, cod z=0): x(x), y(y), z(z){} point operator+(const point &o) const{ return {x+o.x, y+o.y, z+o.z}; } point operator-(const point &o) const{ return {x-o.x, y-o.y, z-o.z}; } point operator*(cod t) const{ return {x*t, y*t, z*t}; } point operator/(cod t) const{ return {x/t, y/t, z/t}; } bool operator==(const point &o) const{ return eq(x, o.x) and eq(y, o.y) and eq(z, o.z); } cod operator*(const point &o) const{ // dot return x*o.x + y*o.y + z*o.z; } point operator^(const point &o) const{ // cross return point(y*o.z - z*o.y, z*o.x - x*o.z, x*o.y - y*o.x); } }; ld dist(point a, point b){ return sqrt((a-b)*(a-b)); } bool nulo(point a){ return (eq(a.x, 0) and eq(a.y, 0) and eq(a.z, 0)); } ld norm(point a){ // Modulo return sqrt(a*a); } ld proj(point a, point b){ // a sobre b return (a*b)/norm(b); } ld angle(point a, point b){ // em radianos return acos((a*b) / norm(a) / norm(b)); } cod triple(point a, point b, point c){ return dot(a, b^c); // Area do paralelepipedo } struct plane{ point p1, p2, p3; plane(point p1=0, point p2=0, point p3=0): p1(p1), p2(p2), p3(p3){} point aux = (p1-p3)^(p2-p3); cod a = aux.x, b = aux.y, c = aux.z; cod d = -a*p1.x - b*p1.y - c*p1.z; // ax+by+cz+d = 0; }; cod dist(plane pl, point p){ return fabs(pl.a*p.x + pl.b*p.y + pl.c*p.z + pl.d) / sqrt(pl.a*pl.a + pl.b*pl.b + pl.c*pl.c); } point rotate(point v, point k, ld theta){ // Rotaciona o vetor v theta graus em torno do eixo k // theta *= PI/180; // graus return rotated = (v*cos(theta)) + ((k^v)*sin(theta)) + (k*(k*v))*(1-cos(theta)); }
#include "mList.h" #include "utils.h" ListNode* buildList(std::string in, char p) { auto nums = split(in.substr(1,in.length()-2), p); ListNode* head = new ListNode(0); ListNode* tail = head; for (int i = 0;i < nums.size();i++) { tail->next = new ListNode(parseInt(nums[i])); tail = tail->next; } return head->next; } void printList(ListNode* head) { while (head) { std::cout << head->val << " "; head = head->next; } std::cout << std::endl; }
#include <algorithm> #include <assert.h> #include "model.h" #include "parameters.h" Model::Model() { } void Model::init(const uint32_t in_epochs, const Batch_Method_T batch_method, const boolean_t in_schuffle_input) { random_engine.generate(weight, PARAMETERS_LOWER_BOUND, PARAMETERS_UPPER_BOUND); random_engine.generate(bias, PARAMETERS_LOWER_BOUND, PARAMETERS_UPPER_BOUND); total_epochs = in_epochs; epoch = 0; if (BATCH_METHOD_STOCHASTIC == batch_method) { batch_size = 1; } else if (BATCH_METHOD_MINI_BATCH == batch_method) { batch_size = MINI_BATCH_SIZE; } else if (BATCH_METHOD_BATCH == batch_method) { batch_size = INPUT_DATA_SIZE; } schuffle_input = in_schuffle_input; pred_out = 0; loss = 0; dL_dw = 0; dL_db = 0; } void Model::setInOut(const float64_t in_inp, const float64_t in_out) { inp = in_inp; out = in_out; } void Model::forwardProp(void) { /* yhat = w*x + b */ pred_out = (inp * weight) + bias; } void Model::findLoss(void) { /* L = 0.5*(yhat - y)^2 */ loss = 0.5*std::pow((pred_out - out), 2); } void Model::backwardProp() { /* * dL_dw = dL_dyhat*dyhat_dw * dL_db = dL_dyhat*dyhat_db * dL_dyhat = (yhat-y) * dyhat_dw = x * dyhat_db = 1 */ dL_dw = (pred_out - out) * inp; dL_db = (pred_out - out); assert(out == inp); sample_num++; batch_loss += loss; batch_dL_dw += dL_dw; batch_dL_db += dL_db; if (0 == (sample_num % batch_size)) { batch_num++; batch_loss /= batch_size; batch_dL_dw /= batch_size; batch_dL_db /= batch_size; updateWeights(); logger.logData(epoch, batch_num, batch_loss, batch_dL_dw, batch_dL_db, weight, bias); batch_loss = 0; batch_dL_dw = 0; batch_dL_db = 0; } } void Model::checkWeights(void) { float64_t weight_diff = std::abs(1 - weight); float64_t bias_diff = std::abs(0 - bias); if ((weight_diff < DIFF_THRESHOLD) && (bias_diff < DIFF_THRESHOLD)) { status = MODEL_STATUS_TRAINING_STOP; } } void Model::updateWeights() { switch (optimizer.getMethod()) { case OPTIMIZER_GD: optimizer.normal(weight, bias, batch_dL_dw, batch_dL_db); break; case OPTIMIZER_GD_WITH_MOMENTUM: optimizer.momentum(weight, bias, batch_dL_dw, batch_dL_db); break; case OPTIMIZER_RMS: optimizer.rms(weight, bias, batch_dL_dw, batch_dL_db); break; case OPTIMIZER_ADAM: optimizer.adam(weight, bias, batch_dL_dw, batch_dL_db); break; default: break; } } void Model::run(std::vector<float64_t> &inp_vec, std::vector<float64_t> &out_vec) { status = MODEL_STATUS_TRAINING_START; while ((epoch < total_epochs) && (MODEL_STATUS_TRAINING_STOP != status)) { epoch++; if (TRUE == schuffle_input) { std::random_shuffle(inp_vec.begin(), inp_vec.end()); out_vec = inp_vec; } for (uint32_t idx = 0; idx < inp_vec.size(); ++idx) { setInOut(inp_vec[idx], out_vec[idx]); forwardProp(); findLoss(); backwardProp(); checkWeights(); if (MODEL_STATUS_TRAINING_STOP == status) { break; } } batch_num = 0; /* Reset all the internal variables of the optimizer after every epoch */ optimizer.reset(); } status = MODEL_STATUS_TRAINING_STOP; } float64_t Model::getWeight(void) { return weight; } float64_t Model::getBias(void) { return bias; } uint32_t Model::getTotalEpochs(void) { return total_epochs; } uint32_t Model::getEpochNum(void) { return epoch; } Optimizer* Model::getOptimizer(void) { return &optimizer; } Logger* Model::getLogger(void) { return &logger; }
// // Created on 21/01/19. // // // Code translated to C++ from the original: https://github.com/iskandr/fancyimpute // #include "IterativeSVD.h" #include "../Algebra/RSVD.h" #include <iostream> namespace Algorithms { bool converged(const arma::mat &X_old, const arma::mat &X_new, const std::vector<arma::uvec> &indices, double threshold) { double delta = 0.0; double old_norm = 0.0; for (uint64_t i = 0; i < X_old.n_cols; ++i) { for (uint64_t j : indices[i]) { old_norm += X_old.at(j, i) * X_old.at(j, i); double diff = X_old.at(j, i) - X_new.at(j, i); delta += diff * diff; } } return old_norm > arma::datum::eps && (delta / old_norm) < threshold; } void IterativeSVD::recoveryIterativeSVD(arma::mat &X, uint64_t rank) { // --defaults for the algorithms from FancyImpute: // fill_method="zero" // min_value=None // max_value=None // normalizer=None // // -- defaults for IterSVD: // svd_algorithm="arpack" // convergence_threshold=0.00001 // max_iters=200 // gradual_rank_increase=True bool gradual_rank_increase = true; constexpr uint64_t max_iters = 100; constexpr double threshold = 0.00001; std::vector<arma::uvec> indices; for (uint64_t i = 0; i < X.n_cols; ++i) { indices.emplace_back(arma::find_nonfinite(X.col(i))); } for (uint64_t i = 0; i < X.n_cols; ++i) { for (uint64_t j : indices[i]) { X.at(j, i) = 0.0; } } // solve() arma::mat U; arma::vec S; arma::mat V; uint64_t iter = 0; while (iter < max_iters) { uint64_t curr_rank; if (gradual_rank_increase) { curr_rank = std::min((uint64_t )std::pow(2, iter), rank); if (iter >= 20) //overflows into 0 due to 2^iter > 2^64 { gradual_rank_increase = false; } } else { curr_rank = rank; } int code = Algebra::Algorithms::RSVD::rsvd(U, S, V, X, curr_rank); if (code != 0) { std::cout << "RSVD returned an error: "; Algebra::Algorithms::RSVD::print_error(code); std::cout << ", aborting remaining recovery" << std::endl; return; } arma::mat X_reconstructed = U(arma::span::all, arma::span(0, curr_rank - 1)) * arma::diagmat(S(arma::span(0, curr_rank - 1))) * ((arma::mat)V.t())(arma::span(0, curr_rank - 1), arma::span::all); bool conv = converged(X, X_reconstructed, indices, threshold); for (uint64_t i = 0; i < X.n_cols; ++i) { for (uint64_t j : indices[i]) { X.at(j, i) = X_reconstructed.at(j, i); } } if (conv) { break; } ++iter; } } } // namespace Algorithms
#ifndef _LogoutProcess_H_ #define _LogoutProcess_H_ #include "BaseProcess.h" class Table; class Player; class LogoutProcess : public BaseProcess { public: LogoutProcess(); virtual ~LogoutProcess(); virtual int doRequest(CDLSocketHandler *clientHandler, InputPacket *pPacket, Context *pt); private: int sendPlayersLogoutInfo(Table *table, Player *leavePlayer); }; #endif
#include <iostream> #include "options.h" using namespace std; void Options::printOptions() { cout << "Options:" << endl; }
// // main.cpp // // Created by Héctor Esteban Cabezos on 15/1/19. // Copyright © 2019 Héctor Esteban Cabezos. All rights reserved. // #include <iostream> #include <string> #include <vector> #include <sstream> #include <iterator> #include <fstream> #include <cmath> using namespace std; int rows, columns; vector<vector<double> > initiliaze_matrix(istringstream& input, int rows, int columns) { vector<vector<double> > array(rows,vector<double>(columns)); for(int i = 0; i<rows; i++){ for (int j = 0; j<columns; j++){ input >> array[i][j]; } } return array; } vector<vector<double> > initiliaze_matrix_from_vector(vector<int> input, int rows, int columns) { vector<vector<double> > array(rows,vector<double>(columns)); int counter = 0; for(int i = 0; i<rows; i++){ for (int j = 0; j<columns; j++){ array[i][j] = input[counter]; counter ++; } } return array; } vector<double> initiliaze_vector(istringstream& input) { input >> columns; vector<double> array(columns); for (int j = 0; j<columns; j++){ input >> array[j]; } return array; } vector<float> multiply_matrices(vector<vector<float> > first, vector<float> second){ vector<float> result(first[1].size()); int i,j; for (i=0; i<first.size(); i++){ for (j=0; j<first[0].size(); j++){ result[j] = result[j] + second[i]*first[i][j]; } } return result; } vector<double> multiply_vectors(vector<double> first, vector<double> second){ vector<double> result(first.size()); int i; for (i=0; i<first.size(); i++){ result[i] = first[i]*second[i]; } return result; } vector<double> select_columns(vector<vector<double> > matrix, int column){ vector<double> ret_vec(matrix.size()); for (int i=0; i<matrix.size(); i++){ ret_vec[i] = matrix[i][column]; } return ret_vec; } int main(int argc, const char * argv[]) { string trans_matrix; getline (cin, trans_matrix); string emis_matrix; getline (cin, emis_matrix); string init_state_prob; getline (cin, init_state_prob); string sequence_emission; getline (cin, sequence_emission); float rows_trans, columns_trans; istringstream trans_stream_matrix = istringstream(trans_matrix); trans_stream_matrix >> rows_trans >> columns_trans; // Matrix transition vector<vector<double> > transition = initiliaze_matrix(trans_stream_matrix, rows_trans, columns_trans); istringstream emis_stream_matrix = istringstream(emis_matrix); emis_stream_matrix >> rows >> columns; // Matrix emision vector<vector<double> > emision = initiliaze_matrix(emis_stream_matrix, rows, columns); istringstream init_state_prob_stream = istringstream(init_state_prob); float rows_state; init_state_prob_stream >> rows_state; // Vector intitial state vector<double> init_state = initiliaze_vector(init_state_prob_stream); // should be converted to int // Vector emisions received istringstream sequence_em = istringstream(sequence_emission); vector<double> emission_vector = initiliaze_vector(sequence_em); // should be converted to int int number_obs = emission_vector.size(); // Matrices vector<int> emission_vector_new(emission_vector.begin(), emission_vector.end()); int M = 0; for (int i = 0; i<emission_vector_new.size(); i++){ if (emission_vector_new[i]>M){ M = emission_vector_new[i]; } } //vector<double> pi(init_state.size(), 1/init_state.size()); vector<double> pi(init_state.size()); pi = init_state; vector<vector<double> > a;//(init_state.size(),vector<double>(init_state.size())); // initialized transition matrix a = transition; // TODO : Check rows sum to 1 vector<vector<double> > b;//(init_state.size(),vector<double>(M+1)); // initialized transition matrix b = emision; // TODO : Check rows sum to 1 int iters = 0; double oldLogProb = -999999999999999999; int maxIters = 50; double logProb = 0; while (iters<maxIters and logProb>oldLogProb){ if (iters>0){ oldLogProb = logProb; } vector<vector<double> > alpha(number_obs,vector<double>(pi.size())); int column = emission_vector[0]; vector<double> column_vector = select_columns(b, column); vector<double> c(number_obs); for (int i = 0; i<pi.size(); i++){ alpha[0][i] = pi[i]*column_vector[i]; c[0] = c[0] + alpha[0][i]; } // scale a0(i) c[0] = 1/c[0]; for (int i = 0; i<pi.size(); i++){ alpha[0][i] = c[0] * alpha[0][i]; } // compute at(i) vector<double> column_v; for (int t=1; t<number_obs; t++){ // the first position (0) is consider before the loop c[t] = 0; column_v = select_columns(b, emission_vector[t]); for (int i=0; i<pi.size(); i++){ alpha[t][i] = 0; for (int j=0; j<pi.size(); j++){ alpha[t][i] = alpha[t][i] + alpha[t-1][j]*a[j][i]; } alpha[t][i] = alpha[t][i]*column_v[i]; c[t] = c[t] + alpha[t][i]; } // scale at(i) c[t] = 1/c[t]; for (int i=0; i<pi.size(); i++){ alpha[t][i] = c[t]*alpha[t][i]; } } vector<vector<double> > beta(number_obs,vector<double>(pi.size())); // the 0 is included vector<double> vect(pi.size(), 1); // initialize a vector to all 0's for (int i=0; i<pi.size(); i++){ beta[number_obs-1][i] = c[number_obs-1]; } // beta pass vector<double> column_beta; for (int t=number_obs-2; t >= 0; t--){ column_beta = select_columns(b, emission_vector[t+1]); for (int i=0; i<pi.size(); i++){ beta[t][i] = 0; for (int j=0; j<pi.size(); j++){ beta[t][i] = beta[t][i] + a[i][j]*column_beta[j]*beta[t+1][j]; } //scale beta_t beta[t][i] = c[t]*beta[t][i]; } } vector<vector<vector<double> > > mu_ij(number_obs , vector<vector<double>>(pi.size(), vector<double>(pi.size()))); vector<vector<double> > mu_i(number_obs , vector<double>(pi.size())); vector<double> column_mu; double denom = 0; for (int t = 0; t < number_obs-1; t++){ denom = 0; column_mu = select_columns(b, emission_vector[t+1]); for (int i=0; i<pi.size(); i++){ for (int j=0; j<pi.size(); j++){ denom = denom + alpha[t][i]*a[i][j]*column_mu[j]*beta[t+1][j]; } } for (int i=0; i<pi.size(); i++){ mu_i[t][i] = 0; for (int j=0; j<pi.size(); j++){ mu_ij[t][i][j] = alpha[t][i]*a[i][j]*column_mu[j]*beta[t+1][j] / denom; mu_i[t][i] = mu_i[t][i] + mu_ij[t][i][j]; } } } // Special case yT-1 for back-propagation denom = 0; for (int i=0; i<pi.size(); i++){ denom = denom + alpha[number_obs-1][i]; } for (int i=0; i<pi.size(); i++){ mu_i[number_obs-1][i] = alpha[number_obs-1][i] / denom; } for (int i=0 ; i<pi.size() ; i++){ pi[i] = mu_i[0][i]; } // re-estimate A double numerator, denominator = 0; for (int i=0 ; i<pi.size() ; i++){ for (int j=0 ; j<pi.size() ; j++){ numerator = 0; denominator = 0; for (int t=0 ; t<number_obs-1 ; t++){ numerator = numerator + mu_ij[t][i][j]; denominator = denominator + mu_i[t][i]; } a[i][j] = numerator / denominator; } } for (int i=0 ; i<pi.size() ; i++){ for (int j=0 ; j<M+1 ; j++){ numerator = 0; denominator = 0; for (int t=0 ; t<number_obs ; t++){ if (emission_vector_new[t] == j){ numerator = numerator + mu_i[t][i]; } denominator = denominator + mu_i[t][i]; } b[i][j] = numerator / denominator; } } logProb = 0; for (int i = 0; i < number_obs; i++){ logProb = logProb + log(c[i]); } logProb = -logProb; iters ++; } cout << a.size() << " " << a[0].size(); for (int i=0 ; i<pi.size() ; i++){ for (int j=0 ; j<pi.size() ; j++){ cout << " " << a[i][j]; } } cout << endl; cout << b.size() << " " << b[0].size(); for (int i=0 ; i<pi.size() ; i++){ for (int j=0 ; j<M+1 ; j++){ cout << " " << b[i][j]; } } cout << endl; return 0; }
/* SD card read/write This example shows how to read and write data to and from an SD card file The circuit: SD card attached to SPI bus as follows: ** MOSI - pin 11 ** MISO - pin 12 ** CLK - pin 13 ** CS - pin 4 */ int led0 = 23; int led1 = 25; int led2 = 27; char comdata; void setup() { pinMode(led0, OUTPUT); digitalWrite(led0, HIGH); pinMode(led1, OUTPUT); digitalWrite(led1, HIGH); pinMode(led2, OUTPUT); digitalWrite(led2, HIGH); Serial.begin(115200); //串口0 Serial1.begin(115200); Serial.println("initialization done.com0"); Serial1.println("initialization done.com1"); } void loop() { while (Serial1.available() > 0) { comdata = char(Serial1.read()); delay(2);//ms } led(); comdata = ' '; } void led(void) { switch (comdata) { case 'a': digitalWrite(led0, HIGH);//OFF Serial.println("led0 OFF"); break; case 'A': digitalWrite(led0, LOW);//ON Serial.println("led0 ON"); break; case 'b': digitalWrite(led1, HIGH);//OFF Serial.println("led1 OFF"); break; case 'B': digitalWrite(led1, LOW);//ON Serial.println("led1 ON"); break; case 'c': digitalWrite(led2, HIGH);//OFF Serial.println("led2 OFF"); break; case 'C': digitalWrite(led2, LOW);//ON Serial.println("led2 ON"); break; default: break; } }
#include <cstdio> #include <iomanip> #include <cmath> #include <algorithm> #include "database.h" DataBase::DataBase() : file(), index(), overflowPtr(Record::NO_PTR), overflowStart(Record::NO_PTR), overflowEnd(Record::NO_PTR), primaryAreaCount(0), overflowAreaCount(0) { } void DataBase::Open(std::string indexFileName, std::string dbFileName, std::string metadataFileName, bool clear, int* IOCounter, int reservedPages, bool tmp) { index.Open(indexFileName, IOCounter, clear); //CREATE NEW FILE if (clear) { file.Open(dbFileName, IOCounter, File::DEFAULT_OUTPUT_MODE); file.Close(); } file.Open(dbFileName, IOCounter, File::DEFAULT_INPUT_OUTPUT_MODE); //INIT FILE if (clear) { primaryAreaSize = reservedPages; int overflowAreaSize = static_cast<int>(std::ceil(primaryAreaSize * o)); file.CreateSpace(reservedPages + overflowAreaSize); overflowPtr = overflowStart = reservedPages * Page::BYTE_SIZE; overflowEnd = (reservedPages + overflowAreaSize) * Page::BYTE_SIZE; if (!tmp) { index.AddIndexRecord({ 0, 0 }); index.Save(); Insert({ 0, 0, 0 }); } } else ReadMetadata(metadataFileName); } void DataBase::Insert(Record r) { if (r.key < 0) // can not insert deleted record return; auto ptr = (Record*)file.buffer.data; auto pageId = index.GetPageId(r.key); file.ReadToBuffer(pageId); auto record = SearchMainArea(r.key); //UPDATE RECORD MAIN AREA if (record->isInitialized() && r.key > 0 && abs(record->key) == r.key) // r.key > 0 <=> can not update guard { if (record->key < 0) primaryAreaCount++; record->key = r.key; //if record was tagged as deleted, remove tag record->v = r.v; record->m = r.m; } //INSERT NEW RECORD (main area) else if(!record->isInitialized()) { record->key = r.key; record->v = r.v; record->m = r.m; primaryAreaCount++; } //UPDATE OR INSERT NEW RECORD (overflow area) else if(r.key > 0) // r.key > 0 <=> can not insert new guard { int offset; bool changedChain = false; //FOLLOW PTRS while (record->isInitialized() && abs(record->key) != r.key && record->ptr != Record::NO_PTR && !changedChain) { if (abs(record->key) > r.key) { r.ptr = record->ptr; std::swap(record->key, r.key); std::swap(record->m, r.m); std::swap(record->v, r.v); changedChain = true; break; } pageId = record->ptr / Page::BYTE_SIZE; offset = (record->ptr % Page::BYTE_SIZE)/Record::RECORD_SIZE; file.ReadToBuffer(pageId); record = ptr + offset; } if (record->isInitialized() && abs(record->key) != r.key) { record->ptr = overflowPtr; if (abs(record->key) > r.key) { std::swap(record->key, r.key); std::swap(record->m, r.m); std::swap(record->v, r.v); } file.buffer.changed = true; file.ReadToBuffer(overflowPtr / Page::BYTE_SIZE); record = ptr + (overflowPtr % Page::BYTE_SIZE) / Record::RECORD_SIZE; overflowPtr += Record::RECORD_SIZE; overflowAreaCount++; } if (record->isInitialized() && record->key < 0) overflowAreaCount++; record->key = r.key; record->v = r.v; record->m = r.m; record->ptr = r.ptr; file.buffer.changed = true; } file.buffer.changed = true; file.WriteBuffer(); if (overflowEnd == overflowPtr) Reorganize(); return; } bool DataBase::Delete(int key) { if (key <= 0) return false; bool mainArea = true; auto ptr = (Record*)file.buffer.data; auto pageId = index.GetPageId(key); file.ReadToBuffer(pageId); auto record = SearchMainArea(key); int offset = 0; while (record->isInitialized() && abs(record->key) != key && record->ptr != Record::NO_PTR) { mainArea = false; pageId = record->ptr / Page::BYTE_SIZE; offset = (record->ptr % Page::BYTE_SIZE) / Record::RECORD_SIZE; file.ReadToBuffer(pageId); record = ptr + offset; } if (!record->isInitialized() || abs(record->key) != key) return false; if (mainArea) primaryAreaCount--; else overflowAreaCount--; record->key = -abs(record->key); file.buffer.changed = true; file.WriteBuffer(); return true; } Record DataBase::Get(int key) { auto ptr = (Record*)file.buffer.data; auto pageId = index.GetPageId(key); file.ReadToBuffer(pageId); auto record = SearchMainArea(key); int offset = 0; while (record->isInitialized() && abs(record->key) != key && record->ptr != Record::NO_PTR) { pageId = record->ptr / Page::BYTE_SIZE; offset = (record->ptr % Page::BYTE_SIZE) / Record::RECORD_SIZE; file.ReadToBuffer(pageId); record = ptr + offset; } return *record; } Record DataBase::GetNext() { static int offset = 0, pageId = 0, overflowPageId = 0, overflowOffset = 0; static bool readOverflow = false; auto ptr = (Record*)file.buffer.data; Record record; if (pageId == primaryAreaSize) { offset = pageId = overflowPageId = overflowOffset = 0; readOverflow = false; return { 0, Record::UNINIT, Record::UNINIT }; } if (readOverflow) { file.ReadToBuffer(overflowPageId); record = ptr[overflowOffset]; if (ptr[overflowOffset].ptr == Record::NO_PTR) readOverflow = false; else { overflowPageId = ptr[overflowOffset].ptr / Page::BYTE_SIZE; overflowOffset = (ptr[overflowOffset].ptr % Page::BYTE_SIZE) / Record::RECORD_SIZE; } } else { file.ReadToBuffer(pageId); record = ptr[offset]; if(ptr[offset].ptr != Record::NO_PTR) { readOverflow = true; overflowPageId = ptr[offset].ptr / Page::BYTE_SIZE; overflowOffset = (ptr[offset].ptr % Page::BYTE_SIZE) / Record::RECORD_SIZE; } offset = (offset + 1) % Page::PAGE_SIZE; if (offset == 0 || !ptr[offset].isInitialized()) { offset = 0; pageId++; } } return record; } void DataBase::Reorganize() { DataBase tmp; std::cout << "\nREORGANIZE - START, IOCounter: " << *file.IOCounter << std::endl; auto newSize = static_cast<int>(std::ceil((primaryAreaCount + overflowAreaCount) / (Page::PAGE_SIZE * alfa))); tmp.Open(index.file.fileName + "_tmp", file.fileName + "_tmp", file.fileName + "_meta" ,true, file.IOCounter, newSize, true); std::cout << "REORGANIZE - CREATED NEW DB, IOCounter: " << *file.IOCounter << std::endl; auto ptr = (Record*)tmp.file.buffer.data; int pageId = 0; Record record = GetNext(); unsigned int q = 0; while (record.isInitialized()) { if (record.key < 0) { record = GetNext(); continue; } if (q == 0) { tmp.file.ReadToBuffer(pageId); tmp.index.AddIndexRecord({ record.key, pageId }); } record.ptr = Record::NO_PTR; tmp.file.buffer.changed = true; ptr[q] = record; q = (q + 1) % static_cast<int>((Page::PAGE_SIZE * alfa)); if (q == 0) pageId++; record = GetNext(); } std::cout << "REORGANIZE - COPIED OLD DB, IOCounter: " << *file.IOCounter << std::endl; tmp.primaryAreaCount = primaryAreaCount + overflowAreaCount; tmp.index.Save(); std::cout << "REORGANIZE - SAVED INDEX, IOCounter: " << *file.IOCounter << std::endl; tmp.GenerateMetadata(file.fileName + "_meta"); std::cout << "REORGANIZE - GENERATED METADATA, IOCounter: " << *file.IOCounter << std::endl; tmp.file.Close(); tmp.index.file.Close(); this->file.Close(); this->index.file.Close(); std::remove(index.file.fileName.c_str()); std::remove(file.fileName.c_str()); std::rename(tmp.index.file.fileName.c_str(), index.file.fileName.c_str()); std::rename(tmp.file.fileName.c_str(), file.fileName.c_str()); Open(index.file.fileName, file.fileName, file.fileName + "_meta", false, file.IOCounter); std::cout << "REORGANIZE - RENAMED AND REOPENED DB, IOCounter: " << *file.IOCounter << std::endl; } void DataBase::Info() { std::cout << "\nName: " << file.fileName << "\n" << "Primary area size: " << primaryAreaSize << "\n" << "Overflow area size: " << (overflowEnd - overflowStart) / Page::BYTE_SIZE << "\n" << "Overflow free ptr: " << overflowPtr << "\n" << "Records in main area: " << primaryAreaCount << "\n" << "Records in overflow: " << overflowAreaCount << "\n" << "BufferPageId: " << file.buffer.id << std::endl; } void DataBase::GenerateMetadata(std::string fileName) { File metadata(fileName, file.IOCounter, File::DEFAULT_OUTPUT_MODE); auto ptr = (int*)metadata.buffer.data; metadata.buffer.id = 0; metadata.buffer.changed = true; ptr[0] = primaryAreaCount; ptr[1] = overflowAreaCount; ptr[2] = overflowPtr; ptr[3] = overflowStart; ptr[4] = overflowEnd; ptr[5] = primaryAreaSize; metadata.WriteBuffer(); } void DataBase::ReadMetadata(std::string fileName) { File metadata(fileName, file.IOCounter, File::DEFAULT_INPUT_MODE); metadata.ReadToBuffer(0); auto ptr = (int*)metadata.buffer.data; primaryAreaCount = ptr[0]; overflowAreaCount = ptr[1]; overflowPtr = ptr[2]; overflowStart = ptr[3]; overflowEnd = ptr[4]; primaryAreaSize = ptr[5]; } void DataBase::Print() { int pageId = 0; auto ptr = (Record*)file.buffer.data; int overflowFirstPage = overflowStart / Page::BYTE_SIZE; std::cout << index << std::endl; std::cout << "File: " << std::endl; while (file.ReadToBuffer(pageId)) { std::cout << "\tPAGE " << std::setw(5) << std::left << pageId; if (pageId < overflowFirstPage) std::cout << std::setw(70) << std::setfill('#') << std::right << " PRIMARY"; else std::cout << std::setw(70) << std::setfill('#') << std::right << " OVERFLOW"; std::cout << "" << std::setfill(' ') << std::endl; for (int i = 0; i < Page::PAGE_SIZE; i++) std::cout << "\t\t" << std::setw(5) << std::right << i << ". " << ptr[i] << std::endl; pageId++; } } Record * DataBase::SearchMainArea(int key) { auto ptr = (Record*)file.buffer.data; Record* record = nullptr; for (int i = 0; i < Page::PAGE_SIZE; i++) { if (i == Page::BYTE_SIZE) record = ptr + Page::PAGE_SIZE - 1; else if (abs(ptr[i].key) <= key && ptr[i + 1].isInitialized() && abs(ptr[i + 1].key) > key) record = ptr + i; else if (ptr[i].isInitialized() && abs(ptr[i].key) == key) record = ptr + i; else if (!ptr[i].isInitialized()) record = ptr + i; if (record != nullptr) break; } return record; }
/* Copyright 2021 University of Manchester Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http: // www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include "acceleration_module_setup_interface.hpp" #include "table_data.hpp" namespace orkhestrafs::dbmstodspi { /** * @brief Class for noting which module has to fully sort the input table. */ class BlockingSortModuleSetup : public virtual AccelerationModuleSetupInterface { private: static void SortDataTableWhileMinimizingMinorRuns( const std::vector<int>& old_sorted_sequence, std::vector<int>& new_sorted_sequence, int record_count, int module_capacity); static void SortDataTableWhileMinimizingMajorRuns( const std::vector<int>& old_sorted_sequence, std::vector<int>& new_sorted_sequence, int record_count, int module_capacity); public: auto GetWorstCaseProcessedTables( const std::vector<int>& min_capacity, const std::vector<std::string>& input_tables, const std::map<std::string, TableMetadata>& data_tables, const std::vector<std::string>& output_table_names) -> std::map<std::string, TableMetadata> override; auto UpdateDataTable(const std::vector<int>& module_capacity, const std::vector<std::string>& input_table_names, std::map<std::string, TableMetadata>& resulting_tables) -> bool override; }; } // namespace orkhestrafs::dbmstodspi
#ifndef COLAT_H #define COLAT_H #include <iostream> #include <stdlib.h> #include "NodoT.h" using namespace std; template <typename T> class ColaT { private: NodoT<T>* extremo; NodoT<T>* cabeza; public: ColaT(){ cabeza = NULL; extremo = NULL; } ~ColaT(){ while(!laColaEstaVacia()){ cout << elimina() << endl; } extremo = NULL; } T primero(void){ return cabeza->dameTuValor(); } bool laColaEstaVacia(void){ return cabeza == NULL; } T elimina(void){ NodoT<T>* aux; T v; if(!laColaEstaVacia()){ aux = cabeza; cabeza = cabeza->dameTuSiguiente(); v = aux->dameTuValor(); delete(aux); return v; } else{ cout << "La cola esta vacia" << endl; exit(0); } } void suma(T v){ if(!laColaEstaVacia()){ extremo->modificaTuSiguiente(new NodoT<T>(v)); extremo = extremo->dameTuSiguiente(); } else cabeza = extremo = new NodoT<T>(v); } }; #endif // COLAT_H
/** * SMuFF Firmware * Copyright (C) 2019 Technik Gegg * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ /* * Module for timer & ISR routines */ #include "ZTimerLib.h" static void (*__timer1Hook)(void) = NULL; static void (*__timer3Hook)(void) = NULL; static void (*__timer4Hook)(void) = NULL; static void (*__timer5Hook)(void) = NULL; void ZTimer::setupTimer(IsrTimer timer, TimerPrescaler prescaler) { _timer = timer; stopTimer(); noInterrupts(); switch(_timer) { case TIMER1: TCCR1A = 0; TCCR1B = prescaler; TCCR1B |= _BV(WGM12); // CTC mode break; case TIMER3: TCCR3A = 0; TCCR3B = prescaler; TCCR3B |= _BV(WGM32); // CTC mode break; case TIMER4: TCCR4A = 0; TCCR4B = prescaler; TCCR4B |= _BV(WGM42); // CTC mode break; case TIMER5: TCCR5A = 0; TCCR5B = prescaler; TCCR5B |= _BV(WGM52); // CTC mode break; } setNextInterruptInterval(1000); interrupts(); } ISR(TIMER1_COMPA_vect) { if(__timer1Hook != NULL) __timer1Hook(); } ISR(TIMER3_COMPA_vect) { if(__timer3Hook != NULL) __timer3Hook(); } ISR(TIMER4_COMPA_vect) { if(__timer4Hook != NULL) __timer4Hook(); } ISR(TIMER5_COMPA_vect) { if(__timer5Hook != NULL) __timer5Hook(); } void ZTimer::setupTimerHook(void (*function)(void)) { switch(_timer) { case TIMER1: __timer1Hook = function; break; case TIMER3: __timer3Hook = function; break; case TIMER4: __timer4Hook = function; break; case TIMER5: __timer5Hook = function; break; } } void ZTimer::setNextInterruptInterval(unsigned int interval) { stopTimer(); switch(_timer) { case TIMER1: OCR1A = interval; TCNT1 = 0; break; case TIMER3: OCR3A = interval; TCNT3 = 0; break; case TIMER4: OCR4A = interval; TCNT4 = 0; break; case TIMER5: OCR5A = interval; TCNT5 = 0; break; } startTimer(); } unsigned int ZTimer::getOCRxA() { switch(_timer) { case TIMER1: return OCR1A; case TIMER3: return OCR3A; case TIMER4: return OCR4A; case TIMER5: return OCR5A; } return 0; } void ZTimer::setOCRxA(unsigned int value) { switch(_timer) { case TIMER1: OCR1A = value; break; case TIMER3: OCR3A = value; break; case TIMER4: OCR4A = value; break; case TIMER5: OCR5A = value; break; } } void ZTimer::setTCNTx(unsigned int value) { switch(_timer) { case TIMER1: TCNT1 = value; break; case TIMER3: TCNT3 = value; break; case TIMER4: TCNT4 = value; break; case TIMER5: TCNT5 = value; break; } } void ZTimer::startTimer() { switch(_timer) { case TIMER1: TIMSK1 |= _BV(OCIE1A); break; case TIMER3: TIMSK3 |= _BV(OCIE3A); break; case TIMER4: TIMSK4 |= _BV(OCIE4A); break; case TIMER5: TIMSK5 |= _BV(OCIE5A); break; } } void ZTimer::stopTimer() { switch(_timer) { case TIMER1: TIMSK1 &= ~_BV(OCIE1A); break; case TIMER3: TIMSK3 &= ~_BV(OCIE3A); break; case TIMER4: TIMSK4 &= ~_BV(OCIE4A); break; case TIMER5: TIMSK5 &= ~_BV(OCIE5A); break; } }
// // Created by JACK on 9/14/2015. // #include "soft.h" #include <iostream> #include <string.h> #include <stdlib.h> #include <sstream> using namespace std; soft::soft():name(nullptr), extension(nullptr), size(0), date(nullptr), time(nullptr){} soft::soft(char* name,char* extension,float size,char* date,char* time) { this -> name = new char[strlen(name) + 1]; strcpy(this -> name, name); this -> extension = new char[strlen(extension) + 1]; strcpy(this -> extension, extension); this -> size = size; this -> date = new char[strlen(date) + 1]; strcpy(this -> date, date); this -> time = new char[strlen(time) + 1]; strcpy(this -> time, time); system("cls"); } void soft::print() { cout << "Name: " << name << endl; cout << "Extension: " << extension << endl; cout << "Size: " << size << " MB" << endl; cout << "Date: " << date << endl; cout << "Time: " << time << endl; } void soft::modify_name() { if(name) { delete [] name; name = nullptr; char aux_name[20]; cout << "Give the new name:" << endl; cin >> aux_name; name = new char[strlen(aux_name+1)]; strcpy(name,aux_name); } } void soft::modify_extension() { if(extension) { delete[] extension; extension = nullptr; char aux_extension[20]; cout << "Give the new extension:" << endl; cin >> aux_extension; extension = new char[strlen(aux_extension +1)]; strcpy(extension,aux_extension); } } soft::soft(string name) { istringstream iss(name); int iterator = 0; do { iterator ++; if(iterator == 1) { this -> name = new char[20]; iss >> this-> name; } else if (iterator == 2) { extension = new char[20]; iss >> extension; } else if (iterator == 3) { iss >> size; } else if (iterator == 4) { date = new char[20]; iss >> date; } else if (iterator == 5) { time = new char[20]; iss >> time; } else break; } while (iss); } soft::~soft() { if(name){ delete [] name; name = nullptr; } if(extension){ delete [] extension; extension = nullptr; } if(date){ delete [] date; date = nullptr; } if(time) { delete[] time; time = nullptr; } size = 0; } soft::soft(const soft& soft1) : size(soft1.size) { name = new char(strlen(soft1.name)+1); strcpy(name,soft1.name); extension = new char(strlen(soft1.extension)+1); strcpy(extension,soft1.extension); date = new char(strlen(soft1.date)+1); strcpy(date,soft1.date); time = new char(strlen(soft1.time)+1); strcpy(time,soft1.time); }
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __DRM_INFO_H__ #define __DRM_INFO_H__ #include "drm_framework_common.h" namespace android { /** * This is an utility class in which necessary information required to transact * between device and online DRM server is described. DRM Framework achieves * server registration, license acquisition and any other server related transaction * by passing an instance of this class to DrmManagerClient::processDrmInfo(const DrmInfo*). * * The Caller can retrieve the DrmInfo instance by using * DrmManagerClient::acquireDrmInfo(const DrmInfoRequest*) by passing DrmInfoRequest instance. * */ class DrmInfo { public: /** * Constructor for DrmInfo * * @param[in] infoType Type of information * @param[in] drmBuffer Trigger data * @param[in] mimeType MIME type */ DrmInfo(int infoType, const DrmBuffer& drmBuffer, const String8& mimeType); /** * Destructor for DrmInfo */ virtual ~DrmInfo() {} public: /** * Iterator for key */ class KeyIterator { friend class DrmInfo; private: KeyIterator(const DrmInfo* drmInfo) : mDrmInfo(const_cast <DrmInfo*> (drmInfo)), mIndex(0) {} public: KeyIterator(const KeyIterator& keyIterator); KeyIterator& operator=(const KeyIterator& keyIterator); virtual ~KeyIterator() {} public: bool hasNext(); const String8& next(); private: DrmInfo* mDrmInfo; unsigned int mIndex; }; /** * Iterator */ class Iterator { friend class DrmInfo; private: Iterator(const DrmInfo* drmInfo) : mDrmInfo(const_cast <DrmInfo*> (drmInfo)), mIndex(0) {} public: Iterator(const Iterator& iterator); Iterator& operator=(const Iterator& iterator); virtual ~Iterator() {} public: bool hasNext(); String8& next(); private: DrmInfo* mDrmInfo; unsigned int mIndex; }; public: /** * Returns information type associated with this instance * * @return Information type */ int getInfoType(void) const; /** * Returns MIME type associated with this instance * * @return MIME type */ String8 getMimeType(void) const; /** * Returns the trigger data associated with this instance * * @return Trigger data */ const DrmBuffer& getData(void) const; /** * Returns the number of attributes contained in this instance * * @return Number of attributes */ int getCount(void) const; /** * Adds optional information as <key, value> pair to this instance * * @param[in] key Key to add * @param[in] value Value to add * @return Returns the error code */ status_t put(const String8& key, const String8& value); /** * Retrieves the value of given key * * @param key Key whose value to be retrieved * @return The value */ String8 get(const String8& key) const; /** * Returns KeyIterator object to walk through the keys associated with this instance * * @return KeyIterator object */ KeyIterator keyIterator() const; /** * Returns Iterator object to walk through the values associated with this instance * * @return Iterator object */ Iterator iterator() const; /** * Returns index of the given key * * @return index */ int indexOfKey(const String8& key) const; protected: int mInfoType; DrmBuffer mData; String8 mMimeType; KeyedVector<String8, String8> mAttributes; }; }; #endif /* __DRM_INFO_H__ */
/* * AndroidEngine.h * * Created on: May 1, 2012 * Author: iwasz */ #ifndef ANDROIDENGINE_H_ #define ANDROIDENGINE_H_ #include <android/sensor.h> #include <EGL/egl.h> #include "android_native_app_glue.h" #include "AndroidCmdDispatcher.h" #include "AndroidInputDispatcher.h" namespace Util { struct AndroidEngine { AndroidEngine () : androidApp (NULL), sensorManager (NULL), display (NULL), surface (NULL), context (NULL), running (false) {} struct android_app* androidApp; ASensorManager* sensorManager; EGLDisplay display; EGLSurface surface; EGLContext context; bool running; Event::AndroidCmdDispatcher cmdDispatcher; Event::AndroidInputDispatcher inputDispatcher; }; } /* namespace Util */ #endif /* ANDROIDENGINE_H_ */
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2009 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ /** * @file OpTrustAndSecurityButton.h * * Button that is used to display encryption and trust information in the address bar. * * @author rfz@opera.com (created by mariusab@opera.com) */ #ifndef OP_TRUST_AND_SECURITY_BUTTON_H #define OP_TRUST_AND_SECURITY_BUTTON_H #include "adjunct/quick/windows/DocumentDesktopWindow.h" #include "modules/widgets/OpButton.h" /** * Class OpTrustAndSecurityButton is the button used to * display encryption and trust information in the address bar. * * The rationale for making this button its own class is to * collect all logic related to appearance and visibility of * this button in one, easily maintainable, place. * * Note that the Type of this derived class when asked will be * that of the superclass, OpButton and OpWidgetInfo will use * that since this class does not overload the method. */ class OpTrustAndSecurityButton : public OpButton { public: /** * Constructor. */ OpTrustAndSecurityButton(); static OP_STATUS Construct(OpTrustAndSecurityButton** obj); /** * Set trust and security level based on windowcommander. * * @param button_text The cn (lo) text on the button if it exists. * @param wic Commander of window in question, provides information about page. * @param show_server_name don't use elablorate info from certificates etc, but use server name * @param always_visible don't let visibility depend on whether the connection to the server is secure * * @return TRUE if the state of the button changed, false otherwise. */ BOOL SetTrustAndSecurityLevel( const OpString &button_text, OpWindowCommander* wic, OpAuthenticationCallback* callback = NULL, BOOL show_server_name = FALSE, BOOL always_visible = FALSE); /** * Function to get easy access to whether the button needs to be visible, * based on the state of the document passed it with * SetTrustAndSecurityLevel. The rules for the button visibility * are collected in this function. */ BOOL ButtonNeedsToBeVisible(); void SuppressText(BOOL suppress); virtual const char* GetInputContextName() {return "TrustAndSecurity Button";} // We never want this button to have focus so override the function virtual void SetFocus(FOCUS_REASON reason) {} /** * * @param rect * @param height */ void GetRequiredSize(INT32& width, INT32& height); /** * If the type of URL is https return TRUE */ #ifdef SECURITY_INFORMATION_PARSER BOOL URLTypeIsHTTPS() { return m_url_type == OpWindowCommander::WIC_URLType_HTTPS; } #else // SECURITY_INFORMATION_PARSER BOOL URLTypeIsHTTPS() { return FALSE; } #endif // SECURITY_INFORMATION_PARSER virtual BOOL HasToolTipText(OpToolTip* tooltip) { return string.GetWidth() > GetWidth(); } virtual INT32 GetToolTipDelay(OpToolTip* tooltip) { return 0; } // Show this right away virtual BOOL AlwaysShowHiddenContent() { return string.GetWidth() > GetWidth(); } private: // Functions to move the actual button modification out of the // structure that selects based on the mode and level, in order // to make that set of if/elsifs more readable. void SetFraudAppearance(); ///< Sets the button to indicate fraud void SetSecureAppearance(const OpString &button_text); ///< Sets the button to indicate security. void SetInsecureAppearance(); void SetUnknownAppearance(); ///< Sets the button to indicate unknown site void SetKnownAppearance(); ///< Sets the button to indicate known, trusted site void SetHighAssuranceAppearance(const OpString &button_text); ///< Sets the button to indicate that the site has extended validation. OP_STATUS SetText(const uni_char* text); // The following may or may not be needed... /** * The security mode of the document in question */ OpDocumentListener::SecurityMode m_sec_mode; BOOL m_suppress_text; #ifdef TRUST_RATING /** * The trust level of the document as fetched from the server. */ OpDocumentListener::TrustMode m_trust_mode; #endif // TRUST_RATING /** * The server name of the document. */ OpString m_server_name; OpString m_button_text; #ifdef SECURITY_INFORMATION_PARSER OpWindowCommander::WIC_URLType m_url_type; #endif // SECURITY_INFORMATION_PARSER }; #endif //OP_TRUST_AND_SECURITY_BUTTON_H
// // main.cpp // BinarySearch // // Created by Prateek Khandelwal on 4/8/15. // Copyright (c) 2015 Prateek Khandelwal. All rights reserved. // #include <iostream> #include <algorithm> #include <vector> #include <fstream> #include <sstream> #include <cstdlib> #include <cstdio> using namespace std; int binarySearchIterative(int target, int *a, int n) { int lo = 0, hi = n - 1, mid; while (lo <= hi) { mid = (lo + hi) / 2; if (a[mid] == target) { return mid; } else if (a[mid] < target) { lo = mid + 1; } else { hi = mid - 1; } } return -1; } int binarySearchRecursive(int target, int *a, int n) { int mid = n / 2, rightMid; if (n == 1 && *a != target) { return -1; } if (*(a + mid) == target) { return mid; } else if (*(a + mid) < target && (rightMid = binarySearchRecursive(target, a + mid, n - n/2)) != -1) { return mid + rightMid; } else { return binarySearchRecursive(target, a, n/2); } } int binarySearchRecursive1(int target, int *a, int n, int low) { int mid = n / 2; if (n == 1 && *a != target) { return -1; } if (*(a + mid) == target) { return low + mid; } else if (*(a + mid) < target) { return binarySearchRecursive1(target, a + mid, n - mid, low + mid); } else { return binarySearchRecursive1(target, a, mid, low); } } int main () { int n, target; cin >> n; int a[n]; for (int i = 0; i < n; i++) { cin >> a[i]; } cin >> target; cout << binarySearchIterative(target, a, n) << endl; cout << binarySearchRecursive(target, a, n) << endl; cout << binarySearchRecursive1(target, a, n, 0) << endl; return 0; }
#pragma once #include "qresource.h" #include <qEngine/DynamicVB.h> namespace qEngine { class qDynamicVB : public qResource { public: qDynamicVB(void); ~qDynamicVB(void); }; }
#include <stdio.h> #include <iostream> #include "sha256.h" #include <string.h> #include <sqlite3.h> #include <ctime> using namespace std; char choice; sqlite3* db; string signedInUser; void promptUser(){ start: cout << "Type 's' for Sign-In or 'r' for Register New User: " << endl; cin >> choice; if ((choice != 's') && (choice !='r')){ goto start; } } static int callback(void *NotUsed, int argc, char **argv, char **azColName){ int i; for(i=0; i<argc; i++){ printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL"); } printf("\n"); return 0; } void registerUser(){ regStart: string username; string password; char *zErrMsg = 0; int rc; cout << "Enter a New Username: " << endl; getline(cin,username); char * selectQuery = "SELECT USERNAME FROM USERS;"; sqlite3_stmt *selectStmt; sqlite3_prepare(db, selectQuery, strlen(selectQuery)+1, &selectStmt, NULL); while (1) { int s; //printf("in select while\n"); s = sqlite3_step(selectStmt); if (s == SQLITE_ROW) { const unsigned char * text; //text = sqlite3_column_text (selectStmt, 0); string stext = string(reinterpret_cast<const char*>(sqlite3_column_text(selectStmt,0))); if(username==stext){ printf("Username already used.\n"); sqlite3_finalize(selectStmt); goto regStart; break; } } else if (s == SQLITE_DONE) { break; } } sqlite3_finalize(selectStmt); cout << "Enter a Password: " << endl; getline(cin,password); string hashPass = sha256(password); char str1[1000]; //char* sql = "INSERT INTO USERS(USERNAME, PASSWORD) VALUES('"; char* q = "','"; char* g = "');"; strcpy(str1,"INSERT INTO USERS(USERNAME, PASSWORD) VALUES('"); strcat(str1,username.c_str()); strcat(str1,q); strcat(str1,hashPass.c_str()); strcat(str1,g); rc = sqlite3_exec(db, str1, callback, 0, NULL); if( rc != SQLITE_OK ){ fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); }else{ //fprintf(stdout, "Table created successfully\n"); } //cout << "register complete" << endl; signedInUser = username; } void signIn() { signStart: string username; string password; char *zErrMsg = 0; int rc; cout << "Please Enter Username: " << endl; getline(cin,username); cout << "Please Enter Password: " << endl; getline(cin,password); string hashPass = sha256(password); password = ""; char * selectQuery = "SELECT * FROM USERS;"; sqlite3_stmt *selectStmt; sqlite3_prepare(db, selectQuery, strlen(selectQuery)+1, &selectStmt, NULL); while (1) { int s; s = sqlite3_step(selectStmt); if (s == SQLITE_ROW) { //const unsigned char * text; //text = sqlite3_column_text (selectStmt, 0); string d_user = string(reinterpret_cast<const char*>(sqlite3_column_text(selectStmt,0))); string d_pass = string(reinterpret_cast<const char*>(sqlite3_column_text(selectStmt,1))); if(username==d_user && hashPass==d_pass){ signedInUser = username; printf("Sign in successful\n"); break; } } else if (s == SQLITE_DONE) { printf("Invalid Username/Password\n"); sqlite3_finalize(selectStmt); goto signStart; } } sqlite3_finalize(selectStmt); //sign in to database } void showMessages() { char *zErrMsg = 0; int rc; char str1[1000]; //char * selectQuery = "select count(receiver) from messages where read = 0 and receiver = "; char* g = "';"; sqlite3_stmt *selectStmt; strcpy(str1,"select count(receiver) from messages where receiver = '"); strcat(str1,signedInUser.c_str()); strcat(str1,g); sqlite3_prepare(db, str1, strlen(str1)+1, &selectStmt, NULL); while (1) { int s; s = sqlite3_step(selectStmt); if (s == SQLITE_ROW) { //const unsigned char * text; //text = sqlite3_column_text (selectStmt, 0); int total = sqlite3_column_int(selectStmt, 0); cout << "You have " << total << " total message(s). " << endl; } else if (s == SQLITE_DONE) { break; } } sqlite3_finalize(selectStmt); strcpy(str1,"select sender from messages where receiver = '"); strcat(str1,signedInUser.c_str()); strcat(str1,g); cout << "Messages from:" << endl; sqlite3_prepare(db, str1, strlen(str1)+1, &selectStmt, NULL); while (1) { int s; s = sqlite3_step(selectStmt); if (s == SQLITE_ROW) { const unsigned char * sender; sender = sqlite3_column_text (selectStmt, 0); cout << sender << endl; } else if (s == SQLITE_DONE) { break; } } sqlite3_finalize(selectStmt); } void readMessage() { char *zErrMsg = 0; int rc; char str1[1000]; char* a = "' and sender = '"; char* g = "';'"; sqlite3_stmt *selectStmt; string readMessageFrom; string pPhrase; readStart: getline(cin,readMessageFrom); cout << "Who's message would you like to read?" << endl; getline(cin,readMessageFrom); //check to make sure this person has a message to be read. strcpy(str1,"select message,passphrase,mlength from messages where receiver = '"); strcat(str1,signedInUser.c_str()); strcat(str1,a); strcat(str1,readMessageFrom.c_str()); strcat(str1,g); sqlite3_prepare(db, str1, strlen(str1)+1, &selectStmt, NULL); while (1) { int s; s = sqlite3_step(selectStmt); if (s == SQLITE_ROW) { string message; // const unsigned char * passphrase; //decrypt here message = string(reinterpret_cast<const char*>(sqlite3_column_text(selectStmt, 0))); string passphrase = string(reinterpret_cast<const char*>(sqlite3_column_text(selectStmt,1))); int mLength; mLength = sqlite3_column_int(selectStmt, 2); cout << "Enter Pin Number: "; getline(cin,pPhrase); if(passphrase == sha256(pPhrase)){ cout << "Message from " << readMessageFrom << ":" << endl; ////////// string decrypt; decrypt = ""; int lower; lower = min((int)(pPhrase.size()), mLength); for (int i = 0; i < mLength; i++){ decrypt += message[i] ^ ((pPhrase[i % lower]) ); } ////////// //message = decrypt; cout << decrypt << endl; }else{ cout << "Passphrase does not match" << endl; goto readStart; } } else if (s == SQLITE_DONE) { break; } } sqlite3_finalize(selectStmt); } void writeMessage() { char *zErrMsg = 0; int rc; char str1[1000]; char* c = "','"; char* g = "');"; sqlite3_stmt *selectStmt; string sendMessageTo; string message; int pinNumber; string passphrase; getline(cin,sendMessageTo); cout << "To: "; getline(cin,sendMessageTo); cout << "Message: "; getline(cin,message); cout << "Pin Number [Must be positive integer]: "; //getline(cin,passphrase); cin >> pinNumber; if(cin.fail()){ cout << "Pin invalid." << endl; exit(EXIT_FAILURE); } else if(pinNumber <= 0){ cout << "Pin invalid." << endl; exit(EXIT_FAILURE); } else{ passphrase = std::to_string(pinNumber); } //for(i = 0; i < passphrase.size(); i++){ // if(passphrase[i] !='1') //} string hashPassphrase = sha256(passphrase); //encrypt message //check to make sure this person is in the system. int mLength = message.length(); char mLen[100]; sprintf(mLen, "%d", mLength); ////////// string encrypt; string temp; temp = min(message, passphrase); int min; min = temp.size(); encrypt = ""; for (int i = 0; i < message.size(); i++){ encrypt += message[i] ^ ((passphrase[i % min]) ); } message = ""; /////////// char* a1 = "',"; char* a2 = ",'"; strcpy(str1,"insert into messages(sender,receiver,message,mlength,passphrase) values('"); strcat(str1,signedInUser.c_str()); strcat(str1,c); strcat(str1,sendMessageTo.c_str()); strcat(str1,c); strcat(str1,encrypt.c_str()); strcat(str1,a1); strcat(str1,mLen); strcat(str1,a2); strcat(str1,hashPassphrase.c_str()); strcat(str1,g); rc = sqlite3_exec(db, str1, callback, 0, NULL); if( rc != SQLITE_OK ){ fprintf(stderr, "SQL error: %s\n", "Message full for this user."); sqlite3_free(zErrMsg); }else{ cout << "Message Sent" << endl; } } int main(){ char *zErrMsg = 0; int rc; rc = sqlite3_open("mail.db", &db); if( rc ){ fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); sqlite3_close(db); return 1; }; string username; promptUser(); // dummy get line needed. getline(cin,username); if (choice == 's'){ signIn(); } else if(choice == 'r'){ registerUser(); } choice = 'a'; showMessages(); bool readWrite; mark1: cout << "Type 'r' to Read a Message, 'w' to Write a Message, or 'q' to Sign Out: " << endl; cin >> choice; cout << endl; if ((choice != 'r') && (choice !='w') && (choice != 'q')){ goto mark1; } if (choice == 'r'){ readMessage(); } else if(choice == 'w'){ writeMessage(); } else if(choice == 'q'){ return 1; } goto mark1; sqlite3_close(db); }
/** * @file utils.h * * @brief Provide some miscellaneous tools for use throughout the code. * * @version 0.1 * @date 2021-06-21 * * @copyright Copyright (c) 2021 * */ #include "globals.h" #ifndef UTILS_PIO_H #define UTILS_PIO_H namespace Utils { /** * @brief The namespace for all the serial communication that can be used. * * @todo Rename finalSerialByte and then find a new location for it. I don't love finalSerialByte * being placed here, but it will work for now. * */ namespace LEDSerial{ // boolean that tells us if the serial has already been initialized. extern bool serialInitialized;// = false; extern char finalSerialByte;// = '\0'; /** * @brief Initialize the program serial. * * @note If serial is already initialized, then initialize serial wont do anything. */ void initializeSerial(unsigned long baudRate = BAUD); /** * @brief Writes serial data. * * @tparam T * @param datum */ template<typename T> void print(T datum); /** * @brief Print char array until a given byte or specified length * * @param buffer * @param endbyte */ void print_char_until(const char * buffer, char endbyte, int length); /** * @brief Return true if there is serial available. * * @return true * @return false */ bool serialAvailable(); /** * @brief Read a serial data stream until a given byte is seen. * * @note Forward write iterator is required. * The iterator must support operator++ and write. * (Since these are the only required operations, a char * will work) * * @note Terminating character is not read into the buffer. * * @param endByte The terminating byte * @param buffer The buffer to read into * @param length The maximum read length * @param timeout The time until the read should fail for taking too long * * @return True * False * -> Returns false if the read fails. Returns true otherwise. */ bool readSerialUntil(char endByte, char * buffer, unsigned int length = MAX_MESSAGE_LENGTH, unsigned long timeout = 1000); /** * @brief Print buffer to serial until length number of bytes have been sent * * @param buffer * @param length * @return true * @return false */ void printSerialUntilLength(const char * buffer, unsigned int length); }; /** * @brief Retrieve a random number. * * @note This function gaurentees a cryptographically secure random number. * * @return unsigned int */ unsigned int random(); /** * @brief Namespace housing the comparison tools. * */ namespace Compare { /** * @brief Compare '\0' terminated c-strings. * * @note do not use this function if cryptography is important (ex. password comparison) * * @param c_str1 * @param c_str2 * @return true * @return false */ bool cstrcmp(const char *c_str1, const char *c_str2); /** * @brief Compare two char arrays * * @note Do not need to be '\0' terminated, but their length must be known prior to * using this function. * * @note do not use this function if cryptography is important (ex. password comparison) * * @param c_str1 * @param c_str1_len * @param c_str2 * @param c_str2_len * @return true * @return false */ bool cstrcmp(const char *c_str1, unsigned int c_str1_len, const char *c_str2, unsigned int c_str2_len); }; /** * @brief Functionality regaurding asserts which can be used in the program. * */ namespace Asserts { /** * @brief Create a dynamic assertion that will only pass if val == PASS. * * @tparam PASS - required value needed for the assert to pass * @tparam STRICT - If true, the program will reset on a failure. * @param val */ template <bool PASS_VAL, bool STRICT = false> bool runtime_assert(bool val); }; /** * @brief Provide interface for different tools that can be used to interface with the program. * */ namespace Program { /** * @brief This allows the program to be completely reset in software. * * @note This works by creating an invalid call, causing freeRTOS to stop the program and reboot. * Use this carefully. * */ extern void (*RESET)(void); }; /** * @brief Check if a value is a nullptr. * * @tparam T * @param val * @return true * @return false */ template<typename T> bool is_nullptr(T val); }; #endif
#include <simpleProtocolParser.h> #include "serialParserStates.h" SimpleProtocolParser::SimpleProtocolParser() { pState = std::make_shared<WaitForStart>(this); } void SimpleProtocolParser::receiveChar(char received) { pState->receiveChar(received); } void SimpleProtocolParser::setState(std::shared_ptr<ParserState> state) { pState = state; }
#ifndef MILLWRIGHT_H #define MILLWRIGHT_H #include "employee.h" class Millwright : public Employee { private: bool department_; public: Millwright(); void setDepartment(string str); bool getDepartment(){return department_;} }; #endif // MILLWRIGHT_H
#include "bitmap_persister.h" #include "../core/types.h" #include "../include/bitmap_image.hpp" namespace persistence { model::Image *BitmapPersister::load(const std::string &fileName) { bitmap_image bmp(fileName); model::Image *image = new model::Image(bmp.width(), bmp.height()); for (unsigned x = 0; x < bmp.width(); ++x) { for (unsigned y = 0; y < bmp.height(); ++y) { core::byte red, green, blue; bmp.get_pixel(x, y, red, green, blue); image->setRed(x, y, red); image->setGreen(x, y, green); image->setBlue(x, y, blue); } } return image; } void BitmapPersister::save(model::Image *image, const std::string &fileName) { bitmap_image bmp(image->width(), image->height()); for (unsigned x = 0; x < bmp.width(); ++x) { for (unsigned y = 0; y < bmp.height(); ++y) { if (image->alpha(x, y) == core::BYTE_MAX) { bmp.set_pixel(x, y, image->red(x, y), image->green(x, y), image->blue(x, y)); } else { bmp.set_pixel(x, y, core::BYTE_MIN, core::BYTE_MIN, core::BYTE_MIN); } } } bmp.save_image(fileName); } }
// // nehe28.cpp // NeheGL // // Created by Andong Li on 10/7/13. // Copyright (c) 2013 Andong Li. All rights reserved. // #include "nehe28.h" const char* NEHE28::TITLE = "NEHE28"; GLfloat NEHE28::sleepTime = 0.0f; int NEHE28::frameCounter = 0; int NEHE28::currentTime = 0; int NEHE28::lastTime = 0; char NEHE28::FPSstr[15] = "Calculating..."; GLfloat NEHE28::rotz = 0.0f; BEZIER_PATCH NEHE28::mybezier; // just for declaration bool NEHE28::showCPoints=true; int NEHE28::divs = 7; bool NEHE28::keys[256] = {}; //all set to false bool NEHE28::specialKeys[256] = {}; //all set to false GLvoid NEHE28::ReSizeGLScene(GLsizei width, GLsizei height){ // Prevent A Divide By Zero By if(height==0) { height=1; } // Reset The Current Viewport glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); // Calculate The Aspect Ratio Of The Window gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f); //gluPerspective(80.0f,(GLfloat)width/(GLfloat)height, 1.0, 5000.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } bool NEHE28::LoadGLTextures(const char* dir, GLuint* texPntr){ glGenTextures(1, texPntr); /* load an image file directly as a new OpenGL texture */ *texPntr = SOIL_load_OGL_texture ( Utils::getAbsoluteDir(dir), SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_INVERT_Y ); if(*texPntr == 0){ return false; } // Typical Texture Generation Using Data From The Bitmap glBindTexture(GL_TEXTURE_2D, *texPntr); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); return true; } // Adds 2 Points. Don't Just Use '+' ;) POINT_3D NEHE28::pointAdd(POINT_3D p, POINT_3D q){ p.x += q.x; p.y += q.y; p.z += q.z; return p; } // Multiplies A Point And A Constant. Don't Just Use '*' POINT_3D NEHE28::pointTimes(double c, POINT_3D p){ p.x *= c; p.y *= c; p.z *= c; return p; } // Function For Quick Point Creation POINT_3D NEHE28::makePoint(double a, double b, double c){ POINT_3D p; p.x = a; p.y = b; p.z = c; return p; } // Calculates 3rd Degree Polynomial Based On Array Of 4 Points // And A Single Variable (u) Which Is Generally Between 0 And 1 POINT_3D NEHE28::Bernstein(float u, POINT_3D *p){ POINT_3D a, b, c, d, r; a = pointTimes(pow(u,3), p[0]); b = pointTimes(3*pow(u,2)*(1-u), p[1]); c = pointTimes(3*u*pow((1-u),2), p[2]); d = pointTimes(pow((1-u),3), p[3]); r = pointAdd(pointAdd(a, b), pointAdd(c, d)); return r; } // Generates A Display List Based On The Data In The Patch // And The Number Of Divisions GLuint NEHE28::genBezier(BEZIER_PATCH patch, int divs){ int u = 0; int v; float py; float px; float pyold; GLuint drawlist = glGenLists(1); // Make The Display List POINT_3D temp[4]; POINT_3D *last = (POINT_3D*)malloc(sizeof(POINT_3D)*(divs+1)); // Array Of Points To Mark The First Line Of Polys if (patch.dlBPatch != 0) // Get Rid Of Any Old Display Lists glDeleteLists(patch.dlBPatch, 1); temp[0] = patch.anchors[0][3]; // The First Derived Curve (Along X-Axis) temp[1] = patch.anchors[1][3]; temp[2] = patch.anchors[2][3]; temp[3] = patch.anchors[3][3]; for (v=0;v<=divs;v++) { // Create The First Line Of Points px = ((float)v)/((float)divs); // Percent Along Y-Axis // Use The 4 Points From The Derived Curve To Calculate The Points Along That Curve last[v] = Bernstein(px, temp); } glNewList(drawlist, GL_COMPILE); // Start A New Display List glBindTexture(GL_TEXTURE_2D, patch.texture); // Bind The Texture for (u=1;u<=divs;u++) { py = ((float)u)/((float)divs); // Percent Along Y-Axis pyold = ((float)u-1.0f)/((float)divs); // Percent Along Old Y Axis temp[0] = Bernstein(py, patch.anchors[0]); // Calculate New Bezier Points temp[1] = Bernstein(py, patch.anchors[1]); temp[2] = Bernstein(py, patch.anchors[2]); temp[3] = Bernstein(py, patch.anchors[3]); glBegin(GL_TRIANGLE_STRIP); // Begin A New Triangle Strip for (v=0;v<=divs;v++) { px = ((float)v)/((float)divs); // Percent Along The X-Axis glTexCoord2f(pyold, px); // Apply The Old Texture Coords glVertex3d(last[v].x, last[v].y, last[v].z); // Old Point last[v] = Bernstein(px, temp); // Generate New Point glTexCoord2f(py, px); // Apply The New Texture Coords glVertex3d(last[v].x, last[v].y, last[v].z); // New Point } glEnd(); // END The Triangle Strip } glEndList(); // END The List free(last); // Free The Old Vertices Array return drawlist; // Return The Display List } void NEHE28::initBezier() { mybezier.anchors[0][0] = makePoint(-0.75, -0.75, -0.50); // Set The Bezier Vertices mybezier.anchors[0][1] = makePoint(-0.25, -0.75, 0.00); mybezier.anchors[0][2] = makePoint( 0.25, -0.75, 0.00); mybezier.anchors[0][3] = makePoint( 0.75, -0.75, -0.50); mybezier.anchors[1][0] = makePoint(-0.75, -0.25, -0.75); mybezier.anchors[1][1] = makePoint(-0.25, -0.25, 0.50); mybezier.anchors[1][2] = makePoint( 0.25, -0.25, 0.50); mybezier.anchors[1][3] = makePoint( 0.75, -0.25, -0.75); mybezier.anchors[2][0] = makePoint(-0.75, 0.25, 0.00); mybezier.anchors[2][1] = makePoint(-0.25, 0.25, -0.50); mybezier.anchors[2][2] = makePoint( 0.25, 0.25, -0.50); mybezier.anchors[2][3] = makePoint( 0.75, 0.25, 0.00); mybezier.anchors[3][0] = makePoint(-0.75, 0.75, -0.50); mybezier.anchors[3][1] = makePoint(-0.25, 0.75, -1.00); mybezier.anchors[3][2] = makePoint( 0.25, 0.75, -1.00); mybezier.anchors[3][3] = makePoint( 0.75, 0.75, -0.50); mybezier.dlBPatch = NULL; // Go Ahead And Initialize This To NULL } GLvoid NEHE28::InitGL(){ //give the relative directory of image under current project folder if(!LoadGLTextures("NeheGL/img/NeHe.png", &(mybezier.texture))){ cout<<"Fail to load textures"<<endl; } initBezier(); mybezier.dlBPatch = genBezier(mybezier, divs); // Enable Texture Mapping glEnable(GL_TEXTURE_2D); // Enables Smooth Shading glShadeModel(GL_SMOOTH); // clear background as black glClearColor(0.05f, 0.05f, 0.05f, 0.5f); glClearDepth(1.0f); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); // want the best perspective correction to be done glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); } GLvoid NEHE28::DrawGLScene(){ int i, j; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); // Reset The Current Modelview Matrix glTranslatef(0.0f,0.0f,-4.0f); // Move Left 1.5 Units And Into The Screen 6.0 glRotatef(-75.0f,1.0f,0.0f,0.0f); glRotatef(rotz,0.0f,0.0f,1.0f); // Rotate The Triangle On The Z-Axis glCallList(mybezier.dlBPatch); // Call The Bezier's Display List // This Need Only Be Updated When The Patch Changes if (showCPoints) { // If Drawing The Grid Is Toggled On glDisable(GL_TEXTURE_2D); glColor3f(1.0f,0.0f,0.0f); for(i=0;i<4;i++) { // Draw The Horizontal Lines glBegin(GL_LINE_STRIP); for(j=0;j<4;j++) glVertex3d(mybezier.anchors[i][j].x, mybezier.anchors[i][j].y, mybezier.anchors[i][j].z); glEnd(); } for(i=0;i<4;i++) { // Draw The Vertical Lines glBegin(GL_LINE_STRIP); for(j=0;j<4;j++) glVertex3d(mybezier.anchors[j][i].x, mybezier.anchors[j][i].y, mybezier.anchors[j][i].z); glEnd(); } glColor3f(1.0f,1.0f,1.0f); glEnable(GL_TEXTURE_2D); } //draw FPS text glDisable(GL_TEXTURE_2D); glLoadIdentity (); glTranslatef(0.0f,0.0f,-1.0f); glColor3f(0.8f,0.8f,0.8f);//set text color computeFPS(); Utils::drawText(-0.54f,-0.4f, GLUT_BITMAP_HELVETICA_12, FPSstr); glEnable(GL_TEXTURE_2D); glutSwapBuffers(); // handle keyboard input if (specialKeys[GLUT_KEY_LEFT]) rotz -= 0.8f; // Rotate Left ( NEW ) if (specialKeys[GLUT_KEY_RIGHT]) rotz += 0.8f; // Rotate Right ( NEW ) if (specialKeys[GLUT_KEY_UP]) { // Resolution Up ( NEW ) divs++; mybezier.dlBPatch = genBezier(mybezier, divs); // Update The Patch specialKeys[GLUT_KEY_UP] = FALSE; } if (specialKeys[GLUT_KEY_DOWN] && divs > 1) { // Resolution Down ( NEW ) divs--; mybezier.dlBPatch = genBezier(mybezier, divs); // Update The Patch specialKeys[GLUT_KEY_DOWN] = FALSE; } if (keys[' ']) { showCPoints = !showCPoints; keys[' '] = FALSE; } } /* This function is used to limit FPS for smooth animation */ GLvoid NEHE28::UpdateScene(int flag){ clock_t startTime = clock(); glutPostRedisplay(); clock_t endTime = clock(); //compute sleep time in millesecond float sleepTime = ((CLOCKS_PER_SEC/EXPECT_FPS)-(endTime-startTime))/1000.0; //sleepTime = floor(sleepTime+0.5); sleepTime < 0 ? sleepTime = 0 : NULL; glutTimerFunc(sleepTime, UpdateScene, flag); } GLvoid NEHE28::KeyboardFuction(unsigned char key, int x, int y){ keys[key] = true; } GLvoid NEHE28::KeyboardUpFuction(unsigned char key, int x, int y){ keys[key] = false; } GLvoid NEHE28::KeySpecialFuction(int key, int x, int y){ specialKeys[key] = true; } GLvoid NEHE28::KeySpecialUpFuction(int key, int x, int y){ specialKeys[key] = false; } void NEHE28::computeFPS(){ frameCounter++; currentTime=glutGet(GLUT_ELAPSED_TIME); if (currentTime - lastTime > FPS_UPDATE_CAP) { sprintf(FPSstr,"FPS: %4.2f",frameCounter*1000.0/(currentTime-lastTime)); lastTime = currentTime; frameCounter = 0; } }
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdio.h> #include <stddef.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <signal.h> #include <unistd.h> #include <systemd/sd-daemon.h> // For systemd watchdog #include <wiringPi.h> #include <compile_time.h> #include <utils.h> #include <timer.h> #include <audio.h> #include <urtp.h> #include <log.h> /* ---------------------------------------------------------------- * COMPILE-TIME MACROS * -------------------------------------------------------------- */ // Things to help with parsing filenames. #define DIR_SEPARATORS "\\/" #define EXT_SEPARATOR "." // The default location for log files #define DEFAULT_LOG_FILE_PATH "./logtmp" /* ---------------------------------------------------------------- * STATIC VARIABLES * -------------------------------------------------------------- */ // For logging. static char gLogBuffer[LOG_STORE_SIZE]; // For writing a log to file in the background. static size_t gLogWriteTicker; // Watchdog timer interval. static long long unsigned int gWatchdogIntervalSeconds; // The GPIO pin to toggle. static int gGpio = -1; /* ---------------------------------------------------------------- * STATIC FUNCTIONS * -------------------------------------------------------------- */ // Print the usage text static void printUsage(char * pExeName) { printf("\n%s: run the Internet of Chuffs client. Usage:\n", pExeName); printf(" %s audio_source audio_server_url <-g max_gain> <-ls log_server_url> <-ld log_directory> <-p gpio>\n", pExeName); printf("where:\n"); printf(" audio_source is the name of the ALSA PCM audio capture device (must be 32 bits per channel, stereo, 16 kHz sample rate),\n"); printf(" audio_server_url is the URL of the Internet of Chuffs server,\n"); printf(" -g optionally specifies the maximum gain to apply; default is max which is %d, lower numbers mean less gain (and noise),\n", AUDIO_MAX_SHIFT_BITS); printf(" -ls optionally specifies the URL of a server to upload log-files to (where a logging server application must be listening),\n"); printf(" -ld optionally specifies the directory to use for log files (default %s); the directory will be created if it does not exist,\n", DEFAULT_LOG_FILE_PATH); printf(" -p optionally specifies a GPIO pin to toggle to show activity (using wiringPi numbering),\n"); printf("For example:\n"); printf(" %s mic io-server.co.uk:1297 -ls logserver.com -ld /var/log -p 0\n\n", pExeName); } // Exit handler static void exitHandler(int retValue) { printf("\nStopping.\n"); stopAudioStreaming(); digitalWrite(gGpio, LOW); printLog(); deinitLog(); deinitTimers(); exit(retValue); } // Signal handler for CTRL-C static void exitHandlerSignal(int signal) { exitHandler(0); } // Watchdog handler static void watchdogHandler() { if (gWatchdogIntervalSeconds > 0) { /* Ping systemd */ sd_notify(0, "WATCHDOG=1"); } } // Handler to toggle the LED static void ledToggleHandler() { if (gGpio >= 0) { int x = 0; // Toggle the LED if (digitalRead(gGpio) == 0) { x = 1; } digitalWrite(gGpio, x); } } /* ---------------------------------------------------------------- * MAIN * -------------------------------------------------------------- */ // Main. int main(int argc, char *argv[]) { int retValue = -1; bool success = false; bool logFileUploadSuccess = false; int x = 0; char *pExeName = NULL; int maxShift = AUDIO_MAX_SHIFT_BITS; char *pPcmAudio = NULL; char *pAudioUrl = NULL; char *pLogUrl = NULL; const char *pLogFilePath = DEFAULT_LOG_FILE_PATH; struct stat st = { 0 }; char *pChar; struct sigaction sigIntHandler; // Find the exe name in the first argument pChar = strtok(argv[x], DIR_SEPARATORS); while (pChar != NULL) { pExeName = pChar; pChar = strtok(NULL, DIR_SEPARATORS); } if (pExeName != NULL) { // Remove the extension pChar = strtok(pExeName, EXT_SEPARATOR); if (pChar != NULL) { pExeName = pChar; } } x++; // Look for all the command line parameters while (x < argc) { // Test for PCM audio device if (x == 1) { pPcmAudio = argv[x]; // Test for server URL } else if (x == 2) { pAudioUrl = argv[x]; // Test for max gain option } else if (strcmp(argv[x], "-g") == 0) { x++; if (x < argc) { maxShift = atoi(argv[x]); } // Test for log server option } else if (strcmp(argv[x], "-ls") == 0) { x++; if (x < argc) { pLogUrl = argv[x]; } // Test for log directory option } else if (strcmp(argv[x], "-ld") == 0) { x++; if (x < argc) { pLogFilePath = argv[x]; } // Test for gpio option } else if (strcmp(argv[x], "-p") == 0) { x++; if (x < argc) { gGpio = atoi(argv[x]); } } x++; } // Must have the two mandatory command-line parameters if ((pPcmAudio != NULL) && (pAudioUrl != NULL)) { // Check that the maximum shift value, if specifed, is sensible if ((maxShift >= 0) && (maxShift <= AUDIO_MAX_SHIFT_BITS)) { // Check if the directory exists if (stat(pLogFilePath, &st) == -1) { // If it doesn't exist create it if (mkdir(pLogFilePath, 0700) == 0) { success = true; } else { printf("Unable to create directory temporary log file directory %s (%s).\n", pLogFilePath, strerror(errno)); } } else { success = true; } } else { printf("Max gain must be between 0 and %d (not %d).\n", AUDIO_MAX_SHIFT_BITS, maxShift); } if (success) { printf("Internet of Chuffs client starting.\nAudio PCM capture device is \"%s\", server is \"%s\"", pPcmAudio, pAudioUrl); if (pLogUrl != NULL) { printf(", log files from previous sessions will be uploaded to \"%s\"", pLogUrl); } if (pLogFilePath != NULL) { printf(", temporarily storing log files in directory \"%s\"", pLogFilePath); } if (gGpio >= 0) { printf(", GPIO%d will be toggled to show activity", gGpio); } printf(".\n"); // Set up the CTRL-C handler sigIntHandler.sa_handler = exitHandlerSignal; sigemptyset(&sigIntHandler.sa_mask); sigIntHandler.sa_flags = 0; sigaction(SIGINT, &sigIntHandler, NULL); // Initialise the timers initTimers(); // Initialise logging initLog(gLogBuffer); initLogFile(pLogFilePath); gLogWriteTicker = startTimer(1000000L, TIMER_PERIODIC, writeLogCallback, NULL); LOG(EVENT_SYSTEM_START, getUSeconds() / 1000000); LOG(EVENT_BUILD_TIME_UNIX_FORMAT, __COMPILE_TIME_UNIX__); // Tell systemd we're awake and determine if the systemd watchdog is on sd_notify(0, "READY=1"); if (sd_watchdog_enabled(0, &gWatchdogIntervalSeconds) <= 0) { gWatchdogIntervalSeconds = 0; } // Set up wiringPi and the LED pin if (gGpio >= 0) { wiringPiSetup(); pinMode(gGpio, OUTPUT); } // Start while (1) { // Keep it up until CTRL-C if (!audioIsStreaming()) { // if we're not streaming then either we've not started or we've dropped // out of streaming. In the latter case we need to clean up, so always // do that here just in case stopAudioStreaming(); if (startAudioStreaming(pPcmAudio, pAudioUrl, maxShift, watchdogHandler, ledToggleHandler)) { printf("Audio streaming started, press CTRL-C to exit\n"); // Safe to upload log files now we've succeeded in making // at least one connection if (!logFileUploadSuccess && (pLogUrl != NULL)) { logFileUploadSuccess = beginLogFileUpload(pLogUrl); } } } // If we weren't successful, and are going to try again, // make sure the watchdog is fed if (gWatchdogIntervalSeconds > 0) { watchdogHandler(); } sleep(1); } } else { printUsage(pExeName); } } else { printUsage(pExeName); } if (success) { retValue = 0; } return retValue; } // End of file
#include "utils.h" namespace Utils { }
// LeastCommonAncestor.cc #include <iostream> using namespace std; #define N 10000 int getIndex(int &key, const int *input, const int length, int *index){ int occur = 0; int i = 0; int j = 0; while(i<length){ if(input[i] == key){ occur++; index[j++] = i; } if(occur==3) break; i++; } return occur; } int pickAsChild(const int *index){ for(int i=0; i<3; ++i){ if(index[i]%2) return index[i]; } return -1; } int getLine(int &key, int *input, const int size, int *line){ int occur; // Each element would occur in 3 times at most. int index[3] = {0}; int aschild; int l = 0; while(key != 1){ occur = getIndex(key, input, size, index); aschild = pickAsChild(index); *line = key; cout<<"*line = "<<(*line)<<endl; l++; line++; key = input[aschild-1]; } *line = 1; l++; cout<<"*line = "<<(*line)<<endl; return l; } int main(int argc, char **argv){ int input[] = {1,2,1,3,2,4,3,5,3,6,4,7,7,12,5,9,5,8,6,10,6,11,11,13}; int key1 = 13; int key2 = 12; int *line1 = new int; int *line2 = new int; int pivot1; int pivot2; int size = sizeof(input)/sizeof(int); pivot1 = getLine(key1, input, size, line1); pivot2 = getLine(key2, input, size, line2); cout<<"pivot1 = "<<pivot1<<endl; cout<<"pivot2 = "<<pivot2<<endl; while(pivot1>0 && pivot2>0){ if(line1[--pivot1] != line2[--pivot2]) break; } cout<<"Common Ancestor = "<<line1[pivot1+1]<<endl; delete line1; delete line2; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- ** ** Copyright (C) 1995-2007 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #include "core/pch.h" #if defined(VEGA_SUPPORT) && defined(VEGA_3DDEVICE) #include "modules/libvega/src/vegabackend_hw3d.h" #include "modules/libvega/vegapath.h" #include "modules/libvega/vegafill.h" #include "modules/libvega/vegastencil.h" #include "modules/libvega/vega3ddevice.h" #include "modules/libvega/src/vegaimage.h" #include "modules/libvega/src/vegagradient.h" #include "modules/libvega/src/vegarendertargetimpl.h" #include "modules/libvega/src/vegafilterdisplace.h" #include "modules/mdefont/processedstring.h" #include "modules/libvega/src/oppainter/vegaopfont.h" #include "modules/libvega/src/oppainter/vegaopbitmap.h" #include "modules/libvega/vegawindow.h" #include "modules/prefs/prefsmanager/collections/pc_core.h" // disable multisampling if not needed - updateQuality cannot do this directly #define NEEDS_MULTISAMPLING(q) ((q) > 1) static inline void CheckMultisampling(unsigned int quality, VEGABackingStore* bstore) { unsigned int samples = VEGABackend_HW3D::qualityToSamples(quality); if (bstore && !NEEDS_MULTISAMPLING(samples)) static_cast<VEGABackingStore_FBO*>(bstore)->DisableMultisampling(); } VEGABackend_HW3D::VEGABackend_HW3D() : m_vbuffer(NULL), m_vlayout2d(NULL), m_vlayout2dTexGen(NULL), m_vert(NULL), m_defaultRenderState(NULL), m_defaultNoBlendRenderState(NULL), m_additiveRenderState(NULL), m_stencilModulateRenderState(NULL), m_updateStencilRenderState(NULL), m_updateStencilXorRenderState(NULL), m_invertRenderState(NULL), m_premultiplyRenderState(NULL), #ifdef VEGA_SUBPIXEL_FONT_BLENDING m_subpixelRenderState(NULL), #endif m_triangleIndexBuffer(NULL), m_triangleIndices(NULL), m_numRemainingBatchVerts(0), m_firstBatchVert(0), m_triangleIndexCount(0), m_batchList(NULL), m_numBatchOperations(0), m_currentFrame(1) { op_memset(shader2dV, 0, sizeof(shader2dV)); op_memset(shader2dTexGenV, 0, sizeof(shader2dTexGenV)); op_memset(shader2dText, 0, sizeof(shader2dText)); op_memset(textShaderLoaded, 0, sizeof(textShaderLoaded)); op_memset(m_vlayout2dText, 0, sizeof(m_vlayout2dText)); } VEGABackend_HW3D::~VEGABackend_HW3D() { OP_ASSERT(!m_firstBatchVert); // Deleting while there are pending batches should never happen OP_DELETEA(m_batchList); releaseShaderPrograms(); for (size_t i=0; i<ARRAY_SIZE(m_vlayout2dText); i++) VEGARefCount::DecRef(m_vlayout2dText[i]); VEGARefCount::DecRef(m_vlayout2d); VEGARefCount::DecRef(m_vlayout2dTexGen); VEGARefCount::DecRef(m_vbuffer); VEGARefCount::DecRef(m_triangleIndexBuffer); OP_DELETEA(m_vert); OP_DELETE(m_additiveRenderState); OP_DELETE(m_stencilModulateRenderState); OP_DELETE(m_updateStencilRenderState); OP_DELETE(m_updateStencilXorRenderState); OP_DELETE(m_invertRenderState); OP_DELETE(m_premultiplyRenderState); #ifdef VEGA_SUBPIXEL_FONT_BLENDING OP_DELETE(m_subpixelRenderState); #endif if (g_vegaGlobals.m_current_batcher == this) g_vegaGlobals.m_current_batcher = NULL; } OP_STATUS VEGABackend_HW3D::init(unsigned int w, unsigned int h, unsigned int q) { quality = q; VEGA3dDevice* device = g_vegaGlobals.vega3dDevice; if (!device) { VEGA3dDevice::UseCase useCase; OP_ASSERT(g_pccore && "VEGA backend initialized before prefs in core"); switch (g_pccore->GetIntegerPref(PrefsCollectionCore::EnableHardwareAcceleration)) { case PrefsCollectionCore::Disable: return OpStatus::ERR; case PrefsCollectionCore::Force: useCase = VEGA3dDevice::Force; break; default: OP_ASSERT(!"Pref value isn't handled! Falling back on For2D."); /* fall through */ case PrefsCollectionCore::Auto: useCase = VEGA3dDevice::For2D; break; } RETURN_IF_ERROR(VEGA3dDeviceFactory::Create(&g_vegaGlobals.vega3dDevice, useCase, g_vegaGlobals.mainNativeWindow)); device = g_vegaGlobals.vega3dDevice; } unsigned int maxVerts = device->getVertexBufferSize(); BOOL all_shaders_present = shader2dText[0] != NULL && shader2dText[Stencil] != NULL; if (all_shaders_present) for (size_t i = 0; i < VEGA3dShaderProgram::WRAP_MODE_COUNT; ++i) { if (!shader2dV[i] || !shader2dTexGenV[i]) { all_shaders_present = FALSE; break; } } if (!all_shaders_present) { releaseShaderPrograms(); for (size_t i = 0; i < VEGA3dShaderProgram::WRAP_MODE_COUNT; ++i) { RETURN_IF_ERROR(device->createShaderProgram(&shader2dV[i], VEGA3dShaderProgram::SHADER_VECTOR2D, (VEGA3dShaderProgram::WrapMode)i)); RETURN_IF_ERROR(device->createShaderProgram(&shader2dTexGenV[i], VEGA3dShaderProgram::SHADER_VECTOR2DTEXGEN, (VEGA3dShaderProgram::WrapMode)i)); } g_vegaGlobals.getShaderLocations(worldProjMatrix2dLocationV, texTransSLocationV, texTransTLocationV, stencilCompBasedLocation, straightAlphaLocation); // 2 basic text shaders must exist, others are created when needed RETURN_IF_ERROR(createTextShader(0)); RETURN_IF_ERROR(createTextShader(Stencil)); } if (!m_vbuffer) { m_vbuffer = device->getTempBuffer(maxVerts*sizeof(VEGA3dDevice::Vega2dVertex)); if (!m_vbuffer) return OpStatus::ERR; VEGARefCount::IncRef(m_vbuffer); } if (!m_triangleIndexBuffer) { device->getTriangleIndexBuffers(&m_triangleIndexBuffer, &m_triangleIndices); if (!m_triangleIndexBuffer) return OpStatus::ERR; VEGARefCount::IncRef(m_triangleIndexBuffer); } if (!m_vlayout2d) RETURN_IF_ERROR(device->createVega2dVertexLayout(&m_vlayout2d, VEGA3dShaderProgram::SHADER_VECTOR2D)); if (!m_vlayout2dTexGen) RETURN_IF_ERROR(device->createVega2dVertexLayout(&m_vlayout2dTexGen, VEGA3dShaderProgram::SHADER_VECTOR2DTEXGEN)); if (!m_vert) { m_vert = OP_NEWA(VEGA3dDevice::Vega2dVertex, maxVerts); RETURN_OOM_IF_NULL(m_vert); } m_defaultRenderState = device->getDefault2dRenderState(); m_defaultNoBlendRenderState = device->getDefault2dNoBlendRenderState(); if (!m_batchList) { m_batchList = OP_NEWA(BatchOperation, maxVerts/4); if (!m_batchList) return OpStatus::ERR_NO_MEMORY; m_numRemainingBatchVerts = maxVerts; } RETURN_IF_ERROR(rasterizer.initialize(w, h)); rasterizer.setConsumer(this); rasterizer.setQuality(q); return OpStatus::OK; } bool VEGABackend_HW3D::bind(VEGARenderTarget* rt) { VEGABackingStore* bstore = rt->GetBackingStore(); if (!bstore || !bstore->IsA(VEGABackingStore::FRAMEBUFFEROBJECT)) // Would be very surprising if we got a NULL backing store return false; CheckMultisampling(quality, bstore); bstore->Validate(); return true; } void VEGABackend_HW3D::unbind() { flushBatches(); } void VEGABackend_HW3D::flush(const OpRect* update_rects, unsigned int num_rects) { flushBatches(); VEGA3dDevice* device = g_vegaGlobals.vega3dDevice; device->setRenderTarget(static_cast<VEGABackingStore_FBO*>(renderTarget->GetBackingStore())->GetReadRenderTarget()); device->flush(); VEGARendererBackend::flush(update_rects, num_rects); ++m_currentFrame; } void VEGABackend_HW3D::flushIfUsingRenderState(VEGA3dRenderState* rs) { OP_ASSERT(rs); for (unsigned int batch = 0; batch < m_numBatchOperations; ++batch) { if (m_batchList[batch].renderState == rs) { flushBatches(); return; } } } void VEGABackend_HW3D::flushIfContainsTexture(VEGA3dTexture* tex) { OP_ASSERT(tex); for (unsigned int batch = 0; batch < m_numBatchOperations; ++batch) { if (m_batchList[batch].texture == tex) { flushBatches(); return; } } } OP_STATUS VEGABackingStore_FBO::Construct(unsigned width, unsigned height) { VEGA3dDevice* device = g_vegaGlobals.vega3dDevice; VEGA3dTexture* fbo_texture; VEGA3dFramebufferObject* fbo; RETURN_IF_ERROR(device->createFramebuffer(&fbo)); OP_STATUS status = device->createTexture(&fbo_texture, width, height, VEGA3dTexture::FORMAT_RGBA8888, false); if (OpStatus::IsError(status)) { VEGARefCount::DecRef(fbo); return status; } status = fbo->attachColor(fbo_texture); VEGARefCount::DecRef(fbo_texture); m_fbo = fbo; return status; } OP_STATUS VEGABackingStore_FBO::Construct(VEGA3dWindow* win3d) { m_fbo = win3d; return OpStatus::OK; } OP_STATUS VEGABackingStore_FBO::Construct(VEGABackingStore_Texture* tex) { VEGA3dDevice* device = g_vegaGlobals.vega3dDevice; VEGA3dFramebufferObject* fbo; RETURN_IF_ERROR(device->createFramebuffer(&fbo)); OP_STATUS status = fbo->attachColor(tex->GetTexture()); m_fbo = fbo; m_textureStore = tex; VEGARefCount::IncRef(tex); return status; } VEGABackingStore_FBO::~VEGABackingStore_FBO() { // Avoid flushing when the device has disappeared if (g_vegaGlobals.vega3dDevice) FlushTransaction(); VEGA3dDevice* device = g_vegaGlobals.vega3dDevice; if (device && device->getRenderTarget() == m_fbo) device->setRenderTarget(0, false); if (m_fbo && m_fbo->getType() == VEGA3dRenderTarget::VEGA3D_RT_TEXTURE) VEGARefCount::DecRef(static_cast<VEGA3dFramebufferObject*>(m_fbo)); else OP_DELETE(m_fbo); VEGARefCount::DecRef(m_msfbo); VEGARefCount::DecRef(m_textureStore); } VEGA3dRenderTarget* VEGABackingStore_FBO::GetReadRenderTarget() { if (m_batcher) m_batcher->flushBatches(); if (m_msfbo && m_writeRTDirty) ResolveMultisampling(); return m_fbo; } VEGA3dRenderTarget* VEGABackingStore_FBO::GetWriteRenderTarget(unsigned int frame) { // If the current frame is not the same as last frame this must be the start of a new frame // If the last frame using ms is different from the last frame when starting a new one that means // the entire last frame was rendered without ms and we can try to disable ms again if (m_msActive && frame != m_lastFrame && m_lastMSFrame != m_lastFrame) DisableMultisampling(); m_lastFrame = frame; if (m_msfbo && (m_msfbo->getWidth() != m_fbo->getWidth() || m_msfbo->getHeight() != m_fbo->getHeight())) { VEGARefCount::DecRef(m_msfbo); m_msfbo = NULL; m_msActive = false; } if (m_textureStore) { m_textureStore->MarkBufferDirty(); } if (m_msActive) { m_writeRTDirty = true; return m_msfbo; } return m_fbo; } void VEGABackingStore_FBO::DisableMultisampling() { m_msActive = false; } bool VEGABackingStore_FBO::EnableMultisampling(unsigned int quality, unsigned int frame) { unsigned int samples = VEGABackend_HW3D::qualityToSamples(quality); m_lastFrame = frame; m_lastMSFrame = frame; if (m_msfbo && (m_msfbo->getWidth() != m_fbo->getWidth() || m_msfbo->getHeight() != m_fbo->getHeight() || samples != m_msSamples)) { if (m_msActive && m_writeRTDirty) ResolveMultisampling(); VEGARefCount::DecRef(m_msfbo); m_msfbo = NULL; m_msActive = false; } VEGA3dDevice* device = g_vegaGlobals.vega3dDevice; // FIXME: When bound to a texture store the invalid flags are a bit messed up, so multisampling currently does not work if (m_msActive || !device->supportsMultisampling() || m_textureStore || !NEEDS_MULTISAMPLING(samples)) return false; if (m_msfbo) { m_msActive = true; } else { VEGA3dRenderbufferObject* rb; RETURN_VALUE_IF_ERROR(device->createRenderbuffer(&rb, m_fbo->getWidth(), m_fbo->getHeight(), VEGA3dRenderbufferObject::FORMAT_RGBA8, samples), false); if (OpStatus::IsError(device->createFramebuffer(&m_msfbo))) { VEGARefCount::DecRef(rb); return false; } if (OpStatus::IsError(m_msfbo->attachColor(rb))) { VEGARefCount::DecRef(rb); return false; } VEGARefCount::DecRef(rb); m_msSamples = samples; } // Copy the non multisampled data to the multisampled buffer #ifdef VEGA_NATIVE_FONT_SUPPORT m_fbo->flushFonts(); #endif VEGA3dTexture* tex = NULL; if (m_fbo->getType() == VEGA3dRenderTarget::VEGA3D_RT_TEXTURE && static_cast<VEGA3dFramebufferObject*>(m_fbo)->getAttachedColorTexture()) { tex = static_cast<VEGA3dFramebufferObject*>(m_fbo)->getAttachedColorTexture(); } else { tex = device->getTempTexture(m_fbo->getWidth(), m_fbo->getHeight()); if (!tex) return false; device->setRenderTarget(m_fbo, false); RETURN_VALUE_IF_ERROR(device->copyToTexture(tex, VEGA3dTexture::CUBE_SIDE_NONE, 0, 0, 0, 0, 0, m_fbo->getWidth(), m_fbo->getHeight()), true); } VEGA3dDevice::Vega2dVertex verts[] = { {0, 0,0,0,0xffffffff}, {(float)m_fbo->getWidth(), 0,((float)m_fbo->getWidth())/((float)tex->getWidth()),0,0xffffffff}, {0, (float)m_fbo->getHeight(),0,((float)m_fbo->getHeight())/((float)tex->getHeight()),0xffffffff}, {(float)m_fbo->getWidth(), (float)m_fbo->getHeight(),((float)m_fbo->getWidth())/((float)tex->getWidth()),((float)m_fbo->getHeight())/((float)tex->getHeight()),0xffffffff} }; VEGA3dBuffer* vbuffer = device->getTempBuffer(4*sizeof(VEGA3dDevice::Vega2dVertex)); unsigned int firstVert; RETURN_VALUE_IF_ERROR(vbuffer->writeAnywhere(4, sizeof(VEGA3dDevice::Vega2dVertex), verts, firstVert), true); device->setRenderState(device->getDefault2dNoBlendNoScissorRenderState()); device->setRenderTarget(m_msfbo); tex->setFilterMode(VEGA3dTexture::FILTER_NEAREST, VEGA3dTexture::FILTER_NEAREST); device->setTexture(0, tex); VEGA3dShaderProgram* shd; RETURN_VALUE_IF_ERROR(device->createShaderProgram(&shd, VEGA3dShaderProgram::SHADER_VECTOR2D, VEGA3dShaderProgram::WRAP_CLAMP_CLAMP), true); device->setShaderProgram(shd); shd->setOrthogonalProjection(); // setShaderProgram will add a reference to the shader program VEGARefCount::DecRef(shd); VEGA3dVertexLayout* layout; RETURN_VALUE_IF_ERROR(device->createVega2dVertexLayout(&layout, VEGA3dShaderProgram::SHADER_VECTOR2D), true); device->drawPrimitives(VEGA3dDevice::PRIMITIVE_TRIANGLE_STRIP, layout, firstVert, 4); VEGARefCount::DecRef(layout); m_writeRTDirty = false; m_msActive = true; return true; } void VEGABackingStore_FBO::ResolveMultisampling() { VEGA3dDevice* device = g_vegaGlobals.vega3dDevice; device->setRenderState(device->getDefault2dNoBlendNoScissorRenderState()); VEGA3dRenderTarget* const oldrt = device->getRenderTarget(); device->setRenderTarget(m_msfbo, false); device->resolveMultisample(m_fbo, 0, 0, m_msfbo->getWidth(), m_msfbo->getHeight()); m_writeRTDirty = false; device->setRenderTarget(oldrt, false); } VEGA3dTexture* VEGABackingStore_FBO::SwapTexture(VEGA3dTexture* tex) { VEGA3dTexture* curtex = NULL; if (m_fbo->getType() == VEGA3dRenderTarget::VEGA3D_RT_TEXTURE) curtex = static_cast<VEGA3dFramebufferObject*>(m_fbo)->getAttachedColorTexture(); if (!curtex) return NULL; if (tex->getWidth() != curtex->getWidth() || tex->getHeight() != curtex->getHeight() || tex->getFormat() != curtex->getFormat()) return NULL; DisableMultisampling(); VEGARefCount::IncRef(curtex); static_cast<VEGA3dFramebufferObject*>(m_fbo)->attachColor(tex); VEGARefCount::DecRef(tex); return curtex; } void VEGABackingStore_FBO::setCurrentBatcher(VEGABackend_HW3D* batcher) { if (batcher == m_batcher) return; if (batcher && m_batcher) m_batcher->flushBatches(); m_batcher = batcher; } void VEGABackingStore_FBO::SetColor(const OpRect& rect, UINT32 color) { FlushTransaction(); // Flush if the texture is currently scheduled in a batch. This can happen // when reusing fbo's in the backbuffer code. if (g_vegaGlobals.m_current_batcher) { if (m_fbo->getType() == VEGA3dRenderTarget::VEGA3D_RT_TEXTURE) { VEGA3dTexture* tex = static_cast<VEGA3dFramebufferObject*>(m_fbo)->getAttachedColorTexture(); g_vegaGlobals.m_current_batcher->flushIfContainsTexture(tex); } } VEGA3dDevice* device = g_vegaGlobals.vega3dDevice; device->setRenderTarget(GetReadRenderTarget()); m_msActive = false; device->setScissor(rect.x, rect.y, rect.width, rect.height); device->setRenderState(device->getDefault2dNoBlendRenderState()); device->clear(true, false, false, VEGAPixelPremultiply_BGRA8888(color), 1.f, 0); } OP_STATUS VEGABackingStore_FBO::CopyRect(const OpPoint& dstp, const OpRect& srcr, VEGABackingStore* store) { FlushTransaction(); if (m_fbo->getType() != VEGA3dRenderTarget::VEGA3D_RT_TEXTURE) return OpStatus::ERR; // Make sure rendering operations are flushed GetReadRenderTarget(); m_msActive = false; if (!store->IsA(VEGABackingStore::FRAMEBUFFEROBJECT)) return FallbackCopyRect(dstp, srcr, store); VEGA3dDevice* device = g_vegaGlobals.vega3dDevice; VEGA3dRenderTarget* oldrt = device->getRenderTarget(); VEGABackingStore_FBO* fbo_store = static_cast<VEGABackingStore_FBO*>(store); fbo_store->GetReadRenderTarget(); // must flush non-multisampled FBO device->setRenderTarget(fbo_store->m_fbo); device->copyToTexture(static_cast<VEGA3dFramebufferObject*>(m_fbo)->getAttachedColorTexture(), VEGA3dTexture::CUBE_SIDE_NONE, 0, dstp.x, dstp.y, srcr.x, srcr.y, srcr.width, srcr.height); device->setRenderTarget(oldrt); return OpStatus::OK; } OP_STATUS VEGABackingStore_FBO::LockRect(const OpRect& rect, AccessType acc) { VEGA3dDevice* device = g_vegaGlobals.vega3dDevice; device->setRenderTarget(GetReadRenderTarget()); OP_ASSERT(OpRect(0, 0, m_fbo->getWidth(), m_fbo->getHeight()).Contains(rect)); m_lock_data.x = rect.x; m_lock_data.y = rect.y; m_lock_data.w = rect.width; m_lock_data.h = rect.height; RETURN_IF_ERROR(device->lockRect(&m_lock_data, acc != ACC_WRITE_ONLY)); OP_STATUS status = m_lock_buffer.Bind(&m_lock_data.pixels); if (OpStatus::IsError(status)) device->unlockRect(&m_lock_data, false); return status; } OP_STATUS VEGABackingStore_FBO::UnlockRect(BOOL commit) { VEGA3dDevice* device = g_vegaGlobals.vega3dDevice; if (commit) m_lock_buffer.Sync(&m_lock_data.pixels); m_lock_buffer.Unbind(&m_lock_data.pixels); device->setRenderTarget(GetReadRenderTarget()); device->unlockRect(&m_lock_data, commit!=FALSE); if (commit && m_msActive) { m_msActive = false; } return OpStatus::OK; } OP_STATUS VEGABackingStore_Texture::Construct(unsigned width, unsigned height, bool indexed) { VEGASWBufferType swtype = indexed ? VSWBUF_INDEXED_COLOR : VSWBUF_COLOR; RETURN_IF_ERROR(VEGABackingStore_SWBuffer::Construct(width, height, swtype, false)); VEGA3dDevice* device = g_vegaGlobals.vega3dDevice; RETURN_IF_ERROR(device->createTexture(&m_texture, width, height, VEGA3dTexture::FORMAT_RGBA8888)); device->RegisterContextLostListener(this); return OpStatus::OK; } VEGABackingStore_Texture::~VEGABackingStore_Texture() { if (m_texture) { g_vegaGlobals.vega3dDevice->UnregisterContextLostListener(this); VEGARefCount::DecRef(m_texture); } } void VEGABackingStore_Texture::OnContextLost() { } void VEGABackingStore_Texture::OnContextRestored() { m_texture_dirty = true; // not necessarily true, but we don't know the context was lost // until after it happened so there's no chance to sync to buffer // beforehand. as texture is completely lost buffer is least // dirty. m_buffer_dirty = false; } OP_STATUS VEGABackingStore_Texture::SyncToBuffer(const OpRect& rect) { OP_ASSERT(!m_texture_dirty); VEGA3dDevice* device = g_vegaGlobals.vega3dDevice; VEGA3dFramebufferObject* fbo; RETURN_IF_ERROR(device->createFramebuffer(&fbo)); OP_STATUS err = fbo->attachColor(m_texture); if (OpStatus::IsSuccess(err)) err = device->setRenderTarget(fbo); if (OpStatus::IsSuccess(err)) { VEGA3dDevice::FramebufferData data; data.x = rect.x; data.y = rect.y; data.w = rect.width; data.h = rect.height; err = device->lockRect(&data, true); if (OpStatus::IsSuccess(err)) { m_buffer.CopyFromPixelStore(&data.pixels); device->unlockRect(&data, false); } } VEGARefCount::DecRef(fbo); return err; } void VEGABackingStore_Texture::SyncToTexture(const OpRect& rect) { OP_ASSERT(!m_buffer_dirty); VEGASWBuffer sub = m_buffer.CreateSubset(rect.x, rect.y, rect.width, rect.height); m_texture->update(rect.x, rect.y, &sub); } void VEGABackingStore_Texture::SetColor(const OpRect& rect, UINT32 color) { if (m_buffer_dirty) { if (WholeArea(rect)) m_buffer_dirty = false; else { if (OpStatus::IsError(SyncToBuffer())) return; } } VEGABackingStore_SWBuffer::SetColor(rect, color); m_texture_dirty = true; } OP_STATUS VEGABackingStore_Texture::CopyRect(const OpPoint& dstp, const OpRect& srcr, VEGABackingStore* store) { if (store->IsA(FRAMEBUFFEROBJECT)) { if (m_texture_dirty) { if (WholeArea(srcr)) m_texture_dirty = false; else SyncToTexture(); } VEGA3dDevice* device = g_vegaGlobals.vega3dDevice; RETURN_IF_ERROR(device->setRenderTarget(static_cast<VEGABackingStore_FBO*>(store)->GetReadRenderTarget())); RETURN_IF_ERROR(device->copyToTexture(m_texture, VEGA3dTexture::CUBE_SIDE_NONE, 0, dstp.x, dstp.y, srcr.x, srcr.y, srcr.width, srcr.height)); m_buffer_dirty = true; } else { if (m_buffer_dirty) { if (WholeArea(srcr)) m_buffer_dirty = false; else RETURN_IF_ERROR(SyncToBuffer()); } RETURN_IF_ERROR(VEGABackingStore_SWBuffer::CopyRect(dstp, srcr, store)); m_texture_dirty = true; } return OpStatus::OK; } VEGASWBuffer* VEGABackingStore_Texture::BeginTransaction(const OpRect& rect, AccessType acc) { if (m_buffer_dirty) { OP_ASSERT(!m_texture_dirty); if (acc != ACC_WRITE_ONLY || !rect.Equals(OpRect(0,0,m_texture->getWidth(), m_texture->getHeight()))) RETURN_VALUE_IF_ERROR(SyncToBuffer(), NULL); m_buffer_dirty = false; } return VEGABackingStore_SWBuffer::BeginTransaction(rect, acc); } void VEGABackingStore_Texture::EndTransaction(BOOL commit) { m_texture_dirty = m_texture_dirty || commit; } void VEGABackingStore_Texture::Validate() { if (!m_texture_dirty) return; SyncToTexture(); } OP_STATUS VEGABackend_HW3D::createBitmapRenderTarget(VEGARenderTarget** rt, OpBitmap* bmp) { #ifdef VEGA_LIMIT_BITMAP_SIZE if (static_cast<VEGAOpBitmap*>(bmp)->isTiled()) { OP_ASSERT(!"this operation is not allowed on tiled bitmaps, check calling code"); return OpStatus::ERR; // better than crashing } #endif // VEGA_LIMIT_BITMAP_SIZE VEGABackingStore* bstore = static_cast<VEGAOpBitmap*>(bmp)->GetBackingStore(); if (bstore->IsA(VEGABackingStore::TEXTURE)) { VEGABackingStore_FBO* nbstore = OP_NEW(VEGABackingStore_FBO, ()); if (!nbstore) return OpStatus::ERR_NO_MEMORY; OP_STATUS err = nbstore->Construct(static_cast<VEGABackingStore_Texture*>(bstore)); if (OpStatus::IsError(err)) { VEGARefCount::DecRef(nbstore); return err; } bstore = nbstore; } else VEGARefCount::IncRef(bstore); OP_ASSERT(bstore->IsA(VEGABackingStore::FRAMEBUFFEROBJECT)); VEGABitmapRenderTarget* rend = OP_NEW(VEGABitmapRenderTarget, (bstore)); if (!rend) { VEGARefCount::DecRef(bstore); return OpStatus::ERR_NO_MEMORY; } *rt = rend; return OpStatus::OK; } OP_STATUS VEGABackend_HW3D::createWindowRenderTarget(VEGARenderTarget** rt, VEGAWindow* window) { VEGA3dWindow* win3d; VEGA3dDevice* device = g_vegaGlobals.vega3dDevice; RETURN_IF_ERROR(device->createWindow(&win3d, window)); OP_STATUS status = window->initHardwareBackend(win3d); if (OpStatus::IsError(status)) { OP_DELETE(win3d); return status; } VEGABackingStore_FBO* wstore = OP_NEW(VEGABackingStore_FBO, ()); if (!wstore) { OP_DELETE(win3d); return OpStatus::ERR_NO_MEMORY; } OpStatus::Ignore(wstore->Construct(win3d)); VEGA3dWindowRenderTarget* winrt = OP_NEW(VEGA3dWindowRenderTarget, (wstore, window, win3d)); if (!winrt) { VEGARefCount::DecRef(wstore); return OpStatus::ERR_NO_MEMORY; } *rt = winrt; return OpStatus::OK; } OP_STATUS VEGABackend_HW3D::createIntermediateRenderTarget(VEGARenderTarget** rt, unsigned int w, unsigned int h) { VEGABackingStore_FBO* bstore = OP_NEW(VEGABackingStore_FBO, ()); if (!bstore) return OpStatus::ERR_NO_MEMORY; OP_STATUS status = bstore->Construct(w, h); if (OpStatus::IsError(status)) { VEGARefCount::DecRef(bstore); return status; } VEGAIntermediateRenderTarget* rend = OP_NEW(VEGAIntermediateRenderTarget, (bstore, VEGARenderTarget::RT_RGBA32)); if (!rend) { VEGARefCount::DecRef(bstore); return OpStatus::ERR_NO_MEMORY; } *rt = rend; return OpStatus::OK; } OP_STATUS VEGABackend_HW3D::createStencil(VEGAStencil** sten, bool component, unsigned int w, unsigned int h) { VEGABackingStore_FBO* bstore = OP_NEW(VEGABackingStore_FBO, ()); if (!bstore) return OpStatus::ERR_NO_MEMORY; OP_STATUS status = bstore->Construct(w, h); if (OpStatus::IsError(status)) { VEGARefCount::DecRef(bstore); return status; } VEGARenderTarget::RTColorFormat fmt = component ? VEGARenderTarget::RT_RGBA32 : VEGARenderTarget::RT_ALPHA8; VEGAIntermediateRenderTarget* rend = OP_NEW(VEGAIntermediateRenderTarget, (bstore, fmt)); if (!rend) { VEGARefCount::DecRef(bstore); return OpStatus::ERR_NO_MEMORY; } bstore->SetColor(OpRect(0, 0, w, h), 0); *sten = rend; return OpStatus::OK; } /* static */ OP_STATUS VEGABackend_HW3D::createBitmapStore(VEGABackingStore** store, unsigned w, unsigned h, bool is_indexed) { VEGABackingStore_Texture* bstore = OP_NEW(VEGABackingStore_Texture, ()); if (!bstore) return OpStatus::ERR_NO_MEMORY; OP_STATUS status = bstore->Construct(w, h, is_indexed); if (OpStatus::IsError(status)) { VEGARefCount::DecRef(bstore); return status; } *store = bstore; return OpStatus::OK; } bool VEGABackend_HW3D::supportsStore(VEGABackingStore* store) { return store->IsA(VEGABackingStore::TEXTURE) || store->IsA(VEGABackingStore::FRAMEBUFFEROBJECT); } #ifdef CANVAS3D_SUPPORT OP_STATUS VEGABackend_HW3D::createImage(VEGAImage* img, VEGA3dTexture* tex, bool isPremultiplied) { return img->init(tex, !!isPremultiplied); } #endif // CANVAS3D_SUPPORT void VEGABackend_HW3D::clear(int x, int y, unsigned int w, unsigned int h, unsigned int color, VEGATransform* transform) { VEGA3dDevice* dev3d = g_vegaGlobals.vega3dDevice; UINT32 col; if (renderTarget->getColorFormat() == VEGARenderTarget::RT_ALPHA8) col = (color&0xff000000) | ((color>>8)&0xff0000) | ((color>>16)&0xff00) | (color>>24); else { col = VEGAPixelPremultiply_BGRA8888(color); col = dev3d->convertToNativeColor(col); } VEGA3dRenderState* renderState = m_defaultRenderState; if ((col>>24) != 255) { renderState = m_defaultNoBlendRenderState; } if (!transform) { int sx = cliprect_sx; int sy = cliprect_sy; int ex = cliprect_ex; int ey = cliprect_ey; if (x > sx) sx = x; if (y > sy) sy = y; if (x+(int)w < ex) ex = x+w; if (y+(int)h < ey) ey = y+h; if (ex <= sx || ey <= sy) return; if ((color>>24) == 0) { int d_left, d_right, d_top, d_bottom; if (renderTarget->getDirtyRect(d_left, d_right, d_top, d_bottom)) { sx = MAX(sx, d_left); sy = MAX(sy, d_top); ex = MIN(ex, d_right + 1); ey = MIN(ey, d_bottom + 1); /* If the dirty rect extends outside the render * target, the call to unmarkDirty below will not work * very well. So trim the excess first. */ if (d_left < 0) renderTarget->unmarkDirty(d_left, -1, d_top, d_bottom); if (d_top < 0) renderTarget->unmarkDirty(d_left, d_right, d_top, -1); if (d_right >= (int)renderTarget->getWidth()) renderTarget->unmarkDirty(renderTarget->getWidth(), d_right, d_top, d_bottom); if (d_bottom >= (int)renderTarget->getHeight()) renderTarget->unmarkDirty(d_left, d_right, renderTarget->getHeight(), d_bottom); } if (ex <= sx || ey <= sy) return; renderTarget->unmarkDirty(sx, ex - 1, sy, ey - 1); } else renderTarget->markDirty(sx, ex - 1, sy, ey - 1); if (m_numRemainingBatchVerts < 4) flushBatches(); m_vert[m_firstBatchVert].x = VEGA_INTTOFIX(sx); m_vert[m_firstBatchVert].y = VEGA_INTTOFIX(sy); m_vert[m_firstBatchVert].color = col; m_vert[m_firstBatchVert+1].x = VEGA_INTTOFIX(ex); m_vert[m_firstBatchVert+1].y = VEGA_INTTOFIX(sy); m_vert[m_firstBatchVert+1].color = col; m_vert[m_firstBatchVert+2].x = VEGA_INTTOFIX(ex); m_vert[m_firstBatchVert+2].y = VEGA_INTTOFIX(ey); m_vert[m_firstBatchVert+2].color = col; m_vert[m_firstBatchVert+3].x = VEGA_INTTOFIX(sx); m_vert[m_firstBatchVert+3].y = VEGA_INTTOFIX(ey); m_vert[m_firstBatchVert+3].color = col; OpRect affected(sx, sy, ex-sx, ey-sy); scheduleBatch(NULL, 4, affected, NULL, renderState == m_defaultRenderState ? NULL : renderState); return; } flushBatches(); dev3d->setRenderTarget(static_cast<VEGABackingStore_FBO*>(renderTarget->GetBackingStore())->GetWriteRenderTarget(m_currentFrame)); if ((color>>24) != 0) { /* We could account for the transform rather than marking the * whole render target as dirty. But it may not be worth the * hassle. * * (On the other hand, properly accounting for the transform * would allow us to call unmarkDirty() when filling with * fully transparent. Again, in practice that may not * actually be very useful.) */ renderTarget->markDirty(cliprect_sx, cliprect_ex - 1, cliprect_sy, cliprect_ey - 1); } dev3d->setScissor(cliprect_sx, cliprect_sy, cliprect_ex-cliprect_sx, cliprect_ey-cliprect_sy); dev3d->setRenderState(renderState); VEGA3dDevice::Vega2dVertex verts[] = { {VEGA_INTTOFIX(x), VEGA_INTTOFIX(y),0,0,col}, {VEGA_INTTOFIX(x+(int)w), VEGA_INTTOFIX(y),1,0,col}, {VEGA_INTTOFIX(x), VEGA_INTTOFIX(y+(int)h),0,1,col}, {VEGA_INTTOFIX(x+(int)w), VEGA_INTTOFIX(y+(int)h),1,1,col} }; unsigned int firstVert; m_vbuffer->writeAnywhere(4, sizeof(VEGA3dDevice::Vega2dVertex), verts, firstVert); const VEGA3dShaderProgram::WrapMode mode = VEGA3dShaderProgram::WRAP_CLAMP_CLAMP; dev3d->setShaderProgram(shader2dV[mode]); if (transform) { VEGATransform3d projection; dev3d->loadOrthogonalProjection(projection); VEGATransform3d trans; trans.copy(*transform); projection.multiply(trans); shader2dV[mode]->setMatrix4(worldProjMatrix2dLocationV[mode], &projection[0], 1); shader2dV[mode]->invalidateOrthogonalProjection(); } else shader2dV[mode]->setOrthogonalProjection(); dev3d->setTexture(0, NULL); dev3d->drawPrimitives(VEGA3dDevice::PRIMITIVE_TRIANGLE_STRIP, m_vlayout2d, firstVert, 4); // FIXME: this invalidates too much dev3d->invalidate(cliprect_sx, cliprect_sy, cliprect_ex, cliprect_ey); } void VEGABackend_HW3D::updateAlphaTextureStencil(VEGAPath* path) { VEGA3dDevice* dev3d = g_vegaGlobals.vega3dDevice; unsigned int maxVerts = dev3d->getVertexBufferSize(); if (xorFill) { //dev3d->setClearValues(0,0,0); //dev3d->clear(false, false, true); dev3d->setRenderState(m_updateStencilXorRenderState); unsigned int numVerts = 0; unsigned int numLines = path->getNumLines(); for (unsigned int i = 0; i < numLines; ++i) { VEGA_FIX* lineData = path->getNonWarpLine(i); if (lineData && lineData[VEGALINE_STARTY] != lineData[VEGALINE_ENDY]) { if (numVerts+4 > maxVerts) { unsigned int firstVert; m_vbuffer->writeAnywhere(numVerts, sizeof(VEGA3dDevice::Vega2dVertex), m_vert, firstVert); unsigned int firstInd = (firstVert/4)*6; dev3d->drawIndexedPrimitives(VEGA3dDevice::PRIMITIVE_TRIANGLE, m_vlayout2d, dev3d->getQuadIndexBuffer(firstInd + (numVerts/4)*6), 2, firstInd, (numVerts/4)*6); numVerts = 0; } m_vert[numVerts].x = lineData[VEGALINE_STARTX]; m_vert[numVerts].y = lineData[VEGALINE_STARTY]; ++numVerts; m_vert[numVerts].x = lineData[VEGALINE_ENDX]; m_vert[numVerts].y = lineData[VEGALINE_ENDY]; ++numVerts; m_vert[numVerts].x = VEGA_INTTOFIX(width+1); m_vert[numVerts].y = lineData[VEGALINE_ENDY]; ++numVerts; m_vert[numVerts].x = VEGA_INTTOFIX(width+1); m_vert[numVerts].y = lineData[VEGALINE_STARTY]; ++numVerts; } } if (numVerts) { unsigned int firstVert; m_vbuffer->writeAnywhere(numVerts, sizeof(VEGA3dDevice::Vega2dVertex), m_vert, firstVert); unsigned int firstInd = (firstVert/4)*6; dev3d->drawIndexedPrimitives(VEGA3dDevice::PRIMITIVE_TRIANGLE, m_vlayout2d, dev3d->getQuadIndexBuffer(firstInd + (numVerts/4)*6), 2, firstInd, (numVerts/4)*6); } } else { unsigned int i; //dev3d->setClearValues(0,0,1); //dev3d->clear(false, false, true); dev3d->setRenderState(m_updateStencilRenderState); unsigned int numVerts = 0; unsigned int numLines = path->getNumLines(); for (i = 0; i < numLines; ++i) { VEGA_FIX* lineData = path->getNonWarpLine(i); if (lineData && lineData[VEGALINE_STARTY] != lineData[VEGALINE_ENDY]) { if (numVerts+4 > maxVerts) { unsigned int firstVert; m_vbuffer->writeAnywhere(numVerts, sizeof(VEGA3dDevice::Vega2dVertex), m_vert, firstVert); unsigned int firstInd = (firstVert/4)*6; dev3d->drawIndexedPrimitives(VEGA3dDevice::PRIMITIVE_TRIANGLE, m_vlayout2d, dev3d->getQuadIndexBuffer(firstInd + (numVerts/4)*6), 2, firstInd, (numVerts/4)*6); numVerts = 0; } m_vert[numVerts].x = lineData[VEGALINE_STARTX]; m_vert[numVerts].y = lineData[VEGALINE_STARTY]; ++numVerts; m_vert[numVerts].x = lineData[VEGALINE_ENDX]; m_vert[numVerts].y = lineData[VEGALINE_ENDY]; ++numVerts; m_vert[numVerts].x = VEGA_INTTOFIX(width+1); m_vert[numVerts].y = lineData[VEGALINE_ENDY]; ++numVerts; m_vert[numVerts].x = VEGA_INTTOFIX(width+1); m_vert[numVerts].y = lineData[VEGALINE_STARTY]; ++numVerts; } } if (numVerts) { unsigned int firstVert; m_vbuffer->writeAnywhere(numVerts, sizeof(VEGA3dDevice::Vega2dVertex), m_vert, firstVert); unsigned int firstInd = (firstVert/4)*6; dev3d->drawIndexedPrimitives(VEGA3dDevice::PRIMITIVE_TRIANGLE, m_vlayout2d, dev3d->getQuadIndexBuffer(firstInd + (numVerts/4)*6), 2, firstInd, (numVerts/4)*6); } } } void VEGABackend_HW3D::releaseShaderPrograms() { size_t i; for (i = 0; i < VEGA3dShaderProgram::WRAP_MODE_COUNT; ++i) { VEGARefCount::DecRef(shader2dV[i]); shader2dV[i] = NULL; VEGARefCount::DecRef(shader2dTexGenV[i]); shader2dTexGenV[i] = NULL; } for (i = 0; i < TEXT_SHADER_COUNT; ++i) { VEGARefCount::DecRef(shader2dText[i]); shader2dText[i] = NULL; } } unsigned VEGABackend_HW3D::calculateArea(VEGA_FIX minx, VEGA_FIX miny, VEGA_FIX maxx, VEGA_FIX maxy) { // It isn't currently expected that this method be called for this // backend. If any code needs to call this method, we need to // decide how the area should be calculated. OP_ASSERT(!"Not implemented"); return 0; } void VEGABackend_HW3D::updateStencil(VEGAStencil* stencil, VEGA_FIX* strans, VEGA_FIX* ttrans, VEGA3dTexture*& stencilTex) { if (stencil) { strans[0] = VEGA_INTTOFIX(1) / stencil->getWidth(); strans[3] = -VEGA_INTTOFIX(stencil->getOffsetX()) / stencil->getWidth(); ttrans[1] = VEGA_INTTOFIX(1) / stencil->getHeight(); ttrans[3] = -VEGA_INTTOFIX(stencil->getOffsetY()) / stencil->getHeight(); VEGABackingStore* stencil_store = stencil->GetBackingStore(); OP_ASSERT(stencil_store->IsA(VEGABackingStore::FRAMEBUFFEROBJECT)); VEGA3dRenderTarget* stencil_rt = static_cast<VEGABackingStore_FBO*>(stencil_store)->GetReadRenderTarget(); OP_ASSERT(stencil_rt->getType() == VEGA3dRenderTarget::VEGA3D_RT_TEXTURE); stencilTex = static_cast<VEGA3dFramebufferObject*>(stencil_rt)->getAttachedColorTexture(); } else stencilTex = NULL; } void VEGABackend_HW3D::DrawTriangleArgs::setVert(VEGA3dDevice::Vega2dVertex* vert, unsigned idx) { const VEGA_FIX* line = path->getLine(idx); vert->color = col; vert->x = line[VEGALINE_STARTX]; vert->y = line[VEGALINE_STARTY]; vert->s = vert->x; vert->t = vert->y; textrans->apply(vert->s, vert->t); } void VEGABackend_HW3D::drawTriangles(DrawTriangleArgs& args) { // FIXME: maybe make second loop for s,t, so they're only set when tex != 0 #ifdef DEBUG_ENABLE_OPASSERT OP_ASSERT(args.path->getCategory() != VEGAPath::COMPLEX); #endif // DEBUG_ENABLE_OPASSERT const unsigned int numLines = args.path->getNumLines(); OP_ASSERT(numLines >= 3); VEGA3dDevice* dev3d = g_vegaGlobals.vega3dDevice; unsigned int maxTris = dev3d->getVertexBufferSize() / 3; flushBatches(); dev3d->setRenderTarget(static_cast<VEGABackingStore_FBO*>(renderTarget->GetBackingStore())->GetWriteRenderTarget(m_currentFrame)); dev3d->setScissor(args.clampRect->x, args.clampRect->y, args.clampRect->width, args.clampRect->height); if (args.prog) { dev3d->setShaderProgram(args.prog); args.prog->setOrthogonalProjection(); } dev3d->setTexture(0, args.tex); dev3d->setTexture(1, args.stencilTex); dev3d->setTexture(2, NULL); dev3d->setRenderState(args.renderState ? args.renderState : m_defaultRenderState); switch (args.mode) { case BM_INDEXED_TRIANGLES: { OP_ASSERT(args.indexedTriangles); OP_ASSERT(args.indexedTriangleCount > 0); int firstTri = 0; unsigned o = 0; do { unsigned int iTris = args.indexedTriangleCount - firstTri; if (iTris > maxTris) iTris = maxTris; VEGA3dDevice::Vega2dVertex* curVert = m_vert; for (unsigned int i = 0; i < 3*iTris; ++i) { args.setVert(curVert, args.indexedTriangles[o]); ++curVert; ++o; } m_vbuffer->update(0, iTris*3*sizeof(VEGA3dDevice::Vega2dVertex), m_vert); dev3d->drawPrimitives(VEGA3dDevice::PRIMITIVE_TRIANGLE, args.layout, 0, iTris*3); firstTri += iTris; } while (firstTri < args.indexedTriangleCount); break; } case BM_TRIANGLE_FAN: { VEGA_FIX x0 = args.path->getLine(0)[VEGALINE_STARTX]; VEGA_FIX y0 = args.path->getLine(0)[VEGALINE_STARTY]; VEGA_FIX s0 = x0, t0 = y0; args.textrans->apply(s0, t0); VEGA_FIX prevs = args.path->getLine(0)[VEGALINE_ENDX]; VEGA_FIX prevt = args.path->getLine(0)[VEGALINE_ENDY]; args.textrans->apply(prevs, prevt); unsigned int firstLine = 1; do { unsigned int numTris = numLines-1-firstLine; if (numTris > maxTris) numTris = maxTris; VEGA3dDevice::Vega2dVertex* curVert = m_vert; for (unsigned int i = 0; i < numTris; ++i) { curVert->color = args.col; curVert->x = x0; curVert->y = y0; curVert->s = s0; curVert->t = t0; ++curVert; const VEGA_FIX* lineData = args.path->getLine(i+firstLine); curVert->color = args.col; curVert->x = lineData[VEGALINE_STARTX]; curVert->y = lineData[VEGALINE_STARTY]; curVert->s = prevs; curVert->t = prevt; ++curVert; prevs = lineData[VEGALINE_ENDX]; prevt = lineData[VEGALINE_ENDY]; curVert->color = args.col; curVert->x = prevs; curVert->y = prevt; args.textrans->apply(prevs, prevt); curVert->s = prevs; curVert->t = prevt; ++curVert; } m_vbuffer->update(0, numTris*3*sizeof(VEGA3dDevice::Vega2dVertex), m_vert); dev3d->drawPrimitives(VEGA3dDevice::PRIMITIVE_TRIANGLE, args.layout, 0, numTris*3); firstLine += numTris; } while (firstLine < numLines-1); break; } default: OP_ASSERT(!"unsupported batch mode"); return; } } void VEGABackend_HW3D::scheduleTriangles(DrawTriangleArgs& args) { // FIXME: maybe make second loop for s,t, so they're only set when tex != 0 #ifdef DEBUG_ENABLE_OPASSERT OP_ASSERT(args.path->getCategory() != VEGAPath::COMPLEX); #endif // DEBUG_ENABLE_OPASSERT const unsigned int numLines = args.path->getNumLines(); OP_ASSERT(numLines >= 3); switch (args.mode) { case BM_INDEXED_TRIANGLES: { OP_ASSERT(args.indexedTriangles); OP_ASSERT(args.indexedTriangleCount > 0); if (numLines > m_numRemainingBatchVerts) { VEGA3dDevice* dev3d = g_vegaGlobals.vega3dDevice; if (numLines <= dev3d->getVertexBufferSize()) flushBatches(); else { // cannot draw indexed triangles unless all vertices can be accessed at once drawTriangles(args); return; } } // copy vertex data OP_ASSERT(numLines <= m_numRemainingBatchVerts); VEGA3dDevice::Vega2dVertex* curVert = m_vert+m_firstBatchVert; for (unsigned int line = 0; line < numLines; ++line) { args.setVert(curVert, line); ++curVert; } // copy index data OP_ASSERT(args.indexedTriangleCount <= (int)(numLines-2)); const int indexCount = 3*args.indexedTriangleCount; OP_ASSERT(m_triangleIndexCount + indexCount <= g_vegaGlobals.vega3dDevice->getTriangleIndexBufferSize()); op_memcpy(m_triangleIndices + m_triangleIndexCount, args.indexedTriangles, indexCount*sizeof(*m_triangleIndices)); // update offsets for (int i = 0; i < indexCount; ++i) m_triangleIndices[m_triangleIndexCount+i] += m_firstBatchVert; scheduleBatch(args.tex, numLines, *args.affected, args.needsClamp ? args.clampRect : 0, args.renderState, args.mode, indexCount); break; } case BM_TRIANGLE_FAN: { unsigned int line = 1; while (line < numLines) { unsigned int numVerts = 1; if (m_numRemainingBatchVerts < 3) flushBatches(); VEGA3dDevice::Vega2dVertex* curVert = m_vert+m_firstBatchVert; args.setVert(curVert, 0); ++curVert; while (line < numLines && m_numRemainingBatchVerts > numVerts) { args.setVert(curVert, line); ++curVert; ++line; ++numVerts; } if (line < numLines) { // We need to chop the path in two, we need to render the final point again // for the next path batch. // If we don't do this, there will be a gap, see DSK-351013 --line; } scheduleBatch(args.tex, numVerts, *args.affected, args.needsClamp ? args.clampRect : 0, args.renderState, args.mode); } break; } default: OP_ASSERT(!"unsupported batch mode"); return; } } OP_STATUS VEGABackend_HW3D::fillPath(VEGAPath *path, VEGAStencil *stencil, VEGA3dRenderState* renderState) { if (!path->isClosed()) { RETURN_IF_ERROR(path->close(false)); } VEGA3dDevice* dev3d = g_vegaGlobals.vega3dDevice; int sx, sy, ex, ey; sx = cliprect_sx; sy = cliprect_sy; ex = cliprect_ex; ey = cliprect_ey; int minx = width-1; int miny = height-1; int maxx = 0; int maxy = 0; unsigned int numLines = path->getNumLines(); // Drawing a shape with less than 3 lines is not possible and could mess up the fast-path if (numLines < 3) return OpStatus::OK; VEGAPath::Category category = path->getCategory(); // If the path has multiple sub paths we need to rebuild it to be able to triangulate it. // This is the rebuilt version (the original path is untouched). VEGAPath mergedPath; if (category == VEGAPath::COMPLEX && !path->cannotBeConvertedToSimple()) { // Merges the sub paths into a single path and checks // if the resulting path is self intersecting. const OP_STATUS status = path->tryToMakeMultipleSubPathsSimple(mergedPath, xorFill); // fallback to slow path for merging error if (OpStatus::IsSuccess(status)) { if (mergedPath.getCategory() == VEGAPath::SIMPLE) { path = &mergedPath; // mergedPath is triangulateable, switch to that one so we don't change the original path category = path->getCategory(); // will be updated by now } } } OP_ASSERT(category != VEGAPath::UNDETERMINED); // If the path is now simple it can be triangulated. if (category == VEGAPath::SIMPLE) { unsigned short* tris; int numTris; const OP_STATUS s = path->getTriangles(&tris, &numTris); RETURN_IF_MEMORY_ERROR(s); // fallback to slow path for triangulation errors if (OpStatus::IsError(s)) category = VEGAPath::COMPLEX; else if (!numTris) return OpStatus::OK; } numLines = path->getNumLines(); // might have changed. VEGA_FIX* lineData = path->getLine(0); VEGA_FIX fixminx = lineData[VEGALINE_STARTX], fixmaxx = lineData[VEGALINE_STARTX], fixminy = lineData[VEGALINE_STARTY], fixmaxy = lineData[VEGALINE_STARTY]; for (unsigned int i = 1; i < numLines; ++i) { lineData = path->getLine(i); VEGA_FIX lineStartX = lineData[VEGALINE_STARTX]; VEGA_FIX lineStartY = lineData[VEGALINE_STARTY]; if (lineStartX < fixminx) { fixminx = lineStartX; } if (lineStartX > fixmaxx) { fixmaxx = lineStartX; } if (lineStartY < fixminy) { fixminy = lineStartY; } if (lineStartY > fixmaxy) { fixmaxy = lineStartY; } } minx = VEGA_FIXTOINT(VEGA_FLOOR(fixminx)); maxx = VEGA_FIXTOINT(VEGA_CEIL(fixmaxx)); miny = VEGA_FIXTOINT(VEGA_FLOOR(fixminy)); maxy = VEGA_FIXTOINT(VEGA_CEIL(fixmaxy)); bool needsClamp = false; if (minx < sx) { minx = sx; needsClamp = true; } if (miny < sy) { miny = sy; needsClamp = true; } if (maxx > ex) { maxx = ex; needsClamp = true; } if (maxy > ey) { maxy = ey; needsClamp = true; } r_minx = minx; r_miny = miny; r_maxx = maxx; r_maxy = maxy; if (maxy <= miny || maxx <= minx) { r_minx = width-1; r_miny = height-1; r_maxx = 0; r_maxy = 0; return OpStatus::OK; } renderTarget->markDirty(minx, maxx, miny, maxy); // initialize stuff that's common for fast (convex) and slow (complex) paths VEGATransform textrans; textrans.loadIdentity(); VEGA3dVertexLayout* layout = m_vlayout2dTexGen; VEGA3dShaderProgram* prog = NULL; VEGAFill* const fill = fillstate.fill; VEGA3dTexture* tex = NULL; BOOL useStraightAlpha = FALSE; BOOL useCustomShader = FALSE; if (fill) { tex = fill->getTexture(); if (tex) { VEGATransform temptrans = fill->getTexTransform(); textrans.loadScale(VEGA_INTTOFIX(1)/tex->getWidth(), VEGA_INTTOFIX(1)/tex->getHeight()); textrans.multiply(temptrans); // OpenGL ES doesn't support clamp-to-border - use slow-path if (category == VEGAPath::SIMPLE) { const bool clamp_x = fill->getXSpread() == VEGAFill::SPREAD_CLAMP_BORDER; const bool clamp_y = fill->getYSpread() == VEGAFill::SPREAD_CLAMP_BORDER; if (clamp_x || clamp_y) category = VEGAPath::COMPLEX; } } // Render target may have changed in the above VEGAFill::getTexture call dev3d->setRenderTarget(static_cast<VEGABackingStore_FBO*>(renderTarget->GetBackingStore())->GetWriteRenderTarget(m_currentFrame)); prog = fill->getCustomShader(); useCustomShader = !!prog; if (fill->usePremulRenderState()) { RETURN_IF_ERROR(createPremulRenderState()); OP_ASSERT(!renderState); renderState = m_premultiplyRenderState; useStraightAlpha = TRUE; } VEGA3dVertexLayout* l = fill->getCustomVertexLayout(); if (l) { OP_ASSERT(prog); // can only get custom layout when using custom shader layout = l; } } VEGA_FIX strans[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; VEGA_FIX ttrans[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; VEGA3dTexture* stencilTex; updateStencil(stencil, strans, ttrans, stencilTex); const VEGA3dShaderProgram::WrapMode stencilMode = VEGA3dShaderProgram::WRAP_CLAMP_CLAMP; BOOL stencilColorToLuminance = stencil ? stencil->isComponentBased() : FALSE; if (category != VEGAPath::COMPLEX) { VEGABackingStore* bstore = renderTarget->GetBackingStore(); #ifdef VEGA_NATIVE_FONT_SUPPORT if (static_cast<VEGABackingStore_FBO*>(bstore)->EnableMultisampling(quality, m_currentFrame)) m_nativeFontRect.Empty(); #else // VEGA_NATIVE_FONT_SUPPORT static_cast<VEGABackingStore_FBO*>(bstore)->EnableMultisampling(quality, m_currentFrame); #endif // VEGA_NATIVE_FONT_SUPPORT OpRect clampRect(sx, sy, ex-sx, ey-sy); if (stencil) { if (!prog) prog = shader2dTexGenV[stencilMode]; } if (prog) { flushBatches(); dev3d->setRenderTarget(static_cast<VEGABackingStore_FBO*>(renderTarget->GetBackingStore())->GetWriteRenderTarget(m_currentFrame)); dev3d->setScissor(clampRect.x, clampRect.y, clampRect.width, clampRect.height); dev3d->setShaderProgram(prog); prog->setOrthogonalProjection(); if (stencil) { int transSLocation = useCustomShader ? prog->getConstantLocation("texTransS") : texTransSLocationV[stencilMode]; int transTLocation = useCustomShader ? prog->getConstantLocation("texTransT") : texTransTLocationV[stencilMode]; prog->setVector4(transSLocation, strans); prog->setVector4(transTLocation, ttrans); } dev3d->setTexture(0, tex); dev3d->setTexture(1, stencilTex); dev3d->setTexture(2, NULL); } VEGAPath constrained; if (tex) { VEGATransform temptrans = fill->getTexTransform(); textrans.loadScale(VEGA_INTTOFIX(1)/tex->getWidth(), VEGA_INTTOFIX(1)/tex->getHeight()); textrans.multiply(temptrans); // OpenGL ES doesn't support clamp-to-border, so we have // to constrain the path when textures shouldn't wrap or // the edge pixels will be repeated - see CT-1287 const bool clamp_x = fill->getXSpread() == VEGAFill::SPREAD_CLAMP_BORDER; const bool clamp_y = fill->getYSpread() == VEGAFill::SPREAD_CLAMP_BORDER; if (clamp_x || clamp_y) { OP_ASSERT(category == VEGAPath::CONVEX); RETURN_IF_ERROR(path->buildConstrainedPath(constrained, textrans, clamp_x, clamp_y)); path = &constrained; numLines = path->getNumLines(); if (!numLines) return OpStatus::OK; } } OpRect affected(r_minx, r_miny, r_maxx-r_minx, r_maxy-r_miny); DrawTriangleArgs args; args.path = path; args.mode = (category == VEGAPath::SIMPLE) ? BM_INDEXED_TRIANGLES : BM_TRIANGLE_FAN; args.affected = &affected; args.clampRect = &clampRect; args.needsClamp = needsClamp; // args.col = 0; // set below args.textrans = &textrans; args.tex = tex; args.stencilTex = stencilTex; args.renderState = renderState; args.layout = m_vlayout2dTexGen; args.prog = prog; if (category == VEGAPath::SIMPLE) // should be cached by previous call RETURN_IF_ERROR(path->getTriangles(&args.indexedTriangles, &args.indexedTriangleCount)); bool direct = false; int compBasedLocation = -1; if (fill && renderTarget->getColorFormat() != VEGARenderTarget::RT_ALPHA8) { unsigned char opacity = fill->getFillOpacity(); args.col = ((opacity<<24)|(opacity<<16)|(opacity<<8)|opacity); if (prog) { if (stencilColorToLuminance) compBasedLocation = useCustomShader ? prog->getConstantLocation("stencilComponentBased") : stencilCompBasedLocation[stencilMode]; direct = true; } } else { UINT32 col = (renderTarget->getColorFormat() == VEGARenderTarget::RT_ALPHA8) ? 0xffffffff : fillstate.color; unsigned char opacity = (col >> 24); col = (opacity << 24) | (col & 0x00ffffff); col = dev3d->convertToNativeColor(VEGAPixelPremultiply_BGRA8888(col)); args.col = col; if (stencil) { dev3d->setTexture(0, NULL); direct = true; } } if (direct) { if (compBasedLocation >= 0) prog->setScalar(compBasedLocation, TRUE); drawTriangles(args); if (compBasedLocation >= 0) prog->setScalar(compBasedLocation, FALSE); } else { scheduleTriangles(args); } // FIXME: this invalidates too much dev3d->invalidate(cliprect_sx, cliprect_sy, cliprect_ex, cliprect_ey); return OpStatus::OK; } flushBatches(); // OpenGL ES cannot clamp to border, so an extra stencil buffer is // needed for this. VEGAAutoRenderTarget _additionalStencil; if (tex) { const bool clamp_x = fill->getXSpread() == VEGAFill::SPREAD_CLAMP_BORDER; const bool clamp_y = fill->getYSpread() == VEGAFill::SPREAD_CLAMP_BORDER; if (clamp_x || clamp_y) { // Gist: create a new stencil buffer, and render the 'clipped // texture' rect to it. VEGAStencil* additionalStencil = 0; RETURN_IF_ERROR(createStencil(&additionalStencil, false, renderTarget->getWidth(), renderTarget->getHeight())); _additionalStencil.reset(additionalStencil); VEGA_FIX px, py; VEGA_FIX mins = 0, mint = 0, maxs = 1, maxt = 1; // if one direction is not clamped, get min and max s and // t from bounding box if (!(clamp_x && clamp_y)) { // upper left px = fixminx; py = fixminy; textrans.apply(px, py); mins = maxs = px; mint = maxt = py; // upper right px = fixmaxx; py = fixminy; textrans.apply(px, py); if (px < mins) mins = px; if (px > maxs) maxs = px; if (py < mint) mint = py; if (py > maxt) maxt = py; // lower left px = fixminx; py = fixmaxy; textrans.apply(px, py); if (px < mins) mins = px; if (px > maxs) maxs = px; if (py < mint) mint = py; if (py > maxt) maxt = py; // lower right px = fixmaxx; py = fixmaxy; textrans.apply(px, py); if (px < mins) mins = px; if (px > maxs) maxs = px; if (py < mint) mint = py; if (py > maxt) maxt = py; } if (clamp_x) { mins = 0; maxs = 1; } if (clamp_y) { mint = 0; maxt = 1; } // 'clipped texture' rect is obtained by applying the // inverse texcoord transformation matrix to the min and // max s and t coords VEGATransform texinv = textrans; #ifdef DEBUG_ENABLE_OPASSERT const bool r = #endif // DEBUG_ENABLE_OPASSERT texinv.invert(); OP_ASSERT(r); VEGA3dDevice::Vega2dVertex* curVert = m_vert; unsigned col = 0xffffffff; px = mins; py = mint; texinv.apply(px, py); curVert->x = px; curVert->y = py; curVert->s = 0; curVert->t = 0; curVert->color = col; ++curVert; px = maxs; py = mint; texinv.apply(px, py); curVert->x = px; curVert->y = py; curVert->s = 1; curVert->t = 0; curVert->color = col; ++curVert; px = maxs; py = maxt; texinv.apply(px, py); curVert->x = px; curVert->y = py; curVert->s = 1; curVert->t = 1; curVert->color = col; ++curVert; px = mins; py = maxt; texinv.apply(px, py); curVert->x = px; curVert->y = py; curVert->s = 0; curVert->t = 1; curVert->color = col; ++curVert; VEGA3dVertexLayout* stencil_layout = m_vlayout2dTexGen; VEGA3dShaderProgram* stencil_prog = shader2dV[VEGA3dShaderProgram::WRAP_CLAMP_CLAMP]; VEGABackingStore* bs = additionalStencil->GetBackingStore(); OP_ASSERT(bs->IsA(VEGABackingStore::FRAMEBUFFEROBJECT)); VEGA3dRenderState* rs = dev3d->getDefault2dNoBlendNoScissorRenderState(); dev3d->setShaderProgram(stencil_prog); stencil_prog->setOrthogonalProjection(); dev3d->setRenderTarget(static_cast<VEGABackingStore_FBO*>(bs)->GetWriteRenderTarget(m_currentFrame)); dev3d->setRenderState(rs); unsigned int firstVert; m_vbuffer->writeAnywhere(4, sizeof(VEGA3dDevice::Vega2dVertex), m_vert, firstVert); dev3d->setTexture(0, NULL); dev3d->drawPrimitives(VEGA3dDevice::PRIMITIVE_TRIANGLE_FAN, stencil_layout, firstVert, 4); stencil = additionalStencil; updateStencil(stencil, strans, ttrans, stencilTex); } } if (!m_stencilModulateRenderState) { RETURN_IF_ERROR(dev3d->createRenderState(&m_stencilModulateRenderState, false)); m_stencilModulateRenderState->enableScissor(true); m_stencilModulateRenderState->setBlendFunc(VEGA3dRenderState::BLEND_DST_COLOR, VEGA3dRenderState::BLEND_ZERO); m_stencilModulateRenderState->enableBlend(true); } // The stencil approach VEGA3dTexture* alphaTexture = dev3d->getAlphaTexture(); if (!alphaTexture) return OpStatus::ERR; // FIXME: use FSAA if available int xscale = 1; int yscale = 1; unsigned int xTileSize = alphaTexture->getWidth()/xscale; unsigned int yTileSize = alphaTexture->getHeight()/yscale; unsigned int numXTiles = ((r_maxx-r_minx)+xTileSize-1)/xTileSize; unsigned int numYTiles = ((r_maxy-r_miny)+yTileSize-1)/yTileSize; unsigned int numTiles = numXTiles*numYTiles; m_curRasterBuffer = dev3d->getAlphaTextureBuffer(); for (unsigned int tile = 0; tile < numTiles; ++tile) { unsigned int ytile = tile/numXTiles; unsigned int xtile = tile-ytile*numXTiles; unsigned int tileX = r_minx+xTileSize*xtile; unsigned int tileY = r_miny+yTileSize*ytile; unsigned int tileWidth = xTileSize; unsigned int tileHeight = yTileSize; if (xtile == numXTiles-1) tileWidth = (r_maxx-r_minx)-(numXTiles-1)*xTileSize; if (ytile == numYTiles-1) tileHeight = (r_maxy-r_miny)-(numYTiles-1)*yTileSize; // Rasterize to an alpha buffer rasterizer.setXORFill(xorFill); rasterizer.setRegion(tileX, tileY, tileX+tileWidth, tileY+tileHeight); m_lastRasterPos = 0; m_curRasterArea.x = tileX; m_curRasterArea.y = tileY; m_curRasterArea.width = tileWidth; m_curRasterArea.height = tileHeight; RETURN_IF_ERROR(rasterizer.rasterize(path)); if (tileWidth*tileHeight > m_lastRasterPos) op_memset(m_curRasterBuffer+m_lastRasterPos, 0, (tileWidth*tileHeight-m_lastRasterPos)); // Upload the alpha buffer to a texture alphaTexture->update(0, 0, tileWidth, tileHeight, m_curRasterBuffer); // Draw using the alpha texture as a mask VEGA3dDevice::Vega2dVertex verts[] = { {VEGA_INTTOFIX(tileX), VEGA_INTTOFIX(tileY),0,0,0xffffffff}, {VEGA_INTTOFIX(tileX), VEGA_INTTOFIX(tileY+tileHeight),0,0,0xffffffff}, {VEGA_INTTOFIX(tileX+tileWidth), VEGA_INTTOFIX(tileY),0,0,0xffffffff}, {VEGA_INTTOFIX(tileX+tileWidth), VEGA_INTTOFIX(tileY+tileHeight),0,0,0xffffffff} }; strans[4] = VEGA_INTTOFIX(xscale)/alphaTexture->getWidth(); strans[7] = -VEGA_INTTOFIX(tileX)*VEGA_INTTOFIX(xscale)/alphaTexture->getWidth(); ttrans[5] = VEGA_INTTOFIX(yscale)/alphaTexture->getHeight(); ttrans[7] = -VEGA_INTTOFIX(tileY)*VEGA_INTTOFIX(yscale)/alphaTexture->getHeight(); dev3d->setRenderTarget(static_cast<VEGABackingStore_FBO*>(renderTarget->GetBackingStore())->GetWriteRenderTarget(m_currentFrame)); dev3d->setScissor(tileX, tileY, tileWidth, tileHeight); dev3d->setRenderState(renderState ? renderState : m_defaultRenderState); dev3d->setTexture(0, tex); dev3d->setTexture(1, stencilTex); dev3d->setTexture(2, alphaTexture); if (tex && renderTarget->getColorFormat() != VEGARenderTarget::RT_ALPHA8) { const VEGA3dShaderProgram::WrapMode mode = VEGA3dShaderProgram::GetWrapMode(tex); if (!prog) prog = shader2dTexGenV[mode]; int transSLocation = useCustomShader ? prog->getConstantLocation("texTransS") : texTransSLocationV[mode]; int transTLocation = useCustomShader ? prog->getConstantLocation("texTransT") : texTransTLocationV[mode]; int alphaLocation = useCustomShader ? prog->getConstantLocation("straightAlpha") : straightAlphaLocation[mode]; dev3d->setShaderProgram(prog); prog->setOrthogonalProjection(); prog->setVector4(transSLocation, strans, 2); prog->setVector4(transTLocation, ttrans, 2); UINT32 col = ((fill->getFillOpacity()<<24)|(fill->getFillOpacity()<<16)|(fill->getFillOpacity()<<8)|fill->getFillOpacity()); verts[0].color = verts[1].color = verts[2].color = verts[3].color = col; verts[0].s = verts[0].x; verts[0].t = verts[0].y; textrans.apply(verts[0].s, verts[0].t); verts[1].s = verts[1].x; verts[1].t = verts[1].y; textrans.apply(verts[1].s, verts[1].t); verts[2].s = verts[2].x; verts[2].t = verts[2].y; textrans.apply(verts[2].s, verts[2].t); verts[3].s = verts[3].x; verts[3].t = verts[3].y; textrans.apply(verts[3].s, verts[3].t); unsigned int firstVert; m_vbuffer->writeAnywhere(4, sizeof(VEGA3dDevice::Vega2dVertex), verts, firstVert); if (useStraightAlpha) prog->setScalar(alphaLocation, TRUE); dev3d->drawPrimitives(VEGA3dDevice::PRIMITIVE_TRIANGLE_STRIP, layout, firstVert, 4); if (useStraightAlpha) prog->setScalar(alphaLocation, FALSE); } else { const VEGA3dShaderProgram::WrapMode mode = VEGA3dShaderProgram::WRAP_CLAMP_CLAMP; // FIXME: what if prog is already set? looks wrong to just overwrite... prog = shader2dTexGenV[mode]; dev3d->setShaderProgram(prog); prog->setOrthogonalProjection(); prog->setVector4(texTransSLocationV[mode], strans, 2); prog->setVector4(texTransTLocationV[mode], ttrans, 2); UINT32 col; if (renderTarget->getColorFormat() == VEGARenderTarget::RT_ALPHA8) col = 0xffffffff; else col = dev3d->convertToNativeColor(VEGAPixelPremultiply_BGRA8888(fillstate.color)); verts[0].color = verts[1].color = verts[2].color = verts[3].color = col; unsigned int firstVert; m_vbuffer->writeAnywhere(4, sizeof(VEGA3dDevice::Vega2dVertex), verts, firstVert); dev3d->setTexture(0, NULL); dev3d->drawPrimitives(VEGA3dDevice::PRIMITIVE_TRIANGLE_STRIP, layout, firstVert, 4); } } dev3d->invalidate(r_minx, r_miny, r_maxx, r_maxy); return OpStatus::OK; } void VEGABackend_HW3D::drawSpans(VEGASpanInfo* raster_spans, unsigned int span_count) { for (unsigned int span_num = 0; span_num < span_count; ++span_num) { VEGASpanInfo& span = raster_spans[span_num]; if (span.length == 0) continue; unsigned int rasterPos = (span.scanline-m_curRasterArea.y)*m_curRasterArea.width + span.pos-m_curRasterArea.x; if (rasterPos > m_lastRasterPos) op_memset(m_curRasterBuffer+m_lastRasterPos, 0, rasterPos-m_lastRasterPos); m_lastRasterPos = rasterPos+span.length; UINT8* stenbuf = m_curRasterBuffer + rasterPos; if (!span.mask) { op_memset(stenbuf, 0xff, span.length); } else /* span.mask && !alphaBlend */ { op_memcpy(stenbuf, span.mask, span.length); } } } OP_STATUS VEGABackend_HW3D::drawString(VEGAFont* font, int x, int y, const ProcessedString* processed_string, VEGAStencil* stencil) { OP_ASSERT(processed_string); OP_STATUS status = OpStatus::OK; VEGA3dDevice* dev3d = g_vegaGlobals.vega3dDevice; VEGA3dTexture* tex = font->getTexture(dev3d, false); if (!tex) return OpStatus::ERR; OpRect clipRect(cliprect_sx, cliprect_sy, cliprect_ex-cliprect_sx, cliprect_ey-cliprect_sy); UINT32 col = dev3d->convertToNativeColor(VEGAPixelPremultiply_BGRA8888(fillstate.color)); int xpos = x, ypos = y + font->Ascent(); // Make sure nothing is bound to texture unit 1 (stencil texture in shader). dev3d->setTexture(1, NULL); if (stencil) flushBatches(); for (unsigned int c = 0; c < processed_string->m_length; ++c) { ypos = y + processed_string->m_processed_glyphs[c].m_pos.y; xpos = x + processed_string->m_processed_glyphs[c].m_pos.x; if (xpos >= cliprect_ex) break; VEGAFont::VEGAGlyph glyph; float s1, t1, s2, t2; unsigned int texx, texy; glyph.advance = 0; OP_STATUS s = font->getGlyph(processed_string->m_processed_glyphs[c].m_id, glyph, texx, texy, processed_string->m_is_glyph_indices); if (OpStatus::IsSuccess(s) && glyph.width>0 && glyph.height>0) { int glyph_sx = xpos + glyph.left; int glyph_sy = ypos - glyph.top; OpRect glyphRect(glyph_sx, glyph_sy, glyph.width, glyph.height); glyphRect.SafeIntersectWith(clipRect); if (glyphRect.IsEmpty()) continue; s1 = (float)(texx + glyphRect.x - glyph_sx)/(float)tex->getWidth(); s2 = (float)(texx + glyphRect.Right() - glyph_sx)/(float)tex->getWidth(); t1 = (float)(texy + glyphRect.y - glyph_sy)/(float)tex->getHeight(); t2 = (float)(texy + glyphRect.Bottom() - glyph_sy)/(float)tex->getHeight(); if (m_numRemainingBatchVerts < 4) { flushBatches(); } m_vert[m_firstBatchVert].x = VEGA_INTTOFIX(glyphRect.x); m_vert[m_firstBatchVert].y = VEGA_INTTOFIX(glyphRect.y); m_vert[m_firstBatchVert].s = s1; m_vert[m_firstBatchVert].t = t1; m_vert[m_firstBatchVert].color = col; m_vert[m_firstBatchVert+1].x = VEGA_INTTOFIX(glyphRect.Right()); m_vert[m_firstBatchVert+1].y = VEGA_INTTOFIX(glyphRect.y); m_vert[m_firstBatchVert+1].s = s2; m_vert[m_firstBatchVert+1].t = t1; m_vert[m_firstBatchVert+1].color = col; m_vert[m_firstBatchVert+2].x = VEGA_INTTOFIX(glyphRect.Right()); m_vert[m_firstBatchVert+2].y = VEGA_INTTOFIX(glyphRect.Bottom()); m_vert[m_firstBatchVert+2].s = s2; m_vert[m_firstBatchVert+2].t = t2; m_vert[m_firstBatchVert+2].color = col; m_vert[m_firstBatchVert+3].x = VEGA_INTTOFIX(glyphRect.x); m_vert[m_firstBatchVert+3].y = VEGA_INTTOFIX(glyphRect.Bottom()); m_vert[m_firstBatchVert+3].s = s1; m_vert[m_firstBatchVert+3].t = t2; m_vert[m_firstBatchVert+3].color = col; scheduleFontBatch(font, 4, glyphRect); } else if (OpStatus::IsError(s) && !OpStatus::IsMemoryError(status)) status = s; } finishCurrentFontBatch(); if (stencil) flushBatches(stencil); ypos = y+font->Height(); if (x < cliprect_sx) x = cliprect_sx; if (y < cliprect_sy) y = cliprect_sy; if (xpos > cliprect_ex) xpos = cliprect_ex; if (ypos > cliprect_ey) ypos = cliprect_ey; if (x<xpos && y<ypos) dev3d->invalidate(x, y, xpos, ypos); return status; } # if defined(VEGA_NATIVE_FONT_SUPPORT) || defined(CSS_TRANSFORMS) OP_STATUS VEGABackend_HW3D::drawString(VEGAFont* font, int x, int y, const uni_char* _text, UINT32 len, INT32 extra_char_space, short adjust, VEGAStencil* stencil) { OP_ASSERT(stencil == NULL); # ifdef VEGA_NATIVE_FONT_SUPPORT if (font->nativeRendering()) { OpRect clipRect(cliprect_sx,cliprect_sy,cliprect_ex-cliprect_sx,cliprect_ey-cliprect_sy); OpRect worstCaseCoverage(x, y, font->MaxAdvance()*len, font->Height()); worstCaseCoverage.IntersectWith(clipRect); scheduleNativeFontBatch(worstCaseCoverage); if (!font->DrawString(OpPoint(x, y), _text, len, extra_char_space, adjust, clipRect, fillstate.color, static_cast<VEGABackingStore_FBO*>(renderTarget->GetBackingStore())->GetWriteRenderTarget(m_currentFrame), renderTarget->getTargetWindow()!=NULL)) return OpStatus::ERR; return OpStatus::OK; } # endif // VEGA_NATIVE_FONT_SUPPORT return OpStatus::ERR; } # endif // VEGA_NATIVE_FONT_SUPPORT || CSS_TRANSFORMS OP_STATUS VEGABackend_HW3D::moveRect(int x, int y, unsigned int width, unsigned int height, int dx, int dy) { flushBatches(); VEGA3dDevice* device = g_vegaGlobals.vega3dDevice; VEGA3dTexture* alphaTexture = device->getTempTexture(renderTarget->getWidth(), renderTarget->getHeight()); if (!alphaTexture) return OpStatus::ERR; /* This texture will only be used for plain pixel copies. * FILTER_NEAREST will protect against small rounding errors. */ alphaTexture->setFilterMode(VEGA3dTexture::FILTER_NEAREST, VEGA3dTexture::FILTER_NEAREST); device->setRenderTarget(static_cast<VEGABackingStore_FBO*>(renderTarget->GetBackingStore())->GetReadRenderTarget()); device->copyToTexture(alphaTexture, VEGA3dTexture::CUBE_SIDE_NONE, 0, 0, 0, x, y, width, height); // Render a textured quad float s1 = 0; float s2 = (float)width/(float)alphaTexture->getWidth(); float t1 = 0; float t2 = (float)height/(float)alphaTexture->getHeight(); VEGA3dDevice::Vega2dVertex verts[] = { {VEGA_INTTOFIX(x+dx), VEGA_INTTOFIX(y+dy),s1,t1,0xffffffff}, {VEGA_INTTOFIX(x+dx+width), VEGA_INTTOFIX(y+dy),s2,t1,0xffffffff}, {VEGA_INTTOFIX(x+dx), VEGA_INTTOFIX(y+dy+height),s1,t2,0xffffffff}, {VEGA_INTTOFIX(x+dx+width), VEGA_INTTOFIX(y+dy+height),s2,t2,0xffffffff} }; unsigned int firstVert; m_vbuffer->writeAnywhere(4, sizeof(VEGA3dDevice::Vega2dVertex), verts, firstVert); device->setRenderTarget(static_cast<VEGABackingStore_FBO*>(renderTarget->GetBackingStore())->GetWriteRenderTarget(m_currentFrame)); // Setting the scissor rect is cheaper than disabling scissor on d3d10 since it does not require re-allocation of the state variables device->setScissor(cliprect_sx, cliprect_sy, cliprect_ex-cliprect_sx, cliprect_ey-cliprect_sy); device->setRenderState(m_defaultNoBlendRenderState); device->setTexture(0, alphaTexture); const VEGA3dShaderProgram::WrapMode mode = VEGA3dShaderProgram::WRAP_CLAMP_CLAMP; device->setShaderProgram(shader2dV[mode]); shader2dV[mode]->setOrthogonalProjection(); device->drawPrimitives(VEGA3dDevice::PRIMITIVE_TRIANGLE_STRIP, m_vlayout2d, firstVert, 4); return OpStatus::OK; } OP_STATUS VEGABackend_HW3D::fillRect(int x, int y, unsigned int width, unsigned int height, VEGAStencil* stencil, bool blend) { int sx = cliprect_sx; int sy = cliprect_sy; int ex = cliprect_ex; int ey = cliprect_ey; if (x > sx) sx = x; if (y > sy) sy = y; if (x+(int)width < ex) ex = x+width; if (y+(int)height < ey) ey = y+height; if (ex <= sx || ey <= sy) return OpStatus::OK; renderTarget->markDirty(sx, ex-1, sy, ey-1); VEGA3dDevice* dev3d = g_vegaGlobals.vega3dDevice; if (stencil || // OpenGL ES don't support clamp to border, so special tricks // are needed in fillPath (fillstate.fill && fillstate.fill->isImage() && (fillstate.fill->getXSpread() == VEGAFill::SPREAD_CLAMP_BORDER || fillstate.fill->getYSpread() == VEGAFill::SPREAD_CLAMP_BORDER))) { OP_ASSERT(blend); // FIXME: far from optimal VEGAPath path; RETURN_IF_ERROR(path.moveTo(VEGA_INTTOFIX(x), VEGA_INTTOFIX(y))); RETURN_IF_ERROR(path.lineTo(VEGA_INTTOFIX(x+width), VEGA_INTTOFIX(y))); RETURN_IF_ERROR(path.lineTo(VEGA_INTTOFIX(x+width), VEGA_INTTOFIX(y+height))); RETURN_IF_ERROR(path.lineTo(VEGA_INTTOFIX(x), VEGA_INTTOFIX(y+height))); RETURN_IF_ERROR(path.close(true)); #ifdef VEGA_3DDEVICE path.forceConvex(); #endif return fillPath(&path, stencil); } else if (fillstate.fill && renderTarget->getColorFormat() != VEGARenderTarget::RT_ALPHA8) { VEGA3dTexture* tex = fillstate.fill->getTexture(); if (tex) { UINT32 col = ((fillstate.fill->getFillOpacity()<<24)|(fillstate.fill->getFillOpacity()<<16)|(fillstate.fill->getFillOpacity()<<8)|fillstate.fill->getFillOpacity()); VEGA3dShaderProgram* prog = fillstate.fill->getCustomShader(); VEGA3dRenderState* renderState = blend ? NULL : m_defaultNoBlendRenderState; if (fillstate.fill->usePremulRenderState() || (fillstate.fill->isImage() && !fillstate.fill->hasPremultipliedAlpha())) { RETURN_IF_ERROR(createPremulRenderState()); if (!blend) { // Emulate the 'source' composite operation by first clearing to 0 and then doing 'over' as per normal. // "dst = 0; dst = src + (1 - src.a) * dst" simplifies to "dst = src". clear(x, y, width, height, 0, NULL); } renderState = m_premultiplyRenderState; col = (fillstate.fill->getFillOpacity()<<24) | 0xffffff; } VEGA3dVertexLayout* vlayout = NULL; if (prog) { vlayout = fillstate.fill->getCustomVertexLayout(); flushBatches(); dev3d->setRenderTarget(static_cast<VEGABackingStore_FBO*>(renderTarget->GetBackingStore())->GetWriteRenderTarget(m_currentFrame)); dev3d->setScissor(0, 0, renderTarget->getWidth(), renderTarget->getHeight()); dev3d->setRenderState(m_defaultRenderState); dev3d->setShaderProgram(prog); prog->setOrthogonalProjection(); dev3d->setTexture(1, NULL); dev3d->setTexture(2, NULL); } else if (m_numRemainingBatchVerts < 4) flushBatches(); VEGATransform temptrans = fillstate.fill->getTexTransform(); VEGATransform textrans; textrans.loadScale(VEGA_INTTOFIX(1)/tex->getWidth(), VEGA_INTTOFIX(1)/tex->getHeight()); textrans.multiply(temptrans); m_vert[m_firstBatchVert].x = VEGA_INTTOFIX(sx); m_vert[m_firstBatchVert].y = VEGA_INTTOFIX(sy); m_vert[m_firstBatchVert].color = col; m_vert[m_firstBatchVert].s = m_vert[m_firstBatchVert].x; m_vert[m_firstBatchVert].t = m_vert[m_firstBatchVert].y; textrans.apply(m_vert[m_firstBatchVert].s, m_vert[m_firstBatchVert].t); m_vert[m_firstBatchVert+1].x = VEGA_INTTOFIX(ex); m_vert[m_firstBatchVert+1].y = VEGA_INTTOFIX(sy); m_vert[m_firstBatchVert+1].color = col; m_vert[m_firstBatchVert+1].s = m_vert[m_firstBatchVert+1].x; m_vert[m_firstBatchVert+1].t = m_vert[m_firstBatchVert+1].y; textrans.apply(m_vert[m_firstBatchVert+1].s, m_vert[m_firstBatchVert+1].t); m_vert[m_firstBatchVert+2].x = VEGA_INTTOFIX(ex); m_vert[m_firstBatchVert+2].y = VEGA_INTTOFIX(ey); m_vert[m_firstBatchVert+2].color = col; m_vert[m_firstBatchVert+2].s = m_vert[m_firstBatchVert+2].x; m_vert[m_firstBatchVert+2].t = m_vert[m_firstBatchVert+2].y; textrans.apply(m_vert[m_firstBatchVert+2].s, m_vert[m_firstBatchVert+2].t); m_vert[m_firstBatchVert+3].x = VEGA_INTTOFIX(sx); m_vert[m_firstBatchVert+3].y = VEGA_INTTOFIX(ey); m_vert[m_firstBatchVert+3].color = col; m_vert[m_firstBatchVert+3].s = m_vert[m_firstBatchVert+3].x; m_vert[m_firstBatchVert+3].t = m_vert[m_firstBatchVert+3].y; textrans.apply(m_vert[m_firstBatchVert+3].s, m_vert[m_firstBatchVert+3].t); if (prog) { if (renderState) dev3d->setRenderState(renderState); dev3d->setTexture(0, tex); unsigned int firstVert; m_vbuffer->writeAnywhere(4, sizeof(VEGA3dDevice::Vega2dVertex), &m_vert[m_firstBatchVert], firstVert); unsigned int firstInd = (firstVert/4)*6; dev3d->drawIndexedPrimitives(VEGA3dDevice::PRIMITIVE_TRIANGLE, vlayout, dev3d->getQuadIndexBuffer(firstInd+6), 2, firstInd, 6); } else { OpRect affected(sx, sy, ex-sx, ey-sy); scheduleBatch(tex, 4, affected, NULL, renderState); } } } else { if ((fillstate.color>>24) != 0) { if (m_numRemainingBatchVerts < 4) flushBatches(); // premultiply alpha UINT32 col = dev3d->convertToNativeColor(VEGAPixelPremultiply_BGRA8888(fillstate.color)); if (renderTarget->getColorFormat() == VEGARenderTarget::RT_ALPHA8) col = 0xffffffff; m_vert[m_firstBatchVert].x = VEGA_INTTOFIX(sx); m_vert[m_firstBatchVert].y = VEGA_INTTOFIX(sy); m_vert[m_firstBatchVert].color = col; m_vert[m_firstBatchVert+1].x = VEGA_INTTOFIX(ex); m_vert[m_firstBatchVert+1].y = VEGA_INTTOFIX(sy); m_vert[m_firstBatchVert+1].color = col; m_vert[m_firstBatchVert+2].x = VEGA_INTTOFIX(ex); m_vert[m_firstBatchVert+2].y = VEGA_INTTOFIX(ey); m_vert[m_firstBatchVert+2].color = col; m_vert[m_firstBatchVert+3].x = VEGA_INTTOFIX(sx); m_vert[m_firstBatchVert+3].y = VEGA_INTTOFIX(ey); m_vert[m_firstBatchVert+3].color = col; OpRect affected(sx, sy, ex-sx, ey-sy); scheduleBatch(NULL, 4, affected, NULL, blend ? NULL : m_defaultNoBlendRenderState); } } dev3d->invalidate(sx, sy, ex, ey); return OpStatus::OK; } OP_STATUS VEGABackend_HW3D::invertRect(int x, int y, unsigned int width, unsigned int height) { int sx = cliprect_sx; int sy = cliprect_sy; int ex = cliprect_ex; int ey = cliprect_ey; if (x > sx) sx = x; if (y > sy) sy = y; if (x+(int)width < ex) ex = x+width; if (y+(int)height < ey) ey = y+height; if (ex <= sx || ey <= sy) return OpStatus::OK; VEGA3dDevice* dev3d = g_vegaGlobals.vega3dDevice; if (m_numRemainingBatchVerts < 4) flushBatches(); UINT32 col = 0xffffffff; m_vert[m_firstBatchVert].x = VEGA_INTTOFIX(sx); m_vert[m_firstBatchVert].y = VEGA_INTTOFIX(sy); m_vert[m_firstBatchVert].color = col; m_vert[m_firstBatchVert+1].x = VEGA_INTTOFIX(ex); m_vert[m_firstBatchVert+1].y = VEGA_INTTOFIX(sy); m_vert[m_firstBatchVert+1].color = col; m_vert[m_firstBatchVert+2].x = VEGA_INTTOFIX(ex); m_vert[m_firstBatchVert+2].y = VEGA_INTTOFIX(ey); m_vert[m_firstBatchVert+2].color = col; m_vert[m_firstBatchVert+3].x = VEGA_INTTOFIX(sx); m_vert[m_firstBatchVert+3].y = VEGA_INTTOFIX(ey); m_vert[m_firstBatchVert+3].color = col; OpRect affected(sx, sy, ex-sx, ey-sy); // FIXME: schedule batch with different blend mode if (!m_invertRenderState) { RETURN_IF_ERROR(dev3d->createRenderState(&m_invertRenderState, false)); m_invertRenderState->enableScissor(true); m_invertRenderState->setBlendFunc(VEGA3dRenderState::BLEND_DST_ALPHA, VEGA3dRenderState::BLEND_ONE, VEGA3dRenderState::BLEND_ZERO, VEGA3dRenderState::BLEND_ONE); m_invertRenderState->setBlendEquation(VEGA3dRenderState::BLEND_OP_SUB, VEGA3dRenderState::BLEND_OP_ADD); m_invertRenderState->enableBlend(true); } scheduleBatch(NULL, 4, affected, NULL, m_invertRenderState); dev3d->invalidate(sx, sy, ex, ey); return OpStatus::OK; } OP_STATUS VEGABackend_HW3D::invertPath(VEGAPath* path) { if (!m_invertRenderState) { VEGA3dDevice* dev3d = g_vegaGlobals.vega3dDevice; RETURN_IF_ERROR(dev3d->createRenderState(&m_invertRenderState, false)); m_invertRenderState->enableScissor(true); m_invertRenderState->setBlendFunc(VEGA3dRenderState::BLEND_DST_ALPHA, VEGA3dRenderState::BLEND_ONE, VEGA3dRenderState::BLEND_ZERO, VEGA3dRenderState::BLEND_ONE); m_invertRenderState->setBlendEquation(VEGA3dRenderState::BLEND_OP_SUB, VEGA3dRenderState::BLEND_OP_ADD); m_invertRenderState->enableBlend(true); } // temporarily set color to opaque white FillState backup = fillstate; fillstate.fill = 0; fillstate.color = 0xffffffff; fillstate.ppixel = 0; fillstate.alphaBlend = true; OP_STATUS status = fillPath(path, NULL, m_invertRenderState); // restore old color fillstate = backup; return status; } OP_STATUS VEGABackend_HW3D::updateQuality() { if (renderTarget) CheckMultisampling(quality, renderTarget->GetBackingStore()); rasterizer.setQuality(quality); return OpStatus::OK; } OP_STATUS VEGABackend_HW3D::applyFilter(VEGAFilter* filter, const VEGAFilterRegion& region) { flushBatches(); if (!filter->hasSource()) return OpStatus::ERR; return filter->apply(static_cast<VEGABackingStore_FBO*>(renderTarget->GetBackingStore()), region, m_currentFrame); } void VEGABackend_HW3D::scheduleBatch(VEGA3dTexture* tex, unsigned int numVerts, const OpRect& affected, OpRect* clip, VEGA3dRenderState* renderState, BatchMode mode/* = BM_AUTO*/, int indexCount/* = -1*/) { if (mode == BM_AUTO) mode = (numVerts == 4) ? BM_QUAD : BM_TRIANGLE_FAN; #ifdef DEBUG_ENABLE_OPASSERT if (mode == BM_INDEXED_TRIANGLES) { OP_ASSERT(indexCount > 0); OP_ASSERT(indexCount + m_triangleIndexCount <= g_vegaGlobals.vega3dDevice->getTriangleIndexBufferSize()); } #endif // DEBUG_ENABLE_OPASSERT // if there's a deferred transaction it has to be flushed now static_cast<VEGABackingStore_FBO*>(renderTarget->GetBackingStore())->FlushTransaction(); if (g_vegaGlobals.m_current_batcher && g_vegaGlobals.m_current_batcher != this) { g_vegaGlobals.m_current_batcher->flushBatches(); } g_vegaGlobals.m_current_batcher = this; static_cast<VEGABackingStore_FBO*>(renderTarget->GetBackingStore())->setCurrentBatcher(this); #ifdef VEGA_NATIVE_FONT_SUPPORT if (!m_nativeFontRect.IsEmpty() && m_nativeFontRect.Intersecting(affected)) { static_cast<VEGABackingStore_FBO*>(renderTarget->GetBackingStore())->GetWriteRenderTarget(m_currentFrame)->flushFonts(); m_nativeFontRect.Empty(); } #endif // Search for potential batch unsigned int potential = m_numBatchOperations; // FIXME: can probably coalesce indexed triangle batches as well, // though i'm not sure it's worth it. (if so, remember to update // indexCount.) if (mode == BM_QUAD) { for (unsigned int batch = m_numBatchOperations; batch > 0 && potential == m_numBatchOperations; --batch) { if (m_batchList[batch-1].texture == tex && (!tex || (m_batchList[batch-1].texWrapS == tex->getWrapModeS() && m_batchList[batch-1].texWrapT == tex->getWrapModeT() && m_batchList[batch-1].texMinFilter == tex->getMinFilter() && m_batchList[batch-1].texMagFilter == tex->getMagFilter())) && !m_batchList[batch-1].font && m_batchList[batch-1].mode == mode && m_batchList[batch-1].renderState == renderState && m_batchList[batch-1].requiresClipping == (clip!=NULL) && (clip==NULL || clip->Equals(m_batchList[batch-1].clipRect))) potential = batch-1; else if (affected.Intersecting(m_batchList[batch-1].affectedRect)) break; } } if (potential != m_numBatchOperations) { if (potential != m_numBatchOperations-1) { VEGA3dDevice::Vega2dVertex temp[4]; m_batchList[m_numBatchOperations].firstVertex = m_firstBatchVert; m_batchList[m_numBatchOperations].numVertices = 4; appendVertexDataToBatch(m_numBatchOperations, potential, temp, affected); } else { m_batchList[potential].numVertices += numVerts; m_batchList[potential].affectedRect.UnionWith(affected); } } else { m_batchList[m_numBatchOperations].firstVertex = m_firstBatchVert; m_batchList[m_numBatchOperations].numVertices = numVerts; m_batchList[m_numBatchOperations].texture = tex; if (tex) { m_batchList[m_numBatchOperations].texWrapS = tex->getWrapModeS(); m_batchList[m_numBatchOperations].texWrapT = tex->getWrapModeT(); m_batchList[m_numBatchOperations].texMinFilter = tex->getMinFilter(); m_batchList[m_numBatchOperations].texMagFilter = tex->getMagFilter(); } m_batchList[m_numBatchOperations].font = NULL; m_batchList[m_numBatchOperations].renderState = renderState; m_batchList[m_numBatchOperations].affectedRect = affected; m_batchList[m_numBatchOperations].mode = mode; m_batchList[m_numBatchOperations].indexCount = indexCount; m_batchList[m_numBatchOperations].requiresClipping = clip!=NULL; if (m_batchList[m_numBatchOperations].requiresClipping) m_batchList[m_numBatchOperations].clipRect = *clip; m_batchList[m_numBatchOperations].inProgress = false; ++m_numBatchOperations; VEGARefCount::IncRef(tex); } if (numVerts&3) { numVerts = (numVerts&~3)+4; if (numVerts > m_numRemainingBatchVerts) m_numRemainingBatchVerts = numVerts; } m_firstBatchVert += numVerts; if (mode == BM_INDEXED_TRIANGLES) m_triangleIndexCount += indexCount; m_numRemainingBatchVerts -= numVerts; } void VEGABackend_HW3D::scheduleFontBatch(VEGAFont* fnt, unsigned int numVerts, const OpRect& affected) { // if there's a deferred transaction it has to be flushed now static_cast<VEGABackingStore_FBO*>(renderTarget->GetBackingStore())->FlushTransaction(); static_cast<VEGABackingStore_FBO*>(renderTarget->GetBackingStore())->setCurrentBatcher(this); OP_ASSERT(numVerts == 4); #ifdef VEGA_NATIVE_FONT_SUPPORT if (!m_nativeFontRect.IsEmpty() && m_nativeFontRect.Intersecting(affected)) { static_cast<VEGABackingStore_FBO*>(renderTarget->GetBackingStore())->GetWriteRenderTarget(m_currentFrame)->flushFonts(); m_nativeFontRect.Empty(); } #endif if (m_numBatchOperations > 0 && m_batchList[m_numBatchOperations-1].font == fnt && m_batchList[m_numBatchOperations-1].inProgress) { m_batchList[m_numBatchOperations-1].numVertices += numVerts; m_batchList[m_numBatchOperations-1].affectedRect.UnionWith(affected); } else { m_batchList[m_numBatchOperations].firstVertex = m_firstBatchVert; m_batchList[m_numBatchOperations].numVertices = numVerts; m_batchList[m_numBatchOperations].texture = NULL; m_batchList[m_numBatchOperations].font = fnt; m_batchList[m_numBatchOperations].renderState = NULL; m_batchList[m_numBatchOperations].affectedRect = affected; m_batchList[m_numBatchOperations].mode = BM_QUAD; m_batchList[m_numBatchOperations].indexCount = 0; m_batchList[m_numBatchOperations].requiresClipping = false; m_batchList[m_numBatchOperations].inProgress = true; ++m_numBatchOperations; fnt->setBatchingBackend(this); } m_firstBatchVert += numVerts; m_numRemainingBatchVerts -= numVerts; } void VEGABackend_HW3D::appendVertexDataToBatch(const unsigned int source_batch_idx, const unsigned int target_batch_idx, VEGA3dDevice::Vega2dVertex* temp_storage, const OpRect& affected) { OP_ASSERT(temp_storage); OP_ASSERT(m_numBatchOperations); // allow using first free batch, assuming its first vertex matches // first free vertex (done from scheduleBatch) OP_ASSERT(source_batch_idx < m_numBatchOperations || (source_batch_idx == m_numBatchOperations && m_batchList[source_batch_idx].firstVertex == m_firstBatchVert)); OP_ASSERT(source_batch_idx > target_batch_idx); const BatchOperation& source = m_batchList[source_batch_idx]; BatchOperation& target = m_batchList[target_batch_idx]; OP_ASSERT(source.firstVertex > target.firstVertex); const unsigned int move_dist = source.firstVertex - m_batchList[target_batch_idx+1].firstVertex; // copy vertex data from vertex_data_offset to temp_storage, it // will be appended after target's vertex data later op_memcpy(temp_storage, m_vert + source.firstVertex, source.numVertices * sizeof(VEGA3dDevice::Vega2dVertex)); if (m_triangleIndexCount) { unsigned int indexOffs = 0; // batch entries before target should not be touched for (unsigned int b = 0; b < target_batch_idx; ++b) { if (m_batchList[b].mode == BM_INDEXED_TRIANGLES) { indexOffs += m_batchList[b].indexCount; } } // update triangle indices for all moved batches for (unsigned int b = target_batch_idx+1; b < source_batch_idx; ++b) { if (m_batchList[b].mode == BM_INDEXED_TRIANGLES) { OP_ASSERT(m_batchList[b].indexCount > 0); const unsigned int ic = m_batchList[b].indexCount; for (unsigned int i = 0; i < ic; ++i) { m_triangleIndices[indexOffs + i] += source.numVertices; } indexOffs += ic; } } } for (unsigned int b = target_batch_idx+1; b < source_batch_idx; ++b) { m_batchList[b].firstVertex += source.numVertices; } // move data after target to the right VEGA3dDevice::Vega2dVertex* target_batch_end = m_vert + source.firstVertex - move_dist; op_memmove(target_batch_end + source.numVertices, target_batch_end, move_dist * sizeof(VEGA3dDevice::Vega2dVertex)); // append data to target op_memcpy(target_batch_end, temp_storage, source.numVertices * sizeof(VEGA3dDevice::Vega2dVertex)); target.numVertices += source.numVertices; target.affectedRect.UnionWith(affected); } void VEGABackend_HW3D::finishCurrentFontBatch() { if (g_vegaGlobals.m_current_batcher && g_vegaGlobals.m_current_batcher != this) { g_vegaGlobals.m_current_batcher->flushBatches(); } g_vegaGlobals.m_current_batcher = this; if (m_numBatchOperations < 1 || !m_batchList[m_numBatchOperations-1].inProgress) return; BatchOperation* current = m_batchList+m_numBatchOperations-1; current->inProgress = false; if (current->requiresClipping && current->clipRect.Contains(current->affectedRect)) current->requiresClipping = false; else if (current->requiresClipping) current->affectedRect.IntersectWith(current->clipRect); unsigned int potential = m_numBatchOperations; for (unsigned int batch = m_numBatchOperations-1; batch > 0 && potential == m_numBatchOperations; --batch) { if (m_batchList[batch-1].font == current->font) potential = batch-1; else if (current->affectedRect.Intersecting(m_batchList[batch-1].affectedRect)) break; } if (potential == m_numBatchOperations) return; if (potential != m_numBatchOperations-2) { VEGA3dDevice::Vega2dVertex* temp = OP_NEWA(VEGA3dDevice::Vega2dVertex, current->numVertices); if (!temp) return; appendVertexDataToBatch(m_numBatchOperations-1, potential, temp, current->affectedRect); OP_DELETEA(temp); } else { m_batchList[potential].numVertices += current->numVertices; m_batchList[potential].affectedRect.UnionWith(current->affectedRect); } --m_numBatchOperations; } #ifdef VEGA_NATIVE_FONT_SUPPORT void VEGABackend_HW3D::scheduleNativeFontBatch(const OpRect& affected) { //setting current batcher to 'this' while m_nativeFontRect is empty would crash later //since the batcher is not going to be reset. if (affected.IsEmpty()) return; if (g_vegaGlobals.m_current_batcher && g_vegaGlobals.m_current_batcher != this) { g_vegaGlobals.m_current_batcher->flushBatches(); } // If this font batch covers a pending drawing operation the batch queue must be flushed for (unsigned int batch = 0; batch < m_numBatchOperations; ++batch) { if (m_batchList[batch].affectedRect.Intersecting(affected)) { // Clear the native font rect to ensure font data is not flushed OpRect old = m_nativeFontRect; m_nativeFontRect.Empty(); flushBatches(); m_nativeFontRect = old; } } m_nativeFontRect.UnionWith(affected); g_vegaGlobals.m_current_batcher = this; } #endif void VEGABackend_HW3D::flushBatches(VEGAStencil* textStencil) { // Some operations modify the rendertarget directly without scheduling a batch. If this happens // we must also make sure other potential batchers are flushed if (g_vegaGlobals.m_current_batcher && g_vegaGlobals.m_current_batcher != this) { g_vegaGlobals.m_current_batcher->flushBatches(); } #ifdef VEGA_NATIVE_FONT_SUPPORT if (!m_nativeFontRect.IsEmpty()) { OP_ASSERT(g_vegaGlobals.m_current_batcher == this); g_vegaGlobals.m_current_batcher = NULL; static_cast<VEGABackingStore_FBO*>(renderTarget->GetBackingStore())->GetWriteRenderTarget(m_currentFrame)->flushFonts(); m_nativeFontRect.Empty(); } #endif if (m_firstBatchVert) { finishCurrentFontBatch(); static_cast<VEGABackingStore_FBO*>(renderTarget->GetBackingStore())->setCurrentBatcher(NULL); #ifdef VEGA_NATIVE_FONT_SUPPORT OP_ASSERT(g_vegaGlobals.m_current_batcher == this || g_vegaGlobals.m_current_batcher == NULL); #else OP_ASSERT(g_vegaGlobals.m_current_batcher == this); #endif g_vegaGlobals.m_current_batcher = NULL; VEGA3dDevice* dev3d = g_vegaGlobals.vega3dDevice; dev3d->setRenderTarget(static_cast<VEGABackingStore_FBO*>(renderTarget->GetBackingStore())->GetWriteRenderTarget(m_currentFrame)); // trigger setShaderProgram and setOrthogonalProjection only when needed VEGA3dShaderProgram::WrapMode prev_wrap_mode = VEGA3dShaderProgram::WRAP_MODE_COUNT; bool shader2dTextUsed[TEXT_SHADER_COUNT]; op_memset(shader2dTextUsed, 0, sizeof(shader2dTextUsed)); unsigned int firstVert; RETURN_VOID_IF_ERROR(m_vbuffer->writeAnywhere(m_firstBatchVert, sizeof(VEGA3dDevice::Vega2dVertex), m_vert, firstVert)); // offset from start of triangle index buffer, accumulates for // each indexed triangle batch size_t triangleIndexOffset = 0; bool clippingSet = true; bool customRenderState = true; for (unsigned int batch = 0; batch < m_numBatchOperations; ++batch) { m_batchList[batch].firstVertex += firstVert; VEGA3dVertexLayout* layout; if (m_batchList[batch].requiresClipping) { dev3d->setScissor(m_batchList[batch].clipRect.x, m_batchList[batch].clipRect.y, m_batchList[batch].clipRect.width, m_batchList[batch].clipRect.height); clippingSet = true; } else if (clippingSet) { dev3d->setScissor(0, 0, renderTarget->getWidth(), renderTarget->getHeight()); clippingSet = false; } if (m_batchList[batch].renderState) { dev3d->setRenderState(m_batchList[batch].renderState); customRenderState = true; } else if (customRenderState && !m_batchList[batch].font) { dev3d->setRenderState(m_defaultRenderState); customRenderState = false; } if (m_batchList[batch].font) { dev3d->setTexture(0, m_batchList[batch].font->getTexture(dev3d, true)); m_batchList[batch].font->setBatchingBackend(NULL); // Requested shader features unsigned char shaderIndex = textStencil ? Stencil : 0; // Index of stencil texture in shader, 1 by default, will be incremented if interpolation texture is present unsigned int stencilIndex = 1; bool renderStateSet = false; #ifdef VEGA_SUBPIXEL_FONT_BLENDING bool subpixelRendering = renderTarget->getTargetWindow() && m_batchList[batch].font->UseSubpixelRendering(); if (subpixelRendering) { // If sub pixel rendering is required we first try ExtBlend for better performance shaderIndex |= ExtBlend; #ifdef VEGA_SUBPIXEL_FONT_INTERPOLATION_WORKAROUND // Enable interpolation if the font requests it if (m_batchList[batch].font->UseGlyphInterpolation() && m_batchList[batch].font->getTexture(dev3d, true, false)) shaderIndex |= Interpolation; #endif // VEGA_SUBPIXEL_FONT_INTERPOLATION_WORKAROUND if (OpStatus::IsError(createTextShader(shaderIndex))) { // Creating shader failed, drop ExtBlend and try again shaderIndex &= (~ExtBlend); if (OpStatus::IsError(createTextShader(shaderIndex))) { #ifdef VEGA_SUBPIXEL_FONT_INTERPOLATION_WORKAROUND // Normally this shouldn't fail, but in case of OOM or driver bug we should // be safe to fall back to the normal text shader without interpolation OP_ASSERT(shaderIndex & Interpolation); shaderIndex &= (~Interpolation); // This can't fail OpStatus::Ignore(createTextShader(shaderIndex)); #else OP_ASSERT(!"shouldn't be here"); #endif } } #ifdef VEGA_SUBPIXEL_FONT_INTERPOLATION_WORKAROUND // Set the interpolation texture if (shaderIndex & Interpolation) { stencilIndex ++; dev3d->setTexture(1, m_batchList[batch].font->getTexture(dev3d, true, false)); } #endif if (OpStatus::IsError(createSubpixelRenderState())) { // Disable subpixel rendering subpixelRendering = false; shaderIndex &= (~ExtBlend); } else if (shaderIndex & ExtBlend) { m_subpixelRenderState->setBlendFunc(VEGA3dRenderState::BLEND_ONE, VEGA3dRenderState::BLEND_EXTENDED_ONE_MINUS_SRC1_COLOR #ifndef VEGA_SUBPIXEL_FONT_OVERWRITE_ALPHA ,VEGA3dRenderState::BLEND_ZERO, VEGA3dRenderState::BLEND_ONE #endif ); dev3d->setRenderState(m_subpixelRenderState); renderStateSet = true; customRenderState = true; } } #endif // VEGA_SUBPIXEL_FONT_BLENDING if (!renderStateSet && customRenderState) { dev3d->setRenderState(m_defaultRenderState); customRenderState = false; renderStateSet = true; } // Now we should have a text shader ready for use, shaderIndex // is not only a index value but also suggest the features this // shader supports VEGA3dShaderProgram* textShader = shader2dText[shaderIndex]; layout = m_vlayout2dText[shaderIndex]; dev3d->setShaderProgram(textShader); // Initialization if shader is used for the first time in this batch if (!shader2dTextUsed[shaderIndex]) { textShader->setOrthogonalProjection(); shader2dTextUsed[shaderIndex] = true; #ifdef VEGA_SUBPIXEL_FONT_BLENDING if (!subpixelRendering) #endif // VEGA_SUBPIXEL_FONT_BLENDING { float acomp[4] = { 0, 0, 0, 1 }; textShader->setVector4(textAlphaCompLocation[shaderIndex], acomp); } } // Initialize if there is a stencil if (shaderIndex & Stencil) { VEGA_FIX strans[4] = { 0, 0, 0, 0 }; VEGA_FIX ttrans[4] = { 0, 0, 0, 0 }; VEGA3dTexture* stencilTex; updateStencil(textStencil, strans, ttrans, stencilTex); shader2dText[shaderIndex]->setVector4(textTexGenTransSLocation[shaderIndex/2], strans); shader2dText[shaderIndex]->setVector4(textTexGenTransTLocation[shaderIndex/2], ttrans); dev3d->setTexture(stencilIndex, stencilTex); } #ifdef VEGA_SUBPIXEL_FONT_BLENDING if (subpixelRendering && !(shaderIndex & ExtBlend)) { int alphaCompLocation = textAlphaCompLocation[shaderIndex]; m_subpixelRenderState->setBlendFunc(VEGA3dRenderState::BLEND_ONE, VEGA3dRenderState::BLEND_ONE_MINUS_SRC_ALPHA); OP_ASSERT(m_batchList[batch].mode == VEGABackend_HW3D::BM_QUAD); OP_ASSERT((m_batchList[batch].firstVertex&3) == 0); float acomp[4] = { 1, 0, 0, 0 }; OP_ASSERT(acomp[0] == 1 && acomp[1] == 0 && acomp[2] == 0 && acomp[3] == 0); m_subpixelRenderState->setColorMask(true, false, false, false); dev3d->setRenderState(m_subpixelRenderState); textShader->setVector4(alphaCompLocation, acomp); dev3d->drawIndexedPrimitives(VEGA3dDevice::PRIMITIVE_TRIANGLE, layout, dev3d->getQuadIndexBuffer((m_batchList[batch].numVertices*6)/4), 2, (m_batchList[batch].firstVertex/4)*6, (m_batchList[batch].numVertices/4)*6); acomp[0] = 0; acomp[1] = 1; OP_ASSERT(acomp[0] == 0 && acomp[1] == 1 && acomp[2] == 0 && acomp[3] == 0); m_subpixelRenderState->setColorMask(false, true, false, false); dev3d->setRenderState(m_subpixelRenderState); textShader->setVector4(alphaCompLocation, acomp); dev3d->drawIndexedPrimitives(VEGA3dDevice::PRIMITIVE_TRIANGLE, layout, dev3d->getQuadIndexBuffer((m_batchList[batch].numVertices*6)/4), 2, (m_batchList[batch].firstVertex/4)*6, (m_batchList[batch].numVertices/4)*6); acomp[1] = 0; acomp[2] = 1; OP_ASSERT(acomp[0] == 0 && acomp[1] == 0 && acomp[2] == 1 && acomp[3] == 0); m_subpixelRenderState->setColorMask(false, false, true, false); dev3d->setRenderState(m_subpixelRenderState); textShader->setVector4(alphaCompLocation, acomp); #ifdef VEGA_SUBPIXEL_FONT_OVERWRITE_ALPHA dev3d->drawIndexedPrimitives(VEGA3dDevice::PRIMITIVE_TRIANGLE, layout, dev3d->getQuadIndexBuffer((m_batchList[batch].numVertices*6)/4), 2, (m_batchList[batch].firstVertex/4)*6, (m_batchList[batch].numVertices/4)*6); acomp[2] = 0; acomp[3] = 1; OP_ASSERT(acomp[0] == 0 && acomp[1] == 0 && acomp[2] == 0 && acomp[3] == 1); m_subpixelRenderState->setColorMask(false, false, false, true); dev3d->setRenderState(m_subpixelRenderState); textShader->setVector4(alphaCompLocation, acomp); #endif // The draw call is intentionally missing here, it will be issued after the "if" block in the regular rendering path customRenderState = true; } #endif // VEGA_SUBPIXEL_FONT_BLENDING } else { VEGA3dTexture* tex = m_batchList[batch].texture; if (tex) { tex->setWrapMode(m_batchList[batch].texWrapS, m_batchList[batch].texWrapT); tex->setFilterMode(m_batchList[batch].texMinFilter, m_batchList[batch].texMagFilter); } const VEGA3dShaderProgram::WrapMode wrap_mode = VEGA3dShaderProgram::GetWrapMode(tex); dev3d->setTexture(0, tex); dev3d->setShaderProgram(shader2dV[wrap_mode]); if (prev_wrap_mode != wrap_mode) { shader2dV[wrap_mode]->setOrthogonalProjection(); prev_wrap_mode = wrap_mode; } layout = m_vlayout2d; } switch (m_batchList[batch].mode) { case BM_QUAD: { OP_ASSERT((m_batchList[batch].firstVertex&3) == 0); unsigned int firstInd = (m_batchList[batch].firstVertex/4)*6; VEGA3dBuffer* buffer = dev3d->getQuadIndexBuffer(firstInd + (m_batchList[batch].numVertices/4)*6); dev3d->drawIndexedPrimitives(VEGA3dDevice::PRIMITIVE_TRIANGLE, layout, buffer, 2, firstInd, (m_batchList[batch].numVertices/4)*6); break; } case BM_TRIANGLE_FAN: dev3d->drawPrimitives(VEGA3dDevice::PRIMITIVE_TRIANGLE_FAN, layout, m_batchList[batch].firstVertex, m_batchList[batch].numVertices); break; case BM_INDEXED_TRIANGLES: { // sync indices to GPU if (!triangleIndexOffset) { if (firstVert) { for (unsigned i = 0; i < m_triangleIndexCount; ++i) m_triangleIndices[i] += firstVert; } m_triangleIndexBuffer->update(0, m_triangleIndexCount*sizeof(*m_triangleIndices), m_triangleIndices); } const size_t numInd = m_batchList[batch].indexCount; OP_ASSERT(numInd > 0); dev3d->drawIndexedPrimitives(VEGA3dDevice::PRIMITIVE_TRIANGLE, layout, m_triangleIndexBuffer, 2, triangleIndexOffset, numInd); triangleIndexOffset += numInd; break; } default: OP_ASSERT(!"unsupported batch type"); } VEGARefCount::DecRef(m_batchList[batch].texture); } m_numRemainingBatchVerts = dev3d->getVertexBufferSize(); m_firstBatchVert = 0; m_numBatchOperations = 0; OP_ASSERT(triangleIndexOffset == m_triangleIndexCount); m_triangleIndexCount = 0; } } void VEGABackend_HW3D::onFontDeleted(VEGAFont* font) { OP_ASSERT(font); if (m_firstBatchVert) { for (unsigned int batch = 0; batch < m_numBatchOperations; ++batch) { if (m_batchList[batch].font == font) { flushBatches(); return; } } } } #ifdef VEGA_SUBPIXEL_FONT_BLENDING OP_STATUS VEGABackend_HW3D::createSubpixelRenderState() { if (!m_subpixelRenderState) { RETURN_IF_ERROR(g_vegaGlobals.vega3dDevice->createRenderState(&m_subpixelRenderState, false)); m_subpixelRenderState->enableScissor(true); m_subpixelRenderState->enableBlend(true); } return OpStatus::OK; } #endif OP_STATUS VEGABackend_HW3D::createTextShader(unsigned char traits) { if (textShaderLoaded[traits]) return shader2dText[traits] ? OpStatus::OK : OpStatus::ERR; VEGA3dDevice* device = g_vegaGlobals.vega3dDevice; // Set to true no matter shader will be created successfully or not // to avoid always trying to load the failed shader textShaderLoaded[traits] = true; VEGA3dShaderProgram::ShaderType shdType = VEGA3dShaderProgram::SHADER_TEXT2D; switch (traits) { case 0: shdType = VEGA3dShaderProgram::SHADER_TEXT2D; break; case Stencil: shdType = VEGA3dShaderProgram::SHADER_TEXT2DTEXGEN; break; #ifdef VEGA_SUBPIXEL_FONT_BLENDING case ExtBlend: shdType = VEGA3dShaderProgram::SHADER_TEXT2DEXTBLEND; break; case Stencil + ExtBlend: shdType = VEGA3dShaderProgram::SHADER_TEXT2DEXTBLENDTEXGEN; break; #ifdef VEGA_SUBPIXEL_FONT_INTERPOLATION_WORKAROUND case Interpolation: shdType = VEGA3dShaderProgram::SHADER_TEXT2D_INTERPOLATE; break; case Stencil + Interpolation: shdType = VEGA3dShaderProgram::SHADER_TEXT2DTEXGEN_INTERPOLATE; break; case ExtBlend + Interpolation: shdType = VEGA3dShaderProgram::SHADER_TEXT2DEXTBLEND_INTERPOLATE; break; case Stencil + ExtBlend + Interpolation: shdType = VEGA3dShaderProgram::SHADER_TEXT2DEXTBLENDTEXGEN_INTERPOLATE; break; #endif // VEGA_SUBPIXEL_FONT_INTERPOLATION_WORKAROUND #endif // VEGA_SUBPIXEL_FONT_BLENDING default: OP_ASSERT(!"shouldn't be here, make sure to update this function if TextShaderTrait is changed"); } #ifdef VEGA_SUBPIXEL_FONT_BLENDING // Don't even try to load ExtBlend shader if device claims no support if (!(traits & ExtBlend) || device->hasExtendedBlend()) #endif { if (OpStatus::IsSuccess(device->createShaderProgram(shader2dText + traits, shdType, VEGA3dShaderProgram::WRAP_CLAMP_CLAMP))) if (OpStatus::IsError(device->createVega2dVertexLayout(m_vlayout2dText + traits, shdType))) { VEGARefCount::DecRef(shader2dText[traits]); shader2dText[traits] = NULL; } } if (!shader2dText[traits]) return OpStatus::ERR; // Initialize texture location variables if this shader has a stencil if (traits & Stencil) { textTexGenTransSLocation[traits/2] = shader2dText[traits]->getConstantLocation("texTransS"); textTexGenTransTLocation[traits/2] = shader2dText[traits]->getConstantLocation("texTransT"); } #ifdef VEGA_SUBPIXEL_FONT_BLENDING // ExtBlend shaders don't have alphaComponent if (!(traits & ExtBlend)) #endif { textAlphaCompLocation[traits] = shader2dText[traits]->getConstantLocation("alphaComponent"); } return OpStatus::OK; } #endif // VEGA_SUPPORT && VEGA_3DDEVICE
#define CATCH_CONFIG_MAIN #include "../external/catch2/catch.hpp" #include "../src/array/includes_any.hpp" #include <vector> #include <string> template<typename T> struct TestStruct { std::vector<T> nums; std::vector<T> incs; bool actual; TestStruct(std::vector<T> nums, std::vector<T> incs, bool actual) : nums(nums), incs(incs), actual(actual) { } }; TEST_CASE("Include Any Test", "[include_any]") { std::vector<TestStruct<int>> testVec { { {1, 2, 3, 3, 3, 3}, {1, 5}, true }, { {-5, 3, 6, 7, 8, 9, 11}, {-5, 76, 54}, true }, { {1, 2, 3, 4, 5, 6}, {7, 8}, false } }; for (auto &&var : testVec) { REQUIRE(Array::includesAny(var.nums, var.incs) == var.actual); } }
#include <iostream> #include <string> #include <vector> using namespace std; class Stack{ private: int *stack; int size; int pos; vector<int> v; public: Stack(int _size = 0){ size = _size; stack = new int[size]; pos = 0; } ~Stack(){ delete[] stack; } void push(int x){ if(pos == size){ return; } stack[pos] = x; pos++; } void pop(){ if(pos == 0){ v.push_back(-1); }else{ pos--; v.push_back(stack[pos]); } } void getSize(){ v.push_back(pos); } void isEmpty(){ if(pos == 0){ v.push_back(1); }else{ v.push_back(0); } } void top(){ if(pos == 0){ v.push_back(-1); }else{ v.push_back(stack[pos-1]); } } vector<int> getV(){ return v; } }; int main(){ Stack *myStack; int size; cin >> size; myStack = new Stack(size); for(int i = 0; i < size; i++){ string a; cin >> a; if(a.compare("push") == 0){ int x; cin >> x; myStack->push(x); }else if(a.compare("pop") == 0){ myStack->pop(); }else if(a.compare("size") == 0){ myStack->getSize(); }else if(a.compare("empty") == 0){ myStack->isEmpty(); }else if(a.compare("top") == 0){ myStack->top(); } } for(int i = 0; i < myStack->getV().size(); i++){ cout << myStack->getV()[i] << endl; } delete myStack; return 0; }
// Copyright 2012 Yandex #ifndef LTR_SCORERS_BAYESIAN_SCORER_H_ #define LTR_SCORERS_BAYESIAN_SCORER_H_ #include <map> #include <string> #include "ltr/density_estimators/base_probability_density_estimator.h"; #include "ltr/utility/shared_ptr.h" #include "ltr/data/object.h" #include "ltr/scorers/scorer.h" using ltr::BaseProbabilityDensityEstimator; using ltr::Object; namespace ltr { class BayesianScorer : public Scorer { public: typedef map<double, double> LabelToPriorProbability; typedef ltr::utility::shared_ptr<BayesianScorer> Ptr; string toString() const { return "Bayesian Scorer"; }; BayesianScorer() { } BayesianScorer(const LabelToPriorProbability& prior_probability, BaseProbabilityDensityEstimator::Ptr estimator) : prior_probability_(prior_probability), estimator_(estimator) { } private: virtual double scoreImpl(const Object& object) const; virtual string generateCppCodeImpl(const string& function_name) const { return ""; } virtual string getDefaultAlias() const {return "BayesianScorer";} LabelToPriorProbability prior_probability_; BaseProbabilityDensityEstimator::Ptr estimator_; }; }; #endif // LTR_SCORERS_BAYESIAN_SCORER_H_
#include <iostream> #include <vector> #include <algorithm> #include <fstream> #include <queue> #include <unordered_set> #include <unordered_map> #define INT_MIN (1<<31) #define INT_MAX (~INT_MIN) #define UNREACHABLE (INT_MAX>>2) using namespace std; ifstream fin("314_input.txt"); #define cin fin struct ele { ele(int row, int col, int ori, int step) { this->row = row; this->col = col; this->ori = ori; this->step = step; } int row; int col; int ori; int step; }; int main() { unordered_map<string, int> orient; orient["east"] = 1; orient["south"] = 2; orient["west"] = 4; orient["north"] = 8; unordered_map<int, int> turn_left; turn_left[1] = 8; turn_left[2] = 1; turn_left[4] = 2; turn_left[8] = 4; unordered_map<int, int> turn_right; turn_right[1] = 2; turn_right[2] = 4; turn_right[4] = 8; turn_right[8] = 1; unordered_map<int, vector<pair<int, int>>> forward_dir; forward_dir[1] = vector<pair<int, int>>(); forward_dir[1].push_back(pair<int, int>(0, 1)); forward_dir[1].push_back(pair<int, int>(0, 2)); forward_dir[1].push_back(pair<int, int>(0, 3)); forward_dir[2] = vector<pair<int, int>>(); forward_dir[2].push_back(pair<int, int>(1, 0)); forward_dir[2].push_back(pair<int, int>(2, 0)); forward_dir[2].push_back(pair<int, int>(3, 0)); forward_dir[4] = vector<pair<int, int>>(); forward_dir[4].push_back(pair<int, int>(0, -1)); forward_dir[4].push_back(pair<int, int>(0, -2)); forward_dir[4].push_back(pair<int, int>(0, -3)); forward_dir[8] = vector<pair<int, int>>(); forward_dir[8].push_back(pair<int, int>(-1, 0)); forward_dir[8].push_back(pair<int, int>(-2, 0)); forward_dir[8].push_back(pair<int, int>(-3, 0)); // cout<<"ok-1"<<endl; int n, m; cin >> n >> m; int case_count = 0; while (n != 0 && m != 0) { case_count++; //cout << "==============================" << endl; //if (case_count == 18) // cout << n << ' ' << m << endl; vector<vector<int>> atlas(n, vector<int>(m, 0)); // cout<<"ok-0.5"<<endl; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) cin >> atlas[i][j]; //if (case_count == 18) //{ // for (int i = 0; i < n; i++, cout << endl) // for (int j = 0; j < m; j++) // cout << atlas[i][j] << ' '; //} // cout<<"ok0"<<endl; vector<vector<bool>> reachable(n, vector<bool>(m, true)); reachable[0][0] = !(atlas[0][0] == 1); for (int i = 1; i<n; i++) reachable[i][0] = !(atlas[i][0] || atlas[i-1][0]); for (int j = 1; j<m; j++) reachable[0][j] = !(atlas[0][j] || atlas[0][j-1]); for (int i = 1; i<n; i++) for (int j = 1; j<m; j++) reachable[i][j] = !(atlas[i][j] || atlas[i-1][j] || atlas[i][j-1] || atlas[i-1][j-1]); //if (case_count == 18) //{ // cout << "+++++++++++++++++++++++++++++++++" << endl; // for (int i = 0; i < n; i++, cout << endl) // for (int j = 0; j < m; j++) // cout << (int)reachable[i][j]; // cout << "---------------------------------------------------------" << endl; //} // cout<<"ok1"<<endl; vector<vector<int>> status(n, vector<int>(m, 0)); int s_row, s_col; int e_row, e_col; string s_orient; cin >> s_row >> s_col >> e_row >> e_col >> s_orient; //if (case_count == 18) //{ // cout << s_row << ' ' << s_col << ' ' << e_row << ' ' << e_col << ' ' << s_orient << endl; //} // cout<<"ok2"<<endl; queue<ele> q; q.push(ele(s_row, s_col, orient[s_orient], 0)); status[s_row][s_col] |= orient[s_orient]; //begin bfs // cout<<"ok3"<<endl; int steps = -1; if (s_row == e_row && s_col == e_col) steps = 0; while (!q.empty() && steps<0) { ele cur = q.front(); q.pop(); int row = cur.row; int col = cur.col; int ori = cur.ori; int step = cur.step; // cout<<"ok4"<<endl; //turn left if (!(status[row][col] & turn_left[ori])) { q.push(ele(row, col, turn_left[ori], step+1)); status[row][col] |= turn_left[ori]; } // turn right if (!(status[row][col] & turn_right[ori])) { q.push(ele(row, col, turn_right[ori], step+1)); status[row][col] |= turn_right[ori]; } // cout<<"ok5"<<endl; // go forward for (auto it : forward_dir[ori]) { int next_row = row + it.first; int next_col = col + it.second; if (next_row <= 0) break; if (next_row >= n) break; if (next_col <= 0) break; if (next_col >= m) break; if (!reachable[next_row][next_col]) break; if (!(status[next_row][next_col] & ori)) { if (next_row == e_row && next_col == e_col) { steps = step + 1; break; } q.push(ele(next_row, next_col, ori, step+1)); status[next_row][next_col] |= ori; } } // cout<<"ok6"<<endl; } //end bfs cout << steps << endl; cin >> n >> m; } }
#include <pthread.h> #include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <time.h> #include "mysql_connection.h" #include <cppconn/driver.h> #include <cppconn/exception.h> #include <cppconn/resultset.h> #include <cppconn/statement.h> #include <cppconn/prepared_statement.h> #define NUM_THREADS 1000 #define roomMax 3 //per day using namespace std; pthread_mutex_t mutex; sql::Driver *driver; sql::Connection *con; sql::Statement *stmt; sql::ResultSet *res,*res1; sql::PreparedStatement *pstmt; void dbConnect() { try{ /* Create a connection */ driver = get_driver_instance(); //printf("inside connect\n"); con = driver->connect("tcp://127.0.0.1:3306", "root", "root"); /* Connect to the MySQL test database */ con->setSchema("project"); cout<<"Database Connection established...\n"; } catch (sql::SQLException &e) { cout << "# ERR: SQLException in " << __FILE__; cout << "# ERR: " << e.what(); cout << " (MySQL error code: " << e.getErrorCode(); cout << ", SQLState: " << e.getSQLState() << " )" << endl; } } /* void createRoomsTable() { //pstmt = con->prepareStatement("drop table rooms;"); pstmt = con->prepareStatement("create table rooms(roomNum integer(4) not null,addharNum varchar(12) not null,name varchar (100) not null, datee date not null, constraint uc_rooms unique (addharNum,name,datee));"); pstmt->execute(); } void createUserRegTable(); { pstmt = con->prepareStatement("create table users(userName varchar(20) not null,userId varchar(20) primary key,password varchar(20) not null);"); pstmt->execute(); }*/ bool updateInsert(int roomNum, char* name, char* addharNum,char* dateBook) { // printf("name is%s\n",name ); try{ //cout<<"inside update insert\n"; pstmt = con->prepareStatement("INSERT INTO rooms(roomNum,addharNum,name,datee) VALUES(?,?,?,?) "); pstmt->setInt(1, roomNum); pstmt->setString(2, addharNum); pstmt->setString(3, name); pstmt->setString(4, dateBook); pstmt->execute(); cout<<"Insert room...\n"; //printf("%d",roomNum); fflush(stdout); return true; } catch (sql::SQLException &e) { cout << "# ERR: SQLException in " << __FILE__; cout << "# ERR: " << e.what(); cout << " (MySQL error code: " << e.getErrorCode(); cout << ", SQLState: " << e.getSQLState() << " )" << endl; return false; } } bool addharCheck(int roomNo, char* addharNo,char* dateBookStr) { try{ cout<<"Checking entry...\n"; pstmt = con->prepareStatement("SELECT roomNum,addharNum,datee from rooms where roomNum=? and addharNum=? and datee=?"); pstmt->setInt(1, roomNo); pstmt->setString(2, addharNo); pstmt->setString(3, dateBookStr); res = pstmt->executeQuery(); if(res->next()){ return true; } else { return false; } } catch (sql::SQLException &e) { cout << "# ERR: SQLException in " << __FILE__; cout << "# ERR: " << e.what(); cout << " (MySQL error code: " << e.getErrorCode(); cout << ", SQLState: " << e.getSQLState() << " )" << endl; } } void cancelledupdate(int roomNo, char* addharNo,char* dateBook)//deletes the entry from the table { try{ cout<<"Cancel room...\n"; pstmt = con->prepareStatement("delete from rooms where roomNum=? and addharNum=? and datee=?"); pstmt->setInt(1, roomNo); pstmt->setString(2, addharNo); pstmt->setString(3, dateBook); res = pstmt->executeQuery(); } catch (sql::SQLException &e) { cout << "# ERR: SQLException in " << __FILE__; cout << "# ERR: " << e.what(); cout << " (MySQL error code: " << e.getErrorCode(); cout << ", SQLState: " << e.getSQLState() << " )" << endl; } } bool ValidateUser(char* userId, char* Pass) { try{ cout<<"Validating user...\n"; pstmt = con->prepareStatement("SELECT userId,password from users where userId=? and password=? "); pstmt->setString(1, userId); pstmt->setString(2, Pass); res = pstmt->executeQuery(); if(res->next()){ return true; } else { return false; } } catch (sql::SQLException &e) { cout << "# ERR: SQLException in " << __FILE__; cout << "# ERR: " << e.what(); cout << " (MySQL error code: " << e.getErrorCode(); cout << ", SQLState: " << e.getSQLState() << " )" << endl; } } bool createUser(char* regName, char* regId, char* regPass) { try{ cout<<"creating user...\n"; pstmt = con->prepareStatement("insert into users values (?,?,?) "); pstmt->setString(1, regName); pstmt->setString(2, regId); pstmt->setString(3, regPass); res = pstmt->executeQuery(); return true; } catch (sql::SQLException &e) { cout << "# ERR: SQLException in " << __FILE__; cout << "# ERR: " << e.what(); cout << " (MySQL error code: " << e.getErrorCode(); cout << ", SQLState: " << e.getSQLState() << " )" << endl; return false; } } int roomsAvailable(char* dateBookStr) { int i=1; int countNumRooms; int roomNumber; cout<<"Checking Rooms available...\n"; try{ pstmt = con->prepareStatement("SELECT count(roomNum) from rooms where datee = ? "); pstmt->setString(1, dateBookStr); res = pstmt->executeQuery(); if(res->next()) { countNumRooms=res->getInt(1); if(countNumRooms>=roomMax) return (0); else { pstmt = con->prepareStatement("SELECT roomNum from rooms where datee = ? "); pstmt->setString(1, dateBookStr); res1 = pstmt->executeQuery(); //cout<<"here"; if(countNumRooms==0) { return 1; } while(res1->next()) { if(i<roomMax) { //cout<<i; //cout<<"value of i"; roomNumber=res1->getInt(1); if(i==roomNumber) { i++; //cout<<"here"<<i<<endl; continue; } } else { //cout<<"here 1 "<<i<<endl; return i; } } //cout<<"here 2 "<<i<<endl; return (i); } } else return (0); } catch (sql::SQLException &e) { cout << "# ERR: SQLException in " << __FILE__; cout << "# ERR: " << e.what(); cout << " (MySQL error code: " << e.getErrorCode(); cout << ", SQLState: " << e.getSQLState() << " )" << endl; } } //thread to book the ticket void book(int clientsock) { char name[30],addhar[30]; // char roomInfo[50];//to give user info about room (booked or not) int i,room_booked=0; char bookStr[10]; char book[] = "Your room number booked is: "; char dateBookStr[30]; memset(&name,'0',sizeof(name)); if((read(clientsock,name,sizeof(name)))<=0) perror("\n"); else { //printf("%s\n",name); fflush(stdout); } memset(&addhar,'0',sizeof(addhar)); if((read(clientsock,addhar,sizeof(addhar)))<=0) perror("\n"); else { //printf("%s\n",addhar); fflush(stdout); } //printf("room count = %d\n",room_count ); memset(&dateBookStr,'0',sizeof(dateBookStr)); if((read(clientsock,dateBookStr,sizeof(dateBookStr)))<=0) { perror("Date not recieved...\n"); pthread_exit(NULL); } else { //printf("-----------------------Date----------------------\n"); //printf("%s\n",dateBookStr); fflush(stdout); } //book the room pthread_mutex_lock(&mutex); room_booked=roomsAvailable(dateBookStr); //cout<<room_booked; //cout<<"room booked"; if(room_booked)//if room available then room number will be returned else 0 { if(updateInsert(room_booked,name,addhar,dateBookStr)) { sprintf(bookStr, "%d", room_booked); strcat(book, bookStr); //cout<<bookStr; fflush(stdout); write(clientsock, book, 40); } else { fflush(stdout); write(clientsock,"Room already booked with same credentials...\n",60); } } else { write(clientsock,"No rooms are available...\n",30); } pthread_mutex_unlock(&mutex); pthread_exit(NULL); } //function to cancel the ticket void cancel(int clientsock) { char roomNum[30],addhar[30]; int i,roomNumberInt; char dateBookStr[30]; memset(&roomNum,'0',sizeof(roomNum)); if((read(clientsock,roomNum,sizeof(roomNum)))<=0) perror("\n"); else { //printf("%s\n",roomNum); fflush(stdout); roomNumberInt=atoi(roomNum); //write in the file } //printf("%d\n",room_count ); memset(&addhar,'0',sizeof(addhar)); if((read(clientsock,addhar,sizeof(addhar)))<=0) perror("\n"); else { //printf("%s\n",addhar); fflush(stdout); //write in the file } memset(&dateBookStr,'0',sizeof(dateBookStr)); if((read(clientsock,dateBookStr,sizeof(dateBookStr)))<=0) { perror("Date not recieved...\n"); pthread_exit(NULL); } else { //printf("-----------------Cancel date------------------\n"); //printf("%s\n",dateBookStr); fflush(stdout); } //cancel the room pthread_mutex_lock(&mutex); if(addharCheck(roomNumberInt,addhar,dateBookStr)) { //cout<<"hereee"; cancelledupdate(roomNumberInt,addhar,dateBookStr); write(clientsock,"Your room is cancelled...",30); } else { write(clientsock,"One of the entry made is wrong...",50); } pthread_mutex_unlock(&mutex); pthread_exit(NULL); } //to reshedule the room void reschedule(int clientsock) { char roomNum[30],addhar[30],name[30]; int i,roomNumberInt; char currentDate[30]; char rescheduleDate[30]; int checkRoom; char bookStr[10]; char book[] = "Rescheduled. Your room number booked is: "; memset(&name,'0',sizeof(name)); if((read(clientsock,name,sizeof(name)))<=0) perror("\n"); else { //printf("%s\n",name); fflush(stdout); //write in the file } memset(&roomNum,'0',sizeof(roomNum)); if((read(clientsock,roomNum,sizeof(roomNum)))<=0) perror("\n"); else { //printf("%s\n",roomNum); fflush(stdout); roomNumberInt=atoi(roomNum); //write in the file } //printf("%d\n",room_count ); memset(&addhar,'0',sizeof(addhar)); if((read(clientsock,addhar,sizeof(addhar)))<=0) perror("\n"); else { //printf("%s\n",addhar); fflush(stdout); //write in the file } memset(&currentDate,'0',sizeof(currentDate)); if((read(clientsock,currentDate,sizeof(currentDate)))<=0) { perror("Date not recieved...\n"); pthread_exit(NULL); } else { //printf("-----------------Current date------------------\n"); //printf("%s\n",currentDate); fflush(stdout); } memset(&rescheduleDate,'0',sizeof(rescheduleDate)); if((read(clientsock,rescheduleDate,sizeof(rescheduleDate)))<=0) { perror("Date not recieved...\n"); pthread_exit(NULL); } else { //printf("-----------------Reshedule date------------------\n"); //printf("%s\n",rescheduleDate); fflush(stdout); } // reshedule the room pthread_mutex_lock(&mutex); if(addharCheck(roomNumberInt,addhar,currentDate)) { //cout<<"hereee"; checkRoom=roomsAvailable(rescheduleDate); if(checkRoom) { if(updateInsert(checkRoom,name,addhar,rescheduleDate)) { cancelledupdate(roomNumberInt,addhar,currentDate); sprintf(bookStr, "%d", checkRoom); strcat(book, bookStr); //cout<<bookStr; fflush(stdout); write(clientsock, book, 60); //write(clientsock,"Your room is rescheduled...",30); } else { write(clientsock,"Your room is already booked on rescheduled date..\n",60); } } else { write(clientsock,"Rooms not available on rescheduled date...\n",60); } } else { write(clientsock,"One of the entry made is wrong...\n",50); } pthread_mutex_unlock(&mutex); pthread_exit(NULL); } //thread to give client options void *ClientOptions(void *clientfd) { long tid; int clientsock = *(int*)clientfd; char choice[1],ch;//to read user choice memset(&choice,'0',sizeof(choice)); char userId[30],Pass[30]; char regName[30],regId[30],regPass[30]; char login[30]; //to register or login read(clientsock,login,30); if(strcmp(login,"login")==0) { //retreive userid and password from client cout<<"Client choose to login...\n"; if(read(clientsock,userId,30)<=0) perror("\n"); if(read(clientsock,Pass,30)<=0) perror("\n"); //cout<<userId<<Pass<<"\n"; if(ValidateUser(userId,Pass)) { write(clientsock,"Yes",3); if((ch=read(clientsock,choice,sizeof(choice)))<=0) perror("\n"); else { if(choice[0]=='b') { printf("Client choose to book...\n"); book(clientsock); } else if(choice[0]=='c') { printf("Client choose to cancel...\n"); cancel(clientsock); } else if(choice[0]=='r') { printf("Client choose to reschedule...\n"); reschedule(clientsock); } else { //invalid; } } pthread_exit(NULL); //switch() } else { write(clientsock,"No",30); //cout<<"Invalid Details entered by client"; pthread_exit(NULL); } } else { cout<<"Client choose to register...\n"; if(read(clientsock,regName,30)<=0) perror("\n"); if(read(clientsock,regId,30)<=0) perror("\n"); if(read(clientsock,regPass,30)<=0) perror("\n"); if(createUser(regName,regId,regPass)) { write(clientsock,"User Created...\n",30); pthread_exit(NULL); } else { write(clientsock,"User Not Created...Choose different User ID...\n",60); pthread_exit(NULL); } } } int main (int argc, char *argv[]) { //parameters for threading pthread_t threads[NUM_THREADS]; int rc,i; long t=0; dbConnect(); pthread_mutex_init(&mutex, NULL); //parameters for socket coonection int listenfd = 0;//to allow number of clients struct sockaddr_in serv_addr,client_addr; socklen_t addr_size; int connfd = 0;//socket discriptor listenfd = socket(AF_INET, SOCK_STREAM, 0);//welcome socket memset(&serv_addr, '0', sizeof(serv_addr)); serv_addr.sin_family = AF_INET;//server family serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(atoi(argv[1]));//host to network short(Big endian)---port number of central server bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));//binding port with the socket listen(listenfd, 10); printf("Welcome to server...\nReady to accept connections...\n"); while(1)//infinite loop to accept multiple connections { addr_size = sizeof(client_addr); //since accept field take 3 arg as socklen_t type connfd = accept(listenfd,(struct sockaddr *)&client_addr,&addr_size); if(connfd<0) { perror("Accept error...\n"); exit(1); } printf("Connection accepted...\n"); fflush(stdout); rc = pthread_create(&threads[t], NULL, ClientOptions, (void *)&connfd); //printf("%d\n",rc ); t++; if (rc){ //printf("ERROR; return code from pthread_create() is %d\n", rc); //exit(-1); } } }
#include "SortingIO.h" #include "stdlib.h" using namespace std; using std::vector; void merge(vector<long>& a, vector<long>& b, int size, int left, int middle); void mergeSort(vector<long>& a, int size); int main(int argc, char *argv[]) { int size; vector<long> myVector; std::string inputFileName; std::string outputFileName; if (argc != 3) { std::cout << "Please include the input file name followed by the output file name..."; exit(0); } inputFileName = argv[1]; outputFileName = argv[2]; valuesIntoArray(myVector, inputFileName); size = myVector.size(); mergeSort(myVector, size); outputToTextFile(myVector, outputFileName); } void merge(vector<long>& a, vector<long>& b, int size, int left, int middle) { int right = middle + middle - left; if (right > size) { right = size; } int i = left; int j = middle; int k = left; while (i < middle && j < right) { if (a[i] < a[j]) { b.push_back(a[i]); i++; } else { b.push_back(a[j]); j++; } } while (i < middle) { b.push_back(a[i]); i++; } while (j < right) { b.push_back(a[j]); j++; } for (i = left; i < right; ++i) { a[i] = b[i]; } } void mergeSort(vector<long>& a, int size) { vector<long> b; for (int i = 1; i < size; i *= 2) { b.resize(0); for (int left = 0, middle = i; middle < size; left = middle + i, middle = left + i) { merge(a, b, size, left, middle); } } }
#include "mesh.h" #include <QOpenGLFunctions> Mesh::Mesh(const QVector<QVector3D> &positions, const QVector<QVector2D> &uvs, const QVector<QVector3D> &normals, const QVector<unsigned int> &indices, const Material &material) : vao(), positionBuffer(QOpenGLBuffer::Type::VertexBuffer), uvBuffer(QOpenGLBuffer::Type::VertexBuffer), normalBuffer(QOpenGLBuffer::Type::VertexBuffer), elementBuffer(QOpenGLBuffer::Type::IndexBuffer), material(material) { vertexCount = indices.size(); this->positions = positions; this->indices = indices; vao.create(); vao.bind(); positionBuffer.create(); positionBuffer.setUsagePattern(QOpenGLBuffer::StaticDraw); positionBuffer.bind(); positionBuffer.allocate(positions.constData(), positions.size() * sizeof(QVector3D)); uvBuffer.create(); uvBuffer.setUsagePattern(QOpenGLBuffer::StaticDraw); uvBuffer.bind(); uvBuffer.allocate(uvs.constData(), uvs.size() * sizeof(QVector2D)); normalBuffer.create(); normalBuffer.setUsagePattern(QOpenGLBuffer::StaticDraw); normalBuffer.bind(); normalBuffer.allocate(normals.constData(), normals.size() * sizeof(QVector3D)); elementBuffer.create(); elementBuffer.setUsagePattern(QOpenGLBuffer::StaticDraw); elementBuffer.bind(); elementBuffer.allocate(indices.constData(), indices.size() * sizeof(unsigned int)); positionBuffer.release(); uvBuffer.release(); normalBuffer.release(); elementBuffer.release(); vao.release(); } void Mesh::render(QOpenGLFunctions *functions, QOpenGLShaderProgram *shaderProgram) { if (material.hasTexture()) { material.getTexture()->bind(GL_TEXTURE0); } shaderProgram->setUniformValue(shaderProgram->uniformLocation("material.textureSampler"), 0); shaderProgram->setUniformValue(shaderProgram->uniformLocation("hasTexture"), material.hasTexture()); // shaderProgram->setUniformValue(shaderProgram->uniformLocation("material.diffuse"), material.getDiffuseColor()); shaderProgram->enableAttributeArray(shaderProgram->attributeLocation("aPos")); positionBuffer.bind(); shaderProgram->setAttributeBuffer(shaderProgram->attributeLocation("aPos"), GL_FLOAT, 0, 3); shaderProgram->enableAttributeArray(shaderProgram->attributeLocation("aTexCoords")); uvBuffer.bind(); shaderProgram->setAttributeBuffer(shaderProgram->attributeLocation("aTexCoords"), GL_FLOAT, 0, 2); shaderProgram->enableAttributeArray(shaderProgram->attributeLocation("aNormal")); normalBuffer.bind(); shaderProgram->setAttributeBuffer(shaderProgram->attributeLocation("aNormal"), GL_FLOAT, 0, 3); elementBuffer.bind(); functions->glDrawElements( GL_TRIANGLES, vertexCount, GL_UNSIGNED_INT, (void *) 0 ); shaderProgram->disableAttributeArray(shaderProgram->uniformLocation("vertexPosition_modelspace")); shaderProgram->disableAttributeArray(shaderProgram->uniformLocation("vertexUV")); shaderProgram->disableAttributeArray(shaderProgram->uniformLocation("vertexNormal_modelspace")); if (material.hasTexture()) { material.getTexture()->release(); } } const QVector<QVector3D> &Mesh::getPositions() const { return positions; } int Mesh::getVertexCount() const { return vertexCount; } const QVector<unsigned int> & Mesh::getIndices() const{ return indices; } const Material &Mesh::getMaterial() const { return material; } void Mesh::setMaterial(const Material &material) { Mesh::material = material; }
// This program tests the integrity of the Mersenne Twister PRNG by comparing the expected average of summed random numbers to the real average // To-do: Get floating-point averages to work as expected, maybe add other PRNGs? #include <iostream> #include <random> #include <ctime> // Global namespace for initializing the Mersenne Twister PRNG namespace InitRNG { std::mt19937 mersenne{ static_cast<std::mt19937::result_type>(std::time(nullptr)) }; } // Return a random number distributed between two numbers int random(int min, int max) { std::uniform_int_distribution randNum{ min, max }; return randNum(InitRNG::mersenne); } // Return the expected sum of the random numbers if it were perfectly uniform int uniformAvg(int min, int max, int seeds) { int range{ (max - min) + 1 }; // Get the uniform distribution of each possible number within a number of seeds int dist{ seeds / range }; int sum{}; // Multiply every possible number by its distribution within the number of seeds and add it together for (int mult{ min }; mult <= max; ++mult) { sum += dist * mult; } return sum; } // Return a positive number representing the difference between two numbers (in this case, the real and expected averages) int difference(int first, int second) { if (first > second) return first - second; else return second - first; } int main() { // Infinite loop that allows the user to restart the program after it's finished while (true) { // Get and store important variables from user input // The lowest random number possible int minDist{}; std::cout << "Minimum distribution: "; std::cin >> minDist; // The highest random number possible int maxDist{}; std::cout << "Maximum distribution: "; std::cin >> maxDist; // How many times the program should sum seeded random numbers together in order to help calculate an average int numTries{}; std::cout << "Tries: "; std::cin >> numTries; // How many random numbers should be seeded and added together within a single try int seedNum{}; std::cout << "Seeds per try: "; std::cin >> seedNum; std::cout << '\n'; int realSum{}; // Seed random numbers a set amount of times and add them together, then print and repeat more times // "Try" is spelled incorrectly on purpose to prevent naming collisions for (int trie{ 1 }; trie <= numTries; ++trie) { int randSum{ 0 }; for (int seed{ 1 }; seed <= seedNum; ++seed) randSum += random(minDist, maxDist); realSum += randSum; std::cout << randSum << '\n'; } int expectedAvg{ uniformAvg(minDist, maxDist, seedNum) }; int realAvg{ realSum / numTries }; // Print final results and ask user if they want to restart std::cout << '\n' << "Expected average: " << expectedAvg << '\n' << "Real average: " << realAvg << '\n' << "Difference: " << difference(expectedAvg, realAvg) << "\n\n" << "Type 'r' to restart or anything else to quit. "; char option{}; std::cin >> option; // Start again from the beginning of the while loop if 'r' is entered, otherwise break the loop and end the program if (option == 'r') std::cout << '\n'; else break; } return 0; }
#include <iostream> #include "Word.h" #include "Translate.h" using namespace::std; namespace md = myDictionary; int main() { try { md::Word a("Hellow", "Eng"); md::Translate t(a); cout << t.GetTrans().GetWord(); } catch (exception &e) { cout << "Exception -> " << e.what() << endl; } catch (...) { cout << "skdfljk" << endl; } cin.get(); return 0; }
#include <cstdio> #include <cstring> #include <queue> #include <functional> using namespace std; int read() { int x=0, t=1; char c = getchar(); while(c<'0'||c>'9') { if(c == '-') t = -1; c = getchar(); } while(c>='0'&&c<='9') { x = x*10 + c-'0'; c = getchar(); } return x*t; } priority_queue<int, vector<int>, greater<int> > q; int sum; void init() { int n = read(); int a; while(n--) { a = read(); q.push(a); } } void process() { int a,b; while(q.size()>1) { a = q.top();q.pop(); b = q.top();q.pop(); sum += (a+b); q.push(a+b); } } void print() { printf("%d", sum); } int main() { init(); process(); print(); }
#pragma once #include "Light.h" class RectangleAreaLight : public Light { public: RGB lightColor; double radianceScalingFactor; vector<Vector> samplePoints; Vector direction; int samplePointWidth; int samplePointHeight; Matrix areaLightMatrix; Vector lightOrigin; double rectangleWidth; double rectangleHeight; void generateSamples(); void setLightOrigin(double x, double y, double z); void setLightDirection(double x, double y, double z); Vector getLightDirection(); void setRectangleAreaLightMatrix(double radianRotation); void setRectangleAreaLightSamplePointAmount(int samplePointAmount); void setRectangleAreaLightWidthHeight(double x, double y); int getNumberOfSamplePoints(); vector<Vector> getSamplePoints(); RectangleAreaLight(); ~RectangleAreaLight(); void setRadianceScalingFactor(double i); void setLightColor(double r, double g, double b); double getRadianceScalingFactor(); RGB getLightColor(); RGB getLightRadiance(); };
#include <ESP8266WiFi.h> #include <FirebaseArduino.h> #define FIREBASE_HOST "meter-gsm-default-rtdb.firebaseio.com" //Your Firebase Project URL goes here without "http:" , "\" and "/" #define FIREBASE_AUTH "mFye9VZL4fQzootlQg1ySxwRLQSqQ3ddQsPcqoNc" //Your Firebase Database Secret goes here #define WIFI_SSID "PTCL-BB" //WiFi SSID to which you want NodeMCU to connect #define WIFI_PASSWORD "pagal1234" //Password of your wifi network int val=0, val3=1000; void setup() { Serial.begin(115200); Serial.println("Serial communication started\n\n"); WiFi.begin(WIFI_SSID, WIFI_PASSWORD); //try to connect with wifi Serial.print("Connecting to "); Serial.print(WIFI_SSID); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(500); } Serial.println(); Serial.print("Connected to "); Serial.println(WIFI_SSID); Serial.print("IP Address is : "); Serial.println(WiFi.localIP()); //print local IP address Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH); // connect to firebase delay(1000); } void loop() { // Firebase Error Handling ************************************************ if (Firebase.failed()) { delay(500); Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH); Serial.println(Firebase.error()); Serial.println("Connection to firebase failed. Reconnecting..."); delay(500); } else { Serial.println("Everything is ready!"); delay(300); Serial.println("Everything is ready!"); delay(300); Serial.println("Everything is ready! \n \n \n"); delay(300); Firebase.setInt("/data",val); Serial.println(val); delay(300); Serial.println("uploaded val to firebase \n \n \n"); Firebase.setInt("/test/val3",val3); Serial.println(val3); delay(300); Serial.println("uploaded val3 to firebase \n \n \n"); val++; val3++; } }
#ifndef ULTRASONIC_HPP #define ULTRASONIC_HPP enum e_UltrasonicSensor : uint8_t { FRONT = 0, LEFT = 1, RIGHT = 2, BACK = 3 }; class UltrasonicSensor { public: static UltrasonicSensor& getInstance() { static UltrasonicSensor instance; return instance; } uint16_t getDistance(e_UltrasonicSensor side); private: UltrasonicSensor(); UltrasonicSensor(const UltrasonicSensor &); uint16_t measureSoundSpeed(uint8_t trigger_pin, uint8_t echo_pin); uint16_t d[4][5] = {{0}}; uint16_t sum[4] = {0}; uint16_t id[4] = {0}; uint16_t dist[4] = {0}; }; #endif // ULTRASONIC_HPP
#include<stdio.h> #include<conio.h> #include<graphics.h> #include<dos.h> #include<math.h> void main() { int gd=DETECT,gm; float h,k,a,b,run,x,y,l,z; do { initgraph(&gd,&gm,"C:\\TURBOC3\\BGI"); printf("Enter the center (h,k)\n==> "); scanf("%f%f",&h,&k); printf("Enter the length of major axis and minor axis\n==> "); scanf("%f%f",&a,&b); setcolor(YELLOW); outtextxy(h-130,k+130,"*** POLYNOMIAL METHOD FOR ELLIPSE ***"); x=0; y=b; while(x <= a) { l=(1-((x*x)/(a*a))); if(l < 0) { z=-l; } else { z=l; } y=b*sqrt(z); putpixel(x+h,y+k,2); putpixel(-x+h,y+k,2); putpixel(x+h,-y+k,2); putpixel(-x+h,-y+k,2); delay(50); x=x+1; } setcolor(CYAN); line(h+a,k,h-a,k); line(h,k+b,h,k-b); setcolor(RED); outtextxy(h-3,k-3,"*"); outtextxy(h,k+5,"(h,k)"); getch(); closegraph(); printf("PRESS [1] TO DRAW ANOTHER ELLIPSE OR [0] TO EXIT\n==> "); scanf("%d",&run); }while (run == 1); }