text
stringlengths
8
6.88M
#pragma once #include <SFML/Graphics.hpp> #include <iostream> using namespace std; using namespace sf; #include "SettingsMgr.h" #include <iostream> #include <iomanip> #include <string> void die(string end); // finish this code; add functions, data as needed class SettingsUI { private: SettingsMgr *settingsMgr; public: // Constructor SettingsUI(SettingsMgr *mgr) { settingsMgr = mgr; } // Displays buttons and text void draw(RenderWindow& win) { Font font; if (!font.loadFromFile("C:\\Windows\\Fonts\\Ebrima.ttf")) { die("Error opening file!"); } // Dssplaying circle colors to choose Text Colors; Colors.setString("Select Color:"); Colors.setFont(font); Colors.setPosition(15, 50); win.draw(Colors); CircleShape redButton(25), blueButton(25), greenButton(25); CircleShape circle(25); // Red button circle settings redButton.setPosition(75, 100); redButton.setOutlineThickness(3); redButton.setFillColor(Color::Transparent); redButton.setOutlineColor(Color::Red); // Blue button circle settings blueButton.setPosition(75, 250); blueButton.setFillColor(Color::Transparent); blueButton.setOutlineThickness(3); blueButton.setOutlineColor(Color::Blue); // Green button Circle Settings greenButton.setPosition(75, 175); greenButton.setOutlineThickness(3); greenButton.setFillColor(Color::Transparent); greenButton.setOutlineColor(Color::Green); Color C = settingsMgr->getCurColor(); if (C == Color::Red) { redButton.setFillColor(Color::Red); } else if (C == Color::Blue) { blueButton.setFillColor(Color::Blue); } else if (C == Color::Green) { greenButton.setFillColor(Color::Green); } RectangleShape square(Vector2f(50, 50)); // Circle option settings circle.setOutlineThickness(3); circle.setPosition(75, 400); circle.setFillColor(Color::Transparent); circle.setOutlineColor(Color::White); // Square settings square.setOutlineThickness(3); square.setPosition(75, 475); square.setFillColor(Color::Transparent); square.setOutlineColor(Color::White); ShapeEnum S = settingsMgr->getCurShape(); if (S == CIRCLE) { circle.setFillColor(Color::White); } else if (S == SQUARE) { square.setFillColor(Color::White); } win.draw(circle); win.draw(square); win.draw(redButton); win.draw(blueButton); win.draw(greenButton); // Displaying shapes to choose Text Shapes; Shapes.setString("Select Shape:"); Shapes.setPosition(5, 350); Shapes.setFont(font); win.draw(Shapes); } // Checks if the mouse has selected any options void handleMouseUp(Vector2f mouse) { if (mouse.x > 75 && mouse.x < 125){ if (mouse.y > 100 && mouse.y < 150){ settingsMgr->setColor(Color::Red); } else if (mouse.y > 250 && mouse.y < 300){ settingsMgr->setColor(Color::Blue); } else if (mouse.y > 175 && mouse.y < 225){ settingsMgr->setColor(Color::Green); } else if (mouse.y > 475 && mouse.y < 525) { settingsMgr->setShape(SQUARE); } else if (mouse.y > 400 && mouse.y < 450){ settingsMgr->setShape(CIRCLE); } } } }; void die(string end) { cout << end << endl; exit(-1); }
/************************************************************* * > File Name : c1083_2.cpp * > Author : Tony * > Created Time : 2019/11/03 17:18:11 * > Algorithm : **************************************************************/ #include <bits/stdc++.h> using namespace std; inline int read() { int x = 0; int f = 1; char ch = getchar(); while (!isdigit(ch)) {if (ch == '-') f = -1; ch = getchar();} while (isdigit(ch)) {x = x * 10 + ch - 48; ch = getchar();} return x * f; } const int maxn = 55; int n, a[maxn][maxn], sum[maxn][maxn]; long long ans; int ask(int x, int y, int _x, int _y) { return sum[_x][_y] - sum[x - 1][_y] - sum[_x][y - 1] + sum[x - 1][y - 1]; } const int N = 2600; const int mod = (1 << 11) - 1; struct Hash_Map { int ver[N], nxt[N], head[mod + 10], cnt, val[N]; void add(int u, int v) { ver[++cnt] = v; nxt[cnt] = head[u]; head[u] = cnt; } int& operator [] (int v) { for (int i = head[v & mod]; i; i = nxt[i]) { if (ver[i] == v) return val[i]; } add(v & mod, v); return val[cnt]; } }m1[maxn][maxn], m2[maxn][maxn]; int main() { n = read(); for (int i = 1; i <= n; ++i) for (int j = 1; j <= n; ++j){ a[i][j] = read(); sum[i][j] = sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1] + a[i][j]; } for (int i = 1; i <= n; ++i) for (int j = 1; j <= n; ++j) for (int k = i; k <= n; ++k) for (int l = j; l <= n; ++l) { int res1 = ask(i, j, k, l); ans += m1[i - 1][j - 1][res1]; m1[k][l][res1]++; } for (int i = 1; i <= n; ++i) for (int j = n; j >= 1; --j) for (int k = i; k <= n; ++k) for (int l = j; l >= 1; --l) { int res1 = ask(i, l, k, j); ans += m2[i - 1][j + 1][res1]; m2[k][l][res1]++; } printf("%lld\n", ans); return 0; }
#include <cmath> #include <iostream> #include <list> #include <map> #include <numeric> #include <queue> #include <unordered_map> #include <unordered_set> #include <vector> #include <set> #include <stack> #include <sstream> #include <string> using namespace std; struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; /* Solution */ const int MOD = 1000000007; class Solution { public: int minDistance(vector<int>& houses, int K) { sort(houses.begin(), houses.end()); int n = houses.size(); vector<vector<int>> presum(n, vector<int>(n, 0)); for (int i = 0; i < n; ++i) { for (int j = i; j < n; ++j) { int med = (i + j) / 2; for (int k = i; k <= j; ++k) { presum[i][j] += abs(houses[k] - houses[med]); } } } vector<vector<int>> dp(K + 1, vector<int>(n, INT_MAX)); for (int i = 0; i < n; ++i) { dp[1][i] = presum[0][i]; } for (int k = 2; k <= K; ++k) { for (int i = 0; i < n; ++i) { if (i == 0) { dp[k][0] = 0; continue; } for (int j = 0; j <= i; ++j) { dp[k][i] = min(dp[k][i], (j == 0 ? 0 : dp[k - 1][j - 1]) + presum[j][i]); } // cout << "dp[" << k << "][" << i << "] = " << dp[k][i] << endl; } } return dp[K][n - 1]; } }; int main() { Solution sol; vector<int> houses = {1,4,8,10,20}; int k = 3; // vector<int> houses = {2,3,5,12,18}; // int k = 2; // vector<int> houses = {7,4,6,1}; // int k = 1; // vector<int> houses = {3,6,14,10}; // int k = 4; cout << sol.minDistance(houses, k) << endl; }
#include "Com.h" #if 0 namespace Cache::Native { thread_local memcached_st *memc = 0; thread_local memcached_server_st *servers = 0; const char* memcached_error = 0; const char* GetLastError() {return memcached_error;} void InitMemcachedThread() { if (memc == NULL) { memcached_return rc; memc = memcached_create(NULL); servers = memcached_server_list_append(servers, "localhost", 11211, &rc); if (rc != MEMCACHED_SUCCESS) { memcached_error = memcached_strerror(memc, rc); } rc = memcached_server_push(memc, servers); if (rc != MEMCACHED_SUCCESS) { memcached_error = memcached_strerror(memc, rc); } rc = memcached_server_push(memc, servers); if (rc != MEMCACHED_SUCCESS) { memcached_error = memcached_strerror(memc, rc); } } } void DeinitMemcachedThread() { if (memc) { memcached_free(memc); memc = 0; } } bool ClearMemcached(const char* key, int keylen) { const char* empty_str = ""; //int keylen = strnlen(key, 1024); memcached_return rc = memcached_set(memc, key, keylen, empty_str, 0, (time_t)0, (uint32_t)0); if (rc != MEMCACHED_SUCCESS) { memcached_error = memcached_strerror(memc, rc); return false; } else return true; } bool SetMemcached(const char* key, int keylen, const char* value, int valuelen) { if (!memc) InitMemcachedThread(); //int keylen = strnlen(key, 1024); //int valuelen = strnlen(value, 100*1024*1024); memcached_return rc = memcached_set(memc, key, keylen, value, valuelen, (time_t)0, (uint32_t)0); if (rc != MEMCACHED_SUCCESS) { memcached_error = memcached_strerror(memc, rc); return false; } else return true; } bool GetMemcached(const char* key, int keylen, const char** value) { uint32_t flags; size_t value_len = 0; memcached_return rc; *value = (const char*)memcached_get(memc, key, keylen, &value_len, &flags, &rc); if (rc != MEMCACHED_SUCCESS) { memcached_error = memcached_strerror(memc, rc); if (*value) free((void*)*value); return false; } return true; } } #endif
/// /// \file Tools.h /// \brief /// \author PISUPATI Phanindra /// \date 01.04.2014 /// #ifndef TOOLS_H #define TOOLS_H #include <cmath> #include "MarkerData.h" namespace Tools { /// /// \brief wrap radians to PI /// \param input angle in radians /// \return angle between (-pi, pi] /// float wrapToPi(float input); /// /// \brief wrap to PI /// \param input angle in degrees /// \return angle between (-180, 180] /// float wrapTo180(float input); /// /// \brief degree to radians /// \param input angle in degrees /// \return angle between (-pi, pi] /// float degToRad(float input); /// /// \brief radians to degree /// \param input angle in radians /// \return angle between (-180, 180] /// float radToDeg(float input); Point2d rotatePoint(Point2d point, float angle); Point2d translatePoint(Point2d point, float x, float y); } // end of namespace Tools #endif
#ifndef BoxCollider_hpp #define BoxCollider_hpp #include <stdio.h> #include "Collider.hpp" class BoxCollider : public Collider { private: float xRange; float yRange; public: GameObject *parent; BoxCollider(float width, float height, GameObject *newParent); ~BoxCollider(); void setParent(GameObject* newParent) override { parent = newParent; } void setBounds(float width, float height); Location *getLocation() override { return parent->getLocation(); } bool isColliding(GameObject *otherObject) override; Direction contactPoint(Collider *otherCollider) override; std::vector<float> *getBounds() override; }; #endif /* BoxCollider_hpp */
/*************************************************************************** listadimensiones.h - description ------------------- begin : mar 24 2004 copyright : (C) 2004 by Oscar G. Duarte email : ogduarte@ing.unal.edu.co ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifndef LISTADIMENSIONES_H #define LISTADIMENSIONES_H #include <wx/wx.h> #include <wx/dynarray.h> WX_DECLARE_OBJARRAY(int, ListaDeDimensiones); /**Lista de dimensiones de configuración para la interfaz gráfica *@author Oscar G. Duarte */ class ListaDimensiones { public: ListaDimensiones(); ~ListaDimensiones(); void adicionarDimension(wxString N, int d); int Dimension(wxString N); void limpiar(); wxArrayString Nombres; ListaDeDimensiones Dimensiones; }; #endif
#include "stdhdr.h" using namespace Singularity; namespace Singularity { namespace Tasks { #pragma region Static Variables DWORD CTaskPool::g_iTLSindex = TLS_OUT_OF_INDEXES; #pragma endregion #pragma region Constructors and Finalizers CTaskPool::CTaskPool() : m_iThreadCount(0), m_pThreads(NULL), m_iState(TASKPOOL_STATE_UNINITIALIZED) { // null out the task & reference array ZeroMemory(this->m_pTasks, sizeof(CTask*) * SINGULARITY_TASKS_MAX_TASKS); ZeroMemory(this->m_pLinks, sizeof(unsigned) * SINGULARITY_TASKS_MAX_TASKS); ::InitializeCriticalSection(&this->m_pLock); } CTaskPool::~CTaskPool() { // release the TLS and set the index to invalid value if(CTaskPool::g_iTLSindex != TLS_OUT_OF_INDEXES) { TlsFree(CTaskPool::g_iTLSindex); CTaskPool::g_iTLSindex = TLS_OUT_OF_INDEXES; } ::DeleteCriticalSection(&this->m_pLock); } #pragma endregion #pragma region Methods void CTaskPool::Initialize(int options) { if(this->m_iState != TASKPOOL_STATE_UNINITIALIZED) throw SingularityException("TaskPool is already initialized!"); // initialize Thread Local Storage // TLS allows us to have a unified heap across all of the threads CTaskPool::g_iTLSindex = ::TlsAlloc(); if (TLS_OUT_OF_INDEXES == CTaskPool::g_iTLSindex) throw SingularityException("Unable to allocate local storage."); // create the worker threads for the tasking // determine the correct thread limit for the process this->m_iThreadCount = CTaskPool::GetHardwareThreadsCount(); if (this->m_iThreadCount > SINGULARITY_TASKS_MAX_THREADS) this->m_iThreadCount = SINGULARITY_TASKS_MAX_THREADS; this->m_pThreads = new CWorkerThread[this->m_iThreadCount]; // update the pool's state this->m_iState = TASKPOOL_STATE_INITIALIZED; ::EnterCriticalSection(&this->m_pLock); { // null out the task & reference array and reset the count ZeroMemory(this->m_pTasks, sizeof(CTask*) * SINGULARITY_TASKS_MAX_TASKS); ZeroMemory(this->m_pLinks, sizeof(unsigned) * SINGULARITY_TASKS_MAX_TASKS); } ::LeaveCriticalSection(&this->m_pLock); } void CTaskPool::Start() { unsigned int index; if(this->m_iState != TASKPOOL_STATE_INITIALIZED && this->m_iState != TASKPOOL_STATE_IDLE && this->m_iState != TASKPOOL_STATE_STOPPED) throw SingularityException("TaskPool is already running or cannot be started!"); // intermediate update to the pool's state this->m_iState = TASKPOOL_STATE_STARTING; // start up all the threads for( index = 0; index < this->m_iThreadCount; index++) this->m_pThreads[index].Start(this); // update the pool's state this->m_iState = TASKPOOL_STATE_STARTED; for(;;) { for( index = 0; index < this->m_iThreadCount; index++) this->m_pThreads[index].Step(); } } void CTaskPool::Stop() { unsigned index; if(this->m_iState != TASKPOOL_STATE_STARTED || this->m_iState != TASKPOOL_STATE_IDLE) throw SingularityException("TaskPool is either already stopped or cannot be stopped!"); // intermediate update to the pool's state this->m_iState = TASKPOOL_STATE_STOPPING; // spin wait for them to finish for( index = 0; index < this->m_iThreadCount; index++) { // this->m_pThreads[index].Abort(); //while (!this->m_pThreads[index].Get_IsCompleted()) //{ // Sleep(0); // wait for the thread to die off //} } // update the pool's state this->m_iState = TASKPOOL_STATE_STOPPED; } CTask* CTaskPool::PopTask() { CTask* task; unsigned i, linkIndex; ::EnterCriticalSection(&this->m_pLock); { // grab the task index; linkIndex = this->m_pLinks[0]; // grab the task task = this->m_pTasks[linkIndex]; if(task) { // reset the head node to the next link this->m_pTasks[linkIndex] = NULL; this->m_pLinks[0] = this->m_pLinks[linkIndex]; this->m_pLinks[linkIndex] = 0; } } ::LeaveCriticalSection(&this->m_pLock); return task; } void CTaskPool::PushTask(CTask* task) { bool inserted; bool linked; unsigned i, linkIndex, storeIndex; CTask* cTask; if(this->m_iState < TASKPOOL_STATE_INITIALIZED) throw SingularityException("Tasks cannot be added to the pool until it is initialized."); ::EnterCriticalSection(&this->m_pLock); { inserted = false; linked = false; for(i = 0, linkIndex = 0; i < SINGULARITY_TASKS_MAX_TASKS; i++) { if(!(inserted || this->m_pTasks[i])) { // mark as inserted inserted = true; // save where we stuck the object storeIndex = i; } if(!linked) { cTask = this->m_pTasks[linkIndex]; // link before longer executing tasks if(!cTask || cTask->m_eState != TaskState::Ready || cTask->Get_EstimatedExecutionTime() > task->Get_EstimatedExecutionTime() || !this->m_pLinks[linkIndex]) { // mark as linked linked = true; } else { // move to the next index in the list linkIndex = this->m_pLinks[linkIndex]; } } // kick out of the loop if you both found a spot and linked the node if(linked && inserted) { this->m_pLinks[storeIndex] = this->m_pLinks[linkIndex]; this->m_pLinks[linkIndex] = storeIndex; this->m_pTasks[storeIndex] = task; break; } } } ::LeaveCriticalSection(&this->m_pLock); } #pragma endregion #pragma region Static Methods unsigned CTaskPool::GetHardwareThreadsCount() { SYSTEM_INFO si; ::GetSystemInfo(&si); return si.dwNumberOfProcessors; } #pragma endregion } }
#ifdef FASTCG_OPENGL #include <FastCG/Graphics/OpenGL/OpenGLUtils.h> #include <FastCG/Graphics/OpenGL/OpenGLTexture.h> #include <FastCG/Graphics/OpenGL/OpenGLExceptions.h> namespace FastCG { OpenGLTexture::OpenGLTexture(const Args &rArgs) : BaseTexture(rArgs) { auto target = GetOpenGLTarget(mType); auto filter = GetOpenGLFilter(mFilter); auto wrapMode = GetOpenGLWrapMode(mWrapMode); auto internalFormat = GetOpenGLInternalFormat(mFormat, mBitsPerChannel, mDataType); auto format = GetOpenGLFormat(mFormat); glGenTextures(1, &mTextureId); glBindTexture(target, mTextureId); #ifdef _DEBUG { std::string textureLabel = GetName() + " (GL_TEXTURE)"; glObjectLabel(GL_TEXTURE, mTextureId, (GLsizei)textureLabel.size(), textureLabel.c_str()); } #endif glTexParameteri(target, GL_TEXTURE_MIN_FILTER, filter); glTexParameteri(target, GL_TEXTURE_MAG_FILTER, filter); glTexParameteri(target, GL_TEXTURE_WRAP_S, wrapMode); glTexParameteri(target, GL_TEXTURE_WRAP_T, wrapMode); glTexParameteri(target, GL_TEXTURE_WRAP_R, wrapMode); if (IsDepthFormat(mFormat)) { glTexParameteri(target, GL_TEXTURE_COMPARE_MODE, GL_NONE); } glTexImage2D(target, 0, internalFormat, (GLsizei)mWidth, (GLsizei)mHeight, 0, format, GetOpenGLDataType(mFormat, mBitsPerChannel), rArgs.pData); if (rArgs.generateMipmap) { glGenerateMipmap(target); } FASTCG_CHECK_OPENGL_ERROR(); } OpenGLTexture::~OpenGLTexture() { if (mTextureId != ~0u) { glDeleteTextures(1, &mTextureId); } } } #endif
#include <pthread.h> #include <vector> #include <cstdio> #include <cstring> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/types.h> #include <sys/time.h> #include <errno.h> std::vector<pthread_mutex_t> mutex_gather(3, (pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER); //default: use backoff; others: don't use int backoff = 1; //default: don't interferring any thread; >0: use sched_yield(); <0: sleep(1) int yield_flag = 0; //iterate ITERATOR times const int ITERATOR = 10; char *get_time_now() { time_t now; time(&now); tm *time_now; time_now = localtime(&now); char *tmp = asctime(time_now); tmp[strlen(tmp) - 2] = 0; return tmp; } void backoff_algorithm(int direction) { int fd; if(direction == 1) fd = open("forward_thread.log", O_WRONLY | O_CREAT); else fd = open("backward_thread.log", O_WRONLY | O_CREAT), direction = 2; FILE *file_pointer[3] = {stdin, stdout, stderr}; FILE *fp = file_pointer[direction]; if(dup2(fd, direction) != direction) { fprintf(fp, "%s: dup2 %d error \n", get_time_now(), direction); pthread_exit(NULL); } if(direction == 1) { for(int tm = 0; tm < ITERATOR; ++tm) { int backoffs = 0; fprintf(fp, "%s:----------------- round %d start ---------------\n", get_time_now(), tm); for(int forward_iter = 0; forward_iter < mutex_gather.size(); ++forward_iter) { int status; if(forward_iter == 0) { status = pthread_mutex_lock(&(mutex_gather[forward_iter])); if(status) { fprintf(fp, "%s, error occurs when lock %d mutex\n", get_time_now(), forward_iter + 1); pthread_exit(NULL); } continue; } if(backoff != 1) status = pthread_mutex_lock(&(mutex_gather[forward_iter])); else status = pthread_mutex_trylock(&(mutex_gather[forward_iter])); if(status == EBUSY) { ++backoffs; fprintf(fp, "%s: backoff occurs\n", get_time_now()); for(; forward_iter >= 0; --forward_iter) { pthread_mutex_unlock(&mutex_gather[forward_iter]); } } else { if(status) { fprintf(fp, "%s, error occurs when lock %d mutex\n", get_time_now(), forward_iter + 1); pthread_exit(NULL); } } if(yield_flag > 0) sched_yield(); else if(yield_flag < 0) sleep(1); } pthread_mutex_unlock(&mutex_gather[0]); pthread_mutex_unlock(&mutex_gather[1]); pthread_mutex_unlock(&mutex_gather[2]); fprintf(fp, "%s: release all locks, %d backoffs occured\n", get_time_now(), backoffs); fprintf(fp, "%s:----------------- round %d end -----------------\n", get_time_now(), tm); sched_yield(); } } else { for(int tm = 0; tm < ITERATOR; ++tm) { int backoffs = 0; fprintf(fp, "%s:----------------- round %d start ---------------\n", get_time_now(), tm); for(int backward_iter = mutex_gather.size() - 1; backward_iter >= 0; --backward_iter) { int status; if(backward_iter == mutex_gather.size() - 1) { status = pthread_mutex_lock(&(mutex_gather[backward_iter])); if(status) { fprintf(fp, "%s, error occurs when lock %d mutex\n", get_time_now(), backward_iter + 1); pthread_exit(NULL); } continue; } if(backoff != 1) status = pthread_mutex_lock(&(mutex_gather[backward_iter])); else status = pthread_mutex_trylock(&(mutex_gather[backward_iter])); if(status == EBUSY) { ++backoffs; fprintf(fp, "%s: backoff occurs\n", get_time_now()); for(; backward_iter < mutex_gather.size(); ++backward_iter) { pthread_mutex_unlock(&mutex_gather[backward_iter]); } } else { if(status) { fprintf(fp, "%s, error occurs when lock %d mutex\n", get_time_now(), backward_iter + 1); pthread_exit(NULL); } } if(yield_flag > 0) sched_yield(); else if(yield_flag < 0) sleep(1); } pthread_mutex_unlock(&mutex_gather[0]); pthread_mutex_unlock(&mutex_gather[1]); pthread_mutex_unlock(&mutex_gather[2]); fprintf(fp, "%s: release all locks, %d backoffs occured\n", get_time_now(), backoffs); fprintf(fp, "%s:----------------- round %d end -----------------\n", get_time_now(), tm); sched_yield(); } } close(fd); return; } void * forward_lock(void *arg) { backoff_algorithm(2); return NULL; } int main(int argc, char ** argv) { int opt; while((opt = getopt(argc, argv, "b:y:")) != -1) { switch(opt) { case 'b': sscanf(optarg, "%d", &backoff); break; case 'y': sscanf(optarg, "%d", &yield_flag); break; } } printf("%d %d\n", backoff, yield_flag); pthread_t forward_locker; pthread_create(&forward_locker, NULL, forward_lock, NULL); backoff_algorithm(1); pthread_join(forward_locker, NULL); return 0; }
#pragma once #include "BlockHandler.h" #include "Entities/Pickup.h" class cBlockLilypadHandler : public cClearMetaOnDrop<cBlockHandler> { typedef cClearMetaOnDrop<cBlockHandler> super; public: cBlockLilypadHandler(BLOCKTYPE a_BlockType) : super(a_BlockType) { } virtual bool CanBeAt(cChunkInterface & a_ChunkInterface, int a_RelX, int a_RelY, int a_RelZ, const cChunk & a_Chunk) override { return ((a_RelY > 0) && ((a_Chunk.GetBlock(a_RelX, a_RelY - 1, a_RelZ) == E_BLOCK_STATIONARY_WATER) || (a_Chunk.GetBlock(a_RelX, a_RelY - 1, a_RelZ) == E_BLOCK_WATER))); } virtual ColourID GetMapBaseColourID(NIBBLETYPE a_Meta) override { UNUSED(a_Meta); return 7; } virtual bool CanBeAt(cChunkInterface & a_ChunkInterface, int a_RelX, int a_RelY, int a_RelZ, const cChunk & a_Chunk) override { return ((a_RelY > 0) && ((a_Chunk.GetBlock(a_RelX, a_RelY - 1, a_RelZ) == E_BLOCK_STATIONARY_WATER) || (a_Chunk.GetBlock(a_RelX, a_RelY - 1, a_RelZ) == E_BLOCK_WATER))); } };
/** * * @file HumanoidFootprintManager.cpp * @author Naoki Takahashi * **/ #include "HumanoidFootprintManager.hpp" #include <stdexcept> #include "ConfigManager.hpp" #include "FootprintPlanner/ConstantRangeBasedHumanoid.hpp" #include "FootprintPlanner/CustomHumanoid.hpp" namespace FootStepPlanner { template <typename Scalar> HumanoidFootprintManager<Scalar>::HumanoidFootprintManager() { footprint_plan_selector = Selector::make_ptr(); if(!footprint_plan_selector) { throw std::runtime_error("Failed make ptr for footprint_plan_selector from FootStepPlanner::HumanoidFootprintManager"); } register_default_footprint_planners(); } template <typename Scalar> HumanoidFootprintManager<Scalar>::~HumanoidFootprintManager() { } template <typename Scalar> typename HumanoidFootprintManager<Scalar>::Ptr HumanoidFootprintManager<Scalar>::make_ptr() { return std::make_unique<HumanoidFootprintManager>(); } template <typename Scalar> void HumanoidFootprintManager<Scalar>::register_footprint_planner(const typename Selector::Key &key, PlannerPtr planner_ptr) { if(!footprint_plan_selector) { throw std::runtime_error("Can not access to footprint_plan_selector from FootStepPlanner::HumanoidFootprintManager"); } footprint_plan_selector->register_planner( key, std::move(planner_ptr) ); } template <typename Scalar> bool HumanoidFootprintManager<Scalar>::is_registered_footprint_planner(const typename Selector::Key &key) { if(!footprint_plan_selector) { throw std::runtime_error("Can not access to footprint_plan_selector from FootStepPlanner::HumanoidFootprintManager"); } return footprint_plan_selector->is_registered(key); } template <typename Scalar> void HumanoidFootprintManager<Scalar>::choice_footprint_planner(const std::string &config_file_name) { if(footprint_planner) { throw std::runtime_error("Already choice footprint planner from FootStepPlanner::HumanoidFootprintManager"); } if(!footprint_plan_selector) { throw std::runtime_error("Can not access to footprint_plan_selector from FootStepPlanner::HumanoidFootprintManager"); } ConfigManager config_manager(config_file_name); const auto choice_key = config_manager.get_value<typename Selector::Key>("Humanoid.Use plan"); if(!is_registered_footprint_planner(choice_key)) { throw std::runtime_error("Not registered " + choice_key + " from FootStepPlanner::HumanoidFootprintManager"); } footprint_planner = std::move(footprint_plan_selector->get_planner(choice_key)); if(!footprint_planner) { throw std::runtime_error("Failed move footprint_planner from FootStepPlanner::HumanoidFootprintManager"); } footprint_plan_selector.reset(); footprint_planner->config(config_file_name); } template <typename Scalar> void HumanoidFootprintManager<Scalar>::set_goal(const typename Planner::Vector &point, const typename Planner::EulerAngles &eularangles) { if(!footprint_planner) { throw std::runtime_error("Can not access to footprint_planner from FootStepPlanner::HumanoidFootprintManager"); } footprint_planner->set_goal(point, eularangles); } template <typename Scalar> void HumanoidFootprintManager<Scalar>::set_goal(const Scalar &x, const Scalar &y, const Scalar &z, const Scalar &roll, const Scalar &pitch, const Scalar &yaw) { if(!footprint_planner) { throw std::runtime_error("Can not access to footprint_planner form FootStepPlanner::HumanoidFootprintManager"); } footprint_planner->set_goal(x, y, z, roll, pitch, yaw); } template <typename Scalar> void HumanoidFootprintManager<Scalar>::set_begin(const typename Planner::Vector &point, const typename Planner::EulerAngles &eularangles) { if(!footprint_planner) { throw std::runtime_error("Can not access to footprint_planner from FootStepPlanner::HumanoidFootprintManager"); } footprint_planner->set_begin(point, eularangles); } template <typename Scalar> void HumanoidFootprintManager<Scalar>::set_begin(const Scalar &x, const Scalar &y, const Scalar &z, const Scalar &roll, const Scalar &pitch, const Scalar &yaw) { if(!footprint_planner) { throw std::runtime_error("Can not access to footprint_planner form FootStepPlanner::HumanoidFootprintManager"); } footprint_planner->set_begin(x, y, z, roll, pitch, yaw); } template <typename Scalar> void HumanoidFootprintManager<Scalar>::make_full_footprint() { if(!footprint_planner) { throw std::runtime_error("Can not access to footprint_planner from FootStepPlanner::HumanoidFootprintManager"); } footprint_planner->full_step(); } template <typename Scalar> typename HumanoidFootprintManager<Scalar>::Planner::FootprintList HumanoidFootprintManager<Scalar>::get_footprint_list() { if(!footprint_planner) { throw std::runtime_error("Can not access to footprint_planner from FootStepPlanner::HumanoidFootprintManager"); } return footprint_planner->get_footprint_list(); } template <typename Scalar> void HumanoidFootprintManager<Scalar>::register_default_footprint_planners() { footprint_plan_selector->register_planner( FootprintPlanner::ConstantRangeBasedHumanoid<Scalar>::get_key(), std::move(FootprintPlanner::ConstantRangeBasedHumanoid<Scalar>::make_ptr()) ); footprint_plan_selector->register_planner( FootprintPlanner::CustomHumanoid<Scalar>::get_key(), std::move(FootprintPlanner::CustomHumanoid<Scalar>::make_ptr()) ); } template class HumanoidFootprintManager<float>; template class HumanoidFootprintManager<double>; }
class Solution { public: double angleClock(int hour, int minutes) { // hour hand, referred to 00 double h = (hour % 12) + minutes / 60.0; // NOTE, 60.0 double hangle = 360.0 / 12 * h; double mangle = 360.0 / 60 * minutes; double angle = abs(mangle - hangle); return (angle <= 180) ? angle : (360 - angle); } };
#include "stdafx.h" #include "StandardCard.h" StandardCard::StandardCard() { } StandardCard::~StandardCard() { }
class Solution { public: int rangeBitwiseAnd(int m, int n) { int diff = n - m; int i = 0; while (diff > 0) { diff /= 2; i++; } return n & ((m >> i ) << i); } };
#include<iostream> using namespace std; // 构造函数调用规则: // 默认情况下c++编译器至少给一个类添加三个函数 // 1.默认构造函数(无参,函数体为空) // 2.默认析构函数(无参,函数体为空) // 3.默认拷贝函数,对属性进行值拷贝 // 规则 // 1.如果用户定义有参构造函数,c++不再提供默认无参构造,但是会提供默认拷贝构造。 // 2.如果用户定义拷贝构造函数。c++不会再提供其他普通构造函数 class Person { public: //无参(默认构造函数) Person() { cout<<"默认构造函数"<<endl; } ~Person() { cout<<"析构函数调用"<<endl; } Person(int age) { m_age = age; cout<<"有参构造函数"<<endl; } // 如果用户定义有参构造函数,c++不再提供默认无参构造,但是会提供默认拷贝构造,对属性进行值拷贝 // Person(const Person & p) // { // m_age = p.m_age; // cout<<"Person拷贝构造函数"<<endl; // } int m_age; }; void test01() { Person p1; p1.m_age = 10; Person p2(p1); cout<<p2.m_age<<endl; } void test02() { Person p3(00); Person p4(p3); cout<<p4.m_age<<endl; } int main() { cout<<"aaa"<<endl; test01(); test02(); return 0; }
#include "../inc.h" /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *rotateRight(ListNode *head, int k) { if(!head || !head->next || k <= 0) return head; ListNode * t; for(;;){ t = head; int sz = 0; for(;sz < k && t;++sz) t = t->next; if(t) break; assert(sz > 0); k %= sz; if(!k) return head; } ListNode * p = head; assert(t); while(t->next){ p = p->next; t = t->next; } t->next = head; head = p->next; p->next = NULL; return head; } }; class Solution2 { public: ListNode *rotateRight(ListNode *head, int k) { if(!head || !k) return head; ListNode * tail = head; for(int i = 1;i <= k;++i){ tail = tail->next; if(!tail) return rotateRight(head, k % i); } ListNode * cur = head; for(;tail->next;cur = cur->next, tail = tail->next); tail->next = head; head = cur->next; cur->next = NULL; return head; } }; int main() { ListNode n1(1), n2(2); n1.next = &n2; print(Solution().rotateRight(&n1, 2)); }
#include<bits/stdc++.h> using namespace std; void solve2(vector<int>& top,int target,int& max_value,int cur,int index) { if(cur > target) { return ; } if(index==top.size()) { if(cur > max_value) { max_value = cur; } return ; } solve2(top,target,max_value,cur,index+1); solve2(top,target,max_value,cur+top[index],index+1); return ; } int solve(vector<int>& base,vector<int>& top,int n,int target) { int max_value2 = INT_MIN; for(int i=0;i<n;i++) { if(base[i] > target) { continue; } int max_value = INT_MIN; solve2(top,target-base[i],max_value,0,0); //cout <<max_value << endl; max_value2 = max(max_value2,max_value+base[i]); } return max_value2; } int main() { int n,m; cin >> n >> m; vector<int> base(n); vector<int> top(2*m); for(int i=0;i<n;i++) { cin >> base[i]; } for(int i=0;i<m;i++) { int a; cin >> a; top.push_back(a); top.push_back(a); } int target; cin >> target; cout << solve(base,top,n,target) << endl; }
//$Id$ //------------------------------------------------------------------------------ // DataBucket //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool // // Copyright (c) 2002 - 2015 United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. // All Other Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.apache.org/licenses/LICENSE-2.0. // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // express or implied. See the License for the specific language // governing permissions and limitations under the License. // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under the FDSS II // contract, Task Order 08 // // Author: Darrel J. Conway, Thinking Systems, Inc. // Created: Jul 20, 2016 /** * Helper class used to collect data to be written using a DataWriter */ //------------------------------------------------------------------------------ #ifndef DataBucket_hpp #define DataBucket_hpp #include "gmatdefs.hpp" /** * A generic container used to store data for use by a DataWriter * * All members here are public to facilitate fast access */ class GMAT_API DataBucket { public: DataBucket(); virtual ~DataBucket(); DataBucket(const DataBucket& db); DataBucket& operator=(const DataBucket& db); Integer AddRealContainer(const std::string &name); Integer FindRealContainer(const std::string &name); Integer AddStringContainer(const std::string &name); Integer FindStringContainer(const std::string &name); Integer AddPoint(); void Clear(); /// Vector to track state for the data, so empty elements can be detected RealArray elementStatus; /// Names of the real data collected StringArray realNames; /// The real data std::vector<RealArray> realValues; /// Names of the string data collected StringArray stringNames; /// The string data std::vector<StringArray> stringValues; bool fillToMatch; }; #endif /* DataBucket_hpp */
// // Created by Peter Chen on 5/29/16. // #include "CWVisualDefinition.h" using namespace CubeWorld; CWVisualDefinition::CWVisualDefinition() { } CWVisualDefinition::~CWVisualDefinition() { } void CWVisualDefinition::Serialize(Serializer serializer) { }
#ifndef LZ78C_H #define LZ78C_H #include "Compressor.h" #include "HashTable.h" class LZ78C : public Compressor { public: LZ78C(FILE* output, int compressionLevel); protected: void feedRawByte(Byte arg); void onClosing(); private: HashTable* hashTable; int dictionarySize; int currentNode; int dictionaryMaxSize; vector<Byte> sequence; void encodeAndWrite(int arg); }; #endif
///CSE50-Data Communication Project ///Selective Reject CRC-16 Implementation ///Author: Razwan Ahmed Tanvir ///Email: razwantanvir8050@gmail.com ///================================================================================================================ ///================================================================================================================ #include<bits/stdc++.h> #include<windows.h> using namespace std; #define DATA_LENGTH 500 #define P 11000000000000101 #define WINDOW_LENGTH 4 #define FCS_BIT 16 #define FRAME_SEQUENCE_NO_RANGE 8 #define SEQUENCE_BIT 1 #define FRAME_LENGTH 50 #define DATA_BIT_PER_FRAME FRAME_LENGTH-SEQUENCE_BIT #define NO_OF_FRAME ((int)(DATA_LENGTH)/((DATA_BIT_PER_FRAME))+1) #define FRAME_DAMAGE 2 #define FRAME_LOST 1 #define SUCCESS 0 struct FRAME { int sequence_no ; int data_in_frame[DATA_BIT_PER_FRAME+FCS_BIT]; //int fcs ; }dummy; //GLOBAL VARIABLES HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); int DATA_STREAM[DATA_LENGTH]; FRAME frame[NO_OF_FRAME]; int read_data_stream = 0; queue <FRAME> frame_queue; queue <FRAME> Source; queue <FRAME> Destination ; queue <FRAME> FramesInDestination; stack <int>NAK_stack ; FRAME log_sent_frame[NO_OF_FRAME]; int sent_frame_counter = 0; int processed_frame_by_destination[100000]; stack <FRAME> sent_frames_by_source; stack <int> recent_ack ; bool STOP = false ; int counter_procesed_frame = 0; int seq_counter = 0; void color (unsigned short v) { /// color function HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(hcon, v); } void initialize_data_stream(){ for(int i=0;i<DATA_LENGTH;i++){ DATA_STREAM[i] = -1; } } void generate_data(){ for(int i=0;i<DATA_LENGTH ;i++){ DATA_STREAM[i] = rand()%2; } } void show_data_stream () { cout<<"Given Data Stream: "<<endl; for(int i=0;i<DATA_LENGTH;i++){ if(i%(int)(DATA_BIT_PER_FRAME)==0 && i!=0){ cout<<endl; } cout<<DATA_STREAM[i]; } cout<<endl; } void showProcessedFramesByDestination(){ cout<<"CONNECTION STATS:"<<endl; cout<<"============================================================================"<<endl; cout<<"Processed frames by destination:"; for(int i=0;i<seq_counter;i++){ cout<<processed_frame_by_destination[i]<<" "; } cout<<endl; color(10); cout<<endl<<"Total frames received="<<seq_counter<<endl<<endl; cout<<"=============================================================================="<<endl; color(4); cout<<"Disconnecting with source"; for(int dot=0;dot<5;dot++){ cout<<"."; Sleep(500); } color(10); cout<<endl<<endl<<"Process terminated successfully!"<<endl; color(7); } void initialize_frame(FRAME f){ f.sequence_no = -1; for(int i=0;i<DATA_BIT_PER_FRAME;i++){ f.data_in_frame[i] = -1 ; } } void set_sequence(FRAME *f , int seq_no) { //cout<<"calling set sequence"<<endl; //cout<<"set_seq: "<<seq_no<<endl; f->sequence_no = seq_no % FRAME_SEQUENCE_NO_RANGE ; } void get_fcs(FRAME *f){ int i,j,keylen,msglen,fcs = 0; char input[1000], key[300],temp[300],quot[1000],rem[300],key1[300],tempKey[300]; for(int i=0;i<DATA_BIT_PER_FRAME;i++){ if(f->data_in_frame[i]==0){ input[i]='0'; } else{ input[i]='1'; } } input[DATA_BIT_PER_FRAME] = '\0'; int len_input = strlen(input); //P 16 bit pre determined divisor value 11000000000000101 key[0] = '1' ; key[1] = '1' ;key[2] ='0' ;key[3] = '0' ;key[4] = '0' ;key[5] ='0' ;key[6] = '0' ;key[7] ='0' ; key[8] ='0' ;key[9] = '0' ;key[10] = '0';key[11] ='0' ;key[12] ='0' ;key[13] ='0' ;key[14] = '1' ;key[15] = '0' ;key[16] = '1' ;key[17] = '\0' ; //key[++keycounter] = '\0' ; //cout<<"Key value(P):"<<key<<endl; keylen=/*strlen(key)*/ 17; //size of P //cout<<"Keylen:"<<keylen<<endl; msglen=strlen(input); strcpy(key1,key); for (i=0;i<keylen-1;i++) { input[msglen+i]='0'; } for (i=0;i<keylen;i++) temp[i]=input[i]; for (i=0;i<msglen;i++) { quot[i]=temp[0]; if(quot[i]=='0'){ for (j=0;j<keylen;j++) key[j]='0'; } else{ for (j=0;j<keylen;j++) key[j]=key1[j]; } for (j=keylen-1;j>0;j--) { if(temp[j]==key[j]) rem[j-1]='0'; else rem[j-1]='1'; } rem[keylen-1]=input[i+keylen]; strcpy(temp,rem); } strcpy(rem,temp); for (i=0;i<keylen-1;i++){ //printf("%c",rem[i]); int multiplier = 100; if(rem[i]=='1'){ fcs += 1*multiplier ; multiplier /= 10; } else{ fcs += 0*multiplier ; multiplier /= 10; } } int save_i ; for(int i=0;i<len_input;i++){ if(input[i]=='1') f->data_in_frame[i] = 1; else f->data_in_frame[i] = 0 ; save_i = i; } for(int i=save_i+1,j=0;i<save_i+keylen;i++,j++){ if(rem[j]=='1') f->data_in_frame[i] = 1; else f->data_in_frame[i] = 0; } } ///getting the remainder of a frame int check_error(FRAME *f){ int i,j,keylen,msglen,fcs = 0; char input[10000], key[300],temp[300],quot[1000],rem[300],key1[300],tempKey[300]; for(int i=0;i<DATA_BIT_PER_FRAME+FCS_BIT;i++){ if(f->data_in_frame[i]==0){ input[i]='0'; } else{ input[i]='1'; } } input[DATA_BIT_PER_FRAME+FCS_BIT] = '\0'; int len_input = strlen(input); key[0] = '1' ; key[1] = '1' ;key[2] ='0' ;key[3] = '0' ;key[4] = '0' ;key[5] ='0' ;key[6] = '0' ;key[7] ='0' ; key[8] ='0' ;key[9] = '0' ;key[10] = '0';key[11] ='0' ;key[12] ='0' ;key[13] ='0' ;key[14] = '1' ;key[15] = '0' ;key[16] = '1' ;key[17] = '\0' ; //key[++keycounter] = '\0' ; //cout<<"Key value(P):"<<key<<endl; keylen=/*strlen(key)*/ 17; //cout<<"Keylen:"<<keylen<<endl; msglen=strlen(input); //cout<<"msglen:"<<msglen<<endl; strcpy(key1,key); for (i=0;i<keylen-1;i++) { input[msglen+i]='0'; } for (i=0;i<keylen;i++) temp[i]=input[i]; for (i=0;i<msglen;i++) { quot[i]=temp[0]; if(quot[i]=='0') for (j=0;j<keylen;j++) key[j]='0'; else for (j=0;j<keylen;j++) key[j]=key1[j]; for (j=keylen-1;j>0;j--) { if(temp[j]==key[j]) rem[j-1]='0'; else rem[j-1]='1'; } rem[keylen-1]=input[i+keylen]; strcpy(temp,rem); } strcpy(rem,temp); for (i=0;i<keylen-1;i++){ //printf("%c",rem[i]); int multiplier = 100; if(rem[i]=='1'){ fcs += 1*multiplier ; multiplier /= 10; } else{ fcs += 0*multiplier ; multiplier /= 10; } } //cout<<"FCS value:"<<fcs<<endl; return fcs ; } void set_data(FRAME *f , int i){ bool val = true; for(int j=0;j<DATA_BIT_PER_FRAME;j++){ f->data_in_frame[j] = DATA_STREAM[read_data_stream++]; if(read_data_stream>DATA_LENGTH){ //f->data_in_frame[j] =-1; //val = false ; //return; } } get_fcs(f); } void generate_frames(){ for(int i=0;i<NO_OF_FRAME;i++){ //initialize_frame(frame[i]); set_sequence(&frame[i], i ); set_data(&frame[i],i); frame_queue.push(frame[i]); } } void ShowAllFrames (){ for(int i=0;i<NO_OF_FRAME;i++){ cout<<"Sequence No:"<<frame[i].sequence_no<<endl; cout<<"Data in frame "<<i<<":"; for(int j = 0;j<DATA_BIT_PER_FRAME && frame[i].data_in_frame[i]!=-1;j++){ cout<<frame[i].data_in_frame[j]; } //cout<<"FCS:"<<frame[i].fcs; cout<<endl; } cout<<endl<<endl<<endl; } void ShowFrameQueue() { queue <FRAME> temp ; temp = frame_queue; while(!temp.empty()){ // FRAME f = cout<<temp.front().sequence_no<<"->" ; for(int i=0;i<DATA_BIT_PER_FRAME+FCS_BIT && temp.front().data_in_frame[i]!=-1;i++){ cout<<temp.front().data_in_frame[i]; } //cout<<"("<<temp.front().fcs<<")"; temp.pop(); cout<<endl; } } void initialize_log_sent_frame(){ for(int i=0;i<NO_OF_FRAME;i++){ log_sent_frame[i] = dummy ; } } int propagation_state(FRAME *f){ int value = rand()%10 ; /*if(value<1){ return FRAME_LOST;//frame lost }*/ int value2 = rand()%10; if(value2<3){ return FRAME_DAMAGE ; //frame damaged } return SUCCESS; } void introduce_damage(FRAME *f){ int value = rand()%((int)(DATA_BIT_PER_FRAME/10)); int select_position_to_damage; for(int i=0;i<value;i++){ select_position_to_damage = rand()%20 ; f->data_in_frame[select_position_to_damage] = (-(~f->data_in_frame[select_position_to_damage]))%2 ; } } void send_nak_frame(){ int seq = NAK_stack.top(); cout<<"SOURCE: "<<"Frame "<<seq<<" Sending again."<<endl; NAK_stack.pop(); stack<FRAME> temp; temp = sent_frames_by_source ; for(int i=0;temp.size()!=0;i++){ //cout<<"Send NAK LOOP"<<endl; if(temp.top().sequence_no==seq){ //cout<<"Sending the frame "<<temp.top().sequence_no<<" to destination."<<endl; Destination.push(temp.top()); //cout<<"Frame "<<temp.top().sequence_no<<" Pushed in Destination."<<endl; break; } temp.pop(); } } bool received_NAK(){ if(NAK_stack.size()!=0){ //cout<<"NAK received"<<endl; return true; } return false ; } void SendFrameFromSource() { FRAME temp; if(received_NAK()){ color(6); cout<<"SOURCE: "<<"NAK "<<NAK_stack.top()<<" received by source."<<endl; color(7); send_nak_frame(); } else{ temp = Source.front(); Source.pop(); sent_frames_by_source.push(temp); if(temp.sequence_no==-1){ return; } cout<<"SOURCE: "<<"Frame "<<temp.sequence_no<<" left source!"<<endl; switch(propagation_state(&temp)) { case FRAME_DAMAGE: introduce_damage(&temp); Destination.push(temp); //cout<<"Damaged frame received"<<endl; break; /*case FRAME_LOST: //cout<<"Lost frame!"<<endl; break;*/ case SUCCESS: Destination.push(temp); //cout<<"Frame "<<temp.sequence_no<<" pushed in destination!"<<endl; break; default: cout<<"Somthing is going wrong here."<<endl; break; } } } void ShowSourceFrames(){ queue <FRAME> temp ; temp = Source; cout<<"Showing frames in source:"<<endl ; while(!temp.empty()){ cout<<temp.front().sequence_no<<"->" ; for(int i=0;i<DATA_BIT_PER_FRAME+FCS_BIT && temp.front().data_in_frame[i]!=-1;i++){ cout<<temp.front().data_in_frame[i]; } temp.pop(); cout<<endl; } cout<<endl<<endl; } void ShowDestinationFrames(){ queue <FRAME> temp ; temp = FramesInDestination; cout<<endl<<endl<<"Showing reached frames in Destination:"<<endl; while(!temp.empty()){ cout<<temp.front().sequence_no<<"->" ; for(int i=0;i<DATA_BIT_PER_FRAME && temp.front().data_in_frame[i]!=-1;i++){ cout<<temp.front().data_in_frame[i]; } temp.pop(); cout<<endl; } cout<<endl<<endl; } void config_source(){ generate_frames(); Source = frame_queue ; //inserting the frames in source } void send_ACK(int ack_no){ recent_ack.push(ack_no) ; } void process_frame(){ //cout<<"IN PROCESSING FRAME FUNCTION"<<endl; queue <FRAME> temp ; FRAME received_frame ; temp = Destination ; int recent_frame_seq; int que_size = Destination.size(); if(que_size!=0){ received_frame= Destination.front(); Destination.pop(); // prev temp.front recent_frame_seq = received_frame.sequence_no; //cout<<"Processing the frame:"<<recent_frame_seq<<endl; if(check_error( &received_frame)==0 ){ color(10); FramesInDestination.push(received_frame); cout<<"DESTINATION: "<<"Processed the received frame("<<received_frame.sequence_no<<")"<<endl<<endl<<endl; color(7); counter_procesed_frame++; if(counter_procesed_frame==WINDOW_LENGTH){ send_ACK((recent_frame_seq+1)%FRAME_SEQUENCE_NO_RANGE); counter_procesed_frame=0; } int serial = abs(processed_frame_by_destination[seq_counter]-recent_frame_seq) ; processed_frame_by_destination[seq_counter++] = recent_frame_seq ; ///edit this field //sent_frame_counter-- ; } else{ color(4); cout<<"DESTINATION: "<<"Got a damaged frame("<<recent_frame_seq<<")!"<<endl; NAK_stack.push(recent_frame_seq); cout<<"DESTINATION: "<<"NAK for frame "<<recent_frame_seq<<" sent to source."<<endl; color(7); } } } void start_connection(){ for(int i=0; Source.size()!=0 ;i++){ if(recent_ack.size()!=0){ color(6); cout<<"SOURCE: "<<"ACK "<<recent_ack.top()<<" received!"<<endl; color(7); recent_ack.pop(); } else{ SendFrameFromSource(); //sent_frame_counter++ ; } process_frame(); } } int main() { processed_frame_by_destination[seq_counter] = 1; dummy.sequence_no = -1 ; cout<<"Configuring Source and Destination"; for(int dot=0;dot<5;dot++){ cout<<"."; Sleep(500); } cout<<endl; cout<<"No of frame:"<<NO_OF_FRAME<<endl<<endl<<endl; srand(time(NULL)); generate_data(); show_data_stream(); initialize_frame(dummy); config_source(); //Source.push(dummy); start_connection(); ShowDestinationFrames(); color(10); showProcessedFramesByDestination(); color(7); }
#include<bits/stdc++.h> using namespace std; void replaceSpace(char *str,int length) { char ch[200]; int k = 0; for (int i = 0; i < length; i++) { if(str[i] != ' ') ch[k++] = str[i]; else { ch[k++] = '%'; ch[k++] = '2'; ch[k++] = '0'; } } ch[k] = '\0'; strcpy(str,ch); } int main() { int n; cin >> n; getchar(); while(n--) { char ch[100]; gets(ch); replaceSpace(ch,strlen(ch)); cout << ch << endl; } return 0; }
#include "ParseHelper.h" #include <string> #include <vector> #include <iostream> #include <sstream> void ParseVector( const std::string s , float* v ) { std::vector<std::string> elements; std::stringstream ss( s ); std::string item; while ( std::getline( ss , item , ',' ) ) { elements.push_back( item ); } for ( int i = 0; i < elements.size(); i++ ) { v[i] = atof( elements[i].c_str() ); } }
/* HC-SR04 Ping distance sensor: VCC to arduino 5v GND to arduino GND Echo to Arduino pin 7 Trig to Arduino pin 8 This sketch originates from Virtualmix: http://goo.gl/kJ8Gl Has been modified by Winkle ink here: http://winkleink.blogspot.com.au/2012/05/arduino-hc-sr04-ultrasonic-distance.html And modified further by ScottC here: http://arduinobasics.blogspot.com.au/2012/11/arduinobasics-hc-sr04-ultrasonic-sensor.html on 10 Nov 2012. */ #include <LiquidCrystal.h> #include <LCDKeypad.h> #define echoPin 25 // Echo Pin #define trigPin 24 // Trigger Pin //#define LEDPin 13 // Onboard LED //#define m1 10 byte c_heart[8] = { B00000, B00000, B01010, B11111, B11111, B01110, B00100, B00000, }; LCDKeypad lcd; int maximumRange = 400; // Maximum range needed int minimumRange = 0; // Minimum range needed long duration, distance, brightness; // Duration used to calculate distance int i; int mode = 0; int led = 44; void setup() { lcd.createChar(1,c_heart); lcd.begin(16, 2); lcd.clear(); lcd.print("Waiting for you..."); Serial.begin (9600); pinMode(trigPin, OUTPUT); //pinMode(m1, OUTPUT); pinMode(echoPin, INPUT); pinMode(led, OUTPUT); } void loop() { /* The following trigPin/echoPin cycle is used to determine the distance of the nearest object by bouncing soundwaves off of it. */ digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); //Calculate the distance (in cm) based on the speed of sound. distance = duration/58.2; if (distance >= 3 && distance <= 100){ brightness = 255 - distance*2; analogWrite(led, brightness); Serial.println(brightness); if(mode == 0) { mode = 1; lcd.clear(); for(i=0;i<16;i++) { lcd.write(1); } lcd.print("Happy Birthday!"); delay(2000); for(i=0;i<16;i++) { lcd.scrollDisplayLeft(); delay(100); } } } else { if(mode == 1) { analogWrite(led, 0); mode = 0; lcd.clear(); lcd.print("Waiting for you..."); } } //Delay 50ms before next reading. delay(50); }
#include "KoreanMessage.h" #include "EnglishMessage.h" #include "LanguageImpl.h" #include <iostream> int main(int argc, char *argv[]) { std::shared_ptr<Message> korean_message = std::make_shared<KoreanMessage>(); std::shared_ptr<Message> english_message = std::make_shared<EnglishMessage>(); std::shared_ptr<Language> langauge = std::make_shared<LanguageImpl>(korean_message); std::cout << langauge->execute() << std::endl; return 0; }
# ifndef JAVABACKENDCOMPILER_FILEUTIL_H_ # define JAVABACKENDCOMPILER_FILEUTIL_H_ # include <iostream> # include <fstream> # include <arpa/inet.h> static unsigned char * readCharsFromFileStream(std::ifstream &openFile, unsigned int length) { char * str = new char[length + 1]; openFile.read(str, length + 1); str[length] = '\0'; unsigned char * uchar = reinterpret_cast<unsigned char *>(str); return uchar; } static short int readShortFromFile(std::ifstream &openFile); static unsigned short int readUnsignedShortFromFile(std::ifstream &openFile) { unsigned short int res = 0; char * buf = new char[2]; openFile.read(buf, 2); void * v_char = reinterpret_cast<void *>(buf); unsigned short int * i_char = reinterpret_cast<unsigned short int *>(v_char); res = *i_char; delete [] buf; return htons(res); } static int readWordFromFile(std::ifstream &openFile); static unsigned int readUnsignedWordFromFile(std::ifstream &openFile) { unsigned int res = 0; char * buf = new char[4]; openFile.read(buf, 4); void * v_char = reinterpret_cast<void *>(buf); unsigned int * i_char = reinterpret_cast<unsigned int *>(v_char); res = *i_char; delete [] buf; return htonl(res); } # endif // JAVABACKENDCOMPILER_FILEUTIL_H_
#ifndef BLOGPOST_H #define BLOGPOST_H #include "App_WebBrowser.h" #include "Button.h" #include "Article.h" class GameWindow; class App_WebBrowser; class ComputerDesktop; class Textures; class Website; class Article; class Blogpost { public: Blogpost(GameWindow* gameWindowP, Website* websiteP, ComputerDesktop* desktopP, Article* articleP); Website* websiteP = 0; GameWindow* gameWindowP = 0; ComputerDesktop* desktopP = 0; Article* articleP = 0; int currentParagraph = 1; bool complete = false; float nBlogPostNotoriety = 0; float nBlogPostFollowers = 0; void update(); void render(); private: void typeText(sf::Text* txt, std::string* str); std::string str_title; std::string str_p1; std::string str_p2; std::string str_p3; sf::Text Title; sf::Text p1; sf::Text p2; sf::Text p3; }; #endif // BLOGPOST_H
/* Copyright (C) 2015 Willi Menapace <willi.menapace@gmail.com>, Simone Lorengo - All Rights Reserved * Unauthorized copying of this file, via any medium is strictly prohibited * Proprietary and confidential * Written by Willi Menapace <willi.menapace@gmail.com> */ #ifndef CONDITION_INCLUDED #define CONDITION_INCLUDED #include "GlobalDefines.h" #include "NetworkResources.h" #include "DateTime.h" #include "FileWriter.h" #include "ConditionTypes.cpp" /** * Classe astratta rappresentante una condizione verificabile * * @author Willi Menapace */ class Condition { public: /** * @return il tipo di condizione */ virtual ConditionTypes getType() = 0; /** * Verifica se la condizione e' soddisfatta * * @param networkResources il contesto di rete * @param now data e ora correnti * @return true se la condizione e' soddisfatta */ virtual bool test(NetworkResources *networkResources, DateTime *now) = 0; /** * Effettua l'output della configurazione su file * * @param fileWriter il file su cui effettuare l'output */ virtual void writeToFile(FileWriter *fileWriter) = 0; virtual ~Condition() {}; }; #endif // CONDITION_INCLUDED
#ifndef RWTPAT_H #define RWTPAT_H /// @file RwtPat.h /// @brief RwtPat のヘッダファイル /// @author Yusuke Matsunaga (松永 裕介) /// /// Copyright (C) 2005-2011 Yusuke Matsunaga /// All rights reserved. #include "YmNetworks/bdn.h" #include "YmLogic/NpnMap.h" BEGIN_NAMESPACE_YM_NETWORKS class RwtNode; ////////////////////////////////////////////////////////////////////// /// @class RwtPat RwtPat.h "RwtPat.h" /// @brief rewriting 用のパタンを表すクラス ////////////////////////////////////////////////////////////////////// class RwtPat { friend class RwtMgr; private: /// @brief コンストラクタ RwtPat(); /// @brief デストラクタ ~RwtPat(); public: ////////////////////////////////////////////////////////////////////// // 内容を取り出す関数 ////////////////////////////////////////////////////////////////////// /// @brief 根のノードを得る. const RwtNode* root_node() const; /// @brief 根の極性を得る. bool root_inv() const; /// @brief 入力数を得る. ymuint input_num() const; /// @brief 入力のノードを得る. /// @param[in] pos 入力番号 ( 0 <= pos < input_num() ) const RwtNode* input_node(ymuint pos) const; /// @brief ノード数を得る. ymuint node_num() const; /// @brief ノードを得る. /// @param[in] pos ノード番号 ( 0 <= pos < node_num() ) /// @note 0 〜 (input_num() - 1) は入力ノード /// @note 最後のノードは根のノード const RwtNode* node(ymuint pos) const; private: ////////////////////////////////////////////////////////////////////// // データメンバ ////////////////////////////////////////////////////////////////////// // ノード数 ymuint32 mNodeNum; // 入力数 + 根のノードの極性 ymuint32 mInputNum; // ノードの配列 // 0 〜 mInputNum - 1 個は入力ノード // 最後は根のノード RwtNode** mNodeList; }; ////////////////////////////////////////////////////////////////////// // インライン関数の定義 ////////////////////////////////////////////////////////////////////// // @brief コンストラクタ inline RwtPat::RwtPat() { mNodeNum = 0; mInputNum = 0; mNodeList = NULL; } // @brief デストラクタ inline RwtPat::~RwtPat() { // mNodeList は RwtMgr が管理する. } // @brief 根のノードを得る. inline const RwtNode* RwtPat::root_node() const { return mNodeList[mNodeNum - 1]; } // @brief 根の極性を得る. inline bool RwtPat::root_inv() const { return static_cast<bool>(mInputNum & 1U); } // @brief 入力数を得る. inline ymuint RwtPat::input_num() const { return mInputNum >> 1; } // @brief 入力のノードを得る. // @param[in] pos 入力番号 ( 0 <= pos < input_num() ) inline const RwtNode* RwtPat::input_node(ymuint pos) const { return node(pos); } // @brief ノード数を得る. inline ymuint RwtPat::node_num() const { return mNodeNum; } // @brief ノードを得る. // @param[in] pos ノード番号 ( 0 <= pos < node_num() ) // @note 0 〜 (input_num() - 1) は入力ノード // @note 最後のノードは根のノード inline const RwtNode* RwtPat::node(ymuint pos) const { return mNodeList[pos]; } END_NAMESPACE_YM_NETWORKS #endif // RWTPAT_H
// // Created by Sweet Acid on 03.05.2021. // #include "Time.h" namespace Snow { float Time::time; float Time::deltaTime; }
/*========================================================================= Program: Visualization Toolkit Module: vtkFindCellStrategy.h Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /** * @class vtkFindCellStrategy * @brief helper class to manage the vtkPointSet::FindCell() METHOD * * vtkFindCellStrategy is a helper class to manage the use of locators for * locating cells containing a query point x[3], the so-called FindCell() * method. The use of vtkDataSet::FindCell() is a common operation in * applications such as streamline generation and probing. However, in some * dataset types FindCell() can be implemented very simply (e.g., * vtkImageData) while in other datasets it is a complex operation requiring * supplemental objects like locators to perform efficiently. In particular, * vtkPointSet and its subclasses (like vtkUnstructuredGrid) require complex * strategies to efficiently implement the FindCell() operation. Subclasses * of the abstract vtkFindCellStrategy implement several of these strategies. * * The are two key methods to this class and subclasses. The Initialize() * method negotiates with an input dataset to define the locator to use: * either a locator associated with the inout dataset, or possibly an * alternative locator defined by the strategy (subclasses do this). The * second important method, FindCell() mimics vtkDataSet::FindCell() and * can be used in place of it. * * @sa * vtkPointSet vtkPolyData vtkStructuredGrid vtkUnstructuredGrid */ #ifndef vtkFindCellStrategy_h #define vtkFindCellStrategy_h #include "vtkCommonDataModelModule.h" // For export macro #include "vtkObject.h" class vtkCell; class vtkGenericCell; class vtkPointSet; class VTKCOMMONDATAMODEL_EXPORT vtkFindCellStrategy : public vtkObject { public: //@{ /** * Standard methdos for type information and printing. */ vtkTypeMacro(vtkFindCellStrategy, vtkObject); void PrintSelf(ostream& os, vtkIndent indent) override; //@} /** * All subclasses of this class must provide an initialize method. This * method performs handshaking and setup between the vtkPointSet dataset * and associated locator(s). A return value==0 means the initialization * process failed. */ virtual int Initialize(vtkPointSet* ps); /** * Virtual method for finding a cell. Subclasses must satisfy this API. * This method is of the same signature as vtkDataSet::FindCell(). */ virtual vtkIdType FindCell(double x[3], vtkCell* cell, vtkGenericCell* gencell, vtkIdType cellId, double tol2, int& subId, double pcoords[3], double* weights) = 0; protected: vtkFindCellStrategy(); ~vtkFindCellStrategy() override; vtkPointSet* PointSet; // vtkPointSet which this strategy is associated with double Bounds[6]; // bounding box of vtkPointSet vtkTimeStamp InitializeTime; // time at which strategy was initialized private: vtkFindCellStrategy(const vtkFindCellStrategy&) = delete; void operator=(const vtkFindCellStrategy&) = delete; }; #endif
#pragma once #include <GL/glew.h> #include <GLFW/glfw3.h> #include <stdlib.h> #include <stdio.h> #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <iostream> class ShaderProgram { private: char* filetobuf(const char* file); void cleanup(); GLuint vertexshader; GLuint fragmentshader; GLchar* vertexsource; GLchar* fragmentsource; public: GLuint shaderprogram; ShaderProgram(); ShaderProgram(const char* vertex_file_path, const char* fragment_file_path); ~ShaderProgram() { cleanup(); } GLuint loadShaders(const char* vertex_file_path, const char* fragment_file_path); GLuint linkShaderProgram(); inline void start() { glUseProgram(shaderprogram); } inline void stop() { glUseProgram(0); } virtual void getAllUniformLocations() = 0; protected: GLuint getUniformLocation(const char* uniformName); void loadFloat(int location, float value); void loadInt(int location, int value); void loadVector(int location, glm::vec3 vector); void loadVector(int location, glm::vec4 vector); void loadBoolean(int location, bool value); void loadMatrix(int location, glm::mat4 matrix); };
// This file has been generated by Py++. #ifndef ItemEntry_hpp__pyplusplus_wrapper #define ItemEntry_hpp__pyplusplus_wrapper void register_ItemEntry_class(); #endif//ItemEntry_hpp__pyplusplus_wrapper
#include<bits/stdc++.h> using namespace std; typedef long long ll; void solve(){ int n; cin>>n; vector<int>a(n); for(int i=0;i<n;i++) cin>>a[i]; sort(a.begin(),a.end()); int prev=a[0],c=1,ans=0; for(int i=1;i<n;i++){ if(prev==a[i]){ c++; } else{ ans=ans+min(prev-1,c); prev=a[i]; c=1; } } ans=ans+min(prev-1,c); cout<<ans<<"\n"; } int main() { #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("op.txt","w",stdout); #endif int t=1; cin>>t; while(t--){ solve(); } }
#ifndef CONTENTPAGE_H #define CONTENTPAGE_H #include <QWidget> #include <QLabel> #include <QScrollArea> #include "PlaylistElement.h" #include "PlaylistElementGUI.h" #include "Playlist.h" #include "PlaylistData.h" #include "ImageLoader.h" #include "ContentType.h" class ContentPage : public QWidget { Q_OBJECT private: QLabel* page_title; QLabel* content_cover; //artist or album cover PlaylistData playlist_data; Playlist* playlist_elements; ContentType page_content; QScrollArea* scroller = nullptr; void buildLayout(); void connections(); void setCustomStyle(); public: ContentPage(ContentType content_type, QWidget* parent = nullptr); ContentPage(ContentType content_type, PlaylistData p_data, QWidget* parent = nullptr); ContentPage(ContentType content_type, std::vector<PlaylistElement> p_data, QWidget* parent = nullptr); void loadData(ContentType content_type, PlaylistData p_data); void loadData(ContentType content_type, std::vector<PlaylistElement> p_data); public slots: void elementSelected(PlaylistElement data); void loadContent(ContentType content_type, PlaylistData data); signals: void requestContent(PlaylistElement data, ContentType type); void sendSongToPlayer(PlaylistElement data); }; #endif
#include <iostream> using namespace std; int findMax(int A[], int size) { int max = INT32_MIN; for (int i = 0; i < size; i++) { if (A[i] > max) max = A[i]; } return max; } void countSort(int A[], int sizeof_array) { int max, i, j; int *c; max = findMax(A, sizeof_array); c = new int[max + 1]; for (i = 0; i < max + 1; i++) c[i] = 0; for (i = 0; i < sizeof_array; i++) c[A[i]]++; i = j = 0; while (j < max + 1) { if (c[j] > 0) { A[i++] = j; c[j]--; } else { j++; } } }
#include "UI.h" #include "Chat.h" #include "main.h" #include "Chunk.h" #include "Blocks.h" #include "Player.h" #include "System.h" #include "Worlds.h" #include "Network.h" #include "Interface.h" #include "Inventory.h" #include <fstream> #include <numeric> #include <iostream> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <glm/gtc/matrix_transform.hpp> const int AVG_UPDATE_RANGE = 10; const double UI_UPDATE_FREQUENCY = 1.0; const std::string FONT = "Roboto"; static double lastUIUpdate; static std::deque<int> CPU; bool UI::ShowDebug = false; bool UI::ShowTitle = true; bool UI::ShowWorlds = false; bool UI::ShowOptions = false; bool UI::ShowServers = false; bool UI::ShowGameMenu = false; bool UI::ShowInventory = false; bool UI::ShowVideoOptions = false; int UI::MouseX = 0; int UI::MouseY = 0; std::string UI::CustomDocument = ""; const std::string BoolStrings[2] = {"False", "True"}; void Init_Menu(); void Init_Debug(); void Init_Title(); void Init_Options(); void Init_World_Select(); void Init_Server_Screen(); void Create_World_List(); void Create_Server_List(); void Toggle_Debug(); void Toggle_Inventory(); void Toggle_Game_Menu(); void Toggle_Title(void* caller); void Toggle_World_Screen(void* caller); void Toggle_Server_Screen(void* caller); void Toggle_Options_Menu(void* caller); void Toggle_Video_Options(void* caller); void Draw_Debug(); void Bind_Current_Document(); void Toggle_AO(void* caller); void Toggle_VSync(void* caller); void Toggle_Wireframe(void* caller); std::pair<bool, float> Get_Slider_Value(void* slider, int &storage) { float value = std::round(static_cast<Slider*>(slider)->Value); if (value == storage) { return {false, 0.0f}; } storage = static_cast<int>(value); Write_Config(); return {true, value}; } void Change_FOV(void* caller); void Change_Mipmap_Level(void* caller); void Change_Render_Distance(void* caller); void Change_Anisotropic_Filtering(void* caller); void Create_World(void* caller); void Load_World(void* caller); void Delete_World(void* caller); void Add_Server(void* caller); void Load_Server(void* caller); void Delete_Server(void* caller); void UI::Init() { Interface::Init(); Inventory::Init(); Chat::Init(); Init_Title(); Init_Options(); Init_Menu(); Init_World_Select(); Init_Server_Screen(); Init_Debug(); } void UI::Draw() { if (Wireframe) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } if (ShowTitle || ShowGameMenu) { Interface::Mouse_Handler(player.LastMousePos.x, player.LastMousePos.y); if (ShowTitle) { Interface::Draw_Document("titleBg"); } else { Interface::Draw_Document("menuBg"); } if (ShowOptions) { if (ShowVideoOptions) { Interface::Draw_Document("videoOptions"); } else { Interface::Draw_Document("options"); } } else if (ShowGameMenu) { Interface::Draw_Document("gameMenu"); } else if (ShowTitle) { if (ShowServers) { Interface::Draw_Document("servers"); } else if (ShowWorlds) { Interface::Draw_Document("worlds"); } else { Interface::Draw_Document("title"); } } } else { Chat::Update(); if (CustomDocument != "") { Interface::Draw_Document("inventory"); Interface::Draw_Document(CustomDocument); Interface::Draw_Document("mouseStack"); } else { Inventory::Draw(); if (ShowDebug) { Draw_Debug(); } } } if (Wireframe) { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); } } void UI::Click(int action, int button) { Bind_Current_Document(); Interface::Click(button, action); Interface::Set_Document(""); if (!GamePaused) { player.Click_Handler(button, action); } } void UI::Load_World(int seed) { Worlds::Load_World(seed); ShowTitle = false; ShowWorlds = false; GamePaused = false; UI::Toggle_Mouse(false); } void UI::Mouse_Handler(int x, int y) { MouseX = x; MouseY = y; Bind_Current_Document(); Interface::Mouse_Handler(x, SCREEN_HEIGHT - y); Interface::Set_Document(""); if (Chat::Focused && !Chat::FocusToggled) { Chat::Mouse_Handler(x, y); } if (!GamePaused && !Chat::Focused) { player.Mouse_Handler(x, y); } } void UI::Key_Handler(int key, int action) { if (action != GLFW_RELEASE) { if (Interface::HoveringType == "textBox") { static_cast<TextBox*>(Interface::HoveringElement)->Key_Handler(key); } } if (action == GLFW_PRESS) { switch (key) { case GLFW_KEY_ESCAPE: if (CustomDocument != "") { player.LookingBlockType->CloseFunction(); } else if (ShowInventory) { Inventory::Is_Open = false; Toggle_Inventory(); } else if (ShowVideoOptions) { Toggle_Video_Options(nullptr); } else { Toggle_Game_Menu(); } break; case GLFW_KEY_U: Toggle_Debug(); break; case GLFW_KEY_TAB: Toggle_Inventory(); break; } } } void UI::Text_Handler(unsigned int codepoint) { if (Chat::Focused && !Chat::FocusToggled) { Chat::Input(codepoint); } else { if (Interface::HoveringType == "textBox") { static_cast<TextBox*>(Interface::HoveringElement)->Input(codepoint); } } } void UI::Toggle_Mouse(bool enable) { MouseEnabled = enable; glfwSetInputMode(Window, GLFW_CURSOR, enable ? GLFW_CURSOR_NORMAL : GLFW_CURSOR_DISABLED); } void Bind_Current_Document() { std::string name; if (UI::CustomDocument != "") { name = UI::CustomDocument; } if (UI::ShowOptions) { if (UI::ShowVideoOptions) { name = "videoOptions"; } else { name = "options"; } } else if (UI::ShowTitle) { if (UI::ShowServers) { name = "servers"; } else if (UI::ShowWorlds) { name = "worlds"; } else { name = "title"; } } else if (UI::ShowGameMenu) { name = "gameMenu"; } else if (UI::ShowInventory) { name = "inventory"; } Interface::Set_Document(name); } void Init_Title() { glm::vec2 buttonSize = Scale(200, 40); glm::vec4 bgDims(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT); glm::vec3 logoDims(Scale(0, 700), 0.5f); glm::vec4 singleButtonDims(Scale(620, 500), buttonSize); glm::vec4 multiButtonDims(Scale(620, 430), buttonSize); glm::vec4 optionButtonDims(Scale(620, 300), buttonSize); glm::vec4 exitButtonDims(Scale(620, 200), buttonSize); glm::vec4 backButtonDims(Scale(620, 200), buttonSize); Interface::Set_Document("titleBg"); Interface::Add_Background("bg", bgDims); Interface::Get_Background("bg")->Color = glm::vec3(0.2f); Interface::Get_Background("bg")->Opacity = 1.0f; Interface::Set_Document(""); Interface::Set_Document("title"); Interface::Add_Image("logo", "logo.png", 3, logoDims); Interface::Get_Image("logo")->Center(); Interface::Add_Button("single", "Single Player", singleButtonDims, Toggle_World_Screen); Interface::Add_Button("multi", "Multi Player", multiButtonDims, Toggle_Server_Screen); Interface::Add_Button("options", "Options", optionButtonDims, Toggle_Options_Menu); Interface::Add_Button("exit", "Quit", exitButtonDims, Exit); Interface::Set_Document(""); } void Init_Options() { glm::vec2 buttonSize(Scale(200, 40)); glm::vec4 vsyncButtonDims(Scale(400, 500), buttonSize); glm::vec4 aoButtonDims(Scale(620, 500), buttonSize); glm::vec4 wireframeButtonDims(Scale(840, 500), buttonSize); glm::vec4 videoOptionsDims(Scale(400, 500), buttonSize); glm::vec4 backButtonDims(Scale(620, 200), buttonSize); glm::vec4 afDims(Scale(400, 700), buttonSize); glm::vec4 renderDistDims(Scale(620, 700), buttonSize); glm::vec4 fovDims(Scale(840, 700), buttonSize); glm::vec4 mipmapDims(Scale(400, 600), buttonSize); glm::vec3 renderDistRange(1, 20, RENDER_DISTANCE); glm::vec3 afRange(1, 16, ANISOTROPIC_FILTERING); glm::vec3 mipmapRange(0, 4, MIPMAP_LEVEL); glm::vec3 fovRange(10, 180, FOV); Interface::Set_Document("options"); Interface::Add_Button("videoOptions", "Video Options", videoOptionsDims, Toggle_Video_Options); Interface::Add_Button("back", "Back", backButtonDims, Toggle_Options_Menu); Interface::Set_Document(""); Interface::Set_Document("videoOptions"); Interface::Add_Button("vsync", "V-Sync: " + BoolStrings[VSYNC], vsyncButtonDims, Toggle_VSync); Interface::Add_Button("wireframe", "Wireframe: " + BoolStrings[Wireframe], wireframeButtonDims, Toggle_Wireframe); Interface::Add_Button("ao", "Ambient Occlusion: " + BoolStrings[AMBIENT_OCCLUSION], aoButtonDims, Toggle_AO); Interface::Add_Button("back", "Back", backButtonDims, Toggle_Video_Options); Interface::Add_Slider( "af", "Anisotropic Filtering: " + std::to_string(ANISOTROPIC_FILTERING), afDims, afRange, Change_Anisotropic_Filtering ); Interface::Add_Slider( "renderDistance", "Render Distance: " + std::to_string(RENDER_DISTANCE), renderDistDims, renderDistRange, Change_Render_Distance ); Interface::Add_Slider("fov", "FOV: " + std::to_string(FOV), fovDims, fovRange, Change_FOV); Interface::Add_Slider( "mipmap", "Mipmapping Level: " + std::to_string(MIPMAP_LEVEL), mipmapDims, mipmapRange, Change_Mipmap_Level ); Interface::Set_Document(""); } void Init_Menu() { glm::vec2 buttonSize(Scale(200, 40)); glm::vec4 bgDims(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT); glm::vec4 optionButtonDims(Scale(620, 500), buttonSize); glm::vec4 exitButtonDims(Scale(620, 200), buttonSize); Interface::Set_Document("menuBg"); Interface::Add_Background("menuBg", bgDims); Interface::Set_Document(""); Interface::Set_Document("gameMenu"); Interface::Add_Button("options", "Options", optionButtonDims, Toggle_Options_Menu); Interface::Add_Button("exit", "Quit to Menu", exitButtonDims, Toggle_Title); Interface::Set_Document(""); } void Init_World_Select() { glm::vec4 bgDims(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT); glm::vec4 newNameDims(Scale(100, 800), Scale(200, 35)); glm::vec4 newSeedDims(Scale(100, 700), Scale(200, 35)); glm::vec4 newWorldDims(Scale(100, 600), Scale(200, 40)); glm::vec4 backButtonDims(Scale(620, 200), Scale(200, 40)); Interface::Set_Document("worlds"); Interface::Add_Text("newNameLabel", "Name:", Scale(100, 840)); Interface::Add_Text_Box("newName", newNameDims); Interface::Add_Text("newSeedLabel", "Seed:", Scale(100, 740)); Interface::Add_Text_Box("newSeed", newSeedDims); Interface::Add_Button("create", "Create New World", newWorldDims, Create_World); Interface::Add_Button("back", "Back", backButtonDims, Toggle_World_Screen); Interface::Set_Document(""); Create_World_List(); } void Create_World_List() { static float worldStartY = 800; static float worldSpacing = 100; static float worldXPos = Scale_X(520); static glm::vec2 worldSize(Scale(350, 40)); static float deleteButtonXPos = Scale_X(880); static glm::vec2 deleteButtonSize(Scale(40, 40)); Interface::Set_Document("worlds"); for (auto const &world : Worlds::Get_Worlds()) { Interface::Delete_Button(world.Name); Interface::Delete_Button("remove_" + world.Name); Interface::Add_Button( world.Name, world.Name, glm::vec4(worldXPos, Scale_Y(worldStartY), worldSize), Load_World ); Interface::Add_Button( "remove_" + world.Name, "X", glm::vec4(deleteButtonXPos, Scale_Y(worldStartY), deleteButtonSize), Delete_World ); worldStartY -= worldSpacing; } Interface::Set_Document(""); } void Init_Server_Screen() { glm::vec4 bgDims(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT); glm::vec4 nameDims(Scale(100, 800), Scale(200, 35)); glm::vec4 serverNameDims(Scale(100, 700), Scale(200, 35)); glm::vec4 ipDims(Scale(100, 600), Scale(200, 35)); glm::vec4 addServerDims(Scale(100, 500), Scale(200, 40)); glm::vec4 backDims(Scale(620, 200), Scale(200, 40)); Interface::Set_Document("servers"); Interface::Add_Text("nameLabel", "User Name", Scale(100, 840)); Interface::Add_Text_Box("name", nameDims); Interface::Add_Text("serverNameLabel", "Server Name", Scale(100, 740)); Interface::Add_Text_Box("serverName", serverNameDims); Interface::Add_Text("ipLabel", "Server Address", Scale(100, 640)); Interface::Add_Text_Box("ip", ipDims); Interface::Add_Button("addServer", "Add", addServerDims, Add_Server); Interface::Add_Text("errMsg", "", Scale(50, 570)); Interface::Get_Text_Element("errMsg")->Center(Scale(50, 570), Scale_X(300), {true, false}); Interface::Add_Button("back", "Back", backDims, Toggle_Server_Screen); Interface::Set_Document(""); Create_Server_List(); } void Create_Server_List() { static float serverStartY = 800; static float serverSpacing = 100; static float serverXPos = Scale_X(520); static glm::vec2 serverSize(Scale(350, 40)); static float deleteButtonXPos = Scale_X(880); static glm::vec2 deleteButtonSize(Scale(40, 40)); std::fstream serverFile("servers.json"); bool fileExists = serverFile.is_open(); serverFile.close(); if (!fileExists) { return; } nlohmann::json json; serverFile.open("servers.json", std::ifstream::in); json << serverFile; serverFile.close(); Interface::Set_Document("servers"); for (auto it = json.begin(); it != json.end(); ++it) { std::string serverName = it.key(); Interface::Delete_Button(serverName); Interface::Delete_Button("remove_" + serverName); Interface::Add_Button( serverName, serverName, glm::vec4(serverXPos, Scale_Y(serverStartY), serverSize), Load_Server ); Interface::Add_Button( "remove_" + serverName, "X", glm::vec4(deleteButtonXPos, Scale_Y(serverStartY), deleteButtonSize), Delete_Server ); serverStartY -= serverSpacing; } Interface::Set_Document(""); } void Init_Debug() { lastUIUpdate = glfwGetTime(); Interface::Set_Document("debug"); std::string ramUsage = System::GetPhysicalMemoryUsage(); Interface::Add_Text("cpu", "CPU: 0%", Scale(30, 820)); Interface::Add_Text("ram", "RAM: " + ramUsage, Scale(30, 790)); Interface::Add_Text("chunkQueue", "Chunks Loaded: ", Scale(30, 760)); Interface::Add_Text("vertQueue", "Vertices Loaded: ", Scale(30, 730)); Interface::Set_Document(""); } #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-parameter" #elif _MSC_VER #pragma warning(push) #pragma warning(disable: 4100) #endif void Toggle_Title(void* caller) { UI::ShowGameMenu = false; UI::ShowOptions = false; UI::ShowInventory = false; UI::ShowDebug = false; Inventory::Is_Open = false; UI::ShowTitle = !UI::ShowTitle; GamePaused = UI::ShowTitle; UI::Toggle_Mouse(UI::ShowTitle); if (UI::ShowTitle) { Worlds::Save_World(); WORLD_NAME = ""; if (Multiplayer) { Network::Disconnect(); Network::Update(1000); Multiplayer = false; } } } void Toggle_Game_Menu() { if (!UI::ShowTitle) { UI::ShowGameMenu = !UI::ShowGameMenu; UI::ShowOptions = false; if (!UI::ShowInventory) { UI::Toggle_Mouse(UI::ShowGameMenu); } } } void Toggle_World_Screen(void* caller) { UI::ShowWorlds = !UI::ShowWorlds; } void Toggle_Server_Screen(void* caller) { UI::ShowServers = !UI::ShowServers; } void Toggle_Inventory() { if (!UI::ShowTitle && UI::CustomDocument == "") { UI::ShowInventory = !UI::ShowInventory; UI::Toggle_Mouse(UI::ShowInventory); } } void Toggle_Debug() { if (!UI::ShowTitle) { UI::ShowDebug = !UI::ShowDebug; } } void Toggle_Options_Menu(void* caller) { UI::ShowOptions = !UI::ShowOptions; } void Toggle_Video_Options(void* caller) { UI::ShowVideoOptions = !UI::ShowVideoOptions; } std::tuple<int, int> Get_Loaded() { int total = 0; int vertices = 0; for (auto const &chunk : ChunkMap) { total += chunk.second->Meshed; if (chunk.second->Visible) { vertices += chunk.second->buffer.Vertices; } } return {total, vertices}; } void Draw_Debug() { CPU.push_back(static_cast<int>(System::GetCPUUsage())); if (CPU.size() > AVG_UPDATE_RANGE) { CPU.pop_front(); } Interface::Set_Document("debug"); if (LastFrame - lastUIUpdate >= UI_UPDATE_FREQUENCY) { lastUIUpdate = LastFrame; int cpu_sum = 0; for (int const &time : CPU) { cpu_sum += time; } Interface::Get_Text_Element("cpu")->Set_Text( "CPU: " + std::to_string(static_cast<int>(cpu_sum / AVG_UPDATE_RANGE)) + "%" ); Interface::Get_Text_Element("ram")->Set_Text( "RAM: " + System::GetPhysicalMemoryUsage() ); } int loadedChunks, loadedVertices; std::tie(loadedChunks, loadedVertices) = Get_Loaded(); Interface::Get_Text_Element("chunkQueue")->Set_Text( "Chunks Queued: " + std::to_string(static_cast<int>(ChunkMap.size()) - loadedChunks) ); Interface::Get_Text_Element("vertQueue")->Set_Text("Vertices Loaded: " + std::to_string(loadedVertices)); Interface::Set_Document(""); Interface::Draw_Document("debug"); } void Toggle_VSync(void* caller) { VSYNC = !VSYNC; static_cast<Button*>(caller)->Text.Set_Text("V-Sync: " + BoolStrings[VSYNC]); glfwSwapInterval(VSYNC); Write_Config(); } void Toggle_AO(void* caller) { AMBIENT_OCCLUSION = !AMBIENT_OCCLUSION; static_cast<Button*>(caller)->Text.Set_Text("Ambient Occlusion: " + BoolStrings[AMBIENT_OCCLUSION]); Write_Config(); player.Queue_Chunks(true); } void Toggle_Wireframe(void* caller) { if (ToggleWireframe) { ToggleWireframe = false; static_cast<Button*>(caller)->Text.Set_Text("Wireframe: False"); } else { ToggleWireframe = true; static_cast<Button*>(caller)->Text.Set_Text("Wireframe: " + BoolStrings[!Wireframe]); } } void Change_Render_Distance(void* caller) { auto result = Get_Slider_Value(caller, RENDER_DISTANCE); if (result.first && !UI::ShowTitle) { player.Queue_Chunks(); } } void Change_Anisotropic_Filtering(void* caller) { auto result = Get_Slider_Value(caller, ANISOTROPIC_FILTERING); if (!result.first) { return; } glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D_ARRAY, Load_Array_Texture("atlas.png", {16, 32}, MIPMAP_LEVEL, result.second)); } void Change_FOV(void* caller) { auto result = Get_Slider_Value(caller, FOV); if (!result.first) { return; } glm::mat4 projection = glm::perspective( glm::radians(static_cast<float>(FOV)), static_cast<float>(SCREEN_WIDTH) / SCREEN_HEIGHT, Z_NEAR_LIMIT, Z_FAR_LIMIT ); UBO.Upload(1, projection); } void Change_Mipmap_Level(void* caller) { auto result = Get_Slider_Value(caller, MIPMAP_LEVEL); if (!result.first) { return; } glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D_ARRAY, Load_Array_Texture("atlas.png", {16, 32}, MIPMAP_LEVEL, static_cast<float>(ANISOTROPIC_FILTERING))); } void Create_World(void* caller) { Interface::Set_Document("worlds"); TextBox* name = Interface::Get_Text_Box("newName"); TextBox* seed = Interface::Get_Text_Box("newSeed"); Interface::Set_Document(""); std::string worldName = name->Text; name->Clear(); std::string seedStr = seed->Text; seed->Clear(); // Check if world already exists. if (Worlds::Get_Seed(worldName) != 0) { return; } if (seedStr.length() >= 20) { seedStr = seedStr.substr(0, 19); } int worldSeed; try { // Prevent integer overflow. worldSeed = std::stoll(seedStr) % 2147483647; } catch (std::invalid_argument) { unsigned long long stringSum = std::accumulate(seedStr.begin(), seedStr.end(), static_cast<unsigned long long>(0)); worldSeed = stringSum % 2147483647; } Worlds::Create_World(worldName, worldSeed); Create_World_List(); } void Load_World(void* caller) { WORLD_NAME = static_cast<Button*>(caller)->Text.Text; Worlds::Load_World(Worlds::Get_Seed(WORLD_NAME)); UI::ShowWorlds = false; UI::ShowTitle = false; GamePaused = false; UI::Toggle_Mouse(false); } void Delete_World(void* caller) { // Remove remove_ prefix. std::string worldName = static_cast<Button*>(caller)->Name.substr(7); Interface::Set_Document("worlds"); Interface::Delete_Button(worldName); Interface::Delete_Button("remove_" + worldName); Interface::Set_Document(""); Worlds::Delete_World(worldName); Create_World_List(); } void Add_Server(void* caller) { Interface::Set_Document("servers"); TextElement* errMsg = Interface::Get_Text_Element("errMsg"); TextBox* serverName = Interface::Get_Text_Box("serverName"); TextBox* username = Interface::Get_Text_Box("name"); TextBox* ipEl = Interface::Get_Text_Box("ip"); Interface::Set_Document(""); std::string host = ipEl->Text; if (username->Text == "") { errMsg->Set_Text("&cError! &fPlease input a user name."); return; } if (serverName->Text == "") { errMsg->Set_Text("&cError! &fPlease input a server name."); return; } if (host == "") { errMsg->Set_Text("&cError! &fPlease input an IP address."); return; } if (std::count(host.begin(), host.end(), '.') != 3) { errMsg->Set_Text("&cError! &fInvalid IP address."); return; } std::string ip; unsigned short port; if (host.find(':') == std::string::npos || host.find(':') == host.length() - 1) { if (ip.find(':') != std::string::npos) { ip = host.substr(0, host.length() - 1); } else { ip = host; } } else { try { port = static_cast<unsigned short>(std::stoi(host.substr(host.find(':') + 1))); ip = host.substr(0, host.find(':')); } catch (...) { errMsg->Set_Text("&cError! &fInvalid port."); return; } } auto ipParts = Split(ip, '.'); if (ipParts.size() < 4) { errMsg->Set_Text("&cError! &fMissing IP value."); return; } else if (ipParts.size() > 4) { errMsg->Set_Text("&cError! &Too many IP values."); return; } for (std::string const &part : ipParts) { if (part.length() > 1 && part.front() == '0') { errMsg->Set_Text("&cError! &fPlease remove leading zeroes from IP values."); return; } try { int partNum = std::stoi(part); if (partNum > 255) { errMsg->Set_Text("&cError! &fIP value out of range. Value &6" + part + " &fis out of range (&60 &f- &6255&f)."); return; } } catch (const std::invalid_argument) { errMsg->Set_Text("&cError! &fNon-numeric characters in IP."); return; } } nlohmann::json servers; std::fstream serverFile("servers.json"); bool fileExists = serverFile.is_open(); if (fileExists) { serverFile.close(); serverFile.open("servers.json", std::ifstream::in); servers << serverFile; serverFile.close(); } else { serverFile.open("servers.json", std::ifstream::out | std::ifstream::trunc); } servers[serverName->Text] = {{"username", username->Text}, {"ip", host}}; serverName->Clear(); username->Clear(); ipEl->Clear(); if (fileExists) { serverFile.open("servers.json", std::ifstream::out | std::ifstream::trunc); } servers >> serverFile; serverFile.close(); Create_Server_List(); } void Load_Server(void* caller) { nlohmann::json json; std::ifstream file("servers.json"); json << file; file.close(); std::string serverName = static_cast<Button*>(caller)->Name; std::string serverIP = json[serverName]["ip"]; PLAYER_NAME = json[serverName]["username"]; if (Network::Connect(PLAYER_NAME, serverIP)) { Multiplayer = true; } else { Interface::Set_Document("servers"); Interface::Get_Text_Element("errMsg")->Set_Text("&cError! &fCould not connect to server!"); Interface::Set_Document(""); } } void Delete_Server(void* caller) { // Remove remove_ prefix. std::string serverName = static_cast<Button*>(caller)->Name.substr(7); Interface::Set_Document("servers"); Interface::Delete_Button(serverName); Interface::Delete_Button("remove_" + serverName); Interface::Set_Document(""); nlohmann::json json; std::ifstream file("servers.json"); json << file; file.close(); json.erase(serverName); std::ofstream outFile("servers.json"); json >> outFile; outFile.close(); Create_Server_List(); } #ifdef __clang__ #pragma clang diagnostic pop #elif _MSC_VER #pragma warning(pop) #endif
#pragma once #include <sstream> #include <assert.h> #include <vector> #include <ctime> #include <cstring> enum ELogColor { ELC_Black, ELC_Red, ELC_Green, ELC_Blue, ELC_Cyan, ELC_Magenta, ELC_Yellow, ELC_White, ELC_Gray, ELC_HiRed, ELC_HiGreen, ELC_HiBlue, ELC_HiCyan, ELC_HiMagenta, ELC_HiYellow, ELC_HiWhite, //default foreground color for normal text ELC_DefaultFG = ELC_HiWhite, //default background color for normal text ELC_DefaultBG = ELC_White, //default foreground color for parameters ELC_DefaultParamFG = ELC_HiGreen }; enum ELogLevel { ELL_Message, ELL_Success, ELL_Warning, ELL_Error, ELL_Debug, ELL_Hint, }; //a simple linear allocator on the stack which only grows template<size_t SizeInByte> struct VLinerAllocStack { size_t mSize = 0; uint8_t mBuffer[SizeInByte]; size_t Avail() const { return mSize - SizeInByte; } void* Alloc(size_t size) { if (size <= Avail()) { auto ret = &mBuffer[mSize]; mSize += size; return ret; } return nullptr; } }; struct VLogToken { //index of the first character of string in the buffer. the token is null terminated. unsigned mIndex : 31; //whether its parameter or normal text unsigned mIsParam : 1; }; struct VLogTokenPack { static constexpr unsigned MAX_TOKEN = 1024; static constexpr unsigned BUFFER_SIZE = 8192; unsigned mTokenCount = 0; unsigned mStringBufferSize = 0; char mStringBuffer[BUFFER_SIZE]; VLogToken mTokens[MAX_TOKEN]; const char* GetTokenStr(int index) const { return &mStringBuffer[mTokens[index].mIndex]; } void NewToken(bool bIsParam) { mTokens[mTokenCount].mIndex = mStringBufferSize; mTokens[mTokenCount].mIsParam = bIsParam; mTokenCount++; assert(mTokenCount < MAX_TOKEN); } void PushChr(char chr) { assert(mStringBufferSize < BUFFER_SIZE - 1); mStringBuffer[mStringBufferSize++] = chr; } void PushStr(const char* str, size_t len) { memcpy(&mStringBuffer[mStringBufferSize], str, len); mStringBufferSize += len; assert(mStringBufferSize < BUFFER_SIZE); } void PushStr(const char* str) { PushStr(str, strlen(str)); } void End() { PushChr(0); } void Print() const; }; struct VlogIndent { int mIndent; explicit VlogIndent(int indent) : mIndent(indent) {} }; ////////////////////////////////////////////////////////////////////////// void VGetLogString(bool b, char* out, size_t size ); void VGetLogString(int i, char* out, size_t size); void VGetLogString(double d, char* out, size_t size); void VGetLogString(unsigned i, char* out, size_t size); void VGetLogString(unsigned long long i, char* out, size_t size); void VGetLogString(char c, char* out, size_t size); void VGetLogString(const void* p, char* out, size_t size); void VGetLogString(const char* str, char* out, size_t size); void VGetLogString(VlogIndent indent, char* out, size_t size); struct VLogEntryData { const char* mFunction; const char* mFilename; const char* mArgsStr; uint32_t mLineNumber; uint32_t mThreadId; //thread id in which log occurred uint32_t mClock; //clock at which log occurred ELogLevel mLevel; VLogTokenPack mTokens; }; inline void ZZSPrintAuto(VLogTokenPack& out, const char* format) { while (*format) { if (*format == ('%')) { assert(false); } out.PushChr(*format); format++; } } template<typename T, typename... TArgs> void ZZSPrintAuto(VLogTokenPack& data, const char* format, const T& value, const TArgs... args) { while (*format) { if (*format == ('%')) { /* data.End(); data.NewToken(true); std::ostringstream osstr; osstr << value; data.PushStr(osstr.str()); data.End(); */ data.End(); data.NewToken(true); char itemBuffer[256]; VGetLogString(value, itemBuffer, sizeof(itemBuffer)); data.PushStr(itemBuffer); data.End(); data.NewToken(false); format++; ZZSPrintAuto(data, format, args...); return; } data.PushChr(*format); format++; } } template<typename... TArgs> void VLogExtractTokens(VLogTokenPack& outTokens, const char* format, const TArgs... args) { outTokens.NewToken(false); ZZSPrintAuto(outTokens, format, args...); outTokens.End(); } void VPrintLogEntryToConsole(const VLogEntryData& data); struct VLogger { static VLogger& Get(); //returns true if we must catch this log bool Check(const char* function); std::vector<VLogEntryData> mLogs; void DumpString(std::string& out); }; #define VLOG_BASE(level, format, ...) \ if(VLogger::Get().Check(__FUNCTION__))\ {\ VLogEntryData logData;\ logData.mFunction = __FUNCTION__;\ logData.mLineNumber = __LINE__;\ logData.mFilename = __FILE__;\ logData.mThreadId = 0; /*#TODO*/ \ logData.mClock = std::clock();\ logData.mLevel = level;\ logData.mArgsStr = #__VA_ARGS__;\ VLogExtractTokens(logData.mTokens, format, ##__VA_ARGS__ );\ VLogger::Get().mLogs.push_back(logData);\ VPrintLogEntryToConsole(logData);\ }\ #if 1 #define VLOG_MSG(format, ...) VLOG_BASE(ELL_Message, format, ##__VA_ARGS__ ) #define VLOG_ERR(format, ...) VLOG_BASE(ELL_Error , format, ##__VA_ARGS__ ) #define VLOG_WRN(format, ...) VLOG_BASE(ELL_Warning, format, ##__VA_ARGS__ ) #define VLOG_SUC(format, ...) VLOG_BASE(ELL_Success, format, ##__VA_ARGS__ ) #define VLOG_DBG(format, ...) VLOG_BASE(ELL_Debug , format, ##__VA_ARGS__ ) #else #define VLOG_MSG(format, ...) #define VLOG_ERR(format, ...) #define VLOG_WRN(format, ...) #define VLOG_SUC(format, ...) #define VLOG_DBG(format, ...) #endif
/*********************************************************************** created: Mon Jan 12 2009 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #ifndef _CEGUIRenderingWindow_h_ #define _CEGUIRenderingWindow_h_ #include "CEGUI/RenderingSurface.h" #include "CEGUI/Rectf.h" #include <glm/gtc/quaternion.hpp> #if defined(_MSC_VER) # pragma warning(push) # pragma warning(disable : 4251) #endif namespace CEGUI { /*! \brief RenderingWindow is a RenderingSurface that can be "drawn back" onto another RenderingSurface and is primarily intended to be used as a kind of cache for rendered imagery. */ class CEGUIEXPORT RenderingWindow : public RenderingSurface { public: /*! \brief Constructor for RenderingWindow objects. \param target The TextureTarget based object that will be used as the target for content rendering done by the RenderingWindow. \param owner The RenderingSurface object that will be our initial owner. This RenderingSurface is also the target where our cached imagery will be rendered back to. \note The TextureTarget \a target remains under it's original ownership, and the RenderingSurface \a owner actually owns \e this object. */ RenderingWindow(TextureTarget& target, RenderingSurface& owner); //! Destructor for RenderingWindow objects. ~RenderingWindow(); /*! \brief Set the clipping region that will be used when rendering the imagery for this RenderingWindow back onto the RenderingSurface that owns it. \note This is not the clipping region used when rendering the queued geometry \e onto the RenderingWindow, that still uses whatever regions are set on the queued GeometryBuffer objects. \param region Rect object describing a rectangular clipping region. \note The region should be described as absolute pixel locations relative to the screen or other root surface. The region should \e not be described relative to the owner of the RenderingWindow. */ void setClippingRegion(const Rectf& region); /*! \brief Set the two dimensional position of the RenderingWindow in pixels. The origin is at the top-left corner. \param position Vector2 object describing the desired location of the RenderingWindow, in pixels. \note This position is an absolute pixel location relative to the screen or other root surface. It is \e not relative to the owner of the RenderingWindow. */ void setPosition(const glm::vec2& position); /*! \brief Set the size of the RenderingWindow in pixels. \param size Size object that describes the desired size of the RenderingWindow, in pixels. */ void setSize(const Sizef& size); /*! \brief Set the rotation quaternion to be used when rendering the RenderingWindow back onto it's owning RenderingSurface. \param rotation Quaternion object describing the rotation. */ void setRotation(const glm::quat& rotation); /*! \brief Set the location of the pivot point around which the RenderingWindow will be rotated. \param pivot Vector3 describing the three dimensional point around which the RenderingWindow will be rotated. */ void setPivot(const glm::vec3& pivot); /*! \brief Return the current pixel position of the RenderingWindow. The origin is at the top-left corner. \return Vector2 object describing the pixel position of the RenderingWindow. \note This position is an absolute pixel location relative to the screen or other root surface. It is \e not relative to the owner of the RenderingWindow. */ const glm::vec2& getPosition() const { return d_position; } /*! \brief Return the current size of the RenderingWindow in pixels. \return Size object describing the current pixel size of the RenderingWindow. */ const Sizef& getSize() const { return d_size; } /*! \brief Return the current rotation being applied to the RenderingWindow \return Quaternion object describing the rotation for the RenderingWindow. */ const glm::quat& getRotation() const { return d_rotation; } /*! \brief Return the rotation pivot point location for the RenderingWindow. \return Vector3 object describing the current location of the pivot point used when rotating the RenderingWindow. */ const glm::vec3& getPivot() const { return d_pivot; } /*! \brief Return the TextureTarget object that is the target for content rendered to this RenderingWindows. This is the same object passed into the constructor. \return The TextureTarget object that receives the rendered output resulting from geometry queued to this RenderingWindow. */ const TextureTarget& getTextureTarget() const { return d_textarget; } TextureTarget& getTextureTarget() { return d_textarget; } /*! \brief Peform time based updated for the RenderingWindow. \note Currently this really only has meaning for RenderingWindow objects that have RenderEffect objects set. Though this may not always be the case. \param elapsed float value describing the number of seconds that have passed since the previous call to update. */ void update(const float elapsed); /*! \brief Set the RenderEffect that should be used with the RenderingWindow. This may be 0 to remove a previously set RenderEffect. \note Ownership of the RenderEffect does not change; the RenderingWindow will not delete a RenderEffect assigned to it when the RenderingWindow is destroyed. */ void setRenderEffect(RenderEffect* effect); /*! \brief Return a pointer to the RenderEffect currently being used with the RenderingWindow. A return value of 0 indicates that no RenderEffect is being used. \return Pointer to the RenderEffect used with this RenderingWindow, or 0 for none. */ RenderEffect* getRenderEffect(); /*! \brief generate geometry to be used when rendering back the RenderingWindow to it's owning RenderingSurface. \note In normal usage you should never have to call this directly. There may be certain cases where it might be useful to call this when using the RenderEffect system. */ void realiseGeometry(); /*! \brief Mark the geometry used when rendering the RenderingWindow back to it's owning RenderingSurface as invalid so that it gets regenerated on the next rendering pass. This is separate from the main invalidate() function because in most cases invalidating the cached imagery will not require the potentially expensive regeneration of the geometry for the RenderingWindow itself. */ void invalidateGeometry() { d_geometryValid = false; } /*! \brief Return the RenderingSurface that owns the RenderingWindow. This is also the RenderingSurface that will be used when the RenderingWindow renders back it's cached imagery content. \return RenderingSurface object that owns, and is targetted by, the RenderingWindow. */ const RenderingSurface& getOwner() const { return *d_owner; } RenderingSurface& getOwner() { return *d_owner; } /*! \brief Fill in Vector2 object \a p_out with an unprojected version of the point described by Vector2 \a p_in. */ void unprojectPoint(const glm::vec2& p_in, glm::vec2& p_out); Rectf getTextureRect() const; // overrides from base void draw(std::uint32_t drawModeMask = DrawModeMaskAll) override; void invalidate() override; bool isRenderingWindow() const override { return true; } protected: //! default generates geometry to draw window as a single quad. virtual void realiseGeometry_impl(); //! set a new owner for this RenderingWindow object void setOwner(RenderingSurface& owner); // friend is so that RenderingSurface can call setOwner to xfer ownership. friend void RenderingSurface::transferRenderingWindow(RenderingWindow&); //! RenderingSurface that owns this object, we render back to this object. RenderingSurface* d_owner = nullptr; //! The same as d_target in base, but avoiding impossible downcast of the virtual base. TextureTarget& d_textarget; //! The geometry buffers that cache the geometry drawn by this Window. GeometryBuffer& d_geometryBuffer; //! Position of this RenderingWindow glm::vec2 d_position = glm::vec2(0.f, 0.f); //! Size of this RenderingWindow Sizef d_size; //! Rotation for this RenderingWindow glm::quat d_rotation = glm::quat(1.f, 0.f, 0.f, 0.f); //! Pivot point used for the rotation. glm::vec3 d_pivot = glm::vec3(0.f, 0.f, 0.f); //! indicates whether data in GeometryBuffer is up-to-date bool d_geometryValid = false; }; } #if defined(_MSC_VER) # pragma warning(pop) #endif #endif // end of guard _CEGUIRenderingWindow_h_
// // Created by Liang on 2019-07-09. // #include <iostream> #include <vector> #include <queue> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} static TreeNode* buildByLevel(vector<int> nums, int null_target=0){ TreeNode* root = new TreeNode(nums[0]); queue<TreeNode* > queue1; queue1.push(root); for(int i=1;i<nums.size();i+=2){ int lchild = nums[i]; int rchild = nums[i+1]; TreeNode* cur = queue1.front(); queue1.pop(); if(lchild != null_target){ cur->left = new TreeNode(lchild); queue1.push(cur->left); } else cur->left= NULL; if(rchild != null_target){ cur->right = new TreeNode(rchild); queue1.push(cur->right); } else cur->right = NULL; } return root; } static void levelOrder(TreeNode* root) { vector<vector<int>> res; vector<int> cur_level; int nums = 1; int count = 0; queue<TreeNode*> nodes; nodes.push(root); int next_levels_num = 0; while(!nodes.empty()){ TreeNode* cur_node = nodes.front(); nodes.pop(); if(cur_node != NULL){ nodes.push(cur_node->left); nodes.push(cur_node->right); cur_level.push_back(cur_node->val); next_levels_num += 2; } count += 1; if(count == nums){ nums = next_levels_num; next_levels_num = 0; count = 0; res.push_back(cur_level); cur_level = {}; } } for(auto v: res){ for(auto e: v){ cout<<e<<", "; } cout<<endl; } } }; class Solution { public: int diameterOfBinaryTreeCore(TreeNode*& root, int& res){ if(root == NULL){ return 0; } if(root->left == NULL && root->right == NULL){ res = max(res, 1); return 1; } int left_len_path = diameterOfBinaryTreeCore(root->left, res); int right_len_path = diameterOfBinaryTreeCore(root->right, res); res = max(res, left_len_path + right_len_path + 1); return max(left_len_path, right_len_path) + 1; } int diameterOfBinaryTree(TreeNode* root) { int res = 0; diameterOfBinaryTreeCore(root, res); res -= 1; res = max(res, 0); return res; } static void solution(){ TreeNode* treeNode = TreeNode::buildByLevel({1, 2, 3, 4, 5, -1, -1}, -1); Solution solution1; cout<<solution1.diameterOfBinaryTree(treeNode)<<endl; } };
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SYNC_INTERNAL_API_PUBLIC_TEST_FAKE_SYNC_MANAGER_H_ #define SYNC_INTERNAL_API_PUBLIC_TEST_FAKE_SYNC_MANAGER_H_ #include <string> #include "base/memory/ref_counted.h" #include "base/observer_list.h" #include "sync/internal_api/public/sync_manager.h" #include "sync/notifier/sync_notifier_registrar.h" namespace base { class SequencedTaskRunner; } namespace syncer { class FakeSyncManager : public SyncManager { public: // |initial_sync_ended_types|: The set of types that have initial_sync_ended // set to true. This value will be used by InitialSyncEndedTypes() until the // next configuration is performed. // // |progress_marker_types|: The set of types that have valid progress // markers. This will be used by GetTypesWithEmptyProgressMarkerToken() until // the next configuration is performed. // // |configure_fail_types|: The set of types that will fail // configuration. Once ConfigureSyncer is called, the // |initial_sync_ended_types_| and |progress_marker_types_| will be updated // to include those types that didn't fail. FakeSyncManager(ModelTypeSet initial_sync_ended_types, ModelTypeSet progress_marker_types, ModelTypeSet configure_fail_types); virtual ~FakeSyncManager(); // Returns those types that have been cleaned (purged from the directory) // since the last call to GetAndResetCleanedTypes(), or since startup if never // called. ModelTypeSet GetAndResetCleanedTypes(); // Returns those types that have been downloaded since the last call to // GetAndResetDownloadedTypes(), or since startup if never called. ModelTypeSet GetAndResetDownloadedTypes(); // Returns those types that have been marked as enabled since the // last call to GetAndResetEnabledTypes(), or since startup if never // called. ModelTypeSet GetAndResetEnabledTypes(); // Posts a method to invalidate the given IDs on the sync thread. void Invalidate(const ObjectIdPayloadMap& id_payloads, IncomingNotificationSource source); // Posts a method to enable notifications on the sync thread. void EnableNotifications(); // Posts a method to disable notifications on the sync thread. void DisableNotifications(NotificationsDisabledReason reason); // Block until the sync thread has finished processing any pending messages. void WaitForSyncThread(); // SyncManager implementation. // Note: we treat whatever message loop this is called from as the sync // loop for purposes of callbacks. virtual bool Init( const FilePath& database_location, const WeakHandle<JsEventHandler>& event_handler, const std::string& sync_server_and_path, int sync_server_port, bool use_ssl, const scoped_refptr<base::TaskRunner>& blocking_task_runner, scoped_ptr<HttpPostProviderFactory> post_factory, const std::vector<ModelSafeWorker*>& workers, ExtensionsActivityMonitor* extensions_activity_monitor, ChangeDelegate* change_delegate, const SyncCredentials& credentials, scoped_ptr<SyncNotifier> sync_notifier, const std::string& restored_key_for_bootstrapping, const std::string& restored_keystore_key_for_bootstrapping, bool keystore_encryption_enabled, scoped_ptr<InternalComponentsFactory> internal_components_factory, Encryptor* encryptor, UnrecoverableErrorHandler* unrecoverable_error_handler, ReportUnrecoverableErrorFunction report_unrecoverable_error_function) OVERRIDE; virtual void ThrowUnrecoverableError() OVERRIDE; virtual ModelTypeSet InitialSyncEndedTypes() OVERRIDE; virtual ModelTypeSet GetTypesWithEmptyProgressMarkerToken( ModelTypeSet types) OVERRIDE; virtual bool PurgePartiallySyncedTypes() OVERRIDE; virtual void UpdateCredentials(const SyncCredentials& credentials) OVERRIDE; virtual void UpdateEnabledTypes(const ModelTypeSet& types) OVERRIDE; virtual void RegisterInvalidationHandler( SyncNotifierObserver* handler) OVERRIDE; virtual void UpdateRegisteredInvalidationIds( SyncNotifierObserver* handler, const ObjectIdSet& ids) OVERRIDE; virtual void UnregisterInvalidationHandler( SyncNotifierObserver* handler) OVERRIDE; virtual void StartSyncingNormally( const ModelSafeRoutingInfo& routing_info) OVERRIDE; virtual void SetEncryptionPassphrase(const std::string& passphrase, bool is_explicit) OVERRIDE; virtual void SetDecryptionPassphrase(const std::string& passphrase) OVERRIDE; virtual void ConfigureSyncer( ConfigureReason reason, const ModelTypeSet& types_to_config, const ModelSafeRoutingInfo& new_routing_info, const base::Closure& ready_task, const base::Closure& retry_task) OVERRIDE; virtual void AddObserver(Observer* observer) OVERRIDE; virtual void RemoveObserver(Observer* observer) OVERRIDE; virtual SyncStatus GetDetailedStatus() const OVERRIDE; virtual bool IsUsingExplicitPassphrase() OVERRIDE; virtual bool GetKeystoreKeyBootstrapToken(std::string* token) OVERRIDE; virtual void SaveChanges() OVERRIDE; virtual void StopSyncingForShutdown(const base::Closure& callback) OVERRIDE; virtual void ShutdownOnSyncThread() OVERRIDE; virtual UserShare* GetUserShare() OVERRIDE; virtual void RefreshNigori(const std::string& chrome_version, const base::Closure& done_callback) OVERRIDE; virtual void EnableEncryptEverything() OVERRIDE; virtual bool ReceivedExperiment(Experiments* experiments) OVERRIDE; virtual bool HasUnsyncedItems() OVERRIDE; private: void InvalidateOnSyncThread( const ObjectIdPayloadMap& id_payloads, IncomingNotificationSource source); void EnableNotificationsOnSyncThread(); void DisableNotificationsOnSyncThread(NotificationsDisabledReason reason); scoped_refptr<base::SequencedTaskRunner> sync_task_runner_; ObserverList<SyncManager::Observer> observers_; // Faked directory state. ModelTypeSet initial_sync_ended_types_; ModelTypeSet progress_marker_types_; // Test specific state. // The types that should fail configuration attempts. These types will not // have their progress markers or initial_sync_ended bits set. ModelTypeSet configure_fail_types_; // The set of types that have been cleaned up. ModelTypeSet cleaned_types_; // The set of types that have been downloaded. ModelTypeSet downloaded_types_; // The set of types that have been enabled. ModelTypeSet enabled_types_; // Faked notifier state. SyncNotifierRegistrar registrar_; DISALLOW_COPY_AND_ASSIGN(FakeSyncManager); }; } // namespace syncer #endif // SYNC_INTERNAL_API_PUBLIC_TEST_FAKE_SYNC_MANAGER_H_
/******************************************************************************* * Cristian Alexandrescu * * 2163013577ba2bc237f22b3f4d006856 * * 11a4bb2c77aca6a9927b85f259d9af10db791ce5cf884bb31e7f7a889d4fb385 * * bc9a53289baf23d369484f5343ed5d6c * *******************************************************************************/ /* Problem 13244 - Space Happiness */ #include <iostream> int main() { int nNoTestCases; std::cin >> nNoTestCases; while (nNoTestCases--) { int nN; std::cin >> nN; (nN -= 1) |= 0x1; std::cout << static_cast<long long>(1 + nN) * (nN / 2) + 1 << std::endl; } return 0; }
#include "Package.h" #include <iostream> PackageA::PackageA() { m_package_name = "Package A"; } void PackageA::process() { std::cout << m_package_name << ", process()" << std::endl; } PackageB::PackageB() { m_package_name = "Package B"; } void PackageB::process() { std::cout << m_package_name << ", process()" << std::endl; } PackageC::PackageC() { m_package_name = "Package C"; } void PackageC::process() { std::cout << m_package_name << ", process()" << std::endl; }
#include <bits/stdc++.h> #define ull unsigned long long #define ll long long #define il inline #define db double #define ls rt << 1 #define rs rt << 1 | 1 #define pb push_back #define mp make_pair #define pii pair<int, int> #define X first #define Y second #define pcc pair<char, char> #define vi vector<int> #define vl vector<ll> #define rep(i, x, y) for(int i = x; i <= y; i ++) #define rrep(i, x, y) for(int i = x; i >= y; i --) #define rep0(i, n) for(int i = 0; i < (n); i ++) #define per0(i, n) for(int i = (n) - 1; i >= 0; i --) #define ept 1e-9 #define INF 0x3f3f3f3f #define sz(x) (x).size() #define ALL(x) (x).begin(), (x).end() using namespace std; static char ibuf[1 << 20]; char *fis = ibuf, *fit = ibuf; inline char readChar() { return fis == fit && (fit = (fis = ibuf) + fread(ibuf, 1, 1 << 20, stdin), fis == fit) ? EOF : *fis++; } inline int read() { char c, _c; int x; for (c = readChar(); !isdigit(c); c = readChar()); for (x = 0; isdigit(c); c = readChar()) { x = x * 10 + c - '0'; } return x; } static char ostc[100], obuf[1 << 20]; int ol = 0; char *fos = obuf, *fot = obuf + (1 << 20) - 1; inline void writeChar(char c) { *fos++ = c; if (fos == fot) { fwrite(obuf, 1, fos - obuf, stdout); fos = obuf; } } inline void write(int n, char c) { if (!n) { writeChar('0'); } else { while (n) { ostc[++ol] = n % 10 + 48, n /= 10; } } for (; ol; ol--) { writeChar(ostc[ol]); } writeChar(c); } const int N = 310; const int Maxn = 310; const ll inf=1e18; #define int long long struct Node { int x, y, z, v; }a[N]; ll n,m,Map[Maxn][Maxn],matched[Maxn]; ll slack[Maxn],pre[Maxn],ex[Maxn],ey[Maxn];//ex,ey顶标 bool visx[Maxn],visy[Maxn]; void match(ll u) { ll x,y=0,yy=0,delta; memset(pre,0,sizeof(pre)); for(ll i=1;i<=n;i++)slack[i]=inf; matched[y]=u; while(1) { x=matched[y];delta=inf;visy[y]=1; for(ll i=1;i<=n;i++) { if(visy[i])continue; if(slack[i]>ex[x]+ey[i]-Map[x][i]) { slack[i]=ex[x]+ey[i]-Map[x][i]; pre[i]=y; } if(slack[i]<delta){delta=slack[i];yy=i;} } for(ll i=0;i<=n;i++) { if(visy[i])ex[matched[i]]-=delta,ey[i]+=delta; else slack[i]-=delta; } y=yy; if(matched[y]==-1)break; } while(y){matched[y]=matched[pre[y]];y=pre[y];} } ll KM() { memset(matched,-1,sizeof(matched)); memset(ex,0,sizeof(ex)); memset(ey,0,sizeof(ey)); for(ll i=1;i<=n;i++) { memset(visy,0,sizeof(visy)); match(i); } ll res=0; for(ll i=1;i<=n;i++) if(matched[i]!=-1)res+=Map[matched[i]][i]; return res; } signed main() { n = read(); ll ans = 0; rep(i, 1, n) { a[i].x = read(); a[i].y = read(); a[i].z = read(); a[i].v = read(); ans += a[i].x * a[i].x; ans += a[i].y * a[i].y; ans += a[i].z * a[i].z; } for(ll i=1;i<=n;i++) for(ll j=1;j<=n;j++) Map[i][j]=-inf; rep(t, 0, n - 1) rep(i, 1, n) { Map[t + 1][i] = -t * t * a[i].v * a[i].v - 2 * t * a[i].v * a[i].z; } printf("%lld\n", ans - KM()); return 0; }
#include "stack.hh" int main(void){ MyStack my_stack; my_stack.getSize(); my_stack.isEmpty(); cout<<"pushing data"<<endl; for(int i=100; i<110; i++){ my_stack.push(i); } my_stack.getSize(); my_stack.isEmpty(); my_stack.readStack(); cout<<"pulling data"<<endl; for(int i=0; i<8; i++){ cout<<i<<". )"<<my_stack.pull()<<endl; } my_stack.getSize(); my_stack.isEmpty(); return 0; }
#include <iostream> using namespace std; int turno,horas,extras; char nombre[30]; double pago,pextras,pnormales; void datos(char nombre[],int &turno, int &horas, int &extras){ cout<<"Nombre del Empleado..: "; cin.getline(nombre,30); cout<<"Ingrese las horas trabajadas..: "; cin>>horas; cout<<"Ingrese las horas extras trabajadas..: "; cin>>extras; do{ cout<<"Ingrese el turno..: "; cin>>turno; }while (!(turno>=1 and turno<=4)); } int PagoHorasN (int turno){ if (turno==1 or turno==3) { return 200; } if (turno==2 or turno==4) { return 300; } } int PagoHorasX (int turno){ if (turno==1 or turno==3) { return 250; } if (turno==2 or turno==4) { return 350; } } void Calcular (double &pago,int horas, int extras,double &pnormales,double &pextras){ pnormales=((PagoHorasN(turno))*horas); pextras=((PagoHorasX(turno))*extras); pago=pnormales+pextras; } int main() { datos(nombre,turno,horas,extras); Calcular(pago,horas,extras,pnormales,pextras); cout<<"Pago por hora Normal..:$"<<PagoHorasN(turno)<<"\n"; cout<<"Pago por hora Extra..:$"<<PagoHorasX(turno)<<"\n"; cout<<"Pago Normales..:$"<<pnormales<<"\n"; cout<<"Pago Extras..:$"<<pextras<<"\n"; cout<<"Pago total es..:$"<<pago<<"\n"; return 0; }
#include "main.h" //user edits //motor ports const int right_intake = 1; const int left_intake = 10; /////////////////////////////////////////////////////// //motor definitions Motor intake1(right_intake, MOTOR_GEARSET_36, 0, MOTOR_ENCODER_DEGREES); Motor intake2(left_intake, MOTOR_GEARSET_36, 1, MOTOR_ENCODER_DEGREES); //usercontroL void intakeOP() { if(controller.get_digital(DIGITAL_R1)) { intake1.move(127); intake2.move(127); } else if(controller.get_digital(DIGITAL_R2)) { intake1.move(-127); intake2.move(-127); } else { intake1.move(0); intake2.move(0); } } /////////////////////////////////////////////////////// //autonomous functions void intake(int ispeed) { intake1.move_velocity(ispeed); intake2.move_velocity(ispeed); }
//////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2006-2010 MStar Semiconductor, Inc. // All rights reserved. // // Unless otherwise stipulated in writing, any and all information contained // herein regardless in any format shall remain the sole proprietary of // MStar Semiconductor Inc. and be kept in strict confidence // (''MStar Confidential Information'') by the recipient. // Any unauthorized act including without limitation unauthorized disclosure, // copying, use, reproduction, sale, distribution, modification, disassembling, // reverse engineering and compiling of the contents of MStar Confidential // Information is unlawful and strictly prohibited. MStar hereby reserves the // rights to any and all damages, losses, costs and expenses resulting therefrom. // //////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // This file is automatically generated by SkinTool [Version:0.2.3][Build:Dec 18 2014 17:25:00] ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////// // MAINFRAME styles.. ///////////////////////////////////////////////////// // BAT_LOW_WARNING_WINDOW styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Bat_Low_Warning_Window_Normal_DrawStyle[] = { { CP_FILL_RECT, CP_ZUI_FILL_RECT_INDEX_0 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // BAT_LOW_HINT_TEXT styles.. static DRAWSTYLE _MP_TBLSEG _Zui_Bat_Low_Hint_Text_Normal_DrawStyle[] = { { CP_BITMAP, CP_ZUI_BITMAP_INDEX_376 }, { CP_NOON, 0 }, }; ///////////////////////////////////////////////////// // BAT_LOW_CHARGE_TEXT styles.. ////////////////////////////////////////////////////// // Window Draw Style List (normal, focused, disable) WINDOWDRAWSTYLEDATA _MP_TBLSEG _GUI_WindowsDrawStyleList_Zui_Bat_Low[] = { // HWND_MAINFRAME { NULL, NULL, NULL }, // HWND_BAT_LOW_WARNING_WINDOW { _Zui_Bat_Low_Warning_Window_Normal_DrawStyle, NULL, NULL }, // HWND_BAT_LOW_HINT_TEXT { _Zui_Bat_Low_Hint_Text_Normal_DrawStyle, NULL, NULL }, // HWND_BAT_LOW_CHARGE_TEXT { NULL, NULL, NULL }, };
/******************************************************************************** ** Form generated from reading UI file 'window.ui' ** ** Created by: Qt User Interface Compiler version 5.9.8 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_WINDOW_H #define UI_WINDOW_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QDialog> #include <QtWidgets/QFrame> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QPushButton> #include <QtWidgets/QRadioButton> #include <QtWidgets/QSpinBox> QT_BEGIN_NAMESPACE class Ui_window { public: QSpinBox *Location1; QSpinBox *Location2; QSpinBox *Location3; QSpinBox *Location4; QSpinBox *Location5; QLabel *setLocationLabel; QLabel *ant1; QLabel *ant2; QLabel *ant3; QLabel *ant4; QLabel *ant5; QLabel *MaxtimeLabel; QLabel *MinTimeLabel; QLabel *Maxtime; QLabel *MinTime; QPushButton *StartButtom; QPushButton *ResetButtom; QLabel *setLengthLabel; QSpinBox *Length; QFrame *line; QFrame *line_2; QRadioButton *MaxAnt1; QRadioButton *MaxAnt2; QRadioButton *MaxAnt3; QRadioButton *MaxAnt4; QRadioButton *MaxAnt5; QRadioButton *MinAnt3; QRadioButton *MinAnt1; QRadioButton *MinAnt2; QRadioButton *MinAnt4; QRadioButton *MinAnt5; void setupUi(QDialog *window) { if (window->objectName().isEmpty()) window->setObjectName(QStringLiteral("window")); window->setEnabled(true); window->resize(685, 664); window->setContextMenuPolicy(Qt::CustomContextMenu); window->setWindowOpacity(1); window->setLayoutDirection(Qt::LeftToRight); window->setAutoFillBackground(false); window->setSizeGripEnabled(false); window->setModal(false); Location1 = new QSpinBox(window); Location1->setObjectName(QStringLiteral("Location1")); Location1->setEnabled(true); Location1->setGeometry(QRect(40, 90, 81, 41)); Location1->setMaximumSize(QSize(81, 41)); QFont font; font.setFamily(QString::fromUtf8("\345\215\216\346\226\207\347\273\206\351\273\221")); font.setPointSize(10); Location1->setFont(font); Location1->setCursor(QCursor(Qt::IBeamCursor)); Location1->setMaximum(9999); Location2 = new QSpinBox(window); Location2->setObjectName(QStringLiteral("Location2")); Location2->setEnabled(true); Location2->setGeometry(QRect(150, 90, 81, 41)); Location2->setMaximumSize(QSize(81, 41)); Location2->setFont(font); Location2->setCursor(QCursor(Qt::IBeamCursor)); Location2->setMaximum(9999); Location3 = new QSpinBox(window); Location3->setObjectName(QStringLiteral("Location3")); Location3->setEnabled(true); Location3->setGeometry(QRect(260, 90, 81, 41)); Location3->setMaximumSize(QSize(81, 41)); Location3->setFont(font); Location3->setCursor(QCursor(Qt::IBeamCursor)); Location3->setMaximum(9999); Location4 = new QSpinBox(window); Location4->setObjectName(QStringLiteral("Location4")); Location4->setEnabled(true); Location4->setGeometry(QRect(370, 90, 81, 41)); Location4->setMaximumSize(QSize(81, 41)); Location4->setFont(font); Location4->setCursor(QCursor(Qt::IBeamCursor)); Location4->setMaximum(9999); Location5 = new QSpinBox(window); Location5->setObjectName(QStringLiteral("Location5")); Location5->setEnabled(true); Location5->setGeometry(QRect(480, 90, 81, 41)); Location5->setMaximumSize(QSize(81, 41)); Location5->setFont(font); Location5->setCursor(QCursor(Qt::IBeamCursor)); Location5->setMaximum(9999); setLocationLabel = new QLabel(window); setLocationLabel->setObjectName(QStringLiteral("setLocationLabel")); setLocationLabel->setEnabled(true); setLocationLabel->setGeometry(QRect(40, 10, 571, 31)); setLocationLabel->setMaximumSize(QSize(571, 31)); QFont font1; font1.setFamily(QString::fromUtf8("\345\215\216\346\226\207\347\273\206\351\273\221")); font1.setPointSize(14); font1.setBold(false); font1.setWeight(50); setLocationLabel->setFont(font1); ant1 = new QLabel(window); ant1->setObjectName(QStringLiteral("ant1")); ant1->setEnabled(true); ant1->setGeometry(QRect(40, 50, 41, 31)); ant1->setMaximumSize(QSize(41, 31)); ant1->setFont(font); ant2 = new QLabel(window); ant2->setObjectName(QStringLiteral("ant2")); ant2->setEnabled(true); ant2->setGeometry(QRect(150, 50, 41, 31)); ant2->setMaximumSize(QSize(41, 31)); ant2->setFont(font); ant3 = new QLabel(window); ant3->setObjectName(QStringLiteral("ant3")); ant3->setEnabled(true); ant3->setGeometry(QRect(260, 50, 41, 31)); ant3->setMaximumSize(QSize(41, 31)); ant3->setFont(font); ant4 = new QLabel(window); ant4->setObjectName(QStringLiteral("ant4")); ant4->setEnabled(true); ant4->setGeometry(QRect(370, 50, 41, 31)); ant4->setMaximumSize(QSize(41, 31)); ant4->setFont(font); ant5 = new QLabel(window); ant5->setObjectName(QStringLiteral("ant5")); ant5->setEnabled(true); ant5->setGeometry(QRect(480, 50, 41, 31)); ant5->setMaximumSize(QSize(41, 31)); ant5->setFont(font); MaxtimeLabel = new QLabel(window); MaxtimeLabel->setObjectName(QStringLiteral("MaxtimeLabel")); MaxtimeLabel->setEnabled(true); MaxtimeLabel->setGeometry(QRect(70, 280, 131, 51)); QFont font2; font2.setFamily(QString::fromUtf8("\345\215\216\346\226\207\347\273\206\351\273\221")); font2.setPointSize(24); font2.setBold(false); font2.setWeight(50); MaxtimeLabel->setFont(font2); MinTimeLabel = new QLabel(window); MinTimeLabel->setObjectName(QStringLiteral("MinTimeLabel")); MinTimeLabel->setEnabled(true); MinTimeLabel->setGeometry(QRect(70, 449, 121, 51)); MinTimeLabel->setFont(font2); Maxtime = new QLabel(window); Maxtime->setObjectName(QStringLiteral("Maxtime")); Maxtime->setEnabled(true); Maxtime->setGeometry(QRect(250, 280, 211, 61)); QFont font3; font3.setFamily(QString::fromUtf8("\345\215\216\346\226\207\347\273\206\351\273\221")); font3.setPointSize(20); Maxtime->setFont(font3); Maxtime->setMouseTracking(true); Maxtime->setTabletTracking(false); Maxtime->setFrameShape(QFrame::WinPanel); Maxtime->setFrameShadow(QFrame::Plain); Maxtime->setLineWidth(1); Maxtime->setTextFormat(Qt::AutoText); Maxtime->setScaledContents(false); MinTime = new QLabel(window); MinTime->setObjectName(QStringLiteral("MinTime")); MinTime->setEnabled(true); MinTime->setGeometry(QRect(250, 450, 211, 51)); MinTime->setFont(font3); MinTime->setContextMenuPolicy(Qt::DefaultContextMenu); MinTime->setLayoutDirection(Qt::LeftToRight); MinTime->setFrameShape(QFrame::WinPanel); MinTime->setFrameShadow(QFrame::Plain); MinTime->setLineWidth(1); MinTime->setMidLineWidth(0); StartButtom = new QPushButton(window); StartButtom->setObjectName(QStringLiteral("StartButtom")); StartButtom->setEnabled(true); StartButtom->setGeometry(QRect(100, 600, 171, 51)); QFont font4; font4.setFamily(QString::fromUtf8("\345\215\216\346\226\207\347\273\206\351\273\221")); font4.setPointSize(16); StartButtom->setFont(font4); ResetButtom = new QPushButton(window); ResetButtom->setObjectName(QStringLiteral("ResetButtom")); ResetButtom->setEnabled(true); ResetButtom->setGeometry(QRect(380, 600, 181, 51)); QFont font5; font5.setFamily(QString::fromUtf8("Aa\345\205\203\346\260\224\346\273\241\346\273\241")); font5.setPointSize(16); ResetButtom->setFont(font5); setLengthLabel = new QLabel(window); setLengthLabel->setObjectName(QStringLiteral("setLengthLabel")); setLengthLabel->setEnabled(true); setLengthLabel->setGeometry(QRect(40, 163, 551, 31)); setLengthLabel->setFont(font1); Length = new QSpinBox(window); Length->setObjectName(QStringLiteral("Length")); Length->setEnabled(true); Length->setGeometry(QRect(40, 210, 81, 41)); Length->setFont(font); Length->setCursor(QCursor(Qt::IBeamCursor)); Length->setMaximum(9999); line = new QFrame(window); line->setObjectName(QStringLiteral("line")); line->setGeometry(QRect(50, 380, 611, 20)); line->setFrameShape(QFrame::HLine); line->setFrameShadow(QFrame::Sunken); line_2 = new QFrame(window); line_2->setObjectName(QStringLiteral("line_2")); line_2->setGeometry(QRect(50, 540, 611, 20)); line_2->setFrameShape(QFrame::HLine); line_2->setFrameShadow(QFrame::Sunken); MaxAnt1 = new QRadioButton(window); MaxAnt1->setObjectName(QStringLiteral("MaxAnt1")); MaxAnt1->setGeometry(QRect(50, 380, 21, 21)); MaxAnt1->setMouseTracking(false); MaxAnt1->setIconSize(QSize(30, 30)); MaxAnt2 = new QRadioButton(window); MaxAnt2->setObjectName(QStringLiteral("MaxAnt2")); MaxAnt2->setGeometry(QRect(50, 380, 21, 21)); MaxAnt2->setMouseTracking(false); MaxAnt2->setIconSize(QSize(30, 30)); MaxAnt3 = new QRadioButton(window); MaxAnt3->setObjectName(QStringLiteral("MaxAnt3")); MaxAnt3->setGeometry(QRect(50, 380, 21, 21)); MaxAnt3->setMouseTracking(false); MaxAnt3->setIconSize(QSize(30, 30)); MaxAnt4 = new QRadioButton(window); MaxAnt4->setObjectName(QStringLiteral("MaxAnt4")); MaxAnt4->setGeometry(QRect(50, 380, 21, 21)); MaxAnt4->setMouseTracking(false); MaxAnt4->setIconSize(QSize(30, 30)); MaxAnt5 = new QRadioButton(window); MaxAnt5->setObjectName(QStringLiteral("MaxAnt5")); MaxAnt5->setGeometry(QRect(50, 380, 21, 21)); MaxAnt5->setMouseTracking(false); MaxAnt5->setIconSize(QSize(30, 30)); MinAnt3 = new QRadioButton(window); MinAnt3->setObjectName(QStringLiteral("MinAnt3")); MinAnt3->setGeometry(QRect(50, 540, 21, 21)); MinAnt3->setMouseTracking(false); MinAnt3->setIconSize(QSize(30, 30)); MinAnt1 = new QRadioButton(window); MinAnt1->setObjectName(QStringLiteral("MinAnt1")); MinAnt1->setGeometry(QRect(50, 540, 21, 21)); MinAnt1->setMouseTracking(false); MinAnt1->setIconSize(QSize(30, 30)); MinAnt2 = new QRadioButton(window); MinAnt2->setObjectName(QStringLiteral("MinAnt2")); MinAnt2->setGeometry(QRect(50, 540, 21, 21)); MinAnt2->setMouseTracking(false); MinAnt2->setIconSize(QSize(30, 30)); MinAnt4 = new QRadioButton(window); MinAnt4->setObjectName(QStringLiteral("MinAnt4")); MinAnt4->setGeometry(QRect(50, 540, 21, 21)); MinAnt4->setMouseTracking(false); MinAnt4->setIconSize(QSize(30, 30)); MinAnt5 = new QRadioButton(window); MinAnt5->setObjectName(QStringLiteral("MinAnt5")); MinAnt5->setGeometry(QRect(50, 540, 21, 21)); MinAnt5->setMouseTracking(false); MinAnt5->setIconSize(QSize(30, 30)); retranslateUi(window); QMetaObject::connectSlotsByName(window); } // setupUi void retranslateUi(QDialog *window) { window->setWindowTitle(QApplication::translate("window", "AntsCreepingGames", Q_NULLPTR)); setLocationLabel->setText(QApplication::translate("window", "Please set the location of the ants:", Q_NULLPTR)); ant1->setText(QApplication::translate("window", "Ant1", Q_NULLPTR)); ant2->setText(QApplication::translate("window", "Ant2", Q_NULLPTR)); ant3->setText(QApplication::translate("window", "Ant3", Q_NULLPTR)); ant4->setText(QApplication::translate("window", "Ant4", Q_NULLPTR)); ant5->setText(QApplication::translate("window", "Ant5", Q_NULLPTR)); MaxtimeLabel->setText(QApplication::translate("window", "Maxtime\357\274\232", Q_NULLPTR)); MinTimeLabel->setText(QApplication::translate("window", "Mintime\357\274\232", Q_NULLPTR)); Maxtime->setText(QApplication::translate("window", "0", Q_NULLPTR)); MinTime->setText(QApplication::translate("window", "0", Q_NULLPTR)); StartButtom->setText(QApplication::translate("window", "Start", Q_NULLPTR)); ResetButtom->setText(QApplication::translate("window", "Reset", Q_NULLPTR)); setLengthLabel->setText(QApplication::translate("window", "Please set the length of the stick:", Q_NULLPTR)); MaxAnt1->setText(QString()); MaxAnt2->setText(QString()); MaxAnt3->setText(QString()); MaxAnt4->setText(QString()); MaxAnt5->setText(QString()); MinAnt3->setText(QString()); MinAnt1->setText(QString()); MinAnt2->setText(QString()); MinAnt4->setText(QString()); MinAnt5->setText(QString()); } // retranslateUi }; namespace Ui { class window: public Ui_window {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_WINDOW_H
#include <ArduinoJson.h> #include <Arduino.h> JsonObject& parseJson(DynamicJsonBuffer& jsonBuffer,String json); bool arrContainsKey(JsonArray& arr,String key);
#include <cstdio> #include <cstdlib> #define MINDATA -100000 typedef int ElemType; typedef struct HNode { ElemType *Data; int Size; int Capacity; } HNode, *Heap; typedef Heap MinHeap; MinHeap CreateHeap(int maxSize) { MinHeap h = (MinHeap)malloc(sizeof(HNode)); h->Data = (ElemType*)malloc((maxSize+1)*sizeof(ElemType)); h->Size = 0; h->Capacity = maxSize; h->Data[0] = MINDATA; return h; } void InsertHeap(ElemType e, MinHeap h) { int index = h->Size+1; int parent = index/2; while (e < h->Data[parent]) { h->Data[index] = h->Data[parent]; index = parent; parent /= 2; } h->Data[index] = e; h->Size++; } void PrintPath(int index, MinHeap h) { while (index > 1) { printf("%d ", h->Data[index]); index /= 2; } printf("%d\n", h->Data[1]); } int main() { freopen("PIHinput.txt", "r", stdin); int N, M; ElemType e; int index; scanf("%d %d", &N, &M); MinHeap h = CreateHeap(N+1); while (N-- > 0) { scanf("%d", &e); InsertHeap(e, h); } while (M-- > 0) { scanf("%d", &index); PrintPath(index, h); } return 0; }
#ifndef NODE_H #define NODE_H #include<iostream> using namespace std; template<class T> class Node{ private: T data; Node<T> *next; Node<T> *prev; public: Node(); T getData(); void setData(T data); Node<T>* getNext(); void setNext(Node<T>* temp); Node<T>* getPrev(); void setPrev(Node<T>* temp); }; #endif
#pragma once #include "Common.h" #include "vertexBufferObject.h" #include "vertexBufferObjectIndexed.h" #include "Texture.h" #include "Actor.h" class AActor; class AObject: public AActor{ private: //control points vector<glm::vec3> m_coffinTopVertices; vector<glm::vec3> m_coffinBotVertices; vector<glm::vec3> m_coffinRightVertices; vector<glm::vec3> m_coffinLeftVertices; vector<glm::vec3> m_coffinFrontVertices; vector<glm::vec3> m_coffinBackVertices; vector<glm::vec3> m_umbrellaVertices; vector<glm::vec3> m_umbrellaHandleVertices; vector<glm::vec3> m_umbrellaBoneFrontVertices; vector<glm::vec3> m_umbrellaBoneBackVertices; vector<glm::vec3> m_umbrellaBoneLeftVertices; vector<glm::vec3> m_umbrellaBoneRightVertices; //vao GLuint m_vaoCoffinTop; GLuint m_vaoCoffinBot; GLuint m_vaoCoffinRight; GLuint m_vaoCoffinLeft; GLuint m_vaoCoffinFront; GLuint m_vaoCoffinBack; GLuint m_vaoUmbrellaTop; GLuint m_vaoUmbrellaHandle; GLuint m_vaoUmbrellaBoneFront; GLuint m_vaoUmbrellaBoneBack; GLuint m_vaoUmbrellaBoneLeft; GLuint m_vaoUmbrellaBoneRight; //texture vector<CTexture> m_textures; CTexture m_texture; GLuint m_vaoWallLeft; GLuint m_vaoWallFront; GLuint m_vaoWallRight; GLuint m_vaoWallTop; GLuint m_vaoWallBot; GLuint m_vaoWallBack; vector<glm::vec3> m_wallLeftVertices; vector<glm::vec3> m_wallFrontVertices; vector<glm::vec3> m_wallRightVertices; vector<glm::vec3> m_wallTopVertices; vector<glm::vec3> m_wallBotVertices; vector<glm::vec3> m_wallBackVertices; public: //AObject(const string &model, CCamera *camera, float speed = 0.00015f, glm::vec3 rotateAround = glm::vec3(0.0f, 1.0f, 0.0f), float angle = 0.0f); AObject(); ~AObject(); virtual void Initialise(Character character, float camPos = 880); //load vertex and texture virtual bool Load(string path); virtual void Update(float m_dt); void Create(string filename); virtual void Render(); //coffin void SetCoffinPoints(); void CreateCoffinOffsetPoints(); void CreateCoffin(); void RenderCoffin(); //umbrella void SetUmbrellaPoints(); void CreateUmbrellaOffsetPoints(); void CreateUmbrella(); void RenderUmbrella(); void CreateWall(); void RenderWall(); void CreateObject(AActor::Character id, vector<glm::vec3> &vertices, GLuint &vao, glm::vec3 normal); private: };
#ifndef BEAM_TREE_H #define BEAM_TREE_H #include <vector> #include <string> class TTree; class TFile; class BeamTree { public: BeamTree(){}; BeamTree(int startRun, int endRun, std::string desc="", bool isLS=false); virtual ~BeamTree(); void LoadData(); void InitTree(); void Process(); void PrintInfo(); TTree* fBeamTree; int fStartRun; int fEndRun; std::string fDescription; std::vector<std::string> fFilenames; TFile* fOutput; std::string fOutputName; float fGain_T1; float fGain_T2; // tree variables; Float_t b_nPE_T1; Float_t b_nPE_T2; Float_t b_nPE_H1; Float_t b_nPE_H2; Float_t b_nPE_H3; Float_t b_nPE_VC; Float_t b_t_T1; Float_t b_t_T2; Float_t b_t_H1; Float_t b_t_H2; Float_t b_t_H3; Float_t b_t_VC; }; #endif
#include <float.h> #include <iomanip> #include <iostream> using namespace std; int main() { cout << fixed << setprecision(5) << "max = " << FLT_MAX << endl; cout << fixed << setprecision(5) << "min = " << -FLT_MAX << endl; }
/* * Copyright (C) 2007-2015 Frank Mertens. * * Use of this source is governed by a BSD-style license that can be * found in the LICENSE file. * */ #ifndef FLUXTAR_ARREADER_H #define FLUXTAR_ARREADER_H #include <flux/tar/ArchiveReader> namespace flux { namespace tar { class ArReader: public ArchiveReader { public: static Ref<ArReader> open(Stream *source); static bool testFormat(Stream *source); bool readHeader(Ref<ArchiveEntry> *entry); void readData(ArchiveEntry *entry, Stream* sink = 0); private: ArReader(Stream *source); Ref<Stream> source_; Ref<ByteArray> data_; off_t i_; }; }} // namespace flux::tar #endif // FLUXTAR_ARREADER_H
#include<bits/stdc++.h> using namespace std; int main(){ int n,sum=0; int arr[105]; cin >> n ; for(int i=0;i<n;i++){ cin >> arr[i]; sum+=arr[i]; } if(sum%2)cout<<sum<<endl; else{ int f=0; int mini=INT_MAX; for(int i=0;i<n;i++) if(arr[i]%2){ f=1; mini=min(mini,arr[i]);} if(f)cout << sum-mini<<endl; else cout << 0 <<endl; } return 0; }
#pragma once #include <landstalker-lib/model/world.hpp> #include <landstalker-lib/model/entity_type.hpp> #include <landstalker-lib/tools/sprite.hpp> #include <landstalker-lib/md_tools.hpp> void extract_nigel_sprites(md::ROM& rom, const World& world) { EntityLowPalette palette_low = world.entity_types().at(0)->low_palette(); EntityHighPalette palette_high = world.entity_types().at(0)->high_palette(); ColorPalette<16> palette {}; palette[0] = { 0, 0, 0 }; // Transparent palette[1] = { 0xC0, 0xC0, 0xC0 }; for(size_t i=0 ; i<palette_low.size() ; ++i) palette[i+2] = palette_low[i]; for(size_t i=0 ; i<palette_high.size() ; ++i) palette[i+2+palette_low.size()] = palette_high[i]; palette[15] = { 0, 0, 0 }; // Black uint32_t base_addr = 0x120800; for(uint8_t frame_id = 0 ; frame_id < 73 ; ++frame_id) { uint32_t frame_addr = rom.get_long(base_addr + (frame_id * 0x4)); Sprite frame = Sprite::decode_from(rom.iterator_at(frame_addr)); frame.write_to_png("./sprites/nigel/" + std::to_string(frame_id) + ".png", palette); } }
#include "main.h" /**************************************************/ //user editable constants //motor ports const int left_front = 11; const int left_rear = 12; const int right_front = 19; const int right_rear = 20; //distance constants const int distance_constant = 620; //ticks per tile const double degree_constant = 3.9; //ticks per degree /**************************************************/ //advanced tuning (PID and slew) //slew control (autonomous only) const int accel_step = 8; //smaller number = more slew const int deccel_step = 256; //256 = no slew //straight driving constants const double driveKP = .4; const double driveKD = .6; //turning constants const double turnKP = .8; const double turnKD = 2.1; /**************************************************/ //edit below with caution!!! #define MAX 127; static int driveMode = 1; static int driveTarget = 0; static int turnTarget = 0; static int maxSpeed = MAX; int driveError; int turnError; //motors Motor left1(left_front, MOTOR_GEARSET_18, 0, MOTOR_ENCODER_DEGREES); Motor left2(left_rear, MOTOR_GEARSET_18, 0, MOTOR_ENCODER_DEGREES); Motor right1(right_front, MOTOR_GEARSET_18, 1, MOTOR_ENCODER_DEGREES); Motor right2(right_rear, MOTOR_GEARSET_18, 1, MOTOR_ENCODER_DEGREES); //LCD Display int getBatteryLevel() { return battery::get_capacity(); } int getDriveError() { return driveError; } int getTurnError() { return turnError; } /**************************************************/ //basic control void left(int vel) { left1.move(vel); left2.move(vel); } void right(int vel) { right1.move(vel); right2.move(vel); } void reset(){ maxSpeed = MAX; driveTarget = 0; turnTarget = 0; left1.tare_position(); left2.tare_position(); right1.tare_position(); right2.tare_position(); left(0); right(0); } void resetDrive(){ left1.tare_position(); left2.tare_position(); right1.tare_position(); right2.tare_position(); } int drivePos(){ return (left1.get_position() + left2.get_position())/2; } /**************************************************/ //slew control static int leftSpeed = 0; static int rightSpeed = 0; void leftSlew(int leftTarget){ int step; if(abs(leftSpeed) < abs(leftTarget)) step = accel_step; else step = deccel_step; if(leftTarget > leftSpeed + step) leftSpeed += step; else if(leftTarget < leftSpeed - step) leftSpeed -= step; else leftSpeed = leftTarget; left(leftSpeed); } //slew control void rightSlew(int rightTarget){ int step; if(abs(rightSpeed) < abs(rightTarget)) step = accel_step; else step = deccel_step; if(rightTarget > rightSpeed + step) rightSpeed += step; else if(rightTarget < rightSpeed - step) rightSpeed -= step; else rightSpeed = rightTarget; right(rightSpeed); } /**************************************************/ //feedback bool isDriving(){ static int count = 0; static int last = 0; static int lastTarget = 0; int curr = left2.get_position(); int target = turnTarget; if(driveMode == 1) target = driveTarget; if(abs(last-curr) < 3) count++; else count = 0; if(target != lastTarget) count = 0; lastTarget = target; last = curr; //not driving if we haven't moved if(count > 4) return false; else return true; } /**************************************************/ //drive modifiers void setSpeed(int speed){ maxSpeed = speed; } /**************************************************/ //autonomous functions void driveAsync(double sp){ sp *= distance_constant; reset(); driveTarget = sp; driveMode = 1; } void turnAsync(double sp){ sp *= degree_constant; if(mirror.get_value()) { sp = -sp; } reset(); turnTarget = sp; driveMode = 0; } void drive(double sp){ driveAsync(sp); delay(450); while(isDriving()) delay(20); } void turn(double sp){ turnAsync(sp); delay(450); while(isDriving()) delay(20); } void slowDrive(double sp, double dp){ driveAsync(sp); if(sp > 0) while(drivePos() < dp) delay(20); else while(drivePos() > dp) delay(20); setSpeed(60); while(isDriving()) delay(20); } /**************************************************/ //task control void driveTask(void* parameter){ int prevError = 0; while(1){ delay (20); if(driveMode != 1) continue; int sp = driveTarget; double kp = driveKP; double kd = driveKD; //read sensors int sv = left2.get_position(); //speed int error = sp-sv; int derivative = error - prevError; prevError = error; int speed = error*kp + derivative*kd; driveError = error; if(speed > maxSpeed) speed = maxSpeed; if(speed < -maxSpeed) speed = -maxSpeed; //set motors leftSlew(speed); rightSlew(speed); printf("%d\n", error); } } void turnTask(void* parameter){ int prevError; while(1){ delay(20); if(driveMode != 0) continue; int sp = turnTarget; double kp = turnKP; double kd = turnKD; int sv = (right1.get_position() - left1.get_position()/2); int error = sp-sv; int derivative = error - prevError; prevError = error; int speed = error*kp + derivative*kd; turnError = error; if(speed > maxSpeed) speed = maxSpeed; if(speed < -maxSpeed) speed = -maxSpeed; leftSlew(-speed); rightSlew(speed); printf("%d\n", error); } } /**************************************************/ //operator control void driveOP(){ //driveMode = 2; //turns off autonomous tasks left1.move(controller.get_analog(ANALOG_LEFT_Y)); left2.move(controller.get_analog(ANALOG_LEFT_Y)); right1.move(controller.get_analog(ANALOG_RIGHT_Y)); right2.move(controller.get_analog(ANALOG_RIGHT_Y)); }
#include<iostream.h> #include<conio.h> class emp { public: int no; char name[20],des[20]; void get() { cout<<"\n Enter the Employee No:"; cin>>no; cout<<"\n Enter the Employee Name:"; cin>>name; cout<<"\n Enter the Designation:"; cin>>des; } }; class sal : public emp { float bs,hra,da,pf,ns; public: void get1() { cout<<"\nEnter the Basic Salary:"; cin>>bs; cout<<"\n Enter the Human Resource:"; cin>>hra; cout<<"\n Enter the Deaness Allowance:"; cin>>da; cout<<"\n Enter the Profibality Fund:"; cin>>pf; } void cal() { ns=bs+hra+da-pf; } void disp() { cout<<no<<"\t"<<name<<"\t"<<des<<"\t"<<bs<<"\t\t"<<hra<<"\t"<<da<<"\t"<<pf<<"\t"<<ns<<"\n"; } }; void main() { int i,n; char ch; sal s[10]; clrscr(); cout<<"\nEnter the Number Of Employee::"; cin>>n; for(i=0;i<n;i++) { s[i].get(); s[i].get1(); s[i].cal(); } cout<<"\n Eno \t Ename \t Des \t BASICSAL \t HRA \t DA \t PF \t NS \n"; for(i=0;i<=n;i++) { s[i].disp(); } getch(); }
#include "wizDatabaseManager.h" #include <QDebug> CWizDatabaseManager::CWizDatabaseManager(const QString& strUserId) : m_strUserId(strUserId) , m_dbPrivate(NULL) { } CWizDatabaseManager::~CWizDatabaseManager() { closeAll(); } bool CWizDatabaseManager::open(const QString& strKbGUID) { Q_ASSERT(!m_strUserId.isEmpty()); CWizDatabase* db = new CWizDatabase(); bool ret = false; if (strKbGUID.isEmpty()) { ret = db->openPrivate(m_strUserId, m_strPasswd); } else { ret = db->openGroup(m_strUserId, strKbGUID); } if (!ret) { delete db; return false; } initSignals(db); if (strKbGUID.isEmpty()) { m_dbPrivate = db; } else { m_dbGroups.append(db); } Q_EMIT databaseOpened(strKbGUID); return true; } bool CWizDatabaseManager::openAll() { // first, open private db if (!open()) { TOLOG("open user private database failed"); return false; } // second, get groups info CWizGroupDataArray arrayGroup; if (!m_dbPrivate->getUserGroupInfo(arrayGroup)) { TOLOG("Failed to get user group info"); return true; } // third, open groups one by one CWizGroupDataArray::const_iterator it; for (it = arrayGroup.begin(); it != arrayGroup.end(); it++) { WIZGROUPDATA group = *it; if (!open(group.strGroupGUID)) { TOLOG1("failed to open group: %1", group.strGroupName); } } return true; } bool CWizDatabaseManager::isOpened(const QString& strKbGUID) { if (strKbGUID.isEmpty() || m_dbPrivate->kbGUID() == strKbGUID) { return true; } QList<CWizDatabase*>::const_iterator it; for (it = m_dbGroups.begin(); it != m_dbGroups.end(); it++) { CWizDatabase* db = *it; if (db->kbGUID() == strKbGUID) { return true; } } return false; } bool CWizDatabaseManager::isPrivate(const QString& strKbGUID) { Q_ASSERT(!strKbGUID.isEmpty()); if (m_dbPrivate->kbGUID() == strKbGUID) { return true; } return false; } CWizDatabase& CWizDatabaseManager::db(const QString& strKbGUID) { Q_ASSERT(m_dbPrivate); if (strKbGUID.isEmpty() || m_dbPrivate->kbGUID() == strKbGUID) { return *m_dbPrivate; } QList<CWizDatabase*>::const_iterator it; for (it = m_dbGroups.begin(); it != m_dbGroups.end(); it++) { CWizDatabase* db = *it; if (db->kbGUID() == strKbGUID) { return *db; } } qDebug() << "Wow, request db not exist: " << strKbGUID; //Q_ASSERT(0); return *m_dbPrivate; } void CWizDatabaseManager::Guids(QStringList& strings) { QList<CWizDatabase*>::const_iterator it; for (it = m_dbGroups.begin(); it != m_dbGroups.end(); it++) { CWizDatabase* db = *it; strings.append(db->kbGUID()); } } int CWizDatabaseManager::count() { return m_dbGroups.size(); } CWizDatabase& CWizDatabaseManager::at(int i) { Q_ASSERT(i < count() && i >= 0); CWizDatabase* db = m_dbGroups.value(i); return *db; } bool CWizDatabaseManager::removeKb(const QString& strKbGUID) { Q_UNUSED(strKbGUID); return false; } bool CWizDatabaseManager::close(const QString& strKbGUID) { // should close all groups db before close user db. if (!m_dbGroups.isEmpty()) { Q_ASSERT(!strKbGUID.isEmpty()); } bool closed = false; QList<CWizDatabase*>::iterator it; for (it = m_dbGroups.begin(); it != m_dbGroups.end(); it++) { CWizDatabase* db = *it; if (db->kbGUID() == strKbGUID) { db->Close(); m_dbGroups.erase(it); closed = true; break; } } if (!closed && !strKbGUID.isEmpty()) { TOLOG("WARNING: nothing closed, guid not found"); return false; } Q_EMIT databaseClosed(strKbGUID); return true; } void CWizDatabaseManager::closeAll() { QList<CWizDatabase*>::iterator it; for (it = m_dbGroups.begin(); it != m_dbGroups.end(); it++) { CWizDatabase* db = *it; close(db->kbGUID()); } // close private db at last close(); } void CWizDatabaseManager::initSignals(CWizDatabase* db) { connect(db, SIGNAL(databaseRename(const QString&)), SIGNAL(databaseRename(const QString&))); connect(db, SIGNAL(databasePermissionChanged(const QString&)), SIGNAL(databasePermissionChanged(const QString&))); connect(db, SIGNAL(tagCreated(const WIZTAGDATA&)), SIGNAL(tagCreated(const WIZTAGDATA&))); connect(db, SIGNAL(tagModified(const WIZTAGDATA&, const WIZTAGDATA&)), SIGNAL(tagModified(const WIZTAGDATA&, const WIZTAGDATA&))); connect(db, SIGNAL(tagDeleted(const WIZTAGDATA&)), SIGNAL(tagDeleted(const WIZTAGDATA&))); connect(db, SIGNAL(styleCreated(const WIZSTYLEDATA&)), SIGNAL(styleCreated(const WIZSTYLEDATA&))); connect(db, SIGNAL(styleModified(const WIZSTYLEDATA&, const WIZSTYLEDATA&)), SIGNAL(styleModified(const WIZSTYLEDATA&, const WIZSTYLEDATA&))); connect(db, SIGNAL(styleDeleted(const WIZSTYLEDATA&)), SIGNAL(styleDeleted(const WIZSTYLEDATA&))); connect(db, SIGNAL(documentCreated(const WIZDOCUMENTDATA&)), SIGNAL(documentCreated(const WIZDOCUMENTDATA&))); connect(db, SIGNAL(documentModified(const WIZDOCUMENTDATA&, const WIZDOCUMENTDATA&)), SIGNAL(documentModified(const WIZDOCUMENTDATA&, const WIZDOCUMENTDATA&))); connect(db, SIGNAL(documentDeleted(const WIZDOCUMENTDATA&)), SIGNAL(documentDeleted(const WIZDOCUMENTDATA&))); connect(db, SIGNAL(documentTagModified(const WIZDOCUMENTDATA&)), SIGNAL(documentTagModified(const WIZDOCUMENTDATA&))); connect(db, SIGNAL(documentDataModified(const WIZDOCUMENTDATA&)), SIGNAL(documentDataModified(const WIZDOCUMENTDATA&))); connect(db, SIGNAL(documentAbstractModified(const WIZDOCUMENTDATA&)), SIGNAL(documentAbstractModified(const WIZDOCUMENTDATA&))); connect(db, SIGNAL(attachmentCreated(const WIZDOCUMENTATTACHMENTDATA&)), SIGNAL(attachmentCreated(const WIZDOCUMENTATTACHMENTDATA&))); connect(db, SIGNAL(attachmentModified(const WIZDOCUMENTATTACHMENTDATA&, const WIZDOCUMENTATTACHMENTDATA&)), SIGNAL(attachmentModified(const WIZDOCUMENTATTACHMENTDATA&, const WIZDOCUMENTATTACHMENTDATA&))); connect(db, SIGNAL(attachmentDeleted(const WIZDOCUMENTATTACHMENTDATA&)), SIGNAL(attachmentDeleted(const WIZDOCUMENTATTACHMENTDATA&))); connect(db, SIGNAL(folderCreated(const QString&)), SIGNAL(folderCreated(const QString&))); connect(db, SIGNAL(folderDeleted(const QString&)), SIGNAL(folderDeleted(const QString&))); }
#ifndef REMOVECOMPONENT_H #define REMOVECOMPONENT_H #include "command.h" #include "room.h" class RemoveComponent: public Command { public: RemoveComponent(Room *r); void execute(std::string s); protected: Room *_room; }; #endif // REMOVECOMPONENT_H
/* Copyright (c) 2005-2023, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TARGETEDCELLKILLER_HPP_ #define TARGETEDCELLKILLER_HPP_ #include "AbstractCellKiller.hpp" #include "ChasteSerialization.hpp" #include <boost/serialization/base_object.hpp> /** * Simple cell killer, which at the first timestep kills any cell * whose corresponding location index is a given number. */ template<unsigned DIM> class TargetedCellKiller : public AbstractCellKiller<DIM> { private: /** * The index of the cell to kill */ unsigned mTargetIndex; /** * Variable to reack when the cell has been killed. * Once the cell has been called mBloodLust will stop the killer killing more cells. */ bool mBloodLust; /** Needed for serialization. */ friend class boost::serialization::access; /** * Archive the object. * * @param archive the archive * @param version the current version of this class */ template<class Archive> void serialize(Archive & archive, const unsigned int version) { archive & boost::serialization::base_object<AbstractCellKiller<DIM> >(*this); // archive & mTargetIndex; // done in load_construct_data // archive & mBloodlust; // done in load_construct_data } public: /** * Default constructor. * * @param pCellPopulation pointer to the cell population * @param targetedIndex The index of the cell to kill * @param bloodLust Wether to kill cells or not defaults to true (used by load methods) */ TargetedCellKiller(AbstractCellPopulation<DIM>* pCellPopulation, unsigned targetedIndex, bool bloodLust = true); /** * @return mTargetIndex. */ unsigned GetTargetIndex() const; /** * @return mBloodLust. */ unsigned GetBloodLust() const; /** * Loop over cells and start apoptosis randomly, based on the user-set * probability. */ void CheckAndLabelCellsForApoptosisOrDeath(); /** * Overridden OutputCellKillerParameters() method. * * @param rParamsFile the file stream to which the parameters are output */ void OutputCellKillerParameters(out_stream& rParamsFile); }; #include "SerializationExportWrapper.hpp" EXPORT_TEMPLATE_CLASS_SAME_DIMS(TargetedCellKiller) namespace boost { namespace serialization { /** * Serialize information required to construct a TargetedCellKiller. */ template<class Archive, unsigned DIM> inline void save_construct_data( Archive & ar, const TargetedCellKiller<DIM> * t, const unsigned int file_version) { // Save data required to construct instance const AbstractCellPopulation<DIM>* const p_cell_population = t->GetCellPopulation(); ar << p_cell_population; unsigned targeted_index = t->GetTargetIndex(); ar << targeted_index; bool blood_lust = t->GetBloodLust(); ar << blood_lust; } /** * De-serialize constructor parameters and initialise a TargetedCellKiller. */ template<class Archive, unsigned DIM> inline void load_construct_data( Archive & ar, TargetedCellKiller<DIM> * t, const unsigned int file_version) { // Retrieve data from archive required to construct new instance AbstractCellPopulation<DIM>* p_cell_population; ar >> p_cell_population; unsigned targeted_index; ar >> targeted_index; bool blood_lust; ar >> blood_lust; // Invoke inplace constructor to initialise instance ::new(t)TargetedCellKiller<DIM>(p_cell_population, targeted_index, blood_lust); } } } // namespace ... #endif /*TARGETEDCELLKILLER_HPP_*/
/*========================================================================= Program: ParaView Module: vtkSelection.h Copyright (c) Kitware, Inc. All rights reserved. See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /** * @class vtkSelection * @brief data object that represents a "selection" in VTK. * * vtkSelection is a data object that represents a selection definition. It is * used to define the elements that are selected. The criteria of the selection * is defined using one or more vtkSelectionNode instances. Parameters of the * vtkSelectionNode define what kind of elements are being selected * (vtkSelectionNode::GetFieldType), how the selection criteria is defined * (vtkSelectionNode::GetContentType), etc. * * Filters like vtkExtractSelection, vtkExtractDataArraysOverTime can be used to * extract the selected elements from a dataset. * * @section CombiningSelection Combining Selections * * When a vtkSelection contains multiple vtkSelectionNode instances, the * selection defined is a union of all the elements identified by each of the * nodes. * * Optionally, one can use `vtkSelection::SetExpression` to define a boolean * expression to build arbitrarily complex combinations. The expression can be * defined using names assigned to the selection nodes when the nodes are added * to vtkSelection (either explicitly or automatically). * * @sa * vtkSelectionNode */ #ifndef vtkSelection_h #define vtkSelection_h #include "vtkCommonDataModelModule.h" // For export macro #include "vtkDataObject.h" #include "vtkSmartPointer.h" // for vtkSmartPointer. #include <memory> // for unique_ptr. #include <string> // for string. class vtkSelectionNode; class vtkSignedCharArray; class VTKCOMMONDATAMODEL_EXPORT vtkSelection : public vtkDataObject { public: vtkTypeMacro(vtkSelection, vtkDataObject); void PrintSelf(ostream& os, vtkIndent indent) override; static vtkSelection* New(); /** * Restore data object to initial state, */ void Initialize() override; /** * Returns VTK_SELECTION enumeration value. */ int GetDataObjectType() override { return VTK_SELECTION; } /** * Returns the number of nodes in this selection. * Each node contains information about part of the selection. */ unsigned int GetNumberOfNodes() const; /** * Returns a node given it's index. Performs bound checking * and will return nullptr if out-of-bounds. */ virtual vtkSelectionNode* GetNode(unsigned int idx) const; /** * Returns a node with the given name, if present, else nullptr is returned. */ virtual vtkSelectionNode* GetNode(const std::string& name) const; /** * Adds a selection node. Assigns the node a unique name and returns that * name. This API is primarily provided for backwards compatibility and * `SetNode` is the preferred method. */ virtual std::string AddNode(vtkSelectionNode*); /** * Adds a vtkSelectionNode and assigns it the specified name. The name * must be a non-empty string. If an item with the same name * has already been added, it will be removed. */ virtual void SetNode(const std::string& name, vtkSelectionNode*); /** * Returns the name for a node at the given index. */ virtual std::string GetNodeNameAtIndex(unsigned int idx) const; //@{ /** * Removes a selection node. */ virtual void RemoveNode(unsigned int idx); virtual void RemoveNode(const std::string& name); virtual void RemoveNode(vtkSelectionNode*); //@} /** * Removes all selection nodes. */ virtual void RemoveAllNodes(); //@{ /** * Get/Set the expression that defines the boolean expression to combine the * selection nodes. Expression consists of node name identifiers, `|` for * boolean-or, '&' for boolean and, '!' for boolean not, and parenthesis `(` * and `)`. If the expression consists of a node name identifier that is not * assigned any `vtkSelectionNode` (using `SetNode`) then it is evaluates to * `false`. * * `SetExpression` does not validate the expression. It will be validated in * `Evaluate` call. */ vtkSetMacro(Expression, std::string); vtkGetMacro(Expression, std::string); //@} /** * Copy selection nodes of the input. */ void DeepCopy(vtkDataObject* src) override; /** * Copy selection nodes of the input. * This is a shallow copy: selection lists and pointers in the * properties are passed by reference. */ void ShallowCopy(vtkDataObject* src) override; /** * Union this selection with the specified selection. * Attempts to reuse selection nodes in this selection if properties * match exactly. Otherwise, creates new selection nodes. */ virtual void Union(vtkSelection* selection); /** * Union this selection with the specified selection node. * Attempts to reuse a selection node in this selection if properties * match exactly. Otherwise, creates a new selection node. */ virtual void Union(vtkSelectionNode* node); /** * Remove the nodes from the specified selection from this selection. * Assumes that selection node internal arrays are vtkIdTypeArrays. */ virtual void Subtract(vtkSelection* selection); /** * Remove the nodes from the specified selection from this selection. * Assumes that selection node internal arrays are vtkIdTypeArrays. */ virtual void Subtract(vtkSelectionNode* node); /** * Return the MTime taking into account changes to the properties */ vtkMTimeType GetMTime() override; //@{ /** * Dumps the contents of the selection, giving basic information only. */ virtual void Dump(); virtual void Dump(ostream& os); //@} //@{ /** * Retrieve a vtkSelection stored inside an invormation object. */ static vtkSelection* GetData(vtkInformation* info); static vtkSelection* GetData(vtkInformationVector* v, int i = 0); //@} /** * Evaluates the expression for each element in the values. The order * matches the order of the selection nodes. If not expression is set or if * it's an empty string, then an expression that simply combines all selection * nodes in an binary-or is assumed. */ vtkSmartPointer<vtkSignedCharArray> Evaluate( vtkSignedCharArray* const* values, unsigned int num_values) const; /** * Convenience method to pass a map of vtkSignedCharArray ptrs (or * vtkSmartPointers). */ template <typename MapType> vtkSmartPointer<vtkSignedCharArray> Evaluate(const MapType& values_map) const; protected: vtkSelection(); ~vtkSelection() override; std::string Expression; private: vtkSelection(const vtkSelection&) = delete; void operator=(const vtkSelection&) = delete; class vtkInternals; vtkInternals* Internals; }; //---------------------------------------------------------------------------- template <typename MapType> inline vtkSmartPointer<vtkSignedCharArray> vtkSelection::Evaluate(const MapType& values_map) const { const unsigned int num_nodes = this->GetNumberOfNodes(); std::unique_ptr<vtkSignedCharArray*[]> values(new vtkSignedCharArray*[num_nodes]); for (unsigned int cc = 0; cc < num_nodes; ++cc) { auto iter = values_map.find(this->GetNodeNameAtIndex(cc)); values[cc] = iter != values_map.end() ? iter->second : nullptr; } return this->Evaluate(&values[0], num_nodes); } #endif
#include <winsock2.h> #include <iostream> #define SUCCESS 0 #define ERROR 1 #define END_LINE 0x0 #define SERVER_PORT 1500 #define MAX_MSG int main() { SOCKET socket = SOCKER return 0; }
#ifndef KARTA_H_INCLUDED #define KARTA_H_INCLUDED #include <iostream> #include "dinstring.cpp" using namespace std; class Karta{ protected: DinString mestoPolaska, mestoDolaska; float duzinaPutovanja, cenaKarte; int identifikatorKarte; public: Karta(); Karta(DinString, DinString, float, float, int); virtual bool jeftinaKarta() = 0; DinString getMestoPolaska()const; DinString getMestoDolaska()const; float getDuzinaPutovanja()const; float getCenaKarte()const; int getIdentifikatorKarte()const; }; Karta::Karta() : mestoPolaska(), mestoDolaska(){ duzinaPutovanja = 0; cenaKarte = 0; identifikatorKarte = 0; } Karta::Karta(DinString polazak, DinString dolazak, float d, float c, int id){ mestoPolaska = polazak; mestoDolaska = dolazak; duzinaPutovanja = d; cenaKarte = c; identifikatorKarte = id; } DinString Karta::getMestoPolaska()const{ return mestoPolaska; } DinString Karta::getMestoDolaska()const{ return mestoDolaska; } float Karta::getDuzinaPutovanja()const{ return duzinaPutovanja; } float Karta::getCenaKarte()const{ return cenaKarte; } int Karta::getIdentifikatorKarte()const{ return identifikatorKarte; } #endif // KARTA_H_INCLUDED
/* * test_ros_wrapper.cpp * * Created on: Dec 5, 2016 * Author: silence */ #include "dragon_driver/propagate/propagate.h" #include "dragon_driver/middleware.h" #include "dragon_driver/hardware/hw_unit.h" #include "dragon_driver/util/parser.h" #include "dragon_driver/ros_wrapper.h" #include <iostream> int main(int argc, char* argv[]) { bool use_sim_time = false; ros::init(argc, argv, "dragon_driver"); ros::NodeHandle nh; if (ros::param::get("use_sim_time", use_sim_time)) { LOG_INFO << ("use_sim_time is set!!"); } middleware::RosWrapper* interface = middleware::RosWrapper::getInstance(); if (nullptr == interface) { LOG_FATAL << "Can't get the instance of QrRosWrapper!"; return -1; } interface->start(); ros::AsyncSpinner spinner(3); spinner.start(); ros::waitForShutdown(); interface->halt(); LOG_INFO << "dragon_driver shutdown... ..."; return 0; }
/** * @file TraversalOption.h * @author F. Gratl * @date 1/18/19 */ #pragma once #include <set> namespace autopas { /** * Possible choices for the cell pair traversal. */ enum TraversalOption { c08 = 0, sliced = 1, c18 = 2, c01 = 3, directSumTraversal = 4, slicedVerlet = 5, c18Verlet = 6, c01Verlet = 7, c01Cuda = 8, verletTraversal = 9, c01CombinedSoA = 10, verletClusters = 11, c04 = 12, varVerletTraversalAsBuild = 13, verletClustersColoring = 14, c04SoA = 15, }; /** * Provides a way to iterate over the possible choices of TraversalOption. */ static const std::set<TraversalOption> allTraversalOptions = { TraversalOption::c08, TraversalOption::sliced, TraversalOption::c18, TraversalOption::c01, TraversalOption::directSumTraversal, TraversalOption::slicedVerlet, TraversalOption::c18Verlet, TraversalOption::c01Verlet, TraversalOption::c01Cuda, TraversalOption::verletTraversal, TraversalOption::c01CombinedSoA, TraversalOption::verletClusters, TraversalOption::c04, TraversalOption::varVerletTraversalAsBuild, TraversalOption::verletClustersColoring, TraversalOption::c04SoA, }; } // namespace autopas
/* KJL 12:27:18 26/06/98 - AvP_MenuGfx.hpp */ enum AVPMENUGFX_ID { AVPMENUGFX_CLOUDY, AVPMENUGFX_SMALL_FONT, AVPMENUGFX_COPYRIGHT_SCREEN, AVPMENUGFX_PRESENTS, AVPMENUGFX_AREBELLIONGAME, AVPMENUGFX_ALIENSVPREDATOR, AVPMENUGFX_SLIDERBAR, AVPMENUGFX_SLIDER, AVPMENUGFX_BACKDROP, AVPMENUGFX_ALIENS_LOGO, AVPMENUGFX_ALIEN_LOGO, AVPMENUGFX_MARINE_LOGO, AVPMENUGFX_PREDATOR_LOGO, AVPMENUGFX_GLOWY_LEFT, AVPMENUGFX_GLOWY_MIDDLE, AVPMENUGFX_GLOWY_RIGHT, AVPMENUGFX_MARINE_EPISODE1, AVPMENUGFX_MARINE_EPISODE2, AVPMENUGFX_MARINE_EPISODE3, AVPMENUGFX_MARINE_EPISODE4, AVPMENUGFX_MARINE_EPISODE5, AVPMENUGFX_MARINE_EPISODE6, AVPMENUGFX_MARINE_EPISODE7, AVPMENUGFX_MARINE_EPISODE8, AVPMENUGFX_MARINE_EPISODE9, AVPMENUGFX_MARINE_EPISODE10, AVPMENUGFX_MARINE_EPISODE11, AVPMENUGFX_PREDATOR_EPISODE1, AVPMENUGFX_PREDATOR_EPISODE2, AVPMENUGFX_PREDATOR_EPISODE3, AVPMENUGFX_PREDATOR_EPISODE4, AVPMENUGFX_PREDATOR_EPISODE5, AVPMENUGFX_PREDATOR_EPISODE6, AVPMENUGFX_PREDATOR_EPISODE7, AVPMENUGFX_PREDATOR_EPISODE8, AVPMENUGFX_PREDATOR_EPISODE9, AVPMENUGFX_PREDATOR_EPISODE10, AVPMENUGFX_PREDATOR_EPISODE11, AVPMENUGFX_ALIEN_EPISODE1, AVPMENUGFX_ALIEN_EPISODE2, AVPMENUGFX_ALIEN_EPISODE3, AVPMENUGFX_ALIEN_EPISODE4, AVPMENUGFX_ALIEN_EPISODE5, AVPMENUGFX_ALIEN_EPISODE6, AVPMENUGFX_ALIEN_EPISODE7, AVPMENUGFX_ALIEN_EPISODE8, AVPMENUGFX_ALIEN_EPISODE9, AVPMENUGFX_ALIEN_EPISODE10, AVPMENUGFX_WINNER_SCREEN, AVPMENUGFX_SPLASH_SCREEN1, AVPMENUGFX_SPLASH_SCREEN2, AVPMENUGFX_SPLASH_SCREEN3, AVPMENUGFX_SPLASH_SCREEN4, AVPMENUGFX_SPLASH_SCREEN5, MAX_NO_OF_AVPMENUGFXS, }; typedef struct { char *FilenamePtr; LPDIRECTDRAWSURFACE ImagePtr; AW_BACKUPTEXTUREHANDLE hBackup; int Width; int Height; } AVPMENUGFX; enum AVPMENUFORMAT_ID { AVPMENUFORMAT_LEFTJUSTIFIED, AVPMENUFORMAT_RIGHTJUSTIFIED, AVPMENUFORMAT_CENTREJUSTIFIED, }; extern void LoadAvPMenuGfx(enum AVPMENUGFX_ID menuGfxID); extern void LoadAllAvPMenuGfx(void); extern void LoadAllSplashScreenGfx(void); extern void ReleaseAllAvPMenuGfx(void); extern int RenderMenuText(char *textPtr, int x, int y, int alpha, enum AVPMENUFORMAT_ID format); extern int RenderSmallMenuText(char *textPtr, int x, int y, int alpha, enum AVPMENUFORMAT_ID format); extern int RenderSmallMenuText_Coloured(char *textPtr, int x, int y, int alpha, enum AVPMENUFORMAT_ID format, int red, int green, int blue); extern int Hardware_RenderSmallMenuText(char *textPtr, int x, int y, int alpha, enum AVPMENUFORMAT_ID format); extern int Hardware_RenderSmallMenuText_Coloured(char *textPtr, int x, int y, int alpha, enum AVPMENUFORMAT_ID format, int red, int green, int blue); extern int RenderMenuText_Clipped(char *textPtr, int x, int y, int alpha, enum AVPMENUFORMAT_ID format, int topY, int bottomY); extern void RenderSmallFontString_Wrapped(char *textPtr,RECT* area,int alpha,int* output_x,int* output_y); extern void DrawAvPMenuGfx(enum AVPMENUGFX_ID menuGfxID, int topleftX, int topleftY, int alpha,enum AVPMENUFORMAT_ID format); extern void DrawAvPMenuGfx_Clipped(enum AVPMENUGFX_ID menuGfxID, int topleftX, int topleftY, int alpha,enum AVPMENUFORMAT_ID format, int topY, int bottomY); extern void DrawAvPMenuGfx_CrossFade(enum AVPMENUGFX_ID menuGfxID,enum AVPMENUGFX_ID menuGfxID2,int alpha); extern void DrawAvPMenuGfx_Faded(enum AVPMENUGFX_ID menuGfxID, int topleftX, int topleftY, int alpha,enum AVPMENUFORMAT_ID format); extern int HeightOfMenuGfx(enum AVPMENUGFX_ID menuGfxID); extern void ClearScreenToBlack(void);
#include <vector> #include <iostream> #include <queue> using namespace std; // TREENODE CLASS CREATION template <typename T> class TreeNode{ public: int data; vector<TreeNode<int>*> children; TreeNode(int data){ this->data = data; } }; //TAKING INPUT A TREE RECURSIVELY TreeNode<int>* takeInputRecursive(){ int rootData; cout<<"Enter node: "; cin>>rootData; TreeNode<int> *root = new TreeNode<int>(rootData); int numChild; cout<<"Enter no. of children of node: "; cin>>numChild; for(int i=0; i<numChild; i++){ TreeNode<int> *child = takeInputRecursive(); //Each child node is inserted into // the list of children nodes. root->children.push_back(child); } return root; } // PRINT TREE RECURSIVELY void printRecursive(TreeNode<int>* root){ if(root == NULL){ return; } cout<<root->data<<":"; for(int i=0; i<root->children.size(); i++){ cout<<root->children[i]->data<<" "; } cout<<endl; for(int i=0; i<root->children.size(); i++){ printRecursive(root->children[i]); } } // TAKING INPUT A TREE LEVEL-WISE TreeNode<int>* takeInputLevelWise(){ int rootData; cout<<"Enter root of tree: "; cin>>rootData; TreeNode<int> *root = new TreeNode<int>(rootData); queue<TreeNode<int>*> pendingNodes; pendingNodes.push(root); while(pendingNodes.size() != 0){ TreeNode<int> *front = pendingNodes.front(); pendingNodes.pop(); int numChild; cout<<"Enter no. of children of node: "; cin>>numChild; for(int i=0; i<numChild; i++){ int childData; cout<<"Enter child of node: "; cin>>childData; TreeNode<int> *child = new TreeNode<int>(childData); front->children.push_back(child); pendingNodes.push(child); } } return root; } // PRINT A TREE LEVEL-WISE void printLevelWise(TreeNode<int> *root){ if(root == NULL){ return; } queue<TreeNode<int>*> pendingNodes; TreeNode<int>* front = root; pendingNodes.push(front); while(pendingNodes.size() != 0){ TreeNode<int> *node = pendingNodes.front(); cout<<node->data<<":"; pendingNodes.pop(); for(int i=0; i< node->children.size(); i++){ if((i+1) == node->children.size()){ cout<<node->children[i]->data; } else{ cout<<node->children[i]->data<<","; } pendingNodes.push(node->children[i]); } cout<<endl; } } // COUNT NODES IN A TREE int count(TreeNode<int>* root){ //Edge Case if(root == NULL){ return 0; } int countnodes = 1; for(int i=0; i<root->children.size(); i++){ countnodes = countnodes + count(root->children[i]); } return countnodes; } //SUM OF NODES IN A TREE int sum(TreeNode<int> *root){ //Edge Case if(root == NULL){ return 0; } int sumnodes = root->data; for(int i=0; i<root->children.size(); i++){ sumnodes = sumnodes + sum(root->children[i]); } return sumnodes; } //MAXIMUM DATA NODE IN A TREE TreeNode<int>* maxNode(TreeNode<int> *root){ //Edge Case if(root == NULL){ return NULL; } TreeNode<int> *max = root; for(int i=0; i<root->children.size(); i++){ TreeNode<int> *ans = maxNode(root->children[i]); if(ans->data > max->data){ max = ans; } } return max; } //FIND HEIGHT OF TREE int heightOfTree(TreeNode<int> *root){ //Edge Case if(root == NULL){ return 0; } int ans = 0; for(int i=0; i<root->children.size(); i++){ int height = heightOfTree(root->children[i]); ans = max(ans, height); } return ans+1; } //COUNT LEAF NODES IN A TREE int countLeafNodes(TreeNode<int>* root){ if(root == NULL){ return 0; } int count = 0; if(root->children.size() == 0){ count += 1; } for(int i=0; i<root->children.size(); i++){ count += countLeafNodes(root->children[i]); } return count; } //POSTORDER TRAVERSAL void postOrderTraversal(TreeNode<int> *root){ if(root == NULL){ return; } for(int i=0; i<root->children.size(); i++){ postOrderTraversal(root->children[i]); } cout<<root->data<<" "; } //PREORDER TRAVERSAL void preOrderTraversal(TreeNode<int> *root){ if(root == NULL){ return; } cout<<root->data<<" "; for(int i=0; i<root->children.size(); i++){ preOrderTraversal(root->children[i]); } } //CHECK IF X IS PRESENT IN THE TREE bool isPresent(TreeNode<int> *root ,int x){ if(root == NULL){ return false; } if(root->data == x){ return true; } for(int i=0; i<root->children.size(); i++){ bool ans = isPresent(root->children[i], x); if(ans == true){ return ans; } } return false; } //COUNT NODES WHICH CONTAIN DATA GREATER THAN X int getLargeNodesCount(TreeNode<int> *root, int x){ if(root == NULL){ return 0; } int count = 0; if(root->data > x){ count += 1; } for(int i=0; i<root->children.size(); i++){ count += getLargeNodesCount(root->children[i], x); } return count; } //CHECK IF TWO TREES ARE STRUCTURALLY IDENTICAL bool isIdentical(TreeNode<int> *root1, TreeNode<int> *root2){ if(root1 == NULL || root2 == NULL){ return false; } if(root1->children.size() != root2->children.size()){ return false; } bool ans = false; if(root1->data == root2->data){ ans = true; } for(int i=0; i<root1->children.size(); i++){ ans = isIdentical(root1->children[i], root2->children[i]); // if(ans == true){ // return ans; // } } return ans; } int main(){ //TreeNode<int> *root = takeInputRecursive(); TreeNode<int> *root = takeInputLevelWise(); //printRecursive(root); printLevelWise(root); cout<<"No. of nodes in the tree: "<< count(root)<< endl; cout<<"Sum of nodes in the tree: "<< sum(root)<< endl; cout<<"Max data node in the tree: "<< maxNode(root)->data<< endl; cout<<"Height of tree: "<<heightOfTree(root)<<endl; cout<<"Leaf nodes in the tree: "<<countLeafNodes(root)<<endl; cout<<"Post-Order Traversal of Tree: "; postOrderTraversal(root); cout<<"\n Pre-Order Traversal of Tree: "; preOrderTraversal(root); cout<<"\n 30 is present in Tree: "<< isPresent(root, 30)<<endl; cout<<"80 is present in Tree: "<< isPresent(root, 80)<<endl; cout<<"Nodes count which have value greater than x: "<<getLargeNodesCount(root, 5); cout<<"\nIdentical Trees Check: "<<isIdentical(root, root); return 0; }
// // Created by Will Smith on 4/12/18. // #include "Dodec.h" double Dodec::calcArea() { return 0; }
/*! *@FileName: KaiXinApp_PokeList.h *@Author: GoZone *@Date: *@Log: Author Date Description * *@section Copyright * =======================================================================<br> * Copyright ? 2010-2012 GOZONE <br> * All Rights Reserved.<br> * The file is generated by Kaixin_Component Wizard for Tranzda Mobile Platform <br> * =======================================================================<br> */ #ifndef __KAIXINAPI_POKELIST_H__ #define __KAIXINAPI_POKELIST_H__ #include "KaiXinAPI.h" //动它一下最大条数 #define KX_POKE_ITEM_MAX_COUNT (64) typedef struct { char action[32]; char actionname[255]; }PokeList_pokes; typedef struct { int ret; char uid[32]; int nSize_pokes; //Save the array size by code_gen tools. PokeList_pokes* pokes; }tResponsePokeList; typedef struct { char uid[32]; TUChar name[32]; }PokeUserData; extern void* KaiXinAPI_PokeList_JsonParse(char *text); typedef struct { int ret; char uid[32]; char wordsucc[256]; }tResponseSendPoke; extern void* KaiXinAPI_SendPoke_JsonParse(char *text); class TPokeListForm : public TWindow { public: TPokeListForm(TApplication* pApp); TPokeListForm(TApplication* pApp, PokeUserData userData); virtual ~TPokeListForm(void); virtual Boolean EventHandler(TApplication * appP, EventType * eventP); private: Boolean _OnWinInitEvent(TApplication * pApp, EventType * pEvent); Boolean _OnWinClose(TApplication * pApp, EventType * pEvent); Boolean _OnCtrlSelectEvent(TApplication * pApp, EventType * pEvent); Int32 _SetPokeList(TApplication * pApp); private: tResponsePokeList* Response; PokeUserData mUserData; TRadioButton* tRadioBtn[KX_POKE_ITEM_MAX_COUNT];//用于存储RadioButton 指针 Int32 m_BackBtn; }; #endif
#ifndef GAMEWORLD_H #define GAMEWORLD_H #include "pacman-main.h" #include <iostream> /// bleeaaaaaaagh. Because you love it. #include <fstream> /// blaaaaaaaaargh. For ifstream. #include <vector> using namespace std ; // This GameWorld class is a // super-container for all // the game world data. // There should only ever be // one copy of the GameWorld object // in our game // The GameWorld contains Tiles and GameObjects and // stats, basically #include "EnumDefinitions.h" #include "Vector2.h" #include "Tile.h" #include "GameObject.h" #include "FourDirectionMovingObject.h" #include "Player.h" #include "Ghost.h" class GameWorld { public: // define game-wide vars // We have to have a WAY to __STORE AND REMEMBER__ // game world data for the level. // We'll do this by keeping a 2D array // of pointers to "Tile" objects. // A "Tile" object represents a game-world tile, // and its defined in Tile.h. // For simplicity, we'll use a // FIXED height/width const static int mapRows = 27 ; const static int mapCols = 21 ; const static int tileSize = 16 ; // Tile size, in pixels. // Each tile is 16x16 pixels. int levelNumber ; // what level number you're on // For re-use when pacman dies Coord pacmanStartPosition ; // This game has a couple of states. // I number them explicitly for easy reference enum GameState { /// The splash screen is where you display your /// company logo etc Splash = 1, /// The menu screen where you start /// to choose what mode to play in or whatever Menu = 2, /// The game is ACTUALLY RUNNING. Most time /// is spent in this state. Running = 3, /// The game is PAUSED, from the running state. /// You may choose to continue to run the music, /// or run some alternate form of music during /// the Paused state, BUT YOU STILL NEED to draw /// the game out! Paused = 4, /// The game is over and the next logical step /// is to move back to the menu. GameOver= 5 }; #pragma region state-machines /* Allowable state transitions: Here's a rough ASCII state change diagram. Its a lot better to draw these in POWERPOINT or something. This actually LOOKS a lot more complicated than it is. Its just a diagram of WHAT STATES transition to WHAT STATES and how it happens. BOOT GAME | | (load minimal things to minimize wait) v Splash | | (load more things, takes a couple of sec.) | | v User "quit" ESC ---->Menu----------------> QUIT 5 sec ----/ | ^ ----/ |user "start game" | | | |user presses ESC | | | | | -----------------/ | | / / user dies v / User presses 'P' GameOver<--------Running <-------------> Paused */ #pragma endregion private: // Define the array to hold // the game level. Tile* level[ mapRows ][ mapCols ] ; // OPEN lvl1.txt TO SEE // Notice we're using pointers... // Notice also this could be layered... // Define the ASCIIMAP object // used only for pathfinding, // NOT for drawing or anything else. AsciiMap *asciiMap ; //!! Note - you might find a way to factor // together AsciiMap and that 2D // array of Tile* together. // If I re-coded this I might find a way to // unify AsciiMap and that Tile* array. // The GameState. GameState gameState ; private: // offset to draw the game board at float xBoardOffset, yBoardOffset, xStatsOffset, yStatsOffset ; Player *pacman ; vector<Ghost*> ghosts ; public: GameWorld() ; ~GameWorld() ; void destroyGameWorld() ; /// Gets the current gamestate GameState getState() ; /// Sets the gamestate to some new state void setState( GameState newState ) ; char* getLevelFilename( int levelNum ) ; /// Loads a level void loadLevel( char *filename ) ; /// Returns true if a level /// has been completed (all normal pellets eaten) bool levelDone() ; /// update the game just a fraction void step( float time ) ; /// Draw the game /// world board void drawBoard() ; /// Draws stat charts /// at right side of screen /// (lives, health, etc) void drawStats() ; /// Draws all game units /// order matters! the last thing /// you draw shows up on top. void drawPeople() ; private: void checkCoords( int & row, int & col ) ; public: Tile* getTileNearestLeft( Vector2 & pos ) ; Tile* getTileNearestRight( Vector2 & pos ) ; Tile* getTileNearestUp( Vector2 & pos ) ; Tile* getTileNearestDown( Vector2 & pos ) ; /// Gets you a specific tile /// at some location Tile* getTileAt( Vector2 & pos ) ; Coord getNearestCoord( Vector2 & pos ) ; Vector2 getVectorAt( const Coord & coord ) ; /// Gets you the vector you should /// use to draw at a certain coordinate Vector2 getDrawingVectorAt( const Coord & coord ) ; /// Gets you the drawing vector /// you should use to draw (just /// adds offsetX and offsetY to /// the vector Vector2 getDrawingVectorAt( const Vector2& pos ) ; Player *getPlayer() ; AsciiMap *getAsciiMap() ; } ; extern GameWorld *game ; // an extern is // like a "variable prototype". Declare one here, // and actually instantiate it in // the GameWorld.cpp file #endif
#include <stdlib.h> #include <iostream> #include "jvalue.h" using namespace std; int main() { const char *j1 = "{\"key3\":1.3E-3,\"key4\":false,\"key1\":1,\"key2\":\"test\"}"; jvalue *table; char *json; table = jvalue_read(j1, 0); json = jvalue_write(table, 0); cout << json << endl; free(json); jvalue_destroy(table); return 0; }
#include<iostream> #include<string> #include <fstream> #include "Continent.h" #include "Country.h" #include "Map.h" #include <sstream> #include "SaveLoadMapComponent.h" #include "MapEditorComponent.h" using namespace std; Map SaveLoadMapComponent::readMap(string mapName){ string line; ifstream myfile; myfile.open(mapName, ios::out | ios::app | ios::binary); if (myfile.is_open()) { Map map; string author; string image; bool wrap; string scroll; bool warn; while (getline(myfile, line)) { if (line == "[Map]\r"){ while (line != "\r") { getline(myfile, line); string delimiter = "="; string attribute = line.substr(0, line.find(delimiter)); string value = line.substr(line.find(delimiter) + 1); string delimiter2 = "\r"; string value2 = value.substr(0, value.find(delimiter2)); if (attribute == "author"){ author = value2; } if (attribute == "image"){ image = value2; } if (attribute == "wrap"){ wrap = value2 == "yes" ? true : false; } if (attribute == "scroll"){ scroll = value2; } if (attribute == "warn"){ warn = value2 == "yes" ? true : false; } } map = Map(author, image, wrap, scroll, warn); } if (line == "[Continents]\r"){ while (line != "\r") { getline(myfile, line); string delimiter = "="; string continentName = line.substr(0, line.find(delimiter)); string value = line.substr(line.find(delimiter) + 1); string delimiter2 = "\r"; string units = value.substr(0, value.find(delimiter2)); if (units != ""){ Continent continent = Continent(continentName, atoi(units.c_str())); map.Continents.push_back(continent); } } } if (line == "[Territories]\r"){ while (getline(myfile, line)) { string name; double latitude; double longitude; string continent; if (line != "\r"){ string::size_type equal = line.find(','); name = line.substr(0, equal); line = line.substr(equal + 1, line.length()); equal = line.find(','); string latitudeString = line.substr(0, equal); std::string::size_type sz; latitude = std::stod(latitudeString, &sz); line = line.substr(equal + 1, line.length()); equal = line.find(','); string longitudeString = line.substr(0, equal); longitude = std::stod(longitudeString, &sz); line = line.substr(equal + 1, line.length()); equal = line.find(','); continent = line.substr(0, equal); line = line.substr(equal + 1, line.length()); vector<Country*> adjacentTerritories; while (line.find(',') != std::string::npos || line.find("\r") != std::string::npos) { if (line.find(',') == std::string::npos) { equal = line.find("\r"); } else { equal = line.find(','); } string adjacentTerritory = line.substr(0, equal); line = line.substr(equal + 1, line.length()); adjacentTerritories.push_back(new Country(adjacentTerritory)); } Country* Territory = new Country(name, latitude, longitude, continent, adjacentTerritories); for (int i = 0; i < map.Continents.size(); i++) { if (map.Continents[i].getName() == continent) { map.Continents[i].Country.push_back(Territory); } } } } } } myfile.close(); vector<Country*> c; for (int i = 0; i < map.Continents.size(); i++){ for (int j = 0; j < map.Continents[i].Country.size(); j++){ for (int k = 0; k < map.Continents[i].Country[j]->getBorderingCountries().size(); k++){ for (int l = 0; l < map.Continents.size(); l++){ for (int m = 0; m < map.Continents[l].Country.size(); m++){ if (map.Continents[i].Country[j]->getBorderingCountries().at(k)->getName()== map.Continents[l].Country[m]->getName()){ c.push_back(map.Continents[l].Country[m]); } } } } map.Continents[i].Country[j]->setBorderingCountries(c); c.clear(); } } return map; } else cout << "Unable to open file"; } void SaveLoadMapComponent::saveMap(string saveMapName, Map map) { ofstream myfile; myfile.open(saveMapName, ios::out | ios::app | ios::binary); myfile << "[Map]" << "\r" <<endl; myfile << "author=" << map.getAuthor() << "\r"<< endl; myfile << "image=" << map.getImage() << "\r"<< endl; myfile << "wrap=" << (map.getWrap()==true?"yes":"no")<< "\r" << endl; myfile << "scroll=" << map.getScroll() << "\r"<< endl; myfile << "warn=" << (map.getWarn() == true ? "yes" : "no") << "\r"<< endl; myfile << "\r" << endl; //CONTINENTS myfile << "[Continents]" << "\r"<< endl; for (int i = 0; i < map.Continents.size(); i++) { myfile << map.Continents[i].getName() << "=" << map.Continents[i].getUnit() << "\r" << endl; } myfile << "\r" << endl; //TERRITORIES myfile << "[Territories]" << "\r"<< endl; for (int i = 0; i < map.Continents.size(); i++) { for (int j = 0; j < map.Continents[i].Country.size(); j++) { myfile << map.Continents[i].Country[j]->getName() << "," << map.Continents[i].Country[j]->getLatitude() << "," << map.Continents[i].Country[j]->getLongitude() << "," << map.Continents[i].getName(); for (int k = 0; k < map.Continents[i].Country[j]->getBorderingCountries().size(); k++) { if (map.Continents[i].Country[j]->getBorderingCountries()[k]->getName() != ""){ myfile << ","; myfile << map.Continents[i].Country[j]->getBorderingCountries()[k]->getName(); } } myfile << "\r" << endl; } myfile << "\r" << endl; } myfile << "\r" << endl; myfile.close(); }
#ifndef CNFIMP_H #define CNFIMP_H /// @file CnfImp.h /// @brief CnfImp のヘッダファイル /// @author Yusuke Matsunaga (松永 裕介) /// /// Copyright (C) 2005-2011 Yusuke Matsunaga /// All rights reserved. #include "YmNetworks/BNetwork.h" BEGIN_NAMESPACE_YM_NETWORKS class ImpMgr; class ImpInfo; ////////////////////////////////////////////////////////////////////// /// @class CnfImp CnfImp.h "CnfImp.h" /// @brief CNFを用いた間接含意エンジン ////////////////////////////////////////////////////////////////////// class CnfImp { public: /// @brief コンストラクタ CnfImp(); /// @brief デストラクタ virtual ~CnfImp(); public: ////////////////////////////////////////////////////////////////////// // 外部インターフェイスの宣言 ////////////////////////////////////////////////////////////////////// /// @brief ネットワーク中の間接含意を求める. /// @param[in] network 対象のネットワーク /// @param[in] imp_info 間接含意のリスト virtual void learning(ImpMgr& imp_mgr, ImpInfo& imp_info); private: ////////////////////////////////////////////////////////////////////// // データメンバ ////////////////////////////////////////////////////////////////////// }; END_NAMESPACE_YM_NETWORKS #endif // CNFIMP_H
#pragma once #define WIN32_LEAN_AND_MEAN #include <windows.h> class SystemController; class Display { private: LPCWSTR m_applicationName; HINSTANCE m_hinstance; HWND m_hwnd; SystemController* systemController; int screenWidth, screenHeight; bool done; void InitializeWindows(); void ShutdownWindows(); public: Display(SystemController* systemController); Display(const Display&); ~Display(); bool Initialize(); void Shutdown(); void Run(); void closeFrame(); HWND getHWND(); HINSTANCE getHinstance(); int getScreenWidth(); int getScreenHeight(); LRESULT CALLBACK MessageHandler(HWND, UINT, WPARAM, LPARAM); }; ///////////////////////// // FUNCTION PROTOTYPES // ///////////////////////// static LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); static Display* ApplicationHandle = 0;
// // Copyright (c) 2003--2009 // Toon Knapen, Karl Meerbergen, Kresimir Fresl, // Thomas Klimpel and Rutger ter Borg // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // THIS FILE IS AUTOMATICALLY GENERATED // PLEASE DO NOT EDIT! // #ifndef BOOST_NUMERIC_BINDINGS_LAPACK_COMPUTATIONAL_TPTRI_HPP #define BOOST_NUMERIC_BINDINGS_LAPACK_COMPUTATIONAL_TPTRI_HPP #include <boost/assert.hpp> #include <boost/mpl/bool.hpp> #include <boost/numeric/bindings/lapack/detail/lapack.h> #include <boost/numeric/bindings/traits/traits.hpp> #include <boost/numeric/bindings/traits/type_traits.hpp> #include <boost/static_assert.hpp> #include <boost/type_traits/is_same.hpp> namespace boost { namespace numeric { namespace bindings { namespace lapack { //$DESCRIPTION // overloaded functions to call lapack namespace detail { inline void tptri( char const uplo, char const diag, integer_t const n, float* ap, integer_t& info ) { LAPACK_STPTRI( &uplo, &diag, &n, ap, &info ); } inline void tptri( char const uplo, char const diag, integer_t const n, double* ap, integer_t& info ) { LAPACK_DTPTRI( &uplo, &diag, &n, ap, &info ); } inline void tptri( char const uplo, char const diag, integer_t const n, traits::complex_f* ap, integer_t& info ) { LAPACK_CTPTRI( &uplo, &diag, &n, traits::complex_ptr(ap), &info ); } inline void tptri( char const uplo, char const diag, integer_t const n, traits::complex_d* ap, integer_t& info ) { LAPACK_ZTPTRI( &uplo, &diag, &n, traits::complex_ptr(ap), &info ); } } // value-type based template template< typename ValueType > struct tptri_impl { typedef ValueType value_type; typedef typename traits::type_traits<ValueType>::real_type real_type; // templated specialization template< typename MatrixAP > static void invoke( char const diag, MatrixAP& ap, integer_t& info ) { BOOST_ASSERT( traits::matrix_uplo_tag(ap) == 'U' || traits::matrix_uplo_tag(ap) == 'L' ); BOOST_ASSERT( diag == 'N' || diag == 'U' ); BOOST_ASSERT( traits::matrix_num_columns(ap) >= 0 ); detail::tptri( traits::matrix_uplo_tag(ap), diag, traits::matrix_num_columns(ap), traits::matrix_storage(ap), info ); } }; // template function to call tptri template< typename MatrixAP > inline integer_t tptri( char const diag, MatrixAP& ap ) { typedef typename traits::matrix_traits< MatrixAP >::value_type value_type; integer_t info(0); tptri_impl< value_type >::invoke( diag, ap, info ); return info; } }}}} // namespace boost::numeric::bindings::lapack #endif
/* --COPYRIGHT--,BSD * Copyright (c) 2011, Texas Instruments Incorporated * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of Texas Instruments Incorporated nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * --/COPYRIGHT--*/ #include "windows.h" #include "setupapi.h" #include <list> #include <vector> #include <string> using namespace std; #include "cmutex.h" #include "cevent.h" #include "cthread.h" #include "cdevicedriver.h" /*! \brief Constructor \fn cDeviceDriver::cDeviceDriver */ cDeviceDriver::cDeviceDriver() { // Init Variables flagCreated = false; flagOpen = false; flagExitThread = false; // Generate Objects Drv = new cDriver(); eDrvError = new cEvent(true); eDrvOpen = new cEvent(true); eDecoderInit = new cEvent(false); eDecoderStart = new cEvent(false); eDecoderStop = new cEvent(false); eDecoderExit = new cEvent(false); eventFrameReceived = new cEvent(true); eventFrameErrorCrc = new cEvent(true); eventFrameErrorTimeOut = new cEvent(true); FrameFifo = new list<sFrame>; ThreadHandle = new TThread<cDeviceDriver>(*this,&cDeviceDriver::run); // Check if Objects are created if(ThreadHandle && Drv && eDrvError && eDrvOpen && eDecoderInit && eDecoderStart && eDecoderStop && eDecoderExit && FrameFifo ) { flagCreated = true; }; // Start Driver Thread; if(flagCreated) { ThreadHandle->StartAndWait(); if(ThreadHandle->IsRunning()) flagCreated = true; else flagCreated = false; }; } /*! \brief Destructor \fn cDeviceDriver::~cDeviceDriver */ cDeviceDriver::~cDeviceDriver() { // Close Thread if(ThreadHandle->IsRunning()) { flagExitThread = true; ThreadHandle->WaitUntilTerminate(); }; // Close Driver if(Drv) { Drv->Close(); delete Drv; Drv = NULL; }; // Clean up objects delete ThreadHandle; delete eDrvError; delete eDrvOpen; delete eDecoderInit; delete eDecoderStart; delete eDecoderStop; delete eDecoderExit; delete FrameFifo; delete Drv; delete eventFrameErrorCrc; delete eventFrameErrorTimeOut; delete eventFrameReceived; } /*! \brief Returns true if constructor generated and init objects successfully, else return false \fn cDeviceDriver::IsInit \param void \return bool */ bool cDeviceDriver::IsInit(void) { return(flagCreated); } // Public Function Defintion /*! \brief Open comport based on std string. Returns true, if comport could be open else return false \fn cDeviceDriver::Open \param strPort \return bool */ bool cDeviceDriver::Open(std::string strPort) { if(!drvOpen(strPort)) { flagOpen = false; } else { // Clear FrameFifo FrameFifoAccess.Lock(); FrameFifo->clear(); FrameFifoAccess.Unlock(); eventFrameErrorCrc->Reset(); eventFrameErrorTimeOut->Reset(); eventFrameReceived->Reset(); flagOpen = true; }; return(flagOpen); } /*! \brief Returns true, if a port is actual open else returns false \fn cDeviceDriver::IsOpen \param void \return bool */ bool cDeviceDriver::IsOpen(void) { return(flagOpen); } /*! \brief Returns true if driver has reported no error, else returns false \fn cDeviceDriver::IsDrvOk \param void \return bool */ bool cDeviceDriver::IsDrvOk(void) { return(!this->eDrvError->Check()); } /*! \brief close active comport. Returns true if done else false \fn cDeviceDriver::Close \param void \return bool */ bool cDeviceDriver::Close(void) { if(this->drvClose()) { flagOpen = false; return(true); }; return(false); } /*! \brief Resets the comport driver (not implemented yet) \fn cDeviceDriver::Reset \param void \return bool */ bool cDeviceDriver::Reset(void) { return(false); } /*! \brief Send a Command Frame to the SA430 device. Return true if command could be sent else false \fn cDeviceDriver::SendFrame \param Cmd Command Byte \param Data Payload \param size Size of Payload \return bool true:done false:failed */ bool cDeviceDriver::SendFrame(unsigned char Cmd, unsigned char *Data, unsigned short size) { bool ok = false; sFrame newFrame; MakeFrame(&newFrame,Cmd,Data,size); ok = drvSendFrame(&newFrame); return(ok); } /*! \brief Checks if any Frames was received from the SA430 device \fn cDeviceDriver::IsFrameFifoEmpty \param void \return bool true:new data frame is available false: No new data received */ bool cDeviceDriver::IsFrameFifoEmpty(void) { bool answ = false; if(Drv) { FrameFifoAccess.Lock(); answ = FrameFifo->empty(); FrameFifoAccess.Unlock(); }; return(answ); } /*! \brief Returns the number of Frames within the receive frame buffer fifo \fn cDeviceDriver::GetFrameFifoSize \param Size \return bool true:done false:failed to get information */ bool cDeviceDriver::GetFrameFifoSize(unsigned short &Size) { if(Drv) { FrameFifoAccess.Lock(); Size = FrameFifo->size(); FrameFifoAccess.Unlock(); return(true); }; Size = 0; return(false); } /*! \brief Get top most frame from the received bufferf Fifo \fn cDeviceDriver::GetFrame \param Frame \return bool true:done false:failed */ bool cDeviceDriver::GetFrame(sFrame *Frame) { if(Drv && Frame!=NULL) { FrameFifoAccess.Lock(); if(!FrameFifo->empty()) { *Frame = FrameFifo->front(); FrameFifo->pop_front(); }; FrameFifoAccess.Unlock(); return(true); }; return(false); } /*! \brief Verifies if a frame was received from the SA430 device, since last call of this function \fn cDeviceDriver::HasFrameReceived \param void \return bool */ bool cDeviceDriver::HasFrameReceived(void) { return(eventFrameReceived->Check()); } /*! \brief Checks if the frame decoder reported a frame with crc error \fn cDeviceDriver::HasFrameCrcError \param void \return bool true:Crc Error false:No Crc Error */ bool cDeviceDriver::HasFrameCrcError(void) { return(eventFrameErrorCrc->Check()); } /*! \brief Checks if the the frame decoder reported a timeout error \fn cDeviceDriver::HasFrameTimeoutError \param void \return bool true:Timeout Error false: No Timeout Error */ bool cDeviceDriver::HasFrameTimeoutError(void) { return(eventFrameErrorTimeOut->Check()); } // Private: /*! \brief Open comport based on std string \fn cDeviceDriver::drvOpen \param strPort \return bool true:done false:failed */ bool cDeviceDriver::drvOpen(std::string strPort) { bool ok = false; if(Drv) { if(eDrvOpen->Check()) drvClose(); DrvAccess.Lock(); drvSignalErrorReset(); if(Drv->Open(strPort,B926100,DAT_8,PAR_NONE,STOP_1,FLOW_HARDWARE)) { ok = true; } else { drvSignalError(Drv->GetLastErrorCode(),Drv->GetLastErrorString()); }; DrvAccess.Unlock(); }; if(ok) { this->eDrvOpen->Signal(); } return(ok); } /*! \brief Read complete comport rx buffer and copy to std string buffer \fn cDeviceDriver::drvGetData \param rxFifo \return bool true:done false: No Data */ bool cDeviceDriver::drvGetData(std::string *rxFifo) { bool ok = false; unsigned long size=0; DrvAccess.Lock(); if(Drv->GetRcvBufferSize(size)) { if(size>0) { rxFifo->resize(rxFifo->size()+size); if(Drv->ReadData((unsigned char*)(rxFifo->data()),(unsigned short)size,0)) { ok = true; } else { drvSignalError(Drv->GetLastErrorCode(),Drv->GetLastErrorString()); }; }; }; DrvAccess.Unlock(); if(!Drv->IsOk()) { drvSignalError(Drv->GetLastErrorCode(),Drv->GetLastErrorString()); ok = false; }; return(ok); } /*! \brief Close active comport \fn cDeviceDriver::drvClose \param void \return bool true:done false: failed */ bool cDeviceDriver::drvClose(void) { bool ok = false; if(Drv) { DrvAccess.Lock(); ok = Drv->Close(); DrvAccess.Unlock(); this->eDrvOpen->Reset(); this->eDrvError->Reset(); }; return(ok); } /*! \brief Converts raw bytestream to SA430 frame format \fn cDeviceDriver::Raw2Frame \param Raw Input Raw Bytestream \param Frame Output sFrame */ void cDeviceDriver::Raw2Frame(std::string &Raw, sFrame &Frame) { if(Raw.size()<4) { return; }; Frame.Cmd = Raw.at(1); Frame.Length = Raw.at(2); Frame.Data.clear(); if(Frame.Length>0) { Frame.Data.append((Raw.data()+4),Frame.Length); Frame.Crc = (unsigned short)((Raw.at(3+Frame.Length)<<8) + (Raw.at(4+Frame.Length)<<8)); } else { Frame.Crc = (unsigned short)((Raw.at(3)<<8) + (Raw.at(4)<<8)); }; }; /*! \brief Converts SA430 frame to raw bytestream \fn cDeviceDriver::Frame2Raw \param Output Raw Bytestream \param Input sFrame */ void cDeviceDriver::Frame2Raw(sFrame &Frame, std::string &Raw) { Raw.clear(); Raw.resize(3); Raw[0] = 0x2A; Raw[1] = Frame.Length; Raw[2] = Frame.Cmd; if(Frame.Data.size()>0) { Raw.append(Frame.Data); }; Raw.resize(Raw.size()+2); Frame.Crc = calcCrc16(Raw); Raw[Raw.size()-2] = (unsigned char) (Frame.Crc >>8); Raw[Raw.size()-1] = (unsigned char) (Frame.Crc & 0xff); } /*! \brief Add byte to current crc value, ensure to init crc16 routine before calling this function \fn cDeviceDriver::crc16AddByte \param crc active crc value \param u8 data byte */ void cDeviceDriver::crc16AddByte(unsigned short &crc, unsigned char u8) { crc = (unsigned char)(crc>>8)|(crc<<8); crc ^= u8; crc ^= (unsigned char)(crc & 0xff)>>4; crc ^= (crc << 8) << 4; crc ^= ((crc & 0xff) << 4)<< 1; } /*! \brief Calculate Crc of given raw data bytestream \fn cDeviceDriver::calcCrc16 \param Raw Bytestream \return unsigned short Generated Crc16 value */ unsigned short cDeviceDriver::calcCrc16(std::string &Raw) { int index; int datalength; unsigned short crc = 0x2A; datalength = Raw.size()-2; for(index=1 ; index<datalength; index++) { crc16AddByte(crc,(unsigned char)Raw.at(index)); }; return(crc); } /*! \brief Send given SA430 Cmd Frame \fn cDeviceDriver::drvSendFrame \param Frame \return bool */ bool cDeviceDriver::drvSendFrame(sFrame *Frame) { bool ok = false; std::string rawFrame; this->Frame2Raw(*Frame,rawFrame); if(Drv) { DrvAccess.Lock(); if(Drv->WriteData((unsigned char*)rawFrame.data(),(unsigned short)rawFrame.size())) { ok = true; } else { drvSignalError(Drv->GetLastErrorCode(),Drv->GetLastErrorString()); ok =false; }; DrvAccess.Unlock(); }; return(ok); } /*! \brief Signals an error from the comport thread to upper class level \fn cDeviceDriver::drvSignalError \param Code \param Msg */ void cDeviceDriver::drvSignalError(unsigned int Code, std::string Msg) { Error.Code = Code; Error.Msg = Msg; eDrvOpen->Reset(); Drv->Close(); eDrvError->Signal(); } /*! \brief Signals Error Reset to received comport thread \fn cDeviceDriver::drvSignalErrorReset \param void */ void cDeviceDriver::drvSignalErrorReset(void) { Error.Code = 0; Error.Msg = "No Error"; eDrvError->Reset(); } /*! \brief Init SA430 Frame Decoder \fn cDeviceDriver::FrameDecoderInit \param void */ void cDeviceDriver::FrameDecoderInit(void) { DecoderState.Crc = 0x2A; DecoderState.CrcIndex = 0; DecoderState.DataIndex = 0; DecoderState.State = DS_WAITSMARKER; ResetFrame(&DecoderState.Frame); } /*! \brief Decodes incoming comport data from the SA430 device and put valid command frames into the receiver frame buffer \fn cDeviceDriver::FrameDecoder \param rxFifo \return bool */ bool cDeviceDriver::FrameDecoder(std::string *rxFifo) { bool exit = false; unsigned char u8Data = 0xff; while(!rxFifo->empty() && !exit) { u8Data = (char) rxFifo->at(0); rxFifo->erase(rxFifo->begin()); switch(DecoderState.State) { case DS_WAITSMARKER: if(u8Data==0x2A) { DecoderState.Crc = 0x2A; DecoderState.CrcIndex = 0; DecoderState.DataIndex = 0; ResetFrame(&DecoderState.Frame); DecoderState.State = DS_WAITLENGTH; }; break; case DS_WAITLENGTH: DecoderState.Frame.Length = u8Data; crc16AddByte(DecoderState.Crc,u8Data); DecoderState.State = DS_WAITCMD; break; case DS_WAITCMD: DecoderState.Frame.Cmd = u8Data; crc16AddByte(DecoderState.Crc,u8Data); if(DecoderState.Frame.Length > 0) DecoderState.State = DS_WAITDATA; else DecoderState.State = DS_CRC_HIGH; break; case DS_WAITDATA: DecoderState.Frame.Data.push_back(u8Data); crc16AddByte(DecoderState.Crc,u8Data); DecoderState.DataIndex++; if(DecoderState.DataIndex == DecoderState.Frame.Length) { DecoderState.State = DS_CRC_HIGH; }; break; case DS_CRC_HIGH: DecoderState.Frame.Crc = (unsigned short)(u8Data<<8); DecoderState.State = DS_CRC_LOW; break; case DS_CRC_LOW: DecoderState.Frame.Length = DecoderState.Frame.Data.size(); DecoderState.Frame.Crc += (unsigned short)(u8Data); DecoderState.State = DS_WAITSMARKER; if(DecoderState.Frame.Crc == DecoderState.Crc) { FrameFifoAccess.Lock(); FrameFifo->push_back(DecoderState.Frame); eventFrameReceived->Signal(); FrameFifoAccess.Unlock(); } else { eventFrameErrorCrc->Signal(); }; break; default: break; }; }; return(false); } /*! \brief Initialize given Frame to the reset values \fn cDeviceDriver::ResetFrame \param Frame */ void cDeviceDriver::ResetFrame(sFrame *Frame) { Frame->Cmd = 0; Frame->Length = 0; Frame->Data.clear(); Frame->Crc = 0; } /*! \brief Generates and SA430 Device Frame based on given parameters and payload \fn cDeviceDriver::MakeFrame \param Frame Output Generated sFrame \param Cmd SA430 Command \param Data Payload \param Length Lebgth of Payload */ void cDeviceDriver::MakeFrame(sFrame *Frame, unsigned char Cmd, unsigned char *Data, unsigned short Length) { Frame->Cmd = Cmd; Frame->Data.clear(); Frame->Length = (unsigned char) Length; if(Data && Length>0) { Frame->Data.append((const char*)Data, (int)Length); }; } /*! \brief Comport driver thread states \enum */ enum { DRV_INIT=0, DRV_RUN, DRV_STOP, DRV_EXIT, }; /*! \brief Comport receiver thread loop \fn cDeviceDriver::run */ void cDeviceDriver::run() { unsigned char State; std::string RxFifo; RxFifo.clear(); State = DRV_INIT; do { switch(State) { case DRV_INIT: if(this->eDrvOpen->CheckSignal(20)) { RxFifo.clear(); FrameDecoderInit(); State = DRV_RUN; }; break; case DRV_RUN: if(!this->drvGetData(&RxFifo) && RxFifo.empty()) { Sleep(1); break; }; FrameDecoder(&RxFifo); break; case DRV_STOP: Sleep(10); break; case DRV_EXIT: break; }; // Check Thread Exit Signals if(this->eDecoderExit->Check()) flagExitThread = true; else if(this->eDrvError->Check()) State = DRV_INIT; else if(!this->eDrvOpen->Check()) State = DRV_INIT; else if(this->eDecoderInit->Check()) State = DRV_INIT; else if(this->eDecoderStop->Check()) State = DRV_STOP; }while(!flagExitThread); }
class Solution { public: vector<vector<int>> palindromePairs(vector<string>& words) { // vector<vector<int>>result; // for (int i = 0; i<words.size(); i++) { // for (int j = 0; j<words.size(); j++) { // if(i==j) // continue; // if(is_palindrome(words[i],words[j])) // result.push_back(vector<int>{i,j}); // } // } // return result; vector<vector<int>>result; unordered_map<string, int>word_map; for (int i = 0; i<words.size(); i++) { word_map[words[i]] = i; } for (int i = 0; i<words.size(); i++) { for (int m = 0; m<words[i].size(); m++) { string temp1(words[i].rend()-m,words[i].rend()); string temp2(words[i].rbegin(),words[i].rbegin()+m); if(is_palindrome(words[i],temp1)&&word_map.find(temp1)!=word_map.end()&&temp1!=words[i]) result.push_back(vector<int>{i,word_map[temp1]}); if(is_palindrome(temp2,words[i])&&word_map.find(temp2)!=word_map.end()&&temp2!=words[i]) result.push_back(vector<int>{word_map[temp2],i}); } string temp3(words[i].rbegin(),words[i].rend()); if(temp3!=words[i]&&is_palindrome(words[i],temp3)&&word_map.find(temp3)!=word_map.end()) result.push_back(vector<int>{i,word_map[temp3]}); } return result; } bool is_palindrome(string &word1,string &word2) { int word1len = int(word1.size()),word2len = int(word2.size()); if (word1len>word2len) { for (int i = 0,j = word2len-1; j>=0;) { if (word1[i++]!=word2[j--]) { return false; } } for (int i = word2len,j = word1len-1; i<j;) { if (word1[i++]!=word1[j--]) { return false; } } return true; }else{ for (int i = 0,j = word2len-1; i<word1len;) { if (word1[i++]!=word2[j--]) { return false; } } for (int i = 0,j = word2len-word1len-1; i<j;) { if (word2[i++]!=word2[j--]) { return false; } } return true; } } };
// // Created by wqy on 19-11-26. // #include "Type.h" namespace esc { void Type::setName(string _typeName) { this->typeName = _typeName; } }
//************************************************************************** //** //** See jlquake.txt for copyright info. //** //** This program is free software; you can redistribute it and/or //** modify it under the terms of the GNU General Public License //** as published by the Free Software Foundation; either version 3 //** of the License, or (at your option) any later version. //** //** This program is distributed in the hope that it will be useful, //** but WITHOUT ANY WARRANTY; without even the implied warranty of //** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //** included (gnu.txt) GNU General Public License for more details. //** //************************************************************************** #include "local.h" #include "../../client_main.h" #include "../../public.h" #include "../../../common/Common.h" #include "../../../common/common_defs.h" #include "../../../common/strings.h" #include "../../../common/message_utils.h" #include "../quake_hexen2/demo.h" #include "../quake_hexen2/main.h" static byte* clqw_upload_data; static int clqw_upload_pos; static int clqw_upload_size; // An q1svc_signonnum has been received, perform a client side setup void CLQ1_SignonReply() { char str[ 8192 ]; common->DPrintf( "CLQ1_SignonReply: %i\n", clc.qh_signon ); switch ( clc.qh_signon ) { case 1: CL_AddReliableCommand( "prespawn" ); break; case 2: CL_AddReliableCommand( va( "name \"%s\"\n", clqh_name->string ) ); CL_AddReliableCommand( va( "color %i %i\n", clqh_color->integer >> 4, clqh_color->integer & 15 ) ); sprintf( str, "spawn %s", cls.qh_spawnparms ); CL_AddReliableCommand( str ); break; case 3: CL_AddReliableCommand( "begin" ); break; case 4: SCR_EndLoadingPlaque(); // allow normal screen updates break; } } int CLQW_CalcNet() { for ( int i = clc.netchan.outgoingSequence - UPDATE_BACKUP_QW + 1 ; i <= clc.netchan.outgoingSequence ; i++ ) { qwframe_t* frame = &cl.qw_frames[ i & UPDATE_MASK_QW ]; if ( frame->receivedtime == -1 ) { clqh_packet_latency[ i & NET_TIMINGSMASK_QH ] = 9999; // dropped } else if ( frame->receivedtime == -2 ) { clqh_packet_latency[ i & NET_TIMINGSMASK_QH ] = 10000; // choked } else if ( frame->invalid ) { clqh_packet_latency[ i & NET_TIMINGSMASK_QH ] = 9998; // invalid delta } else { clqh_packet_latency[ i & NET_TIMINGSMASK_QH ] = ( frame->receivedtime - frame->senttime ) * 20; } } int lost = 0; for ( int a = 0; a < NET_TIMINGS_QH; a++ ) { int i = ( clc.netchan.outgoingSequence - a ) & NET_TIMINGSMASK_QH; if ( clqh_packet_latency[ i ] == 9999 ) { lost++; } } return lost * 100 / NET_TIMINGS_QH; } void CLQW_NextUpload() { if ( !clqw_upload_data ) { return; } int r = clqw_upload_size - clqw_upload_pos; if ( r > 768 ) { r = 768; } byte buffer[ 1024 ]; Com_Memcpy( buffer, clqw_upload_data + clqw_upload_pos, r ); clc.netchan.message.WriteByte( qwclc_upload ); clc.netchan.message.WriteShort( r ); clqw_upload_pos += r; int size = clqw_upload_size; if ( !size ) { size = 1; } int percent = clqw_upload_pos * 100 / size; clc.netchan.message.WriteByte( percent ); clc.netchan.message.WriteData( buffer, r ); common->DPrintf( "UPLOAD: %6d: %d written\n", clqw_upload_pos - r, r ); if ( clqw_upload_pos != clqw_upload_size ) { return; } common->Printf( "Upload completed\n" ); Mem_Free( clqw_upload_data ); clqw_upload_data = 0; clqw_upload_pos = clqw_upload_size = 0; } void CLQW_StartUpload( const byte* data, int size ) { if ( cls.state < CA_LOADING ) { return; // gotta be connected } // override if ( clqw_upload_data ) { free( clqw_upload_data ); } common->DPrintf( "Upload starting of %d...\n", size ); clqw_upload_data = ( byte* )Mem_Alloc( size ); Com_Memcpy( clqw_upload_data, data, size ); clqw_upload_size = size; clqw_upload_pos = 0; CLQW_NextUpload(); } bool CLQW_IsUploading() { if ( clqw_upload_data ) { return true; } return false; } void CLQW_StopUpload() { if ( clqw_upload_data ) { Mem_Free( clqw_upload_data ); } clqw_upload_data = NULL; } void CLQW_SendCmd() { if ( cls.state == CA_DISCONNECTED ) { return; } if ( clc.demoplaying ) { return; // sendcmds come from the demo } // save this command off for prediction int i = clc.netchan.outgoingSequence & UPDATE_MASK_QW; qwusercmd_t* cmd = &cl.qw_frames[ i ].cmd; cl.qw_frames[ i ].senttime = cls.realtime * 0.001; cl.qw_frames[ i ].receivedtime = -1; // we haven't gotten a reply yet int seq_hash = clc.netchan.outgoingSequence; // get basic movement from keyboard Com_Memset( cmd, 0, sizeof ( *cmd ) ); in_usercmd_t inCmd = CL_CreateCmd(); cmd->forwardmove = inCmd.forwardmove; cmd->sidemove = inCmd.sidemove; cmd->upmove = inCmd.upmove; cmd->buttons = inCmd.buttons; cmd->impulse = inCmd.impulse; cmd->msec = inCmd.msec; VectorCopy( inCmd.fAngles, cmd->angles ); // // allways dump the first two message, because it may contain leftover inputs // from the last level // if ( ++cl.qh_movemessages <= 2 ) { return; } // send this and the previous cmds in the message, so // if the last packet was dropped, it can be recovered QMsg buf; byte data[ 128 ]; buf.InitOOB( data, 128 ); buf.WriteByte( q1clc_move ); // save the position for a checksum byte int checksumIndex = buf.cursize; buf.WriteByte( 0 ); // write our lossage percentage int lost = CLQW_CalcNet(); buf.WriteByte( ( byte )lost ); i = ( clc.netchan.outgoingSequence - 2 ) & UPDATE_MASK_QW; cmd = &cl.qw_frames[ i ].cmd; qwusercmd_t nullcmd = {}; MSGQW_WriteDeltaUsercmd( &buf, &nullcmd, cmd ); qwusercmd_t* oldcmd = cmd; i = ( clc.netchan.outgoingSequence - 1 ) & UPDATE_MASK_QW; cmd = &cl.qw_frames[ i ].cmd; MSGQW_WriteDeltaUsercmd( &buf, oldcmd, cmd ); oldcmd = cmd; i = ( clc.netchan.outgoingSequence ) & UPDATE_MASK_QW; cmd = &cl.qw_frames[ i ].cmd; MSGQW_WriteDeltaUsercmd( &buf, oldcmd, cmd ); // calculate a checksum over the move commands buf._data[ checksumIndex ] = COMQW_BlockSequenceCRCByte( buf._data + checksumIndex + 1, buf.cursize - checksumIndex - 1, seq_hash ); // request delta compression of entities if ( clc.netchan.outgoingSequence - cl.qh_validsequence >= UPDATE_BACKUP_QW - 1 ) { cl.qh_validsequence = 0; } if ( cl.qh_validsequence && !cl_nodelta->value && cls.state == CA_ACTIVE && !clc.demorecording ) { cl.qw_frames[ clc.netchan.outgoingSequence & UPDATE_MASK_QW ].delta_sequence = cl.qh_validsequence; buf.WriteByte( qwclc_delta ); buf.WriteByte( cl.qh_validsequence & 255 ); } else { cl.qw_frames[ clc.netchan.outgoingSequence & UPDATE_MASK_QW ].delta_sequence = -1; } if ( clc.demorecording ) { CLQW_WriteDemoCmd( cmd ); } // // deliver the message // Netchan_Transmit( &clc.netchan, buf.cursize, buf._data ); }
#include <fd/Laplacian.h> #include <fd/Utils.h> #include <cmath> PetscReal quad_spatial_func(PetscReal x, PetscReal y) { return std::sin(2*x)*std::sin(3*y); } int main(int argc, char **argv) { std::vector<std::tuple<PetscInt,PetscInt,PetscReal>> grid_params { {5,5,2.0}, {10,10,2.0}, {20,20,2.0}, {40,40,2.0}, {80,80,2.0}, {160,160,2.0}, {320,320,2.0}, {640,640,2.0} }; PetscInt nscale=1; PetscReal gridscale=1.0; PetscBool sflg,gflg; /* PetscPrintf(PETSC_COMM_WORLD,"params: %D,%D,%g",std::get<0>(*ptpl),std::get<1>(*ptpl),std::get<2>(*ptpl)); }*/ std::vector<std::tuple<PetscReal,PetscReal,PetscInt>> ksp_tols { {1.0e-8,PETSC_DEFAULT,PETSC_DEFAULT}, {1.0e-8,PETSC_DEFAULT,PETSC_DEFAULT}, {1.0e-8,PETSC_DEFAULT,PETSC_DEFAULT}, {1.0e-8,PETSC_DEFAULT,PETSC_DEFAULT}, {1.0e-8,PETSC_DEFAULT,PETSC_DEFAULT}, {1.0e-8,1.0e-8,PETSC_DEFAULT}, {1.0e-8,1.0e-8,PETSC_DEFAULT}, {1.0e-8,1.0e-8,PETSC_DEFAULT}, }; std::vector<std::string> plotfiles { std::string{"tests/plot1"}, std::string{"tests/plot2"}, std::string{"tests/plot3"}, std::string{"tests/plot4"}, std::string{"tests/plot5"}, std::string{"tests/plot6"}, std::string{"tests/plot7"}, std::string{"tests/plot8"} }; auto ierr = PetscInitialize(&argc,&argv,NULL,NULL);CHKERRQ(ierr); PetscOptionsGetInt(NULL,NULL,"-scale_nodes",&nscale,&sflg); PetscOptionsGetReal(NULL,NULL,"-scale_grid",&gridscale,&gflg); for (auto ptpl = grid_params.begin(); ptpl != grid_params.end(); ++ptpl) { if (sflg) { std::get<0>(*ptpl) *= nscale; std::get<1>(*ptpl) *= nscale; } if (gflg) { std::get<2>(*ptpl) *= gridscale; } } { auto residuals = fd::TestConvergence<fd::Laplacian>( PETSC_COMM_WORLD, grid_params, quad_spatial_func, std::nullopt, std::nullopt, true, plotfiles ); } PetscFinalize(); return 0; }
#include<bits/stdc++.h> using namespace std; int lcs3(char* a,char* b,int m,int n) { int** output = new int*[m+1]; for(int i=0;i<=m;i++) { output[i]=new int[n+1]; for(int j=0;j<=n;j++) { output[i][j]=0; } } // base case for(int i=0;i<=m;i++) // if n==0 { output[i][0]=0; } for(int i=0;i<=n;i++) // if m==0 { output[0][i]=0; } for(int i=1;i<=m;i++) { for(int j=1;j<=n;j++) { if(a[m-i] == b[n-j]) // i and j means the remaining characters in str1 and str2 from the start not from the end { output[i][j] = 1 + output[i-1][j-1]; } else { output[i][j] = max(output[i][j-1],output[i-1][j]); } } } int ans = output[m][n]; for(int i=0;i<=m;i++) { delete[] output[i]; } delete[] output; return ans; } int smallestSuperSequence(char str1[], int len1, char str2[], int len2) { int lcs = lcs3(str1,str2,len1,len2); int result = lcs + len1-lcs + len2 - lcs; return result; }
//----------------------------------------------------------------------------- // Perimeter Map Compiler // Copyright (c) 2005, Don Reba // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // • Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // • Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // • Neither the name of Don Reba nor the names of his contributors may be used // to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. //----------------------------------------------------------------------------- inline int exp2(unsigned int n) { int e(1); while (0 != n) { e <<= 1; --n; } return e; } inline int log2(unsigned int n) { int l(-1); while (0 != n) { n >>= 1; ++l; } return l; } inline void ScreenToClient(HWND hwnd, RECT *rect) { POINT corner; RECT &rect_ref(*rect); corner.x = rect_ref.left; corner.y = rect_ref.top; ScreenToClient(hwnd, &corner); rect_ref.left = corner.x; rect_ref.top = corner.y; corner.x = rect_ref.right; corner.y = rect_ref.bottom; ScreenToClient(hwnd, &corner); rect_ref.right = corner.x; rect_ref.bottom = corner.y; } inline void ClientToScreen(HWND hwnd, RECT *rect) { POINT corner; RECT &rect_ref(*rect); corner.x = rect_ref.left; corner.y = rect_ref.top; ClientToScreen(hwnd, &corner); rect_ref.left = corner.x; rect_ref.top = corner.y; corner.x = rect_ref.right; corner.y = rect_ref.bottom; ClientToScreen(hwnd, &corner); rect_ref.right = corner.x; rect_ref.bottom = corner.y; } // binary search on cstrings inline const char * const * binary_search( const char * const * begin, const char * const * end, const char * val) { const char * const *l = begin; const char * const *r = end; while (l <= r) { const char * const * m = l + (r - l) / 2; int result(strcmp(*m, val)); if (result < 0) l = m + 1; else if (result > 0) r = m - 1; else return m; } return end; } // find the index of a cstring in a sorted array inline size_t string_index( const char * const name_array[], size_t array_size, const char * name) { const char * const * const begin = name_array; const char * const * const end = name_array + array_size; const char * const * const result = binary_search(begin, end, name); if (result != end) return static_cast<size_t>(end - result); _RPT1(_CRT_ERROR, "Unknown enumeration value: %s.", name); return static_cast<size_t>(-1); } // determine the size of a static array as a compile-time constant // the trick is to call sizeof on a function that returns a reference // to a char array with the same number of elements as in the argument template <typename T, size_t N> char (&equal_char_array(T (&)[N]))[N] { } #define MacroArraySize(array) \ sizeof(equal_char_array(array))
#include <cstdio> // A+B C int main() { long long a, b, c, sum; int times = 0; bool flag = false; scanf("%d", &times); for(int i = 0; i < times; i++) { scanf("%lld %lld %lld", &a, &b, &c); sum = a + b; if(a < 0 && b < 0 && sum >= 0) { // 下溢 flag = false; } else if(a > 0 && b > 0 && sum <= -2) { // 上溢 flag = true; } else if(sum > c) { flag = true; } else { flag = false; } if(flag) { printf("Case #%d: true\n", i+1); } else { printf("Case #%d: false\n", i+1); } } return 0; }
#include "drake/systems/lcm/lcm_publisher_system.h" #include <cmath> #include <memory> #include <gtest/gtest.h> #include "drake/common/test_utilities/is_dynamic_castable.h" #include "drake/lcm/drake_lcm.h" #include "drake/lcm/drake_mock_lcm.h" #include "drake/lcm/lcmt_drake_signal_utils.h" #include "drake/lcmt_drake_signal.hpp" #include "drake/systems/analysis/simulator.h" #include "drake/systems/framework/basic_vector.h" #include "drake/systems/lcm/lcm_translator_dictionary.h" #include "drake/systems/lcm/lcmt_drake_signal_translator.h" using std::make_unique; using std::unique_ptr; namespace drake { namespace systems { namespace lcm { namespace { const int kDim = 10; const int kPortNumber = 0; using drake::lcm::CompareLcmtDrakeSignalMessages; using drake::lcm::DrakeLcmInterface; using drake::lcm::DrakeMockLcm; using drake::lcm::DrakeLcm; void TestPublisher(const std::string& channel_name, lcm::DrakeMockLcm* lcm, LcmPublisherSystem* dut) { EXPECT_EQ(dut->get_name(), "LcmPublisherSystem(" + channel_name + ")"); unique_ptr<Context<double>> context = dut->CreateDefaultContext(); unique_ptr<SystemOutput<double>> output = dut->AllocateOutput(); // Verifies that the context has one input port. EXPECT_EQ(context->get_num_input_ports(), 1); // Instantiates a BasicVector with known state. This is the basic vector that // we want the LcmPublisherSystem to publish as a drake::lcmt_drake_signal // message. auto vec = make_unique<BasicVector<double>>(kDim); Eigen::VectorBlock<VectorX<double>> vector_value = vec->get_mutable_value(); for (int i = 0; i < kDim; ++i) { vector_value[i] = i; } context->FixInputPort(kPortNumber, std::move(vec)); // Sets the timestamp within the context. This timestamp should be transmitted // by the LCM message. const double time = 1.41421356; context->set_time(time); dut->Publish(*context.get()); // Verifies that the correct message was published. const std::vector<uint8_t>& published_message_bytes = lcm->get_last_published_message(dut->get_channel_name()); drake::lcmt_drake_signal received_message; received_message.decode(&published_message_bytes[0], 0, published_message_bytes.size()); drake::lcmt_drake_signal expected_message; expected_message.dim = kDim; expected_message.val.resize(kDim); expected_message.coord.resize(kDim); for (int i = 0; i < kDim; ++i) { expected_message.val[i] = i; expected_message.coord[i] = ""; } expected_message.timestamp = static_cast<int64_t>(time * 1000); // TODO(liang.fok) Replace this with a Google Test matcher. EXPECT_TRUE(CompareLcmtDrakeSignalMessages(received_message, expected_message)); EXPECT_EQ( lcm->get_last_publication_time(dut->get_channel_name()).value_or(-1.0), time); } // Test that failure to specify an LCM interface results in an internal one // of being allocated. Can't check for operation in this case // since we won't have a mock LCM to look at. GTEST_TEST(LcmPublisherSystemTest, DefaultLcmTest) { const std::string channel_name = "junk"; // Use a translator just so we can invoke a constructor. LcmtDrakeSignalTranslator translator(kDim); // Provide an explicit LCM interface and check that it gets used. DrakeMockLcm mock_lcm; LcmPublisherSystem dut1(channel_name, translator, &mock_lcm); EXPECT_EQ(&dut1.lcm(), &mock_lcm); // Now leave out the LCM interface and check that a DrakeLcm gets allocated. LcmPublisherSystem dut2(channel_name, translator, nullptr); EXPECT_TRUE(is_dynamic_castable<DrakeLcm>(&dut2.lcm())); } // Test that an initialization publisher gets invoked properly by an // initialization event, and that the initialization event doesn't cause // publishing. GTEST_TEST(LcmPublisherSystemTest, TestInitializationEvent) { const std::string channel_name = "junk"; // Use a translator just so we can invoke a constructor. LcmtDrakeSignalTranslator translator(kDim); DrakeMockLcm mock_lcm; LcmPublisherSystem dut1(channel_name, translator, &mock_lcm); bool init_was_called{false}; dut1.AddInitializationMessage([&dut1, &init_was_called]( const Context<double>&, DrakeLcmInterface* lcm) { EXPECT_EQ(lcm, &dut1.lcm()); init_was_called = true; }); auto context = dut1.AllocateContext(); // Put something on the input port so that an attempt to publish would // succeed if (erroneously) attempted after initialization. auto vec = make_unique<BasicVector<double>>(kDim); for (int i = 0; i < kDim; ++i) (*vec)[i] = i; context->FixInputPort(kPortNumber, std::move(vec)); // Get the initialization event and publish it (this is mocking // Simulator::Initialize() behavior. auto init_events = dut1.AllocateCompositeEventCollection(); dut1.GetInitializationEvents(*context, &*init_events); dut1.Publish(*context, init_events->get_publish_events()); EXPECT_TRUE(init_was_called); // Nothing should have been published to this channel. EXPECT_FALSE(mock_lcm.get_last_publication_time(channel_name)); } // Tests LcmPublisherSystem using a translator. GTEST_TEST(LcmPublisherSystemTest, PublishTest) { lcm::DrakeMockLcm lcm; const std::string channel_name = "drake_system2_lcm_test_publisher_channel_name"; LcmtDrakeSignalTranslator translator(kDim); // Instantiates an LcmPublisherSystem that takes as input System 2.0 Vectors // of type drake::systems::VectorBase and publishes LCM messages of type // drake::lcmt_drake_signal. // // The LcmPublisherSystem is called "dut" to indicate it is the // "device under test". LcmPublisherSystem dut(channel_name, translator, &lcm); TestPublisher(channel_name, &lcm, &dut); } // Tests LcmPublisherSystem using a dictionary that contains a translator. GTEST_TEST(LcmPublisherSystemTest, PublishTestUsingDictionary) { lcm::DrakeMockLcm lcm; const std::string channel_name = "drake_system2_lcm_test_publisher_channel_name"; // Creates a dictionary with one translator. LcmTranslatorDictionary dictionary; dictionary.AddEntry( channel_name, make_unique<const LcmtDrakeSignalTranslator>(kDim)); EXPECT_TRUE(dictionary.HasTranslator(channel_name)); // Instantiates an LcmPublisherSystem that takes as input System 2.0 Vectors // of type drake::systems::VectorBase and publishes LCM messages of type // drake::lcmt_drake_signal. // // The LcmPublisherSystem is called "dut" to indicate it is the // "device under test". LcmPublisherSystem dut(channel_name, dictionary, &lcm); TestPublisher(channel_name, &lcm, &dut); } // Tests LcmPublisherSystem using a Serializer. GTEST_TEST(LcmPublisherSystemTest, SerializerTest) { lcm::DrakeMockLcm lcm; const std::string channel_name = "channel_name"; // The "device under test". auto dut = LcmPublisherSystem::Make<lcmt_drake_signal>(channel_name, &lcm); ASSERT_NE(dut.get(), nullptr); // Establishes the context, output, and input for the dut. unique_ptr<Context<double>> context = dut->CreateDefaultContext(); unique_ptr<SystemOutput<double>> output = dut->AllocateOutput(); const lcmt_drake_signal sample_data{ 2, { 1.0, 2.0, }, { "x", "y", }, 12345, }; context->FixInputPort(kPortNumber, make_unique<Value<lcmt_drake_signal>>(sample_data)); // Verifies that a correct message is published. dut->Publish(*context.get()); const auto& bytes = lcm.get_last_published_message(channel_name); drake::lcmt_drake_signal received_message{}; received_message.decode(bytes.data(), 0, bytes.size()); EXPECT_TRUE(CompareLcmtDrakeSignalMessages(received_message, sample_data)); } // Tests that the published LCM message has the expected timestamps. GTEST_TEST(LcmPublisherSystemTest, TestPublishPeriod) { const double kPublishPeriod = 1.5; // Seconds between publications. lcm::DrakeMockLcm lcm; const std::string channel_name = "channel_name"; LcmtDrakeSignalTranslator translator(kDim); // Instantiates the "device under test". auto dut = make_unique<LcmPublisherSystem>(channel_name, translator, &lcm); dut->set_publish_period(kPublishPeriod); unique_ptr<Context<double>> context = dut->AllocateContext(); context->FixInputPort(kPortNumber, make_unique<BasicVector<double>>(Eigen::VectorXd::Zero(kDim))); // Prepares to integrate. drake::systems::Simulator<double> simulator(*dut, std::move(context)); simulator.set_publish_every_time_step(false); simulator.Initialize(); for (double time = 0; time < 4; time += 0.01) { simulator.StepTo(time); EXPECT_NEAR(simulator.get_mutable_context().get_time(), time, 1e-10); // Note that the expected time is in milliseconds. const double expected_time = std::floor(time / kPublishPeriod) * kPublishPeriod * 1000; EXPECT_EQ(lcm.DecodeLastPublishedMessageAs<lcmt_drake_signal>( channel_name).timestamp, expected_time); } } } // namespace } // namespace lcm } // namespace systems } // namespace drake
#ifndef __DATASTRUCTURES_H #define __DATASTRUCTURES_H enum EObjectType { TYPE_SPHERE, TYPE_PLANE }; //////////////////////////////////////// //class decls //////////////////////////////////////// class Ray; class sphere; class plane; class object; class vect; class color; struct light; //###################################### //end class decls //###################################### //////////////////////////////////////// //data structures //////////////////////////////////////// class color { public: float r, g, b; // Color (R,G,B values) color(); color(float r,float g, float b); void scale(); }; class vect { public: float x, y, z; // Color (R,G,B values) vect(); vect(float x, float y, float z); }; class Ray { public: vect p0; vect d; Ray(){} Ray(vect p0, vect d); }; class object { public: EObjectType eType; color c; float reflPerc; float kamb; // The coefficient of ambient reflection float kdiff; // The coefficient of diffuse reflection float kspec; // The coefficient of specular reflection int shininess; // The exponent to use for Specular Phong Illumination virtual bool intersect(Ray const &ray, float &t) = 0; vect getReflection(vect v, vect point); //this function assumes you already have a valid point virtual vect getNormal(const vect &point) = 0; }; class sphere : public object { public: vect pc; float r; sphere(); sphere(vect const &pc, float r); bool intersect(Ray const &ray, float &t); vect getNormal(vect const &point); }; class plane : public object { public: float a0,b0,c0,d0; plane(); plane(float a, float b, float c, float d); bool intersect(Ray const &ray, float &t); vect getNormal(vect const &point); }; struct light { // Note: assume all lights are white vect p; // x, y, z coordinates of light color brightness; // Level of brightness of light (0.0 - 1.0) }; //###################################### //end data structures //###################################### //////////////////////////////////////// //overloaded operator declarations //////////////////////////////////////// color operator* (float const &f, color const &c); color operator* (color const &c, float const &f); color operator* (color const &c1, color const &c2); color operator/ (color const &c, float const &f); color operator+ (color const &c1, color const &c2); bool operator== (color const &c1, color const &c2); vect operator- (vect const &v1, vect const &v2); vect operator+ (vect const &v1, vect const &v2); vect operator* (float const &f, vect const &v); vect operator* (vect const &v, float const &f); vect operator/ (vect const &v, float const &f); //###################################### //end overloaded operator declarations //###################################### #endif
// // Created by wxy on 2018/2/25. // // // Created by wxy on 2018/2/25. // // // Created by wxy on 2018/2/24. // #include <unordered_set> #include <unordered_map> #include <vector> using namespace std; namespace p219 { class Solution { public: bool containsNearbyDuplicate(vector<int> &nums, int k) { unordered_set<int> record; for (int i = 0; i < nums.size(); ++i) { if (record.find(nums[i]) != record.end()) return true; record.insert(nums[i]); if (record.size() > k) record.erase(nums[i - k]); } return false; } }; }
#include <iostream> #include <bits/stdc++.h> struct TreeNode { int val; TreeNode * left; TreeNode * right; }; // 98. Validate Binary Search Tree class Solution { public: bool isValidBST(TreeNode* root) { if (!root) return true; return helper(root, LONG_MAX, LONG_MIN); } bool helper(TreeNode * root, long maxPath, long minPath) { if (!root) return true; if (root->val <= minPath || root->val >= maxPath) return false; // NOTE, <= return helper(root->left, root->val, minPath) && helper(root->right, maxPath, root->val); } }; /* Invalid tree - mismatch with parent invalid node: leaf 10 / \ 7 15 / \ / \ 8 9 13 18 invalid node : non-leaf 10 / \ 9 15 / \ / \ 8 7 13 18 12 // maxPath=INT_MIN, minPath=INT_MAX ==> maxPath=12, minPath=left-val(12) / \ 11 15 // 15: maxPath=12, minPath=12 ==> maxPath=15, minPath=left-val(12) / / \ 9 13 18 // 13: maxPath=15, minPath=left-val(12) ==> maxPath=15, minPath=left-val(12) / \ / \ 8 13 17 // 17: maxPath=18, minPath=left-val(12) // condition 1: left->val < cur->val // condition 2: cur->val < right->val // condition 3: cur->val < maxPath & right->val < maxPath cur->val > minPath & left->val < minPath // update maxPath, minPath 10 / \ 7 15 / \ / \ 8 9 13 18 */ int main() { // you can write to stdout for debugging purposes, e.g. std::cout << "This is a debug message" << std::endl; return 0; }
// // LABOLATORIUM_NR-9.cpp // LABOLATORIUM_NR-9 // // Created by Paweł Gaborek on 15/04/2019. // Copyright © 2019 Paweł Gaborek. All rights reserved. // #include "LABOLATORIUM_NR-9.hpp"
#ifndef CDTMANAGER_H #define CDTMANAGER_H #ifdef SINGLE #define REAL float #else /* not SINGLE */ #define REAL double #endif /* not SINGLE */ #define VOID int #include "triangulation.h" #include "triangle.h" #include "poly.h" #include <QObject> #include <QPolygonF> #include <QPointF> #include <QLineF> #include <QVector> class CDTManager : public QObject { Q_OBJECT public: static CDTManager& get_inst() { static CDTManager inst; return inst; } void set_points(const QVector<QPointF>& p) { _points = p; } void set_points_group_idx(const QVector<int>& p) { _points_group_idx = p; } void set_group_idx(const QVector<QVector<int> >& g) { _group_idx = g; } void clear(); void cdt(); const QVector<QLineF>& get_lines() const { return _lines; } const QVector<Triangle>& get_triangles() const { return _triangles; } signals: public slots: private: explicit CDTManager(QObject *parent = 0); void _group_to_segments(); struct triangulateio _create_input() const; struct triangulateio _create_mid() const; void _set_lines_by_edges(const triangulateio& io); void _set_triangles(const triangulateio& io); // raw data QVector<QPointF> _points; QVector<int> _points_group_idx; QVector<QVector<int> > _group_idx; QVector<QPair<int, int> > _segments; // output QVector<QLineF> _lines; QVector<Triangle> _triangles; }; inline CDTManager& get_cdt_manager() { return CDTManager::get_inst(); } #endif // CDTMANAGER_H
#include <FastBVH.h> #include <gtest/gtest.h> #include <list> #include "Primitive.h" using namespace FastBVH; namespace { //! \brief This is just boilerplate code for google test //! to be able to run template tests. template <typename T> class BuildStrategyTest : public ::testing::Test { public: using List = std::list<T>; static T shared_; T value_; }; //! \brief The floating point types to be tested. using FloatTypes = ::testing::Types<float, double, long double>; } // namespace TYPED_TEST_CASE(BuildStrategyTest, FloatTypes); TYPED_TEST(BuildStrategyTest, build) { Testing::Primitive<TypeParam> p[3] = {{{1, 2, 3}, {4, 5, 8}}, {{9, 8, 4}, {11, 15, 9}}, {{2, 6, 5}, {3, 7, 6}}}; std::vector<Testing::Primitive<TypeParam>> primitives; primitives.emplace_back(p[0]); primitives.emplace_back(p[1]); primitives.emplace_back(p[2]); Testing::BoxConverter<TypeParam> box_converter; BuildStrategy<TypeParam, 0> build_strategy; auto bvh = build_strategy(primitives, box_converter); auto nodes = bvh.getNodes(); constexpr TypeParam cmp_bias = 0.001; EXPECT_EQ(bvh.countLeafs(), 1); ASSERT_EQ(nodes.size(), 1); EXPECT_EQ(nodes[0].primitive_count, 3); EXPECT_NEAR(nodes[0].bbox.min.x, 1, cmp_bias); EXPECT_NEAR(nodes[0].bbox.min.y, 2, cmp_bias); EXPECT_NEAR(nodes[0].bbox.min.z, 3, cmp_bias); EXPECT_NEAR(nodes[0].bbox.max.x, 11, cmp_bias); EXPECT_NEAR(nodes[0].bbox.max.y, 15, cmp_bias); EXPECT_NEAR(nodes[0].bbox.max.z, 9, cmp_bias); }
/* * imagine.c * * Created on: 2018年11月1日 * Author: x */ #include "terrain.h" #include "texture.h" #include <GL/glut.h> #include <stdio.h> #include <stdlib.h> #include <math.h> static float FRAND() // returns a number ranging from -1.0 to 1.0 { return ((float) rand() - (float) rand()) / RAND_MAX; } Terrain::Terrain() { // glEnable(GL_DEPTH_TEST); // glEnable(GL_TEXTURE_2D); // glEnable(GL_CULL_FACE); // glCullFace(GL_CCW); // glClearColor(0.5, 0.5, 1.0, 0.0); // float blue[4] = {0.5, 0.5, 1.0, 0.0}; // float white[4] = {0.9, 0.9, 0.9, 1}; // glEnable(GL_FOG); // glFogfv(GL_FOG_COLOR, white); // glFogf(GL_FOG_MODE, GL_EXP2); // glFogf(GL_FOG_START, 500); // glFogf(GL_FOG_END, 800); // glFogf(GL_FOG_DENSITY, 0.01f); // Texture t; texture_id_ = Load_texture((char*) "models/ground.bmp"); init_terrain(); } Terrain::~Terrain() { } void Terrain::init_terrain() { int k; float h = 0.2; // loop through all of the heightfield points, randomly generating height values for(int z = 0; z < MAP_Z; z++) { for(int x = 0; x < MAP_X; x++) { k = z * MAP_X + x; terrain_[k][0] = float(x) * MAP_SCALE; terrain_[k][1] = h + FRAND() * h; terrain_[k][2] = -float(z) * MAP_SCALE; // set the values in the color array color_ar_[k][0] = color_ar_[k][1] = color_ar_[k][2] = terrain_[x + z * MAP_X][1] / 20.0f + 0.5; // set the values in the texture coordinate array. since the texture // is tiled over each "square", we can use texture wrapping texcoord_ar_[k][0] = (float) x / (MAP_X); texcoord_ar_[k][1] = (float) z / (MAP_Z); } } for(int z = MAP_Z / 2 - 4; z >= 0 && z < MAP_Z / 2 + 4; z++) { for(int x = MAP_X / 2 - 2; x >= 0 && x < MAP_X / 2 + 2; x++) { k = z * MAP_X + x; // terrain_[k][0] = float(x) * MAP_SCALE; terrain_[k][1] += h * 10; // terrain_[k][2] = -float(z) * MAP_SCALE; } } #if GL_DRAW_ELEMENTS // loop over all vertices in the terrain map int i = 0; for(int z = 0; z < MAP_Z - 1; z++) { for(int x = 0; x < MAP_X; x++) { k = z * MAP_X + x; // add next two elements to the triangle strip index_ar_[i++] = k + MAP_X; index_ar_[i++] = k; // printf("%d %d \n", k + MAP_X, k); } } glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 0, terrain_); glEnableClientState(GL_COLOR_ARRAY); glColorPointer(3, GL_FLOAT, 0, color_ar_); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer(2, GL_FLOAT, 0, texcoord_ar_); #endif } void Terrain::draw_terrain() { glBindTexture(GL_TEXTURE_2D, texture_id_); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); #if GL_DRAW_ELEMENTS for(int z = 0; z < MAP_Z - 1; z++) { glDrawElements(GL_TRIANGLE_STRIP, MAP_X * 2, GL_UNSIGNED_INT, &index_ar_[MAP_X * 2 * z]); } #else glColor3f(0, 0, 1); int i = 0; for(int z = 0; z < MAP_Z - 1; z++) { glBegin(GL_TRIANGLE_STRIP); for(int x = 0; x < MAP_X; x++) { i = z * MAP_X + x; i += MAP_X; glColor3f(color_ar_[i][0], color_ar_[i][1], color_ar_[i][2]); glTexCoord2f(texcoord_ar_[i][0], texcoord_ar_[i][1]); glVertex3f(terrain_[i][0], terrain_[i][1], terrain_[i][2]); i -= MAP_X; glTexCoord2f(texcoord_ar_[i][0], texcoord_ar_[i][1]); glVertex3f(terrain_[i][0], terrain_[i][1], terrain_[i][2]); } glEnd(); } #endif } void Terrain::draw_terrain_lines() { // select the sand texture glDisable(GL_TEXTURE_2D); #if GL_DRAW_ELEMENTS for(int z = 0; z < MAP_Z - 1; z++) { glDrawElements(GL_LINE_STRIP, MAP_X * 2, GL_UNSIGNED_INT, &index_ar_[MAP_X * 2 * z]); break; } #else glColor3f(0, 0, 1); int i = 0; for(int z = 0; z < MAP_Z - 1; z++) { glBegin(GL_LINE_STRIP); for(int x = 0; x < MAP_X; x++) { i = z * MAP_X + x; i += MAP_X; glVertex3f(terrain_[i][0], terrain_[i][1], terrain_[i][2]); i -= MAP_X; glVertex3f(terrain_[i][0], terrain_[i][1], terrain_[i][2]); } glEnd(); } #endif } int Terrain::width() { return (MAP_X - 1) * MAP_SCALE; } int Terrain::height() { return (MAP_Z - 1) * MAP_SCALE; } void Terrain::draw(void) { // glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // draw_terrain_lines(); draw_terrain(); // draw_cacus(); } bool Terrain::coord_is_in_map(float x, float z) { // if(geometric_center_coord_.x < 0) // geometric_center_coord_.x = 0; // if(geometric_center_coord_.x > (terrain_->width() - 1) * terrain_->terrain_mul()) // geometric_center_coord_.x = (terrain_->width() - 1) * terrain_->terrain_mul(); // if(geometric_center_coord_.z < -(terrain_->height() - 1) * terrain_->terrain_mul()) // geometric_center_coord_.z = -(terrain_->height() - 1) * terrain_->terrain_mul(); // if(geometric_center_coord_.z > 0) // geometric_center_coord_.z = 0; bool b = true; b &= (x >= 0); b &= (x <= width()); b &= (z <= 0); b &= (z >= -height()); return b; } float Terrain::terrain_Y_coord(float x, float z) { if(coord_is_in_map(x, z) == false) { return -1 * LARGE_FLOAT_NUMBER; // -1*a is more eye-catching than -a } // x = Clamp<float>(x, 0, (MAP_X - 1) * MAP_SCALE); // z = Clamp<float>(z, -(MAP_Z - 1) * MAP_SCALE, 0); // divide by the grid-spacing if it is not 1 float projCameraX = x / MAP_SCALE; float projCameraZ = -z / MAP_SCALE; // compute the height field coordinates (hflCol0, hflRow0) and // (hflCol1, hflRow1) that identify the height field cell directly below the camera. int hflCol0 = int(projCameraX); int hflRow0 = int(projCameraZ); int hflCol1 = hflCol0 + 1; int hflRow1 = hflRow0 + 1; // get the four corner heights of the cell from the height field float h00 = terrain_[hflCol0 + hflRow0 * MAP_X][1]; float h01 = terrain_[hflCol1 + hflRow0 * MAP_X][1]; float h11 = terrain_[hflCol1 + hflRow1 * MAP_X][1]; float h10 = terrain_[hflCol0 + hflRow1 * MAP_X][1]; // calculate the position of the camera relative to the cell. // note, that 0 <= tx, ty <= 1. float tx = projCameraX - float(hflCol0); float ty = projCameraZ - float(hflRow0); // the next step is to perform a bilinear interpolation to compute the height // of the terrain directly below the object. float txty = tx * ty; return h00 * (1.0f - ty - tx + txty) + h01 * (tx - txty) + h11 * txty + h10 * (ty - txty); }
/* * ===================================================================================== * * Filename: test.cpp * * Description: * * Version: 1.0 * Created: 09/16/2013 03:47:36 PM * Revision: none * Compiler: gcc * * Author: Shuai YUAN (galoisplusplus), yszheda@gmail.com * Organization: * * ===================================================================================== */ #include <iostream> #include "InsertionSort.hpp" using namespace std; int main(int argc, char *argv[]) { int myints[] = {32,71,12,45,26,80,53,33}; std::vector<int> elems (myints, myints+8); InsertionSort(elems); for (auto& elem : elems) { cout << elem << " "; } cout << endl; return 0; }
#ifndef CALCULATOR_H #define CALCULATOR_H #include "Move.h" #include "TaskManager.h" #include "Player.h" #include "ObjectManager.h" #include "Camera.h" namespace MP { class Calculator { private: void _computer_players_procedure(TaskManager& aMainTaskManager, SoundManager& aSoundManager, ObjectManager& aObiectManager, sf::Clock& gameClock,Map& aMap); void _trees_procedure(TaskManager& aMainTaskManager, sf::Clock& globalClock, ObjectManager& aObiectManager); public: void updateGame(SoundManager& aSoundManager, TaskManager& aTaskManager, ObjectManager& aObiectManager, sf::Clock& globalClock, Camera& aCamera); }; } #endif
#ifndef IMPBASE_H #define IMPBASE_H /// @file ImpBase.h /// @brief ImpBase のヘッダファイル /// @author Yusuke Matsunaga (松永 裕介) /// /// Copyright (C) 2005-2012 Yusuke Matsunaga /// All rights reserved. #include "YmNetworks/bdn.h" BEGIN_NAMESPACE_YM_NETWORKS class ImpMgr; class ImpInfo; ////////////////////////////////////////////////////////////////////// /// @class ImpBase ImpBase.h "ImpBase.h" /// @brief 含意を求めるクラス ////////////////////////////////////////////////////////////////////// class ImpBase { public: /// @brief コンストラクタ ImpBase(); /// @brief デストラクタ ~ImpBase(); public: ////////////////////////////////////////////////////////////////////// // 外部インターフェイスの宣言 ////////////////////////////////////////////////////////////////////// /// @brief ネットワーク中の間接含意を求める. /// @param[in] imp_mgr マネージャ /// @param[in] method 手法を表す文字列 /// @param[out] imp_info 間接含意のリスト void learning(ImpMgr& imp_mgr, const string& method, ImpInfo& imp_info); }; END_NAMESPACE_YM_NETWORKS #endif // IMPBASE_H
#pragma once #include "GameFramework/Actor.h" #include "Weapon.generated.h" UCLASS() class SPOOL_API AWeapon : public AActor { GENERATED_BODY() FTimerHandle TimerHandle_Fire; public: UPROPERTY(EditDefaultsOnly, Category = Firearm) float FireCooldown; UPROPERTY(EditDefaultsOnly, Category = Firearm) bool bAuto; AWeapon(); class ASpoolCharacter * GetCharacter(); float GetCooldownRatio() const; virtual bool Fire(); void LoopFire(); UFUNCTION(NetMulticast, Reliable) void MulticastOnFired(); };
#ifndef __PRINTTAB_H__ #define __PRINTTAB_H__ #include "tabbase.h" enum class BuildPlatformState { Lowered, Raising, Raised, Lowering, }; inline constexpr int operator+( BuildPlatformState const value ) { return static_cast<int>( value ); } char const* ToString( BuildPlatformState const value ); class PrintTab: public InitialShowEventMixin<PrintTab, TabBase> { Q_OBJECT public: PrintTab( QWidget* parent = nullptr ); virtual ~PrintTab( ) override; bool isPrintButtonEnabled( ) const { return _printButton->isEnabled( ); } virtual TabIndex tabIndex( ) const override { return TabIndex::Print; } protected: virtual void _connectPrintJob( ) override; virtual void _connectShepherd( ) override; virtual void initialShowEvent( QShowEvent* event ) override; private: bool _isPrinterOnline { false }; bool _isPrinterAvailable { true }; bool _isPrinterPrepared { false }; bool _isModelRendered { false }; BuildPlatformState _buildPlatformState { BuildPlatformState::Lowered }; QLabel* _exposureTimeLabel { new QLabel }; QLabel* _exposureTimeValue { new QLabel }; QHBoxLayout* _exposureTimeValueLayout { }; QSlider* _exposureTimeSlider { new QSlider }; QVBoxLayout* _exposureTimeLayout { new QVBoxLayout }; QLabel* _exposureTimeScaleFactorLabel { new QLabel }; QLabel* _exposureTimeScaleFactorValue { new QLabel }; QHBoxLayout* _exposureTimeScaleFactorValueLayout { }; QSlider* _exposureTimeScaleFactorSlider { new QSlider }; QVBoxLayout* _exposureTimeScaleFactorLayout { new QVBoxLayout }; QHBoxLayout* _exposureLayout { new QHBoxLayout }; QLabel* _powerLevelLabel { new QLabel }; QLabel* _powerLevelValue { new QLabel }; QSlider* _powerLevelSlider { new QSlider }; QLabel* _printSpeedLabel { new QLabel }; QLabel* _printSpeedValue { new QLabel }; QSlider* _printSpeedSlider { new QSlider }; QVBoxLayout* _optionsLayout { new QVBoxLayout }; QGroupBox* _optionsGroup { new QGroupBox }; QPushButton* _printButton { new QPushButton }; QPushButton* _raiseOrLowerButton { new QPushButton }; QPushButton* _homeButton { new QPushButton }; QGroupBox* _adjustmentsGroup { new QGroupBox }; QGridLayout* _layout { new QGridLayout }; void _updateUiState( ); signals: void printerAvailabilityChanged( bool const available ); void printRequested( ); public slots: virtual void tab_uiStateChanged( TabIndex const sender, UiState const state ) override; void setModelRendered( bool const value ); void setPrinterPrepared( bool const value ); void clearPrinterPrepared( ); void setPrinterAvailable( bool const value ); protected slots: private slots: void printer_online( ); void printer_offline( ); void raiseBuildPlatform_moveAbsoluteComplete( bool const success ); void lowerBuildPlatform_moveAbsoluteComplete( bool const success ); void home_homeComplete( bool const success ); void exposureTimeSlider_valueChanged( int value ); void exposureTimeScaleFactorSlider_valueChanged( int value ); void powerLevelSlider_valueChanged( int value ); void printSpeedSlider_valueChanged( int value ); void printButton_clicked( bool ); void raiseOrLowerButton_clicked( bool ); void homeButton_clicked( bool ); }; #endif // __PRINTTAB_H__