text
string
size
int64
token_count
int64
#include "semantic_version.h" #include <algorithm> #include <cctype> #include <cstdlib> #include <sstream> #include <tuple> #include <vector> using namespace std; //------------------------------------------------------------------------------ // From http://semver.org/ - Version 2.0.0 // Pre-release versions satisfy but have a lower precedence than the associated // normal version. // Build versions satisfy and have a higher precedence than the associated // normal version. // Precedence MUST be calculated by separating the version into major, minor, // patch, pre-release, and build identifiers in that order. Major, minor, and // patch versions are always compared numerically. Pre-release and build version // precedence MUST be determined by comparing each dot separated identifier as // follows: identifiers consisting of only digits are compared numerically and // identifiers with letters or dashes are compared lexically in ASCII sort // order. Numeric identifiers always have lower precedence than non-numeric // identifiers. Example: 1.0.0-alpha < 1.0.0-alpha.1 < 1.0.0-beta.2 < // 1.0.0-beta.11 < 1.0.0-rc.1 < 1.0.0-rc.1+build.1 < 1.0.0 < 1.0.0+0.3.7 < // 1.3.7+build < 1.3.7+build.2.b8f12d7 < 1.3.7+build.11.e0f985a. namespace { void SplitDottedString(const string& s, vector<string>& v) { istringstream ss(s); for (string part; getline(ss, part, '.'); v.push_back(part)); } int CompareIdentifiers(const string& s1, const string& s2) { // We need to split the dotted identifier list into individual identifiers, // and treat purely numeric identifiers as the numbers they represent. vector<string> v1; SplitDottedString(s1, v1); vector<string> v2; SplitDottedString(s2, v2); for (size_t i = 0; ; ++i) { // exhausted both vectors: they must be equal if (i >= v1.size() && i >= v2.size()) { return 0; } // exhausted one vector: it's the smaller one if (i >= v1.size()) { return -1; } if (i >= v2.size()) { return 1; } // is either of v1[i] or v2[i] a number? const string& id1 = v1[i]; bool id1IsNumber = all_of(id1.cbegin(), id1.cend(), [] (char c) { return isdigit(c); }); const string& id2 = v2[i]; bool id2IsNumber = all_of(id2.cbegin(), id2.cend(), [] (char c) { return isdigit(c); }); // if both numbers - compare them as such if (id1IsNumber && id2IsNumber) { long num1 = atol(id1.c_str()); long num2 = atol(id2.c_str()); if (num1 - num2 != 0) { return num1 - num2; } else { continue; } } // if one is a number - that one is lesser if (id1IsNumber) { return -1; } if (id2IsNumber) { return 1; } // neither are numbers: compare them int c = id1.compare(id2); if (c != 0) { return c; } } } bool IdentifierIsValid(const string& i) { vector<string> v; SplitDottedString(i, v); for (const auto& s : v) { // Identifiers must not be empty. if (s.empty()) { return false; } // Identifiers must contain only alphanumerics and '-'. if (any_of(s.cbegin(), s.cend(), [] (char c) { return !isalnum(c) && c != '-' && c != '.'; })) { return false; } // Numeric identifiers must not contain leading zeroes. bool numeric = all_of(s.cbegin(), s.cend(), [] (char c) { return isdigit(c); }); if (numeric && s[0] == '0') { return false; } } return true; } } namespace semver { inline namespace v2 { //------------------------------------------------------------------------------ Version::Version( unsigned int major, unsigned int minor, unsigned int patch, const std::string& prerelease, const std::string& build) : m_majorVersion(major) , m_minorVersion(minor) , m_patchVersion(patch) , m_prereleaseVersion(prerelease) , m_buildVersion(build) { } Version::Version(const string& s) { // major.minor.patch-release+build istringstream ss(s); string part; if (!getline(ss, part, '.')) return; m_majorVersion = static_cast<unsigned int>(strtoul(part.c_str(), 0, 0)); if (!getline(ss, part, '.')) return; m_minorVersion = static_cast<unsigned int>(strtoul(part.c_str(), 0, 0)); if (!getline(ss, part)) return; m_patchVersion = static_cast<unsigned int>(strtoul(part.c_str(), 0, 0)); const size_t preLoc = part.find_first_of("-"); const size_t buildLoc = part.find_first_of("+"); if (preLoc != string::npos) { const size_t length = (buildLoc != string::npos ) ? (buildLoc -1) - preLoc : string::npos; m_prereleaseVersion = part.substr(preLoc+1, length); } if (buildLoc != string::npos) { m_buildVersion = part.substr(buildLoc + 1, string::npos); } } //------------------------------------------------------------------------------ bool Version::IsWellFormed() const { return IdentifierIsValid(m_prereleaseVersion) && IdentifierIsValid(m_buildVersion); } //------------------------------------------------------------------------------ // When incrementing versions, all lower version parts are reset. Version Version::NextMajorVersion() const { return Version(m_majorVersion + 1, 0, 0); } Version Version::NextMinorVersion() const { return Version(m_majorVersion, m_minorVersion + 1, 0); } Version Version::NextPatchVersion() const { return Version(m_majorVersion, m_minorVersion, m_patchVersion + 1); } //------------------------------------------------------------------------------ bool Version::Satisfies(const Version& other) const { return tie(m_majorVersion, m_minorVersion, m_patchVersion) >= tie(other.m_majorVersion, other.m_minorVersion, other.m_patchVersion); } //------------------------------------------------------------------------------ bool operator==(const Version& a, const Version& b) { return tie(a.m_majorVersion, a.m_minorVersion, a.m_patchVersion, a.m_prereleaseVersion) == tie(b.m_majorVersion, b.m_minorVersion, b.m_patchVersion, b.m_prereleaseVersion); } //------------------------------------------------------------------------------ bool operator<(const Version& a, const Version& b) { const auto ta = tie(a.m_majorVersion, a.m_minorVersion, a.m_patchVersion); const auto tb = tie(b.m_majorVersion, b.m_minorVersion, b.m_patchVersion); if (ta < tb) return true; if (ta > tb) return false; // pre-release version < normal version if (!a.m_prereleaseVersion.empty() && b.m_prereleaseVersion.empty()) { return true; } if (a.m_prereleaseVersion.empty() && !b.m_prereleaseVersion.empty()) { return false; } return CompareIdentifiers(a.m_prereleaseVersion, b.m_prereleaseVersion) < 0; } //------------------------------------------------------------------------------ bool Version::Equals(const Version& other) const { return tie(m_majorVersion, m_minorVersion, m_patchVersion, m_prereleaseVersion, m_buildVersion) == tie(other.m_majorVersion, other.m_minorVersion, other.m_patchVersion, other.m_prereleaseVersion, other.m_buildVersion); } //------------------------------------------------------------------------------ ostream& operator<<(ostream& s, const Version& v) { s << v.m_majorVersion << '.' << v.m_minorVersion << '.' << v.m_patchVersion; if (!v.m_prereleaseVersion.empty()) { s << '-' << v.m_prereleaseVersion; } if (!v.m_buildVersion.empty()) { s << '+' << v.m_buildVersion; } return s; } } }
7,800
2,567
#include "utils.h" void setBit(uint8_t* data, uint8_t bit, bool flag) { if (flag) { *data = *data | (1 << bit); } else { *data = *data & ~(1 << bit); } } Dimension createDimension(unit w, unit h) { return {w, h}; } Vec2D createVec2D(unit x, unit y) { return {x, y}; } sunit getVecX(Vec2D* vec) { return (sunit) vec->x; } sunit getVecY(Vec2D* vec) { return (sunit) vec->y; } unit abs(sunit x) { if (x & (1 << 7) != 0) { x = ~x; x + 1; } return x; }
524
233
/* ----------------------------------------------------------------------------- * This file is a part of the NVCM project: https://github.com/nvitya/nvcm * Copyright (c) 2018 Viktor Nagy, nvitya * * This software is provided 'as-is', without any express or implied warranty. * In no event will the authors be held liable for any damages arising from * the use of this software. Permission is granted to anyone to use this * software for any purpose, including commercial applications, and to alter * it and redistribute it freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software in * a product, an acknowledgment in the product documentation would be * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. * --------------------------------------------------------------------------- */ /* * file: spiflash.cpp * brief: SPI Flash Memory Implementation * version: 1.00 * date: 2018-02-10 * authors: nvitya */ #include "spiflash.h" bool TSpiFlash::InitInherited() { if (!pin_cs.Assigned()) { return false; } if (!txdma.initialized || !rxdma.initialized) { return false; } spi.DmaAssign(true, &txdma); spi.DmaAssign(false, &rxdma); return true; } bool TSpiFlash::ReadIdCode() { txbuf[0] = 0x9F; txbuf[1] = 0x00; txbuf[2] = 0x00; txbuf[3] = 0x00; rxbuf[0] = 0; rxbuf[1] = 0; rxbuf[2] = 0; rxbuf[3] = 0; //rxbuf[0] = 0x55; rxbuf[1] = 0x56; rxbuf[2] = 0x57; rxbuf[3] = 0x58; ExecCmd(4); unsigned * up = (unsigned *)&(rxbuf[0]); idcode = (*up >> 8); if ((idcode == 0) || (idcode == 0x00FFFFFF)) { // SPI communication error return false; } return true; } void TSpiFlash::StartCmd(unsigned acmdlen) { pin_cs.Set1(); curcmdlen = acmdlen; txfer.srcaddr = &txbuf[0]; txfer.bytewidth = 1; txfer.count = curcmdlen; txfer.flags = 0; rxfer.dstaddr = &rxbuf[0]; rxfer.bytewidth = 1; rxfer.flags = 0; rxfer.count = txfer.count; pin_cs.Set0(); // activate CS spi.DmaStartRecv(&rxfer); spi.DmaStartSend(&txfer); } void TSpiFlash::ExecCmd(unsigned acmdlen) { StartCmd(acmdlen); while (!spi.DmaRecvCompleted()) { // wait } pin_cs.Set1(); } void TSpiFlash::Run() { if (0 == state) { // idle return; } if (SERIALFLASH_STATE_READMEM == state) // read memory { switch (phase) { case 0: // start remaining = datalen; txbuf[0] = 0x03; // read command txbuf[1] = ((address >> 16) & 0xFF); txbuf[2] = ((address >> 8) & 0xFF); txbuf[3] = ((address >> 0) & 0xFF); StartCmd(4); // activates the CS too phase = 1; break; case 1: // wait for address phase completition if (spi.DmaRecvCompleted()) { phase = 2; Run(); // phase jump return; } break; case 2: // start read next data chunk if (remaining == 0) { // finished. phase = 10; Run(); // phase jump return; } // start data phase chunksize = maxchunksize; if (chunksize > remaining) chunksize = remaining; txbuf[0] = 0; txfer.srcaddr = &txbuf[0]; txfer.bytewidth = 1; txfer.count = chunksize; txfer.flags = DMATR_NO_ADDR_INC; // sending the same zero character rxfer.dstaddr = dataptr; rxfer.bytewidth = 1; rxfer.flags = 0; rxfer.count = chunksize; spi.DmaStartRecv(&rxfer); spi.DmaStartSend(&txfer); phase = 3; break; case 3: // wait for completion if (spi.DmaRecvCompleted()) { // read next chunk dataptr += chunksize; remaining -= chunksize; phase = 2; Run(); // phase jump return; } // TODO: timeout handling break; case 10: // finished pin_cs.Set1(); completed = true; state = 0; // go to idle break; } } else if (SERIALFLASH_STATE_WRITEMEM == state) // write memory { switch (phase) { case 0: // initialization remaining = datalen; ++phase; break; // write next chunk case 1: // set write enable if (remaining == 0) { // finished. phase = 20; Run(); // phase jump return; } // set write enable txbuf[0] = 0x06; StartCmd(1); // activates the CS too ++phase; break; case 2: // wait for command phase completition if (spi.DmaRecvCompleted()) { pin_cs.Set1(); // pull back the CS ++phase; Run(); // phase jump return; } break; case 3: // write data txbuf[0] = 0x02; // page program command txbuf[1] = ((address >> 16) & 0xFF); txbuf[2] = ((address >> 8) & 0xFF); txbuf[3] = ((address >> 0) & 0xFF); StartCmd(4); // activates the CS too ++phase; break; case 4: // wait for command phase completition if (spi.DmaRecvCompleted()) { ++phase; Run(); // phase jump return; } break; case 5: // data phase chunksize = 256 - (address & 0xFF); // page size if (chunksize > remaining) chunksize = remaining; txfer.srcaddr = dataptr; txfer.bytewidth = 1; txfer.count = chunksize; txfer.flags = 0; rxfer.dstaddr = &rxbuf[0]; rxfer.bytewidth = 1; rxfer.flags = DMATR_NO_ADDR_INC; // ignore the received data rxfer.count = chunksize; spi.DmaStartRecv(&rxfer); spi.DmaStartSend(&txfer); ++phase; break; case 6: // wait for completion if (spi.DmaRecvCompleted()) { pin_cs.Set1(); // pull back the CS ++phase; Run(); return; } // TODO: timeout handling break; case 7: // read status register, repeat until BUSY flag is set StartReadStatus(); ++phase; break; case 8: if (spi.DmaRecvCompleted()) { pin_cs.Set1(); // pull back the CS // check the result if (rxbuf[1] & 1) // busy { // repeat status register read phase = 7; Run(); return; } // Write finished. address += chunksize; dataptr += chunksize; remaining -= chunksize; phase = 1; Run(); // phase jump return; } // TODO: timeout break; case 20: // finished completed = true; state = 0; // go to idle break; } } else if (SERIALFLASH_STATE_ERASE == state) // erase memory { switch (phase) { case 0: // initialization // correct start address if necessary if (address & erasemask) { // correct the length too datalen += (address & erasemask); address &= ~erasemask; } // round up to 4k the data length datalen = ((datalen + erasemask) & ~erasemask); remaining = datalen; ++phase; break; // erase next sector case 1: // set write enable if (remaining == 0) { // finished. phase = 20; Run(); // phase jump return; } // set write enable txbuf[0] = 0x06; StartCmd(1); // activates the CS too ++phase; break; case 2: // wait for command phase completition if (spi.DmaRecvCompleted()) { pin_cs.Set1(); // pull back the CS ++phase; Run(); // phase jump return; } break; case 3: // erase sector / block if (has4kerase && ((address & 0xFFFF) || (datalen < 0x10000))) { // 4k sector erase chunksize = 0x01000; txbuf[0] = 0x20; } else { // 64k block erase chunksize = 0x10000; txbuf[0] = 0xD8; } txbuf[1] = ((address >> 16) & 0xFF); txbuf[2] = ((address >> 8) & 0xFF); txbuf[3] = ((address >> 0) & 0xFF); StartCmd(4); // activates the CS too ++phase; break; case 4: // wait for command phase completition if (spi.DmaRecvCompleted()) { phase = 7; Run(); // phase jump return; } break; case 7: // read status register, repeat until BUSY flag is set StartReadStatus(); ++phase; break; case 8: if (spi.DmaRecvCompleted()) { pin_cs.Set1(); // pull back the CS // check the result if (rxbuf[1] & 1) // busy { // repeat status register read phase = 7; Run(); return; } // Write finished. address += chunksize; remaining -= chunksize; phase = 1; Run(); // phase jump return; } // TODO: timeout break; case 20: // finished completed = true; state = 0; // go to idle break; } } else if (SERIALFLASH_STATE_ERASEALL == state) // erase all / chip { switch (phase) { case 0: // initialization ++phase; break; case 1: // set write enable // set write enable txbuf[0] = 0x06; StartCmd(1); // activates the CS too ++phase; break; case 2: // wait for command phase completition if (spi.DmaRecvCompleted()) { pin_cs.Set1(); // pull back the CS ++phase; Run(); // phase jump return; } break; case 3: // issue bulk erase txbuf[0] = 0xC7; StartCmd(1); // activates the CS too ++phase; break; case 4: // wait for command phase completition if (spi.DmaRecvCompleted()) { phase = 7; Run(); // phase jump return; } break; case 7: // read status register, repeat until BUSY flag is set StartReadStatus(); ++phase; break; case 8: if (spi.DmaRecvCompleted()) { pin_cs.Set1(); // pull back the CS // check the result if (rxbuf[1] & 1) // busy { // repeat status register read phase = 7; Run(); return; } // finished. phase = 20; Run(); // phase jump return; } // TODO: timeout break; case 20: // finished completed = true; state = 0; // go to idle break; } } } bool TSpiFlash::StartReadStatus() { txbuf[0] = 0x05; txbuf[1] = 0x00; rxbuf[1] = 0x7F; StartCmd(2); return true; } void TSpiFlash::ResetChip() { txbuf[0] = 0x66; ExecCmd(1); txbuf[0] = 0x99; ExecCmd(1); }
10,090
4,796
#include "ipconnstats.h" #include "IPUtility.h" // // JSON formatted output strings // ostream& operator<<(ostream &out, const IPConnStatsKey &key) { string src = IPUtility::int_to_ip_str(key.isIpv6, &key.ipSrc[0]); string dst = IPUtility::int_to_ip_str(key.isIpv6, &key.ipDst[0]); out << "\"src_ip\" : \""<< src <<"\", "; out << "\"dst_ip\" : \""<< dst <<"\""; return out; } ostream& operator<<(ostream &out, const IPConnStatsData &data) { out << "\"src_bytes\" : " << data.src_bytes << ", "; out << "\"dst_bytes\" : " << data.dst_bytes << ", "; out << "\"src_frames\" : " << data.src_frames << ", "; out << "\"dst_frames\" : " << data.dst_frames << ", "; if(data.src_frames == 0) { out << "\"src_min_len\" : 0, "; out << "\"src_max_len\" : 0, "; } else { out << "\"src_min_len\" : " << data.src_min_len << ", "; out << "\"src_max_len\" : " << data.src_max_len << ", "; } if(data.dst_frames == 0) { out << "\"dst_min_len\" : 0, "; out << "\"dst_max_len\" : 0, "; } else { out << "\"dst_min_len\" : " << data.dst_min_len << ", "; out << "\"dst_max_len\" : " << data.dst_max_len << ", "; } out << "\"start_time\" : " << data.start_time << ", "; const int num_bins = 10; out << "\"src_bins\" : [ "; for(int i=0; i<num_bins; ++i) { out << data.src_bins[i]; if(i+1<num_bins) out << ", "; } out << "], "; out << "\"dst_bins\" : [ "; for(int i=0; i<num_bins; ++i) { out << data.dst_bins[i]; if(i+1<num_bins) out << ", "; } out << "] "; return out; }
1,781
742
#pragma once namespace lib { void hello(); }
48
17
/********************************************************************** * $Id: SweepLineSegment.cpp 1820 2006-09-06 16:54:23Z mloskot $ * * GEOS - Geometry Engine Open Source * http://geos.refractions.net * * Copyright (C) 2001-2002 Vivid Solutions Inc. * Copyright (C) 2005 Refractions Research Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * **********************************************************************/ #include <geos/geomgraph/index/SweepLineSegment.h> #include <geos/geomgraph/index/SegmentIntersector.h> #include <geos/geom/CoordinateSequence.h> #include <geos/geom/Coordinate.h> #include <geos/geomgraph/Edge.h> using namespace geos::geom; namespace geos { namespace geomgraph { // geos.geomgraph namespace index { // geos.geomgraph.index SweepLineSegment::SweepLineSegment(Edge *newEdge, int newPtIndex): edge(newEdge), pts(newEdge->getCoordinates()), ptIndex(newPtIndex) { //pts=newEdge->getCoordinates(); //edge=newEdge; //ptIndex=newPtIndex; } SweepLineSegment::~SweepLineSegment() { } double SweepLineSegment::getMinX() { double x1=pts->getAt(ptIndex).x; double x2=pts->getAt(ptIndex+1).x; return x1<x2?x1:x2; } double SweepLineSegment::getMaxX() { double x1=pts->getAt(ptIndex).x; double x2=pts->getAt(ptIndex+1).x; return x1>x2?x1:x2; } void SweepLineSegment::computeIntersections(SweepLineSegment *ss, SegmentIntersector *si) { si->addIntersections(edge, ptIndex, ss->edge, ss->ptIndex); } } // namespace geos.geomgraph.index } // namespace geos.geomgraph } // namespace geos /********************************************************************** * $Log$ * Revision 1.6 2006/03/15 17:16:31 strk * streamlined headers inclusion * * Revision 1.5 2006/03/09 16:46:47 strk * geos::geom namespace definition, first pass at headers split * * Revision 1.4 2006/02/19 19:46:49 strk * Packages <-> namespaces mapping for most GEOS internal code (uncomplete, but working). Dir-level libs for index/ subdirs. * * Revision 1.3 2005/11/15 10:04:37 strk * * Reduced heap allocations (vectors, mostly). * Enforced const-correctness, changed some interfaces * to use references rather then pointers when appropriate. * * Revision 1.2 2004/07/02 13:28:27 strk * Fixed all #include lines to reflect headers layout change. * Added client application build tips in README. * * Revision 1.1 2004/04/14 06:04:26 ybychkov * "geomgraph/index" committ problem fixed. * * Revision 1.10 2004/03/19 09:49:29 ybychkov * "geomgraph" and "geomgraph/indexl" upgraded to JTS 1.4 * * Revision 1.9 2003/11/07 01:23:42 pramsey * Add standard CVS headers licence notices and copyrights to all cpp and h * files. * * Revision 1.8 2003/10/15 15:30:32 strk * Declared a SweepLineEventOBJ from which MonotoneChain and * SweepLineSegment derive to abstract SweepLineEvent object * previously done on void * pointers. * No more compiler warnings... * **********************************************************************/
3,179
1,222
struct Audio { void coprocessor_enable(bool state); void coprocessor_frequency(double frequency); void sample(int16 lsample, int16 rsample); void coprocessor_sample(int16 lsample, int16 rsample); void init(); private: nall::DSP dspaudio; bool coprocessor; enum : unsigned { buffer_size = 256, buffer_mask = buffer_size - 1 }; uint32 dsp_buffer[buffer_size], cop_buffer[buffer_size]; unsigned dsp_rdoffset, cop_rdoffset; unsigned dsp_wroffset, cop_wroffset; unsigned dsp_length, cop_length; void flush(); }; extern Audio audio;
556
210
#include "storm/modelchecker/prctl/helper/BaierUpperRewardBoundsComputer.h" #include "storm/adapters/RationalNumberAdapter.h" #include "storm/storage/SparseMatrix.h" #include "storm/storage/BitVector.h" #include "storm/storage/StronglyConnectedComponentDecomposition.h" #include "storm/utility/macros.h" namespace storm { namespace modelchecker { namespace helper { template<typename ValueType> BaierUpperRewardBoundsComputer<ValueType>::BaierUpperRewardBoundsComputer(storm::storage::SparseMatrix<ValueType> const& transitionMatrix, std::vector<ValueType> const& rewards, std::vector<ValueType> const& oneStepTargetProbabilities) : _transitionMatrix(transitionMatrix), _rewards(rewards), _oneStepTargetProbabilities(oneStepTargetProbabilities) { // Intentionally left empty. } template<typename ValueType> std::vector<ValueType> BaierUpperRewardBoundsComputer<ValueType>::computeUpperBoundOnExpectedVisitingTimes(storm::storage::SparseMatrix<ValueType> const& transitionMatrix, std::vector<ValueType> const& oneStepTargetProbabilities) { std::vector<uint64_t> stateToScc(transitionMatrix.getRowGroupCount()); { // Start with an SCC decomposition of the system. storm::storage::StronglyConnectedComponentDecomposition<ValueType> sccDecomposition(transitionMatrix); uint64_t sccIndex = 0; for (auto const& block : sccDecomposition) { for (auto const& state : block) { stateToScc[state] = sccIndex; } ++sccIndex; } } // The states that we still need to assign a value. storm::storage::BitVector remainingStates(transitionMatrix.getRowGroupCount(), true); // A choice is valid iff it goes to non-remaining states with non-zero probability. storm::storage::BitVector validChoices(transitionMatrix.getRowCount()); // Initially, mark all choices as valid that have non-zero probability to go to the target states directly. uint64_t index = 0; for (auto const& e : oneStepTargetProbabilities) { if (!storm::utility::isZero(e)) { validChoices.set(index); } ++index; } // Vector that holds the result. std::vector<ValueType> result(transitionMatrix.getRowGroupCount()); // Process all states as long as there are remaining ones. std::vector<uint64_t> newStates; while (!remainingStates.empty()) { for (auto state : remainingStates) { bool allChoicesValid = true; for (auto row = transitionMatrix.getRowGroupIndices()[state], endRow = transitionMatrix.getRowGroupIndices()[state + 1]; row < endRow; ++row) { if (validChoices.get(row)) { continue; } bool choiceValid = false; for (auto const& entry : transitionMatrix.getRow(row)) { if (storm::utility::isZero(entry.getValue())) { continue; } if (!remainingStates.get(entry.getColumn())) { choiceValid = true; break; } } if (choiceValid) { validChoices.set(row); } else { allChoicesValid = false; } } if (allChoicesValid) { newStates.push_back(state); } } // Compute d_t over the newly found states. for (auto state : newStates) { result[state] = storm::utility::one<ValueType>(); for (auto row = transitionMatrix.getRowGroupIndices()[state], endRow = transitionMatrix.getRowGroupIndices()[state + 1]; row < endRow; ++row) { ValueType rowValue = oneStepTargetProbabilities[row]; for (auto const& entry : transitionMatrix.getRow(row)) { if (!remainingStates.get(entry.getColumn())) { rowValue += entry.getValue() * (stateToScc[state] == stateToScc[entry.getColumn()] ? result[entry.getColumn()] : storm::utility::one<ValueType>()); } } STORM_LOG_ASSERT(rowValue > storm::utility::zero<ValueType>(), "Expected entry with value greater 0."); result[state] = std::min(result[state], rowValue); } } remainingStates.set(newStates.begin(), newStates.end(), false); newStates.clear(); } // Transform the d_t to an upper bound for zeta(t) for (auto& r : result) { r = storm::utility::one<ValueType>() / r; } return result; } template<typename ValueType> ValueType BaierUpperRewardBoundsComputer<ValueType>::computeUpperBound() { STORM_LOG_TRACE("Computing upper reward bounds using variant-2 of Baier et al."); std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now(); auto expVisits = computeUpperBoundOnExpectedVisitingTimes(_transitionMatrix, _oneStepTargetProbabilities); ValueType upperBound = storm::utility::zero<ValueType>(); for (uint64_t state = 0; state < expVisits.size(); ++state) { ValueType maxReward = storm::utility::zero<ValueType>(); for (auto row = _transitionMatrix.getRowGroupIndices()[state], endRow = _transitionMatrix.getRowGroupIndices()[state + 1]; row < endRow; ++row) { maxReward = std::max(maxReward, _rewards[row]); } upperBound += expVisits[state] * maxReward; } STORM_LOG_TRACE("Baier algorithm for reward bound computation (variant 2) computed bound " << upperBound << "."); std::chrono::high_resolution_clock::time_point end = std::chrono::high_resolution_clock::now(); STORM_LOG_TRACE("Computed upper bounds on rewards in " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms."); return upperBound; } template class BaierUpperRewardBoundsComputer<double>; #ifdef STORM_HAVE_CARL template class BaierUpperRewardBoundsComputer<storm::RationalNumber>; #endif } } }
7,706
1,860
#include <iostream> #include "stack.h" #define INCREASE_SWITCH 'z' #define DECREASE_SWITCH 'o' #define PUSH_CARS 'w' #define POP_CARS 'j' #define RAIL_SWITCH_SIZE 10 using namespace std; int main() { char command; int temp, numberOFTracks, numberofCars, commandArg, numberOfCommands, currentTrack = 0; Stack railSwitch(RAIL_SWITCH_SIZE); Stack** tracks; cin >> numberOFTracks; tracks = new Stack*[numberOFTracks]; for (int i = 0; i < numberOFTracks; i++) { cin >> numberofCars; tracks[i] = new Stack(512 + numberofCars); for (int q = 0; q < numberofCars; q++) { cin >> temp; tracks[i]->pushToPosition(temp, numberofCars - q -1); } } currentTrack = 0; cin >> numberOfCommands; for (int i = 0; i < numberOfCommands; i++) { cin >> command; cin >> commandArg; switch (command) { case INCREASE_SWITCH: currentTrack += commandArg % numberOFTracks; if (currentTrack >= numberOFTracks) currentTrack -= numberOFTracks; break; case DECREASE_SWITCH: currentTrack -= commandArg % numberOFTracks; if (currentTrack < 0) currentTrack += numberOFTracks; break; case POP_CARS: for (int q = 0; q < commandArg; q++) { if (!railSwitch.isEmpty() && !(tracks[currentTrack]->isFull())) tracks[currentTrack]->push(railSwitch.pop()); } break; case PUSH_CARS: for (int q = 0; q < commandArg; q++) { if (!railSwitch.isFull() && !(tracks[currentTrack]->isEmpty())) railSwitch.push(tracks[currentTrack]->pop()); } break; default: break; } } cout << railSwitch.getSize(); while(!railSwitch.isEmpty()) cout << " " << railSwitch.pop(); cout << endl; for (int i = 0; i < numberOFTracks; i++) { cout << tracks[currentTrack]->getSize(); while(!(tracks[currentTrack]->isEmpty())) cout << " " << tracks[currentTrack]->pop(); cout << endl; currentTrack++; if (currentTrack >= numberOFTracks) currentTrack = 0; } for(int i = 0; i < numberOFTracks; i++) delete tracks[i]; delete[] tracks; return 0; }
2,044
886
/* * ===================================================================================== * * Filename: * * Description: * * Version: 1.0 * Created: Thanks to github you know it * Revision: none * Compiler: g++ * * Author: Mahmut Erdem ÖZGEN m.erdemozgen@gmail.com * * * ===================================================================================== */ #include <iostream> #include <random> #include <vector> std::random_device rd; std::mt19937 gen(rd()); int getRandomNumber(const int&, const int&); int main(int argc, const char *argv[]) { // offsets v set 1 v v set 2 v v set 3 v std::vector<int> set {2, 4, 6, 8, 10, 2, 5, 7, 9, 11, 6, 10, 14, 18, 22}; std::cout << "Random number from each of the following sets: " << std::endl; std::cout << "\n2 4 6 8 10: " << set[getRandomNumber(0, 4)]; std::cout << "\n2 5 7 9 11: " << set[getRandomNumber(5, 9)]; std::cout << "\n6 10 14 18 22: " << set[getRandomNumber(10, set.size() - 1)] << std::endl; return 0; } /** * Creates a random distribution and returns a value in the range min max. * @param int * @param int * @return int */ int getRandomNumber(const int& min, const int& max) { return std::uniform_int_distribution<int>{min, max}(gen); } // end method getRandomNumber
1,378
495
#include "CloudLoadAllResponse.h" FCloudLoadAllResponse::FCloudLoadAllResponse() { }
87
30
/* # # ---------------------------------------------------------------------------- # # Copyright 2019 IBM Corporation # # 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 "buffer.h" #include "support/check.h" #include "support/safeformat.h" #include <fcntl.h> #include <linux/limits.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <sys/syscall.h> using namespace chopstix; #define PERM_664 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH TraceBuffer::~TraceBuffer() { if (pos_ > 0) write_back(); if (fd_ != -1) { syscall(SYS_close, fd_); fd_ = -1; } } void TraceBuffer::setup(const char *trace_root) { char fpath[PATH_MAX]; sfmt::format(fpath, sizeof(fpath), "%s/trace.bin", trace_root); fd_ = syscall(SYS_openat, AT_FDCWD, fpath, O_WRONLY | O_CREAT | O_TRUNC, PERM_664); check(fd_ != -1, "Unable to open 'trace.bin'"); } void TraceBuffer::start_trace(int trace_id, bool isNewInvocation) { if(isNewInvocation) write(-3); write(-1); } void TraceBuffer::stop_trace(int trace_id) { write(-2); } void TraceBuffer::save_page(long page_addr) { write(page_addr); } void TraceBuffer::write_back() { syscall(SYS_write, fd_, buf_, pos_ * sizeof(long)); pos_ = 0; } void TraceBuffer::write(long dat) { if (pos_ == buf_size) write_back(); buf_[pos_++] = dat; }
1,936
692
/* Copyright (c) 2017-2021, Battelle Memorial Institute; Lawrence Livermore National Security, LLC; Alliance for Sustainable Energy, LLC. See the top-level NOTICE for additional details. All rights reserved. SPDX-License-Identifier: BSD-3-Clause */ #pragma once #include "SmallBuffer.hpp" #include "helics/helics-config.h" #include "helicsTime.hpp" #include <memory> #include <string> #include <utility> #include <vector> /** @file @details defining data used for storing the data for values and for messages */ /** \namespace helics @details the core namespace for the helics C++ library all user functions are found in this namespace along with many other functions in the Core API */ namespace helics { /** class containing a message structure*/ class Message { public: Time time = timeZero; //!< the event time the message is sent std::uint16_t flags{0}; //!< message flags std::uint16_t messageValidation{0U}; //!< extra field for user object usage, not used by HELICS std::int32_t messageID{0}; //!< the messageID for a message SmallBuffer data; //!< the data packet for the message std::string dest; //!< the destination of the message std::string source; //!< the most recent source of the message std::string original_source; //!< the original source of the message std::string original_dest; //!< the original destination of a message std::int32_t counter{0}; //!< indexing counter not used directly by helics void* backReference{nullptr}; //!< back referencing pointer not used by helics /** default constructor*/ Message() = default; /** swap operation for the Message*/ void swap(Message& m2) noexcept { std::swap(time, m2.time); std::swap(flags, m2.flags); std::swap(messageID, m2.messageID); original_source.swap(m2.original_source); source.swap(m2.source); dest.swap(m2.dest); data.swap(m2.data); original_dest.swap(m2.original_dest); } /** check if the Message contains an actual Message @return false if there is no Message data*/ bool isValid() const noexcept { return (!data.empty()) ? true : ((!source.empty()) ? true : (!dest.empty())); } /** get the payload as a string*/ std::string_view to_string() const { return data.to_string(); } /** clear all data from the message*/ void clear() { time = timeZero; flags = 0; messageID = 0; data.resize(0); dest.clear(); source.clear(); original_source.clear(); original_dest.clear(); counter = 0; } }; /** * FilterOperator abstract class @details FilterOperators will transform a message in some way in a direct fashion * */ class FilterOperator { public: /** default constructor*/ FilterOperator() = default; /**virtual destructor*/ virtual ~FilterOperator() = default; /** filter the message either modify the message or generate a new one*/ virtual std::unique_ptr<Message> process(std::unique_ptr<Message> message) = 0; /** filter the message either modify the message or generate a new one*/ virtual std::vector<std::unique_ptr<Message>> processVector(std::unique_ptr<Message> message) { std::vector<std::unique_ptr<Message>> ret; auto res = process(std::move(message)); if (res) { ret.push_back(std::move(res)); } return ret; } /** make the operator work like one @details calls the process function*/ std::unique_ptr<Message> operator()(std::unique_ptr<Message> message) { return process(std::move(message)); } /** indicator if the filter Operator has the capability of generating completely new messages or * redirecting messages*/ virtual bool isMessageGenerating() const { return false; } }; /** special filter operator defining no operation the original message is simply returned */ class NullFilterOperator final: public FilterOperator { public: /**default constructor*/ NullFilterOperator() = default; virtual std::unique_ptr<Message> process(std::unique_ptr<Message> message) override { return message; } }; /** helper template to check whether an index is actually valid for a particular vector @tparam SizedDataType a vector like data type that must have a size function @param testSize an index to test @param vec a reference to a vector like object that has a size method @return true if it is a valid index false otherwise*/ template<class sizeType, class SizedDataType> inline bool isValidIndex(sizeType testSize, const SizedDataType& vec) { return ((testSize >= sizeType(0)) && (testSize < static_cast<sizeType>(vec.size()))); } } // namespace helics
4,794
1,346
/** * @file ParamTable.cc * @Author Miikka Silfverberg * @brief Parameter table for structured and unstructured parameters. Used * by both Tagger and LemmaExtractor. */ /////////////////////////////////////////////////////////////////////////////// // // // (C) Copyright 2014, University of Helsinki // // 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 "ParamTable.hh" #ifndef TEST_ParamTable_cc #include "Word.hh" #include <cassert> ParamTable::ParamTable(void): label_extractor(0), trained(0), update_threshold(0), avg_mass_threshold(0), filter_type(NO_FILTER) {} ParamTable::~ParamTable(void) {} ParamTable &ParamTable::operator=(const ParamTable &another) { if (this == &another) { return *this; } update_count_map = another.update_count_map; trained = another.trained; feature_template_map = another.feature_template_map; unstruct_param_table = another.unstruct_param_table; struct_param_table = another.struct_param_table; update_threshold = another.update_threshold; avg_mass_threshold = another.avg_mass_threshold; filter_type = another.filter_type; train_iters = another.train_iters; update_count_map = another.update_count_map; return *this; } void ParamTable::set_trained(void) { trained = 1; } void ParamTable::set_param_filter(const TaggerOptions &options) { if (options.filter_type == UPDATE_COUNT) { update_threshold = options.param_threshold; filter_type = UPDATE_COUNT; } else if (options.filter_type == AVG_VALUE) { avg_mass_threshold = options.param_threshold; filter_type = AVG_VALUE; } } unsigned int ParamTable::get_feat_template (const std::string &feat_template_string) { if (feature_template_map.find(feat_template_string) == feature_template_map.end()) { feature_template_map[feat_template_string] = feature_template_map.size(); } return feature_template_map[feat_template_string]; } FeatureTemplateVector ParamTable::get_feat_templates (StringVector &feat_template_strings) { FeatureTemplateVector feat_templates; for (unsigned int i = 0; i < feat_template_strings.size(); ++i) { if (trained and feature_template_map.count(feat_template_strings[i]) == 0) { continue; } feat_templates.push_back(get_feat_template(feat_template_strings[i])); } return feat_templates; } void ParamTable::p(void) const { std::cerr << update_count_map.size() << std::endl; } long ParamTable::get_unstruct_param_id(unsigned int feature_template, unsigned int label) const { return (MAX_LABEL + 1) * feature_template + label; } void ParamTable::set_label_extractor(const LabelExtractor &le) { this->label_extractor = &le; } void ParamTable::set_train_iters(int iters) { train_iters = iters; } long ParamTable::get_struct_param_id(unsigned int label) const { return (MAX_LABEL + 1) * (MAX_LABEL + 1) * (MAX_LABEL + 1) + (MAX_LABEL + 1) * (MAX_LABEL + 1) + label; } long ParamTable::get_struct_param_id(unsigned int plabel, unsigned int label) const { return (MAX_LABEL + 1) * (MAX_LABEL + 1) * (MAX_LABEL + 1) + plabel * (MAX_LABEL + 1) + label; } long ParamTable::get_struct_param_id(unsigned int pplabel, unsigned int plabel, unsigned int label) const { return pplabel * (MAX_LABEL + 1) * (MAX_LABEL + 1) + plabel * (MAX_LABEL + 1) + label; } std::string ParamTable::get_unstruct_feat_repr(long feat_id, const InvFeatureTemplateMap &m) const { long label = feat_id % (MAX_LABEL + 1); long feat_template = (feat_id - label) / (MAX_LABEL + 1); std::string label_string = label_extractor->get_label_string(label); std::string feat_template_string = m[feat_template]; return feat_template_string + " " + label_string; } std::string ParamTable::get_struct_feat_repr(long feat_id) const { if (feat_id >= (MAX_LABEL + 1) * (MAX_LABEL + 1) * (MAX_LABEL + 1) + (MAX_LABEL + 1) * (MAX_LABEL + 1)) { feat_id -= (MAX_LABEL + 1) * (MAX_LABEL + 1) * (MAX_LABEL + 1) + (MAX_LABEL + 1) * (MAX_LABEL + 1); return label_extractor->get_label_string(feat_id); } else if (feat_id >= (MAX_LABEL + 1) * (MAX_LABEL + 1) * (MAX_LABEL + 1)) { feat_id -= (MAX_LABEL + 1) * (MAX_LABEL + 1) * (MAX_LABEL + 1); long label1 = feat_id % (MAX_LABEL + 1); feat_id -= label1; long label2 = feat_id / (MAX_LABEL + 1); return label_extractor->get_label_string(label2) + " " + label_extractor->get_label_string(label1); } else { long label1 = feat_id % (MAX_LABEL + 1); feat_id -= label1; feat_id /= (MAX_LABEL + 1); long label2 = feat_id % (MAX_LABEL + 1); feat_id -= label2; long label3 = feat_id / (MAX_LABEL + 1); return label_extractor->get_label_string(label3) + " " + label_extractor->get_label_string(label2) + " " + label_extractor->get_label_string(label1); } } void ParamTable::set_update_counts(const ParamTable &another) { update_count_map = another.update_count_map; } float ParamTable::get_filtered_param(long param_id, float param) const { if (trained or filter_type != UPDATE_COUNT) { return param; } if (update_count_map.count(param_id) == 0) { assert(param == 0); return 0; } if (update_count_map.find(param_id)->second < update_threshold) { return 0; } return param; } float ParamTable::get_unstruct(unsigned int feature_template, unsigned int label) const { long id = get_unstruct_param_id(feature_template, label); ParamMap::const_iterator it = unstruct_param_table.find(id); if (it == unstruct_param_table.end()) { return 0; } return get_filtered_param(id, it->second); } float ParamTable::get_struct1(unsigned int label, Degree sublabel_order) const { long id = get_struct_param_id(label); ParamMap::const_iterator it = struct_param_table.find(id); float res = 0; if (it != struct_param_table.end()) { res += get_filtered_param(id, it->second); } if (label_extractor != 0 and sublabel_order > NODEG) { const LabelVector &sub_labels = label_extractor->sub_labels(label); for (unsigned int j = 0; j < sub_labels.size(); ++j) { id = get_struct_param_id(sub_labels[j]); it = struct_param_table.find(id); if (it != struct_param_table.end()) { res += get_filtered_param(id, it->second); } } } return res; } float ParamTable::get_struct2(unsigned int plabel, unsigned int label, Degree sublabel_order) const { long id = get_struct_param_id(plabel, label); ParamMap::const_iterator it = struct_param_table.find(id); float res = 0; if (it != struct_param_table.end()) { res += get_filtered_param(id, it->second); } if (label_extractor != 0 and sublabel_order > ZEROTH) { const LabelVector &sub_labels = label_extractor->sub_labels(label); const LabelVector &psub_labels = label_extractor->sub_labels(plabel); for (unsigned int i = 0; i < psub_labels.size(); ++i) { for (unsigned int j = 0; j < sub_labels.size(); ++j) { id = get_struct_param_id(psub_labels[i], sub_labels[j]); it = struct_param_table.find(id); if (it != struct_param_table.end()) { res += get_filtered_param(id, it->second); } } } } return res; } float ParamTable::get_struct3(unsigned int pplabel, unsigned int plabel, unsigned int label, Degree sublabel_order) const { long id = get_struct_param_id(pplabel, plabel, label); ParamMap::const_iterator it = struct_param_table.find(id); float total = 0; if (it != struct_param_table.end()) { total += get_filtered_param(id, it->second); } if (label_extractor != 0 and sublabel_order > FIRST) { const LabelVector &sub_labels = label_extractor->sub_labels(label); const LabelVector &psub_labels = label_extractor->sub_labels(plabel); const LabelVector &ppsub_labels = label_extractor->sub_labels(pplabel); for (unsigned int i = 0; i < ppsub_labels.size(); ++i) { for (unsigned int j = 0; j < psub_labels.size(); ++j) { for (unsigned int k = 0; k < sub_labels.size(); ++k) { size_t id = get_struct_param_id(ppsub_labels[i], psub_labels[j], sub_labels[k]); it = struct_param_table.find(id); if (it != struct_param_table.end()) { total += get_filtered_param(id, it->second); } } } } } return total; } float ParamTable::get_all_unstruct(const Word &word, unsigned int label, Degree sub_label_order) const { float res = 0; for (unsigned int i = 0; i < word.get_feature_template_count(); ++i) { res += get_unstruct(word.get_feature_template(i), label); } if (sub_label_order > NODEG and label_extractor != 0) { const LabelVector &sub_labels = label_extractor->sub_labels(label); for (unsigned int i = 0; i < word.get_feature_template_count(); ++i) { for (unsigned int j = 0; j < sub_labels.size(); ++j) { res += get_unstruct(word.get_feature_template(i), sub_labels[j]); } } } return res; } float ParamTable::get_all_struct_fw(unsigned int pplabel, unsigned int plabel, unsigned int label, Degree sublabel_order, Degree model_order) const { return (model_order > FIRST ? get_struct3(pplabel, plabel, label, sublabel_order) : 0) + (model_order > ZEROTH ? get_struct2(plabel, label, sublabel_order) : 0) + get_struct1(label, sublabel_order); } float ParamTable::get_all_struct_bw(unsigned int pplabel, unsigned int plabel, unsigned int label, Degree sublabel_order, Degree model_order) const { return (model_order > FIRST ? get_struct3(pplabel, plabel, label, sublabel_order) : 0) + (model_order > ZEROTH ? get_struct2(plabel, label, sublabel_order) : 0) + get_struct1(label, sublabel_order); } void ParamTable::update_unstruct(unsigned int feature_template, unsigned int label, float ud) { size_t id = get_unstruct_param_id(feature_template, label); if (unstruct_param_table.count(id) == 0) { unstruct_param_table[id] = 0; } if (filter_type == UPDATE_COUNT) { ++update_count_map[id]; } unstruct_param_table[get_unstruct_param_id(feature_template, label)] += ud; } void ParamTable::update_struct1(unsigned int label, float ud, Degree sublabel_order) { size_t id = get_struct_param_id(label); if (struct_param_table.count(id) == 0) { struct_param_table[id] = 0; } if (filter_type == UPDATE_COUNT) { ++update_count_map[id]; } struct_param_table[get_struct_param_id(label)] += ud; if (label_extractor != 0 and sublabel_order > NODEG) { const LabelVector &sub_labels = label_extractor->sub_labels(label); for (unsigned int i = 0; i < sub_labels.size(); ++i) { size_t id = get_struct_param_id(sub_labels[i]); if (struct_param_table.count(id) == 0) { struct_param_table[id] = 0; } if (filter_type == UPDATE_COUNT) { ++update_count_map[id]; } struct_param_table[get_struct_param_id(sub_labels[i])] += ud; } } } void ParamTable::regularize_struct1(unsigned int label, float sigma, Degree sublabel_order) { size_t id = get_struct_param_id(label); if (struct_param_table.count(id) == 0) { struct_param_table[id] = 0; } if (filter_type == UPDATE_COUNT) { ++update_count_map[id]; } float ud = -1 * struct_param_table[id] * sigma; struct_param_table[id] += ud; if (label_extractor != 0 and sublabel_order > NODEG) { const LabelVector &sub_labels = label_extractor->sub_labels(label); for (unsigned int i = 0; i < sub_labels.size(); ++i) { size_t id = get_struct_param_id(sub_labels[i]); if (struct_param_table.count(id) == 0) { struct_param_table[id] = 0; } if (filter_type == UPDATE_COUNT) { ++update_count_map[id]; } float ud = -1 * struct_param_table[id] * sigma; struct_param_table[id] += ud; } } } void ParamTable::update_struct2(unsigned int plabel, unsigned int label, float ud, Degree sublabel_order) { size_t id = get_struct_param_id(plabel, label); if (struct_param_table.count(id) == 0) { struct_param_table[id] = 0; } if (filter_type == UPDATE_COUNT) { ++update_count_map[id]; } struct_param_table[get_struct_param_id(plabel, label)] += ud; if (label_extractor != 0 and sublabel_order > ZEROTH) { const LabelVector &sub_labels = label_extractor->sub_labels(label); const LabelVector &psub_labels = label_extractor->sub_labels(plabel); for (unsigned int i = 0; i < psub_labels.size(); ++i) { for (unsigned int j = 0; j < sub_labels.size(); ++j) { size_t id = get_struct_param_id(psub_labels[i], sub_labels[j]); if (struct_param_table.count(id) == 0) { struct_param_table[id] = 0; } if (filter_type == UPDATE_COUNT) { ++update_count_map[id]; } struct_param_table[get_struct_param_id(psub_labels[i], sub_labels[j])] += ud; } } } } void ParamTable::regularize_struct2(unsigned int plabel, unsigned int label, float sigma, Degree sublabel_order) { size_t id = get_struct_param_id(plabel, label); if (struct_param_table.count(id) == 0) { struct_param_table[id] = 0; } if (filter_type == UPDATE_COUNT) { ++update_count_map[id]; } float ud = -1 * struct_param_table[id] * sigma; struct_param_table[id] += ud; if (label_extractor != 0 and sublabel_order > ZEROTH) { const LabelVector &sub_labels = label_extractor->sub_labels(label); const LabelVector &psub_labels = label_extractor->sub_labels(plabel); for (unsigned int i = 0; i < psub_labels.size(); ++i) { for (unsigned int j = 0; j < sub_labels.size(); ++j) { size_t id = get_struct_param_id(psub_labels[i], sub_labels[j]); if (struct_param_table.count(id) == 0) { struct_param_table[id] = 0; } if (filter_type == UPDATE_COUNT) { ++update_count_map[id]; } float ud = -1 * struct_param_table[id] * sigma; struct_param_table[id] += ud; } } } } void ParamTable::update_struct3(unsigned int pplabel, unsigned int plabel, unsigned int label, float ud, Degree sublabel_order) { size_t id = get_struct_param_id(pplabel, plabel, label); if (struct_param_table.count(id) == 0) { struct_param_table[id] = 0; } if (filter_type == UPDATE_COUNT) { ++update_count_map[id]; } struct_param_table[get_struct_param_id(pplabel, plabel, label)] += ud; if (label_extractor != 0 and sublabel_order > FIRST) { const LabelVector &sub_labels = label_extractor->sub_labels(label); const LabelVector &psub_labels = label_extractor->sub_labels(plabel); const LabelVector &ppsub_labels = label_extractor->sub_labels(pplabel); for (unsigned int i = 0; i < ppsub_labels.size(); ++i) { for (unsigned int j = 0; j < psub_labels.size(); ++j) { for (unsigned int k = 0; k < sub_labels.size(); ++k) { size_t id = get_struct_param_id(ppsub_labels[i], psub_labels[j], sub_labels[k]); if (struct_param_table.count(id) == 0) { struct_param_table[id] = 0; } if (filter_type == UPDATE_COUNT) { ++update_count_map[id]; } struct_param_table[get_struct_param_id(ppsub_labels[i], psub_labels[j], sub_labels[k])] += ud; } } } } } void ParamTable::regularize_struct3(unsigned int pplabel, unsigned int plabel, unsigned int label, float sigma, Degree sublabel_order) { size_t id = get_struct_param_id(pplabel, plabel, label); if (struct_param_table.count(id) == 0) { struct_param_table[id] = 0; } if (filter_type == UPDATE_COUNT) { ++update_count_map[id]; } float ud = -1 * sigma * struct_param_table[id]; struct_param_table[id] += ud; if (label_extractor != 0 and sublabel_order > FIRST) { const LabelVector &sub_labels = label_extractor->sub_labels(label); const LabelVector &psub_labels = label_extractor->sub_labels(plabel); const LabelVector &ppsub_labels = label_extractor->sub_labels(pplabel); for (unsigned int i = 0; i < ppsub_labels.size(); ++i) { for (unsigned int j = 0; j < psub_labels.size(); ++j) { for (unsigned int k = 0; k < sub_labels.size(); ++k) { size_t id = get_struct_param_id(ppsub_labels[i], psub_labels[j], sub_labels[k]); if (struct_param_table.count(id) == 0) { struct_param_table[id] = 0; } if (filter_type == UPDATE_COUNT) { ++update_count_map[id]; } float ud = -1* sigma* struct_param_table[id]; struct_param_table[id] += ud; } } } } } void ParamTable::update_all_struct_fw(unsigned int pplabel, unsigned int plabel, unsigned int label, float update, Degree sublabel_order, Degree model_order) { update_struct1(label, update, sublabel_order); if (model_order > ZEROTH) update_struct2(plabel, label, update, sublabel_order); if (model_order > FIRST) update_struct3(pplabel, plabel, label, update, sublabel_order); } void ParamTable::update_all_struct_bw(unsigned int pplabel, unsigned int plabel, unsigned int label, float update, Degree sublabel_order, Degree model_order) { if (model_order > FIRST) update_struct3(pplabel, plabel, label, update, sublabel_order); if (model_order > ZEROTH) update_struct2(plabel, label, update, sublabel_order); update_struct1(label, update, sublabel_order); } void ParamTable::update_all_unstruct(const Word &word, unsigned int label, float update, Degree sub_label_order) { for (unsigned int i = 0; i < word.get_feature_template_count(); ++i) { update_unstruct(word.get_feature_template(i), label, update); } if (label_extractor != 0 and sub_label_order > NODEG) { const LabelVector &sub_labels = label_extractor->sub_labels(label); for (unsigned int i = 0; i < word.get_feature_template_count(); ++i) { for (unsigned int j = 0; j < sub_labels.size(); ++j) { update_unstruct(word.get_feature_template(i), sub_labels[j], update); } } } } void ParamTable::regularize_all_unstruct(const Word &word, unsigned int label, float sigma, Degree sub_label_order) { for (unsigned int i = 0; i < word.get_feature_template_count(); ++i) { float ud = -1 * get_unstruct(word.get_feature_template(i), label) * sigma; update_unstruct(word.get_feature_template(i), label, ud); } if (label_extractor != 0 and sub_label_order > NODEG) { const LabelVector &sub_labels = label_extractor->sub_labels(label); for (unsigned int i = 0; i < word.get_feature_template_count(); ++i) { for (unsigned int j = 0; j < sub_labels.size(); ++j) { float ud = -1 * get_unstruct(word.get_feature_template(i), sub_labels[j]) * sigma; update_unstruct(word.get_feature_template(i), sub_labels[j], ud); } } } } ParamMap::iterator ParamTable::get_unstruct_begin(void) { return unstruct_param_table.begin(); } ParamMap::iterator ParamTable::get_struct_begin(void) { return struct_param_table.begin(); } ParamMap::iterator ParamTable::get_unstruct_end(void) { return unstruct_param_table.end(); } ParamMap::iterator ParamTable::get_struct_end(void) { return struct_param_table.end(); } #include <cassert> void ParamTable::store(std::ostream &out) const { write_val(out, trained); write_map(out, feature_template_map); if (filter_type == UPDATE_COUNT) { write_filtered_map(out, unstruct_param_table, update_count_map, update_threshold, 1); } else if (filter_type == AVG_VALUE) { write_avg_filtered_map(out, unstruct_param_table, avg_mass_threshold, train_iters, 1); } else { write_map(out, unstruct_param_table, 1); } if (filter_type == UPDATE_COUNT) { write_filtered_map(out, struct_param_table, update_count_map, update_threshold, 1); } else if (filter_type == AVG_VALUE) { write_avg_filtered_map(out, struct_param_table, avg_mass_threshold, train_iters, 1); } else { write_map(out, struct_param_table, 1); } } void ParamTable::load(std::istream &in, bool reverse_bytes) { read_val<bool>(in, trained, reverse_bytes); std::cerr << trained << std::endl; read_map(in, feature_template_map, reverse_bytes); read_map(in, unstruct_param_table, reverse_bytes); read_map(in, struct_param_table, reverse_bytes); label_extractor = 0; } bool ParamTable::operator==(const ParamTable &another) const { // if (this == &another) // { return 1; } return (label_extractor->operator==(*(another.label_extractor)) and trained == another.trained and feature_template_map == another.feature_template_map and unstruct_param_table == another.unstruct_param_table and struct_param_table == another.struct_param_table); } std::ostream &operator<<(std::ostream &out, const ParamTable &table) { ParamTable::InvFeatureTemplateMap m(table.feature_template_map.size()); for (ParamTable::FeatureTemplateMap::const_iterator it = table.feature_template_map.begin(); it != table.feature_template_map.end(); ++it) { m[it->second] = it->first; } out << "UNSTRUCTURED FEATURES" << std::endl; for (ParamMap::const_iterator it = table.unstruct_param_table.begin(); it != table.unstruct_param_table.end(); ++it) { std::string feat_str = table.get_unstruct_feat_repr(it->first, m); out << feat_str << ' ' << it->second << std::endl; } out << "STRUCTURED FEATURES" << std::endl; for (ParamMap::const_iterator it = table.struct_param_table.begin(); it != table.struct_param_table.end(); ++it) { std::string feat_str = table.get_struct_feat_repr(it->first); out << feat_str << ' ' << it->second << std::endl; } return out; } #else // TEST_ParamTable_cc #include <sstream> #include <cassert> #include "LabelExtractor.hh" int main(void) { ParamTable pt; LabelExtractor le; static_cast<void>(le.get_label("a")); pt.set_label_extractor(le); unsigned int label_foo = pt.get_feat_template("FOO"); unsigned int label_bar = pt.get_feat_template("BAR"); assert(label_foo != label_bar); assert(label_foo == pt.get_feat_template("FOO")); assert(label_bar == pt.get_feat_template("BAR")); assert(pt.get_unstruct(pt.get_feat_template("FOO"), 0) == 0); pt.update_unstruct(pt.get_feat_template("FOO"), 0, 1); assert(pt.get_unstruct(pt.get_feat_template("FOO"), 0) == 1); assert(pt.get_unstruct(pt.get_feat_template("BAR"), 0) == 0); pt.update_unstruct(pt.get_feat_template("BAR"), 0, 2); assert(pt.get_unstruct(pt.get_feat_template("BAR"), 0) == 2); assert(pt.get_unstruct(pt.get_feat_template("FOO"), 1) == 0); pt.update_unstruct(pt.get_feat_template("FOO"), 1, 3); assert(pt.get_unstruct(pt.get_feat_template("FOO"), 1) == 3); assert(pt.get_unstruct(pt.get_feat_template("FOO"), 0) == 1); pt.update_unstruct(pt.get_feat_template("FOO"), 0, 1); assert(pt.get_unstruct(pt.get_feat_template("FOO"), 0) == 2); assert(pt.get_struct1(0,NODEG) == 0); pt.update_struct1(0, 1,NODEG); assert(pt.get_struct1(0, NODEG) == 1); assert(pt.get_struct1(1,NODEG) == 0); pt.update_struct1(1, 2,NODEG); assert(pt.get_struct1(1,NODEG) == 2); assert(pt.get_struct2(0, 0, NODEG) == 0); pt.update_struct2(0, 0, 1, NODEG); assert(pt.get_struct2(0, 0, NODEG) == 1); assert(pt.get_struct2(0, 1, NODEG) == 0); pt.update_struct2(0, 1, 2, NODEG); assert(pt.get_struct2(0, 1, NODEG) == 2); assert(pt.get_struct3(0, 0, 0, NODEG) == 0); pt.update_struct3(0, 0, 0, 1, NODEG); assert(pt.get_struct3(0, 0, 0, NODEG) == 1); assert(pt.get_struct3(0, 1, 0, NODEG) == 0); pt.update_struct3(0, 1, 0, 2, NODEG); assert(pt.get_struct3(0, 1, 0, NODEG) == 2); std::ostringstream pt_out; pt.store(pt_out); std::istringstream pt_in(pt_out.str()); ParamTable pt_copy; pt_copy.load(pt_in, false); pt_copy.set_label_extractor(le); assert(pt_copy == pt); std::cout << pt << std::endl; } #endif // TEST_ParamTable_cc
25,439
9,682
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/imagebuilder/model/PipelineExecutionStartCondition.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace imagebuilder { namespace Model { namespace PipelineExecutionStartConditionMapper { static const int EXPRESSION_MATCH_ONLY_HASH = HashingUtils::HashString("EXPRESSION_MATCH_ONLY"); static const int EXPRESSION_MATCH_AND_DEPENDENCY_UPDATES_AVAILABLE_HASH = HashingUtils::HashString("EXPRESSION_MATCH_AND_DEPENDENCY_UPDATES_AVAILABLE"); PipelineExecutionStartCondition GetPipelineExecutionStartConditionForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == EXPRESSION_MATCH_ONLY_HASH) { return PipelineExecutionStartCondition::EXPRESSION_MATCH_ONLY; } else if (hashCode == EXPRESSION_MATCH_AND_DEPENDENCY_UPDATES_AVAILABLE_HASH) { return PipelineExecutionStartCondition::EXPRESSION_MATCH_AND_DEPENDENCY_UPDATES_AVAILABLE; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<PipelineExecutionStartCondition>(hashCode); } return PipelineExecutionStartCondition::NOT_SET; } Aws::String GetNameForPipelineExecutionStartCondition(PipelineExecutionStartCondition enumValue) { switch(enumValue) { case PipelineExecutionStartCondition::EXPRESSION_MATCH_ONLY: return "EXPRESSION_MATCH_ONLY"; case PipelineExecutionStartCondition::EXPRESSION_MATCH_AND_DEPENDENCY_UPDATES_AVAILABLE: return "EXPRESSION_MATCH_AND_DEPENDENCY_UPDATES_AVAILABLE"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace PipelineExecutionStartConditionMapper } // namespace Model } // namespace imagebuilder } // namespace Aws
2,987
867
/** * VUT FIT IMS project - Freshbox food distribution. * * @file Work shift process implementation. * @author Dominik Harmim <xharmi00@stud.fit.vutbr.cz> * @author Vojtech Hertl <xhertl04@stud.fit.vutbr.cz> */ #include <iostream> #include "WorkShift.hpp" #include "WorkShiftTimer.hpp" #include "Car.hpp" #include "AverageUniformDistribution.hpp" using namespace std; WorkShift::WorkShift( unsigned long cars, double foodAverage, double foodDeviation ) { this->cars = new Store("Car store", cars); // Round number of food to be divisible by car capacity. food = new unsigned long(static_cast<unsigned long>( AverageUniformDistribution::Generate(foodAverage, foodDeviation) )); unsigned long remainder = *food % Car::CAR_CAPACITY; if (remainder < Car::CAR_CAPACITY / 2.0) { *food -= remainder; } else { *food += Car::CAR_CAPACITY - remainder; } carLoadingStat = new Stat("Car loading duration"); carRideStat = new Stat("Car ride duration"); carRideDistanceStat = new Stat("Car ride distance"); carRideConsumptionStat = new Stat("Car ride consumption"); PrintStartOfShift(); } WorkShift::~WorkShift() { PrintEndOfShift(); delete food; delete carLoadingStat; delete carRideStat; delete carRideDistanceStat; delete carRideConsumptionStat; } void WorkShift::Behavior() { auto *workShiftTimer = new WorkShiftTimer(this); // While there is food left and there is free car, take it and start // car process. while (*food > 0) { Enter(*cars, 1); // If food has been taken during waiting for car, leave the car. if (*food == 0) { Leave(*cars, 1); break; } *food -= Car::CAR_CAPACITY; // Start car process. (new Car( cars, carLoadingStat, carRideStat, carRideDistanceStat, carRideConsumptionStat ))->Activate(); } // Wait for all cars and then end the work shift. Enter(*cars, cars->Capacity()); Leave(*cars, cars->Capacity()); delete workShiftTimer; } void WorkShift::PrintStartOfShift() { cout << "////////////////////////////////////////////////////////////\n" << "Work shift started.\n" << "\tStart time: " << Time << ".\n" << "\tNumber of cars: " << cars->Capacity() << ".\n" << "\tNumber of food: " << *food << ".\n" << endl; } void WorkShift::PrintEndOfShift() { cout << "End of work shift.\n" << "\tEnd time: " << Time << ".\n" << "\tNumber of food left: " << *food << ".\n" << "\tTotal car ride distance: " << carRideDistanceStat->Sum() << ".\n" << "\tTotal cars consumption: " << carRideDistanceStat->Sum() / 100.0 * Car::CAR_CONSUMPTION << ".\n" << endl; cars->Output(); carLoadingStat->Output(); carRideStat->Output(); carRideDistanceStat->Output(); carRideConsumptionStat->Output(); cout << "////////////////////////////////////////////////////////////\n"; }
2,805
1,041
#include "ofGLRenderer.h" #include "ofMesh.h" #include "ofPath.h" #include "ofGraphics.h" #include "ofAppRunner.h" #include "ofMesh.h" #include "ofBitmapFont.h" #include "ofGLUtils.h" #include "ofImage.h" #include "ofFbo.h" //---------------------------------------------------------- ofGLRenderer::ofGLRenderer(bool useShapeColor){ bBackgroundAuto = true; linePoints.resize(2); rectPoints.resize(4); triPoints.resize(3); currentFbo = NULL; } //---------------------------------------------------------- void ofGLRenderer::update(){ } //---------------------------------------------------------- void ofGLRenderer::draw(ofMesh & vertexData, bool useColors, bool useTextures, bool useNormals){ if(vertexData.getNumVertices()){ glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), &vertexData.getVerticesPointer()->x); } if(vertexData.getNumNormals() && useNormals){ glEnableClientState(GL_NORMAL_ARRAY); glNormalPointer(GL_FLOAT, sizeof(ofVec3f), &vertexData.getNormalsPointer()->x); } if(vertexData.getNumColors() && useColors){ glEnableClientState(GL_COLOR_ARRAY); glColorPointer(4,GL_FLOAT, sizeof(ofFloatColor), &vertexData.getColorsPointer()->r); } if(vertexData.getNumTexCoords() && useTextures){ glEnableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer(2, GL_FLOAT, sizeof(ofVec2f), &vertexData.getTexCoordsPointer()->x); } if(vertexData.getNumIndices()){ #ifdef TARGET_OPENGLES glDrawElements(ofGetGLPrimitiveMode(vertexData.getMode()), vertexData.getNumIndices(),GL_UNSIGNED_SHORT,vertexData.getIndexPointer()); #else glDrawElements(ofGetGLPrimitiveMode(vertexData.getMode()), vertexData.getNumIndices(),GL_UNSIGNED_INT,vertexData.getIndexPointer()); #endif }else{ glDrawArrays(ofGetGLPrimitiveMode(vertexData.getMode()), 0, vertexData.getNumVertices()); } if(vertexData.getNumColors()){ glDisableClientState(GL_COLOR_ARRAY); } if(vertexData.getNumNormals()){ glDisableClientState(GL_NORMAL_ARRAY); } if(vertexData.getNumTexCoords()){ glDisableClientState(GL_TEXTURE_COORD_ARRAY); } } //---------------------------------------------------------- void ofGLRenderer::draw(ofMesh & vertexData, ofPolyRenderMode renderType, bool useColors, bool useTextures, bool useNormals){ if (bSmoothHinted) startSmoothing(); #ifndef TARGET_OPENGLES glPushAttrib(GL_POLYGON_BIT); glPolygonMode(GL_FRONT_AND_BACK, ofGetGLPolyMode(renderType)); draw(vertexData,useColors,useTextures,useNormals); glPopAttrib(); //TODO: GLES doesnt support polygon mode, add renderType to gl renderer? #else if(vertexData.getNumVertices()){ glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), vertexData.getVerticesPointer()); } if(vertexData.getNumNormals() && useNormals){ glEnableClientState(GL_NORMAL_ARRAY); glNormalPointer(GL_FLOAT, 0, vertexData.getNormalsPointer()); } if(vertexData.getNumColors() && useColors){ glEnableClientState(GL_COLOR_ARRAY); glColorPointer(4,GL_FLOAT, sizeof(ofFloatColor), vertexData.getColorsPointer()); } if(vertexData.getNumTexCoords() && useTextures){ glEnableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer(2, GL_FLOAT, 0, vertexData.getTexCoordsPointer()); } GLenum drawMode; switch(renderType){ case OF_MESH_POINTS: drawMode = GL_POINTS; break; case OF_MESH_WIREFRAME: drawMode = GL_LINES; break; case OF_MESH_FILL: drawMode = ofGetGLPrimitiveMode(vertexData.getMode()); break; default: drawMode = ofGetGLPrimitiveMode(vertexData.getMode()); break; } if(vertexData.getNumIndices()){ glDrawElements(drawMode, vertexData.getNumIndices(),GL_UNSIGNED_SHORT,vertexData.getIndexPointer()); }else{ glDrawArrays(drawMode, 0, vertexData.getNumVertices()); } if(vertexData.getNumColors() && useColors){ glDisableClientState(GL_COLOR_ARRAY); } if(vertexData.getNumNormals() && useNormals){ glDisableClientState(GL_NORMAL_ARRAY); } if(vertexData.getNumTexCoords() && useTextures){ glDisableClientState(GL_TEXTURE_COORD_ARRAY); } #endif if (bSmoothHinted) endSmoothing(); } //---------------------------------------------------------- void ofGLRenderer::draw(vector<ofPoint> & vertexData, ofPrimitiveMode drawMode){ if(!vertexData.empty()) { if (bSmoothHinted) startSmoothing(); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), &vertexData[0].x); glDrawArrays(ofGetGLPrimitiveMode(drawMode), 0, vertexData.size()); if (bSmoothHinted) endSmoothing(); } } //---------------------------------------------------------- void ofGLRenderer::draw(ofPolyline & poly){ if(!poly.getVertices().empty()) { // use smoothness, if requested: if (bSmoothHinted) startSmoothing(); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), &poly.getVertices()[0].x); glDrawArrays(poly.isClosed()?GL_LINE_LOOP:GL_LINE_STRIP, 0, poly.size()); // use smoothness, if requested: if (bSmoothHinted) endSmoothing(); } } //---------------------------------------------------------- void ofGLRenderer::draw(ofPath & shape){ ofColor prevColor; if(shape.getUseShapeColor()){ prevColor = ofGetStyle().color; } if(shape.isFilled()){ ofMesh & mesh = shape.getTessellation(); if(shape.getUseShapeColor()){ setColor( shape.getFillColor() * ofGetStyle().color,shape.getFillColor().a/255. * ofGetStyle().color.a); } draw(mesh); } if(shape.hasOutline()){ float lineWidth = ofGetStyle().lineWidth; if(shape.getUseShapeColor()){ setColor( shape.getStrokeColor() * ofGetStyle().color, shape.getStrokeColor().a/255. * ofGetStyle().color.a); } setLineWidth( shape.getStrokeWidth() ); vector<ofPolyline> & outlines = shape.getOutline(); for(int i=0; i<(int)outlines.size(); i++) draw(outlines[i]); setLineWidth(lineWidth); } if(shape.getUseShapeColor()){ setColor(prevColor); } } //---------------------------------------------------------- void ofGLRenderer::draw(ofImage & image, float x, float y, float z, float w, float h, float sx, float sy, float sw, float sh){ if(image.isUsingTexture()){ ofTexture& tex = image.getTextureReference(); if(tex.bAllocated()) { tex.drawSubsection(x,y,z,w,h,sx,sy,sw,sh); } else { ofLogWarning() << "ofGLRenderer::draw(): texture is not allocated"; } } } //---------------------------------------------------------- void ofGLRenderer::draw(ofFloatImage & image, float x, float y, float z, float w, float h, float sx, float sy, float sw, float sh){ if(image.isUsingTexture()){ ofTexture& tex = image.getTextureReference(); if(tex.bAllocated()) { tex.drawSubsection(x,y,z,w,h,sx,sy,sw,sh); } else { ofLogWarning() << "ofGLRenderer::draw(): texture is not allocated"; } } } //---------------------------------------------------------- void ofGLRenderer::draw(ofShortImage & image, float x, float y, float z, float w, float h, float sx, float sy, float sw, float sh){ if(image.isUsingTexture()){ ofTexture& tex = image.getTextureReference(); if(tex.bAllocated()) { tex.drawSubsection(x,y,z,w,h,sx,sy,sw,sh); } else { ofLogWarning() << "ofGLRenderer::draw(): texture is not allocated"; } } } //---------------------------------------------------------- void ofGLRenderer::setCurrentFBO(ofFbo * fbo){ currentFbo = fbo; } //---------------------------------------------------------- void ofGLRenderer::pushView() { GLint viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); ofRectangle currentViewport; currentViewport.set(viewport[0], viewport[1], viewport[2], viewport[3]); viewportHistory.push(currentViewport); /*glMatrixMode(GL_PROJECTION); glPushMatrix(); glMatrixMode(GL_MODELVIEW); glPushMatrix();*/ // done like this cause i was getting GL_STACK_UNDERFLOW // should ofPush/PopMatrix work the same way, what if it's mixed with glPush/PopMatrix ofMatrix4x4 m; glGetFloatv(GL_PROJECTION_MATRIX,m.getPtr()); projectionStack.push(m); glGetFloatv(GL_MODELVIEW_MATRIX,m.getPtr()); modelViewStack.push(m); } //---------------------------------------------------------- void ofGLRenderer::popView() { if( viewportHistory.size() ){ ofRectangle viewRect = viewportHistory.top(); viewport(viewRect.x, viewRect.y, viewRect.width, viewRect.height,false); viewportHistory.pop(); } /*glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix();*/ // done like this cause i was getting GL_STACK_UNDERFLOW // should ofPush/PopMatrix work the same way, what if it's mixed with glPush/PopMatrix glMatrixMode(GL_PROJECTION); if(!projectionStack.empty()){ glLoadMatrixf(projectionStack.top().getPtr()); projectionStack.pop(); }else{ ofLogError() << "popView: couldn't pop projection matrix, stack empty. probably wrong anidated push/popView"; } glMatrixMode(GL_MODELVIEW); if(!modelViewStack.empty()){ glLoadMatrixf(modelViewStack.top().getPtr()); modelViewStack.pop(); }else{ ofLogError() << "popView: couldn't pop modelView matrix, stack empty. probably wrong anidated push/popView"; } } //---------------------------------------------------------- void ofGLRenderer::viewport(ofRectangle viewport_){ viewport(viewport_.x, viewport_.y, viewport_.width, viewport_.height,true); } //---------------------------------------------------------- void ofGLRenderer::viewport(float x, float y, float width, float height, bool invertY) { if(width == 0) width = ofGetWindowWidth(); if(height == 0) height = ofGetWindowHeight(); if (invertY){ if(currentFbo){ y = currentFbo->getHeight() - (y + height); }else{ y = ofGetWindowHeight() - (y + height); } } glViewport(x, y, width, height); } //---------------------------------------------------------- ofRectangle ofGLRenderer::getCurrentViewport(){ // I am using opengl calls here instead of returning viewportRect // since someone might use glViewport instead of ofViewport... GLint viewport[4]; // Where The Viewport Values Will Be Stored glGetIntegerv(GL_VIEWPORT, viewport); ofRectangle view; view.x = viewport[0]; view.y = viewport[1]; view.width = viewport[2]; view.height = viewport[3]; return view; } //---------------------------------------------------------- int ofGLRenderer::getViewportWidth(){ GLint viewport[4]; // Where The Viewport Values Will Be Stored glGetIntegerv(GL_VIEWPORT, viewport); return viewport[2]; } //---------------------------------------------------------- int ofGLRenderer::getViewportHeight(){ GLint viewport[4]; // Where The Viewport Values Will Be Stored glGetIntegerv(GL_VIEWPORT, viewport); return viewport[3]; } //---------------------------------------------------------- void ofGLRenderer::setCoordHandedness(ofHandednessType handedness) { coordHandedness = handedness; } //---------------------------------------------------------- ofHandednessType ofGLRenderer::getCoordHandedness() { return coordHandedness; } //---------------------------------------------------------- void ofGLRenderer::setupScreenPerspective(float width, float height, ofOrientation orientation, bool vFlip, float fov, float nearDist, float farDist) { if(width == 0) width = ofGetWidth(); if(height == 0) height = ofGetHeight(); float viewW = ofGetViewportWidth(); float viewH = ofGetViewportHeight(); float eyeX = viewW / 2; float eyeY = viewH / 2; float halfFov = PI * fov / 360; float theTan = tanf(halfFov); float dist = eyeY / theTan; float aspect = (float) viewW / viewH; if(nearDist == 0) nearDist = dist / 10.0f; if(farDist == 0) farDist = dist * 10.0f; glMatrixMode(GL_PROJECTION); glLoadIdentity(); ofMatrix4x4 persp; persp.makePerspectiveMatrix(fov, aspect, nearDist, farDist); loadMatrix( persp ); //gluPerspective(fov, aspect, nearDist, farDist); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); ofMatrix4x4 lookAt; lookAt.makeLookAtViewMatrix( ofVec3f(eyeX, eyeY, dist), ofVec3f(eyeX, eyeY, 0), ofVec3f(0, 1, 0) ); loadMatrix( lookAt ); //gluLookAt(eyeX, eyeY, dist, eyeX, eyeY, 0, 0, 1, 0); //note - theo checked this on iPhone and Desktop for both vFlip = false and true if(ofDoesHWOrientation()){ if(vFlip){ glScalef(1, -1, 1); glTranslatef(0, -height, 0); } }else{ if( orientation == OF_ORIENTATION_UNKNOWN ) orientation = ofGetOrientation(); switch(orientation) { case OF_ORIENTATION_180: glRotatef(-180, 0, 0, 1); if(vFlip){ glScalef(1, -1, 1); glTranslatef(-width, 0, 0); }else{ glTranslatef(-width, -height, 0); } break; case OF_ORIENTATION_90_RIGHT: glRotatef(-90, 0, 0, 1); if(vFlip){ glScalef(-1, 1, 1); }else{ glScalef(-1, -1, 1); glTranslatef(0, -height, 0); } break; case OF_ORIENTATION_90_LEFT: glRotatef(90, 0, 0, 1); if(vFlip){ glScalef(-1, 1, 1); glTranslatef(-width, -height, 0); }else{ glScalef(-1, -1, 1); glTranslatef(-width, 0, 0); } break; case OF_ORIENTATION_DEFAULT: default: if(vFlip){ glScalef(1, -1, 1); glTranslatef(0, -height, 0); } break; } } } //---------------------------------------------------------- void ofGLRenderer::setupScreenOrtho(float width, float height, ofOrientation orientation, bool vFlip, float nearDist, float farDist) { if(width == 0) width = ofGetWidth(); if(height == 0) height = ofGetHeight(); float viewW = ofGetViewportWidth(); float viewH = ofGetViewportHeight(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); ofSetCoordHandedness(OF_RIGHT_HANDED); #ifndef TARGET_OPENGLES if(vFlip) { ofSetCoordHandedness(OF_LEFT_HANDED); } if(nearDist == -1) nearDist = 0; if(farDist == -1) farDist = 10000; glOrtho(0, viewW, 0, viewH, nearDist, farDist); #else if(vFlip) { ofMatrix4x4 ortho = ofMatrix4x4::newOrthoMatrix(0, width, height, 0, nearDist, farDist); ofSetCoordHandedness(OF_LEFT_HANDED); } ofMatrix4x4 ortho = ofMatrix4x4::newOrthoMatrix(0, viewW, 0, viewH, nearDist, farDist); glMultMatrixf(ortho.getPtr()); #endif glMatrixMode(GL_MODELVIEW); glLoadIdentity(); //note - theo checked this on iPhone and Desktop for both vFlip = false and true if(ofDoesHWOrientation()){ if(vFlip){ glScalef(1, -1, 1); glTranslatef(0, -height, 0); } }else{ if( orientation == OF_ORIENTATION_UNKNOWN ) orientation = ofGetOrientation(); switch(orientation) { case OF_ORIENTATION_180: glRotatef(-180, 0, 0, 1); if(vFlip){ glScalef(1, -1, 1); glTranslatef(-width, 0, 0); }else{ glTranslatef(-width, -height, 0); } break; case OF_ORIENTATION_90_RIGHT: glRotatef(-90, 0, 0, 1); if(vFlip){ glScalef(-1, 1, 1); }else{ glScalef(-1, -1, 1); glTranslatef(0, -height, 0); } break; case OF_ORIENTATION_90_LEFT: glRotatef(90, 0, 0, 1); if(vFlip){ glScalef(-1, 1, 1); glTranslatef(-width, -height, 0); }else{ glScalef(-1, -1, 1); glTranslatef(-width, 0, 0); } break; case OF_ORIENTATION_DEFAULT: default: if(vFlip){ glScalef(1, -1, 1); glTranslatef(0, -height, 0); } break; } } } //---------------------------------------------------------- //Resets openGL parameters back to OF defaults void ofGLRenderer::setupGraphicDefaults(){ glEnableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); } //---------------------------------------------------------- void ofGLRenderer::setupScreen(){ setupScreenPerspective(); // assume defaults } //---------------------------------------------------------- void ofGLRenderer::setCircleResolution(int res){ if((int)circlePolyline.size()!=res+1){ circlePolyline.clear(); circlePolyline.arc(0,0,0,1,1,0,360,res); circlePoints.resize(circlePolyline.size()); } } //---------------------------------------------------------- void ofGLRenderer::setSphereResolution(int res) { if(sphereMesh.getNumVertices() == 0 || res != ofGetStyle().sphereResolution) { int n = res * 2; float ndiv2=(float)n/2; /* Original code by Paul Bourke A more efficient contribution by Federico Dosil (below) Draw a point for zero radius spheres Use CCW facet ordering http://paulbourke.net/texture_colour/texturemap/ */ float theta2 = TWO_PI; float phi1 = -HALF_PI; float phi2 = HALF_PI; float r = 1.f; // normalize the verts // sphereMesh.clear(); sphereMesh.setMode(OF_PRIMITIVE_TRIANGLE_STRIP); int i, j; float theta1 = 0.f; float jdivn,j1divn,idivn,dosdivn,unodivn=1/(float)n,t1,t2,t3,cost1,cost2,cte1,cte3; cte3 = (theta2-theta1)/n; cte1 = (phi2-phi1)/ndiv2; dosdivn = 2*unodivn; ofVec3f e,p,e2,p2; if (n < 0){ n = -n; ndiv2 = -ndiv2; } if (n < 4) {n = 4; ndiv2=(float)n/2;} if(r <= 0) r = 1; t2=phi1; cost2=cos(phi1); j1divn=0; ofVec3f vert, normal; ofVec2f tcoord; for (j=0;j<ndiv2;j++) { t1 = t2; t2 += cte1; t3 = theta1 - cte3; cost1 = cost2; cost2 = cos(t2); e.y = sin(t1); e2.y = sin(t2); p.y = r * e.y; p2.y = r * e2.y; idivn=0; jdivn=j1divn; j1divn+=dosdivn; for (i=0;i<=n;i++) { t3 += cte3; e.x = cost1 * cos(t3); e.z = cost1 * sin(t3); p.x = r * e.x; p.z = r * e.z; normal.set( e.x, e.y, e.z ); tcoord.set( idivn, jdivn ); vert.set( p.x, p.y, p.z ); sphereMesh.addNormal(normal); sphereMesh.addTexCoord(tcoord); sphereMesh.addVertex(vert); e2.x = cost2 * cos(t3); e2.z = cost2 * sin(t3); p2.x = r * e2.x; p2.z = r * e2.z; normal.set(e2.x, e2.y, e2.z); tcoord.set(idivn, j1divn); vert.set(p2.x, p2.y, p2.z); sphereMesh.addNormal(normal); sphereMesh.addTexCoord(tcoord); sphereMesh.addVertex(vert); idivn += unodivn; } } } } //our openGL wrappers //---------------------------------------------------------- void ofGLRenderer::pushMatrix(){ glPushMatrix(); } //---------------------------------------------------------- void ofGLRenderer::popMatrix(){ glPopMatrix(); } //---------------------------------------------------------- void ofGLRenderer::translate(const ofPoint& p){ glTranslatef(p.x, p.y, p.z); } //---------------------------------------------------------- void ofGLRenderer::translate(float x, float y, float z){ glTranslatef(x, y, z); } //---------------------------------------------------------- void ofGLRenderer::scale(float xAmnt, float yAmnt, float zAmnt){ glScalef(xAmnt, yAmnt, zAmnt); } //---------------------------------------------------------- void ofGLRenderer::rotate(float degrees, float vecX, float vecY, float vecZ){ glRotatef(degrees, vecX, vecY, vecZ); } //---------------------------------------------------------- void ofGLRenderer::rotateX(float degrees){ glRotatef(degrees, 1, 0, 0); } //---------------------------------------------------------- void ofGLRenderer::rotateY(float degrees){ glRotatef(degrees, 0, 1, 0); } //---------------------------------------------------------- void ofGLRenderer::rotateZ(float degrees){ glRotatef(degrees, 0, 0, 1); } //same as ofRotateZ //---------------------------------------------------------- void ofGLRenderer::rotate(float degrees){ glRotatef(degrees, 0, 0, 1); } //---------------------------------------------------------- void ofGLRenderer::loadIdentityMatrix (void){ glLoadIdentity(); } //---------------------------------------------------------- void ofGLRenderer::loadMatrix (const ofMatrix4x4 & m){ loadMatrix( m.getPtr() ); } //---------------------------------------------------------- void ofGLRenderer::loadMatrix (const float *m){ glLoadMatrixf(m); } //---------------------------------------------------------- void ofGLRenderer::multMatrix (const ofMatrix4x4 & m){ multMatrix( m.getPtr() ); } //---------------------------------------------------------- void ofGLRenderer::multMatrix (const float *m){ glMultMatrixf(m); } //---------------------------------------------------------- void ofGLRenderer::setColor(const ofColor & color){ setColor(color.r,color.g,color.b,color.a); } //---------------------------------------------------------- void ofGLRenderer::setColor(const ofColor & color, int _a){ setColor(color.r,color.g,color.b,_a); } //---------------------------------------------------------- void ofGLRenderer::setColor(int _r, int _g, int _b){ glColor4f(_r/255.f,_g/255.f,_b/255.f,1.f); } //---------------------------------------------------------- void ofGLRenderer::setColor(int _r, int _g, int _b, int _a){ glColor4f(_r/255.f,_g/255.f,_b/255.f,_a/255.f); } //---------------------------------------------------------- void ofGLRenderer::setColor(int gray){ setColor(gray, gray, gray); } //---------------------------------------------------------- void ofGLRenderer::setHexColor(int hexColor){ int r = (hexColor >> 16) & 0xff; int g = (hexColor >> 8) & 0xff; int b = (hexColor >> 0) & 0xff; setColor(r,g,b); } //---------------------------------------------------------- void ofGLRenderer::clear(float r, float g, float b, float a) { glClearColor(r / 255., g / 255., b / 255., a / 255.); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } //---------------------------------------------------------- void ofGLRenderer::clear(float brightness, float a) { clear(brightness, brightness, brightness, a); } //---------------------------------------------------------- void ofGLRenderer::clearAlpha() { glColorMask(0, 0, 0, 1); glClearColor(0, 0, 0, 1); glClear(GL_COLOR_BUFFER_BIT); glColorMask(1, 1, 1, 1); } //---------------------------------------------------------- void ofGLRenderer::setBackgroundAuto(bool bAuto){ bBackgroundAuto = bAuto; } //---------------------------------------------------------- bool ofGLRenderer::bClearBg(){ return bBackgroundAuto; } //---------------------------------------------------------- ofFloatColor & ofGLRenderer::getBgColor(){ return bgColor; } //---------------------------------------------------------- void ofGLRenderer::background(const ofColor & c){ bgColor = c; glClearColor(bgColor[0],bgColor[1],bgColor[2], bgColor[3]); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } //---------------------------------------------------------- void ofGLRenderer::background(float brightness) { background(brightness); } //---------------------------------------------------------- void ofGLRenderer::background(int hexColor, float _a){ background ( (hexColor >> 16) & 0xff, (hexColor >> 8) & 0xff, (hexColor >> 0) & 0xff, _a); } //---------------------------------------------------------- void ofGLRenderer::background(int r, int g, int b, int a){ background(ofColor(r,g,b,a)); } //---------------------------------------------------------- void ofGLRenderer::setFillMode(ofFillFlag fill){ bFilled = fill; } //---------------------------------------------------------- ofFillFlag ofGLRenderer::getFillMode(){ return bFilled; } //---------------------------------------------------------- void ofGLRenderer::setRectMode(ofRectMode mode){ rectMode = mode; } //---------------------------------------------------------- ofRectMode ofGLRenderer::getRectMode(){ return rectMode; } //---------------------------------------------------------- void ofGLRenderer::setLineWidth(float lineWidth){ glLineWidth(lineWidth); } //---------------------------------------------------------- void ofGLRenderer::setLineSmoothing(bool smooth){ bSmoothHinted = smooth; } //---------------------------------------------------------- void ofGLRenderer::startSmoothing(){ #ifndef TARGET_OPENGLES glPushAttrib(GL_COLOR_BUFFER_BIT | GL_ENABLE_BIT); #endif glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); glEnable(GL_LINE_SMOOTH); //why do we need this? glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } //---------------------------------------------------------- void ofGLRenderer::endSmoothing(){ #ifndef TARGET_OPENGLES glPopAttrib(); #endif } //---------------------------------------------------------- void ofGLRenderer::setBlendMode(ofBlendMode blendMode){ switch (blendMode){ case OF_BLENDMODE_ALPHA:{ glEnable(GL_BLEND); #ifndef TARGET_OPENGLES glBlendEquation(GL_FUNC_ADD); #endif glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); break; } case OF_BLENDMODE_ADD:{ glEnable(GL_BLEND); #ifndef TARGET_OPENGLES glBlendEquation(GL_FUNC_ADD); #endif glBlendFunc(GL_SRC_ALPHA, GL_ONE); break; } case OF_BLENDMODE_MULTIPLY:{ glEnable(GL_BLEND); #ifndef TARGET_OPENGLES glBlendEquation(GL_FUNC_ADD); #endif glBlendFunc(GL_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA /* GL_ZERO or GL_ONE_MINUS_SRC_ALPHA */); break; } case OF_BLENDMODE_SCREEN:{ glEnable(GL_BLEND); #ifndef TARGET_OPENGLES glBlendEquation(GL_FUNC_ADD); #endif glBlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ONE); break; } case OF_BLENDMODE_SUBTRACT:{ glEnable(GL_BLEND); #ifndef TARGET_OPENGLES glBlendEquation(GL_FUNC_REVERSE_SUBTRACT); #else ofLog(OF_LOG_WARNING, "OF_BLENDMODE_SUBTRACT not currently supported on OpenGL/ES"); #endif glBlendFunc(GL_SRC_ALPHA, GL_ONE); break; } default: break; } } //---------------------------------------------------------- void ofGLRenderer::enablePointSprites(){ #ifdef TARGET_OPENGLES glEnable(GL_POINT_SPRITE_OES); glTexEnvi(GL_POINT_SPRITE_OES, GL_COORD_REPLACE_OES, GL_TRUE); // does look like this needs to be enabled in ES because // it is always eneabled... //glEnable(GL_VERTEX_PROGRAM_POINT_SIZE); #else glEnable(GL_POINT_SPRITE); glTexEnvi(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE); glEnable(GL_VERTEX_PROGRAM_POINT_SIZE); #endif } //---------------------------------------------------------- void ofGLRenderer::disablePointSprites(){ #ifdef TARGET_OPENGLES glDisable(GL_POINT_SPRITE_OES); #else glDisable(GL_POINT_SPRITE); #endif } //---------------------------------------------------------- void ofGLRenderer::drawLine(float x1, float y1, float z1, float x2, float y2, float z2){ linePoints[0].set(x1,y1,z1); linePoints[1].set(x2,y2,z2); // use smoothness, if requested: if (bSmoothHinted) startSmoothing(); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), &linePoints[0].x); glDrawArrays(GL_LINES, 0, 2); // use smoothness, if requested: if (bSmoothHinted) endSmoothing(); } //---------------------------------------------------------- void ofGLRenderer::drawRectangle(float x, float y, float z,float w, float h){ if (rectMode == OF_RECTMODE_CORNER){ rectPoints[0].set(x,y,z); rectPoints[1].set(x+w, y, z); rectPoints[2].set(x+w, y+h, z); rectPoints[3].set(x, y+h, z); }else{ rectPoints[0].set(x-w/2.0f, y-h/2.0f, z); rectPoints[1].set(x+w/2.0f, y-h/2.0f, z); rectPoints[2].set(x+w/2.0f, y+h/2.0f, z); rectPoints[3].set(x-w/2.0f, y+h/2.0f, z); } // use smoothness, if requested: if (bSmoothHinted && bFilled == OF_OUTLINE) startSmoothing(); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), &rectPoints[0].x); glDrawArrays((bFilled == OF_FILLED) ? GL_TRIANGLE_FAN : GL_LINE_LOOP, 0, 4); // use smoothness, if requested: if (bSmoothHinted && bFilled == OF_OUTLINE) endSmoothing(); } //---------------------------------------------------------- void ofGLRenderer::drawTriangle(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3){ triPoints[0].set(x1,y1,z1); triPoints[1].set(x2,y2,z2); triPoints[2].set(x3,y3,z3); // use smoothness, if requested: if (bSmoothHinted && bFilled == OF_OUTLINE) startSmoothing(); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), &triPoints[0].x); glDrawArrays((bFilled == OF_FILLED) ? GL_TRIANGLE_FAN : GL_LINE_LOOP, 0, 3); // use smoothness, if requested: if (bSmoothHinted && bFilled == OF_OUTLINE) endSmoothing(); } //---------------------------------------------------------- void ofGLRenderer::drawCircle(float x, float y, float z, float radius){ vector<ofPoint> & circleCache = circlePolyline.getVertices(); for(int i=0;i<(int)circleCache.size();i++){ circlePoints[i].set(radius*circleCache[i].x+x,radius*circleCache[i].y+y,z); } // use smoothness, if requested: if (bSmoothHinted && bFilled == OF_OUTLINE) startSmoothing(); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), &circlePoints[0].x); glDrawArrays((bFilled == OF_FILLED) ? GL_TRIANGLE_FAN : GL_LINE_STRIP, 0, circlePoints.size()); // use smoothness, if requested: if (bSmoothHinted && bFilled == OF_OUTLINE) endSmoothing(); } //---------------------------------------------------------- void ofGLRenderer::drawSphere(float x, float y, float z, float radius) { glEnable(GL_NORMALIZE); glPushMatrix(); glScalef(radius, radius, radius); if(bFilled) { sphereMesh.draw(); } else { sphereMesh.drawWireframe(); } glPopMatrix(); glDisable(GL_NORMALIZE); } //---------------------------------------------------------- void ofGLRenderer::drawEllipse(float x, float y, float z, float width, float height){ float radiusX = width*0.5; float radiusY = height*0.5; vector<ofPoint> & circleCache = circlePolyline.getVertices(); for(int i=0;i<(int)circleCache.size();i++){ circlePoints[i].set(radiusX*circlePolyline[i].x+x,radiusY*circlePolyline[i].y+y,z); } // use smoothness, if requested: if (bSmoothHinted && bFilled == OF_OUTLINE) startSmoothing(); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), &circlePoints[0].x); glDrawArrays((bFilled == OF_FILLED) ? GL_TRIANGLE_FAN : GL_LINE_STRIP, 0, circlePoints.size()); // use smoothness, if requested: if (bSmoothHinted && bFilled == OF_OUTLINE) endSmoothing(); } //---------------------------------------------------------- void ofGLRenderer::drawString(string textString, float x, float y, float z, ofDrawBitmapMode mode){ // this is copied from the ofTrueTypeFont //GLboolean blend_enabled = glIsEnabled(GL_BLEND); //TODO: this is not used? GLint blend_src, blend_dst; glGetIntegerv( GL_BLEND_SRC, &blend_src ); glGetIntegerv( GL_BLEND_DST, &blend_dst ); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); int len = (int)textString.length(); //float yOffset = 0; float fontSize = 8.0f; bool bOrigin = false; float sx = 0; float sy = -fontSize; /////////////////////////// // APPLY TRANSFORM / VIEW /////////////////////////// // bool hasModelView = false; bool hasProjection = false; bool hasViewport = false; ofRectangle rViewport; #ifdef TARGET_OPENGLES if(mode == OF_BITMAPMODE_MODEL_BILLBOARD) { mode = OF_BITMAPMODE_SIMPLE; } #endif switch (mode) { case OF_BITMAPMODE_SIMPLE: sx += x; sy += y; break; case OF_BITMAPMODE_SCREEN: hasViewport = true; ofPushView(); rViewport = ofGetWindowRect(); ofViewport(rViewport); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(-1, 1, 0); glScalef(2/rViewport.width, -2/rViewport.height, 1); ofTranslate(x, y, 0); break; case OF_BITMAPMODE_VIEWPORT: rViewport = ofGetCurrentViewport(); hasProjection = true; glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); hasModelView = true; glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glTranslatef(-1, 1, 0); glScalef(2/rViewport.width, -2/rViewport.height, 1); ofTranslate(x, y, 0); break; case OF_BITMAPMODE_MODEL: hasModelView = true; glMatrixMode(GL_MODELVIEW); glPushMatrix(); ofTranslate(x, y, z); ofScale(1, -1, 0); break; case OF_BITMAPMODE_MODEL_BILLBOARD: //our aim here is to draw to screen //at the viewport position related //to the world position x,y,z // *************** // this will not compile for opengl ES // *************** #ifndef TARGET_OPENGLES //gluProject method GLdouble modelview[16], projection[16]; GLint view[4]; double dScreenX, dScreenY, dScreenZ; glGetDoublev(GL_MODELVIEW_MATRIX, modelview); glGetDoublev(GL_PROJECTION_MATRIX, projection); glGetIntegerv(GL_VIEWPORT, view); view[0] = 0; view[1] = 0; //we're already drawing within viewport gluProject(x, y, z, modelview, projection, view, &dScreenX, &dScreenY, &dScreenZ); if (dScreenZ >= 1) return; rViewport = ofGetCurrentViewport(); hasProjection = true; glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); hasModelView = true; glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glTranslatef(-1, -1, 0); glScalef(2/rViewport.width, 2/rViewport.height, 1); glTranslatef(dScreenX, dScreenY, 0); if(currentFbo == NULL) { glScalef(1, -1, 1); } else { glScalef(1, 1, 1); // invert when rendering inside an fbo } #endif break; default: break; } // /////////////////////////// // (c) enable texture once before we start drawing each char (no point turning it on and off constantly) //We do this because its way faster ofDrawBitmapCharacterStart(textString.size()); for(int c = 0; c < len; c++){ if(textString[c] == '\n'){ sy += bOrigin ? -1 : 1 * (fontSize*1.7); if(mode == OF_BITMAPMODE_SIMPLE) { sx = x; } else { sx = 0; } //glRasterPos2f(x,y + (int)yOffset); } else if (textString[c] >= 32){ // < 32 = control characters - don't draw // solves a bug with control characters // getting drawn when they ought to not be ofDrawBitmapCharacter(textString[c], (int)sx, (int)sy); sx += fontSize; } } //We do this because its way faster ofDrawBitmapCharacterEnd(); if (hasModelView) glPopMatrix(); if (hasProjection) { glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); } if (hasViewport) ofPopView(); glBlendFunc(blend_src, blend_dst); }
34,219
13,673
#include "MainWindow.h" #include "ui_MainWindow.h" #include <QVBoxLayout> #include "MyWidget.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); auto* pLayout = new QVBoxLayout(this); ui->centralwidget->setLayout(pLayout); pLayout->addWidget(new MyWidget(this)); } MainWindow::~MainWindow() { delete ui; }
399
151
#include <wiringPi.h> #include <stdio.h> #include "servo.h" #include "logger.h" namespace robo { /* * Clock and range values from * http://stackoverflow.com/questions/20081286/controlling-a-servo-with-raspberry-pi-using-the-hardware-pwm-with-wiringpi * Range tests: * Clock: 384 Range: 30 - 115 * Clock: 500 Range: 25 - 80 * Clock: 400 Range: 29 - 111 * Clock: 250 Range: 46 - 178 * Clock: 200 Range: 57 - 223 * Clock: 100 Not working */ static const int SERVO_PIN = 1; static const int MIN = 30; static const int MAX = 115; static const int ZERO = (MIN + MAX) / 2; static constexpr char const * const arr[] = { "INFO", "WARNING", "ERROR", "CRASH" }; static const char * const error_values[] = { "SERVO_OK", "SERVO_OUT_OF_RANGE", "SERVO_ERROR" }; void Servo::Init() { //pinMode(SERVO_PIN, PWM_OUTPUT); //pwmSetMode(PWM_MODE_MS); //pwmSetClock(384); //pwmSetRange(1000); SetAngle(0); LogDebug("Servo Initialized."); } servo_status_t Servo::setGpioRegister(int16_t value) { auto status = servo_status_t::SERVO_ERROR; if (value > MAX) { status = servo_status_t::SERVO_OUT_OF_RANGE; value = MAX; } else if (value < MIN) { status = servo_status_t::SERVO_OUT_OF_RANGE; value = MIN; } else { status = servo_status_t::SERVO_OK; } LogDebug("Setting servo gpio: %d", value); m_gpio_value = value; pwmWrite(SERVO_PIN, value); return status; } servo_status_t Servo::SetAngle(int16_t angle) { return setGpioRegister(angleToGpioValue(angle)); } int Servo::angleToGpioValue(int16_t angle) const { return ZERO + angle; } int16_t Servo::gpioValueToAngle(int value) const { return value - ZERO; } servo_status_t Servo::StepLeft() { return setGpioRegister(m_gpio_value - 10); } servo_status_t Servo::StepRight() { return setGpioRegister(m_gpio_value + 10); } const char* Servo::getStatusText(servo_status_t status) const { return error_values[status]; } }
2,102
905
#include <iostream> #include <cmath> #include <algorithm> #include <vector> using namespace std; int main() { int X, Y, Z; cin >> X >> Y >> Z; int sum = 0, cnt = 0; while(true) { sum += Y + Z; if (sum + Z > X) break; cnt++; } printf("%d\n", cnt); }
293
115
/** ########################################################################## # If not stated otherwise in this file or this component's LICENSE # file the following copyright and licenses apply: # # Copyright 2019 RDK Management # # 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. ########################################################################## **/ #ifdef HAS_MEDIA_TS #include "mediaformats/readers/ts/streamdescriptors.h" #include "mediaformats/readers/ts/tsboundscheck.h" bool ReadStreamDescriptor(StreamDescriptor &descriptor, uint8_t *pBuffer, uint32_t &cursor, uint32_t maxCursor) { TS_CHECK_BOUNDS(2); descriptor.type = pBuffer[cursor++]; descriptor.length = pBuffer[cursor++]; TS_CHECK_BOUNDS(descriptor.length); //iso13818-1.pdf Table 2-39, page 81/174 switch (descriptor.type) { case 14://Maximum_bitrate_descriptor { TS_CHECK_BOUNDS(3); descriptor.payload.maximum_bitrate_descriptor.maximum_bitrate = (((pBuffer[cursor] << 16) | (pBuffer[cursor + 1] << 8) | (pBuffer[cursor + 2]))&0x3fffff) * 50 * 8; break; } #ifdef HAS_MULTIPROGRAM_TS case DESCRIPTOR_TYPE_ISO_639_LANGUAGE: { TS_CHECK_BOUNDS(4); for (uint8_t i = 0; i < 3; i++) descriptor.payload.iso_639_descriptor.language_code[i] = pBuffer[cursor + i]; descriptor.payload.iso_639_descriptor.audio_type = pBuffer[cursor + 3]; break; } #endif /* HAS_MULTIPROGRAM_TS */ default: break; } cursor += descriptor.length; return true; } #endif /* HAS_MEDIA_TS */
1,988
746
#include <iostream> #include "Line.h" #include "Rectangle.h" #include "Color.h" using namespace std; int main() { Point p1(1, 2); Point p2(3, 4); Line l1(p1, p2, RED); l1.setA(p2); l1.setB(Point(2, 3)); l1.print(); Rectangle rec(p1, 3, 4, BLUE); return 0; }
274
146
#include "common_mc.h" #ifndef KCLIB_OOP #include "kcCatScene_functional.h" #include "../ac_exe/ghidra_types_min.h" #include "kcFileInfo_functional.h" ///WARNING: This file is outdated compared to the OOP version "kcDoubleBuffer.cpp", /// which has more up to date refactoring and code //unsigned int * __thiscall kcMacroReader_initRun(void *this, char *param_1) ///FID:cs2_full_v401/system/scene/mc.exe: FUN_004119a0 kcCatScene * __thiscall kcCatScene_ctor(kcCatScene *this, IN const char *filename) { this->LineBuffer = nullptr; this->MemoryLines = nullptr; this->LineOffsets = nullptr; this->MemoryOffsets = nullptr; this->BufferSize = 0; this->LineCount = 0; this->MacUnk0 = 0; // ??? this->LastLineMultibyteContinue = FALSE; std::strcpy(&this->Filename[0], filename); kcCatScene_Read(this, filename); return this; } // undefined4 __thiscall kcCatScene_Read(int this,char *filename) ///FID:cs2_full_v401/system/scene/mc.exe: FUN_004114d0 BOOL __thiscall kcCatScene_Read(kcCatScene *this, IN const char *filename) { HGLOBAL hMemLines = nullptr; HGLOBAL hMemOffsets = nullptr; char *lineBuffer = nullptr; unsigned int *lineOffsets = nullptr; unsigned int lineCount = 0; // all this just to read fileSize... nice FILE_READER *fileinfo = (FILE_READER *)std::malloc(0x598);//_newalloc(0x598); if (fileinfo != nullptr) { fileinfo = (FILE_READER *)kcFileInfo_ctor(fileinfo, filename); } kcFileInfo_SetReadMode(fileinfo); unsigned int bufferSize = kcFileInfo_GetSize(fileinfo); if (fileinfo != nullptr) { kcFileInfo_scalar_dtor(fileinfo, 1); } // allocate MemoryLines and copy lines into buffer, // nullterminated with newlines and control chars removed if ((int)bufferSize > 0) { // the original source was likely a goto-failure control flow, // decompiled it's just layers upon layers of if statements, so it has been cleaned up bufferSize += 0x10; // extra space, for unknown reasons. Could be useful? *shrug* FILE *file = nullptr; // text file (mode "rt") //0x42 (GHND, GMEM_MOVEABLE | GMEM_ZEROINIT) hMemLines = ::GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT, bufferSize); if (hMemLines != nullptr) { lineBuffer = (char *)::GlobalLock(hMemLines); } if (lineBuffer != nullptr) { file = std::fopen(filename, "rt"); } // reading file (final 'if' in setup) if (file != nullptr) { int offset = 0; while (!std::feof(file) && std::fgets(&lineBuffer[offset], bufferSize - offset, file)) { // trim control chars from end of line (excluding whitespace) int length = (int)std::strlen(&lineBuffer[offset]); for (; length > 0; length--) { if ((unsigned int)lineBuffer[offset + length - 1] >= 0x20 || lineBuffer[offset + length - 1] == '\t') break; } lineBuffer[offset + length] = '\0'; offset += length + 1; // +1 for null-termination lineCount++; } // cleanup file std::fclose(file); } // cleanup if (lineBuffer != nullptr) { ::GlobalUnlock(hMemLines); } // done } // No lines in the file? That's a paddlin' (return FALSE) if (lineCount < 1) { if (hMemLines != nullptr) { ::GlobalFree(hMemLines); } return FALSE; } // allocate MemoryOffsets and add byte offsets of each line in MemoryLines (return TRUE) else //if (lineCount >= 1) { // the original source was likely a goto-failure control flow, // decompiled it's just layers upon layers of if statements, so it has been cleaned up this->LineCount = lineCount; this->BufferSize = bufferSize; this->MemoryLines = hMemLines; lineBuffer = nullptr; lineOffsets = nullptr; //0x42 (GHND, GMEM_MOVEABLE | GMEM_ZEROINIT) hMemOffsets = ::GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT, lineCount * sizeof(unsigned int)); if (hMemOffsets != nullptr) { lineBuffer = (char *)::GlobalLock(hMemLines); } if (lineBuffer != nullptr) { lineOffsets = (unsigned int *)::GlobalLock(hMemOffsets); } // reading file (final 'if' in setup) if (lineOffsets != nullptr) { // unsigned int offset = 0; for (unsigned int line = 0, offset = 0; line < this->LineCount; line++) { lineOffsets[line] = offset; offset += (unsigned int)std::strlen(&lineBuffer[offset]) + 1; // +1 for null-termination } ::GlobalUnlock(hMemOffsets); } // cleanup if (lineBuffer != nullptr) { ::GlobalUnlock(hMemLines); } // done this->MemoryOffsets = hMemOffsets; return TRUE; } } ///FID:cs2_full_v401/system/scene/mc.exe: FUN_00411410 BOOL __fastcall kcCatScene_LockBuffers(kcCatScene *this) { LPVOID pvVar1; undefined4 uVar2; if (this->LineBuffer == nullptr || this->LineOffsets == nullptr) // 0x8, 0xc { if (this->MemoryLines != nullptr) // 0x414 { this->LineBuffer = (char *)::GlobalLock(this->MemoryLines); // 0x8, 0x414 } if (this->MemoryOffsets != nullptr) // 0x418 { this->LineOffsets = (unsigned int *)::GlobalLock(this->MemoryOffsets); // 0xc, 0x418 } } if (this->LineBuffer == nullptr || this->LineOffsets == nullptr) // 0x8, 0xc { kcCatScene_UnlockBuffers(this); return FALSE; } return TRUE; } ///FID:cs2_full_v401/system/scene/mc.exe: FUN_004113b0 void __fastcall kcCatScene_UnlockBuffers(kcCatScene *this) { if (this->LineBuffer != nullptr) // 0x8 { ::GlobalUnlock(this->MemoryLines); // 0x414 this->LineBuffer = nullptr; // 0x8 } if (this->LineOffsets != nullptr) // 0xc { ::GlobalUnlock(this->MemoryOffsets); // 0x418 this->LineOffsets = nullptr; // 0xc } } ///FID:cs2_full_v401/system/scene/mc.exe: FUN_004114a0 BOOL __fastcall kcCatScene_IsLocked(kcCatScene *this) { undefined4 uVar1; if (this->LineBuffer == nullptr || this->LineOffsets == nullptr) { uVar1 = 0; } else { uVar1 = 1; } return uVar1; } ///FID:cs2_full_v401/system/scene/mc.exe: FUN_00411920 const char * __thiscall kcCatScene_GetLineAt(kcCatScene *this, int index) { int iVar1; // iVar1 = ; if (!kcCatScene_IsLocked(this)) return nullptr; // if ((index < 0) || (*(int *)(this + 4) <= index)) if (index < 0 || index >= this->LineCount) return nullptr; return &this->LineBuffer[this->LineOffsets[index]]; // iVar1 = *(int *)(this + 8) + *(int *)(*(int *)(this + 0xc) + index * 4); } ///FID:cs2_full_v401/system/scene/mc.exe: FUN_00411970 BOOL __thiscall kcCatScene_HasLineAt(kcCatScene *this, int index) { // int iVar1; // iVar1 = kcCatScene_GetLineAt(this, index); // return (BOOL)(iVar1 != 0); return (BOOL)(kcCatScene_GetLineAt(this, index) != nullptr); } ///FLAG: ALLOW_LINE_CONTINUE 0x1 ///FID:cs2_full_v401/system/scene/mc.exe: FUN_00411a30 unsigned int __thiscall kcCatScene_CopyLineAt(kcCatScene *this, OUT char *outBuffer, int bufferSize, IN OUT int *inoutIndex, unsigned int flags) { int index = *inoutIndex; char *out_ptr = outBuffer; bool lineContinued = false; while (true) { if (false) // probably a preprocessor flag (that's changed based on the needs of a specific script type) break; const char *line_ptr = kcCatScene_GetLineAt(this, index); if (line_ptr == nullptr) break; // no more lines, finish index++; // increment index (moved up for visibility) if (this->LastLineMultibyteContinue != FALSE) { this->LastLineMultibyteContinue = FALSE; // only set back to false if a line at index exists } //TRIM: when continuing, trim (skip) control chars and whitespace from start of line while (lineContinued && line_ptr[0] != '\0' && (unsigned char)line_ptr[0] <= 0x20) // '\0', 0x21 { line_ptr++; } //COPY: copy current line into buffer int line_len = (int)std::strlen(line_ptr); if (line_len >= bufferSize) { std::memcpy(out_ptr, line_ptr, bufferSize - 1U); out_ptr += (bufferSize - 1U); // lineEnd = out_ptr + (bufferSize - 1U); break; // end of buffer reached, finish here } std::memcpy(out_ptr, line_ptr, line_len); ///FIXME: Buffer size subtraction doesn't account for -1 from skipping '\\' (non-fatal, minor issue) bufferSize -= line_len; //CONTINUE?: some flags (it's that "allow line comment/continue?" flag again!) if ((flags & 1) == 0 || line_len < 1 || out_ptr[line_len - 1] != '\\') break; // no line continuation, finish //CHECK: A VERY rudimentary scan of multibyte characters in the line to see if // the final '\\' isn't actually part of a double-byte Shift_JIS character. int i, char_width; for (i = 0, char_width = 0; i + 1 < line_len; i += char_width) // while (line_len >= 2) { if ((unsigned char)out_ptr[i] >= 0x80) char_width = 2; else char_width = 1; } if (i == line_len && char_width == 2 && out_ptr[i - 1] == '\\') // 0x5c { this->LastLineMultibyteContinue = TRUE; // *(unk4 *)0x10 = 1 break; // multi-byte ending in '\\' (0x5c) not a line continuation } //NEXT: normal line continuation, keep going and copy next line lineContinued = true; out_ptr += line_len - 1; // -1 to overwrite (ignore) '\\' line continuation char } *inoutIndex = index; out_ptr[0] = '\0'; // null-terminate ///PTRMATH: string distance return (unsigned int)(out_ptr - outBuffer); } #endif
10,450
3,557
#include "granada/util/application.h" namespace granada{ namespace util{ namespace application{ const std::string& get_selfpath(){ if (selfpath.empty()){ #ifdef __APPLE__ int ret; pid_t pid; char pathbuf[PROC_PIDPATHINFO_MAXSIZE]; pid = getpid(); ret = proc_pidpath (pid, pathbuf, sizeof(pathbuf)); if ( ret > 0 ) { std::string totalPath = std::string(pathbuf); selfpath = totalPath.substr(0,totalPath.find_last_of("/")); } #elif _WIN32 std::vector<wchar_t> pathBuf; DWORD copied = 0; do { pathBuf.resize(pathBuf.size() + MAX_PATH); copied = GetModuleFileName(0, (PWSTR)&pathBuf.at(0), pathBuf.size()); } while (copied >= pathBuf.size()); pathBuf.resize(copied); selfpath = utility::conversions::to_utf8string(std::wstring(pathBuf.begin(), pathBuf.end())); selfpath = selfpath.substr(0, selfpath.find_last_of("\\")); #else char buff[PATH_MAX]; ssize_t len = ::readlink("/proc/self/exe", buff, sizeof(buff)-1); if (len != -1) { buff[len] = '\0'; std::string totalPath = std::string(buff); selfpath = totalPath.substr(0,totalPath.find_last_of("/")); } #endif } return selfpath; } const std::string GetProperty(const std::string& name){ if (property_file_ == NULL){ std::string configuration_file_path = get_selfpath() + "/server.conf"; property_file_ = std::unique_ptr<granada::util::file::PropertyFile>(new granada::util::file::PropertyFile(configuration_file_path)); } return property_file_->GetProperty(name); } } } }
1,750
643
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/apps/app_service/fake_lacros_web_apps_host.h" #include <utility> #include <vector> #include "base/notreached.h" #include "chromeos/lacros/lacros_service.h" #include "components/services/app_service/public/mojom/types.mojom.h" #include "mojo/public/cpp/bindings/remote.h" namespace { // Test push one test app. void PushOneApp() { auto* service = chromeos::LacrosService::Get(); std::vector<apps::mojom::AppPtr> apps; apps::mojom::AppPtr app = apps::mojom::App::New(); app->app_type = apps::mojom::AppType::kWeb; app->app_id = "abcdefg"; app->readiness = apps::mojom::Readiness::kReady; app->name = "lacros test name"; app->short_name = "lacros test name"; app->last_launch_time = base::Time(); app->install_time = base::Time(); app->install_source = apps::mojom::InstallSource::kUser; app->is_platform_app = apps::mojom::OptionalBool::kFalse; app->recommendable = apps::mojom::OptionalBool::kTrue; app->searchable = apps::mojom::OptionalBool::kTrue; app->paused = apps::mojom::OptionalBool::kFalse; app->show_in_launcher = apps::mojom::OptionalBool::kTrue; app->show_in_shelf = apps::mojom::OptionalBool::kTrue; app->show_in_search = apps::mojom::OptionalBool::kTrue; app->show_in_management = apps::mojom::OptionalBool::kTrue; apps.push_back(std::move(app)); service->GetRemote<crosapi::mojom::AppPublisher>()->OnApps(std::move(apps)); } // Test push one test capability_access. void PushOneCapabilityAccess() { auto* service = chromeos::LacrosService::Get(); std::vector<apps::mojom::CapabilityAccessPtr> capability_accesses; apps::mojom::CapabilityAccessPtr capability_access = apps::mojom::CapabilityAccess::New(); capability_access->app_id = "abcdefg"; capability_access->camera = apps::mojom::OptionalBool::kTrue; capability_access->microphone = apps::mojom::OptionalBool::kFalse; capability_accesses.push_back(std::move(capability_access)); service->GetRemote<crosapi::mojom::AppPublisher>()->OnCapabilityAccesses( std::move(capability_accesses)); } } // namespace namespace apps { FakeLacrosWebAppsHost::FakeLacrosWebAppsHost() {} FakeLacrosWebAppsHost::~FakeLacrosWebAppsHost() = default; void FakeLacrosWebAppsHost::Init() { auto* service = chromeos::LacrosService::Get(); if (!service) { return; } if (!service->IsAvailable<crosapi::mojom::AppPublisher>()) return; if (service->init_params()->web_apps_enabled) { service->GetRemote<crosapi::mojom::AppPublisher>()->RegisterAppController( receiver_.BindNewPipeAndPassRemote()); PushOneApp(); PushOneCapabilityAccess(); } } void FakeLacrosWebAppsHost::Uninstall( const std::string& app_id, apps::mojom::UninstallSource uninstall_source, bool clear_site_data, bool report_abuse) { NOTIMPLEMENTED(); } void FakeLacrosWebAppsHost::PauseApp(const std::string& app_id) { NOTIMPLEMENTED(); } void FakeLacrosWebAppsHost::UnpauseApp(const std::string& app_id) { NOTIMPLEMENTED(); } } // namespace apps
3,202
1,174
/* Winamp plugin interface for vgmstream */ /* Based on: */ /* ** Example Winamp .RAW input plug-in ** Copyright (c) 1998, Justin Frankel/Nullsoft Inc. */ #ifdef _MSC_VER #define _CRT_SECURE_NO_DEPRECATE #endif #include <windows.h> #include <windowsx.h> #include <commctrl.h> #include <stdio.h> #include <io.h> #include <foobar2000.h> #include <helpers.h> #include <shared.h> extern "C" { #include "../src/vgmstream.h" #include "../src/util.h" } #include "foo_vgmstream.h" #ifndef VERSION #define VERSION #endif #define APP_NAME "vgmstream plugin" #define PLUGIN_DESCRIPTION "vgmstream plugin " VERSION " " __DATE__ #define PLUGIN_VERSION VERSION " " __DATE__ #define INI_NAME "plugin.ini" #define DECODE_SIZE 1024 /* format detection and VGMSTREAM setup, uses default parameters */ VGMSTREAM * init_vgmstream_foo(const char * const filename, abort_callback & p_abort) { VGMSTREAM *vgmstream = NULL; STREAMFILE *streamFile = open_foo_streamfile(filename, &p_abort); if (streamFile) { vgmstream = init_vgmstream_from_STREAMFILE(streamFile); close_streamfile(streamFile); } return vgmstream; } class input_vgmstream { public: void open(service_ptr_t<file> p_filehint,const char * p_path,t_input_open_reason p_reason,abort_callback & p_abort) { currentreason = p_reason; if(p_path) strcpy(filename, p_path); switch(p_reason) { case input_open_decode: vgmstream = init_vgmstream_foo(p_path, p_abort); /* were we able to open it? */ if (!vgmstream) { return; } if (ignore_loop) vgmstream->loop_flag = 0; /* will we be able to play it? */ if (vgmstream->channels <= 0) { close_vgmstream(vgmstream); vgmstream=NULL; return; } decode_abort = 0; seek_needed_samples = -1; decode_pos_ms = 0; decode_pos_samples = 0; paused = 0; stream_length_samples = get_vgmstream_play_samples(loop_count,fade_seconds,fade_delay_seconds,vgmstream); fade_samples = (int)(fade_seconds * vgmstream->sample_rate); break; case input_open_info_read: break; case input_open_info_write: //cant write...ever break; default: break; } } void get_info(file_info & p_info,abort_callback & p_abort ) { int length_in_ms=0, channels = 0, samplerate = 0; char title[256]; getfileinfo(filename, title, &length_in_ms, &samplerate, &channels, p_abort); p_info.info_set_int("samplerate", samplerate); p_info.info_set_int("channels", channels); p_info.info_set_int("bitspersample",16); p_info.info_set("encoding","lossless"); p_info.info_set_bitrate(16); p_info.set_length(((double)length_in_ms)/1000); } void decode_initialize(unsigned p_flags,abort_callback & p_abort) { }; bool decode_run(audio_chunk & p_chunk,abort_callback & p_abort) { int l = 0, samples_to_do = DECODE_SIZE, t= 0; if(vgmstream && (seek_needed_samples == -1 )) { if (decode_pos_samples+DECODE_SIZE>stream_length_samples && (!loop_forever || !vgmstream->loop_flag)) samples_to_do=stream_length_samples-decode_pos_samples; else samples_to_do=DECODE_SIZE; l = (samples_to_do*vgmstream->channels*2); if (samples_to_do /*< DECODE_SIZE*/ == 0) { return false; } t = ((test_length*vgmstream->sample_rate)/1000); render_vgmstream(sample_buffer,samples_to_do,vgmstream); /* fade! */ if (vgmstream->loop_flag && fade_samples > 0 && !loop_forever) { int samples_into_fade = decode_pos_samples - (stream_length_samples - fade_samples); if (samples_into_fade + samples_to_do > 0) { int j,k; for (j=0;j<samples_to_do;j++,samples_into_fade++) { if (samples_into_fade > 0) { double fadedness = (double)(fade_samples-samples_into_fade)/fade_samples; for (k=0;k<vgmstream->channels;k++) { sample_buffer[j*vgmstream->channels+k] = (short)(sample_buffer[j*vgmstream->channels+k]*fadedness); } } } } } p_chunk.set_data_fixedpoint((char*)sample_buffer, l, vgmstream->sample_rate,vgmstream->channels,16,audio_chunk::g_guess_channel_config(vgmstream->channels)); decode_pos_samples+=samples_to_do; decode_pos_ms=decode_pos_samples*1000LL/vgmstream->sample_rate; return true; } return false; } void decode_seek(double p_seconds,abort_callback & p_abort) { } input_vgmstream() { vgmstream = NULL; decode_thread_handle = INVALID_HANDLE_VALUE; paused = 0; decode_abort = 0; seek_needed_samples = -1; decode_pos_ms = 0; decode_pos_samples = 0; stream_length_samples = 0; fade_samples = 0; fade_seconds = 10.0f; fade_delay_seconds = 0.0f; loop_count = 2.0f; thread_priority = 3; loop_forever = 0; ignore_loop = 0; } ~input_vgmstream() { } t_filestats get_file_stats(abort_callback & p_abort) { t_filestats t; return t; } bool decode_can_seek() {return false;} /*not implemented yet*/ bool decode_get_dynamic_info(file_info & p_out, double & p_timestamp_delta) { //do we need anything else 'cept the samplrate return true; } bool decode_get_dynamic_info_track(file_info & p_out, double & p_timestamp_delta) {return false;} void decode_on_idle(abort_callback & p_abort) {/*m_file->on_idle(p_abort);*/} void retag(const file_info & p_info,abort_callback & p_abort) {}; static bool g_is_our_content_type(const char * p_content_type) {return false;} static bool g_is_our_path(const char * p_path,const char * p_extension) { if(!stricmp_utf8(p_extension,"adx")) return 1; if(!stricmp_utf8(p_extension,"afc")) return 1; if(!stricmp_utf8(p_extension,"agsc")) return 1; if(!stricmp_utf8(p_extension,"ast")) return 1; if(!stricmp_utf8(p_extension,"brstm")) return 1; if(!stricmp_utf8(p_extension,"brstmspm")) return 1; if(!stricmp_utf8(p_extension,"hps")) return 1; if(!stricmp_utf8(p_extension,"strm")) return 1; if(!stricmp_utf8(p_extension,"adp")) return 1; if(!stricmp_utf8(p_extension,"rsf")) return 1; if(!stricmp_utf8(p_extension,"dsp")) return 1; if(!stricmp_utf8(p_extension,"gcw")) return 1; if(!stricmp_utf8(p_extension,"ads")) return 1; if(!stricmp_utf8(p_extension,"ss2")) return 1; if(!stricmp_utf8(p_extension,"npsf")) return 1; if(!stricmp_utf8(p_extension,"rwsd")) return 1; if(!stricmp_utf8(p_extension,"xa")) return 1; if(!stricmp_utf8(p_extension,"rxw")) return 1; if(!stricmp_utf8(p_extension,"int")) return 1; if(!stricmp_utf8(p_extension,"sts")) return 1; if(!stricmp_utf8(p_extension,"svag")) return 1; if(!stricmp_utf8(p_extension,"mib")) return 1; if(!stricmp_utf8(p_extension,"mi4")) return 1; if(!stricmp_utf8(p_extension,"mpdsp")) return 1; if(!stricmp_utf8(p_extension,"mic")) return 1; if(!stricmp_utf8(p_extension,"gcm")) return 1; if(!stricmp_utf8(p_extension,"mss")) return 1; if(!stricmp_utf8(p_extension,"raw")) return 1; if(!stricmp_utf8(p_extension,"vag")) return 1; if(!stricmp_utf8(p_extension,"gms")) return 1; if(!stricmp_utf8(p_extension,"str")) return 1; if(!stricmp_utf8(p_extension,"ild")) return 1; if(!stricmp_utf8(p_extension,"pnb")) return 1; if(!stricmp_utf8(p_extension,"wavm")) return 1; if(!stricmp_utf8(p_extension,"xwav")) return 1; if(!stricmp_utf8(p_extension,"wp2")) return 1; if(!stricmp_utf8(p_extension,"pnb")) return 1; if(!stricmp_utf8(p_extension,"str")) return 1; if(!stricmp_utf8(p_extension,"sng")) return 1; if(!stricmp_utf8(p_extension,"asf")) return 1; if(!stricmp_utf8(p_extension,"eam")) return 1; if(!stricmp_utf8(p_extension,"cfn")) return 1; if(!stricmp_utf8(p_extension,"vpk")) return 1; if(!stricmp_utf8(p_extension,"genh")) return 1; return 0; } public: service_ptr_t<file> m_file; char filename[260]; t_input_open_reason currentreason; VGMSTREAM * vgmstream; HANDLE decode_thread_handle; int paused; int decode_abort; int seek_needed_samples; int decode_pos_ms; int decode_pos_samples; int stream_length_samples; int fade_samples; int test_length; double fade_seconds; double fade_delay_seconds; double loop_count; int thread_priority; int loop_forever; int ignore_loop; short sample_buffer[576*2*2]; /* 576 16-bit samples, stereo, possibly doubled in size for DSP */ void getfileinfo(char *filename, char *title, int *length_in_ms, int *sample_rate, int *channels, abort_callback & p_abort); }; /* retrieve information on this or possibly another file */ void input_vgmstream::getfileinfo(char *filename, char *title, int *length_in_ms, int *sample_rate, int *channels, abort_callback & p_abort) { VGMSTREAM * infostream; if (length_in_ms) { *length_in_ms=-1000; if ((infostream=init_vgmstream_foo(filename, p_abort))) { *length_in_ms = get_vgmstream_play_samples(loop_count,fade_seconds,fade_delay_seconds,infostream)*1000LL/infostream->sample_rate; test_length = *length_in_ms; *sample_rate = infostream->sample_rate; *channels = infostream->channels; close_vgmstream(infostream); infostream=NULL; } } if (title) { char *p=filename+strlen(filename); while (*p != '\\' && p >= filename) p--; strcpy(title,++p); } } static input_singletrack_factory_t<input_vgmstream> g_input_vgmstream_factory; DECLARE_COMPONENT_VERSION(APP_NAME,PLUGIN_VERSION,PLUGIN_DESCRIPTION); DECLARE_MULTIPLE_FILE_TYPE("ADX Audio File (*.ADX)", adx); DECLARE_MULTIPLE_FILE_TYPE("AFC Audio File (*.AFC)", afc); DECLARE_MULTIPLE_FILE_TYPE("AGSC Audio File (*.AGSC)", agsc); DECLARE_MULTIPLE_FILE_TYPE("AST Audio File (*.AST)", ast); DECLARE_MULTIPLE_FILE_TYPE("BRSTM Audio File (*.BRSTM)", brstm); DECLARE_MULTIPLE_FILE_TYPE("BRSTM Audio File (*.BRSTMSPM)", brstmspm); DECLARE_MULTIPLE_FILE_TYPE("HALPST Audio File (*.HPS)", hps); DECLARE_MULTIPLE_FILE_TYPE("STRM Audio File (*.STRM)", strm); DECLARE_MULTIPLE_FILE_TYPE("ADP Audio File (*.ADP)", adp); DECLARE_MULTIPLE_FILE_TYPE("RSF Audio File (*.RSF)", rsf); DECLARE_MULTIPLE_FILE_TYPE("DSP Audio File (*.DSP)", dsp); DECLARE_MULTIPLE_FILE_TYPE("GCW Audio File (*.GCW)", gcw); DECLARE_MULTIPLE_FILE_TYPE("PS2 ADS Audio File (*.ADS)", ads); DECLARE_MULTIPLE_FILE_TYPE("PS2 SS2 Audio File (*.SS2)", ss2); DECLARE_MULTIPLE_FILE_TYPE("PS2 NPSF Audio File (*.NPSF)", npsf); DECLARE_MULTIPLE_FILE_TYPE("RWSD Audio File (*.RWSD)", rwsd); DECLARE_MULTIPLE_FILE_TYPE("PSX CD-XA File (*.XA)", xa); DECLARE_MULTIPLE_FILE_TYPE("PS2 RXWS File (*.RXW)", rxw); DECLARE_MULTIPLE_FILE_TYPE("PS2 RAW Interleaved PCM (*.INT)", int); DECLARE_MULTIPLE_FILE_TYPE("PS2 EXST Audio File (*.STS)", sts); DECLARE_MULTIPLE_FILE_TYPE("PS2 SVAG Audio File (*.SVAG)", svag); DECLARE_MULTIPLE_FILE_TYPE("PS2 MIB Audio File (*.MIB)", mib); DECLARE_MULTIPLE_FILE_TYPE("PS2 MI4 Audio File (*.MI4)", mi4); DECLARE_MULTIPLE_FILE_TYPE("MPDSP Audio File (*.MPDSP)", mpdsp); DECLARE_MULTIPLE_FILE_TYPE("PS2 MIC Audio File (*.MIC)", mic); DECLARE_MULTIPLE_FILE_TYPE("GCM Audio File (*.GCM)", gcm); DECLARE_MULTIPLE_FILE_TYPE("MSS Audio File (*.MSS)", mss); DECLARE_MULTIPLE_FILE_TYPE("RAW Audio File (*.RAW)", raw); DECLARE_MULTIPLE_FILE_TYPE("VAG Audio File (*.VAG)", vag); DECLARE_MULTIPLE_FILE_TYPE("GMS Audio File (*.GMS)", gms); DECLARE_MULTIPLE_FILE_TYPE("STR Audio File (*.STR)", str);
12,171
4,911
// Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at // the Lawrence Livermore National Laboratory. LLNL-CODE-734707. All Rights // reserved. See files LICENSE and NOTICE for details. // // This file is part of CEED, a collection of benchmarks, miniapps, software // libraries and APIs for efficient high-order finite element and spectral // element discretizations for exascale applications. For more information and // source code availability see http://github.com/ceed. // // The CEED research is supported by the Exascale Computing Project (17-SC-20-SC) // a collaborative effort of two U.S. Department of Energy organizations (Office // of Science and the National Nuclear Security Administration) responsible for // the planning and preparation of a capable exascale ecosystem, including // software, applications, hardware, advanced system engineering and early // testbed platforms, in support of the nation's exascale computing imperative. #include "laghos_assembly.hpp" #ifdef MFEM_USE_MPI using namespace std; namespace mfem { namespace hydrodynamics { QuadratureData::QuadratureData(int dim, int nzones, int nqp) { Setup(dim, nzones, nqp); } void QuadratureData::Setup(int dim, int nzones, int nqp) { rho0DetJ0w.SetSize(nqp * nzones); stressJinvT.SetSize(dim * dim * nqp * nzones); dtEst.SetSize(nqp * nzones); } void DensityIntegrator::AssembleRHSElementVect(const FiniteElement &fe, ElementTransformation &Tr, Vector &elvect) { const int ip_cnt = integ_rule.GetNPoints(); Vector shape(fe.GetDof()); Vector rho0DetJ0w = quad_data.rho0DetJ0w; elvect.SetSize(fe.GetDof()); elvect = 0.0; for (int q = 0; q < ip_cnt; q++) { fe.CalcShape(integ_rule.IntPoint(q), shape); shape *= rho0DetJ0w(Tr.ElementNo*ip_cnt + q); elvect += shape; } } // ***************************************************************************** CudaMassOperator::CudaMassOperator(CudaFiniteElementSpace &fes_, const IntegrationRule &integ_rule_, QuadratureData *quad_data_) : CudaOperator(fes_.GetTrueVSize()), fes(fes_), integ_rule(integ_rule_), ess_tdofs_count(0), bilinearForm(&fes), quad_data(quad_data_), x_gf(fes), y_gf(fes) {} // ***************************************************************************** CudaMassOperator::~CudaMassOperator() { } // ***************************************************************************** void CudaMassOperator::Setup() { dim=fes.GetMesh()->Dimension(); nzones=fes.GetMesh()->GetNE(); CudaMassIntegrator &massInteg = *(new CudaMassIntegrator()); massInteg.SetIntegrationRule(integ_rule); massInteg.SetOperator(quad_data->rho0DetJ0w); bilinearForm.AddDomainIntegrator(&massInteg); bilinearForm.Assemble(); bilinearForm.FormOperator(Array<int>(), massOperator); } // ************************************************************************* void CudaMassOperator::SetEssentialTrueDofs(Array<int> &dofs) { ess_tdofs_count = dofs.Size(); if (ess_tdofs.Size()==0) { #ifdef MFEM_USE_MPI int global_ess_tdofs_count; const MPI_Comm comm = fes.GetParMesh()->GetComm(); MPI_Allreduce(&ess_tdofs_count,&global_ess_tdofs_count, 1, MPI_INT, MPI_SUM, comm); assert(global_ess_tdofs_count>0); ess_tdofs.allocate(global_ess_tdofs_count); #else assert(ess_tdofs_count>0); ess_tdofs.allocate(ess_tdofs_count); #endif } else { assert(ess_tdofs_count<=ess_tdofs.Size()); } assert(ess_tdofs.ptr()); if (ess_tdofs_count == 0) { return; } assert(ess_tdofs_count>0); assert(dofs.GetData()); rHtoD(ess_tdofs.ptr(),dofs.GetData(),ess_tdofs_count*sizeof(int)); } // ***************************************************************************** void CudaMassOperator::EliminateRHS(CudaVector &b) { if (ess_tdofs_count > 0) { b.SetSubVector(ess_tdofs, 0.0, ess_tdofs_count); } } // ************************************************************************* void CudaMassOperator::Mult(const CudaVector &x, CudaVector &y) const { distX = x; if (ess_tdofs_count) { distX.SetSubVector(ess_tdofs, 0.0, ess_tdofs_count); } massOperator->Mult(distX, y); if (ess_tdofs_count) { y.SetSubVector(ess_tdofs, 0.0, ess_tdofs_count); } } // ***************************************************************************** // * CudaForceOperator // ***************************************************************************** CudaForceOperator::CudaForceOperator(CudaFiniteElementSpace &h1fes_, CudaFiniteElementSpace &l2fes_, const IntegrationRule &integ_rule_, const QuadratureData *quad_data_) : CudaOperator(l2fes_.GetTrueVSize(), h1fes_.GetTrueVSize()), dim(h1fes_.GetMesh()->Dimension()), nzones(h1fes_.GetMesh()->GetNE()), h1fes(h1fes_), l2fes(l2fes_), integ_rule(integ_rule_), quad_data(quad_data_), gVecL2(l2fes.GetLocalDofs() * nzones), gVecH1(h1fes.GetVDim() * h1fes.GetLocalDofs() * nzones) { } // ***************************************************************************** CudaForceOperator::~CudaForceOperator() {} // ************************************************************************* void CudaForceOperator::Setup() { h1D2Q = CudaDofQuadMaps::Get(h1fes, integ_rule); l2D2Q = CudaDofQuadMaps::Get(l2fes, integ_rule); } // ************************************************************************* void CudaForceOperator::Mult(const CudaVector &vecL2, CudaVector &vecH1) const { l2fes.GlobalToLocal(vecL2, gVecL2); const int NUM_DOFS_1D = h1fes.GetFE(0)->GetOrder()+1; const IntegrationRule &ir1D = IntRules.Get(Geometry::SEGMENT, integ_rule.GetOrder()); const int NUM_QUAD_1D = ir1D.GetNPoints(); const int L2_DOFS_1D = l2fes.GetFE(0)->GetOrder()+1; const int H1_DOFS_1D = h1fes.GetFE(0)->GetOrder()+1; if (rconfig::Get().Share()) rForceMultS(dim, NUM_DOFS_1D, NUM_QUAD_1D, L2_DOFS_1D, H1_DOFS_1D, nzones, l2D2Q->dofToQuad, h1D2Q->quadToDof, h1D2Q->quadToDofD, quad_data->stressJinvT, gVecL2, gVecH1); else rForceMult(dim, NUM_DOFS_1D, NUM_QUAD_1D, L2_DOFS_1D, H1_DOFS_1D, nzones, l2D2Q->dofToQuad, h1D2Q->quadToDof, h1D2Q->quadToDofD, quad_data->stressJinvT, gVecL2, gVecH1); h1fes.LocalToGlobal(gVecH1, vecH1); } // ************************************************************************* void CudaForceOperator::MultTranspose(const CudaVector &vecH1, CudaVector &vecL2) const { h1fes.GlobalToLocal(vecH1, gVecH1); const int NUM_DOFS_1D = h1fes.GetFE(0)->GetOrder()+1; const IntegrationRule &ir1D = IntRules.Get(Geometry::SEGMENT, integ_rule.GetOrder()); const int NUM_QUAD_1D = ir1D.GetNPoints(); const int L2_DOFS_1D = l2fes.GetFE(0)->GetOrder()+1; const int H1_DOFS_1D = h1fes.GetFE(0)->GetOrder()+1; if (rconfig::Get().Share()) rForceMultTransposeS(dim, NUM_DOFS_1D, NUM_QUAD_1D, L2_DOFS_1D, H1_DOFS_1D, nzones, l2D2Q->quadToDof, h1D2Q->dofToQuad, h1D2Q->dofToQuadD, quad_data->stressJinvT, gVecH1, gVecL2); else rForceMultTranspose(dim, NUM_DOFS_1D, NUM_QUAD_1D, L2_DOFS_1D, H1_DOFS_1D, nzones, l2D2Q->quadToDof, h1D2Q->dofToQuad, h1D2Q->dofToQuadD, quad_data->stressJinvT, gVecH1, gVecL2); l2fes.LocalToGlobal(gVecL2, vecL2); } } // namespace hydrodynamics } // namespace mfem #endif // MFEM_USE_MPI
8,867
2,984
// Copyright 2004-present Facebook. All Rights Reserved. #include "ABI26_0_0PrivateDataBase.h" namespace facebook { namespace ReactABI26_0_0 { PrivateDataBase::~PrivateDataBase() {} } }
190
71
#include "stdafx.h" #include "fv2id.h" #include <string.h> char* strtokf(char*, const char*, char**); unsigned short fv2id(char *fpav) { for (int i = 0; i < FonSk; i++) if (strcmp(fpav, FonV[i].fv) == 0) return FonV[i].id; return FonV[0].id; //pauze "_" } char* id2fv(unsigned short id) { for (int i = 0; i < FonSk; i++) if (id == FonV[i].id) return FonV[i].fv; return FonV[0].fv; //pauze "_" } int trText2UnitList(char *TrSakinys, unsigned short *units, unsigned short *unitseparators) { char temp[500], *pos, *newpos; //turetu pakakti 480 strcpy(temp, TrSakinys); int i = 0; pos = strtokf(temp, "+- ", &newpos); while (pos != NULL) { units[i] = fv2id(pos); pos = strtokf(NULL, "+- ", &newpos); if (pos == NULL) unitseparators[i] = '+'; else unitseparators[i] = TrSakinys[pos - temp - 1]; i++; } return i; }
849
414
#include ZZ_Prelude_hh #include "PArr.hh" #include <vector> #include <memory> using namespace ZZ; //mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm struct MyInt { uint n; uint waste[15]; MyInt(uint n = 0) : n(n) {} operator uint() const { return n; } }; int main(int argc, char** argv) { ZZ_Init; #if 0 // Simple test: PArr<int> arr; arr = arr.push(1); arr = arr.push(2); arr = arr.push(3); PArr<int> arr2 = arr.pop(); Dump(arr); Dump(arr2); arr2 = arr2.set(100, 42); Dump(arr2); wr("numbers:"); arr2.enumAll([](uind idx, int n){ wr(" %_=%_", idx, n); return true; }); newLn(); #endif #if 0 // Correctness test: uint64 seed = 0; #if 0 Vec<PArr<int>> arrs(10); #else Vec<vector<int>> arrs(10, vector<int>(30)); #endif for (uint n = 0; n < 1000000; n++){ uint i = irand(seed, arrs.size()); uint j = irand(seed, 30); uint v = irand(seed, 10000 - 1000) + 1000; //**/wrLn("arrs[%_].set(%_, %_)", i, j, v); #if 0 arrs[i] = arrs[i].set(j, v); #else arrs[i][j] = v; #endif //**/wr(" -> "); arrs[i].dump(); newLn(); if (n % 1000 == 0){ uint i0 = irand(seed, arrs.size()); uint i1 = irand(seed, arrs.size()); arrs[i0] = arrs[i1]; } } wrLn("%\n_", arrs); #endif #if 0 uint64 seed = 0; Vec<PArr<MyInt, 8, 2>> arrs(10); // Speed test: uint N = 1000000; uint sz = 30000; double T0 = realTime(); for (uint n = 0; n < N; n++){ uint i = irand(seed, arrs.size()); uint j = irand(seed, sz); uint v = irand(seed, 10000 - 1000) + 1000; arrs[i] = arrs[i].set(j, v); if (n % 1000 == 0){ uint i0 = irand(seed, arrs.size()); uint i1 = irand(seed, arrs.size()); arrs[i0] = arrs[i1]; } } double T1 = realTime(); wrLn("Cycles/write: %_", (T1-T0) / N * 2.4e9); #endif // Iteration speed test: uint N = 10000; PArr<MyInt,4> arr; for (uint i = 0; i < 20; i++) arr = arr.push(i); { double T0 = realTime(); uint64 sum = 0; for (uint n = 0; n < N; n++){ for (uint i = 0; i < arr.size(); i++) sum += arr[i]; } double T1 = realTime(); wrLn("LOOP: sum=%_ time=%t (%.0f cycles)", sum, (T1-T0) / N, (T1-T0) / N * 2.4e9); } { double T0 = realTime(); uint64 sum = 0; for (uint n = 0; n < N; n++){ arr.forAllCondRev([&](MyInt const& v) { sum += v; return true; }); } double T1 = realTime(); wrLn("ITER: sum=%_ time=%t (%.0f cycles)", sum, (T1-T0) / N, (T1-T0) / N * 2.4e9); } return 0; } /* [1195, 8025, 2330, 6909, 6214, 9379, 9308, 8788, 6198, 4952, 1802, 1087, 2321, 4546, 8536, 4030, 8695, 5455, 8509, 4664, 7999, 1533, 6433, 2418, 1532, 7387, 5372, 7431, 6036, 1711] [4240, 6760, 7950, 3579, 8589, 4009, 4333, 6233, 4888, 2592, 3177, 4712, 2216, 2231, 8506, 8830, 3885, 4125, 1849, 3144, 6444, 1598, 4723, 8338, 5192, 5247, 5897, 1121, 5161, 2486] [6340, 1005, 2170, 1384, 8589, 4094, 5023, 7018, 2393, 2592, 2692, 6242, 9446, 5686, 8506, 9150, 3390, 7975, 5414, 3144, 4494, 9868, 8118, 6838, 5192, 4592, 5272, 5721, 3096, 2486] [4960, 8950, 6005, 9649, 5194, 2984, 3743, 6043, 8173, 9317, 7917, 1697, 5041, 5531, 4526, 1140, 9185, 9435, 5454, 7469, 7579, 4693, 4933, 9068, 2067, 8467, 2997, 3251, 1281, 7426] [9030, 5110, 5550, 3409, 2909, 8284, 5978, 1398, 5088, 4952, 4547, 9207, 9046, 9296, 1256, 9580, 5650, 5710, 9434, 9224, 7044, 3608, 2148, 8418, 5637, 9242, 7357, 1721, 5256, 4016] [3940, 7485, 5575, 6754, 5044, 5739, 7138, 6693, 1053, 2162, 3827, 8352, 2326, 2851, 8001, 1225, 4220, 8410, 9444, 9059, 1129, 1023, 1913, 3618, 9047, 5147, 6047, 3556, 6601, 3261] [2985, 5480, 5640, 8119, 9344, 1814, 6538, 7908, 8088, 1667, 8417, 5317, 7841, 5341, 5726, 4895, 9170, 1285, 1214, 6434, 2349, 4898, 4978, 1773, 8462, 2637, 5712, 5256, 1516, 5826] [6585, 1125, 2105, 3629, 1579, 8169, 7858, 4408, 3173, 9277, 8087, 9712, 9541, 9271, 7776, 1260, 5275, 7905, 9459, 5024, 9349, 6183, 8963, 9993, 2837, 4602, 1357, 1581, 2661, 3931] [1775, 8070, 9145, 4074, 4729, 3974, 8663, 1203, 1158, 2632, 8697, 8402, 1336, 1916, 4556, 5855, 2115, 5275, 1069, 3439, 3709, 8618, 5438, 3203, 4137, 8992, 2742, 9881, 7821, 7611] [4960, 4425, 1625, 6909, 1364, 2984, 1343, 4713, 6198, 8852, 7917, 9827, 1441, 4546, 1831, 1140, 7655, 8180, 8509, 2579, 7579, 9238, 7268, 2418, 1222, 8467, 5837, 2051, 6036, 6851] */
4,712
3,092
#include "timer.hpp" #include <iostream> #include <thread> #include <chrono> #include <cmath> TimerSet::TimerSet(int maximumFPS) : currentTime(std::chrono::system_clock::duration::zero()), maxFPS(maximumFPS) { startTimer(); time = 0; deltaTime = 0; FPS = 0; frameCounter = 0; } void TimerSet::startTimer() { startTime = std::chrono::high_resolution_clock::now(); prevTime = startTime; //std::this_thread::sleep_for(std::chrono::microseconds(1000)); // Avoids deltaTime == 0 (i.e. currentTime == lastTime) } void TimerSet::computeDeltaTime() { // Get deltaTime currentTime = std::chrono::high_resolution_clock::now(); //time = std::chrono::duration_cast<std::chrono::microseconds>(currentTime - startTime).count() / 1000000.l; //time = std::chrono::duration<float, std::chrono::seconds::period>(currentTime - startTime).count(); deltaTime = std::chrono::duration<long double, std::chrono::seconds::period>(currentTime - prevTime).count(); // Add some time to deltaTime to adjust the FPS (if FPS control is enabled) if (maxFPS > 0) { int waitTime = (1.l / maxFPS - deltaTime) * 1000000; // microseconds (for the sleep) if (waitTime > 0) { std::this_thread::sleep_for(std::chrono::microseconds(waitTime)); currentTime = std::chrono::high_resolution_clock::now(); deltaTime = std::chrono::duration<long double, std::chrono::seconds::period>(currentTime - prevTime).count(); } } prevTime = currentTime; // Get FPS FPS = std::round(1 / deltaTime); // Get time time = std::chrono::duration<long double, std::chrono::seconds::period>(currentTime - startTime).count(); // Increment the frame count ++frameCounter; } long double TimerSet::getDeltaTime() { return deltaTime; } long double TimerSet::getTime() { return time; } long double TimerSet::getTimeNow() { std::chrono::high_resolution_clock::time_point timeNow = std::chrono::high_resolution_clock::now(); return std::chrono::duration<long double, std::chrono::seconds::period>(timeNow - startTime).count(); } int TimerSet::getFPS() { return FPS; } void TimerSet::setMaxFPS(int newFPS) { maxFPS = newFPS; } size_t TimerSet::getFrameCounter() { return frameCounter; };
2,385
796
/************************************************************ ************************************************************/ #include "ofApp.h" /************************************************************ ************************************************************/ char targetIP[] = "10.7.206.7"; enum LED_TYPE{ LEDTYPE_STAGELIGHT, LEDTYPE_TAPE, }; struct Led{ LED_TYPE LedType; int OdeOffset; }; /* */ Led Led[] = { // DMX/PWM converter 1 { LEDTYPE_TAPE , 0 }, // 0 HardOffset = 1 { LEDTYPE_TAPE , 3 }, // 1 { LEDTYPE_TAPE , 6 }, // 2 { LEDTYPE_TAPE , 9 }, // 3 { LEDTYPE_TAPE , 12 }, // 4 { LEDTYPE_TAPE , 15 }, // 5 { LEDTYPE_TAPE , 18 }, // 6 { LEDTYPE_TAPE , 21 }, // 7 // DMX/PWM converter 2 { LEDTYPE_TAPE , 24 }, // 8 HardOffset = 25 { LEDTYPE_TAPE , 27 }, // 9 { LEDTYPE_TAPE , 30 }, // 10 { LEDTYPE_TAPE , 33 }, // 11 { LEDTYPE_TAPE , 36 }, // 12 { LEDTYPE_TAPE , 39 }, // 13 { LEDTYPE_TAPE , 42 }, // 14 { LEDTYPE_TAPE , 45 }, // 15 // Stage Light { LEDTYPE_STAGELIGHT , 48 }, // 16 HardOffset = 49 }; const int NUM_LEDS = sizeof(Led)/sizeof(Led[0]); /************************************************************ ************************************************************/ //-------------------------------------------------------------- void ofApp::setup(){ /******************** ********************/ ofSetWindowShape(600, 400); ofSetVerticalSync(false); ofSetFrameRate(60); //at first you must specify the Ip address of this machine artnet.setup("10.0.0.2"); //make sure the firewall is deactivated at this point /******************** ********************/ for(int i = 0; i < DMX_SIZE; i++){ data[i] = 0; } /******************** ********************/ ofColor initColor = ofColor(0, 0, 0, 255); ofColor minColor = ofColor(0, 0, 0, 0); ofColor maxColor = ofColor(255, 255, 255, 255); /******************** ********************/ gui.setup(); gui.add(LedId.setup("LedId", 0, 0, NUM_LEDS - 1)); gui.add(color.setup("color", initColor, minColor, maxColor)); } //-------------------------------------------------------------- void ofApp::update(){ /* // All Led on ofColor CurrentColor = color; for(int i = 0; i < NUM_LEDS; i++){ set_dataArray(i, CurrentColor); } /*/ // single Led on for(int i = 0; i < DMX_SIZE; i++){ data[i] = 0; } ofColor CurrentColor = color; set_dataArray(LedId, CurrentColor); //*/ } //-------------------------------------------------------------- void ofApp::set_dataArray(int id, ofColor CurrentColor){ switch(Led[id].LedType){ case LEDTYPE_STAGELIGHT: data[Led[id].OdeOffset + 0] = CurrentColor.a; data[Led[id].OdeOffset + 1] = CurrentColor.r; data[Led[id].OdeOffset + 2] = CurrentColor.g; data[Led[id].OdeOffset + 3] = CurrentColor.b; data[Led[id].OdeOffset + 4] = 0; // w; data[Led[id].OdeOffset + 5] = 1; // Strobe. 1-9:open break; case LEDTYPE_TAPE: data[Led[id].OdeOffset + 0] = CurrentColor.r; data[Led[id].OdeOffset + 1] = CurrentColor.g; data[Led[id].OdeOffset + 2] = CurrentColor.b; break; } } //-------------------------------------------------------------- void ofApp::exit(){ for(int i = 0; i < DMX_SIZE; i++){ data[i] = 0; } artnet.sendDmx(targetIP, data, DMX_SIZE); } //-------------------------------------------------------------- void ofApp::draw(){ /******************** ********************/ ofBackground(30); /******************** ********************/ // list nodes for sending // with subnet / universe // artnet.sendDmx("10.0.0.149", 0xf, 0xf, testImage.getPixels(), 512); artnet.sendDmx(targetIP, data, DMX_SIZE); /******************** ********************/ gui.draw(); /******************** ********************/ printf("%5.1f\r", ofGetFrameRate()); fflush(stdout); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
5,147
1,968
#include <algorithm> #include <cmath> #include <cstdlib> #include <ctime> #include <afxres.h> #include <fstream> #include <sstream> #include <vector> using namespace std; //#include <Crispen.h> // #include <sqlite3.h/sqlite3> #include <iostream> #include <cstdlib> using namespace std; #include <map> #include <vector> #include <string> /* VECTORS AND STRUCTURES */ struct Person{ int age;double weight;string name; string surname; }person[5]; /// creating vectors of ages, weight, names and surnames vector<int> ages = {22, 20, 21, 21,27}; vector<double> weights ={78.7, 69.4,88.9,100,79.8}; vector<string> names = {"Grossary", "Maxwell", "Clocktick", "Rebbalion", "Stalion"}; vector<string> surnames = {"Mark", "Zoran", "Clasic", "Mark", "Peter"}; void printSruct(); int main(){ /// inserting names into our structur person int i=0; for(string nam: names){ person[i].name = nam; i++; } /// inserting surnames into our structure person int s=0; for(string element: surnames){ person[s].surname = element; s++; } int k=0; for(int i: ages){ person[k].age =i; k++; } size_t j=0; for(double w: weights){ person[j].weight = w; j++; } printSruct(); return 0; } void printSruct(){ for(int i =0; i<sizeof(person)/sizeof(person[0]);i++){ cout<<"("<<person[i].name<<", " <<person[i].surname<<", " <<person[i].age<<", " <<person[i].weight<<")"<<endl; } }
1,460
566
#include "StateManager.h" StateManager::StateManager() { SDLBase::initSDL(); inst = InputManager::getInstance(); currentState = new State_Splash(); currentState->load(); srand(time(NULL)); inst->update(); stack = 0; } StateManager::~StateManager() { SDLBase::exitSDL(); currentState->unload(); free(currentState); } void StateManager::run() { bool quit = false; float accumulator, lastTime; const float dt = TIME_STEP; lastTime = SDL_GetTicks()/1000.f; accumulator = 0.f; while(!quit) { float nowTime = SDL_GetTicks()/1000.f; float frameTime = nowTime - lastTime; lastTime = nowTime; accumulator += frameTime; if(accumulator >= dt) { inst->update(); if(inst->quitGame()) { quit = true; continue; } switch(currentState->update()) { case STATE: break; case STATE_SPLASH: stack = currentState->unload(); delete(currentState); currentState = new State_Splash(); currentState->load(stack); break; case STATE_GAME: stack = currentState->unload(); delete(currentState); currentState = new State_Game(); currentState->load(stack); break; case STATE_END: stack = currentState->unload(); delete(currentState); currentState = new State_End(); currentState->load(stack); break; case STATE_QUIT: quit = true; break; } accumulator -= dt; } currentState->render(); SDLBase::updateScreen(); /* now = SDL_GetTicks(); if(next_time > now) SDL_Delay(next_time - now); next_time += TICK_INTERVAL; */ } }
2,162
595
//******************************************************************** //* //* Warning: This file was generated by ecore4CPP Generator //* //******************************************************************** #ifndef UML_STRUCTURALFEATUREACTION_HPP #define UML_STRUCTURALFEATUREACTION_HPP #include <map> #include <list> #include <memory> #include <string> // forward declarations template<class T, class ... U> class Subset; class AnyObject; typedef std::shared_ptr<AnyObject> Any; //********************************* // generated Includes #include <map> namespace persistence { namespace interfaces { class XLoadHandler; // used for Persistence class XSaveHandler; // used for Persistence } } namespace uml { class UmlFactory; } //Forward Declaration for used types namespace uml { class Action; } namespace uml { class Activity; } namespace uml { class ActivityEdge; } namespace uml { class ActivityGroup; } namespace uml { class ActivityNode; } namespace uml { class ActivityPartition; } namespace uml { class Classifier; } namespace uml { class Comment; } namespace uml { class Constraint; } namespace uml { class Dependency; } namespace uml { class Element; } namespace uml { class ExceptionHandler; } namespace uml { class InputPin; } namespace uml { class InterruptibleActivityRegion; } namespace uml { class Namespace; } namespace uml { class OutputPin; } namespace uml { class RedefinableElement; } namespace uml { class StringExpression; } namespace uml { class StructuralFeature; } namespace uml { class StructuredActivityNode; } // base class includes #include "uml/Action.hpp" // enum includes #include "uml/VisibilityKind.hpp" //********************************* namespace uml { /*! StructuralFeatureAction is an abstract class for all Actions that operate on StructuralFeatures. <p>From package UML::Actions.</p> */ class StructuralFeatureAction:virtual public Action { public: StructuralFeatureAction(const StructuralFeatureAction &) {} StructuralFeatureAction& operator=(StructuralFeatureAction const&) = delete; protected: StructuralFeatureAction(){} public: virtual std::shared_ptr<ecore::EObject> copy() const = 0; //destructor virtual ~StructuralFeatureAction() {} //********************************* // Operations //********************************* /*! The multiplicity of the object InputPin must be 1..1. object.is(1,1) */ virtual bool multiplicity(Any diagnostics,std::map < Any, Any > context) = 0; /*! The structuralFeature must not be static. not structuralFeature.isStatic */ virtual bool not_static(Any diagnostics,std::map < Any, Any > context) = 0; /*! The structuralFeature must either be an owned or inherited feature of the type of the object InputPin, or it must be an owned end of a binary Association whose opposite end had as a type to which the type of the object InputPin conforms. object.type.oclAsType(Classifier).allFeatures()->includes(structuralFeature) or object.type.conformsTo(structuralFeature.oclAsType(Property).opposite.type) */ virtual bool object_type(Any diagnostics,std::map < Any, Any > context) = 0; /*! The structuralFeature must have exactly one featuringClassifier. structuralFeature.featuringClassifier->size() = 1 */ virtual bool one_featuring_classifier(Any diagnostics,std::map < Any, Any > context) = 0; /*! The visibility of the structuralFeature must allow access from the object performing the ReadStructuralFeatureAction. structuralFeature.visibility = VisibilityKind::public or _'context'.allFeatures()->includes(structuralFeature) or structuralFeature.visibility=VisibilityKind::protected and _'context'.conformsTo(structuralFeature.oclAsType(Property).opposite.type.oclAsType(Classifier)) */ virtual bool visibility(Any diagnostics,std::map < Any, Any > context) = 0; //********************************* // Attributes Getter Setter //********************************* //********************************* // Reference //********************************* /*! The InputPin from which the object whose StructuralFeature is to be read or written is obtained. <p>From package UML::Actions.</p> */ virtual std::shared_ptr<uml::InputPin > getObject() const = 0; /*! The InputPin from which the object whose StructuralFeature is to be read or written is obtained. <p>From package UML::Actions.</p> */ virtual void setObject(std::shared_ptr<uml::InputPin> _object_object) = 0; /*! The StructuralFeature to be read or written. <p>From package UML::Actions.</p> */ virtual std::shared_ptr<uml::StructuralFeature > getStructuralFeature() const = 0; /*! The StructuralFeature to be read or written. <p>From package UML::Actions.</p> */ virtual void setStructuralFeature(std::shared_ptr<uml::StructuralFeature> _structuralFeature_structuralFeature) = 0; protected: //********************************* // Attribute Members //********************************* //********************************* // Reference Members //********************************* /*! The InputPin from which the object whose StructuralFeature is to be read or written is obtained. <p>From package UML::Actions.</p> */ std::shared_ptr<uml::InputPin > m_object; /*! The StructuralFeature to be read or written. <p>From package UML::Actions.</p> */ std::shared_ptr<uml::StructuralFeature > m_structuralFeature; public: //********************************* // Union Getter //********************************* /*! ActivityGroups containing the ActivityNode. <p>From package UML::Activities.</p> */ virtual std::shared_ptr<Union<uml::ActivityGroup>> getInGroup() const = 0;/*! The ordered set of InputPins representing the inputs to the Action. <p>From package UML::Actions.</p> */ virtual std::shared_ptr<SubsetUnion<uml::InputPin, uml::Element>> getInput() const = 0;/*! The Elements owned by this Element. <p>From package UML::CommonStructure.</p> */ virtual std::shared_ptr<Union<uml::Element>> getOwnedElement() const = 0;/*! The Element that owns this Element. <p>From package UML::CommonStructure.</p> */ virtual std::weak_ptr<uml::Element > getOwner() const = 0;/*! The RedefinableElement that is being redefined by this element. <p>From package UML::Classification.</p> */ virtual std::shared_ptr<Union<uml::RedefinableElement>> getRedefinedElement() const = 0; virtual std::shared_ptr<ecore::EObject> eContainer() const = 0; //********************************* // Persistence Functions //********************************* virtual void load(std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler) = 0; virtual void resolveReferences(const int featureID, std::list<std::shared_ptr<ecore::EObject> > references) = 0; virtual void save(std::shared_ptr<persistence::interfaces::XSaveHandler> saveHandler) const = 0; }; } #endif /* end of include guard: UML_STRUCTURALFEATUREACTION_HPP */
7,231
2,433
// Source : https://leetcode.com/problems/product-of-array-except-self/ // Author : Hao Chen // Date : 2015-07-17 /********************************************************************************** * * Given an array of n integers where n > 1, nums, return an array output such that * output[i] is equal to the product of all the elements of nums except nums[i]. * * Solve it without division and in O(n). * * For example, given [1,2,3,4], return [24,12,8,6]. * * Follow up: * Could you solve it with constant space complexity? (Note: The output array does not * count as extra space for the purpose of space complexity analysis.) * **********************************************************************************/ class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { int len = nums.size(); vector<int> result(len, 1); //from the left to right for (int i=1; i<len; i++) { result[i] = result[i-1]*nums[i-1]; } //from the right to left int factorial = 1; for (int i=len-2; i>=0; i--){ factorial *= nums[i+1]; result[i] *= factorial; } return result; } };
1,263
386
#include "stub.hpp" #include <errno.h> #include <kprint> #define FUTEX_WAIT 0 #define FUTEX_WAKE 1 #define FUTEX_FD 2 #define FUTEX_REQUEUE 3 #define FUTEX_CMP_REQUEUE 4 #define FUTEX_WAKE_OP 5 #define FUTEX_LOCK_PI 6 #define FUTEX_UNLOCK_PI 7 #define FUTEX_TRYLOCK_PI 8 #define FUTEX_WAIT_BITSET 9 #define FUTEX_PRIVATE 128 #define FUTEX_CLOCK_REALTIME 256 extern void print_backtrace(); static int sys_futex(int *uaddr, int /*futex_op*/, int val, const struct timespec *timeout, int /*val3*/) { if (*uaddr != val){ return EAGAIN; } else { *uaddr = 0; } if (timeout == nullptr){ kprintf("No timeout\n"); } return 0; } extern "C" int syscall_SYS_futex(int *uaddr, int futex_op, int val, const struct timespec *timeout, int val3) { return stubtrace(sys_futex, "futex", uaddr, futex_op, val, timeout, val3); }
885
388
#include"Enemy.h" USING_NS_CC; using namespace std; int hitSound = experimental::AudioEngine::play2d("sounds/hit.mp3", false, 0); Enemy* Enemy::create(int xMapNumber, int xWaveNumber, int xBossNumber) { Enemy* pSprite = new Enemy(); pSprite->eeeFrames = SpriteFrameCache::getInstance(); if (pSprite && pSprite->initWithSpriteFrame(pSprite->eeeFrames->getSpriteFrameByName (std::to_string(xMapNumber) + std::to_string(xWaveNumber) + std::to_string(xBossNumber) + "0_idle0.png"))) { pSprite->autorelease(); pSprite->mapNumber = xMapNumber; pSprite->waveNumber = xWaveNumber; pSprite->bossNumber = xBossNumber; pSprite->isSpawned = false; return pSprite; } CC_SAFE_DELETE(pSprite); return nullptr; } void Enemy::initOption() { this->direction = 0; this->canDrop = false; this->canChase = true; this->canRespawn = true; this->getHitTime = 0; this->inviTime = 1.8; if (this->bossNumber == 1) inviTime = 6; if (this->bossNumber == 2) inviTime = 8; if (this->bossNumber == 3) inviTime = 10; this->isDead = false; this->getLastFrameNumberOf("attack"); this->getLastFrameNumberOf("projectile"); spell = Sprite::create(); //spell->setAnchorPoint(Vec2(0.5, 0)); //if (this->waveNumber == 2 && this->mapNumber == 1) spell->setAnchorPoint(Vec2(0, 0)); spellLanded = Sprite::create(); spellLanded->setAnchorPoint(Vec2(0.5f, 0.3f)); spellLanded->setScale(2); spell->setScale(2); this->isOnCD = false; this->isAttacking = false; this->isMoving = false; this->canDamage = false; this->canSpawn = true; attackHelper = Sprite::create(); if(attackHelper) this->addChild(attackHelper); movementHelper = Sprite::create(); if(movementHelper) this->addChild(movementHelper); this->hp->setVisible(false); this->idleStatus(); this->scheduleUpdate(); } void Enemy::setHP(int HP) { if (hp == nullptr) { hp = Label::create(); hp->setAnchorPoint(Vec2(0.5, 0)); hp->setPosition(this->getPosition().x + (this->getContentSize().width / 2), this->getPosition().y + this->getContentSize().height); hp->setColor(Color3B(255, 0, 0)); //hp->setColor(Color4B::RED); hp->setSystemFontSize(16); this->hpBar = false; } hp->setString(std::to_string(HP)); if (!hpBar && hp) { this->addChild(hp, 1); this->hpBar = true; } } void Enemy::getLastFrameNumberOf(std::string actionName) { for (int i = 0; i < 99; i++) { auto frameName = std::to_string(mapNumber) + std::to_string(waveNumber) + std::to_string(bossNumber) +std::to_string(this->direction) +"_" + actionName + std::to_string(i) + ".png"; SpriteFrame* test = eeeFrames->getSpriteFrameByName(frameName); if (!test) { if (actionName == "attack") useSkillLastFN = i; if (actionName == "projectile") skillLastFN = i; break; } } } void Enemy::idleStatus() { if (!this->isIdle &&( !this->isDead || this->canRespawn)) { this->stopAllActionsByTag(1); this->stopAllActionsByTag(3); //auto idleState = RepeatForever::create(animation("Idle", 0.12f)); auto idleState = RepeatForever::create(makeAnimation("idle", 0.12f)); idleState->setTag(1); this->runAction(idleState); this->isIdle = true; this->canMove = true; this->canChase = true; } } void Enemy::movingAnimation() { if (this->mapNumber == 2 && this->waveNumber == 1) { //what does the tree do? } else if (this->canMove) { this->stopAllActionsByTag(1); this->stopAllActionsByTag(3); //auto anim = RepeatForever::create(animation("Moving", 0.12f)); auto anim = RepeatForever::create(makeAnimation("moving", 0.12f)); anim->setTag(3); this->runAction(anim); this->isMoving = true; canMove = false; } } void Enemy::chasing() { float howFar = std::fabsf(ppp->getPosition().x - (this->getPosition().x + this->getContentSize().width / 2)); if (this->canChase && !this->isMoving && !this->isAttacking &&this->isChasing && howFar>skillRange-69) { float pppX = ppp->getPosition().x; this->canChase = false; this->isIdle = false; this->isMoving = true; this->breakTime = false; float moveByX = pppX - (this->getPosition().x + this->getContentSize().width / 2); if (moveByX < 0) this->direction = 0; else this->direction = 1; this->movingAnimation(); this->stopAllActionsByTag(4); if (this->mapNumber == 2 && this->waveNumber == 1) { //what a tree should do } else { auto move2 = Sequence::create(DelayTime::create(std::fabsf(moveByX)/moveSpeed), CallFunc::create([=]() {this->breakTime = false; this->canMove = true; this->canChase = true; this->isMoving = false; if (std::fabsf(ppp->getPosition().x - this->getPosition().x) > visionRange + 100) this->isChasing = false; this->idleStatus(); }), nullptr); //could need some fix?! nah move2->setTag(4); this->runAction(move2); } } } void Enemy::randomMoving() { this->isMoving = true; if((this->waveNumber==1 || this->bossNumber==1) && (this->mapNumber != 2 || (this->mapNumber == 2 && this->bossNumber == 0))) randomX = RandomHelper::random_real(listLineX.at(0), listLineX.at(1)); //di chuyen trong 1 khoang giua line1 va line2 trong tiledMap if((this->waveNumber==2 || this->bossNumber==2) && (this->mapNumber!=2 || (this->mapNumber==2 && this->bossNumber==0))) randomX = RandomHelper::random_real(listLineX.at(2), listLineX.at(3)); if (this->mapNumber == 2 && this->bossNumber > 0) randomX = RandomHelper::random_real(listLineX.at(4), listLineX.at(5)); float eX = this->getPositionX(); float moveByX = randomX - eX; this->isIdle = false; this->stopAllActionsByTag(4); if (moveByX > 0) this->direction = 1; //done else { moveByX *= -1; this->direction = 0; } this->movingAnimation(); if (this->mapNumber == 2 && this->waveNumber == 1) { //wat a tree shoud do } else { auto seq = Sequence::create(DelayTime::create(moveByX/moveSpeed), CallFunc::create([=]() {this->isMoving = false; this->canMove = true; this->idleStatus(); }), DelayTime::create(RandomHelper::random_real(0.5f, 1.0f)), CallFunc::create([=]() { this->breakTime = false; }), nullptr); seq->setTag(4); this->runAction(seq); } } void Enemy::moving() { float howFar = std::fabsf(ppp->getPosition().x - this->getPosition().x); auto eeePosY = this->getPositionY() - 43; if (this->mapNumber == 3 && bossNumber != 1) { if (this->bossNumber == 2) eeePosY -= 69; else eeePosY -= 40; } if (howFar < skillRange && !this->isAttacking && !this->isOnCD && std::fabsf(ppp->getPosition().y - eeePosY) < 145 && (ppp->getPositionY() - eeePosY)>0 && ppp->getPositionX() > spotPlayerLineLeft && ppp->getPositionX()<spotPlayerLineRight) { this->attack(); } if (ppp->getPosition().y - eeePosY > 145 || ppp->getPositionX() < spotPlayerLineLeft || ppp->getPositionX() > spotPlayerLineRight) this->isChasing = false; if (howFar < visionRange && !this->isChasing && !this->isAttacking && std::fabsf(ppp->getPosition().y - eeePosY) < 145 && (ppp->getPositionY() - eeePosY)>0 && ppp->getPositionX() > spotPlayerLineLeft && ppp->getPositionX()<spotPlayerLineRight) { this->isChasing = true; } else { if (!this->isMoving && !this->isAttacking && !this->isChasing && !this->breakTime) { this->breakTime = true; this->randomMoving(); } else { this->chasing(); } } } void Enemy::attack() { if (this->isSpawned) { float howFar = ppp->getPosition().x - (this->getPosition().x + this->getContentSize().width / 2); if (howFar < skillRange) { if (howFar < 0) this->direction = 0; else this->direction = 1; //if (checkFrame("projectile")) // this->spell->setFlippedX(this->isFlippedX()); this->stopAllActions(); this->isIdle = false; this->isAttacking = true; this->isOnCD = true; this->isMoving = false; this->canMove = true; this->breakTime = false; //this->runAction(Sequence::create(animation("SkillUsing", castSpeed), this->runAction(Sequence::create(makeAnimation("attack", castSpeed), CallFunc::create([=]() {this->canDamage = false; this->isAttacking = false; this->idleStatus(); }), nullptr)); if (this->isCaster) { this->casterSpell(); } if (this->isSSMobility) { this->mobilitySS(); } if (!this->isCaster && !this->isSSMobility) { this->runAction(Sequence::create(DelayTime::create(castSpeed*norAtkDmgAfterF), CallFunc::create([=]() {this->canDamage = true; }), DelayTime::create(castSpeed*doneAtkAfterF), CallFunc::create([=]() {this->canDamage = false; }), nullptr)); } this->attackHelper->runAction(Sequence::create(DelayTime::create(0.12*useSkillLastFN*skillCD), CallFunc::create([=]() {this->isOnCD = false; }), nullptr)); } } } void Enemy::casterSpell() { float range = 500.f; if (this->direction==0) range *= -1; float move2X = this->getPosition().x; float move2Y = this->getPositionY(); if (this->mapNumber == 2 && this->bossNumber == 2)move2Y -= 20; if (this->mapNumber == 1 && this->waveNumber == 1) move2Y += 10; if (this->direction==1) { move2X += this->getContentSize().width/2; } else move2X -= this->getContentSize().width / 2; if(this->waveNumber==2 && this->mapNumber == 1) this->spell->runAction(Sequence::create( MoveTo::create(0, Vec2(move2X, this->getPosition().y+this->getContentSize().height/2)), CallFunc::create([=]() {this->spell->setVisible(true); }), makeAnimation("projectile", castSpeed), CallFunc::create([=]() {this->spell->setVisible(false); this->attackLandedEffect(); }), nullptr)); if ((this->waveNumber == 1 && this->mapNumber == 1)||(this->mapNumber==2 && this->bossNumber==2)) { this->spell->runAction(RepeatForever::create(makeAnimation("projectile", castSpeed))); this->spell->runAction(Sequence::create( CallFunc::create([=]() {this->interuptable=true; }), DelayTime::create(castSpeed * skillAtkAfterF), CallFunc::create([=]() { this->interuptable = false; this->spell->setPosition(move2X, move2Y); this->spell->setVisible(true); }), MoveBy::create(0.69f, Vec2(range, 0)), CallFunc::create([=]() {this->spell->setVisible(false); this->spell->setPosition(0, 0); }), nullptr)); } if (this->mapNumber == 2 && this->bossNumber == 1) { this->spell->runAction(Sequence::create(CallFunc::create([=]() {this->interuptable = true; }), DelayTime::create(castSpeed * skillAtkAfterF), CallFunc::create([=]() { this->interuptable = false; this->spell->setPosition(ppp->getPositionX(), ppp->getPositionY() + 10); this->spell->setVisible(true); this->spell->runAction(Sequence::create(makeAnimation("projectile", castSpeed), CallFunc::create([=]() {this->spell->setVisible(false); }), nullptr)); }), DelayTime::create(castSpeed * 2), CallFunc::create([=]() {this->attackLandedEffect(); }),nullptr)); } //this->spell->runAction(RepeatForever::create(animation("Spell", castSpeed))); } void Enemy::mobilitySS() { this->mobilityUsing = true; this->invulnerable = true; this->movementHelper->stopActionByTag(123); float howFar = ppp->getPosition().x - (this->getPosition().x + this->getContentSize().width / 2); if (howFar < 0) howFar *= -1; if (this->bossNumber == 1 && this->mapNumber == 1) this->runAction(Sequence::create(DelayTime::create(castSpeed*(mobilitySSAt + 1)), JumpTo::create(castSpeed*mobilitySpeed, Vec2(ppp->getPosition().x - this->getContentSize().width / 2, this->getPosition().y), 72, 1), CallFunc::create([=]() {this->mobilityUsing = false; this->canDamage = true; this->invulnerable = false; }), DelayTime::create(castSpeed*mobilityDoneAfterF), CallFunc::create([=]() {this->canDamage = false; }), nullptr)); else this->runAction(Sequence::create(DelayTime::create(castSpeed*(mobilitySSAt + 1)), MoveTo::create(castSpeed*mobilitySpeed, Vec2(ppp->getPosition().x - this->getContentSize().width / 2, this->getPosition().y)), CallFunc::create([=]() {this->mobilityUsing = false; this->canDamage = true; this->invulnerable = false; }), DelayTime::create(castSpeed*mobilityDoneAfterF), CallFunc::create([=]() {this->canDamage = false; }), nullptr)); } void Enemy::attackLandedEffect() { if (this->checkFrame("impact")) { this->spellLanded->setPosition(Vec2(ppp->getPosition().x, ppp->getPosition().y)); this->spellLanded->runAction(Sequence::create( //CallFunc::create([=]() {this->canDamage = true; this->spellLanded->setVisible(true); }), animation("SkillLanded", 0.12f), CallFunc::create([=]() {this->canDamage = false; this->spellLanded->setVisible(false); this->spellLanded->setPosition(0, 0); }), nullptr)); CallFunc::create([=]() {this->canDamage = true; this->spellLanded->setVisible(true); }), makeAnimation("impact", 0.12f), CallFunc::create([=]() {this->canDamage = false; this->spellLanded->setVisible(false); this->spellLanded->setPosition(0, 0); }), nullptr)); } } void Enemy::getHit(int damage) { if (!this->isDead && this->isSpawned && !this->invulnerable) { /* if(this->mapNumber==1 || this->mapNumber==2) this->stopAllActions(); else */ this->forbidAllAction(); this->canChase = true; this->isIdle = false; this->isAttacking = false; this->isMoving = false; this->breakTime = false; this->getHitTime++; if (getHitTime == 3) { getHitTime = 0; this->invulnerable = true; auto doIt = Sequence::create(DelayTime::create(inviTime), CallFunc::create([=]() {this->invulnerable = false; }), nullptr); doIt->setTag(123); this->movementHelper->runAction(doIt); } SpriteFrame * hit = eeeFrames->getSpriteFrameByName(std::to_string(mapNumber) + std::to_string(waveNumber) + std::to_string(bossNumber) + std::to_string(this->direction) + "_hurt0.png"); if(hit) this->setSpriteFrame(hit); int x = -16; if (ppp->getPositionX() - 25 < this->getPositionX()) { x *= -1; this->direction = 0; } else this->direction = 1; this->runAction(MoveBy::create(0.33f,Vec2(x, 0))); int healthP = std::stoi(this->hp->getString()); healthP -= damage; if (healthP < 0 || healthP == 0) { this->hp->setString("0"); this->dead(); } else this->hp->setString(std::to_string(healthP)); if(!this->isDead) this->runAction(Sequence::create(DelayTime::create(0.3f), CallFunc::create([=]() { this->idleStatus(); }), DelayTime::create(0.4f), CallFunc::create([=]() {this->isMoving=false; this->canMove = true; this->breakTime = false; }), nullptr)); } } void Enemy::autoRespawn() { if (this->canRespawn && this->bossNumber==0) { float timeTillRespawn = RandomHelper::random_real(5.0f, 10.0f); //this->setVisible(true); //this->setOpacity(0); this->runAction( Sequence::create( DelayTime::create(timeTillRespawn), CallFunc::create([=]() {this->idleStatus(); }), FadeIn::create(1.0f), nullptr)); this->runAction( Sequence::create( DelayTime::create(timeTillRespawn + 1.0f), CallFunc::create([=]() { this->isDead = false; this->isSpawned = true; this->setHP(this->baseHP); this->canRespawn = false; }), nullptr)); } } void Enemy::dead() { if (this->waveNumber == 1) ppp->w1kills++; if (this->waveNumber == 2) ppp->w2kills++; this->isDead = true; this->isSpawned = false; this->canRespawn = true; this->canDrop = true; //this->stopAllActions(); this->forbidAllAction(); experimental::AudioEngine::play2d("sounds/monsterdie.mp3", false, 0.4f); if(this->checkFrame("die")) this->runAction(Sequence::create(makeAnimation("die", 0.12f), FadeOut::create(0), CallFunc::create([=]() {this->autoRespawn(); }), nullptr)); auto howFar = ppp->getPosition().x - this->getPosition().x; auto theX = 40.f; if (howFar > 0) theX *= -1; this->runAction(MoveBy::create(0.5, Vec2(theX, 0))); ppp->currentEXP += this->expReward; } void Enemy::forbidAllAction() { this->stopAllActions(); if ((this->mapNumber == 1 && this->waveNumber > 0)||this->interuptable) { this->spell->stopAllActions(); this->spell->setVisible(false); } } bool Enemy::checkFrame(std::string action) { action = "_" + action + "0.png"; //auto checkSprite = Sprite::create(combination +"/"+ action); auto checkSprite = eeeFrames->getSpriteFrameByName (std::to_string(this->mapNumber) + std::to_string(this->waveNumber) + std::to_string(this->bossNumber) + std::to_string(this->direction) + action); if (checkSprite) return true; else return false; } void Enemy::update(float elapsed) { if(!this->isDead && this->isSpawned) moving(); if (this->isChasing && !this->canChase && !this->isAttacking) { if (this->direction==0 && ppp->getPositionX() > this->getPositionX()+this->getContentSize().width) { this->stopAllActionsByTag(3); this->stopAllActionsByTag(4); if(!this->mobilityUsing) this->direction = 1; this->canChase = true; this->isMoving = false; this->idleStatus(); } else if (this->direction==1 && ppp->getPositionX() < this->getPositionX() - this->getContentSize().width) { this->stopAllActionsByTag(3); this->stopAllActionsByTag(4); if(!this->mobilityUsing) this->direction = 0; this->canChase = true; this->isMoving = false; this->idleStatus(); } } if (this->isMoving && (this->mapNumber!=2 || (this->mapNumber==2 && this->waveNumber!=1))) { this->setPositionX(this->getPositionX() + ( this->direction ? (moveSpeed * elapsed) : - (moveSpeed * elapsed) ) ); } } Animate* Enemy::makeAnimation(std::string actionName, float timeEachFrame) { std::string key = std::to_string(this->mapNumber) + std::to_string(this->waveNumber) + std::to_string(this->bossNumber) + std::to_string(this->direction) + "_" + actionName; Animate* anim = listAnimations.at(key); if (anim == nullptr) { Vector<SpriteFrame*> runningFrames; for (int i = 0; i < 99; i++) { auto frameName = key + std::to_string(i) + ".png"; SpriteFrame* frame = eeeFrames->getSpriteFrameByName(frameName); if (!frame) break; runningFrames.pushBack(frame); } Animation* runningAnimation = Animation::createWithSpriteFrames(runningFrames, timeEachFrame); anim = Animate::create(runningAnimation); listAnimations.insert(key, anim); } return anim; }
18,461
7,486
#ifndef STEREO_HPP #define STEREO_HPP #include <iostream> #include <opencv2/opencv.hpp> #include "calibration.hpp" namespace sl_oc { namespace tools { /*! * \brief STEREO_PAR_FILENAME default stereo parameter configuration file */ const std::string STEREO_PAR_FILENAME = "zed_oc_stereo.yaml"; /*! * \brief The StereoSgbmPar class is used to store/retrieve the stereo matching parameters */ class StereoSgbmPar { public: /*! * \brief Default constructor */ StereoSgbmPar() { setDefaultValues(); } /*! * \brief load stereo matching parameters * \return true if a configuration file exists */ bool load(); /*! * \brief save stereo matching parameters * \return true if a configuration file has been correctly created */ bool save(); /*! * \brief set default stereo matching parameters */ void setDefaultValues(); /*! * \brief print the current stereo matching parameters on standard output */ void print(); public: int blockSize; //!< [default: 3] Matched block size. It must be an odd number >=1 . Normally, it should be somewhere in the 3..11 range. int minDisparity; //!< [default: 0] Minimum possible disparity value. Normally, it is zero but sometimes rectification algorithms can shift images, so this parameter needs to be adjusted accordingly. int numDisparities; //!< [default: 96] Maximum disparity minus minimum disparity. The value is always greater than zero. In the current implementation, this parameter must be divisible by 16. int mode; //!< Set it to StereoSGBM::MODE_HH to run the full-scale two-pass dynamic programming algorithm. It will consume O(W*H*numDisparities) bytes, which is large for 640x480 stereo and huge for HD-size pictures. By default, it is set to `cv::StereoSGBM::MODE_SGBM_3WAY`. int P1; //!< [default: 24*blockSize*blockSize] The first parameter controlling the disparity smoothness. See below. int P2; //!< [default: 4*PI]The second parameter controlling the disparity smoothness. The larger the values are, the smoother the disparity is. P1 is the penalty on the disparity change by plus or minus 1 between neighbor pixels. P2 is the penalty on the disparity change by more than 1 between neighbor pixels. The algorithm requires P2 > P1 . See stereo_match.cpp sample where some reasonably good P1 and P2 values are shown (like 8*number_of_image_channels*blockSize*blockSize and 32*number_of_image_channels*blockSize*blockSize , respectively). int disp12MaxDiff; //!< [default: 96] Maximum allowed difference (in integer pixel units) in the left-right disparity check. Set it to a non-positive value to disable the check. int preFilterCap; //!< [default: 63] Truncation value for the prefiltered image pixels. The algorithm first computes x-derivative at each pixel and clips its value by [-preFilterCap, preFilterCap] interval. The result values are passed to the Birchfield-Tomasi pixel cost function. int uniquenessRatio; //!< [default: 5] Margin in percentage by which the best (minimum) computed cost function value should "win" the second best value to consider the found match correct. Normally, a value within the 5-15 range is good enough. int speckleWindowSize; //!< [default: 255] Maximum size of smooth disparity regions to consider their noise speckles and invalidate. Set it to 0 to disable speckle filtering. Otherwise, set it somewhere in the 50-200 range. int speckleRange; //!< [default: 1] Maximum disparity variation within each connected component. If you do speckle filtering, set the parameter to a positive value, it will be implicitly multiplied by 16. Normally, 1 or 2 is good enough. float minDepth_mm; //!< [default: 300] Minimum value of depth for the extracted depth map float maxDepth_mm; //!< [default: 10000] Maximum value of depth for the extracted depth map }; void StereoSgbmPar::setDefaultValues() { blockSize = 3; minDisparity = 0; numDisparities = 96; mode = cv::StereoSGBM::MODE_SGBM_3WAY; // MODE_SGBM = 0, MODE_HH = 1, MODE_SGBM_3WAY = 2, MODE_HH4 = 3 P1 = 24*blockSize*blockSize; P2 = 4*P1; disp12MaxDiff = 96; preFilterCap = 63; uniquenessRatio = 5; speckleWindowSize = 255; speckleRange = 1; minDepth_mm = 300.f; maxDepth_mm = 10000.f; } bool StereoSgbmPar::load() { std::string path = getHiddenDir(); std::string par_file = path + STEREO_PAR_FILENAME; cv::FileStorage fs; if(!fs.open(par_file, cv::FileStorage::READ)) { std::cerr << "Error opening stereo parameters file. Using default values." << std::endl << std::endl; setDefaultValues(); return false; } fs["blockSize"] >> blockSize; fs["minDisparity"] >> minDisparity; fs["numDisparities"] >> numDisparities; fs["mode"] >> mode; fs["disp12MaxDiff"] >> disp12MaxDiff; fs["preFilterCap"] >> preFilterCap; fs["uniquenessRatio"] >> uniquenessRatio; fs["speckleWindowSize"] >> speckleWindowSize; fs["speckleRange"] >> speckleRange; P1 = 24*blockSize*blockSize; P2 = 96*blockSize*blockSize; fs["minDepth_mm"] >> minDepth_mm; fs["maxDepth_mm"] >> maxDepth_mm; std::cout << "Stereo parameters load done: " << par_file << std::endl << std::endl; return true; } bool StereoSgbmPar::save() { std::string path = getHiddenDir(); std::string par_file = path + STEREO_PAR_FILENAME; cv::FileStorage fs; if(!fs.open(par_file, cv::FileStorage::WRITE)) { std::cerr << "Error saving stereo parameters. Cannot open file for writing: " << par_file << std::endl << std::endl; return false; } fs << "blockSize" << blockSize; fs << "minDisparity" << minDisparity; fs << "numDisparities" << numDisparities; fs << "mode" << mode; fs << "disp12MaxDiff" << disp12MaxDiff; fs << "preFilterCap" << preFilterCap; fs << "uniquenessRatio" << uniquenessRatio; fs << "speckleWindowSize" << speckleWindowSize; fs << "speckleRange" << speckleRange; fs << "minDepth_mm" << minDepth_mm; fs << "maxDepth_mm" << maxDepth_mm; std::cout << "Stereo parameters write done: " << par_file << std::endl << std::endl; return true; } void StereoSgbmPar::print() { std::cout << "Stereo SGBM parameters:" << std::endl; std::cout << "------------------------------------------" << std::endl; std::cout << "blockSize:\t\t" << blockSize << std::endl; std::cout << "minDisparity:\t" << minDisparity << std::endl; std::cout << "numDisparities:\t" << numDisparities << std::endl; std::cout << "mode:\t\t" << mode << std::endl; std::cout << "disp12MaxDiff:\t" << disp12MaxDiff << std::endl; std::cout << "preFilterCap:\t" << preFilterCap << std::endl; std::cout << "uniquenessRatio:\t" << uniquenessRatio << std::endl; std::cout << "speckleWindowSize:\t" << speckleWindowSize << std::endl; std::cout << "speckleRange:\t" << speckleRange << std::endl; std::cout << "P1:\t\t" << P1 << " [Calculated]" << std::endl; std::cout << "P2:\t\t" << P2 << " [Calculated]" << std::endl; std::cout << "minDepth_mm:\t" << minDepth_mm << std::endl; std::cout << "maxDepth_mm:\t" << maxDepth_mm << std::endl; std::cout << "------------------------------------------" << std::endl << std::endl; } } // namespace tools } // namespace sl_oc #endif // STEREO_HPP
7,444
2,502
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "google/cloud/storage/internal/grpc_object_request_parser.h" #include "google/cloud/storage/internal/grpc_common_request_params.h" #include "google/cloud/storage/internal/grpc_object_access_control_parser.h" #include "google/cloud/storage/internal/grpc_object_metadata_parser.h" #include "google/cloud/storage/internal/openssl_util.h" #include "google/cloud/internal/invoke_result.h" #include "google/cloud/internal/time_utils.h" #include "google/cloud/log.h" #include <crc32c/crc32c.h> namespace google { namespace cloud { namespace storage { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN namespace internal { namespace { template <typename GrpcRequest, typename StorageRequest> Status SetCommonObjectParameters(GrpcRequest& request, StorageRequest const& req) { if (req.template HasOption<EncryptionKey>()) { auto data = req.template GetOption<EncryptionKey>().value(); auto key_bytes = Base64Decode(data.key); if (!key_bytes) return std::move(key_bytes).status(); auto key_sha256_bytes = Base64Decode(data.sha256); if (!key_sha256_bytes) return std::move(key_sha256_bytes).status(); request.mutable_common_object_request_params()->set_encryption_algorithm( std::move(data.algorithm)); request.mutable_common_object_request_params()->set_encryption_key_bytes( std::string{key_bytes->begin(), key_bytes->end()}); request.mutable_common_object_request_params() ->set_encryption_key_sha256_bytes( std::string{key_sha256_bytes->begin(), key_sha256_bytes->end()}); } return Status{}; } template <typename GrpcRequest> struct GetPredefinedAcl { auto operator()(GrpcRequest const& q) -> decltype(q.predefined_acl()); }; template < typename GrpcRequest, typename StorageRequest, typename std::enable_if< std::is_same<google::storage::v2::PredefinedObjectAcl, google::cloud::internal::invoke_result_t< GetPredefinedAcl<GrpcRequest>, GrpcRequest>>::value, int>::type = 0> void SetPredefinedAcl(GrpcRequest& request, StorageRequest const& req) { if (req.template HasOption<PredefinedAcl>()) { request.set_predefined_acl(GrpcObjectRequestParser::ToProtoObject( req.template GetOption<PredefinedAcl>())); } } template <typename GrpcRequest, typename StorageRequest> void SetPredefinedDefaultObjectAcl(GrpcRequest& request, StorageRequest const& req) { if (req.template HasOption<PredefinedDefaultObjectAcl>()) { request.set_predefined_default_object_acl( ToProto(req.template GetOption<PredefinedDefaultObjectAcl>())); } } template <typename GrpcRequest, typename StorageRequest> void SetMetagenerationConditions(GrpcRequest& request, StorageRequest const& req) { if (req.template HasOption<IfMetagenerationMatch>()) { request.set_if_metageneration_match( req.template GetOption<IfMetagenerationMatch>().value()); } if (req.template HasOption<IfMetagenerationNotMatch>()) { request.set_if_metageneration_not_match( req.template GetOption<IfMetagenerationNotMatch>().value()); } } template <typename GrpcRequest, typename StorageRequest> void SetGenerationConditions(GrpcRequest& request, StorageRequest const& req) { if (req.template HasOption<IfGenerationMatch>()) { request.set_if_generation_match( req.template GetOption<IfGenerationMatch>().value()); } if (req.template HasOption<IfGenerationNotMatch>()) { request.set_if_generation_not_match( req.template GetOption<IfGenerationNotMatch>().value()); } } template <typename StorageRequest> void SetResourceOptions(google::storage::v2::Object& resource, StorageRequest const& request) { if (request.template HasOption<ContentEncoding>()) { resource.set_content_encoding( request.template GetOption<ContentEncoding>().value()); } if (request.template HasOption<ContentType>()) { resource.set_content_type( request.template GetOption<ContentType>().value()); } if (request.template HasOption<KmsKeyName>()) { resource.set_kms_key(request.template GetOption<KmsKeyName>().value()); } } template <typename StorageRequest> Status SetObjectMetadata(google::storage::v2::Object& resource, StorageRequest const& req) { if (!req.template HasOption<WithObjectMetadata>()) { return Status{}; } auto metadata = req.template GetOption<WithObjectMetadata>().value(); if (!metadata.content_encoding().empty()) { resource.set_content_encoding(metadata.content_encoding()); } if (!metadata.content_disposition().empty()) { resource.set_content_disposition(metadata.content_disposition()); } if (!metadata.cache_control().empty()) { resource.set_cache_control(metadata.cache_control()); } for (auto const& acl : metadata.acl()) { *resource.add_acl() = GrpcObjectAccessControlParser::ToProto(acl); } if (!metadata.content_language().empty()) { resource.set_content_language(metadata.content_language()); } if (!metadata.content_type().empty()) { resource.set_content_type(metadata.content_type()); } if (metadata.event_based_hold()) { resource.set_event_based_hold(metadata.event_based_hold()); } for (auto const& kv : metadata.metadata()) { (*resource.mutable_metadata())[kv.first] = kv.second; } if (!metadata.storage_class().empty()) { resource.set_storage_class(metadata.storage_class()); } resource.set_temporary_hold(metadata.temporary_hold()); if (metadata.has_customer_encryption()) { auto encryption = GrpcObjectMetadataParser::ToProto(metadata.customer_encryption()); if (!encryption) return std::move(encryption).status(); *resource.mutable_customer_encryption() = *std::move(encryption); } return Status{}; } google::storage::v2::PredefinedObjectAcl ToProtoObjectAcl( std::string const& value) { if (value == PredefinedAcl::BucketOwnerFullControl().value()) { return google::storage::v2::OBJECT_ACL_BUCKET_OWNER_FULL_CONTROL; } if (value == PredefinedAcl::BucketOwnerRead().value()) { return google::storage::v2::OBJECT_ACL_BUCKET_OWNER_READ; } if (value == PredefinedAcl::AuthenticatedRead().value()) { return google::storage::v2::OBJECT_ACL_AUTHENTICATED_READ; } if (value == PredefinedAcl::Private().value()) { return google::storage::v2::OBJECT_ACL_PRIVATE; } if (value == PredefinedAcl::ProjectPrivate().value()) { return google::storage::v2::OBJECT_ACL_PROJECT_PRIVATE; } if (value == PredefinedAcl::PublicRead().value()) { return google::storage::v2::OBJECT_ACL_PUBLIC_READ; } if (value == PredefinedAcl::PublicReadWrite().value()) { GCP_LOG(ERROR) << "Invalid predefinedAcl value " << value; return google::storage::v2::PREDEFINED_OBJECT_ACL_UNSPECIFIED; } GCP_LOG(ERROR) << "Unknown predefinedAcl value " << value; return google::storage::v2::PREDEFINED_OBJECT_ACL_UNSPECIFIED; } } // namespace google::storage::v2::PredefinedObjectAcl GrpcObjectRequestParser::ToProtoObject( PredefinedAcl const& acl) { return ToProtoObjectAcl(acl.value()); } google::storage::v2::PredefinedObjectAcl GrpcObjectRequestParser::ToProtoObject( DestinationPredefinedAcl const& acl) { return ToProtoObjectAcl(acl.value()); } google::storage::v2::DeleteObjectRequest GrpcObjectRequestParser::ToProto( DeleteObjectRequest const& request) { google::storage::v2::DeleteObjectRequest result; SetGenerationConditions(result, request); SetMetagenerationConditions(result, request); SetCommonParameters(result, request); result.set_bucket("projects/_/buckets/" + request.bucket_name()); result.set_object(request.object_name()); result.set_generation(request.GetOption<Generation>().value_or(0)); return result; } google::storage::v2::GetObjectRequest GrpcObjectRequestParser::ToProto( GetObjectMetadataRequest const& request) { google::storage::v2::GetObjectRequest result; SetGenerationConditions(result, request); SetMetagenerationConditions(result, request); SetCommonParameters(result, request); result.set_bucket("projects/_/buckets/" + request.bucket_name()); result.set_object(request.object_name()); result.set_generation(request.GetOption<Generation>().value_or(0)); auto projection = request.GetOption<Projection>().value_or(""); if (projection == "full") result.mutable_read_mask()->add_paths("*"); return result; } StatusOr<google::storage::v2::ReadObjectRequest> GrpcObjectRequestParser::ToProto(ReadObjectRangeRequest const& request) { google::storage::v2::ReadObjectRequest r; auto status = SetCommonObjectParameters(r, request); if (!status.ok()) return status; r.set_object(request.object_name()); r.set_bucket("projects/_/buckets/" + request.bucket_name()); if (request.HasOption<Generation>()) { r.set_generation(request.GetOption<Generation>().value()); } if (request.HasOption<ReadRange>()) { auto const range = request.GetOption<ReadRange>().value(); r.set_read_offset(range.begin); r.set_read_limit(range.end - range.begin); } if (request.HasOption<ReadLast>()) { auto const offset = request.GetOption<ReadLast>().value(); r.set_read_offset(-offset); } if (request.HasOption<ReadFromOffset>()) { auto const offset = request.GetOption<ReadFromOffset>().value(); if (offset > r.read_offset()) { if (r.read_limit() > 0) { r.set_read_limit(offset - r.read_offset()); } r.set_read_offset(offset); } } SetGenerationConditions(r, request); SetMetagenerationConditions(r, request); SetCommonParameters(r, request); return r; } StatusOr<google::storage::v2::WriteObjectRequest> GrpcObjectRequestParser::ToProto(InsertObjectMediaRequest const& request) { google::storage::v2::WriteObjectRequest r; auto& object_spec = *r.mutable_write_object_spec(); auto& resource = *object_spec.mutable_resource(); SetResourceOptions(resource, request); auto status = SetObjectMetadata(resource, request); if (!status.ok()) return status; SetPredefinedAcl(object_spec, request); SetGenerationConditions(object_spec, request); SetMetagenerationConditions(object_spec, request); status = SetCommonObjectParameters(r, request); if (!status.ok()) return status; SetCommonParameters(r, request); resource.set_bucket("projects/_/buckets/" + request.bucket_name()); resource.set_name(request.object_name()); r.set_write_offset(0); auto& checksums = *r.mutable_object_checksums(); if (request.HasOption<Crc32cChecksumValue>()) { // The client library accepts CRC32C checksums in the format required by the // REST APIs (base64-encoded big-endian, 32-bit integers). We need to // convert this to the format expected by proto, which is just a 32-bit // integer. But the value received by the application might be incorrect, so // we need to validate it. auto as_proto = GrpcObjectMetadataParser::Crc32cToProto( request.GetOption<Crc32cChecksumValue>().value()); if (!as_proto.ok()) return std::move(as_proto).status(); checksums.set_crc32c(*as_proto); } else if (request.GetOption<DisableCrc32cChecksum>().value_or(false)) { // Nothing to do, the option is disabled (mostly useful in tests). } else { checksums.set_crc32c(crc32c::Crc32c(request.contents())); } if (request.HasOption<MD5HashValue>()) { auto as_proto = GrpcObjectMetadataParser::MD5ToProto( request.GetOption<MD5HashValue>().value()); if (!as_proto.ok()) return std::move(as_proto).status(); checksums.set_md5_hash(*std::move(as_proto)); } else if (request.GetOption<DisableMD5Hash>().value_or(false)) { // Nothing to do, the option is disabled. } else { checksums.set_md5_hash( GrpcObjectMetadataParser::ComputeMD5Hash(request.contents())); } return r; } ResumableUploadResponse GrpcObjectRequestParser::FromProto( google::storage::v2::WriteObjectResponse const& p, Options const& options) { ResumableUploadResponse response; response.upload_state = ResumableUploadResponse::kInProgress; if (p.has_persisted_size()) { response.committed_size = static_cast<std::uint64_t>(p.persisted_size()); } if (p.has_resource()) { response.payload = GrpcObjectMetadataParser::FromProto(p.resource(), options); response.upload_state = ResumableUploadResponse::kDone; } return response; } google::storage::v2::ListObjectsRequest GrpcObjectRequestParser::ToProto( ListObjectsRequest const& request) { google::storage::v2::ListObjectsRequest result; result.set_parent("projects/_/buckets/" + request.bucket_name()); auto const page_size = request.GetOption<MaxResults>().value_or(0); // Clamp out of range values. The service will clamp to its own range // ([0, 1000] as of this writing) anyway. if (page_size < 0) { result.set_page_size(0); } else if (page_size < std::numeric_limits<std::int32_t>::max()) { result.set_page_size(static_cast<std::int32_t>(page_size)); } else { result.set_page_size(std::numeric_limits<std::int32_t>::max()); } result.set_page_token(request.page_token()); result.set_delimiter(request.GetOption<Delimiter>().value_or("")); result.set_include_trailing_delimiter( request.GetOption<IncludeTrailingDelimiter>().value_or(false)); result.set_prefix(request.GetOption<Prefix>().value_or("")); result.set_versions(request.GetOption<Versions>().value_or("")); result.set_lexicographic_start(request.GetOption<StartOffset>().value_or("")); result.set_lexicographic_end(request.GetOption<EndOffset>().value_or("")); SetCommonParameters(result, request); return result; } ListObjectsResponse GrpcObjectRequestParser::FromProto( google::storage::v2::ListObjectsResponse const& response, Options const& options) { ListObjectsResponse result; result.next_page_token = response.next_page_token(); for (auto const& o : response.objects()) { result.items.push_back(GrpcObjectMetadataParser::FromProto(o, options)); } for (auto const& p : response.prefixes()) result.prefixes.push_back(p); return result; } StatusOr<google::storage::v2::RewriteObjectRequest> GrpcObjectRequestParser::ToProto(RewriteObjectRequest const& request) { google::storage::v2::RewriteObjectRequest result; SetCommonParameters(result, request); auto status = SetCommonObjectParameters(result, request); if (!status.ok()) return status; auto& destination = *result.mutable_destination(); destination.set_name(request.destination_object()); destination.set_bucket("projects/_/buckets/" + request.destination_bucket()); destination.set_kms_key( request.GetOption<DestinationKmsKeyName>().value_or("")); if (request.HasOption<WithObjectMetadata>()) { // Only a few fields can be set as part of the metadata request. auto m = request.GetOption<WithObjectMetadata>().value(); destination.set_storage_class(m.storage_class()); destination.set_content_encoding(m.content_encoding()); destination.set_content_disposition(m.content_disposition()); destination.set_cache_control(m.cache_control()); destination.set_content_language(m.content_language()); destination.set_content_type(m.content_type()); destination.set_temporary_hold(m.temporary_hold()); for (auto const& kv : m.metadata()) { (*destination.mutable_metadata())[kv.first] = kv.second; } if (m.event_based_hold()) { // The proto is an optional<bool>, avoid setting it to `false`, seems // confusing. destination.set_event_based_hold(m.event_based_hold()); } if (m.has_custom_time()) { *destination.mutable_custom_time() = google::cloud::internal::ToProtoTimestamp(m.custom_time()); } } result.set_source_bucket("projects/_/buckets/" + request.source_bucket()); result.set_source_object(request.source_object()); result.set_source_generation( request.GetOption<SourceGeneration>().value_or(0)); result.set_rewrite_token(request.rewrite_token()); if (request.HasOption<DestinationPredefinedAcl>()) { result.set_destination_predefined_acl( ToProtoObject(request.GetOption<DestinationPredefinedAcl>())); } SetGenerationConditions(result, request); SetMetagenerationConditions(result, request); if (request.HasOption<IfSourceGenerationMatch>()) { result.set_if_source_generation_match( request.GetOption<IfSourceGenerationMatch>().value()); } if (request.HasOption<IfSourceGenerationNotMatch>()) { result.set_if_source_generation_not_match( request.GetOption<IfSourceGenerationNotMatch>().value()); } if (request.HasOption<IfSourceMetagenerationMatch>()) { result.set_if_source_metageneration_match( request.GetOption<IfSourceMetagenerationMatch>().value()); } if (request.HasOption<IfSourceMetagenerationNotMatch>()) { result.set_if_source_metageneration_not_match( request.GetOption<IfSourceMetagenerationNotMatch>().value()); } result.set_max_bytes_rewritten_per_call( request.GetOption<MaxBytesRewrittenPerCall>().value_or(0)); if (request.HasOption<SourceEncryptionKey>()) { auto data = request.template GetOption<SourceEncryptionKey>().value(); auto key_bytes = Base64Decode(data.key); if (!key_bytes) return std::move(key_bytes).status(); auto key_sha256_bytes = Base64Decode(data.sha256); if (!key_sha256_bytes) return std::move(key_sha256_bytes).status(); result.set_copy_source_encryption_algorithm(data.algorithm); result.set_copy_source_encryption_key_bytes( std::string{key_bytes->begin(), key_bytes->end()}); result.set_copy_source_encryption_key_sha256_bytes( std::string{key_sha256_bytes->begin(), key_sha256_bytes->end()}); } return result; } RewriteObjectResponse GrpcObjectRequestParser::FromProto( google::storage::v2::RewriteResponse const& response, Options const& options) { RewriteObjectResponse result; result.done = response.done(); result.object_size = response.object_size(); result.total_bytes_rewritten = response.total_bytes_rewritten(); result.rewrite_token = response.rewrite_token(); if (response.has_resource()) { result.resource = GrpcObjectMetadataParser::FromProto(response.resource(), options); } return result; } StatusOr<google::storage::v2::StartResumableWriteRequest> GrpcObjectRequestParser::ToProto(ResumableUploadRequest const& request) { google::storage::v2::StartResumableWriteRequest result; auto status = SetCommonObjectParameters(result, request); if (!status.ok()) return status; auto& object_spec = *result.mutable_write_object_spec(); auto& resource = *object_spec.mutable_resource(); SetResourceOptions(resource, request); status = SetObjectMetadata(resource, request); if (!status.ok()) return status; SetPredefinedAcl(object_spec, request); SetGenerationConditions(object_spec, request); SetMetagenerationConditions(object_spec, request); SetCommonParameters(result, request); resource.set_bucket("projects/_/buckets/" + request.bucket_name()); resource.set_name(request.object_name()); return result; } google::storage::v2::QueryWriteStatusRequest GrpcObjectRequestParser::ToProto( QueryResumableUploadRequest const& request) { google::storage::v2::QueryWriteStatusRequest r; r.set_upload_id(request.upload_session_url()); return r; } } // namespace internal GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace storage } // namespace cloud } // namespace google
20,225
6,378
// 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. // AdvApp2Var_ApproxF2var.hxx /*--------------------------------------------------------------- | description de la macro et du prototype des routines | de l'approximation a deux variables | a utiliser dans AdvApp2Var |--------------------------------------------------------------*/ #ifndef AdvApp2Var_ApproxF2var_HeaderFile #define AdvApp2Var_ApproxF2var_HeaderFile #include <Standard_Macro.hxx> #include <AdvApp2Var_Data_f2c.hxx> #include <AdvApp2Var_EvaluatorFunc2Var.hxx> // class AdvApp2Var_ApproxF2var { public: Standard_EXPORT static int mma2fnc_(integer *ndimen, integer *nbsesp, integer *ndimse, doublereal *uvfonc, const AdvApp2Var_EvaluatorFunc2Var& foncnp, doublereal *tconst, integer *isofav, integer *nbroot, doublereal *rootlg, integer *iordre, integer *ideriv, integer *ndgjac, integer *nbcrmx, integer *ncflim, doublereal *epsapr, integer *ncoeff, doublereal *courbe, integer *nbcrbe, doublereal *somtab, doublereal *diftab, doublereal *contr1, doublereal *contr2, doublereal *tabdec, doublereal *errmax, doublereal *errmoy, integer *iercod); Standard_EXPORT static int mma2roo_(integer *nbpntu, integer *nbpntv, doublereal *urootl, doublereal *vrootl); Standard_EXPORT static int mma2jmx_(integer *ndgjac, integer *iordre, doublereal *xjacmx); Standard_EXPORT static int mmapptt_(const integer * , const integer * , const integer * , doublereal * , integer * ); Standard_EXPORT static int mma2cdi_(integer *ndimen, integer *nbpntu, doublereal *urootl, integer *nbpntv, doublereal *vrootl, integer *iordru, integer *iordrv, doublereal *contr1, doublereal *contr2, doublereal *contr3, doublereal *contr4, doublereal *sotbu1, doublereal *sotbu2, doublereal *ditbu1, doublereal *ditbu2, doublereal *sotbv1, doublereal *sotbv2, doublereal *ditbv1, doublereal *ditbv2, doublereal *sosotb, doublereal *soditb, doublereal *disotb, doublereal *diditb, integer *iercod); Standard_EXPORT static int mma2ds1_(integer *ndimen, doublereal *uintfn, doublereal *vintfn, const AdvApp2Var_EvaluatorFunc2Var& foncnp, integer *nbpntu, integer *nbpntv, doublereal *urootb, doublereal *vrootb, integer *isofav, doublereal *sosotb, doublereal *disotb, doublereal *soditb, doublereal *diditb, doublereal *fpntab, doublereal *ttable, integer *iercod); Standard_EXPORT static int mma2ce1_(integer *numdec, integer *ndimen, integer *nbsesp, integer *ndimse, integer *ndminu, integer *ndminv, integer *ndguli, integer *ndgvli, integer *ndjacu, integer *ndjacv, integer *iordru, integer *iordrv, integer *nbpntu, integer *nbpntv, doublereal *epsapr, doublereal *sosotb, doublereal *disotb, doublereal *soditb, doublereal *diditb, doublereal *patjac, doublereal *errmax, doublereal *errmoy, integer *ndegpu, integer *ndegpv, integer *itydec, integer *iercod); Standard_EXPORT static int mma2can_(const integer * , const integer * , const integer * , const integer * , const integer * , const integer * , const integer * , const doublereal *, doublereal * , doublereal * , integer * ); Standard_EXPORT static int mma1her_(const integer * , doublereal * , integer * ); Standard_EXPORT static int mma2ac2_(const integer * , const integer * , const integer * , const integer * , const integer * , const integer * , const doublereal * , const integer * , const doublereal * , const doublereal * , doublereal * ); Standard_EXPORT static int mma2ac3_(const integer * , const integer * , const integer * , const integer * , const integer * , const integer * , const doublereal * , const integer * , const doublereal * , const doublereal * , doublereal * ); Standard_EXPORT static int mma2ac1_(const integer * , const integer * , const integer * , const integer * , const integer * , const doublereal * , const doublereal * , const doublereal * , const doublereal * , const doublereal * , const doublereal * , doublereal * ); Standard_EXPORT static int mma2fx6_(integer *ncfmxu, integer *ncfmxv, integer *ndimen, integer *nbsesp, integer *ndimse, integer *nbupat, integer *nbvpat, integer *iordru, integer *iordrv, doublereal *epsapr, doublereal *epsfro, doublereal *patcan, doublereal *errmax, integer *ncoefu, integer *ncoefv); }; #endif
6,133
2,775
/* ============================================================================== This is an automatically generated GUI class created by the Projucer! Be careful when adding custom code to these files, as only the code within the "//[xyz]" and "//[/xyz]" sections will be retained when the file is loaded and re-saved. Created with Projucer version: 5.4.1 ------------------------------------------------------------------------------ The Projucer is part of the JUCE library. Copyright (c) 2017 - ROLI Ltd. ============================================================================== */ //[Headers] You can add your own extra header files here... #include "ui/components/wave_label.h" #include "ui/components/info_display.h" #include "adl/instrument.h" #include "parameter_block.h" #include <cmath> //[/Headers] #include "operator_editor.h" //[MiscUserDefs] You can add your own user definitions and misc code here... //[/MiscUserDefs] //============================================================================== Operator_Editor::Operator_Editor (unsigned op_id, Parameter_Block &pb) { //[Constructor_pre] You can add your own custom stuff here.. operator_id_ = op_id; parameter_block_ = &pb; //[/Constructor_pre] kn_attack.reset (new Styled_Knob_Default()); addAndMakeVisible (kn_attack.get()); kn_attack->setName ("new component"); kn_attack->setBounds (24, 3, 48, 48); kn_decay.reset (new Styled_Knob_Default()); addAndMakeVisible (kn_decay.get()); kn_decay->setName ("new component"); kn_decay->setBounds (96, 3, 48, 48); kn_sustain.reset (new Styled_Knob_Default()); addAndMakeVisible (kn_sustain.get()); kn_sustain->setName ("new component"); kn_sustain->setBounds (24, 48, 48, 48); kn_release.reset (new Styled_Knob_Default()); addAndMakeVisible (kn_release.get()); kn_release->setName ("new component"); kn_release->setBounds (96, 48, 48, 48); btn_prev_wave.reset (new TextButton ("new button")); addAndMakeVisible (btn_prev_wave.get()); btn_prev_wave->setButtonText (TRANS("<")); btn_prev_wave->setConnectedEdges (Button::ConnectedOnRight); btn_prev_wave->addListener (this); btn_prev_wave->setBounds (3, 96, 23, 24); btn_next_wave.reset (new TextButton ("new button")); addAndMakeVisible (btn_next_wave.get()); btn_next_wave->setButtonText (TRANS(">")); btn_next_wave->setConnectedEdges (Button::ConnectedOnLeft); btn_next_wave->addListener (this); btn_next_wave->setBounds (132, 96, 23, 24); btn_trem.reset (new TextButton ("new button")); addAndMakeVisible (btn_trem.get()); btn_trem->setButtonText (String()); btn_trem->addListener (this); btn_trem->setColour (TextButton::buttonOnColourId, Colour (0xff42a2c8)); btn_trem->setBounds (168, 3, 15, 15); btn_vib.reset (new TextButton ("new button")); addAndMakeVisible (btn_vib.get()); btn_vib->setButtonText (String()); btn_vib->addListener (this); btn_vib->setColour (TextButton::buttonOnColourId, Colour (0xff42a2c8)); btn_vib->setBounds (168, 20, 15, 15); btn_sus.reset (new TextButton ("new button")); addAndMakeVisible (btn_sus.get()); btn_sus->setButtonText (String()); btn_sus->addListener (this); btn_sus->setColour (TextButton::buttonOnColourId, Colour (0xff42a2c8)); btn_sus->setBounds (168, 37, 15, 15); btn_env.reset (new TextButton ("new button")); addAndMakeVisible (btn_env.get()); btn_env->setButtonText (String()); btn_env->addListener (this); btn_env->setColour (TextButton::buttonOnColourId, Colour (0xff42a2c8)); btn_env->setBounds (168, 54, 15, 15); lbl_level.reset (new Label ("new label", TRANS("Lv"))); addAndMakeVisible (lbl_level.get()); lbl_level->setFont (Font (14.0f, Font::plain).withTypefaceStyle ("Regular")); lbl_level->setJustificationType (Justification::centredLeft); lbl_level->setEditable (false, false, false); lbl_level->setColour (Label::textColourId, Colours::aliceblue); lbl_level->setColour (TextEditor::textColourId, Colours::black); lbl_level->setColour (TextEditor::backgroundColourId, Colour (0x00000000)); lbl_level->setBounds (163, 72, 28, 16); lbl_wave.reset (new Wave_Label (chip_waves_)); addAndMakeVisible (lbl_wave.get()); lbl_wave->setName ("new component"); lbl_wave->setBounds (26, 96, 106, 24); label.reset (new Label ("new label", TRANS("A"))); addAndMakeVisible (label.get()); label->setFont (Font (15.0f, Font::plain).withTypefaceStyle ("Regular")); label->setJustificationType (Justification::centredTop); label->setEditable (false, false, false); label->setColour (Label::textColourId, Colours::aliceblue); label->setColour (TextEditor::textColourId, Colours::black); label->setColour (TextEditor::backgroundColourId, Colour (0x00000000)); label->setBounds (4, 0, 20, 16); label2.reset (new Label ("new label", TRANS("D"))); addAndMakeVisible (label2.get()); label2->setFont (Font (15.0f, Font::plain).withTypefaceStyle ("Regular")); label2->setJustificationType (Justification::centredTop); label2->setEditable (false, false, false); label2->setColour (Label::textColourId, Colours::aliceblue); label2->setColour (TextEditor::textColourId, Colours::black); label2->setColour (TextEditor::backgroundColourId, Colour (0x00000000)); label2->setBounds (76, 0, 20, 16); label3.reset (new Label ("new label", TRANS("S"))); addAndMakeVisible (label3.get()); label3->setFont (Font (15.0f, Font::plain).withTypefaceStyle ("Regular")); label3->setJustificationType (Justification::centredTop); label3->setEditable (false, false, false); label3->setColour (Label::textColourId, Colours::aliceblue); label3->setColour (TextEditor::textColourId, Colours::black); label3->setColour (TextEditor::backgroundColourId, Colour (0x00000000)); label3->setBounds (4, 48, 20, 16); label4.reset (new Label ("new label", TRANS("R"))); addAndMakeVisible (label4.get()); label4->setFont (Font (15.0f, Font::plain).withTypefaceStyle ("Regular")); label4->setJustificationType (Justification::centredTop); label4->setEditable (false, false, false); label4->setColour (Label::textColourId, Colours::aliceblue); label4->setColour (TextEditor::textColourId, Colours::black); label4->setColour (TextEditor::backgroundColourId, Colour (0x00000000)); label4->setBounds (76, 48, 20, 16); label5.reset (new Label ("new label", TRANS("Tremolo"))); addAndMakeVisible (label5.get()); label5->setFont (Font (14.0f, Font::plain).withTypefaceStyle ("Regular")); label5->setJustificationType (Justification::centredLeft); label5->setEditable (false, false, false); label5->setColour (Label::textColourId, Colours::aliceblue); label5->setColour (TextEditor::textColourId, Colours::black); label5->setColour (TextEditor::backgroundColourId, Colour (0x00000000)); label5->setBounds (184, 3, 80, 15); label6.reset (new Label ("new label", TRANS("Vibrato"))); addAndMakeVisible (label6.get()); label6->setFont (Font (14.0f, Font::plain).withTypefaceStyle ("Regular")); label6->setJustificationType (Justification::centredLeft); label6->setEditable (false, false, false); label6->setColour (Label::textColourId, Colours::aliceblue); label6->setColour (TextEditor::textColourId, Colours::black); label6->setColour (TextEditor::backgroundColourId, Colour (0x00000000)); label6->setBounds (184, 20, 80, 15); label7.reset (new Label ("new label", TRANS("Sustain"))); addAndMakeVisible (label7.get()); label7->setFont (Font (14.0f, Font::plain).withTypefaceStyle ("Regular")); label7->setJustificationType (Justification::centredLeft); label7->setEditable (false, false, false); label7->setColour (Label::textColourId, Colours::aliceblue); label7->setColour (TextEditor::textColourId, Colours::black); label7->setColour (TextEditor::backgroundColourId, Colour (0x00000000)); label7->setBounds (184, 37, 80, 15); label8.reset (new Label ("new label", TRANS("Key scaling"))); addAndMakeVisible (label8.get()); label8->setFont (Font (14.0f, Font::plain).withTypefaceStyle ("Regular")); label8->setJustificationType (Justification::centredLeft); label8->setEditable (false, false, false); label8->setColour (Label::textColourId, Colours::aliceblue); label8->setColour (TextEditor::textColourId, Colours::black); label8->setColour (TextEditor::backgroundColourId, Colour (0x00000000)); label8->setBounds (184, 54, 80, 15); lbl_fmul.reset (new Label ("new label", TRANS("F*"))); addAndMakeVisible (lbl_fmul.get()); lbl_fmul->setFont (Font (14.0f, Font::plain).withTypefaceStyle ("Regular")); lbl_fmul->setJustificationType (Justification::centredLeft); lbl_fmul->setEditable (false, false, false); lbl_fmul->setColour (Label::textColourId, Colours::aliceblue); lbl_fmul->setColour (TextEditor::textColourId, Colours::black); lbl_fmul->setColour (TextEditor::backgroundColourId, Colour (0x00000000)); lbl_fmul->setBounds (163, 88, 28, 16); lbl_ksl.reset (new Label ("new label", TRANS("Ksl"))); addAndMakeVisible (lbl_ksl.get()); lbl_ksl->setFont (Font (14.0f, Font::plain).withTypefaceStyle ("Regular")); lbl_ksl->setJustificationType (Justification::centredLeft); lbl_ksl->setEditable (false, false, false); lbl_ksl->setColour (Label::textColourId, Colours::aliceblue); lbl_ksl->setColour (TextEditor::textColourId, Colours::black); lbl_ksl->setColour (TextEditor::backgroundColourId, Colour (0x00000000)); lbl_ksl->setBounds (163, 104, 28, 16); sl_level.reset (new Styled_Slider_DefaultSmall()); addAndMakeVisible (sl_level.get()); sl_level->setName ("new component"); sl_level->setBounds (195, 70, 64, 20); sl_fmul.reset (new Styled_Slider_DefaultSmall()); addAndMakeVisible (sl_fmul.get()); sl_fmul->setName ("new component"); sl_fmul->setBounds (195, 86, 64, 20); sl_ksl.reset (new Styled_Slider_DefaultSmall()); addAndMakeVisible (sl_ksl.get()); sl_ksl->setName ("new component"); sl_ksl->setBounds (195, 102, 64, 20); //[UserPreSize] sl_level->add_listener(this); sl_level->set_range(0, 63); sl_level->set_max_increment(1); sl_fmul->add_listener(this); sl_fmul->set_range(0, 15); sl_fmul->set_max_increment(1); sl_ksl->add_listener(this); sl_ksl->set_range(0, 3); sl_ksl->set_max_increment(1); kn_attack->add_listener(this); kn_attack->set_max_increment(1); kn_decay->add_listener(this); kn_decay->set_max_increment(1); kn_sustain->add_listener(this); kn_sustain->set_max_increment(1); kn_release->add_listener(this); kn_release->set_max_increment(1); btn_trem->setClickingTogglesState(true); btn_vib->setClickingTogglesState(true); btn_sus->setClickingTogglesState(true); btn_env->setClickingTogglesState(true); //[/UserPreSize] setSize (264, 128); //[Constructor] You can add your own custom stuff here.. kn_attack->set_range(0, 15); kn_decay->set_range(0, 15); kn_sustain->set_range(0, 15); kn_release->set_range(0, 15); //[/Constructor] } Operator_Editor::~Operator_Editor() { //[Destructor_pre]. You can add your own custom destruction code here.. //[/Destructor_pre] kn_attack = nullptr; kn_decay = nullptr; kn_sustain = nullptr; kn_release = nullptr; btn_prev_wave = nullptr; btn_next_wave = nullptr; btn_trem = nullptr; btn_vib = nullptr; btn_sus = nullptr; btn_env = nullptr; lbl_level = nullptr; lbl_wave = nullptr; label = nullptr; label2 = nullptr; label3 = nullptr; label4 = nullptr; label5 = nullptr; label6 = nullptr; label7 = nullptr; label8 = nullptr; lbl_fmul = nullptr; lbl_ksl = nullptr; sl_level = nullptr; sl_fmul = nullptr; sl_ksl = nullptr; //[Destructor]. You can add your own custom destruction code here.. //[/Destructor] } //============================================================================== void Operator_Editor::paint (Graphics& g) { //[UserPrePaint] Add your own custom painting code here.. //[/UserPrePaint] { int x = 25, y = 96, width = 108, height = 24; Colour strokeColour = Colour (0xff8e989b); //[UserPaintCustomArguments] Customize the painting arguments here.. //[/UserPaintCustomArguments] g.setColour (strokeColour); g.drawRect (x, y, width, height, 1); } { float x = 0.0f, y = 0.0f, width = 264.0f, height = 128.0f; Colour fillColour = Colour (0x662e4c4d); //[UserPaintCustomArguments] Customize the painting arguments here.. //[/UserPaintCustomArguments] g.setColour (fillColour); g.fillRoundedRectangle (x, y, width, height, 7.0f); } //[UserPaint] Add your own custom painting code here.. //[/UserPaint] } void Operator_Editor::resized() { //[UserPreResize] Add your own custom resize code here.. //[/UserPreResize] //[UserResized] Add your own custom resize handling here.. //[/UserResized] } void Operator_Editor::buttonClicked (Button* buttonThatWasClicked) { //[UserbuttonClicked_Pre] Parameter_Block &pb = *parameter_block_; Parameter_Block::Part &part = pb.part[midichannel_]; Parameter_Block::Operator &op = part.nth_operator(operator_id_); Button *btn = buttonThatWasClicked; //[/UserbuttonClicked_Pre] if (buttonThatWasClicked == btn_prev_wave.get()) { //[UserButtonCode_btn_prev_wave] -- add your button handler code here.. AudioParameterChoice &p = *op.p_wave; p.beginChangeGesture(); int wave = std::max(p.getIndex() - 1, 0); p = wave; p.endChangeGesture(); lbl_wave->set_wave(wave, dontSendNotification); //[/UserButtonCode_btn_prev_wave] } else if (buttonThatWasClicked == btn_next_wave.get()) { //[UserButtonCode_btn_next_wave] -- add your button handler code here.. AudioParameterChoice &p = *op.p_wave; p.beginChangeGesture(); int wave = std::min(p.getIndex() + 1, p.choices.size() - 1); p = wave; p.endChangeGesture(); lbl_wave->set_wave(wave, dontSendNotification); //[/UserButtonCode_btn_next_wave] } else if (buttonThatWasClicked == btn_trem.get()) { //[UserButtonCode_btn_trem] -- add your button handler code here.. AudioParameterBool &p = *op.p_trem; p.beginChangeGesture(); p = btn->getToggleState(); p.endChangeGesture(); //[/UserButtonCode_btn_trem] } else if (buttonThatWasClicked == btn_vib.get()) { //[UserButtonCode_btn_vib] -- add your button handler code here.. AudioParameterBool &p = *op.p_vib; p.beginChangeGesture(); p = btn->getToggleState(); p.endChangeGesture(); //[/UserButtonCode_btn_vib] } else if (buttonThatWasClicked == btn_sus.get()) { //[UserButtonCode_btn_sus] -- add your button handler code here.. AudioParameterBool &p = *op.p_sus; p.beginChangeGesture(); p = btn->getToggleState(); p.endChangeGesture(); //[/UserButtonCode_btn_sus] } else if (buttonThatWasClicked == btn_env.get()) { //[UserButtonCode_btn_env] -- add your button handler code here.. AudioParameterBool &p = *op.p_env; p.beginChangeGesture(); p = btn->getToggleState(); p.endChangeGesture(); //[/UserButtonCode_btn_env] } //[UserbuttonClicked_Post] if (display_info_for_component(btn)) info_->expire_info_in(); //[/UserbuttonClicked_Post] } //[MiscUserCode] You can add your own definitions of your custom methods or any other code here... static unsigned swap_ksl(unsigned ksl) { // OPL mapping for KSL (dB/oct): 0=>0, 1=>3, 2=>1.5, 3=>6 // for user-friendly ordering, the UI control will swap 1 and 2 switch (ksl) { case 1: return 2; case 2: return 1; default: return ksl; } } void Operator_Editor::set_operator_parameters(const Instrument &ins, unsigned op, NotificationType ntf) { kn_attack->set_value(ins.attack(op), ntf); kn_decay->set_value(ins.decay(op), ntf); kn_sustain->set_value(ins.sustain(op), ntf); kn_release->set_value(ins.release(op), ntf); sl_level->set_value(ins.level(op), ntf); sl_fmul->set_value(ins.fmul(op), ntf); sl_ksl->set_value(swap_ksl(ins.ksl(op)), ntf); btn_trem->setToggleState(ins.trem(op), ntf); btn_vib->setToggleState(ins.vib(op), ntf); btn_sus->setToggleState(ins.sus(op), ntf); btn_env->setToggleState(ins.env(op), ntf); lbl_wave->set_wave(ins.wave(op), ntf); } void Operator_Editor::set_operator_enabled(bool b) { if (b == operator_enabled_) return; operator_enabled_ = b; repaint(); } void Operator_Editor::knob_value_changed(Knob *k) { Parameter_Block &pb = *parameter_block_; Parameter_Block::Part &part = pb.part[midichannel_]; Parameter_Block::Operator &op = part.nth_operator(operator_id_); if (k == sl_level.get()) { AudioParameterInt &p = *op.p_level; p = (int)std::lround(k->value()); } else if (k == sl_fmul.get()) { AudioParameterInt &p = *op.p_fmul; p = (int)std::lround(k->value()); } else if (k == sl_ksl.get()) { AudioParameterInt &p = *op.p_ksl; p = swap_ksl((int)std::lround(k->value())); } else if (k == kn_attack.get()) { AudioParameterInt &p = *op.p_attack; p = (int)std::lround(k->value()); } else if (k == kn_decay.get()) { AudioParameterInt &p = *op.p_decay; p = (int)std::lround(k->value()); } else if (k == kn_sustain.get()) { AudioParameterInt &p = *op.p_sustain; p = (int)std::lround(k->value()); } else if (k == kn_release.get()) { AudioParameterInt &p = *op.p_release; p = (int)std::lround(k->value()); } display_info_for_component(k); } void Operator_Editor::knob_drag_started(Knob *k) { Parameter_Block &pb = *parameter_block_; Parameter_Block::Part &part = pb.part[midichannel_]; Parameter_Block::Operator &op = part.nth_operator(operator_id_); if (k == sl_level.get()) { AudioParameterInt &p = *op.p_level; p.beginChangeGesture(); } else if (k == sl_fmul.get()) { AudioParameterInt &p = *op.p_fmul; p.beginChangeGesture(); } else if (k == sl_ksl.get()) { AudioParameterInt &p = *op.p_ksl; p.beginChangeGesture(); } else if (k == kn_attack.get()) { AudioParameterInt &p = *op.p_attack; p.beginChangeGesture(); } else if (k == kn_decay.get()) { AudioParameterInt &p = *op.p_decay; p.beginChangeGesture(); } else if (k == kn_sustain.get()) { AudioParameterInt &p = *op.p_sustain; p.beginChangeGesture(); } else if (k == kn_release.get()) { AudioParameterInt &p = *op.p_release; p.beginChangeGesture(); } display_info_for_component(k); } void Operator_Editor::knob_drag_ended(Knob *k) { Parameter_Block &pb = *parameter_block_; Parameter_Block::Part &part = pb.part[midichannel_]; Parameter_Block::Operator &op = part.nth_operator(operator_id_); if (k == sl_level.get()) { AudioParameterInt &p = *op.p_level; p.endChangeGesture(); } else if (k == sl_fmul.get()) { AudioParameterInt &p = *op.p_fmul; p.endChangeGesture(); } else if (k == sl_ksl.get()) { AudioParameterInt &p = *op.p_ksl; p.endChangeGesture(); } else if (k == kn_attack.get()) { AudioParameterInt &p = *op.p_attack; p.endChangeGesture(); } else if (k == kn_decay.get()) { AudioParameterInt &p = *op.p_decay; p.endChangeGesture(); } else if (k == kn_sustain.get()) { AudioParameterInt &p = *op.p_sustain; p.endChangeGesture(); } else if (k == kn_release.get()) { AudioParameterInt &p = *op.p_release; p.endChangeGesture(); } info_->expire_info_in(); } void Operator_Editor::paintOverChildren(Graphics &g) { if (!operator_enabled_) { Rectangle<int> bounds = getLocalBounds(); g.setColour(Colour(0x66777777)); g.fillRoundedRectangle(bounds.toFloat(), 7.0f); } } bool Operator_Editor::display_info_for_component(Component *c) { String param; int val = 0; const char *prefixes[4] = {"Op2 ", "Op1 ", "Op4 ", "Op3 "}; String prefix = prefixes[operator_id_]; Knob *kn = static_cast<Knob *>(c); if (c == sl_level.get()) { param = prefix + "Level"; val = (int)std::lround(kn->value()); } else if (c == sl_fmul.get()) { param = prefix + "Frequency multiplier"; val = (int)std::lround(kn->value()); } else if (c == sl_ksl.get()) { param = prefix + "Key scale level"; val = swap_ksl((int)std::lround(kn->value())); } else if (c == kn_attack.get()) { param = prefix + "Attack"; val = (int)std::lround(kn->value()); } else if (c == kn_decay.get()) { param = prefix + "Decay"; val = (int)std::lround(kn->value()); } else if (c == kn_sustain.get()) { param = prefix + "Sustain"; val = (int)std::lround(kn->value()); } else if (c == kn_release.get()) { param = prefix + "Release"; val = (int)std::lround(kn->value()); } else if (c == btn_next_wave.get() || c == btn_prev_wave.get()) { param = prefix + "Wave"; val = lbl_wave->wave(); } if (param.isEmpty()) return false; info_->display_info(param + " = " + String(val)); return true; } //[/MiscUserCode] //============================================================================== #if 0 /* -- Projucer information section -- This is where the Projucer stores the metadata that describe this GUI layout, so make changes in here at your peril! BEGIN_JUCER_METADATA <JUCER_COMPONENT documentType="Component" className="Operator_Editor" componentName="" parentClasses="public Component, public Knob::Listener" constructorParams="unsigned op_id, Parameter_Block &amp;pb" variableInitialisers="" snapPixels="8" snapActive="1" snapShown="1" overlayOpacity="0.33" fixedSize="0" initialWidth="264" initialHeight="128"> <BACKGROUND backgroundColour="323e44"> <RECT pos="25 96 108 24" fill="solid: 0" hasStroke="1" stroke="1, mitered, butt" strokeColour="solid: ff8e989b"/> <ROUNDRECT pos="0 0 264 128" cornerSize="7.0" fill="solid: 662e4c4d" hasStroke="0"/> </BACKGROUND> <GENERICCOMPONENT name="new component" id="7c54ff103d9f5d" memberName="kn_attack" virtualName="" explicitFocusOrder="0" pos="24 3 48 48" class="Styled_Knob_Default" params=""/> <GENERICCOMPONENT name="new component" id="be39ad00dcf6efe1" memberName="kn_decay" virtualName="" explicitFocusOrder="0" pos="96 3 48 48" class="Styled_Knob_Default" params=""/> <GENERICCOMPONENT name="new component" id="8d88729c124c7b16" memberName="kn_sustain" virtualName="" explicitFocusOrder="0" pos="24 48 48 48" class="Styled_Knob_Default" params=""/> <GENERICCOMPONENT name="new component" id="7d576b68e9b588f" memberName="kn_release" virtualName="" explicitFocusOrder="0" pos="96 48 48 48" class="Styled_Knob_Default" params=""/> <TEXTBUTTON name="new button" id="cbf65c7349d1d293" memberName="btn_prev_wave" virtualName="" explicitFocusOrder="0" pos="3 96 23 24" buttonText="&lt;" connectedEdges="2" needsCallback="1" radioGroupId="0"/> <TEXTBUTTON name="new button" id="6fc5dc04c6c5d6b9" memberName="btn_next_wave" virtualName="" explicitFocusOrder="0" pos="132 96 23 24" buttonText="&gt;" connectedEdges="1" needsCallback="1" radioGroupId="0"/> <TEXTBUTTON name="new button" id="f60e70ed4f10ef32" memberName="btn_trem" virtualName="" explicitFocusOrder="0" pos="168 3 15 15" bgColOn="ff42a2c8" buttonText="" connectedEdges="0" needsCallback="1" radioGroupId="0"/> <TEXTBUTTON name="new button" id="501ccf7ad0bc53a7" memberName="btn_vib" virtualName="" explicitFocusOrder="0" pos="168 20 15 15" bgColOn="ff42a2c8" buttonText="" connectedEdges="0" needsCallback="1" radioGroupId="0"/> <TEXTBUTTON name="new button" id="3e46dd6b966c40b2" memberName="btn_sus" virtualName="" explicitFocusOrder="0" pos="168 37 15 15" bgColOn="ff42a2c8" buttonText="" connectedEdges="0" needsCallback="1" radioGroupId="0"/> <TEXTBUTTON name="new button" id="eb8e9dfd42dd8f57" memberName="btn_env" virtualName="" explicitFocusOrder="0" pos="168 54 15 15" bgColOn="ff42a2c8" buttonText="" connectedEdges="0" needsCallback="1" radioGroupId="0"/> <LABEL name="new label" id="ce54b68fc1a1f1e1" memberName="lbl_level" virtualName="" explicitFocusOrder="0" pos="163 72 28 16" textCol="fff0f8ff" edTextCol="ff000000" edBkgCol="0" labelText="Lv" editableSingleClick="0" editableDoubleClick="0" focusDiscardsChanges="0" fontname="Default font" fontsize="14.0" kerning="0.0" bold="0" italic="0" justification="33"/> <GENERICCOMPONENT name="new component" id="dd16fb8d4c488877" memberName="lbl_wave" virtualName="" explicitFocusOrder="0" pos="26 96 106 24" class="Wave_Label" params="chip_waves_"/> <LABEL name="new label" id="664ae98bd7a6b3a5" memberName="label" virtualName="" explicitFocusOrder="0" pos="4 0 20 16" textCol="fff0f8ff" edTextCol="ff000000" edBkgCol="0" labelText="A" editableSingleClick="0" editableDoubleClick="0" focusDiscardsChanges="0" fontname="Default font" fontsize="15.0" kerning="0.0" bold="0" italic="0" justification="12"/> <LABEL name="new label" id="360efe252ecea296" memberName="label2" virtualName="" explicitFocusOrder="0" pos="76 0 20 16" textCol="fff0f8ff" edTextCol="ff000000" edBkgCol="0" labelText="D" editableSingleClick="0" editableDoubleClick="0" focusDiscardsChanges="0" fontname="Default font" fontsize="15.0" kerning="0.0" bold="0" italic="0" justification="12"/> <LABEL name="new label" id="d276bb335fab1f40" memberName="label3" virtualName="" explicitFocusOrder="0" pos="4 48 20 16" textCol="fff0f8ff" edTextCol="ff000000" edBkgCol="0" labelText="S" editableSingleClick="0" editableDoubleClick="0" focusDiscardsChanges="0" fontname="Default font" fontsize="15.0" kerning="0.0" bold="0" italic="0" justification="12"/> <LABEL name="new label" id="2ad02ec8c7135a27" memberName="label4" virtualName="" explicitFocusOrder="0" pos="76 48 20 16" textCol="fff0f8ff" edTextCol="ff000000" edBkgCol="0" labelText="R" editableSingleClick="0" editableDoubleClick="0" focusDiscardsChanges="0" fontname="Default font" fontsize="15.0" kerning="0.0" bold="0" italic="0" justification="12"/> <LABEL name="new label" id="ffcd49be138de78b" memberName="label5" virtualName="" explicitFocusOrder="0" pos="184 3 80 15" textCol="fff0f8ff" edTextCol="ff000000" edBkgCol="0" labelText="Tremolo" editableSingleClick="0" editableDoubleClick="0" focusDiscardsChanges="0" fontname="Default font" fontsize="14.0" kerning="0.0" bold="0" italic="0" justification="33"/> <LABEL name="new label" id="37e7947c4443e047" memberName="label6" virtualName="" explicitFocusOrder="0" pos="184 20 80 15" textCol="fff0f8ff" edTextCol="ff000000" edBkgCol="0" labelText="Vibrato" editableSingleClick="0" editableDoubleClick="0" focusDiscardsChanges="0" fontname="Default font" fontsize="14.0" kerning="0.0" bold="0" italic="0" justification="33"/> <LABEL name="new label" id="f04d949c957007e" memberName="label7" virtualName="" explicitFocusOrder="0" pos="184 37 80 15" textCol="fff0f8ff" edTextCol="ff000000" edBkgCol="0" labelText="Sustain" editableSingleClick="0" editableDoubleClick="0" focusDiscardsChanges="0" fontname="Default font" fontsize="14.0" kerning="0.0" bold="0" italic="0" justification="33"/> <LABEL name="new label" id="e8cd7412f499955d" memberName="label8" virtualName="" explicitFocusOrder="0" pos="184 54 80 15" textCol="fff0f8ff" edTextCol="ff000000" edBkgCol="0" labelText="Key scaling" editableSingleClick="0" editableDoubleClick="0" focusDiscardsChanges="0" fontname="Default font" fontsize="14.0" kerning="0.0" bold="0" italic="0" justification="33"/> <LABEL name="new label" id="e77fa8c6c00316b7" memberName="lbl_fmul" virtualName="" explicitFocusOrder="0" pos="163 88 28 16" textCol="fff0f8ff" edTextCol="ff000000" edBkgCol="0" labelText="F*" editableSingleClick="0" editableDoubleClick="0" focusDiscardsChanges="0" fontname="Default font" fontsize="14.0" kerning="0.0" bold="0" italic="0" justification="33"/> <LABEL name="new label" id="dbcb4d45f32ea3e9" memberName="lbl_ksl" virtualName="" explicitFocusOrder="0" pos="163 104 28 16" textCol="fff0f8ff" edTextCol="ff000000" edBkgCol="0" labelText="Ksl" editableSingleClick="0" editableDoubleClick="0" focusDiscardsChanges="0" fontname="Default font" fontsize="14.0" kerning="0.0" bold="0" italic="0" justification="33"/> <GENERICCOMPONENT name="new component" id="d7383c8ec7f64dfc" memberName="sl_level" virtualName="" explicitFocusOrder="0" pos="195 70 64 20" class="Styled_Slider_DefaultSmall" params=""/> <GENERICCOMPONENT name="new component" id="37e9a27164f2dd8e" memberName="sl_fmul" virtualName="" explicitFocusOrder="0" pos="195 86 64 20" class="Styled_Slider_DefaultSmall" params=""/> <GENERICCOMPONENT name="new component" id="1836679269ce1d4f" memberName="sl_ksl" virtualName="" explicitFocusOrder="0" pos="195 102 64 20" class="Styled_Slider_DefaultSmall" params=""/> </JUCER_COMPONENT> END_JUCER_METADATA */ #endif //[EndFile] You can add extra defines here... //[/EndFile]
31,992
11,792
// specialization for small alphabets ----------------------------------------- template <typename T, class M> class PCencoder<T, M, false> { public: PCencoder(RCencoder* re, RCmodel*const* rm) : re(re), rm(rm) {} T encode(T real, T pred, uint context = 0); static const uint symbols = 2 * (1 << M::bits) - 1; private: static const uint bias = (1 << M::bits) - 1; // perfect prediction symbol M map; // maps T to integer type RCencoder*const re; // entropy encoder RCmodel*const* rm; // probability modeler(s) }; // encode narrow range type template <typename T, class M> T PCencoder<T, M, false>::encode(T real, T pred, uint context) { // map type T to unsigned integer type typedef typename M::Range U; U r = map.forward(real); U p = map.forward(pred); // entropy encode d = r - p re->encode(static_cast<uint>(bias + r - p), rm[context]); // return decoded value return map.inverse(r); } // specialization for large alphabets ----------------------------------------- template <typename T, class M> class PCencoder<T, M, true> { public: PCencoder(RCencoder* re, RCmodel*const* rm) : re(re), rm(rm) {} T encode(T real, T pred, uint context = 0); static const uint symbols = 2 * M::bits + 1; private: static const uint bias = M::bits; // perfect prediction symbol M map; // maps T to integer type RCencoder*const re; // entropy encoder RCmodel*const* rm; // probability modeler(s) }; // encode wide range type template <typename T, class M> T PCencoder<T, M, true>::encode(T real, T pred, uint context) { // map type T to unsigned integer type typedef typename M::Range U; U r = map.forward(real); U p = map.forward(pred); // compute (-1)^s (2^k + m) = r - p, entropy code (s, k), // and encode the k-bit number m verbatim if (p < r) { // underprediction U d = r - p; uint k = PC::bsr(d); re->encode(bias + 1 + k, rm[context]); re->encode(d - (U(1) << k), k); } else if (p > r) { // overprediction U d = p - r; uint k = PC::bsr(d); re->encode(bias - 1 - k, rm[context]); re->encode(d - (U(1) << k), k); } else // perfect prediction re->encode(bias, rm[context]); // return decoded value return map.inverse(r); }
2,386
800
#include "../.././Core/IO/Pipes.hh"
38
21
// Copyright 2016-2018 Doug Moen // Licensed under the Apache License, version 2.0 // See accompanying file LICENSE or https://www.apache.org/licenses/LICENSE-2.0 #include <cassert> #include <cmath> #include <cstdlib> #include <string> #include <boost/math/constants/constants.hpp> #include <boost/filesystem.hpp> #include <curv/arg.h> #include <curv/builtin.h> #include <curv/program.h> #include <curv/exception.h> #include <curv/file.h> #include <curv/function.h> #include <curv/shape.h> #include <curv/system.h> #include <curv/gl_context.h> #include <curv/array_op.h> #include <curv/analyser.h> #include <curv/math.h> using namespace std; using namespace boost::math::double_constants; namespace curv { Shared<Meaning> Builtin_Value::to_meaning(const Identifier& id) const { return make<Constant>(share(id), value_); } struct Is_Null_Function : public Polyadic_Function { Is_Null_Function() : Polyadic_Function(1) {} Value call(Frame& args) override { return {args[0].is_null()}; } }; struct Is_Bool_Function : public Polyadic_Function { Is_Bool_Function() : Polyadic_Function(1) {} Value call(Frame& args) override { return {args[0].is_bool()}; } }; struct Is_Num_Function : public Polyadic_Function { Is_Num_Function() : Polyadic_Function(1) {} Value call(Frame& args) override { return {args[0].is_num()}; } }; struct Is_String_Function : public Polyadic_Function { Is_String_Function() : Polyadic_Function(1) {} Value call(Frame& args) override { return {args[0].dycast<String>() != nullptr}; } }; struct Is_List_Function : public Polyadic_Function { Is_List_Function() : Polyadic_Function(1) {} Value call(Frame& args) override { return {args[0].dycast<List>() != nullptr}; } }; struct Is_Record_Function : public Polyadic_Function { Is_Record_Function() : Polyadic_Function(1) {} Value call(Frame& args) override { return {args[0].dycast<Structure>() != nullptr}; } }; struct Is_Fun_Function : public Polyadic_Function { Is_Fun_Function() : Polyadic_Function(1) {} Value call(Frame& args) override { return {args[0].dycast<Function>() != nullptr}; } }; struct Bit_Function : public Polyadic_Function { Bit_Function() : Polyadic_Function(1) {} Value call(Frame& args) override { return {double(args[0].to_bool(At_Arg(args)))}; } GL_Value gl_call(GL_Frame& f) const override { auto arg = f[0]; if (arg.type != GL_Type::Bool) throw Exception(At_GL_Arg(0, f), "bit: argument is not a bool"); auto result = f.gl.newvalue(GL_Type::Num); f.gl.out << " float "<<result<<" = float("<<arg<<");\n"; return result; } }; struct Sqrt_Function : public Polyadic_Function { Sqrt_Function() : Polyadic_Function(1) {} struct Scalar_Op { static double f(double x) { return sqrt(x); } static Shared<const String> callstr(Value x) { return stringify("sqrt(",x,")"); } }; static Unary_Numeric_Array_Op<Scalar_Op> array_op; Value call(Frame& args) override { return array_op.op(args[0], At_Frame(&args)); } GL_Value gl_call(GL_Frame& f) const override { return gl_call_unary_numeric(f, "sqrt"); } }; // log(x) is the natural logarithm of x struct Log_Function : public Polyadic_Function { Log_Function() : Polyadic_Function(1) {} struct Scalar_Op { static double f(double x) { return log(x); } static Shared<const String> callstr(Value x) { return stringify("log(",x,")"); } }; static Unary_Numeric_Array_Op<Scalar_Op> array_op; Value call(Frame& args) override { return array_op.op(args[0], At_Frame(&args)); } GL_Value gl_call(GL_Frame& f) const override { return gl_call_unary_numeric(f, "log"); } }; struct Abs_Function : public Polyadic_Function { Abs_Function() : Polyadic_Function(1) {} struct Scalar_Op { static double f(double x) { return abs(x); } static Shared<const String> callstr(Value x) { return stringify("abs(",x,")"); } }; static Unary_Numeric_Array_Op<Scalar_Op> array_op; Value call(Frame& args) override { return array_op.op(args[0], At_Frame(&args)); } GL_Value gl_call(GL_Frame& f) const override { return gl_call_unary_numeric(f, "abs"); } }; struct Floor_Function : public Polyadic_Function { Floor_Function() : Polyadic_Function(1) {} struct Scalar_Op { static double f(double x) { return floor(x); } static Shared<const String> callstr(Value x) { return stringify("floor(",x,")"); } }; static Unary_Numeric_Array_Op<Scalar_Op> array_op; Value call(Frame& args) override { return array_op.op(args[0], At_Frame(&args)); } GL_Value gl_call(GL_Frame& f) const override { return gl_call_unary_numeric(f, "floor"); } }; // round(x) -- round x to nearest integer. // CPU: in case of tie, round to even. // GPU: in case of tie, it's GPU/driver dependent. struct Round_Function : public Polyadic_Function { Round_Function() : Polyadic_Function(1) {} struct Scalar_Op { static double f(double x) { return rint(x); } static Shared<const String> callstr(Value x) { return stringify("round(",x,")"); } }; static Unary_Numeric_Array_Op<Scalar_Op> array_op; Value call(Frame& args) override { return array_op.op(args[0], At_Frame(&args)); } GL_Value gl_call(GL_Frame& f) const override { return gl_call_unary_numeric(f, "round"); } }; struct Sin_Function : public Polyadic_Function { Sin_Function() : Polyadic_Function(1) {} struct Scalar_Op { static double f(double x) { return sin(x); } static Shared<const String> callstr(Value x) { return stringify("sin(",x,")"); } }; static Unary_Numeric_Array_Op<Scalar_Op> array_op; Value call(Frame& args) override { return array_op.op(args[0], At_Frame(&args)); } GL_Value gl_call(GL_Frame& f) const override { return gl_call_unary_numeric(f, "sin"); } }; struct Asin_Function : public Polyadic_Function { Asin_Function() : Polyadic_Function(1) {} struct Scalar_Op { static double f(double x) { return asin(x); } static Shared<const String> callstr(Value x) { return stringify("asin(",x,")"); } }; static Unary_Numeric_Array_Op<Scalar_Op> array_op; Value call(Frame& args) override { return array_op.op(args[0], At_Frame(&args)); } GL_Value gl_call(GL_Frame& f) const override { return gl_call_unary_numeric(f, "asin"); } }; struct Cos_Function : public Polyadic_Function { Cos_Function() : Polyadic_Function(1) {} struct Scalar_Op { static double f(double x) { return cos(x); } static Shared<const String> callstr(Value x) { return stringify("cos(",x,")"); } }; static Unary_Numeric_Array_Op<Scalar_Op> array_op; Value call(Frame& args) override { return array_op.op(args[0], At_Frame(&args)); } GL_Value gl_call(GL_Frame& f) const override { return gl_call_unary_numeric(f, "cos"); } }; struct Acos_Function : public Polyadic_Function { Acos_Function() : Polyadic_Function(1) {} struct Scalar_Op { static double f(double x) { return acos(x); } static Shared<const String> callstr(Value x) { return stringify("acos(",x,")"); } }; static Unary_Numeric_Array_Op<Scalar_Op> array_op; Value call(Frame& args) override { return array_op.op(args[0], At_Frame(&args)); } GL_Value gl_call(GL_Frame& f) const override { return gl_call_unary_numeric(f, "acos"); } }; struct Atan2_Function : public Polyadic_Function { Atan2_Function() : Polyadic_Function(2) {} struct Scalar_Op { static double f(double x, double y) { return atan2(x, y); } static const char* name() { return "atan2"; } static Shared<const String> callstr(Value x, Value y) { return stringify("atan2(",x,",",y,")"); } }; static Binary_Numeric_Array_Op<Scalar_Op> array_op; Value call(Frame& args) override { return array_op.op(args[0], args[1], At_Arg(args)); } GL_Value gl_call(GL_Frame& f) const override { auto x = f[0]; auto y = f[1]; GL_Type rtype = GL_Type::Bool; if (x.type == y.type) rtype = x.type; else if (x.type == GL_Type::Num) rtype = y.type; else if (y.type == GL_Type::Num) rtype = x.type; if (rtype == GL_Type::Bool) throw Exception(At_GL_Phrase(f.call_phrase_, &f), "GL domain error"); GL_Value result = f.gl.newvalue(rtype); f.gl.out <<" "<<rtype<<" "<<result<<" = atan("; gl_put_as(f, x, At_GL_Arg(0, f), rtype); f.gl.out << ","; gl_put_as(f, y, At_GL_Arg(1, f), rtype); f.gl.out << ");\n"; return result; } }; GL_Value gl_minmax(const char* name, Operation& argx, GL_Frame& f) { auto list = dynamic_cast<List_Expr*>(&argx); if (list) { std::list<GL_Value> args; GL_Type type = GL_Type::Num; for (auto op : *list) { auto val = op->gl_eval(f); args.push_back(val); if (val.type == GL_Type::Num) ; else if (gl_type_count(val.type) >= 2) { if (type == GL_Type::Num) type = val.type; else if (type != val.type) throw Exception(At_GL_Phrase(op->source_, &f), stringify( "GL: ",name, ": vector arguments of different lengths")); } else { throw Exception(At_GL_Phrase(op->source_, &f), stringify( "GL: ",name,": argument has bad type")); } } auto result = f.gl.newvalue(type); if (args.size() == 0) f.gl.out << " " << type << " " << result << " = -0.0/0.0;\n"; else if (args.size() == 1) return args.front(); else { f.gl.out << " " << type << " " << result << " = "; int rparens = 0; while (args.size() > 2) { f.gl.out << name << "(" << args.front() << ","; args.pop_front(); ++rparens; } f.gl.out << name << "(" << args.front() << "," << args.back() << ")"; while (rparens > 0) { f.gl.out << ")"; --rparens; } f.gl.out << ";\n"; } return result; } else { auto arg = argx.gl_eval(f); auto result = f.gl.newvalue(GL_Type::Num); f.gl.out << " float "<<result<<" = "; if (arg.type == GL_Type::Vec2) f.gl.out << name <<"("<<arg<<".x,"<<arg<<".y);\n"; else if (arg.type == GL_Type::Vec3) f.gl.out << name<<"("<<name<<"("<<arg<<".x,"<<arg<<".y)," <<arg<<".z);\n"; else if (arg.type == GL_Type::Vec4) f.gl.out << name<<"("<<name<<"("<<name<<"("<<arg<<".x,"<<arg<<".y)," <<arg<<".z),"<<arg<<".w);\n"; else throw Exception(At_GL_Phrase(argx.source_, &f), stringify( name,": argument is not a vector")); return result; } } struct Max_Function : public Polyadic_Function { Max_Function() : Polyadic_Function(1) {} struct Scalar_Op { static double f(double x, double y) { // return NaN if either argument is NaN. if (x >= y) return x; if (x < y) return y; return 0.0/0.0; } static const char* name() { return "max"; } static Shared<const String> callstr(Value x, Value y) { return stringify("max(",x,",",y,")"); } }; static Binary_Numeric_Array_Op<Scalar_Op> array_op; Value call(Frame& args) override { return array_op.reduce(-INFINITY, args[0], At_Arg(args)); } GL_Value gl_call_expr(Operation& argx, const Call_Phrase*, GL_Frame& f) const override { return gl_minmax("max",argx,f); } }; struct Min_Function : public Polyadic_Function { Min_Function() : Polyadic_Function(1) {} struct Scalar_Op { static double f(double x, double y) { // return NaN if either argument is NaN if (x <= y) return x; if (x > y) return y; return 0.0/0.0; } static const char* name() { return "min"; } static Shared<const String> callstr(Value x, Value y) { return stringify("min(",x,",",y,")"); } }; static Binary_Numeric_Array_Op<Scalar_Op> array_op; Value call(Frame& args) override { return array_op.reduce(INFINITY, args[0], At_Arg(args)); } GL_Value gl_call_expr(Operation& argx, const Call_Phrase*, GL_Frame& f) const override { return gl_minmax("min",argx,f); } }; // Generalized dot product that includes vector dot product and matrix product. // Same as Mathematica Dot[A,B]. Like APL A+.×B, Python numpy.dot(A,B) struct Dot_Function : public Polyadic_Function { Dot_Function() : Polyadic_Function(2) {} Value call(Frame& args) override { return dot(args[0], args[1], At_Frame(&args)); } GL_Value gl_call(GL_Frame& f) const override { auto a = f[0]; auto b = f[1]; if (gl_type_count(a.type) < 2) throw Exception(At_GL_Arg(0, f), "dot: argument is not a vector"); if (a.type != b.type) throw Exception(At_GL_Arg(1, f), "dot: arguments have different types"); auto result = f.gl.newvalue(GL_Type::Num); f.gl.out << " float "<<result<<" = dot("<<a<<","<<b<<");\n"; return result; } }; struct Mag_Function : public Polyadic_Function { Mag_Function() : Polyadic_Function(1) {} Value call(Frame& args) override { // TODO: use hypot() or BLAS DNRM2 or Eigen stableNorm/blueNorm? // Avoids overflow/underflow due to squaring of large/small values. // Slower. https://forum.kde.org/viewtopic.php?f=74&t=62402 auto& list = arg_to_list(args[0], At_Arg(args)); double sum = 0.0; for (auto val : list) { double x = val.get_num_or_nan(); sum += x * x; } if (sum == sum) return {sqrt(sum)}; throw Exception(At_Arg(args), "mag: domain error"); } GL_Value gl_call(GL_Frame& f) const override { auto arg = f[0]; if (gl_type_count(arg.type) < 2) throw Exception(At_GL_Arg(0, f), "mag: argument is not a vector"); auto result = f.gl.newvalue(GL_Type::Num); f.gl.out << " float "<<result<<" = length("<<arg<<");\n"; return result; } }; struct Count_Function : public Polyadic_Function { Count_Function() : Polyadic_Function(1) {} Value call(Frame& args) override { if (auto list = args[0].dycast<const List>()) return {double(list->size())}; if (auto string = args[0].dycast<const String>()) return {double(string->size())}; throw Exception(At_Arg(args), "not a list or string"); } }; struct Fields_Function : public Polyadic_Function { Fields_Function() : Polyadic_Function(1) {} Value call(Frame& args) override { if (auto structure = args[0].dycast<const Structure>()) return {structure->fields()}; throw Exception(At_Arg(args), "not a record"); } }; struct Strcat_Function : public Polyadic_Function { Strcat_Function() : Polyadic_Function(1) {} Value call(Frame& args) override { if (auto list = args[0].dycast<const List>()) { String_Builder sb; for (auto val : *list) { if (auto str = val.dycast<const String>()) sb << str; else sb << val; } return {sb.get_string()}; } throw Exception(At_Arg(args), "not a list"); } }; struct Repr_Function : public Polyadic_Function { Repr_Function() : Polyadic_Function(1) {} Value call(Frame& args) override { String_Builder sb; sb << args[0]; return {sb.get_string()}; } }; struct Decode_Function : public Polyadic_Function { Decode_Function() : Polyadic_Function(1) {} Value call(Frame& f) override { String_Builder sb; At_Arg cx(f); auto list = f[0].to<List>(cx); for (size_t i = 0; i < list->size(); ++i) sb << (char)arg_to_int((*list)[i], 1, 127, At_Index(i,cx)); return {sb.get_string()}; } }; struct Encode_Function : public Polyadic_Function { Encode_Function() : Polyadic_Function(1) {} Value call(Frame& f) override { List_Builder lb; At_Arg cx(f); auto str = f[0].to<String>(cx); for (size_t i = 0; i < str->size(); ++i) lb.push_back({(double)(int)str->at(i)}); return {lb.get_list()}; } }; struct Match_Function : public Polyadic_Function { Match_Function() : Polyadic_Function(1) {} Value call(Frame& f) override { At_Arg ctx0(f); auto list = f[0].to<List>(ctx0); std::vector<Shared<Function>> cases; for (size_t i = 0; i < list->size(); ++i) cases.push_back(list->at(i).to<Function>(At_Index(i,ctx0))); return {make<Piecewise_Function>(cases)}; } }; // The filename argument to "file", if it is a relative filename, // is interpreted relative to the parent directory of the script file from // which "file" is called. // // Because "file" has this hidden parameter (the name of the script file from // which it is called), it is not a pure function. For this reason, it isn't // a function value at all, it's a metafunction. struct File_Expr : public Just_Expression { Shared<Operation> arg_; File_Expr(Shared<const Call_Phrase> src, Shared<Operation> arg) : Just_Expression(std::move(src)), arg_(std::move(arg)) {} virtual Value eval(Frame& f) const override { auto& callphrase = dynamic_cast<const Call_Phrase&>(*source_); At_Phrase cx(*callphrase.arg_, &f); Value arg = arg_->eval(f); auto argstr = arg.to<String>(cx); namespace fs = boost::filesystem; fs::path filepath; auto caller_script_name = source_->location().script().name_; if (caller_script_name->empty()) { filepath = fs::path(argstr->c_str()); } else { filepath = fs::path(caller_script_name->c_str()).parent_path() / fs::path(argstr->c_str()); } auto file = make<File_Script>(make_string(filepath.c_str()), cx); Program prog{*file, f.system_}; std::unique_ptr<Frame> f2 = Frame::make(0, f.system_, &f, &callphrase, nullptr); prog.compile(nullptr, &*f2); return prog.eval(); } }; struct File_Metafunction : public Metafunction { using Metafunction::Metafunction; virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override { return make<File_Expr>(share(ph), analyse_op(*ph.arg_, env)); } }; /// The meaning of a call to `print`, such as `print "foo"`. struct Print_Action : public Just_Action { Shared<Operation> arg_; Print_Action( Shared<const Phrase> source, Shared<Operation> arg) : Just_Action(std::move(source)), arg_(std::move(arg)) {} virtual void exec(Frame& f) const override { Value arg = arg_->eval(f); if (auto str = arg.dycast<String>()) f.system_.console() << *str; else f.system_.console() << arg; f.system_.console() << std::endl; } }; /// The meaning of the phrase `print` in isolation. struct Print_Metafunction : public Metafunction { using Metafunction::Metafunction; virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override { return make<Print_Action>(share(ph), analyse_op(*ph.arg_, env)); } }; struct Warning_Action : public Just_Action { Shared<Operation> arg_; Warning_Action( Shared<const Phrase> source, Shared<Operation> arg) : Just_Action(std::move(source)), arg_(std::move(arg)) {} virtual void exec(Frame& f) const override { Value arg = arg_->eval(f); Shared<String> msg; if (auto str = arg.dycast<String>()) msg = str; else msg = stringify(arg); Exception exc{At_Phrase(*source_, &f), msg}; f.system_.console() << "WARNING: " << exc << std::endl; } }; /// The meaning of the phrase `warning` in isolation. struct Warning_Metafunction : public Metafunction { using Metafunction::Metafunction; virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override { return make<Warning_Action>(share(ph), analyse_op(*ph.arg_, env)); } }; /// The meaning of a call to `error`, such as `error("foo")`. struct Error_Operation : public Operation { Shared<Operation> arg_; Error_Operation( Shared<const Phrase> source, Shared<Operation> arg) : Operation(std::move(source)), arg_(std::move(arg)) {} [[noreturn]] void run(Frame& f) const { Value val = arg_->eval(f); Shared<const String> msg; if (auto s = val.dycast<String>()) msg = s; else msg = stringify(val); throw Exception(At_Frame(&f), msg); } virtual void exec(Frame& f) const override { run(f); } virtual Value eval(Frame& f) const override { run(f); } virtual void generate(Frame& f, List_Builder&) const override { run(f); } virtual void bind(Frame& f, Record&) const override { run(f); } }; /// The meaning of the phrase `error` in isolation. struct Error_Metafunction : public Metafunction { using Metafunction::Metafunction; virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override { return make<Error_Operation>(share(ph), analyse_op(*ph.arg_, env)); } }; // exec(expr) -- a debug action that evaluates expr, then discards the result. // It is used to call functions or scripts for their side effects. struct Exec_Action : public Just_Action { Shared<Operation> arg_; Exec_Action( Shared<const Phrase> source, Shared<Operation> arg) : Just_Action(std::move(source)), arg_(std::move(arg)) {} virtual void exec(Frame& f) const override { arg_->eval(f); } }; struct Exec_Metafunction : public Metafunction { using Metafunction::Metafunction; virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override { return make<Exec_Action>(share(ph), analyse_op(*ph.arg_, env)); } }; struct Assert_Action : public Just_Action { Shared<Operation> arg_; Assert_Action( Shared<const Phrase> source, Shared<Operation> arg) : Just_Action(std::move(source)), arg_(std::move(arg)) {} virtual void exec(Frame& f) const override { Value a = arg_->eval(f); if (!a.is_bool()) throw Exception(At_Phrase(*source_, &f), "domain error"); bool b = a.get_bool_unsafe(); if (!b) throw Exception(At_Phrase(*source_, &f), "assertion failed"); } }; struct Assert_Metafunction : public Metafunction { using Metafunction::Metafunction; virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override { auto args = ph.analyse_args(env); if (args.size() != 1) throw Exception(At_Phrase(ph, env), "assert: expecting 1 argument"); return make<Assert_Action>(share(ph), args.front()); } }; struct Assert_Error_Action : public Just_Action { Shared<Operation> expected_message_; Shared<const String> actual_message_; Shared<Operation> expr_; Assert_Error_Action( Shared<const Phrase> source, Shared<Operation> expected_message, Shared<const String> actual_message, Shared<Operation> expr) : Just_Action(std::move(source)), expected_message_(std::move(expected_message)), actual_message_(std::move(actual_message)), expr_(std::move(expr)) {} virtual void exec(Frame& f) const override { Value expected_msg_val = expected_message_->eval(f); auto expected_msg_str = expected_msg_val.to<const String>( At_Phrase(*expected_message_->source_, &f)); if (actual_message_ != nullptr) { if (*actual_message_ != *expected_msg_str) throw Exception(At_Phrase(*source_, &f), stringify("assertion failed: expected error \"", expected_msg_str, "\", actual error \"", actual_message_, "\"")); return; } Value result; try { result = expr_->eval(f); } catch (Exception& e) { if (*e.shared_what() != *expected_msg_str) { throw Exception(At_Phrase(*source_, &f), stringify("assertion failed: expected error \"", expected_msg_str, "\", actual error \"", e.shared_what(), "\"")); } return; } throw Exception(At_Phrase(*source_, &f), stringify("assertion failed: expected error \"", expected_msg_str, "\", got value ", result)); } }; struct Assert_Error_Metafunction : public Metafunction { using Metafunction::Metafunction; virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override { auto parens = cast<Paren_Phrase>(ph.arg_); Shared<Comma_Phrase> commas = nullptr; if (parens) commas = cast<Comma_Phrase>(parens->body_); if (parens && commas && commas->args_.size() == 2) { auto msg = analyse_op(*commas->args_[0].expr_, env); Shared<Operation> expr = nullptr; Shared<const String> actual_msg = nullptr; try { expr = analyse_op(*commas->args_[1].expr_, env); } catch (Exception& e) { actual_msg = e.shared_what(); } return make<Assert_Error_Action>(share(ph), msg, actual_msg, expr); } else { throw Exception(At_Phrase(ph, env), "assert_error: expecting 2 arguments"); } } }; struct Defined_Expression : public Just_Expression { Shared<const Operation> expr_; Atom_Expr selector_; Defined_Expression( Shared<const Phrase> source, Shared<const Operation> expr, Atom_Expr selector) : Just_Expression(std::move(source)), expr_(std::move(expr)), selector_(std::move(selector)) { } virtual Value eval(Frame& f) const override { auto val = expr_->eval(f); auto s = val.dycast<Structure>(); if (s) { auto id = selector_.eval(f); return {s->hasfield(id)}; } else { return {false}; } } }; struct Defined_Metafunction : public Metafunction { using Metafunction::Metafunction; virtual Shared<Meaning> call(const Call_Phrase& ph, Environ& env) override { auto arg = analyse_op(*ph.arg_, env); auto dot = cast<Dot_Expr>(arg); if (dot != nullptr) return make<Defined_Expression>( share(ph), dot->base_, dot->selector_); throw Exception(At_Phrase(*ph.arg_, env), "defined: argument must be `expression.identifier`"); } }; const Namespace& builtin_namespace() { static const Namespace names = { {"pi", make<Builtin_Value>(pi)}, {"tau", make<Builtin_Value>(two_pi)}, {"inf", make<Builtin_Value>(INFINITY)}, {"null", make<Builtin_Value>(Value())}, {"false", make<Builtin_Value>(Value(false))}, {"true", make<Builtin_Value>(Value(true))}, {"is_null", make<Builtin_Value>(Value{make<Is_Null_Function>()})}, {"is_bool", make<Builtin_Value>(Value{make<Is_Bool_Function>()})}, {"is_num", make<Builtin_Value>(Value{make<Is_Num_Function>()})}, {"is_string", make<Builtin_Value>(Value{make<Is_String_Function>()})}, {"is_list", make<Builtin_Value>(Value{make<Is_List_Function>()})}, {"is_record", make<Builtin_Value>(Value{make<Is_Record_Function>()})}, {"is_fun", make<Builtin_Value>(Value{make<Is_Fun_Function>()})}, {"bit", make<Builtin_Value>(Value{make<Bit_Function>()})}, {"sqrt", make<Builtin_Value>(Value{make<Sqrt_Function>()})}, {"log", make<Builtin_Value>(Value{make<Log_Function>()})}, {"abs", make<Builtin_Value>(Value{make<Abs_Function>()})}, {"floor", make<Builtin_Value>(Value{make<Floor_Function>()})}, {"round", make<Builtin_Value>(Value{make<Round_Function>()})}, {"sin", make<Builtin_Value>(Value{make<Sin_Function>()})}, {"asin", make<Builtin_Value>(Value{make<Asin_Function>()})}, {"cos", make<Builtin_Value>(Value{make<Cos_Function>()})}, {"acos", make<Builtin_Value>(Value{make<Acos_Function>()})}, {"atan2", make<Builtin_Value>(Value{make<Atan2_Function>()})}, {"max", make<Builtin_Value>(Value{make<Max_Function>()})}, {"min", make<Builtin_Value>(Value{make<Min_Function>()})}, {"dot", make<Builtin_Value>(Value{make<Dot_Function>()})}, {"mag", make<Builtin_Value>(Value{make<Mag_Function>()})}, {"count", make<Builtin_Value>(Value{make<Count_Function>()})}, {"fields", make<Builtin_Value>(Value{make<Fields_Function>()})}, {"strcat", make<Builtin_Value>(Value{make<Strcat_Function>()})}, {"repr", make<Builtin_Value>(Value{make<Repr_Function>()})}, {"decode", make<Builtin_Value>(Value{make<Decode_Function>()})}, {"encode", make<Builtin_Value>(Value{make<Encode_Function>()})}, {"match", make<Builtin_Value>(Value{make<Match_Function>()})}, {"file", make<Builtin_Meaning<File_Metafunction>>()}, {"print", make<Builtin_Meaning<Print_Metafunction>>()}, {"warning", make<Builtin_Meaning<Warning_Metafunction>>()}, {"error", make<Builtin_Meaning<Error_Metafunction>>()}, {"assert", make<Builtin_Meaning<Assert_Metafunction>>()}, {"assert_error", make<Builtin_Meaning<Assert_Error_Metafunction>>()}, {"exec", make<Builtin_Meaning<Exec_Metafunction>>()}, {"defined", make<Builtin_Meaning<Defined_Metafunction>>()}, }; return names; } } // namespace curv
31,250
10,183
/* The copyright in this software is being made available under the BSD * License, included below. This software may be subject to other third party * and contributor rights, including patent rights, and no such rights are * granted under this license. * * Copyright (c) 2010-2017, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the ISO/IEC nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include "PCCCommon.h" #include "PCCKdTree.h" #include "tbb/tbb.h" #include "PCCNormalsGenerator.h" using namespace pcc; void PCCNormalsGenerator3::init( const size_t pointCount, const PCCNormalsGenerator3Parameters& params ) { normals_.resize( pointCount ); if ( params.storeNumberOfNearestNeighborsInNormalEstimation_ ) { numberOfNearestNeighborsInNormalEstimation_.resize( pointCount ); } else { numberOfNearestNeighborsInNormalEstimation_.resize( 0 ); } if ( params.storeEigenvalues_ ) { eigenvalues_.resize( pointCount ); } else { eigenvalues_.resize( 0 ); } if ( params.storeCentroids_ ) { barycenters_.resize( pointCount ); } else { barycenters_.resize( 0 ); } } void PCCNormalsGenerator3::compute( const PCCPointSet3& pointCloud, const PCCKdTree& kdtree, const PCCNormalsGenerator3Parameters& params, const size_t nbThread ) { nbThread_ = nbThread; init( pointCloud.getPointCount(), params ); computeNormals( pointCloud, kdtree, params ); if ( params.numberOfIterationsInNormalSmoothing_ != 0u ) { smoothNormals( pointCloud, kdtree, params ); } orientNormals( pointCloud, kdtree, params ); } void PCCNormalsGenerator3::computeNormal( const size_t index, const PCCPointSet3& pointCloud, const PCCKdTree& kdtree, const PCCNormalsGenerator3Parameters& params, PCCNNResult& nNResult ) { PCCVector3D bary( pointCloud[index][0], pointCloud[index][1], pointCloud[index][2] ); PCCVector3D normal( 0.0 ); PCCVector3D eigenval( 0.0 ); PCCMatrix3D covMat; PCCMatrix3D Q; PCCMatrix3D D; kdtree.search( pointCloud[index], params.numberOfNearestNeighborsInNormalEstimation_, nNResult ); if ( nNResult.count() > 1 ) { bary = 0.0; for ( size_t i = 0; i < nNResult.count(); ++i ) { bary += pointCloud[nNResult.indices( i )]; } bary /= double( nNResult.count() ); covMat = 0.0; PCCVector3D pt; for ( size_t i = 0; i < nNResult.count(); ++i ) { pt = pointCloud[nNResult.indices( i )] - bary; covMat[0][0] += pt[0] * pt[0]; covMat[1][1] += pt[1] * pt[1]; covMat[2][2] += pt[2] * pt[2]; covMat[0][1] += pt[0] * pt[1]; covMat[0][2] += pt[0] * pt[2]; covMat[1][2] += pt[1] * pt[2]; } covMat[1][0] = covMat[0][1]; covMat[2][0] = covMat[0][2]; covMat[2][1] = covMat[1][2]; covMat /= ( nNResult.count() - 1.0 ); PCCDiagonalize( covMat, Q, D ); D[0][0] = fabs( D[0][0] ); D[1][1] = fabs( D[1][1] ); D[2][2] = fabs( D[2][2] ); if ( D[0][0] < D[1][1] && D[0][0] < D[2][2] ) { normal[0] = Q[0][0]; normal[1] = Q[1][0]; normal[2] = Q[2][0]; eigenval[0] = D[0][0]; if ( D[1][1] < D[2][2] ) { eigenval[1] = D[1][1]; eigenval[2] = D[2][2]; } else { eigenval[2] = D[1][1]; eigenval[1] = D[2][2]; } } else if ( D[1][1] < D[2][2] ) { normal[0] = Q[0][1]; normal[1] = Q[1][1]; normal[2] = Q[2][1]; eigenval[0] = D[1][1]; if ( D[0][0] < D[2][2] ) { eigenval[1] = D[0][0]; eigenval[2] = D[2][2]; } else { eigenval[2] = D[0][0]; eigenval[1] = D[2][2]; } } else { normal[0] = Q[0][2]; normal[1] = Q[1][2]; normal[2] = Q[2][2]; eigenval[0] = D[2][2]; if ( D[0][0] < D[1][1] ) { eigenval[1] = D[0][0]; eigenval[2] = D[1][1]; } else { eigenval[2] = D[0][0]; eigenval[1] = D[1][1]; } } } if ( normal * ( params.viewPoint_ - pointCloud[index] ) < 0.0 ) { normals_[index] = -normal; } else { normals_[index] = normal; } if ( params.storeEigenvalues_ ) { eigenvalues_[index] = eigenval; } if ( params.storeCentroids_ ) { barycenters_[index] = bary; } if ( params.storeNumberOfNearestNeighborsInNormalEstimation_ ) { numberOfNearestNeighborsInNormalEstimation_[index] = uint32_t( nNResult.count() ); } } void PCCNormalsGenerator3::computeNormals( const PCCPointSet3& pointCloud, const PCCKdTree& kdtree, const PCCNormalsGenerator3Parameters& params ) { const size_t pointCount = pointCloud.getPointCount(); normals_.resize( pointCount ); std::vector<size_t> subRanges; const size_t chunckCount = 64; PCCDivideRange( 0, pointCount, chunckCount, subRanges ); tbb::task_arena limited( static_cast<int>( nbThread_ ) ); limited.execute( [&] { tbb::parallel_for( size_t( 0 ), subRanges.size() - 1, [&]( const size_t i ) { const size_t start = subRanges[i]; const size_t end = subRanges[i + 1]; PCCNNResult nNResult; for ( size_t ptIndex = start; ptIndex < end; ++ptIndex ) { computeNormal( ptIndex, pointCloud, kdtree, params, nNResult ); } } ); } ); } void PCCNormalsGenerator3::orientNormals( const PCCPointSet3& pointCloud, const PCCKdTree& kdtree, const PCCNormalsGenerator3Parameters& params ) { if ( params.orientationStrategy_ == PCC_NORMALS_GENERATOR_ORIENTATION_SPANNING_TREE ) { const size_t pointCount = pointCloud.getPointCount(); PCCNNResult nNResult; visited_.resize( pointCount ); std::fill( visited_.begin(), visited_.end(), 0 ); PCCNNQuery3 nNQuery = {PCCPoint3D( 0.0 ), static_cast<float>( params.radiusNormalOrientation_ ) * params.radiusNormalOrientation_, params.numberOfNearestNeighborsInNormalOrientation_}; PCCNNQuery3 nNQuery2 = {PCCPoint3D( 0.0 ), ( std::numeric_limits<float>::max )(), params.numberOfNearestNeighborsInNormalOrientation_}; size_t processedPointCount = 0; for ( size_t ptIndex = 0; ptIndex < pointCount; ++ptIndex ) { if ( visited_[ptIndex] == 0u ) { visited_[ptIndex] = 1; ++processedPointCount; size_t numberOfNormals; PCCVector3D accumulatedNormals; addNeighbors( uint32_t( ptIndex ), pointCloud, kdtree, nNQuery2, nNResult, accumulatedNormals, numberOfNormals ); if ( numberOfNormals == 0u ) { if ( ptIndex != 0u ) { accumulatedNormals = normals_[ptIndex - 1]; } else { accumulatedNormals = ( params.viewPoint_ - pointCloud[ptIndex] ); } } if ( normals_[ptIndex] * accumulatedNormals < 0.0 ) { normals_[ptIndex] = -normals_[ptIndex]; } while ( !edges_.empty() ) { PCCWeightedEdge edge = edges_.top(); edges_.pop(); uint32_t current = edge.end_; if ( visited_[current] == 0u ) { visited_[current] = 1; ++processedPointCount; if ( normals_[edge.start_] * normals_[current] < 0.0 ) { normals_[current] = -normals_[current]; } addNeighbors( current, pointCloud, kdtree, nNQuery, nNResult, accumulatedNormals, numberOfNormals ); } } } } size_t negNormalCount = 0; for ( size_t ptIndex = 0; ptIndex < pointCount; ++ptIndex ) { negNormalCount += static_cast<unsigned long long>( normals_[ptIndex] * ( params.viewPoint_ - pointCloud[ptIndex] ) < 0.0 ); } if ( negNormalCount > ( pointCount + 1 ) / 2 ) { for ( size_t ptIndex = 0; ptIndex < pointCount; ++ptIndex ) { normals_[ptIndex] = -normals_[ptIndex]; } } } else if ( params.orientationStrategy_ == PCC_NORMALS_GENERATOR_ORIENTATION_VIEW_POINT ) { const size_t pointCount = pointCloud.getPointCount(); tbb::task_arena limited( static_cast<int>( nbThread_ ) ); limited.execute( [&] { tbb::parallel_for( size_t( 0 ), pointCount, [&]( const size_t ptIndex ) { if ( normals_[ptIndex] * ( params.viewPoint_ - pointCloud[ptIndex] ) < 0.0 ) { normals_[ptIndex] = -normals_[ptIndex]; } } ); } ); } } void PCCNormalsGenerator3::addNeighbors( const uint32_t current, const PCCPointSet3& pointCloud, const PCCKdTree& kdtree, PCCNNQuery3& nNQuery, PCCNNResult& nNResult, PCCVector3D& accumulatedNormals, size_t& numberOfNormals ) { accumulatedNormals = 0.0; numberOfNormals = 0; if ( nNQuery.radius > 32768.0 ) { kdtree.search( pointCloud[current], nNQuery.nearestNeighborCount, nNResult ); } else { kdtree.searchRadius( pointCloud[current], nNQuery.nearestNeighborCount, nNQuery.radius, nNResult ); } PCCWeightedEdge newEdge; uint32_t index; for ( size_t i = 0; i < nNResult.count(); ++i ) { index = static_cast<uint32_t>( nNResult.indices( i ) ); if ( visited_[index] == 0u ) { newEdge.weight_ = fabs( normals_[current] * normals_[index] ); newEdge.end_ = index; newEdge.start_ = current; edges_.push( newEdge ); } else if ( index != current ) { accumulatedNormals += normals_[index]; ++numberOfNormals; } } } void PCCNormalsGenerator3::smoothNormals( const PCCPointSet3& pointCloud, const PCCKdTree& kdtree, const PCCNormalsGenerator3Parameters& params ) { const double w2 = params.weightNormalSmoothing_; const double w0 = ( 1 - w2 ); const size_t pointCount = pointCloud.getPointCount(); PCCVector3D n0; PCCVector3D n1; PCCVector3D n2; std::vector<size_t> subRanges; const size_t chunckCount = 64; PCCDivideRange( 0, pointCount, chunckCount, subRanges ); const double radius = params.radiusNormalSmoothing_ * params.radiusNormalSmoothing_; for ( size_t it = 0; it < params.numberOfIterationsInNormalSmoothing_; ++it ) { tbb::task_arena limited( static_cast<int>( nbThread_ ) ); limited.execute( [&] { tbb::parallel_for( size_t( 0 ), subRanges.size() - 1, [&]( const size_t i ) { const size_t start = subRanges[i]; const size_t end = subRanges[i + 1]; PCCNNResult result; for ( size_t ptIndex = start; ptIndex < end; ++ptIndex ) { kdtree.searchRadius( pointCloud[ptIndex], params.numberOfNearestNeighborsInNormalSmoothing_, radius, result ); n0 = normals_[ptIndex]; n1 = 0.0; for ( size_t i = 1; i < result.count(); ++i ) { n2 = normals_[result.indices( i )]; if ( n0 * n2 < 0.0 ) { n1 -= n2; } else { n1 += n2; } } n1.normalize(); n1 = w0 * n0 + w2 * n1; n1.normalize(); normals_[ptIndex] = n1; } } ); } ); } }
13,643
4,744
/* ======================================== * UltrasonX - UltrasonX.h * Copyright (c) 2016 airwindows, All rights reserved * ======================================== */ #ifndef __UltrasonX_H #include "UltrasonX.h" #endif AudioEffect* createEffectInstance(audioMasterCallback audioMaster) {return new UltrasonX(audioMaster);} UltrasonX::UltrasonX(audioMasterCallback audioMaster) : AudioEffectX(audioMaster, kNumPrograms, kNumParameters) { A = 0.5; for (int x = 0; x < fix_total; x++) {fixA[x] = 0.0;} fixA[fix_reso] = 0.7071; //butterworth Q fpdL = 1.0; while (fpdL < 16386) fpdL = rand()*UINT32_MAX; fpdR = 1.0; while (fpdR < 16386) fpdR = rand()*UINT32_MAX; //this is reset: values being initialized only once. Startup values, whatever they are. _canDo.insert("plugAsChannelInsert"); // plug-in can be used as a channel insert effect. _canDo.insert("plugAsSend"); // plug-in can be used as a send effect. _canDo.insert("x2in2out"); setNumInputs(kNumInputs); setNumOutputs(kNumOutputs); setUniqueID(kUniqueId); canProcessReplacing(); // supports output replacing canDoubleReplacing(); // supports double precision processing programsAreChunks(true); vst_strncpy (_programName, "Default", kVstMaxProgNameLen); // default program name } UltrasonX::~UltrasonX() {} VstInt32 UltrasonX::getVendorVersion () {return 1000;} void UltrasonX::setProgramName(char *name) {vst_strncpy (_programName, name, kVstMaxProgNameLen);} void UltrasonX::getProgramName(char *name) {vst_strncpy (name, _programName, kVstMaxProgNameLen);} //airwindows likes to ignore this stuff. Make your own programs, and make a different plugin rather than //trying to do versioning and preventing people from using older versions. Maybe they like the old one! static float pinParameter(float data) { if (data < 0.0f) return 0.0f; if (data > 1.0f) return 1.0f; return data; } VstInt32 UltrasonX::getChunk (void** data, bool isPreset) { float *chunkData = (float *)calloc(kNumParameters, sizeof(float)); chunkData[0] = A; *data = chunkData; return kNumParameters * sizeof(float); } VstInt32 UltrasonX::setChunk (void* data, VstInt32 byteSize, bool isPreset) { float *chunkData = (float *)data; A = pinParameter(chunkData[0]); /* We're ignoring byteSize as we found it to be a filthy liar */ /* calculate any other fields you need here - you could copy in code from setParameter() here. */ return 0; } void UltrasonX::setParameter(VstInt32 index, float value) { switch (index) { case kParamA: A = value; break; default: throw; // unknown parameter, shouldn't happen! } } float UltrasonX::getParameter(VstInt32 index) { switch (index) { case kParamA: return A; break; default: break; // unknown parameter, shouldn't happen! } return 0.0; //we only need to update the relevant name, this is simple to manage } void UltrasonX::getParameterName(VstInt32 index, char *text) { switch (index) { case kParamA: vst_strncpy (text, "Q", kVstMaxParamStrLen); break; default: break; // unknown parameter, shouldn't happen! } //this is our labels for displaying in the VST host } void UltrasonX::getParameterDisplay(VstInt32 index, char *text) { switch (index) { case kParamA: switch((VstInt32)( A * 4.999 )) //0 to almost edge of # of params { case kA: vst_strncpy (text, "Reso A", kVstMaxParamStrLen); break; case kB: vst_strncpy (text, "Reso B", kVstMaxParamStrLen); break; case kC: vst_strncpy (text, "Reso C", kVstMaxParamStrLen); break; case kD: vst_strncpy (text, "Reso D", kVstMaxParamStrLen); break; case kE: vst_strncpy (text, "Reso E", kVstMaxParamStrLen); break; default: break; // unknown parameter, shouldn't happen! } break; default: break; // unknown parameter, shouldn't happen! } //this displays the values and handles 'popups' where it's discrete choices } void UltrasonX::getParameterLabel(VstInt32 index, char *text) { switch (index) { case kParamA: vst_strncpy (text, "", kVstMaxParamStrLen); break; default: break; // unknown parameter, shouldn't happen! } } VstInt32 UltrasonX::canDo(char *text) { return (_canDo.find(text) == _canDo.end()) ? -1: 1; } // 1 = yes, -1 = no, 0 = don't know bool UltrasonX::getEffectName(char* name) { vst_strncpy(name, "UltrasonX", kVstMaxProductStrLen); return true; } VstPlugCategory UltrasonX::getPlugCategory() {return kPlugCategEffect;} bool UltrasonX::getProductString(char* text) { vst_strncpy (text, "airwindows UltrasonX", kVstMaxProductStrLen); return true; } bool UltrasonX::getVendorString(char* text) { vst_strncpy (text, "airwindows", kVstMaxVendorStrLen); return true; }
4,737
1,736
/* * zsummerX License * ----------- * * zsummerX is licensed under the terms of the MIT license reproduced below. * This means that zsummerX is free software and can be used for both academic * and commercial purposes at absolutely no cost. * * * =============================================================================== * * Copyright (C) 2010-2017 YaweiZhang <yawei.zhang@foxmail.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. * * =============================================================================== * * (end of COPYRIGHT) */ #include <zsummerX/select/select_impl.h> #include <zsummerX/select/tcpsocket_impl.h> #include <zsummerX/select/tcpaccept_impl.h> #include <zsummerX/select/udpsocket_impl.h> using namespace zsummer::network; bool EventLoop::initialize() { ////////////////////////////////////////////////////////////////////////// //create socket pair sockaddr_in pairAddr; memset(&pairAddr, 0, sizeof(pairAddr)); pairAddr.sin_family = AF_INET; pairAddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); int acpt = socket(AF_INET, SOCK_STREAM, 0); _sockpair[0] = socket(AF_INET, SOCK_STREAM, 0); _sockpair[1] = socket(AF_INET, SOCK_STREAM, 0); if (_sockpair[0] == -1 || _sockpair[1] == -1 || acpt == -1) { LCF("ZSummerImpl::initialize[this0x" << this << "] bind sockpair socket error. " ); return false; } if (::bind(acpt, (sockaddr*)&pairAddr, sizeof(pairAddr)) == -1) { LCF("EventLoop::initialize[this0x" << this << "] bind sockpair socket error. " ); ::close(acpt); ::close(_sockpair[0]); ::close(_sockpair[1]); return false; } if (listen(acpt, 1) == -1) { LCF("EventLoop::initialize[this0x" << this << "] listen sockpair socket error. " ); ::close(acpt); ::close(_sockpair[0]); ::close(_sockpair[1]); return false; } socklen_t len = sizeof(pairAddr); if (getsockname(acpt, (sockaddr*)&pairAddr, &len) != 0) { LCF("EventLoop::initialize[this0x" << this << "] getsockname sockpair socket error. " ); ::close(acpt); ::close(_sockpair[0]); ::close(_sockpair[1]); return false; } if (::connect(_sockpair[0], (sockaddr*)&pairAddr, sizeof(pairAddr)) == -1) { LCF("EventLoop::initialize[this0x" << this << "] connect sockpair socket error. " ); ::close(acpt); ::close(_sockpair[0]); ::close(_sockpair[1]); return false; } _sockpair[1] = accept(acpt, (sockaddr*)&pairAddr, &len); if (_sockpair[1] == -1) { LCF("EventLoop::initialize[this0x" << this << "] accept sockpair socket error. " ); ::close(acpt); ::close(_sockpair[0]); ::close(_sockpair[1]); return false; } ::close(acpt); setNonBlock(_sockpair[0]); setNonBlock(_sockpair[1]); setNoDelay(_sockpair[0]); setNoDelay(_sockpair[1]); FD_ZERO(&_fdreads); FD_ZERO(&_fdwrites); FD_ZERO(&_fderrors); setEvent(_sockpair[1], 0); _arrayTcpAccept.resize(MAX_NUMBER_FD); _arrayTcpSocket.resize(MAX_NUMBER_FD); _arrayUdpSocket.resize(MAX_NUMBER_FD); return true; } void EventLoop::setEvent(int fd, int op /*0 read, 1 write, 2 error*/) { if (fd >= MAX_NUMBER_FD) { LCE("EventLoop::setEvent error. fd = " << fd << " greater than MAX_NUMBER_FD = " << MAX_NUMBER_FD); return; } if (fd > _maxfd) _maxfd = fd; if (op == 0) FD_SET(fd, &_fdreads); else if(op == 1) FD_SET(fd, &_fdwrites); else if(op == 2) FD_SET(fd, &_fderrors); } void EventLoop::unsetEvent(int fd, int op /*0 read, 1 write, 2 error*/) { if (fd >= MAX_NUMBER_FD) { LCE("EventLoop::setEvent error. fd = " << fd << " greater than MAX_NUMBER_FD = " << MAX_NUMBER_FD); return; } if (op == 0) FD_CLR(fd, &_fdreads); else if(op == 1) FD_CLR(fd, &_fdwrites); else if(op == 2) FD_CLR(fd, &_fderrors); } void EventLoop::addTcpAccept(int fd, TcpAcceptPtr s) { if (fd >= MAX_NUMBER_FD) { LCE("EventLoop::setEvent error. fd = " << fd << " greater than MAX_NUMBER_FD = " << MAX_NUMBER_FD); return; } _arrayTcpAccept[fd] = s; } void EventLoop::addTcpSocket(int fd, TcpSocketPtr s) { if (fd >= MAX_NUMBER_FD) { LCE("EventLoop::setEvent error. fd = " << fd << " greater than MAX_NUMBER_FD = " << MAX_NUMBER_FD); return; } _arrayTcpSocket[fd] = s; } void EventLoop::addUdpSocket(int fd, UdpSocketPtr s) { if (fd >= MAX_NUMBER_FD) { LCE("EventLoop::setEvent error. fd = " << fd << " greater than MAX_NUMBER_FD = " << MAX_NUMBER_FD); return; } _arrayUdpSocket[fd] = s; } void EventLoop::clearSocket(int fd) { if (fd >= MAX_NUMBER_FD) { LCE("EventLoop::setEvent error. fd = " << fd << " greater than MAX_NUMBER_FD = " << MAX_NUMBER_FD); return; } unsetEvent(fd, 0); unsetEvent(fd, 1); unsetEvent(fd, 2); _arrayTcpAccept[fd].reset(); _arrayTcpSocket[fd].reset(); _arrayUdpSocket[fd].reset(); } void EventLoop::PostMessage(_OnPostHandler &&handle) { _OnPostHandler * pHandler = new _OnPostHandler(std::move(handle)); bool needNotice = false; _postQueueLock.lock(); if (_postQueue.empty()){ needNotice = true;} _postQueue.push_back(pHandler); _postQueueLock.unlock(); if (needNotice) { char c = '0'; send(_sockpair[0], &c, 1, 0); } } std::string EventLoop::logSection() { std::stringstream os; _postQueueLock.lock(); MessageStack::size_type msgSize = _postQueue.size(); _postQueueLock.unlock(); os << " logSection: _sockpair[2]={" << _sockpair[0] << "," << _sockpair[1] << "}" << " _postQueue.size()=" << msgSize << ", current total timer=" << _timer.getTimersCount() << " _maxfd=" << _maxfd; return os.str(); } void EventLoop::runOnce(bool isImmediately) { fd_set fdr; fd_set fdw; fd_set fde; memcpy(&fdr, &_fdreads, sizeof(_fdreads)); memcpy(&fdw, &_fdwrites, sizeof(_fdwrites)); memcpy(&fde, &_fderrors, sizeof(_fderrors)); timeval tv; if (isImmediately) { tv.tv_sec = 0; tv.tv_usec = 0; } else { unsigned int ms = _timer.getNextExpireTime(); tv.tv_sec = ms / 1000; tv.tv_usec = (ms % 1000) * 1000; } int retCount = ::select(_maxfd+1, &fdr, &fdw, &fde, &tv); if (retCount == -1) { return; } //check timer { _timer.checkTimer(); if (retCount == 0) return;//timeout } if (FD_ISSET(_sockpair[1], &fdr)) { char buf[1000]; while (recv(_sockpair[1], buf, 1000, 0) > 0); MessageStack msgs; _postQueueLock.lock(); msgs.swap(_postQueue); _postQueueLock.unlock(); for (auto pfunc : msgs) { _OnPostHandler * p = (_OnPostHandler*)pfunc; try { (*p)(); } catch (const std::exception & e) { LCW("OnPostHandler have runtime_error exception. err=" << e.what()); } catch (...) { LCW("OnPostHandler have unknown exception."); } delete p; } } for (int i = 0; i <= _maxfd ; ++i) { //tagHandle type if (FD_ISSET(i, &fdr) || FD_ISSET(i, &fdw) || FD_ISSET(i, &fde)) { if (_arrayTcpAccept[i]) _arrayTcpAccept[i]->onSelectMessage(); if (_arrayTcpSocket[i]) { _arrayTcpSocket[i]->onSelectMessage(FD_ISSET(i, &fdr), FD_ISSET(i, &fdw), FD_ISSET(i, &fde)); } if (_arrayUdpSocket[i]) { _arrayUdpSocket[i]->onSelectMessage(FD_ISSET(i, &fdr), FD_ISSET(i, &fdw), FD_ISSET(i, &fde)); } } } }
9,091
3,311
// (C) Copyright Peter Dimov 2007. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/config for most recent version. // MACRO: BOOST_NO_STD_TYPEINFO // TITLE: type_info not in namespace std // DESCRIPTION: The <typeinfo> header declares type_info in the global namespace instead of std #include <typeinfo> namespace boost_no_std_typeinfo { int test() { std::type_info * p = 0; return 0; } }
625
230
/*========================================================================= Program: Visualization Toolkit Module: TaskParallelismWithPorts.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // This example demonstrates how to write a task parallel application // with VTK. It creates two different pipelines and assigns each to // one processor. These pipelines are: // 1. rtSource -> contour -> probe .-> append // \ / port // -> gradient magnitude / // 2. rtSource -> gradient -> shrink -> glyph3D -> port // See task3.cxx and task4.cxx for the pipelines. #include "TaskParallelismWithPorts.h" // This function sets up properties common to both processes // and executes the task corresponding to the current process void process(vtkMultiProcessController* controller, void* vtkNotUsed(arg)) { taskFunction task; int myId = controller->GetLocalProcessId(); // Chose the appropriate task (see task3.cxx and task4.cxx) if ( myId == 0 ) { task = task3; } else { task = task4; } // Run the tasks (see task3.cxx and task4.cxx) (*task)(EXTENT); } int main( int argc, char* argv[] ) { // Note that this will create a vtkMPIController if MPI // is configured, vtkThreadedController otherwise. vtkMultiProcessController* controller = vtkMultiProcessController::New(); controller->Initialize(&argc, &argv); // When using MPI, the number of processes is determined // by the external program which launches this application. // However, when using threads, we need to set it ourselves. if (controller->IsA("vtkThreadedController")) { // Set the number of processes to 2 for this example. controller->SetNumberOfProcesses(2); } int numProcs = controller->GetNumberOfProcesses(); if (numProcs != 2) { cerr << "This example requires two processes." << endl; controller->Finalize(); controller->Delete(); return 1; } // Execute the function named "process" on both processes controller->SetSingleMethod(process, 0); controller->SingleMethodExecute(); // Clean-up and exit controller->Finalize(); controller->Delete(); return 0; }
2,739
819
//연구소 3 다시풀기 8시 40분 #include <iostream> #include <vector> #include <queue> #include <algorithm> #include <string> using namespace std; #define debug 0 int dx[4] ={ -1, 0, 1, 0}; int dy[4] ={ 0, 1, 0, -1 }; class lab { public: int n, m; vector<int> t; vector<int> vis; int blac=0; int time; void input() { cin>>n >> m; t= vector<int>(n*n); for(int i=0; i<n*n; i++){ cin>> t[i]; if(t[i]==2) vis.push_back(i); if(t[i]==0) blac++; } } int spread(vector<int> selected) { vector<int> nt =t; //퍼진 후 멥 queue<int> q_vis; vector<int> sp_t(n*n); //각 칸에 퍼진 시간을 기록 int spread_time=0; int sp_area=0; #if debug cout<<"\n selected :" ; #endif for(int i: selected) //활성 비이러스로 바꾸기, 활성 바이러스는 4로 표시 { nt[i] = 4; q_vis.push(i); #if debug cout<<i<<" "; #endif } while(!q_vis.empty()) { int cur = q_vis.front(); q_vis.pop(); int x = cur%n; int y = cur/n; for(int j=0; j<4 ;j++)//현재 위치를 기준으로 4방향 조사 { int nx= x+dx[j]; int ny= y+dy[j]; if(nx>=n || nx<0 || ny>=n || ny<0 ) continue; //큐에 넣을 필요 없는놈들 if(nt[ny*n+nx]==1 || nt[ny*n+nx]==4) continue; if(t[ny*n+nx]==0) sp_area++; sp_t[ny*n+nx] = sp_t[cur]+1; // 이 칸에 최초로 퍼진 시간은, 이칸을 퍼트린 놈의 시간 +1 if( spread_time < sp_t[cur]+1 && t[ny*n+nx]==0 ) spread_time = sp_t[cur]+1 ; // 저 조건들을 제외하면 0 또는 2(비 활성 바이러스) nt[ny*n+nx] = 4; //활성 시켜주고 q_vis.push(ny*n+nx); //다음에 여기서부터 뻗어가도록 추가 } #if debug cout<<endl; for(int i=0; i<n; i++){ for(int j=0; j<n; j++){ char a; if(t[i*n+j]==1) a='-'; else if(t[i*n+j]==2) a='*'; else a= to_string(sp_t[i*n+j])[0]; cout<< a<<" "; } cout<<endl; } cout<<endl; #endif } if(sp_area == blac) return spread_time; else return -1; } int sol() { input(); // if(vis.size()==0 && blac !=0) return -1; if(blac ==0) return 0; //vis 중에 m개를 선택 int min_time=999999; int time; vector<int> selected; vector<bool> combintaion; for(int i=0; i<m; i++) combintaion.push_back(1); while(combintaion.size() < vis.size()) combintaion.push_back(0); sort(combintaion.begin(), combintaion.end()); do { for(int i=0; i<combintaion.size(); i++) if(combintaion[i]) selected.push_back(vis[i]); time= spread(selected); if(time <min_time && time != -1) min_time=time; selected.clear(); selected.resize(0); }while(next_permutation(combintaion.begin(), combintaion.end())); if(min_time != 999999) return min_time; else return -1; } }; int main() { lab l; cout<<l.sol(); return 0; }
3,240
1,448
#include "glfw_renderer_frontend.hpp" #include <mbgl/renderer/renderer.hpp> #include <mbgl/gfx/backend_scope.hpp> GLFWRendererFrontend::GLFWRendererFrontend(std::unique_ptr<mbgl::Renderer> renderer_, GLFWView& glfwView_) : glfwView(glfwView_) , renderer(std::move(renderer_)) { glfwView.setRenderFrontend(this); } GLFWRendererFrontend::~GLFWRendererFrontend() = default; void GLFWRendererFrontend::reset() { assert(renderer); renderer.reset(); } void GLFWRendererFrontend::setObserver(mbgl::RendererObserver& observer) { assert(renderer); renderer->setObserver(&observer); } void GLFWRendererFrontend::update(std::shared_ptr<mbgl::UpdateParameters> params) { updateParameters = std::move(params); glfwView.invalidate(); } void GLFWRendererFrontend::render() { assert(renderer); if (!updateParameters) return; mbgl::gfx::BackendScope guard { glfwView.getRendererBackend(), mbgl::gfx::BackendScope::ScopeType::Implicit }; // onStyleImageMissing might be called during a render. The user implemented method // could trigger a call to MGLRenderFrontend#update which overwrites `updateParameters`. // Copy the shared pointer here so that the parameters aren't destroyed while `render(...)` is // still using them. auto updateParameters_ = updateParameters; renderer->render(*updateParameters_); } mbgl::Renderer* GLFWRendererFrontend::getRenderer() { assert(renderer); return renderer.get(); }
1,492
480
#include "application.h" #include "game/brick.h" #include "game/paddle.h" #include "game/platform.h" #include "game/background.h" #include "game/camera.h" #include "game/ball.h" //-------------------------------------------------------------- MiniVkApplication::MiniVkApplication() : currentFrame(0) , framebufferResized(false) , m_window(nullptr) { } //-------------------------------------------------------------- MiniVkApplication::~MiniVkApplication() { } //-------------------------------------------------------------- void MiniVkApplication::run() { initWindow(); initVulkan(); initScene(); mainLoop(); cleanup(); } //-------------------------------------------------------------- void MiniVkApplication::initWindow() { glfwInit(); // dont create OGL context glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); // special case of resizing (disable for this time) glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); m_window = glfwCreateWindow(APP_WIDTH, APP_HEIGHT, "Brick Breaker with Vulkan", nullptr, nullptr); glfwSetWindowUserPointer(m_window, this); glfwSetFramebufferSizeCallback(m_window, framebufferResizeCallback); } //-------------------------------------------------------------- void MiniVkApplication::framebufferResizeCallback(GLFWwindow* window, int /*width*/, int /*height*/) { auto app = reinterpret_cast<MiniVkApplication*>(glfwGetWindowUserPointer(window)); app->framebufferResized = true; } //-------------------------------------------------------------- void MiniVkApplication::initVulkan() { m_gcore = new GraphicsCore(m_window); m_gcore->initialize(); m_swapchain = new SwapChainResources(m_gcore->device(), m_gcore->surface()); m_swapchain->initialize(); m_descpool = new DescriptorPool(m_gcore->device(), m_swapchain->count(), 10); m_pipeline = new ShaderPipeline(m_gcore->device(), m_swapchain->getRenderPass(), m_swapchain->getSwapChain()->getExtent()); m_drawcmd = new DrawCommandBuffer(m_swapchain, m_pipeline->pipeline()); m_drawcmd->initialize(); m_sync = new Synchronization(m_gcore->device()); m_sync->initialize(); } //-------------------------------------------------------------- void MiniVkApplication::initScene() { m_assets = new AssetsLoader(m_gcore->device(), m_descpool, m_pipeline->layout()); m_drawables = new DrawableAllocator(m_gcore->device(), m_swapchain, m_pipeline->layout(), m_descpool); Camera* cam = new Camera(30.0, m_gcore->device(), m_descpool, m_pipeline->layout(), m_swapchain); m_sceneObjects.setView(cam); Paddle* paddle = new Paddle(); paddle->position.y = -6.0; m_sceneObjects.add(paddle); m_collisions.setPaddle(paddle); std::srand(0); float depf = 1.4; for(int x=0;x<20;++x) for(int y=0;y<5;++y) { float xf = float(x) * depf - 13.0; float yf = float(y) * depf + 3.5; Brick* brick = new Brick(); brick->position.x = xf; brick->position.y = yf; brick->color.x = float(std::rand())/RAND_MAX; brick->color.y = float(std::rand())/RAND_MAX; brick->color.z = float(std::rand())/RAND_MAX; brick->m_timeOffset = float(std::rand()); m_sceneObjects.add(brick); m_collisions.addBrick(brick); } Platform* platform = new Platform(); platform->position.y = -10.0; m_sceneObjects.add(platform); m_collisions.setPlatform(platform); Background* background = new Background(); background->position.z = -2.0; m_sceneObjects.add(background); Ball* ball = new Ball(); m_sceneObjects.add(ball); m_collisions.setBall(ball); } //-------------------------------------------------------------- void MiniVkApplication::mainLoop() { while (!glfwWindowShouldClose(m_window)) { glfwPollEvents(); drawFrame(); } vkDeviceWaitIdle(m_gcore->device()->get()); } //-------------------------------------------------------------- void MiniVkApplication::drawFrame() { m_sync->waitForFence(); uint32_t imageIndex = m_swapchain->getSwapChain()->acquireNextImage(m_sync->getImgAvailableSemaphore()); m_sceneObjects.updateState(m_window); m_sceneObjects.animateScene(); m_collisions.checkCollisions(); m_sceneObjects.updateUniform(imageIndex); m_drawcmd->beginDraw(imageIndex); m_drawcmd->drawScene(&m_sceneObjects); m_drawcmd->endDraw(); VkSubmitInfo submitInfo = {}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; VkSemaphore waitSemaphores[] = {m_sync->getImgAvailableSemaphore()}; VkPipelineStageFlags waitStages[] = {VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT}; submitInfo.waitSemaphoreCount = 1; submitInfo.pWaitSemaphores = waitSemaphores; submitInfo.pWaitDstStageMask = waitStages; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &m_drawcmd->get(imageIndex)->get(); VkSemaphore signalSemaphores[] = {m_sync->getRenderFinishedSemaphore()}; submitInfo.signalSemaphoreCount = 1; submitInfo.pSignalSemaphores = signalSemaphores; m_sync->resetFence(); if (vkQueueSubmit(m_gcore->device()->getGraphicQueue()->get(), 1, &submitInfo, m_sync->getFence()) != VK_SUCCESS) { throw std::runtime_error("failed to submit draw command buffer!"); } m_gcore->device()->getPresentQueue()->present(m_sync->getRenderFinishedSemaphore(), m_swapchain->getSwapChain(), imageIndex); m_sync->nextFrame(); m_gcore->device()->getPresentQueue()->wait(); } //-------------------------------------------------------------- void MiniVkApplication::cleanup() { glfwDestroyWindow(m_window); glfwTerminate(); }
5,912
1,966
// kjvm.cpp : Defines the entry point for the console application. // #include <stdio.h> #include <string.h> #include <assert.h> #include "kjvm.h" #include "JavaClass.h" #include "ClassHeap.h" #include "types.h" #include "constants.h" #include "ExecutionEngine.h" #include "ObjectHeap.h" JavaClass *LoadClass(std::string strClassPath) { JavaClass *pClass = new JavaClass(); if (!pClass->LoadClassFromFile(strClassPath)) { delete pClass; pClass = NULL; } return pClass; } void ShowClassInfo(JavaClass *pClass); int Execute(std::string strClass) { std::string path = strClass; ClassHeap heap; JavaClass *pClass1, *pClass2, *pClass3; pClass1 = new JavaClass(); pClass2 = new JavaClass(); heap.AddClassRoot("/home/boltu/workspaces/jvm/kjvm/lib"); bool bRet = heap.LoadClass(strClass, pClass1); bRet = heap.LoadClass("java/lang/Object", pClass2); ObjectHeap oheap; Frame *pFrameStack = new Frame[20]; Frame::pBaseFrame = pFrameStack; memset(pFrameStack, 0, sizeof(Frame) * 20); Frame::pOpStack = new Variable[100]; memset(Frame::pOpStack, 0, sizeof(Variable) * 100); ExecutionEngine ex; ex.pClassHeap = &heap; ex.pObjectHeap = &oheap; int startFrame = 0; Object object = oheap.CreateObject(pClass1); JavaClass *pVirtualClass = pClass1; int mindex = pClass1->GetMethodIndex("Entry", "()I", pVirtualClass); pFrameStack[startFrame].pClass = pVirtualClass; pFrameStack[startFrame].pMethod = &pVirtualClass->methods[mindex]; pFrameStack[startFrame].stack = Frame::pOpStack; pFrameStack[startFrame].sp = pFrameStack[startFrame].pMethod->pCode_attr->max_locals; pFrameStack[startFrame].stack[0].object = object; ex.Execute(&pFrameStack[startFrame]); return 0; } int main(int argc, char *argv[]) { if (argc < 2) { return -1; } return Execute(argv[1]); } void Test2() { std::string path = "Test"; std::string path2 = "java\\lang\\Object"; ClassHeap heap; JavaClass *pClass1, *pClass2, *pClass3; pClass1 = new JavaClass(); pClass2 = new JavaClass(); bool bRet = heap.LoadClass(path, pClass1); bRet = heap.LoadClass(path2, pClass2); pClass3 = heap.GetClass("Test"); for (int i = 0; pClass3 && i < pClass3->interfaces_count; i++) { u2 intr = pClass3->interfaces[i]; std::string name; cp_info *pi = pClass3->constant_pool[intr]; assert(pi->tag == CONSTANT_Class); char *p = (char *)pi; int ni = getu2((char *)(&p[1])); pClass3->GetStringFromConstPool(ni, name); printf("Loading Interface %s\n", name); JavaClass *pClass4 = new JavaClass(); bRet = heap.LoadClass(name.c_str(), pClass4); if (bRet) ShowClassInfo(pClass4); } } void ShowClassInfo(JavaClass *pClass) { if (!pClass) return; std::string name = pClass->GetName(); printf("Class Name = [%s]\n", name.c_str()); name = pClass->GetSuperClassName(); printf("Super Class Name = [%s]\n", name.c_str()); printf("Object Size = [%lu]\n", pClass->GetObjectSize()); for (int i = 1; i < pClass->constant_pool_count - 1; i++) { std::string strRetVal; printf("Pool %d Type = %d ", i, pClass->constant_pool[i]->tag); if (1 != pClass->constant_pool[i]->tag) continue; pClass->GetStringFromConstPool(i, strRetVal); printf("String at %d [%s]\n", i, strRetVal.c_str()); } for (int i = 0; i < pClass->methods_count; i++) { std::cout << "Method " << i << ":" << std::endl; std::cout << "Access flags: " << pClass->methods[i].access_flags << std::endl; if (pClass->methods[i].pCode_attr != NULL) { printf("ode Length= %d\n", pClass->methods[i].pCode_attr->code_length); printf("Max stack = %d, Max Locals = %d, Exception table length= %d\nCODE\n", pClass->methods[i].pCode_attr->max_stack, pClass->methods[i].pCode_attr->max_locals, pClass->methods[i].pCode_attr->exception_table_length); for (u4 j = 0; j < pClass->methods[i].pCode_attr->code_length; j++) printf("%d ", pClass->methods[i].pCode_attr->code[j]); printf("\nENDCODE\n"); } else if (pClass->methods[i].access_flags && ACC_NATIVE) { printf("Method %d is native\n", i); } } for (int i = 0; i < pClass->fields_count; i++) { std::string name, desc; pClass->GetStringFromConstPool(pClass->fields[i].name_index, name); pClass->GetStringFromConstPool(pClass->fields[i].descriptor_index, desc); printf("Filed %d: Name: %s Type: %s\n", i, name, desc); } for (int i = 0; i < pClass->interfaces_count; i++) { u2 intr = pClass->interfaces[i]; std::string name; cp_info *pi = pClass->constant_pool[intr]; assert(pi->tag == CONSTANT_Class); char *p = (char *)pi; int ni = getu2((char *)(&p[1])); pClass->GetStringFromConstPool(ni, name); printf("Interface %d: Name %s\n", i, name); } }
4,840
1,959
/* Count and Say The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21, 1211, 111221, ... 1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1" or 1211. Given an integer n, generate the nth sequence. Note: The sequence of integers will be represented as a string. @author Zixuan @date 2015/8/12 */ #include <string> using namespace std; class Solution { public: string countAndSay(int n) { string sequence("1"); for (int i = 1; i < n; ++i) { string temp = sequence; sequence.clear(); //It is sure temp.length() >= 1. //Initalization. char thisDigit = temp[0]; int thisTime = 0; for (char j : temp) { if (j == thisDigit) ++thisTime; else { sequence += (thisTime + '0'); sequence += thisDigit; //Reconfigure thisDigit and thisTime; thisDigit = j; thisTime = 1; } } //There must be an end. sequence += (thisTime + '0'); sequence += thisDigit; } return sequence; } };
1,064
479
#include <iostream> #include <list> const int MAX = 20; const int MAX_NUMBER = 101; void eraseLessThan(std::list<int> &l, int max) { std::cout << "removing all less than " << max << std::endl; auto it = l.begin(); while (it != l.end()) { if (*it < max) { it = l.erase(it); } else { it++; } } } void init(std::list<int> &l) { for (auto i = 0; i < MAX; i++) l.emplace_back(rand() % MAX_NUMBER); } void print(std::list<int> &l) { for (auto el : l) std::cout << el << ' '; std::cout << std::endl; } int main() { std::list<int> l; init(l); print(l); eraseLessThan(l, rand() % 50 + 50 - rand() % 30); print(l); }
658
289
// test_fseek.cc #include "menon/io.hh" #include <boost/core/lightweight_test.hpp> #include <cstddef> #include <vector> #include <fstream> // テストデータの作成 long long make_test_file(char const* path) { std::vector<std::byte> v(256, std::byte(123)); if (auto stream = std::fopen(path, "wb")) { std::fwrite(v.data(), 1, v.size(), stream); std::fclose(stream); } return static_cast<long long>(v.size()); } int main() { char const* path = "test.data"; [[maybe_unused]] auto n = make_test_file(path); { // fseek/ftell関数の基本的な使い方 auto stream = std::fopen(path, "rb"); menon::fseek(stream, 100, SEEK_SET); BOOST_TEST_EQ(std::ftell(stream), 100); BOOST_TEST_EQ(std::ftell(stream), menon::ftell(stream)); std::fclose(stream); } { // fseek/ftell関数とfsetpos/fgetpos関数の混在 auto stream = std::fopen(path, "rb"); menon::fpos_t pos; menon::fseek(stream, 100, SEEK_SET); BOOST_TEST_EQ(menon::fgetpos(stream, &pos), 0); BOOST_TEST_EQ(pos, 100); BOOST_TEST_EQ(menon::fsetpos(stream, &pos), 0); BOOST_TEST_EQ(std::ftell(stream), 100); std::fclose(stream); } { // istream版のfseek関数 std::ifstream ifs(path); menon::fseek(ifs, 100, SEEK_SET); BOOST_TEST_EQ(ifs.tellg(), 100); } { // istream版のfseek関数とfsetpos/fgetos関数の混在 std::ifstream ifs(path); menon::fpos_t pos; menon::fseek(ifs, 100, SEEK_SET); BOOST_TEST_EQ(menon::fgetpos(ifs, &pos), 0); BOOST_TEST_EQ(pos, 100); BOOST_TEST_EQ(menon::fsetpos(ifs, &pos), 0); BOOST_TEST_EQ(ifs.tellg(), 100); } { // iostream版のfseek関数 std::fstream fs(path); menon::fseek(fs, 100, SEEK_SET); BOOST_TEST_EQ(fs.tellp(), 100); BOOST_TEST_EQ(fs.tellg(), 100); } { // ostream版のfseek関数 std::ofstream ofs(path); menon::fseek(ofs, 100, SEEK_SET); BOOST_TEST_EQ(ofs.tellp(), 100); } { // ostream版のfseek関数とfsetpos/fgetpos関数の混在 std::ofstream ofs(path); menon::fpos_t pos; menon::fseek(ofs, 100, SEEK_SET); BOOST_TEST_EQ(menon::fgetpos(ofs, &pos), 0); BOOST_TEST_EQ(pos, 100); BOOST_TEST_EQ(menon::fsetpos(ofs, &pos), 0); BOOST_TEST_EQ(ofs.tellp(), 100); } std::remove(path); return boost::report_errors(); }
2,214
1,082
#include"stdafx.h" CLC7NavBar::CLC7NavBar(QStackedWidget *stackedwidget):QScrollArea(NULL), m_buttongroup(this) { TR; m_stackedwidget=stackedwidget; installEventFilter(this); ILC7ColorManager *colman = CLC7App::getInstance()->GetMainWindow()->GetColorManager(); m_buttongroup.setExclusive(true); m_groupwidget=new CLC7NavBarWidget(this); setWidget(m_groupwidget); setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setWidgetResizable(true); m_scrollupbutton=new QPushButton(this); m_scrollupbutton->setFixedHeight(16*colman->GetSizeRatio()); m_scrollupbutton->setObjectName("scroll-up-button"); m_scrollupbutton->setIcon(colman->GetMonoColorIcon(":/qss_icons/rc/up_arrow_disabled.png")); m_scrolldownbutton=new QPushButton(this); m_scrolldownbutton->setFixedHeight(16 * colman->GetSizeRatio()); m_scrolldownbutton->setObjectName("scroll-down-button"); m_scrolldownbutton->setIcon(colman->GetMonoColorIcon(":/qss_icons/rc/down_arrow_disabled.png")); m_scrollupbutton->setVisible(false); m_scrolldownbutton->setVisible(false); connect(m_scrollupbutton, &QAbstractButton::pressed, this, &CLC7NavBar::slot_scrollUpButtonPressed); connect(m_scrolldownbutton, &QAbstractButton::pressed, this, &CLC7NavBar::slot_scrollDownButtonPressed); connect(m_scrollupbutton, &QAbstractButton::released, this, &CLC7NavBar::slot_scrollUpButtonReleased); connect(m_scrolldownbutton, &QAbstractButton::released, this, &CLC7NavBar::slot_scrollDownButtonReleased); m_timer = new QTimer(this); connect(m_timer, SIGNAL(timeout()), this, SLOT(slot_doScrolling())); m_scrolling_up=false; m_scrolling_down=false; } void CLC7NavBar::slot_doScrolling(void) {TR; if (m_scrolling_up) { this->verticalScrollBar()->setValue(this->verticalScrollBar()->value() - 5); } if (m_scrolling_down) { this->verticalScrollBar()->setValue(this->verticalScrollBar()->value() + 5); } } void CLC7NavBar::slot_scrollUpButtonPressed(void) {TR; m_scrolling_up = true; m_timer->start(20); } void CLC7NavBar::slot_scrollDownButtonPressed(void) {TR; m_scrolling_down = true; m_timer->start(20); } void CLC7NavBar::slot_scrollUpButtonReleased(void) {TR; m_timer->stop(); m_scrolling_up = false; } void CLC7NavBar::slot_scrollDownButtonReleased(void) {TR; m_timer->stop(); m_scrolling_down = false; } void CLC7NavBar::resizeEvent(QResizeEvent *evt) {TR; QSize sz=evt->size(); m_scrollupbutton->resize(200,16); m_scrollupbutton->move(0,0); m_scrolldownbutton->resize(200, 16); m_scrolldownbutton->move(0,sz.height()-3); } bool CLC7NavBar::eventFilter(QObject *object, QEvent *event) { if(object==this && event->type()==QEvent::Enter) { QSize sz=size(); if(sz.height()<m_groupwidget->height()) { m_scrollupbutton->setVisible(true); m_scrolldownbutton->setVisible(true); } return true; } else if(object==this && event->type()==QEvent::Leave) { m_scrollupbutton->setVisible(false); m_scrolldownbutton->setVisible(false); return true; } return QScrollArea::eventFilter(object,event); } CLC7NavBarGroup *CLC7NavBar::addGroup(QString groupname) {TR; CLC7NavBarGroup *group=new CLC7NavBarGroup(this); if(!groupname.isEmpty()) { m_groups_by_name[groupname]=group; } m_groups.append(group); QVBoxLayout *layout=(QVBoxLayout *)(m_groupwidget->layout()); layout->insertWidget(-1,group); hide(); show(); return group; } CLC7NavBarGroup *CLC7NavBar::insertGroup(int pos, QString groupname) {TR; CLC7NavBarGroup *group=new CLC7NavBarGroup(this); if(!groupname.isEmpty()) { m_groups_by_name[groupname]=group; } m_groups.insert(pos,group); QVBoxLayout *layout=(QVBoxLayout *)(m_groupwidget->layout()); layout->insertWidget(pos,group); hide(); show(); return group; } void CLC7NavBar::removeGroup(int pos) {TR; CLC7NavBarGroup *group=m_groups[pos]; QString key=m_groups_by_name.key(group); if(!key.isEmpty()) { m_groups_by_name.remove(key); } m_groups.removeAt(pos); QVBoxLayout *layout=(QVBoxLayout *)(m_groupwidget->layout()); layout->removeWidget(group); delete group; hide(); show(); } void CLC7NavBar::removeGroup(CLC7NavBarGroup *group) {TR; int pos=m_groups.indexOf(group); QString key=m_groups_by_name.key(group); if(!key.isEmpty()) { m_groups_by_name.remove(key); } m_groups.removeAt(pos); QVBoxLayout *layout=(QVBoxLayout *)(m_groupwidget->layout()); layout->removeWidget(group); delete group; hide(); show(); } void CLC7NavBar::removeGroup(QString groupname) {TR; if(m_groups_by_name.contains(groupname)) { CLC7NavBarGroup *group=m_groups_by_name[groupname]; int pos=m_groups.indexOf(group); QString key=m_groups_by_name.key(group); if(!key.isEmpty()) { m_groups_by_name.remove(key); } m_groups.removeAt(pos); QVBoxLayout *layout=(QVBoxLayout *)(m_groupwidget->layout()); layout->removeWidget(group); delete group; hide(); show(); } } CLC7NavBarGroup *CLC7NavBar::group(QString groupname) {TR; if(m_groups_by_name.contains(groupname)) { CLC7NavBarGroup *group=m_groups_by_name[groupname]; return group; } return NULL; } CLC7NavBarGroup *CLC7NavBar::group(int pos) {TR; return m_groups[pos]; } int CLC7NavBar::indexOf(CLC7NavBarGroup *group) {TR; return m_groups.indexOf(group); } int CLC7NavBar::indexOf(QString groupname) {TR; if(m_groups_by_name.contains(groupname)) { CLC7NavBarGroup *group=m_groups_by_name[groupname]; return m_groups.indexOf(group); } return -1; } CLC7NavBarItem *CLC7NavBar::item(QWidget *buddy) {TR; foreach(CLC7NavBarGroup *group, m_groups) { CLC7NavBarItem *item=group->item(buddy); if(item) { return item; } } return NULL; } int CLC7NavBar::count() {TR; return m_groups.count(); } QStackedWidget *CLC7NavBar::stackedwidget() { return m_stackedwidget; }
6,084
2,441
/* * This file is part of So-bogus, a C++ sparse block matrix library and * Second Order Cone solver. * * Copyright 2013 Gilles Daviet <gdaviet@gmail.com> * * So-bogus 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. * So-bogus 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 So-bogus. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BOGUS_SOCLAW_IMPL_HPP #define BOGUS_SOCLAW_IMPL_HPP #include "SOCLaw.hpp" #include "../../Core/Utils/NumTraits.hpp" #include "FischerBurmeister.hpp" #include "LocalSOCSolver.hpp" #include "LocalSOCSolver.impl.hpp" namespace bogus { template < DenseIndexType Dimension, typename Scalar, bool DeSaxceCOV, local_soc_solver::Strategy Strat > SOCLaw< Dimension, Scalar, DeSaxceCOV, Strat >::SOCLaw(const unsigned n, const double *mu ) : m_mu(mu), m_n(n), m_localTol( std::pow( NumTraits< Scalar >::epsilon(), .75 ) ) { } template < DenseIndexType Dimension, typename Scalar, bool DeSaxceCOV, local_soc_solver::Strategy Strat > bool SOCLaw< Dimension, Scalar, DeSaxceCOV, Strat >::solveLocal(const unsigned problemIndex, const typename Traits::Matrix &A, const typename Traits::Vector &b, typename Traits::Vector &xm , const Scalar scaling ) const { typedef LocalSOCSolver< Traits::dimension, typename Traits::Scalar, DeSaxceCOV, Strat > LocalSolver ; return m_localTol > LocalSolver::solve( A, b, xm, m_mu[ problemIndex ], m_localTol, scaling ) ; } template < DenseIndexType Dimension, typename Scalar, bool DeSaxceCOV, local_soc_solver::Strategy Strat > void SOCLaw< Dimension, Scalar, DeSaxceCOV, Strat >::projectOnConstraint( const unsigned problemIndex, typename Traits::Vector &x ) const { const Scalar nxt = Traits::tp( x ).norm() ; const Scalar mu = m_mu[ problemIndex ] ; const Scalar xn = Traits::np( x ) ; if( mu < 0 ){ x.setZero() ; return ; } // x inside cone if ( nxt <= mu * xn ) return ; // x inside dual cone if( mu * nxt <= -xn ) { x.setZero() ; return ; } const Scalar den2 = ( 1 + mu * mu ) ; const Scalar proj = ( xn + mu * nxt ) / den2 ; Traits::np( x ) = proj ; Traits::tp( x ) *= proj * mu / nxt ; } } #endif
2,589
982
/** * @file fwf - Firewall filter test (also regression test for MXS-683 "qc_mysqlembedded reports as-name * instead of original-name") * - setup Firewall filter to use rules from rule file fw/ruleXX, where XX - number of sub-test * - execute queries for fw/passXX file, expect OK * - execute queries from fw/denyXX, expect Access Denied error (mysql_error 1141) * - repeat for all XX * - setup Firewall filter to block queries next 2 minutes using 'at_time' statement (see template * fw/rules_at_time) * - start sending queries, expect Access Denied now and OK after two mintes * - setup Firewall filter to limit a number of queries during certain time * - start sending queries as fast as possible, expect OK for N first quries and Access Denied for next * queries * - wait, start sending queries again, but only one query per second, expect OK * - try to load rules with syntax error, expect failure for all sessions and queries */ #include <iostream> #include <ctime> #include <maxtest/testconnections.hh> #include <maxtest/sql_t1.hh> #include <maxtest/fw_copy_rules.hh> int main(int argc, char* argv[]) { TestConnections::skip_maxscale_start(true); TestConnections* Test = new TestConnections(argc, argv); int local_result; char str[4096]; char sql[4096]; char pass_file[4096]; char deny_file[4096]; char rules_dir[4096]; FILE* file; sprintf(rules_dir, "%s/fw/", test_dir); int N = 19; int i; for (i = 1; i < N + 1; i++) { Test->set_timeout(180); local_result = 0; sprintf(str, "rules%d", i); copy_rules(Test, str, rules_dir); Test->maxscales->restart_maxscale(0); Test->maxscales->connect_rwsplit(0); sprintf(pass_file, "%s/fw/pass%d", test_dir, i); sprintf(deny_file, "%s/fw/deny%d", test_dir, i); if (Test->verbose) { Test->tprintf("Pass file: %s", pass_file); Test->tprintf("Deny file: %s", deny_file); } file = fopen(pass_file, "r"); if (file != NULL) { if (Test->verbose) { Test->tprintf("********** Trying queries that should be OK ********** "); } while (fgets(sql, sizeof(sql), file)) { if (strlen(sql) > 1) { if (Test->verbose) { Test->tprintf("%s", sql); } int rv = execute_query(Test->maxscales->conn_rwsplit[0], "%s", sql); Test->add_result(rv, "Query should succeed: %s", sql); local_result += rv; } } fclose(file); } else { Test->add_result(1, "Error opening query file"); } file = fopen(deny_file, "r"); if (file != NULL) { if (Test->verbose) { Test->tprintf("********** Trying queries that should FAIL ********** "); } while (fgets(sql, sizeof(sql), file)) { Test->set_timeout(180); if (strlen(sql) > 1) { if (Test->verbose) { Test->tprintf("%s", sql); } execute_query_silent(Test->maxscales->conn_rwsplit[0], sql); if (mysql_errno(Test->maxscales->conn_rwsplit[0]) != 1141) { Test->tprintf("Expected 1141, Access Denied but got %d, %s instead: %s", mysql_errno(Test->maxscales->conn_rwsplit[0]), mysql_error(Test->maxscales->conn_rwsplit[0]), sql); local_result++; } } } fclose(file); } else { Test->add_result(1, "Error opening query file"); } if (local_result) { Test->add_result(1, "********** rules%d test FAILED", i); } else { Test->tprintf("********** rules%d test PASSED", i); } mysql_close(Test->maxscales->conn_rwsplit[0]); } Test->set_timeout(180); // Test for at_times clause if (Test->verbose) { Test->tprintf("Trying at_times clause"); } copy_rules(Test, (char*) "rules_at_time", rules_dir); if (Test->verbose) { Test->tprintf("DELETE quries without WHERE clause will be blocked during the 30 seconds"); Test->tprintf("Put time to rules.txt: %s", str); } Test->maxscales->ssh_node_f(0, false, "start_time=`date +%%T`;" "stop_time=` date --date \"now +30 secs\" +%%T`;" "%s sed -i \"s/###time###/$start_time-$stop_time/\" %s/rules/rules.txt", Test->maxscales->access_sudo(0), Test->maxscales->access_homedir(0)); Test->maxscales->restart_maxscale(0); Test->maxscales->connect_rwsplit(0); sleep(10); Test->tprintf("Trying 'DELETE FROM t1' and expecting FAILURE"); execute_query_silent(Test->maxscales->conn_rwsplit[0], "DELETE FROM t1"); if (mysql_errno(Test->maxscales->conn_rwsplit[0]) != 1141) { Test->add_result(1, "Query succeded, but fail expected, error is %d", mysql_errno(Test->maxscales->conn_rwsplit[0])); } Test->tprintf("Waiting 30 seconds and trying 'DELETE FROM t1', expecting OK"); Test->stop_timeout(); sleep(30); Test->set_timeout(180); Test->try_query(Test->maxscales->conn_rwsplit[0], "DELETE FROM t1"); mysql_close(Test->maxscales->conn_rwsplit[0]); Test->maxscales->stop_maxscale(0); Test->tprintf("Trying limit_queries clause"); Test->tprintf("Copying rules to Maxscale machine: %s", str); copy_rules(Test, (char*) "rules_limit_queries", rules_dir); Test->maxscales->start_maxscale(0); Test->maxscales->connect_rwsplit(0); Test->tprintf("Trying 10 quries as fast as possible"); for (i = 0; i < 10; i++) { Test->add_result(execute_query_silent(Test->maxscales->conn_rwsplit[0], "SELECT * FROM t1"), "%d -query failed", i); } Test->tprintf("Expecting failures during next 5 seconds"); time_t start_time_clock = time(NULL); timeval t1, t2; double elapsedTime; gettimeofday(&t1, NULL); do { gettimeofday(&t2, NULL); elapsedTime = (t2.tv_sec - t1.tv_sec); elapsedTime += (double) (t2.tv_usec - t1.tv_usec) / 1000000.0; } while ((execute_query_silent(Test->maxscales->conn_rwsplit[0], "SELECT * FROM t1") != 0) && (elapsedTime < 10)); Test->tprintf("Quries were blocked during %f (using clock_gettime())", elapsedTime); Test->tprintf("Quries were blocked during %lu (using time())", time(NULL) - start_time_clock); if ((elapsedTime > 6) or (elapsedTime < 4)) { Test->add_result(1, "Queries were blocked during wrong time"); } Test->set_timeout(180); Test->tprintf("Trying 12 quries, 1 query / second"); for (i = 0; i < 12; i++) { sleep(1); Test->add_result(execute_query_silent(Test->maxscales->conn_rwsplit[0], "SELECT * FROM t1"), "query failed"); if (Test->verbose) { Test->tprintf("%d ", i); } } int rval = Test->global_result; delete Test; return rval; }
7,806
2,511
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "lite/kernels/x86/search_grnn_compute.h" #include <gtest/gtest.h> #include <memory> #include <utility> #include <vector> #include "lite/core/op_registry.h" namespace paddle { namespace lite { namespace kernels { namespace x86 { TEST(search_grnn_x86, retrive_op) { auto kernel = KernelRegistry::Global().Create<TARGET(kX86), PRECISION(kFloat)>( "search_grnn"); ASSERT_FALSE(kernel.empty()); ASSERT_TRUE(kernel.front()); } TEST(search_grnn_x86, init) { SearchGrnnCompute<float> ssdc; ASSERT_EQ(ssdc.precision(), PRECISION(kFloat)); ASSERT_EQ(ssdc.target(), TARGET(kX86)); } TEST(search_grnn_x86, run_test) { int num_input = 128; int num_hidden = 128; int num_batch = 3; lite::Tensor x, wi, wh, out, idx_sorted_by_width, layout_input, tmp_buffer; x.Resize({num_batch, num_input}); wi.Resize({3, num_hidden, num_input}); wh.Resize({3, num_hidden, num_hidden}); // out.Resize({num_batch, num_hidden}); LoD x_lod{}; x_lod.push_back({0, 1, 3}); x.set_lod(x_lod); auto* x_data = x.mutable_data<float>(); for (int64_t i = 0; i < x.numel(); i++) { x_data[i] = static_cast<float>(i); } auto* wi_data = wi.mutable_data<float>(); for (int64_t i = 0; i < wi.numel(); i++) { wi_data[i] = static_cast<float>(i); } auto* wh_data = wh.mutable_data<float>(); for (int64_t i = 0; i < wh.numel(); i++) { wh_data[i] = static_cast<float>(i); } std::unique_ptr<KernelContext> ctx(new KernelContext); ctx->As<X86Context>(); operators::SearchGrnnParam param; param.x = &x; param.wi = &wi; param.wh = &wh; param.out = &out; param.idx_sorted_by_width = &idx_sorted_by_width; param.layout_input = &layout_input; param.tmp_buffer = &tmp_buffer; param.num_input = num_input; param.num_hidden = num_hidden; SearchGrnnCompute<float> sgc; sgc.SetContext(std::move(ctx)); sgc.SetParam(param); sgc.Run(); // std::vector<float> ref_results = {0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 18, 19}; auto* out_data = out.mutable_data<float>(); LOG(INFO) << out.numel(); for (int i = 0; i < out.numel(); i++) { // EXPECT_NEAR(out_data[i], ref_results[i], 1e-3); LOG(INFO) << out_data[i]; } } } // namespace x86 } // namespace kernels } // namespace lite } // namespace paddle USE_LITE_KERNEL(search_grnn, kX86, kFloat, kNCHW, def);
2,956
1,221
#include "../.././Contrib/RawVidFileFormat/GrabfileReader.hh"
64
28
/* Copyright 2017-2019 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "lullaby/tools/common/file_utils.h" #if defined(_MSC_VER) #include <direct.h> // Windows functions for directory creation. #else #include <sys/stat.h> #endif #include <fstream> #include <string> namespace lull { namespace tool { bool DefaultLoadFile(const char* filename, bool binary, std::string* out); static LoadFileFunction g_load_file_fn = DefaultLoadFile; void SetLoadFileFunction(LoadFileFunction fn) { if (fn) { g_load_file_fn = fn; } else { g_load_file_fn = DefaultLoadFile; } } bool FileExists(const char* filename) { std::ifstream file(filename, std::ios::binary); return file ? true : false; } bool DefaultLoadFile(const char* filename, bool binary, std::string* out) { std::ifstream file(filename, binary ? std::ios::binary : std::ios::in); if (!file) { return false; } file.seekg(0, std::ios::end); out->resize(file.tellg()); file.seekg(0, std::ios::beg); file.read(const_cast<char*>(out->c_str()), out->size()); return true; } bool LoadFile(const char* filename, bool binary, std::string* out) { return g_load_file_fn(filename, binary, out); } bool SaveFile(const void* bytes, size_t num_bytes, const char* filename, bool binary) { std::ofstream file(filename, binary ? std::ios::binary : std::ios::out); if (!file) { return false; } file.write(reinterpret_cast<const char*>(bytes), num_bytes); file.close(); return true; } bool CopyFile(const char* dst, const char* src) { std::ifstream srcfile(src, std::ios::binary); std::ofstream dstfile(dst, std::ios::binary); if (srcfile.is_open() && dstfile.is_open()) { dstfile << srcfile.rdbuf(); return true; } return false; } static int MakeDir(const char* sub_dir) { #if defined(_MSC_VER) return _mkdir(sub_dir); #else static const mode_t kDirectoryMode = 0755; return mkdir(sub_dir, kDirectoryMode); #endif } bool CreateFolder(const char* directory) { if (directory == nullptr || *directory == 0) { return true; } std::string dir = directory; for (size_t slash = 0; slash != std::string::npos;) { // Find the next sub-directory (after the last one we just created). slash = dir.find_first_of("\\/", slash + 1); // If slash is npos, we take the entire `dir` and create it. const std::string sub_dir = dir.substr(0, slash); // Create the sub-directory (or continue if the directory already exists). const int result = MakeDir(sub_dir.c_str()); if (result != 0 && errno != EEXIST) { return false; } } return true; } } // namespace tool } // namespace lull
3,180
1,076
#include <cstdio> #include <iostream> using namespace std; void print_array(int* arr, int n) // 打印数组 { if (n == 0) { printf("ERROR: Array length is ZERO\n"); return; } printf("%d", arr[0]); for (int i = 1; i < n; i++) { printf(" %d", arr[i]); } printf("\n"); } void adjustHeap(int* arr, int start, int end) // 编程实现堆的调整 { // 请在这里补充代码,完成本关任务 /********** Begin *********/ // When this function is called, // the two subtrees should already be heaps. for (int parent = start, son = start * 2 + 1; son <= end; parent = son, son = son * 2 + 1 ) { // The parent should swap with the bigger son (if it's going to swap) if (son + 1 <= end && arr[son] < arr[son + 1]) son = son + 1; if (arr[parent] >= arr[son]) return; swap(arr[parent], arr[son]); } /********** End **********/ } int* heap_sort(int* arr, int n) // 基于adjustHeap函数编程实现堆排序 // 函数参数:无序数组arr 数组长度n // 函数返回值:返回从小到大排序后的数组 { // 请在这里补充代码,完成本关任务 /********** Begin *********/ // Build a heap. for (int i = (n - 2) / 2; i >= 0; --i) adjustHeap(arr, i, n - 1); // Remove the max of arr, which is the top of heap. for (int i = n - 1; i > 0; --i) { swap(arr[0], arr[i]); adjustHeap(arr, 0, i - 1); } return arr; /********** End **********/ }
1,393
595
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/app_list/search/ranking/score_normalizing_ranker.h" #include "base/strings/strcat.h" #include "base/strings/string_number_conversions.h" #include "chrome/browser/ui/app_list/search/chrome_search_result.h" #include "chrome/browser/ui/app_list/search/search_controller.h" namespace app_list { namespace { // Prefix added to the name of each score normalizer, which is used for prefs // storage. constexpr char kNormalizerPrefix[] = "categorical_search_normalizer_"; // Returns true if results from this provider should not have their result // scores normalized. This is to prevent creating an unnecessary number of // normalizers. bool ShouldIgnoreProvider(ProviderType type) { switch (type) { // Deprecated types: case ProviderType::kLauncher: case ProviderType::kAnswerCard: // Types not associated with a provider: case ProviderType::kFileChip: case ProviderType::kDriveChip: // Types that only create suggestion chips: case ProviderType::kAssistantChip: // Types that only ever create one result: case ProviderType::kPlayStoreReinstallApp: // Internal types: case ProviderType::kUnknown: case ProviderType::kInternalPrivacyInfo: return true; default: return false; } } } // namespace ScoreNormalizingRanker::ScoreNormalizingRanker(Profile* profile) { static constexpr int kProviderMin = static_cast<int>(ProviderType::kUnknown); static constexpr int kProviderMax = static_cast<int>(ProviderType::kMaxValue); for (int provider_int = kProviderMin; provider_int <= kProviderMax; ++provider_int) { const ProviderType provider = static_cast<ProviderType>(provider_int); if (ShouldIgnoreProvider(provider)) continue; const std::string name = base::StrCat({kNormalizerPrefix, base::NumberToString(provider_int)}); } } ScoreNormalizingRanker::~ScoreNormalizingRanker() {} void ScoreNormalizingRanker::Rank(ResultsMap& results, CategoriesMap& categories, ProviderType provider) {} } // namespace app_list
2,297
669
#include "segment_accessor.hpp" #include "resolve_type.hpp" namespace opossum::detail { template <typename T> std::unique_ptr<AbstractSegmentAccessor<T>> CreateSegmentAccessor<T>::create( const std::shared_ptr<const BaseSegment>& segment) { std::unique_ptr<AbstractSegmentAccessor<T>> accessor; resolve_segment_type<T>(*segment, [&](const auto& typed_segment) { using SegmentType = std::decay_t<decltype(typed_segment)>; if constexpr (std::is_same_v<SegmentType, ReferenceSegment>) { const auto& pos_list = *typed_segment.pos_list(); if (pos_list.references_single_chunk() && !pos_list.empty()) { // If the pos list stores a NULL value, its chunk_id references a non-existing chunk. If all entries reference // the same chunk_id, we can safely assume that all other entries are also NULL. Instead of using an accessor // that checks for the reference being NULL, we can simply use the NullAccessor, which always returns nullopt, // i.e., the accessors representation of NULL values. // Note that this is independent of the row being pointed to holding a NULL value. if (pos_list[ChunkOffset{0}].is_null()) { accessor = std::make_unique<NullAccessor<T>>(); } else { auto chunk_id = pos_list[ChunkOffset{0}].chunk_id; auto referenced_segment = typed_segment.referenced_table()->get_chunk(chunk_id)->get_segment(typed_segment.referenced_column_id()); // If only a single segment is referenced, we can resolve it once and avoid some more expensive // virtual method calls later. resolve_segment_type<T>(*referenced_segment, [&](const auto& typed_referenced_segment) { using ReferencedSegment = std::decay_t<decltype(typed_referenced_segment)>; if constexpr (!std::is_same_v<ReferencedSegment, ReferenceSegment>) { accessor = std::make_unique<SingleChunkReferenceSegmentAccessor<T, ReferencedSegment>>( pos_list, chunk_id, typed_referenced_segment); } else { Fail("Encountered nested ReferenceSegments"); } }); } } else { accessor = std::make_unique<MultipleChunkReferenceSegmentAccessor<T>>(typed_segment); } } else { accessor = std::make_unique<SegmentAccessor<T, SegmentType>>(typed_segment); } }); return accessor; } EXPLICITLY_INSTANTIATE_DATA_TYPES(CreateSegmentAccessor); } // namespace opossum::detail
2,517
729
#include "kernsem.h" #include "asystem.h" KernelSem::KernelSem(int init, Semaphore *initSemph) : count(init), semph(initSemph) { System::semaphores.add(this); } KernelSem::~KernelSem() { while (count < 0) signal(); } int KernelSem::val() const { return count; } int KernelSem::wait(Time maxTimeToWait) { lock if (count-- > 0) { unlock return 1; } System::runningPcb->state = PCB::BLOCKED; if (maxTimeToWait == 0) { // Cisto blokiranje do nekog signal()-a blockedThreads.add((PCB*) System::runningPcb); } else { // Vremensko blokiranje, novi SemaphoredThread se ubacuje na pravo mesto u nizu tako da poredak vremena budjenja ostane rastuci SemaphoredThread st = SemaphoredThread((PCB*) System::runningPcb, System::bootTimeDelta + maxTimeToWait); if (timeBlocked.empty()) { // Nema sta da se pretrazuje timeBlocked.add(st); } else { Iterator<SemaphoredThread> t = timeBlocked.iterStart(), rightPlace = timeBlocked.iterEnd(); while (t != timeBlocked.iterEnd() && st.futureWakeupTime < t.current->data.futureWakeupTime) { rightPlace = t; t++; } if (rightPlace != timeBlocked.iterEnd()) { // Nadjena je vrednost posle koje treba ubaciti ovu novu timeBlocked.insert(rightPlace, st); } else { // rightPlace je ostao kraj niza, znaci da nema onog elementa POSLE koga bi ovo trebalo ubaciti // To znaci da su svi VECI od ovog novog, i on onda ide pre svih njih timeBlocked.addToFront(st); } } } unlock dispatch(); // Mozda je isteklo vreme? if (!System::runningPcb->semphTimeExceeded) { System::runningPcb->semphTimeExceeded = false; return 0; } return 1; } void KernelSem::releaseBlocked() { PCB *pcb = blockedThreads.front(); blockedThreads.popFront(); pcb->state = PCB::READY; pcb->semphTimeExceeded = true; //? Scheduler::put(pcb); } void KernelSem::releaseTimed() { PCB *pcb = timeBlocked.front().myPCB; timeBlocked.popFront(); pcb->state = PCB::READY; pcb->semphTimeExceeded = true; Scheduler::put(pcb); } void KernelSem::signal() { lock if (count++ < 0) { if (!blockedThreads.empty()) { releaseBlocked(); } else if (!timeBlocked.empty()) { releaseTimed(); } } unlock } void KernelSem::timerCleanup() { lock while (!timeBlocked.empty()) { if (timeBlocked.front().futureWakeupTime > System::bootTimeDelta) break; PCB *pcb = timeBlocked.front().myPCB; timeBlocked.popFront(); pcb->state = PCB::READY; pcb->semphTimeExceeded = false; Scheduler::put(pcb); } unlock }
2,535
1,095
#include "Segment.h"
20
9
// Copyright Eric Niebler 2013-2015 // Copyright 2015-2020 Hartmut Kaiser // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // This was modeled after the code available in the Range v3 library #pragma once #include <hpx/config.hpp> #include <hpx/assert.hpp> #include <hpx/datastructures/tagged.hpp> #include <hpx/datastructures/tuple.hpp> #include <hpx/type_support/decay.hpp> #include <cstddef> #include <type_traits> #include <utility> namespace hpx { namespace util { /////////////////////////////////////////////////////////////////////////// template <typename F, typename S> struct tagged_pair : tagged<std::pair<typename detail::tag_elem<F>::type, typename detail::tag_elem<S>::type>, typename detail::tag_spec<F>::type, typename detail::tag_spec<S>::type> { typedef tagged<std::pair<typename detail::tag_elem<F>::type, typename detail::tag_elem<S>::type>, typename detail::tag_spec<F>::type, typename detail::tag_spec<S>::type> base_type; template <typename... Ts> tagged_pair(Ts&&... ts) : base_type(std::forward<Ts>(ts)...) { } }; /////////////////////////////////////////////////////////////////////////// template <typename Tag1, typename Tag2, typename T1, typename T2> constexpr HPX_FORCEINLINE tagged_pair<Tag1(typename decay<T1>::type), Tag2(typename decay<T2>::type)> make_tagged_pair(std::pair<T1, T2>&& p) { typedef tagged_pair<Tag1(typename decay<T1>::type), Tag2(typename decay<T2>::type)> result_type; return result_type(std::move(p)); } template <typename Tag1, typename Tag2, typename T1, typename T2> constexpr HPX_FORCEINLINE tagged_pair<Tag1(typename decay<T1>::type), Tag2(typename decay<T2>::type)> make_tagged_pair(std::pair<T1, T2> const& p) { typedef tagged_pair<Tag1(typename decay<T1>::type), Tag2(typename decay<T2>::type)> result_type; return result_type(p); } template <typename Tag1, typename Tag2, typename... Ts> constexpr HPX_FORCEINLINE tagged_pair< Tag1(typename hpx::tuple_element<0, hpx::tuple<Ts...>>::type), Tag2(typename hpx::tuple_element<1, hpx::tuple<Ts...>>::type)> make_tagged_pair(hpx::tuple<Ts...>&& p) { static_assert( sizeof...(Ts) >= 2, "hpx::tuple must have at least 2 elements"); typedef tagged_pair< Tag1(typename hpx::tuple_element<0, hpx::tuple<Ts...>>::type), Tag2(typename hpx::tuple_element<1, hpx::tuple<Ts...>>::type)> result_type; return result_type(std::move(get<0>(p)), std::move(get<1>(p))); } template <typename Tag1, typename Tag2, typename... Ts> constexpr HPX_FORCEINLINE tagged_pair< Tag1(typename hpx::tuple_element<0, hpx::tuple<Ts...>>::type), Tag2(typename hpx::tuple_element<1, hpx::tuple<Ts...>>::type)> make_tagged_pair(hpx::tuple<Ts...> const& p) { static_assert( sizeof...(Ts) >= 2, "hpx::tuple must have at least 2 elements"); typedef tagged_pair< Tag1(typename hpx::tuple_element<0, hpx::tuple<Ts...>>::type), Tag2(typename hpx::tuple_element<1, hpx::tuple<Ts...>>::type)> result_type; return result_type(get<0>(p), get<1>(p)); } /////////////////////////////////////////////////////////////////////////// template <typename Tag1, typename Tag2, typename T1, typename T2> constexpr HPX_FORCEINLINE tagged_pair<Tag1(typename decay<T1>::type), Tag2(typename decay<T2>::type)> make_tagged_pair(T1&& t1, T2&& t2) { typedef tagged_pair<Tag1(typename decay<T1>::type), Tag2(typename decay<T2>::type)> result_type; return result_type(std::forward<T1>(t1), std::forward<T2>(t2)); } }} // namespace hpx::util namespace hpx { /////////////////////////////////////////////////////////////////////////// template <typename Tag1, typename Tag2> struct tuple_size<util::tagged_pair<Tag1, Tag2>> : std::integral_constant<std::size_t, 2> { }; template <std::size_t N, typename Tag1, typename Tag2> struct tuple_element<N, util::tagged_pair<Tag1, Tag2>> : hpx::tuple_element<N, std::pair<typename util::detail::tag_elem<Tag1>::type, typename util::detail::tag_elem<Tag2>::type>> { }; } // namespace hpx
4,735
1,593
#include "d3d/voxel/voxelize.h" #include <unordered_map> #include <unordered_set> #include <array> #include <tuple> #include <vector> #include <iostream> #include <limits> using namespace std; using namespace at; using namespace pybind11::literals; template <typename T> using toptional = torch::optional<T>; typedef tuple<int, int, int> coord_t; struct coord_hash : public std::unary_function<coord_t, std::size_t> { std::size_t operator()(const coord_t& k) const { constexpr int p = 997; // match this to the range of k size_t ret = std::get<0>(k); ret = ret * p + std::get<1>(k); ret = ret * p + std::get<2>(k); return ret; } }; struct coord_equal : public std::binary_function<coord_t, coord_t, bool> { bool operator()(const coord_t& v0, const coord_t& v1) const { return ( std::get<0>(v0) == std::get<0>(v1) && std::get<1>(v0) == std::get<1>(v1) && std::get<2>(v0) == std::get<2>(v1) ); } }; typedef unordered_map<coord_t, int, coord_hash, coord_equal> coord_m; // XXX: Consider use robin-map template <ReductionType Reduction> py::dict voxelize_3d_dense_templated( const Tensor points, const Tensor voxel_shape, const Tensor voxel_bound, const int max_points, const int max_voxels ) { auto points_ = points.accessor<float, 2>(); auto voxel_shape_ = voxel_shape.accessor<int, 1>(); auto voxel_bound_ = voxel_bound.accessor<float, 1>(); Tensor voxels = torch::zeros({max_voxels, max_points, points_.size(1)}, torch::dtype(torch::kFloat32)); Tensor coords = torch::empty({max_voxels, 3}, torch::dtype(torch::kLong)); Tensor voxel_pmask = torch::empty({max_voxels, max_points}, torch::dtype(torch::kBool)); Tensor voxel_npoints = torch::zeros(max_voxels, torch::dtype(torch::kInt32)); auto voxels_ = voxels.accessor<float, 3>(); auto coords_ = coords.accessor<int64_t, 2>(); auto voxel_pmask_ = voxel_pmask.accessor<bool, 2>(); auto voxel_npoints_ = voxel_npoints.accessor<int, 1>(); // initialize aggregated values Tensor aggregates; switch(Reduction) { case ReductionType::NONE: aggregates = torch::empty({0, 0}); break; case ReductionType::MEAN: aggregates = torch::zeros({max_voxels, points_.size(1)}, torch::dtype(torch::kFloat32)); break; case ReductionType::MAX: aggregates = torch::full({max_voxels, points_.size(1)}, -numeric_limits<float>::infinity(), torch::dtype(torch::kFloat32)); break; case ReductionType::MIN: aggregates = torch::full({max_voxels, points_.size(1)}, numeric_limits<float>::infinity(), torch::dtype(torch::kFloat32)); break; } auto aggregates_ = aggregates.accessor<float, 2>(); // calculate voxel sizes and other variables float voxel_size_[3]; for (int d = 0; d < 3; ++d) voxel_size_[d] = (voxel_bound_[(d<<1) | 1] - voxel_bound_[d<<1]) / voxel_shape_[d]; auto npoints = points_.size(0); auto nfeatures = points_.size(1); coord_m voxel_idmap; int coord_temp[3]; int nvoxels = 0; for (int i = 0; i < npoints; ++i) { // calculate voxel-wise coordinates bool out_of_range = false; for (int d = 0; d < 3; ++d) { int idx = int((points_[i][d] - voxel_bound_[d << 1]) / voxel_size_[d]); if (idx < 0 || idx >= voxel_shape_[d]) { out_of_range = true; break; } coord_temp[d] = idx; } if (out_of_range) continue; // assign voxel int voxel_idx; auto coord_tuple = make_tuple(coord_temp[0], coord_temp[1], coord_temp[2]); auto voxel_iter = voxel_idmap.find(coord_tuple); if (voxel_iter == voxel_idmap.end()) { if (nvoxels >= max_voxels) continue; voxel_idx = nvoxels++; voxel_idmap[coord_tuple] = voxel_idx; for (int d = 0; d < 3; ++d) coords_[voxel_idx][d] = coord_temp[d]; } else voxel_idx = voxel_iter->second; // assign voxel mask and original features int n = voxel_npoints_[voxel_idx]++; if (n < max_points) { voxel_pmask_[voxel_idx][n] = true; for (int d = 0; d < nfeatures; ++d) voxels_[voxel_idx][n][d] = points_[i][d]; } // reduce features for (int d = 0; d < nfeatures; ++d) { switch (Reduction) { case ReductionType::MEAN: // mean aggregates_[voxel_idx][d] += points_[i][d]; break; case ReductionType::MAX: // max, aggregates should be initialized as positive huge numbers aggregates_[voxel_idx][d] = max(aggregates_[voxel_idx][d], points_[i][d]); break; case ReductionType::MIN: // min, aggregates should be initialized as negative huge numbers aggregates_[voxel_idx][d] = min(aggregates_[voxel_idx][d], points_[i][d]); break; case ReductionType::NONE: default: break; } } } // if aggregate is mean, divide them by the numbers now if (Reduction == ReductionType::MEAN) for (int i = 0; i < nvoxels; i++) for (int d = 0; d < nfeatures; d++) aggregates_[i][d] /= voxel_npoints_[i]; // remove unused voxel entries if (Reduction != ReductionType::NONE) return py::dict("voxels"_a=voxels.slice(0, 0, nvoxels), "coords"_a=coords.slice(0, 0, nvoxels), "voxel_pmask"_a=voxel_pmask.slice(0, 0, nvoxels), "voxel_npoints"_a=voxel_npoints.slice(0, 0, nvoxels), "aggregates"_a=aggregates.slice(0, 0, nvoxels) ); else return py::dict("voxels"_a=voxels.slice(0, 0, nvoxels), "coords"_a=coords.slice(0, 0, nvoxels), "voxel_pmask"_a=voxel_pmask.slice(0, 0, nvoxels), "voxel_npoints"_a=voxel_npoints.slice(0, 0, nvoxels) ); } py::dict voxelize_3d_dense( const Tensor points, const Tensor voxel_shape, const Tensor voxel_bound, const int max_points, const int max_voxels, const ReductionType reduction_type ) { #define _VOXELIZE_3D_REDUCTION_TYPE_CASE(n) case n: \ return voxelize_3d_dense_templated<n>(points, voxel_shape, voxel_bound, max_points, max_voxels) switch (reduction_type) { _VOXELIZE_3D_REDUCTION_TYPE_CASE(ReductionType::NONE); _VOXELIZE_3D_REDUCTION_TYPE_CASE(ReductionType::MEAN); _VOXELIZE_3D_REDUCTION_TYPE_CASE(ReductionType::MIN); _VOXELIZE_3D_REDUCTION_TYPE_CASE(ReductionType::MAX); default: throw py::value_error("Unsupported reduction type in voxelization!"); } #undef _VOXELIZE_3D_REDUCTION_TYPE_CASE } py::dict voxelize_3d_sparse( const Tensor points, const Tensor voxel_shape, const Tensor voxel_bound, const toptional<int> max_points, const toptional<int> max_voxels ) { auto points_ = points.accessor<float, 2>(); auto voxel_shape_ = voxel_shape.accessor<int, 1>(); auto voxel_bound_ = voxel_bound.accessor<float, 1>(); // fill points mapping with -1 (unassigned) Tensor points_mapping = torch::full(points_.size(0), -1, torch::dtype(torch::kLong)); auto points_mapping_ = points_mapping.accessor<int64_t, 1>(); // calculate voxel sizes and other variables float voxel_size_[3]; for (int d = 0; d < 3; ++d) voxel_size_[d] = (voxel_bound_[(d<<1) | 1] - voxel_bound_[d<<1]) / voxel_shape_[d]; auto npoints = points_.size(0); auto nfeatures = points_.size(1); coord_m voxel_idmap; vector<int> voxel_npoints; vector<Tensor> coords_list; int coord_temp[3]; int nvoxels = 0; bool need_mask = false; for (int i = 0; i < npoints; ++i) { // calculate voxel-wise coordinates bool out_of_range = false; for (int d = 0; d < 3; ++d) { int idx = int((points_[i][d] - voxel_bound_[d << 1]) / voxel_size_[d]); if (idx < 0 || idx >= voxel_shape_[d]) { out_of_range = true; break; } coord_temp[d] = idx; } if (out_of_range) { need_mask = true; continue; } // assign voxel int voxel_idx; auto coord_tuple = make_tuple(coord_temp[0], coord_temp[1], coord_temp[2]); auto voxel_iter = voxel_idmap.find(coord_tuple); if (voxel_iter == voxel_idmap.end()) { voxel_idx = nvoxels++; voxel_idmap[coord_tuple] = voxel_idx; voxel_npoints.push_back(1); coords_list.push_back(torch::tensor({coord_temp[0], coord_temp[1], coord_temp[2]}, torch::kLong)); } else { voxel_idx = voxel_iter->second; voxel_npoints[voxel_idx] += 1; } points_mapping_[i] = voxel_idx; } // process mask Tensor points_filtered = points; Tensor masked; if (need_mask) { masked = torch::where(points_mapping >= 0)[0]; points_filtered = torch::index_select(points, 0, masked); points_mapping = torch::index_select(points_mapping, 0, masked); } else { masked = torch::arange(npoints); } return py::dict( "points"_a=points_filtered, "points_mask"_a=masked, "points_mapping"_a=points_mapping, "coords"_a=torch::stack(coords_list), "voxel_npoints"_a=torch::tensor(voxel_npoints, torch::kInt32)); } py::dict voxelize_sparse( const Tensor points, const Tensor voxel_size, const toptional<int> ndim ) { auto points_ = points.accessor<float, 2>(); auto voxel_size_ = voxel_size.accessor<float, 1>(); int ndim_ = ndim.value_or(3); auto npoints = points_.size(0); Tensor points_mapping = torch::empty(npoints, torch::dtype(torch::kLong)); auto points_mapping_ = points_mapping.accessor<int64_t, 1>(); coord_m voxel_idmap; // coord to voxel id vector<int> voxel_npoints; // number of points per voxel vector<Tensor> coords_list; // list of coordinates int coord_temp[ndim_]; // array to store temporary coordinate int nvoxels = 0; // number of total voxels for (int i = 0; i < npoints; ++i) { // calculate voxel-wise coordinates for (int d = 0; d < ndim_; ++d) coord_temp[d] = floor(points_[i][d] / voxel_size_[d]); // assign voxel int voxel_idx; auto coord_tuple = make_tuple(coord_temp[0], coord_temp[1], coord_temp[2]); auto voxel_iter = voxel_idmap.find(coord_tuple); if (voxel_iter == voxel_idmap.end()) { voxel_idx = nvoxels++; voxel_idmap[coord_tuple] = voxel_idx; voxel_npoints.push_back(1); coords_list.push_back(torch::tensor({coord_temp[0], coord_temp[1], coord_temp[2]}, torch::kLong)); } else { voxel_idx = voxel_iter->second; voxel_npoints[voxel_idx] += 1; } points_mapping_[i] = voxel_idx; } return py::dict( "points_mapping"_a=points_mapping, "coords"_a=torch::stack(coords_list), "voxel_npoints"_a=torch::tensor(voxel_npoints, torch::kInt32) ); } py::dict voxelize_filter( const Tensor feats, const Tensor points_mapping, const Tensor coords, const Tensor voxel_npoints, const toptional<Tensor> coords_bound, const toptional<int> min_points, const toptional<int> max_points, const toptional<int> max_voxels, const toptional<MaxPointsFilterType> max_points_filter, const toptional<MaxVoxelsFilterType> max_voxels_filter ) { auto feats_ = feats.accessor<float, 2>(); auto coords_ = coords.accessor<int64_t, 2>(); auto voxel_npoints_ = voxel_npoints.accessor<int, 1>(); auto points_mapping_ = points_mapping.accessor<int64_t, 1>(); Tensor coord_bound_default = coords_bound.value_or(torch::empty({0, 0}, torch::dtype(torch::kFloat))); auto coords_bound_ = coord_bound_default.accessor<int64_t, 2>(); int nvoxels = coords_.size(0); int ndim = coords_.size(1); int npoints = feats_.size(0); int nfeats = feats_.size(1); // default values MaxPointsFilterType max_points_filter_ = max_points_filter.value_or(MaxPointsFilterType::NONE); MaxVoxelsFilterType max_voxels_filter_ = max_voxels_filter.value_or(MaxVoxelsFilterType::NONE); if (max_voxels_filter != MaxVoxelsFilterType::NONE && !max_voxels.has_value()) throw py::value_error("Must specify maximum voxel count to filter voxels!"); int max_voxels_ = max_voxels.value(); if (max_points_filter != MaxPointsFilterType::NONE && !max_points.has_value()) throw py::value_error("Must specify maximum points per voxel to filter points!"); int max_points_ = max_points.value(); int min_points_ = min_points.value_or(0); // filter out voxels at first std::unordered_map<int, int> voxel_indices; int nvoxel_filtered = 0; auto test_bound = [&](int i) -> bool{ bool out_of_range = false; for (int d = 0; d < ndim; d++) if (coords_[i][d] < coords_bound_[d][0] || coords_[i][d] >= coords_bound_[d][1]) { out_of_range = true; break; } return out_of_range; }; switch (max_voxels_filter_) { case MaxVoxelsFilterType::NONE: for (int i = 0; i < nvoxels; i++) { if (voxel_npoints_[i] < min_points_) // skip voxels with few points continue; if (coords_bound.has_value() && test_bound(i)) continue; voxel_indices[i] = nvoxel_filtered++; } break; case MaxVoxelsFilterType::TRIM: cout << "In trim" << endl; for (int i = 0; i < nvoxels; i++) { if (nvoxel_filtered >= max_voxels_) break; if (voxel_npoints_[i] < min_points_) // skip voxels with few points continue; if (coords_bound.has_value() && test_bound(i)) continue; voxel_indices[i] = nvoxel_filtered++; } break; case MaxVoxelsFilterType::DESCENDING: auto order = torch::argsort(voxel_npoints, 0, true); auto ordered_ = order.accessor<long, 1>(); for (int i = 0; i < nvoxels; i++) { if (nvoxel_filtered >= max_voxels_) break; if (voxel_npoints_[ordered_[i]] < min_points_) break; // skip voxels with few points if (coords_bound.has_value() && test_bound(ordered_[i])) continue; voxel_indices[ordered_[i]] = nvoxel_filtered++; } break; } // filter coordinates Tensor coords_filtered = torch::empty({nvoxel_filtered, ndim}, coords.options()); auto coords_filtered_ = coords_filtered.accessor<int64_t, 2>(); for (auto iter = voxel_indices.begin(); iter != voxel_indices.end(); iter++) for (int d = 0; d < ndim; d++) coords_filtered_[iter->second][d] = coords_[iter->first][d]; // filter out points, first create output tensors Tensor points_mapping_filtered = torch::empty_like(points_mapping); Tensor voxel_npoints_filtered = torch::zeros({nvoxel_filtered}, voxel_npoints.options()); auto points_mapping_filtered_ = points_mapping_filtered.accessor<int64_t, 1>(); auto voxel_npoints_filtered_ = voxel_npoints_filtered.accessor<int, 1>(); switch(max_points_filter_) { case MaxPointsFilterType::NONE: for (int i = 0; i < npoints; i++) { auto new_id = voxel_indices.find(points_mapping_[i]); if (new_id != voxel_indices.end()) { int vid = new_id->second; points_mapping_filtered_[i] = vid; voxel_npoints_filtered_[vid]++; } else points_mapping_filtered_[i] = -1; } break; case MaxPointsFilterType::TRIM: for (int i = 0; i < npoints; i++) { auto new_id = voxel_indices.find(points_mapping_[i]); if (new_id != voxel_indices.end()) { int vid = new_id->second; if (voxel_npoints_filtered_[vid] >= max_points_) { points_mapping_filtered_[i] = -1; continue; } points_mapping_filtered_[i] = vid; voxel_npoints_filtered_[vid]++; } else points_mapping_filtered_[i] = -1; } break; case MaxPointsFilterType::FARTHEST_SAMPLING: throw py::value_error("Farthest Sampling not implemented!"); break; } Tensor masked = torch::where(points_mapping_filtered >= 0)[0]; Tensor feats_filtered = torch::index_select(feats, 0, masked); points_mapping_filtered = torch::index_select(points_mapping_filtered, 0, masked); return py::dict( "points"_a=feats_filtered, // FIXME: use consistent name for point features (`points` or `feats`) "points_mask"_a=masked, "points_mapping"_a=points_mapping_filtered, "voxel_npoints"_a=voxel_npoints_filtered, "coords"_a=coords_filtered ); }
17,882
6,441
// Copyright 2020 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <memory> #include <string> #include <utility> #include <base/bind.h> #include <base/check.h> #include <base/run_loop.h> #include <base/test/task_environment.h> #include <dbus/object_path.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include <mojo/core/embedder/embedder.h> #include <mojo/public/cpp/bindings/pending_receiver.h> #include <mojo/public/cpp/bindings/receiver.h> #include "diagnostics/common/system/bluetooth_client.h" #include "diagnostics/common/system/fake_bluetooth_client.h" #include "diagnostics/cros_healthd/events/bluetooth_events_impl.h" #include "diagnostics/cros_healthd/system/mock_context.h" #include "diagnostics/mojom/public/cros_healthd_events.mojom.h" namespace diagnostics { namespace { namespace mojo_ipc = ::chromeos::cros_healthd::mojom; using ::testing::Invoke; using ::testing::StrictMock; void PropertyChanged(const std::string& property_name) {} std::unique_ptr<BluetoothClient::AdapterProperties> CreateAdapterProperties() { auto properties = std::make_unique<BluetoothClient::AdapterProperties>( nullptr, base::Bind(&PropertyChanged)); properties->name.ReplaceValue("hci0"); properties->address.ReplaceValue("aa:bb:cc:dd:ee:ff"); properties->powered.ReplaceValue(true); return properties; } std::unique_ptr<BluetoothClient::DeviceProperties> CreateDeviceProperties() { auto properties = std::make_unique<BluetoothClient::DeviceProperties>( nullptr, base::Bind(&PropertyChanged)); properties->name.ReplaceValue("keyboard"); properties->address.ReplaceValue("70:88:6B:92:34:70"); properties->connected.ReplaceValue(true); properties->adapter.ReplaceValue(dbus::ObjectPath("/org/bluez/hci0")); return properties; } class MockCrosHealthdBluetoothObserver : public mojo_ipc::CrosHealthdBluetoothObserver { public: MockCrosHealthdBluetoothObserver( mojo::PendingReceiver<mojo_ipc::CrosHealthdBluetoothObserver> receiver) : receiver_{this /* impl */, std::move(receiver)} { DCHECK(receiver_.is_bound()); } MockCrosHealthdBluetoothObserver(const MockCrosHealthdBluetoothObserver&) = delete; MockCrosHealthdBluetoothObserver& operator=( const MockCrosHealthdBluetoothObserver&) = delete; MOCK_METHOD(void, OnAdapterAdded, (), (override)); MOCK_METHOD(void, OnAdapterRemoved, (), (override)); MOCK_METHOD(void, OnAdapterPropertyChanged, (), (override)); MOCK_METHOD(void, OnDeviceAdded, (), (override)); MOCK_METHOD(void, OnDeviceRemoved, (), (override)); MOCK_METHOD(void, OnDevicePropertyChanged, (), (override)); private: mojo::Receiver<mojo_ipc::CrosHealthdBluetoothObserver> receiver_; }; // Tests for the BluetoothEventsImpl class. class BluetoothEventsImplTest : public testing::Test { protected: BluetoothEventsImplTest() = default; BluetoothEventsImplTest(const BluetoothEventsImplTest&) = delete; BluetoothEventsImplTest& operator=(const BluetoothEventsImplTest&) = delete; void SetUp() override { // Before any observers have been added, we shouldn't have subscribed to // BluetoothClient. ASSERT_FALSE(fake_bluetooth_client()->HasObserver(&bluetooth_events_impl_)); mojo::PendingRemote<mojo_ipc::CrosHealthdBluetoothObserver> observer; mojo::PendingReceiver<mojo_ipc::CrosHealthdBluetoothObserver> observer_receiver(observer.InitWithNewPipeAndPassReceiver()); observer_ = std::make_unique<StrictMock<MockCrosHealthdBluetoothObserver>>( std::move(observer_receiver)); bluetooth_events_impl_.AddObserver(std::move(observer)); // Now that an observer has been added, we should have subscribed to // BluetoothClient. ASSERT_TRUE(fake_bluetooth_client()->HasObserver(&bluetooth_events_impl_)); } BluetoothEventsImpl* bluetooth_events_impl() { return &bluetooth_events_impl_; } FakeBluetoothClient* fake_bluetooth_client() { return mock_context_.fake_bluetooth_client(); } MockCrosHealthdBluetoothObserver* mock_observer() { return observer_.get(); } dbus::ObjectPath adapter_path() { return dbus::ObjectPath("/org/bluez/hci0"); } dbus::ObjectPath device_path() { return dbus::ObjectPath("/org/bluez/hci0/dev_70_88_6B_92_34_70"); } void DestroyMojoObserver() { observer_.reset(); // Make sure |bluetooth_events_impl_| gets a chance to observe the // connection error. task_environment_.RunUntilIdle(); } private: base::test::TaskEnvironment task_environment_; MockContext mock_context_; BluetoothEventsImpl bluetooth_events_impl_{&mock_context_}; std::unique_ptr<StrictMock<MockCrosHealthdBluetoothObserver>> observer_; }; // Test that we can receive an adapter added event. TEST_F(BluetoothEventsImplTest, ReceiveAdapterAddedEvent) { base::RunLoop run_loop; EXPECT_CALL(*mock_observer(), OnAdapterAdded()).WillOnce(Invoke([&]() { run_loop.Quit(); })); fake_bluetooth_client()->EmitAdapterAdded(adapter_path(), *CreateAdapterProperties()); run_loop.Run(); } // Test that we can receive an adapter removed event. TEST_F(BluetoothEventsImplTest, ReceiveAdapterRemovedEvent) { base::RunLoop run_loop; EXPECT_CALL(*mock_observer(), OnAdapterRemoved()).WillOnce(Invoke([&]() { run_loop.Quit(); })); fake_bluetooth_client()->EmitAdapterRemoved(adapter_path()); run_loop.Run(); } // Test that we can receive an adapter property changed event. TEST_F(BluetoothEventsImplTest, ReceiveAdapterPropertyChangedEvent) { base::RunLoop run_loop; EXPECT_CALL(*mock_observer(), OnAdapterPropertyChanged()) .WillOnce(Invoke([&]() { run_loop.Quit(); })); fake_bluetooth_client()->EmitAdapterPropertyChanged( adapter_path(), *CreateAdapterProperties()); run_loop.Run(); } // Test that we can receive a device added event. TEST_F(BluetoothEventsImplTest, ReceiveDeviceAddedEvent) { base::RunLoop run_loop; EXPECT_CALL(*mock_observer(), OnDeviceAdded()).WillOnce(Invoke([&]() { run_loop.Quit(); })); fake_bluetooth_client()->EmitDeviceAdded(device_path(), *CreateDeviceProperties()); run_loop.Run(); } // Test that we can receive a device removed event. TEST_F(BluetoothEventsImplTest, ReceiveDeviceRemovedEvent) { base::RunLoop run_loop; EXPECT_CALL(*mock_observer(), OnDeviceRemoved()).WillOnce(Invoke([&]() { run_loop.Quit(); })); fake_bluetooth_client()->EmitDeviceRemoved(device_path()); run_loop.Run(); } // Test that we can receive a device property changed event. TEST_F(BluetoothEventsImplTest, ReceiveDevicePropertyChangedEvent) { base::RunLoop run_loop; EXPECT_CALL(*mock_observer(), OnDevicePropertyChanged()) .WillOnce(Invoke([&]() { run_loop.Quit(); })); fake_bluetooth_client()->EmitDevicePropertyChanged(device_path(), *CreateDeviceProperties()); run_loop.Run(); } // Test that BluetoothEvents unsubscribes from BluetoothClient when // BluetoothEvents loses all of its Mojo observers. TEST_F(BluetoothEventsImplTest, UnsubscribeFromBluetoothClientWhenAllObserversLost) { DestroyMojoObserver(); // Emit an event so that BluetoothEventsImpl has a chance to check for any // remaining Mojo observers. fake_bluetooth_client()->EmitAdapterRemoved(adapter_path()); EXPECT_FALSE(fake_bluetooth_client()->HasObserver(bluetooth_events_impl())); } } // namespace } // namespace diagnostics
7,608
2,505
#include "title.h" #include "loginwindow.h" #include <QMessageBox> Title::Title(View *view, QWidget *parent) : QGraphicsScene(parent){ viewer = view; scroll = new QScrollBar; scroll = viewer->horizontalScrollBar(); background = new AnimatedGraphicsItem; background->setPixmap(QPixmap(":/images/background.png")); foreground = new QGraphicsPixmapItem(QPixmap(":/images/title.png")); //cursor = new QGraphicsPixmapItem(QPixmap(":/images/cursor.png")); logo = new QGraphicsPixmapItem(QPixmap(":/images/logo.png")); animation = new QPropertyAnimation(background, "pos"); animation->setLoopCount(-1); animation->setDuration(150000); animation->setStartValue(QPoint(-width,0)); animation->setEndValue(QPoint(0,0)); animation->start(); logo->setPos((width - logo->boundingRect().width()) / 2, height / 12); addItem(background); addItem(foreground); addItem(logo); this->setFocus(); this->setSceneRect(0,0,1280,720); view->sceneSet(this); //Push Button for login loginButton = new QPushButton(viewer); loginButton->setText("Login"); loginButton->setObjectName(QString("loginButton")); loginButton->setToolTip("Click to login"); loginButton->setGeometry(QRect(540, 500, 100, 32)); connect(loginButton, SIGNAL(clicked()), this, SLOT(login())); //Push Button for developer login developerButton = new QPushButton(viewer); developerButton->setText("Guest Login"); developerButton->setObjectName(QString("developerButton")); developerButton->setToolTip("Login as a guest"); developerButton->setGeometry(QRect(540, 535, 100, 32)); connect(developerButton, SIGNAL(clicked()), this, SLOT(developerLogin())); //Push Button to quit quitButton = new QPushButton(viewer); quitButton->setText("Quit"); quitButton->setObjectName(QString("quitButton")); quitButton->setToolTip("Quit program"); quitButton->setGeometry(QRect(642, 535, 100, 32)); connect(quitButton, SIGNAL(clicked()), this, SLOT(quitProgram())); //Push Button for new user newUserButton = new QPushButton(viewer); newUserButton->setText("New User"); newUserButton->setObjectName(QString("newUserButton")); newUserButton->setToolTip("Click to create a login"); newUserButton->setGeometry(QRect(642, 500, 100, 32)); connect(newUserButton, SIGNAL(clicked()), this, SLOT(newUser())); //Add line edit for username, set tooltip userLine = new QLineEdit(viewer); //userLine->setObjectName(QString("userLine")); userLine->setToolTip("Enter an email address"); userLine->setGeometry(QRect(540, 420, 200, 25)); //Add Label for username QFont font("MV Boli", 15, QFont::Bold); userName = new QLabel(viewer); userName->setFont(font); userName->setText("Username"); userName->setObjectName(QString("username")); userName->setGeometry(QRect(430, 420, 100, 25)); //Add line edit for password, set tooltip passLine = new QLineEdit(viewer); passLine->setEchoMode(QLineEdit::Password); passLine->setObjectName(QString("passLine")); passLine->setToolTip("Enter password"); passLine->setGeometry(QRect(540, 450, 200, 25)); //Add Label For password password = new QLabel(viewer); password->setFont(font); password->setText("Password"); password->setObjectName(QString("password")); password->setGeometry(QRect(430, 450, 100, 25)); //Add radio button and connect signal to slot,set tooltip radioButton = new QRadioButton(viewer); radioButton->setObjectName(QString("radioButton")); radioButton->setToolTip("Click to show password text"); radioButton->setGeometry(QRect(760, 450, 100, 25)); connect(radioButton, SIGNAL(toggled(bool)), this, SLOT(on_radioButton_toggled(bool))); //add radio button text radioText = new QLabel(viewer); radioText->setText("Show Password"); radioText->setToolTip("Click to show password text"); radioText->setGeometry(QRect(780, 450, 100, 25)); } bool Title::regExUserTest(){ bool accessGranted = false; usernameRegEx = new QRegularExpression("^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$"); usernamenameMatch = new QRegularExpressionMatch(usernameRegEx->match(userLine->text())); accessGranted = usernamenameMatch->hasMatch(); if(accessGranted){ return true; } else return false; } void Title::on_radioButton_toggled(bool checked) { if(checked){ passLine->setEchoMode(QLineEdit::Normal); } else{ passLine->setEchoMode(QLineEdit::Password); } } void Title::quitProgram(){ qApp->quit(); } void Title::login(){ //Connect to Database DataB::DBConnect(DBase); //Error for lack of input if(userLine->text().isEmpty()){ QMessageBox msgBox; msgBox.setText("You must enter a username. "); msgBox.setWindowTitle("Warning"); msgBox.exec(); return; } if(regExUserTest()== false){ QMessageBox msgBoxFail; msgBoxFail.setText("That is not a valid email address. "); msgBoxFail.setWindowTitle("Warning"); msgBoxFail.exec(); return; } if(passLine->text().isEmpty()){ QMessageBox msgBox2; msgBox2.setText("You must enter a password. "); msgBox2.setWindowTitle("Warning"); msgBox2.exec(); return; } //Gather Input Query uInput; uInput.uName=userLine->text(); uInput.pass=passLine->text(); qDebug() << uInput.uName; qDebug() << uInput.pass; //Try to check User if(DataB::cUsrPas(uInput,DBase.db)){ //Then it worked loginButton->close(); newUserButton->close(); passLine->close(); userLine->close(); userName->close(); password->close(); radioButton->close(); radioText->close(); developerButton->close(); quitButton->close(); scene = new MyScene(scroll,this); viewer->sceneSet(scene); } else{ //Then it didnt QMessageBox msgBox3; msgBox3.setText(" Combination of username and/or password incorrect. "); msgBox3.setWindowTitle("Warning"); msgBox3.exec(); return; } } void Title::newUser(){ loginWindow = new LoginWindow(); loginWindow->exec(); } void Title::developerLogin(){ loginButton->close(); newUserButton->close(); passLine->close(); userLine->close(); userName->close(); password->close(); radioButton->close(); radioText->close(); developerButton->close(); quitButton->close(); scene = new MyScene(scroll,this); viewer->sceneSet(scene); }
6,852
2,210
#include "stdafx.h" #include "WizardSheet.h" #include "CommandDlg.h" CPostProcessAdd::CPostProcessAdd( CWizardSheet* pTheSheet ) : m_pTheSheet( pTheSheet ) { m_strTitle.LoadString( IDS_TITLE_POSTPROCESS ); m_strSubTitle.LoadString( IDS_SUBTITLE_POSTPROCESS ); SetHeaderTitle( m_strTitle ); SetHeaderSubTitle( m_strSubTitle ); } LRESULT CPostProcessAdd::OnAddFile( WORD wNotifyCode, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& bHandled ) { CString strFilter; UIUtils::LoadOFNFilterFromRes( IDS_FILTER_POSTPROCESSFILES, /*r*/strFilter ); CFileDialog dlg( TRUE, NULL, NULL, OFN_ENABLESIZING | OFN_EXPLORER | OFN_NOREADONLYRETURN | OFN_FILEMUSTEXIST, strFilter, m_hWnd ); if ( dlg.DoModal() == IDCANCEL ) return 0; // File names must be unique as the path is not preserved // Check if there is already a file with the same name WCHAR wszNew[ MAX_PATH + 1 ]; ::wcscpy( wszNew, dlg.m_szFileName ); ::PathStripPath( wszNew ); for ( TStringList::const_iterator it = m_Files.begin(); it != m_Files.end(); ++it ) { WCHAR wszCurrent[ MAX_PATH + 1 ]; ::wcscpy( wszCurrent, it->c_str() ); ::PathStripPathW( wszCurrent ); if ( ::_wcsicmp( wszCurrent, wszNew ) == 0 ) { UIUtils::MessageBox( m_hWnd, IDS_E_PPFILENOTUNIQUE, IDS_APPTITLE, MB_OK | MB_ICONSTOP ); return 0 ; } } m_Files.push_back( std::wstring( dlg.m_szFileName ) ); ::wcscpy( wszNew, dlg.m_szFileName ); UIUtils::PathCompatCtrlWidth( GetDlgItem( IDC_FILES ), wszNew, ::GetSystemMetrics( SM_CXVSCROLL ) ); ListBox_AddString( GetDlgItem( IDC_FILES ), wszNew ); return 0; } LRESULT CPostProcessAdd::OnDelFile( WORD wNotifyCode, WORD /*wID*/, HWND hWndCtl, BOOL& bHandled ) { HWND hwndFiles = GetDlgItem( IDC_FILES ); int nCurSel = ListBox_GetCurSel( hwndFiles ); _ASSERT( nCurSel != LB_ERR ); ListBox_DeleteString( hwndFiles, nCurSel ); if ( ListBox_GetCount( hwndFiles ) > 0 ) { ListBox_SetCurSel( hwndFiles, max( nCurSel - 1, 0 ) ); } else { ::EnableWindow( hWndCtl, FALSE ); } return 0; } LRESULT CPostProcessAdd::LBSelChanged( WORD /*wNotifyCode*/, WORD wID, HWND hWndCtl, BOOL& /*bHandled*/ ) { // If selection is not changed - do nothing if ( ListBox_GetCurSel( hWndCtl ) == LB_ERR ) return 0; if ( wID == IDC_FILES ) { ::EnableWindow( GetDlgItem( IDC_DELFILE ), TRUE ); } else if ( wID == IDC_COMMANDS ) { ::EnableWindow( GetDlgItem( IDC_DELCMD ), TRUE ); ::EnableWindow( GetDlgItem( IDC_EDITCMD ), TRUE ); int iLastEl = ListBox_GetCount( hWndCtl ) - 1; int iCurSel = ListBox_GetCurSel( hWndCtl ); _ASSERT( iCurSel != LB_ERR ); // Enable / Disable the MoveUp and MoveDown Btns ::EnableWindow( GetDlgItem( IDC_MOVEUP ), iCurSel > 0 ); ::EnableWindow( GetDlgItem( IDC_MOVEDOWN ), iCurSel < iLastEl ); } return 0; } LRESULT CPostProcessAdd::OnAddCmd( WORD wNotifyCode, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& bHandled ) { CCommandDlg dlg; if ( dlg.DoModal() != IDOK ) return 0; CmdInfo Cmd; Cmd.bIgnoreErrors = dlg.m_bIgnoreErrors; Cmd.dwTimeout = dlg.m_dwTimeout; Cmd.strText = dlg.m_strText; m_Commands.push_back( Cmd ); UIUtils::TrimTextToCtrl( GetDlgItem( IDC_COMMANDS ), dlg.m_strText.GetBuffer( dlg.m_strText.GetLength() ), ::GetSystemMetrics( SM_CXVSCROLL ) ); dlg.m_strText.ReleaseBuffer(); BOOL bUnused = FALSE;; ListBox_InsertString( GetDlgItem( IDC_COMMANDS ), -1, dlg.m_strText ); LBSelChanged( LBN_SELCHANGE, IDC_COMMANDS, GetDlgItem( IDC_COMMANDS ), bUnused ); return 0; } LRESULT CPostProcessAdd::OnDelCmd( WORD wNotifyCode, WORD /*wID*/, HWND hWndCtl, BOOL& bHandled ) { HWND hwndCmds = GetDlgItem( IDC_COMMANDS ); int nCurSel = ListBox_GetCurSel( hwndCmds ); _ASSERT( nCurSel != LB_ERR ); ListBox_DeleteString( hwndCmds, nCurSel ); m_Commands.erase( m_Commands.begin() + nCurSel ); if ( ListBox_GetCount( hwndCmds ) > 0 ) { BOOL bUnused = FALSE; ListBox_SetCurSel( hwndCmds, max( nCurSel - 1, 0 ) ); LBSelChanged( LBN_SELCHANGE, IDC_COMMANDS, GetDlgItem( IDC_COMMANDS ), bUnused ); } else { ::EnableWindow( hWndCtl, FALSE ); ::EnableWindow( GetDlgItem( IDC_EDITCMD ), FALSE ); } return 0; } LRESULT CPostProcessAdd::OnEditCmd( WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/ ) { HWND hwndCmds = GetDlgItem( IDC_COMMANDS ); int iCmd = ListBox_GetCurSel( hwndCmds ); if ( LB_ERR == iCmd ) return 0; CCommandDlg dlg; dlg.m_bIgnoreErrors = m_Commands[ iCmd ].bIgnoreErrors; dlg.m_dwTimeout = m_Commands[ iCmd ].dwTimeout; dlg.m_strText = m_Commands[ iCmd ].strText; if ( dlg.DoModal() != IDOK ) return 0; m_Commands[ iCmd ].bIgnoreErrors = dlg.m_bIgnoreErrors; m_Commands[ iCmd ].dwTimeout = dlg.m_dwTimeout; m_Commands[ iCmd ].strText = dlg.m_strText; UIUtils::TrimTextToCtrl( hwndCmds, dlg.m_strText.GetBuffer( dlg.m_strText.GetLength() ), ::GetSystemMetrics( SM_CXVSCROLL ) ); dlg.m_strText.ReleaseBuffer(); ListBox_InsertString( hwndCmds, iCmd, dlg.m_strText ); ListBox_DeleteString( hwndCmds, iCmd + 1 ); ListBox_SetCurSel( hwndCmds, iCmd ); return 0; } LRESULT CPostProcessAdd::LBDoubleClick( WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/ ) { if ( wID != IDC_COMMANDS ) return 0; BOOL bUnused = FALSE; OnEditCmd( BN_CLICKED, IDC_EDITCMD, GetDlgItem( IDC_EDITCMD ), bUnused ); return 0; } LRESULT CPostProcessAdd::OnMoveUp( WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/ ) { HWND hwndCmds = GetDlgItem( IDC_COMMANDS ); int iSel = ListBox_GetCurSel( hwndCmds ); _ASSERT( ( iSel != LB_ERR ) && ( iSel > 0 ) ); LBSwapElements( hwndCmds, iSel, iSel - 1 ); ListBox_SetCurSel( hwndCmds, iSel - 1 ); BOOL bUnused = FALSE; LBSelChanged( LBN_SELCHANGE, IDC_COMMANDS, GetDlgItem( IDC_COMMANDS ), bUnused ); CmdInfo cmdTemp = m_Commands[ iSel ]; m_Commands[ iSel ] = m_Commands[ iSel - 1 ]; m_Commands[ iSel - 1 ] = cmdTemp; return 0; } LRESULT CPostProcessAdd::OnMoveDown( WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/ ) { HWND hwndCmds = GetDlgItem( IDC_COMMANDS ); int iSel = ListBox_GetCurSel( hwndCmds ); _ASSERT( ( iSel != LB_ERR ) && ( iSel < ( ListBox_GetCount( hwndCmds ) - 1 ) ) ); LBSwapElements( hwndCmds, iSel, iSel + 1 ); ListBox_SetCurSel( hwndCmds, iSel + 1 ); BOOL bUnused = FALSE; LBSelChanged( LBN_SELCHANGE, IDC_COMMANDS, GetDlgItem( IDC_COMMANDS ), bUnused ); CmdInfo cmdTemp = m_Commands[ iSel ]; m_Commands[ iSel ] = m_Commands[ iSel + 1 ]; m_Commands[ iSel + 1 ] = cmdTemp; return 0; } void CPostProcessAdd::LBSwapElements( HWND hwndLB, int iSrc, int iTarget ) { _ASSERT( hwndLB != NULL ); _ASSERT( iSrc != iTarget ); CString strSrc; CString strTarget; ListBox_GetText( hwndLB, iSrc, strSrc.GetBuffer( ListBox_GetTextLen( hwndLB, iSrc ) + 1 ) ); ListBox_GetText( hwndLB, iTarget, strTarget.GetBuffer( ListBox_GetTextLen( hwndLB, iTarget ) + 1 ) ); strSrc.ReleaseBuffer(); strTarget.ReleaseBuffer(); ListBox_InsertString( hwndLB, iTarget, strSrc ); ListBox_DeleteString( hwndLB, iTarget + 1 ); ListBox_InsertString( hwndLB, iSrc, strTarget ); ListBox_DeleteString( hwndLB, iSrc + 1 ); } int CPostProcessAdd::OnWizardNext() { int nRet = 0; // Goto next page int nMsgRes = 0; // Check if there are files, but no commands if ( m_Commands.empty() && !m_Files.empty() ) { nMsgRes = UIUtils::MessageBox( m_hWnd, IDS_W_NOCMDS, IDS_APPTITLE, MB_YESNO | MB_ICONWARNING ); // User wants to continue and ignore the files if ( IDYES == nMsgRes ) { m_Files.clear(); ListBox_ResetContent( GetDlgItem( IDC_FILES ) ); } else { nRet = -1; // Stay on this page } } return nRet; }
8,899
3,738
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ //////////////////////////////////////////////////////////////////////////////// // cookie_remap: ATS plugin to do (simple) cookie based remap rules // To use this plugin, configure a remap.config rule like // map http://foo.com http://bar.com @plugin=.../libexec/cookie_remap.so // @pparam=maps.reg #include "cookiejar.h" #include <ts/ts.h> #include <pcre.h> #include <ts/remap.h> #include <yaml-cpp/yaml.h> #include <string> #include <vector> #include <string_view> #include <cstddef> #include "hash.h" #undef FMT_SV #define FMT_SV(SV) static_cast<int>((SV).size()), (SV).data() using namespace std; #define MY_NAME "cookie_remap" const int OVECCOUNT = 30; // We support $1 - $9 only, and this needs to be 3x that class UrlComponents { public: UrlComponents(TSRemapRequestInfo *rri, TSHttpTxn txn) : _rri(rri), _txn(txn) {} std::string const & path(bool pre_remap) { if (_d[pre_remap].path_str.empty()) { auto urlh = _get_url(pre_remap); // based on RFC2396, matrix params are part of path segments so // we will just // append them to the path _d[pre_remap].path_str = _get_url_comp(urlh, TSUrlPathGet); auto matrix = _get_url_comp(urlh, TSUrlHttpParamsGet); if (!matrix.empty()) { _d[pre_remap].path_str.append(";", 1).append(matrix); } } return _d[pre_remap].path_str; } std::string_view query(bool pre_remap) { if (_d[pre_remap].query.empty()) { _d[pre_remap].query = _get_url_comp(_get_url(pre_remap), TSUrlHttpQueryGet); } return _d[pre_remap].query; } std::string_view from_path() { if (_from_path.empty()) { _UrlHandle urlh{_rri->requestBufp, _rri->mapFromUrl}; _from_path = _get_url_comp(urlh, TSUrlPathGet); } return _from_path; } std::string_view url(bool pre_remap) { if (_d[pre_remap].url.empty()) { auto urlh = _get_url(pre_remap); int length; auto data = TSUrlStringGet(urlh.bufp, urlh.urlp, &length); _d[pre_remap].url = std::string_view(data, length); } return _d[pre_remap].url; } // No copying/moving. // UrlComponents(UrlComponents const &) = delete; UrlComponents &operator=(UrlComponents const &) = delete; ~UrlComponents() { // Not calling TSHandleMLocRelease() for the URL TSMLoc pointers because it doesn't do anything. if (_d[0].url.data() != nullptr) { TSfree(const_cast<char *>(_d[0].url.data())); } if (_d[1].url.data() != nullptr) { TSfree(const_cast<char *>(_d[1].url.data())); } } private: TSRemapRequestInfo *_rri; TSHttpTxn _txn; struct _UrlHandle { TSMBuffer bufp = nullptr; TSMLoc urlp; }; // Buffer any data that's likely to be used more than once. struct _Data { _UrlHandle urlh; std::string path_str; std::string_view url; std::string_view query; }; // index 0 - remapped // index 1 - pre-remap // _Data _d[2]; std::string_view _from_path; _UrlHandle _get_url(bool pre_remap) { _UrlHandle h = _d[pre_remap].urlh; if (!h.bufp) { if (pre_remap) { if (TSHttpTxnPristineUrlGet(_txn, &h.bufp, &h.urlp) != TS_SUCCESS) { TSError("%s: Plugin is unable to get pristine url", MY_NAME); return _UrlHandle(); } } else { h.bufp = _rri->requestBufp; h.urlp = _rri->requestUrl; } _d[pre_remap].urlh = h; } return h; } static std::string_view _get_url_comp(_UrlHandle urlh, char const *(*comp_func)(TSMBuffer, TSMLoc, int *)) { int length; auto data = comp_func(urlh.bufp, urlh.urlp, &length); return std::string_view(data, length); } }; enum operation_type { UNKNOWN = -1, EXISTS = 1, NOTEXISTS, REGEXP, STRING, BUCKET }; enum target_type { COOKIE = 1, URI, // URI = PATH + QUERY PRE_REMAP_URI, UNKNOWN_TARGET }; /*************************************************************************************** Decimal to Hex converter This is a template function which returns a char* array filled with hex digits when passed to it a number(can work as a decimal to hex conversion)and will work for signed and unsigned: char, short, and integer(long) type parameters passed to it. Shortcomings:It won't work for decimal numbers because of presence of bitshifting in its algorithm. Arguments: * _num is the number to convert to hex * hdigits two-byte character array, will be populated with the hex number ***************************************************************************************/ template <class type> // template usage to allow multiple types of parameters void dec_to_hex(type _num, char *hdigits) { const char *hlookup = "0123456789ABCDEF"; // lookup table stores the hex digits into their // corresponding index. if (_num < 0) { _num *= -1; // and make _num positive to clear(zero) the sign bit } char mask = 0x000f; // mask will clear(zero) out all the bits except lowest 4 // which represent a single hex digit hdigits[1] = hlookup[mask & _num]; hdigits[0] = hlookup[mask & (_num >> 4)]; return; } void urlencode(std::string &str) { auto orig = str.size(); auto enc = orig; for (auto c : str) { if (!isalnum(c)) { enc += 2; } } if (enc == orig) { // No changes needed. return; } str.resize(enc); while (orig--) { if (!isalnum(str[orig])) { enc -= 3; dec_to_hex(str[orig], &(str[enc + 1])); str[enc] = '%'; } else { str[--enc] = str[orig]; } } } //---------------------------------------------------------------------------- class subop { public: subop() : cookie(""), operation(""), str_match(""), bucket("") { TSDebug(MY_NAME, "subop constructor called"); } ~subop() { TSDebug(MY_NAME, "subop destructor called"); if (regex) { pcre_free(regex); } if (regex_extra) { pcre_free(regex_extra); } } bool empty() const { return (cookie == "" && operation == "" && op_type == UNKNOWN); } void setCookieName(const std::string &s) { cookie = s; } const std::string & getCookieName() const { return cookie; } const std::string & getOperation() const { return operation; } operation_type getOpType() const { return op_type; } target_type getTargetType() const { return target; } void setOperation(const std::string &s) { operation = s; if (operation == "string") { op_type = STRING; } if (operation == "regex") { op_type = REGEXP; } if (operation == "exists") { op_type = EXISTS; } if (operation == "not exists") { op_type = NOTEXISTS; } if (operation == "bucket") { op_type = BUCKET; } } void setTarget(const std::string &s) { if (s == "uri") { target = URI; } else if (s == "puri") { target = PRE_REMAP_URI; } else { target = COOKIE; } } void setStringMatch(const std::string &s) { op_type = STRING; str_match = s; } const std::string & getStringMatch() const { return str_match; } void setBucket(const std::string &s) { int start_pos = s.find('/'); op_type = BUCKET; bucket = s; how_many = atoi(bucket.substr(0, start_pos).c_str()); out_of = atoi(bucket.substr(start_pos + 1).c_str()); } int bucketGetTaking() const { return how_many; } int bucketOutOf() const { return out_of; } bool setRegexMatch(const std::string &s) { const char *error_comp = nullptr; const char *error_study = nullptr; int erroffset; op_type = REGEXP; regex_string = s; regex = pcre_compile(regex_string.c_str(), 0, &error_comp, &erroffset, nullptr); if (regex == nullptr) { return false; } regex_extra = pcre_study(regex, 0, &error_study); if ((regex_extra == nullptr) && (error_study != nullptr)) { return false; } if (pcre_fullinfo(regex, regex_extra, PCRE_INFO_CAPTURECOUNT, &regex_ccount) != 0) { return false; } return true; } const std::string & getRegexString() const { return regex_string; } int getRegexCcount() const { return regex_ccount; } int regexMatch(const char *str, int len, int ovector[]) const { return pcre_exec(regex, // the compiled pattern regex_extra, // Extra data from study (maybe) str, // the subject std::string len, // the length of the subject 0, // start at offset 0 in the subject 0, // default options ovector, // output vector for substring information OVECCOUNT); // number of elements in the output vector }; void printSubOp() const { TSDebug(MY_NAME, "\t+++subop+++"); TSDebug(MY_NAME, "\t\tcookie: %s", cookie.c_str()); TSDebug(MY_NAME, "\t\toperation: %s", operation.c_str()); if (str_match.size() > 0) { TSDebug(MY_NAME, "\t\tmatching: %s", str_match.c_str()); } if (regex) { TSDebug(MY_NAME, "\t\tregex: %s", regex_string.c_str()); } if (bucket.size() > 0) { TSDebug(MY_NAME, "\t\tbucket: %s", bucket.c_str()); TSDebug(MY_NAME, "\t\ttaking: %d", how_many); TSDebug(MY_NAME, "\t\tout of: %d", out_of); } } private: std::string cookie; std::string operation; enum operation_type op_type = UNKNOWN; enum target_type target = UNKNOWN_TARGET; std::string str_match; pcre *regex = nullptr; pcre_extra *regex_extra = nullptr; std::string regex_string; int regex_ccount = 0; std::string bucket; unsigned int how_many = 0; unsigned int out_of = 0; }; using SubOpQueue = std::vector<const subop *>; //---------------------------------------------------------------------------- class op { public: op() { TSDebug(MY_NAME, "op constructor called"); } ~op() { TSDebug(MY_NAME, "op destructor called"); for (auto &subop : subops) { delete subop; } } void addSubOp(const subop *s) { subops.push_back(s); } void setSendTo(const std::string &s) { sendto = s; } const std::string & getSendTo() const { return sendto; } void setElseSendTo(const std::string &s) { else_sendto = s; } void setStatus(const std::string &s) { if (else_sendto.size() > 0) { else_status = static_cast<TSHttpStatus>(atoi(s.c_str())); } else { status = static_cast<TSHttpStatus>(atoi(s.c_str())); } } void setElseStatus(const std::string &s) { else_status = static_cast<TSHttpStatus>(atoi(s.c_str())); } void printOp() const { TSDebug(MY_NAME, "++++operation++++"); TSDebug(MY_NAME, "sending to: %s", sendto.c_str()); TSDebug(MY_NAME, "if these operations match: "); for (auto subop : subops) { subop->printSubOp(); } if (else_sendto.size() > 0) { TSDebug(MY_NAME, "else: %s", else_sendto.c_str()); } } bool process(CookieJar &jar, std::string &dest, TSHttpStatus &retstat, TSRemapRequestInfo *rri, UrlComponents &req_url) const { if (sendto == "") { return false; // guessing every operation must have a // sendto url??? } int retval = 1; bool cookie_found = false; std::string c; std::string cookie_data; std::string object_name; // name of the thing being processed, // cookie, or // request url TSDebug(MY_NAME, "starting to process a new operation"); for (auto subop : subops) { // subop* s = *it; int subop_type = subop->getOpType(); target_type target = subop->getTargetType(); c = subop->getCookieName(); if (c.length()) { TSDebug(MY_NAME, "processing cookie: %s", c.c_str()); size_t period_pos = c.find_first_of('.'); if (period_pos == std::string::npos) { // not a sublevel // cookie name TSDebug(MY_NAME, "processing non-sublevel cookie"); cookie_found = jar.get_full(c, cookie_data); TSDebug(MY_NAME, "full cookie: %s", cookie_data.c_str()); object_name = c; } else { // is in the format FOO.BAR std::string cookie_main = c.substr(0, period_pos); std::string cookie_subkey = c.substr(period_pos + 1); TSDebug(MY_NAME, "processing sublevel cookie"); TSDebug(MY_NAME, "c key: %s", cookie_main.c_str()); TSDebug(MY_NAME, "c subkey: %s", cookie_subkey.c_str()); cookie_found = jar.get_part(cookie_main, cookie_subkey, cookie_data); object_name = cookie_main + " . " + cookie_subkey; } // invariant: cookie name is in object_name and // cookie data (if any) is // in cookie_data if (cookie_found == false) { // cookie name or sub-key not found // inside cookies if (subop_type == NOTEXISTS) { TSDebug(MY_NAME, "cookie %s was not " "found (and we wanted " "that)", object_name.c_str()); continue; // we can short // circuit more // testing } TSDebug(MY_NAME, "cookie %s was not found", object_name.c_str()); retval &= 0; break; } else { // cookie exists if (subop_type == NOTEXISTS) { // we found the cookie // but are asking // for non existence TSDebug(MY_NAME, "cookie %s was found, " "but operation " "requires " "non-existence", object_name.c_str()); retval &= 0; break; } if (subop_type == EXISTS) { TSDebug(MY_NAME, "cookie %s was found", object_name.c_str()); // got what // we were // looking // for continue; // we can short // circuit more // testing } } // handled EXISTS / NOTEXISTS subops TSDebug(MY_NAME, "processing cookie data: \"%s\"", cookie_data.c_str()); } else if (target != PRE_REMAP_URI) { target = URI; } // INVARIANT: we now have the data from the cookie (if // any) inside // cookie_data and we are here because we need // to continue processing this suboperation in some way if (!rri) { // too dangerous to continue without the // rri; hopefully that // never happens TSDebug(MY_NAME, "request info structure is " "empty; can't continue " "processing this subop"); retval &= 0; break; } // If the user has specified a cookie in his // suboperation, use the cookie // data for matching; // otherwise, use the request uri (path + query) std::string request_uri; // only set the value if we // need it; we might // match the cookie data instead bool use_url = (target == URI) || (target == PRE_REMAP_URI); const std::string &string_to_match(use_url ? request_uri : cookie_data); if (use_url) { request_uri = req_url.path(target == PRE_REMAP_URI); TSDebug(MY_NAME, "process req_url.path = %s", request_uri.c_str()); if (request_uri.length() && request_uri[0] != '/') { request_uri.insert(0, 1, '/'); } auto query = req_url.query(target == PRE_REMAP_URI); if (query.size() > 0) { request_uri += '?'; request_uri += query; } object_name = "request uri"; } // invariant: we've decided at this point what string // we'll match, if we // do matching // OPERATION::string matching if (subop_type == STRING) { if (string_to_match == subop->getStringMatch()) { TSDebug(MY_NAME, "string match succeeded"); continue; } else { TSDebug(MY_NAME, "string match failed"); retval &= 0; break; } } // OPERATION::regex matching if (subop_type == REGEXP) { int ovector[OVECCOUNT]; int ret = subop->regexMatch(string_to_match.c_str(), string_to_match.length(), ovector); if (ret >= 0) { std::string::size_type pos = sendto.find('$'); std::string::size_type ppos = 0; dest.erase(); // we only reset dest if // there is a successful // regex // match dest.reserve(sendto.size() * 2); // Wild guess at this // time ... is // sucks we can't precalculate this // like regex_remap. TSDebug(MY_NAME, "found %d matches", ret); TSDebug(MY_NAME, "successful regex " "match of: %s with %s " "rewriting string: %s", string_to_match.c_str(), subop->getRegexString().c_str(), sendto.c_str()); // replace the $(1-9) in the sendto url // as necessary const size_t LAST_IDX_TO_SEARCH(sendto.length() - 2); // otherwise the below loop can // access "sendto" out of range while (pos <= LAST_IDX_TO_SEARCH) { if (isdigit(sendto[pos + 1])) { int ix = sendto[pos + 1] - '0'; if (ix <= subop->getRegexCcount()) { // Just skip an illegal regex group dest += sendto.substr(ppos, pos - ppos); dest += string_to_match.substr(ovector[ix * 2], ovector[ix * 2 + 1] - ovector[ix * 2]); ppos = pos + 2; } else { TSDebug(MY_NAME, "bad " "rewriting " "string, " "for group " "%d: %s", ix, sendto.c_str()); } } pos = sendto.find('$', pos + 1); } dest += sendto.substr(ppos); continue; // next subop, please } else { TSDebug(MY_NAME, "could not match " "regular expression " "%s to %s", subop->getRegexString().c_str(), string_to_match.c_str()); retval &= 0; break; } } // OPERATION::bucket ranges if (subop_type == BUCKET) { unsigned int taking = subop->bucketGetTaking(); unsigned int out_of = subop->bucketOutOf(); uint32_t hash; if (taking == 0 || out_of == 0) { TSDebug(MY_NAME, "taking %d out of %d " "makes no sense?!", taking, out_of); retval &= 0; break; } hash = hash_fnv32_buckets(cookie_data.c_str(), cookie_data.size(), out_of); TSDebug(MY_NAME, "we hashed this to bucket: %u " "taking: %u out of: %u", hash, taking, out_of); if (hash < taking) { TSDebug(MY_NAME, "we hashed in the range, yay!"); continue; // we hashed in the range } else { TSDebug(MY_NAME, "we didn't hash in the " "range requested, so " "sad"); retval &= 0; break; } } } if (retval == 1) { if (dest.size() == 0) { // Unless already set by one of // the operators (e.g. regex) dest = sendto; } if (status > 0) { retstat = status; } return true; } else if (else_sendto.size() > 0 && retval == 0) { dest = else_sendto; if (else_status > 0) { retstat = else_status; } return true; } else { dest = ""; return false; } } private: SubOpQueue subops{}; std::string sendto{""}; std::string else_sendto{""}; TSHttpStatus status = TS_HTTP_STATUS_NONE; TSHttpStatus else_status = TS_HTTP_STATUS_NONE; }; using StringPair = std::pair<std::string, std::string>; using OpMap = std::vector<StringPair>; //---------------------------------------------------------------------------- static bool build_op(op &o, OpMap const &q) { subop *sub = new subop(); // loop through the array of key->value pairs for (auto const &pr : q) { std::string const &key = pr.first; std::string const &val = pr.second; TSDebug(MY_NAME, "build_op: key=%s val=%s", key.c_str(), val.c_str()); if (key == "cookie") { if (!sub->empty()) { TSDebug(MY_NAME, "ERROR: you need to define a connector"); goto error; } sub->setCookieName(val); } if (key == "sendto" || key == "url") { o.setSendTo(val); } if (key == "else") { o.setElseSendTo(val); } if (key == "status") { o.setStatus(val); } if (key == "operation") { sub->setOperation(val); } if (key == "target") { sub->setTarget(val); } if (key == "match") { sub->setStringMatch(val); } if (key == "regex") { bool ret = sub->setRegexMatch(val); if (!ret) { goto error; } } if (key == "bucket" || key == "hash") { sub->setBucket(val); } if (key == "connector") { o.addSubOp(sub); sub = new subop(); } } o.addSubOp(sub); return true; error: TSDebug(MY_NAME, "error building operation"); return false; } using OpsQueue = std::vector<const op *>; //---------------------------------------------------------------------------- // init TSReturnCode TSRemapInit(TSRemapInterface *api_info, char *errbuf, int errbuf_size) { return TS_SUCCESS; } //---------------------------------------------------------------------------- // initialization of structures from config parameters TSReturnCode TSRemapNewInstance(int argc, char *argv[], void **ih, char *errbuf, int errbuf_size) { if (argc != 3) { TSError("arguments not equal to 3: %d", argc); TSDebug(MY_NAME, "arguments not equal to 3: %d", argc); return TS_ERROR; } std::string filename(argv[2]); try { YAML::Node config = YAML::LoadFile(filename); std::unique_ptr<OpsQueue> ops(new OpsQueue); OpMap op_data; for (YAML::const_iterator it = config.begin(); it != config.end(); ++it) { const string &name = it->first.as<std::string>(); YAML::NodeType::value type = it->second.Type(); if (name != "op" || type != YAML::NodeType::Map) { const string reason = "Top level nodes must be named op and be of type map"; TSError("Invalid YAML Configuration format for cookie_remap: %s, reason: %s", filename.c_str(), reason.c_str()); return TS_ERROR; } for (YAML::const_iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) { const YAML::Node first = it2->first; const YAML::Node second = it2->second; if (second.IsScalar() == false) { const string reason = "All op nodes must be of type scalar"; TSError("Invalid YAML Configuration format for cookie_remap: %s, reason: %s", filename.c_str(), reason.c_str()); return TS_ERROR; } const string &key = first.as<std::string>(); const string &value = second.as<std::string>(); op_data.emplace_back(key, value); } if (op_data.size()) { op *o = new op(); if (!build_op(*o, op_data)) { delete o; TSError("building operation, check configuration file: %s", filename.c_str()); return TS_ERROR; } else { ops->push_back(o); } o->printOp(); op_data.clear(); } } TSDebug(MY_NAME, "# of ops: %d", static_cast<int>(ops->size())); *ih = static_cast<void *>(ops.release()); } catch (const YAML::Exception &e) { TSError("YAML::Exception %s when parsing YAML config file %s for cookie_remap", e.what(), filename.c_str()); return TS_ERROR; } return TS_SUCCESS; } namespace { std::string unmatched_path(UrlComponents &req_url, bool pre_remap) { std::string path = req_url.path(pre_remap); std::string_view from_path = req_url.from_path(); std::size_t pos = path.find(from_path); if (pos != std::string::npos) { path.erase(pos, from_path.size()); } TSDebug(MY_NAME, "from_path: %*s", FMT_SV(from_path)); TSDebug(MY_NAME, "%s: %s", pre_remap ? "unmatched_ppath" : "unmatched_path", path.c_str()); return path; } int const sub_req_url_id = 0; int const sub_req_purl_id = -1; int const sub_path_id = -2; int const sub_ppath_id = -3; int const sub_unmatched_path_id = -4; int const sub_unmatched_ppath_id = -5; int const sub_url_encode_id = -6; struct CompNext { std::string_view const comp; int const *const next; CompNext(std::string_view p, int const *n) : comp(p), next(n) {} }; struct SubUnmatched { SubUnmatched() = default; // Work-around for Intel compiler problem. int count = 2; CompNext o1{"ath", &sub_unmatched_path_id}; CompNext o2{"path", &sub_unmatched_ppath_id}; }; SubUnmatched const sub_unmatched; struct SubP { SubP() = default; // Work-around for Intel compiler problem. int count = 2; CompNext o1{"ath", &sub_path_id}; CompNext o2{"path", &sub_ppath_id}; }; SubP const sub_p; struct SubCrReq { SubCrReq() = default; // Work-around for Intel compiler problem. int count = 2; CompNext o1{"url", &sub_req_url_id}; CompNext o2{"purl", &sub_req_purl_id}; }; SubCrReq const sub_cr_req; struct SubCr { SubCr() = default; // Work-around for Intel compiler problem. int count = 2; CompNext o1{"req_", &sub_cr_req.count}; CompNext o2{"urlencode(", &sub_url_encode_id}; }; SubCr const sub_cr; struct Sub { Sub() = default; // Work-around for Intel compiler problem. int count = 3; CompNext o1{"cr_", &sub_cr.count}; CompNext o2{"p", &sub_p.count}; CompNext o3{"unmatched_p", &sub_unmatched.count}; }; Sub const sub; int sub_lookup(char const *targ, int targ_len) { int count = sub.count; auto opt = &sub.o1; for (;;) { while ((targ_len < static_cast<int>(opt->comp.size())) || (std::string_view(targ, opt->comp.size()) != opt->comp)) { if (!--count) { return 1; // Failed lookup, return some positive number. } ++opt; } count = *opt->next; if (count <= 0) { break; } targ += opt->comp.size(); targ_len -= opt->comp.size(); opt = reinterpret_cast<CompNext const *>(reinterpret_cast<char const *>(opt->next) + offsetof(decltype(sub), o1)); } return count; } } // end anonymous namespace //---------------------------------------------------------------------------- // called whenever we need to perform substitutions on a string; used to replace // things like // $path, $ppath, $unmatched_path, $unmatched_ppath, $cr_req_url, $cr_req_purl, and $cr_url_encode void cr_substitutions(std::string &obj, UrlComponents &req_url) { { auto path = req_url.path(false); TSDebug(MY_NAME, "x req_url.path: %*s %d", FMT_SV(path), static_cast<int>(path.size())); auto url = req_url.url(false); TSDebug(MY_NAME, "x req_url.url: %*s %d", FMT_SV(url), static_cast<int>(url.size())); } auto npos = std::string::npos; std::string tmp; std::size_t pos = 0; for (;;) { pos = obj.find('$', pos); if (npos == pos) { break; } std::string_view variable, value; switch (sub_lookup(obj.data() + pos + 1, static_cast<int>(obj.size()) - pos - 1)) { case sub_req_url_id: { variable = "$cr_req_url"; value = req_url.url(false); } break; case sub_req_purl_id: { variable = "$cr_req_purl"; value = req_url.url(true); } break; case sub_path_id: { variable = "$path"; value = req_url.path(false); } break; case sub_ppath_id: { variable = "$ppath"; value = req_url.path(true); } break; case sub_unmatched_path_id: { variable = "$unmatched_path"; tmp = unmatched_path(req_url, false); value = tmp; } break; case sub_unmatched_ppath_id: { variable = "$unmatched_ppath"; tmp = unmatched_path(req_url, true); value = tmp; } break; case sub_url_encode_id: { std::size_t bpos = pos + sizeof("cr_urlencode(") - 1; std::size_t epos = obj.find(')', bpos); if (npos == epos) { variable = "$"; value = variable; } else { variable = std::string_view(obj.data() + pos, epos + 1 - pos); tmp = obj.substr(bpos, epos - bpos); cr_substitutions(tmp, req_url); urlencode(tmp); value = tmp; } } break; default: { variable = "$"; value = variable; } break; } // end switch TSDebug(MY_NAME, "%*s => %*s", FMT_SV(variable), FMT_SV(value)); obj.replace(pos, variable.size(), value); pos += value.size(); } // end for (;;) } //---------------------------------------------------------------------------- // called on each request // returns 0 on error or failure to match rules, 1 on a match TSRemapStatus TSRemapDoRemap(void *ih, TSHttpTxn txnp, TSRemapRequestInfo *rri) { OpsQueue *ops = static_cast<OpsQueue *>(ih); TSHttpStatus status = TS_HTTP_STATUS_NONE; UrlComponents req_url{rri, txnp}; if (ops == (OpsQueue *)nullptr) { TSError("serious error with encountered while attempting to " "cookie_remap"); TSDebug(MY_NAME, "serious error with encountered while attempting to remap"); return TSREMAP_NO_REMAP; } // get any query params..we will append that to the answer (possibly) std::string client_req_query_params; auto query = req_url.query(false); if (!query.empty()) { client_req_query_params = "?"; client_req_query_params += query; } TSDebug(MY_NAME, "Query Parameters: %s", client_req_query_params.c_str()); std::string rewrite_to; char cookie_str[] = "Cookie"; TSMLoc field = TSMimeHdrFieldFind(rri->requestBufp, rri->requestHdrp, cookie_str, sizeof(cookie_str) - 1); // cookie header doesn't exist if (field == nullptr) { TSDebug(MY_NAME, "no cookie header"); // return TSREMAP_NO_REMAP; } const char *cookie = nullptr; int cookie_len = 0; if (field != nullptr) { cookie = TSMimeHdrFieldValueStringGet(rri->requestBufp, rri->requestHdrp, field, -1, &cookie_len); } std::string temp_cookie(cookie, cookie_len); CookieJar jar; jar.create(temp_cookie); for (auto &op : *ops) { TSDebug(MY_NAME, ">>> processing new operation"); if (op->process(jar, rewrite_to, status, rri, req_url)) { cr_substitutions(rewrite_to, req_url); size_t pos = 7; // 7 because we want to ignore the // in // http:// :) size_t tmp_pos = rewrite_to.find('?', pos); // we don't want to alter the query string do { pos = rewrite_to.find("//", pos); if (pos < tmp_pos) { rewrite_to.erase(pos, 1); // remove one '/' } } while (pos <= rewrite_to.length() && pos < tmp_pos); // Add Query Parameters if not already present if (!client_req_query_params.empty() && rewrite_to.find('?') == std::string::npos) { rewrite_to.append(client_req_query_params); } TSDebug(MY_NAME, "rewriting to: %s", rewrite_to.c_str()); // Maybe set the return status if (status > TS_HTTP_STATUS_NONE) { TSDebug(MY_NAME, "Setting return status to %d", status); TSHttpTxnStatusSet(txnp, status); if ((status == TS_HTTP_STATUS_MOVED_PERMANENTLY) || (status == TS_HTTP_STATUS_MOVED_TEMPORARILY)) { if (rewrite_to.size() > 8192) { TSError("Redirect in target " "URL too long"); TSHttpTxnStatusSet(txnp, TS_HTTP_STATUS_REQUEST_URI_TOO_LONG); } else { const char *start = rewrite_to.c_str(); int dest_len = rewrite_to.size(); if (TS_PARSE_ERROR == TSUrlParse(rri->requestBufp, rri->requestUrl, &start, start + dest_len)) { TSHttpTxnStatusSet(txnp, TS_HTTP_STATUS_INTERNAL_SERVER_ERROR); TSError("can't parse " "substituted " "URL string"); } else { rri->redirect = 1; } } } if (field != nullptr) { TSHandleMLocRelease(rri->requestBufp, rri->requestHdrp, field); } if (rri->redirect) { return TSREMAP_DID_REMAP; } else { return TSREMAP_NO_REMAP; } } const char *start = rewrite_to.c_str(); // set the new url if (TSUrlParse(rri->requestBufp, rri->requestUrl, &start, start + rewrite_to.length()) == TS_PARSE_ERROR) { TSHttpTxnStatusSet(txnp, TS_HTTP_STATUS_INTERNAL_SERVER_ERROR); TSError("can't parse substituted URL string"); goto error; } else { if (field != nullptr) { TSHandleMLocRelease(rri->requestBufp, rri->requestHdrp, field); } return TSREMAP_DID_REMAP; } // Cleanup error: if (field != nullptr) { TSHandleMLocRelease(rri->requestBufp, rri->requestHdrp, field); } return TSREMAP_NO_REMAP; } } TSDebug(MY_NAME, "could not execute ANY of the cookie remap operations... " "falling back to default in remap.config"); if (field != nullptr) { TSHandleMLocRelease(rri->requestBufp, rri->requestHdrp, field); } return TSREMAP_NO_REMAP; } //---------------------------------------------------------------------------- // unload void TSRemapDeleteInstance(void *ih) { OpsQueue *ops = static_cast<OpsQueue *>(ih); TSDebug(MY_NAME, "deleting loaded operations"); for (auto &op : *ops) { delete op; } delete ops; return; }
35,929
12,164
#ifndef FAST_WFC_OVERLAPPING_WFC_HPP_ #define FAST_WFC_OVERLAPPING_WFC_HPP_ #include <unordered_map> #include <vector> #include "array2D.hpp" #include "wfc.hpp" /** * Options needed to use the overlapping wfc. */ struct OverlappingWFCOptions { bool periodic_input; // True if the input is toric. bool periodic_output; // True if the output is toric. unsigned out_height; // The height of the output in pixels. unsigned out_width; // The width of the output in pixels. unsigned symmetry; // The number of symmetries (the order is defined in wfc). bool ground; // True if the ground needs to be set (see init_ground). unsigned pattern_size; // The width and height in pixel of the patterns. /** * Get the wave height given these options. */ unsigned get_wave_height() const noexcept { return periodic_output ? out_height : out_height - pattern_size + 1; } /** * Get the wave width given these options. */ unsigned get_wave_width() const noexcept { return periodic_output ? out_width : out_width - pattern_size + 1; } }; /** * Class generating a new image with the overlapping WFC algorithm. */ template <typename T> class OverlappingWFC { private: /** * The input image. T is usually a color. */ Array2D<T> input; /** * Options needed by the algorithm. */ OverlappingWFCOptions options; /** * The array of the different patterns extracted from the input. */ std::vector<Array2D<T>> patterns; /** * The underlying generic WFC algorithm. */ WFC wfc; /** * Constructor initializing the wfc. * This constructor is called by the other constructors. * This is necessary in order to initialize wfc only once. */ OverlappingWFC(const Array2D<T>& input, const OverlappingWFCOptions& options, const int& seed, const std::pair<std::vector<Array2D<T>>, std::vector<double>>& patterns, const std::vector<std::array<std::vector<unsigned>, 4>>& propagator) noexcept : input(input) , options(options) , patterns(patterns.first) , wfc(options.periodic_output, seed, patterns.second, propagator, options.get_wave_height(), options.get_wave_width()) { // If necessary, the ground is set. if (options.ground) { init_ground(wfc, input, patterns.first, options); } } /** * Constructor used only to call the other constructor with more computed * parameters. */ OverlappingWFC(const Array2D<T>& input, const OverlappingWFCOptions& options, const int& seed, const std::pair<std::vector<Array2D<T>>, std::vector<double>>& patterns) noexcept : OverlappingWFC(input, options, seed, patterns, generate_compatible(patterns.first)) { } /** * Init the ground of the output image. * The lowest middle pattern is used as a floor (and ceiling when the input is * toric) and is placed at the lowest possible pattern position in the output * image, on all its width. The pattern cannot be used at any other place in * the output image. */ static void init_ground(WFC& wfc, const Array2D<T>& input, const std::vector<Array2D<T>>& patterns, const OverlappingWFCOptions& options) noexcept { unsigned ground_pattern_id = get_ground_pattern_id(input, patterns, options); // Place the pattern in the ground. for (unsigned j = 0; j < options.get_wave_width(); j++) { for (unsigned p = 0; p < patterns.size(); p++) { if (ground_pattern_id != p) { wfc.remove_wave_pattern(options.get_wave_height() - 1, j, p); } } } // Remove the pattern from the other positions. for (unsigned i = 0; i < options.get_wave_height() - 1; i++) { for (unsigned j = 0; j < options.get_wave_width(); j++) { wfc.remove_wave_pattern(i, j, ground_pattern_id); } } // Propagate the information with wfc. wfc.propagate(); } /** * Return the id of the lowest middle pattern. */ static unsigned get_ground_pattern_id(const Array2D<T>& input, const std::vector<Array2D<T>>& patterns, const OverlappingWFCOptions& options) noexcept { // Get the pattern. Array2D<T> ground_pattern = input.get_sub_array( input.height - 1, input.width / 2, options.pattern_size, options.pattern_size); // Retrieve the id of the pattern. for (unsigned i = 0; i < patterns.size(); i++) { if (ground_pattern == patterns[i]) { return i; } } // The pattern exists. assert(false); return 0; } /** * Return the list of patterns, as well as their probabilities of apparition. */ static std::pair<std::vector<Array2D<T>>, std::vector<double>> get_patterns( const Array2D<T>& input, const OverlappingWFCOptions& options) noexcept { std::unordered_map<Array2D<T>, unsigned> patterns_id; std::vector<Array2D<T>> patterns; // The number of time a pattern is seen in the input image. std::vector<double> patterns_weight; std::vector<Array2D<T>> symmetries( 8, Array2D<T>(options.pattern_size, options.pattern_size)); unsigned max_i = options.periodic_input ? input.height : input.height - options.pattern_size + 1; unsigned max_j = options.periodic_input ? input.width : input.width - options.pattern_size + 1; for (unsigned i = 0; i < max_i; i++) { for (unsigned j = 0; j < max_j; j++) { // Compute the symmetries of every pattern in the image. symmetries[0].data = input.get_sub_array(i, j, options.pattern_size, options.pattern_size).data; symmetries[1].data = symmetries[0].reflected().data; symmetries[2].data = symmetries[0].rotated().data; symmetries[3].data = symmetries[2].reflected().data; symmetries[4].data = symmetries[2].rotated().data; symmetries[5].data = symmetries[4].reflected().data; symmetries[6].data = symmetries[4].rotated().data; symmetries[7].data = symmetries[6].reflected().data; // The number of symmetries in the option class define which symetries // will be used. for (unsigned k = 0; k < options.symmetry; k++) { auto res = patterns_id.insert(std::make_pair(symmetries[k], patterns.size())); // If the pattern already exist, we just have to increase its number // of appearance. if (!res.second) { patterns_weight[res.first->second] += 1; } else { patterns.push_back(symmetries[k]); patterns_weight.push_back(1); } } } } return { patterns, patterns_weight }; } /** * Return true if the pattern1 is compatible with pattern2 * when pattern2 is at a distance (dy,dx) from pattern1. */ static bool agrees( const Array2D<T>& pattern1, const Array2D<T>& pattern2, int dy, int dx) noexcept { unsigned xmin = dx < 0 ? 0 : dx; unsigned xmax = dx < 0 ? dx + pattern2.width : pattern1.width; unsigned ymin = dy < 0 ? 0 : dy; unsigned ymax = dy < 0 ? dy + pattern2.height : pattern1.width; // Iterate on every pixel contained in the intersection of the two pattern. for (unsigned y = ymin; y < ymax; y++) { for (unsigned x = xmin; x < xmax; x++) { // Check if the color is the same in the two patterns in that pixel. if (pattern1.get(y, x) != pattern2.get(y - dy, x - dx)) { return false; } } } return true; } /** * Precompute the function agrees(pattern1, pattern2, dy, dx). * If agrees(pattern1, pattern2, dy, dx), then compatible[pattern1][direction] * contains pattern2, where direction is the direction defined by (dy, dx) * (see direction.hpp). */ static std::vector<std::array<std::vector<unsigned>, 4>> generate_compatible( const std::vector<Array2D<T>>& patterns) noexcept { std::vector<std::array<std::vector<unsigned>, 4>> compatible = std::vector<std::array<std::vector<unsigned>, 4>>(patterns.size()); // Iterate on every dy, dx, pattern1 and pattern2 for (unsigned pattern1 = 0; pattern1 < patterns.size(); pattern1++) { for (unsigned direction = 0; direction < 4; direction++) { for (unsigned pattern2 = 0; pattern2 < patterns.size(); pattern2++) { if (agrees(patterns[pattern1], patterns[pattern2], directions_y[direction], directions_x[direction])) { compatible[pattern1][direction].push_back(pattern2); } } } } return compatible; } /** * Transform a 2D array containing the patterns id to a 2D array containing * the pixels. */ Array2D<T> to_image(const Array2D<unsigned>& output_patterns) const noexcept { Array2D<T> output = Array2D<T>(options.out_height, options.out_width); if (options.periodic_output) { for (unsigned y = 0; y < options.get_wave_height(); y++) { for (unsigned x = 0; x < options.get_wave_width(); x++) { output.get(y, x) = patterns[output_patterns.get(y, x)].get(0, 0); } } } else { for (unsigned y = 0; y < options.get_wave_height(); y++) { for (unsigned x = 0; x < options.get_wave_width(); x++) { output.get(y, x) = patterns[output_patterns.get(y, x)].get(0, 0); } } for (unsigned y = 0; y < options.get_wave_height(); y++) { const Array2D<T>& pattern = patterns[output_patterns.get(y, options.get_wave_width() - 1)]; for (unsigned dx = 1; dx < options.pattern_size; dx++) { output.get(y, options.get_wave_width() - 1 + dx) = pattern.get(0, dx); } } for (unsigned x = 0; x < options.get_wave_width(); x++) { const Array2D<T>& pattern = patterns[output_patterns.get(options.get_wave_height() - 1, x)]; for (unsigned dy = 1; dy < options.pattern_size; dy++) { output.get(options.get_wave_height() - 1 + dy, x) = pattern.get(dy, 0); } } const Array2D<T>& pattern = patterns[output_patterns.get( options.get_wave_height() - 1, options.get_wave_width() - 1)]; for (unsigned dy = 1; dy < options.pattern_size; dy++) { for (unsigned dx = 1; dx < options.pattern_size; dx++) { output.get( options.get_wave_height() - 1 + dy, options.get_wave_width() - 1 + dx) = pattern.get(dy, dx); } } } return output; } public: /** * The constructor used by the user. */ OverlappingWFC( const Array2D<T>& input, const OverlappingWFCOptions& options, int seed) noexcept : OverlappingWFC(input, options, seed, get_patterns(input, options)) { } /** * Run the WFC algorithm, and return the result if the algorithm succeeded. */ std::optional<Array2D<T>> run() noexcept { std::optional<Array2D<unsigned>> result = wfc.run(); if (result.has_value()) { return to_image(*result); } return std::nullopt; } }; #endif // FAST_WFC_WFC_HPP_
12,190
3,586
#include "ofApp.h" const int width = 800; const int height = 600; //-------------------------------------------------------------- void ofApp::setup(){ counter = 0; ofSetCircleResolution(50); //ofBackground(0,0,0); bSmooth = false; ofSetWindowTitle("ofxSyphon Example"); mainOutputSyphonServer.setName("Screen Output"); individualTextureSyphonServer.setName("Texture Output"); mClient.setup(); //using Syphon app Simple Server, found at http://syphon.v002.info/ mClient.set("","Simple Server"); tex.allocate(200, 100, GL_RGBA); ofSetFrameRate(60); // if vertical sync is off, we can go a bit fast... this caps the framerate at 60fps. } //-------------------------------------------------------------- void ofApp::update(){ counter = counter + 0.033f; } //-------------------------------------------------------------- void ofApp::draw(){ // Clear with alpha, so we can capture via syphon and composite elsewhere should we want. glClearColor(0.0, 0.0, 0.0, 0.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //--------------------------- circles //let's draw a circle: ofSetColor(255,130,0); float radius = 50 + 10 * sin(counter); ofFill(); // draw "filled shapes" ofDrawCircle(100,400,radius); // now just an outline ofNoFill(); ofSetHexColor(0xCCCCCC); ofDrawCircle(100,400,80); // use the bitMap type // note, this can be slow on some graphics cards // because it is using glDrawPixels which varies in // speed from system to system. try using ofTrueTypeFont // if this bitMap type slows you down. ofSetHexColor(0x000000); ofDrawBitmapString("circle", 75,500); //--------------------------- rectangles ofFill(); for (int i = 0; i < 200; i++){ ofSetColor((int)ofRandom(0,255),(int)ofRandom(0,255),(int)ofRandom(0,255)); ofDrawRectangle(ofRandom(250,350),ofRandom(350,450),ofRandom(10,20),ofRandom(10,20)); } ofSetHexColor(0x000000); ofDrawBitmapString("rectangles", 275,500); //--------------------------- transparency ofSetHexColor(0x00FF33); ofDrawRectangle(100,150,100,100); // alpha is usually turned off - for speed puposes. let's turn it on! ofEnableAlphaBlending(); ofSetColor(255,0,0,127); // red, 50% transparent ofDrawRectangle(150,230,100,33); ofSetColor(255,0,0,(int)(counter * 10.0f) % 255); // red, variable transparent ofDrawRectangle(150,170,100,33); ofDisableAlphaBlending(); ofSetHexColor(0x000000); ofDrawBitmapString("transparency", 110,300); //--------------------------- lines // a bunch of red lines, make them smooth if the flag is set if (bSmooth){ ofEnableSmoothing(); } ofSetHexColor(0xFF0000); for (int i = 0; i < 20; i++){ ofDrawLine(300,100 + (i*5),500, 50 + (i*10)); } if (bSmooth){ ofDisableSmoothing(); } ofSetColor(255,255,255); ofDrawBitmapString("lines\npress 's' to toggle smoothness", 300,300); // draw static into our one texture. unsigned char pixels[200*100*4]; for (int i = 0; i < 200*100*4; i++) { pixels[i] = (int)(255 * ofRandomuf()); } tex.loadData(pixels, 200, 100, GL_RGBA); ofSetColor(255, 255, 255); ofEnableAlphaBlending(); tex.draw(50, 50); // Syphon Stuff mClient.draw(50, 50); mainOutputSyphonServer.publishScreen(); individualTextureSyphonServer.publishTexture(&tex); ofDrawBitmapString("Note this text is not captured by Syphon since it is drawn after publishing.\nYou can use this to hide your GUI for example.", 150,500); } //-------------------------------------------------------------- void ofApp::keyPressed (int key){ if (key == 's'){ bSmooth = !bSmooth; } }
3,721
1,504
// Axel '0vercl0k' Souchet - January 12 2022 #pragma once #include "disassenginewrapper.hpp" #include <beaengine/BeaEngine.h> class IntelBeaEngine : public DisassEngineWrapper { public: /*! The different architectures BeaRopGadgetFinder handles */ enum E_Arch { x86 = 32, x64 = 64 }; explicit IntelBeaEngine(const E_Arch arch) : m_arch(uint32_t(arch)) { // those options are mostly display option for the disassembler engine m_disasm.Options = PrefixedNumeral + NasmSyntax; // this one is to precise what architecture we'll disassemble m_disasm.Archi = m_arch; } InstructionInformation disass(const uint8_t *data, uint64_t len, const uint64_t vaddr, DisassEngineReturn &ret) override { InstructionInformation instr; m_disasm.EIP = UIntPtr(data); m_disasm.VirtualAddr = vaddr; m_disasm.SecurityBlock = uint32_t(len); const int len_instr = Disasm(&m_disasm); if (len_instr == OUT_OF_BLOCK) { ret = OutOfBlock; return instr; } // OK this one is an unknow opcode, goto the next one if (len_instr == UNKNOWN_OPCODE) { ret = UnknownInstruction; return instr; } ret = AllRight; instr.address = m_disasm.EIP; instr.virtual_address_in_memory = uintptr_t(m_disasm.VirtualAddr); instr.disassembly = m_disasm.CompleteInstr; instr.mnemonic = m_disasm.Instruction.Mnemonic; instr.size = len_instr; const auto branch_type = m_disasm.Instruction.BranchType; const auto addr_value = m_disasm.Instruction.AddrValue; const char *mnemonic_s = m_disasm.Instruction.Mnemonic; const char *disass_s = instr.disassembly.c_str(); instr.is_branch = branch_type != 0; const bool is_good_branch_type = // We accept all the ret type instructions (except retf/iret) (branch_type == RetType && (strncmp(mnemonic_s, "retf", 4) != 0) && (strncmp(mnemonic_s, "iretd", 5) != 0)) || // call reg32 / call [reg32] (branch_type == CallType && addr_value == 0) || // jmp reg32 / jmp [reg32] (branch_type == JmpType && addr_value == 0) || // int 0x80 & int 0x2e ((strncmp(disass_s, "int 0x80", 8) == 0) || (strncmp(disass_s, "int 0x2e", 8) == 0) || (strncmp(disass_s, "syscall", 7) == 0)); instr.is_valid_ending_instr = is_good_branch_type && // Yeah, we don't accept jmp far/call far instr.disassembly.find("far") == std::string::npos; return instr; } uint32_t get_size_biggest_instruction() const override { return 15; } uint32_t get_alignement() const override { return 1; } private: uint32_t m_arch = 0; /*!< architecture the BeaEngine will use to disassemble*/ DISASM m_disasm = {}; };
2,801
1,042
#include <gtest/gtest.h> #include <iostream> #include <vector> using namespace std; /** * This file is generated by leetcode_add.py * * 1288. * Remove Covered Intervals * * ––––––––––––––––––––––––––––– Description ––––––––––––––––––––––––––––– * * Given an array ‘intervals’ where ‘intervals[i] = [lᵢ, rᵢ]’ represent * the interval ‘[lᵢ, rᵢ)’ , remove all intervals that are covered by * another interval in the * The interval ‘[a, b)’ is covered by the interval ‘[c, d)’ if and only * if ‘c ≤ a’ and ‘b ≤ d’ * Return “the number of remaining intervals” . * * ––––––––––––––––––––––––––––– Constraints ––––––––––––––––––––––––––––– * * • ‘1 ≤ intervals.length ≤ 1000’ * • ‘intervals[i].length = 2’ * • ‘0 ≤ lᵢ ≤ rᵢ ≤ 10⁵’ * • All the given intervals are “unique” . * */ struct q1288 : public ::testing::Test { // Leetcode answer here class Solution { public: int removeCoveredIntervals(vector<vector<int>> &intervals) { sort(intervals.begin(), intervals.end(), [](const vector<int> &x, const vector<int> &y) { return x[0] == y[0] ? x[1] > y[1] : x[0] < y[0]; }); int res = intervals.size(); vector<int> curr = intervals.front(); for (auto it = intervals.begin() + 1; it != intervals.end(); ++it) { int l = curr[0], r = curr[1]; if (l <= (*it)[0] && r >= (*it)[1]) { --res; } else { curr = *it; } } return res; } }; class Solution *solution; }; TEST_F(q1288, sample_input01) { solution = new Solution(); vector<vector<int>> intervals = {{1, 4}, {3, 6}, {2, 8}}; int exp = 2; int act = solution->removeCoveredIntervals(intervals); EXPECT_EQ(act, exp); delete solution; } TEST_F(q1288, sample_input02) { solution = new Solution(); vector<vector<int>> intervals = {{1, 4}, {2, 3}}; int exp = 1; int act = solution->removeCoveredIntervals(intervals); EXPECT_EQ(act, exp); delete solution; }
2,005
835
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/cast/test/receiver/framer.h" #include "base/logging.h" #include "media/cast/constants.h" namespace media { namespace cast { Framer::Framer(const base::TickClock* clock, RtpPayloadFeedback* incoming_payload_feedback, uint32_t ssrc, bool decoder_faster_than_max_frame_rate, int max_unacked_frames) : decoder_faster_than_max_frame_rate_(decoder_faster_than_max_frame_rate), cast_msg_builder_(clock, incoming_payload_feedback, this, ssrc, decoder_faster_than_max_frame_rate, max_unacked_frames), waiting_for_key_(true), last_released_frame_(FrameId::first() - 1), newest_frame_id_(FrameId::first() - 1) { DCHECK(incoming_payload_feedback) << "Invalid argument"; } Framer::~Framer() = default; bool Framer::InsertPacket(const uint8_t* payload_data, size_t payload_size, const RtpCastHeader& rtp_header, bool* duplicate) { *duplicate = false; if (rtp_header.is_key_frame && waiting_for_key_) { last_released_frame_ = rtp_header.frame_id - 1; waiting_for_key_ = false; } VLOG(1) << "InsertPacket frame:" << rtp_header.frame_id << " packet:" << static_cast<int>(rtp_header.packet_id) << " max packet:" << static_cast<int>(rtp_header.max_packet_id); if ((rtp_header.frame_id <= last_released_frame_) && !waiting_for_key_) { // Packet is too old. return false; } // Update the last received frame id. if (rtp_header.frame_id > newest_frame_id_) { newest_frame_id_ = rtp_header.frame_id; } // Insert packet. const auto it = frames_.find(rtp_header.frame_id); FrameBuffer* buffer; if (it == frames_.end()) { buffer = new FrameBuffer(); frames_.insert(std::make_pair(rtp_header.frame_id, std::unique_ptr<FrameBuffer>(buffer))); } else { buffer = it->second.get(); } if (!buffer->InsertPacket(payload_data, payload_size, rtp_header)) { VLOG(3) << "Packet already received, ignored: frame " << rtp_header.frame_id << ", packet " << rtp_header.packet_id; *duplicate = true; return false; } return buffer->Complete(); } // This does not release the frame. bool Framer::GetEncodedFrame(EncodedFrame* frame, bool* next_frame, bool* have_multiple_decodable_frames) { *have_multiple_decodable_frames = HaveMultipleDecodableFrames(); // Find frame id. FrameBuffer* buffer = FindNextFrameForRelease(); if (buffer) { // We have our next frame. *next_frame = true; } else { // Check if we can skip frames when our decoder is too slow. if (!decoder_faster_than_max_frame_rate_) return false; buffer = FindOldestDecodableFrame(); if (!buffer) return false; *next_frame = false; } return buffer->AssembleEncodedFrame(frame); } void Framer::AckFrame(FrameId frame_id) { VLOG(2) << "ACK frame " << frame_id; cast_msg_builder_.CompleteFrameReceived(frame_id); } void Framer::ReleaseFrame(FrameId frame_id) { const auto it = frames_.begin(); const bool skipped_old_frame = it->first < frame_id; frames_.erase(it, frames_.upper_bound(frame_id)); last_released_frame_ = frame_id; if (skipped_old_frame) cast_msg_builder_.UpdateCastMessage(); } bool Framer::TimeToSendNextCastMessage(base::TimeTicks* time_to_send) { return cast_msg_builder_.TimeToSendNextCastMessage(time_to_send); } void Framer::SendCastMessage() { cast_msg_builder_.UpdateCastMessage(); } FrameBuffer* Framer::FindNextFrameForRelease() { for (const auto& entry : frames_) { if (entry.second->Complete() && IsNextFrameForRelease(*entry.second)) return entry.second.get(); } return nullptr; } FrameBuffer* Framer::FindOldestDecodableFrame() { for (const auto& entry : frames_) { if (entry.second->Complete() && IsDecodableFrame(*entry.second)) return entry.second.get(); } return nullptr; } bool Framer::HaveMultipleDecodableFrames() const { bool found_one = false; for (const auto& entry : frames_) { if (entry.second->Complete() && IsDecodableFrame(*entry.second)) { if (found_one) return true; // Found another. else found_one = true; // Found first one. Continue search for another. } } return false; } bool Framer::Empty() const { return frames_.empty(); } int Framer::NumberOfCompleteFrames() const { int count = 0; for (const auto& entry : frames_) { if (entry.second->Complete()) ++count; } return count; } bool Framer::FrameExists(FrameId frame_id) const { return frames_.end() != frames_.find(frame_id); } void Framer::GetMissingPackets(FrameId frame_id, bool last_frame, PacketIdSet* missing_packets) const { const auto it = frames_.find(frame_id); if (it == frames_.end()) return; it->second->GetMissingPackets(last_frame, missing_packets); } bool Framer::IsNextFrameForRelease(const FrameBuffer& buffer) const { if (waiting_for_key_ && !buffer.is_key_frame()) return false; return (last_released_frame_ + 1) == buffer.frame_id(); } bool Framer::IsDecodableFrame(const FrameBuffer& buffer) const { if (buffer.is_key_frame()) return true; if (waiting_for_key_) return false; // Self-reference? if (buffer.last_referenced_frame_id() == buffer.frame_id()) return true; // Current frame is not necessarily referencing the last frame. // Has the reference frame been released already? return buffer.last_referenced_frame_id() <= last_released_frame_; } } // namespace cast } // namespace media
6,024
1,983
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. namespace config { template <typename ConfigType> void ConfigPoller::subscribe(const std::string & configId, IFetcherCallback<ConfigType> * callback, milliseconds subscribeTimeout) { std::unique_ptr<ConfigHandle<ConfigType> > handle(_subscriber.subscribe<ConfigType>(configId, subscribeTimeout)); _handleList.emplace_back(std::make_unique<GenericHandle<ConfigType>>(std::move(handle))); _callbackList.push_back(callback); } } // namespace config
580
171
/* * Copyright (c) 2001, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #include "precompiled.hpp" #include "runtime/thread.inline.hpp" #include "runtime/threadCritical.hpp" // OS-includes here #include <thread.h> #include <synch.h> // // See threadCritical.hpp for details of this class. // // For some reason, we don't do locking until the // os::init() call completes. I'm not sure why this // is, and have left it that way for now. This should // be reviewed later. static mutex_t global_mut; static thread_t global_mut_owner = -1; static int global_mut_count = 0; static bool initialized = false; ThreadCritical::ThreadCritical() { if (initialized) { thread_t owner = thr_self(); if (global_mut_owner != owner) { if (os::Solaris::mutex_lock(&global_mut)) fatal(err_msg("ThreadCritical::ThreadCritical: mutex_lock failed (%s)", strerror(errno))); assert(global_mut_count == 0, "must have clean count"); assert(global_mut_owner == -1, "must have clean owner"); } global_mut_owner = owner; ++global_mut_count; } else { assert (Threads::number_of_threads() == 0, "valid only during initialization"); } } ThreadCritical::~ThreadCritical() { if (initialized) { assert(global_mut_owner == thr_self(), "must have correct owner"); assert(global_mut_count > 0, "must have correct count"); --global_mut_count; if (global_mut_count == 0) { global_mut_owner = -1; if (os::Solaris::mutex_unlock(&global_mut)) fatal(err_msg("ThreadCritical::~ThreadCritical: mutex_unlock failed " "(%s)", strerror(errno))); } } else { assert (Threads::number_of_threads() == 0, "valid only during initialization"); } } void ThreadCritical::initialize() { // This method is called at the end of os::init(). Until // then, we don't do real locking. initialized = true; } void ThreadCritical::release() { }
2,943
959
/* *********************************************************************************************************************** * * Copyright (c) 2019 Advanced Micro Devices, Inc. All Rights Reserved. * * 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. * **********************************************************************************************************************/ /** *********************************************************************************************************************** * @file llpcBuilder.cpp * @brief LLPC source file: implementation of Llpc::Builder *********************************************************************************************************************** */ #include "llpcBuilderImpl.h" #include "llpcPipelineState.h" #include "llpcContext.h" #include "llpcInternal.h" #include "llvm/Linker/Linker.h" #include "llvm/Support/CommandLine.h" #include <set> #define DEBUG_TYPE "llpc-builder" using namespace Llpc; using namespace llvm; // -use-builder-recorder static cl::opt<uint32_t> UseBuilderRecorder("use-builder-recorder", cl::desc("Do lowering via recording and replaying LLPC builder:\n" "0: Generate IR directly; no recording\n" "1: Do lowering via recording and replaying LLPC builder (default)\n" "2: Do lowering via recording; no replaying"), cl::init(1)); // ===================================================================================================================== // Create a Builder object // If -use-builder-recorder is 0, this creates a BuilderImpl. Otherwise, it creates a BuilderRecorder. Builder* Builder::Create( LLVMContext& context) // [in] LLVM context { if (UseBuilderRecorder == 0) { // -use-builder-recorder=0: generate LLVM IR directly without recording return CreateBuilderImpl(context); } // -use-builder-recorder=1: record with BuilderRecorder and replay with BuilderReplayer // -use-builder-recorder=2: record with BuilderRecorder and do not replay return CreateBuilderRecorder(context, UseBuilderRecorder == 1 /*wantReplay*/); } // ===================================================================================================================== // Create a BuilderImpl object Builder* Builder::CreateBuilderImpl( LLVMContext& context) // [in] LLVM context { return new BuilderImpl(context); } // ===================================================================================================================== Builder::Builder( LLVMContext& context) // [in] LLPC context : IRBuilder<>(context) { m_pPipelineState = new PipelineState(&context); } // ===================================================================================================================== Builder::~Builder() { delete m_pPipelineState; } // ===================================================================================================================== // Get the type pElementTy, turned into a vector of the same vector width as pMaybeVecTy if the latter // is a vector type. Type* Builder::GetConditionallyVectorizedTy( Type* pElementTy, // [in] Element type Type* pMaybeVecTy) // [in] Possible vector type to get number of elements from { if (auto pVecTy = dyn_cast<VectorType>(pMaybeVecTy)) { return VectorType::get(pElementTy, pVecTy->getNumElements()); } return pElementTy; } // ===================================================================================================================== // Set the resource mapping nodes for the given shader stage. // This stores the nodes as IR metadata. void Builder::SetUserDataNodes( ArrayRef<ResourceMappingNode> nodes, // The resource mapping nodes ArrayRef<DescriptorRangeValue> rangeValues) // The descriptor range values { m_pPipelineState->SetUserDataNodes(nodes, rangeValues); } // ===================================================================================================================== // Base implementation of linking shader modules into a pipeline module. Module* Builder::Link( ArrayRef<Module*> modules, // Array of modules indexed by shader stage, with nullptr entry // for any stage not present in the pipeline bool linkNativeStages) // Whether to link native shader stage modules { // Add IR metadata for the shader stage to each function in each shader, and rename the entrypoint to // ensure there is no clash on linking. if (linkNativeStages) { uint32_t metaKindId = getContext().getMDKindID(LlpcName::ShaderStageMetadata); for (uint32_t stage = 0; stage < modules.size(); ++stage) { Module* pModule = modules[stage]; if (pModule == nullptr) { continue; } auto pStageMetaNode = MDNode::get(getContext(), { ConstantAsMetadata::get(getInt32(stage)) }); for (Function& func : *pModule) { if (func.isDeclaration() == false) { func.setMetadata(metaKindId, pStageMetaNode); if (func.getLinkage() != GlobalValue::InternalLinkage) { func.setName(Twine(LlpcName::EntryPointPrefix) + GetShaderStageAbbreviation(static_cast<ShaderStage>(stage), true) + "." + func.getName()); } } } } } // If there is only one shader, just change the name on its module and return it. Module* pPipelineModule = nullptr; for (auto pModule : modules) { if (pPipelineModule == nullptr) { pPipelineModule = pModule; } else if (pModule != nullptr) { pPipelineModule = nullptr; break; } } if (pPipelineModule != nullptr) { pPipelineModule->setModuleIdentifier("llpcPipeline"); // Record pipeline state into IR metadata. if (m_pPipelineState != nullptr) { m_pPipelineState->RecordState(pPipelineModule); } } else { // Create an empty module then link each shader module into it. We record pipeline state into IR // metadata before the link, to avoid problems with a Constant for an immutable descriptor value // disappearing when modules are deleted. bool result = true; pPipelineModule = new Module("llpcPipeline", getContext()); static_cast<Llpc::Context*>(&getContext())->SetModuleTargetMachine(pPipelineModule); Linker linker(*pPipelineModule); if (m_pPipelineState != nullptr) { m_pPipelineState->RecordState(pPipelineModule); } for (int32_t shaderIndex = 0; shaderIndex < modules.size(); ++shaderIndex) { if (modules[shaderIndex] != nullptr) { // NOTE: We use unique_ptr here. The shader module will be destroyed after it is // linked into pipeline module. if (linker.linkInModule(std::unique_ptr<Module>(modules[shaderIndex]))) { result = false; } } } if (result == false) { delete pPipelineModule; pPipelineModule = nullptr; } } return pPipelineModule; } // ===================================================================================================================== // Create a map to i32 function. Many AMDGCN intrinsics only take i32's, so we need to massage input data into an i32 // to allow us to call these intrinsics. This helper takes a function pointer, massage arguments, and passthrough // arguments and massages the mappedArgs into i32's before calling the function pointer. Note that all massage // arguments must have the same type. Value* Builder::CreateMapToInt32( PFN_MapToInt32Func pfnMapFunc, // [in] The function to call on each provided i32. ArrayRef<Value*> mappedArgs, // The arguments to be massaged into i32's and passed to function. ArrayRef<Value*> passthroughArgs) // The arguments to be passed through as is (no massaging). { // We must have at least one argument to massage. LLPC_ASSERT(mappedArgs.size() > 0); Type* const pType = mappedArgs[0]->getType(); // Check the massage types all match. for (uint32_t i = 1; i < mappedArgs.size(); i++) { LLPC_ASSERT(mappedArgs[i]->getType() == pType); } if (mappedArgs[0]->getType()->isVectorTy()) { // For vectors we extract each vector component and map them individually. const uint32_t compCount = pType->getVectorNumElements(); SmallVector<Value*, 4> results; for (uint32_t i = 0; i < compCount; i++) { SmallVector<Value*, 4> newMappedArgs; for (Value* const pMappedArg : mappedArgs) { newMappedArgs.push_back(CreateExtractElement(pMappedArg, i)); } results.push_back(CreateMapToInt32(pfnMapFunc, newMappedArgs, passthroughArgs)); } Value* pResult = UndefValue::get(VectorType::get(results[0]->getType(), compCount)); for (uint32_t i = 0; i < compCount; i++) { pResult = CreateInsertElement(pResult, results[i], i); } return pResult; } else if (pType->isIntegerTy() && pType->getIntegerBitWidth() == 1) { SmallVector<Value*, 4> newMappedArgs; for (Value* const pMappedArg : mappedArgs) { newMappedArgs.push_back(CreateZExt(pMappedArg, getInt32Ty())); } Value* const pResult = CreateMapToInt32(pfnMapFunc, newMappedArgs, passthroughArgs); return CreateTrunc(pResult, getInt1Ty()); } else if (pType->isIntegerTy() && pType->getIntegerBitWidth() < 32) { SmallVector<Value*, 4> newMappedArgs; Type* const pVectorType = VectorType::get(pType, (pType->getPrimitiveSizeInBits() == 16) ? 2 : 4); Value* const pUndef = UndefValue::get(pVectorType); for (Value* const pMappedArg : mappedArgs) { Value* const pNewMappedArg = CreateInsertElement(pUndef, pMappedArg, static_cast<uint64_t>(0)); newMappedArgs.push_back(CreateBitCast(pNewMappedArg, getInt32Ty())); } Value* const pResult = CreateMapToInt32(pfnMapFunc, newMappedArgs, passthroughArgs); return CreateExtractElement(CreateBitCast(pResult, pVectorType), static_cast<uint64_t>(0)); } else if (pType->getPrimitiveSizeInBits() == 64) { SmallVector<Value*, 4> castMappedArgs; for (Value* const pMappedArg : mappedArgs) { castMappedArgs.push_back(CreateBitCast(pMappedArg, VectorType::get(getInt32Ty(), 2))); } Value* pResult = UndefValue::get(castMappedArgs[0]->getType()); for (uint32_t i = 0; i < 2; i++) { SmallVector<Value*, 4> newMappedArgs; for (Value* const pCastMappedArg : castMappedArgs) { newMappedArgs.push_back(CreateExtractElement(pCastMappedArg, i)); } Value* const pResultComp = CreateMapToInt32(pfnMapFunc, newMappedArgs, passthroughArgs); pResult = CreateInsertElement(pResult, pResultComp, i); } return CreateBitCast(pResult, pType); } else if (pType->isFloatingPointTy()) { SmallVector<Value*, 4> newMappedArgs; for (Value* const pMappedArg : mappedArgs) { newMappedArgs.push_back(CreateBitCast(pMappedArg, getIntNTy(pMappedArg->getType()->getPrimitiveSizeInBits()))); } Value* const pResult = CreateMapToInt32(pfnMapFunc, newMappedArgs, passthroughArgs); return CreateBitCast(pResult, pType); } else if (pType->isIntegerTy(32)) { return pfnMapFunc(*this, mappedArgs, passthroughArgs); } else { LLPC_NEVER_CALLED(); return nullptr; } } // ===================================================================================================================== // Gets new matrix type after doing matrix transposing. Type* Builder::GetTransposedMatrixTy( Type* const pMatrixType // [in] The matrix type to get the transposed type from. ) const { LLPC_ASSERT(pMatrixType->isArrayTy()); Type* const pColumnVectorType = pMatrixType->getArrayElementType(); LLPC_ASSERT(pColumnVectorType->isVectorTy()); const uint32_t columnCount = pMatrixType->getArrayNumElements(); const uint32_t rowCount = pColumnVectorType->getVectorNumElements(); return ArrayType::get(VectorType::get(pColumnVectorType->getVectorElementType(), columnCount), rowCount); } // ===================================================================================================================== // Get the LLPC context. This overrides the IRBuilder method that gets the LLVM context. Context& Builder::getContext() const { return *static_cast<Llpc::Context*>(&IRBuilder<>::getContext()); } // ===================================================================================================================== // Get the type of pointer returned by CreateLoadBufferDesc. PointerType* Builder::GetBufferDescTy( Type* pPointeeTy) // [in] Type that the returned pointer should point to. { return PointerType::get(pPointeeTy, ADDR_SPACE_BUFFER_FAT_POINTER); } // ===================================================================================================================== // Get the type of an image descriptor VectorType* Builder::GetImageDescTy() { return VectorType::get(getInt32Ty(), 8); } // ===================================================================================================================== // Get the type of an fmask descriptor VectorType* Builder::GetFmaskDescTy() { return VectorType::get(getInt32Ty(), 8); } // ===================================================================================================================== // Get the type of a texel buffer descriptor VectorType* Builder::GetTexelBufferDescTy() { return VectorType::get(getInt32Ty(), 4); } // ===================================================================================================================== // Get the type of a sampler descriptor VectorType* Builder::GetSamplerDescTy() { return VectorType::get(getInt32Ty(), 4); } // ===================================================================================================================== // Get the type of pointer to image descriptor. // This is in fact a struct containing the pointer itself plus the stride in dwords. Type* Builder::GetImageDescPtrTy() { return StructType::get(getContext(), { PointerType::get(GetImageDescTy(), ADDR_SPACE_CONST), getInt32Ty() }); } // ===================================================================================================================== // Get the type of pointer to fmask descriptor. // This is in fact a struct containing the pointer itself plus the stride in dwords. Type* Builder::GetFmaskDescPtrTy() { return StructType::get(getContext(), { PointerType::get(GetFmaskDescTy(), ADDR_SPACE_CONST), getInt32Ty() }); } // ===================================================================================================================== // Get the type of pointer to texel buffer descriptor. // This is in fact a struct containing the pointer itself plus the stride in dwords. Type* Builder::GetTexelBufferDescPtrTy() { return StructType::get(getContext(), { PointerType::get(GetTexelBufferDescTy(), ADDR_SPACE_CONST), getInt32Ty() }); } // ===================================================================================================================== // Get the type of pointer to sampler descriptor. // This is in fact a struct containing the pointer itself plus the stride in dwords. Type* Builder::GetSamplerDescPtrTy() { return StructType::get(getContext(), { PointerType::get(GetSamplerDescTy(), ADDR_SPACE_CONST), getInt32Ty() }); } // ===================================================================================================================== // Get the type of a built-in. Where the built-in has a shader-defined array size (ClipDistance, // CullDistance, SampleMask), inOutInfo.GetArraySize() is used as the array size. Type* Builder::GetBuiltInTy( BuiltInKind builtIn, // Built-in kind InOutInfo inOutInfo) // Extra input/output info (shader-defined array size) { enum TypeCode: uint32_t { a2f32, a4f32, af32, ai32, f32, i1, i32, i64, mask, v2f32, v3f32, v3i32, v4f32, v4i32, a4v3f32 }; uint32_t arraySize = inOutInfo.GetArraySize(); TypeCode typeCode = TypeCode::i32; switch (builtIn) { #define BUILTIN(name, number, out, in, type) \ case BuiltIn ## name: \ typeCode = TypeCode:: type; \ break; #include "llpcBuilderBuiltIns.h" #undef BUILTIN default: LLPC_NEVER_CALLED(); break; } switch (typeCode) { case TypeCode::a2f32: return ArrayType::get(getFloatTy(), 2); case TypeCode::a4f32: return ArrayType::get(getFloatTy(), 4); // For ClipDistance and CullDistance, the shader determines the array size. case TypeCode::af32: return ArrayType::get(getFloatTy(), arraySize); // For SampleMask, the shader determines the array size. case TypeCode::ai32: return ArrayType::get(getInt32Ty(), arraySize); case TypeCode::f32: return getFloatTy(); case TypeCode::i1: return getInt1Ty(); case TypeCode::i32: return getInt32Ty(); case TypeCode::i64: return getInt64Ty(); case TypeCode::v2f32: return VectorType::get(getFloatTy(), 2); case TypeCode::v3f32: return VectorType::get(getFloatTy(), 3); case TypeCode::v4f32: return VectorType::get(getFloatTy(), 4); case TypeCode::v3i32: return VectorType::get(getInt32Ty(), 3); case TypeCode::v4i32: return VectorType::get(getInt32Ty(), 4); case TypeCode::a4v3f32: return ArrayType::get(VectorType::get(getFloatTy(), 3), 4); default: LLPC_NEVER_CALLED(); return nullptr; } } // ===================================================================================================================== // Get a constant of FP or vector of FP type from the given APFloat, converting APFloat semantics where necessary Constant* Builder::GetFpConstant( Type* pTy, // [in] FP scalar or vector type APFloat value) // APFloat value { const fltSemantics* pSemantics = &APFloat::IEEEdouble(); Type* pScalarTy = pTy->getScalarType(); if (pScalarTy->isHalfTy()) { pSemantics = &APFloat::IEEEhalf(); } else if (pScalarTy->isFloatTy()) { pSemantics = &APFloat::IEEEsingle(); } bool ignored = true; value.convert(*pSemantics, APFloat::rmNearestTiesToEven, &ignored); return ConstantFP::get(pTy, value); } // ===================================================================================================================== // Get a constant of FP or vector of FP type for the value PI/180, for converting radians to degrees. Constant* Builder::GetPiOver180( Type* pTy) // [in] FP scalar or vector type { // PI/180, 0.017453292 // TODO: Use a value that works for double as well. return GetFpConstant(pTy, APFloat(APFloat::IEEEdouble(), APInt(64, 0x3F91DF46A0000000))); } // ===================================================================================================================== // Get a constant of FP or vector of FP type for the value 180/PI, for converting degrees to radians. Constant* Builder::Get180OverPi( Type* pTy) // [in] FP scalar or vector type { // 180/PI, 57.29577951308232 // TODO: Use a value that works for double as well. return GetFpConstant(pTy, APFloat(APFloat::IEEEdouble(), APInt(64, 0x404CA5DC20000000))); } // ===================================================================================================================== // Get a constant of FP or vector of FP type for the value 1/(2^n - 1) Constant* Builder::GetOneOverPower2MinusOne( Type* pTy, // [in] FP scalar or vector type uint32_t n) // Power of two to use { // We could calculate this here, using knowledge that 1(2^n - 1) in binary has a repeating bit pattern // of {n-1 zeros, 1 one}. But instead we just special case the values of n that we know are // used from the frontend. uint64_t bits = 0; switch (n) { case 7: // 1/127 bits = 0x3F80204081020408; break; case 8: // 1/255 bits = 0x3F70101010101010; break; case 15: // 1/32767 bits = 0x3F00002000400080; break; case 16: // 1/65535 bits = 0x3EF0001000100010; break; default: LLPC_NEVER_CALLED(); } return GetFpConstant(pTy, APFloat(APFloat::IEEEdouble(), APInt(64, bits))); } // ===================================================================================================================== // Create a call to the specified intrinsic with one operand, mangled on its type. // This is an override of the same method in IRBuilder<>; the difference is that this one sets fast math // flags from the Builder if none are specified by pFmfSource. CallInst* Builder::CreateUnaryIntrinsic( Intrinsic::ID id, // Intrinsic ID Value* pValue, // [in] Input value Instruction* pFmfSource, // [in] Instruction to copy fast math flags from; nullptr to get from Builder const Twine& instName) // [in] Name to give instruction { CallInst* pResult = IRBuilder<>::CreateUnaryIntrinsic(id, pValue, pFmfSource, instName); if ((pFmfSource == nullptr) && isa<FPMathOperator>(pResult)) { // There are certain intrinsics with an FP result that we do not want FMF on. switch (id) { case Intrinsic::amdgcn_wqm: case Intrinsic::amdgcn_wwm: break; default: pResult->setFastMathFlags(getFastMathFlags()); break; } } return pResult; } // ===================================================================================================================== // Create a call to the specified intrinsic with two operands of the same type, mangled on that type. // This is an override of the same method in IRBuilder<>; the difference is that this one sets fast math // flags from the Builder if none are specified by pFmfSource. CallInst* Builder::CreateBinaryIntrinsic( Intrinsic::ID id, // Intrinsic ID Value* pValue1, // [in] Input value 1 Value* pValue2, // [in] Input value 2 Instruction* pFmfSource, // [in] Instruction to copy fast math flags from; nullptr to get from Builder const Twine& name) // [in] Name to give instruction { CallInst* pResult = IRBuilder<>::CreateBinaryIntrinsic(id, pValue1, pValue2, pFmfSource, name); if ((pFmfSource == nullptr) && isa<FPMathOperator>(pResult)) { pResult->setFastMathFlags(getFastMathFlags()); } return pResult; } // ===================================================================================================================== // Create a call to the specified intrinsic with the specified operands, mangled on the specified types. // This is an override of the same method in IRBuilder<>; the difference is that this one sets fast math // flags from the Builder if none are specified by pFmfSource. CallInst* Builder::CreateIntrinsic( Intrinsic::ID id, // Intrinsic ID ArrayRef<Type*> types, // [in] Types ArrayRef<Value*> args, // [in] Input values Instruction* pFmfSource, // [in] Instruction to copy fast math flags from; nullptr to get from Builder const Twine& name) // [in] Name to give instruction { CallInst* pResult = IRBuilder<>::CreateIntrinsic(id, types, args, pFmfSource, name); if ((pFmfSource == nullptr) && isa<FPMathOperator>(pResult)) { pResult->setFastMathFlags(getFastMathFlags()); } return pResult; }
25,904
7,393
/* This file is part of the Tweeny library. Copyright (c) 2016-2018 Leonardo G. Lucena de Freitas Copyright (c) 2016 Guilherme R. Costa 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. */ /* * This file implements the tweenpoint class */ #ifndef TWEENY_TWEENPOINT_TCC #define TWEENY_TWEENPOINT_TCC #include <algorithm> #include <type_traits> #include "tweenpoint.h" #include "tweentraits.h" #include "easing.h" #include "easingresolve.h" #include "int2type.h" namespace tweeny { namespace detail { template<typename TypeTupleT, typename EasingCollectionT, typename EasingT, size_t I> void easingfill(EasingCollectionT &f, EasingT easing, int2type<I>) { easingresolve<I, TypeTupleT, EasingCollectionT, EasingT>::impl(f, easing); easingfill<TypeTupleT, EasingCollectionT, EasingT>(f, easing, int2type<I - 1>{}); } template<typename TypeTupleT, typename EasingCollectionT, typename EasingT> void easingfill(EasingCollectionT &f, EasingT easing, int2type<0>) { easingresolve<0, TypeTupleT, EasingCollectionT, EasingT>::impl(f, easing); } template<class ...T> struct are_same; template<class A, class B, class ...T> struct are_same<A, B, T...> { static const bool value = std::is_same<A, B>::value && are_same<B, T...>::value; }; template<class A> struct are_same<A> { static const bool value = true; }; template<typename... Ts> inline tweenpoint<Ts...>::tweenpoint(Ts... vs) : values{vs...} { during(static_cast<uint16_t>(0)); via(easing::linear); } template<typename... Ts> template<typename D> inline void tweenpoint<Ts...>::during(D milis) { for (uint16_t &t : durations) { t = static_cast<uint16_t>(milis); } } template<typename... Ts> template<typename... Ds> inline void tweenpoint<Ts...>::during(Ds... milis) { static_assert(sizeof...(Ds) == sizeof...(Ts), "Amount of durations should be equal to the amount of values in a currentPoint"); std::array<int, sizeof...(Ts)> list = {{milis...}}; std::copy(list.begin(), list.end(), durations.begin()); } template<typename... Ts> template<typename... Fs> inline void tweenpoint<Ts...>::via(Fs... fs) { static_assert(sizeof...(Fs) == sizeof...(Ts), "Number of functions passed to via() must be equal the number of values."); detail::easingresolve<0, std::tuple<Ts...>, typename traits::easingCollection, Fs...>::impl(easings, fs...); } template<typename... Ts> template<typename F> inline void tweenpoint<Ts...>::via(F f) { easingfill<typename traits::valuesType>(easings, f, int2type<sizeof...(Ts) - 1>{}); } template<typename... Ts> inline uint16_t tweenpoint<Ts...>::duration() const { return *std::max_element(durations.begin(), durations.end()); } template<typename... Ts> inline uint16_t tweenpoint<Ts...>::duration(size_t i) const { return durations.at(i); } } } #endif //TWEENY_TWEENPOINT_TCC
4,324
1,402
#include "defs.h" bool fbp_gpu_20_fs(allData *aD){ unsigned int onx, ony, wo, ho, obnx, obny, nx, ny, wh, wh2, wu, vH; float sx, sy, ps; double angleStart, angleStep; Ipp32f *vux, *vuy, *v; Ipp64f *v1, *v2, *v3, *v4; xFBP_gpu *fg; gpu_info *gi; xData *xd; xRoi *xr; fg = aD->fg; gi = aD->gi; xd = aD->data; xr = aD->hms->fbp->backprojection->roi; nx = aD->ta_nx; ny = aD->ta_ny; wh = gi->ho * gi->wo; wh2 = wh/2; wu = ny/wh2; onx = gi->mxo; ony = gi->myo; wo = gi->wo; ho = gi->ho; obnx = onx/wo; obny = ony/ho; ps = gi->outputPixelSize; angleStart = pi*double(xr->angle)/180.0; angleStep = double(gi->rotAngleStep); v1 = ippsMalloc_64f(ny); v2 = ippsMalloc_64f(ny); v3 = ippsMalloc_64f(ny); v4 = ippsMalloc_64f(2*ny); xd->vecCS = ippsMalloc_32f(2*ny); ippsVectorSlope_64f(v1,ny,angleStart,angleStep); ippsCos_64f_A53(v1,v2,ny); ippsSin_64f_A53(v1,v3,ny); ippsRealToCplx_64f(v2, v3, (Ipp64fc *)v4, ny); ippsConvert_64f32f(v4,xd->vecCS,2*ny); ippsFree(v1); v1 = NULL; ippsFree(v2); v2 = NULL; ippsFree(v3); v3 = NULL; ippsFree(v4); v4 = NULL; sx = 0.5f*ps * float(onx - 1); sy = 0.5f*ps * float(ony - 1); aD->roiRadius = sqrt(sx*sx+sy*sy); aD->to_nx = onx; aD->to_ny = ony; vux = ippsMalloc_32f(onx); vuy = ippsMalloc_32f(onx); if(vux == NULL || vuy == NULL){ printError(aD,"can not allocate memory (fbp, ux, uy)"); return false; } xd->vecXY_block = ippsMalloc_32f(2*wo*ho); xd->vecXY = ippsMalloc_32f(2*onx*ony); xd->vecRA = ippsMalloc_32f(2*onx*ony); xd->vecbXY = ippsMalloc_32f(2*obnx*obny); if(xd->vecXY == NULL || xd->vecbXY == NULL || xd->vecRA == NULL){ printError(aD, "can not allocate memory (FBP, vecXY, vecbXY, vecRA)"); return false; } ippsVectorSlope_32f(vux,wo,-0.5f*ps*(wo-1),ps); for(unsigned int i=0; i<ho; i++){ ippsSet_32f(-0.5f*ps*(ho-1)+float(i)*ps,vuy,wo); ippsRealToCplx_32f(vux,vuy,(Ipp32fc*)(xd->vecXY_block)+i*wo,wo); } ippsVectorSlope_32f(vux,onx,-0.5f*ps*(onx-1),ps); for(unsigned int i=0; i<ony; i++){ ippsSet_32f(-0.5f*ps*(ony-1)+float(i)*ps,vuy,onx); ippsRealToCplx_32f(vux,vuy,(Ipp32fc*)(xd->vecXY)+i*onx,onx); } ippsCartToPolar_32fc((Ipp32fc *)xd->vecXY, xd->vecRA, xd->vecRA+onx*ony, onx*ony); v = xd->vecRA+onx*ony; for(unsigned int i=0; i<onx*ony; i++){ if(v[i]<0.0f) v[i] += (2.0f*pif); } ippsMulC_32f_I(float(aD->ta_ny_13-1)/pif,v,onx*ony); ippsThreshold_LTValGTVal_32f_I(v, onx*ony, 0.0f, 0.0f, float(2*aD->ta_ny_13-2), float(2*aD->ta_ny_13-2)); ippsFree(vux); vux = NULL; ippsFree(vuy); vuy = NULL; xd->vecAT = ippsMalloc_32f(onx*ony); ippsPhase_32fc((Ipp32fc*)xd->vecXY, xd->vecAT, onx*ony); ippsAddC_32f_I(pif,xd->vecAT,onx*ony); ippsMulC_32f_I(float(aD->ta_ny_13)/pif,xd->vecAT,onx*ony); for(unsigned int i=0; i<obny; i++){ for(unsigned int j=0; j<obnx; j++){ xd->vecbXY[2*(i*obnx+j)] = 0.5f * (xd->vecXY[2*(i*ho*onx+j*wo)] + xd->vecXY[2*(((i+1)*ho-1)*onx+(j+1)*wo-1)]); xd->vecbXY[2*(i*obnx+j)+1] = 0.5f * (xd->vecXY[2*(i*ho*onx+j*wo)+1] + xd->vecXY[2*(((i+1)*ho-1)*onx+(j+1)*wo-1)+1]); } } xd->vto = ippsMalloc_32f(onx*ony); if(xd->vto == NULL){ printError(aD, "can not allocate memory (output matrix)"); return false; } if(!form_filter(aD))return false; vH = gi->vertH; xd->veccF = ippsMalloc_32fc(nx*vH); Ipp32f *vz = ippsMalloc_32f(nx); ippsZero_32f(vz, nx); ippsRealToCplx_32f(xd->vfilter, vz, xd->veccF, nx); for(unsigned int i=1; i<vH; i++){ ippsCopy_32fc(xd->veccF, xd->veccF + i*nx, nx); } ippsFree(vz); vz = NULL; return true; } bool fbp_gpu_fs(allData *aD){ xData *xd; xFBP_gpu *fg; gpu_info *gi; xRoi *xr; unsigned int onx, ony, wo, ho, ny, nx; double angleStart, angleStep; unsigned int ont; unsigned int ndiam, ndiameter, nleft; unsigned int vH; float sx, sy, ps; double dps, xmin, ymin, yval; double rat; Ipp64f *v1, *v2, *v3, *v4; xd = aD->data; fg = aD->fg; gi = aD->gi; fg->nx = aD->ta_nx; fg->ny = aD->ta_ny; fg->nxo = gi->mxo; fg->nyo = gi->myo; fg->blockWidth = gi->wo; fg->blockHeight = gi->ho; fg->vH = gi->vertH; nx = aD->ta_nx; ny = aD->ta_ny; xr = aD->hms->fbp->backprojection->roi; ps = gi->outputPixelSize; angleStart = pi*double(xr->angle)/180.0; angleStep = double(gi->rotAngleStep); v1 = ippsMalloc_64f(ny); v2 = ippsMalloc_64f(ny); v3 = ippsMalloc_64f(ny); v4 = ippsMalloc_64f(2*ny); xd->vecCS = ippsMalloc_32f(2*ny); ippsVectorSlope_64f(v1,ny,angleStart,angleStep); ippsCos_64f_A53(v1,v2,ny); ippsSin_64f_A53(v1,v3,ny); ippsRealToCplx_64f(v2, v3, (Ipp64fc *)v4, ny); ippsConvert_64f32f(v4,xd->vecCS,2*ny); ippsFree(v1); v1 = NULL; ippsFree(v2); v2 = NULL; ippsFree(v3); v3 = NULL; ippsFree(v4); v4 = NULL; onx = gi->mxo; ony = gi->myo; ont = onx*ony; wo = gi->wo; ho = gi->ho; sx = 0.5f*ps * float(onx - 1); sy = 0.5f*ps * float(ony - 1); aD->roiRadius = sqrt(sx*sx+sy*sy); ndiam = __min(nx,(unsigned int)(ceil(2.0f*aD->roiRadius))+2); int_ratio(ndiam,wo,&ndiameter); fg->chunkWidth = ndiameter; nleft = (unsigned int)(floor(aD->new_xc - 0.5f*float(ndiameter) - 1.0f)); if (nleft + fg->chunkWidth > nx){ nleft = nx - fg->chunkWidth; } fg->chunkLeft = nleft; fg->xc = aD->new_xc - float(nleft); fg->numChunks = fg->ny/fg->vH; aD->to_nx = onx; aD->to_ny = ony; xd->vecX = ippsMalloc_32f(ont); xd->vecY = ippsMalloc_32f(ont); dps = double(ps); xmin = -0.5 * double(onx-1) * dps; ymin = -0.5 * double(ony-1) * dps; v1 = ippsMalloc_64f(onx); v2 = ippsMalloc_64f(onx); ippsVectorSlope_64f(v1,onx,xmin,dps); rat = double(aD->ta_ny_13-1)/pi; for(unsigned int i = 0; i<ony; i++){ yval = ymin + double(i)*dps; ippsSet_64f(yval,v2,onx); ippsConvert_64f32f(v1,xd->vecX+i*onx,onx); ippsConvert_64f32f(v2,xd->vecY+i*onx,onx); } ippsFree(v1); v1 = NULL; ippsFree(v2); v2 = NULL; xd->vto = ippsMalloc_32f(onx*ony); if(xd->vto == NULL){ printError(aD, "can not allocate memory (output matrix)"); return false; } vH = gi->vertH; if(!form_filter(aD))return false; xd->veccF = ippsMalloc_32fc(nx*vH); Ipp32f *vz = ippsMalloc_32f(nx); ippsZero_32f(vz, nx); ippsRealToCplx_32f(xd->vfilter, vz, xd->veccF, nx); for(unsigned int i=1; i<vH; i++){ ippsCopy_32fc(xd->veccF, xd->veccF + i*nx, nx); } ippsFree(vz); vz = NULL; return true; } bool fbp_gpu_cpu2_fs(allData *aD){ xData *xd; xFBP_gpu *fg; gpu_info *gi; xRoi *xr; unsigned int onx, ony, wo, ho, ny, nx; double angleStart, angleStep; unsigned int ont; unsigned int ndiam, ndiameter, nleft; unsigned int vH; float sx, sy, ps; double dps, xmin, ymin, yval; double rat; Ipp64f *v1, *v2, *v3, *v4; xd = aD->data; fg = aD->fg; gi = aD->gi; fg->nx = aD->ta_nx; fg->ny = aD->ta_ny; fg->nxo = gi->mxo; fg->nyo = gi->myo; fg->blockWidth = gi->wo; fg->blockHeight = gi->ho; fg->vH = gi->vertH; nx = aD->ta_nx; ny = aD->ta_ny; xr = aD->hms->fbp->backprojection->roi; ps = gi->outputPixelSize; unsigned int na, nr, pol_a, pol_r; wo = gi->wo; ho = gi->ho; na = 2*aD->ta_ny_13 -1; int_ratio(na,wo,&pol_a); angleStart = pi*double(xr->angle)/180.0; angleStep = double(gi->rotAngleStep); v1 = ippsMalloc_64f(ny); v2 = ippsMalloc_64f(ny); xd->vecCos = ippsMalloc_32f(aD->ta_ny_13); ippsVectorSlope_64f(v1,ny,angleStart,angleStep); ippsCos_64f_A53(v1,v2,aD->ta_ny_13); ippsConvert_64f32f(v2,xd->vecCos,aD->ta_ny_13); ippsFree(v1); v1 = NULL; ippsFree(v2); v2 = NULL; onx = gi->mxo; ony = gi->myo; sx = 0.5f*ps * float(onx - 1); sy = 0.5f*ps * float(ony - 1); aD->roiRadius = sqrt(sx*sx+sy*sy); nr = (unsigned int)(ceil(aD->roiRadius/ps)+1.0f); int_ratio(nr,ho,&pol_r); xd->vecPol = ippsMalloc_32f(pol_r*pol_a); gi->pol_r = pol_r; gi->pol_a = pol_a; onx = gi->mxo; ony = gi->myo; xd->vto = ippsMalloc_32f(onx*ony); if(xd->vto == NULL){ printError(aD, "can not allocate memory (output matrix)"); return false; } vH = gi->vertH; if(!form_filter(aD))return false; xd->veccF = ippsMalloc_32fc(nx*vH); Ipp32f *vz = ippsMalloc_32f(nx); ippsZero_32f(vz, nx); ippsRealToCplx_32f(xd->vfilter, vz, xd->veccF, nx); for(unsigned int i=1; i<vH; i++){ ippsCopy_32fc(xd->veccF, xd->veccF + i*nx, nx); } ippsFree(vz); vz = NULL; return true; } bool fbp_gpu(allData *aD){ printTagStart(aD,"FilteredBackprojectionGPU"); #ifdef _ALGORITHM2 if(aD->isFirstSlice){ if(!fbp_gpu_20_fs(aD))return false; } if(!fbp_cuda_20(aD))return false; #elif _ALGORITHM_CPU_2 if(aD->isFirstSlice){ if(!fbp_gpu_cpu2_fs(aD))return false; } if(!fbp_cuda_cpu2(aD))return false; #else if(aD->isFirstSlice){ if(!fbp_gpu_fs(aD))return false; } if(!fbp_cuda(aD))return false; #endif printTagEnd(aD); return true; }
9,142
5,179
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include <stdlib.h> #include <stdio.h> #include <iostream> #include <gtest/gtest.h> #include "arrow/util/uri.h" #include "parquet/parquet_reader.h" #include "storage/storage.h" #include "storage/storage_factory.h" #include "test/gtest-util.h" namespace pegasus { TEST(ParquetReaderTest, Unit) { std::string partition_path = "hdfs://10.239.47.55:9000/genData1000/customer/part-00005-f6fb1ced-d4d4-4dac-a584-02e398d988b4-c000.snappy.parquet"; std::shared_ptr<StorageFactory> worker_storage_factory( new StorageFactory()); std::shared_ptr<Storage> worker_storage; ASSERT_OK(worker_storage_factory->GetStorage(partition_path, &worker_storage)); ASSERT_NE(nullptr, worker_storage); ASSERT_EQ(Storage::HDFS, worker_storage->GetStorageType()); std::shared_ptr<HdfsReadableFile> file; ASSERT_OK(std::dynamic_pointer_cast<HDFSStorage>(worker_storage) ->GetReadableFile(partition_path, &file)); parquet::ArrowReaderProperties properties = parquet::default_arrow_reader_properties(); // static parquet::ArrowReaderProperties properties; arrow::MemoryPool *pool = arrow::default_memory_pool(); std::unique_ptr<ParquetReader> parquet_reader(new ParquetReader(file, pool, properties)); std::shared_ptr<arrow::Schema> schema; ASSERT_OK(parquet_reader->GetSchema(&schema)); ASSERT_EQ(18, schema->num_fields()); std::shared_ptr<arrow::Table> table1; ASSERT_OK(parquet_reader->ReadParquetTable(&table1)); ASSERT_NE(nullptr, table1); ASSERT_EQ(18, table1->num_columns()); // ASSERT_EQ(144000, table1->num_rows()); std::shared_ptr<arrow::Table> table2; std::vector<int> column_indices; column_indices.push_back(0); ASSERT_OK(parquet_reader->ReadParquetTable(column_indices, &table2)); ASSERT_NE(nullptr, table2); ASSERT_EQ(1, table2->num_columns()); // ASSERT_EQ(144000, table2->num_rows()); std::shared_ptr<arrow::ChunkedArray> chunked_out1; ASSERT_OK(parquet_reader->ReadColumnChunk(0, 0, &chunked_out1)); // ASSERT_EQ(144000, chunked_out1->length()); // ASSERT_EQ(1, chunked_out1->num_chunks()); std::shared_ptr<arrow::ChunkedArray> chunked_out2; ASSERT_OK(parquet_reader->ReadColumnChunk(0, &chunked_out2, 2)); ASSERT_EQ(2, chunked_out2->length()); ASSERT_EQ(1, chunked_out2->num_chunks()); std::shared_ptr<arrow::ChunkedArray> chunked_out3; ASSERT_OK(parquet_reader->ReadColumnChunk(0, &chunked_out3)); // ASSERT_EQ(144000, chunked_out3->length()); // ASSERT_EQ(1, chunked_out3->num_chunks()); } } PEGASUS_TEST_MAIN();
3,316
1,229
// // Created by ZL on 2019-06-13. // #include "zqcnn_mtcnn_nchwc4.h" #include <android/log.h> #include <jni.h> #include <string> #include <vector> #include <imgproc/types_c.h> #define TAG "ZQCNN" #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,TAG,__VA_ARGS__) using namespace std; using namespace cv; using namespace ZQ; static MTCNNNCHWC *mtcnnnchwc; extern "C" { JNIEXPORT jboolean JNICALL Java_com_zl_demo_MTCNNNCHWC_initModelPath(JNIEnv *env, jobject instance, jstring modelPath_) { if (NULL == modelPath_) { return false; } //获取MTCNN模型的绝对路径的目录(不是/aaa/bbb.bin这样的路径,是/aaa/) const char *modelPath = env->GetStringUTFChars(modelPath_, 0); if (NULL == modelPath) { return false; } string tFaceModelDir = modelPath; string tLastChar = tFaceModelDir.substr(tFaceModelDir.length() - 1, 1); //目录补齐/ if ("\\" == tLastChar) { tFaceModelDir = tFaceModelDir.substr(0, tFaceModelDir.length() - 1) + "/"; } else if (tLastChar != "/") { tFaceModelDir += "/"; } LOGD("init, tFaceModelDir=%s", tFaceModelDir.c_str()); mtcnnnchwc = new MTCNNNCHWC(tFaceModelDir); return true; } JNIEXPORT jfloatArray JNICALL Java_com_zl_demo_MTCNNNCHWC_detectFace(JNIEnv *env, jobject instance, jstring imgPath_) { const char *imgPath = env->GetStringUTFChars(imgPath_, 0); vector<ZQ_CNN_BBox> faceInfo = mtcnnnchwc->detect(imgPath); int32_t num_face = static_cast<int32_t>(faceInfo.size()); LOGD("检测到的人脸数目:%d\n", num_face); int out_size = 1 + num_face * 29; float *faces = new float[out_size]; faces[0] = num_face; for (int i = 0; i < num_face; i++) { float score = faceInfo[i].score; int row1 = faceInfo[i].row1; int col1 = faceInfo[i].col1; int row2 = faceInfo[i].row2; int col2 = faceInfo[i].col2; LOGD("faceInfo:score=%.3f;row1=%d,col1=%d,row2=%d,col2=%d\n", score, row1, col1, row2, col2); } jfloatArray tFaces = env->NewFloatArray(out_size); env->SetFloatArrayRegion(tFaces, 0, out_size, faces); return tFaces; } JNIEXPORT jobjectArray JNICALL Java_com_zl_demo_MTCNNNCHWC_detect(JNIEnv *env, jobject instance, jbyteArray yuv, jint width, jint height) { jobjectArray faceArgs = nullptr; jbyte *pBuf = (jbyte *) env->GetByteArrayElements(yuv, 0); Mat image(height + height / 2, width, CV_8UC1, (unsigned char *) pBuf); Mat mBgr; cvtColor(image, mBgr, CV_YUV2BGR_NV21); vector<ZQ_CNN_BBox> faceInfo = mtcnnnchwc->detectMat(mBgr); int32_t num_face = static_cast<int32_t>(faceInfo.size()); /** * 获取Face类以及其对于参数的签名 */ jclass faceClass = env->FindClass("com/zl/demo/FaceInfo");//获取Face类 jmethodID faceClassInitID = (env)->GetMethodID(faceClass, "<init>", "()V"); jfieldID faceScore = env->GetFieldID(faceClass, "score", "F");//获取int类型参数confidence jfieldID faceRect = env->GetFieldID(faceClass, "faceRect", "Landroid/graphics/Rect;");//获取faceRect的签名 /** * 获取RECT类以及对应参数的签名 */ jclass rectClass = env->FindClass("android/graphics/Rect");//获取到RECT类 jmethodID rectClassInitID = (env)->GetMethodID(rectClass, "<init>", "()V"); jfieldID rect_left = env->GetFieldID(rectClass, "left", "I");//获取x的签名 jfieldID rect_top = env->GetFieldID(rectClass, "top", "I");//获取y的签名 jfieldID rect_right = env->GetFieldID(rectClass, "right", "I");//获取width的签名 jfieldID rect_bottom = env->GetFieldID(rectClass, "bottom", "I");//获取height的签名 faceArgs = (env)->NewObjectArray(num_face, faceClass, 0); LOGD("检测到的人脸数目:%d\n", num_face); for (int i = 0; i < num_face; i++) { float score = faceInfo[i].score; int row1 = faceInfo[i].row1; int col1 = faceInfo[i].col1; int row2 = faceInfo[i].row2; int col2 = faceInfo[i].col2; jobject newFace = (env)->NewObject(faceClass, faceClassInitID); jobject newRect = (env)->NewObject(rectClass, rectClassInitID); (env)->SetIntField(newRect, rect_left, row1); (env)->SetIntField(newRect, rect_top, col1); (env)->SetIntField(newRect, rect_right, row2); (env)->SetIntField(newRect, rect_bottom, col2); (env)->SetObjectField(newFace, faceRect, newRect); (env)->SetFloatField(newFace, faceScore, score); (env)->SetObjectArrayElement(faceArgs, i, newFace); } free(pBuf); return faceArgs; } }
4,532
1,813
#include <stdio.h> #include <algorithm> using namespace std; const int MAXN = 128; int A[MAXN][MAXN], B[MAXN][MAXN], n; int mark[MAXN][MAXN]; void print(char c) { printf("%c\n", c); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) if (mark[i][j]) printf("%d %d\n", i, j); } } void solve() { for (int i = 0; i < n; i++) { int sum = 0, l, r; for (int j = 0; j < n; j++) sum += A[i][j]; l = 0, r = sum; for (int j = 0; j < n; j++) { r -= A[i][j]; mark[i][j] = (l == r); l += A[i][j]; } } print('H'); for (int i = 0; i < n; i++) { int sum = 0, l, r; for (int j = 0; j < n; j++) sum += A[j][i]; l = 0, r = sum; for (int j = 0; j < n; j++) { r -= A[j][i]; mark[j][i] = (l == r); l += A[j][i]; } } print('V'); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i-1 >= 0 && j-1 >= 0) B[i][j] = B[i-1][j-1] + A[i][j]; else B[i][j] = A[i][j]; } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int l = 0, r = 0; if (i-1 >= 0 && j-1 >= 0) l = B[i-1][j-1]; int ex, ey; ex = i + min(n-1-i, n-1-j), ey = j + min(n-1-i, n-1-j); r = B[ex][ey] - l - A[i][j]; mark[i][j] = (l == r); } } print('D'); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i-1 >= 0 && j+1 < n) B[i][j] = B[i-1][j+1] + A[i][j]; else B[i][j] = A[i][j]; } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int l = 0, r = 0; if (i-1 >= 0 && j+1 < n) l = B[i-1][j+1]; int ex, ey; ex = i + min(n-1-i, j), ey = j - min(n-1-i, j); r = B[ex][ey] - l - A[i][j]; mark[i][j] = (l == r); } } print('A'); } int main() { int testcase; scanf("%d", &testcase); while (testcase--) { scanf("%d", &n); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) scanf("%d", &A[i][j]); solve(); } return 0; } /* 3 3 1 2 3 4 5 6 7 8 9 3 1 1 1 1 1 1 1 1 1 4 5 7 7 6 2 4 0 8 6 1 0 7 6 8 7 5 */
1,980
1,240
#include "FunctionsStringSearch.h" #include "FunctionFactory.h" #include "MatchImpl.h" namespace DB { namespace { struct NameILike { static constexpr auto name = "ilike"; }; using ILikeImpl = MatchImpl<NameILike, MatchTraits::Syntax::Like, MatchTraits::Case::Insensitive, MatchTraits::Result::DontNegate>; using FunctionILike = FunctionsStringSearch<ILikeImpl>; } void registerFunctionILike(FunctionFactory & factory) { factory.registerFunction<FunctionILike>(); } }
481
155
// 00000011111111112222222222333333333344444444445555555555666666666677777777778 // 45678901234567890123456789012345678901234567890123456789012345678901234567890 // // File Name : addStrings.cpp // File Type : Source code // Purpose : Main program (Adding two strings). // // Date : 2017-02-23 // Version : 1.0.0 // Copyrights : FRCC // // Author : Mohammad Huwaidi // E-Mail : Mohammad.Huwaidi@frontrange.edu // Style : http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml // Document : http://www.stack.nl/~dimitri/doxygen/index.html // // 00000011111111112222222222333333333344444444445555555555666666666677777777778 // 45678901234567890123456789012345678901234567890123456789012345678901234567890 // // // Define the PAUSE depending on the operating system: // Do not worry about this code until where HERE is written #if defined(_WIN32) || defined(WIN32) // Windows machine #include <windows.h> #define PAUSE "pause" // The pause command for DOS window. #else // Unix-based machines // Following is the pause command for the BASH script that runs on UNIX: #define PAUSE "read -p 'Press [Enter] key to continue ...'" #endif // HERE // C++ include files: #include <iostream> // I/O manipulation; e.g., cout. #include <string> // String types and operations. using namespace std; // 0000001111111111222222222233333333334444444444555555555566666666667777777777 // 4567890123456789012345678901234567890123456789012345678901234567890123456789 // // The main function that is invoked by the operating system. // int main(int argc, char * argv[]) { // Define some variables. It is a good idea to make them constants if they // will not be modified later in the program. string fname; string lname; cout << "What is your first name?" << endl; cin >> fname; cout << "Now your last name." << endl; cin >> lname; const string first_name = fname; // Define and initialize the 1st name. const string last_name = lname; // Define and initialize the last name. const string full_name = first_name + string(" ") + last_name; // Combine the two names cout << "Your name is " << first_name + last_name << endl; cout << "Full name is " << full_name << endl; //system(PAUSE); // Pause for the user so the window doesn't disappear. return 0; // Since nothing went wrong, go back to the OS normally. }
2,449
1,083
#include "catch.hpp" #include "isBalanced.hpp" namespace BT = BinaryTreeUnique; TEST_CASE("isBalanced test", "[isBalanced]") { auto tree = BT::create("[]"); REQUIRE(isBalanced(tree) == true); tree = BT::create("[1]"); REQUIRE(isBalanced(tree) == true); tree = BT::create("[1,2]"); REQUIRE(isBalanced(tree) == true); tree = BT::create("[1,null,2]"); REQUIRE(isBalanced(tree) == true); tree = BT::create("[1,2,3]"); REQUIRE(isBalanced(tree) == false); tree = BT::create("[1,2,3,null,null,4]"); REQUIRE(isBalanced(tree) == false); tree = BT::create("[1,2,3,null,null,null,4]"); REQUIRE(isBalanced(tree) == true); }
648
290
#ifndef ENGINE_HPP #define ENGINE_HPP #include <iostream> #include <sstream> #include <string> #include <map> #include "Command.hpp" #include "Argument.hpp" namespace gtp { /** * Defines a function that may be registered to the GTP Engine. * When an engine recives the corresponding Command, the registered * function will be called. This function should return the string * representing the result of the function, it will then be output by the * Engine (including any additional data needed by the controller). */ typedef std::string (*ProcCmd)(const ARG_LIST&); /** * An engine for the Go Text Protocol. * An instance of this class may be used to communicate between * with the go server that maintains the current game. */ class Engine { public: /** * Constructs an Engine by registering the default implementation * for each supported command. */ Engine(); /** * Main game loop for the engine. * This will read and execute commands from the given input stream * until either an EOF is sent or the 'quit' command is given. * \param is Input stream to read commands from. */ void play(std::istream &is); /** * Read and execute a single command from the input stream. * \param is Input stream to read a command from. */ void proc_command(std::istream &is); /** * Registers the input proc to the given command. * Whenever that command is received from the controller, * the proc function will be executed with the arguments * as supplied by the controller. * If a proccess is already registered to the input Command, * that process will be overridden. * \param cmd Command to register the input proc to. * \param proc The process to execute on receiving the given command. */ void register_proc(Command cmd, const ProcCmd &proc); private: std::map<Command,ProcCmd> commands; /** * Parse all arguments from the input line, given the type of argument that will be parsed. * \param cmd Type of command to parse arguments for. * \param iss Input string stream of the line being parsed. * \return Array of pointers to argument objects. */ ARG_LIST args_for_cmd(const Command &cmd, std::istringstream &iss); /** * Performs preprocessing on a line of text. * The following operation are performed in accordance with the GTP specification. * 1. Remove all occurences of CR and other control characters except for HT and LF. * 2. For each line with a hash sign (#), remove all text following and including this characeter. * 3. Convert all occurences of HT to SPACE. * 4. Discard any empty or white-space only lines. * \param line to the line to be processed. * \return Processed version of the input string. */ std::string preproc_line(const std::string &line); /** * \param The line in question. * \return Should this line be ignored? */ bool ignore_line(const std::string &line); }; } #endif
2,901
821
//#include "Triangle.hpp" //#include "rasterizer.hpp" //#include <eigen3/Eigen/Eigen> //#include <iostream> //#include <opencv2/opencv.hpp> ///* //constexpr double MY_PI = 3.1415926; // //Eigen::Matrix4f get_view_matrix(Eigen::Vector3f eye_pos) //{ // Eigen::Matrix4f view = Eigen::Matrix4f::Identity(); // // Eigen::Matrix4f translate; // translate << 1, 0, 0, -eye_pos[0], // 0, 1, 0, -eye_pos[1], // 0, 0, 1, -eye_pos[2], // 0, 0, 0, 1; // // view = translate * view; // // return view; //} // //Eigen::Matrix4f get_model_matrix(float rotation_angle) //{ // Eigen::Matrix4f model = Eigen::Matrix4f::Identity(); // // // TODO: Implement this function // // Create the model matrix for rotating the triangle around the Z axis. // // Then return it. // double theta = rotation_angle / 180.0 * MY_PI; // // model << std::cos(theta), std::sin(theta), 0, 0, // -std::sin(theta), std::cos(theta), 0, 0, // 0, 0, 1, 0, // 0, 0, 0, 1; // // return model; //} // //Eigen::Matrix4f get_projection_matrix(float eye_fov, float aspect_ratio, // float zNear, float zFar) //{ // // Students will implement this function // // Eigen::Matrix4f projection = Eigen::Matrix4f::Identity(); // // // TODO: Implement this function // // Create the projection matrix for the given parameters. // // Then return it. // // // Transformation matrix of perspective projection to orthographic projection // Eigen::Matrix4f PerspToOrth; // PerspToOrth << zNear, 0, 0, 0, // 0, zNear, 0, 0, // 0, 0, zNear + zFar, -zNear * zFar, // 0, 0, 0, 1; // // // Tan(fov/2) = height/2, aspect = weight / height // float Height = std::atan(eye_fov / 2 / 180 * MY_PI) * 2; // float Width = aspect_ratio * Height; // // Eigen::Matrix4f ViewPort; // ViewPort << Width / 2, 0, 0, Width / 2, // 0, Height / 2, 0, Height / 2, // 0, 0, 1, 0, // 0, 0, 0, 1; // // projection = ViewPort * PerspToOrth; // // return projection; //} // //Eigen::Matrix4f get_rotation(Vector3f axis, float angle) //{ // // https://www.bilibili.com/read/cv11925407 // Eigen::Matrix4f model = Eigen::Matrix4f::Identity(); // angle = angle / 180.f * MY_PI; // axis.normalize(); // /* // float = square = axis[0]*axis[0] + axis[1]*axis[1] + axis[2]*axis[2]; // axis[0] /= std::sqrt(square); // axis[1] /= std::sqrt(square); // axis[2] /= std::sqrt(square); // // Eigen::Matrix3f k; // k << 0.f, -axis[2], axis[1], // axis[2], 0.f, -axis[0], // -axis[1], axis[0], 0.f; // Eigen::Matrix3f E = Eigen::Matrix3f::Identity(); // Eigen::Matrix3f rotation_matrix; // rotation_matrix = E * std::cos(angle) + std::sin(angle) * k + (1 - std::cos(angle)) * axis * axis.transpose(); // // model.block<3, 3>(0, 0) = rotation_matrix; // return model; // //} // // //int main(int argc, const char** argv) //{ // float angle = 45.0f; // Eigen::Vector3f axis(0, 0, 1); // bool command_line = false; // std::string filename = "output.png"; // // if (argc >= 3) { // command_line = true; // angle = std::stof(argv[2]); // -r by default // if (argc == 4) { // filename = std::string(argv[3]); // } // } // // rst::rasterizer r(700, 700); // // Eigen::Vector3f eye_pos = { 0, 0, 5 }; // // std::vector<Eigen::Vector3f> pos{ {2, 0, -2}, {0, 2, -2}, {-2, 0, -2} }; // // std::vector<Eigen::Vector3i> ind{ {0, 1, 2} }; // // auto pos_id = r.load_positions(pos); // auto ind_id = r.load_indices(ind); // // int key = 0; // int frame_count = 0; // // if (command_line) { // r.clear(rst::Buffers::Color | rst::Buffers::Depth); // // r.set_model(get_model_matrix(angle)); // r.set_view(get_view_matrix(eye_pos)); // r.set_projection(get_projection_matrix(45, 1, 0.1, 50)); // // r.draw(pos_id, ind_id, rst::Primitive::Triangle); // cv::Mat image(700, 700, CV_32FC3, r.frame_buffer().data()); // image.convertTo(image, CV_8UC3, 1.0f); // // cv::imwrite(filename, image); // // return 0; // } // // while (key != 27) { // r.clear(rst::Buffers::Color | rst::Buffers::Depth); // // //r.set_model(get_rotation(axis, angle)); // // r.set_model(get_model_matrix(angle)); // r.set_view(get_view_matrix(eye_pos)); // r.set_projection(get_projection_matrix(45, 1, 0.1, 50)); // // r.draw(pos_id, ind_id, rst::Primitive::Triangle); // // cv::Mat image(700, 700, CV_32FC3, r.frame_buffer().data()); // image.convertTo(image, CV_8UC3, 1.0f); // cv::imshow("image", image); // key = cv::waitKey(10); // // std::cout << "frame count: " << frame_count++ << '\n'; // // if (key == 'a') { // angle += 10; // } // else if (key == 'd') { // angle -= 10; // } // } // // return 0; //} //*/
4,524
2,116
#include "SpriteBatch.h" namespace prb { void SpriteBatch::init() { vao = { { { {}, 4 } } }; //this probably leaks memory if you reinitialize the spritebatch sh = { "assets/shaders/spritebatch.vert", "assets/shaders/spritebatch.frag" }; } SpriteBatch::SpriteBatch() {} SpriteBatch::SpriteBatch(Sprite const& atlas) : atlas(atlas) { init(); } void SpriteBatch::draw(Sprite const& s, vec2 const& txmin, vec2 const& txmax, mat3 const& transform) { if (s.tex.texID != atlas.tex.texID) flushAndClear(); vec2 v0 = transform * vec2(-1.f, -1.f); vec2 v1 = transform * vec2(-1.f, 1.f); vec2 v2 = transform * vec2(1.f, 1.f); vec2 v3 = transform * vec2(1.f, -1.f); if (data.size() < curFloat + 3 * 2 * 4) data.resize(curFloat + 3 * 2 * 4); data[curFloat++] = v0.x; data[curFloat++] = v0.y; data[curFloat++] = txmin.x; data[curFloat++] = txmin.y; data[curFloat++] = v1.x; data[curFloat++] = v1.y; data[curFloat++] = txmin.x; data[curFloat++] = txmax.y; data[curFloat++] = v2.x; data[curFloat++] = v2.y; data[curFloat++] = txmax.x; data[curFloat++] = txmax.y; data[curFloat++] = v2.x; data[curFloat++] = v2.y; data[curFloat++] = txmax.x; data[curFloat++] = txmax.y; data[curFloat++] = v3.x; data[curFloat++] = v3.y; data[curFloat++] = txmax.x; data[curFloat++] = txmin.y; data[curFloat++] = v0.x; data[curFloat++] = v0.y; data[curFloat++] = txmin.x; data[curFloat++] = txmin.y; } void SpriteBatch::draw(Sprite const& s, Sprite::AnimationPlayer const& sa, mat3 const& transform) { vec2 offset = s.getOffset(sa) / s.tex.size; draw(s, offset, offset + s.size / s.tex.size, transform); } void SpriteBatch::draw(Sprite const& s, mat3 const& transform) { draw(s, 0.f, 1.f, transform); } void SpriteBatch::flush() { vao.vbos[0].setData(data, curFloat); sh.use(); sh.setUniform("transform", transform); sh.setUniform("tex", 0); util::bindTexture(0, atlas.tex.texID); vao.draw(); sh.release(); } void SpriteBatch::clear() { curFloat = 0; } void SpriteBatch::flushAndClear() { flush(); clear(); } }
2,040
886
// Copyright Heikki Berg 2017 - 2018 // Distributed under the Boost Software License, Version 1.0. // (See accompanying file ../../LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <random> #include <gtest/gtest.h> #include <dsp/complex.h> #include <dsp/dsp_types.h> #include <dsp/virtual_float.h> TEST(virtual_float, creation) { { cnl::dsp::virtual_float<float> val{1.0f}; float val_float = static_cast<float>(val); EXPECT_EQ(val_float, 1.0f); } { cnl::dsp::virtual_float<float> val{7.0f}; float val_float = static_cast<float>(val); EXPECT_EQ(val_float, 7.0f); } { q4_20 val{2.0f}; cnl::dsp::virtual_float<q4_20> valvf{val}; EXPECT_EQ(static_cast<float>(valvf), 2.0f); EXPECT_EQ(static_cast<float>(valvf.mantissa()), 2.0f); EXPECT_EQ(valvf.exponent(), 0); } { q4_20 val{7.0f}; cnl::dsp::virtual_float<q4_20> valvf{val}; EXPECT_EQ(static_cast<float>(valvf), 7.0f); EXPECT_EQ(static_cast<float>(valvf.mantissa()), 3.5f); EXPECT_EQ(valvf.exponent(), 1); } { q8_40 val{7.0f}; cnl::dsp::virtual_float<q8_40> valvf{val}; EXPECT_EQ(static_cast<float>(valvf), 7.0f); EXPECT_EQ(static_cast<float>(valvf.mantissa()), 3.5f); EXPECT_EQ(valvf.exponent(), 1); } { cnl::dsp::virtual_float<q4_20> val{3.0f}; cnl::dsp::virtual_float<q4_20> valvf{val}; EXPECT_EQ(static_cast<float>(valvf), 3.0f); EXPECT_EQ(static_cast<float>(valvf.mantissa()), 3.0f); EXPECT_EQ(valvf.exponent(), 0); } { cnl::dsp::virtual_float<q4_20> val{3.0f}; cnl::dsp::virtual_float<q4_20> valvf{std::move(val)}; EXPECT_EQ(static_cast<float>(valvf), 3.0f); EXPECT_EQ(static_cast<float>(valvf.mantissa()), 3.0f); EXPECT_EQ(valvf.exponent(), 0); } } TEST(virtual_float, sum) { { cnl::dsp::virtual_float<float> f1(1.0f); cnl::dsp::virtual_float<float> f2(2.0f); cnl::dsp::virtual_float<float> f = f1 + f2; EXPECT_EQ(static_cast<float>(f), 3.0f); } { cnl::dsp::virtual_float<q4_20> f1{1.0f}; cnl::dsp::virtual_float<q4_20> f2{2.0f}; cnl::dsp::virtual_float<q4_20> f = f1 + f2; EXPECT_EQ(static_cast<float>(f1), 1.0f); EXPECT_EQ(static_cast<float>(f2), 2.0f); EXPECT_EQ(static_cast<float>(f), 3.0f); } { cnl::dsp::virtual_float<q8_40> f1{1.0f}; cnl::dsp::virtual_float<q8_40> f2{2.0f}; cnl::dsp::virtual_float<q8_40> f = f1 + f2; EXPECT_EQ(static_cast<float>(f1), 1.0f); EXPECT_EQ(static_cast<float>(f2), 2.0f); EXPECT_EQ(static_cast<float>(f), 3.0f); } } TEST(virtual_float, subtract) { { cnl::dsp::virtual_float<float> f1(1.0f); cnl::dsp::virtual_float<float> f2(2.0f); cnl::dsp::virtual_float<float> f = f1 - f2; EXPECT_EQ(static_cast<float>(f), -1.0f); } { cnl::dsp::virtual_float<q4_20> f1{1.0f}; cnl::dsp::virtual_float<q4_20> f2{2.0f}; cnl::dsp::virtual_float<q4_20> f = f1 - f2; EXPECT_EQ(static_cast<float>(f), -1.0f); } { cnl::dsp::virtual_float<q8_40> f1{1.0f}; cnl::dsp::virtual_float<q8_40> f2{2.0f}; cnl::dsp::virtual_float<q8_40> f = f1 - f2; EXPECT_EQ(static_cast<float>(f), -1.0f); } } TEST(virtual_float, negate) { { cnl::dsp::virtual_float<q4_20> f1{1.0f}; cnl::dsp::virtual_float<q4_20> f = -f1; EXPECT_EQ(static_cast<float>(f), -1.0f); } { cnl::dsp::virtual_float<q8_40> f1{1.0f}; cnl::dsp::virtual_float<q8_40> f = -f1; EXPECT_EQ(static_cast<float>(f), -1.0f); } } TEST(virtual_float, multiply) { { cnl::dsp::virtual_float<q4_20> f1{1.0f}; cnl::dsp::virtual_float<q4_20> f2{2.0f}; cnl::dsp::virtual_float<q4_20> f = f1 * f2; EXPECT_EQ(static_cast<float>(f), 2.0f); } { cnl::dsp::virtual_float<q4_20> f1{0.125f}; cnl::dsp::virtual_float<q4_20> f2{2.0f}; cnl::dsp::virtual_float<q4_20> f = f1 * f2; EXPECT_EQ(static_cast<float>(f), 0.250f); } { cnl::dsp::virtual_float<q4_20> f1{0.34561825f}; cnl::dsp::virtual_float<q4_20> f2{1.5678196f}; cnl::dsp::virtual_float<q4_20> f = f1 * f2; EXPECT_FLOAT_EQ(static_cast<float>(f), 0.54186706f); } { cnl::dsp::virtual_float<q8_40> f1{1.0f}; cnl::dsp::virtual_float<q8_40> f2{2.0f}; cnl::dsp::virtual_float<q8_40> f = f1 * f2; EXPECT_EQ(static_cast<float>(f), 2.0f); } { cnl::dsp::virtual_float<q8_40> f1{0.34561825f}; cnl::dsp::virtual_float<q8_40> f2{1.5678196f}; cnl::dsp::virtual_float<q8_40> f = f1 * f2; EXPECT_FLOAT_EQ(static_cast<float>(f), 0.54186706f); } } TEST(virtual_float, division) { { cnl::dsp::virtual_float<q4_20> f1{1.0f}; cnl::dsp::virtual_float<q4_20> f2{2.0f}; cnl::dsp::virtual_float<q4_20> f = f1 / f2; EXPECT_EQ(static_cast<float>(f), 0.5f); } { cnl::dsp::virtual_float<q4_20> f1{0.125f}; cnl::dsp::virtual_float<q4_20> f2{2.0f}; cnl::dsp::virtual_float<q4_20> f = f1 / f2; EXPECT_EQ(static_cast<float>(f), 0.0625f); } { cnl::dsp::virtual_float<q4_20> f1{0.34561825f}; cnl::dsp::virtual_float<q4_20> f2{1.5678196f}; cnl::dsp::virtual_float<q4_20> f = f1 / f2; EXPECT_FLOAT_EQ(static_cast<float>(f), 0.22044516f); } { cnl::dsp::virtual_float<q8_40> f1{0.34561825f}; cnl::dsp::virtual_float<q8_40> f2{1.5678196f}; cnl::dsp::virtual_float<q8_40> f = f1 / f2; EXPECT_FLOAT_EQ(static_cast<float>(f), 0.22044516f); } } TEST(virtual_float, assignment) { { cnl::dsp::virtual_float<float> e = 2.0f; EXPECT_EQ(static_cast<float>(e), 2.0f); } { cnl::dsp::virtual_float<q4_20> e = q4_20{3.0f}; EXPECT_EQ(static_cast<float>(e), 3.0f); } { cnl::dsp::virtual_float<q4_20> f = q4_20{3.0f}; cnl::dsp::virtual_float<q8_40> e = f; EXPECT_EQ(static_cast<float>(e), 3.0f); } { cnl::dsp::virtual_float<q8_40> f = q8_40{3.0f}; cnl::dsp::virtual_float<q4_20> e = f; EXPECT_EQ(static_cast<float>(e), 3.0f); } } TEST(virtual_float, comparison) { { cnl::dsp::virtual_float<float> a{1.0f}; cnl::dsp::virtual_float<float> b{0.0f}; EXPECT_TRUE(a > b); EXPECT_TRUE(a >= b); EXPECT_FALSE(b > a); EXPECT_FALSE(b >= a); EXPECT_TRUE(b < a); EXPECT_TRUE(b <= a); EXPECT_FALSE(a < b); EXPECT_FALSE(a <= b); EXPECT_FALSE(a < a); EXPECT_FALSE(a > a); EXPECT_TRUE(a >= a); EXPECT_TRUE(a <= a); EXPECT_TRUE(a == a); EXPECT_FALSE(a != a); EXPECT_TRUE(a != b); EXPECT_TRUE(b != a); } { cnl::dsp::virtual_float<q4_20> a{2.0f}; cnl::dsp::virtual_float<q4_20> b{1.0f}; EXPECT_TRUE(a > b); EXPECT_TRUE(a >= b); EXPECT_FALSE(b > a); EXPECT_FALSE(b >= a); EXPECT_TRUE(b < a); EXPECT_TRUE(b <= a); EXPECT_FALSE(a < b); EXPECT_FALSE(a <= b); EXPECT_FALSE(a < a); EXPECT_FALSE(a > a); EXPECT_TRUE(a >= a); EXPECT_TRUE(a <= a); EXPECT_TRUE(a == a); EXPECT_FALSE(a != a); EXPECT_TRUE(a != b); EXPECT_TRUE(b != a); } { cnl::dsp::virtual_float<q8_40> a{2.0f}; cnl::dsp::virtual_float<q8_40> b{1.0f}; EXPECT_TRUE(a > b); EXPECT_TRUE(a >= b); EXPECT_FALSE(b > a); EXPECT_FALSE(b >= a); EXPECT_TRUE(b < a); EXPECT_TRUE(b <= a); EXPECT_FALSE(a < b); EXPECT_FALSE(a <= b); EXPECT_FALSE(a < a); EXPECT_FALSE(a > a); EXPECT_TRUE(a >= a); EXPECT_TRUE(a <= a); EXPECT_TRUE(a == a); EXPECT_FALSE(a != a); EXPECT_TRUE(a != b); EXPECT_TRUE(b != a); } } TEST(virtual_float, square_root) { { cnl::dsp::virtual_float<float> a{1.0f}; cnl::dsp::virtual_float<float> b = sqrt(a); EXPECT_EQ(static_cast<float>(b), 1.0f); } { cnl::dsp::virtual_float<float> a{2.0f}; cnl::dsp::virtual_float<float> b = sqrt(a); EXPECT_EQ(static_cast<float>(b), std::sqrt(2.0f)); } { cnl::dsp::virtual_float<q4_20> a{2.0f}; EXPECT_EQ(static_cast<float>(a), 2.0f); cnl::dsp::virtual_float<q4_20> b = sqrt(a); EXPECT_FLOAT_EQ(static_cast<float>(b), std::sqrt(2.0f)); } { cnl::dsp::virtual_float<q4_20> a{3.5783958f}; EXPECT_FLOAT_EQ(static_cast<float>(a), 3.5783958f); cnl::dsp::virtual_float<q4_20> b = sqrt(a); EXPECT_FLOAT_EQ(static_cast<float>(b), std::sqrt(3.5783958f)); } { cnl::dsp::virtual_float<q4_20> a{1.349885940551758f}; EXPECT_FLOAT_EQ(static_cast<float>(a), 1.349885940551758f); cnl::dsp::virtual_float<q4_20> b = sqrt(a); EXPECT_NEAR(static_cast<float>(b), std::sqrt(1.349885940551758f), 0.00001); } #if defined(CNL_INT128_ENABLED) { cnl::dsp::virtual_float<q8_40> a{1.349885940551758f}; EXPECT_FLOAT_EQ(static_cast<float>(a), 1.349885940551758f); cnl::dsp::virtual_float<q8_40> b = sqrt(a); EXPECT_NEAR(static_cast<float>(b), std::sqrt(1.349885940551758f), 0.00001); } #endif } TEST(virtual_float, from_virtual_float) { { cnl::dsp::virtual_float<q4_20> a{2.0f}; q4_20 b = static_cast<q4_20>(a); EXPECT_EQ(static_cast<float>(b), 2.0f); } { cnl::dsp::virtual_float<q8_40> a{2.0f}; q8_40 b = static_cast<q8_40>(a); EXPECT_EQ(static_cast<float>(b), 2.0f); } { cnl::dsp::virtual_float<q8_40> a{2.0f}; q4_20 b = static_cast<q4_20>(a); EXPECT_EQ(static_cast<float>(b), 2.0f); } { cnl::dsp::virtual_float<q8_40> a{2.0f}; cnl::dsp::virtual_float<q4_20> b = static_cast<q4_20>(a); EXPECT_EQ(static_cast<float>(b), 2.0f); } } TEST(virtual_float, cumulative_sum_q4_20) { std::mt19937 mt(91); std::uniform_real_distribution<float> fdist(-0.5, 0.5); double float_sum(0); cnl::dsp::virtual_float<q4_20> vf_sum(0.0); for (unsigned int loop = 0; loop < 1000; loop++) { q4_20 efxp_num = static_cast<q4_20>(fdist(mt)); double float_num = static_cast<double>(efxp_num); cnl::dsp::virtual_float<q4_20> vfe_num = efxp_num; ASSERT_FLOAT_EQ(static_cast<float>(vfe_num), static_cast<float>(float_num)); float_sum += float_num; vf_sum += vfe_num; EXPECT_NEAR(static_cast<float>(float_sum), static_cast<float>(vf_sum), 5e-4f); } } TEST(virtual_float, cumulative_sum_q8_40) { std::mt19937 mt(91); std::uniform_real_distribution<float> fdist(-0.5, 0.5); double float_sum(0); cnl::dsp::virtual_float<q8_40> vf_sum(0.0); for (unsigned int loop = 0; loop < 1000000; loop++) { q8_40 efxp_num = static_cast<q8_40>(fdist(mt)); double float_num = static_cast<double>(efxp_num); cnl::dsp::virtual_float<q8_40> vfe_num = efxp_num; ASSERT_FLOAT_EQ(static_cast<float>(vfe_num), static_cast<float>(float_num)); float_sum += float_num; vf_sum += vfe_num; EXPECT_NEAR(static_cast<float>(float_sum), static_cast<float>(vf_sum), 1e-7f); } }
11,701
5,546
#include <iostream> #include <fstream> #include <string> #include <sstream> #include <iomanip> #include <stdexcept> #include "opencv2/gpu/gpu.hpp" #include "opencv2/highgui/highgui.hpp" using namespace std; using namespace cv; /** Contains all properties of application (including those which can be changed by user in runtime) */ class Settings { public: /** Sets default values */ Settings(); /** Reads settings from command args */ static Settings Read(int argc, char** argv); string src; bool src_is_video; bool make_gray; bool resize_src; double resize_src_scale; double scale; int nlevels; int gr_threshold; double hit_threshold; int win_width; int win_stride_width; int win_stride_height; bool gamma_corr; }; /** Describes aplication logic */ class App { public: /** Initializes application */ App(const Settings& s); /** Runs demo using OpenCV highgui module for GUI building */ void RunOpencvGui(); /** Processes user keybord input */ void HandleKey(char key); void HogWorkBegin(); void HogWorkEnd(); double HogWorkFps() const; void WorkBegin(); void WorkEnd(); double WorkFps() const; const string GetPerformanceSummary() const; private: App operator=(App&); Settings settings; bool running; bool use_gpu; bool make_gray; double scale; int gr_threshold; int nlevels; double hit_threshold; bool gamma_corr; int64 hog_work_begin; double hog_work_fps; int64 work_begin; double work_fps; }; int main(int argc, char** argv) { try { if (argc < 2) { cout << "Usage:\nsample_hog\n" << " -src <path_to_the_source>\n" << " [-src_is_video <true/false>] # says to interp. src as img or as video\n" << " [-make_gray <true/false>] # convert image to gray one or not\n" << " [-resize_src <true/false>] # do resize of the source image or not\n" << " [-resize_src_scale <double>] # preprocessing image scale factor\n" << " [-hit_threshold <double>] # classifying plane dist. threshold (0.0 usually)\n" << " [-scale <double>] # HOG window scale factor\n" << " [-nlevels <int>] # max number of HOG window scales\n" << " [-win_width <int>] # width of the window (48 or 64)\n" << " [-win_stride_width <int>] # distance by OX axis between neighbour wins\n" << " [-win_stride_height <int>] # distance by OY axis between neighbour wins\n" << " [-gr_threshold <int>] # merging similar rects constant\n" << " [-gamma_corr <int>] # do gamma correction or not\n"; return 1; } App app(Settings::Read(argc, argv)); app.RunOpencvGui(); } catch (const Exception& e) { return cout << "Error: " << e.what() << endl, 1; } catch (const exception& e) { return cout << "Error: " << e.what() << endl, 1; } catch(...) { return cout << "Unknown exception" << endl, 1; } return 0; } Settings::Settings() { src_is_video = false; make_gray = false; resize_src = true; resize_src_scale = 1.5; scale = 1.05; nlevels = 13; gr_threshold = 8; hit_threshold = 1.4; win_width = 48; win_stride_width = 8; win_stride_height = 8; gamma_corr = true; } Settings Settings::Read(int argc, char** argv) { cout << "Parsing command args" << endl; Settings settings; for (int i = 1; i < argc - 1; i += 2) { string key = argv[i]; string val = argv[i + 1]; if (key == "-src") settings.src = val; else if (key == "-src_is_video") settings.src_is_video = (val == "true"); else if (key == "-make_gray") settings.make_gray = (val == "true"); else if (key == "-resize_src") settings.resize_src = (val == "true"); else if (key == "-resize_src_scale") settings.resize_src_scale = atof(val.c_str()); else if (key == "-hit_threshold") settings.hit_threshold = atof(val.c_str()); else if (key == "-scale") settings.scale = atof(val.c_str()); else if (key == "-nlevels") settings.nlevels = atoi(val.c_str()); else if (key == "-win_width") settings.win_width = atoi(val.c_str()); else if (key == "-win_stride_width") settings.win_stride_width = atoi(val.c_str()); else if (key == "-win_stride_height") settings.win_stride_height = atoi(val.c_str()); else if (key == "-gr_threshold") settings.gr_threshold = atoi(val.c_str()); else if (key == "-gamma_corr") settings.gamma_corr = atoi(val.c_str()) != 0; else throw runtime_error((string("Unknown key: ") + key)); } cout << "Command args are parsed\n"; return settings; } App::App(const Settings &s) { settings = s; cout << "\nControls:\n" << "\tESC - exit\n" << "\tm - change mode GPU <-> CPU\n" << "\tg - convert image to gray or not\n" << "\t1/q - increase/decrease HOG scale\n" << "\t2/w - increase/decrease levels count\n" << "\t3/e - increase/decrease HOG group threshold\n" << "\t4/r - increase/decrease hit threshold\n" << endl; use_gpu = true; make_gray = settings.make_gray; scale = settings.scale; gr_threshold = settings.gr_threshold; nlevels = settings.nlevels; hit_threshold = settings.hit_threshold; gamma_corr = settings.gamma_corr; if (settings.win_width != 64 && settings.win_width != 48) settings.win_width = 64; cout << "Scale: " << scale << endl; cout << "Group threshold: " << gr_threshold << endl; cout << "Levels number: " << nlevels << endl; cout << "Win width: " << settings.win_width << endl; cout << "Win stride: (" << settings.win_stride_width << ", " << settings.win_stride_height << ")\n"; cout << "Hit threshold: " << hit_threshold << endl; cout << "Gamma correction: " << gamma_corr << endl; cout << endl; } void App::RunOpencvGui() { running = true; Size win_size(settings.win_width, settings.win_width * 2); //(64, 128) or (48, 96) Size win_stride(settings.win_stride_width, settings.win_stride_height); vector<float> detector; if (win_size == Size(64, 128)) detector = cv::gpu::HOGDescriptor::getPeopleDetector_64x128(); else detector = cv::gpu::HOGDescriptor::getPeopleDetector_48x96(); // GPU's HOG classifier cv::gpu::HOGDescriptor gpu_hog(win_size, Size(16, 16), Size(8, 8), Size(8, 8), 9, cv::gpu::HOGDescriptor::DEFAULT_WIN_SIGMA, 0.2, gamma_corr, cv::gpu::HOGDescriptor::DEFAULT_NLEVELS); gpu_hog.setSVMDetector(detector); // CPU's HOG classifier cv::HOGDescriptor cpu_hog(win_size, Size(16, 16), Size(8, 8), Size(8, 8), 9, 1, -1, HOGDescriptor::L2Hys, 0.2, gamma_corr, cv::HOGDescriptor::DEFAULT_NLEVELS); cpu_hog.setSVMDetector(detector); // Make endless cycle from video (if src is video) while (running) { VideoCapture vc; Mat frame; if (settings.src_is_video) { vc.open(settings.src.c_str()); if (!vc.isOpened()) throw runtime_error(string("Can't open video file: " + settings.src)); vc >> frame; } else { frame = imread(settings.src); if (frame.empty()) throw runtime_error(string("Can't open image file: " + settings.src)); } Mat img_aux, img, img_to_show; gpu::GpuMat gpu_img; // Iterate over all frames while (running && !frame.empty()) { WorkBegin(); vector<Rect> found; // Change format of the image (input must be 8UC3) if (make_gray) cvtColor(frame, img_aux, CV_BGR2GRAY); else if (use_gpu) cvtColor(frame, img_aux, CV_BGR2BGRA); else img_aux = frame; // Resize image if (settings.resize_src) resize(img_aux, img, Size(int(frame.cols * settings.resize_src_scale), int(frame.rows * settings.resize_src_scale))); else img = img_aux; img_to_show = img; gpu_hog.nlevels = nlevels; cpu_hog.nlevels = nlevels; // Perform HOG classification HogWorkBegin(); if (use_gpu) { gpu_img = img; gpu_hog.detectMultiScale(gpu_img, found, hit_threshold, win_stride, Size(0, 0), scale, gr_threshold); } else cpu_hog.detectMultiScale(img, found, hit_threshold, win_stride, Size(0, 0), scale, gr_threshold); HogWorkEnd(); // Draw positive classified windows for (size_t i = 0; i < found.size(); i++) { Rect r = found[i]; rectangle(img_to_show, r.tl(), r.br(), CV_RGB(0, 255, 0), 3); } WorkEnd(); // Show results putText(img_to_show, GetPerformanceSummary(), Point(5, 25), FONT_HERSHEY_SIMPLEX, 1.0, Scalar(0, 0, 255), 2); imshow("opencv_gpu_hog", img_to_show); HandleKey((char)waitKey(3)); if (settings.src_is_video) { vc >> frame; } } } } void App::HandleKey(char key) { switch (key) { case 27: running = false; break; case 'm': case 'M': use_gpu = !use_gpu; cout << "Switched to " << (use_gpu ? "CUDA" : "CPU") << " mode\n"; break; case 'g': case 'G': make_gray = !make_gray; cout << "Convert image to gray: " << (make_gray ? "YES" : "NO") << endl; break; case '1': scale *= 1.05; cout << "Scale: " << scale << endl; break; case 'q': case 'Q': scale /= 1.05; cout << "Scale: " << scale << endl; break; case '2': nlevels++; cout << "Levels number: " << nlevels << endl; break; case 'w': case 'W': nlevels = max(nlevels - 1, 1); cout << "Levels number: " << nlevels << endl; break; case '3': gr_threshold++; cout << "Group threshold: " << gr_threshold << endl; break; case 'e': case 'E': gr_threshold = max(0, gr_threshold - 1); cout << "Group threshold: " << gr_threshold << endl; break; case '4': hit_threshold+=0.25; cout << "Hit threshold: " << hit_threshold << endl; break; case 'r': case 'R': hit_threshold = max(0.0, hit_threshold - 0.25); cout << "Hit threshold: " << hit_threshold << endl; break; case 'c': case 'C': gamma_corr = !gamma_corr; cout << "Gamma correction: " << gamma_corr << endl; break; } } inline void App::HogWorkBegin() { hog_work_begin = getTickCount(); } inline void App::HogWorkEnd() { int64 delta = getTickCount() - hog_work_begin; double freq = getTickFrequency(); hog_work_fps = freq / delta; } inline double App::HogWorkFps() const { return hog_work_fps; } inline void App::WorkBegin() { work_begin = getTickCount(); } inline void App::WorkEnd() { int64 delta = getTickCount() - work_begin; double freq = getTickFrequency(); work_fps = freq / delta; } inline double App::WorkFps() const { return work_fps; } inline const string App::GetPerformanceSummary() const { stringstream ss; ss << (use_gpu ? "GPU" : "CPU") << " HOG FPS: " << setiosflags(ios::left) << setprecision(4) << setw(7) << HogWorkFps() << " Total FPS: " << setprecision(4) << setw(7) << WorkFps(); return ss.str(); }
11,993
4,115
/* * =BEGIN MIT LICENSE * * The MIT License (MIT) * * Copyright (c) 2014 Andras Csizmadia * http://www.vpmedia.hu * * 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. * * =END MIT LICENSE * */ /** * ClientExtensionTest * ClientExtensionTest.cpp * Purpose: Test for ClientExtension * * @author Andras Csizmadia (andras at vpmedia.hu) * @version 1.0.0 */ //---------------------------------- // Import Custom Headers //---------------------------------- #include "ClientExtensionTest.h" //---------------------------------- // Main //---------------------------------- int main(int argc, char** argv) { printf("Testing Crypto\n"); CryptoPP::SHA512 hash; byte digest[ CryptoPP::SHA512::DIGESTSIZE ]; std::string message = "HelloWorld"; hash.CalculateDigest( digest, (byte*) message.c_str(), message.length() ); CryptoPP::HexEncoder encoder; std::string output; encoder.Attach( new CryptoPP::StringSink( output ) ); encoder.Put( digest, sizeof(digest) ); encoder.MessageEnd(); std::cout << output << std::endl; return EXIT_SUCCESS; }
2,160
717
/** System that manages sound effects **************************************** * * * Copyright (c) 2016 Florian Oetke * * This file is distributed under the MIT License * * See LICENSE file for details. * \*****************************************************************************/ #pragma once #include <core/audio/audio_ctx.hpp> #include <core/audio/sound.hpp> #include <core/engine.hpp> #include <core/utils/str_id.hpp> #include <core/utils/messagebus.hpp> #include <core/units.hpp> #include <core/ecs/ecs.hpp> namespace lux { namespace renderer { struct Animation_event; } namespace sys { namespace sound { struct Sound_mappings; class Sound_sys { public: Sound_sys(Engine&, ecs::Entity_manager& ecs); ~Sound_sys(); void update(Time dt); private: struct Sound_effect { audio::Sound_ptr sound; bool loop = false; }; audio::Audio_ctx& _audio_ctx; asset::Asset_manager& _assets; ecs::Entity_manager& _ecs; asset::Ptr<Sound_mappings> _mappings; util::Mailbox_collection _mailbox; int _last_rev = 0; std::unordered_map<util::Str_id, Sound_effect> _event_sounds; void _reload(); void _on_anim_event(const renderer::Animation_event& event); }; } } }
1,413
471
// Problem: https://www.hackerrank.com/challenges/minimum-absolute-difference-in-an-array/problem // Score: 15 #include <iostream> #include <vector> #include <algorithm> using namespace std; int main(){ int n; cin >> n; vector<int> arr; for (int i = 0; i < n; i++){ int tmp; cin >> tmp; arr.push_back(tmp); } sort(arr.begin(), arr.end()); int ans = abs(arr[0] - arr[1]); for (int i = 1; i < arr.size(); i++){ if (abs(arr[i] - arr[i-1]) < ans){ ans = abs(arr[i] - arr[i-1]); } } cout << ans; return 0; }
608
240
/** * Swaggy Jenkins * Jenkins API clients generated from Swagger / Open API specification * * OpenAPI spec version: 1.1.1 * Contact: blah@cliffano.com * * NOTE: This class is auto generated by OpenAPI-Generator 3.2.1-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ #include "GenericResource.h" namespace org { namespace openapitools { namespace client { namespace model { GenericResource::GenericResource() { m__class = utility::conversions::to_string_t(""); m__classIsSet = false; m_DisplayName = utility::conversions::to_string_t(""); m_DisplayNameIsSet = false; m_DurationInMillis = 0; m_DurationInMillisIsSet = false; m_Id = utility::conversions::to_string_t(""); m_IdIsSet = false; m_Result = utility::conversions::to_string_t(""); m_ResultIsSet = false; m_StartTime = utility::conversions::to_string_t(""); m_StartTimeIsSet = false; } GenericResource::~GenericResource() { } void GenericResource::validate() { // TODO: implement validation } web::json::value GenericResource::toJson() const { web::json::value val = web::json::value::object(); if(m__classIsSet) { val[utility::conversions::to_string_t("_class")] = ModelBase::toJson(m__class); } if(m_DisplayNameIsSet) { val[utility::conversions::to_string_t("displayName")] = ModelBase::toJson(m_DisplayName); } if(m_DurationInMillisIsSet) { val[utility::conversions::to_string_t("durationInMillis")] = ModelBase::toJson(m_DurationInMillis); } if(m_IdIsSet) { val[utility::conversions::to_string_t("id")] = ModelBase::toJson(m_Id); } if(m_ResultIsSet) { val[utility::conversions::to_string_t("result")] = ModelBase::toJson(m_Result); } if(m_StartTimeIsSet) { val[utility::conversions::to_string_t("startTime")] = ModelBase::toJson(m_StartTime); } return val; } void GenericResource::fromJson(web::json::value& val) { if(val.has_field(utility::conversions::to_string_t("_class"))) { setClass(ModelBase::stringFromJson(val[utility::conversions::to_string_t("_class")])); } if(val.has_field(utility::conversions::to_string_t("displayName"))) { setDisplayName(ModelBase::stringFromJson(val[utility::conversions::to_string_t("displayName")])); } if(val.has_field(utility::conversions::to_string_t("durationInMillis"))) { setDurationInMillis(ModelBase::int32_tFromJson(val[utility::conversions::to_string_t("durationInMillis")])); } if(val.has_field(utility::conversions::to_string_t("id"))) { setId(ModelBase::stringFromJson(val[utility::conversions::to_string_t("id")])); } if(val.has_field(utility::conversions::to_string_t("result"))) { setResult(ModelBase::stringFromJson(val[utility::conversions::to_string_t("result")])); } if(val.has_field(utility::conversions::to_string_t("startTime"))) { setStartTime(ModelBase::stringFromJson(val[utility::conversions::to_string_t("startTime")])); } } void GenericResource::toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix) const { utility::string_t namePrefix = prefix; if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(".")) { namePrefix += utility::conversions::to_string_t("."); } if(m__classIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("_class"), m__class)); } if(m_DisplayNameIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("displayName"), m_DisplayName)); } if(m_DurationInMillisIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("durationInMillis"), m_DurationInMillis)); } if(m_IdIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("id"), m_Id)); } if(m_ResultIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("result"), m_Result)); } if(m_StartTimeIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("startTime"), m_StartTime)); } } void GenericResource::fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix) { utility::string_t namePrefix = prefix; if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(".")) { namePrefix += utility::conversions::to_string_t("."); } if(multipart->hasContent(utility::conversions::to_string_t("_class"))) { setClass(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("_class")))); } if(multipart->hasContent(utility::conversions::to_string_t("displayName"))) { setDisplayName(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("displayName")))); } if(multipart->hasContent(utility::conversions::to_string_t("durationInMillis"))) { setDurationInMillis(ModelBase::int32_tFromHttpContent(multipart->getContent(utility::conversions::to_string_t("durationInMillis")))); } if(multipart->hasContent(utility::conversions::to_string_t("id"))) { setId(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("id")))); } if(multipart->hasContent(utility::conversions::to_string_t("result"))) { setResult(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("result")))); } if(multipart->hasContent(utility::conversions::to_string_t("startTime"))) { setStartTime(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("startTime")))); } } utility::string_t GenericResource::getClass() const { return m__class; } void GenericResource::setClass(utility::string_t value) { m__class = value; m__classIsSet = true; } bool GenericResource::_classIsSet() const { return m__classIsSet; } void GenericResource::unset_class() { m__classIsSet = false; } utility::string_t GenericResource::getDisplayName() const { return m_DisplayName; } void GenericResource::setDisplayName(utility::string_t value) { m_DisplayName = value; m_DisplayNameIsSet = true; } bool GenericResource::displayNameIsSet() const { return m_DisplayNameIsSet; } void GenericResource::unsetDisplayName() { m_DisplayNameIsSet = false; } int32_t GenericResource::getDurationInMillis() const { return m_DurationInMillis; } void GenericResource::setDurationInMillis(int32_t value) { m_DurationInMillis = value; m_DurationInMillisIsSet = true; } bool GenericResource::durationInMillisIsSet() const { return m_DurationInMillisIsSet; } void GenericResource::unsetDurationInMillis() { m_DurationInMillisIsSet = false; } utility::string_t GenericResource::getId() const { return m_Id; } void GenericResource::setId(utility::string_t value) { m_Id = value; m_IdIsSet = true; } bool GenericResource::idIsSet() const { return m_IdIsSet; } void GenericResource::unsetId() { m_IdIsSet = false; } utility::string_t GenericResource::getResult() const { return m_Result; } void GenericResource::setResult(utility::string_t value) { m_Result = value; m_ResultIsSet = true; } bool GenericResource::resultIsSet() const { return m_ResultIsSet; } void GenericResource::unsetResult() { m_ResultIsSet = false; } utility::string_t GenericResource::getStartTime() const { return m_StartTime; } void GenericResource::setStartTime(utility::string_t value) { m_StartTime = value; m_StartTimeIsSet = true; } bool GenericResource::startTimeIsSet() const { return m_StartTimeIsSet; } void GenericResource::unsetStartTime() { m_StartTimeIsSet = false; } } } } }
8,152
2,797
/** \file astrolabe_exception.hpp \brief Definition of the topmost, general ASTROLABE exception. \ingroup ASTROLABE_exceptions_group */ #ifndef ASTROLABE_EXCEPTION_HPP #define ASTROLABE_EXCEPTION_HPP #include <stdexcept> #include <string> using namespace std; class astrolabe_time; /** \brief ASTROLABE's topmost, general exception. \ingroup ASTROLABE_exceptions_group */ class astrolabe_exception : public exception { public: /// \brief Default constructor. astrolabe_exception (void); /// \brief Copy constructor. /** \param other The other exception from which the values will be copied. */ astrolabe_exception (const astrolabe_exception & other); /// \brief Destructor. virtual ~astrolabe_exception (void); public: /// \brief Print the exception. /** \param the_stream The stream to print the exception to. */ virtual void print (ostream & the_stream) const; /// \brief Set the description of the exception. /** \param the_description The description of the exception. */ virtual void set_description (const string & the_description); /// \brief Get the description of the exception. /** \return The description of the exception. */ virtual string _description (void) const; /// \brief Set the name of the source file where the exception takes place. /** \param the_file The name of the file to set. */ virtual void set_file (const string & the_file); /// \brief Get the name of the file where the exception takes place. /** \return The name of the file where the exception takes place. */ virtual string _file (void) const; /// \brief Set the line number (in the source file) where the exception takes place. /** \param the_line The line number to set. */ virtual void set_line (int the_line); /// \brief Ge the line number (in the source file) where the exception takes place. /** \return The line number (in the source file) where the exception takes place. */ virtual int _line (void) const; /// \brief Set the name of the class where the exception takes place. /** \param the_class The name of the class to set. */ virtual void set_class_in (const string & the_class); /// \brief Retrieve the name of the class where the exception takes place. /** \return The name of the class where the exception takes place. */ virtual string _class_in (void) const; /// \brief Set the name of the method where the exception takes place. /** \param the_method The name of the method to set. */ virtual void set_method_in (const string & the_method); /// \brief Retrieve the name of the method where the exception takes place. /** \return The name of the method where the exception takes place. */ virtual string _method_in (void) const; /// \brief Set the severity level of the exception. /** \param The severity level to set. It must be coded as follows: - Severity = 000 -> INFORMATIONAL (simply information to user) - Severity = 1000 -> WARNING (it makes sense to continue with the execution) - Severity = 2000 -> FATAL ERROR (execution was broken) */ virtual void set_severity (int the_sever); /// \brief Retrieve the severity level of the exception. /** \return The severity level of the exception. The meaning of the numerical code returned is: - Severity = 000 -> INFORMATIONAL (simply information to user) - Severity = 1000 -> WARNING (it makes sense to continue with the execution) - Severity = 2000 -> FATAL ERROR (execution was broken) */ virtual string _severity (void) const; /// \brief Set the time when the exception takes place. /** \param Time The time when the exception takes place. */ virtual void set_time (const astrolabe_time Time); /// \brief Retrieve the time when the exception takes place. /** \param Time The object to which the time when the exception takes placw will be copied. */ virtual void _time ( astrolabe_time & Time) const; /// \brief Retrieve the exception's alphanumeric code. /** \return The exception's alphanumeric code. */ virtual string _name_code (void) const; /// \brief Retrieve the exception's numeric code. /** \return The exception's numeric code. */ virtual int _num_code (void) const; protected: /// \brief Source file where the exception took place. string file_; /// \brief Line number within the source file where the exception took place. int line_; /// \brief Class of the object throwing the exception. string class_; /// \brief Method of the object throwing the exception. string method_; /// \brief Short description. string description_; /// \brief Error degree. /** Three severity levels are allowed: - Severity = 000 -> INFORMATIONAL (simply information to user) - Severity = 1000 -> WARNING (it makes sense to continue with the execution) - Severity = 2000 -> FATAL ERROR (execution was broken) */ int severity_; /// \brief Time of event: year. int yy_; /// \brief Time of event: month. int mm_; /// \brief Time of event: day. int dd_; /// \brief Time of event: hour. int ho_; /// \brief Time of event: minute. int mi_; /// \brief Time of event: second. long double se_; }; ostream & operator << (ostream & result, const astrolabe_exception & the_exception); #endif
5,970
1,731