text
stringlengths
8
6.88M
// // AcidAudioBuffer.cpp // SRXvert // // Created by Dennis Lapchenko on 04/05/2016. // // #include "AcidAudioBuffer.h" using namespace AcidR; AcidAudioBuffer::AcidAudioBuffer() { } AcidAudioBuffer::~AcidAudioBuffer() { } void AcidAudioBuffer::PeakNormalise(float maxPeak, float threshold) { float peakGainMult = maxPeak / getMagnitude(0, getNumSamples()); for(int index = 0; index < getNumSamples(); index++) { float sampleGain = getSample(0, index); if(std::fabs(sampleGain) > threshold) { sampleGain *= peakGainMult; //get new value, which is current amplitude * peak gain } applyGain(0, index, 0, sampleGain); //0 channel, index sample, apply gain to 1 sample, apply new value to that sample } } void AcidAudioBuffer::WriteFromReader(AudioFormatReader *reader) { if(getNumSamples() >= 0) clear(); //clears the buffer if something was already written AudioSampleBuffer leftChannel, rightChannel; //seperate stereo channel buffers, which will be summed up into mono channel leftChannel.setSize(1, reader->lengthInSamples); //left channel buffer set to 1 channel and length of converted files samples reader->read(&leftChannel, 0, reader->lengthInSamples, 0, true, false); //left channel filled with leftchannel data from file reader rightChannel.setSize(1, reader->lengthInSamples); //right channel buffer set to 1 channel and length of converted files samples reader->read(&rightChannel, 0, reader->lengthInSamples, 0, false, true); //right channel filled with rightchannel data from file reader const float* leftSamples = leftChannel.getReadPointer(0); //get the pointer to the start of left channel samples array const float* rightSamples = rightChannel.getReadPointer(0); //get the pointer to the start of right channel samples array if(getNumChannels() < 2) //if Stereo is unticked, file will be converted to mono, else - stereo { //MONO: summing R+L channels for(int index = 0; index < reader->lengthInSamples; index++) { float averageSample = (leftSamples[index] + rightSamples[index]) / 2.0f; addSample(0, index, averageSample); } } else { //STEREO: writing left and right channels to buffer for(int index = 0; index < reader->lengthInSamples; index++) { addSample(0, index, leftSamples[index]); addSample(1, index, rightSamples[index]); } } leftChannel.clear(); //clear temporary read channels rightChannel.clear(); } void AcidAudioBuffer::setSampleRate(double newSampleRate) { sampleRate = newSampleRate; } double AcidAudioBuffer::getSampleRate() { return sampleRate; }
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> using namespace std; const int maxn = 210; int maze[maxn][maxn]; int gap[maxn],dis[maxn],pre[maxn],cur[maxn]; int sap(int s,int t,int num) { memset(cur,0,sizeof(cur)); memset(dis,0,sizeof(dis)); memset(gap,0,sizeof(gap)); int u = pre[s] = s,maxflow = 0,aug = -1; gap[0] = num; while (dis[s] < num) { loop: for (int v = cur[u]; v < num; v++) if (maze[u][v] && dis[u] == dis[v] + 1) { if (aug == -1 || aug > maze[u][v]) aug = maze[u][v]; pre[v] = u; u = cur[u] = v; if (v == t) { maxflow += aug; for (u = pre[u]; v != s; v = u,u = pre[u]) { maze[u][v] -= aug; maze[v][u] += aug; } aug = -1; } goto loop; } int mindis = num -1; for (int v = 0; v < num; v++) if (maze[u][v] && mindis > dis[v]) { cur[u] = v; mindis = dis[v]; } if ((--gap[dis[u]]) == 0) break; gap[dis[u] = mindis+1]++; u = pre[u]; } return maxflow; } int main() { int n,m; int from,to,flw; scanf("%d%d",&n,&m); for (int i = 1; i <= n; i++) { scanf("%d%d%d",&from,&to,&flw); if (maze[from][to] < 0) continue; maze[from][to] += flw; maze[to][from] = -maze[from][to]; } cout << sap(1,m,m+1) << endl; return 0; }
#include "stdafx.h" #include "Act_Blizzard.h" #include "../Monster.h" #include "ACTEffect.h" #include "../../GameData.h" Act_Blizzard::Act_Blizzard() { m_ActionId = enBlizzard; } Act_Blizzard::~Act_Blizzard() { } bool Act_Blizzard::Action(Monster* me) { if (m_target == nullptr) return true; if (m_first) { if (me->GetMP() < m_cost) return true; me->SetMP(me->GetMP() - m_cost); m_cBeam.InitAbnormalStateInfo(L"Assets/effect/KOTIKOTI.efk",ACTEffectGrant::State::enHardCC,m_efs,m_DoTEndTime,m_grantAbsTime, m_DoTDamageParam); m_cBeam.Fire(me, m_target, L"Assets/effect/briza.efk", L"Assets/sound/blizzard.wav", laserRange, m_damage,m_cost); m_first = false; } else if (m_timer >= m_cooltime) { me->anim_idle(); return true; } if (m_cBeam.DamageCalc()) m_timer += IGameTime().GetFrameDeltaTime(); return false; }
// Example 2_2 : Initialization, move, swap, auto, decltype // Created by Oleksiy Grechnyev 2017 #include <iostream> #include <string> int main(){ using namespace std; { cout << "5 forms of initialization" << endl; // No copy/move/assignment here, only 1 object created by ctor each time int i1 = 17; // Does not work with explicit ctor int i2(17); // Cannot be used for class fields int i3 = int(17); // No copy/move here ! int i4{17}; int i5 = {17}; // Does not work with explicit ctor cout << i1 << " " << i2 << " " << i3 << " " << i4 << " " << i5 << endl << endl; } { cout << "move and swap operations" << endl; string s1("Brianna"); string s2 = move(s1); string s3("Mira"); string s4("Visas"); swap(s3, s4); cout << "s1 = " << s1 << endl; cout << "s2 = " << s2 << endl; cout << "s3 = " << s3 << endl; cout << "s4 = " << s4 << endl << endl; } { cout << "auto, decltype, decltype(auto)" << endl; int a = 13; auto b = a; // b is int = 13 decltype(a) c = 14; // c is int = 14 int &d = a; // d is a reference to a // auto gives int even though d is a ref auto e = d; // e is int = 13 // decltype(auto) gives ref decltype(auto) f = d; // f is a reference to a a = 22; // Change a, d, f cout << "a = " << a << endl; // 22 cout << "b = " << b << endl; // 13 cout << "c = " << c << endl; // 14 cout << "d = " << d << endl; // 22 cout << "e = " << e << endl; // 13 cout << "f = " << f << endl << endl; // 22 } return 0; }
#include "pch.h" #include "Mesh.h" #include "RenderDevice.h" #include "Core\FileUtils.h" Hourglass::Mesh::Mesh() : m_AabbScale(1.0f) { } void Hourglass::Mesh::Serialize(FileArchive& archive) { archive.EnsureHeader("HMDL", 4); archive.Serialize(m_Type); archive.Serialize(PositionArray); archive.Serialize(UV0Array); archive.Serialize(NormalArray); archive.Serialize(TangentArray); archive.Serialize(BoneIdArray); archive.Serialize(BoneWeightArray); archive.Serialize(TriangleIndices); archive.Serialize(Submeshes); archive.Serialize(skeleton); } void Hourglass::Mesh::AppendVertices(const std::vector<MeshLoaderVertex>& vertexData, int vertexComponentMask) { std::vector<MeshLoaderVertex>::const_iterator iter; for (iter = vertexData.begin(); iter != vertexData.end(); iter++) { PositionArray.push_back(iter->pos); UV0Array.push_back(iter->uv0); NormalArray.push_back(iter->normal); TangentArray.push_back(iter->tangent); BoneIdArray.push_back(iter->boneId); BoneWeightArray.push_back(iter->weight); } } void Hourglass::Mesh::AppendTriangles(const std::vector<UINT>& triangleData, int baseVertexOffset) { Submeshes.push_back({ (UINT)triangleData.size(), (UINT)TriangleIndices.size(), baseVertexOffset }); TriangleIndices.insert(TriangleIndices.end(), triangleData.begin(), triangleData.end()); } void Hourglass::Mesh::UpdateRenderBuffer() { m_RenderBuffer.Reset(); BYTE* compactVertexData = nullptr; int offset = 0; if (m_Type == Type::kStandard) { int stride = sizeof( float ) * 12; // Size of position, UV0, normal and tangent compactVertexData = new BYTE[PositionArray.size() * stride]; for (size_t i = 0; i < PositionArray.size(); i++) { memcpy( compactVertexData + offset, &PositionArray[i], sizeof( Vector3 ) ); offset += sizeof( Vector3 ); memcpy( compactVertexData + offset, &UV0Array[i], sizeof( Vector2 ) ); offset += sizeof( Vector2 ); memcpy( compactVertexData + offset, &NormalArray[i], sizeof( Vector3 ) ); offset += sizeof( Vector3 ); memcpy( compactVertexData + offset, &TangentArray[i], sizeof( Vector4 ) ); offset += sizeof( Vector4 ); } m_RenderBuffer.CreateVertexBuffer( compactVertexData, stride, (UINT)PositionArray.size(), D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST, g_InputLayouts[kVertexDecl_PosUV0NormTan].Get() ); } else if (m_Type == Type::kSkinned) { int stride = sizeof( float ) * 16 + sizeof( int ) * 4; // Size of position, UV0, normal, tangent, bone id and bone weight compactVertexData = new BYTE[PositionArray.size() * stride]; for (size_t i = 0; i < PositionArray.size(); i++) { memcpy( compactVertexData + offset, &PositionArray[i], sizeof( Vector3 ) ); offset += sizeof( Vector3 ); memcpy( compactVertexData + offset, &UV0Array[i], sizeof( Vector2 ) ); offset += sizeof( Vector2 ); memcpy( compactVertexData + offset, &NormalArray[i], sizeof( Vector3 ) ); offset += sizeof( Vector3 ); memcpy( compactVertexData + offset, &TangentArray[i], sizeof( Vector4 ) ); offset += sizeof( Vector4 ); memcpy( compactVertexData + offset, &BoneIdArray[i], sizeof( XMINT4 ) ); offset += sizeof( XMINT4 ); memcpy( compactVertexData + offset, &BoneWeightArray[i], sizeof( Vector4 ) ); offset += sizeof( Vector4 ); } m_RenderBuffer.CreateVertexBuffer( compactVertexData, stride, (UINT)PositionArray.size(), D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST, g_InputLayouts[kVertexDecl_PosUV0NormTanSkin].Get() ); } else { assert( 0 ); } int indexCount = 0; for (int i = 0; i < Submeshes.size(); i++) { indexCount += Submeshes[i].indexCount; } m_RenderBuffer.CreateIndexBuffer(TriangleIndices.data(), sizeof(UINT), indexCount); delete[] compactVertexData; CalculateAabb(); } void Hourglass::Mesh::CalculateAabb() { // Invalidate current aabb m_Aabb.Invalidate(); // Create aabb based on vertex positions for (std::vector<Vector3>::iterator iter = PositionArray.begin(); iter != PositionArray.end(); iter++) m_Aabb.Expand(*iter * m_AabbScale); } Hourglass::MeshManager Hourglass::g_MeshManager; void Hourglass::MeshManager::Init() { LoadMeshes("Assets/Mesh/"); } void Hourglass::MeshManager::Shutdown() { for (std::vector<Mesh*>::iterator iter = m_Meshes.begin(); iter != m_Meshes.end(); iter++) { delete *iter; } m_Meshes.clear(); } Hourglass::Mesh* Hourglass::MeshManager::GetMesh(const char* path) const { std::string meshPath(path); FileUtils::TrimPathDelimiter(meshPath); for (int i = 0; i < m_Meshes.size(); i++) { if (FileUtils::iequals(meshPath, m_Meshes[i]->GetPath())) return m_Meshes[i]; } return nullptr; } void Hourglass::MeshManager::LoadMeshes(const char* path) { char searchPath[MAX_PATH]; strcpy_s(searchPath, path); strcat_s(searchPath, "\\*.*"); FileUtils::IterateFolderForFiles(searchPath, ".hmdl", [&](const char* filename) { FileArchive archive; if (archive.Open(filename, kFileOpenMode_Read)) { Mesh* pMesh = new Mesh; // Unify delimiter in path std::string strFilename = filename; FileUtils::TrimPathDelimiter(strFilename); pMesh->SetPath(strFilename); pMesh->Serialize(archive); // Load xml for extra settings std::string xmlFile = strFilename.substr(0, strFilename.length() - 4); xmlFile += "xml"; tinyxml2::XMLDocument doc; if (doc.LoadFile(xmlFile.c_str()) == tinyxml2::XML_SUCCESS) { tinyxml2::XMLElement * xmlMesh = doc.FirstChildElement("Mesh"); if (xmlMesh) { float aabbScale = 1.0f; xmlMesh->QueryFloatAttribute("AabbScale", &aabbScale); pMesh->SetAabbScale(aabbScale); } } pMesh->UpdateRenderBuffer(); m_Meshes.push_back(pMesh); archive.Close(); } else { char buf[1024]; sprintf_s(buf, "Unable to load mesh: %s\n", filename); OutputDebugStringA(buf); } }); }
#ifndef Q_COMMON_FUNCTIONS #define Q_COMMON_FUNCTIONS 1 /* C includes for time retrival */ #include <stdio.h> #include <sys/timeb.h> #include <time.h> namespace qEngine { char* returnCurrentTime() { //TODO: Figure out why struct __timeb64 timebuffer; char *timeline; char *timeOutput = NULL; _ftime64( &timebuffer ); timeline = _ctime64( & ( timebuffer.time ) ); sprintf(timeOutput, "%.19s.%hu %s", timeline, timebuffer.millitm, &timeline[20] ); return timeOutput; } } #endif
/** * @file np_arctan2_arcsinh_f4_combi_hw.cc * @author Gerbrand De Laender * @date 19/04/2021 * @version 1.0 * * @brief E091103, Master thesis * * @section DESCRIPTION * * Combined component including: * - Element-wise arc tangent of x1/x2 choosing the quadrant correctly. * - Inverse hyperbolic sine element-wise. * Single precision (f4) implementation. * */ #include <hls_math.h> #include "np_arctan2_arcsinh_f4_combi.h" #include "stream.h" void np_arctan2_f4_hw(stream_t &X1, stream_t &X2, stream_t &OUT, len_t stream_len) { #pragma HLS inline for(int i = 0; i < stream_len; i++) { #pragma HLS PIPELINE II=1 np_t a = pop_stream<np_t, channel_t>(X1.read()); np_t b = pop_stream<np_t, channel_t>(X2.read()); OUT << push_stream<np_t, channel_t>(hls::atan2(a, b), i == (stream_len - 1)); } } void np_arcsinh_f4_hw(stream_t &X1, stream_t &OUT, len_t stream_len) { #pragma HLS inline for(int i = 0; i < stream_len; i++) { #pragma HLS PIPELINE II=1 np_t a = pop_stream<np_t, channel_t>(X1.read()); OUT << push_stream<np_t, channel_t>(hls::asinh(a), i == (stream_len - 1)); } } void np_arctan2_arcsinh_f4_combi_hw(stream_t &X1, stream_t &X2, stream_t &OUT, len_t stream_len, sel_t sel) { #pragma HLS INTERFACE axis port=X1 #pragma HLS INTERFACE axis port=X2 #pragma HLS INTERFACE axis port=OUT #pragma HLS INTERFACE s_axilite port=stream_len #pragma HLS INTERFACE s_axilite port=sel #pragma HLS INTERFACE s_axilite port=return switch(sel){ case 0x00: np_arctan2_f4_hw(X1, X2, OUT, stream_len); break; default: np_arcsinh_f4_hw(X1, OUT, stream_len); } }
#include "Mage.h" const WeaponType Mage::type = WeaponType::dark; Mage::Mage(string name):Character() { setHealth(16); setStrength(0); setMagic(3); setSkill(1); setSpeed(3); setLuck(0); setDefense(2); setResistance(3); setMovement(6); setName(name); setExp(0); setLevel(1); Dark dark; this->setWeapon(&dark); } Mage::~Mage() { //dtor } Mage::Mage(const Mage& other):Character(other) { setWeapon(other.getWeapon()); } Mage& Mage::operator=(const Mage& rhs) { if (this == &rhs) return *this; // handle self assignment Character::operator=(rhs); setWeapon(rhs.getWeapon()); return *this; } void Mage::setWeapon(Weapon* weapon) { if(weapon->TYPE == type) { Character::setWeapon(weapon); } } Mage* Mage::clone()const { return new Mage(*this); } //Methode qui ajoute un point de caracteristique selon un random et qui le compare une variable qui determine la chance d'obtenir un point en plus void Mage::addHealth(){ int tmp= this->getHealth(); int ran=rand(); while (ran>100){ ran=rand(); } int max; if(this->getName()=="Luana"){ max=70; } else{ max=95; } if((tmp>=0) && (ran>=max)){ tmp++; } this->setHealth(tmp); } //Methode qui ajoute un point de caracteristique selon un random et qui le compare une variable qui determine la chance d'obtenir un point en plus void Mage::addStrength(){ int tmp= this->getStrength(); int ran= rand(); while(ran>100){ ran = rand(); } int max; if(this->getName()=="Luana"){ max=80; } else{ max=90; } if((tmp>=0) && (ran>=max)){ tmp++; } this->setStrength(tmp); } //Methode qui ajoute un point de caracteristique selon un random et qui le compare une variable qui determine la chance d'obtenir un point en plus void Mage::addDefense(){ int tmp= this->getDefense(); int ran= rand(); while(ran>100){ ran = rand(); } int max; if(this->getName()=="Luana"){ max=80; } else{ max=90; } if((tmp>=0) && (ran>=max)){ tmp++; } this->setDefense(tmp); } //Methode qui ajoute un point de caracteristique selon un random et qui le compare une variable qui determine la chance d'obtenir un point en plus void Mage::addSpeed(){ int tmp= this->getSpeed(); int ran=rand(); while(ran>100){ ran=rand(); } int max; if(this->getName()=="Luana"){ max=50; } else{ max=85; } if((tmp>=0) && (ran>=max)){ tmp++; } this->setSpeed(tmp); } //Methode qui ajoute un point de caracteristique selon un random et qui le compare une variable qui determine la chance d'obtenir un point en plus void Mage::addResistance(){ int tmp= this->getResistance(); int ran=rand(); while(ran>100){ ran=rand(); } int max; if(this->getName()=="Luana"){ max=80; } else{ max=85; } if((tmp>=0) && (ran>=max)){ tmp++; } this->setResistance(tmp); } //Methode qui ajoute un point de caracteristique selon un random et qui le compare une variable qui determine la chance d'obtenir un point en plus void Mage::addMagic(){ int tmp= this->getMagic(); int ran=rand(); while(ran>100){ ran=rand(); } int max; if(this->getName()=="Luana"){ max=35; } else{ max=55; } if((tmp>=0) && (ran>=max)){ tmp++; } this->setMagic(tmp); } //Methode qui ajoute un point de caracteristique selon un random et qui le compare une variable qui determine la chance d'obtenir un point en plus void Mage::addLuck(){ int tmp= this->getLuck(); int ran=rand(); while(ran>100){ ran=rand(); } int max; if(this->getName()=="Luana"){ max=75; } else{ max=90; } if((tmp>=0) && (ran>=max)){ tmp++; } this->setLuck(tmp); } //Methode qui ajoute un point de caracteristique selon un random et qui le compare une variable qui determine la chance d'obtenir un point en plus void Mage::addSkill(){ int tmp= this->getSkill(); int ran=rand(); while(ran>100){ ran=rand(); } int max; if(this->getName()=="Luana"){ max=55; } else{ max=75; } if((tmp>=0) && (ran>=max)){ tmp++; } this->setSkill(tmp); }
#include <algorithm> #include <iterator> #include <numeric> #include <limits> #include <iostream> #include <utility> #include <cmath> #include "DP_multiprec.hpp" cpp_dec_float_100 DPSolver_multi::compute_score_optimized(int i, int j) { cpp_dec_float_100 score = a_sums_[i][j] / b_sums_[i][j]; return score; } cpp_dec_float_100 DPSolver_multi::compute_score(int i, int j) { cpp_dec_float_100 num_ = std::accumulate(a_.begin()+i, a_.begin()+j, static_cast<cpp_dec_float_100>(0.)); cpp_dec_float_100 den_ = std::accumulate(b_.begin()+i, b_.begin()+j, static_cast<cpp_dec_float_100>(0.)); cpp_dec_float_100 score = num_*num_/den_; return score; } void DPSolver_multi::compute_partial_sums() { cpp_dec_float_100 a_cum; a_sums_ = std::vector<std::vector<cpp_dec_float_100>>(n_, std::vector<cpp_dec_float_100>(n_+1, static_cast<cpp_dec_float_100>(std::numeric_limits<float>::min()))); b_sums_ = std::vector<std::vector<cpp_dec_float_100>>(n_, std::vector<cpp_dec_float_100>(n_+1, static_cast<cpp_dec_float_100>(std::numeric_limits<float>::min()))); for (int i=0; i<n_; ++i) { a_sums_[i][i] = 0.; b_sums_[i][i] = 0.; } for (int i=0; i<n_; ++i) { a_cum = (i == 0)? static_cast<cpp_dec_float_100>(0.) : -a_[i-1]; for (int j=i+1; j<=n_; ++j) { a_cum += (j >= 2)? a_[j-2] : static_cast<cpp_dec_float_100>(0.); a_sums_[i][j] = a_sums_[i][j-1] + (2*a_cum + a_[j-1])*a_[j-1]; b_sums_[i][j] = b_sums_[i][j-1] + b_[j-1]; } } } void DPSolver_multi::sort_by_priority(std::vector<cpp_dec_float_100>& a, std::vector<cpp_dec_float_100>& b) { std::vector<int> ind(a.size()); std::iota(ind.begin(), ind.end(), 0); std::stable_sort(ind.begin(), ind.end(), [&a, &b](int i, int j) { return (a[i]/b[i]) < (a[j]/b[j]); }); priority_sortind_ = ind; // Inefficient reordering std::vector<cpp_dec_float_100> a_s, b_s; for (auto i : ind) { a_s.push_back(a[i]); b_s.push_back(b[i]); } std::copy(a_s.begin(), a_s.end(), a.begin()); std::copy(b_s.begin(), b_s.end(), b.begin()); } void DPSolver_multi::print_maxScore_() { for (int i=0; i<n_; ++i) { std::copy(maxScore_[i].begin(), maxScore_[i].end(), std::ostream_iterator<cpp_dec_float_100>(std::cout, " ")); std::cout << std::endl; } } void DPSolver_multi::print_nextStart_() { for (int i=0; i<n_; ++i) { std::copy(nextStart_[i].begin(), nextStart_[i].end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; } } void DPSolver_multi::create() { optimal_score_ = 0.; cpp_dec_float_100 (DPSolver_multi::*score_function)(int,int) = &DPSolver_multi::compute_score; // sort vectors by priority function G(x,y) = x/y sort_by_priority(a_, b_); // Initialize matrix maxScore_ = std::vector<std::vector<cpp_dec_float_100>>(n_, std::vector<cpp_dec_float_100>(T_+1, static_cast<cpp_dec_float_100>(std::numeric_limits<float>::min()))); nextStart_ = std::vector<std::vector<int>>(n_, std::vector<int>(T_+1, -1)); subsets_ = std::vector<std::vector<int>>(T_, std::vector<int>()); // Precompute partial sums if (use_rational_optimization_) { compute_partial_sums(); score_function = &DPSolver_multi::compute_score_optimized; } // Fill in first,second columns corresponding to T = 1,2 for(int j=0; j<2; ++j) { for (int i=0; i<n_; ++i) { maxScore_[i][j] = (j==0)?0.:(this->*score_function)(i,n_); nextStart_[i][j] = (j==0)?-1:n_; } } // Precompute partial sums std::vector<std::vector<cpp_dec_float_100>> partialSums; partialSums = std::vector<std::vector<cpp_dec_float_100>>(n_, std::vector<cpp_dec_float_100>(n_, 0.)); for (int i=0; i<n_; ++i) { for (int j=i; j<n_; ++j) { partialSums[i][j] = (this->*score_function)(i, j); } } // Fill in column-by-column from the left cpp_dec_float_100 score; cpp_dec_float_100 maxScore; int maxNextStart = -1; for(int j=2; j<=T_; ++j) { for (int i=0; i<n_; ++i) { maxScore = static_cast<cpp_dec_float_100>(std::numeric_limits<float>::min()); for (int k=i+1; k<=(n_-(j-1)); ++k) { score = partialSums[i][k] + maxScore_[k][j-1]; if (score > maxScore) { maxScore = score; maxNextStart = k; } } maxScore_[i][j] = maxScore; nextStart_[i][j] = maxNextStart; // Only need the initial entry in last column if (j == T_) break; } } } void DPSolver_multi::optimize() { // Pick out associated maxScores element int currentInd = 0, nextInd = 0; cpp_dec_float_100 score_num = 0., score_den = 0.; for (int t=T_; t>0; --t) { nextInd = nextStart_[currentInd][t]; for (int i=currentInd; i<nextInd; ++i) { subsets_[T_-t].push_back(priority_sortind_[i]); score_num += a_[priority_sortind_[i]]; score_den += b_[priority_sortind_[i]]; } optimal_score_ += score_num*score_num/score_den; currentInd = nextInd; } } std::vector<std::vector<int>> DPSolver_multi::get_optimal_subsets_extern() const { return subsets_; } cpp_dec_float_100 DPSolver_multi::get_optimal_score_extern() const { return optimal_score_; }
class Solution { private: long long splitArray(int pos, int m, vector<int>& nums, vector< vector<long long> >& DP){ if(DP[m][pos]) return DP[m][pos]; int N = nums.size(); // found a solution if(pos == N && m == 0) return 0; // no solution here if(pos == N || m == 0) return INT_MAX; long long sum = 0; long long res = INT_MAX; // try splitting from ith index for(int i=pos;i<N;i++){ sum += nums[i]; long long subres = splitArray(i+1, m-1, nums, DP); res = min(res, max(subres, sum)); if(sum > subres) break; } DP[m][pos] = res; return res; } public: int splitArray(vector<int>& nums, int m) { vector< vector<long long> > DP(m+1, vector<long long>(nums.size() + 1, 0)); return (int)splitArray(0, m, nums, DP); } };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2008 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. * * @author Manuela Hutter (manuelah) */ #ifndef WEBSERVER_ADVANCED_SETTINGS_DIALOG_H #define WEBSERVER_ADVANCED_SETTINGS_DIALOG_H #ifdef WEBSERVER_SUPPORT #include "adjunct/quick_toolkit/widgets/Dialog.h" class WebServerSettingsContext; /*********************************************************************************** ** @class WebServerAdvancedSettingsDialog ** @brief ************************************************************************************/ class WebServerAdvancedSettingsDialog : public Dialog { public: WebServerAdvancedSettingsDialog(const WebServerSettingsContext * preset_settings, WebServerSettingsContext * out_settings); //===== Dialog implementations ==== virtual Type GetType() {return DIALOG_TYPE_WEBSERVER_ADVANCED_SETTINGS;} virtual const char* GetWindowName() {return "Webserver Advanced Settings Dialog";} virtual const char* GetHelpAnchor() {return "unite.html";} virtual BOOL GetProtectAgainstDoubleClick() {return FALSE;} virtual void OnInit(); virtual UINT32 OnOk(); //===== OpWidgetListener implementations ==== //virtual void OnChange(OpWidget *widget, BOOL changed_by_mouse); private: const WebServerSettingsContext* m_preset_settings; WebServerSettingsContext* m_out_settings; OpString m_unlimited_text; }; #endif // WEBSERVER_SUPPORT #endif // WEBSERVER_ADVANCED_SETTINGS_DIALOG_H
#pragma once #include <vector> #define LAYA_MARKER (JPEG_APP0 + 2)//ICC #define LAYA_PROFILE "LAYA_PROFILE" #define LayaMin(x,y) (((x) < (y)) ? (x) : (y)) struct ImageJPEG { int width = 0; int height = 0; char* buffer = nullptr; ~ImageJPEG() { if (buffer) { delete[] buffer; buffer = nullptr; } } }; /*quality 0 -- 100*/ void write_JPEG_file(char * filename, int quality, const ImageJPEG& image, const char* buffer, size_t bufferLength); int read_JPEG_file(char * filename, ImageJPEG& image); class JPEG { public: JPEG(); void Read(const char* file); ~JPEG(); private: std::vector<char*> m_Chunks; };
#include <stdio.h> #include <math.h> #define A 2 #define B 42 int main(void) { double x, y; printf("Please, type x: "); scanf("%lf", &x); y = (B*A)*sqrt(A*x*log10(A + x)) + pow(M_E, (A*x)); putchar('\n'); printf("x = %.4f\n", x); printf("y = %.4f \n", y); putchar('\n'); return 0; }
// Copyright 2015 Stef Pletinck // License: view LICENSE file #ifndef EPCAMERA_H #define EPCAMERA_H // SFML includes #include <SFML/Graphics.hpp> // C++ includes // My includes class EpCamera { private: // Absolute position of camera // (number of pixels from origin) sf::Vector2f position; // Coordinates the camera might be moving towards sf::Vector2f target; // Optional moving speed (towards target), between 0.0 and 1.0 float movementSpeedToTarget; // Size, obviously sf::Vector2i size; public: EpCamera(int w, int h, float speed); ~EpCamera(); void Jump(int x, int y); void JumpCenter(int x, int y); // Sets the target void MoveTo(int x, int y); void MoveToCenter(int x, int y); // Update position void Update(); sf::Vector2i GetPosition() {return sf::Vector2i((int)position.x,(int)position.y);} // Little helper that is supposed to tell us the offset from the nearest tile sf::Vector2i GetTileOffset(int tileSize) {return sf::Vector2i((int)(position.x) % tileSize, (int)(position.y) % tileSize); } // 'Nother little helper, giving a rectangle defining the visible tiles sf::IntRect GetTileBounds(int tileSize); }; #endif
#include <iostream> using namespace std; namespace std{ int f(int a, int b){ return a>b?a:b; } } struct testa{ char a; short b; }; int main(void){ cout << "Size of int: " << sizeof(int) << endl; cout << "Size of char: " << sizeof(char) << endl; cout << "Size of bool: " << sizeof(bool) << endl; cout << "Size of double: " << sizeof(double) << endl; cout << "Size of float: " << sizeof(float) << endl; cout << "Size of short: " << sizeof(short) << endl; cout << "Size of long: " << sizeof(long) << endl; cout << "Size of struct: " << sizeof(testa) << endl; getchar(); return 0; }
#include <iostream> #include <unordered_map> #include <unordered_set> #include <vector> #include <sstream> #include <algorithm> #include <cctype> using namespace std; class WordFreq{ public: WordFreq(string input) : s(input) { transform(s.begin(), s.end(), s.begin(), [](unsigned char c) -> unsigned char { return std::tolower(c); }); } double compute(string target){ if(wordMap.find(target) != wordMap.end()) return wordMap[target]; stringstream ss(s); string word; double count = 0; double sLen = 0; while(getline(ss, word, ' ')){ if(!word.empty()){ sLen++; count += (word == target ? 1 : 0); } } double ans = count / sLen; wordMap.insert({target, ans}); return ans; } private: unordered_map<string, double> wordMap; string s; }; class WordFreqMulti{ public: WordFreqMulti(string& input) : s(input) { transform(s.begin(), s.end(), s.begin(), [](unsigned char c) -> unsigned char { return std::tolower(c); }); stringstream ss(s); string word; bookSize = 0; while(getline(ss, word, ' ')){ if(!word.empty()){ bookSize++; if(wordMap.find(word) == wordMap.end()){ wordMap.insert({word, 0}); } wordMap[word]++; } } } double compute(string target){ if(wordMap.find(target) == wordMap.end()) return 0; return wordMap[target] / bookSize; } private: unordered_map<string, double> wordMap; string s; vector<string> targets; double bookSize; }; int main(void){ string s = "A new door to the unbelievable, to the possible, a new day that can always bring you anything if you have no objection to it."; WordFreq wf(s); cout << wf.compute("to") << endl; cout << wf.compute("a") << endl; WordFreqMulti wfm(s); cout << wfm.compute("to") << endl; cout << wfm.compute("a") << endl; return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2011 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #include "core/pch.h" #include "ExtensionsModel.h" #include "adjunct/desktop_util/prefs/PrefsCollectionDesktopUI.h" #include "adjunct/quick/extensions/ExtensionUtils.h" #include "adjunct/quick/managers/CommandLineManager.h" #include "modules/windowcommander/src/WindowCommander.h" #include "modules/gadgets/OpGadgetClass.h" #include "modules/gadgets/OpGadgetManager.h" #include "modules/dochand/win.h" ExtensionsModel::~ExtensionsModel() { OpStatus::Ignore(DisableAllExtensions()); OpStatus::Ignore(DestroyDeletedExtensions()); } OP_STATUS ExtensionsModel::Init() { Refresh(); return OpStatus::OK; } void ExtensionsModel::StartAutoStartServices() { BOOL clean_startup_list = FALSE; if (!g_pcui->GetIntegerPref(PrefsCollectionUI::RestartUniteServicesAfterCrash)) { WindowRecoveryStrategy startupType = WindowRecoveryStrategy( g_pcui->GetIntegerPref(PrefsCollectionUI::WindowRecoveryStrategy)); if (startupType== Restore_NoWindows) { clean_startup_list = TRUE; } if (g_pcui->GetIntegerPref(PrefsCollectionUI::ShowStartupDialog) || (g_pcui->GetIntegerPref(PrefsCollectionUI::Running) && g_pcui->GetIntegerPref(PrefsCollectionUI::ShowProblemDlg) && !CommandLineManager::GetInstance()->GetArgument(CommandLineManager::NoSession))) { clean_startup_list = TRUE; } g_pcui->WriteIntegerL(PrefsCollectionUI::RestartUniteServicesAfterCrash, TRUE); } for (StringHashIterator<ExtensionsModelItem> it(m_extensions); it; it++) { ExtensionsModelItem* model_item = it.GetData(); if (clean_startup_list) { model_item->GetGadget()->SetPersistentData(GADGET_ENABLE_ON_STARTUP,(const uni_char*) NULL); } else { if (model_item->EnableOnStartup()) EnableExtension(model_item->GetExtensionId()); } } } int ExtensionsModel::CompareItems(const ExtensionsModelItem** a, const ExtensionsModelItem** b) { OpStringC name_a = (*a)->GetGadgetClass()->GetAttribute(WIDGET_NAME_TEXT); OpStringC name_b = (*b)->GetGadgetClass()->GetAttribute(WIDGET_NAME_TEXT); return name_b.Compare(name_a); } OP_STATUS ExtensionsModel::Refresh() { // Sort by name in descending order. Only extensions. ExtensionsModel::RefreshInfo refresh_info; OpAutoVector<ExtensionsModelItem> extensions; for (unsigned i = 0; i < g_gadget_manager->NumGadgets(); ++i) { OpGadget* gadget = g_gadget_manager->GetGadget(i); if (!gadget->IsExtension()) continue; OpAutoPtr<ExtensionsModelItem> item_ptr(OP_NEW(ExtensionsModelItem, (*gadget))); RETURN_OOM_IF_NULL(item_ptr.get()); RETURN_IF_ERROR(item_ptr->Init()); RETURN_IF_ERROR(extensions.Add(item_ptr.get())); ExtensionsModelItem* item = item_ptr.release(); BOOL dev_mode = FALSE; RETURN_IF_ERROR(ExtensionUtils::IsDevModeExtension(*gadget->GetClass(), dev_mode)); item->SetIsInDevMode(dev_mode); if (item->IsDeleted()) continue; if (dev_mode) refresh_info.m_dev_count++; else refresh_info.m_normal_count++; } extensions.QSort(CompareItems); NotifyAboutBeforeRefresh(refresh_info); // Remove old model items. m_extensions.DeleteAll(); // Push to listeners. for (unsigned i = extensions.GetCount(); i > 0; --i) { OpAutoPtr<ExtensionsModelItem> item_ptr(extensions.Remove(i - 1)); RETURN_IF_ERROR(m_extensions.Add(item_ptr->GetExtensionId(), item_ptr.get())); ExtensionsModelItem* item = item_ptr.release(); // Keep extensions marked for deletion to ourselves. if (item->IsDeleted()) continue; if (item->IsInDevMode()) NotifyAboutDeveloperExtensionAdded(*item); else NotifyAboutNormalExtensionAdded(*item); } NotifyAboutAfterRefresh(); return OpStatus::OK; } OP_STATUS ExtensionsModel::AddListener(Listener* listener) { if (!listener) return OpStatus::ERR; return m_listeners.Add(listener); } OP_STATUS ExtensionsModel::RemoveListener(Listener* listener) { return m_listeners.Remove(listener); } OP_STATUS ExtensionsModel::UninstallExtension(const OpStringC& extension_id) { ExtensionsModelItem* item = FindExtensionById(extension_id); OP_ASSERT(item); if (!item) { return OpStatus::ERR; } return UninstallExtension(item); } OP_STATUS ExtensionsModel::UninstallExtension(ExtensionsModelItem* item) { // Before triggering uninstall update on listeners, disable // extension. RETURN_IF_ERROR(DisableExtension(item,TRUE)); // Call listeners before removing the model item. It will // be still available for them. NotifyAboutUninstall(*item); RETURN_IF_ERROR(item->SetDeleted(TRUE)); Refresh(); return OpStatus::OK; } OP_STATUS ExtensionsModel::ReloadExtension(const OpStringC& extension_id) { ExtensionsModelItem* item = FindExtensionById(extension_id); OP_ASSERT(item && item->GetGadget()); if (!item || !item->GetGadget()) { return OpStatus::ERR; } item->GetGadget()->Reload(); // in this case we dont want to notify listeners about // reload, if we would do that, then speeddial would // remove it from list and change order of extensions DisableExtension(item, TRUE, item->IsInDevMode()); EnableExtension(item); return OpStatus::OK; } OP_STATUS ExtensionsModel::UpdateAvailable(const OpStringC& extension_id) { ExtensionsModelItem* item = FindExtensionById(extension_id); OP_ASSERT(item && item->GetGadget()); if (!item || !item->GetGadget()) { return OpStatus::ERR; } item->SetIsUpdateAvailable(TRUE); NotifyAboutUpdateAvailable(*item); return OpStatus::OK; } OP_STATUS ExtensionsModel::UpdateExtendedName(const OpStringC& extension_id,const OpStringC& name) { ExtensionsModelItem* item = FindExtensionById(extension_id); OP_ASSERT(item && item->GetGadget()); if (!item || !item->GetGadget()) { return OpStatus::ERR; } RETURN_IF_ERROR(item->SetExtendedName(name)); NotifyAboutExtendedNameUpdate(*item); return OpStatus::OK; } OP_STATUS ExtensionsModel::UpdateFinished(const OpStringC& extension_id) { ExtensionsModelItem* item = FindExtensionById(extension_id); OP_ASSERT(item && item->GetGadget()); if (!item || !item->GetGadget()) { return OpStatus::ERR; } item->SetIsUpdateAvailable(FALSE); NotifyAboutUpdateAvailable(*item); return OpStatus::OK; } OP_STATUS ExtensionsModel::EnableExtension(const OpStringC& extension_id) { OP_NEW_DBG("ExtensionsModel::EnableExtension", "extensions"); OP_DBG(("wuid = ") << extension_id); ExtensionsModelItem* item = FindExtensionById(extension_id); OP_ASSERT(item && item->GetGadget()); if (!item || !item->GetGadget()) { return OpStatus::ERR; } if (item->IsDeleted()) { OP_DBG(("resurrecting extension")); RETURN_IF_ERROR(item->SetDeleted(FALSE)); Refresh(); item = FindExtensionById(extension_id); OP_ASSERT(item); } return EnableExtension(item); } OP_STATUS ExtensionsModel::EnableExtension(ExtensionsModelItem* item) { OP_ASSERT(item && item->GetGadget()); if (item->GetGadget()->GetWindow()) return OpStatus::OK; // extension is running. RETURN_IF_ERROR(g_gadget_manager->OpenGadget(item->GetGadget())); item->SetEnableOnStartup(TRUE); NotifyAboutEnable(*item); return OpStatus::OK; } OP_STATUS ExtensionsModel::DisableAllExtensions() { for (StringHashIterator<ExtensionsModelItem> it(m_extensions); it; it++) { RETURN_IF_ERROR(DisableExtension(it.GetData())); } return OpStatus::OK; } OP_STATUS ExtensionsModel::DisableExtension(const OpStringC& extension_id, BOOL user_requested, BOOL notify_listeners) { ExtensionsModelItem* item = FindExtensionById(extension_id); OP_ASSERT(item && item->GetGadget()); if (!item || !item->GetGadget()) { return OpStatus::ERR; } return DisableExtension(item, user_requested, notify_listeners); } OP_STATUS ExtensionsModel::DisableExtension(ExtensionsModelItem* item, BOOL user_requested, BOOL notify_listeners) { RETURN_IF_ERROR(CloseExtensionWindows(item->GetGadget())); // Set that this should not be run on next startup. if (user_requested) { item->SetEnableOnStartup(FALSE); } // Notify listeners. if (notify_listeners) NotifyAboutDisable(*item); return OpStatus::OK; } BOOL ExtensionsModel::IsEnabled(const OpStringC& extension_id) { ExtensionsModelItem* model_item = FindExtensionById(extension_id); OP_ASSERT(model_item); if (!model_item) { return FALSE; } return model_item->IsEnabled(); } BOOL ExtensionsModel::CanShowOptionsPage(const OpStringC& extension_id) { ExtensionsModelItem* model_item = FindExtensionById(extension_id); OP_ASSERT(model_item); if (!model_item) { return FALSE; } return model_item->GetGadget()->HasOptionsPage() && model_item->IsEnabled(); } OP_STATUS ExtensionsModel::OpenExtensionOptionsPage( const OpStringC& extension_id) { ExtensionsModelItem* model_item = FindExtensionById(extension_id); OP_ASSERT(model_item); if (!model_item) { return FALSE; } return model_item->GetGadget()->OpenExtensionOptionsPage(); } ExtensionsModelItem* ExtensionsModel::FindExtensionById(const OpStringC& extension_id) const { if (extension_id.IsEmpty()) return NULL; ExtensionsModelItem* item = NULL; RETURN_VALUE_IF_ERROR( m_extensions.GetData(extension_id, &item), NULL); return item; } OP_STATUS ExtensionsModel::OpenExtensionUrl(const OpStringC& url,const OpStringC& extension_id) { ExtensionsModelItem* item = FindExtensionById(extension_id); if (!item || !item->GetGadget()) return OpStatus::ERR; OpUiWindowListener::CreateUiWindowArgs args; args.regular.scrollbars = true; args.regular.toolbars = true; args.regular.focus_document = true; args.regular.user_initiated = true; args.opener = item->GetGadget()->GetWindow() ? item->GetGadget()->GetWindow()->GetWindowCommander() : NULL; args.type = OpUiWindowListener::WINDOWTYPE_REGULAR; return item->GetGadget()->CreateNewUiExtensionWindow(args, url.CStr()); } ExtensionButtonComposite* ExtensionsModel::GetButton(ExtensionId id) { ExtensionButtonComposite *button = NULL; if (OpStatus::IsError(m_extension_buttons.GetData(INT32(id), &button))) { RETURN_VALUE_IF_ERROR(m_zombie_buttons.GetData(INT32(id), &button), NULL); } OP_ASSERT(button); return button; } OP_STATUS ExtensionsModel::CreateButton(ExtensionId id) { if (m_extension_buttons.Contains(INT32(id))) return OpStatus::ERR; ExtensionButtonComposite *button = OP_NEW(ExtensionButtonComposite, ()); RETURN_OOM_IF_NULL(button); if (OpStatus::IsError(m_extension_buttons.Add(INT32(id), button))) { OP_DELETE(button); return OpStatus::ERR; } return OpStatus::OK; } OP_STATUS ExtensionsModel::DeleteButton(ExtensionId id) { ExtensionButtonComposite *button = NULL; RETURN_IF_ERROR(m_extension_buttons.Remove(INT32(id), &button)); // actual destruction is delayed until all associated UI elements are destroyed // (UI buttons are usually destroyed from ClassicApplication::SyncSettings() which // is called some after extension is uninstalled) if (button->HasComponents()) { if (OpStatus::IsSuccess(m_zombie_buttons.Add(INT32(id), button))) return OpStatus::OK; } OP_DELETE(button); return OpStatus::OK; } void ExtensionsModel::OnButtonRemovedFromComposite(INT32 id) { ExtensionButtonComposite *button = NULL; if (OpStatus::IsSuccess(m_zombie_buttons.GetData(id, &button))) { if (!button->HasComponents()) { if (OpStatus::IsSuccess(m_zombie_buttons.Remove(id, &button))) { OP_DELETE(button); } } } } OP_STATUS ExtensionsModel::GetAllSpeedDialExtensions(OpVector<OpGadget>& extensions) { for (StringHashIterator<ExtensionsModelItem> it(m_extensions); it; it++) { ExtensionsModelItem* item = it.GetData(); if (ExtensionUtils::RequestsSpeedDialWindow(*(item->GetGadgetClass()))) { RETURN_IF_ERROR(extensions.Add(item->GetGadget())); } } return OpStatus::OK; } void ExtensionsModel::ReloadDevModeExtensions() { bool refresh = false; for (StringHashIterator<ExtensionsModelItem> it(m_extensions); it; it++) { ExtensionsModelItem* item = it.GetData(); if (!item || !item->IsInDevMode() || !item->GetGadget()) { continue; } item->GetGadget()->Reload(); if (item->IsEnabled()) { DisableExtension(item, TRUE); EnableExtension(item); } refresh = true; } if (refresh) Refresh(); } OP_STATUS ExtensionsModel::CloseExtensionWindows(OpGadget* extension) { OP_ASSERT(extension); if (!extension) { return OpStatus::ERR; } if (extension->IsRunning()) { Window* gadget_window = extension->GetWindow(); if (gadget_window != NULL) { RETURN_IF_ERROR(g_gadget_manager->CloseWindowPlease(gadget_window)); gadget_window->Close(); if (extension->IsExtension()) { extension->SetIsClosing(FALSE); extension->SetIsRunning(FALSE); } // Notify CORE that we want to close the window now, after call to // OnUiWindowClosing gadget_window will return incorrect pointers, // that's why we need to remember them before this call. OpWindow* wnd = gadget_window->GetOpWindow(); WindowCommander* commander = gadget_window->GetWindowCommander(); commander->OnUiWindowClosing(); g_windowCommanderManager->ReleaseWindowCommander(commander); OP_DELETE(wnd); } else { return OpStatus::ERR; } } return OpStatus::OK; } void ExtensionsModel::NotifyAboutBeforeRefresh(const ExtensionsModel::RefreshInfo& info) { for (OpListenersIterator it(m_listeners); m_listeners.HasNext(it);) { m_listeners.GetNext(it)->OnBeforeExtensionsModelRefresh(info); } } void ExtensionsModel::NotifyAboutAfterRefresh() { for (OpListenersIterator it(m_listeners); m_listeners.HasNext(it);) { m_listeners.GetNext(it)->OnAfterExtensionsModelRefresh(); } } void ExtensionsModel::NotifyAboutNormalExtensionAdded(const ExtensionsModelItem& item) { for (OpListenersIterator it(m_listeners); m_listeners.HasNext(it);) { m_listeners.GetNext(it)->OnNormalExtensionAdded(item); } } void ExtensionsModel::NotifyAboutDeveloperExtensionAdded(const ExtensionsModelItem& item) { for (OpListenersIterator it(m_listeners); m_listeners.HasNext(it);) { m_listeners.GetNext(it)->OnDeveloperExtensionAdded(item); } } void ExtensionsModel::NotifyAboutUninstall(const ExtensionsModelItem& item) { for (OpListenersIterator it(m_listeners); m_listeners.HasNext(it);) { m_listeners.GetNext(it)->OnExtensionUninstall(item); } } void ExtensionsModel::NotifyAboutEnable(const ExtensionsModelItem& item) { for (OpListenersIterator it(m_listeners); m_listeners.HasNext(it);) { m_listeners.GetNext(it)->OnExtensionEnabled(item); } } void ExtensionsModel::NotifyAboutDisable(const ExtensionsModelItem& item) { for (OpListenersIterator it(m_listeners); m_listeners.HasNext(it);) { m_listeners.GetNext(it)->OnExtensionDisabled(item); } } void ExtensionsModel::NotifyAboutUpdateAvailable(const ExtensionsModelItem& item) { for (OpListenersIterator it(m_listeners); m_listeners.HasNext(it);) { m_listeners.GetNext(it)->OnExtensionUpdateAvailable(item); } } void ExtensionsModel::NotifyAboutExtendedNameUpdate(const ExtensionsModelItem& item) { for (OpListenersIterator it(m_listeners); m_listeners.HasNext(it);) { m_listeners.GetNext(it)->OnExtensionExtendedNameUpdate(item); } } OP_STATUS ExtensionsModel::DestroyDeletedExtensions() { for (StringHashIterator<ExtensionsModelItem> it(m_extensions); it; it++) { ExtensionsModelItem* item = it.GetData(); if (item->IsDeleted()) RETURN_IF_ERROR(g_gadget_manager->DestroyGadget(item->GetGadget())); } return OpStatus::OK; }
int vis[MAXN]; int dfn[MAXN],low[MAXN]; int dfc; bool iscut[MAXN]; //bool brg[MAXN][MAXN]; int maxs=0; vector<pii> edges[MAXN]; void cut_brg(int cur,int fa) //适用于没有重边的图 { vis[cur] = 1; dfn[cur] = low[cur] = ++dfc; int child = 0; int cuts = 0; feach(edges[cur],p) { int to = p->x; if(to != fa && vis[to]) //返祖边 low[cur] = min(low[cur],dfn[to]); if(!vis[to]) { cut_brg(to,cur); child++; low[cur] = min(low[cur],low[to]); if((fa == -1 && child > 1)||(fa != -1 && low[to] >= dfn[cur])) iscut[cur] = 1, cuts ++; if(low[to] > dfn[cur]) //brig judge brg[to][cur] = brg[cur][to] = 1; } } if(iscut[cur]) maxs = max(maxs,cuts); vis[cur] = 2; } // 适用于有重边的图 vector<pr<pii,int> > brigs; void cut_brg(int cur,node * fa) //适用于存在重边的图 { vis[cur] = 1; dfn[cur] = low[cur] = ++dfc; for(node * p =head[cur];p;p=p->next) { int to = p->num; if(fa!= NULL &&p != fa->back && vis[to]) //返祖边 low[cur] = min(low[cur],dfn[to]); if(!vis[to]) { cut_brg(to,p); low[cur] = min(low[cur],low[to]); if(low[to] > dfn[cur]) brigs.pb(pr<pii,int>(pii(cur,to),p->val)); } } }
////////////////////////////////////////////////////////////////////// ///Copyright (C) 2011-2012 Benjamin Quach // //This file is part of the "Lost Horizons" video game demo // //"Lost Horizons" is free software: you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation, either version 3 of the License, or //(at your option) any later version. // //This program is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. // //You should have received a copy of the GNU General Public License //along with this program. If not, see <http://www.gnu.org/licenses/>. // /////////////////////////////////////////////////////////////////////// //gameloop.cpp //'main' gameloop object //checks for player input //creates objects and sets up level //updates all the other objects in the scene //and manages the camera control code (for now) //----------------------- //developer note: //refer to main.cpp //for program hierarchy // //THIS IS HOW THE PLANE INGAME WORKS, MODIFY ROTATION AND POSITION ACCOORDING TO THIS!!! //CARTESIAN PLANE //POSITION //X = FRONT AND BACK //Y = UP AND DOWN //Z = LEFT AND RIGHT // | // | // |Y // /\ // / \ // X/ \Z // //ROTATION //X = UP AND DOWN //Y = LEFT AND RIGHT //Z = TILT, NOT USED // //SECOND IMPORTANT NOTE : //CAMERA FOV IS IN RADIANS!!!!!! //global variable for screen size //should not change without a game restart #include "stdafx.h" #include "gameloop.h" #include "GFramework.h" //useful variables bool menuop; bool menu_open; bool target_menu_open; bool dock_open; float angle; float angle2; float distance; float nav_distance; int tMouseX; int tMouseY; float tMouseW; float tMouseW_old; //TODO //BRING SHADERS INTO MAIN LOOP SO THAT THEY CAN BE MANAGED GLOBALLY //INSTEAD OF CREATING THEM INSIDE EACH OF THE OBJECTS CLASS //for easier saving and loading //to be used later enum SYSTEMS_GAME { SYSTEM_TAU_CETI = 0, SYSTEM_DX_CANCRI = 1, SYSTEM_EPSILION_INDI=2, }; core::dimension2d<int> screen_size; //constructor to inherit objects from init class GameLoop::GameLoop(irr::IrrlichtDevice *graphics, KeyListener *receiver, irrklang::ISoundEngine *sound, bool loadgame, bool quality): graphics(graphics),sound(sound), receiver(receiver), GamePaused(false), pCam(0),then(0),velocity(0) { //set up game //establish game object variables initialized in the init.cpp file //initialize essential stuff first //setup variables player_target = 0; //very important to initialize it to 0 jump_target = 0; //ditto velocity = 0; angle = 0; angle2 = 0; camera_sway = 0; //for camera distance = 1000.0; nav_distance = 400000.0; fired = false; GameExit = false; menu_open = false; dock_open = false; NavView = false; CommandView = false; Warp = false; LaunchFighters = false; display_tut = false; //replace this with non shitty function //irrlichts timer is so fucking broken //need PRECISE timer u32 then = graphics->getTimer()->getTime(); //set the global variable screen_size = graphics->getVideoDriver()->getScreenSize(); //add spacebox, skybox, whatever the hell you call it //TODO: adjust this to the system scene file //TODO: create system scene manager scene::ISceneNode *skybox = graphics->getSceneManager()->addSkyBoxSceneNode( graphics->getVideoDriver()->getTexture("res/textures/skyboxes/1/space_top3.jpg"), graphics->getVideoDriver()->getTexture("res/textures/skyboxes/1/space_bottom4.jpg"), graphics->getVideoDriver()->getTexture("res/textures/skyboxes/1/space_left2.jpg"), graphics->getVideoDriver()->getTexture("res/textures/skyboxes/1/space_right1.jpg"), graphics->getVideoDriver()->getTexture("res/textures/skyboxes/1/space_front5.jpg"), graphics->getVideoDriver()->getTexture("res/textures/skyboxes/1/space_back6.jpg")); //some flat lighting graphics->getSceneManager()->setAmbientLight(video::SColor(155,32,32,32)); //star class comes with lighting tau_ceti_star = new sun(graphics,core::vector3df(-60000,0,-100000)); //create shader and assign lighting //chcek graphics quality callback = new ShaderCallBack; if(quality==true) { callback->shader_enabled = true; callback->fBumpStrength=4; callback->fSpecularStrength=1; callback->fSpecularPower=20; callback->fvAmbient=SColorf(0.5,0.5,0.5); callback->fLightStrength[0]=1; callback->fvLightColor[0]=SColorf(0.6,0.6,0.6); callback->fvLightPosition[0]=graphics->getSceneManager()->getActiveCamera()->getAbsolutePosition(); //sun callback->fLightStrength[1] = 5000000; callback->fvLightColor[1] = SColorf(0.7,0.7,0.9); callback->fvLightPosition[1] = vector3df(-60000,0,-100000); } else { callback->shader_enabled = false; } //create essential objects alertBox = new CAlertBox(graphics); Manager = new gameManager(graphics,receiver,sound); CPlayer = new Player(graphics,sound,alertBox,receiver,core::vector3df(0,0,-3000),ships().TERR_PRAETORIAN_CRUISER, callback); CHud = new Hud(graphics,CPlayer); gameMenu = new CMenu(graphics,sound,receiver, CPlayer); escapeMenu = new CEscapeMenu(graphics); missionM = new missionManager(graphics); dialogueM = new dialogueManager(); targetMenu = new CTargetMenu(graphics); dockMenu = new CDockMenu(graphics,receiver); //player camera create pCam = graphics->getSceneManager()->addCameraSceneNode(); if(pCam) { pCam->setFarValue(CAMERA_VIEW_DISTANCE); pCam->setFOV(CAMERA_FOV); } //important GUI stuff //shows what direction the ship wants to face XYcircle = graphics->getSceneManager()->addCubeSceneNode(); if(XYcircle) { XYcircle->setPosition(CPlayer->getPos()); XYcircle->setScale(core::vector3df(60,0,60)); XYcircle->setMaterialTexture(0,graphics->getVideoDriver()->getTexture("res/textures/circle.png")); XYcircle->setMaterialFlag(video::EMF_LIGHTING,false); XYcircle->setMaterialType(video::EMT_TRANSPARENT_ALPHA_CHANNEL); XYcircle->setMaterialFlag(video::EMF_ZBUFFER,true); XYcircle->setVisible(false); } ZYcircle = graphics->getSceneManager()->addCubeSceneNode(); if(ZYcircle) { ZYcircle->setPosition(CPlayer->getPos()); ZYcircle->setScale(core::vector3df(0,60,60)); ZYcircle->setMaterialTexture(0,graphics->getVideoDriver()->getTexture("res/textures/circle.png")); ZYcircle->setMaterialFlag(video::EMF_LIGHTING,false); ZYcircle->setMaterialType(video::EMT_TRANSPARENT_ALPHA_CHANNEL); ZYcircle->setMaterialFlag(video::EMF_ZBUFFER,true); ZYcircle->setVisible(false); } TurningArrow=graphics->getSceneManager()->addCubeSceneNode(); if(TurningArrow) { TurningArrow->setScale(core::vector3df(60,0,60)); TurningArrow->setMaterialTexture(0,graphics->getVideoDriver()->getTexture("res/textures/arrow.png")); TurningArrow->setMaterialFlag(video::EMF_LIGHTING, false); TurningArrow->setMaterialType(video::EMT_TRANSPARENT_ALPHA_CHANNEL); TurningArrow->setVisible(false); } core::dimension2d<s32> p = graphics->getSceneManager()->getSceneCollisionManager()->getScreenCoordinatesFrom3DPosition(CPlayer->getPos(),pCam); player_nav = graphics->getGUIEnvironment()->addImage(graphics->getVideoDriver()->getTexture("res/menu/buoy.png"),p); player_nav->setVisible(false); //GLOBAL EFFECTS //FOR STUFF LIKE SPASCE FOG //AND STARDUST //CAUSE THAT NEEDS TO FOLLOW THE CAMERA NOT THE PLAYER OR ANYTHING ELSE!!!! //TEMPORARY //SETUP SYSTEM terran = new planet(graphics,planets().HABITABLE,core::vector3df(25000,-1000,14000),FACTION_TERRAN_FEDERATION, L"Blacksun Delta","res/textures/planets/habitable_1.jpg"); Manager->addPlanet(terran); planet *terran2 = new planet(graphics,planets().BARREN,core::vector3df(-30000,00,300000),FACTION_TERRAN_FEDERATION, L"Argrea","res/textures/planets/barren_1.jpg"); Manager->addPlanet(terran2); planet *prov = new planet(graphics,planets().HABITABLE,core::vector3df(-300000,-5000,20000),FACTION_PROVIAN_CONSORTIUM, L"New Imperial","res/textures/planets/earth.jpg"); Manager->addPlanet(prov); planet *roid = new planet(graphics,planets().ASTEROIDS,core::vector3df(-50000,0,-10000),FACTION_PROVIAN_CONSORTIUM, L"Asteroid Belt","res/roid.jpg"); Manager->addPlanet(roid); //create nebula with particle system planet *moon = new planet(graphics,planets().MOON,core::vector3df(-5000,-1000,-25000),FACTION_TERRAN_FEDERATION, L"Drall", "res/textures/planets/moon.jpg"); Manager->addPlanet(moon); planet* gasgiant = new planet(graphics,planets().GAS,core::vector3df(300000,-3000,-300000),FACTION_NEUTRAL, L"Farstar", "res/textures/planets/gas.jpg"); Manager->addPlanet(gasgiant); //stardust effect for(int i = 0;i<50;i++) { scene::IBillboardSceneNode *s = graphics->getSceneManager()->addBillboardSceneNode(0,dimension2df(500,500),vector3df(0,0,0)); s->setMaterialTexture(0,graphics->getVideoDriver()->getTexture("res/textures/dust.png")); s->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR); s->setMaterialFlag(video::EMF_LIGHTING,false); dust_manager.push_back(s); } //load game or create new scene if(loadgame==true) { //newGame(); loadGame(); } else { newGame(); } } GameLoop::~GameLoop() { //destructor //nuke everything //also ew CHud->drop(); escapeMenu->drop(); Manager->drop(); //gameMenu->drop(); //dockMenu->drop(); missionM->drop(); dialogueM->drop(); //targetMenu->drop(); //be careful about removing scenenodes //often it is much easier tojust clear the scene //XYcircle->remove(); //ZYcircle->remove(); //TurningArrow->remove(); //pCam->remove(); //tau_ceti_star->drop(); CPlayer->drop(); //did i miss somethin? graphics->getSceneManager()->clear(); graphics->getGUIEnvironment()->clear(); } void GameLoop::drop() { delete this; } void GameLoop::newGame() { //move to xml file gui::IGUIWindow *tutorial = graphics->getGUIEnvironment()->addWindow(rect<s32>(0,0,350,420),false,L"Controls"); graphics->getGUIEnvironment()->addImage(graphics->getVideoDriver()->getTexture("res/menu/tutorial/controls.png"),core::position2d<s32>(0,20),-1,tutorial); CDialogueTree *test = new CDialogueTree(graphics,L"Admiral Brennan",L"Hello Captain. I know that you've been in stasis for a long time now, but the Terran Navy is extremely undermanned, especially with the disappearance of the Earth jumpgate all those years ago."); test->addText(L"On your left is a short log detailing how to use your ship functions. Go over it carefully. Try using the X and Z keys in order to adjust your cruiser's speed, and the WASD keys to tell your helmsman to adjust your ship orientation. Once you're done, press OK"); test->addText(L"Right now, we've got enemy cruisers in orbit around this planet. We're going to need your help in eleminating these ships. I'll try to update you on combating enemy warships as quickly as I can."); test->addText(L"I've given you a mission to destroy these enemy ships. In order to check your list of missions, open up your ship's command console and check your missions log. You can then check the missions objectives. Now, in order to attack enemy capital ships, you must target them by clicking on them, then you can them open fire with your primary turrets by holding down Spacebar"); test->addText(L"Remember, you're in charge of a warship with a crew compliment of 1200 men, not a fighter. Don't be a hero, you've got over a thousand lives on your ship. Pick your fights intelligently and tactically. Winning fights helps level up your crew and officers, which helps your ship run more efficiently"); test->addText(L"Once you've finished destroying these enemy ships, I'll contact you again"); dialogueM->addTree(test); //PLACEHOLDER //TODO: ADD INITIAL SHIPS TO SYSTEM SCENE FILE const wchar_t *pname = ships().provian_ship_name[rand()%ships().provian_ship_name.size()]; CShip *prov_cruiser1 = new CShip(graphics,sound, core::vector3df(-5000,50,5000),core::vector3df(0,0,0),ships().PROV_ARES_DESTROYER,FACTION_PROVIAN_CONSORTIUM,pname, callback); Manager->addShip(prov_cruiser1); const wchar_t *tname = ships().terran_ship_name[rand()%ships().terran_ship_name.size()]; CShip *terr_cruiser1 = new CShip(graphics,sound, core::vector3df(-500,0,0),core::vector3df(0,0,0),ships().TERR_LEGION_DESTROYER,FACTION_TERRAN_FEDERATION, tname, callback); Manager->addShip(terr_cruiser1); const wchar_t *tname2 = ships().terran_ship_name[rand()%ships().terran_ship_name.size()]; //CShip *terr_cruiser2 = new CShip(graphics,sound, core::vector3df(500,500,-2000),core::vector3df(0,0,0),ships().TERR_LEGION_DESTROYER,FACTION_TERRAN_FEDERATION, tname2); //Manager->addShip(terr_cruiser2); const wchar_t *tname3 = ships().terran_ship_name[rand()%ships().terran_ship_name.size()]; //CShip *terr_cruiser3 = new CShip(graphics,sound, core::vector3df(1500,500,-1000),core::vector3df(0,0,0),ships().TERR_PRAETORIAN_CRUISER,FACTION_TERRAN_FEDERATION, tname3); //Manager->addShip(terr_cruiser3); const wchar_t *tname4 = ships().terran_ship_name[rand()%ships().terran_ship_name.size()]; //CShip *terr_cruiser4 = new CShip(graphics,sound, core::vector3df(1500,500,-1000),core::vector3df(0,0,0),ships().TERR_PRAETORIAN_CRUISER,FACTION_TERRAN_FEDERATION, tname4); //Manager->addShip(terr_cruiser4); const wchar_t *tname5 = ships().terran_ship_name[rand()%ships().terran_ship_name.size()]; //CShip *terr_cruiser5 = new CShip(graphics,sound, core::vector3df(0,-500,0),core::vector3df(0,0,0),ships().TERR_PRAETORIAN_CRUISER,FACTION_TERRAN_FEDERATION, tname5); //Manager->addShip(terr_cruiser5); CShip *s = new CShip(graphics,sound,core::vector3df(500,-1000,3000),core::vector3df(0,0,0),ships().HQ,FACTION_TERRAN_FEDERATION,L"Terran System Headquarters", callback); if(s) { //give station stuff to sell item* in = new item(items().NANOALLOY); s->addItemToInventory(in); item* in2 = new item(items().WATER); s->addItemToInventory(in2); item* in3 = new item(items().LIGHT_GATLING); s->addItemToInventory(in3); item* in4 = new item(items().PRI_PHOTON); s->addItemToInventory(in4); item* in5 = new item(items().SEC_PLASMA); s->addItemToInventory(in5); Manager->addStation(s); //CPlayer->setPos(vector3df(-5000,0,2000)); //CPlayer->setMoney(50000); } CShip *trade = new CShip(graphics,sound,vector3df(-3000,0,-13000),vector3df(0,0,0),ships().TRADING_STATION,FACTION_TERRAN_FEDERATION,L"Drall Trading Station", callback); if(trade) { item *i = new item(items().HEAVY_METALS); trade->addItemToInventory(i); item *i2 = new item(items().RATIONS); trade->addItemToInventory(i2); Manager->addStation(trade); } CShip *argrea_trade = new CShip(graphics,sound,vector3df(-30000,0,275000),vector3df(0,0,0),ships().TRADING_STATION, FACTION_TERRAN_FEDERATION, L"Argrea Trading Station", callback); Manager->addStation(argrea_trade); CShip *shipyard = new CShip(graphics,sound,vector3df(5000,-20,-3000), vector3df(0,0,0), ships().SHIPYARD, FACTION_TERRAN_FEDERATION, L"Blacksun Delta Shipyard", callback); if(shipyard) { item *rail = new item(items().PRI_RAIL); shipyard->addItemToInventory(rail); } Manager->addStation(shipyard); CShip *s2 = new CShip(graphics,sound,core::vector3df(-160000,-4000,3000),core::vector3df(0,0,0),ships().HQ,FACTION_PROVIAN_CONSORTIUM,L"Provian Headquarters", callback); Manager->addStation(s2); CShip *mine = new CShip(graphics,sound,core::vector3df(-40000,0,0),core::vector3df(0,0,0),ships().MINING_STATION,FACTION_PROVIAN_CONSORTIUM,L"Provian Mining Base", callback); Manager->addStation(mine); const wchar_t *pname2 = ships().provian_ship_name[rand()%ships().provian_ship_name.size()]; CShip *prov_cruiser2 = new CShip(graphics,sound, core::vector3df(-40000,0,-2000),core::vector3df(0,0,0),ships().PROV_ISHTAR_CRUISER,FACTION_PROVIAN_CONSORTIUM,pname2, callback); Manager->addShip(prov_cruiser2); const wchar_t *pname3 = ships().provian_ship_name[rand()%ships().provian_ship_name.size()]; CShip *prov_cruiser3 = new CShip(graphics,sound, core::vector3df(-7000,0,8000),core::vector3df(0,0,0),ships().PROV_ISHTAR_CRUISER,FACTION_PROVIAN_CONSORTIUM,pname3 ,callback); Manager->addShip(prov_cruiser3); const wchar_t *pname4 = ships().provian_ship_name[rand()%ships().provian_ship_name.size()]; CShip *prov_cruiser4 = new CShip(graphics,sound, core::vector3df(-8000,1000,7000),core::vector3df(0,0,0),ships().PROV_ISHTAR_CRUISER,FACTION_PROVIAN_CONSORTIUM,pname4, callback); Manager->addShip(prov_cruiser4); const wchar_t *pname5 = ships().provian_ship_name[rand()%ships().provian_ship_name.size()]; CShip *prov_cruiser5 = new CShip(graphics,sound, core::vector3df(-7000,0,6000),core::vector3df(0,0,0),ships().PROV_ARES_DESTROYER,FACTION_PROVIAN_CONSORTIUM,pname5, callback); Manager->addShip(prov_cruiser5); const wchar_t *pname6 = ships().provian_ship_name[rand()%ships().provian_ship_name.size()]; //CShip *prov_cruiser6 = new CShip(graphics,sound, core::vector3df(-7000,-1000,4000),core::vector3df(0,0,0),ships().PROV_ISHTAR_CRUISER,FACTION_PROVIAN_CONSORTIUM,pname6); //Manager->addShip(prov_cruiser6); const wchar_t *pname7 = ships().provian_ship_name[rand()%ships().provian_ship_name.size()]; //CShip *prov_cruiser7 = new CShip(graphics,sound, core::vector3df(-6000,500,6000),core::vector3df(0,0,0),ships().PROV_ISHTAR_CRUISER,FACTION_PROVIAN_CONSORTIUM,pname7); //Manager->addShip(prov_cruiser7); //create first objective //TODO: SAVE MISSIONS //TODO: READ MISSION TEXT FROM XML //USING STRINGS IN CODE IS NO BUENO missionM->addMission(missionCreate(graphics,1).tut); } void GameLoop::saveGame() { io::IXMLWriter *writer; writer = graphics->getFileSystem()->createXMLWriter("saves/save.lsav"); writer->writeXMLHeader(); writer->writeComment(L"edit this if you're lame or you're me"); //save ingame timer core::array<stringw> value; value.push_back(L"time"); core::array<stringw> num; //save number of missions stringw t(L""); t+=graphics->getTimer()->getTime(); num.push_back(t); writer->writeElement(L"gameInfo",true,value,num); //save all scene objects into xml file //donnt save hud and crap cause that changes dynamically writer->writeLineBreak(); CPlayer->saveObject(writer); writer->writeLineBreak(); CPlayer->saveCargo(writer); writer->writeLineBreak(); Manager->saveObjects(writer); writer->writeLineBreak(); missionM->saveMissions(writer); writer->drop(); } //Load game from xml saved file //TODO: LOAD MISSIONS void GameLoop::loadGame() { //xml stored save file //read data io::IXMLReader *reader = graphics->getFileSystem()->createXMLReader("saves/save.lsav"); if(!reader) { //couldnt read the save file for some reason } stringw currentSection; int num_ships; int num_cargo; int num_missions; while(reader->read()) { switch(reader->getNodeType()) { case io::EXN_ELEMENT: { //load time info if(core::stringw(L"gameInfo").equals_ignore_case(reader->getNodeName())) { graphics->getTimer()->setTime(reader->getAttributeValueAsInt(0)); } //read from playerstats if(core::stringw(L"playerStats").equals_ignore_case(reader->getNodeName())) { CPlayer->loadObject(reader); } //load from cargo elemeent //the extra code is because there are nested elements if(currentSection==L"" && core::stringw(L"playerCargo").equals_ignore_case(reader->getNodeName())) { currentSection=L"playerCargo"; num_cargo = reader->getAttributeValueAsInt(0); } else if (currentSection.equals_ignore_case(L"playerCargo")) { CPlayer->loadCargo(reader,num_cargo); } //read from shipstats element if(currentSection==L"" && core::stringw(L"shipStats").equals_ignore_case(reader->getNodeName())) { currentSection=L"shipStats"; num_ships = reader->getAttributeValueAsInt(0); } else if (currentSection.equals_ignore_case(L"shipStats")) { Manager->loadShips(reader,num_ships,callback); } //read from missions element if(currentSection==L"" && core::stringw(L"missions").equals_ignore_case(reader->getNodeName())) { currentSection=L"missions"; num_missions = reader->getAttributeValueAsInt(0); } else if(currentSection.equals_ignore_case(L"missions")) { missionM->loadMissions(reader,num_missions); } } break; case io::EXN_ELEMENT_END: { currentSection=L""; } break; } } printf("End of Loading Process"); reader->drop(); } bool GameLoop::exitGame() { //returns true if game wants to exit return GameExit; } void GameLoop::Run() { //main game loop //determine fps difference for frame independent movement u32 now = graphics->getTimer()->getTime(); frameDeltaTime = (f32)(now - then) *0.001f; // Time in seconds then = now; //escape menu code if(receiver->IsKeyDown(irr::KEY_ESCAPE)) { if(menu_open==false) { if(GamePaused==false) { menu_open = true; GamePaused=true; } else { menu_open = true; GamePaused=false; } } } else { menu_open = false; } //IF GAME RUNNING if(GamePaused==false) { escapeMenu->setVisible(false); //set to camera pos sound->setListenerPosition(pCam->getPosition(),pCam->getRotation()); // //CAMPAIGN STUFF //PLEASE PUT THIS //INSIDE SPECIFIC CAMPAIGN MANAGER CODEs if(missionM->getMissionList().size()>0) { if(missionM->getMissionList()[0]->getMissionComplete()==true) { if(display_tut==false) { CDialogueTree *complete = new CDialogueTree(graphics, L"Admiral Brennan", L"Excellent work! Destroying enemy ships is vital our operations in this system. If you haven't already noticed, destroyed enemy ships often leave behind cargo containers, which you can pick up for loot and then sell at the nearest station."); complete->addText(L"Now, things here have changed significantly since the time you left Earth. The Free-Traders Union is the most powerful group in this part of the galaxy, and we're in desperate need of their support"); complete->addText(L"We don't have the resources here to provide you with all supplies and weaponry that you'll need. You'll have to work as a semi-freelancer in order to get the money to equip your ship. You can make credits here by trading with different space stations, and doing jobs for the different corporations around this sector"); complete->addText(L"You'll still be needed for the war effort though. Terran Cruisers, such as your own, are in high demand around here. Our objectives in this system is to push the aliens back by capturing their planets. You can get to different planets by targetting them in the Navigations Console and then Warping towards that target."); complete->addText(L"That's not all though. There are some mysterious things occuring in this sector, and we might need you to check out some events. Stay safe, Captain"); dialogueM->addTree(complete); display_tut=true; } } } // //constantly update position of turning circle GUI XYcircle->setPosition(CPlayer->getPos()); XYcircle->setRotation(core::vector3df(0,CPlayer->turn.Y,0)); ZYcircle->setPosition(CPlayer->getPos()); ZYcircle->setRotation(core::vector3df(CPlayer->getRot().X,CPlayer->turn.Y,0)); TurningArrow->setRotation(core::vector3df(CPlayer->turn.X,CPlayer->turn.Y,0)); TurningArrow->setPosition(CPlayer->getPos()); //run functions alertBox->run(); //show alert texts Manager->gameManagerLoop(frameDeltaTime,sound, CPlayer,alertBox,callback); //update nodes and game scene ai CPlayer->manageTurrets(player_target,frameDeltaTime); //gives player target to turrets cameraControl(receiver,frameDeltaTime); //camera movement input dockMenu->menuLoop(CPlayer,docked_station); //dockmenu loop dialogueM->loop(); //communications missionM->loop(CPlayer,current_mission, Manager->ship_manager,alertBox); //loop through missions gameMenu->menuLoop(CPlayer,missionM); //menu loop CPlayer->playerRun(frameDeltaTime); //run through player funcs playerControl(receiver,frameDeltaTime,sound); //player key input CHud->updateHud(player_target,jump_target); //continually update hud targetMenu->loop(player_target); //update target info //dust is very very simple //simple moves around the dust cloud so the camera is always immersed in it for(int i=0; i<dust_manager.size();i++) { if(dust_manager[i]->getPosition().getDistanceFrom(pCam->getPosition())>1000) { vector3df pos(pCam->getPosition().X+rand()%2000-1000,pCam->getPosition().Y+rand()%2000-1000,pCam->getPosition().Z+rand()%2000-1000); dust_manager[i]->setPosition(pos); } } } else { //IF GAME PAUSED //escape menu escapeMenu->setVisible(true); //save game if(escapeMenu->getSaveButtonPressed()) { saveGame(); } if(escapeMenu->getQuitButtonPressed()) { GameExit=true; } } } //turns the turning circle on or off void GameLoop::setTurnCircleGUI(bool is_visible) { TurningArrow->setVisible(is_visible); XYcircle->setVisible(is_visible); ZYcircle->setVisible(is_visible); } //big func to move player and stuff //going to comment it more void GameLoop::playerControl(KeyListener *receiver, f32 frameDeltaTime,irrklang::ISoundEngine *sound) { //Used to constantly check whether the player is shooting or not //And pass on the target the player is targetting in order to shoot it Manager->playerShoot(graphics,CPlayer,sound,player_target,frameDeltaTime, targetMenu->getSelected()); //If the player clicks with the left mouse button //Check the gameManger object if there is any ship that the mouse is near //if there is a ship, return the ship object and set player_target to that ship //if there is no ship, return 0 if(CommandView!=true) { //player can only target other ships in normal view //player can only target planets in nav view if(NavView!=true) { //target selection only for non navigation view if(receiver->mouseLButtonDown()) { //this is so the player can select subsystems n stuff if(targetMenu->getVisible()!=true) player_target = Manager->getTarget(); } } else { //only be able to target planets in nav mode if(receiver->mouseLButtonDown()) { jump_target = Manager->getTargetPlanet(); } } } //a little bit of safety against crashes if(player_target!=0) { //if the player target is destroyed, set player target to zero so there is no crash if(player_target->getHullPoints()<1) { player_target=0; } //able to display the target menu if(receiver->IsKeyDown(irr::KEY_KEY_U)) { targetMenu->setVisible(true); } else targetMenu->setVisible(false); } else { targetMenu->setVisible(false); } //give the player a current mission if(gameMenu->getSelectedMission()!=0) { current_mission = gameMenu->getSelectedMission(); } else { current_mission = 0; } //if the player is alive if(CPlayer->getHull()>0) { //F1 Normal View //Shows ship targets but not planet targets if(NavView==false) { Manager->showPlanetTargets(false); Manager->showShipTargets(true); } else { Manager->showPlanetTargets(true); Manager->showShipTargets(false); } if(receiver->IsKeyDown(irr::KEY_F1)) { CommandView=false; NavView=false; } //F2 Command View //Used to order ships around if(receiver->IsKeyDown(irr::KEY_F2)) { CommandView=true; NavView=false; } //F3 Navigational View //Shows planet targets but not ship targets if(receiver->IsKeyDown(irr::KEY_F3)) { CommandView = false; NavView = true; } //if docked open dockmenu if(CPlayer->getDocked()==true) { dockMenu->setMenuOpen(true); } else { dockMenu->setMenuOpen(false); } //show nav lines if(NavView==true) { core::dimension2d<s32> p = graphics->getSceneManager()->getSceneCollisionManager()->getScreenCoordinatesFrom3DPosition(CPlayer->getPos(),pCam); player_nav->setVisible(true); player_nav->setRelativePosition(vector2d<s32>(p.Width-32,p.Height-32)); if(jump_target!=0) { core::dimension2d<s32> t = graphics->getSceneManager()->getSceneCollisionManager()->getScreenCoordinatesFrom3DPosition(jump_target->getPos(),pCam); graphics->getVideoDriver()->draw2DLine(p,t,SColor(255,255,255,0)); } } else player_nav->setVisible(false); //If the player presses V (to dock) dock player at station //station has to be targetted if(receiver->IsKeyDown(irr::KEY_KEY_V)) { //dock_open === key release //temporary if(dock_open==false) { dock_open=true; if(CPlayer->getDocked()==false) { if(player_target!=0) { //Ensure that the target is within a certain distance in order to dock if(player_target->getPos().getDistanceFrom(CPlayer->getPos())<SHIP_DOCK_DISTANCE) { if(player_target->getIsStation()) { docked_station = player_target; velocity=0; CPlayer->setVelocity(velocity); CPlayer->setDocked(true); CPlayer->setPos(player_target->getPos()); CPlayer->setRot(vector3df(0,0,0)); } } } } else { CPlayer->setDocked(false); } } } else { dock_open=false; } //warp code //If the Player presses J (to warp) if(receiver->IsKeyDown(irr::KEY_KEY_J)) { if(jump_target!=0) { float x(jump_target->getPos().X - CPlayer->getPos().X); float y(jump_target->getPos().Y - CPlayer->getPos().Y); float z(jump_target->getPos().Z - CPlayer->getPos().Z); float angleY = std::atan2(x,z)*180/3.14159265; float tmp = sqrt(x*x+ z*z); float angleX = std::atan2(tmp,y)*180/3.14159265; angleX-=90; CPlayer->turn.X = angleX; CPlayer->turn.Y = angleY; Warp=true; } } //if warp button pressed if(Warp == true) { //ensure that player hasn't deselected the target, or else game will crash if(jump_target!=0) { if(CPlayer->getRot().Y+3>CPlayer->turn.Y && CPlayer->getRot().Y-3<CPlayer->turn.Y &&CPlayer->getRot().X+3>CPlayer->turn.X && CPlayer->getRot().X-3<CPlayer->turn.X) { if(CPlayer->getPos().getDistanceFrom(jump_target->getPos())>SHIP_WARP_DISTANCE) { velocity = SHIP_WARP_SPEED; CPlayer->setVelocity(velocity); if(distance<CAMERA_DISTANCE_MAX) distance+=50; } else { Warp = false; velocity = 0; CPlayer->setVelocity(velocity); if(distance>CAMERA_DISTANCE_MAX/2) { distance-=50; } } } } else { //if the player deselects planet, cancel warp Warp = false; } } //end warp code //fighter code if(gameMenu->getSendFighters() || receiver->IsKeyDown(irr::KEY_KEY_N)) { LaunchFighters=true; } if(LaunchFighters==true) { //deploy fighters if(CPlayer->getNumFighters()>0) { if(CPlayer->getFighterCreationTime() < graphics->getTimer()->getTime()) { vector3df pos = CPlayer->getPos(); pos+=vector3df(rand()%100-50,rand()%100-50,rand()%100-50); fighter *f = new fighter(graphics,sound,CPlayer->getPos(),CPlayer->getRot(),CPlayer->getFighterType(),FACTION_TERRAN_FEDERATION,CPlayer->ship); f->setTarget(player_target); if(player_target!=0) f->moveToPoint(player_target->getPos()); Manager->addFighter(f); CPlayer->addFighterCount(-1); CPlayer->setFighterCreationTime(graphics->getTimer()->getTime()+CPlayer->getFighterLaunchTime()); CPlayer->fighter_manager.push_back(f); } } else LaunchFighters=false; } if(gameMenu->getReturnFighters()) { /* for(int i=0; i<Manager->fighter_manager.size();i++) { //find player fighters if(Manager->fighter_manager[i]->getHomeBase()==CPlayer->ship) { Manager->fighter_manager[i]->setReturnHome(true); } } */ CPlayer->setFighterCount(10); } //movement code //ensure movement code is done only when not docked //and not during warps if(CPlayer->getDocked()!=true) { if(Warp!=true) { //get input and do stuff with it if(receiver->IsKeyDown(irr::KEY_KEY_A)) { CPlayer->turn.Y-=35*frameDeltaTime; } if(receiver->IsKeyDown(irr::KEY_KEY_D)) { CPlayer->turn.Y += 35*frameDeltaTime; } if(receiver->IsKeyDown(irr::KEY_KEY_W)) { if(CPlayer->turn.X<70) CPlayer->turn.X+=35*frameDeltaTime; } if(receiver->IsKeyDown(irr::KEY_KEY_S)) { if(CPlayer->turn.X>-70) CPlayer->turn.X-=35*frameDeltaTime; } if(receiver->IsKeyDown(irr::KEY_KEY_Q)) { CPlayer->turn.Y=CPlayer->getRot().Y; CPlayer->turn.X=CPlayer->getRot().X; CPlayer->turn.Z=CPlayer->getRot().Z; } //get input to add velocity to player if(receiver->IsKeyDown(irr::KEY_KEY_X)) { if(CPlayer->getVelocity() < CPlayer->getMaxSpeed()) //dont let velocity get above maxspeed { velocity+=(5+abs(velocity)/2)*frameDeltaTime; CPlayer->setVelocity(velocity); } } if(receiver->IsKeyDown(irr::KEY_KEY_Z)) { if(CPlayer->getVelocity() > -10) { velocity-=5*frameDeltaTime; CPlayer->setVelocity(velocity); } } //self explainatory if(receiver->IsKeyDown(irr::KEY_SPACE)) { if(player_target!=0) CPlayer->shoot(); } else CPlayer->resetCannons(); } } if(CPlayer->getHull()<1) { //if player died //fade out the screen gui::IGUIInOutFader *fader =graphics->getGUIEnvironment()->addInOutFader(0,0); fader->setColor(SColor(0,0,0,0)); fader->fadeOut(400); GamePaused=true; } //show turning circle only when turning if(CPlayer->getRot().Y-3>CPlayer->turn.Y | CPlayer->getRot().Y+3<CPlayer->turn.Y | CPlayer->getRot().X-3>CPlayer->turn.X | CPlayer->getRot().X+3<CPlayer->turn.X) setTurnCircleGUI(true); else setTurnCircleGUI(false); // open the crew/cargo/stats/loadout menu if(receiver->IsKeyDown(irr::KEY_KEY_C)) { if(CPlayer->getDocked()==false) { if(menuop==true) { menuop=false; if(gameMenu->getMenuOpen()==true) { gameMenu->setMenuOpen(false); } else { gameMenu->setMenuOpen(true); } } } } else { menuop=true; } } } void GameLoop::cameraControl(KeyListener *receiver, f32 frameDeltaTime) { tMouseW = receiver->mouseWheel(); //different camera for nav view if(NavView!=true) { //pCam->bindTargetAndRotation(true); //constantly update camera position //to track player //TODO::add camera sway like in BSGO and EvE pCam->setTarget(CPlayer->getPos()); //use sine? //vector3df pos = CPlayer->getPos(); //float tmp = camera_sway*frameDeltaTime; //pos.Y += sin(tmp); //pCam->setTarget(pos); //move camera by determining if mouse moved //check pixels the mouse moved if(receiver->mouseRButtonDown()==true) { if(receiver->mouseX()!=tMouseX) { int i=receiver->mouseX()-tMouseX; tMouseX=receiver->mouseX(); angle+=i; } if(receiver->mouseY()!=tMouseY) { int t=receiver->mouseY()-tMouseY; tMouseY=receiver->mouseY(); angle2+=t; } } //change distance of camera to player if(receiver->IsKeyDown(irr::KEY_MINUS)) { if(distance<CAMERA_DISTANCE_MAX) distance+=10; } if(receiver->IsKeyDown(irr::KEY_PLUS)) { if(distance>CAMERA_DISTANCE_MIN) distance-=10; } //mousewheel if(tMouseW < tMouseW_old) { if(distance > CAMERA_DISTANCE_MIN) { distance+=(tMouseW-tMouseW_old)*CAMERA_MOUSE_WHEEL; tMouseW_old = tMouseW; } } if(tMouseW > tMouseW_old) { if(distance < CAMERA_DISTANCE_MAX) { distance+=(tMouseW-tMouseW_old)*CAMERA_MOUSE_WHEEL; tMouseW_old = tMouseW; } } //if angle is too big or too small //put it back in 360 limit if (angle > 360) angle -= 360; else if (angle < 0) angle += 360; if(angle2>360) angle-=360; if(angle<0) angle+=360; //distance cannot be less than zero, or else there will be inversion if(distance<0) distance=0; tMouseX=receiver->mouseX(); tMouseY=receiver->mouseY(); core::vector3df targ = pCam->getTarget(); core::vector3df playerCameraPos; //3d trig //this math is to determine the location of orbiting camera playerCameraPos.Y = sin(angle2*3.14/180)*distance; playerCameraPos.Y += targ.Y; float temp; temp=cos(angle2*3.14/180); //some code to calculate position core::vector3df old; playerCameraPos.X = (sin((angle) * 3.141 / 180) * (distance)); playerCameraPos.X = playerCameraPos.X*temp; playerCameraPos.X += targ.X; playerCameraPos.Z = (cos((angle) * 3.141/ 180) * (distance)); playerCameraPos.Z = playerCameraPos.Z*temp; playerCameraPos.Z += targ.Z; //smooth out camera motion old = pCam->getPosition(); old=old*0.8+playerCameraPos*0.2f; pCam->setPosition(old); } else { //nav view //pCam->bindTargetAndRotation(false); pCam->setPosition(core::vector3df(CPlayer->getPos().X,nav_distance,CPlayer->getPos().Z)); if(tMouseW < tMouseW_old) { nav_distance+=(tMouseW-tMouseW_old)*500; tMouseW_old = tMouseW; } if(tMouseW > tMouseW_old) { nav_distance+=(tMouseW-tMouseW_old)*500; tMouseW_old = tMouseW; } } }
#include<bits/stdc++.h> using namespace std; int main() { int x,y,rem; cin>>x>>y; if(x == y) { cout<<"O JOGO DUROU 24 HORA(S)\n"; } else if(x>y) { rem = 24-x; rem = rem+y; cout<<"O JOGO DUROU "<<rem<<" HORA(S)\n"; } else if(x<y) { rem = y-x; cout<<"O JOGO DUROU "<<rem<<" HORA(S)\n"; } return 0; }
#include "topicTree.h" #include "frame.h" #include "util.h" #include <map> #include <vector> TopicNode::TopicNode(std::string part, std::string fPath) : name(part), nodes(), fullPath(fPath), retainMessage(""), retainQoS(0), subscribers() {} TopicNode::~TopicNode() { for (std::map<std::string, TopicNode*>::iterator itPair = nodes.begin(); itPair != nodes.end(); itPair++) { delete itPair->second; } } MQTT_ERROR TopicNode::getNodesByNumberSign(std::vector<TopicNode*>* resp) { if (fullPath.find_last_of("/") != std::string::npos) { fullPath = fullPath.substr(0, fullPath.size()-1); } MQTT_ERROR err = NO_ERROR; resp->push_back(this); if (nodes.size() > 0) { for (std::map<std::string, TopicNode*>::iterator itPair = nodes.begin(); itPair != nodes.end(); itPair++) { if (itPair->first[0] == '$') { continue; } err = itPair->second->getNodesByNumberSign(resp); if (err != NO_ERROR) { return err; } } } return err; } MQTT_ERROR TopicNode::getTopicNode(const std::string topic, bool addNewNode, std::vector<TopicNode*>* resp) { std::string currentPath = ""; std::vector<std::string> parts; split(topic, "/", &parts); TopicNode *nxt = this, *bef; MQTT_ERROR err = NO_ERROR; std::string part; for (int i = 0; i < parts.size(); i++) { bef = nxt; part = parts[i]; if (part == "+") { for (std::map<std::string, TopicNode*>::iterator itPair = bef->nodes.begin(); itPair != bef->nodes.end(); itPair++) { if (itPair->first[0] == '$') { continue; } std::string filledStr = topic; filledStr.replace(topic.find_first_of("+"), 1, itPair->first); err = getTopicNode(filledStr, addNewNode, resp); if (err != NO_ERROR) { return err; } } } else if (part == "#") { if (i != parts.size() - 1) { return MULTI_LEVEL_WILDCARD_MUST_BE_ON_TAIL; } err = getNodesByNumberSign(resp); } else { if (part.find_last_of("#") != std::string::npos || part.find_last_of("+") != std::string::npos) { return WILDCARD_MUST_NOT_BE_ADJACENT_TO_NAME; } currentPath += part; if (part.size()-1 != i) { currentPath += "/"; } if (bef->nodes.find(part) == bef->nodes.end() && addNewNode) { bef->nodes[part] = new TopicNode(part, currentPath); } else if (bef->nodes.find(part) == bef->nodes.end()) { continue; } nxt = bef->nodes[part]; if (parts.size() - 1 == i) { resp->push_back(nxt); } } } return err; } MQTT_ERROR TopicNode::applySubscriber(const std::string clientID, const std::string topic, uint8_t qos, std::vector<SubackCode>* resp) { std::vector<TopicNode*> subNodes; MQTT_ERROR err = getTopicNode(topic, true, &subNodes); if (err != NO_ERROR) { return err; } for (std::vector<TopicNode*>::iterator it = subNodes.begin(); it != subNodes.end(); it++) { // TODO: the return qos should be managed by broker (*it)->subscribers[clientID] = qos; resp->push_back((SubackCode)qos); } return err; } MQTT_ERROR TopicNode::deleteSubscriber(const std::string clientID, const std::string topic) { std::vector<TopicNode*> subNodes; MQTT_ERROR err= getTopicNode(topic, false, &subNodes); if (err != NO_ERROR) { return err; } for (std::vector<TopicNode*>::iterator it = subNodes.begin(); it != subNodes.end(); it++) { (*it)->subscribers.erase(clientID); } return err; } MQTT_ERROR TopicNode::applyRetain(const std::string topic, uint8_t qos, const std::string retain) { std::vector<TopicNode*> retainNodes; MQTT_ERROR err = getTopicNode(topic, true, &retainNodes); if (err != NO_ERROR) { return err; } for (std::vector<TopicNode*>::iterator it = retainNodes.begin(); it != retainNodes.end(); it++) { (*it)->retainMessage = retain; (*it)->retainQoS = qos; } return err; } std::vector<std::string> TopicNode::dumpTree() { std::vector<std::string> strs; if (nodes.size() == 0) { strs.push_back(this->name); return strs; } for (std::map<std::string, TopicNode*>::iterator itPair = nodes.begin(); itPair != nodes.end(); itPair++) { std::vector<std::string> deepStrs = itPair->second->dumpTree(); std::string currentPath = ""; if (this->name.size() > 0) { currentPath = this->name + "/"; } for (std::vector<std::string>::iterator it = deepStrs.begin(); it != deepStrs.end(); it++) { strs.push_back(currentPath + *it); } } return strs; }
#include <fstream> #include "psef22_8_opt.h" int main() { ofstream in_pix("input_pixels_regression_result_psef22_8_opt.txt"); ofstream fout("regression_result_psef22_8_opt.txt"); HWStream<hw_uint<128> > in_update_0_read; HWStream<hw_uint<128> > psef22_8_update_0_write; // Loading input data // cmap : { in_update_0[root = 0, in_0, in_1] -> in_off_chip[0, 0] : 0 <= in_0 <= 159 and 0 <= in_1 <= 1262 } // read map: { in_off_chip[0, 0] -> in_update_0[root = 0, in_0, in_1] : 0 <= in_0 <= 159 and 0 <= in_1 <= 1262 } // rng : { in_update_0[root = 0, in_0, in_1] : 0 <= in_0 <= 159 and 0 <= in_1 <= 1262 } for (int i = 0; i < 202080; i++) { hw_uint<128> in_val; set_at<0*16, 128, 16>(in_val, 8*i + 0); in_pix << in_val << endl; set_at<1*16, 128, 16>(in_val, 8*i + 1); in_pix << in_val << endl; set_at<2*16, 128, 16>(in_val, 8*i + 2); in_pix << in_val << endl; set_at<3*16, 128, 16>(in_val, 8*i + 3); in_pix << in_val << endl; set_at<4*16, 128, 16>(in_val, 8*i + 4); in_pix << in_val << endl; set_at<5*16, 128, 16>(in_val, 8*i + 5); in_pix << in_val << endl; set_at<6*16, 128, 16>(in_val, 8*i + 6); in_pix << in_val << endl; set_at<7*16, 128, 16>(in_val, 8*i + 7); in_pix << in_val << endl; in_update_0_read.write(in_val); } psef22_8_opt(in_update_0_read, psef22_8_update_0_write); for (int i = 0; i < 196250; i++) { hw_uint<128> actual = psef22_8_update_0_write.read(); auto actual_lane_0 = actual.extract<0*16, 15>(); fout << actual_lane_0 << endl; auto actual_lane_1 = actual.extract<1*16, 31>(); fout << actual_lane_1 << endl; auto actual_lane_2 = actual.extract<2*16, 47>(); fout << actual_lane_2 << endl; auto actual_lane_3 = actual.extract<3*16, 63>(); fout << actual_lane_3 << endl; auto actual_lane_4 = actual.extract<4*16, 79>(); fout << actual_lane_4 << endl; auto actual_lane_5 = actual.extract<5*16, 95>(); fout << actual_lane_5 << endl; auto actual_lane_6 = actual.extract<6*16, 111>(); fout << actual_lane_6 << endl; auto actual_lane_7 = actual.extract<7*16, 127>(); fout << actual_lane_7 << endl; } in_pix.close(); fout.close(); return 0; }
#ifndef DESIGNPATTERN_OBSERVER_IOBSERVER_H_ #define DESIGNPATTERN_OBSERVER_IOBSERVER_H_ #include "common.h" #include <string> namespace DesignPatter { interface IObserver { virtual bool Update(const std::string& data) = 0; }; } #endif
#include <iostream> #include <string> #include <map> using namespace std; int main(int argc, const char *argv[]) { map< string,int > word_count; string str; while(cin >> str) { ++word_count[str]; } for (map<string,int>::iterator map_iter = word_count.begin(); map_iter != word_count.end(); ++map_iter) { cout << map_iter->first << " " << map_iter->second << endl; } return 0; }
#ifndef FRAME_H #define FRAME_H #include "slaveslam/camera.h" #include "slaveslam/common_include.h" namespace slaveslam { class Frame { public: typedef std::shared_ptr<Frame> Ptr; unsigned long id_; double time_stamp_; SE3 T_c_w_; Camera::Ptr camera_; Mat color_ , depth_; public: Frame(); Frame(long id, double time_stamp = 0.0, SE3 T_c_w = SE3(), Camera::Ptr camera = nullptr, Mat color = Mat(), Mat depth = Mat()); ~Frame(); //factory function static Frame::Ptr createFrame(); //find the depth in depth map double findDepth(const cv::KeyPoint& kp); //Get Camera Center Vector3d getCamCenter() const; //check if a point is in this frame bool isInFrame(const Vector3d& pt_world); }; } #endif
#include <iostream> #include <cstdlib> #include <cassert> #include <cstdlib> #include <cstdlib> #include <cassert> #include <cstdlib> #include <cassert> // #template random.h: do not remove this line int rand32() { return (int(rand()) << 20) ^ (int(rand()) << 10) ^ int(rand()); } LL rand64() { return (LL(rand32()) << 32) ^ LL(rand32()); } uint randu32() { return (uint(rand()) << 20) ^ (uint(rand()) << 10) ^ uint(rand()); } ULL randu64() { return (ULL(randu32()) << 32) ^ ULL(randu32()); } bool flip_coin(const uint a, const uint b) { return randu32() % (a + b) < a; } int randint(int l, int r) { return randu32() % (r - l + 1) + l; } double randfloat() { return LD(randu64()) / (1ll << 32) / (1ll << 32); } // end of random.h // #template base.h: do not remove this line typedef long long LL; typedef unsigned long long ULL; typedef long double LD; typedef unsigned int uint; // end of base.h int main() { return 0; }
// Copyright (c) 2017 Mozart Alexander Louis. All rights reserved. // Includes #include "data_utils.hxx" #include "xxhash/xxhash.h" void DataUtils::initDatabase() { // Get database instance. const auto db = getDatabase(); // Creating the main sqlite statement to create the tables if they haven't been created yet sqlite3_stmt* stmt = nullptr; vector<const char*> statements = {__DI_SQLC_OTHER_DATA__, __DI_SQLC_SCORE_DATA__, __DI_SQLC_STORE_DATA__, __DI_SQLC_TRIAL_DATA__}; // Run each create statement.. for (const auto& statement : statements) if (sqlite3_prepare_v2(db, statement, -1, &stmt, nullptr) == SQLITE_OK) if (sqlite3_step(stmt) != SQLITE_DONE) __CCLOGWITHFUNCTION("Error trying to create table..."); // Finalize the transactions, Close the database sqlite3_finalize(stmt); sqlite3_close(db); } void DataUtils::saveOtherData(const string& key, const int value) { // Get database instance. const auto db = getDatabase(); // Create the local statement that will be used to insert data. Doing it this // way to make it more readable stringstream fmt; fmt << "INSERT OR REPLACE INTO " << __DI_SQLT_OTHER_DATA__ << "(key, value_int) VALUES(?, ?)"; const auto statement = fmt.str(); // Attempt to insert data sqlite3_stmt* stmt; if (sqlite3_prepare_v2(db, statement.c_str(), -1, &stmt, nullptr) == SQLITE_OK) { // Bind all of the necessary variables sqlite3_bind_int(stmt, 1, generateHashKey(key)); sqlite3_bind_int(stmt, 2, value); if (sqlite3_step(stmt) != SQLITE_DONE) __CCLOGWITHFUNCTION("Failed while saving data... STATEMENT: %s", sqlite3_errmsg(db)); } // Reset, finalize and close db sqlite3_reset(stmt); sqlite3_finalize(stmt); sqlite3_close(db); } void DataUtils::saveOtherData(const string& key, const string value) { // Get database instance. const auto db = getDatabase(); // Create the local statement that will be used to insert data. Doing it this // way to make it more readable stringstream fmt; fmt << "INSERT OR REPLACE INTO " << __DI_SQLT_OTHER_DATA__ << "(key, value_string) VALUES(?, ?)"; // Attempt to insert data sqlite3_stmt* stmt; if (sqlite3_prepare_v2(db, fmt.str().c_str(), -1, &stmt, nullptr) == SQLITE_OK) { // Bind all of the necessary variables sqlite3_bind_int(stmt, 1, generateHashKey(key)); sqlite3_bind_text(stmt, 2, value.c_str(), -1, SQLITE_STATIC); if (sqlite3_step(stmt) != SQLITE_DONE) __CCLOGWITHFUNCTION("Error... Attempting to save data... STATEMENT: %s", sqlite3_errmsg(db)); } // Reset, finalize and close db sqlite3_reset(stmt); sqlite3_finalize(stmt); sqlite3_close(db); } int DataUtils::getOtherData(const string& key, const int default_value) { // Get database instance. const auto db = getDatabase(); // Create the local statement that will be used to insert data. Doing it this // way to make it more readable stringstream fmt; fmt << "SELECT value_int FROM " << __DI_SQLT_OTHER_DATA__ << " WHERE key=?"; // select data sqlite3_stmt* stmt; if (sqlite3_prepare_v2(db, fmt.str().c_str(), -1, &stmt, nullptr) == SQLITE_OK) { // Bind hash key to query sqlite3_bind_int(stmt, 1, generateHashKey(key)); // If the key returns a row, the data is good if (sqlite3_step(stmt) == SQLITE_ROW) { const auto result = sqlite3_column_int(stmt, 0); // Reset, finalize and close db sqlite3_reset(stmt); sqlite3_finalize(stmt); sqlite3_close(db); // Return result return result; } __CCLOGWITHFUNCTION("Error... Key Does not exist: %s", key.c_str()); } else __CCLOGWITHFUNCTION("Error... : %s", sqlite3_errmsg(db)); // Reset, finalize and close db sqlite3_reset(stmt); sqlite3_finalize(stmt); sqlite3_close(db); // check the return value and cipher if it's not the default; return default_value; } string DataUtils::getOtherData(const string& key, const string& default_value) { // Get database instance. const auto db = getDatabase(); // Create the local statement that will be used to insert data. Doing it this // way to make it more readable stringstream fmt; fmt << "SELECT value_string FROM " << __DI_SQLT_OTHER_DATA__ << " WHERE key=?"; // select data sqlite3_stmt* stmt; if (sqlite3_prepare_v2(db, fmt.str().c_str(), -1, &stmt, nullptr) == SQLITE_OK) { // Bind hash key to query sqlite3_bind_int(stmt, 1, generateHashKey(key)); // If the key returns a row, the data is good if (sqlite3_step(stmt) == SQLITE_ROW) { auto result = string(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0))); // Reset, finalize and close db sqlite3_reset(stmt); sqlite3_finalize(stmt); sqlite3_close(db); // Return result return result; } __CCLOGWITHFUNCTION("Error... Key Does not exist: %s", key.c_str()); } else __CCLOGWITHFUNCTION("Error... : %s", sqlite3_errmsg(db)); // Reset, finalize and close db sqlite3_reset(stmt); sqlite3_finalize(stmt); sqlite3_close(db); // check the return value and cipher if it's not the default; return default_value; } void DataUtils::saveScoreData(ValueMap values) { // Get database instance. const auto db = getDatabase(); // Create the local statement that will be used to insert data. Doing it this way to make it more readable stringstream fmt; fmt << "INSERT OR REPLACE INTO " << __DI_SQLT_SCORE_DATA__; fmt << "(level, trial, score, stars, lluma, color, music, pattern) VALUES(?, ?, ?, ?, ?, ?, ?, ?)"; // Attempt to insert data sqlite3_stmt* stmt; if (sqlite3_prepare_v2(db, fmt.str().c_str(), -1, &stmt, nullptr) == SQLITE_OK) { // Bind all of the necessary variables sqlite3_bind_int(stmt, 1, values[__LEVEL__].asInt()); sqlite3_bind_int(stmt, 2, values[__TRIAL__].asInt()); sqlite3_bind_int(stmt, 3, values[__SCORE__].asInt()); sqlite3_bind_int(stmt, 4, values[__STARS__].asInt()); sqlite3_bind_text(stmt, 5, values[__LLUMA__].asString().c_str(), -1, SQLITE_STATIC); sqlite3_bind_text(stmt, 6, values[__COLOR__].asString().c_str(), -1, SQLITE_STATIC); sqlite3_bind_text(stmt, 7, values[__MUSIC__].asString().c_str(), -1, SQLITE_STATIC); sqlite3_bind_text(stmt, 8, values[__PATTERN__].asString().c_str(), -1, SQLITE_STATIC); if (sqlite3_step(stmt) != SQLITE_DONE) __CCLOGWITHFUNCTION("Error... Attempting to save data... STATEMENT: %s", sqlite3_errmsg(db)); } else __CCLOGWITHFUNCTION("Error... STATEMENT: %s", sqlite3_errmsg(db)); // Reset, finalize and close db sqlite3_reset(stmt); sqlite3_finalize(stmt); sqlite3_close(db); } void DataUtils::saveTrialData(ValueMap values) { // Get database instance. const auto db = getDatabase(); // Create the local statement that will be used to insert data. Doing it this way to make it more readable stringstream fmt; fmt << "INSERT OR REPLACE INTO " << __DI_SQLT_TRIAL_DATA__ << "(trial, stars, unlocked, last) VALUES(?, ?, ?, ?)"; // Attempt to insert data sqlite3_stmt* stmt; if (sqlite3_prepare_v2(db, fmt.str().c_str(), -1, &stmt, nullptr) == SQLITE_OK) { // Bind all of the necessary variables sqlite3_bind_int(stmt, 1, values[__TRIAL__].asInt()); sqlite3_bind_int(stmt, 2, values[__STARS__].asInt()); sqlite3_bind_int(stmt, 3, values[__UNLOCKED__].asInt()); sqlite3_bind_int(stmt, 4, values[__LAST__].asInt()); if (sqlite3_step(stmt) != SQLITE_DONE) __CCLOGWITHFUNCTION("Error... Attempting to save data... STATEMENT: %s", sqlite3_errmsg(db)); } else __CCLOGWITHFUNCTION("Error... STATEMENT: %s", sqlite3_errmsg(db)); // Reset, finalize and close db sqlite3_reset(stmt); sqlite3_finalize(stmt); sqlite3_close(db); } void DataUtils::saveStoreData(const string& item) { // Get database instance. const auto db = getDatabase(); // Create the local statement that will be used to insert data. Doing it this // way to make it more readable stringstream fmt; fmt << "INSERT OR REPLACE INTO " << __DI_SQLT_STORE_DATA__ << "(item) VALUES(?)"; // Attempt to insert data sqlite3_stmt* stmt; if (sqlite3_prepare_v2(db, fmt.str().c_str(), -1, &stmt, nullptr) == SQLITE_OK) { // Bind all of the necessary variables sqlite3_bind_text(stmt, 1, item.c_str(), -1, SQLITE_STATIC); if (sqlite3_step(stmt) != SQLITE_DONE) __CCLOGWITHFUNCTION("Error... Attempting to save data... STATEMENT: %s", sqlite3_errmsg(db)); } // Reset, finalize and close db sqlite3_reset(stmt); sqlite3_finalize(stmt); sqlite3_close(db); } string DataUtils::getStoreData(const string& item, const string& default_value) { // Get database instance. const auto db = getDatabase(); // Create the local statement that will be used to insert data. Doing it this way to make it more readable stringstream fmt; fmt << "SELECT * FROM " << __DI_SQLT_STORE_DATA__ << " WHERE item=?"; // select data sqlite3_stmt* stmt; if (sqlite3_prepare_v2(db, fmt.str().c_str(), -1, &stmt, nullptr) == SQLITE_OK) { // Bind hash key to query sqlite3_bind_text(stmt, 1, item.c_str(), -1, SQLITE_STATIC); // If the key returns a row, the data is good if (sqlite3_step(stmt) == SQLITE_ROW) { // Generate all the ciphers for the player and return the data; const auto result = string(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0))); // Reset, finalize and close db sqlite3_reset(stmt); sqlite3_finalize(stmt); sqlite3_close(db); // Return result return result; } __CCLOGWITHFUNCTION("Error... Key Does not exist: %s", item.c_str()); } else __CCLOGWITHFUNCTION("Error... : %s", sqlite3_errmsg(db)); // Reset, finalize and close db sqlite3_reset(stmt); sqlite3_finalize(stmt); sqlite3_close(db); // check the return value and cipher if it's not the default; return default_value; } vector<string> DataUtils::getAllStoreData() { // Get database instance. const auto db = getDatabase(); vector<string> data; // Create the local statement that will be used to insert data. Doing it this way to make it more readable stringstream fmt; fmt << "SELECT * FROM " << __DI_SQLT_STORE_DATA__; // select data sqlite3_stmt* stmt; if (sqlite3_prepare_v2(db, fmt.str().c_str(), -1, &stmt, nullptr) == SQLITE_OK) { while (sqlite3_step(stmt) == SQLITE_ROW) { // Generate all the ciphers for the player and return the data; data.emplace_back(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0))); } } else __CCLOGWITHFUNCTION("Error... : %s", sqlite3_errmsg(db)); // Reset, finalize and close db sqlite3_reset(stmt); sqlite3_finalize(stmt); sqlite3_close(db); return data; } sqlite3* DataUtils::getDatabase() { // Use FileUtils to get the path of the database const auto& path = FileUtils::getInstance()->getWritablePath() + __DI_DB_NAME__; sqlite3* db; // Attempt to open this database on the device if (sqlite3_open(path.c_str(), &db) == SQLITE_OK) { sqlite3_key(db, to_string(getDatabaseKey()).c_str(), int(strlen(to_string(getDatabaseKey()).c_str()))); return db; } // This will only happen if the user has somehow tampered with the database. throw runtime_error("Error: Cannot open or create database..."); } int DataUtils::getDatabaseKey() { const string part1 = "a728df263ab5d6fdb3d8"; const string part2 = "c6730c6eafafe58839bb"; const string part3 = "054c4fba1cfd2b6df083"; const string part4 = "be76b7ab05dd4198d23b"; return generateHashKey(part1 + part3 + part2 + part4); } int DataUtils::generateHashKey(const string& key) { // WARNING, CHANGING THIS BASICALLY BRAKES EVERYTHING. return abs(int(XXH32((key + to_string(__DI_HSALT_03__)).c_str(), int(key.length()), __DI_HSALT_01__ + __DI_HSALT_02__))); }
// // Created by Brady Bodily on 2/3/17. // #ifndef ANALYSTCOMPARER_ANALYST_HPP #define ANALYSTCOMPARER_ANALYST_HPP #include <string> #include <vector> #include "History.hpp" class Analyst { private: std::string m_name; std::string m_initials; History m_history; public: Analyst(std::string name, std::string initials, int days, int seedMoney); std::string getName(); std::string getInitials(); std::vector<std::string> getStocks(); double computeTLPD(); int getDays(); int getSeedMoney(); }; #endif //ANALYSTCOMPARER_ANALYST_HPP
#include <petunia/ipc_medium_default.h> #include <petunia/petunia.h> #include <petunia/osutils.h> #include <assert.h> #include <sqlite3/CppSQLite3.h> #define CHANNEL_FILE_EXTENSION ".ipc.db" #define MAX_CHANNEL_DELETE_TRIES 1 namespace Petunia { class IPCInternalMedium : public IPCMedium { public: IPCInternalMedium(std::string &channel, ConnectionRole connection_role /*= ConnectionRole::Auto*/) :IPCMedium(channel, connection_role) { m_channel_path = GenerateChannelPath(); InitializeDatabase(); } void InitializeDatabase() { m_ipc_database.open(m_channel_path.c_str()); m_ipc_database.execDML("PRAGMA synchronous = OFF"); m_ipc_database.execDML("PRAGMA journal_mode = OFF"); m_ipc_database.execDML("PRAGMA mmap_size=44194304"); m_ipc_database.execDML("PRAGMA busy_timeout=30000"); bool database_already_created = m_ipc_database.tableExists("to_client"); if (m_connection_role == ConnectionRole::Auto) { if (!database_already_created) { m_connection_role = ConnectionRole::Server; } else { m_connection_role = ConnectionRole::Client; } } if (!database_already_created) { m_ipc_database.execDML("CREATE TABLE to_client(type TEXT, size NUMBER, blob_message BLOB, row_id INTEGER PRIMARY KEY)"); m_ipc_database.execDML("CREATE TABLE to_server(type TEXT, size NUMBER, blob_message BLOB, row_id INTEGER PRIMARY KEY)"); m_ipc_database.execDML("CREATE INDEX idx_to_client_type ON to_client(type)"); m_ipc_database.execDML("CREATE INDEX idx_to_server_type ON to_server(type)"); } CreateStatements(); } ~IPCInternalMedium() { m_begin_transaction_stmt.finalize(); m_commit_transaction_stmt.finalize(); m_insert_message_stmt.finalize(); m_update_message_stmt.finalize(); m_delete_old_messages_stmt.finalize(); m_select_messages_stmt.finalize(); m_ipc_database.close(); if (m_connection_role == ConnectionRole::Server) { TryDeleteChannel(); } } void CreateStatements() { m_begin_transaction_stmt = m_ipc_database.compileStatement("BEGIN TRANSACTION"); m_commit_transaction_stmt = m_ipc_database.compileStatement("COMMIT"); if (m_connection_role == ConnectionRole::Server) { m_insert_message_stmt = m_ipc_database.compileStatement("INSERT INTO to_client " "(" " type," " size," " blob_message" ")" "VALUES" "(" " @type," " @size," " @blob_message" ")"); m_update_message_stmt = m_ipc_database.compileStatement("UPDATE to_client SET " " size = @size," " blob_message = @blob_message " "WHERE " " type = @type"); m_delete_old_messages_stmt = m_ipc_database.compileStatement("DELETE FROM to_server WHERE row_id <= @row_id"); m_select_messages_stmt = m_ipc_database.compileStatement("SELECT * FROM to_server"); } else { m_insert_message_stmt = m_ipc_database.compileStatement("INSERT INTO to_server " "(" " type," " size," " blob_message" ")" "VALUES" "(" " @type," " @size," " @blob_message" ")"); m_update_message_stmt = m_ipc_database.compileStatement("UPDATE to_server SET " " size = @size," " blob_message = @blob_message " "WHERE " " type = @type"); m_delete_old_messages_stmt = m_ipc_database.compileStatement("DELETE FROM to_client WHERE row_id <= @row_id"); m_select_messages_stmt = m_ipc_database.compileStatement("SELECT * FROM to_client"); } } void BeginTransaction() { m_begin_transaction_stmt.reset(); m_begin_transaction_stmt.execDML(); } void Commit() { m_commit_transaction_stmt.reset(); m_commit_transaction_stmt.execDML(); } std::shared_ptr<Message> CreateMessageFromRow(CppSQLite3Query &received_messages) { int size = received_messages.getSizeTField("size"); std::shared_ptr<std::string> buffer = std::make_shared<std::string>(); const unsigned char *message = received_messages.getBlobField("blob_message", size); buffer->resize(size); memcpy((void *)buffer->data(), message, size); return std::make_shared<Message>(std::string(received_messages.getStringField("type")), buffer); } CppSQLite3Query QueryReceivedMessages() { m_select_messages_stmt.reset(); CppSQLite3Query query_result = m_select_messages_stmt.execQuery(); return query_result; } void DeleteOldMessages(unsigned long long reference_id) { BeginTransaction(); m_delete_old_messages_stmt.reset(); m_delete_old_messages_stmt.bindInt64("@row_id", reference_id); m_delete_old_messages_stmt.execDML(); Commit(); } bool SendMessages(std::queue<std::shared_ptr<Message>> &outbox_queue) { if (!outbox_queue.empty()) { BeginTransaction(); while (!outbox_queue.empty()) { std::shared_ptr<Message> message = outbox_queue.front(); WriteSendingMessage(message); outbox_queue.pop(); } Commit(); return true; } return false; } void WriteSendingMessage(std::shared_ptr<Message> message) { if (message->GetOverwriteMode()) { m_update_message_stmt.reset(); m_update_message_stmt.bind("@type", message->GetType()); m_update_message_stmt.bindInt64("@size", message->GetDataSize()); m_update_message_stmt.bind("@blob_message", (const unsigned char *)message->GetData()->data(), message->GetDataSize()); if (m_update_message_stmt.execDML() != 0) { return; } } m_insert_message_stmt.reset(); m_insert_message_stmt.bind("@type", message->GetType()); m_insert_message_stmt.bindInt64("@size", message->GetDataSize()); m_insert_message_stmt.bind("@blob_message", (const unsigned char *)message->GetData()->data(), message->GetDataSize()); m_insert_message_stmt.execDML(); } std::string GenerateChannelPath() { std::string petunia_folder_path = Petunia::GetPetuniaFolder(); return petunia_folder_path + m_channel + CHANNEL_FILE_EXTENSION; } void TryDeleteChannel() { for (size_t i = 0; i < MAX_CHANNEL_DELETE_TRIES; ++i) { if (remove(m_channel_path.c_str()) == 0) { break; } } } bool ReceiveMessages(std::queue<std::shared_ptr<Message>> &inbox_queue) { unsigned long long delete_reference_id = 0; CppSQLite3Query received_messages = QueryReceivedMessages(); while (!received_messages.eof()) { delete_reference_id = received_messages.getInt64Field("row_id"); std::shared_ptr<Message> message = CreateMessageFromRow(received_messages); inbox_queue.push(message); received_messages.nextRow(); } if (delete_reference_id > 0) { DeleteOldMessages(delete_reference_id); return true; } return false; } private: CppSQLite3DB m_ipc_database; CppSQLite3Statement m_begin_transaction_stmt; CppSQLite3Statement m_commit_transaction_stmt; CppSQLite3Statement m_insert_message_stmt; CppSQLite3Statement m_update_message_stmt; CppSQLite3Statement m_delete_old_messages_stmt; CppSQLite3Statement m_select_messages_stmt; std::string m_channel_path; }; IPCMediumDefault::IPCMediumDefault(std::string &channel, ConnectionRole connection_role /*= ConnectionRole::Auto*/) :IPCMedium(channel, connection_role) { m_internal_medium = std::make_shared<IPCInternalMedium>(channel, connection_role); } IPCMediumDefault::~IPCMediumDefault() { } bool IPCMediumDefault::ReceiveMessages(std::queue<std::shared_ptr<Message>> &inbox_queue) { return m_internal_medium->ReceiveMessages(inbox_queue); } bool IPCMediumDefault::SendMessages(std::queue<std::shared_ptr<Message>> &outbox_queue) { return m_internal_medium->SendMessages(outbox_queue); } }
#ifndef SOBELFILTER_H #define SOBELFILTER_H #include "iimageexpander.h" #include "iimagefilter.h" class SobelFilter : public IImageFilter { public: SobelFilter(); QImage *process(IImageExpander *expander, QImage *img) override; private: IImageExpander *expander; }; #endif // SOBELFILTER_H
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2003 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef _FIND_TEXT_DIALOG_H #define _FIND_TEXT_DIALOG_H #include "adjunct/quick_toolkit/widgets/Dialog.h" class FindTextManager; class FindTextDialog : public Dialog { public: FindTextDialog(const FindTextManager* manager); virtual ~FindTextDialog() {}; Type GetType() {return DIALOG_TYPE_FIND_TEXT;} const char* GetWindowName() {return "Find Text Dialog";} BOOL GetModality() {return FALSE;} DialogType GetDialogType() {return TYPE_CLOSE;} protected: virtual BOOL HasDefaultButton() {return TRUE;} virtual void OnInit(); virtual void OnClick(OpWidget *widget, UINT32 id); virtual void OnClose(BOOL user_initiated); private: FindTextManager* m_manager; }; #endif //_FIND_TEXT_DIALOG_H
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2008 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #include "core/pch.h" #if defined(SELFTEST) #include "modules/selftest/src/testutils.h" #include "modules/network_selftest/scanpass.h" #include "modules/cache/url_stream.h" #include "modules/locale/oplanguagemanager.h" OP_STATUS ScanPass_SimpleTester::Construct(const OpStringC8 &pass_string) { return test_string.Set(pass_string); } OP_STATUS ScanPass_SimpleTester::Construct(URL &a_url, URL &ref, const OpStringC8 &pass_string, BOOL unique) { URL_DocSelfTest_Item::Construct(a_url, ref, unique); return test_string.Set(pass_string); } OP_STATUS ScanPass_SimpleTester::Construct(URL &a_url, URL &ref, const OpStringC &pass_string, BOOL unique) { URL_DocSelfTest_Item::Construct(a_url, ref, unique); return test_string.SetUTF8FromUTF16(pass_string); } OP_STATUS ScanPass_SimpleTester::Construct(const OpStringC8 &source_url, URL &ref, const OpStringC8 &pass_string, BOOL unique) { if(source_url.IsEmpty()) return OpStatus::ERR; URL a_url; URL empty; a_url = g_url_api->GetURL(empty, source_url, unique); if(a_url.IsEmpty()) return OpStatus::ERR; return Construct(a_url, ref, pass_string, unique); } OP_STATUS ScanPass_SimpleTester::Construct(const OpStringC &source_url, URL &ref, const OpStringC &pass_string, BOOL unique) { if(source_url.IsEmpty()) return OpStatus::ERR; URL a_url; URL empty; a_url = g_url_api->GetURL(empty, source_url, unique); if(a_url.IsEmpty()) return OpStatus::ERR; return Construct(a_url, ref, pass_string, unique); } BOOL ScanPass_SimpleTester::Verify_function(URL_DocSelfTest_Event event, Str::LocaleString status_code) { switch(event) { case URLDocST_Event_Header_Loaded: if(header_loaded) { ReportFailure("Multiple header loaded."); return FALSE; } header_loaded = TRUE; break; case URLDocST_Event_Redirect: if(header_loaded) { ReportFailure("Redirect after header loaded."); return FALSE; } break; case URLDocST_Event_Data_Received: { if(!header_loaded) { ReportFailure("Data before header loaded."); return FALSE; } URLStatus status = (URLStatus) url.GetAttribute(URL::KLoadStatus, TRUE); if(status == URL_LOADED) { if(!CheckPass(test_string)) return FALSE; if(extra_test_string.HasContent() && !CheckPass(extra_test_string)) return FALSE; } else if(status != URL_LOADING) { ReportFailure("Some kind of loading failure %d.", status); return FALSE; } } break; default: { OpString temp; OpString8 lang_code, errorstring; g_languageManager->GetString(Str::LocaleString(status_code), temp); lang_code.SetUTF8FromUTF16(temp); temp.Empty(); url.GetAttribute(URL::KInternalErrorString, temp); errorstring.SetUTF8FromUTF16(temp); ReportFailure("Some kind of loading failure %d:%d:\"%s\":\"%s\" .", (int) event, (int) status_code, (lang_code.HasContent() ? lang_code.CStr() : "<No String>"), (errorstring.HasContent() ? errorstring.CStr() : "") ); } return FALSE; } return TRUE; } BOOL ScanPass_SimpleTester::CheckPass(const OpStringC8 &string) { OpAutoPtr<URL_DataDescriptor> desc(NULL); desc.reset(url.GetDescriptor(NULL, TRUE, TRUE, TRUE)); if(desc.get() == NULL) { ReportFailure("Compare failed."); return FALSE; } BOOL more=TRUE; size_t pass_len = string.Length(); while(more) { size_t buf_len; buf_len = desc->RetrieveData(more); if(buf_len == 0) { if(more) { ReportFailure("Read descriptor failed."); return FALSE; } continue; } if(desc->GetBuffer() == NULL) { ReportFailure("Compare failed."); return FALSE; } if(pass_len <= buf_len) { const char *buf = string.CStr(); const char *comp_buffer = desc->GetBuffer(); size_t scan_len = buf_len -pass_len; size_t i; for(i=0; i<= scan_len; i++) { if(op_memcmp(comp_buffer+i, buf , pass_len) == 0) return TRUE; } desc->ConsumeData((unsigned)i); } } desc.reset(); ReportFailure("Pass string not found."); return FALSE; } OP_STATUS UniScanPass_SimpleTester::Construct(const OpStringC &pass_string) { return test_string.Set(pass_string); } OP_STATUS UniScanPass_SimpleTester::Construct(URL &a_url, URL &ref, const OpStringC &pass_string, BOOL unique) { URL_DocSelfTest_Item::Construct(a_url, ref, unique); return test_string.Set(pass_string); } OP_STATUS UniScanPass_SimpleTester::Construct(const OpStringC8 &source_url, URL &ref, const OpStringC &pass_string, BOOL unique) { if(source_url.IsEmpty()) return OpStatus::ERR; URL a_url; a_url = g_url_api->GetURL(source_url); if(a_url.IsEmpty()) return OpStatus::ERR; return Construct(a_url, ref, pass_string, unique); } OP_STATUS UniScanPass_SimpleTester::Construct(const OpStringC &source_url, URL &ref, const OpStringC &pass_string, BOOL unique) { if(source_url.IsEmpty()) return OpStatus::ERR; URL a_url; a_url = g_url_api->GetURL(source_url); if(a_url.IsEmpty()) return OpStatus::ERR; return Construct(a_url, ref, pass_string, unique); } BOOL UniScanPass_SimpleTester::Verify_function(URL_DocSelfTest_Event event, Str::LocaleString status_code) { switch(event) { case URLDocST_Event_Header_Loaded: if(header_loaded) { ReportFailure("Multiple header loaded."); return FALSE; } header_loaded = TRUE; break; case URLDocST_Event_Redirect: if(header_loaded) { ReportFailure("Redirect after header loaded."); return FALSE; } break; case URLDocST_Event_Data_Received: { if(!header_loaded) { ReportFailure("Data before header loaded."); return FALSE; } URLStatus status = (URLStatus) url.GetAttribute(URL::KLoadStatus, TRUE); if(status == URL_LOADED) { if(!CheckPass()) return FALSE; } else if(status != URL_LOADING) { ReportFailure("Some kind of loading failure %d.", status); return FALSE; } } break; default: { OpString temp; OpString8 lang_code, errorstring; g_languageManager->GetString(Str::LocaleString(status_code), temp); lang_code.SetUTF8FromUTF16(temp); temp.Empty(); url.GetAttribute(URL::KInternalErrorString, temp); errorstring.SetUTF8FromUTF16(temp); ReportFailure("Some kind of loading failure %d:%d:\"%s\":\"%s\" .", (int) event, (int) status_code, (lang_code.HasContent() ? lang_code.CStr() : "<No String>"), (errorstring.HasContent() ? errorstring.CStr() : "") ); } return FALSE; } return TRUE; } BOOL UniScanPass_SimpleTester::CheckPass() { OpAutoPtr<URL_DataDescriptor> desc(NULL); desc.reset(url.GetDescriptor(NULL, TRUE, FALSE, TRUE)); if(desc.get() == NULL) { ReportFailure("Compare failed."); return FALSE; } BOOL more=TRUE; size_t pass_len = UNICODE_SIZE(test_string.Length()); while(more) { size_t buf_len; buf_len = desc->RetrieveData(more); if(buf_len == 0) { if(more) { ReportFailure("Read descriptor failed."); return FALSE; } continue; } if(desc->GetBuffer() == NULL) { ReportFailure("Compare failed."); return FALSE; } if(pass_len <= buf_len) { const byte *buf = (const byte *) test_string.CStr(); const byte *comp_buffer = (const byte *) desc->GetBuffer(); size_t scan_len = buf_len -pass_len; size_t i; for(i=0; i<= scan_len; i++) { if(op_memcmp(comp_buffer+i, buf , pass_len) == 0) return TRUE; } desc->ConsumeData((unsigned)i); } } desc.reset(); ReportFailure("Pass string not found."); return FALSE; } #endif // SELFTEST
#include <iostream> #include <conio.h> #include <cctype> #include "board.h" using namespace std; Board::Board() { // initialize board board = InitBoard(); bEnpassantW = bEnpassantB = true; turn = 0; pawnCountW = pawnCountB = 8; bishopCountW = bishopCountB = 2; knightCountW = knightCountB = 2; rookCountW = rookCountB = 2; queenCountW = queenCountB = 1; } void Board::BeginGame() { int tX, tY; // for movement inputs char inputX, inputY; int nX, nY; bool loop = true; bool selectLoop; while (loop) { int i, j; bIndex = false; switch (turn % 2) { // WHITE TURN case 0 : { for ( i = BOARD_MIN; i <= BOARD_MAX; i++ ) { for ( j = BOARD_MIN; j <= BOARD_MAX; j++ ) { // delete before index board[i][j].DelIndex(); // set white pieces index if ( ( board[i][j].GetPiece() != NULL )&&( board[i][j].GetPiece()->GetColor() == WHITE ) ) { board[i][j].SetIndex(); if ( board[i][j].GetPiece()->GetPieceType() == 'K' ) { // bCheckMateW == true bCheckMateW = mRule.Attacked(i, j, WHITE, board); } } else if ( ( board[i][j].GetPiece() != NULL )&&( board[i][j].GetPiece()->GetColor() == BLACK ) ) { // bCheckMateB == true if ( board[i][j].GetPiece()->GetPieceType() == 'K' ) { bCheckMateB = mRule.Attacked(i, j, BLACK, board); } } } } do { selectLoop = false; system("cls"); Draw(board); cout << "WHITE Turn : "; cin >> inputX >> inputY; // char to int conversion nX = 8 - (inputY - '0'); nY = (inputX - 'A'); if ( ( nX < BOARD_MIN ) || ( nX > BOARD_MAX ) || ( nY < BOARD_MIN ) || ( nY > BOARD_MAX ) || ( board[nX][nY].GetIndex() == false ) ) { cout << "Please try again!" << endl; _getch(); selectLoop = true; } } while ( selectLoop ); break; } // BLACK TURN case 1 : { for ( i = BOARD_MIN; i <= BOARD_MAX; i++ ) { for ( j = BOARD_MIN; j <= BOARD_MAX; j++ ) { // delete before index board[i][j].DelIndex(); if ( ( board[i][j].GetPiece() != NULL )&&( board[i][j].GetPiece()->GetColor() == BLACK ) ) { // set black pieces index board[i][j].SetIndex(); if ( board[i][j].GetPiece()->GetPieceType() == 'K' ) { // bCheckMateB == true bCheckMateB = mRule.Attacked(i, j, BLACK, board); } } else if ( ( board[i][j].GetPiece() != NULL )&&( board[i][j].GetPiece()->GetColor() == WHITE ) ) { if ( board[i][j].GetPiece()->GetPieceType() == 'K' ) { // bCheckMateW == true bCheckMateW = mRule.Attacked(i, j, WHITE, board); } } } } do { selectLoop = false; system("cls"); Draw(board); cout << "Black Turn : "; cin >> inputX >> inputY; // char to int conversion nX = 8 - (inputY - '0'); nY = (inputX - 'A'); if ( ( nX < BOARD_MIN ) || ( nX > BOARD_MAX ) || ( nY < BOARD_MIN ) || ( nY > BOARD_MAX ) || ( board[nX][nY].GetIndex() == false ) ) { cout << "Please try again!" << endl; _getch(); selectLoop = true; } } while (selectLoop); break; } } // loop through the board for ( i = BOARD_MIN; i <= BOARD_MAX; i++ ) { for ( j = BOARD_MIN; j <= BOARD_MAX; j++ ) { // delete before index board[i][j].DelIndex(); if ( board[nX][nY].GetPiece()->Move(i, j, board) == true ) { // set index if movement is possible board[i][j].SetIndex(); bIndex = true; } } } // if moving to any locations is impossible if ( bIndex == false ) { cout << "No possible locations to move!!" << endl; _getch(); // if movement is possible } else { do { selectLoop = false; system("cls"); Draw(board); // draw board // check possible enpassant movements if ( board[nX][nY].GetPiece()->GetEnp() == false ) { for ( i = BOARD_MIN; i <= BOARD_MAX; i++ ) { for ( j = BOARD_MIN; j <= BOARD_MAX; j++ ) { if ( ( board[i][j].GetPiece() != NULL )&&( board[i][j].GetPiece()->GetEnp() == true ) ) { // set bEnpassant to false board[i][j].GetPiece()->DelEnp(); } } } } cout << "Input a location to move : "; cin >> inputX >> inputY; // char to int conversion tX = 8 - (inputY - '0'); tY = inputX - 'A'; if ( ( tX < BOARD_MIN ) || ( tX > BOARD_MAX ) || ( tY < BOARD_MIN ) || ( tY > BOARD_MAX ) || ( board[tX][tY].GetIndex() == false ) ) { cout << "Please try again!" << endl; _getch(); selectLoop = true; } } while ( selectLoop ); // check castling movements if ( ( board[nX][nY].GetPiece()->GetCast() == true )&&( board[nX][nY].GetPiece()->GetPieceType() == 'K' ) &&( ( tY == nY + 2 ) || ( tY == nY - 2 ) ) ) { // right col castling if ( tY == nY + 2 ) { // move the king board[tX][tY].SetPiece(board[nX][nY].GetPiece()); board[nX][nY].DelPiece(); board[tX][tY].GetPiece()->SetXY(tX, tY); board[tX][tY].GetPiece()->DelCast(); // move the rook board[nX][nY + 1].SetPiece(board[nX][7].GetPiece()); board[nX][7].DelPiece(); board[nX][nY + 1].GetPiece()->SetXY(nX, nY + 1); // left col castling } else if ( tY == nY - 2 ) { // move the king board[tX][tY].SetPiece(board[nX][nY].GetPiece()); board[nX][nY].DelPiece(); board[tX][tY].GetPiece()->SetXY(tX, tY); board[tX][tY].GetPiece()->DelCast(); // move the rook board[nX][nY - 1].SetPiece(board[nX][0].GetPiece()); board[nX][0].DelPiece(); board[nX][nY - 1].GetPiece()->SetXY(nX, nY - 1); } // enpassant movements } else if ( ( board[nX][nY].GetPiece()->GetEnp() == true ) &&( ( tX == nX - 1 ) || ( tX == nX + 1 ) ) &&( ( tY == nY - 1 ) || ( tY == nY + 1 ) ) ) { // BLACK ENPASSANT if ( board[nX][nY].GetPiece()->GetColor() == WHITE ) { if ( board[tX + 1][tY].GetPiece()->GetColor() == BLACK ) { // count dead pieces pawnCountB--; } else { pawnCountW--; } // delete a piece killed by enpassant delete board[tX + 1][tY].GetPiece(); board[tX + 1][tY].DelPiece(); board[tX][tY].SetPiece(board[nX][nY].GetPiece()); board[nX][nY].DelPiece(); board[tX][tY].GetPiece()->SetXY(tX, tY); // set bEnpassantB to false bEnpassantB = false; // WHITE ENPASSANT } else { if ( board[tX - 1][tY].GetPiece()->GetColor() == BLACK ) { // count dead pieces pawnCountB--; } else { pawnCountW--; } // delete a piece killed by enpassant delete board[tX - 1][tY].GetPiece(); board[tX - 1][tY].DelPiece(); board[tX][tY].SetPiece(board[nX][nY].GetPiece()); board[nX][nY].DelPiece(); board[tX][tY].GetPiece() -> SetXY(tX, tY); // set bEnpassantB to false bEnpassantW = false; } // set enpassant to false board[tX][tY].GetPiece() -> DelEnp(); // normal movements } else { if ( board[tX][tY].GetPiece() != NULL ) { // delete target location's piece if ( board[tX][tY].GetPiece()->GetColor() == BLACK ) { // count the dead pieces if (board[tX][tY].GetPiece()->GetPieceType() == 'P') pawnCountB--; if (board[tX][tY].GetPiece()->GetPieceType() == 'N') knightCountB--; if (board[tX][tY].GetPiece()->GetPieceType() == 'B') bishopCountB--; if (board[tX][tY].GetPiece()->GetPieceType() == 'R') rookCountB--; if (board[tX][tY].GetPiece()->GetPieceType() == 'Q') queenCountB--; } else { if (board[tX][tY].GetPiece()->GetPieceType() == 'P') pawnCountW--; if (board[tX][tY].GetPiece()->GetPieceType() == 'N') knightCountW--; if (board[tX][tY].GetPiece()->GetPieceType() == 'B') bishopCountW--; if (board[tX][tY].GetPiece()->GetPieceType() == 'R') rookCountW--; if (board[tX][tY].GetPiece()->GetPieceType() == 'Q') queenCountW--; } delete board[tX][tY].GetPiece(); } // move to a target location and delete current location index, piece board[tX][tY].SetPiece(board[nX][nY].GetPiece()); board[nX][nY].DelPiece(); board[tX][tY].GetPiece()->SetXY(tX, tY); if ( ( board[tX][tY].GetPiece()->GetPieceType() == 'P' ) &&( board[tX][tY].GetPiece()->GetEnp() == true ) ) { // change from enpassant to normal movement for ( i = BOARD_MIN; i <= BOARD_MAX; i++ ) { for ( j = BOARD_MIN; j <= BOARD_MAX; j++ ) { if ( ( board[i][j].GetPiece() != NULL )&&( board[i][j].GetPiece()->GetEnp() == true ) ) { // set enpassant to false board[i][j].GetPiece()->DelEnp(); } } } } } // check any possible enpassant movements { // check black enpassant if ((bEnpassantB != false) && (board[tX][tY].GetPiece()->GetColor() == BLACK)) { if (((tX == 3) || (tX == 4)) && (board[tX][tY].GetPiece()->GetPieceType() == 'P') && (board[tX][tY].GetPiece()->GetFirst() == true)) { //set enpassant mRule.Enpassant(tX, tY, board); } } // check white enpassant else if ((bEnpassantW != false) && (board[tX][tY].GetPiece()->GetColor() == WHITE)) { if (((tX == 3) || (tX == 4)) && (board[tX][tY].GetPiece()->GetPieceType() == 'P') && (board[tX][tY].GetPiece()->GetFirst() == true)) { // set enpassant mRule.Enpassant(tX, tY, board); } } } // set piece's first move bool to false board[tX][tY].GetPiece()->DelFirst(); // check any possible castling movements mRule.Castling(board); // check promotion if ( ( board[tX][tY].GetPiece()->GetPieceType() == 'P' ) &&( ( tX == 0 ) || ( tX == 7 ) ) ) { mRule.Promotion(tX, tY, board); } if ( EndGame(board) == true ) { // check game's end loop = false; } turn++; } } } // check end game conditions bool Board::EndGame(Location** board) { int i,j; int end = 0; // search thorugh the board for ( i = BOARD_MIN; i <= BOARD_MAX; i++ ) { for ( j = BOARD_MIN; j <= BOARD_MAX; j++ ) { if ( ( board[i][j].GetPiece() != NULL )&&( board[i][j].GetPiece()->GetPieceType() == 'K' ) ) { // find king if ( board[i][j].GetPiece()->GetColor() == BLACK ) { // BLACK KING end++; } else { // WHITE KING end += 3; } } } } switch (end) { case 1 : // BLACK KING EndGameDraw(BLACK); for ( i = BOARD_MIN; i <= BOARD_MAX; i++ ) delete[] board[i]; delete[] board; board = NULL; return true; break; case 3 : // WHITE KING EndGameDraw(WHITE); for(i = BOARD_MIN; i <= BOARD_MAX; i++) delete[] board[i]; delete[] board; board = NULL; return true; break; default : return false; break; } } // replay the game void Board::ReplayMode() { } // draw a board void Board::Draw(Location** board) { for ( int i = 0; i <= BOARD_MAX; i++ ) { if (i == 0) { cout << " TURN : " << turn; cout << " - LEFT PIECES -" << endl; cout << " WP BP" << endl; cout << " P " << pawnCountW << " " << pawnCountB << endl; cout << " N " << knightCountW << " " << knightCountB << endl; cout << " B " << bishopCountW << " " << bishopCountB << endl; cout << " R " << rookCountW << " " << rookCountB << endl; cout << " Q " << queenCountW << " " << queenCountB << endl; } for (int j = 0; j <= BOARD_MAX; j++) { if (board[i][j].GetPiece() != NULL) {// if piece exists // set piece depending on color if (board[i][j].GetPiece()->GetColor() == BLACK) { // black char black = tolower(board[i][j].GetPiece()->GetPieceType()); cout << black << " "; } else { // white cout << board[i][j].GetPiece()->GetPieceType() << " "; } } else { cout << ". "; } } cout << " " << 8-i << endl; // row if( i == 7 ) { cout << endl << "A B C D E F G H " << endl << endl; // col } } } // return a initialized board Location** Board::InitBoard() { Location** board; board = new Location*[8]; for ( int i = BOARD_MIN; i <= BOARD_MAX; i++ ) { board[i] = new Location[8]; } board[0][0].SetPiece(new Rook(0, 0, BLACK)); board[0][1].SetPiece(new Knight(0, 1, BLACK)); board[0][2].SetPiece(new Bishop(0, 2, BLACK)); board[0][3].SetPiece(new King(0, 3, BLACK)); board[0][4].SetPiece(new Queen(0, 4, BLACK)); board[0][5].SetPiece(new Bishop(0, 5, BLACK)); board[0][6].SetPiece(new Knight(0, 6, BLACK)); board[0][7].SetPiece(new Rook(0, 7, BLACK)); board[1][0].SetPiece(new Pawn(1, 0, BLACK)); board[1][1].SetPiece(new Pawn(1, 1, BLACK)); board[1][2].SetPiece(new Pawn(1, 2, BLACK)); board[1][3].SetPiece(new Pawn(1, 3, BLACK)); board[1][4].SetPiece(new Pawn(1, 4, BLACK)); board[1][5].SetPiece(new Pawn(1, 5, BLACK)); board[1][6].SetPiece(new Pawn(1, 6, BLACK)); board[1][7].SetPiece(new Pawn(1, 7, BLACK)); board[6][0].SetPiece(new Pawn(6, 0, WHITE)); board[6][1].SetPiece(new Pawn(6, 1, WHITE)); board[6][2].SetPiece(new Pawn(6, 2, WHITE)); board[6][3].SetPiece(new Pawn(6, 3, WHITE)); board[6][4].SetPiece(new Pawn(6, 4, WHITE)); board[6][5].SetPiece(new Pawn(6, 5, WHITE)); board[6][6].SetPiece(new Pawn(6, 6, WHITE)); board[6][7].SetPiece(new Pawn(6, 7, WHITE)); board[7][0].SetPiece(new Rook(7, 0, WHITE)); board[7][1].SetPiece(new Knight(7, 1, WHITE)); board[7][2].SetPiece(new Bishop(7, 2, WHITE)); board[7][3].SetPiece(new King(7, 3, WHITE)); board[7][4].SetPiece(new Queen(7, 4, WHITE)); board[7][5].SetPiece(new Bishop(7, 5, WHITE)); board[7][6].SetPiece(new Knight(7, 6, WHITE)); board[7][7].SetPiece(new Rook(7, 7, WHITE)); return board; } void Board::EndGameDraw(bool color) { system("cls"); cout << "----------------------" << endl; cout << "| |" << endl; cout << "| GAME OVER |" << endl; if (color == WHITE) cout << "| WHITE |" << endl; else cout << "| BLACK |" << endl; cout << "| player |" << endl; cout << "| wins! |" << endl; cout << "| |" << endl; cout << "----------------------" << endl; cout << endl; cout << "Please try again!"; _getch(); }
#include "Renderer.h" #include "imgui.h" #include "imgui_impl_dx11.h" using namespace DirectX; Renderer::Renderer( Microsoft::WRL::ComPtr<ID3D11Device> device, Microsoft::WRL::ComPtr<ID3D11DeviceContext> context, Microsoft::WRL::ComPtr<IDXGISwapChain> swapChain, Microsoft::WRL::ComPtr<ID3D11RenderTargetView> backBufferRTV, Microsoft::WRL::ComPtr<ID3D11DepthStencilView> depthBufferDSV, unsigned int windowWidth, unsigned int windowHeight, Sky* sky, const std::vector<GameEntity*>& entities, const std::vector<Light>& lights, SimpleVertexShader* lightVS, SimplePixelShader* lightPS) : device(device), context(context), swapChain(swapChain), backBufferRTV(backBufferRTV), depthBufferDSV(depthBufferDSV), windowWidth(windowWidth), windowHeight(windowHeight), sky(sky), entities(entities), lights(lights), lightVS(lightVS), lightPS(lightPS) { } void Renderer::PostResize( unsigned int windowWidth, unsigned int windowHeight, Microsoft::WRL::ComPtr<ID3D11RenderTargetView> backBufferRTV, Microsoft::WRL::ComPtr<ID3D11DepthStencilView> depthBufferDSV) { this->backBufferRTV = backBufferRTV; this->depthBufferDSV = depthBufferDSV; this->windowWidth = windowWidth; this->windowHeight = windowHeight; } void Renderer::Render(Camera* camera, Mesh* lightMesh, DirectX::SpriteFont* arial, DirectX::SpriteBatch* spriteBatch) { // Background color for clearing const float color[4] = { 0, 0, 0, 1 }; // Clear the render target and depth buffer (erases what's on the screen) // - Do this ONCE PER FRAME // - At the beginning of Draw (before drawing *anything*) context->ClearRenderTargetView(backBufferRTV.Get(), color); context->ClearDepthStencilView( depthBufferDSV.Get(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); // Draw all of the entities for (auto ge : entities) { // Set the "per frame" data // Note that this should literally be set once PER FRAME, before // the draw loop, but we're currently setting it per entity since // we are just using whichever shader the current entity has. // Inefficient!!! SimplePixelShader* ps = ge->GetMaterial()->GetPS(); ps->SetData("Lights", (void*)(&lights[0]), sizeof(Light) * lights.size()); ps->SetInt("LightCount", lights.size()); ps->SetFloat3("CameraPosition", camera->GetTransform()->GetPosition()); // Set IBL vars ps->SetShaderResourceView("brdfLookUpMap", sky->GetIBLBRDFLookUpTexture()); ps->SetShaderResourceView("irradianceIBLMap", sky->GetIBLIrradianceMap()); ps->SetShaderResourceView("specularIBLMap", sky->GetIBLConvolvedSpecularMap()); ps->SetInt("SpecIBLTotalMipLevels", sky->GetIBLMipLevelCount()); ps->CopyBufferData("perFrame"); // Draw the entity ge->Draw(context, camera); } // Draw the light sources DrawPointLights(camera, lightMesh); // Draw the sky sky->Draw(camera); // Draw some UI DrawUI(arial, spriteBatch); // Draw ImGui ImGui::Render(); ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); // Present the back buffer to the user // - Puts the final frame we're drawing into the window so the user can see it // - Do this exactly ONCE PER FRAME (always at the very end of the frame) swapChain->Present(0, 0); // Due to the usage of a more sophisticated swap chain, // the render target must be re-bound after every call to Present() context->OMSetRenderTargets(1, backBufferRTV.GetAddressOf(), depthBufferDSV.Get()); } void Renderer::Renderer::DrawPointLights(Camera* camera, Mesh* lightMesh) { // Turn on these shaders lightVS->SetShader(); lightPS->SetShader(); // Set up vertex shader lightVS->SetMatrix4x4("view", camera->GetView()); lightVS->SetMatrix4x4("projection", camera->GetProjection()); for (int i = 0; i < lights.size(); i++) { Light light = lights[i]; // Only drawing points, so skip others if (light.Type != LIGHT_TYPE_POINT) continue; // Calc quick scale based on range // (assuming range is between 5 - 10) float scale = light.Range / 10.0f; // Make the transform for this light XMMATRIX rotMat = XMMatrixIdentity(); XMMATRIX scaleMat = XMMatrixScaling(scale, scale, scale); XMMATRIX transMat = XMMatrixTranslation(light.Position.x, light.Position.y, light.Position.z); XMMATRIX worldMat = scaleMat * rotMat * transMat; XMFLOAT4X4 world; XMFLOAT4X4 worldInvTrans; XMStoreFloat4x4(&world, worldMat); XMStoreFloat4x4(&worldInvTrans, XMMatrixInverse(0, XMMatrixTranspose(worldMat))); // Set up the world matrix for this light lightVS->SetMatrix4x4("world", world); lightVS->SetMatrix4x4("worldInverseTranspose", worldInvTrans); // Set up the pixel shader data XMFLOAT3 finalColor = light.Color; finalColor.x *= light.Intensity; finalColor.y *= light.Intensity; finalColor.z *= light.Intensity; lightPS->SetFloat3("Color", finalColor); // Copy data lightVS->CopyAllBufferData(); lightPS->CopyAllBufferData(); // Draw lightMesh->SetBuffersAndDraw(context); } } // -------------------------------------------------------- // Draws a simple informational "UI" using sprite batch // -------------------------------------------------------- void Renderer::DrawUI(DirectX::SpriteFont* arial, DirectX::SpriteBatch* spriteBatch) { spriteBatch->Begin(); // Basic controls float h = 10.0f; arial->DrawString(spriteBatch, L"Controls:", XMVectorSet(10, h, 0, 0)); arial->DrawString(spriteBatch, L" (WASD, X, Space) Move camera", XMVectorSet(10, h + 20, 0, 0)); arial->DrawString(spriteBatch, L" (Left Click & Drag) Rotate camera", XMVectorSet(10, h + 40, 0, 0)); arial->DrawString(spriteBatch, L" (Left Shift) Hold to speed up camera", XMVectorSet(10, h + 60, 0, 0)); arial->DrawString(spriteBatch, L" (Left Ctrl) Hold to slow down camera", XMVectorSet(10, h + 80, 0, 0)); arial->DrawString(spriteBatch, L" (TAB) Randomize lights", XMVectorSet(10, h + 100, 0, 0)); // Current "scene" info h = 150; arial->DrawString(spriteBatch, L"Scene Details:", XMVectorSet(10, h, 0, 0)); arial->DrawString(spriteBatch, L" Top: PBR materials", XMVectorSet(10, h + 20, 0, 0)); arial->DrawString(spriteBatch, L" Bottom: Non-PBR materials", XMVectorSet(10, h + 40, 0, 0)); spriteBatch->End(); // Reset render states, since sprite batch changes these! context->OMSetBlendState(0, 0, 0xFFFFFFFF); context->OMSetDepthStencilState(0, 0); }
#pragma once #include <Eigen/Dense> #include <iostream> #include <vector> namespace tools::linalg { struct SolverData { double relative_residual = 0; double initial_algebraic_error = 0; double algebraic_error = 0; size_t iterations = 0; bool converged = false; }; enum StoppingCriterium { Relative, Algebraic }; // Loosely based off Eigen/ConjugateGradient.h. template <typename MatType, typename PrecondType> std::pair<Eigen::VectorXd, SolverData> PCG( const MatType &A, const Eigen::VectorXd &b, const PrecondType &M, const Eigen::VectorXd &x0, int imax, double tol, enum StoppingCriterium stopping = StoppingCriterium::Relative); template <typename MatType, typename PrecondType> class Lanczos { public: Lanczos(const MatType &A, const PrecondType &P, size_t max_iterations = 200, double tol = 0.0001, double tol_bisec = 0.000001) : Lanczos(A, P, Eigen::VectorXd::Random(A.cols()), max_iterations, tol, tol_bisec) {} Lanczos(const MatType &A, const PrecondType &P, const Eigen::VectorXd &initial_guess, size_t max_iterations = 200, double tol = 0.0001, double tol_bisec = 0.000001); double max() const { return lmax_; } double min() const { return lmin_; } double cond() const { return lmax_ / lmin_; } float time() const { return time_; }; size_t iterations() const { return iterations_; } bool converged() const { return converged_; } // overload the << operator friend std::ostream &operator<<(std::ostream &os, const Lanczos &lanczos) { if (lanczos.converged()) os << "converged\t"; else os << "NOT converged\t"; os << "its=" << lanczos.iterations() << "\tlmax=" << lanczos.max() << "\tlmin=" << lanczos.min() << "\tkappa=" << lanczos.cond() << "\ttime=" << lanczos.time() << " s"; return os; } private: Eigen::VectorXd alpha_, beta_; double lmax_, lmin_; size_t iterations_; bool converged_; float time_; void bisec(size_t k, double &ymax, double &zmin, double tol_bisec); double pol(int k, double x); }; }; // namespace tools::linalg #include "linalg.ipp"
#ifndef __IVIEW_FAV_H #define __IVIEW_FAV_H #include "IViewWindow.h" #include "ModelBrowserData.h" #include "IViewFilterList.h" namespace wh { //----------------------------------------------------------------------------- class IViewFav: public IViewWindow { public: virtual void SetBeforeUpdate(const std::vector<const ICls64*>&, const ICls64&) = 0; virtual void SetAfterUpdate(const std::vector<const ICls64*>&, const ICls64&) = 0; sig::signal<void()> sigRefresh; sig::signal<void(int64_t)> sigAddClsProp; sig::signal<void(int64_t)> sigAddObjProp; sig::signal<void(int64_t, FavAPropInfo)> sigAddActProp; sig::signal<void(int64_t, int64_t)> sigRemoveClsProp; sig::signal<void(int64_t, int64_t)> sigRemoveObjProp; sig::signal<void(int64_t, int64_t, FavAPropInfo)> sigRemoveActProp; sig::signal<void(const wxString&)> sigShowHelp; }; //----------------------------------------------------------------------------- } //namespace wh{ #endif // __*_H
#include "MacroManager.h" using namespace sc2; MacroManager::MacroManager() { } MacroManager::~MacroManager() { } Orders MacroManager::ThinkAndSendOrders(const sc2::ObservationInterface* observation) { Orders orders = Orders(); Units populationSize = observation->GetUnits(Unit::Alliance::Ally); int pop_size = observation->GetFoodUsed(); // Standard build int ordersSize = 0; if (pop_size == 14){ orders.AddBuildOrder(Order(Point3D(0, 0, 0), UNIT_TYPEID::TERRAN_SUPPLYDEPOT, static_cast<int>(populationSize.size())), 0); ordersSize++; } if (pop_size == 16) { orders.AddBuildOrder(Order(Point3D(0, 0, 0), UNIT_TYPEID::TERRAN_BARRACKS, static_cast<int>(populationSize.size())), 0); ordersSize++; } if (pop_size > 16) { orders.AddBuildOrder(Order(Point3D(0, 0, 0), UNIT_TYPEID::TERRAN_MARINE, static_cast<int>(populationSize.size())), static_cast<int>(populationSize.size()) + ordersSize); ordersSize++; } orders.AddBuildOrder(Order(Point3D(0, 0, 0), UNIT_TYPEID::TERRAN_SCV, static_cast<int>(populationSize.size()) + ordersSize), ordersSize - 1); // Attack orders orders.AddAttackOrder(Order( Point3D( observation->GetGameInfo().enemy_start_locations[0].x, observation->GetGameInfo().enemy_start_locations[0].y, observation->GetStartLocation().z), ordersSize), 0); return orders; }
#pragma once #ifndef WEEK_H #define WEEK_H #include "Day.h" class Week { private: string date; vector<Day> week; //array of days, should probable change to an array public: string getDate() { return date; } void setDate(string date) { this->date = date; } Day getDay(string day); string toString(); Week(string date); ~Week(); }; #endif
#pragma once class Gt2DObject : public GtObject { GnDeclareRTTI; public: const static gint OBJECT_TYPE = 0; private: Gn2DMeshObjectPtr mpsMesh; GnSimpleString mGMFileName; guint m2DObjectType; public: Gt2DObject(void); ~Gt2DObject(void); public: bool SaveData(const gchar* pcBasePath = NULL); bool LoadData(); bool CreateData(); gint8 GetType() { return OBJECT_TYPE; } void SetObjectName(const gchar* pcVal); public: inline Gn2DMeshObject* Get2DMeshObjecct() { return mpsMesh; } inline void SetGMFileName(const gchar* pcVal) { mGMFileName = pcVal; } inline const gchar* GetGMFileName() { return mGMFileName; } inline guint Get2DObjectType() { return m2DObjectType; } inline void Set2DObjectType(guint val) { m2DObjectType = val; } protected: void ChangeTextureAniInfoFileName(const gchar* pcBasePath); }; GnSmartPointer(Gt2DObject);
// // Created by manout on 18-3-25. // #include <numeric> #include <vector> #include <algorithm> using std::vector; using std::accumulate; using std::max; int double_core_process(vector<int>& data) { using Matrix = vector<vector<int>>; std::for_each(data.begin(), data.end(), [](int& a){a = a / 1024;}); int sum = accumulate(data.begin(), data.end(), 0); int len = sum / 2; Matrix mat (data.size() + 1, vector<int>(len + 1, 0)); for (int i = 1; i < data.size() + 1; ++i) { for (int w = 1; w < len + 1; ++w) { if (data[i] > w) mat[i][w] = mat[i - 1][w]; else mat[i][w] = max(mat[i - 1][w], data[i] + mat[i - 1][w - data[i]]); } } /** 返回两个核中的较长处理时间*/ return max(mat[data.size()][len], sum - mat[data.size()][len]) * 1024; }
/* * File: main.cpp * Author: ovoloshchuk * * Created on March 9, 2011, 12:04 PM */ #include <stdlib.h> #include <cstring> #include <iostream> #include <string> #include <fstream> #include <stdio.h> #include "Reader.h" #include "KMeans.h" #include "Upgma.h" #include "EuclidMetric.h" #include "Regression.h" #include <time.h> #include <list> #include <cmath> #include "clustering.h" #include "validity.h" #include "dbscan.h" using namespace std; char* generateFilename(time_t time) { struct tm *pTime = localtime(&time); char *pResults = "results_"; char *pExt = ".txt"; size_t nDateLength = 16; char *pchrDate = new char[nDateLength]; strftime(pchrDate, nDateLength, "%Y%m%d_%H%M%S", pTime); size_t nResultLength = strlen(pResults) + strlen(pchrDate) + strlen(pExt)+1; char *pResult = new char[nResultLength]; memset(pResult, 0, sizeof(char)*nResultLength); memcpy(pResult, pResults, sizeof(char)*strlen(pResults)); memcpy(pResult+strlen(pResults), pchrDate, sizeof(char)*strlen(pchrDate)); memcpy(pResult+strlen(pResults)+strlen(pchrDate), pExt, sizeof(char)*strlen(pExt)+1); delete[] pchrDate; return pResult; } int main(int argc, char** argv) { char *filename; int nClusters = 5; int nMethod = 0; int nNeighbors = 4; float eps = 0.05; if (argc > 1) { if (strcmp(argv[1], "short") == 0) filename = "../../data/dmc2008_train_short.txt"; else if (strcmp(argv[1], "medium") == 0) filename = "../../data/dmc2008_train_medium.txt"; else if (strcmp(argv[1], "test") == 0) filename = "../../data/train.txt"; else if (strcmp(argv[1], "p") == 0) filename = "../../data/dmc2008_train_predicted.txt"; else if (strcmp(argv[1], "np") == 0) filename = "../../data/dmc2008_train_predicted_normalized.txt"; else if (strcmp(argv[1], "snp") == 0) filename = "../../data/short_normalized.txt"; else filename = argv[1];//"../../data/dmc2008_train.txt"; if (strcmp(argv[2], "kmeans") == 0) { nMethod = 0; nClusters = atoi(argv[3]); } else if (strcmp(argv[2], "upgma") == 0) { nMethod = 1; } else if (strcmp(argv[2], "dbscan") == 0) { nMethod = 2; nNeighbors = atoi(argv[3]); eps = atof(argv[4]); } } else return 0; Reader rdr(filename); DataContainer container; rdr.fill(container); container.normalize(); KMeans km(&container, nClusters); Upgma up(&container); DBScan dbscan(&container); AbstractMetric *pMetric = new EuclidMetric(&container); pMetric->predictMissingData(&container); FILE *pFile; /* list<int> ids = container.ids(); Object *pObj; FILE *pFile = fopen("predicted_data.txt", "w"); for (list<int>::iterator id = ids.begin(); id != ids.end(); id++) { pObj = container.get(*id); fprintf(pFile, "%i;%i;", *id, pObj->actualClass()); for (int i = 0; i < pObj->attributeCount(); i++) { fprintf(pFile, "%.2f;", pObj->attr(i)); } fprintf(pFile, "\n"); } fclose(pFile); */ Clustering *pClus = NULL; time_t start, end; start = time(NULL); switch (nMethod) { case 0: pClus = km.clusterize(pMetric); break; case 1: pClus = up.clusterize(pMetric); break; case 2: pClus = dbscan.clusterize(eps, nNeighbors, pMetric); break; }; end = time(NULL); printf("Clusterized, %i seconds spent.\r\n", (int)(end-start)); printf("Results: \n"); if (pClus) { char *pFilename = generateFilename(time(NULL)); pFile = fopen(pFilename, "w"); fprintf(pFile, "run as: "); for (int i = 0; i < argc; i++) { fprintf(pFile, "%s ", argv[i]); } fprintf(pFile, "\n"); for (list<Cluster*>::iterator iC = pClus->clusters().begin(); iC != pClus->clusters().end(); iC++) { list<Object*> lsObjects = (*iC)->objects(); printf("%i objects\n", lsObjects.size()); for (list<Object*>::iterator iO = lsObjects.begin(); iO != lsObjects.end(); iO++) { fprintf(pFile, "%i\t", (*iO)->id()); } fprintf(pFile, "\n"); } fclose(pFile); } //printf("Clustering validity: %.5f\n", Validity::dunn(*pClus, pMetric)); delete pMetric; if (pClus) delete pClus; return (EXIT_SUCCESS); }
#include "nv/lines.h" #include <gtest/gtest.h> TEST(nv_lines, init) { nv_lines lines; nv_lines_init(&lines); ASSERT_NE(nullptr, lines.data); ASSERT_LT(0, lines.capacity); ASSERT_EQ(0, lines.size); nv_lines_cleanup(&lines); } TEST(nv_lines, add) { nv_lines lines; nv_lines_init(&lines); nv_lines_add(&lines, 4711); ASSERT_EQ(1, lines.size); ASSERT_EQ(4711, lines.data[0]); nv_lines_cleanup(&lines); } TEST(nv_lines, increase_capacity) { nv_lines lines; nv_lines_init(&lines); size_t initial_capacity = lines.capacity; for(size_t i = 0; i < initial_capacity; i++) { nv_lines_add(&lines, i); } nv_lines_add(&lines, 4711); ASSERT_LT(initial_capacity, lines.capacity); ASSERT_EQ(initial_capacity + 1, lines.size); ASSERT_EQ(4711, lines.data[initial_capacity]); nv_lines_cleanup(&lines); }
#include <iostream> #include "../code/Scope.h"
#define ANNDLL_EXPORTS #include "NeuralRealisation.h" using namespace std; NeuralRealisation::NeuralRealisation(vector<size_t> conf, ANeuralNetwork::ActivationType aType, float scale) { this->configuration = conf; this->activation_type = aType; this->scale = scale; if (conf.empty()) return; } NeuralRealisation::~NeuralRealisation() { } string NeuralRealisation::GetType() { return ("This is SkyNet which will consume humankind!"); } vector<float> NeuralRealisation::Predict(vector<float> & input) { /* if (!is_trained || configuration.empty() || configuration[0] != input.size()) { cout << "Problems!" << endl; } */ vector<float> prev_out = input; vector<float> cur_out; for (size_t layer_idx = 0; layer_idx < configuration.size() - 1; layer_idx++) { cur_out.resize(configuration[layer_idx + 1], 0); for (size_t to_idx = 0; to_idx < configuration[layer_idx + 1]; to_idx++) { for (size_t from_idx = 0; from_idx < configuration[layer_idx]; from_idx++) { cur_out[to_idx] += weights[layer_idx][from_idx][to_idx] * prev_out[from_idx]; } cur_out[to_idx] = Activation(cur_out[to_idx]); } prev_out = cur_out; } return prev_out; } ANNDLL_API shared_ptr<ANN::ANeuralNetwork> ANN::CreateNeuralNetwork( vector<size_t> & config, ANN::ANeuralNetwork::ActivationType actType, float scale) { return make_shared<NeuralRealisation>(config, actType, scale); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2012 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. * * @author Manuela Hutter (manuelah) */ #ifndef DESKTOP_OP_DROP_DOWN_H #define DESKTOP_OP_DROP_DOWN_H #include "adjunct/desktop_util/adt/opdelegate.h" #include "modules/widgets/OpDropDown.h" #include "modules/util/OpHashTable.h" class OpInputAction; /** * @brief A dropdown just as OpDropDown, with the difference that dropdown item actions are stored separately, instead of in one OR-action. */ class DesktopOpDropDown : public OpDropDown { public: static OP_STATUS Construct(DesktopOpDropDown** obj, BOOL editable_text = FALSE); virtual ~DesktopOpDropDown(); OP_STATUS AddItem(const OpStringC & text, INT32 index = -1, INT32 * got_index = NULL, INTPTR user_data = 0, OpInputAction * action = NULL, const OpStringC8 & widget_image = NULL); /** * Sets the delegate to be invoked upon adding an item. * * @param handler the delegate. Ownership is transferred. */ void SetItemAddedHandler(OpDelegateBase<INT32>* handler); void SetEditableText(); // Override OpDropDown virtual OP_STATUS AddItem(const uni_char* txt, INT32 index = -1, INT32 *got_index = NULL, INTPTR user_data = 0); virtual OpScopeWidgetInfo* CreateScopeWidgetInfo(); protected: DesktopOpDropDown(BOOL editable_text = FALSE); // Override OpDropDown virtual void InvokeAction(INT32 index); virtual void OnUpdateActionState(); private: class DropdownWidgetInfo; OpAutoINT32HashTable<OpInputAction> m_item_actions; //< The actions stored by item id OpDelegateBase<INT32>* m_item_added_handler; }; #endif // DESKTOP_OP_DROP_DOWN_H
#include <glad/glad.h> #include <GLFW/glfw3.h> #include <iostream> void WindowResize(GLFWwindow* window, int width, int height); int main() { // main window setings GLFWwindow* window = nullptr; unsigned int window_width = 800; unsigned int window_height = 600; const char* window_name = "EdgaEngine2D"; const char** glfw_error = nullptr; if ( !glfwInit() ) { // initialization glfw glfwGetError(glfw_error); std::cout << "Can`t initialization GLFW, error:" << glfw_error << "\n"; return -1; } // seting opengl contexts glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // creating main window window = glfwCreateWindow(window_width, window_height, window_name, NULL, NULL); if (!window) { glfwGetError(glfw_error); std::cout << "Can`t initialization window, error:" << glfw_error << "\n"; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { // initialization glad std::cout << "Cat`t initialization GLAD \n"; return -1; } glViewport(0, 0, window_width, window_height); // domain of viewer glfwSetFramebufferSizeCallback(window,WindowResize); // callback for resize window while (!glfwWindowShouldClose(window)) { // loop of render glClearColor(0.0f, 1.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glfwSwapBuffers(window); glfwPollEvents(); } glfwTerminate(); return 0; } void WindowResize(GLFWwindow* window, int width, int height) { glViewport(0, 0, width, height); }
#include "core/pch.h" #ifdef IRC_SUPPORT #include "chattersmodel.h" #include "adjunct/m2/src/engine/chatinfo.h" #include "adjunct/m2/src/engine/message.h" #include "adjunct/m2/src/engine/engine.h" #include "adjunct/m2/src/engine/store.h" #include "adjunct/quick/hotlist/HotlistManager.h" #include "adjunct/quick/hotlist/HotlistModelItem.h" #include "modules/locale/oplanguagemanager.h" //#include "modules/prefs/prefsmanager/prefstypes.h" UINT32 ChattersModelItem::s_chatter_id_counter = 1; /*********************************************************************************** ** ** ChattersModelItem ** ***********************************************************************************/ ChattersModelItem::ChattersModelItem(UINT16 account_id, const OpStringC& name, BOOL is_operator, BOOL is_voiced, const OpStringC& prefix) : m_chat_status(AccountTypes::ONLINE), m_is_operator(is_operator), m_is_voiced(is_voiced), m_account_id(account_id), m_chatter_id(s_chatter_id_counter++) { SetName(name); m_prefix.Set(prefix); if (g_hotlist_manager) g_hotlist_manager->GetContactsModel()->AddModelListener(this); } ChattersModelItem::~ChattersModelItem() { if (g_hotlist_manager) g_hotlist_manager->GetContactsModel()->RemoveModelListener(this); } OP_STATUS ChattersModelItem::GetItemData(ItemData* item_data) { if (item_data->query_type != COLUMN_QUERY) { return OpStatus::OK; } item_data->column_query_data.column_image = m_contact ? m_contact->GetImage() : "Contact Unknown"; switch (m_chat_status) { case AccountTypes::BUSY: item_data->column_query_data.column_image_2 = "Status Busy"; break; case AccountTypes::BE_RIGHT_BACK: item_data->column_query_data.column_image_2 = "Status Be Right Back"; break; case AccountTypes::AWAY: item_data->column_query_data.column_image_2 = "Status Away"; break; case AccountTypes::ON_THE_PHONE: item_data->column_query_data.column_image_2 = "Status On The Phone"; break; case AccountTypes::OUT_TO_LUNCH: item_data->column_query_data.column_image_2 = "Status Out To Lunch"; break; } if (IsOperator()) { item_data->flags |= FLAG_BOLD; } else if (IsVoiced()) { // item_data->flags |= FLAG_ITALIC; } else if (GetModel()->IsModerated() && !IsVoiced()) { item_data->column_query_data.column_text_color = OP_RGB(0x80, 0x80, 0x80); } OpString user_name; if (m_prefix.HasContent()) user_name.AppendFormat(UNI_L("%s"), m_prefix.CStr()); user_name.Append(m_name); item_data->column_query_data.column_text->Set(user_name); item_data->column_query_data.column_sort_order = (IsOperator() ? 0 : (IsVoiced() ? 1 : 2)); return OpStatus::OK; } void ChattersModelItem::SetName(const OpStringC& name) { m_contact = g_hotlist_manager->GetContactsModel()->GetByNickname(name); m_name.Set(name); } /*********************************************************************************** ** ** ChattersModel ** ***********************************************************************************/ ChattersModel::ChattersModel() { } ChattersModel::~ChattersModel() { MessageEngine::GetInstance()->RemoveChatListener(this); } OP_STATUS ChattersModel::Init(UINT16 account_id, OpString& room) { m_account_id = account_id; m_room.Set(room); m_is_moderated = FALSE; return MessageEngine::GetInstance()->AddChatListener(this); } INT32 ChattersModel::GetColumnCount() { return 1; } OP_STATUS ChattersModel::GetColumnData(ColumnData* column_data) { RETURN_IF_ERROR(g_languageManager->GetString(Str::DI_IDSTR_M2_COL_IRCNICK, column_data->text)); return OpStatus::OK; } #ifdef ACCESSIBILITY_EXTENSION_SUPPORT OP_STATUS ChattersModel::GetTypeString(OpString& type_string) { return g_languageManager->GetString(Str::S_USERS_TYPE, type_string); } #endif /*********************************************************************************** ** ** IsModelForRoom ** ***********************************************************************************/ BOOL ChattersModel::IsModelForRoom(UINT16 account_id, const OpStringC& room) { return account_id == m_account_id && (room.IsEmpty() || m_room.CompareI(room) == 0); } /*********************************************************************************** ** ** GetChatter ** ***********************************************************************************/ ChattersModelItem* ChattersModel::GetChatter(const OpStringC& chatter) { if (chatter.IsEmpty()) return NULL; ChattersModelItem* item = NULL; m_chatters_hash_table.GetData(chatter.CStr(), &item); return item; } /*********************************************************************************** ** ** OnChatterJoining ** ***********************************************************************************/ BOOL ChattersModel::OnChatterJoining(UINT16 account_id, const ChatInfo& room, const OpStringC& chatter, BOOL is_operator, BOOL is_voiced, const OpStringC& prefix, BOOL initial) { if (!IsModelForRoom(account_id, room.ChatName())) { return TRUE; } if (GetChatter(chatter)) return FALSE; ChattersModelItem* item = OP_NEW(ChattersModelItem, (m_account_id, chatter, is_operator, is_voiced, prefix)); if (!item) return FALSE; m_chatters_hash_table.Add(item->GetName(), item); AddLast(item); return TRUE; } /*********************************************************************************** ** ** OnChatterLeft ** ***********************************************************************************/ void ChattersModel::OnChatterLeft(UINT16 account_id, const ChatInfo& room, const OpStringC& chatter, const OpStringC& message, const OpStringC& kicker) { if (!IsModelForRoom(account_id, room.ChatName())) return; ChattersModelItem* item = 0; m_chatters_hash_table.Remove(chatter.CStr(), &item); if (item != 0) item->Delete(); } /*********************************************************************************** ** ** OnChatPropertyChanged ** ***********************************************************************************/ void ChattersModel::OnChatPropertyChanged(UINT16 account_id, const ChatInfo& room, const OpStringC& chatter, const OpStringC& changed_by, EngineTypes::ChatProperty property, const OpStringC& property_string, INT32 property_value) { if (!IsModelForRoom(account_id, room.ChatName())) { return; } if (property == EngineTypes::ROOM_MODERATED) { m_is_moderated = property_value; ChangeAll(); return; } ChattersModelItem* item = GetChatter(chatter); if (item) { switch (property) { case EngineTypes::CHATTER_NICK: { m_chatters_hash_table.Remove(item->GetName(), &item); item->SetName(property_string); m_chatters_hash_table.Add(item->GetName(), item); break; } case EngineTypes::CHATTER_OPERATOR: { item->SetOperator(property_value); break; } case EngineTypes::CHATTER_VOICED: { item->SetVoiced(property_value); break; } case EngineTypes::CHATTER_PRESENCE: { item->SetStatus((AccountTypes::ChatStatus) property_value); break; } case EngineTypes::CHATTER_UNKNOWN_MODE_OPERATOR: { item->SetOperator(property_value == 1); } case EngineTypes::CHATTER_UNKNOWN_MODE_VOICED: { item->SetVoiced(property_value == 1); } } item->Change(TRUE); } } #endif // IRC_SUPPORT
#include "profit.h" #include "ui_profit.h" #include<rone.h> profit::profit(QWidget *parent) : QDialog(parent), ui(new Ui::profit) { ui->setupUi(this); } profit::~profit() { delete ui; } void profit::on_pushButton_clicked() { hide(); rone s; s.setModal(true); s.exec(); }
#include<iostream> #include<cstdio> #include<cstring> #define fo(i,u,d) for (long i=(u); i<=(d); ++i) #define min(u,d) (u)<(d)?(u):(d) using namespace std; const long maxn=5100; const long maxm=100010; const long inf=1000000000; long head[maxn],next[maxm],node[maxm],tt; long c[maxm],cost[maxm]; //残留网,边费用 long dist[maxn]; //距离标号 long pre_d[maxn],pre_e[maxn]; //记录增广路上每点的前驱、到达它的边 long que[maxm]; bool vis[maxn]; long n,m,st,ed; long maxflow,mincost; void add(long x, long y, long ff, long cc) { node[++tt]=y, next[tt]=head[x], head[x]=tt; c[tt]=ff, cost[tt]=cc; } void init() { } bool cal_dist() //spfa求出最短增广路 { memset(vis,0,sizeof(vis)); fo(i,st,ed) dist[i]=inf; dist[st]=0; que[0]=st; vis[st]=1; for (long x=que[0],s=0,t=1; s!=t; vis[x]=0, ++s, x=que[s]) for (long dd, i=head[x]; i>-1; i=next[i]) if (c[i] && dist[node[i]]>(dd=dist[x]+cost[i])) { pre_d[node[i]]=x, pre_e[node[i]]=i, dist[node[i]]=dd; if (!vis[node[i]]) { vis[node[i]]=1; que[t++]=node[i]; } } return dist[ed]!=inf; } long aug() //沿最短路增广 { long x, aug_flow=inf; for (x=ed; x!=st; x=pre_d[x]) aug_flow=min(aug_flow,c[pre_e[x]]); mincost+=aug_flow*dist[ed]; for (x=ed; x!=st; x=pre_d[x]) c[pre_e[x]]-=aug_flow, c[pre_e[x]^1]+=aug_flow; return aug_flow; } void solve() { maxflow=0; mincost=0; while (cal_dist()) maxflow+=aug(); } int main() { init(); solve(); return 0; }
#include <stdio.h> #include"mytcp.h" #include <string.h> #include <stdlib.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/socket.h> #include <algorithm> using std::min; bool strcmp1(const char *,const char *); int main(){ char buff[100]; char ret_msg[100]; tcp_client client; client.init("127.0.0.1",1234); client.client_connect(); int n=0; while(1) { client.resv_msg(buff,sizeof(buff)); printf("copy it :\n%s\n",buff); ++n; sprintf(ret_msg,"I have %d messages",n); client.send_msg(ret_msg,strlen(ret_msg)+1); if(strcmp1(buff,"$end")) break; } } bool strcmp1(const char * a,const char *b) { int len=min(strlen(a),strlen(b)); for(int i=0;i<len;++i) if(a[i]!=b[i]) return 0; return 1; }
#ifndef MIANVIEW_H #define MIANVIEW_H #include <QWidget> #include <QStandardItemModel> #include <QSqlTableModel> #include <QMessageBox> #include <adddata.h> #include <databases.h> namespace Ui { class MianView; } class MianView : public QWidget { Q_OBJECT public: explicit MianView(QWidget *parent = nullptr); ~MianView(); adddata *add; databases da; void updataTablewidgetData(); private slots: void on_pB_del_clicked(); void on_pB_add_clicked(); void on_pB_exit_clicked(); void on_pB_shuaxin_clicked(); void on_pB_modify_clicked(); void on_pB_Inquire_clicked(); private: Ui::MianView *ui; }; #endif // MIANVIEW_H
// Created on: 2002-12-12 // Created by: data exchange team // Copyright (c) 2002-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _StepElement_ElementDescriptor_HeaderFile #define _StepElement_ElementDescriptor_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <StepElement_ElementOrder.hxx> #include <Standard_Transient.hxx> class TCollection_HAsciiString; class StepElement_ElementDescriptor; DEFINE_STANDARD_HANDLE(StepElement_ElementDescriptor, Standard_Transient) //! Representation of STEP entity ElementDescriptor class StepElement_ElementDescriptor : public Standard_Transient { public: //! Empty constructor Standard_EXPORT StepElement_ElementDescriptor(); //! Initialize all fields (own and inherited) Standard_EXPORT void Init (const StepElement_ElementOrder aTopologyOrder, const Handle(TCollection_HAsciiString)& aDescription); //! Returns field TopologyOrder Standard_EXPORT StepElement_ElementOrder TopologyOrder() const; //! Set field TopologyOrder Standard_EXPORT void SetTopologyOrder (const StepElement_ElementOrder TopologyOrder); //! Returns field Description Standard_EXPORT Handle(TCollection_HAsciiString) Description() const; //! Set field Description Standard_EXPORT void SetDescription (const Handle(TCollection_HAsciiString)& Description); DEFINE_STANDARD_RTTIEXT(StepElement_ElementDescriptor,Standard_Transient) protected: private: StepElement_ElementOrder theTopologyOrder; Handle(TCollection_HAsciiString) theDescription; }; #endif // _StepElement_ElementDescriptor_HeaderFile
//prime number #include<iostream> using namespace std; int main(){ int n; cin>>n; int m=n/2; int flag=0; for(int i=2;i<=m;i++) { if(n%i==0) { cout<<"Not prime"; flag=1; break; } } if(flag==0) { cout<<"Prime"; } return 0; }
#include<bits/stdc++.h> using namespace std; vector<int> merge(int arr1[],int arr2[],int n1,int n2) { int i=0,j=0; vector<int> v; while(i<n1 && j<n2) { if(arr1[i]<=arr2[j]){v.push_back(arr1[i]);i++;} else{v.push_back(arr2[j]);j++;} } while(i<n1){v.push_back(arr1[i]);i++;} while(j<n2){v.push_back(arr2[j]);j++;} return v; } int main() { int n1; cout<<"Enter the number of elements in array1:";cin>>n1; cout<<"Enter the first sorted array:"<<endl; int arr1[n1]; for(int i=0;i<n1;i++){cin>>arr1[i];} int n2; cout<<"Enter the number of elements in array2:";cin>>n2; cout<<"Enter the second array:"<<endl; int arr2[n2]; for(int i=0;i<n2;i++){cin>>arr2[i];} vector<int> v=merge(arr1,arr2,n1,n2); for(auto x:v){cout<<x<<" ";} return 0; }
#pragma once #include "plbase/PluginBase.h" #include "CTaskComplex.h" #include "CAiTimer.h" #pragma pack(push, 4) class PLUGIN_API CTaskComplexKillPedOnFoot : public CTaskComplex { public: unsigned __int8 m_nFlags; class CPed *m_pTarget; unsigned __int32 m_dwAttackFlags; unsigned __int32 m_dwActionDelay; unsigned __int32 m_dwActionChance; __int8 field_20; unsigned __int32 m_dwLaunchTime; signed __int32 m_dwTime; CAiTimer m_AiTimer; CTaskComplexKillPedOnFoot(); ~CTaskComplexKillPedOnFoot(); }; #pragma pack(pop) //VALIDATE_SIZE(CTaskComplexKillPedOnFoot, 0x38);
#ifndef GNTEXTURE_H #define GNTEXTURE_H #include "GnTextureMap.h" class GnTexture : public GnObject { GnDeclareRTTI; GnDeclareStream; protected: static gchar msTextureWorkPath[GN_MAX_PATH]; GnTextureMap* mpTextureMap; GnSimpleString mFileName; guint mWidth; guint mHeight; public: GnTexture(); virtual ~GnTexture(); public: static gchar* GetTextureWorkPath(); static void SetTextureWorkPath(const gchar* val); inline bool CreateTexture(GnTextureMap::eMapType mapType, const gchar* pcPathName) { mFileName = pcPathName; return CreateTexture( mapType ); } inline GnTextureMap* GetTextureMap() { return mpTextureMap; } inline gtuint GetIndex() { return mpTextureMap->GetMapType(); } inline guint GetWidth() const { return mWidth; } inline guint GetHeight() const { return mHeight; } inline const gchar* GetTextureFileName() { return mFileName; } protected: virtual bool DoCreateTexture(const gchar* tcPathName) = 0; inline void SetWidth(guint val) { mWidth = val; } inline void SetHeight(guint val) { mHeight = val; } private: bool CreateTexture(GnTextureMap::eMapType mapType); }; GnSmartPointer(GnTexture); #endif // GNTEXTURE_H
#include<iostream> #include<vector> #include<algorithm> #include<map> #include<set> #include<stack> using namespace std; class Solution { public: vector<double> res; //最后返回的结果 map<string,int> vex; //顶点string转化为int映射,方便用连接矩阵存储有向加权图 vector<vector<double>> arc; //连接矩阵表示有向加权图 vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) { //基本思想:递归dfs深度优先搜索,抽象成有向加权图,使用深度优先遍历找寻路径,路径上的值相乘即为结果 int cnt=0; //将顶点string转化为int映射,方便用连接矩阵表示有向加权图 for(int i=0;i<equations.size();i++) { if(vex.find(equations[i][0])==vex.end()) vex[equations[i][0]]=cnt++; if(vex.find(equations[i][1])==vex.end()) vex[equations[i][1]]=cnt++; } vector<double> temp(cnt,0.0); arc.resize(cnt,temp); //初始化连接矩阵 for(int i=0;i<equations.size();i++) { arc[vex[equations[i][0]]][vex[equations[i][1]]]=values[i]; arc[vex[equations[i][1]]][vex[equations[i][0]]]=1.0/values[i]; arc[vex[equations[i][0]]][vex[equations[i][0]]]=1.0; arc[vex[equations[i][1]]][vex[equations[i][1]]]=1.0; } //遍历每一个需要查询的顶点from到to的路径权重 for(int i=0;i<queries.size();i++) { //没有存储过的顶点,保存-1 if(vex.find(queries[i][0])==vex.end()||vex.find(queries[i][1])==vex.end()) { res.push_back(-1.0); continue; } //visited记录当前顶点是否访问过 vector<bool> visited(cnt,false); visited[vex[queries[i][0]]]=true; //深度优先搜索from到to的路径权重 if(!dfs(vex[queries[i][0]],vex[queries[i][1]],1.0,visited)) res.push_back(-1.0); } return res; } bool dfs(int from,int to,double cur,vector<bool> visited) { if(from==to) { res.push_back(cur); return true; } for(int i=0;i<arc[from].size();i++) { if(arc[from][i]!=0&&visited[i]==false) { visited[i]=true; if(dfs(i,to,cur*arc[from][i],visited)) return true; visited[i]=false; } } return false; } }; int main() { Solution solute; vector<vector<string>> equations = {{"a","b"},{"b","c"}}; vector<double> values = {2.0,3.0}; vector<vector<string>> queries = {{"a","c"},{"b","a"},{"a","e"},{"a","a"},{"x","x"}}; vector<double> res=solute.calcEquation(equations,values,queries); for_each(res.begin(),res.end(),[](double v){cout<<v<<endl;}); return 0; }
#include<iostream> #include<vector> #include<unordered_map> using namespace std; string addUp2K(vector<int> list, int k){ unordered_map<int, bool> hash; for(int i:list){ if (hash[k-i]){ cout<<"numbers are "<<i<<","<<k-i<<endl; return "true"; } else hash[i] = true; } return "false"; } int main(){ vector<int> arr; for(int i=0; i<10; i++){ arr.push_back(10-i); } cout<<addUp2K(arr, 12)<<endl; }
// // Created by fab on 05/12/2020. // #include "../../../headers/components/IComponent.hpp" #include "../../../headers/components/rendering/SkyBox.hpp" void SkyBox::start() { IComponent::start(); } void SkyBox::draw() { IComponent::draw(); } void SkyBox::drawInspector() { IComponent::drawInspector(); }
/* Copyright 2021 University of Manchester Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http: // www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include "graph_creator_interface.hpp" #include "gmock/gmock.h" using orkhestrafs::dbmstodspi::GraphCreatorInterface; class MockGraphCreator : public GraphCreatorInterface { public: MOCK_METHOD(std::unique_ptr<ExecutionPlanGraphInterface>, MakeGraph, (std::string graph_def_filename, std::unique_ptr<ExecutionPlanGraphInterface> graph), (override)); };
/*********************************************************************** ÀࣺNOISE SceneManger ¼òÊö£ºCenter of many manager object£¨MESH,LIGHT,MATERIAL,TEXTURE...£© ************************************************************************/ //!!!!!!!!!IMPORTANT : when a new class need to be bound to IScene,remember to modify // 1. Inheritance // 2. Destructor // 3. Corresponding Creation method #include "Noise3D.h" #include "Scene.h" using namespace Noise3D; IScene::IScene(): IFactory<IRenderer>(1), IFactory<ICamera>(1), IFactory<IMeshManager>(1), IFactory<ILightManager>(1), IFactory<ITextureManager>(2),//scene/font-internal IFactory<IMaterialManager>(1), IFactory<IGraphicObjectManager>(2),//scene/font-internal IFactory<IAtmosphere>(1), IFactory<IFontManager>(1), IFactory<IModelLoader>(1), IFactory<IModelProcessor>(1), IFactory<ICollisionTestor>(1) { } IScene::~IScene() { ReleaseAllChildObject(); } void IScene::ReleaseAllChildObject() { IFactory<IMeshManager>::DestroyAllObject(); IFactory<IRenderer>::DestroyAllObject(); IFactory<ICamera>::DestroyAllObject(); IFactory<ILightManager>::DestroyAllObject(); IFactory<ITextureManager>::DestroyAllObject(); IFactory<IMaterialManager>::DestroyAllObject(); IFactory<IAtmosphere>::DestroyAllObject(); IFactory<IGraphicObjectManager>::DestroyAllObject(); IFactory<ICollisionTestor>::DestroyAllObject(); } //first time to init RENDERER IRenderer * IScene::CreateRenderer(UINT BufferWidth, UINT BufferHeight,HWND renderWindowHWND) { static const N_UID uid = "sceneRenderer"; if (IFactory<IRenderer>::FindUid(uid) == false) { IRenderer* pRd = IFactory<IRenderer>::CreateObject(uid); //init of shaders/RV/states/.... bool isSucceeded = pRd->mFunction_Init(BufferWidth,BufferHeight, renderWindowHWND); if (isSucceeded) { return pRd; } else { IFactory<IRenderer>::DestroyObject(uid); ERROR_MSG("IScene: Renderer Initialization failed."); return nullptr; } } return IFactory<IRenderer>::GetObjectPtr(uid); } IRenderer * IScene::GetRenderer() { static const N_UID uid = "sceneRenderer"; if (IFactory<IRenderer>::FindUid(uid) == false) { ERROR_MSG("IScene: GetRenderer() : Renderer must be initialized by CreateRenderer() method."); return nullptr; } else { //return initialized renderer ptr return IFactory<IRenderer>::GetObjectPtr(uid); } }; IMeshManager * IScene::GetMeshMgr() { static const N_UID uid = "sceneMeshMgr"; if (IFactory<IMeshManager>::FindUid(uid) == false) { IFactory<IMeshManager>::CreateObject(uid); } return IFactory<IMeshManager>::GetObjectPtr(uid); }; ICamera * IScene::GetCamera() { const N_UID uid = "sceneCamera"; if (IFactory<ICamera>::FindUid(uid) == false) { IFactory<ICamera>::CreateObject(uid); } return IFactory<ICamera>::GetObjectPtr(uid); } ILightManager * IScene::GetLightMgr() { const N_UID uid = "sceneLightMgr"; if (IFactory<ILightManager>::FindUid(uid) == false) { IFactory<ILightManager>::CreateObject(uid); } return IFactory<ILightManager>::GetObjectPtr(uid); } ITextureManager * IScene::GetTextureMgr() { const N_UID uid = "sceneTexMgr"; if (IFactory<ITextureManager>::FindUid(uid) == false) { IFactory<ITextureManager>::CreateObject(uid); } return IFactory<ITextureManager>::GetObjectPtr(uid); } IMaterialManager * IScene::GetMaterialMgr() { const N_UID uid = "sceneMatMgr"; if (IFactory<IMaterialManager>::FindUid(uid) == false) { IFactory<IMaterialManager>::CreateObject(uid); } return IFactory<IMaterialManager>::GetObjectPtr(uid); } IAtmosphere * IScene::GetAtmosphere() { const N_UID uid = "sceneAtmos"; if (IFactory<IAtmosphere>::FindUid(uid) == false) { IFactory<IAtmosphere>::CreateObject(uid); } return IFactory<IAtmosphere>::GetObjectPtr(uid); } IGraphicObjectManager * IScene::GetGraphicObjMgr() { const N_UID uid = "sceneGObjMgr"; if (IFactory<IGraphicObjectManager>::FindUid(uid) == false) { IFactory<IGraphicObjectManager>::CreateObject(uid); } return IFactory<IGraphicObjectManager>::GetObjectPtr(uid); } IFontManager * IScene::GetFontMgr() { const N_UID uid = "sceneFontMgr"; if (IFactory<IFontManager>::FindUid(uid) == false) { IFontManager* pFontMgr = IFactory<IFontManager>::CreateObject(uid); //init of FreeType, internal TexMgr,GraphicObjMgr auto pTexMgr = mFunction_GetTexMgrInsideFontMgr(); auto pGObjMgr = mFunction_GetGObjMgrInsideFontMgr(); bool isSucceeded = pFontMgr->mFunction_Init(pTexMgr,pGObjMgr); if (isSucceeded) { return pFontMgr; } else { IFactory<IFontManager>::DestroyObject(uid); ERROR_MSG("IScene: Font Manager Initialization failed."); return nullptr; } } return IFactory<IFontManager>::GetObjectPtr(uid); } IModelLoader * IScene::GetModelLoader() { const N_UID uid = "sceneModelLoader"; if (IFactory<IModelLoader>::FindUid(uid) == false) { IFactory<IModelLoader>::CreateObject(uid); } return IFactory<IModelLoader>::GetObjectPtr(uid); } IModelProcessor * Noise3D::IScene::GetModelProcessor() { const N_UID uid = "sceneModelProcessor"; if (IFactory<IModelProcessor>::FindUid(uid) == false) { IFactory<IModelProcessor>::CreateObject(uid); } return IFactory<IModelProcessor>::GetObjectPtr(uid); } ICollisionTestor * IScene::GetCollisionTestor() { const N_UID uid = "sceneCollisionTestor"; if (IFactory<ICollisionTestor>::FindUid(uid) == false) { ICollisionTestor* pCT = IFactory<ICollisionTestor>::CreateObject(uid); //init of FreeType, internal TexMgr,GraphicObjMgr bool isSucceeded = pCT->mFunction_Init(); if (isSucceeded) { return pCT; } else { IFactory<ICollisionTestor>::DestroyObject(uid); ERROR_MSG("IScene: Collision Testor Initialization failed."); return nullptr; } } return IFactory<ICollisionTestor>::GetObjectPtr(uid); } /************************************************************************ P R I V A T E ************************************************************************/ ITextureManager * IScene::mFunction_GetTexMgrInsideFontMgr() { //get internal texMgr singleton instance const N_UID uid = "TexMgrOfFont"; if (IFactory<ITextureManager>::FindUid(uid) == false) { IFactory<ITextureManager>::CreateObject(uid); } return IFactory<ITextureManager>::GetObjectPtr(uid); } IGraphicObjectManager * IScene::mFunction_GetGObjMgrInsideFontMgr() { //get internal GObjMgr singleton instance const N_UID uid = "GObjMgrOfFont"; if (IFactory<IGraphicObjectManager>::FindUid(uid) == false) { IFactory<IGraphicObjectManager>::CreateObject(uid); } return IFactory<IGraphicObjectManager>::GetObjectPtr(uid); } IScene * Noise3D::GetScene() { return GetRoot()->GetScenePtr(); }
/***************************************************************************************************************** * File Name : DetectLoopInLL.h * File Location : C:\Users\AVINASH\Desktop\CC++\Programming\src\sites\geeksforgeeks\linkedlist\page04\DetectLoopInLL.h * Created on : Dec 18, 2013 :: 1:17:36 AM * Author : AVINASH * Testing Status : TODO * URL : TODO *****************************************************************************************************************/ /************************************************ Namespaces ****************************************************/ using namespace std; using namespace __gnu_cxx; /************************************************ User Includes *************************************************/ #include <string> #include <vector> #include <cstdlib> #include <cstdio> #include <cmath> #include <algorithm> #include <ctime> #include <list> #include <map> #include <set> #include <bitset> #include <functional> #include <utility> #include <iostream> #include <fstream> #include <sstream> #include <string.h> #include <hash_map> #include <stack> #include <queue> #include <limits.h> #include <programming/ds/tree.h> #include <programming/ds/linkedlist.h> #include <programming/utils/treeutils.h> #include <programming/utils/llutils.h> /************************************************ User defined constants *******************************************/ #define null NULL /************************************************* Main code ******************************************************/ #ifndef DETECTLOOPINLL_H_ #define DETECTLOOPINLL_H_ bool detectLoopInLLHashmapIterative(llNode *ptr){ if(ptr == NULL){ return false; } hash_map<uint32_t,bool> visitedFlagMap; llNode *traversalPtr = ptr; while(traversalPtr != NULL){ if(traversalPtr->next == NULL){ return false; } if(visitedFlagMap.find((uint32_t)traversalPtr->next) != visitedFlagMap.end()){ return true; } visitedFlagMap.insert(pair<uint32_t,bool>((uint32_t)traversalPtr,true)); } return false; } bool detectLoopAuxspaceIterative(llNodeWithFlag *ptr){ if(ptr == NULL){ return false; } llNodeWithFlag *traversalPtr = ptr; while(traversalPtr != NULL){ if(traversalPtr->next == NULL){ return false; } if(traversalPtr->next->flag){ return true; } traversalPtr->flag = true; } return false; } bool detectLoopAuxspace(llNodeWithFlag *ptr){ if(ptr == NULL || ptr->next == NULL){ return false; } if(ptr->next->flag){ return true; } ptr->flag = true; return detectLoopAuxspaceRecursive(ptr->next); } bool detectLoopTwoPtrsIterative(llNodeWithFlag *ptr){ if(ptr == NULL){ return false; } llNode *slowPtr = ptr,*fastPtr = ptr; while(slowPtr != NULL && fastPtr != NULL && fastPtr->next != NULL){ if(slowPtr == fastPtr){ return true; } slowPtr = slowPtr->next; fastPtr = fastPtr->next->next; } return false; } #endif /* DETECTLOOPINLL_H_ */ /************************************************* End code *******************************************************/
#pragma once #include "cq.h" #include "kmerutil.h" namespace bns { class CircusEnt { circ::deque<char> q_; uint8_t counts_[4]; uint8_t cqsz_; const uint8_t qsz_; const double qszinv_; public: static constexpr double NOT_FULL = -1.; CircusEnt(unsigned qsz): q_(qsz), counts_{0}, cqsz_(0), qsz_(qsz), qszinv_(1./qsz) { if(qsz == 0 || qsz > 255) RUNTIME_ERROR(std::string("Illegal queue size with qsz = " + std::to_string(qsz) + " and maximum value " + std::to_string(std::numeric_limits<uint8_t>::max()))); } CircusEnt(const CircusEnt &other): q_(other.q_), qsz_(other.qsz_), qszinv_(other.qszinv_) { std::memcpy(counts_, other.counts_, sizeof(counts_)); } CircusEnt(CircusEnt &&other) = default; void clear() { *(reinterpret_cast<uint32_t *>(counts_)) = cqsz_ = 0; q_.clear(); } void push(char c) { #if !NDEBUG if(cqsz_ == qsz_) { auto to_pop = cstr_lut[q_.pop()]; assert(to_pop != static_cast<int8_t>(-1)); assert(counts_[to_pop]); --counts_[to_pop]; } q_.push(c); assert(cstr_lut[c] != static_cast<int8_t>(-1)); ++counts_[cstr_lut[c]]; static_assert(std::is_unsigned<typename std::decay<decltype(q_.size())>::type>::value, "q's size should be unsigned."); assert(unsigned(counts_[0] + counts_[1] + counts_[2] + counts_[3]) == q_.size()); #else // Increment count of added nucleotide // If not fu ++counts_[cstr_lut[c]]; if(cqsz_ == qsz_) { --counts_[cstr_lut[q_.pop()]]; // Pop and decrement } else { ++cqsz_; // Or just keep filling the window } q_.push(c); #endif } double value() const { if(unlikely(cqsz_ < qsz_)) return NOT_FULL; assert(cqsz_ == q_.size()); double tmp(qszinv_ * (counts_[0])), sum(tmp * std::log2(tmp)); tmp = qszinv_ * counts_[1], sum += tmp * std::log2(tmp); tmp = qszinv_ * counts_[2], sum += tmp * std::log2(tmp); tmp = qszinv_ * counts_[3], sum += tmp * std::log2(tmp); return sum; } u64 score() const { return UINT64_MAX - static_cast<u64>(UINT64_C(7958933093282078720) * value()); } double next_ent(char c) { push(c); return value(); } }; } // namespace bns
#ifndef SCHEME_VALUES_ATOM_HPP #define SCHEME_VALUES_ATOM_HPP #include "Utils.hpp" #include <memory> #include <string> class Scheme_value; class Environment; class Symbol { public: explicit Symbol(const std::string& atom); std::string as_string() const; private: std::string name; }; #endif // SCHEME_VALUES_ATOM_HPP
/* * Program: Blending.h * Usage: Blend result images into one stitched image */ #ifndef BLENDING_H #define BLENDING_H #include <iostream> #include <vector> #include "CImg.h" using namespace std; using namespace cimg_library; class Blender{ public: Blender(CImg<unsigned char>& src1, CImg<unsigned char>& src2); CImg<unsigned char> blendImages(); private: CImg<unsigned char> srcImg1; CImg<unsigned char> srcImg2; // Judge empty function inline bool empty(CImg<unsigned char> img, int x, int y){ if(img(x, y, 0) == 0 && img(x, y, 1) == 0 && img(x, y, 2) == 0) return true; else return false; } }; #endif
#pragma once #ifndef CITY_H #define CITY_H #include <string> #include <vector> #include "Flight.h" using namespace std; class City { public: City(string city) : myCity(city) {}; void addflight(City* end, int mile, int price) { Flight toPlace(this, end, mile, price); outflights.push_back(toPlace); end->inflights.push_back(toPlace); } int sizeOut() { return outflights.size(); } string getReturn(int i) { return (outflights[i].getDestination()->getCityName()); } string getCityName() { return myCity; }; private: string myCity; vector<Flight> inflights; vector<Flight> outflights; }; #endif
#include <AssetsManager.h> #include <TexturesManager.h> #include <ShadersManager.h> #include <FontsManager.h> #include <OGLML/Texture2D.h> #include <OGLML/Shader.h> #include <OGLML/Font.h> #include <cassert> using namespace breakout; AssetManager::AssetManager() { } AssetManager::~AssetManager() { UnloadAll(); } AssetManager& AssetManager::Get() { static AssetManager assetManager; return assetManager; } void AssetManager::LoadAll() { TexturesManager& texturesManager = TexturesManager::Get(); for (auto& path : m_texturesPaths) texturesManager.Load(static_cast<int>(path.first), path.second); ShadersManager& shadersManager =ShadersManager::Get(); for (auto& path : m_shadersPaths) shadersManager.Load(static_cast<int>(path.first), path.second); FontsManager& fontsManager = FontsManager::Get(); for (auto& path : m_fontsPaths) fontsManager.Load(static_cast<int>(path.first), path.second); } void AssetManager::UnloadAll() { TexturesManager& texturesManager = TexturesManager::Get(); for (auto& path : m_texturesPaths) texturesManager.Unload(static_cast<int>(path.first)); ShadersManager& shadersManager = ShadersManager::Get(); for (auto& path : m_shadersPaths) shadersManager.Unload(static_cast<int>(path.first)); FontsManager& fontsManager = FontsManager::Get(); for (auto& path : m_fontsPaths) fontsManager.Unload(static_cast<int>(path.first)); } //---------------------------------------------------------------------------------------- void AssetManager::Bind(breakout::ETextureAssetId textureId, const std::string& texturePath) { m_texturesPaths[textureId] = texturePath; } bool AssetManager::Get(breakout::ETextureAssetId textureId, oglml::Texture2D& texture) { int id = static_cast<int>(textureId); return TexturesManager::Get().GetResource(id, texture); } bool AssetManager::Load(breakout::ETextureAssetId textureId) { int id = static_cast<int>(textureId); return TexturesManager::Get().Load(id, m_texturesPaths[textureId]); } bool AssetManager::Unload(breakout::ETextureAssetId textureId) { int id = static_cast<int>(textureId); return TexturesManager::Get().Unload(id); } //---------------------------------------------------------------------------------------- void AssetManager::Bind(breakout::EShaderAssetId shaderId, const std::string& shaderPath) { m_shadersPaths[shaderId] = shaderPath; } bool AssetManager::Get(breakout::EShaderAssetId shaderId, oglml::Shader& shader) { int id = static_cast<int>(shaderId); return ShadersManager::Get().GetResource(id, shader); } bool AssetManager::Load(breakout::EShaderAssetId shaderId) { int id = static_cast<int>(shaderId); return ShadersManager::Get().Load(id, m_shadersPaths[shaderId]); } bool AssetManager::Unload(breakout::EShaderAssetId shaderId) { int id = static_cast<int>(shaderId); return ShadersManager::Get().Unload(id); } //---------------------------------------------------------------------------------------- void AssetManager::Bind(breakout::EFontsAssetId fontId, const std::string& fontPath) { m_fontsPaths[fontId] = fontPath; } bool AssetManager::Get(breakout::EFontsAssetId fontId, oglml::Font& font) { int id = static_cast<int>(fontId); return FontsManager::Get().GetResource(id, font); } bool AssetManager::Load(breakout::EFontsAssetId fontId) { int id = static_cast<int>(fontId); return FontsManager::Get().Load(id, m_fontsPaths[fontId]); } bool AssetManager::Unload(breakout::EFontsAssetId fontId) { int id = static_cast<int>(fontId); return FontsManager::Get().Unload(id); } //---------------------------------------------------------------------------------------- void AssetManager::Bind(breakout::ESoundAssetId soundId, const std::string& soundPath) { m_soundPaths[soundId] = soundPath; } const std::string& AssetManager::GetPath(breakout::ESoundAssetId soundId) { assert(m_soundPaths.find(soundId) != m_soundPaths.end()); return m_soundPaths[soundId]; } //---------------------------------------------------------------------------------------- void AssetManager::Bind(breakout::EMusicAssetId musicId, const std::string& musicPath) { m_musicPaths[musicId] = musicPath; } const std::string& AssetManager::GetPath(breakout::EMusicAssetId musicId) { assert(m_musicPaths.find(musicId) != m_musicPaths.end()); return m_musicPaths[musicId]; }
#include <iostream> // knapsack #include "knapsackP.h" #include "knapsack.h" // TSP #include "route.h" #include "tsp.h" // real function #include "real_function.h" #include "real_vector.h" #include "EA.hpp" template <typename problem_class, typename solution_class> void solve_problem(size_t problem_size){ // Create a random problem problem_class problem(100); problem.disp(); for (int i = 0; i < 3; ++i) { // Create a solver for the problem using solver_t = EA<problem_class,solution_class>; solver_t solver(problem); // Choose an algorithm enum solver_t::algorithm alg = (i==0) ? solver_t::algorithm::DEFAULT : (i==1) ? solver_t::algorithm::GA : solver_t::algorithm::EE; solver.algorithm(alg); // Run! solver.run(); // Print final statistics int idx = 1; for (auto iter = solver.best_solutions_begin(); iter != solver.best_solutions_end(); ++iter) { std::cout << "Solution " << idx << ": " << std::endl; // (*iter)->disp(problem); // std::cout << "Objetive function " << idx << ": " << (*iter)->fx << std::endl; idx++; } } }; int main() { const size_t problem_size = 20; solve_problem<knapsack_p,knapsack>(problem_size); solve_problem<real_function,real_vector>(problem_size); solve_problem<tsp,route>(problem_size); return 0; }
#include "Timer.h" #include "RobotException.h" Timer::Timer() : nextID(1), timerHandle(NULL), time(0), repeat(false) {} Timer::~Timer() { if(mTimer.lock() != WAIT_OBJECT_0 || mHook.lock() != WAIT_OBJECT_0) throw RobotException("Timer destructor could not get locks!");; stop(); disconnect(); } Timer::Timer(DWORD setTime, Caller<void>* newCaller, bool repeat): nextID(1) { takeCaller(newCaller); setTimer(setTime); this->repeat = repeat; } bool Timer::start() { if(mTimer.lock() != WAIT_OBJECT_0) throw RobotException("Timer::start could not get timer lock!"); if(time == 0 || !hasCallers()) return false; DWORD period = 0; if(repeat) period = time; if(!CreateTimerQueueTimer(&timerHandle, // our handle NULL, // handle to the queue timerCallback, // the shared callback function for timers this, // pass along a pointer to the timer object time, // how long until first trigger period, // how long the period is 0 )) { timerHandle = NULL; mTimer.unlock(); return false; } mTimer.unlock(); return true; } void Timer::stop() { if(timerHandle != NULL) { if(mTimer.lock() != WAIT_OBJECT_0) throw RobotException("Timer::stop could not get lock!"); DeleteTimerQueueTimer(NULL, timerHandle, INVALID_HANDLE_VALUE); timerHandle = NULL; mTimer.unlock(); } } void Timer::setTimer(DWORD setTime) { if(mTimer.lock() != WAIT_OBJECT_0) throw RobotException("Timer::setTimer could not get lock!"); time = setTime; if(timerHandle) { DWORD period = 0; if(repeat) period = time; ChangeTimerQueueTimer(NULL, timerHandle, time, period); } mTimer.unlock(); } void Timer::setRepeating(bool repeating) { if(mTimer.lock() != WAIT_OBJECT_0) throw RobotException("Timer::setRepeating could not get lock!"); repeat = repeating; if(timerHandle) ChangeTimerQueueTimer(NULL, timerHandle, time, time); mTimer.unlock(); } UINT Timer::takeCaller(Caller<void>* newCaller) { if(!newCaller) return 0; if(mHook.lock() != WAIT_OBJECT_0) throw RobotException("Timer::takeCaller could not get lock!"); callerList.push_front(PAIRDEF(nextID, newCaller)); mHook.unlock(); return nextID++; } Caller<void>* Timer::giveCaller(UINT id) { if(mHook.lock() != WAIT_OBJECT_0) throw RobotException("Timer::giveCaller could not get lock!"); if(!hasCallers() || id == 0) { mHook.unlock(); return 0; } Caller<void>* tmp = 0; std::list<PAIRDEF>::iterator iter = callerList.begin(); while(iter != callerList.end()) { if(iter->first == id) { tmp = iter->second; callerList.erase(iter); break; } ++iter; } mHook.unlock(); return tmp; } void Timer::disconnect() { // aquiring mTimer might seem agressive but we need to prevent // users from starting the clock while we disconnect everything if(mTimer.lock() != WAIT_OBJECT_0 || mHook.lock() != WAIT_OBJECT_0) throw RobotException("disconnect could not get both locks!"); stop(); while(hasCallers()) { Caller<void>* tmp = callerList.front().second; callerList.pop_front(); delete tmp; } mTimer.unlock(); mHook.unlock(); } bool Timer::isRepeating() { return repeat; } bool Timer::hasCallers() { return !callerList.empty(); } void Timer::doCallback() { if(mHook.lock() != WAIT_OBJECT_0) throw RobotException("Timer::doCallback could not get lock!"); std::list<PAIRDEF>::iterator iter = callerList.begin(); while(iter != callerList.end()) { iter->second->doCall(); ++iter; } mHook.unlock(); } VOID CALLBACK timerCallback(PVOID lpParameter, BOOLEAN TimerOrWaitFired) { Timer* triggered = (Timer*) lpParameter; if(!lpParameter) throw RobotException("timerCallback was passed lpParameter of 0!"); triggered->doCallback(); }
#ifndef ACCESSMODEL_H #define ACCESSMODEL_H #include "adjunct/m2/src/include/defs.h" #include "adjunct/m2/src/engine/listeners.h" #include "adjunct/desktop_util/treemodel/optreemodel.h" class AccessModel; /*********************************************************************************** ** ** AccessModelItem ** ***********************************************************************************/ class AccessModelItem : public TreeModelItem<AccessModelItem, AccessModel> { public: AccessModelItem() {} AccessModelItem(int id) { m_id = id; m_is_sorting = FALSE;} virtual ~AccessModelItem() {} virtual OP_STATUS GetItemData(ItemData* item_data); virtual Type GetType() { return (INDEX_TYPE); } virtual int GetID() { return m_id; } virtual void PrepareForSorting() { m_is_sorting = TRUE; } private: BOOL IsCategory(index_gid_t index_id); OP_STATUS GetItemDescription(OpString& description); int m_id; BOOL m_is_sorting; AccessModelItem(const AccessModelItem&); AccessModelItem& operator=(const AccessModelItem&); }; /*********************************************************************************** ** ** AccessModel ** ***********************************************************************************/ class AccessModel : public TreeModel<AccessModelItem> , public IndexerListener , public EngineListener , public ProgressInfoListener { public: AccessModel(UINT32 category, Indexer* indexer); void ShowHiddenIndexes() { m_show_hidden_indexes = TRUE; } UINT32 GetCategoryID() { return m_category_id; } ~AccessModel(); virtual OP_STATUS Init(); void ReInit(); virtual INT32 GetColumnCount(); virtual OP_STATUS GetColumnData(ColumnData* column_data); #ifdef ACCESSIBILITY_EXTENSION_SUPPORT virtual OP_STATUS GetTypeString(OpString& type_string); #endif // Functions implementing the Indexer::Observer interface virtual OP_STATUS IndexAdded(Indexer *indexer, UINT32 index_id); virtual OP_STATUS IndexRemoved(Indexer *indexer, UINT32 index_id); virtual OP_STATUS IndexChanged(Indexer *indexer, UINT32 index_id) { return OpStatus::OK; } virtual OP_STATUS IndexNameChanged(Indexer *indexer, UINT32 index_id); virtual OP_STATUS IndexVisibleChanged(Indexer *indexer, UINT32 index_id); virtual OP_STATUS IndexParentIdChanged(Indexer *indexer, UINT32 index_id, UINT32 old_parent_id, UINT32 new_parent_id); virtual OP_STATUS IndexKeywordChanged(Indexer *indexer, UINT32 index_id, const OpStringC8& old_keyword, const OpStringC8& new_keyword) { return OpStatus::OK; } virtual OP_STATUS IndexIconChanged(Indexer* indexer, UINT32 index_id) { return AccessModel::IndexNameChanged(indexer, index_id); } virtual OP_STATUS KeywordAdded(Indexer* indexer, message_gid_t message_id, const OpStringC8& keyword) { return OpStatus::OK; } virtual OP_STATUS KeywordRemoved(Indexer* indexer, message_gid_t message_id, const OpStringC8& keyword) { return OpStatus::OK; } // Functions implementing the MessageEngine::EngineListener interface virtual void OnImporterProgressChanged(const Importer* importer, const OpStringC& infoMsg, OpFileLength current, OpFileLength total, BOOL simple = FALSE) {} virtual void OnImporterFinished(const Importer* importer, const OpStringC& infoMsg) {} virtual void OnIndexChanged(UINT32 index_id); virtual void OnActiveAccountChanged(); virtual void OnReindexingProgressChanged(INT32 progress, INT32 total) {}; // Functions implementing the ProgressInfoListener interface virtual void OnProgressChanged(const ProgressInfo& progress) {} virtual void OnSubProgressChanged(const ProgressInfo& progress) {} virtual void OnStatusChanged(const ProgressInfo& progress); private: BOOL BelongsToThisModel(Index* index); UINT32 m_category_id; BOOL m_show_hidden_indexes; Indexer* m_indexer; BOOL IsHiddenAccount(Index* index); ///< Temporarily hide POP-accounts void AddFolderItem(Index* index); AccessModel(); // dummy copy constructor and assignment operator AccessModel(const AccessModel&); AccessModel& operator=(const AccessModel&); }; #endif
// // LearnedLTFOS.hpp // GA // // Created by Tom den Ottelander on 09/12/2019. // Copyright © 2019 Tom den Ottelander. All rights reserved. // #ifndef LearnedLTFOS_hpp #define LearnedLTFOS_hpp #include <stdio.h> #include <vector> #include <unordered_set> #include <unordered_map> #include <set> #include "FOS.hpp" #include "Utility.hpp" #include "Individual.hpp" #include "ProblemType.hpp" class LearnedLT_FOS : public FOS { public: ProblemType *problemType; LearnedLT_FOS(ProblemType *problemType); std::vector<std::vector<int>> getFOS (std::vector<Individual> &population) override; std::vector<std::vector<int>> getFOS (int genotypeLength) override; std::string id() override; std::string toString() override; std::vector<std::vector<int>> GenerateLinkageTreeFOS(const std::vector<Individual>& population); std::vector<std::vector<int>> BuildLinkageTreeFromSimilarityMatrix(size_t number_of_nodes, std::vector<std::vector<double_t>> &sim_matrix); int DetermineNearestNeighbour(int index, std::vector<std::vector<double_t>> &S_matrix, std::vector<int> & mpm_number_of_indices, int mpm_length); std::vector<std::vector<int>> transformLinkageTreeFOS(std::vector<std::vector<size_t>>); }; #endif /* LearnedLTFOS_hpp */
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <sys/stat.h> #include <semaphore.h> #include <sys/types.h> #include <sys/mman.h> #include <csignal> #include <unistd.h> #include <errno.h> using namespace std; #define INTVAL 1 #define ERR -1 #define SHMBUFFLEN 256 sem_t *sem; int shmfd; key_t key; char *shm_buffer; void sig_usr1( int signo ) { if( signo != SIGUSR1 ) { printf( "...oops...\n" ); } // decrement the POSIX semaphore using sem_wait sem_wait( sem ); // display contents of shared memory segment printf( "<%s>\n", shm_buffer ); // clear contents of shared memory for( int i = 0; i < SHMBUFFLEN; i++ ) { *( shm_buffer + i ) = '\0'; } // release semaphore (using sem_post) sem_post( sem ); } int main( ) { // get pid pid_t pid = getpid( ); // setup signal handler if( signal( SIGUSR1, sig_usr1 ) == SIG_ERR ) { printf( "%s\n", strerror( errno )); exit( ERR ); } // just in case the POSIX semaphore is left over from a previous run sem_unlink( "/tmpsem" ); // create a named POSIX semaphore if( SEM_FAILED == ( sem = sem_open( "/tmpsem", O_CREAT | O_EXCL, S_IRWXU | S_IRGRP | S_IROTH, INTVAL ))) { printf( "%s\n", strerror( errno )); exit( ERR ); } // create a POSIX shared memory segment if( ERR == ( shmfd = shm_open( "/tmpshm", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH ))) { printf( "%s\n", strerror( errno )); exit( ERR ); } // the newly created shared memory segment is 0, so // resize it using ftruncate if( ERR == ftruncate( shmfd, SHMBUFFLEN )) { printf( "%s\n", strerror( errno )); exit( ERR ); } if( MAP_FAILED == ( shm_buffer = ( char * ) mmap ( NULL, SHMBUFFLEN, PROT_READ | PROT_WRITE, MAP_SHARED, shmfd, 0 ))) { printf( "%s\n", strerror( errno )); exit( ERR ); } // loop for-ever for(;;) { printf( "...tick...(%d)...\n", pid ); sleep( 1 ); } }
#ifdef DEBUG #define _GLIBCXX_DEBUG #endif #include <iostream> #include <algorithm> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <memory.h> #include <math.h> #include <string> #include <string.h> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> #include <sstream> #include <cassert> typedef long double LD; typedef long long LL; typedef unsigned long long ULL; typedef unsigned int uint; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; #define N 422222 #define NONE -2147483646 int n, m, w[N]; int pr[N]; int was[N]; int d[N]; vector<int> g[N]; void HLDoT(int x) { was[x] = true; for (size_t i = 0; i < g[x].size(); ++i) { int y = g[x][i]; if (!was[y]) { pr[y] = x; d[y] = d[x] + 1; HLDoT(y); } } } int main() { #ifdef DEBUG freopen(".in", "r", stdin); freopen(".out", "w", stdout); #endif scanf("%d%d", &n, &m); for (int i = 1; i <= n; ++i) scanf("%d", &w[i]); for (int i = 1; i < n; ++i) { int x, y; scanf("%d%d", &x, &y); g[x].push_back(y); g[y].push_back(x); } pr[1] = 0; HLDoT(1); while (m--) { int t, a, b, c; scanf("%d%d%d%d", &t, &a, &b, &c); if (t == 1) { while (d[a] > d[b]) { w[a] = c; a = pr[a]; } while (d[b] > d[a]) { w[b] = c; b = pr[b]; } while (a != b) { w[a] = c; w[b] = c; a = pr[a]; b = pr[b]; } w[a] = c; } else { vector<int> v1, v2; while (d[a] > d[b]) { v1.push_back(w[a]); a = pr[a]; } while (d[b] > d[a]) { v2.push_back(w[b]); b = pr[b]; } while (a != b) { v1.push_back(w[a]); v2.push_back(w[b]); a = pr[a]; b = pr[b]; } v1.push_back(w[a]); reverse(v2.begin(), v2.end()); for (int i = 0; i < v2.size(); ++i) v1.push_back(v2[i]); #ifdef DEBUG for (int i = 0; i < v1.size(); ++i) cerr << v1[i] << ' '; cerr << '\n'; #endif int ans = v1[0]; int ps = v1[0]; int lastps = min(0, v1[0]); for (int i = 1; i < v1.size(); ++i) { ps += v1[i]; if (ps - lastps > ans) ans = ps - lastps; if (ps < lastps) lastps = ps; } printf("%d\n", ans); } } cerr << clock() << endl; return 0; }
// Created on: 1996-04-01 // Created by: Flore Lantheaume // Copyright (c) 1996-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _DsgPrs_FixPresentation_HeaderFile #define _DsgPrs_FixPresentation_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Prs3d_Drawer.hxx> #include <Prs3d_Presentation.hxx> class gp_Pnt; class gp_Dir; //! class which draws the presentation of Fixed objects class DsgPrs_FixPresentation { public: DEFINE_STANDARD_ALLOC //! draws the presentation of fixed objects by //! drawing the 'fix' symbol at position <aPntEnd>. //! A binding segment is drawn between <aPntAttach> //! ( which belongs to the fixed object) and <aPntEnd>. //! aSymbSize is the size of the 'fix'symbol Standard_EXPORT static void Add (const Handle(Prs3d_Presentation)& aPresentation, const Handle(Prs3d_Drawer)& aDrawer, const gp_Pnt& aPntAttach, const gp_Pnt& aPntEnd, const gp_Dir& aNormPln, const Standard_Real aSymbSize); protected: private: }; #endif // _DsgPrs_FixPresentation_HeaderFile
#include<iostream> using namespace std; main(){ int size=10; int values[size][size],a,o1[100],i,j,max=0,k1,k2,num=0; for(i=0;i<size;i++){ for(j=0;j<size;j++){ values[i][j]=0; } } while(1){ cout<<"1: Irmeg nemeh, 2: Irmeg hasah, 3: Oroi nemeh, 4:Oroi hasah, 5: hewleh, 0: exit\n"; cin>>a; switch(a){ case 1: cout<<"Holbogdoh ontsguudiig oruul\n"; cin>>k1>>k2; if(max<k1 || max<k2){ if(k1<k2){ max=k2; }else{ max=k1; } } for(i=0; i<num; i++){ if(o1[i]==k1){ for(j=0; j<num; j++){ if(o1[j]==k2){ values[i][j]=1; values[j][i]=1; cout<<"Amjilttai holbogdloo\n"; break; } } } } if(j==max && i==max){ cout<<"Ali neg oroi buruu baina\n"; } break; case 2: cout<<"Oroinuudiig oruul\n"; cin>>k1>>k2; if(max<k1 || max<k2){ if(k1<k2){ max=k2; }else{ max=k1; } } for(i=0; i<num; i++){ if(o1[i]==k1){ for(j=0; j<num; j++){ if(o1[j]==k2){ values[i][j]=0; values[j][i]=0; cout<<"Ontsoguud holboltgui bolloo\n"; break; } } } } if(j==max && i==max){ cout<<"Ali neg oroi buruu baina\n"; } break; case 3: cout<<"Oroig oruul\n"; cin>>k1; o1[num]=k1; if(max<k1){ max=k1; } num++; break; case 4: cout<<"Oroig oruul\n"; cin>>k1; for(i=0;i<num;i++){ if(o1[i]==k1){ for(i;i<num-1;i++){ o1[i]=o1[i+1]; } cout<<"Amjilttai ustlaa\n"; num--; break; } } if(i==num){ cout<<"Oroig olj chadsangui\n"; } break; case 5: cout<<"Massiv-aar\n "; for(j=0;j<num;j++){ cout<<" "<<o1[j]; } cout<<endl; for(i=0;i<num;i++){ cout<<o1[i]<<" "; for(j=0;j<num;j++){ cout<<values[i][j]<<" "; } cout<<"\n"; } break; default: return 0; } } }
#include "block.h" #include "visitor.h" Block::Block(Variable_list* _v_list, Statement_list* _s_list) : v_list(_v_list), s_list(_s_list) {} void Block::Accept(AbstractDispatcher& dispatcher) { dispatcher.Dispatch(*this); } Block::~Block() { if (v_list != NULL) delete v_list; if (s_list != NULL) delete s_list; }
#include "Material.h" using namespace std; Material::Material(float aR, float aG, float aB, float dR, float dG, float dB, float sR, float sG, float sB, int P, float rR, float rG, float rB){ ambR = aR; ambG = aG; ambB = aB; difR = dR; difG = dG; difB = dB; speR = sR; speG = sG; speB = sB; speExpP = P; refR = rR; refG = rG; refB = rB; }
#include<iostream> using namespace std; int findMxmRecurrsion(int arr[], int length) { if(length == 1) return arr[0]; return max(findMxmRecurrsion(arr,length-1),arr[length-1]); } int findMimRecurrsion(int arr[], int length) { if(length == 1) return arr[0]; return min(findMimRecurrsion(arr,length-1),arr[length-1]); } int main() { int arr[] = {100,4,5,2,10}; int s = sizeof(arr)/sizeof(arr[0]); int maximumNumber = findMxmRecurrsion(arr,s); cout<<"Maximum number is: "<<maximumNumber<<endl; cout<<"Minimum number is: "<<findMimRecurrsion(arr,s)<<endl; }
// arr == &arr[0] // *arr == arr[0] // ptr + 1 == ptr에 sizeof(*ptr)를 더한 값 #include <iostream> int main(){ int arr[2][3] = {{1,2,3},{4,5,6}}; // 3개짜리 일차원 배열을 가르키는 포인터 int(*ptr)[3] = &arr[0]; // arr == &arr[0] for(int i=0; i<2; i++){ for(int j=0; j<3; j++){ printf("%d ", ptr[i][j]); } } printf("\n"); }
/** * 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. */ #ifndef CLIENT_H #define CLIENT_H #include <napi.h> #include <pulsar/c/client.h> struct LogMessage { pulsar_logger_level_t level; std::string file; int line; std::string message; LogMessage(pulsar_logger_level_t level, std::string file, int line, std::string message) : level(level), file(file), line(line), message(message) {} }; struct LogCallback { Napi::ThreadSafeFunction callback; }; class Client : public Napi::ObjectWrap<Client> { public: static Napi::Object Init(Napi::Env env, Napi::Object exports); static void SetLogHandler(const Napi::CallbackInfo &info); static void LogMessage(pulsar_logger_level_t level, const char *file, int line, const char *message, void *ctx); Client(const Napi::CallbackInfo &info); ~Client(); private: static LogCallback *logCallback; static Napi::FunctionReference constructor; std::shared_ptr<pulsar_client_t> cClient; std::shared_ptr<pulsar_client_configuration_t> cClientConfig; Napi::Value CreateProducer(const Napi::CallbackInfo &info); Napi::Value Subscribe(const Napi::CallbackInfo &info); Napi::Value CreateReader(const Napi::CallbackInfo &info); Napi::Value GetPartitionsForTopic(const Napi::CallbackInfo &info); Napi::Value Close(const Napi::CallbackInfo &info); }; #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2012 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. * * @author Alexander Remen (alexr@opera.com) * */ #include "core/pch.h" #ifdef M2_SUPPORT #include "adjunct/desktop_util/prefs/PrefsCollectionM2.h" #include "adjunct/m2/src/engine/accountmgr.h" #include "adjunct/m2/src/engine/engine.h" #include "adjunct/m2_ui/dialogs/SignatureEditor.h" #include "adjunct/m2_ui/controllers/ComposeWindowOptionsController.h" #include "adjunct/m2_ui/windows/ComposeDesktopWindow.h" #include "adjunct/quick_toolkit/bindings/QuickBinder.h" #include "adjunct/quick_toolkit/widgets/QuickCheckBox.h" #include "adjunct/quick_toolkit/widgets/CalloutDialogPlacer.h" #include "adjunct/quick_toolkit/widgets/QuickOverlayDialog.h" #include "adjunct/quick_toolkit/widgets/QuickDropDown.h" #include "modules/widgets/WidgetContainer.h" void ComposeWindowOptionsController::InitL() { QuickOverlayDialog* overlay_dialog = OP_NEW_L(QuickOverlayDialog, ()); LEAVE_IF_ERROR(SetDialog("Mail Compose Window Options Popup", overlay_dialog)); CalloutDialogPlacer* placer = OP_NEW_L(CalloutDialogPlacer, (*GetAnchorWidget())); overlay_dialog->SetDialogPlacer(placer); overlay_dialog->SetBoundingWidget(*GetAnchorWidget()->GetParentDesktopWindow()->GetWidgetContainer()->GetRoot()); overlay_dialog->SetAnimationType(QuickOverlayDialog::DIALOG_ANIMATION_CALLOUT); LEAVE_IF_ERROR(GetBinder()->Connect("Message_expanded_checkbox", m_expanded_draft)); m_expanded_draft.Set(g_pcm2->GetIntegerPref(PrefsCollectionM2::PaddingInComposeWindow) == 0); LEAVE_IF_ERROR(m_expanded_draft.Subscribe(MAKE_DELEGATE(*this, &ComposeWindowOptionsController::UpdateExpandedDraft))); int flags = g_pcm2->GetIntegerPref(PrefsCollectionM2::MailComposeHeaderDisplay); for (int i = 0; i < AccountTypes::HEADER_DISPLAY_LAST; i++) { m_show_flags[i].Set((flags & (1<<i)) != FALSE); OpString8 checkbox_name; LEAVE_IF_ERROR(checkbox_name.AppendFormat("cb_show_%d", i)); if (!overlay_dialog->GetWidgetCollection()->Contains<QuickWidget>(checkbox_name.CStr())) continue; LEAVE_IF_ERROR(GetBinder()->Connect(checkbox_name.CStr(), m_show_flags[i])); LEAVE_IF_ERROR(m_show_flags[i].Subscribe(MAKE_DELEGATE(*this, &ComposeWindowOptionsController::UpdateShowFlags))); } if (g_m2_engine->GetAccountManager()->GetMailNewsAccountCount() <= 1) overlay_dialog->GetWidgetCollection()->Get<QuickCheckBox>("cb_show_5")->Hide(); if (g_m2_engine->GetAccountManager()->GetFirstAccountWithType(AccountTypes::NEWS) == NULL) { if (overlay_dialog->GetWidgetCollection()->Contains<QuickCheckBox>("cb_show_10")) overlay_dialog->GetWidgetCollection()->Get<QuickCheckBox>("cb_show_10")->Hide(); overlay_dialog->GetWidgetCollection()->Get<QuickCheckBox>("cb_show_11")->Hide(); } QuickDropDown* from_dropdown = overlay_dialog->GetWidgetCollection()->Get<QuickDropDown>("Default_Account_Dropdown"); for (int i = 0; i < g_m2_engine->GetAccountManager()->GetAccountCount(); i++) { Account* account = g_m2_engine->GetAccountManager()->GetAccountByIndex(i); if (account && account->GetOutgoingProtocol() == AccountTypes::SMTP) { OpString16 mail; account->GetEmail(mail); if (mail.IsEmpty()) continue; if (account->GetAccountName().HasContent() && account->GetAccountName() != mail) { mail.Set(account->GetAccountName()); } LEAVE_IF_ERROR(from_dropdown->AddItem(mail.CStr(), -1, NULL, account->GetAccountId())); } } LEAVE_IF_ERROR(GetBinder()->Connect(*from_dropdown, g_m2_engine->GetAccountManager()->m_default_mail_account)); } OP_STATUS ComposeWindowOptionsController::HandleAction(OpInputAction* action) { if (action->GetAction() == OpInputAction::ACTION_OPEN_SIGNATURE_DIALOG) { SignatureEditor * signature_editor = OP_NEW(SignatureEditor,()); RETURN_OOM_IF_NULL(signature_editor); signature_editor->Init(GetAnchorWidget()->GetParentDesktopWindow(), static_cast<ComposeDesktopWindow*>(GetAnchorWidget()->GetParentDesktopWindow())->GetAccountId()); } return OpStatus::OK; } void ComposeWindowOptionsController::UpdateShowFlags(bool) { int flags = g_pcm2->GetIntegerPref(PrefsCollectionM2::MailComposeHeaderDisplay); for (int i = 0; i < AccountTypes::HEADER_DISPLAY_LAST; i++) { flags = m_show_flags[i].Get() ? flags | (1<<i) : flags & ~(1 << i); } TRAPD(err, g_pcm2->WriteIntegerL(PrefsCollectionM2::MailComposeHeaderDisplay, flags)); } void ComposeWindowOptionsController::UpdateExpandedDraft(bool expanded) { if (expanded) { TRAPD(err, g_pcm2->WriteIntegerL(PrefsCollectionM2::PaddingInComposeWindow, 0)); } else { TRAPD(err, g_pcm2->ResetIntegerL(PrefsCollectionM2::PaddingInComposeWindow)); } } #endif // M2_SUPPORT
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. #pragma once #include "EngineMinimal.h" #include "Modules/ModuleManager.h" UENUM(BlueprintType) enum class ECharacterState : uint8 { PREINIT, LOADING, READY, DEAD //NODAMAGE? -> 이건플래그로두는게낫나 }; class FSYCharacterModule : public IModuleInterface { public: /** IModuleInterface implementation */ virtual void StartupModule() override; virtual void ShutdownModule() override; };
#include "var.hpp" #ifndef VECTOR_HPP #define VECTOR_HPP class Vector{ protected: int size; int countForPush; int countForPop; Var* vector; public: Vector(); Vector(Vector& vec); Vector(Vector&& vec); ~Vector(); Vector(int n, Var fill); int getSize(); Var* getVector(); Var getElem(int index); void push(Var newElem); void pop(); void printVec(); }; #endif
class Point; class PointManagement { public: double getDistance(Point& a, Point& b); }; class Point { public: Point(double xx, double yy); friend double PointManagement::getDistance(Point& a, Point& b); private: double x, y; };
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup" -*- */ #include "core/pch.h" #include "modules/ecmascript/carakan/src/es_pch.h" #include "modules/ecmascript/carakan/src/builtins/es_builtins.h" #ifdef ES_DEBUG_BUILTINS #include "modules/ecmascript/carakan/src/builtins/es_debug_builtins.h" #ifdef ES_HEAP_DEBUGGER #ifndef _STANDALONE #include "modules/dom/domenvironment.h" #include "modules/dom/domtypes.h" #include "modules/dom/domutils.h" #endif // _STANDALONE #include "modules/ecmascript/carakan/src/es_program_cache.h" const char *g_ecmaClassName[] = { "free", "JStringStorage", "ES_Box", "JString", "JStringSegmented", "ES_Identifier_Array", "ES_IdentifierCell_Array", "ES_Property_Table", "ES_Property_Value_Table", "ES_Compact_Indexed_Properties", "ES_Sparse_Indexed_Properties", "ES_Byte_Array_Indexed", "ES_Type_Array_Indexed", "ES_Identifier_Hash_Table", "ES_Identifier_List", "ES_Identifier_Boxed_Hash_Table", "ES_Boxed_Array", "ES_Boxed_List", "ES_Class_Node", "ES_Class_Compact_Node", "ES_Class_Compact_Node_Frozen", "ES_Class_Singleton", "ES_Class_Class_Hash", "ES_Class_Extra", "ES_Class_Data", "ES_ProgramCode", "ES_FunctionCode", "ES_Properties", "ES_Special_Aliased", "ES_Special_Mutable_Access", "ES_Special_Global_Variable", "ES_Special_Builtin_Function_Name", "ES_Special_Builtin_Function_Length", "ES_Special_Builtin_Function_Prototype", "ES_Special_Function_Arguments", "ES_Special_Function_Caller", "ES_Special_RegExp_Capture", "ES_Special_Error_StackTrace", "ES_Object", "ES_Object_Number", "ES_Object_String", "ES_Object_Date", "ES_Object_Boolean", "ES_Object_Array", "ES_Object_Function", "ES_Object_RegExp", "ES_Object_RegExp_CTOR", "ES_Object_Error", "ES_Object_Arguments", "ES_Object_Variables", "ES_Object_TypedArray", "ES_Object_ArrayBuffer" }; /* static */ BOOL ES_DebugBuiltins::getHeapInformation(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { Head *active, *inactive, *destroy; g_ecmaManager->GetHeapLists(active, inactive, destroy); TempBuffer *buffer = g_ecmaManager->GetHeapDebuggerBuffer(); buffer->Clear(); buffer->Append("{ \"heaps\": { "); ES_Heap *heads[3] = { static_cast<ES_Heap *>(active->First()), static_cast<ES_Heap *>(inactive->First()), static_cast<ES_Heap *>(destroy->First()) }; for (unsigned head = 0; head < 3; ++head) for (ES_Heap *heap = heads[head]; heap; heap = static_cast<ES_Heap *>(heap->Suc())) { buffer->AppendFormat(UNI_L("\"%u\": { \"bytesLive\": %u, \"bytesLivePeak\": %u, \"bytesLimit\": %u, \"runtimes\": ["), heap->Id(), heap->GetBytesLive(), heap->GetBytesLivePeak(), heap->GetBytesLimit()); ES_Runtime *runtime = heap->GetFirstRuntime(); while (runtime) { #ifndef _STANDALONE ES_Object *global_object = runtime->GetGlobalObject(); if (global_object->IsHostObject() && ES_Runtime::GetHostObject(global_object)->IsA(DOM_TYPE_WINDOW)) { OpString url; DOM_Utils::GetOriginURL(DOM_Utils::GetDOM_Runtime(runtime)).GetAttribute(URL::KUniName, url); for (unsigned index = 0; index < static_cast<unsigned>(url.Length()); ++index) if (url.CStr()[index] == '"') url.Insert(index++, "\\"); buffer->AppendFormat(UNI_L("\"%s\""), url.CStr()); } else #endif // _STANDALONE buffer->Append("\"<unidentified runtime>\""); runtime = g_ecmaManager->GetNextRuntimePerHeap(runtime); if (runtime) buffer->Append(", "); } buffer->Append("] }, "); } buffer->AppendFormat(UNI_L("\"count\": %u }, \"allocators\": ["), active->Cardinal() + inactive->Cardinal() + destroy->Cardinal()); for (ES_PageAllocator *allocator = static_cast<ES_PageAllocator *>(g_ecmaPageAllocatorList->First()); allocator; allocator = static_cast<ES_PageAllocator *>(allocator->Suc())) { buffer->AppendFormat(UNI_L("{ \"chunks\": %u, \"chunkSize\": %u, \"pages\": %u, \"pageSize\": %u, \"heaps\": ["), allocator->CountChunks(), allocator->ChunkSize(), allocator->CountPages(), allocator->PageSize()); for (ES_HeapHandle *heaph = allocator->GetFirstHeapHandle(); heaph; heaph = static_cast<ES_HeapHandle *>(heaph->Suc())) { buffer->AppendUnsignedLong(heaph->heap->Id()); if (heaph->Suc()) buffer->Append(", "); } buffer->Append("] }"); if (allocator->Suc()) buffer->Append(", "); } buffer->Append("], \"cachedPrograms\": ["); for (Link *link = RT_DATA.program_cache->GetCachedPrograms()->First(); link; link = link->Suc()) { ES_ProgramCodeStatic *program = static_cast<ES_ProgramCodeStatic *>(link); buffer->AppendFormat(UNI_L("{ \"url\": \"\", \"length\": %u }"), program->source.GetSource()->length); if (link->Suc()) buffer->Append(", "); } buffer->Append("] }"); return_value->SetString(JString::Make(context, buffer->GetStorage(), buffer->Length())); return TRUE; } /* static */ BOOL ES_DebugBuiltins::getObjectDemographics(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { return_value->SetNull(); if (argc == 1) { if (!argv[0].ToNumber(context) || !argv[0].IsUInt32()) return FALSE; if (ES_Heap *heap = g_ecmaManager->GetHeapById(argv[0].GetNumAsUInt32())) { TempBuffer *buffer = g_ecmaManager->GetHeapDebuggerBuffer(); buffer->Clear(); buffer->Append("{ "); unsigned *live_objects = heap->live_objects; for (unsigned index = 0; index < GCTAG_UNINITIALIZED; ++index) { if (index != 0) buffer->Append(", "); buffer->Append("\""); buffer->Append(g_ecmaClassName[index]); buffer->Append("\": "); buffer->AppendUnsignedLong(live_objects[index]); } buffer->Append(" }"); return_value->SetString(JString::Make(context, buffer->GetStorage(), buffer->Length())); } } return TRUE; } #endif // ES_HEAP_DEBUGGER #ifndef ES_HEAP_DEBUGGER /* static */ BOOL do_nothing(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value) { return TRUE; } #endif // ES_HEAP_DEBUGGER /* static */ void ES_DebugBuiltins::PopulateDebug(ES_Context *context, ES_Global_Object *global_object, ES_Object *prototype) { #define MAKE_DEBUG_BUILTIN_WITH_NAME(length, name) ES_Function::Make(context, global_object, length, name, 0, TRUE) ES_Value_Internal undefined; ASSERT_CLASS_SIZE(ES_DebugBuiltins); #ifdef ES_HEAP_DEBUGGER APPEND_PROPERTY(ES_DebugBuiltins, getHeapInformation, MAKE_DEBUG_BUILTIN_WITH_NAME(0, getHeapInformation)); APPEND_PROPERTY(ES_DebugBuiltins, getObjectDemographics, MAKE_DEBUG_BUILTIN_WITH_NAME(1, getObjectDemographics)); #else APPEND_PROPERTY(ES_DebugBuiltins, getHeapInformation, MAKE_DEBUG_BUILTIN_WITH_NAME(0, do_nothing)); APPEND_PROPERTY(ES_DebugBuiltins, getObjectDemographics, MAKE_DEBUG_BUILTIN_WITH_NAME(1, do_nothing)); #endif // ES_HEAP_DEBUGGER ASSERT_OBJECT_COUNT(ES_DebugBuiltins); #undef MAKE_DEBUG_BUILTIN_WITH_NAME } /* static */ void ES_DebugBuiltins::PopulateDebugClass(ES_Context *context, ES_Class_Singleton *prototype_class) { OP_ASSERT(prototype_class->GetPropertyTable()->Capacity() >= ES_DebugBuiltinsCount); ES_Layout_Info layout; #define DECLARE_DEBUG_PROPERTY(class, property, attributes, type) prototype_class->AddL(context, JString::Make(context, #property), ES_Property_Info(attributes | CP), type, FALSE) DECLARE_DEBUG_PROPERTY(ES_DebugBuiltins, getHeapInformation, DE | DD | RO, ES_STORAGE_OBJECT); DECLARE_DEBUG_PROPERTY(ES_DebugBuiltins, getObjectDemographics, DE | DD | RO, ES_STORAGE_OBJECT); #undef DECLARE_DEBUG_PROPERTY } #endif // ES_DEBUG_BUILTINS
#pragma once #include<string> #include"Action.h" #include"MAction.h" #include<string> class Parser { Game* game; public: Parser(Game*); Game* getGame(); Action* parse(std::string str); };
/* * Creature.cpp * * Created on: Jun 27, 2017 * Author: root */ #include "Creature.h" #include "SvrConfig.h" CreatureObj::CreatureObj(eObjType type):Object(type),m_ID(-1) { } CreatureObj::~CreatureObj() { } void CreatureObj::Release() { Object::Release(); m_ID = -1; CreatureState state; m_CreatureState = state; }
class Solution { public: string removeOuterParentheses(string S) { string res; stack<char> st; for (int i=0 ; i<S.length(); i++) { if (S[i]=='(') { if (st.size()>0) res+=S[i]; st.push(S[i]); } else { if (st.size() > 1) res+=S[i]; st.pop(); } } return res; } };
#ifndef AMVK_G_BUFFER_H #define AMVK_G_BUFFER_H #include "macro.h" #include "vulkan.h" #include "buffer_helper.h" #include "image_helper.h" #include "state.h" #include "fullscreen_quad.h" #include "camera.h" #include "timer.h" #include "utils.h" #include <cfloat> #include <array> #include <unordered_set> #include <glm/gtx/string_cast.hpp> struct FramebufferAttachment { VkImage image; VkDeviceMemory memory; VkImageView view; VkFormat format; }; class GBuffer { public: static const constexpr uint32_t INDEX_POSITION = 0; static const constexpr uint32_t INDEX_NORMAL = 1; static const constexpr uint32_t INDEX_ALBEDO = 2; static const constexpr uint32_t INDEX_DEPTH = 3; static const constexpr uint32_t INDEX_TILING_OUT_IMAGE = 0; static const constexpr uint32_t INDEX_TILING_NORMAL_DEPTH = 1; static const constexpr uint32_t INDEX_TILING_POSITION = 2; static const constexpr uint32_t INDEX_TILING_ALBEDO = 3; static const constexpr uint32_t INDEX_TILING_UBO = 4; static const constexpr uint32_t INDEX_TILING_POINT_LIGHTS = 5; static const constexpr uint32_t DEPTH_ATTACHMENT_COUNT = 1; static const constexpr uint32_t ATTACHMENT_COUNT = 4; static const constexpr uint32_t COLOR_ATTACHMENT_COUNT = ATTACHMENT_COUNT - DEPTH_ATTACHMENT_COUNT; static const constexpr uint32_t TILING_IMAGE_COUNT = 4; static const constexpr uint32_t UNIFORM_BUFFER_COUNT = 2; static const constexpr uint32_t STORAGE_BUFFER_COUNT = 1; static const constexpr uint32_t MAX_LIGHTS = 1024; static const constexpr uint32_t WORK_GROUP_SIZE = 16; struct TilingUBO { glm::mat4 view; glm::mat4 proj; glm::vec2 textureDimens; uint32_t lightCount; }; struct PointLight { glm::vec3 position; float radius; glm::vec3 color; float pad; }; inline FramebufferAttachment& position() { return attachments[INDEX_POSITION]; } inline FramebufferAttachment& normal() { return attachments[INDEX_NORMAL]; } inline FramebufferAttachment& albedo() { return attachments[INDEX_ALBEDO]; } inline FramebufferAttachment& depth() { return attachments[INDEX_DEPTH]; } GBuffer(State& state); virtual ~GBuffer(); void init(const VkPhysicalDevice& physicalDevice, const VkDevice& device, uint32_t width, uint32_t height); void createCmdBuffer(const VkDevice& device, const VkCommandPool& cmdPool); void drawDeferredQuad(VkCommandBuffer& cmdBuffer); void dispatch(); void updateTextureDimens(uint32_t width, uint32_t height); void updateTiling(VkCommandBuffer& cmdBuffer, const Timer& timer, Camera& camera); void update(VkCommandBuffer& cmdBuffer, const Timer& timer, Camera& camera); std::array<FramebufferAttachment, ATTACHMENT_COUNT> attachments; std::array<VkClearValue, ATTACHMENT_COUNT> clearValues; int32_t width, height; VkFramebuffer frameBuffer; VkRenderPass renderPass; VkSampler sampler; VkCommandBuffer cmdBuffer; VkCommandBuffer tilingCmdBuffer; VkCommandPool tilingCmdPool; TilingUBO ubo; std::vector<PointLight> pointLights; struct TilingImage { VkImage image; VkDeviceMemory memory; VkImageView view; } tilingImage; private: void createFramebuffers(const VkPhysicalDevice& physicalDevice, const VkDevice& device); void createBuffers(); void createAttachment( const VkPhysicalDevice& physicalDevice, const VkDevice& device, FramebufferAttachment& attachment, VkFormat format, VkImageUsageFlags usage); void createTilingResultImage(); void createTilingCmdPool(); void createSampler(const VkDevice& device); void createDescriptorPool(); void createDescriptors(); void createColorAttachmentDesc(VkAttachmentDescription& desc, VkFormat format); void createDepthAttachmentDesc(VkAttachmentDescription& desc, VkFormat format); void createLights(); VkImageTiling getTiling(VkFormat format, VkImageUsageFlags usage); void initColorImageTransition(CmdPass& cmd, FramebufferAttachment& attachment); State* mState; VkDescriptorPool mDescriptorPool; VkDescriptorSet mDescriptorSet; VkDescriptorSet mTilingDescriptorSet; BufferInfo mUniformBufferInfo; BufferInfo mTilingUniformBufferInfo; BufferInfo mTilingStagingUniformBufferInfo; BufferInfo mPointLightsBufferInfo; public: FullscreenQuad deferredQuad; }; #endif
#pragma once #include "StrID.h" #include <unordered_map> namespace Hourglass { class Entity; class EntityAssembler { public: /** * Get a fully assembled entity, given the name of * the pre-assembled entity type */ static Entity* GetAssembledEntity( StrID name ); /** * Get a fully assembled entity, give the name of * the pre-assembled entity type * @param name - name of the assembled entity * @param pos - position to place the assembled entity * @param rot - rotation to orient the assembled entity */ static Entity* GetAssembledEntity( StrID name, const XMFLOAT3& pos, const XMFLOAT3& rot ); /** * Get a fully assembled entity, give the name of * the pre-assembled entity type * @param name - name of the assembled entity * @param pos - position to place the assembled entity * @param rot - rotation to orient the assembled entity * @param scale - scale the assembled entity by this amount */ static Entity* GetAssembledEntity( StrID name, const XMFLOAT3& pos, const XMFLOAT3& rot, const XMFLOAT3& scale ); static void Shutdown(); protected: void Register( StrID name, Entity* root ); private: static std::unordered_map< StrID, Entity*>* m_AssembledEntities; }; }
#include"sensor.h" void Sensor::int_set(int i) { m_i = i; } int Sensor::int_get() { return m_i; }
#include <fstream> #include <memory> #include <stdexcept> #include <string> #include <SDL2/SDL_opengles2.h> #include "utils/utils.hpp" std::unique_ptr<std::string> get_file_contents(const char *filename) { std::ifstream in(filename, std::ios::in | std::ios::binary); if (in) { std::unique_ptr<std::string> contents (new std::string); std::string& contents_ref = *contents; in.seekg(0, std::ios::end); contents_ref.resize(in.tellg()); in.seekg(0, std::ios::beg); in.read(&contents_ref[0], contents_ref.size()); in.close(); return contents; } throw std::runtime_error("couldn't open file \"" + std::string(filename) + "\""); } std::unique_ptr<std::string> get_gl_error_str(const char *function_name) { std::string error_str; bool done = false; while (!done) { GLenum error_code = glGetError(); switch (error_code) { case GL_NO_ERROR: done = true; break; case GL_INVALID_ENUM: error_str += " invalid enum."; break; case GL_INVALID_VALUE: error_str += " invalid value."; break; case GL_INVALID_OPERATION: error_str += " invalid operation."; break; case GL_INVALID_FRAMEBUFFER_OPERATION: error_str += " invalid framebuffer operation."; break; case GL_OUT_OF_MEMORY: error_str += " out of memory."; break; default: error_str += " unknown error code " + error_code + std::string("."); } } if (!error_str.empty()) { error_str = "error in " + std::string(function_name) + ":" + error_str; } return std::make_unique<std::string>(error_str); }
#include <iostream> #include <vector> #include <algorithm> #include <iterator> #include <sequtils.h> using namespace std; int main(int argc, char *argv[]) { vector<int> v1; populate_rand(v1, 10); print_seq(v1); iter_swap(v1.begin(), ++v1.begin()); print_seq(v1); iter_swap(v1.begin(), --v1.end()); print_seq(v1); return 0; }
#include <stdio.h> #include<stdlib.h> /******************************** * * function init_matrix() * * arg * n inttype the matrix size n*n * *********************************/ int** init_matrix(int n){ int i,j; // temp rows; int **temp=(int**) malloc(n*sizeof(int*)); //temp columns for(i=0;i<n;i++) temp[i]=(int*)malloc(n*sizeof(int)); if(temp!=NULL){ for(i=0;i<n;i++) for(j=0;j<n;j++) temp[i][j]=0; } return temp; } /****************************************** * * function add_matrix() * * args sub_M1,sub_M2 inttype **pointers * n the size of sub_M1 sub_M2 n*n * * return matrix **inttype * * *****************************************/ int** add_matrix(int** sub_ma1, int** sub_ma2, int n) { int** temp = init_matrix(n); for(int i=0; i<n; i++) for(int j=0; j<n; j++) temp[i][j] = sub_ma1[i][j] + sub_ma2[i][j]; return temp; } /****************************************** * * function subtract_matrix() * * args sub_M1,sub_M2 inttype **pointers * n the size of sub_M1 sub_M2 n*n * * return matrix **inttype * * *****************************************/ int** subtract_matrix(int** sub_ma1, int** sub_ma2, int n) { int** temp = init_matrix(n); for(int i=0; i<n; i++) for(int j=0; j<n; j++) temp[i][j] = sub_ma1[i][j] - sub_ma2[i][j]; return temp; } /********************************************** * * function square_matrix_mutiply_recursive() * * args * A,B, inttype ** pointer * n inttype matrix size n*n * * return C inttype array * ************************************************/ int** square_matrix_strassen_mutiply(int **A,int **B,int n){ int i,j; //only one element if (n == 1) { int** C = init_matrix(1); C[0][0] = A[0][0] * B[0][0]; return C; } else{ //init C,A,B int** C = init_matrix(n); int k = n/2; int** A11 = init_matrix(k); int** A12 = init_matrix(k); int** A21 = init_matrix(k); int** A22 = init_matrix(k); int** B11 = init_matrix(k); int** B12 = init_matrix(k); int** B21 = init_matrix(k); int** B22 = init_matrix(k); //resolve A,B matrixs to A11...A22,B11...B22 for(i=0; i<k; i++) for(j=0; j<k; j++) { A11[i][j] = A[i][j]; A12[i][j] = A[i][k+j]; A21[i][j] = A[k+i][j]; A22[i][j] = A[k+i][k+j]; B11[i][j] = B[i][j]; B12[i][j] = B[i][k+j]; B21[i][j] = B[k+i][j]; B22[i][j] = B[k+i][k+j]; } //calculate P[1-7] int** P1 = square_matrix_strassen_mutiply(A11, subtract_matrix(B12, B22, k), k); int** P2 = square_matrix_strassen_mutiply(add_matrix(A11, A12, k), B22, k); int** P3 = square_matrix_strassen_mutiply(add_matrix(A21, A22, k), B11, k); int** P4 = square_matrix_strassen_mutiply(A22, subtract_matrix(B21, B11, k), k); int** P5 = square_matrix_strassen_mutiply(add_matrix(A11, A22, k), add_matrix(B11, B22, k), k); int** P6 = square_matrix_strassen_mutiply(subtract_matrix(A12, A22, k), add_matrix(B21, B22, k), k); int** P7 = square_matrix_strassen_mutiply(subtract_matrix(A11, A21, k), add_matrix(B11, B12, k), k); //calculate C11.....C22 int** C11 = subtract_matrix(add_matrix(add_matrix(P5, P4, k), P6, k), P2, k); int** C12 = add_matrix(P1, P2, k); int** C21 = add_matrix(P3, P4, k); int** C22 = subtract_matrix(subtract_matrix(add_matrix(P5, P1, k), P3, k), P7, k); //copy C11,C12,C13,C14 to C for(i=0; i<k; i++) for(j=0; j<k; j++) { C[i][j] = C11[i][j]; C[i][j+k] = C12[i][j]; C[k+i][j] = C21[i][j]; C[k+i][k+j] = C22[i][j]; } //free memory for(i=0;i<k;i++){ // free subarrays of A,B free(A11[i]); free(A12[i]); free(A21[i]); free(A22[i]); free(B11[i]); free(B12[i]); free(B21[i]); free(B22[i]); //free subarray of P free(P1[i]); free(P2[i]); free(P3[i]); free(P4[i]); free(P5[i]); free(P6[i]); free(P7[i]); //free subarray of C free(C11[i]); free(C12[i]); free(C21[i]); free(C22[i]); } //free rows of A,B free(A11); free(A12); free(A21); free(A22); free(B11); free(B12); free(B21); free(B22); //free rows of P free(P1); free(P2); free(P3); free(P4); free(P5); free(P6); free(P7); //free rows of C free(C11); free(C12); free(C21); free(C22); //make NULL A11=NULL; A12=NULL; A21=NULL; A22=NULL; B11=NULL; B12=NULL; B21=NULL; B22=NULL; P1=NULL; P2=NULL; P3=NULL; P4=NULL; P5=NULL; P6=NULL; P7=NULL; C11=NULL; C12=NULL; C21=NULL; C22=NULL; return C; } } int main() { int n=2; int i,j; // init A,B int**A=init_matrix(2); int**B=init_matrix(2); A[0][0]=1; A[0][1]=3; A[1][0]=7; A[1][1]=5; B[0][0]=6; B[0][1]=8; B[1][0]=4; B[1][1]=2; //use square_matrix_strassen_mutiply() int **C=square_matrix_strassen_mutiply(A,B,n); //output C printf("the result of C is:\n"); for(i=0;i<n;i++){ for(j=0;j<n;j++) printf("%d ",*(*(C+i)+j)); printf("\n"); //next line } return 0; } /**************************************** * * input A={{1,3},{7,5}} B={{6,8},{4,2}} * * output C={{18,14},{62,66}}; * * **************************************/
#include <iostream> #include "custom_date.h" #ifndef __CUSTOM_PERSON_H__ #define __CUSTOM_PERSON_H__ using namespace std; string occupation_list[] = { "Unemployed", "Engineer", "Doctor", "Teacher", }; class Person { public: string get_name() const; // string get_occupation() const; void get_birthdate(Date&) const; // void set_name(string n); // void set_occupation(int oid); // void set_birthdate(Date&); Person(const string p_name = "Bully", int dd = 1, int mm = 1, int yy = 1960, int oid = 0); ~Person(); private: string name; Date birth_date; string occupation; }; /* * Class Objects as members example * See how we call constructor for member objects */ Person::Person(const string p_name, int d, int m, int y, int occ_id) : birth_date(d,m,y) { cout << "Default constructor called" << endl; name = p_name; occupation = occupation_list[occ_id]; } Person::~Person() { cout << "Destructor called" << endl; } string Person::get_name() const { return (name); } void Person::get_birthdate(Date& date) const { date = birth_date; return; } #endif /* End of header guard */
/* $Id: QKDDisplay.cpp 631 2012-07-02 17:34:33Z lwy $ $URL: http://172.17.8.1/svn/QUESS/tags/QKDBench-2.2.1/QKDDisplay.cpp $ */ #include "stdafx.h" #include <afx.h> #include <math.h> #include "QKDDisplay.h" #include "QKDTimer.h" double QKDDisplay::LuaProcess(lua_State *pLua, unsigned char *pBuf, int startByte, int byteLength, int dispIndex, char *msg) { msg[0] = 0; if(!pLua){ return 0; } char fname[200]; sprintf(fname,"Calc%02d\0",dispIndex); lua_getglobal(pLua,fname); lua_pushlstring(pLua,(char *)pBuf+startByte, byteLength); lua_pcall(pLua,1,2,0); LUA_NUMBER f; f = lua_tonumber(pLua,-2); const char *pMsg; pMsg = lua_tostring(pLua,-1); if(pMsg){ memcpy(msg, pMsg,strlen(pMsg) + 1); } lua_pop(pLua,2); return f; } QKDDisplay::QKDDisplay() { m_pListMessage = NULL; m_pListMonitor = NULL; m_pXmlMonitor = NULL; m_pXmlMessage = NULL; m_Lua = luaL_newstate(); if(luaL_loadfile(m_Lua,"display.lua")){ lua_close(m_Lua); m_Lua = NULL; } if(lua_pcall(m_Lua,0,0,0)){ lua_close(m_Lua); m_Lua = NULL; } if(m_Lua){ luaL_openlibs(m_Lua); } } QKDDisplay::~QKDDisplay() { Close(); if(m_Lua){ lua_close(m_Lua); } } void QKDDisplay::Open(char *fileMonitor, char *fileMessage, CListCtrl *pListMonitor, CListCtrl *pListMessage) { HWND hWnd; hWnd = pListMonitor->GetSafeHwnd(); if(IsWindow(hWnd)){ m_pXmlMonitor = new CXML; m_pXmlMonitor->Open(fileMonitor); m_pListMonitor = pListMonitor; FillMonitorHead(); } else{ m_pListMonitor = NULL; } hWnd = pListMessage->GetSafeHwnd(); if(IsWindow(hWnd)){ m_pXmlMessage = new CXML; m_pXmlMessage->Open(fileMessage); m_pListMessage = pListMessage; FillMessageHead(); } else{ m_pListMessage = NULL; } } void QKDDisplay::Close() { if(m_pXmlMonitor){ delete m_pXmlMonitor; } if(m_pXmlMessage){ delete m_pXmlMessage; } } void QKDDisplay::FillMonitorHead() { if(!m_pListMonitor){ return; } LONG lStyle; lStyle = GetWindowLong(m_pListMonitor->m_hWnd, GWL_STYLE); lStyle &= ~LVS_TYPEMASK; lStyle |= LVS_REPORT; SetWindowLong(m_pListMonitor->m_hWnd, GWL_STYLE, lStyle); DWORD dwStyle = dwStyle = m_pListMonitor->GetExtendedStyle(); //获取当前扩展样式 dwStyle |= LVS_EX_FULLROWSELECT; //选中某行使整行高亮(report风格时) dwStyle |= LVS_EX_GRIDLINES; //网格线(report风格时) // dwStyle |= LVS_EX_CHECKBOXES; //item前生成checkbox控件 m_pListMonitor->SetExtendedStyle(dwStyle); //设置扩展风格 m_pListMonitor->SetExtendedStyle(dwStyle); LV_COLUMN lvc[5]; int i; for (i = 0; i < 5; i++) { lvc[i].mask = LVCF_TEXT | LVCF_SUBITEM | LVCF_WIDTH; } lvc[0].iSubItem = 0; lvc[0].pszText = "序号"; lvc[0].cx = 80; lvc[1].iSubItem = 0; lvc[1].pszText = "参数名称"; lvc[1].cx = 200; lvc[2].iSubItem = 0; lvc[2].pszText = "功能描述"; lvc[2].cx = 200; lvc[3].iSubItem = 0; lvc[3].pszText = "参数值"; lvc[3].cx = 200; lvc[4].iSubItem = 0; lvc[4].pszText = ""; lvc[4].cx = 300; for (i = 0; i < 5; i++) { m_pListMonitor->InsertColumn(i, &lvc[i]); } } void QKDDisplay::FillMessageHead() { if(!m_pListMessage){ return; } CListCtrl* pListCtrl = m_pListMessage; int item = 0; int rowIndex; xmlXPathObjectPtr xpathObj; xmlNodePtr pNode,pChild; xmlChar *xmlRtn; int i; int blockByte,startByte; CString idsName, strByteLength, strByteOffset, strBitOffset; LONG lStyle; lStyle = GetWindowLong(pListCtrl->m_hWnd, GWL_STYLE); lStyle &= ~LVS_TYPEMASK; lStyle |= LVS_REPORT; SetWindowLong(pListCtrl->m_hWnd, GWL_STYLE, lStyle); DWORD dwStyle = pListCtrl->GetExtendedStyle(); dwStyle |= LVS_EX_FULLROWSELECT; dwStyle |= LVS_EX_GRIDLINES; pListCtrl->SetExtendedStyle(dwStyle); LV_COLUMN lvc[5]; for (i = 0; i < 5; i++) { lvc[i].mask = LVCF_TEXT | LVCF_SUBITEM | LVCF_WIDTH; } lvc[0].iSubItem = 0; lvc[0].pszText = "字节"; lvc[0].cx = 40; lvc[1].iSubItem = 0; lvc[1].pszText = "参数名称"; lvc[1].cx = 200; lvc[2].iSubItem = 0; lvc[2].pszText = "长度"; lvc[2].cx = 40; lvc[3].iSubItem = 0; lvc[3].pszText = "参数值"; lvc[3].cx = 170; lvc[4].iSubItem = 0; lvc[4].pszText = "参数解析"; lvc[4].cx = 300; pListCtrl->DeleteAllItems(); for (i = 0; i < 5; i++) { pListCtrl->InsertColumn(i, &lvc[i]); } xpathObj = m_pXmlMessage->GetNodesByXPath(BAD_CAST("//MessageBlock[@startByte]")); if(xpathObj){ for(i = 0; i < xpathObj->nodesetval->nodeNr; i++){ pNode = xpathObj->nodesetval->nodeTab[i]; xmlRtn = xmlGetProp(pNode,BAD_CAST("startByte")); blockByte = atoi((char *)xmlRtn); xmlFree(xmlRtn); pNode = pNode->xmlChildrenNode; while(pNode != NULL){ if(!xmlStrcmp(pNode->name,BAD_CAST("Message"))){ xmlRtn = CXML::xmlGetPropGBK(pNode,BAD_CAST("name")); idsName.Format("%s",xmlRtn); xmlFree(xmlRtn); xmlRtn = xmlGetProp(pNode,BAD_CAST("byteLength")); strByteLength.Format("%s",xmlRtn); xmlFree(xmlRtn); xmlRtn = xmlGetProp(pNode,BAD_CAST("startByte")); startByte = atoi((char *)xmlRtn); xmlFree(xmlRtn); xmlRtn = CXML::xmlGetPropGBK(pNode,BAD_CAST("name")); idsName.Format("%s",xmlRtn); xmlFree(xmlRtn); rowIndex = pListCtrl->InsertItem(item, ""); strByteOffset.Format("%d", blockByte+startByte); pListCtrl->SetItemText(rowIndex, 0, strByteOffset); pListCtrl->SetItemText(rowIndex, 1, idsName); pListCtrl->SetItemText(rowIndex, 2, strByteLength); item++; xmlRtn = xmlGetProp(pNode,BAD_CAST("parseType")); if(!xmlStrcmp(xmlRtn,BAD_CAST("bits"))){ xmlFree(xmlRtn); pChild = pNode->xmlChildrenNode; while(pChild != NULL){ if(!xmlStrcmp(pChild->name,BAD_CAST("Bits"))){ xmlRtn = CXML::xmlGetPropGBK(pChild,BAD_CAST("name")); idsName.Format("%s",xmlRtn); xmlFree(xmlRtn); xmlRtn = xmlGetProp(pChild,BAD_CAST("startBit")); strBitOffset = strByteOffset; strBitOffset += "."; strBitOffset += (CString)xmlRtn; xmlFree(xmlRtn); rowIndex = pListCtrl->InsertItem(item, ""); pListCtrl->SetItemText(rowIndex, 0, strBitOffset); pListCtrl->SetItemText(rowIndex, 1, "--"+idsName); item++; } pChild = pChild->next; } } else{ xmlFree(xmlRtn); } } pNode=pNode->next; } } xmlXPathFreeObject(xpathObj); } } void QKDDisplay::FormDisplayString(unsigned char *pBuf, int startByte, int byteLength, int dispIndex,CString &strDisplay) { char msg[200]; LuaProcess(m_Lua,pBuf,startByte,byteLength,dispIndex,msg); strDisplay = msg; return; } void QKDDisplay::DisplayMessage(unsigned char *pBuf) { if(!m_pListMessage){ return; } CListCtrl* pListCtrl = m_pListMessage; int rowIndex = 0; xmlXPathObjectPtr xpathObj; xmlNodePtr pNode,pChild,pBitValue; xmlChar *xmlRtn; int i,j; int blockByte,startByte,byteLength,dispIndex,startBit,bitLength,bitValue; CString strData,strRst; CString temp; char *endptr; xpathObj = m_pXmlMessage->GetNodesByXPath(BAD_CAST("//MessageBlock[@startByte]")); if(xpathObj){ for(i = 0; i < xpathObj->nodesetval->nodeNr; i++){ pNode = xpathObj->nodesetval->nodeTab[i]; xmlRtn = xmlGetProp(pNode,BAD_CAST("startByte")); blockByte = atoi((char *)xmlRtn); xmlFree(xmlRtn); pNode = pNode->xmlChildrenNode; while(pNode != NULL){ if(!xmlStrcmp(pNode->name,BAD_CAST("Message"))){ xmlRtn = xmlGetProp(pNode,BAD_CAST("byteLength")); byteLength = atoi((char *)xmlRtn); xmlFree(xmlRtn); xmlRtn = xmlGetProp(pNode,BAD_CAST("startByte")); startByte = atoi((char *)xmlRtn); xmlFree(xmlRtn); xmlRtn = xmlGetProp(pNode,BAD_CAST("dispIndex")); dispIndex = atoi((char *)xmlRtn); xmlFree(xmlRtn); strData.Format(""); for(j = 0; j < byteLength; j++){ temp.Format("%02X",pBuf[j+blockByte+startByte]); strData += temp; } pListCtrl->SetItemText(rowIndex, 3, strData); FormDisplayString(pBuf,startByte+blockByte,byteLength,dispIndex,strRst); pListCtrl->SetItemText(rowIndex, 4, strRst); rowIndex++; xmlRtn = xmlGetProp(pNode,BAD_CAST("parseType")); if(!xmlStrcmp(xmlRtn,BAD_CAST("bits"))){ xmlFree(xmlRtn); pChild = pNode->xmlChildrenNode; while(pChild != NULL){ if(!xmlStrcmp(pChild->name,BAD_CAST("Bits"))){ xmlRtn = xmlGetProp(pChild,BAD_CAST("startBit")); startBit = atoi((char *)xmlRtn); xmlFree(xmlRtn); xmlRtn = xmlGetProp(pChild,BAD_CAST("bitLength")); bitLength = atoi((char *)xmlRtn); xmlFree(xmlRtn); strData.Format(""); for(j = bitLength - 1; j >=0 ; j--){ temp.Format("%d",(pBuf[startByte+blockByte] & (1 << (startBit+j))) >> (startBit+j)); strData += temp; } pListCtrl->SetItemText(rowIndex, 3, strData); bitValue = strtol((LPCSTR)strData,&endptr,2); strRst = "非法值"; pBitValue = pChild->xmlChildrenNode; while(pBitValue != NULL){ if(!xmlStrcmp(pBitValue->name,BAD_CAST("BitsValue"))){ xmlRtn = xmlGetProp(pBitValue,BAD_CAST("value")); if(atoi((char *)xmlRtn) == bitValue){ xmlFree(xmlRtn); xmlRtn = CXML::xmlGetPropGBK(pBitValue,BAD_CAST("name")); strRst = xmlRtn; xmlFree(xmlRtn); break; } xmlFree(xmlRtn); } pBitValue = pBitValue->next; } pListCtrl->SetItemText(rowIndex, 4, strRst); rowIndex++; } pChild = pChild->next; } } else{ xmlFree(xmlRtn); } } pNode=pNode->next; } } xmlXPathFreeObject(xpathObj); } } void QKDDisplay::DisplayMonitor(unsigned char *pBuf) { if(!m_pListMonitor){ return; } CListCtrl* pListCtrl = m_pListMonitor; int idx = 0; xmlXPathObjectPtr xpathObj; xmlNodePtr pNode,pChild,pBitValue; xmlChar *xmlRtn; int i,j; int startByte,byteLength,dispIndex,startBit,bitLength,bitValue; CString strName,strValue; xpathObj = m_pXmlMonitor->GetNodesByXPath(BAD_CAST("//Message[@startByte]")); if(xpathObj){ for(i = 0; i < xpathObj->nodesetval->nodeNr; i++){ pNode = xpathObj->nodesetval->nodeTab[i]; xmlRtn = xmlGetProp(pNode,BAD_CAST("startByte")); startByte = atoi((char *)xmlRtn); xmlFree(xmlRtn); xmlRtn = xmlGetProp(pNode,BAD_CAST("byteLength")); byteLength = atoi((char *)xmlRtn); xmlFree(xmlRtn); xmlRtn = xmlGetProp(pNode,BAD_CAST("dispIndex")); dispIndex = atoi((char *)xmlRtn); xmlFree(xmlRtn); xmlRtn = xmlGetProp(pNode,BAD_CAST("parseType")); if(!xmlStrcmp(xmlRtn,BAD_CAST("bits"))){ xmlFree(xmlRtn); pChild = pNode->xmlChildrenNode; while(pChild != NULL){ if(!xmlStrcmp(pChild->name,BAD_CAST("Bits"))){ xmlRtn = xmlGetProp(pChild,BAD_CAST("startBit")); startBit = atoi((char *)xmlRtn); xmlFree(xmlRtn); xmlRtn = xmlGetProp(pChild,BAD_CAST("bitLength")); bitLength = atoi((char *)xmlRtn); xmlFree(xmlRtn); bitValue = 0; for(j = bitLength - 1; j >=0 ; j--){ bitValue <<= 1; bitValue += (pBuf[startByte] & (1 << (startBit+j))) >> (startBit+j); } xmlRtn = CXML::xmlGetPropGBK(pChild,BAD_CAST("name")); strValue.Format("%s%s",xmlRtn,"数据无效"); xmlFree(xmlRtn); pBitValue = pChild->xmlChildrenNode; while(pBitValue != NULL){ if(!xmlStrcmp(pBitValue->name,BAD_CAST("BitsValue"))){ xmlRtn = xmlGetProp(pBitValue,BAD_CAST("value")); if(atoi((char *)xmlRtn) == bitValue){ xmlFree(xmlRtn); xmlRtn = CXML::xmlGetPropGBK(pBitValue,BAD_CAST("name")); strValue = xmlRtn; xmlFree(xmlRtn); break; } xmlFree(xmlRtn); } pBitValue = pBitValue->next; } pListCtrl->SetItemText(idx/5, idx % 5, strValue); idx ++; } pChild = pChild->next; } } else{ xmlFree(xmlRtn); xmlRtn = CXML::xmlGetPropGBK(pNode,BAD_CAST("name")); strName = xmlRtn; xmlFree(xmlRtn); FormDisplayString(pBuf,startByte,byteLength,dispIndex,strValue); pListCtrl->SetItemText(idx/5, idx % 5, strName+":"+strValue); idx ++; } } xmlXPathFreeObject(xpathObj); } return; }
class ItemWaterBottle : FoodDrink { scope = 2; model = "\dayz_equip\models\waterbottle_gear.p3d"; picture = "\z\addons\dayz_epoch\pictures\equip_waterbottle10oz_ca.paa"; displayName = $STR_EQUIP_NAME_12; descriptionShort = $STR_EQUIP_DESC_12; Nutrition[] = {0,0,1000,0}; infectionChance = 0.3; consumeOutput = "ItemWaterBottleUnfilled"; containerEmpty = "ItemWaterBottleUnfilled"; class ItemActions : ItemActions { class Consume : Consume {}; class Empty { text = $STR_EQUIP_NAME_13_EMPTY; script = "spawn player_emptyContainer"; }; }; wateroz = 10; //Custom Epoch value }; class ItemWaterBottleInfected : ItemWaterBottle { infectionChance = 1; }; class ItemWaterBottleSafe : ItemWaterBottle { infectionChance = 0; }; class ItemWaterBottleBoiled : ItemWaterBottle { displayName = $STR_ITEMWATERBOTTLEBOILED_CODE_NAME; descriptionShort = $STR_ITEMWATERBOTTLEBOILED_CODE_DESC; infectionChance = 0; class ItemActions { class Consume { text = $STR_ACTIONS_DRINK2; script = "spawn player_consume"; }; class Crafting { text = $STR_CRAFTING_HERBALDRINK; script = ";['Crafting','CfgMagazines', _id] spawn player_craftItem;"; neednearby[] = {}; requiretools[] = {}; output[] = {{"ItemWaterBottleHerbal",1}}; input[] = {{"equip_herb_box",1},{"ItemWaterBottleBoiled",1}}; }; class Empty { text = $STR_EQUIP_NAME_13_EMPTY; script = "spawn player_emptyContainer"; }; }; }; class ItemWaterBottleHerbal : ItemWaterBottle { displayName = $STR_ITEM_NAME_HerbalDrink; descriptionShort = $STR_ITEM_DESC_HerbalDrink; infectionChance = -0.5; }; class ItemWaterBottleUnfilled : CA_Magazine { scope = 2; count = 1; type = 256; model = "\dayz_equip\models\waterbottle_gear.p3d"; picture = "\dayz_equip\textures\equip_waterbottle_empty_ca.paa"; displayName = $STR_EQUIP_NAME_13; descriptionShort = $STR_EQUIP_DESC_13; containerWater = "ItemWaterBottle"; containerWaterSafe = "ItemWaterBottleSafe"; containerWaterInfected = "ItemWaterBottleInfected"; class ItemActions { class Fill { text = $STR_ACTIONS_FILL_W; script = "spawn player_fillWater;"; }; }; }; class ItemWaterBottleDmg : CA_Magazine //We don't have a damaged canteen image/model , so the regular bottle image is used for now { scope = 2; count = 1; type = 256; model = "\dayz_equip\models\waterbottle_gear.p3d"; picture = "\dayz_equip\textures\equip_waterbottle_empty_ca.paa"; displayName = $STR_ITEMWATERBOTTLEDMG_CODE_NAME; descriptionShort = $STR_ITEMWATERBOTTLEDMG_CODE_DESC; sfx = "bandage"; class ItemActions { class Crafting { text = $STR_ACTIONS_FIX_W; script = ";['Crafting','CfgMagazines', _id] spawn player_craftItem;"; neednearby[] = {}; requiretools[] = {}; output[] = {{"ItemWaterbottleUnfilled",1}}; input[] = {{"ItemWaterBottleDmg",1},{"equip_duct_tape",1}}; }; }; }; class ItemWaterbottle1oz : ItemWaterbottle { displayName = $STR_EPOCH_WATERBOTTLE1OZ; descriptionShort = $STR_EPOCH_WATERBOTTLE1OZ_DESC; picture = "\z\addons\dayz_epoch\pictures\equip_waterbottle_1oz_ca.paa"; wateroz = 1; containerWater = "ItemWaterBottle"; containerWaterSafe = "ItemWaterBottleSafe"; containerWaterInfected = "ItemWaterBottleInfected"; Nutrition[] = {0,0,100,0}; infectionChance = 0.03; consumeOutput = "ItemWaterBottleUnfilled"; containerEmpty = "ItemWaterBottleUnfilled"; class ItemActions { class Consume { text = $STR_ACTIONS_DRINK2; script = "spawn player_consume"; }; class Empty { text = $STR_EQUIP_NAME_13_EMPTY; script = "spawn player_emptyContainer"; }; class Fill { text = "$STR_ACTIONS_FILL_W"; script = "spawn player_fillWater;"; }; }; }; class ItemWaterbottle2oz : ItemWaterbottle { displayName = $STR_EPOCH_WATERBOTTLE2OZ; descriptionShort = $STR_EPOCH_WATERBOTTLE2OZ_DESC; picture = "\z\addons\dayz_epoch\pictures\equip_waterbottle_2oz_ca.paa"; wateroz = 2; containerWater = "ItemWaterBottle"; containerWaterSafe = "ItemWaterBottleSafe"; containerWaterInfected = "ItemWaterBottleInfected"; Nutrition[] = {0,0,200,0}; infectionChance = 0.06; consumeOutput = "ItemWaterBottleUnfilled"; containerEmpty = "ItemWaterBottleUnfilled"; class ItemActions { class Consume { text = $STR_ACTIONS_DRINK2; script = "spawn player_consume"; }; class Empty { text = $STR_EQUIP_NAME_13_EMPTY; script = "spawn player_emptyContainer"; }; class Fill { text = "$STR_ACTIONS_FILL_W"; script = "spawn player_fillWater;"; }; }; }; class ItemWaterbottle3oz : ItemWaterbottle { displayName = $STR_EPOCH_WATERBOTTLE3OZ; descriptionShort = $STR_EPOCH_WATERBOTTLE3OZ_DESC; picture = "\z\addons\dayz_epoch\pictures\equip_waterbottle_3oz_ca.paa"; wateroz = 3; containerWater = "ItemWaterBottle"; containerWaterSafe = "ItemWaterBottleSafe"; containerWaterInfected = "ItemWaterBottleInfected"; Nutrition[] = {0,0,300,0}; infectionChance = 0.09; consumeOutput = "ItemWaterBottleUnfilled"; containerEmpty = "ItemWaterBottleUnfilled"; class ItemActions { class Consume { text = $STR_ACTIONS_DRINK2; script = "spawn player_consume"; }; class Empty { text = $STR_EQUIP_NAME_13_EMPTY; script = "spawn player_emptyContainer"; }; class Fill { text = "$STR_ACTIONS_FILL_W"; script = "spawn player_fillWater;"; }; }; }; class ItemWaterbottle4oz : ItemWaterbottle { displayName = $STR_EPOCH_WATERBOTTLE4OZ; descriptionShort = $STR_EPOCH_WATERBOTTLE4OZ_DESC; picture = "\z\addons\dayz_epoch\pictures\equip_waterbottle_4oz_ca.paa"; wateroz = 4; containerWater = "ItemWaterBottle"; containerWaterSafe = "ItemWaterBottleSafe"; containerWaterInfected = "ItemWaterBottleInfected"; Nutrition[] = {0,0,400,0}; infectionChance = 0.12; consumeOutput = "ItemWaterBottleUnfilled"; containerEmpty = "ItemWaterBottleUnfilled"; class ItemActions { class Consume { text = $STR_ACTIONS_DRINK2; script = "spawn player_consume"; }; class Empty { text = $STR_EQUIP_NAME_13_EMPTY; script = "spawn player_emptyContainer"; }; class Fill { text = "$STR_ACTIONS_FILL_W"; script = "spawn player_fillWater;"; }; }; }; class ItemWaterbottle5oz : ItemWaterbottle { displayName = $STR_EPOCH_WATERBOTTLE5OZ; descriptionShort = $STR_EPOCH_WATERBOTTLE5OZ_DESC; picture = "\z\addons\dayz_epoch\pictures\equip_waterbottle_5oz_ca.paa"; wateroz = 5; containerWater = "ItemWaterBottle"; containerWaterSafe = "ItemWaterBottleSafe"; containerWaterInfected = "ItemWaterBottleInfected"; Nutrition[] = {0,0,500,0}; infectionChance = 0.15; consumeOutput = "ItemWaterBottleUnfilled"; containerEmpty = "ItemWaterBottleUnfilled"; class ItemActions { class Consume { text = $STR_ACTIONS_DRINK2; script = "spawn player_consume"; }; class Empty { text = $STR_EQUIP_NAME_13_EMPTY; script = "spawn player_emptyContainer"; }; class Fill { text = "$STR_ACTIONS_FILL_W"; script = "spawn player_fillWater;"; }; }; }; class ItemWaterbottle6oz : ItemWaterbottle { displayName = $STR_EPOCH_WATERBOTTLE6OZ; descriptionShort = $STR_EPOCH_WATERBOTTLE6OZ_DESC; picture = "\z\addons\dayz_epoch\pictures\equip_waterbottle_6oz_ca.paa"; wateroz = 6; containerWater = "ItemWaterBottle"; containerWaterSafe = "ItemWaterBottleSafe"; containerWaterInfected = "ItemWaterBottleInfected"; Nutrition[] = {0,0,600,0}; infectionChance = 0.18; consumeOutput = "ItemWaterBottleUnfilled"; containerEmpty = "ItemWaterBottleUnfilled"; class ItemActions { class Consume { text = $STR_ACTIONS_DRINK2; script = "spawn player_consume"; }; class Empty { text = $STR_EQUIP_NAME_13_EMPTY; script = "spawn player_emptyContainer"; }; class Fill { text = "$STR_ACTIONS_FILL_W"; script = "spawn player_fillWater;"; }; }; }; class ItemWaterbottle7oz : ItemWaterbottle { displayName = $STR_EPOCH_WATERBOTTLE7OZ; descriptionShort = $STR_EPOCH_WATERBOTTLE7OZ_DESC; picture = "\z\addons\dayz_epoch\pictures\equip_waterbottle_7oz_ca.paa"; wateroz = 7; containerWater = "ItemWaterBottle"; containerWaterSafe = "ItemWaterBottleSafe"; containerWaterInfected = "ItemWaterBottleInfected"; Nutrition[] = {0,0,700,0}; infectionChance = 0.21; consumeOutput = "ItemWaterBottleUnfilled"; containerEmpty = "ItemWaterBottleUnfilled"; class ItemActions { class Consume { text = $STR_ACTIONS_DRINK2; script = "spawn player_consume"; }; class Empty { text = $STR_EQUIP_NAME_13_EMPTY; script = "spawn player_emptyContainer"; }; class Fill { text = "$STR_ACTIONS_FILL_W"; script = "spawn player_fillWater;"; }; }; }; class ItemWaterbottle8oz : ItemWaterbottle { displayName = $STR_EPOCH_WATERBOTTLE8OZ; descriptionShort = $STR_EPOCH_WATERBOTTLE8OZ_DESC; picture = "\z\addons\dayz_epoch\pictures\equip_waterbottle_8oz_ca.paa"; wateroz = 8; containerWater = "ItemWaterBottle"; containerWaterSafe = "ItemWaterBottleSafe"; containerWaterInfected = "ItemWaterBottleInfected"; Nutrition[] = {0,0,800,0}; infectionChance = 0.24; consumeOutput = "ItemWaterBottleUnfilled"; containerEmpty = "ItemWaterBottleUnfilled"; class ItemActions { class Consume { text = $STR_ACTIONS_DRINK2; script = "spawn player_consume"; }; class Empty { text = $STR_EQUIP_NAME_13_EMPTY; script = "spawn player_emptyContainer"; }; class Fill { text = "$STR_ACTIONS_FILL_W"; script = "spawn player_fillWater;"; }; }; }; class ItemWaterbottle9oz : ItemWaterbottle { displayName = $STR_EPOCH_WATERBOTTLE9OZ; descriptionShort = $STR_EPOCH_WATERBOTTLE9OZ_DESC; picture = "\z\addons\dayz_epoch\pictures\equip_waterbottle_9oz_ca.paa"; wateroz = 9; containerWater = "ItemWaterBottle"; containerWaterSafe = "ItemWaterBottleSafe"; containerWaterInfected = "ItemWaterBottleInfected"; Nutrition[] = {0,0,900,0}; infectionChance = 0.27; consumeOutput = "ItemWaterBottleUnfilled"; containerEmpty = "ItemWaterBottleUnfilled"; class ItemActions { class Consume { text = $STR_ACTIONS_DRINK2; script = "spawn player_consume"; }; class Empty { text = $STR_EQUIP_NAME_13_EMPTY; script = "spawn player_emptyContainer"; }; class Fill { text = "$STR_ACTIONS_FILL_W"; script = "spawn player_fillWater;"; }; }; }; //inherit from ItemWaterbottle because that's how the crafting script checks required input class ItemWaterbottle1ozBoiled : ItemWaterbottle { displayName = $STR_EPOCH_WATERBOTTLE1OZBOILED; descriptionShort = $STR_EPOCH_WATERBOTTLE1OZBOILED_DESC; infectionChance = 0; picture = "\z\addons\dayz_epoch\pictures\equip_waterbottle_1oz_ca.paa"; wateroz = 1; containerWater = "ItemWaterBottle"; containerWaterSafe = "ItemWaterBottleSafe"; containerWaterInfected = "ItemWaterBottleInfected"; Nutrition[] = {0,0,100,0}; consumeOutput = "ItemWaterBottleUnfilled"; containerEmpty = "ItemWaterBottleUnfilled"; class ItemActions { class Consume { text = $STR_ACTIONS_DRINK2; script = "spawn player_consume"; }; class Empty { text = $STR_EQUIP_NAME_13_EMPTY; script = "spawn player_emptyContainer"; }; class Fill { text = "$STR_ACTIONS_FILL_W"; script = "spawn player_fillWater;"; }; }; }; class ItemWaterbottle2ozBoiled : ItemWaterbottle { displayName = $STR_EPOCH_WATERBOTTLE2OZBOILED; descriptionShort = $STR_EPOCH_WATERBOTTLE2OZBOILED_DESC; infectionChance = 0; picture = "\z\addons\dayz_epoch\pictures\equip_waterbottle_2oz_ca.paa"; wateroz = 2; containerWater = "ItemWaterBottle"; containerWaterSafe = "ItemWaterBottleSafe"; containerWaterInfected = "ItemWaterBottleInfected"; Nutrition[] = {0,0,200,0}; consumeOutput = "ItemWaterBottleUnfilled"; containerEmpty = "ItemWaterBottleUnfilled"; class ItemActions { class Consume { text = $STR_ACTIONS_DRINK2; script = "spawn player_consume"; }; class Empty { text = $STR_EQUIP_NAME_13_EMPTY; script = "spawn player_emptyContainer"; }; class Fill { text = "$STR_ACTIONS_FILL_W"; script = "spawn player_fillWater;"; }; }; }; class ItemWaterbottle3ozBoiled : ItemWaterbottle { displayName = $STR_EPOCH_WATERBOTTLE3OZBOILED; descriptionShort = $STR_EPOCH_WATERBOTTLE3OZBOILED_DESC; infectionChance = 0; picture = "\z\addons\dayz_epoch\pictures\equip_waterbottle_3oz_ca.paa"; wateroz = 3; containerWater = "ItemWaterBottle"; containerWaterSafe = "ItemWaterBottleSafe"; containerWaterInfected = "ItemWaterBottleInfected"; Nutrition[] = {0,0,300,0}; consumeOutput = "ItemWaterBottleUnfilled"; containerEmpty = "ItemWaterBottleUnfilled"; class ItemActions { class Consume { text = $STR_ACTIONS_DRINK2; script = "spawn player_consume"; }; class Empty { text = $STR_EQUIP_NAME_13_EMPTY; script = "spawn player_emptyContainer"; }; class Fill { text = "$STR_ACTIONS_FILL_W"; script = "spawn player_fillWater;"; }; }; }; class ItemWaterbottle4ozBoiled : ItemWaterbottle { displayName = $STR_EPOCH_WATERBOTTLE4OZBOILED; descriptionShort = $STR_EPOCH_WATERBOTTLE4OZBOILED_DESC; infectionChance = 0; picture = "\z\addons\dayz_epoch\pictures\equip_waterbottle_4oz_ca.paa"; wateroz = 4; containerWater = "ItemWaterBottle"; containerWaterSafe = "ItemWaterBottleSafe"; containerWaterInfected = "ItemWaterBottleInfected"; Nutrition[] = {0,0,400,0}; consumeOutput = "ItemWaterBottleUnfilled"; containerEmpty = "ItemWaterBottleUnfilled"; class ItemActions { class Consume { text = $STR_ACTIONS_DRINK2; script = "spawn player_consume"; }; class Empty { text = $STR_EQUIP_NAME_13_EMPTY; script = "spawn player_emptyContainer"; }; class Fill { text = "$STR_ACTIONS_FILL_W"; script = "spawn player_fillWater;"; }; }; }; class ItemWaterbottle5ozBoiled : ItemWaterbottle { displayName = $STR_EPOCH_WATERBOTTLE5OZBOILED; descriptionShort = $STR_EPOCH_WATERBOTTLE5OZBOILED_DESC; infectionChance = 0; picture = "\z\addons\dayz_epoch\pictures\equip_waterbottle_5oz_ca.paa"; wateroz = 5; containerWater = "ItemWaterBottle"; containerWaterSafe = "ItemWaterBottleSafe"; containerWaterInfected = "ItemWaterBottleInfected"; Nutrition[] = {0,0,500,0}; consumeOutput = "ItemWaterBottleUnfilled"; containerEmpty = "ItemWaterBottleUnfilled"; class ItemActions { class Consume { text = $STR_ACTIONS_DRINK2; script = "spawn player_consume"; }; class Empty { text = $STR_EQUIP_NAME_13_EMPTY; script = "spawn player_emptyContainer"; }; class Fill { text = "$STR_ACTIONS_FILL_W"; script = "spawn player_fillWater;"; }; }; }; class ItemWaterbottle6ozBoiled : ItemWaterbottle { displayName = $STR_EPOCH_WATERBOTTLE6OZBOILED; descriptionShort = $STR_EPOCH_WATERBOTTLE6OZBOILED_DESC; infectionChance = 0; picture = "\z\addons\dayz_epoch\pictures\equip_waterbottle_6oz_ca.paa"; wateroz = 6; containerWater = "ItemWaterBottle"; containerWaterSafe = "ItemWaterBottleSafe"; containerWaterInfected = "ItemWaterBottleInfected"; Nutrition[] = {0,0,600,0}; consumeOutput = "ItemWaterBottleUnfilled"; containerEmpty = "ItemWaterBottleUnfilled"; class ItemActions { class Consume { text = $STR_ACTIONS_DRINK2; script = "spawn player_consume"; }; class Empty { text = $STR_EQUIP_NAME_13_EMPTY; script = "spawn player_emptyContainer"; }; class Fill { text = "$STR_ACTIONS_FILL_W"; script = "spawn player_fillWater;"; }; }; }; class ItemWaterbottle7ozBoiled : ItemWaterbottle { displayName = $STR_EPOCH_WATERBOTTLE7OZBOILED; descriptionShort = $STR_EPOCH_WATERBOTTLE7OZBOILED_DESC; infectionChance = 0; picture = "\z\addons\dayz_epoch\pictures\equip_waterbottle_7oz_ca.paa"; wateroz = 7; containerWater = "ItemWaterBottle"; containerWaterSafe = "ItemWaterBottleSafe"; containerWaterInfected = "ItemWaterBottleInfected"; Nutrition[] = {0,0,700,0}; consumeOutput = "ItemWaterBottleUnfilled"; containerEmpty = "ItemWaterBottleUnfilled"; class ItemActions { class Consume { text = $STR_ACTIONS_DRINK2; script = "spawn player_consume"; }; class Empty { text = $STR_EQUIP_NAME_13_EMPTY; script = "spawn player_emptyContainer"; }; class Fill { text = "$STR_ACTIONS_FILL_W"; script = "spawn player_fillWater;"; }; }; }; class ItemWaterbottle8ozBoiled : ItemWaterbottle { displayName = $STR_EPOCH_WATERBOTTLE8OZBOILED; descriptionShort = $STR_EPOCH_WATERBOTTLE8OZBOILED_DESC; infectionChance = 0; picture = "\z\addons\dayz_epoch\pictures\equip_waterbottle_8oz_ca.paa"; wateroz = 8; containerWater = "ItemWaterBottle"; containerWaterSafe = "ItemWaterBottleSafe"; containerWaterInfected = "ItemWaterBottleInfected"; Nutrition[] = {0,0,800,0}; consumeOutput = "ItemWaterBottleUnfilled"; containerEmpty = "ItemWaterBottleUnfilled"; class ItemActions { class Consume { text = $STR_ACTIONS_DRINK2; script = "spawn player_consume"; }; class Empty { text = $STR_EQUIP_NAME_13_EMPTY; script = "spawn player_emptyContainer"; }; class Fill { text = "$STR_ACTIONS_FILL_W"; script = "spawn player_fillWater;"; }; }; }; class ItemWaterbottle9ozBoiled : ItemWaterbottle { displayName = $STR_EPOCH_WATERBOTTLE9OZBOILED; descriptionShort = $STR_EPOCH_WATERBOTTLE9OZBOILED_DESC; infectionChance = 0; picture = "\z\addons\dayz_epoch\pictures\equip_waterbottle_9oz_ca.paa"; wateroz = 9; containerWater = "ItemWaterBottle"; containerWaterSafe = "ItemWaterBottleSafe"; containerWaterInfected = "ItemWaterBottleInfected"; Nutrition[] = {0,0,900,0}; consumeOutput = "ItemWaterBottleUnfilled"; containerEmpty = "ItemWaterBottleUnfilled"; class ItemActions { class Consume { text = $STR_ACTIONS_DRINK2; script = "spawn player_consume"; }; class Empty { text = $STR_EQUIP_NAME_13_EMPTY; script = "spawn player_emptyContainer"; }; class Fill { text = "$STR_ACTIONS_FILL_W"; script = "spawn player_fillWater;"; }; }; };
#include "dialog.h" #include <QtGui> #include <Qt> #include "server/KServer.h" #include "common/KWhiteList.h" #include <tchdb.h> #include <pthread.h> #include <time.h> #include <string> KServer newServer; pthread_t pt; Dialog::Dialog(QWidget *parent) : QWidget(parent) { this->userLogFile.InitLogCfg(LEVEL_DEBUG, "log/userLogFile", 5*1024*1024); this->serverLogFile.InitLogCfg(LEVEL_DEBUG, "log/serverLogFile", 5*1024*1024); this->whitelistLogFile.InitLogCfg(LEVEL_DEBUG, "log/whitelistLogFile", 5*1024*1024); this->serverEncryptMode=CBC; //Default encrypt mode this->whitelisIssuePolicy=BROADCAST; //Indicate the server will broadcast the new MAC to all the clients this->startOrNot=STOP; //Indicate the server has not been started //The default value of IP and port memcpy(this->ccArrLocalAddr, g_ccArrLocalAddr, g_ciAddrStrLen); this->ciPort=5000; //The four button this->startButton=new QPushButton(tr("&Start")); this->startButton->setFixedSize(100, 50); this->stopButton=new QPushButton(tr("&Stop")); this->stopButton->setEnabled(false); this->stopButton->setFixedSize(100, 50); this->setButton=new QPushButton(tr("&Set")); this->setButton->setFixedSize(100, 50); this->logButton=new QPushButton(tr("&Log")); this->logButton->setFixedSize(100, 50); this->whitelistButton=new QPushButton(tr("&Whitelist")); this->whitelistButton->setFixedSize(100, 50); this->exitButton=new QPushButton(tr("&Exit")); this->exitButton->setFixedSize(100, 50); this->userInfoButton=new QPushButton(tr("&Users")); this->userInfoButton->setFixedSize(100,50); this->aboutButton=new QPushButton(tr("&About")); this->aboutButton->setFixedSize(100,50); this->hideWhitelistButton=new QPushButton(tr("&Hide")); this->hideWhitelistButton->setFixedSize(100,30); this->hideWhitelistButton->setVisible(false); this->addMacButton=new QPushButton(tr("&Add")); this->addMacButton->setFixedSize(100, 30); this->addMacButton->setVisible(false); this->deleteMacButton=new QPushButton(tr("&Delete")); this->deleteMacButton->setFixedSize(100,30); this->deleteMacButton->setVisible(false); this->submitButton=new QPushButton(tr("&Submit")); this->submitButton->setFixedSize(100, 30); this->submitButton->setVisible(false); this->hideLogButton=new QPushButton(tr("&Hide")); this->hideLogButton->setFixedSize(100,30); this->hideLogButton->setVisible(false); this->hideSetButton=new QPushButton(tr("&Hide")); this->hideSetButton->setFixedSize(100,30); this->hideSetButton->setVisible(false); this->hideUserInfoButton=new QPushButton(tr("&Hide")); this->hideUserInfoButton->setFixedSize(100,30); this->hideUserInfoButton->setVisible(false); this->addUserButton=new QPushButton(tr("&Add")); this->addUserButton->setFixedSize(100,30); this->addUserButton->setVisible(false); this->deleteUserButton=new QPushButton(tr("&Delete")); this->deleteUserButton->setFixedSize(100,30); this->deleteUserButton->setVisible(false); this->userLogButton=new QPushButton(tr("&User")); this->userLogButton->setFixedSize(100,30); this->userLogButton->setVisible(false); this->serverLogButton=new QPushButton(tr("&Server")); this->serverLogButton->setFixedSize(100,30); this->serverLogButton->setVisible(false); this->whitelistLogButton=new QPushButton(tr("Whitelist")); this->whitelistLogButton->setFixedSize(100,30); this->whitelistLogButton->setVisible(false); this->ipAddress=new QLabel("IP :"); this->ipAddress->setFixedWidth(35); this->ipAddress->setVisible(false); this->portNumber=new QLabel("Port:"); this->portNumber->setFixedWidth(35); this->portNumber->setVisible(false); this->ipLine=new QLineEdit; this->ipLine->setVisible(false); this->portLine=new QLineEdit; this->portLine->setVisible(false); this->macAddress=new QLabel("MAC:"); this->macAddress->setFixedWidth(40); this->macAddress->setVisible(false); this->macLine=new QLineEdit; this->macLine->setVisible(false); this->sampleMacLabel=new QLabel("<font color='green'>Sample input: 00:01:0B:1C:04:05</font>"); this->sampleMacLabel->setVisible(false); this->logLabel=new QLabel("<font color='blue'>Display log file, including server, user and whitelist.</font>"); this->logLabel->setVisible(false); this->whiteListLabel=new QLabel("Display whitelist file and add a new mac to whitelist."); this->whiteListLabel->setVisible(false); this->setLabel=new QLabel("Set server's IP address, port number and operation mode"); this->setLabel->setVisible(false); this->userLabel=new QLabel("Display online users' and total users' information and you can add a new user."); this->userLabel->setVisible(false); this->onlineUserLabel=new QLabel("Online users' information:"); this->onlineUserLabel->setVisible(false); this->totalUserLabel=new QLabel("Total users' information:"); this->totalUserLabel->setVisible(false); this->usernameLabel=new QLabel("Username:"); this->usernameLabel->setVisible(false); this->usernameLine=new QLineEdit; this->usernameLine->setVisible(false); this->passwordLabel=new QLabel("Password:"); this->passwordLabel->setVisible(false); this->passwordLine=new QLineEdit; this->passwordLine->setVisible(false); this->passwordLine->setEchoMode(QLineEdit::Password); connect(this->setButton, SIGNAL(clicked()), this, SLOT(setMode())); connect(this->exitButton, SIGNAL(clicked()), this, SLOT(exitServer())); connect(this->submitButton, SIGNAL(clicked()), this, SLOT(setModeOk())); connect(this->logButton, SIGNAL(clicked()), this, SLOT(showLog())); connect(this->hideLogButton, SIGNAL(clicked()), this, SLOT(hideLog())); connect(this->startButton, SIGNAL(clicked()), this, SLOT(startServer())); connect(this->stopButton, SIGNAL(clicked()), this, SLOT(stopServer())); connect(this->whitelistButton, SIGNAL(clicked()), this, SLOT(showWhitelist())); connect(this->hideWhitelistButton, SIGNAL(clicked()), this, SLOT(hideWhitelist())); connect(this->addMacButton, SIGNAL(clicked()), this, SLOT(addNewMac())); connect(this->aboutButton, SIGNAL(clicked()), this, SLOT(showAbout())); connect(this->hideSetButton, SIGNAL(clicked()), this, SLOT(hideSet())); connect(this->userInfoButton, SIGNAL(clicked()), this, SLOT(showUserInfo())); connect(this->hideUserInfoButton, SIGNAL(clicked()), this, SLOT(hideUserInfo())); connect(this->addUserButton, SIGNAL(clicked()), this, SLOT(addNewUser())); connect(this->deleteUserButton, SIGNAL(clicked()), this, SLOT(deleteUser())); connect(this->deleteMacButton, SIGNAL(clicked()),this, SLOT(deleteMac())); connect(this->userLogButton, SIGNAL(clicked()), this, SLOT(showUserLog())); connect(this->serverLogButton, SIGNAL(clicked()), this, SLOT(showServerLog())); connect(this->whitelistLogButton, SIGNAL(clicked()), this, SLOT(showWhitelistLog())); //The check box for set this->isBroadcastWhitelist=new QCheckBox(tr("&Don't broadcast the whitelist by server")); this->isBroadcastWhitelist->setVisible(false); this->encryptModeBox=new QComboBox; this->encryptModeBox->setVisible(false); this->encryptModeBox->setFixedSize(120, 30); this->encryptModeBox->addItem("CBC", NULL); this->encryptModeBox->addItem("ECB", NULL); //The text file for log this->logFile=new QTextEdit; this->logFile->setVisible(false); this->logFile->setReadOnly(true); //The text file for server listening this->listeningFile=new QTextEdit; this->listeningFile->setReadOnly(true); connect(this->listeningFile, SIGNAL(textChanged()), this, SLOT(moveEndLisFile())); //The text file for whitelist this->whitelistFile=new QTextEdit; this->whitelistFile->setVisible(false); this->whitelistFile->setReadOnly(true); //The text file for user information this->onlineUserFile=new QTextEdit; this->onlineUserFile->setVisible(false); this->onlineUserFile->setReadOnly(true); this->onlineUserFile->setLineWrapMode(QTextEdit::NoWrap); this->totalUserFile=new QTextEdit; this->totalUserFile->setVisible(false); this->totalUserFile->setReadOnly(true); this->totalUserFile->setLineWrapMode(QTextEdit::NoWrap); this->totalUserFile->setAutoFormatting(QTextEdit::AutoBulletList); QHBoxLayout *topLayout=new QHBoxLayout; //All the buttons is in one horizontal layout topLayout->addWidget(this->startButton); topLayout->addWidget(this->stopButton); topLayout->addWidget(this->setButton); topLayout->addWidget(this->logButton); topLayout->addWidget(this->whitelistButton); topLayout->addWidget(this->userInfoButton); topLayout->addWidget(this->aboutButton); topLayout->addWidget(this->exitButton); QHBoxLayout *ipLayout=new QHBoxLayout; ipLayout->addWidget(this->ipAddress); ipLayout->addWidget(this->ipLine); QHBoxLayout *portLayout=new QHBoxLayout; portLayout->addWidget(this->portNumber); portLayout->addWidget(this->portLine); QHBoxLayout *submitLayout=new QHBoxLayout; submitLayout->addWidget(this->hideSetButton); submitLayout->addStretch(); submitLayout->addWidget(this->setLabel); submitLayout->addStretch(); submitLayout->addWidget(this->submitButton); QHBoxLayout *boxLayout=new QHBoxLayout; boxLayout->addWidget(this->isBroadcastWhitelist); boxLayout->addStretch(); boxLayout->addWidget(this->encryptModeBox); boxLayout->addStretch(); QVBoxLayout *setLayout=new QVBoxLayout; //The set layout setLayout->addLayout(ipLayout); setLayout->addLayout(portLayout); setLayout->addLayout(boxLayout); setLayout->addLayout(submitLayout); QHBoxLayout *logLayout=new QHBoxLayout; logLayout->addWidget(this->hideLogButton); logLayout->addStretch(); logLayout->addWidget(this->logLabel); logLayout->addStretch(); logLayout->addWidget(this->serverLogButton); logLayout->addWidget(this->userLogButton); logLayout->addWidget(this->whitelistLogButton); QVBoxLayout *allLogLayout=new QVBoxLayout; //The layout of logfile with a hide button allLogLayout->addWidget(this->logFile); allLogLayout->addLayout(logLayout); QHBoxLayout *macLayout=new QHBoxLayout; macLayout->addWidget(this->macAddress); macLayout->addWidget(this->macLine); macLayout->addSpacing(20); macLayout->addWidget(this->sampleMacLabel); QHBoxLayout *addMacLayout=new QHBoxLayout; addMacLayout->addWidget(this->hideWhitelistButton); addMacLayout->addStretch(); addMacLayout->addWidget(this->whiteListLabel); addMacLayout->addStretch(); addMacLayout->addWidget(this->addMacButton); addMacLayout->addWidget(this->deleteMacButton); QVBoxLayout *whitelistLayout=new QVBoxLayout; //The whitelist layout with the function of adding new mac address to whitelist whitelistLayout->addWidget(this->whitelistFile); whitelistLayout->addLayout(macLayout); whitelistLayout->addLayout(addMacLayout); QHBoxLayout *hideUserLayout=new QHBoxLayout; hideUserLayout->addWidget(this->hideUserInfoButton); hideUserLayout->addStretch(); hideUserLayout->addWidget(this->userLabel); hideUserLayout->addStretch(); hideUserLayout->addWidget(this->addUserButton); hideUserLayout->addWidget(this->deleteUserButton); QHBoxLayout *addUserLayout=new QHBoxLayout; addUserLayout->addWidget(this->usernameLabel); addUserLayout->addWidget(this->usernameLine); addUserLayout->addStretch(); addUserLayout->addWidget(this->passwordLabel); addUserLayout->addWidget(this->passwordLine); QVBoxLayout *userInfoLayout=new QVBoxLayout; userInfoLayout->addWidget(this->onlineUserLabel); userInfoLayout->addWidget(this->onlineUserFile); userInfoLayout->addWidget(this->totalUserLabel); userInfoLayout->addWidget(this->totalUserFile); userInfoLayout->addLayout(addUserLayout); userInfoLayout->addLayout(hideUserLayout); QVBoxLayout *middleLayout=new QVBoxLayout; middleLayout->addWidget(this->listeningFile); //Add listening file middleLayout->addLayout(setLayout); //Add set layout middleLayout->addLayout(allLogLayout); //Add log layout middleLayout->addLayout(whitelistLayout); //Add whitelist layout middleLayout->addLayout(userInfoLayout); QVBoxLayout *mainLayout=new QVBoxLayout; mainLayout->addLayout(topLayout); //Add all the buttons mainLayout->addLayout(middleLayout); this->setLayout(mainLayout); } Dialog::~Dialog() { } void Dialog::showUserInfo() { this->hideSet(); this->hideWhitelist(); this->hideLog(); this->listeningFile->setVisible(false); this->onlineUserLabel->setVisible(true); this->onlineUserFile->setVisible(true); this->totalUserLabel->setVisible(true); this->totalUserFile->setVisible(true); this->userLabel->setVisible(true); this->hideUserInfoButton->setVisible(true); this->addUserButton->setVisible(true); this->deleteUserButton->setVisible(true); this->usernameLabel->setVisible(true); this->usernameLine->setVisible(true); this->passwordLabel->setVisible(true); this->passwordLine->setVisible(true); this->totalUserFile->clear(); this->onlineUserFile->clear(); this->usernameLine->clear(); this->passwordLine->clear(); KUsrInfo kui; kui.Initialize(); TCHDB *hdb=(TCHDB *)kui.getDb(); //Connect the database to display all the user information struct userInfo *newUserInfo; tchdbiterinit(hdb); char *key=tchdbiternext2(hdb); int number=0; QString s; s.sprintf("<font color='blue'>Username:::::::::::::::::::::::::Flag:::::::::::::::::::::::::Last login time:::::::::::::::::::::::::Last logout time:::::::::::::::::::::::::Total login count:::::::::::::::::::::::::Total online time</font>"); this->totalUserFile->append(s); this->onlineUserFile->append(s); while(key!=NULL) { int ksize = -1; newUserInfo = (struct userInfo*)tchdbget(hdb, key, strlen(key) + 1, &ksize); QString s; s.sprintf("%7s %28d %35s %28s %25d %42d", key, newUserInfo->flag, newUserInfo->lastLoginTime, newUserInfo->lastLogoutTime, newUserInfo->totalLoginCount, newUserInfo->totalOnlineTime); this->totalUserFile->append(s); if(newUserInfo->flag==1)//This user is online { ++number; //Increment the online user number this->onlineUserFile->append(s); } key=tchdbiternext2(hdb); } s.clear(); s.sprintf("<font color='red'>There are %d users now.</font>", tchdbrnum(hdb)); this->totalUserFile->append(s); s.clear(); s.sprintf("<font color='red'>Tere are %d users online now.</font>", number); this->onlineUserFile->append(s); this->userLogFile.WriteLog(LEVEL_INFO, "Look up user database. Total online user number is %d. Total user number is %d.", number, tchdbrnum(hdb)); //Writelog } void Dialog::deleteUser() { if(!(this->usernameLine->text().length()<3)) { KUsrInfo kui; kui.Initialize(); TCHDB *hdb=(TCHDB *)kui.getDb(); //Connect the database to display all the user information char username[g_ciMaxUserNameLen]; int l=this->usernameLine->text().length(); int length=l<g_ciMaxUserNameLen-1 ? l : g_ciMaxUserNameLen-1; strncpy(username, this->usernameLine->text().toLatin1(), length); username[length]='\0'; int ksize = -1; if(((struct userInfo*)tchdbget(hdb, username, strlen(username) + 1, &ksize))==NULL ) //User not found, so return 1 { QMessageBox::warning(this, "Delete a user", "User not found!"); }else { this->listeningFile->setVisible(true); this->onlineUserLabel->setVisible(false); this->onlineUserFile->setVisible(false); this->totalUserLabel->setVisible(false); this->totalUserFile->setVisible(false); this->hideUserInfoButton->setVisible(false); this->userLabel->setVisible(false); this->addUserButton->setVisible(false); this->deleteUserButton->setVisible(false); this->usernameLabel->setVisible(false); this->usernameLine->setVisible(false); this->passwordLabel->setVisible(false); this->passwordLine->setVisible(false); if (!tchdbout(hdb, username, strlen(username) + 1)) //Delete a user { int ecode; ecode = tchdbecode(hdb); QString s; s.sprintf("<font color='blue'>Delete user "); s.append(this->usernameLine->text().toLatin1()); s.append(" failure!</font> Reason:"); s.append(tchdberrmsg(ecode)); this->listeningFile->append(s); this->userLogFile.WriteLog(LEVEL_ERROR, "Delete user %s failure!", this->usernameLine->text().toStdString().c_str()); //Write user log file }else { QString s; s.sprintf("<font color='blue'>Delete user "); s.append(this->usernameLine->text().toLatin1()); s.append(" successful!</font>"); this->listeningFile->append(s); this->userLogFile.WriteLog(LEVEL_INFO, "Delete user %s successful!", this->usernameLine->text().toStdString().c_str()); } } }else { QMessageBox::warning(this, "Delete a user", "Please input username!"); } } void Dialog::addNewUser() { if(!(this->usernameLine->text().length()<3 || this->passwordLine->text().length()<3)) {//If you input an username and a password KUsrInfo kui; kui.Initialize(); TCHDB *hdb=(TCHDB *)kui.getDb(); //Connect the database to display all the user information struct userInfo newUserInfo; char username[g_ciMaxUserNameLen]; int l=this->usernameLine->text().length(); int length=l<g_ciMaxUserNameLen-1 ? l : g_ciMaxUserNameLen-1; strncpy(username, this->usernameLine->text().toLatin1(), length); username[length]='\0'; int ksize=-1; if(((struct userInfo*)tchdbget(hdb, username, strlen(username) + 1, &ksize))==NULL) {//If you want to add a new user and the username is not exist, you can add it this->listeningFile->setVisible(true); this->onlineUserLabel->setVisible(false); this->onlineUserFile->setVisible(false); this->totalUserLabel->setVisible(false); this->totalUserFile->setVisible(false); this->hideUserInfoButton->setVisible(false); this->userLabel->setVisible(false); this->addUserButton->setVisible(false); this->deleteUserButton->setVisible(false); this->usernameLabel->setVisible(false); this->usernameLine->setVisible(false); this->passwordLabel->setVisible(false); this->passwordLine->setVisible(false); l=this->passwordLine->text().length(); length=l<g_ciMaxPwdLen-1 ? l : g_ciMaxPwdLen-1; strncpy(newUserInfo.ccArrPwd, this->passwordLine->text().toLatin1(), length); newUserInfo.ccArrPwd[length]='\0'; newUserInfo.flag=0; newUserInfo.lastLoginTime[0]='0'; newUserInfo.lastLoginTime[1]='\0'; newUserInfo.lastLogoutTime[0]='0'; newUserInfo.lastLogoutTime[1]='\0'; newUserInfo.totalLoginCount=0; newUserInfo.totalOnlineTime=0; if (!tchdbput(hdb, username, strlen(username) + 1, &newUserInfo, sizeof(struct userInfo))) //Update user information { int ecode; ecode = tchdbecode(hdb); QString s; s.sprintf("<font color='blue'>Add new user "); s.append(this->usernameLine->text().toLatin1()); s.append(" failure!</font> Reason:"); s.append(tchdberrmsg(ecode)); this->listeningFile->append(s); this->userLogFile.WriteLog(LEVEL_ERROR, "Add new user %s failure!", this->usernameLine->text().toStdString().c_str()); }else { QString s; s.sprintf("<font color='blue'>Add new user "); s.append(this->usernameLine->text().toLatin1()); s.append(" successful!</font>"); this->listeningFile->append(s); this->userLogFile.WriteLog(LEVEL_INFO, "Add new user %s successful!", this->usernameLine->text().toStdString().c_str()); } }else { QMessageBox::warning(this, "Add a new user", "The username is in the database!"); } }else { QMessageBox::warning(this, "Add a new user", "Please input username and password!"); } } void Dialog::hideUserInfo() { this->listeningFile->setVisible(true); this->onlineUserLabel->setVisible(false); this->onlineUserFile->setVisible(false); this->totalUserLabel->setVisible(false); this->totalUserFile->setVisible(false); this->hideUserInfoButton->setVisible(false); this->userLabel->setVisible(false); this->addUserButton->setVisible(false); this->deleteUserButton->setVisible(false); this->usernameLabel->setVisible(false); this->usernameLine->setVisible(false); this->passwordLabel->setVisible(false); this->passwordLine->setVisible(false); } void Dialog::showWhitelist() { this->hideSet(); this->hideLog(); this->hideUserInfo(); this->listeningFile->setVisible(false); this->whitelistFile->setVisible(true); this->macAddress->setVisible(true); this->macLine->setVisible(true); this->sampleMacLabel->setVisible(true); this->hideWhitelistButton->setVisible(true); this->whiteListLabel->setVisible(true); this->addMacButton->setVisible(true); this->deleteMacButton->setVisible(true); this->whitelistFile->clear(); this->macLine->clear(); vector<KMac> whitelist=newServer.getKWhitelist().getWhitelist(); int count=whitelist.size(); int i=0; while(i<count) { QString mac; mac.sprintf("%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x", whitelist[i].GetAddr()[0], whitelist[i].GetAddr()[1], whitelist[i].GetAddr()[2], whitelist[i].GetAddr()[3], whitelist[i].GetAddr()[4], whitelist[i].GetAddr()[5], whitelist[i].GetAddr()[6], whitelist[i].GetAddr()[7]); this->whitelistFile->append(mac); ++i; } QString s; s.sprintf("<font color='red'>There are total %d MACs in the whitelist.</font>", count); this->whitelistFile->append(s); this->whitelistLogFile.WriteLog(LEVEL_INFO, "Look up whitelist information. There are total %d MACs in the whitelist.", count); } void Dialog::hideWhitelist() { this->listeningFile->setVisible(true); this->whitelistFile->setVisible(false); this->macAddress->setVisible(false); this->macLine->setVisible(false); this->sampleMacLabel->setVisible(false); this->hideWhitelistButton->setVisible(false); this->whiteListLabel->setVisible(false); this->addMacButton->setVisible(false); this->deleteMacButton->setVisible(false); } void Dialog::addNewMac() { if(this->macLine->text().isEmpty() || this->macLine->text().length()!=17) { QMessageBox::warning(this, "Add a new MAC", "Please input a correct new MAC!"); return; } QString s=this->macLine->text(); //The MAC that you input s=s.toUpper(); unsigned char newMac[g_ciMaxMacAddrLen]={0x00}; if(!(this->string_to_unsignedchar(s.toStdString().c_str(), newMac))) //If return false, this indicates the input has error { QMessageBox::warning(this, "Add a new MAC", "Please input a correct new MAC!"); return; } KMac kmac; kmac.SetAddr(newMac); if(newServer.addWhitelist(kmac))//Add MAC successfully { QString sm; if(this->startOrNot==START) //If the server has been started, we should issue the new MAC to other clients { struct clientInfo addNewMac; addNewMac.dialog=this; vector<int> vcs=newServer.getClientSocket(); addNewMac.vClientSockfds=&vcs; addNewMac.kpProto.m_kmMac=kmac; //The new MAC newServer.notifyAllClients(ADD, &addNewMac); sm.sprintf("<font color='blue'>Add! Has notified all other %d clients.</font>", vcs.size()); this->listeningFile->append(sm); this->whitelistLogFile.WriteLog(LEVEL_INFO, "Add! Has notified all other %d clients.", vcs.size()); } sm.clear(); sm.sprintf("Add a new MAC to whitelist, it is : %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x", newMac[0], newMac[1], newMac[2], newMac[3], newMac[4], newMac[5], newMac[6], newMac[7]); this->listeningFile->append(sm); this->whitelistLogFile.WriteLog(LEVEL_INFO, sm.toStdString().c_str()); this->listeningFile->setVisible(true); this->whitelistFile->setVisible(false); this->macAddress->setVisible(false); this->macLine->setVisible(false); this->hideWhitelistButton->setVisible(false); this->whiteListLabel->setVisible(false); this->addMacButton->setVisible(false); this->deleteMacButton->setVisible(false); }else { QMessageBox::warning(this, "Add a new MAC", "The MAC is already in the whitelist! Please input again!"); } } void Dialog::deleteMac() { if(this->macLine->text().isEmpty()) { QMessageBox::warning(this, "Delete a MAC", "Please input a MAC from the whitelist!"); return; } QString s=this->macLine->text(); //The MAC that you input s=s.toUpper(); unsigned char newMac[g_ciMaxMacAddrLen]={0x00}; if(!(this->string_to_unsignedchar(s.toStdString().c_str(), newMac))) //If return false, this indicates the input has error { QMessageBox::warning(NULL, "Add a new MAC", "Please input a correct new MAC!"); return; } KMac kmac; kmac.SetAddr(newMac); QString sm; if(this->startOrNot==START) //If the server has been started, we should issue the new MAC to other clients { struct clientInfo addNewMac; addNewMac.dialog=this; vector<int> vcs=newServer.getClientSocket(); addNewMac.vClientSockfds=&vcs; addNewMac.kpProto.m_kmMac=kmac; //The new MAC newServer.notifyAllClients(DEL, &addNewMac); sm.sprintf("<font color='blue'>Delete! Has notified all other %d clients.</font>", vcs.size()); this->listeningFile->append(sm); this->whitelistLogFile.WriteLog(LEVEL_INFO, "Delete! Has notified all other %d clients.", vcs.size()); } if(newServer.deleteWhitelist(kmac)) //Delete successful { sm.clear(); sm.sprintf("Delete a MAC from whitelist, it is : %02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x", newMac[0], newMac[1], newMac[2], newMac[3], newMac[4], newMac[5], newMac[6], newMac[7]); this->listeningFile->append(sm); this->whitelistLogFile.WriteLog(LEVEL_INFO, sm.toStdString().c_str()); this->listeningFile->setVisible(true); this->whitelistFile->setVisible(false); this->macAddress->setVisible(false); this->macLine->setVisible(false); this->hideWhitelistButton->setVisible(false); this->whiteListLabel->setVisible(false); this->addMacButton->setVisible(false); this->deleteMacButton->setVisible(false); }else //Attempt to delete a not exist MAC { QMessageBox::warning(this, "Delete a MAC", "The MAC is not in the whitelist! Please input again!"); } } void Dialog::setMode() { this->hideLog(); this->hideWhitelist(); this->hideUserInfo(); this->listeningFile->setVisible(false); this->isBroadcastWhitelist->setVisible(true); this->encryptModeBox->setVisible(true);; this->submitButton->setVisible(true); this->setLabel->setVisible(true); this->hideSetButton->setVisible(true); this->ipAddress->setVisible(true); this->portNumber->setVisible(true); this->ipLine->setVisible(true); this->portLine->setVisible(true); this->ipLine->clear(); this->portLine->clear(); } void Dialog::setModeOk() { this->listeningFile->setVisible(true); this->isBroadcastWhitelist->setVisible(false); this->encryptModeBox->setVisible(false); this->submitButton->setVisible(false); this->setLabel->setVisible(false); this->hideSetButton->setVisible(false); this->ipAddress->setVisible(false); this->portNumber->setVisible(false); this->ipLine->setVisible(false); this->portLine->setVisible(false); if(this->isBroadcastWhitelist->isChecked()) { this->whitelisIssuePolicy=REQUEST; //Indicate the server's will not broadcast the new MAC to all the clients, it will only broadcast a new MAC to all the application server this->serverLogFile.WriteLog(LEVEL_INFO, "Set whitelist issue policy to client-request!"); }else { this->whitelisIssuePolicy=BROADCAST; this->serverLogFile.WriteLog(LEVEL_INFO, "Set whitelist issue policy to server-broadcast!"); } if(this->encryptModeBox->currentText()=="CBC") { this->serverEncryptMode=CBC; this->serverLogFile.WriteLog(LEVEL_INFO, "Set encrypt mode to CBC!"); }else { this->serverEncryptMode=ECB; this->serverLogFile.WriteLog(LEVEL_INFO, "Set encrypt mode to ECB!"); } if(!(this->ipLine->text().isEmpty())) //Set IP address { int l=this->ipLine->text().length(); int length=l<g_ciAddrStrLen-1 ? l : g_ciAddrStrLen-1; strncpy(this->ccArrLocalAddr, (this->ipLine->text()).toLatin1(), length); this->ccArrLocalAddr[length]='\0'; this->serverLogFile.WriteLog(LEVEL_INFO, "Set server's IP address to %s.", this->ccArrLocalAddr); } if(!(this->portLine->text().isEmpty())) //Set port number { this->ciPort=this->portLine->text().toInt(); this->serverLogFile.WriteLog(LEVEL_INFO, "Set server's port number to %d.", this->ciPort); } } void Dialog::hideSet() { this->listeningFile->setVisible(true); this->isBroadcastWhitelist->setVisible(false); this->submitButton->setVisible(false); this->encryptModeBox->setVisible(false); this->setLabel->setVisible(false); this->hideSetButton->setVisible(false); this->ipAddress->setVisible(false); this->portNumber->setVisible(false); this->ipLine->setVisible(false); this->portLine->setVisible(false); } void Dialog::showLog() { this->hideSet(); this->hideWhitelist(); this->hideUserInfo(); this->listeningFile->setVisible(false); this->logFile->setVisible(true); this->logLabel->setVisible(true); this->hideLogButton->setVisible(true); this->serverLogButton->setVisible(true); this->userLogButton->setVisible(true); this->whitelistLogButton->setVisible(true); } void Dialog::showUserLog() { this->logFile->clear(); ifstream file("log/userLogFile"); if(!file.is_open()) //If open the file fail { this->serverLogFile.WriteLog(LEVEL_ERROR, "Open the userLogFile fail!"); this->logFile->append("<font color='red'>Open the userLogFile fail!</font>"); }else { //this->serverLogFile.WriteLog(LEVEL_INFO, "Look up user log file"); QString qs; while(!file.eof()) { string s; getline(file, s); s.append("\n"); qs.prepend(s.c_str()); } this->logFile->append(qs.toStdString().c_str()); } file.close(); } void Dialog::showServerLog() { this->logFile->clear(); ifstream file("log/serverLogFile"); if(!file.is_open()) //If open the file fail { this->serverLogFile.WriteLog(LEVEL_ERROR, "Open the serverLogFile fail!"); this->logFile->append("<font color='red'>Open the serverLogFile fail!</font>"); }else { //this->serverLogFile.WriteLog(LEVEL_INFO, "Look up server log file"); QString qs; while(!file.eof()) { string s; getline(file, s); s.append("\n"); qs.prepend(s.c_str()); } this->logFile->append(qs.toStdString().c_str()); } file.close(); } void Dialog::showWhitelistLog() { this->logFile->clear(); ifstream file("log/whitelistLogFile"); if(!file.is_open()) //If open the file fail { this->serverLogFile.WriteLog(LEVEL_ERROR, "Open the whitelistLogFile fail!"); this->logFile->append("<font color='red'>Open the whitelistLogFile fail!</font>"); }else { //this->serverLogFile.WriteLog(LEVEL_INFO, "Look up whitelist log file"); QString qs; while(!file.eof()) { string s; getline(file, s); s.append("\n"); qs.prepend(s.c_str()); } this->logFile->append(qs.toStdString().c_str()); } file.close(); } void Dialog::hideLog() { this->logFile->clear(); this->listeningFile->setVisible(true); this->logFile->setVisible(false); this->logLabel->setVisible(false); this->hideLogButton->setVisible(false); this->serverLogButton->setVisible(false); this->userLogButton->setVisible(false); this->whitelistLogButton->setVisible(false); } void *startNow(void *dialog) { newServer.startServer(dialog); pthread_exit(NULL); } void Dialog::startServer() { if(newServer.getRsaKeyN()==0) //Rsa has not been set, so server can not be started { QMessageBox::warning(this, "NacServer", "The server is in configuration, pleas wait for a moment. Thank you!", QMessageBox::Ok, 0); return; } newServer.InitWhitelist(); this->startOrNot=START; //Indicate the server has been started this->listeningFile->clear(); this->hideSet(); this->hideWhitelist(); this->hideLog(); this->hideUserInfo(); this->startButton->setEnabled(false); this->stopButton->setEnabled(true); this->setButton->setEnabled(false); this->exitButton->setEnabled(false); this->submitButton->setEnabled(false); KUsrInfo kui; kui.Initialize(); TCHDB *hdb=(TCHDB *)kui.getDb(); //First, connect the database to offline all the online users struct userInfo *newUserInfo; tchdbiterinit(hdb); char *key=tchdbiternext2(hdb); while(key!=NULL) { int ksize = -1; char username[g_ciMaxUserNameLen]; strncpy(username, key, strlen(key)); username[strlen(key)]='\0'; newUserInfo = (struct userInfo*)tchdbget(hdb, username, strlen(username) + 1, &ksize); if(newUserInfo->flag==1)//This user is online { newUserInfo->flag=0; //All online users are forcing quit time_t t; t=time(NULL); char *tt=ctime(&t); strncpy(newUserInfo->lastLogoutTime, tt, strlen(tt)); //Record this login time newUserInfo->lastLogoutTime[strlen(tt)-1]='\0'; if (!tchdbput(hdb, username, strlen(username) + 1, newUserInfo, sizeof(struct userInfo))) //Update user information { int ecode; ecode = tchdbecode(hdb); QString ms; ms.sprintf("Start server failure: %d!", ecode); this->listeningFile->append(ms); this->serverLogFile.WriteLog(LEVEL_ERROR, ms.toStdString().c_str()); return; } } key=tchdbiternext2(hdb); } time_t t; t=time(NULL); QString startInfo; startInfo.sprintf("<font color='red'>Start server!</font>:::%s", ctime(&t)); this->listeningFile->append(startInfo); this->serverLogFile.WriteLog(LEVEL_INFO, "Start server!"); QString s; s.sprintf("Set RSA key N to %lld.", newServer.getRsaKeyN()); this->listeningFile->append(s); this->serverLogFile.WriteLog(LEVEL_INFO, s.toStdString().c_str()); s.clear(); s.sprintf("Set RSA key E to %lld.", newServer.getRsaKeyE()); this->listeningFile->append(s); this->serverLogFile.WriteLog(LEVEL_INFO, s.toStdString().c_str()); pthread_attr_t attr; //The attribute of the thread pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&pt, &attr, &startNow, (void *)this); pthread_attr_destroy(&attr); } void *stopNow(void *) { newServer.stopServer(); pthread_exit(NULL); } void Dialog::stopServer() { int yesOrNo=QMessageBox::question(this, "Question", "Are you sure to stop server?", QMessageBox::Yes, QMessageBox::No); if(yesOrNo==QMessageBox::Yes) { newServer.clearWhitelist(); //Stop the server and clear the whitelist this->startOrNot=STOP; //Indicate the server has been stopped this->hideSet(); this->hideWhitelist(); this->hideLog(); this->startButton->setEnabled(true); this->stopButton->setEnabled(false); this->setButton->setEnabled(true); this->exitButton->setEnabled(true); this->submitButton->setEnabled(true); time_t t; t=time(NULL); QString startInfo; startInfo.sprintf("<font color='red'>Stop server!</font>:::%s", ctime(&t)); this->listeningFile->append(startInfo); this->listeningFile->append(""); this->serverLogFile.WriteLog(LEVEL_INFO, "Stop server!"); pthread_cancel(pt); //Shutdown the server pthread_attr_t attr; //The attribute of the thread pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&pt, &attr, &stopNow, NULL); pthread_attr_destroy(&attr); } } void Dialog::exitServer() { this->close(); } void Dialog::showAbout() { QMessageBox::about(this, "About NacClient", "NacServer 1.0.0\nBased on Linux & C++ & Qt 4.7.0\nBuilt on May 20 2013\nCopyright 2013-2013 Nac Corporation. All rights reserved.\nAuthor: Qin Peixi, Hao Zhanzhu, Zhang Yaolin"); } QTextEdit* Dialog::getLisFile() { return this->listeningFile; } char* Dialog::getIpAddr() { return this->ccArrLocalAddr; } int Dialog::getPort() { return this->ciPort; } enum wlIssuePolicy Dialog::getWlIssuePolicy() { return this->whitelisIssuePolicy; } void Dialog::setWlIssuePolicy(enum wlIssuePolicy policy) { this->whitelisIssuePolicy=policy; } char digit_convert(char ch) { return (ch-'0'); } char char_convert(char ch) { return (ch-'A'+10); } bool Dialog::string_to_unsignedchar(const char *mac,unsigned char newMac[]) { int cnt=0; for(int i=0;i<17;i=i+3) { char ch1; unsigned char result; if(mac[i]>='0' && mac[i]<='9') { ch1=(digit_convert(mac[i])<<4); }else if(mac[i]>='A' && mac[i]<='F') { ch1=(char_convert(mac[i])<<4); }else //Input error { return false; } if(mac[i+1]>='0' && mac[i+1]<='9') { result=(ch1)+(digit_convert(mac[i+1])); } else if(mac[i+1]>='A' && mac[i+1]<='F') { result=(ch1)+(char_convert(mac[i+1])); }else //Input error { return false; } newMac[cnt++]=result; } return true; } CMyLog Dialog::getUserLogFile() { return this->userLogFile; } CMyLog Dialog::getServerLogFile() { return this->serverLogFile; } CMyLog Dialog::getWhitelistLogFile() { return this->whitelistLogFile; } void Dialog::serverWriteLog(LEVEL_TYPE logLevel, const char* format,...) { this->serverLogFile.WriteLog(logLevel, format); } void Dialog::appendLisFile(QString s) { this->listeningFile->append(s); } enum encryptMode Dialog::getEnMode() { return this->serverEncryptMode; } void Dialog::closeEvent( QCloseEvent* qce ) { int yesOrNo=QMessageBox::question(this, "NacClient", "Are you sure to exit?", QMessageBox::Yes, QMessageBox::No); if(yesOrNo == QMessageBox::Yes) { this->serverLogFile.WriteLog(LEVEL_INFO, "Exit server!"); qce->accept(); }else { qce->ignore(); } } void Dialog::moveEndLisFile() { QTextCursor cur=this->listeningFile->textCursor(); cur.movePosition(QTextCursor::End, QTextCursor::MoveAnchor); this->listeningFile->setTextCursor(cur); } void Dialog::enableStartButton() { this->startButton->setEnabled(true); } void Dialog::showRsaOk() { while(newServer.getRsaKeyN()==0) { } QMessageBox::information(this, "NacSever", "Rsa has been set!", QMessageBox::Ok, 0); }
#include <iostream> using namespace std; int main() { char ch; cout<<"请输入一个字母:"<<endl; cin>>ch; if(96<ch &&ch<123) switch(ch){ case 'a':cout<<"元音"<<endl;break; case 'e':cout<<"元音"<<endl;break; case 'i':cout<<"元音"<<endl;break; case 'o':cout<<"元音"<<endl;break; case 'u':cout<<"元音"<<endl;break; default:cout<<"辅音"<<endl; } else cout<<"不是英文字母"; return 0; }
#pragma once namespace aeEngineSDK { struct AE_UTILITY_EXPORT aeAABB { /*************************************************************************************************/ /* Constructors declaration /*************************************************************************************************/ public: aeAABB(); aeAABB(const aeAABB& A); aeAABB(const aeVector3& A, const aeVector3& B); ~aeAABB(); /*************************************************************************************************/ /* Variable declaration /*************************************************************************************************/ public: aeVector3 m_xMax; aeVector3 m_xMin; /*************************************************************************************************/ /* Functions declaration /*************************************************************************************************/ public: bool operator^(const aeAABB& AB); bool operator^(const aeVector3& V); }; }