text
stringlengths
8
6.88M
#include "device.h" // Device header #include "shape.h" #include "colors16bit.h" #ifndef VERLINE_H #define VERLINE_H class Verline : public Shape { private: uint16_t x, y, length; uint8_t thick; uint16_t * color; public: Verline (uint16_t x_, uint16_t y_, uint16_t * color_, uint16_t length_, uint8_t thick_); void draw () const override; void setPosition (uint16_t x_, uint16_t y_) override; }; #endif
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstdlib> #include "instruction.h" #include <dlfcn.h> int main(int argc, char **argv) { if (argc != 2) { std::cout << "usage: ./testInstruction <instruction in hex>" << std::endl; exit(1); } Instruction myInstruction; unsigned char *sym = (unsigned char *)dlsym(RTLD_NEXT, argv[1]); if (!sym) { printf("couldnt find a symbol\n"); exit(1); } int i; for (i = 0; i < 11; i++) { printf("1: %x\n",sym[i]); } int length, patches; int n = 0; while ( n < 15) { printf("sym[0] = %x\n", *sym); length = myInstruction.decodeInstruction(sym, 0); if (length == 0) { std::cout << "Invalid instruction" << std::endl; exit(1); } for (i = 0; i < length; i++) { printf("%d: %x\n",i,sym[i]); } patches = myInstruction.getPatch(); printf("length: %d, patches: %x\n",length,patches); n += length; sym += length; myInstruction.clear(); } return 0; }
// // MosquittoClient.cpp // IPCT // // Created by SteveKim on 2020/03/04. // #include "MosquittoClient.h" #include "libmosquitto/mosquitto.h" #include "../../Classes/SMFrameWork/Util/encrypt/AES.h" #include <sstream> bool MosquittoClient::_init = false; static void on_connect(void *ptr, int rc) { MosquittoClient* client = (MosquittoClient*)ptr; if(client->getMQTTProtocol()!=NULL){ client->getMQTTProtocol()->didConnect(rc); } } static void on_disconnect(void *ptr) { MosquittoClient* client = (MosquittoClient*)ptr; if(client->getMQTTProtocol()!=NULL){ client->getMQTTProtocol()->didDisconnect(); } } static void on_publish(void *ptr, uint16_t message_id) { MosquittoClient* client = (MosquittoClient*)ptr; if(client->getMQTTProtocol()!=NULL){ client->getMQTTProtocol()->didPublish(message_id); } } static void on_message(void *ptr, const struct mosquitto_message *message) { MosquittoClient* client = (MosquittoClient*)ptr; if(client->getMQTTProtocol()!=NULL){ std::string topic(message->topic); std::string payload((char*)message->payload, message->payloadlen); std::string getmsg = aes_decryt(payload); // for test if (getmsg=="") { getmsg = payload; } client->getMQTTProtocol()->didReceiveMessage(getmsg, topic); } } static void on_subscribe(void *ptr, uint16_t message_id, int qos_count, const uint8_t *granted_qos) { MosquittoClient* client = (MosquittoClient*)ptr; if(client->getMQTTProtocol()!=NULL){ //TODO: implement this client->getMQTTProtocol()->didSubscribe(message_id, nullptr); } } static void on_unsubscribe(void *ptr, uint16_t message_id) { MosquittoClient* client = (MosquittoClient*)ptr; if(client->getMQTTProtocol()!=NULL){ //TODO: implement this client->getMQTTProtocol()->didUnsubscribe(message_id); } } MosquittoClient::MosquittoClient(std::string clientId){ if(!MosquittoClient::_init){ mosquitto_lib_init(); MosquittoClient::_init=true; } mosq = mosquitto_new(clientId.c_str(), this); mosquitto_connect_callback_set(mosq, on_connect); mosquitto_disconnect_callback_set(mosq, on_disconnect); mosquitto_publish_callback_set(mosq, on_publish); mosquitto_message_callback_set(mosq, on_message); mosquitto_subscribe_callback_set(mosq, on_subscribe); mosquitto_unsubscribe_callback_set(mosq, on_unsubscribe); } std::string MosquittoClient::version() { int major, minor, revision; std::stringstream out; mosquitto_lib_version(&major, &minor, &revision); out<<major<<"."<<minor<<"."<<revision; return out.str(); } MosquittoClient::~MosquittoClient(){ if (mosq) { mosquitto_destroy(mosq); mosq = NULL; } this->stopAllActions(); // this->unscheduleAllSelectors(); //[super dealloc] } MosquittoClient* MosquittoClient::create(std::string clientId, MQTTProtocol* caller){ MosquittoClient* salida = new (std::nothrow) MosquittoClient(clientId); if (salida) { salida->setMQTTProtocol(caller); salida->setHost(std::string("")); salida->setPort(1883); salida->setKeepAlive(30); salida->setCleanSession(true); salida->autorelease(); } return salida; } void MosquittoClient::setLogPriorities(int priorities, int destinations){ mosquitto_log_init(mosq, priorities, destinations); } void MosquittoClient::connect(){ //std::string host = gethost(); char *cstrHost=(char*)malloc(getHost().size()); strcpy(cstrHost, getHost().c_str()); //const char *cstrHost = gethost().c_str(); const char *cstrUsername = NULL, *cstrPassword = NULL; if (getUserName() != "") cstrUsername = getUserName().c_str(); if (getPassword() != "") cstrPassword = getPassword().c_str(); // FIXME: check for errors mosquitto_username_pw_set(mosq, cstrUsername, cstrPassword); mosquitto_connect(mosq, cstrHost, _port, _keepAlive, _cleanSession); // Setup timer to handle network events // FIXME: better way to do this - hook into iOS Run Loop select() ? // or run in seperate thread? this->schedule(schedule_selector(MosquittoClient::loop),0.01); } void MosquittoClient::loop(float dt){ mosquitto_loop(mosq, 0); } void MosquittoClient::connectToHost(std::string host) { setHost(host); connect(); } void MosquittoClient::reconnect() { mosquitto_reconnect(mosq); } void MosquittoClient::disconnect() { mosquitto_disconnect(mosq); } // FIXME: add QoS parameter? void MosquittoClient::publishString(std::string payload, std::string topic, bool retain){ // retain : 마지막으로 발송된 메시지를 Broker가 보관 std::string sendMsg = aes_encryt(payload); mosquitto_publish(mosq, NULL, topic.c_str(), sendMsg.size(), (const uint8_t*)sendMsg.c_str(), 0, retain); } void MosquittoClient::subscribe(std::string topic){ subscribe(topic, 0); } void MosquittoClient::subscribe(std::string topic, int qos){ mosquitto_subscribe(mosq, NULL, topic.c_str(), qos); } void MosquittoClient::unsubscribe(std::string topic){ mosquitto_unsubscribe(mosq, NULL, topic.c_str()); } void MosquittoClient::setMessageRetry(unsigned int seconds){ mosquitto_message_retry_set(mosq, seconds); }
#ifndef _GLX_MAT4X4_MATH_INLINE_H_ #define _GLX_MAT4X4_MATH_INLINE_H_ #include "GLXVec3.h" #include "GLXMat4x4.h" /* Supports only floats resets do identity matrix */ template<class T> inline void glx::mat4<T>::Clear() { m[0][0] = m[1][1] = m[3][3] = T(1); m[0][1] = m[0][2] = m[0][3] = m[1][0] = m[1][2] = m[1][3] = m[2][0] = m[2][1] = m[2][3] = m[3][0] = m[3][1] = m[3][2] = T(0); } template<class T> inline glx::mat4<T>::mat4(T m11, T m21, T m31, T m41, T m12, T m22, T m32, T m42, T m13, T m23, T m33, T m43, T m14, T m24, T m34, T m44) { _11 = m11; _21 = m21; _31 = m31; _41 = m41; _12 = m12; _22 = m22; _32 = m32; _42 = m42; _13 = m13; _23 = m23; _33 = m33; _43 = m43; _14 = m14; _24 = m24; _34 = m34; _44 = m44; } template<class T> inline glx::mat4<T>::mat4(glx::mat4<T>& mat) { std::memcpy(&_11, &mat, sizeof(glx::mat4<T>)); } template<class T> inline glx::mat4<T>::mat4(const T* pF) { if (!pF)return; std::memcpy(&_11, pF, sizeof(glx::mat4<T>)); } //acces grants template<class T> inline T& glx::mat4<T>::operator () (unsigned int row, unsigned int col) { return m[row][col]; } template<class T> inline T glx::mat4<T>::operator () (unsigned int row, unsigned int col)const { return m[row][col]; } //casting operators template<class T> inline glx::mat4<T>::operator float* () { return (float*)&_11; } template<class T> inline glx::mat4<T>::operator const float* () const { return (const float*)&_11; } //assignement operators template<class T> inline glx::mat4<T>& glx::mat4<T>::operator *= (const glx::mat4<T>& mat) { //wrooooooong. Do you eve math microsoft? //GLXMatrixMultiply(this, this, &mat); return *this; } template<class T> inline glx::mat4<T>& glx::mat4<T>::operator += (const glx::mat4<T>& mat) { _11 += mat._11; _12 += mat._12; _13 += mat._13; _14 += mat._14; _21 += mat._21; _22 += mat._22; _23 += mat._23; _24 += mat._24; _31 += mat._31; _32 += mat._32; _33 += mat._33; _34 += mat._34; _41 += mat._41; _42 += mat._42; _43 += mat._43; _44 += mat._44; return *this; } template<class T> inline glx::mat4<T>& glx::mat4<T>::operator -= (const glx::mat4<T>& mat) { _11 -= mat._11; _12 -= mat._12; _13 -= mat._13; _14 -= mat._14; _21 -= mat._21; _22 -= mat._22; _23 -= mat._23; _24 -= mat._24; _31 -= mat._31; _32 -= mat._32; _33 -= mat._33; _34 -= mat._34; _41 -= mat._41; _42 -= mat._42; _43 -= mat._43; _44 -= mat._44; return *this; } template<class T> inline glx::mat4<T>& glx::mat4<T>::operator *= (T f) { _11 *= f; _12 *= f; _13 *= f; _14 *= f; _21 *= f; _22 *= f; _23 *= f; _24 *= f; _31 *= f; _32 *= f; _33 *= f; _34 *= f; _41 *= f; _42 *= f; _43 *= f; _44 *= f; return *this; } template<class T> inline glx::mat4<T>& glx::mat4<T>::operator /= (T f) { _11 /= f; _12 /= f; _13 /= f; _14 /= f; _21 /= f; _22 /= f; _23 /= f; _24 /= f; _31 /= f; _32 /= f; _33 /= f; _34 /= f; _41 /= f; _42 /= f; _43 /= f; _44 /= f; return *this; } template<class T> inline glx::mat4<T>& glx::mat4<T>::operator = (const mat4<T>& mat) { _11 = mat._11; _12 = mat._12; _13 = mat._13; _14 = mat._14; _21 = mat._21; _22 = mat._22; _23 = mat._23; _24 = mat._24; _31 = mat._31; _32 = mat._32; _33 = mat._33; _34 = mat._34; _41 = mat._41; _42 = mat._42; _43 = mat._43; _44 = mat._44; return *this; } //unary operators template<class T> inline glx::mat4<T> glx::mat4<T>::operator + () const { return *this; } template<class T> inline glx::mat4<T> glx::mat4<T>::operator - () const { return glx::mat4<T>(-_11, -_12, -_13, -_14, -_21, -_22, -_23, -_24, -_31, -_32, -_33, -_34, -_41, -_42, -_43, -_44); } //binary operators template<class T> inline glx::mat4<T> glx::mat4<T>::operator * (const glx::mat4<T>& mat) const { glx::mat4<T> buf; GLXMatrixMultiply(&buf, this, &mat); return buf; } template<class T> inline glx::mat4<T> glx::mat4<T>::operator + (const glx::mat4<T>& mat) const { return glx::mat4<T>(_11 + mat._11, _12 + mat._12, _13 + mat._13, _14 + mat._14, _21 + mat._21, _22 + mat._22, _23 + mat._23, _24 + mat._24, _31 + mat._31, _32 + mat._32, _33 + mat._33, _34 + mat._34, _41 + mat._41, _42 + mat._42, _43 + mat._43, _44 + mat._44); } template<class T> inline glx::mat4<T> glx::mat4<T>::operator - (const glx::mat4<T>& mat) const { return glx::mat4<T>(_11 - mat._11, _12 - mat._12, _13 - mat._13, _14 - mat._14, _21 - mat._21, _22 - mat._22, _23 - mat._23, _24 - mat._24, _31 - mat._31, _32 - mat._32, _33 - mat._33, _34 - mat._34, _41 - mat._41, _42 - mat._42, _43 - mat._43, _44 - mat._44); } template<class T> inline glx::mat4<T> glx::mat4<T>::operator * (T f) const { return glx::mat4<T>( _11 * f, _12 * f, _13 * f, _14 * f, _21 * f, _22 * f, _23 * f, _24 * f, _31 * f, _32 * f, _33 * f, _34 * f, _41 * f, _42 * f, _43 * f, _44 * f); } template<class T> inline glx::mat4<T> glx::mat4<T>::operator / (T f) const { return glx::mat4<T>( _11 / f, _12 / f, _13 / f, _14 / f, _21 / f, _22 / f, _23 / f, _24 / f, _31 / f, _32 / f, _33 / f, _34 / f, _41 / f, _42 / f, _43 / f, _44 / f); } template<class T> inline glx::mat4<T> operator * (T f, const glx::mat4<T>& mat) { return glx::mat4<T>(f * mat._11, f * mat._12, f * mat._13, f * mat._14, f * mat._21, f * mat._22, f * mat._23, f * mat._24, f * mat._31, f * mat._32, f * mat._33, f * mat._34, f * mat._41, f * mat._42, f * mat._43, f * mat._44); } template<class T> inline bool glx::mat4<T>::operator == (const glx::mat4<T>& mat) const { return (std::memcpy(this, &mat, sizeof(glx::mat4<T>)) == 0); } template<class T> inline bool glx::mat4<T>::operator != (const glx::mat4<T>& mat) const { return (std::memcpy(this, &mat, sizeof(glx::mat4<T>)) != 0); } //Setters template<class T> inline void glx::mat4<T>::SetPosition(const glx::vec3<T> &vec) { _41 = vec.x; _42 = vec.y; _43 = vec.z; } template<class T> inline void glx::mat4<T>::SetPosition(const glx::vec4<T> &vec) { _41 = vec.x; _42 = vec.y; _43 = vec.z; _44 = vec.w; } template<class T> inline void glx::mat4<T>::SetScale(const glx::vec3<T> &vec) { _11 = vec.x; _22 = vec.y; _33 = vec.z; } template<class T> inline void glx::mat4<T>::SetRotation(const glx::mat4<T> & m) { _11 = m.m[0][0]; _12 = m.m[1][0]; _13 = m.m[2][0]; _21 = m.m[0][1]; _22 = m.m[1][1]; _23 = m.m[2][1]; _31 = m.m[0][2]; _32 = m.m[1][2]; _33 = m.m[2][2]; } //Getters template<class T> inline glx::vec3<T> glx::mat4<T>::GetPosition() const { return glx::vec3<T>(_41, _42, _43); } template<class T> inline glx::vec3<T> glx::mat4<T>::GetScale() const { return glx::vec3<T>(_11, _22, _33); } template<class T> inline glx::vec3<T> glx::mat4<T>::GetDirection() const { // Note - the following code can be used to double check the vector construction above. glx::mat4<T> justRot = *this; //justRot.SetPosition(Vec3(0.f, 0.f, 0.f)); //Vec3 forward = justRot.Xform(g_Forward); return justRot; } #endif
#include <bits/stdc++.h> using namespace std; int strLen(char* s){ int count = 0; while(*s != '\0') { count++; s +=1; } return count; } void delete_char(char *S, char c){ char* pr = S, * pw = S; while (*pr !='\0') { *pw = *(pr++); if(*pw != c) pw++; } *pw = '\0'; } void pad_right(char *s, int n){ if(strLen(s)<n){ *(s+strLen(s))='_'; return pad_right(s, n); } } void pad_left(char *s, int n){ if(strLen(s)<n){ for(int i=strLen(s)-1;i>=0;i--){ s[i+1]=s[i]; } s[0]='_'; return pad_left(s,n); } } void reverse(char *s){ for(int i =0; i < strLen(s)/2;++i ){ char t = s[i]; s[i]=s[strLen(s)-i-1]; s[strLen(s)-i-1] = t; } } void trim_right(char *s){ } #include<cstring> void trim_left(char *s){ for(int i = 0; i <strlen(s); ++i){ if(s[0]!=' ') break; if(*(s+i) != ' ') { for(int j=i; j<strlen(s); ++j) { char temp = *(s+j-i); *(s+j-i)=*(s+j); *(s+j) = temp; } break; } } } int main() { char* s = "aaasdd"; cout << strLen(s) << endl; }
// It sets pre and suc as predecessor and successor respectively void findPreSuc(Node* root, Node*& pre, Node*& suc, int key) { if(root==NULL) { return ; } if(root->key == key) { if(root->left!=NULL) { Node* temp = root->left; while(temp!=NULL && temp->right!=NULL) { temp=temp->right; } pre = temp; } if(root->right!=NULL) { Node* temp = root->right; while(temp!=NULL && temp->left!=NULL) { temp = temp->left; } suc = temp; } return ; } if(key < root->key) { suc = root; // even if key is not present this can be suc return findPreSuc(root->left,pre,suc,key); } else { pre = root; // even if key is not present this can be pre return findPreSuc(root->right,pre,suc,key); } }
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; int main() { char str[6 + 1]; while (scanf("%s", str) != EOF) { int len = strlen(str); do { for (int i = 0; i < len; i++) { printf("%c", str[i]); } printf("\n"); } while (next_permutation(str, str + len)); printf("\n"); } }
#include <iostream> #include <stdlib.h> #include <time.h> #include "inout.h" #include "assign.h" #include "wyarray.h" #include "solver.h" using namespace std; /* ------------------------------------------------- * algorithm * * while (r2/r1 - 1 > eps) * compute dx * while (dr > 0) * step = step * beta * x = x0 + step * dx * dr = r2 - (1 - alpha * step) * r1 ---------------------------------------------- */ SolverNle::SolverNle (int nm) { this->nm = nm; this->inner = 10; this->outer = 50; // x1 = x0 + step * dx this->step = 0.001; this->alpha = 0.1; this->beta = 0.5; this->eps = 1e-06; this->iprint = 0; } // equality constrained minimization void SolverNle::NewtonEcm (assign &ass) { double *dx = new double[nm]; double *x0 = new double[nm]; double *x1 = new double[nm]; double *xr = new double[nm]; double *b0 = new double[nm]; double *b1 = new double[nm]; // CG parameters int cg_niter = 50; double cg_eps = 1e-06; double cg_wns = 0.01; // define a CG operator used in computing dx SolverCG solcg (cg_eps, cg_wns, cg_niter, nm); // check the operator // solcg.CheckCgsOp(ass); exit(0); // define an inout class inout exaio; // copy initial value from ass to x1 ass.GetX (x1); int iter_out = 0; int iter_inn = 0; double r_perc = 1.0; double r_x0 = 1.0, r_x1, dr; double mis0, mis1; double r1, r2; while (r_perc > this->eps && iter_out < this->outer) { iter_out += 1; cout << " ### " << endl; cout << " ### ------ outer=" << iter_out << "/" << outer << ":" << endl; memcpy(x0, x1, nm * sizeof(double)); if (iprint == 1) { cout << endl << " --- initial x --- " << endl; exaio.printArray(x0, nm); } // calculate residual and norm ass.residual(b0, x0); mis0 = ass.misfit(x0); r_x0 = norm2(b0, nm); if (iprint == 1) { cout << endl << " --- initial residual --- " << endl; exaio.printArray(b0, nm); exit(0); } memset(dx, 0, nm * sizeof(double)); solcg.CgsWy (dx, dx, b0, ass); //solcg.cgsly (dx, dx, b0, ass); if (iprint == 1) { cout << endl << " --- solve dx --- " << endl; exaio.printArray(dx, nm); } iter_inn = 0; dr = 1.0; step /= beta; while (dr > 0 && iter_inn < inner) { iter_inn += 1; /* x1 = x0 + step * dx; */ VectorAdd (x1, x0, dx, 1.0, step, nm); if (iprint == 1) { cout << endl << " --- inner update x ---- " << endl; exaio.printArray(x1, nm); } if (vector_min(x1, nm) < 1e-36) { mis1 = 0.0; r_x1 = 2.0 * r_x0; } else { ass.residual(b1, x1); mis1 = ass.misfit(x1); r_x1 = norm2(b1, nm); if (iprint == 1) { cout << endl << " --- update residual ---- " << endl; exaio.printArray(b1, nm); } } dr = r_x1 - (1.0 - alpha * step) * r_x0; cout << " ------ inner=" << iter_inn << "/" << inner <<", step=" << step << ", mis=" << mis1 <<", r_x0=" << r_x0 << ", r_x1=" << r_x1 << ", dr=" << dr << endl; step = beta * step; } if (iter_out % 10 == 1 && iprint == 1) { cout << " --- outer update x ---- " << endl; exaio.printArray(x1, nm); } // update ass.x0 ass.UpdateX (x1); ass.maxres(&r1, &r2, b1); r_perc = abs(r_x1 / r_x0 - 1.0); cout << " --- outer = " << iter_out << "/" << outer << " mis=" << mis1 << " r_perc = " << r_perc << " r1=" << r1 << " r2=" << r2 << endl; } cout << endl; cout << " --- final x ---- " << endl; //exaio.printArray(x1, nm); delete [] dx; delete [] x0; delete [] x1; delete [] xr; delete [] b0; delete [] b1; }
#ifndef CATEGORY #define CATEGORY // Entity/scene node category used to dispatch commands namespace Category { enum Type { None = 0, SceneAirLayer = 1 << 0, PlayerCharacter = 1 << 1, AlliedCharacter = 1 << 2, NeutralCharacter = 1 << 3, EnemyCharacter = 1 << 4, EveryCharacters = PlayerCharacter | AlliedCharacter | NeutralCharacter | EnemyCharacter, NonPlayableCharacters = AlliedCharacter | NeutralCharacter | EnemyCharacter, NonEnnemyCharacters = AlliedCharacter | NeutralCharacter, }; } #endif // CATEGORY
// Copyright 2016 Tamas Palagyi #ifndef APP_SRC_DICOM_H_ #define APP_SRC_DICOM_H_ #include <limits.h> #include <iostream> #include <string> #include <vector> #include <map> #include <stdexcept> #include <sstream> #include <set> // Since DCMTK does not manage blocking select - it is not able to // give a NULL timeout value to select (see ASC_associationWaiting // source code), we need to force to a very long timeout that is // 2147483647 seconds ~ 68 years on my x86_64. #define TIMEOUT INT_MAX // STUDY LEVEL typedef std::string PatientID; typedef std::string PatientName; typedef std::string StudyUID; typedef std::string StudyDesc; // SERIES LEVEL typedef std::string SeriesUID; typedef std::string SeriesDesc; // IMAGE LEVEL typedef std::string SOPInstanceUID; typedef std::string SOPClassUID; typedef std::string TransferSyntaxUID; typedef std::map<std::string, std::string> AetMap; typedef std::set<std::string> Xfers; typedef std::map<TransferSyntaxUID, void*> DatasetMap; class DcmDataset; //------------------------------------------------------------------------------ #define THROW_DICOM_EXCEPTION(a) throw dicom_exception(a, 0, __FILE__, __LINE__); class dicom_exception : public std::exception { std::string what_; unsigned int code_; std::string file_; int line_; std::string where_; public: dicom_exception(const std::string& what, int code, const char* file, int line) : what_(what), code_(code), file_(file), line_(line) { std::ostringstream out; out << "Exception from " << file_ << ":" << line_; where_ = out.str(); std::cerr << where_ << std::endl; } virtual const char* what() const throw() { return what_.c_str(); } virtual unsigned int code() const throw() { return code_; } virtual const char* where() const throw() { return where_.c_str(); } }; //------------------------------------------------------------------------------ struct Image { std::string source_; TransferSyntaxUID transfer_syntax_uid_; // STUDY LEVEL PatientID patient_id_; PatientName patient_name_; StudyUID study_uid_; StudyDesc study_desc_; // SERIES LEVEL SeriesUID series_uid_; SeriesDesc series_desc_; // IMAGE LEVEL SOPInstanceUID sop_instance_uid_; SOPClassUID sop_class_uid_; // void* dataset_; DatasetMap datasets_; void init(std::string source, TransferSyntaxUID transfer_syntax_uid, // STUDY PatientID patient_id, PatientName patient_name, StudyUID study_uid, StudyDesc study_desc, // SERIES LEVEL SeriesUID series_uid, SeriesDesc series_desc, // IMAGE LEVEL SOPInstanceUID sop_instance_uid, SOPClassUID sop_class_uid) { source_ = source; transfer_syntax_uid_ = transfer_syntax_uid; // STUDY patient_id_ = patient_id; patient_name_ = patient_name; study_uid_ = study_uid; study_desc_ = study_desc; // SERIES LEVEL series_uid_ = series_uid; series_desc_ = series_desc; // IMAGE LEVEL sop_instance_uid_ = sop_instance_uid; sop_class_uid_ = sop_class_uid; } }; //------------------------------------------------------------------------------ class ImageStore; class Dicom { public: enum QueryLevel {IMAGE, SERIES, STUDY}; const ImageStore* imagestore_; const AetMap* rhosts_; const std::string aet_; const std::string dicom_host_; const int dicom_port_; const int timeout_; const bool multi_; const bool need_response_; // FIXME: Maybe imagestore shall be only given to the movescp_execute explicit Dicom(int port, const std::string& aet, const ImageStore* imagestore, const AetMap* rhosts, bool multi, bool need_response) : imagestore_(imagestore), rhosts_(rhosts), aet_(aet), dicom_port_(port), timeout_(TIMEOUT), multi_(multi), need_response_(need_response) {}; explicit Dicom(const std::string& aet, const std::string& host, int port, bool need_response) : imagestore_(0), rhosts_(0), aet_(aet), dicom_host_(host), dicom_port_(port), timeout_(TIMEOUT), multi_(false), need_response_(need_response) {}; // Implementer must make sure all data is loaded into memory. // No leasy loading. static void load_image_file(const std::string& path, Image* image); virtual void init() = 0; virtual void waitfor_association() = 0; virtual void process_request() = 0; virtual void movescu_execute(const std::string& raet, const std::string& raddress, QueryLevel level, const std::string& study_uid, const std::string& series_uid, const std::string& instance_uid, const std::string& xfer, int message_id) = 0; virtual void cleanup() = 0; }; //------------------------------------------------------------------------------ #endif // APP_SRC_DICOM_H_
#include "PanelConsole.h" PanelConsole::PanelConsole(std::string name, bool active, std::vector<SDL_Scancode> shortcuts): Panel(name, active, shortcuts) { } PanelConsole::~PanelConsole() { output.clear(); } void PanelConsole::Log(const char * sentence) { output.appendf(sentence); } void PanelConsole::Draw() { ImGui::Begin(name.c_str()); ImGui::TextUnformatted(output.begin()); ImGui::End(); }
// SPDX-License-Identifier: LGPL-2.1 /* * Copyright (C) 2017 VMware Inc, Yordan Karadzhov <ykaradzhov@vmware.com> */ /** * @file KsUtils.cpp * @brief KernelShark Utils. */ // C #include <dlfcn.h> // KernelShark #include "libkshark-plugin.h" #include "libkshark-tepdata.h" #include "KsUtils.hpp" #include "KsPlugins.hpp" #include "KsWidgetsLib.hpp" namespace KsUtils { /** @brief Get a sorted vector of CPU Ids. */ QVector<int> getCPUList(int sd) { kshark_context *kshark_ctx(nullptr); kshark_data_stream *stream; if (!kshark_instance(&kshark_ctx)) return {}; stream = kshark_get_data_stream(kshark_ctx, sd); if (!stream) return {}; QVector<int> allCPUs = QVector<int>(stream->n_cpus); std::iota(allCPUs.begin(), allCPUs.end(), 0); return allCPUs; } /** * @brief Get a sorteg vector of Task's Pids. * * @param sd: Data stream identifier. */ QVector<int> getPidList(int sd) { kshark_context *kshark_ctx(nullptr); int nTasks, *tempPids; QVector<int> pids; if (!kshark_instance(&kshark_ctx)) return pids; nTasks = kshark_get_task_pids(kshark_ctx, sd, &tempPids); for (int r = 0; r < nTasks; ++r) { pids.append(tempPids[r]); } free(tempPids); return pids; } QVector<int> getEventIdList(int sd) { kshark_context *kshark_ctx(nullptr); kshark_data_stream *stream; int *ids; if (!kshark_instance(&kshark_ctx)) return {}; stream = kshark_get_data_stream(kshark_ctx, sd); if (!stream) return {}; ids = kshark_get_all_event_ids(stream); QVector<int> allEvts(stream->n_events); for (int i = 0; i < stream->n_events; ++i) allEvts[i] = ids[i]; return allEvts; } QVector<int> getStreamIdList() { kshark_context *kshark_ctx(nullptr); QVector<int> v; int *ids; if (!kshark_instance(&kshark_ctx)) return {}; ids = kshark_all_streams(kshark_ctx); v.resize(kshark_ctx->n_streams); for (int i = 0; i < kshark_ctx->n_streams; ++i) v[i] = ids[i]; free(ids); return v; } /** @brief Get a sorted vector of Id values of a filter. */ QVector<int> getFilterIds(kshark_hash_id *filter) { kshark_context *kshark_ctx(nullptr); int *cpuFilter, n; QVector<int> v; if (!kshark_instance(&kshark_ctx)) return v; cpuFilter = kshark_hash_ids(filter); n = filter->count; for (int i = 0; i < n; ++i) v.append(cpuFilter[i]); free(cpuFilter); return v; } /** * Set the bit of the filter mask of the kshark session context responsible * for the visibility of the events in the Table View. */ void listFilterSync(bool state) { kshark_context *kshark_ctx(nullptr); if (!kshark_instance(&kshark_ctx)) return; if (state) { kshark_ctx->filter_mask |= KS_TEXT_VIEW_FILTER_MASK; } else { kshark_ctx->filter_mask &= ~KS_TEXT_VIEW_FILTER_MASK; } } /** * Set the bit of the filter mask of the kshark session context responsible * for the visibility of the events in the Graph View. */ void graphFilterSync(bool state) { kshark_context *kshark_ctx(nullptr); if (!kshark_instance(&kshark_ctx)) return; if (state) { kshark_ctx->filter_mask |= KS_GRAPH_VIEW_FILTER_MASK; kshark_ctx->filter_mask |= KS_EVENT_VIEW_FILTER_MASK; } else { kshark_ctx->filter_mask &= ~KS_GRAPH_VIEW_FILTER_MASK; kshark_ctx->filter_mask &= ~KS_EVENT_VIEW_FILTER_MASK; } } /** * @brief Add a checkbox to a menu. * * @param menu: Input location for the menu object, to which the checkbox will be added. * @param name: The name of the checkbox. * * @returns The checkbox object; */ QCheckBox *addCheckBoxToMenu(QMenu *menu, QString name) { QWidget *containerWidget = new QWidget(menu); containerWidget->setLayout(new QHBoxLayout()); containerWidget->layout()->setContentsMargins(FONT_WIDTH, FONT_HEIGHT/5, FONT_WIDTH, FONT_HEIGHT/5); QCheckBox *checkBox = new QCheckBox(name, menu); containerWidget->layout()->addWidget(checkBox); QWidgetAction *action = new QWidgetAction(menu); action->setDefaultWidget(containerWidget); menu->addAction(action); return checkBox; } /** * @brief Simple CPU matching function to be user for data collections. * * @param kshark_ctx: Input location for the session context pointer. * @param e: kshark_entry to be checked. * @param sd: Data stream identifier. * @param cpu: Matching condition value. * * @returns True if the CPU of the entry matches the value of "cpu" and * the entry is visibility in Graph. Otherwise false. */ bool matchCPUVisible(struct kshark_context *kshark_ctx, struct kshark_entry *e, int sd, int *cpu) { return (e->cpu == *cpu && e->stream_id == sd && (e->visible & KS_GRAPH_VIEW_FILTER_MASK)); } /** * @brief Get an elided version of the string that will fit within a label. * * @param label: Pointer to the label object. * @param text: The text to be elided. * @param mode: Parameter specifies whether the text is elided on the left, * in the middle, or on the right. * @param labelWidth: The desired width of the label. */ void setElidedText(QLabel* label, QString text, enum Qt::TextElideMode mode, int labelWidth) { QFontMetrics metrix(label->font()); QString elidedText; int textWidth; textWidth = labelWidth - FONT_WIDTH * 3; elidedText = metrix.elidedText(text, Qt::ElideRight, textWidth); while(labelWidth < STRING_WIDTH(elidedText) + FONT_WIDTH * 5) { textWidth -= FONT_WIDTH * 3; elidedText = metrix.elidedText(text, mode, textWidth); } label->setText(elidedText); } /** * @brief Check if the application runs from its installation location. */ bool isInstalled() { QString appPath = QCoreApplication::applicationDirPath(); QString installPath(_INSTALL_PREFIX); installPath += "/bin"; installPath = QDir::cleanPath(installPath); return appPath == installPath; } static QString getFileDialog(QWidget *parent, const QString &windowName, const QString &filter, QString &lastFilePath, bool forSave) { QString fileName; if (lastFilePath.isEmpty()) { lastFilePath = isInstalled() ? QDir::homePath() : QDir::currentPath(); } if (forSave) { fileName = QFileDialog::getSaveFileName(parent, windowName, lastFilePath, filter); } else { fileName = QFileDialog::getOpenFileName(parent, windowName, lastFilePath, filter); } if (!fileName.isEmpty()) lastFilePath = QFileInfo(fileName).path(); return fileName; } static QStringList getFilesDialog(QWidget *parent, const QString &windowName, const QString &filter, QString &lastFilePath) { QStringList fileNames; if (lastFilePath.isEmpty()) { lastFilePath = isInstalled() ? QDir::homePath() : QDir::currentPath(); } fileNames = QFileDialog::getOpenFileNames(parent, windowName, lastFilePath, filter); if (!fileNames.isEmpty()) lastFilePath = QFileInfo(fileNames[0]).path(); return fileNames; } /** * @brief Open a standard Qt getFileName dialog and return the name of the * selected file. Only one file can be selected. */ QString getFile(QWidget *parent, const QString &windowName, const QString &filter, QString &lastFilePath) { return getFileDialog(parent, windowName, filter, lastFilePath, false); } /** * @brief Open a standard Qt getFileName dialog and return the names of the * selected files. Multiple files can be selected. */ QStringList getFiles(QWidget *parent, const QString &windowName, const QString &filter, QString &lastFilePath) { return getFilesDialog(parent, windowName, filter, lastFilePath); } /** * @brief Open a standard Qt getFileName dialog and return the name of the * selected file. Only one file can be selected. */ QString getSaveFile(QWidget *parent, const QString &windowName, const QString &filter, const QString &extension, QString &lastFilePath) { QString fileName = getFileDialog(parent, windowName, filter, lastFilePath, true); if (!fileName.isEmpty() && !fileName.endsWith(extension)) { fileName += extension; if (QFileInfo(fileName).exists()) { if (!KsWidgetsLib::fileExistsDialog(fileName)) fileName.clear(); } } return fileName; } /** * Separate the command line arguments inside the string taking into account * possible shell quoting and new lines. */ QStringList splitArguments(QString cmd) { QString::SplitBehavior opt = QString::SkipEmptyParts; int i, progress = 0, size; QStringList argv; QChar quote = 0; /* Remove all new lines. */ cmd.replace("\\\n", " "); size = cmd.count(); auto lamMid = [&] () {return cmd.mid(progress, i - progress);}; for (i = 0; i < size; ++i) { if (cmd[i] == '\\') { cmd.remove(i, 1); size --; continue; } if (cmd[i] == '\'' || cmd[i] == '"') { if (quote.isNull()) { argv << lamMid().split(" ", opt); quote = cmd[i++]; progress = i; } else if (quote == cmd[i]) { argv << lamMid(); quote = 0; progress = ++i; } } } argv << cmd.right(size - progress).split(" ", opt); return argv; } /** * @brief Split the ststem name from the actual name of the event itself. * * @param stream: Input location for a Trace data stream pointer. * @param eventId: Identifier of the Event. */ QStringList getTepEvtName(int sd, int eventId) { QString name(kshark_event_from_id(sd, eventId)); return name.split('/'); } /** * @brief Get a string to be used as a standard name of a task graph. * * @param sd: Graph's Data stream identifier. * @param pid: Graph's progress Id. */ QString taskPlotName(int sd, int pid) { kshark_context *kshark_ctx(nullptr); kshark_data_stream *stream; QString name; if (!kshark_instance(&kshark_ctx)) return {}; stream = kshark_get_data_stream(kshark_ctx, sd); if (!stream) return {}; name = kshark_comm_from_pid(sd, pid); name += "-"; name += QString("%1").arg(pid); return name; } QString streamDescription(kshark_data_stream *stream) { QString descr(stream->file); QString buffName(stream->name); if (!buffName.isEmpty() && buffName != "top") { descr += ":"; descr += stream->name; } return descr; } }; // KsUtils /** A stream operator for converting QColor into KsPlot::Color. */ KsPlot::Color& operator <<(KsPlot::Color &thisColor, const QColor &c) { thisColor.set(c.red(), c.green(), c.blue()); return thisColor; } /** A stream operator for converting KsPlot::Color into QColor. */ QColor& operator <<(QColor &thisColor, const KsPlot::Color &c) { thisColor.setRgb(c.r(), c.g(), c.b()); return thisColor; } /** Create a default (empty) KsDataStore. */ KsDataStore::KsDataStore(QWidget *parent) : QObject(parent), _rows(nullptr), _dataSize(0) {} /** Destroy the KsDataStore object. */ KsDataStore::~KsDataStore() {} int KsDataStore::_openDataFile(kshark_context *kshark_ctx, const QString &file) { int sd = kshark_open(kshark_ctx, file.toStdString().c_str()); if (sd < 0) { qCritical() << "ERROR:" << sd << "while loading file " << file; return sd; } if (kshark_ctx->stream[sd]->format == KS_TEP_DATA) { kshark_tep_init_all_buffers(kshark_ctx, sd); for (int i = 0; i < kshark_ctx->n_streams; ++i) kshark_tep_handle_plugins(kshark_ctx, i); } return sd; } void KsDataStore::_addPluginsToStream(kshark_context *kshark_ctx, int sd, QVector<kshark_dpi *> plugins) { kshark_data_stream *stream; stream = kshark_get_data_stream(kshark_ctx, sd); if (!stream) return; for (auto const &p: plugins) { struct kshark_dpi_list *plugin; plugin = kshark_register_plugin_to_stream(stream, p, true); kshark_handle_dpi(stream, plugin, KSHARK_PLUGIN_INIT); } } /** Load trace data for file. */ int KsDataStore::loadDataFile(const QString &file, QVector<kshark_dpi *> plugins) { kshark_context *kshark_ctx(nullptr); int sd, n_streams; if (!kshark_instance(&kshark_ctx)) return -EFAULT; clear(); unregisterCPUCollections(); kshark_close_all(kshark_ctx); sd = _openDataFile(kshark_ctx, file); if (sd != 0) return sd; /* * The file may contain multiple buffers so we can have multiple * streams loaded. */ n_streams = kshark_ctx->n_streams; for (sd = 0; sd < n_streams; ++sd) _addPluginsToStream(kshark_ctx, sd, plugins); _dataSize = kshark_load_all_entries(kshark_ctx, &_rows); if (_dataSize <= 0) { kshark_close(kshark_ctx, sd); return _dataSize; } registerCPUCollections(); return sd; } /** * @brief Append a trace data file to the data-set that is already loaded. * The clock of the new data will be calibrated in order to be * compatible with the clock of the prior data. * * @param file: Trace data file, to be append to the already loaded data. * @param offset: The offset in time of the Data stream to be appended. */ int KsDataStore::appendDataFile(const QString &file, int64_t offset) { kshark_context *kshark_ctx(nullptr); struct kshark_entry **mergedRows; ssize_t nLoaded = _dataSize; int i, sd; if (!kshark_instance(&kshark_ctx)) return -EFAULT; unregisterCPUCollections(); sd = _openDataFile(kshark_ctx, file); for (i = sd; i < kshark_ctx->n_streams; ++i) { kshark_ctx->stream[sd]->calib = kshark_offset_calib; kshark_ctx->stream[sd]->calib_array = (int64_t *) calloc(1, sizeof(int64_t)); kshark_ctx->stream[sd]->calib_array[0] = offset; kshark_ctx->stream[sd]->calib_array_size = 1; } _dataSize = kshark_append_all_entries(kshark_ctx, _rows, nLoaded, sd, &mergedRows); if (_dataSize <= 0 || _dataSize == nLoaded) { QErrorMessage *em = new QErrorMessage(); em->showMessage(QString("File %1 contains no data.").arg(file)); em->exec(); for (i = sd; i < kshark_ctx->n_streams; ++i) kshark_close(kshark_ctx, i); return _dataSize; } _rows = mergedRows; registerCPUCollections(); return sd; } void KsDataStore::_freeData() { if (_dataSize > 0) { for (ssize_t r = 0; r < _dataSize; ++r) free(_rows[r]); free(_rows); _rows = nullptr; } _dataSize = 0; } /** Reload the trace data. */ void KsDataStore::reload() { kshark_context *kshark_ctx(nullptr); if (!kshark_instance(&kshark_ctx)) return; _freeData(); if (kshark_ctx->n_streams == 0) return; unregisterCPUCollections(); _dataSize = kshark_load_all_entries(kshark_ctx, &_rows); registerCPUCollections(); emit updateWidgets(this); } /** Free the loaded trace data and close the file. */ void KsDataStore::clear() { kshark_context *kshark_ctx(nullptr); if (!kshark_instance(&kshark_ctx)) return; _freeData(); unregisterCPUCollections(); } /** Update the visibility of the entries (filter). */ void KsDataStore::update() { kshark_context *kshark_ctx(nullptr); if (!kshark_instance(&kshark_ctx)) return; unregisterCPUCollections(); kshark_filter_all_entries(kshark_ctx, _rows, _dataSize); registerCPUCollections(); emit updateWidgets(this); } /** Register a collection of visible entries for each CPU. */ void KsDataStore::registerCPUCollections() { kshark_context *kshark_ctx(nullptr); int *streamIds, nCPUs, sd; if (!kshark_instance(&kshark_ctx)) return; streamIds = kshark_all_streams(kshark_ctx); for (int i = 0; i < kshark_ctx->n_streams; ++i) { sd = streamIds[i]; nCPUs = kshark_ctx->stream[sd]->n_cpus; for (int cpu = 0; cpu < nCPUs; ++cpu) { kshark_register_data_collection(kshark_ctx, _rows, _dataSize, KsUtils::matchCPUVisible, sd, &cpu, 1, 0); } } free(streamIds); } /** Unregister all CPU collections. */ void KsDataStore::unregisterCPUCollections() { kshark_context *kshark_ctx(nullptr); int *streamIds, nCPUs, sd; if (!kshark_instance(&kshark_ctx)) return; streamIds = kshark_all_streams(kshark_ctx); for (int i = 0; i < kshark_ctx->n_streams; ++i) { sd = streamIds[i]; nCPUs = kshark_ctx->stream[sd]->n_cpus; for (int cpu = 0; cpu < nCPUs; ++cpu) { kshark_unregister_data_collection(&kshark_ctx->collections, KsUtils::matchCPUVisible, sd, &cpu, 1); } } free(streamIds); } void KsDataStore::_applyIdFilter(int filterId, QVector<int> vec, int sd) { kshark_context *kshark_ctx(nullptr); kshark_data_stream *stream; if (!kshark_instance(&kshark_ctx)) return; stream = kshark_get_data_stream(kshark_ctx, sd); if (!stream) return; switch (filterId) { case KS_SHOW_EVENT_FILTER: case KS_HIDE_EVENT_FILTER: kshark_filter_clear(kshark_ctx, sd, KS_SHOW_EVENT_FILTER); kshark_filter_clear(kshark_ctx, sd, KS_HIDE_EVENT_FILTER); break; case KS_SHOW_TASK_FILTER: case KS_HIDE_TASK_FILTER: kshark_filter_clear(kshark_ctx, sd, KS_SHOW_TASK_FILTER); kshark_filter_clear(kshark_ctx, sd, KS_HIDE_TASK_FILTER); break; case KS_SHOW_CPU_FILTER: case KS_HIDE_CPU_FILTER: kshark_filter_clear(kshark_ctx, sd, KS_SHOW_CPU_FILTER); kshark_filter_clear(kshark_ctx, sd, KS_HIDE_CPU_FILTER); break; default: return; } for (auto &&val: vec) kshark_filter_add_id(kshark_ctx, sd, filterId, val); if (!kshark_ctx->n_streams) return; unregisterCPUCollections(); /* * If the advanced event filter is set the data has to be reloaded, * because the advanced filter uses tep_records. */ if (stream->format == KS_TEP_DATA && kshark_tep_filter_is_set(stream)) reload(); else kshark_filter_stream_entries(kshark_ctx, sd, _rows, _dataSize); registerCPUCollections(); emit updateWidgets(this); } /** Apply Show Task filter. */ void KsDataStore::applyPosTaskFilter(int sd, QVector<int> vec) { kshark_context *kshark_ctx(nullptr); int nTasks, *pids; if (!kshark_instance(&kshark_ctx)) return; nTasks = kshark_get_task_pids(kshark_ctx, sd, &pids); free(pids); if (vec.count() == nTasks) return; _applyIdFilter(KS_SHOW_TASK_FILTER, vec, sd); } /** Apply Hide Task filter. */ void KsDataStore::applyNegTaskFilter(int sd, QVector<int> vec) { if (!vec.count()) return; _applyIdFilter(KS_HIDE_TASK_FILTER, vec, sd); } /** Apply Show Event filter. */ void KsDataStore::applyPosEventFilter(int sd, QVector<int> vec) { _applyIdFilter(KS_SHOW_EVENT_FILTER, vec, sd); } /** Apply Hide Event filter. */ void KsDataStore::applyNegEventFilter(int sd, QVector<int> vec) { if (!vec.count()) return; _applyIdFilter(KS_HIDE_EVENT_FILTER, vec, sd); } /** Apply Show CPU filter. */ void KsDataStore::applyPosCPUFilter(int sd, QVector<int> vec) { kshark_context *kshark_ctx(nullptr); kshark_data_stream *stream; if (!kshark_instance(&kshark_ctx)) return; stream = kshark_get_data_stream(kshark_ctx, sd); if (!stream) return; if (vec.count() == stream->n_cpus) return; _applyIdFilter(KS_SHOW_CPU_FILTER, vec, sd); } /** Apply Hide CPU filter. */ void KsDataStore::applyNegCPUFilter(int sd, QVector<int> vec) { if (!vec.count()) return; _applyIdFilter(KS_HIDE_CPU_FILTER, vec, sd); } /** Disable all filters. */ void KsDataStore::clearAllFilters() { kshark_context *kshark_ctx(nullptr); int *streamIds, sd; if (!kshark_instance(&kshark_ctx) || !kshark_ctx->n_streams) return; unregisterCPUCollections(); streamIds = kshark_all_streams(kshark_ctx); for (int i = 0; i < kshark_ctx->n_streams; ++i) { sd = streamIds[i]; kshark_filter_clear(kshark_ctx, sd, KS_SHOW_TASK_FILTER); kshark_filter_clear(kshark_ctx, sd, KS_HIDE_TASK_FILTER); kshark_filter_clear(kshark_ctx, sd, KS_SHOW_EVENT_FILTER); kshark_filter_clear(kshark_ctx, sd, KS_HIDE_EVENT_FILTER); kshark_filter_clear(kshark_ctx, sd, KS_SHOW_CPU_FILTER); kshark_filter_clear(kshark_ctx, sd, KS_HIDE_CPU_FILTER); if (kshark_ctx->stream[sd]->format == KS_TEP_DATA) kshark_tep_filter_reset(kshark_ctx->stream[sd]); } kshark_clear_all_filters(kshark_ctx, _rows, _dataSize); free(streamIds); emit updateWidgets(this); } /** * @brief Apply constant offset to the timestamps of all entries from a given * Data stream. * * @param sd: Data stream identifier. * @param offset: The constant offset to be added (in nanosecond). */ void KsDataStore::setClockOffset(int sd, int64_t offset) { kshark_context *kshark_ctx(nullptr); if (!kshark_instance(&kshark_ctx)) return; if (!kshark_get_data_stream(kshark_ctx, sd)) return; unregisterCPUCollections(); kshark_set_clock_offset(kshark_ctx, _rows, _dataSize, sd, offset); registerCPUCollections(); } /** * @brief Create Plugin Manager. Use list of plugins declared in the * CMake-generated header file. */ KsPluginManager::KsPluginManager(QWidget *parent) : QObject(parent) { _loadPluginList(KsUtils::getPluginList()); } QVector<kshark_plugin_list *> KsPluginManager::_loadPluginList(const QStringList &plugins) { kshark_context *kshark_ctx(nullptr); QVector<kshark_plugin_list *> vec; kshark_plugin_list *plugin; std::string name, lib; int nPlugins; if (!kshark_instance(&kshark_ctx)) return vec; nPlugins = plugins.count(); for (int i = 0; i < nPlugins; ++i) { if (plugins[i].endsWith(".so")) { lib = plugins[i].toStdString(); name = _pluginNameFromLib(plugins[i]); } else { lib = _pluginLibFromName(plugins[i]); name = plugins[i].toStdString(); } plugin = kshark_find_plugin(kshark_ctx->plugins, lib.c_str()); if (!plugin) { plugin = kshark_register_plugin(kshark_ctx, name.c_str(), lib.c_str()); if (plugin) vec.append(plugin); } } return vec; } QStringList KsPluginManager::getPluginList() const { kshark_context *kshark_ctx(nullptr); kshark_plugin_list *plugin; QStringList list; if (!kshark_instance(&kshark_ctx)) return {}; plugin = kshark_ctx->plugins; while (plugin) { list.append(plugin->file); plugin = plugin->next; } return list; } QStringList KsPluginManager::getStreamPluginList(int sd) const { kshark_context *kshark_ctx(nullptr); kshark_data_stream *stream; kshark_dpi_list *plugin; QStringList list; if (!kshark_instance(&kshark_ctx)) return {}; stream = kshark_get_data_stream(kshark_ctx, sd); if (!stream) return {}; plugin = stream->plugins; while (plugin) { list.append(plugin->interface->name); plugin = plugin->next; } return list; } QVector<int> KsPluginManager::getActivePlugins(int sd) const { kshark_context *kshark_ctx(nullptr); kshark_data_stream *stream; kshark_dpi_list *plugin; QVector<int> vec; int i(0); if (!kshark_instance(&kshark_ctx)) return {}; stream = kshark_get_data_stream(kshark_ctx, sd); if (!stream) return {}; plugin = stream->plugins; while (plugin) { vec.append(plugin->status & KSHARK_PLUGIN_ENABLED); plugin = plugin->next; i++; } return vec; } QVector<int> KsPluginManager::getPluginsByStatus(int sd, int status) const { kshark_context *kshark_ctx(nullptr); kshark_data_stream *stream; kshark_dpi_list *plugin; QVector<int> vec; int i(0); if (!kshark_instance(&kshark_ctx)) return {}; stream = kshark_get_data_stream(kshark_ctx, sd); if (!stream) return {}; plugin = stream->plugins; while (plugin) { if (plugin->status & status) vec.append(i); plugin = plugin->next; i++; } return vec; } void KsPluginManager::registerPluginMenues() { kshark_context *kshark_ctx(nullptr); kshark_plugin_list *plugin; if (!kshark_instance(&kshark_ctx)) return; for (plugin = kshark_ctx->plugins; plugin; plugin = plugin->next) if (plugin->handle && plugin->ctrl_interface) { void *dialogPtr = plugin->ctrl_interface(parent()); if (dialogPtr) { QWidget *dialog = static_cast<QWidget *>(dialogPtr); _pluginDialogs.append(dialog); } } } std::string KsPluginManager::_pluginLibFromName(const QString &plugin) { QString appPath = QCoreApplication::applicationDirPath(); QString libPath = appPath + "/../lib"; std::string lib; auto lamFileName = [&] () { return std::string("/plugin-" + plugin.toStdString() + ".so"); }; libPath = QDir::cleanPath(libPath); if (!KsUtils::isInstalled() && QDir(libPath).exists()) lib = libPath.toStdString() + lamFileName(); else lib = std::string(KS_PLUGIN_INSTALL_PREFIX) + lamFileName(); return lib; } std::string KsPluginManager::_pluginNameFromLib(const QString &plugin) { QString name = plugin.section('/', -1); name.remove("plugin-"); name.remove(".so"); return name.toStdString(); } /** * @brief Register a Plugin. * * @param plugin: Provide here the name of the plugin (as in the CMake-generated * header file) or a name of the plugin's library file (.so * including path). */ void KsPluginManager::registerPlugins(const QString &pluginNames) { _userPlugins.append(_loadPluginList(pluginNames.split(' '))); } void KsPluginManager::_pluginToStream(const QString &pluginName, QVector<int> streamId, bool reg) { kshark_context *kshark_ctx(nullptr); kshark_plugin_list *plugin; kshark_data_stream *stream; if (!kshark_instance(&kshark_ctx)) return; plugin = kshark_find_plugin_by_name(kshark_ctx->plugins, pluginName.toStdString().c_str()); if (!plugin || !plugin->process_interface) return; for (auto const &sd: streamId) { stream = kshark_get_data_stream(kshark_ctx, sd); if (reg) kshark_register_plugin_to_stream(stream, plugin->process_interface, true); else kshark_unregister_plugin_from_stream(stream, plugin->process_interface); kshark_handle_all_dpis(stream, KSHARK_PLUGIN_UPDATE); } emit dataReload(); } void KsPluginManager::registerPluginToStream(const QString &pluginName, QVector<int> streamId) { _pluginToStream(pluginName, streamId, true); } void KsPluginManager::unregisterPluginFromStream(const QString &pluginName, QVector<int> streamId) { _pluginToStream(pluginName, streamId, false); } /** * @brief Unregister a list pf plugins. * * @param pluginNames: Provide here a space separated list of plugin names (as * in the CMake-generated header file). */ void KsPluginManager::unregisterPlugins(const QString &pluginNames) { kshark_context *kshark_ctx(nullptr); kshark_plugin_list *plugin; kshark_data_stream *stream; int *streamArray; if (!kshark_instance(&kshark_ctx)) return; for (auto const &name: pluginNames.split(' ')) { plugin = kshark_find_plugin_by_name(kshark_ctx->plugins, name.toStdString().c_str()); streamArray = kshark_all_streams(kshark_ctx); for (int i = 0; i < kshark_ctx->n_streams; ++i) { stream = kshark_get_data_stream(kshark_ctx, streamArray[i]); kshark_unregister_plugin_from_stream(stream, plugin->process_interface); } kshark_unregister_plugin(kshark_ctx, name.toStdString().c_str(), plugin->file); } } /** @brief Add to the list and initialize user-provided plugins. All other * previously loaded plugins will be reinitialized and the data will be * reloaded. * * @param fileNames: the library files (.so) of the plugins. */ void KsPluginManager::addPlugins(const QStringList &fileNames, QVector<int> streamIds) { QVector<kshark_plugin_list *> plugins; kshark_context *kshark_ctx(nullptr); kshark_data_stream *stream; if (!kshark_instance(&kshark_ctx)) return; plugins = _loadPluginList(fileNames); _userPlugins.append(plugins); if (streamIds.isEmpty()) { int *streamArray; streamIds.resize(kshark_ctx->n_streams); streamArray = kshark_all_streams(kshark_ctx); for (int i = 0; i < kshark_ctx->n_streams; ++i) streamIds[i] = streamArray[i]; free(streamArray); } for (int i = 0; i < streamIds.count(); ++i) { stream = kshark_get_data_stream(kshark_ctx, streamIds[i]); for (auto const &p: plugins) { if (p->process_interface) kshark_register_plugin_to_stream(stream, p->process_interface, true); } kshark_handle_all_dpis(stream, KSHARK_PLUGIN_UPDATE); } } /** @brief Update (change) the plugins for a given Data stream. * * @param sd: Data stream identifier. * @param pluginStates: A vector of plugin's states (0 or 1) telling which * plugins to be loaded. */ void KsPluginManager::updatePlugins(int sd, QVector<int> pluginStates) { kshark_context *kshark_ctx(nullptr); kshark_data_stream *stream; kshark_dpi_list *plugin; QVector<int> vec; int i(0); if (!kshark_instance(&kshark_ctx)) return; stream = kshark_get_data_stream(kshark_ctx, sd); if (!stream) return; plugin = stream->plugins; while (plugin) { if (pluginStates[i++]) plugin->status |= KSHARK_PLUGIN_ENABLED; else plugin->status &= ~KSHARK_PLUGIN_ENABLED; plugin = plugin->next; } kshark_handle_all_dpis(stream, KSHARK_PLUGIN_UPDATE); } /** * @brief Destroy all Plugin dialogs. */ void KsPluginManager::deletePluginDialogs() { /** Delete all register plugin dialogs. */ for (auto &pd: _pluginDialogs) delete pd; }
#include <bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--) { int x, y; cin>>x>>y; if(x<y) cout<<"No Number"<<endl; else if(x%2==0 && y%2==0 && (x==y || x-2==y)) cout<<x+y<<endl; else if(x%2!=0 && y%2!=0 && (x==y || x-2==y)) cout<<x+y-1<<endl; else cout<<"No Number"<<endl; } }
#include <iostream> using namespace std; int main() { int str[3], i, max, min; for (i = 0; i < 3; i++) { cin >> str[i]; } max = min = str[0]; for (i = 0; i < 3; i++) { if(str[i] > max) max = str[i]; if (str[i] < min) min = str[i]; } cout << max << ' ' << min << endl; }
/* #include <iostream> //#include <scriptstdstring/scriptstdstring.h> #include "as/ScriptContext.hpp" #include "as/ScriptEngine.hpp" #include "as/ScriptModule.hpp" namespace { int add( int a, int b ) { return a + b; } void mult( int a, int b, int& out ) { out = a * b; } struct MyClass { float f; double d; MyClass() : f( 1.f ), d( 2.D ) { } void print() const { std::cout << "MyClass " << this << ": f=" << f << " d=" << d << std::endl; } }; void printSum( const MyClass* mc ) { std::cout << "MyClass " << mc << ": f+d=" << mc->f + mc->d << std::endl; } void doStuff( MyClass& a, float b, double c ) { a.f += b; a.d += c; } void print( const std::string& str ) { std::cout << str; } void messageCallback( as::Message& message ) { std::cout << '['; switch ( message.getType() ) { case as::Message::Info: std::cout << "INFO"; break; case as::Message::Warning: std::cout << "WARNING"; break; case as::Message::Error: std::cout << "ERROR"; break; } std::cout << "] "; std::cout << message.getSection() << ':' << message.getRow() << ':' << message.getColumn() << ' '; std::cout << message.getMessage() << std::endl; } sf::Int32 i = 0; sf::Int64 l = 0; } namespace as { template<> class TypeGetter< std::string > { public: static std::string getType() { return "string"; } }; template<> class TypeGetter< MyClass > { public: static std::string getType() { return "MyClass"; } }; } int main_as() { try { std::cout << "Starting..." << std::endl; as::ScriptEngine engine; engine.setMessageCallback( std::bind( &messageCallback, std::placeholders::_1 ) ); using std::cout; //RegisterStdString( engine.getRaw() ); //RegisterStdStringUtils( engine.getRaw() ); engine.registerClassValueType< MyClass >( "MyClass" ); engine.registerClassProperty< decltype( &MyClass::f ), &MyClass::f >( "f" ); engine.registerClassProperty< decltype( &MyClass::d ), &MyClass::d >( "d" ); //engine.registerClassFunction< decltype( &MyClass::print ), &MyClass::print >( "print" ); //engine.registerClassFunction( &printSum, "printSum" ); engine.registerGlobalFunction( add, "add" ); engine.registerGlobalFunction( mult, "multiply" ); engine.registerGlobalFunction( doStuff, "doStuff" ); //engine.registerGlobalFunction( print, "print" ); engine.registerGlobalProperty( i, "i" ); engine.registerGlobalProperty( l, "l" ); std::cout << "Making module..." << std::endl; as::ScriptModule& module = ( * engine.createModule( "test" ) ); module.define( "KITTY" ); module.addSectionFromFile( "test.angelscript" ); module.build(); std::cout << "Printing metadata..." << std::endl; auto data = module.getAllTypeMetadata(); for ( auto it = data.begin(); it != data.end(); ++it ) { if ( it->second == "" ) { continue; } std::cout << it->first << ": [" << it->second << "]" << std::endl; } std::cout << "Running..." << std::endl; auto oldI = i; auto oldL = l; { as::ScriptContext& context = ( * engine.createContext() ); auto func = module.getFunction< void >( "main" ); func( context ); } std::cout << "i is now " << i << ", but it was " << oldI << std::endl; std::cout << "l is now " << l << ", but it was " << oldL << std::endl; } catch ( std::exception& exception ) { std::cout << "Exception: " << exception.what() << std::endl; } return 0; } int main() { return main_as(); } //*/
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #include "nanodet.h" #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include "cpu.h" static inline float intersection_area(const Object &a, const Object &b) { cv::Rect_<float> inter = a.rect & b.rect; return inter.area(); } static void qsort_descent_inplace(std::vector<Object> &faceobjects, int left, int right) { int i = left; int j = right; float p = faceobjects[(left + right) / 2].prob; while (i <= j) { while (faceobjects[i].prob > p) i++; while (faceobjects[j].prob < p) j--; if (i <= j) { // swap std::swap(faceobjects[i], faceobjects[j]); i++; j--; } } // #pragma omp parallel sections { // #pragma omp section { if (left < j) qsort_descent_inplace(faceobjects, left, j); } // #pragma omp section { if (i < right) qsort_descent_inplace(faceobjects, i, right); } } } static void qsort_descent_inplace(std::vector<Object> &faceobjects) { if (faceobjects.empty()) return; qsort_descent_inplace(faceobjects, 0, faceobjects.size() - 1); } static void nms_sorted_bboxes(const std::vector<Object> &faceobjects, std::vector<int> &picked, float nms_threshold) { picked.clear(); const int n = faceobjects.size(); std::vector<float> areas(n); for (int i = 0; i < n; i++) { areas[i] = faceobjects[i].rect.width * faceobjects[i].rect.height; } for (int i = 0; i < n; i++) { const Object &a = faceobjects[i]; int keep = 1; for (int j = 0; j < (int) picked.size(); j++) { const Object &b = faceobjects[picked[j]]; // intersection over union float inter_area = intersection_area(a, b); float union_area = areas[i] + areas[picked[j]] - inter_area; // float IoU = inter_area / union_area if (inter_area / union_area > nms_threshold) keep = 0; } if (keep) picked.push_back(i); } } static void generate_proposals(const ncnn::Mat &cls_pred, const ncnn::Mat &dis_pred, int stride, const ncnn::Mat &in_pad, float prob_threshold, std::vector<Object> &objects) { const int num_grid = cls_pred.h; int num_grid_x; int num_grid_y; if (in_pad.w > in_pad.h) { num_grid_x = in_pad.w / stride; num_grid_y = num_grid / num_grid_x; } else { num_grid_y = in_pad.h / stride; num_grid_x = num_grid / num_grid_y; } const int num_class = cls_pred.w; const int reg_max_1 = dis_pred.w / 4; //__android_log_print(ANDROID_LOG_WARN, "ncnn","cls_pred h %d, w %d",cls_pred.h,cls_pred.w); //__android_log_print(ANDROID_LOG_WARN, "ncnn","%d,%d,%d,%d",num_grid_x,num_grid_y,num_class,reg_max_1); for (int i = 0; i < num_grid_y; i++) { for (int j = 0; j < num_grid_x; j++) { const int idx = i * num_grid_x + j; const float *scores = cls_pred.row(idx); // find label with max score int label = -1; float score = -FLT_MAX; for (int k = 0; k < num_class; k++) { if (scores[k] > score) { label = k; score = scores[k]; } } if (score >= prob_threshold) { ncnn::Mat bbox_pred(reg_max_1, 4, (void *) dis_pred.row(idx)); { ncnn::Layer *softmax = ncnn::create_layer("Softmax"); ncnn::ParamDict pd; pd.set(0, 1); // axis pd.set(1, 1); softmax->load_param(pd); ncnn::Option opt; opt.num_threads = 1; opt.use_packing_layout = false; softmax->create_pipeline(opt); softmax->forward_inplace(bbox_pred, opt); softmax->destroy_pipeline(opt); delete softmax; } float pred_ltrb[4]; for (int k = 0; k < 4; k++) { float dis = 0.f; const float *dis_after_sm = bbox_pred.row(k); for (int l = 0; l < reg_max_1; l++) { dis += l * dis_after_sm[l]; } pred_ltrb[k] = dis * stride; } float pb_cx = (j + 0.5f) * stride; float pb_cy = (i + 0.5f) * stride; float x0 = pb_cx - pred_ltrb[0]; float y0 = pb_cy - pred_ltrb[1]; float x1 = pb_cx + pred_ltrb[2]; float y1 = pb_cy + pred_ltrb[3]; Object obj; obj.rect.x = x0; obj.rect.y = y0; obj.rect.width = x1 - x0; obj.rect.height = y1 - y0; obj.label = label; obj.prob = score; objects.push_back(obj); } } } } NanoDet::NanoDet() { blob_pool_allocator.set_size_compare_ratio(0.f); workspace_pool_allocator.set_size_compare_ratio(0.f); } int NanoDet::load(const char *modeltype, int _target_size, const float *_mean_vals, const float *_norm_vals, bool use_gpu) { nanodetFace.clear(); nanodetLandmask.clear(); blob_pool_allocator.clear(); workspace_pool_allocator.clear(); ncnn::set_cpu_powersave(2); ncnn::set_omp_num_threads(ncnn::get_big_cpu_count()); nanodetFace.opt = ncnn::Option(); nanodetLandmask.opt = ncnn::Option(); #if NCNN_VULKAN nanodetFace.opt.use_vulkan_compute = use_gpu; nanodetLandmask.opt.use_vulkan_compute = use_gpu; #endif nanodetFace.opt.num_threads = ncnn::get_big_cpu_count(); nanodetFace.opt.blob_allocator = &blob_pool_allocator; nanodetFace.opt.workspace_allocator = &workspace_pool_allocator; nanodetLandmask.opt.num_threads = ncnn::get_big_cpu_count(); nanodetLandmask.opt.blob_allocator = &blob_pool_allocator; nanodetLandmask.opt.workspace_allocator = &workspace_pool_allocator; char parampath[256]; char modelpath[256]; sprintf(parampath, "nanodet-%s.param", modeltype); sprintf(modelpath, "nanodet-%s.bin", modeltype); nanodetFace.load_param("nanodet_m_face.param"); nanodetFace.load_model("nanodet_m_face.bin"); nanodetLandmask.load_param(parampath); nanodetLandmask.load_model(modelpath); target_size = _target_size; mean_vals[0] = _mean_vals[0]; mean_vals[1] = _mean_vals[1]; mean_vals[2] = _mean_vals[2]; norm_vals[0] = _norm_vals[0]; norm_vals[1] = _norm_vals[1]; norm_vals[2] = _norm_vals[2]; return 0; } int NanoDet::load(AAssetManager *mgr, const char *modeltype, int _target_size, const float *_mean_vals, const float *_norm_vals, bool use_gpu) { __android_log_print(ANDROID_LOG_WARN, "ncnn", "load %s", modeltype); nanodetFace.clear(); nanodetLandmask.clear(); blob_pool_allocator.clear(); workspace_pool_allocator.clear(); ncnn::set_cpu_powersave(2); ncnn::set_omp_num_threads(ncnn::get_big_cpu_count()); nanodetFace.opt = ncnn::Option(); nanodetLandmask.opt = ncnn::Option(); #if NCNN_VULKAN nanodetFace.opt.use_vulkan_compute = use_gpu; nanodetLandmask.opt.use_vulkan_compute = use_gpu; #endif nanodetFace.opt.num_threads = ncnn::get_big_cpu_count(); nanodetFace.opt.blob_allocator = &blob_pool_allocator; nanodetFace.opt.workspace_allocator = &workspace_pool_allocator; nanodetLandmask.opt.num_threads = ncnn::get_big_cpu_count(); nanodetLandmask.opt.blob_allocator = &blob_pool_allocator; nanodetLandmask.opt.workspace_allocator = &workspace_pool_allocator; char parampath[256]; char modelpath[256]; sprintf(parampath, "pfld-%s.param", modeltype); sprintf(modelpath, "pfld-%s.bin", modeltype); //__android_log_print(ANDROID_LOG_WARN, "ncnn", "load %s,%s", parampath,modelpath); nanodetFace.load_param("nanodet_m_face.param"); nanodetFace.load_model("nanodet_m_face.bin"); nanodetLandmask.load_param(mgr, parampath); nanodetLandmask.load_model(mgr, modelpath); target_size = _target_size; mean_vals[0] = _mean_vals[0]; mean_vals[1] = _mean_vals[1]; mean_vals[2] = _mean_vals[2]; norm_vals[0] = _norm_vals[0]; norm_vals[1] = _norm_vals[1]; norm_vals[2] = _norm_vals[2]; return 0; } int NanoDet::detectFace(ncnn::Net &nanodet_face, const cv::Mat &rgb, std::vector<Object> &objects, float target_size, float prob_threshold, float nms_threshold) { int width = rgb.cols; int height = rgb.rows; // pad to multiple of 32 int w = width; int h = height; float scale = 1.f; if (w > h) { scale = (float) target_size / w; w = target_size; h = h * scale; } else { scale = (float) target_size / h; h = target_size; w = w * scale; } ncnn::Mat in = ncnn::Mat::from_pixels_resize(rgb.data, ncnn::Mat::PIXEL_RGB2BGR, width, height, w, h); // pad to target_size rectangle int wpad = 320 - w; //(w + 31) / 32 * 32 - w; int hpad = 320 - h; //(h + 31) / 32 * 32 - h; ncnn::Mat in_pad; ncnn::copy_make_border(in, in_pad, hpad / 2, hpad - hpad / 2, wpad / 2, wpad - wpad / 2, ncnn::BORDER_CONSTANT, 0.f); const float mean_vals[3] = {103.53f, 116.28f, 123.675f}; const float norm_vals[3] = {1.f / 57.375f, 1.f / 57.12f, 1.f / 58.395f}; in_pad.substract_mean_normalize(mean_vals, norm_vals); ncnn::Extractor ex = nanodet_face.create_extractor(); //__android_log_print(ANDROID_LOG_WARN, "ncnn","input w:%d,h:%d",in_pad.w,in_pad.h); ex.input("input.1", in_pad); std::vector<Object> proposals; // stride 8 { ncnn::Mat cls_pred; ncnn::Mat dis_pred; ex.extract("cls_pred_stride_8", cls_pred); ex.extract("dis_pred_stride_8", dis_pred); std::vector<Object> objects8; generate_proposals(cls_pred, dis_pred, 8, in_pad, prob_threshold, objects8); proposals.insert(proposals.end(), objects8.begin(), objects8.end()); } // stride 16 { ncnn::Mat cls_pred; ncnn::Mat dis_pred; ex.extract("cls_pred_stride_16", cls_pred); ex.extract("dis_pred_stride_16", dis_pred); std::vector<Object> objects16; generate_proposals(cls_pred, dis_pred, 16, in_pad, prob_threshold, objects16); proposals.insert(proposals.end(), objects16.begin(), objects16.end()); } // stride 32 { ncnn::Mat cls_pred; ncnn::Mat dis_pred; ex.extract("cls_pred_stride_32", cls_pred); ex.extract("dis_pred_stride_32", dis_pred); std::vector<Object> objects32; generate_proposals(cls_pred, dis_pred, 32, in_pad, prob_threshold, objects32); proposals.insert(proposals.end(), objects32.begin(), objects32.end()); } // sort all proposals by score from highest to lowest qsort_descent_inplace(proposals); // apply nms with nms_threshold std::vector<int> picked; nms_sorted_bboxes(proposals, picked, nms_threshold); int count = picked.size(); objects.resize(count); for (int i = 0; i < count; i++) { objects[i] = proposals[picked[i]]; // adjust offset to original unpadded float x0 = (objects[i].rect.x - (wpad / 2)) / scale; float y0 = (objects[i].rect.y - (hpad / 2)) / scale; float x1 = (objects[i].rect.x + objects[i].rect.width - (wpad / 2)) / scale; float y1 = (objects[i].rect.y + objects[i].rect.height - (hpad / 2)) / scale; // clip x0 = std::max(std::min(x0, (float) (width - 1)), 0.f); y0 = std::max(std::min(y0, (float) (height - 1)), 0.f); x1 = std::max(std::min(x1, (float) (width - 1)), 0.f); y1 = std::max(std::min(y1, (float) (height - 1)), 0.f); objects[i].rect.x = x0; objects[i].rect.y = y0; objects[i].rect.width = (x1 - x0); objects[i].rect.height = (y1 - y0); } // sort objects by area struct { bool operator()(const Object &a, const Object &b) const { return a.rect.area() > b.rect.area(); } } objects_area_greater; std::sort(objects.begin(), objects.end(), objects_area_greater); __android_log_print(ANDROID_LOG_WARN, "face count ", "load %d", objects.size()); return 0; } int NanoDet::detectLandmask(ncnn::Net &pfld, const cv::Mat &img, Object &face) { ncnn::Mat in = ncnn::Mat::from_pixels_resize(img.data, ncnn::Mat::PIXEL_BGR2RGB, img.cols, img.rows, 112, 112); const float norm_vals[3] = {1 / 255.f, 1 / 255.f, 1 / 255.f}; in.substract_mean_normalize(0, norm_vals); ncnn::Extractor ex = pfld.create_extractor(); ex.input("input", in); ncnn::Mat out; ex.extract("output", out); cv::Mat rgb = img.clone(); for (int c = 0; c < out.c; c++) { ncnn::Mat data = out.channel(c); const float *ptr = data.row(0); for (size_t j = 0; j < 98; j++) { float pt_x = ptr[j * 2] * img.cols; float pt_y = ptr[j * 2 + 1] * img.rows; face.pts.push_back(cv::Point2f(pt_x + face.rect.x, pt_y + face.rect.y)); } } return 0; } int NanoDet::detect(const cv::Mat& rgb, std::vector<Object>& faces) { detectFace(nanodetFace, rgb, faces, 320, 0.1f, 0.1f); for (size_t i = 0; i < faces.size(); i++) { cv::Mat roi_image = rgb(faces[i].rect); detectLandmask(nanodetLandmask, roi_image, faces[i]); } return 0; } int NanoDet::draw(cv::Mat&rgb, const std::vector<Object>& faces) { for (size_t i = 0; i < faces.size(); i++) { cv::Scalar cc(255, 0, 0); cv::rectangle(rgb, faces[i].rect, cc, 2); for (size_t j = 0; j < faces[i].pts.size(); j++) { cv::circle(rgb, faces[i].pts[j], 2, cv::Scalar(0, 0, 255), -1); } } return 0; }
#include <zmq.hpp> #include <string> #include <iostream> #include "Usuario.hpp" #include "PosicionUsuario.hpp" #include <json/json.h> #include <sstream> #include <thread> // std::this_thread::sleep_for #include <chrono> // std::chrono::seconds std::string enviarObjetoServer(zmq::socket_t* soc, std::string tipoObjeto, std::string* jsonObjetcString, zmq::message_t* reply){ Json::Value enviar; Json::FastWriter writer; std::string mensaje; enviar["idObjeto"] = tipoObjeto; enviar["data"] = *jsonObjetcString; std::stringstream lineStream(writer.write(enviar)); zmq::message_t request((void*)lineStream.str().c_str(), lineStream.str().size()+1, NULL); soc->send (request); // Do some work soc->recv (reply); std::string rpl = std::string(static_cast<char*>(reply->data()), reply->size()); // COnversión de message_t a string std::cout << "Recibiendo..." << rpl << "tamaño: " << reply->size() << std::endl; return rpl; } int main (int argc, char *argv[]) { std::string nombreCLiente; std::string json_output; // Varaible para almacenar el string json resultante zmq::message_t reply; //Variable para almacenar la respuesta del servidor std::cout << "Bienvenido al Juego" << std::endl; if(argc != 3) { std::cout << argv[0] << " Id NombreJugador" << std::endl; return -1; } std::string nombreJugador = argv[2]; int idJugador = std::stoi(argv[1]); int nivelJudador = 3; int vidaJudador = 100; int vidaMaxUsuario = 100; double longitud = 6.244747; double latitud = -75.574828; Usuario* jugaa = new Usuario(&idJugador,&nombreJugador,&nivelJudador,&vidaJudador ,&vidaMaxUsuario,&longitud,&latitud); std::string cambioPos = "{\"idUsuario\":"+std::string(argv[1])+",\"latitud\":1,\"longitud\":1}"; // Se prepara el contexto y el socket para iniciar la comunicación con el servidor zmq::context_t context (1); zmq::socket_t socket (context, ZMQ_REQ); // socket de tipo REQUEST std::cout << "Connecting to hello world server…" << std::endl; socket.connect ("tcp://localhost:5555"); // el socket se connecta std::cout << "ID jugador: "<< jugaa->getIdUsuario() << std::endl; jugaa->usuarioToJson(&json_output); // Se obtiene el string json del usuario enviarObjetoServer(&socket,"usuario",&json_output,&reply) ; delete jugaa; return 0; }
/* 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 POLYNOMIALMATERIALLAW3D_HPP_ #define POLYNOMIALMATERIALLAW3D_HPP_ #include "AbstractIsotropicIncompressibleMaterialLaw.hpp" /** * PolynomialMaterialLaw3d * * An incompressible, isotropic, hyperelastic material law with a polynomial form * * W(I_1,I_2) = Sigma_{0<p+q<=N} alpha_{pq} (I_1-3)^p (I_2-3)^q - (pressure/2) C^{-1} * * For example, if N=1, this reduces to the Mooney Rivlin law * W(I_1,I_2) = alpha_{10} (I_1-3) + alpha_{01} (I_2-3) - (pressure/2) C^{-1} * ie the matrix alpha has the form * [ 0 c1 ] * [ c2 0 ] * where c1 and c2 is the usual notation for the Mooney-Rivlin constants * * The polynomial is specified by passing in N and the matrix (actually a std::vector * of std::vector<double>s) alpha. alpha should be of size N+1 by N+1, with the bottom * right hand block (ie the components such that p+q>N) all zero. alpha[0][0] should * really also be 0, but, being since alpha[0][0] (I1_3)^0 (I2-3)^0 is a constant * and disappears when the strain energy W is differentiated to obtain the stress, it is * not used. An exception is thrown if alpha[p][q]!=0 for p+q > N though. */ class PolynomialMaterialLaw3d : public AbstractIsotropicIncompressibleMaterialLaw<3> { private: /** Parameter N. */ unsigned mN; /** Matrix of parameters alpha. */ std::vector< std::vector<double> > mAlpha; public: /** * @return the first derivative dW/dI1. * * \todo The name of this method should not include underscores. * * @param I1 first principal invariant of C * @param I2 second principal invariant of C */ double Get_dW_dI1(double I1, double I2); /** * @return the first derivative dW/dI2. * * \todo The name of this method should not include underscores. * * @param I1 first principal invariant of C * @param I2 second principal invariant of C */ double Get_dW_dI2(double I1, double I2); /** * @return the second derivative d^2W/dI1^2. * * \todo The name of this method should not include underscores. * * @param I1 first principal invariant of C * @param I2 second principal invariant of C */ double Get_d2W_dI1(double I1, double I2); /** * @return the second derivative d^2W/dI2^2. * * \todo The name of this method should not include underscores. * * @param I1 first principal invariant of C * @param I2 second principal invariant of C */ double Get_d2W_dI2(double I1, double I2); /** * @return the second derivative d^2W/dI1dI2. * * \todo The name of this method should not include underscores. * * @param I1 first principal invariant of C * @param I2 second principal invariant of C */ double Get_d2W_dI1I2(double I1, double I2); /** * @return the parameter alpha_{ij}. * * @param i index i * @param j index j */ double GetAlpha(unsigned i, unsigned j); public: /** * Constructor. * * @param n the parameter n * @param alpha the matrix of parameters alpha */ PolynomialMaterialLaw3d(unsigned n, std::vector<std::vector<double> > alpha); /** * Resize the matrix alpha to be of size (n+1)*(n+1) and zero all entries. * * @param n the parameter n * @return the matrix alpha */ static std::vector<std::vector<double> > GetZeroedAlpha(unsigned n); }; #endif /*POLYNOMIALMATERIALLAW3D_HPP_*/
/* * myEvents.h * * Created on: Jul 8, 2015 * Author: shapa */ #ifndef MYEVENTS_H_ #define MYEVENTS_H_ #include "qp_port.h" #include <stdint.h> namespace QP { class DataEvt : public QEvt { public: union { void *ptr; char *string; uint32_t uint32; uint16_t uint16; uint8_t uint8; char charachter; }; }; } #endif /* MYEVENTS_H_ */
/*********************************************************************** created: 13/4/2004 author: Paul D Turner purpose: Interface to base class for ButtonBase widget *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2006 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. ***************************************************************************/ #pragma once #include "../Window.h" namespace CEGUI { //! \brief Base class for all the 'button' type widgets (push button, radio button, check-box, etc) class CEGUIEXPORT ButtonBase : public Window { public: ButtonBase(const String& type, const String& name); /************************************************************************* Accessor type functions *************************************************************************/ /*! \brief return true if user is hovering over this widget (or it's pushed and user is not over it for highlight) \return true if the user is hovering or if the button is pushed and the pointer is not over the button. Otherwise return false. */ bool isHovering() const {return d_hovering;} /*! \brief Return true if the button widget is in the pushed state. \return true if the button-type widget is pushed, false if the widget is not pushed. */ bool isPushed() const {return d_pushed;} /** Internal function to set button's pushed state. Normally you would * not call this, except perhaps when building compound widgets. */ void setPushedState(bool pushed); protected: /************************************************************************* Overridden event handlers *************************************************************************/ void onCursorMove(CursorMoveEventArgs& e) override; void onCursorLeaves(CursorInputEventArgs& e) override; void onMouseButtonDown(MouseButtonEventArgs& e) override; void onMouseButtonUp(MouseButtonEventArgs& e) override; void onCaptureLost(WindowEventArgs& e) override; /************************************************************************* Implementation Functions *************************************************************************/ /*! \brief Update the internal state of the widget with the cursor at the given position. \param cursor_pos Point object describing, in screen pixel co-ordinates, the location of the cursor. \return Nothing */ void updateInternalState(const glm::vec2& cursor_pos); bool calculateCurrentHoverState(const glm::vec2& cursor_pos); /************************************************************************* Implementation Data *************************************************************************/ bool d_pushed = false; //!< true when widget is pushed bool d_hovering = false; //!< true when the button is in 'hover' state and requires the hover rendering. }; } // End of CEGUI namespace section
/*========================================================================= Library : project/applications Module : $RCSfile: blur.cc,v $ Authors : (C)opyright Daniel Rueckert and Julia Schnabel 1994-2000++ See COPYRIGHT statement in top level directory. Purpose : Date : $Date: 2003/04/17 14:10:51 $ Version : $Revision: 1.2 $ Changes : $Locker: $ $Log: blur.cc,v $ Revision 1.2 2003/04/17 14:10:51 dr Merged branch Revision 1.1.1.1.2.1 2002/06/11 10:03:33 dr Added compatibility for MS Visual Studio Revision 1.1.1.1 2000/10/29 15:12:17 dr Imported sources =========================================================================*/ #include <irtkImage.h> #include <irtkGaussianBlurring.h> char *input_name = NULL, *output_name = NULL; void usage() { cerr << "Usage: blurWithPadding [in] [out] [sigma] [pad]" << endl; exit(1); } int main(int argc, char **argv) { irtkRealImage input; if (argc < 5){ usage(); } double sigma; irtkRealPixel pad = -1.0 * FLT_MAX; input_name = argv[1]; argc--; argv++; output_name = argv[1]; argc--; argv++; sigma = atof(argv[1]); argc--; argv++; pad = atof(argv[1]); argc--; argv++; // Read input input.Read(input_name); // Blur image irtkGaussianBlurringWithPadding<irtkRealPixel> gaussianBlurring(sigma, pad); gaussianBlurring.SetInput (&input); gaussianBlurring.SetOutput(&input); gaussianBlurring.Run(); // Write image input.Write(output_name); return 0; }
//Jason Strange //The tree is the fundamental building block behind our database. #include "Tree.h" #include "Comparable.h" #define NULL 0 Tree::Tree () { root = NULL; } Tree::~Tree () { delete root; } void Tree::setroot (TreeNode *r) { root = r; }//setting root //Adding a node to the tree void Tree::add (Comparable *key, Item* data) { if(!root) root = new TreeNode (key,data,NULL,NULL,NULL,this); else root->add (key, data); } //Locating a key in the tree bool Tree::locate (Comparable *key) {//finding the key if (!root) return false; return root->search (key); } //Searching for a node TreeNode * Tree::searchnode (Comparable *key) { if (!root) return NULL; return root->searchnode (key); } //Finds the first node in the tree. Comparable * Tree::first () { if (!root) return NULL; return root->first ()->getk (); } //Finds the last node in the tree Comparable * Tree::last () { if (!root) return NULL; return root->last ()->getk (); } //Next node after the given key Comparable * Tree::next (Comparable *key) { if (!root) return NULL; return root->next (key); } //Node before the given key Comparable * Tree::prev (Comparable *key) { if (!root) return NULL; return root->prev (key); } //Remove the node with the given key from the tree void Tree::remove (Comparable *key) { if (!root) return; TreeNode *found = searchnode (key); if (!found) return; found->remove (); } //Lookup a key and return the item Item * Tree::lookup(Comparable *key){ if(!root) return NULL; return root->lookup(key); }
/************************************************************* * > File Name : c1080_1.cpp * > Author : Tony * > Created Time : 2019/10/28 13:02:57 * > Algorithm : **************************************************************/ #include <bits/stdc++.h> using namespace std; typedef long long LL; inline LL read() { LL x = 0; LL 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 LL maxn = 1000010; LL vis[maxn]; LL prime[maxn], sum[maxn], num; void getprime(LL n) { memset(vis, 0, sizeof(vis)); for (int i = 2; i <= n; ++i) { if (vis[i] == 0) { vis[i] = i; prime[++num] = i; } for (int j = 1; j <= num; ++j) { if (prime[j] > vis[i] || prime[j] > n / i) break; vis[i * prime[j]] = prime[j]; } } } int main() { LL T = read(); getprime(1000000); // for (int i = 1; i <= num; ++i) { // printf("%lld\n", prime[i]); // } for (LL i = 1; i <= num; ++i) sum[i] = sum[i - 1] + prime[i]; while (T--) { LL n = read(), k = read(); LL l = 1, r = num - k + 1, ans = -1; while (l <= r) { LL mid = (l + r) >> 1; if (sum[mid + k - 1] - sum[mid - 1] <= n) { ans = mid; l = mid + 1; } else r = mid - 1; } if (sum[ans + k - 1] - sum[ans - 1] <= n && ans != -1) { printf("%lld\n", sum[ans + k - 1] - sum[ans - 1]); } else printf("-1\n"); } return 0; }
#ifndef SAMPLE_SETTINGS_HPP #define SAMPLE_SETTINGS_HPP namespace Model { enum CurrencyUnit { CURRENCY_UNIT_EURO = 0, CURRENCY_UNIT_DOLLAR, CURRENCY_UNIT_POUND, CURRENCY_UNIT_YEN, }; inline QString currencyUnitToString(CurrencyUnit unit) { switch (unit) { case CURRENCY_UNIT_EURO: return QString::fromUtf8("Euro (\xE2\x82\xAC)"); case CURRENCY_UNIT_DOLLAR: return QString("Dollar ($)"); case CURRENCY_UNIT_POUND: return QString::fromUtf8("Pound (\xC2\xA3)"); case CURRENCY_UNIT_YEN: return QString::fromUtf8("Yen (\xC2\xA5)"); default: return QString("Unknown (?)"); } } inline QString currencyUnitToSymbol(CurrencyUnit unit) { switch (unit) { case CURRENCY_UNIT_EURO: return QString::fromUtf8("\xE2\x82\xAC"); case CURRENCY_UNIT_DOLLAR: return QString("$"); case CURRENCY_UNIT_POUND: return QString::fromUtf8("\xC2\xA3"); case CURRENCY_UNIT_YEN: return QString::fromUtf8("\xC2\xA5"); default: return QString("?"); } } enum TemperatureUnit : int { TEMPERATURE_UNIT_CELSIUS = 0, TEMPERATURE_UNIT_FAHRENHEIT, TEMPERATURE_UNIT_KELVIN, }; inline QString temperatureUnitToString(TemperatureUnit unit) { switch (unit) { case TEMPERATURE_UNIT_CELSIUS: return QString::fromUtf8("Celsius (\xC2\xB0" "C)"); case TEMPERATURE_UNIT_FAHRENHEIT: return QString::fromUtf8("Fahrenheit (\xC2\xB0" "F)"); case TEMPERATURE_UNIT_KELVIN: return QString("Kelvin (K)"); default: return QString("Unknown (?)"); } } inline QString temperatureUnitToSymbol(TemperatureUnit unit) { switch (unit) { case TEMPERATURE_UNIT_CELSIUS: return QString::fromUtf8("\xC2\xB0" "C"); case TEMPERATURE_UNIT_FAHRENHEIT: return QString::fromUtf8("\xC2\xB0" "F"); case TEMPERATURE_UNIT_KELVIN: return QString("K"); default: return QString("?"); } } class SampleSettings { public: QString userName; QString password; QString firstName; QString lastName; QString street; QString city; QString stateOrProvince; QString postalCode; QString country; bool enablePriceFields = false; CurrencyUnit priceUnit = CURRENCY_UNIT_EURO; double priceMin = 10.0; double priceMax = 100.0; double priceValue = 30.0; bool enableTemperatureFields = false; TemperatureUnit temperatureUnit = TEMPERATURE_UNIT_CELSIUS; double temperatureMin = 0.0; double temperatureMax = 30.0; double temperatureValue = 20.0; QString notes; }; } // namespace Model #endif // SAMPLE_SETTINGS_HPP
#ifndef GUARD_NETLIST_H #define GUARD_NETLIST_H #include "module.h" #include <sstream> #include "gates.h" using namespace std; class netlist; class net; class pin; class gate; class net { //net() {} net(string name); net(const net &); net &operator=(const net &); ~net() {} friend class netlist; string net_name; typedef pair<pin *, size_t> pin_info; list<pin_info> connections_; public: void append_pin(pin *p, size_t net_index); }; // class net class pin { pin() {} pin(const pin &); pin &operator=(const pin &); ~pin(){} friend class gate; vector<net *> nets_; bool create(gate *g, size_t pin_index, const evl_pin &p, const map<string, net *> &netlist_nets); size_t pin_index_; gate * gate_; public: int pin_size; const vector<net *> get_nets(); const int get_pin_index(); const gate* get_gate_handle(); }; // class pin class netlist { list<gate *> gates_; map<string, net *> nets_; bool create_nets(const evl_wires &wires); void create_net(string net_name); bool create_gates(const evl_components &comps); bool create_gate(const evl_component &c); void display_netlist(ostream &out); public: netlist() {} netlist(const netlist &); netlist &operator=(const netlist &); ~netlist(); bool create(const evl_wires &wires, const evl_components &comps); void save(string inputfilename); }; // class netlist bool parse_evl_file(std::string evl_file, evl_wires &wires, evl_components &comps); #endif
#include <windows.h> #include <gl/glut.h> void DoDisplay(); void DoReshape(GLsizei width, GLsizei height); int APIENTRY WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance ,LPSTR lpszCmdParam,int nCmdShow) { glutCreateWindow("OpenGL"); glutDisplayFunc(DoDisplay); glutReshapeFunc(DoReshape); glutMainLoop(); return 0; } void DoReshape(GLsizei width, GLsizei height) { /* 뷰포트 변환으로 종횡비 유지 if (width > height) { glViewport((width - height)/2, 0, height, height); } else { glViewport(0, (height - width)/2, width, width); } //*/ //* 직교 투영 영역을 조정하여 종횡비 유지 glViewport(0,0,width,height); if (height == 0) return; glMatrixMode(GL_PROJECTION); glLoadIdentity(); GLfloat aspect = (GLfloat)width / (GLfloat)height; if (width > height) { glOrtho(-1.0 * aspect, 1.0 * aspect, -1.0, 1.0, 1.0, -1.0); } else { glOrtho(-1.0, 1.0, -1.0/aspect, 1.0/aspect, 1.0, -1.0); } glMatrixMode(GL_MODELVIEW); glLoadIdentity(); //*/ } void DoDisplay() { glClear(GL_COLOR_BUFFER_BIT); glColor3f(0.0, 1.0, 0.0); glRectf(-1.0, 1.0, 1.0, -1.0); glBegin(GL_POLYGON); glColor3f(1.0, 0.0, 0.0); glVertex2f(0.0, 0.5); glVertex2f(-0.5, -0.5); glVertex2f(0.5, -0.5); glEnd(); glFlush(); }
#pragma once #include <string> #include <iostream> class bill_format { public: bill_format(); bill_format(float amount, std::string * namelist , unsigned int noOfPeople) { myAmount = amount; myNameList = namelist; myNoOfPeople = noOfPeople; } void set_bill_format(float amount, std::string * namelist, unsigned int noOfPeople) { myAmount = amount; myNameList = namelist; myNoOfPeople = noOfPeople; } float getAmount() { return myAmount; } std::string getName(int index = 0) { return *(myNameList+index) ; } unsigned int getNoOfPeople() { return myNoOfPeople; } ~bill_format(); virtual void printBill() { std::cerr << "Error. Balance not available for base type." << std::endl; }; private: float myAmount; std::string* myNameList ; unsigned int myNoOfPeople; };
#pragma once extern "C" { #include "SDL.h" #include "SDL_thread.h" } // VideoWindow 对话框 class VideoWindow : public CDialogEx { DECLARE_DYNAMIC(VideoWindow) public: VideoWindow(CWnd* pParent = NULL); // 标准构造函数 virtual ~VideoWindow(); HDC hDC; // 对话框数据 enum { IDD = IDD_DIALOG1 }; SDL_Window * screen; int windowIsCreate; int DisPlaynum;//当前屏幕的个数 RECT DisPlayRect[3];//每个屏幕的尺寸 int WindowShowType; void CreateScreen(); void DestroyScreen(); SDL_Window * GetScreen(); void getScreenRect(CRect *rect); void setWindowType(int type);//0:在第一屏小屏显示 1:第二屏全屏显示(有第二屏的话) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: afx_msg void OnSize(UINT nType, int cx, int cy); virtual BOOL Create(LPCTSTR lpszTemplateName, CWnd* pParentWnd = NULL); virtual void OnOK(); afx_msg void OnPaint(); afx_msg void OnStnClickedStatic2(); CStatic m_ShowPic; // virtual BOOL OnInitDialog(); };
#include <fcntl.h> #include <fstream> #include <linux/fb.h> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <sys/ioctl.h> struct framebuffer_info { uint32_t bits_per_pixel; // framebuffer depth uint32_t xres_virtual; // how many pixel in a row in virtual screen }; struct framebuffer_info get_framebuffer_info(const char *framebuffer_device_path); int main(int argc, const char *argv[]) { cv::Mat image; cv::Size2f image_size; framebuffer_info fb_info = get_framebuffer_info("/dev/fb0"); std::ofstream ofs("/dev/fb0"); // read image file (sample.bmp) from opencv libs. // https://docs.opencv.org/3.4.7/d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56 image= cv::imread("sample.bmp"); // get image size of the image. // https://docs.opencv.org/3.4.7/d3/d63/classcv_1_1Mat.html#a146f8e8dda07d1365a575ab83d9828d1 image_size = image.size(); // transfer color space from BGR to BGR565 (16-bit image) to fit the requirement of the LCD // https://docs.opencv.org/3.4.7/d8/d01/group__imgproc__color__conversions.html#ga397ae87e1288a81d2363b61574eb8cab // https://docs.opencv.org/3.4.7/d8/d01/group__imgproc__color__conversions.html#ga4e0972be5de079fed4e3a10e24ef5ef0 int framebuffer_width = fb_info.xres_virtual; int framebuffer_depth = fb_info.bits_per_pixel; cv::Mat framebuffer_compat; switch (framebuffer_depth) { case 16: //cv::cvtColor(image, framebuffer_compat, cv::COLOR_RGBA2BGR565); cv::cvtColor(image, framebuffer_compat, cv::COLOR_BGR2BGR565); break; // case 32: { // std::vector<cv::Mat> split_bgr; // cv::split(image, split_bgr); // split_bgr.push_back(cv::Mat(image_size,CV_8UC1,cv::Scalar(255))); // cv::merge(split_bgr, framebuffer_compat); // for (int y = 0; y < image_size.height ; y++) { // ofs.seekp(y*framebuffer_width*4); // ofs.write(reinterpret_cast<char*>(framebuffer_compat.ptr(y)),image_size.width*4); // } // } // break; } // output to framebufer row by row // move to the next written position of output device framebuffer by "std::ostream::seekp()". // posisiotn can be calcluated by "y", "fb_info.xres_virtual", and "fb_info.bits_per_pixel". // http://www.cplusplus.com/reference/ostream/ostream/seekp/ // write to the framebuffer by "std::ostream::write()". // you could use "cv::Mat::ptr()" to get the pointer of the corresponding row. // you also have to count how many bytes to write to the buffer // http://www.cplusplus.com/reference/ostream/ostream/write/ // https://docs.opencv.org/3.4.7/d3/d63/classcv_1_1Mat.html#a13acd320291229615ef15f96ff1ff738 for (int y = 0; y < image_size.height ; y++) { //*2 is because one pixel has two byte ofs.seekp(y*framebuffer_width*2); ofs.write(reinterpret_cast<char*>(framebuffer_compat.ptr(y)),image_size.width*2); } return 0; } struct framebuffer_info get_framebuffer_info(const char* framebuffer_device_path) { struct framebuffer_info info; struct fb_var_screeninfo screen_info; int fd = -1; fd = open(framebuffer_device_path, O_RDWR); if (fd >= 0) { if (!ioctl(fd, FBIOGET_VSCREENINFO, &screen_info)) { info.xres_virtual = screen_info.xres_virtual; info.bits_per_pixel = screen_info.bits_per_pixel; } } return info; };
#include <bits/stdc++.h> using namespace std; #define ll long long std::random_device rd; mt19937 gen(rd()); const uint32_t PRIME = 4294967291; class hashSet { uint32_t cnt, a, b, p = PRIME; uint32_t sz; vector<list<uint32_t> > table; vector<list<uint32_t> > newTable; public: hashSet() { sz = 10; table.resize(sz); rebuildKeys(); cnt = 0; } uint32_t getHash(uint32_t x) { return static_cast<uint32_t>(a * x + b) % p % sz; } void rebuildKeys() { a = uniform_int_distribution<uint32_t>(1, INT_MAX)(gen); b = uniform_int_distribution<uint32_t>(0, INT_MAX)(gen); } void expand() { if (cnt * 3 > ((uint32_t)sz * 4)) { sz *= 2; newTable.clear(); vector<list<uint32_t> > newTable(sz); rebuildKeys(); for (const list<uint32_t> &L : table) { for (uint32_t elem : L) { newTable[getHash(elem)].push_back(elem); } } table.swap(newTable); } } void insert(uint32_t x) { if (exists(x)) return; table[getHash(x)].push_back(x); cnt++; expand(); } void erase(uint32_t x) { int t = getHash(x); for (auto it = table[t].begin(); it != table[t].end(); it++) { if (*it == x) { table[t].erase(it); cnt--; return; } } } bool exists(uint32_t x) { int t = getHash(x); for (uint32_t &it : table[t]) { if (it == x) { return true; } } return false; } }; int main() { // freopen("file.in", "r", stdin); freopen("set.in", "r", stdin); freopen("set.out", "w", stdout); ios_base::sync_with_stdio(false); cin.tie(nullptr); hashSet H; uint32_t k; string act, ans = ""; while (cin >> act) { if (act == "insert") { cin >> k; H.insert(k); } else if (act == "exists") { cin >> k; if (H.exists(k)) { ans += "true\n"; } else { ans += "false\n"; } } else if (act == "delete") { cin >> k; H.erase(k); } } cout << ans; return 0; }
#ifndef RANDOM_H #define RANDOM_H class BasicRandom { public: BasicRandom(unsigned int seed=0) : mRnd(seed) {} ~BasicRandom() {} __forceinline void setSeed(unsigned int seed) { mRnd = seed; } __forceinline unsigned int getCurrentValue() const { return mRnd; } unsigned int randomize() { mRnd = mRnd * 2147001325 + 715136305; return mRnd; } __forceinline unsigned int rand() { return randomize() & 0xffff; } float rand(float a, float b) { const float r = (float)rand()/((float)0x7fff+1); return r*(b-a) + a; } float randomFloat() { return (float(randomize() & 0xffff)/65535.0f) - 0.5f; } void unitRandomPt(Point& v); private: unsigned int mRnd; }; #endif
#include "Room.hpp" Room::Room(string title) { this->title = title; this->currNumOfDoors = 0; } void Room::addDoor(Door* door) { int i = this->currNumOfDoors; this->collectionOfDoors[i] = door; this->currNumOfDoors++; }
//! Bismillahi-Rahamanirahim. /** ========================================** ** @Author: Md. Abu Farhad ( RUET, CSE'15) ** @Category: /** ========================================**/ #include<bits/stdc++.h> using namespace std; #define ll long long struct Seller { ll first,second,diff; } a[200005]; bool cmp(Seller p, Seller q) { return ( p.diff>q.diff); } int main() { ll n,m,i,j,ans=0; cin>>n>>m; for(i=0; i<n; i++) cin>>a[i].first; for(i=0; i<n; i++) cin>>a[i].second; for(i=0; i<n; i++) { a[i].diff=(a[i].second-a[i].first ); } sort(a,a+n,cmp); // for(i=0;i<n;i++) cout<<a[i].first<<" "; // cout<<endl; // for(i=0;i<n;i++) cout<<a[i].second<<" "; for(i=0; i<m; i++) ans+=a[i].first; for(i=m; i<n; i++) ans+=min(a[i].first, a[i].second); cout<<ans<<endl; }
#pragma once #include <array> class RotationMatrix { private: std::array<std::array<float, 3>, 3> m_matrix; public: RotationMatrix(); RotationMatrix(const std::array<float, 3> &row_1, const std::array<float, 3> &row_2, const std::array<float, 3> &row_3); std::array<float, 3> &operator[](const int index); std::array<float, 3> operator[](const int index) const; RotationMatrix operator*(const RotationMatrix &other) const; void print() const; bool isValid() const; std::array<float, 4> toQuat() const; }; class HomogeneousMatrix { private: RotationMatrix m_rotation_matrix; std::array<float, 3> m_translation_vector; // Order of Rotation x -> y -> z (around intrinsic coordinates) results in R_x*R_y*R_z RotationMatrix eulerAngleXYZ(const float rotation_x, const float rotation_y, const float rotation_z, const bool is_degree) const; public: HomogeneousMatrix(const RotationMatrix &rotation_matrix, const std::array<float, 3> &translation_vector); // Rotation angles in order x, y, z, Translation vector in order x, y, z HomogeneousMatrix(const std::array<float, 3> &rotation_angles, const std::array<float, 3> &translation_vector, const bool is_degree); HomogeneousMatrix(); HomogeneousMatrix operator*(const HomogeneousMatrix &b) const; void print() const; void resetToIdentity(); // Order of Rotation x -> y -> z (around intrinsic coordinates) results in R_x*R_y*R_z void rotate(const float x, const float y, const float z, const bool is_degree); // Order of Rotation x -> y -> z (around intrinsic coordinates) results in R_x*R_y*R_z void rotate(const std::array<float, 3> &rotation_angles, const bool is_degree); void translate(const std::array<float, 3> &translation_vector); void translate(const float x, const float y, const float z); RotationMatrix getRotationMatrix() const; std::array<float, 3> getTranslationVector() const; bool rotationMatrixIsValid() const; std::array<float, 7> toPoseArray() const; std::array<float, 4> rotationMatrixToQuaternion() const; };
#ifndef SLICE_H #define SLICE_H #include <string> class Slice { public: explicit Slice(); explicit Slice(unsigned char* key, int key_size, unsigned char* value, int value_size); explicit Slice(unsigned char* key, int key_size, unsigned char* value, int value_size, bool is_deleted); ~Slice(); unsigned char* getKey(); unsigned char* getValue(); void setValue(unsigned char* value, int size); void delValue(); bool isDeleted(); void cancelDelValue(); int getKeySize(); int getValueSize(); public: Slice& operator =(const Slice& slice); private: unsigned char* key; int key_size; unsigned char* value; int value_size; bool is_deleted; }; #endif // ! SLICE_H
#ifndef GAME_H #define GAME_H #include <fstream> class Game { private: //Enums enum class GameStates{ mainMenu, gameRunning, gameOver }; enum GameStates m_currentGameState; //Integers int m_currentScore; int m_highScore; //Objects //Resources std::ifstream m_highScoreFile; //Strings std::string m_scoreFilename; public: Game( ); void renderGameOver( ); void renderMenu( ); void runGame( ); void update( ); }; #endif // !GAME_H
#ifndef LOGICSRV_CONNNODE_LOGICSRV_H #define LOGICSRV_CONNNODE_LOGICSRV_H #include "../../zcomm/activeconnnodebase.h" // 未避免理解上和 gateserver 相冲突 namespace logicsrv { class ConnNodeLogicSrv:public ActiveConnNodeBase { public: ConnNodeLogicSrv(); ~ConnNodeLogicSrv(); public: // 接收 gatesrver::connnode_logicsrv 发送来的消息,带上了AuxData表示源地址 int DispatchMsg(MsgHead *head, AuxData *aux_data); }; } #endif
//https://www.hackerrank.com/contests/sda-2019-2020-test3/challenges/tree-specific-print/ #include <bits/stdc++.h> using namespace std; struct Node { Node* l=nullptr,*r=nullptr; int data; Node(int data):data(data){} }; Node* root; Node* add(Node* root, int a) { if(root==nullptr) return new Node(a); else if(a>root->data) root->r=add(root->r,a); else if(a<root->data) root->l=add(root->l,a); return root; } void spec_print(Node* root,int& d) { if(root) { if(root->data%d==0&&(root->l||root->r)) cout<<root->data<<' '; spec_print(root->l,d); spec_print(root->r,d); } } int main() { int n,a,d; cin>>n; while(n--) { cin>>a; root=add(root,a); } cin>>d; spec_print(root,d); return 0; }
//#include "mpi.h" // for local development #include "/usr/lib/openmpi/include/mpi.h" #include "mpi_tournament_barrier.h" #define ROUND 100 int main(int argc, char** argv){ int my_id, num_processors; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &num_processors); MPI_Comm_rank(MPI_COMM_WORLD, &my_id); double time1, time2, local_sum, total_sum; local_sum = 0; //*************************************** bool sense; Mpi_Tournament_Barrier tb(&sense, &num_processors); for (int i=0; i<ROUND; i++){ time1 = MPI_Wtime(); tb.sync(&my_id, &sense); time2 = MPI_Wtime(); local_sum += time2 - time1; } //******** end of barrier stuff ********** printf("rank %i spend %f secconds\n", my_id, local_sum); MPI_Reduce(&local_sum, &total_sum, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); if (my_id == 0){ double avg = total_sum/(1.0*num_processors*ROUND); printf("total time is %f seconds\n", total_sum); printf("average time per processor per round: %f microsecs\n", avg*1000000); } MPI_Finalize(); return 0; }
//******************************************************** // // Michael J Phillips // Copyright 2015 // All rights reserved. // //******************************************************** #ifndef _EUROPTION_H_ #define _EUROPTION_H_ #include <cmath> static const double PI = 4.0 * std::atan(1.0); class EurOption { public: EurOption(double T, double K) : mT(T), mK(K) {}; virtual ~EurOption() {} virtual double PriceByJumpDiffusion(double S0, double Sigma, double Lambda, double r, double s, double m, int N) const = 0; virtual double priceByBSFormula(double S0, double sigma, double r) const = 0; virtual double deltaByBSFormula(double S0, double sigma, double r) const = 0; virtual double gammaByBSFormula(double S0, double sigma, double r) const = 0; virtual double thetaByBSFormula(double S0, double sigma, double r) const = 0; double crossCheck(double S0, double sigma, double r) const { // Check against BS PDE const double p = priceByBSFormula(S0, sigma, r); const double d = deltaByBSFormula(S0, sigma, r); const double g = gammaByBSFormula(S0, sigma, r); const double t = thetaByBSFormula(S0, sigma, r); return t + sigma*sigma*S0*S0 * g/2.0 + r*S0*d - r*p; } protected: double d_plus(double S0, double sigma, double r) const; double d_minus(double S0, double sigma, double r) const; double cumNorm(double x) const; const double mT; const double mK; }; #endif
#include <bits/stdc++.h> using namespace std; #define loop(i, n) for (int i = 0; i < n; i++) int input() { int n; cin >> n; return n; } void print(int a, int b) { cout << a << " " << b; } int main() { int arr[5]; loop(i, 5) arr[i] = input(); loop(i, 2) swap((int)i, 5 - (int)i); loop(i, 5) cout << arr[i] << " "; return 0; }
#pragma once #include "gtest/gtest.h" #include "gmock/gmock.h" #include "Engine/Common/SmallVector.h" namespace { using namespace Engine; TEST(SmallVector, emplace_back_and_access_to_fit) { SmallVector<int, 3> vector; vector.push_back(2); ASSERT_EQ(vector[0], 2); vector.push_back(3); vector.push_back(4); ASSERT_EQ(vector[2], 4); ASSERT_EQ(vector[1], 3); } TEST(SmallVector, emplace_back_and_access_to_reallocate) { SmallVector<int, 3> vector; vector.push_back(2); ASSERT_EQ(vector[0], 2); vector.push_back(3); vector.push_back(4); ASSERT_EQ(vector[2], 4); ASSERT_EQ(vector[1], 3); vector.push_back(7); vector.push_back(5); ASSERT_EQ(vector[2], 4); ASSERT_EQ(vector[1], 3); ASSERT_EQ(vector[3], 7); ASSERT_EQ(vector[4], 5); ASSERT_EQ(vector[3], 7); } TEST(SmallVector, size_stack) { SmallVector<int, 3> vector; ASSERT_EQ(vector.size(), 0); for (int i = 0; i < 2; ++i) vector.push_back(i); ASSERT_EQ(vector.size(), 2); } TEST(SmallVector, size_heap) { SmallVector<int, 3> vector; ASSERT_EQ(vector.size(), 0); for (int i = 0; i < 5; ++i) vector.push_back(i); ASSERT_EQ(vector.size(), 5); } TEST(SmallVector, to_std_vector_conversion_stack) { SmallVector<int, 3> vector; ASSERT_EQ(vector.size(), 0); for (int i = 0; i < 2; ++i) vector.push_back(i); auto vec = (std::vector<int>)vector; ASSERT_EQ(vector.size(), 2); //checking for not breaking SmallVector for (int i = 0; i < 2; ++i) ASSERT_EQ(vector[i], i); ASSERT_EQ(vec.size(), 2); //checking for getting proper result for (int i = 0; i < 2; ++i) ASSERT_EQ(vec[i], i); } TEST(SmallVector, to_std_vector_conversion_heap) { SmallVector<int, 3> vector; ASSERT_EQ(vector.size(), 0); for (int i = 0; i < 5; ++i) vector.push_back(i); auto vec = (std::vector<int>)vector; //checking for not breaking SmallVector ASSERT_EQ(vector.size(), 5); for (int i = 0; i < 5; ++i) ASSERT_EQ(vector[i], i); //checking for getting proper result ASSERT_EQ(vec.size(), 5); for (int i = 0; i < 5; ++i) ASSERT_EQ(vec[i], i); } TEST(SmallVector, iterators_stack) { SmallVector<int, 4> vector; vector.push_back(2); vector.push_back(1); vector.push_back(3); std::vector<int> vec; for (int v : vector) vec.push_back(v); auto it = vector.begin(); ASSERT_EQ(*it, 2); ASSERT_EQ(*(it + 2), 3); ASSERT_EQ(*(it++), 2); ASSERT_EQ(*it, 1); ASSERT_EQ((std::vector<int>)vector, vec); } TEST(SmallVector, iterators_heap) { SmallVector<int, 1> vector; vector.push_back(2); vector.push_back(1); std::vector<int> vec; for (int v : vector) vec.push_back(v); auto it = vector.begin(); ASSERT_EQ(*it, 2); ASSERT_EQ(*(it++), 2); ASSERT_EQ(*it, 1); ASSERT_EQ((std::vector<int>)vector, vec); } }
#pragma once #include <math.h> #include <omp.h> #include <vector> #include <cassert> void interp_cic_par(const int nz, const int ny, const int nx, const double *vals, const int N, const double *z, const double dz, const double *y, const double dy, const double *x, const double dx, double *c); void weight_cic_par(const int nz, const int ny, const int nx, double *grid, const int N, const double *z, const double dz, const double *y, const double dy, const double *x, const double dx, const double *q);
//map.find(key),返回键为key的映射的迭代器,时间复杂度为O(logN) #include<stdio.h> #include<map> using namespace std; int main() { map<char,int> mp; mp['m']=10; mp['r']=20; mp['a']=40; map<char,int>::iterator it=mp.find('r'); printf("%c %d",it->first,it->second); return 0; }
/* 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 _COLUMNDATAREADER_HPP_ #define _COLUMNDATAREADER_HPP_ #include "AbstractDataReader.hpp" #include <string> #include <vector> #include <map> #include "FileFinder.hpp" /** * A concrete column data reader class. */ class ColumnDataReader : public AbstractDataReader { private: std::map<std::string, int> mVariablesToColumns; /**< Map between variable names and data column numbers. \todo Change int to unsigned? (#991) */ std::map<std::string, std::string> mVariablesToUnits; /**< Map between variable names and variable units. */ int mNumFixedDimensions; /**< The number of fixed dimensions in data file. */ bool mHasUnlimitedDimension; /**< Whether the data file has an unlimited dimension. */ int mNumVariables; /**< The number of variables in the data file. */ std::string mInfoFilename; /**< The name of the info file.*/ std::string mDataFilename; /**< The name of the data file.*/ std::string mAncillaryFilename; /**< The name of the ancillary file.*/ std::vector<double> mValues; /**< Vector to hold values for a variable.*/ unsigned mFieldWidth; /**< Width of each column in the text file (excludes column headers). Determined from the first data entry*/ /** * Push back an entry from the data file into #mValues. * * @param rLine the line of the data file * @param col the column number */ void PushColumnEntryFromLine(const std::string& rLine, int col); /** * Read in a given column from a data file into #mValues. * * @param rFilename the file name * @param col the column number */ void ReadColumnFromFile(const std::string& rFilename, int col); /** * Push back an entry from a file into #mValues. * * @param rFilename the file name * @param col the column number * @param row the row number */ void ReadValueFromFile(const std::string& rFilename, int col, int row); /** * Set up internal data structures based on file structure, checking that they * contain data in roughly the expected format. * * @param rDirectory Absolute path of the directory the files are stored in * @param rBaseName The base name of the files to read (i.e. without the extensions) */ void CheckFiles(const std::string& rDirectory, const std::string& rBaseName); public: /** * Read data from the given files into memory. The files should be formatted as if * written by ColumnDataWriter, with fixed width columns (except for the header line) * and fields in scientific notation. * * This will attempt to determine the field width from the input file. However, it * needs some data to work with in order to do so. Provided at least one correctly * formatted entry exists, it will be able to determine the field width, assuming * that space is allowed for 3 digits in the exponent. Release 1.1 and earlier of * Chaste only allowed 2 digits for the exponent; we can cope with this provided that * the first data entry in the file has another entry immediately to the right of it. * * @param rDirectory The directory the files are stored in * @param rBaseName The base name of the files to read (i.e. without the extensions) * @param makeAbsolute Whether to convert directory to an absolute path using the * OutputFileHandler (defaults to true) */ ColumnDataReader(const std::string& rDirectory, const std::string& rBaseName, bool makeAbsolute=true); /** * Alternative constructor using FileFinder to specify the directory files are stored * in. * * @param rDirectory The directory the files are stored in * @param rBaseName The base name of the files to read (i.e. without the extensions) */ ColumnDataReader(const FileFinder& rDirectory, const std::string& rBaseName); /** * @return the entries for a given variable. * * @param rVariableName */ std::vector<double> GetValues(const std::string& rVariableName); /** * @return the entries for a given variable with fixed dimension. * * @param rVariableName * @param fixedDimension */ std::vector<double> GetValues(const std::string& rVariableName, int fixedDimension); /** * @return the entries for a given variable with unlimited dimension. */ std::vector<double> GetUnlimitedDimensionValues(); /** * @return true if the data file has entries for a given variable. * * @param rVariableName */ bool HasValues(const std::string& rVariableName); /** * @return the field width (the number of characters (excl. preceding '+' or '-') printed for each data entry in the file). */ unsigned GetFieldWidth(); }; #endif //_COLUMNDATAREADER_HPP_
#ifndef NOSTA_H #define NOSTA_H #include <QDialog> #include <dllmysql.h> namespace Ui { class Nosta; } class Nosta : public QDialog { Q_OBJECT public: explicit Nosta(QWidget *parent = nullptr); ~Nosta(); public slots: void asetaSaldo(double s){saldo=s;} void asetaTili(int t){idTili=t;} private slots: void vaihdaTeksti(int i); void on_btn20_clicked(); void on_btn40_clicked(); void on_btn60_clicked(); void on_btn80_clicked(); void on_btn100_clicked(); void on_btnPeruuta_clicked(); void on_btnnosta_clicked(); void on_spinBoxSumma_valueChanged(); private: Ui::Nosta *ui; DLLMySQL *olio3MysqlDLL; int nostoSumma = 0; double saldo = 0.0; int idTili; double saldoP = 0.0; //palautuva saldo kannasta. }; #endif // NOSTA_H
// 53. Maximum (continuous) Subarray // Greedy: O(n) class Solution { public: int maxSubArray(vector<int>& nums) { int res = INT_MIN, curSum = 0; for (int num : nums) { curSum = max(curSum + num, num); res = max(res, curSum); } return res; } }; // DC : O(logn) class Solution { public: int maxSubArray(vector<int>& nums) { if (nums.empty()) return 0; return maxSubArray_DC(nums, 0, (int)nums.size() - 1); } int maxSubArray_DC(vector<int>& nums, int left, int right) { //only check (left == right) results in runtime error if (left >= right) return nums[left]; int mid = left + (right - left) / 2; int leftmax = maxSubArray_DC(nums, left, mid - 1); int rightmax = maxSubArray_DC(nums, mid + 1, right); int midmax = nums[mid], tmp = midmax; for (int i = mid - 1; i >= left; i--) { tmp += nums[i]; midmax = max(midmax, tmp); } tmp = midmax; for (int i = mid + 1; i <= right; i++) { tmp += nums[i]; midmax = max(midmax, tmp); } return max(midmax, max(leftmax, rightmax)); } }; // 148. Sort a linked list in O(n log n) time using constant space complexity. class Solution { public: ListNode* sortList(ListNode* head) { if (!head || !head->next) return head; ListNode * slow = head, * fast = head, * mid = head; while (fast && fast->next) { // slow at middle when fast hits the end mid = slow; slow = slow->next; fast = fast->next->next; } mid->next = NULL; // divide the list, and conquer (merge) return mergeTwoSortedLists(sortList(head), sortList(slow)); } ListNode * mergeTwoSortedLists(ListNode * l1, ListNode * l2) { ListNode * dummyHead = new ListNode(-1); ListNode * cur = dummyHead; while (l1 && l2) { if (l1->val < l2->val) { cur->next = l1; l1 = l1->next; } else { cur->next = l2; l2 = l2->next; } cur = cur->next; } if (!l1) cur->next = l2; if (!l2) cur->next = l1; return dummyHead->next; } }; // 215. Kth Largest Element in an Array // Input: [3,2,3,1,2,4,5,5,6] and k = 4; Output: 4 class Solution { public: int findKthLargest(vector<int>& nums, int k) { int left = 0, right = nums.size() - 1; while (true) { // Divide and Conquer int pos = findKthLargest(nums, left, right); if (pos == k - 1) return nums[pos]; else if (pos > k - 1) right = pos - 1; else left = pos + 1; } } // quick sort partition: decreasing int findKthLargest(vector<int> & nums, int left, int right) { int pivot = nums[left], l = left + 1, r = right; while (l <= r) { if (nums[l] < pivot && nums[r] > pivot) swap(nums[l++], nums[r--]); if (nums[l] >= pivot) l++; // decreasing if (nums[r] <= pivot) r--; // decreasing } swap(nums[left], nums[r]); return r; } }; // 95. Unique Binary Search Trees II // Given an integer n, generate all structurally unique BST's that store values 1 ... n. // DC, similar to Q241 class Solution { public: vector<TreeNode*> generateTrees(int n) { if (n == 0) return {}; return generateTrees(1, n); } vector<TreeNode*> generateTrees(int start, int end) { if (start > end) return {nullptr}; // vector {nullptr} vector<TreeNode*> res; for (int i = start; i <= end; ++i) { vector<TreeNode*> left = generateTrees(start, i - 1); // divide vector<TreeNode*> right = generateTrees(i + 1, end); for (auto a : left) { // conque for (auto b : right) { TreeNode* node = new TreeNode(i); node->left = a; node->right = b; res.push_back(node); } } } return res; } }; // 241. Different Ways to Add Parentheses // DC class Solution { public: vector<int> diffWaysToCompute(string input) { if (input.empty()) return {}; vector<int> res; for (int i = 0; i < input.size(); ++i) { // divide and conquer at position i if (input[i] == '+' || input[i] == '-' || input[i] == '*') { vector<int> left = diffWaysToCompute(input.substr(0, i)); // calculate left substring vector<int> right = diffWaysToCompute(input.substr(i + 1)); // calculate right substring for (int j = 0; j < left.size(); ++j) { // conquer for (int k = 0; k < right.size(); ++k) { if (input[i] == '+') res.push_back(left[j] + right[k]); else if (input[i] == '-') res.push_back(left[j] - right[k]); else res.push_back(left[j] * right[k]); } } } } if (res.empty()) res.push_back(stoi(input)); // input only includes a number return res; } }; // 315. Count of Smaller Numbers After Self // Input: nums = [5,2,6,1]; Output: [2,1,1,0] class Solution { public: vector<int> countSmaller(vector<int>& nums) { int n = nums.size(); if (n == 0) return {}; vector<int> sortedNums = nums; vector<int> counts(n,0); DivideConque(nums,sortedNums, counts, 0, n - 1); return counts; } void DivideConque(vector<int>& nums, vector<int>& sortedNums, vector<int>& counts, int start, int end){ if (start == end) return; // divide: sort each part int mid = start + (end - start) / 2; DivideConque(nums, sortedNums, counts, start, mid); DivideConque(nums, sortedNums, counts, mid + 1, end); // since nums[start, mid] and nums[mid + 1, end] are sorted // for each num in [start, mid], we know how many num in [mid + 1, end] less than it for (int i = start; i <= mid; i++) { auto pos = lower_bound(sortedNums.begin() + mid + 1, sortedNums.begin() + end + 1, nums[i]); counts[i] += pos - (sortedNums.begin() + mid + 1); } // here use sort(), but implemented as mergesort can be more faster sort(sortedNums.begin() + start, sortedNums.begin() + end + 1); } }; // 327. Count of Range Sum // Input: nums = [-2,5,-1], lower = -2, upper = 2 // Output: 3; ranges: 0,0], [2,2], and [0,2] and their respective sums are: -2, -1, 2. // Time: O(nlog(n)); Space: O(n) class Solution { public: // function counts the ranges with sum greater than or equal to k int countAndSort(vector<long>::iterator begin, vector<long>::iterator end, int k) { // if subarray contains a single element if(begin + 1 == end) return (*begin >= k); auto mid = begin + (end - begin) / 2; int res = countAndSort(begin, mid, k) + countAndSort(mid, end, k); for(auto i = begin, j = mid; i != mid; ++i) { // we know that if the value of (j - i) >= k, // then for all greater values of j this condition will hold until // i is increased, as both the arrays are sorted while(j != end && (long)*j - (long)*i < (long)k) j++; res += (end - j); } inplace_merge(begin, mid, end); return res; } // calling the main function with a copy of sums array int countGreaterThanK(vector<long> nums, int k) { return countAndSort(nums.begin(), nums.end(), k); } int countRangeSum(vector<int>& nums, int lower, int upper) { int n = nums.size(); vector<long> sums(n, 0); sums[0] = nums[0]; // generating sums sum array for(int i = 1; i < n; ++i) sums[i] += sums[i - 1] + nums[i]; return countGreaterThanK(sums, lower) - countGreaterThanK(sums, upper + 1); } };
#include <iostream> #include <cmath> using namespace std; int main() { const double pi = 3.141592; int radius = 3; double circumference; circumference = 2 * pi * radius; double area1; double area2; area1 = pi * (radius * radius); area2 = pi * pow((double) radius, 2); double volume; volume = (4/3) * pi * (radius * radius * radius); cout << "Circumference: " << circumference << endl; cout << "Area: " << area1 << endl; cout << "Area: " << area2 << endl; cout << "Volume: " << volume << endl; return 0; }
/* * 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. * */ #include "ServiceDelegate.h" namespace fluxnode { class EchoDelegate: public ServiceDelegate { public: static Ref<EchoDelegate> create(ServiceWorker *worker) { return new EchoDelegate(worker); } virtual void process(Request *request) { { Format echo = chunk(); echo << request->method() << " " << request->target() << " " << request->version() << "\r\n"; for (int i = 0; i < request->count(); ++i) echo << request->keyAt(i) << ": " << request->valueAt(i) << "\r\n"; echo << "\r\n"; } Ref<ByteArray> buf = ByteArray::create(0x3FFF); while (true) { int n = request->payload()->read(buf); if (n == 0) break; write(buf->select(0, n)); } } private: EchoDelegate(ServiceWorker *worker) : ServiceDelegate(worker) {} }; } // namespace fluxnode
#include <iostream> #include <iomanip> float sum, x, y; int n; using namespace std; int main() { for (n = 1; n <= 6; n++) { setlocale(LC_CTYPE, "Russian"); printf("Введите x%i: ",n); cin >> x; printf("Введите y%i: ",n); cin >> y; sum += x * y; } printf("Сумма произведений данных x и y равна: %f", sum); }
#ifndef JUNCTION_MESH_GENERATOR_H #define JUNCTION_MESH_GENERATOR_H #include <Data/MultiMesh.h> class JunctionMeshGenerator { private: MyMesh &JunctionMesh; float DeltaUV; // public: // void ParametrizeHalfedge(); // JunctionMeshGenerator(MyMesh &junction_mesh,float delta_uv) :JunctionMesh(junction_mesh),DeltaUV(delta_uv) {} // ~JunctionMeshGenerator() {} /* * End of class */ }; #endif // JUNCTION_MESH_GENERATOR_H
#include "headerFiles/akinatorHeader.h" int main() { Processing(); return 0; }
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ ListNode* Solution::rotateRight(ListNode* A, int B) { if(A==NULL)return A; int len=0; ListNode* head=A; ListNode* tail=A; ListNode* ans=A; while(A) { len++; if(A->next) { tail=A->next; } A=A->next; } B=B%len; if(B==0)return ans; len=len-B-1; ListNode* temp=head; while(len) { len--; temp=temp->next; } tail->next=head; ans=temp->next; temp->next=NULL; return ans; }
/* * The Akafugu Nixie Clock * (C) 2012-13 Akafugu Corporation * * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * */ #include "backlight.h" static uint8_t saved_mode; extern volatile uint8_t g_digits; #if defined(HAVE_RGB_BACKLIGHT) #include "rgbled.h" void fade_in_backlight(int ch) { for (uint16_t i = 0; i <= 4000; i+=10) { pca9685_set_channel(ch, i); delay(1); } } void test_backlight() { fade_in_backlight(0); delay(1000); for (uint8_t i = 1; i < 16; i++) { pca9685_set_channel(i-1, 0); fade_in_backlight(i); delay(1000); } } void init_backlight() { pca9685_wake(); // Turn off all LEDs for (uint8_t i = 0; i < 16; i++) pca9685_set_channel(i, 0); } void set_backlight_mode(uint8_t mode) { saved_mode = mode; set_rgb_mode(mode); } void set_backlight_hh() { set_rgb_mode(0); set_rgb_ch(0, 1000, 1000, 1000); set_rgb_ch(1, 1000, 1000, 1000); } void set_backlight_mm() { set_rgb_mode(0); set_rgb_ch(2, 1000, 1000, 1000); set_rgb_ch(3, 1000, 1000, 1000); } void set_backlight_ss() { set_rgb_mode(0); set_rgb_ch(2, 0, 500, 1000); set_rgb_ch(3, 0, 500, 1000); } void backlight_tick() { rgb_tick(); } #elif defined(HAVE_LED_BACKLIGHT) void set_backlight(uint8_t val) { analogWrite(PinMap::backlight_1, val); analogWrite(PinMap::backlight_2, val); if (PinMap::backlight_3 != -1) analogWrite(PinMap::backlight_3, val); } void set_backlight(uint8_t b1, uint8_t b2, uint8_t b3) { analogWrite(PinMap::backlight_1, b1); analogWrite(PinMap::backlight_2, b2); if (PinMap::backlight_3 != -1) analogWrite(PinMap::backlight_3, b3); } void init_backlight() { // backlight pinMode(PinMap::backlight_1, OUTPUT); pinMode(PinMap::backlight_2, OUTPUT); if (PinMap::backlight_3 != -1) { pinMode(PinMap::backlight_3, OUTPUT); } set_backlight(255); //analogWrite(PinMap::backlight_3, 255); } extern volatile int8_t g_pulse_direction; extern volatile uint16_t g_pulse_value; volatile bool g_pulse; void set_backlight_mode(uint8_t mode) { Serial.print("set_backlight_mode "); Serial.println(mode); saved_mode = mode; g_pulse = false; if (mode == 0) { set_backlight(255); } else if (mode == 1) { set_backlight(0); } else if (mode == 2) { set_backlight(100); } else if (mode == 3) { set_backlight(200); } else if (mode == 4) { set_backlight(0); g_pulse = true; } } void set_backlight_hh() { set_backlight(100, 255, 255); } void set_backlight_mm() { set_backlight(255, 100, 255); } void set_backlight_ss() { if (g_digits == 6) set_backlight(255, 255, 100); else set_backlight(255, 100, 255); } void backlight_tick() { g_pulse_value += g_pulse_direction; if (g_pulse) { set_backlight(255-g_pulse_value); //set_backlight(255-g_pulse_value, 255-g_pulse_value, 255-g_pulse_value); } } #endif // HAVE_RGB_BACKLIGHT / HAVE_LED_BACKLIGHT void increment_backlight_mode() { saved_mode++; if (saved_mode == BACKLIGHT_MODES) saved_mode = 0; set_backlight_mode(saved_mode); } void push_backlight_mode() { uint8_t temp = saved_mode; set_backlight_mode(0); saved_mode = temp; } void pop_backlight_mode() { set_backlight_mode(saved_mode); }
#include "BoostedTTH/BoostedAnalyzer/interface/THQJetSelection.hpp" using namespace std; THQJetSelection::THQJetSelection (){} THQJetSelection::~THQJetSelection (){} void THQJetSelection::InitCutflow(Cutflow& cutflow){ cutflow.AddStep(">= 4 single top jets >= 30 GeV"); cutflow.AddStep(">= 3 b-tagged single top jets"); cutflow.AddStep(">= 1 untagged single top jet"); initialized=true; } bool THQJetSelection::IsSelected(const InputCollections& input,Cutflow& cutflow){ if(!initialized) cerr << "THQJetSelection not initialized" << endl; int njets30=0; int ntags=0; int nuntagged=0; for(auto j=input.selectedJetsSingleTop.begin(); j!=input.selectedJetsSingleTop.end(); j++){ if(j->pt()>30) njets30++; if(fabs(j->eta())<2.4&&BoostedUtils::PassesCSV(*j,'T')) ntags++; else nuntagged++; } if(njets30>=4){ cutflow.EventSurvivedStep(">= 4 single top jets >= 30 GeV",input.weights.at("Weight")); } else{ return false; } if(ntags>=3){ cutflow.EventSurvivedStep(">= 3 b-tagged single top jets",input.weights.at("Weight")); } else{ return false; } if(nuntagged>1){ cutflow.EventSurvivedStep(">= 1 untagged single top jet",input.weights.at("Weight")); } else{ return false; } return true; }
#include <iostream> using namespace std; /** * Leia um valor inteiro N. Este valor será a quantidade de valores * inteiros X que serão lidos em seguida. Mostre, ao final do programa, * quantos destes valores X estão dentro do intervalo [10,20] * e quantos estão fora do intervalo */ int main () { int n, x, lims=20, limi=10, contdentro=0, contfora=0; // le um valor digitado pelo usuario que determina quantos valores serao lidos cout<<"Digite um numero n: "<<endl; cin>>n; for (int i=1; i<=n; i++) { // le um valor digitado pelo usuario cout<<"Digite um numero x: "<<endl; cin>>x; // verifica se o numero estao no intervalo [10, 20] if(x<=lims && x>=limi) // total de valores compreendidos no intervalo [10, 20] contdentro++; else // total de valores nao compreendidos no intervalo [10, 20] contfora++; } // imprime os totais calculados cout<<"Total de numeros dentro do intervalo: "<<contdentro<<endl; cout<<"Total de numeros fora do intervalo: "<<contfora<<endl; return 0; }
#ifndef _HS_SFM_SFM_PIPELINE_GCP_SIMILAR_TRANSFORM_ESTIMATOR_HPP_ #define _HS_SFM_SFM_PIPELINE_GCP_SIMILAR_TRANSFORM_ESTIMATOR_HPP_ #include "hs_math/linear_algebra/eigen_macro.hpp" #include "hs_sfm/sfm_utility/camera_type.hpp" #include "hs_sfm/sfm_utility/key_type.hpp" #include "hs_sfm/sfm_utility/match_type.hpp" #include "hs_sfm/sfm_utility/similar_transform_estimator.hpp" #include "hs_sfm/sfm_pipeline/point_expandor.hpp" namespace hs { namespace sfm { namespace pipeline { template <typename _Scalar> class GCPSimilarTransformEstimator { public: typedef _Scalar Scalar; typedef int Err; typedef CameraExtrinsicParams<Scalar> ExtrinsicParams; typedef CameraIntrinsicParams<Scalar> IntrinsicParams; typedef EIGEN_STD_VECTOR(ExtrinsicParams) ExtrinsicParamsContainer; typedef EIGEN_STD_VECTOR(IntrinsicParams) IntrinsicParamsContainer; typedef ImageKeys<Scalar> Keyset; typedef EIGEN_STD_VECTOR(Keyset) KeysetContainer; typedef EIGEN_VECTOR(Scalar, 3) Point; typedef EIGEN_STD_VECTOR(Point) PointContainer; private: typedef hs::sfm::SimilarTransformEstimator<Scalar> SimilarTransformEstimator; public: typedef hs::sfm::triangulate::MultipleViewMaximumLikelihoodEstimator<Scalar> TriangulateMLEstimator; typedef typename TriangulateMLEstimator::Key Key; typedef typename TriangulateMLEstimator::KeyContainer KeyContainer; typedef typename SimilarTransformEstimator::Rotation Rotation; typedef typename SimilarTransformEstimator::Translate Translate; public: Err operator() (const KeysetContainer& keysets_gcp, const IntrinsicParamsContainer& intrinsic_params_set, const ExtrinsicParamsContainer& extrinsic_params_set, const hs::sfm::TrackContainer& tracks_gcp, const PointContainer& gcps, const hs::sfm::ObjectIndexMap& image_intrinsic_map, const hs::sfm::ObjectIndexMap& image_extrinsic_map, size_t min_triangulate_views, Scalar triangulate_error_threshold, Rotation& rotation_similar, Translate& translate_similar, Scalar& scale_similar, hs::sfm::ObjectIndexMap& track_point_map_gcp, PointContainer& gcps_relative) const { //计算像控点在相对坐标系下的坐标 size_t number_of_gcps = tracks_gcp.size(); if (gcps.size() != number_of_gcps) { std::cout<<"Error:-1\n"; return -1; } track_point_map_gcp.Resize(number_of_gcps); gcps_relative.clear(); for (size_t track_id = 0; track_id < tracks_gcp.size(); track_id++) { size_t number_of_views = tracks_gcp[track_id].size(); hs::sfm::Track track_views; for (size_t i = 0; i < number_of_views; i++) { size_t image_id = tracks_gcp[track_id][i].first; if (image_extrinsic_map.IsValid(image_id)) { track_views.push_back(tracks_gcp[track_id][i]); } } if (track_views.size() >= min_triangulate_views) { size_t track_size = track_views.size(); IntrinsicParamsContainer intrinsic_params_set_view(track_size); ExtrinsicParamsContainer extrinsic_params_set_view(track_size); KeyContainer keys(track_size); for (size_t i = 0; i < track_size; i++) { size_t image_id = track_views[i].first; size_t key_id = track_views[i].second; size_t intrinsic_id = image_intrinsic_map[image_id]; size_t extrinsic_id = image_extrinsic_map[image_id]; intrinsic_params_set_view[i] = intrinsic_params_set[intrinsic_id]; extrinsic_params_set_view[i] = extrinsic_params_set[extrinsic_id]; keys[i] = keysets_gcp[image_id][key_id]; } TriangulateMLEstimator estimator; Point point; if (estimator(intrinsic_params_set_view, extrinsic_params_set_view, keys, point) == 0) { gcps_relative.push_back(point); track_point_map_gcp[track_id] = gcps_relative.size() - 1; } } } //计算相似变换 size_t number_of_available_gcps = gcps_relative.size(); if (number_of_available_gcps < 4) { std::cout<<"Error:-3\n"; return -1; } PointContainer gcps_absolute(number_of_available_gcps); for (size_t i = 0; i < number_of_gcps; i++) { if (track_point_map_gcp.IsValid(i)) { gcps_absolute[track_point_map_gcp[i]] = gcps[i]; } } SimilarTransformEstimator transform_estimator; if (transform_estimator(gcps_relative, gcps_absolute, rotation_similar, translate_similar, scale_similar) != 0) { std::cout<<"Error:-4\n"; return -1; } #ifdef _DEBUG for (size_t i = 0; i < number_of_available_gcps; i++) { Point gcp_abs = gcps_relative[i]; gcp_abs = scale_similar * (rotation_similar * gcp_abs) + translate_similar; Point diff = gcp_abs - gcps_absolute[i]; int bp = 0; } #endif return 0; } }; } } } #endif
#include "Patcher_UseDataFolder.h" #include "../Addr.h" #include "../FileSystem.h" //----------------------------------------------------------------------------- // Constructor CPatcher_UseDataFolder::CPatcher_UseDataFolder( void ) { patchname = "Use Data Folder"; LPBYTE addrSetLookUpOrder = CAddr::Addr(CFileSystem_SetLookUpOrder); if (!addrSetLookUpOrder) { WriteLog("Patch initialization failed: %s.\n", patchname.c_str()); WriteLog(" Missing dependency.\n"); return; } vector<WORD> patch; vector<WORD> backup; backup += 0x8B, 0x45, 0xEC, // MOV EAX, [EBP-14h] 0x8B, 0x40, 0x04, // MOV EAX, [EAX+04h] 0x8B, 0x40, 0x18, // MOV EAX, [EAX+18h] 0x83, 0xE8, 0x01; // SUB EAX, 0 (wat?) patch += -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0x00; // SUB EAX, 0 => SUB EAX, 1 MemoryPatch mp( addrSetLookUpOrder + 0xAF, patch, backup ); patches += mp; if (CheckPatches()) WriteLog("Patch initialization successful: %s.\n", patchname.c_str()); else WriteLog("Patch initialization failed: %s.\n", patchname.c_str()); } //----------------------------------------------------------------------------- // INI Functions bool CPatcher_UseDataFolder::ReadINI( void ) { if ( ReadINI_Bool( L"DisableDataFolder" )) return Install(); return true; } bool CPatcher_UseDataFolder::WriteINI( void ) { WriteINI_Bool( L"DisableDataFolder", IsInstalled() ); return true; }
// Filename: cPetBrain.h // Created by: darren (13Jul04) // //////////////////////////////////////////////////////////////////// #include "cPetBrain.h" #include "luse.h" //////////////////////////////////////////////////////////////////// // Function: CPetBrain::Constructor // Access: Published // Description: //////////////////////////////////////////////////////////////////// CPetBrain:: CPetBrain() { } //////////////////////////////////////////////////////////////////// // Function: CPetBrain::is_attending_us // Access: Published // Description: Calculates whether another avatar is paying // attention to us //////////////////////////////////////////////////////////////////// bool CPetBrain:: is_attending_us(NodePath &us, NodePath &them) { LVector3f avRelPos(them.get_pos(us)); float distSq = avRelPos.length_squared(); //cerr << "distSq " << distSq << endl; if (distSq > 100) { return false; } LVector3f selfRelPos(us.get_pos(them)); selfRelPos.normalize(); float dot = selfRelPos.dot(selfRelPos.forward()); //cerr << "dot " << dot << endl; if (dot < .8) { return false; } return true; }
#include "facerecognize.hpp" #include "caffe_mtcnn.hpp" #include "preprocess.h" #include "face_align.hpp" #include "scale_angle.h" #include "opencv2/opencv.hpp" #include "opencv2/core/core_c.h" #include "opencv2/core/types_c.h" #include <chrono> #include <time.h> #include <string.h> #include <stdlib.h> #include<sys/time.h> #define UNKNOWN_FACE_ID_MAX 1000 #ifndef CV_BGR2GRAY #define CV_BGR2GRAY COLOR_BGR2GRAY #define cvPoint CvPoint #endif static bool GreaterSort (FaceBox a, FaceBox b) { return (abs(a.x1 - a.x0) * (a.y1 - a.y0) > abs((b.x1 - b.x0) * (b.y1 - b.y0))); } /*****************************************************************************************************/ FaceRecognize::FaceRecognize(const std::string& _dir,int mode){ pmtcnn = new caffe_mtcnn(); pmtcnn->load_3model(_dir); mfnet=new MobileFacenet(_dir); vanface=new VanFace(_dir); feature_len=0; std::cout<<"mtcnn="<<pmtcnn<<" mfnet="<<mfnet<<" vanface="<<vanface<<std::endl; #ifndef NDEBUG verbose=1; #endif } /* *P-net R-net O-net *P-net :Proposal Network select face's bound,NMS *R-net :Refine Network *O-net :Output Network last step get landmark positions *threshold_score:the score used by (face verifier)feature compare * */ int FaceRecognize::Init(double theshold_p, double theshold_r, double theshold_o, double threshold_score, double factor, int min_size) { pmtcnn->set_threshold(theshold_p, theshold_r, theshold_o); pmtcnn->set_factor_min_size(factor, min_size); //agc.Init(); return 0; } void FaceRecognize::SetThreshold(float threshold_p,float threshold_r,float threshold_o) { pmtcnn->set_threshold(threshold_p, threshold_r, threshold_o); } void FaceRecognize::SetFactorMinFace(float factor,int min_size){ pmtcnn->set_factor_min_size(factor, min_size); } bool FaceRecognize::AlignedFace(Mat&frame,FaceBox &fb,int width,int height,Mat&aligned){ return get_aligned_face(frame,(float*)&fb.landmark,5,width,height,aligned); } void FaceRecognize::GetAgeGender(cv::Mat&frame, FaceBox &b,int*age,int*gender) { float pad=(b.landmark[6]-b.landmark[5]); float padlr=pad*1.3f; float padtop=pad*2.5f; float padbt=pad*1.5f; cv::Rect r(b.x0-padlr,b.y0-padtop,b.x1-b.x0+padlr+padlr,b.y1-b.y0+padtop+padbt); if( (r.x<0) || (r.x+r.width>frame.cols) || (r.y<0) || (r.y+r.height>frame.rows) ) return; struct timeval tv_start; cv::Mat face(frame,r); gettimeofday(&tv_start,NULL); //agc.GetAgeGender(face,age,gender); if(verbose){ struct timeval tv_end; gettimeofday(&tv_end, NULL); std::cout<<"GetAgeGender's time:"<<tv_end.tv_sec * 1000 + tv_end.tv_usec / 1000 - tv_start.tv_sec * 1000 - tv_start.tv_usec / 1000<<std::endl; } } int FaceRecognize::Detect(cv::Mat &frame,std::vector<FaceBox>&boxes,bool landmark68){ struct timeval tv_start; gettimeofday(&tv_start,NULL); pmtcnn->detect(frame,boxes); if(landmark68 &&boxes.size()>0) vanface->GetLandmark(frame,boxes); if(verbose){ struct timeval tv_end; gettimeofday(&tv_end, NULL); std::cout<<"Detect's time:"<<tv_end.tv_sec*1000 + tv_end.tv_usec/1000 - tv_start.tv_sec*1000 - tv_start.tv_usec/1000<<std::endl; } return boxes.size(); } int FaceRecognize::GetFeature(cv::Mat& frame,FaceBox& fb,std::vector<float>& feature){ float fbuf[512]; int rc=mfnet->GetFeature(frame,fb,fbuf); feature.resize(rc); for(int i=0;i<rc;i++)feature[i]=fbuf[i]; return rc; } int FaceRecognize::GetFeature(cv::Mat& frame,FaceBox &box,float* feature,int fsize){ return get_feature(frame,box,feature,fsize); } int FaceRecognize::get_feature(cv::Mat& frame,FaceBox &box,float* feature,int fsize){ struct timeval tv_start; gettimeofday(&tv_start,NULL); int ret=mfnet->GetFeature(frame,box,feature); if(verbose){ struct timeval tv_end; gettimeofday(&tv_end, NULL); std::cout<<"GetFeature's time:"<<tv_end.tv_sec*1000 + tv_end.tv_usec/1000 - tv_start.tv_sec*1000 - tv_start.tv_usec/1000<<std::endl; } return ret; } int FaceRecognize::GetFeatureLength(){ return mfnet->GetFeatureLen(); } void FaceRecognize::FaceMatch(const float*feature1,const float*feature2, float*match_score) { int feature_len=GetFeatureLength(); cv::Mat m1(feature_len, 1, CV_32FC1, (void*)feature1), m2(feature_len, 1, CV_32FC1, (void*)feature2); *match_score= m1.dot(m2) / cv::norm(m1, CV_L2) / cv::norm(m2, CV_L2); } void drawLandmark(cv::Mat frame,FaceBox fb,int start,int num,bool closed){ std::vector<cv::Point> points; for(int i=start,j=0;j<num;i++,j++){ points.push_back(cv::Point(fb.landmark68[i],fb.landmark68[i+68])); } cv::polylines(frame,points,closed,Scalar(0,0,255));//,1,8,0); } void FaceRecognize::LableFace(Mat&frame,FaceBox& box,Scalar color){ cv::rectangle(frame,cvPoint(box.x0,box.y0),cvPoint(box.x1,box.y1),color,1); for(int i=0;i<5;i++){ cv::circle(frame,cvPoint(box.landmark[i],box.landmark[i+5]),2,color,-1); } if(box.landmark68[0]!=.0f&&box.landmark68[1]!=.0f){ drawLandmark(frame, box, 0, 17, false); drawLandmark(frame, box, 17, 5, false);//eyeblow_right drawLandmark(frame, box, 22, 5, false);//eyebrow_left drawLandmark(frame, box, 27, 4, false);//nose bridge drawLandmark(frame, box, 30, 6, true);//nose drawLandmark(frame, box, 36, 6, true);//eye_right drawLandmark(frame, box, 42, 6, true);//eye_left drawLandmark(frame, box, 48, 12,true);//mouse outter drawLandmark(frame, box, 60, 8, true); } } void FaceRecognize::LableFaces(cv::Mat &frame,std::vector<FaceBox>&boxes,Scalar color) { for(size_t i=0;i<boxes.size();i++) LableFace(frame,boxes[i],color); }
// Copyright (c) Facebook, Inc. and its affiliates. // All rights reserved. // // Copyright 2019 Google LLC // // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. // // Auto-generated file. Do not edit! // Specification: test/q8-dwconv.yaml // Generator: tools/generate-dwconv-test.py #include <gtest/gtest.h> #include <xnnpack/common.h> #include <xnnpack/isa-checks.h> #include <xnnpack/dwconv.h> #include "dwconv-microkernel-tester.h" #if XNN_ARCH_ARM TEST(Q8_DWCONV_UP8X9__AARCH32_NEON, c_eq_8) { TEST_REQUIRES_ARM_NEON; DWConvMicrokernelTester() .cr(8) .kr(9) .channels(8) .Test(xnn_q8_dwconv_ukernel_up8x9__aarch32_neon); } TEST(Q8_DWCONV_UP8X9__AARCH32_NEON, c_div_8) { TEST_REQUIRES_ARM_NEON; for (uint32_t channels = 16; channels < 128; channels += 24) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .Test(xnn_q8_dwconv_ukernel_up8x9__aarch32_neon); } } TEST(Q8_DWCONV_UP8X9__AARCH32_NEON, c_div_8_with_qmin) { TEST_REQUIRES_ARM_NEON; for (uint32_t channels = 16; channels < 128; channels += 24) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .qmin(128) .Test(xnn_q8_dwconv_ukernel_up8x9__aarch32_neon); } } TEST(Q8_DWCONV_UP8X9__AARCH32_NEON, c_div_8_with_qmax) { TEST_REQUIRES_ARM_NEON; for (uint32_t channels = 16; channels < 128; channels += 24) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .qmax(128) .Test(xnn_q8_dwconv_ukernel_up8x9__aarch32_neon); } } TEST(Q8_DWCONV_UP8X9__AARCH32_NEON, c_lt_8) { TEST_REQUIRES_ARM_NEON; for (uint32_t channels = 1; channels < 8; channels++) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .Test(xnn_q8_dwconv_ukernel_up8x9__aarch32_neon); } } TEST(Q8_DWCONV_UP8X9__AARCH32_NEON, c_gt_8) { TEST_REQUIRES_ARM_NEON; for (uint32_t channels = 9; channels < 16; channels++) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .Test(xnn_q8_dwconv_ukernel_up8x9__aarch32_neon); } } TEST(Q8_DWCONV_UP8X9__AARCH32_NEON, c_gt_8_with_qmin) { TEST_REQUIRES_ARM_NEON; for (uint32_t channels = 9; channels < 16; channels++) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .qmin(128) .Test(xnn_q8_dwconv_ukernel_up8x9__aarch32_neon); } } TEST(Q8_DWCONV_UP8X9__AARCH32_NEON, c_gt_8_with_qmax) { TEST_REQUIRES_ARM_NEON; for (uint32_t channels = 9; channels < 16; channels++) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .qmax(128) .Test(xnn_q8_dwconv_ukernel_up8x9__aarch32_neon); } } TEST(Q8_DWCONV_UP8X9__AARCH32_NEON, multipixel) { TEST_REQUIRES_ARM_NEON; for (size_t channels = 1; channels <= 40; channels += 7) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .width(3) .Test(xnn_q8_dwconv_ukernel_up8x9__aarch32_neon); } } TEST(Q8_DWCONV_UP8X9__AARCH32_NEON, multipixel_with_step) { TEST_REQUIRES_ARM_NEON; for (size_t channels = 1; channels <= 40; channels += 7) { for (size_t step = 2; step <= 9; step++) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .width(3) .step(step) .Test(xnn_q8_dwconv_ukernel_up8x9__aarch32_neon); } } } TEST(Q8_DWCONV_UP8X9__AARCH32_NEON, multipixel_with_output_stride) { TEST_REQUIRES_ARM_NEON; for (size_t channels = 1; channels <= 40; channels += 7) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(8) .width(5) .output_stride(43) .Test(xnn_q8_dwconv_ukernel_up8x9__aarch32_neon); } } TEST(Q8_DWCONV_UP8X9__AARCH32_NEON, multipixel_with_qmin) { TEST_REQUIRES_ARM_NEON; for (size_t channels = 1; channels <= 40; channels += 7) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .width(3) .qmin(128) .Test(xnn_q8_dwconv_ukernel_up8x9__aarch32_neon); } } TEST(Q8_DWCONV_UP8X9__AARCH32_NEON, multipixel_with_qmax) { TEST_REQUIRES_ARM_NEON; for (size_t channels = 1; channels <= 40; channels += 7) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .width(3) .qmax(128) .Test(xnn_q8_dwconv_ukernel_up8x9__aarch32_neon); } } TEST(Q8_DWCONV_UP8X9__AARCH32_NEON, input_zero_point_only) { TEST_REQUIRES_ARM_NEON; for (size_t channels = 1; channels <= 40; channels += 7) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .width(3) .input_zero_point(255) .kernel_zero_point(0) .Test(xnn_q8_dwconv_ukernel_up8x9__aarch32_neon); } } TEST(Q8_DWCONV_UP8X9__AARCH32_NEON, kernel_zero_point_only) { TEST_REQUIRES_ARM_NEON; for (size_t channels = 1; channels <= 40; channels += 7) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .width(3) .input_zero_point(0) .kernel_zero_point(255) .Test(xnn_q8_dwconv_ukernel_up8x9__aarch32_neon); } } #endif // XNN_ARCH_ARM #if XNN_ARCH_ARM || XNN_ARCH_ARM64 TEST(Q8_DWCONV_UP8X9__NEON, c_eq_8) { TEST_REQUIRES_ARM_NEON; DWConvMicrokernelTester() .cr(8) .kr(9) .channels(8) .Test(xnn_q8_dwconv_ukernel_up8x9__neon); } TEST(Q8_DWCONV_UP8X9__NEON, c_div_8) { TEST_REQUIRES_ARM_NEON; for (uint32_t channels = 16; channels < 128; channels += 24) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .Test(xnn_q8_dwconv_ukernel_up8x9__neon); } } TEST(Q8_DWCONV_UP8X9__NEON, c_div_8_with_qmin) { TEST_REQUIRES_ARM_NEON; for (uint32_t channels = 16; channels < 128; channels += 24) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .qmin(128) .Test(xnn_q8_dwconv_ukernel_up8x9__neon); } } TEST(Q8_DWCONV_UP8X9__NEON, c_div_8_with_qmax) { TEST_REQUIRES_ARM_NEON; for (uint32_t channels = 16; channels < 128; channels += 24) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .qmax(128) .Test(xnn_q8_dwconv_ukernel_up8x9__neon); } } TEST(Q8_DWCONV_UP8X9__NEON, c_lt_8) { TEST_REQUIRES_ARM_NEON; for (uint32_t channels = 1; channels < 8; channels++) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .Test(xnn_q8_dwconv_ukernel_up8x9__neon); } } TEST(Q8_DWCONV_UP8X9__NEON, c_gt_8) { TEST_REQUIRES_ARM_NEON; for (uint32_t channels = 9; channels < 16; channels++) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .Test(xnn_q8_dwconv_ukernel_up8x9__neon); } } TEST(Q8_DWCONV_UP8X9__NEON, c_gt_8_with_qmin) { TEST_REQUIRES_ARM_NEON; for (uint32_t channels = 9; channels < 16; channels++) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .qmin(128) .Test(xnn_q8_dwconv_ukernel_up8x9__neon); } } TEST(Q8_DWCONV_UP8X9__NEON, c_gt_8_with_qmax) { TEST_REQUIRES_ARM_NEON; for (uint32_t channels = 9; channels < 16; channels++) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .qmax(128) .Test(xnn_q8_dwconv_ukernel_up8x9__neon); } } TEST(Q8_DWCONV_UP8X9__NEON, multipixel) { TEST_REQUIRES_ARM_NEON; for (size_t channels = 1; channels <= 40; channels += 7) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .width(3) .Test(xnn_q8_dwconv_ukernel_up8x9__neon); } } TEST(Q8_DWCONV_UP8X9__NEON, multipixel_with_step) { TEST_REQUIRES_ARM_NEON; for (size_t channels = 1; channels <= 40; channels += 7) { for (size_t step = 2; step <= 9; step++) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .width(3) .step(step) .Test(xnn_q8_dwconv_ukernel_up8x9__neon); } } } TEST(Q8_DWCONV_UP8X9__NEON, multipixel_with_output_stride) { TEST_REQUIRES_ARM_NEON; for (size_t channels = 1; channels <= 40; channels += 7) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(8) .width(5) .output_stride(43) .Test(xnn_q8_dwconv_ukernel_up8x9__neon); } } TEST(Q8_DWCONV_UP8X9__NEON, multipixel_with_qmin) { TEST_REQUIRES_ARM_NEON; for (size_t channels = 1; channels <= 40; channels += 7) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .width(3) .qmin(128) .Test(xnn_q8_dwconv_ukernel_up8x9__neon); } } TEST(Q8_DWCONV_UP8X9__NEON, multipixel_with_qmax) { TEST_REQUIRES_ARM_NEON; for (size_t channels = 1; channels <= 40; channels += 7) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .width(3) .qmax(128) .Test(xnn_q8_dwconv_ukernel_up8x9__neon); } } TEST(Q8_DWCONV_UP8X9__NEON, input_zero_point_only) { TEST_REQUIRES_ARM_NEON; for (size_t channels = 1; channels <= 40; channels += 7) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .width(3) .input_zero_point(255) .kernel_zero_point(0) .Test(xnn_q8_dwconv_ukernel_up8x9__neon); } } TEST(Q8_DWCONV_UP8X9__NEON, kernel_zero_point_only) { TEST_REQUIRES_ARM_NEON; for (size_t channels = 1; channels <= 40; channels += 7) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .width(3) .input_zero_point(0) .kernel_zero_point(255) .Test(xnn_q8_dwconv_ukernel_up8x9__neon); } } #endif // XNN_ARCH_ARM || XNN_ARCH_ARM64 #if XNN_ARCH_X86 || XNN_ARCH_X86_64 TEST(Q8_DWCONV_UP8X9__SSE2, c_eq_8) { TEST_REQUIRES_X86_SSE2; DWConvMicrokernelTester() .cr(8) .kr(9) .channels(8) .Test(xnn_q8_dwconv_ukernel_up8x9__sse2); } TEST(Q8_DWCONV_UP8X9__SSE2, c_div_8) { TEST_REQUIRES_X86_SSE2; for (uint32_t channels = 16; channels < 128; channels += 24) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .Test(xnn_q8_dwconv_ukernel_up8x9__sse2); } } TEST(Q8_DWCONV_UP8X9__SSE2, c_div_8_with_qmin) { TEST_REQUIRES_X86_SSE2; for (uint32_t channels = 16; channels < 128; channels += 24) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .qmin(128) .Test(xnn_q8_dwconv_ukernel_up8x9__sse2); } } TEST(Q8_DWCONV_UP8X9__SSE2, c_div_8_with_qmax) { TEST_REQUIRES_X86_SSE2; for (uint32_t channels = 16; channels < 128; channels += 24) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .qmax(128) .Test(xnn_q8_dwconv_ukernel_up8x9__sse2); } } TEST(Q8_DWCONV_UP8X9__SSE2, c_lt_8) { TEST_REQUIRES_X86_SSE2; for (uint32_t channels = 1; channels < 8; channels++) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .Test(xnn_q8_dwconv_ukernel_up8x9__sse2); } } TEST(Q8_DWCONV_UP8X9__SSE2, c_gt_8) { TEST_REQUIRES_X86_SSE2; for (uint32_t channels = 9; channels < 16; channels++) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .Test(xnn_q8_dwconv_ukernel_up8x9__sse2); } } TEST(Q8_DWCONV_UP8X9__SSE2, c_gt_8_with_qmin) { TEST_REQUIRES_X86_SSE2; for (uint32_t channels = 9; channels < 16; channels++) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .qmin(128) .Test(xnn_q8_dwconv_ukernel_up8x9__sse2); } } TEST(Q8_DWCONV_UP8X9__SSE2, c_gt_8_with_qmax) { TEST_REQUIRES_X86_SSE2; for (uint32_t channels = 9; channels < 16; channels++) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .qmax(128) .Test(xnn_q8_dwconv_ukernel_up8x9__sse2); } } TEST(Q8_DWCONV_UP8X9__SSE2, multipixel) { TEST_REQUIRES_X86_SSE2; for (size_t channels = 1; channels <= 40; channels += 7) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .width(3) .Test(xnn_q8_dwconv_ukernel_up8x9__sse2); } } TEST(Q8_DWCONV_UP8X9__SSE2, multipixel_with_step) { TEST_REQUIRES_X86_SSE2; for (size_t channels = 1; channels <= 40; channels += 7) { for (size_t step = 2; step <= 9; step++) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .width(3) .step(step) .Test(xnn_q8_dwconv_ukernel_up8x9__sse2); } } } TEST(Q8_DWCONV_UP8X9__SSE2, multipixel_with_output_stride) { TEST_REQUIRES_X86_SSE2; for (size_t channels = 1; channels <= 40; channels += 7) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(8) .width(5) .output_stride(43) .Test(xnn_q8_dwconv_ukernel_up8x9__sse2); } } TEST(Q8_DWCONV_UP8X9__SSE2, multipixel_with_qmin) { TEST_REQUIRES_X86_SSE2; for (size_t channels = 1; channels <= 40; channels += 7) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .width(3) .qmin(128) .Test(xnn_q8_dwconv_ukernel_up8x9__sse2); } } TEST(Q8_DWCONV_UP8X9__SSE2, multipixel_with_qmax) { TEST_REQUIRES_X86_SSE2; for (size_t channels = 1; channels <= 40; channels += 7) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .width(3) .qmax(128) .Test(xnn_q8_dwconv_ukernel_up8x9__sse2); } } TEST(Q8_DWCONV_UP8X9__SSE2, input_zero_point_only) { TEST_REQUIRES_X86_SSE2; for (size_t channels = 1; channels <= 40; channels += 7) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .width(3) .input_zero_point(255) .kernel_zero_point(0) .Test(xnn_q8_dwconv_ukernel_up8x9__sse2); } } TEST(Q8_DWCONV_UP8X9__SSE2, kernel_zero_point_only) { TEST_REQUIRES_X86_SSE2; for (size_t channels = 1; channels <= 40; channels += 7) { DWConvMicrokernelTester() .cr(8) .kr(9) .channels(channels) .width(3) .input_zero_point(0) .kernel_zero_point(255) .Test(xnn_q8_dwconv_ukernel_up8x9__sse2); } } #endif // XNN_ARCH_X86 || XNN_ARCH_X86_64 TEST(Q8_DWCONV_UP1X9__SCALAR, c_eq_1) { DWConvMicrokernelTester() .cr(1) .kr(9) .channels(1) .Test(xnn_q8_dwconv_ukernel_up1x9__scalar, DWConvMicrokernelTester::Variant::Scalar); } TEST(Q8_DWCONV_UP1X9__SCALAR, c_gt_1) { for (uint32_t channels = 2; channels < 10; channels++) { DWConvMicrokernelTester() .cr(1) .kr(9) .channels(channels) .Test(xnn_q8_dwconv_ukernel_up1x9__scalar, DWConvMicrokernelTester::Variant::Scalar); } } TEST(Q8_DWCONV_UP1X9__SCALAR, c_gt_1_with_qmin) { for (uint32_t channels = 2; channels < 10; channels++) { DWConvMicrokernelTester() .cr(1) .kr(9) .channels(channels) .qmin(128) .Test(xnn_q8_dwconv_ukernel_up1x9__scalar, DWConvMicrokernelTester::Variant::Scalar); } } TEST(Q8_DWCONV_UP1X9__SCALAR, c_gt_1_with_qmax) { for (uint32_t channels = 2; channels < 10; channels++) { DWConvMicrokernelTester() .cr(1) .kr(9) .channels(channels) .qmax(128) .Test(xnn_q8_dwconv_ukernel_up1x9__scalar, DWConvMicrokernelTester::Variant::Scalar); } } TEST(Q8_DWCONV_UP1X9__SCALAR, multipixel) { for (size_t channels = 1; channels <= 5; channels += 1) { DWConvMicrokernelTester() .cr(1) .kr(9) .channels(channels) .width(3) .Test(xnn_q8_dwconv_ukernel_up1x9__scalar, DWConvMicrokernelTester::Variant::Scalar); } } TEST(Q8_DWCONV_UP1X9__SCALAR, multipixel_with_step) { for (size_t channels = 1; channels <= 5; channels += 1) { for (size_t step = 2; step <= 9; step++) { DWConvMicrokernelTester() .cr(1) .kr(9) .channels(channels) .width(3) .step(step) .Test(xnn_q8_dwconv_ukernel_up1x9__scalar, DWConvMicrokernelTester::Variant::Scalar); } } } TEST(Q8_DWCONV_UP1X9__SCALAR, multipixel_with_output_stride) { for (size_t channels = 1; channels <= 5; channels += 1) { DWConvMicrokernelTester() .cr(1) .kr(9) .channels(1) .width(5) .output_stride(7) .Test(xnn_q8_dwconv_ukernel_up1x9__scalar, DWConvMicrokernelTester::Variant::Scalar); } } TEST(Q8_DWCONV_UP1X9__SCALAR, multipixel_with_qmin) { for (size_t channels = 1; channels <= 5; channels += 1) { DWConvMicrokernelTester() .cr(1) .kr(9) .channels(channels) .width(3) .qmin(128) .Test(xnn_q8_dwconv_ukernel_up1x9__scalar, DWConvMicrokernelTester::Variant::Scalar); } } TEST(Q8_DWCONV_UP1X9__SCALAR, multipixel_with_qmax) { for (size_t channels = 1; channels <= 5; channels += 1) { DWConvMicrokernelTester() .cr(1) .kr(9) .channels(channels) .width(3) .qmax(128) .Test(xnn_q8_dwconv_ukernel_up1x9__scalar, DWConvMicrokernelTester::Variant::Scalar); } } TEST(Q8_DWCONV_UP1X9__SCALAR, input_zero_point_only) { for (size_t channels = 1; channels <= 5; channels += 1) { DWConvMicrokernelTester() .cr(1) .kr(9) .channels(channels) .width(3) .input_zero_point(255) .kernel_zero_point(0) .Test(xnn_q8_dwconv_ukernel_up1x9__scalar, DWConvMicrokernelTester::Variant::Scalar); } } TEST(Q8_DWCONV_UP1X9__SCALAR, kernel_zero_point_only) { for (size_t channels = 1; channels <= 5; channels += 1) { DWConvMicrokernelTester() .cr(1) .kr(9) .channels(channels) .width(3) .input_zero_point(0) .kernel_zero_point(255) .Test(xnn_q8_dwconv_ukernel_up1x9__scalar, DWConvMicrokernelTester::Variant::Scalar); } }
#include <iostream> #include <fstream> #include <vector> #include <cstdlib> #include "omp.h" #include <algorithm> #include <list> #include <string> #include <map> #include <numeric> #include <math.h> std::vector<int> vectore; std::map<int, int> user; std::list<double> list; // Funcion cambia formato hora 00 std::string chrs (std::string pors) { int porsi = std::stoi(pors); if (porsi < 10) { pors = "0" + pors; } return pors; } // Funcion compara y cuenta registros por hora std::map<int, unsigned int> counter(const std::vector<int>& vals) { std::map<int, unsigned int> rv; for (auto val = vals.begin(); val != vals.end(); ++val) { rv[*val]++; } return rv; } // Funcion crea archivo csv a partir del mapa void display(const std::map<int, unsigned int>& counts) { std::ofstream csv; csv.open("resultado.csv"); //abre archivo desde ruta std::string line; //crea string para guardar linea de txt #pragma omp parallel { #pragma omp single { csv << "Hora;Cantidad" << std::endl; for (auto count = counts.begin(); count != counts.end(); ++count) { #pragma omp task { std::string key = std::to_string(count->first); std::string value = std::to_string(count->second); line = chrs(key) + ";" + value; #pragma omp critical csv << line << std::endl; } } } } csv.close(); } auto lectura(std::string path) { std::vector<int> vec; std::string file_path = path; std::ifstream csv; csv.open(file_path); std::string line; while (csv.peek() != EOF) { getline(csv, line); line.erase(std::remove(line.begin(), line.end(), '\n'), line.end()); std::string ext = line.substr(line.find(":")+1, 2); int exti = std::stoi(ext); vec.push_back(exti); } csv.close(); return vec; } int main() { vectore = lectura("/Compartido/archivo/access.log"); // Cambiar por ruta del archivo access.log display(counter(vectore)); return 0; }
#pragma once #include <vector> #include "Datastructs.h" #include "Model.h" #include "OBJimporter.h" #include "LightSource.h" #include "Compute.h" #include "QuadTree.h" #include <iostream> #include <SDL\SDL.h> #include <GL/glew.h> #include <Windows.h> #include "Player.h" #include "GLSLprogram.h" class App { private: SDL_Window* window; Player _player; QuadTree* quadTree; int screen_height; int screen_width; void init(); void initShader(); void render(); void createScreenQuad(); void drawOnScreenQuad(); void gaussiate(); void deferredDraw(); std::vector<Model*> models; Model* terrain; OBJimporter* importer; GLuint screen; LightSource lights; Compute gaussianFilter; GLuint gaussianTexture; void initGaussTex(); GLSLprogram _colorProgram; GLSLprogram _deferredProgram; GLSLprogram testProgram; GLSLprogram _wireFrameProgram; public: App(); ~App(); void update(float deltaTime); };
// github.com/andy489 // https://www.spoj.com/problems/LCA/ #include <iostream> #include <vector> #include <list> using namespace std; #define ios ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr) #define pb push_back int timer, n, N, K; vector<list<int>> adj; vector<int> first, euler, dep, flog; vector<vector<int>> st; void init() { int m, child; cin >> n; adj.assign(n + 1, list<int>()); for (int i = 1; i <= n; ++i) { cin >> m; while (m--) { cin >> child; adj[i].pb(child); adj[child].pb(i); } } N = 2 * n - 1; first.assign(n + 1, 0); dep.assign(n + 1, 0); euler.assign(N, 0); } void dfs(int u = 1, int p = 0) { dep[u] = dep[p] + 1; first[u] = timer; euler[timer++] = u; for (const int &child: adj[u]) { if (child == p) continue; else { dfs(child, u); euler[timer++] = u; } } } void build() { K = flog[N]; st.assign(K + 1, vector<int>(N)); for (int i = 0; i < N; ++i) st[0][i] = euler[i]; for (int j = 1; j <= K; ++j) for (int i = 0; i + (1 << j) <= N; ++i) { int a = st[j - 1][i], b = st[j - 1][i + (1 << (j - 1))]; st[j][i] = (dep[a] < dep[b] ? a : b); } } int LCA(int u, int v) { if (u == v) return u; int L = first[u], R = first[v]; if (L > R) swap(L, R); int k = flog[R - L + 1]; int a = st[k][L], b = st[k][R - (1 << k) + 1]; return (dep[a] < dep[b] ? a : b); } void queries() { int q, u, v; cin >> q; while (q--) { cin >> u >> v; cout << LCA(u, v) << '\n'; } } void solve() { int t; cin >> t; for (int i = 1; i <= t; ++i) { cout << "Case " << i << ":\n"; init(), dfs(), build(), queries(); timer = 0; } } void pre() { const int mxN = 1000; int sz = mxN << 1; flog.resize(sz); for (int i = 2; i < sz; ++i) flog[i] = flog[i >> 1] + 1; } int main() { ios; return pre(), solve(), 0; }
#include<iostream> #include<opencv2/opencv.hpp> cv::Mat Thersdhold_process(cv::Mat img,int thershold) { int width=img.cols; int height=img.rows; cv::Mat gary=cv::Mat::zeros(height,width,CV_8UC1); cv::Mat out=cv::Mat::zeros(height,width,CV_8UC1); cvtColor(img,gary,cv::COLOR_BGR2GRAY); for (int x =0;x<width;x++) { for(int y=0;y<height;y++) { if(gary.at<uchar>(y,x) <thershold) { out.at<uchar>(y,x)=0; }else { out.at<uchar>(y,x)=255; } } } return out; } int main() { cv::Mat img=cv::imread("F:\\learnOpencv\\unit1\\imori.jpg"); cv::Mat out=Thersdhold_process(img,128); cv::namedWindow("img"); cv::namedWindow("out"); cv::imshow("img",img); cv::imshow("out",out); cv::imwrite("F:\\learnOpencv\\unit1\\answer_image\\answer3.jpg",out); cv::waitKey(); cv::destroyAllWindows(); }
/* * Project MQ5 * Description: Seeed Studio TCS3472 I2C Color Sensor V2 * Author: Patrick Bolton * Date: 05/27/21 */ #include "Particle.h" #include "math.h" #include "Adafruit_TCS34725.h" SYSTEM_THREAD(ENABLED); boolean commonAnode = false; char szInfo[128]; Adafruit_TCS34725 tcs = Adafruit_TCS34725(TCS34725_INTEGRATIONTIME_50MS, TCS34725_GAIN_4X); #define dbSerial Serial SerialLogHandler logHandler; #define UPDATE_INTERVAL 5000 //1 sec = 1000 millis unsigned long UpdateInterval; int min_last, min_time; int tcs_lux, tcs_cct; void setup() { dbSerial.begin(9600); if (tcs.begin()) {Log.info("TCS34725 Began");} else{Log.info("TCS34725 Error");} UpdateInterval = millis(); min_last=-1; } void loop() { Time.zone(-7); if(Particle.disconnected()){return;} uint16_t clear, red, green, blue; if ((millis() - UpdateInterval) > UPDATE_INTERVAL) { tcs.setInterrupt(false); // turn on LED delay(60); // takes 50ms to read tcs.getRawData(&red, &green, &blue, &clear); tcs.setInterrupt(true); // turn off LED tcs_lux=tcs.calculateLux(red, green, blue); tcs_cct=tcs.calculateColorTemperature(red, green, blue); // Figure out some basic hex code for visualization uint32_t sum = clear; float r, g, b; r = red; r /= sum; g = green; g /= sum; b = blue; b /= sum; r *= 256; g *= 256; b *= 256; //sprintf(szInfo, "%d,%d,%d", (int)r, (int)g, (int)b); Log.info("Raw Red: %d", red); Log.info("Raw Green: %d", green); Log.info("Raw Blue: %d", blue); Log.info("Raw Clear: %d", clear); Log.info("Color Coordinates"); Log.info("Red: %d", int(r)); Log.info("Green: %d", int(g)); Log.info("Blue: %d", int(b)); Log.info("Illum: %d", tcs_lux); Log.info("ColorTempK: %d", tcs_cct); Serial.println(szInfo); min_time=Time.minute(); if((min_time!=min_last)&&(min_time==0||min_time==15||min_time==30||min_time==45)) { //createEventPayload1(); min_last = min_time; Log.info("Last Update: %d", min_last); Log.info(Time.timeStr()); } Log.info("loop"); Log.info(Time.timeStr()); UpdateInterval = millis(); } }
#include "mainwindow.h" #include <QApplication> #include <stdio.h> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); union { int i; struct { int j; int m; }byte; struct { char k; char p; char q; char s; }bit; } jin; jin.bit.p=0x2; jin.i=0x12345678; /*printf("%x\n",jin.bit.k); printf("%x\n",jin.bit.p); printf("%x\n",jin.bit.q); printf("%x\n",jin.bit.s); printf("%d\n",sizeof(jin)); */ return a.exec(); }
// ============================================================== // RTL generated by Vivado(TM) HLS - High-Level Synthesis from C, C++ and SystemC // Version: 2013.4 // Copyright (C) 2013 Xilinx Inc. All rights reserved. // // =========================================================== #include "load_points_buffer.h" #include "AESL_pkg.h" using namespace std; namespace ap_rtl { const sc_logic load_points_buffer::ap_const_logic_1 = sc_dt::Log_1; const sc_logic load_points_buffer::ap_const_logic_0 = sc_dt::Log_0; const sc_lv<3> load_points_buffer::ap_ST_st1_fsm_0 = "000"; const sc_lv<3> load_points_buffer::ap_ST_pp0_stg0_fsm_1 = "1"; const sc_lv<3> load_points_buffer::ap_ST_pp1_stg0_fsm_2 = "10"; const sc_lv<3> load_points_buffer::ap_ST_pp1_stg1_fsm_3 = "11"; const sc_lv<3> load_points_buffer::ap_ST_st13_fsm_4 = "100"; const sc_lv<1> load_points_buffer::ap_const_lv1_0 = "0"; const sc_lv<6> load_points_buffer::ap_const_lv6_0 = "000000"; const sc_lv<5> load_points_buffer::ap_const_lv5_0 = "00000"; const sc_lv<32> load_points_buffer::ap_const_lv32_0 = "00000000000000000000000000000000"; const sc_lv<32> load_points_buffer::ap_const_lv32_30 = "110000"; const sc_lv<32> load_points_buffer::ap_const_lv32_2 = "10"; const sc_lv<32> load_points_buffer::ap_const_lv32_1F = "11111"; const sc_lv<6> load_points_buffer::ap_const_lv6_30 = "110000"; const sc_lv<6> load_points_buffer::ap_const_lv6_1 = "1"; const sc_lv<5> load_points_buffer::ap_const_lv5_10 = "10000"; const sc_lv<5> load_points_buffer::ap_const_lv5_1 = "1"; const sc_lv<2> load_points_buffer::ap_const_lv2_0 = "00"; const sc_lv<7> load_points_buffer::ap_const_lv7_1 = "1"; const sc_lv<7> load_points_buffer::ap_const_lv7_2 = "10"; load_points_buffer::load_points_buffer(sc_module_name name) : sc_module(name), mVcdFile(0) { int_buffer_U = new load_points_buffer_int_buffer("int_buffer_U"); int_buffer_U->clk(ap_clk); int_buffer_U->reset(ap_rst); int_buffer_U->address0(int_buffer_address0); int_buffer_U->ce0(int_buffer_ce0); int_buffer_U->we0(int_buffer_we0); int_buffer_U->d0(int_buffer_d0); int_buffer_U->q0(int_buffer_q0); int_buffer_U->address1(int_buffer_address1); int_buffer_U->ce1(int_buffer_ce1); int_buffer_U->q1(int_buffer_q1); SC_METHOD(thread_ap_clk_no_reset_); dont_initialize(); sensitive << ( ap_clk.pos() ); SC_METHOD(thread_ap_done); sensitive << ( ap_start ); sensitive << ( ap_CS_fsm ); SC_METHOD(thread_ap_idle); sensitive << ( ap_start ); sensitive << ( ap_CS_fsm ); SC_METHOD(thread_ap_ready); sensitive << ( ap_CS_fsm ); SC_METHOD(thread_ap_sig_bdd_79); sensitive << ( bus_r_rsp_empty_n ); sensitive << ( ap_reg_ppstg_exitcond2_reg_350_pp0_it5 ); SC_METHOD(thread_buffer_0_value_address0); sensitive << ( ap_CS_fsm ); sensitive << ( ap_reg_ppiten_pp1_it0 ); sensitive << ( tmp_6_fu_324_p1 ); SC_METHOD(thread_buffer_0_value_ce0); sensitive << ( ap_CS_fsm ); sensitive << ( ap_reg_ppiten_pp1_it0 ); SC_METHOD(thread_buffer_0_value_d0); sensitive << ( ap_CS_fsm ); sensitive << ( ap_reg_ppiten_pp1_it0 ); sensitive << ( int_buffer_q0 ); SC_METHOD(thread_buffer_0_value_we0); sensitive << ( ap_CS_fsm ); sensitive << ( exitcond1_reg_368 ); sensitive << ( ap_reg_ppiten_pp1_it0 ); SC_METHOD(thread_buffer_1_value_address0); sensitive << ( ap_CS_fsm ); sensitive << ( ap_reg_ppiten_pp1_it0 ); sensitive << ( tmp_6_fu_324_p1 ); SC_METHOD(thread_buffer_1_value_ce0); sensitive << ( ap_CS_fsm ); sensitive << ( ap_reg_ppiten_pp1_it0 ); SC_METHOD(thread_buffer_1_value_d0); sensitive << ( ap_CS_fsm ); sensitive << ( ap_reg_ppiten_pp1_it0 ); sensitive << ( int_buffer_q1 ); SC_METHOD(thread_buffer_1_value_we0); sensitive << ( ap_CS_fsm ); sensitive << ( exitcond1_reg_368 ); sensitive << ( ap_reg_ppiten_pp1_it0 ); SC_METHOD(thread_buffer_2_value_address0); sensitive << ( ap_CS_fsm ); sensitive << ( ap_reg_ppiten_pp1_it1 ); sensitive << ( tmp_6_reg_392 ); SC_METHOD(thread_buffer_2_value_ce0); sensitive << ( ap_CS_fsm ); sensitive << ( ap_reg_ppiten_pp1_it1 ); SC_METHOD(thread_buffer_2_value_d0); sensitive << ( ap_CS_fsm ); sensitive << ( ap_reg_ppiten_pp1_it1 ); sensitive << ( int_buffer_q1 ); SC_METHOD(thread_buffer_2_value_we0); sensitive << ( ap_CS_fsm ); sensitive << ( exitcond1_reg_368 ); sensitive << ( ap_reg_ppiten_pp1_it1 ); SC_METHOD(thread_bus_r_address); sensitive << ( ap_CS_fsm ); sensitive << ( ap_reg_ppiten_pp0_it1 ); sensitive << ( exitcond2_reg_350 ); sensitive << ( ap_sig_bdd_79 ); sensitive << ( ap_reg_ppiten_pp0_it6 ); sensitive << ( bus_addr_reg_344 ); sensitive << ( isIter0_reg_359 ); SC_METHOD(thread_bus_r_dataout); SC_METHOD(thread_bus_r_req_din); sensitive << ( ap_CS_fsm ); sensitive << ( ap_reg_ppiten_pp0_it1 ); sensitive << ( exitcond2_reg_350 ); sensitive << ( ap_sig_bdd_79 ); sensitive << ( ap_reg_ppiten_pp0_it6 ); sensitive << ( isIter0_reg_359 ); SC_METHOD(thread_bus_r_req_write); sensitive << ( ap_CS_fsm ); sensitive << ( ap_reg_ppiten_pp0_it1 ); sensitive << ( exitcond2_reg_350 ); sensitive << ( ap_sig_bdd_79 ); sensitive << ( ap_reg_ppiten_pp0_it6 ); sensitive << ( isIter0_reg_359 ); SC_METHOD(thread_bus_r_rsp_read); sensitive << ( ap_CS_fsm ); sensitive << ( ap_reg_ppstg_exitcond2_reg_350_pp0_it5 ); sensitive << ( ap_sig_bdd_79 ); sensitive << ( ap_reg_ppiten_pp0_it6 ); SC_METHOD(thread_bus_r_size); sensitive << ( ap_CS_fsm ); sensitive << ( ap_reg_ppiten_pp0_it1 ); sensitive << ( exitcond2_reg_350 ); sensitive << ( ap_sig_bdd_79 ); sensitive << ( ap_reg_ppiten_pp0_it6 ); sensitive << ( isIter0_reg_359 ); SC_METHOD(thread_exitcond1_fu_262_p2); sensitive << ( ap_CS_fsm ); sensitive << ( ap_reg_ppiten_pp1_it0 ); sensitive << ( i_phi_fu_204_p4 ); SC_METHOD(thread_exitcond2_fu_239_p2); sensitive << ( ap_CS_fsm ); sensitive << ( ap_reg_ppiten_pp0_it0 ); sensitive << ( ap_sig_bdd_79 ); sensitive << ( ap_reg_ppiten_pp0_it6 ); sensitive << ( indvar_phi_fu_192_p4 ); SC_METHOD(thread_i_1_fu_268_p2); sensitive << ( i_phi_fu_204_p4 ); SC_METHOD(thread_i_cast1_fu_274_p1); sensitive << ( i_phi_fu_204_p4 ); SC_METHOD(thread_i_phi_fu_204_p4); sensitive << ( ap_CS_fsm ); sensitive << ( i_reg_200 ); sensitive << ( exitcond1_reg_368 ); sensitive << ( ap_reg_ppiten_pp1_it1 ); sensitive << ( i_1_reg_372 ); SC_METHOD(thread_indvar_next_fu_245_p2); sensitive << ( indvar_phi_fu_192_p4 ); SC_METHOD(thread_indvar_phi_fu_192_p4); sensitive << ( ap_CS_fsm ); sensitive << ( indvar_reg_188 ); sensitive << ( ap_reg_ppiten_pp0_it1 ); sensitive << ( exitcond2_reg_350 ); sensitive << ( indvar_next_reg_354 ); SC_METHOD(thread_int_buffer_address0); sensitive << ( ap_CS_fsm ); sensitive << ( ap_reg_ppiten_pp0_it7 ); sensitive << ( ap_reg_ppiten_pp1_it0 ); sensitive << ( tmp_s_fu_257_p1 ); sensitive << ( tmp_9_fu_304_p1 ); SC_METHOD(thread_int_buffer_address1); sensitive << ( ap_CS_fsm ); sensitive << ( ap_reg_ppiten_pp1_it0 ); sensitive << ( tmp_9_1_fu_319_p1 ); sensitive << ( tmp_9_2_fu_339_p1 ); SC_METHOD(thread_int_buffer_ce0); sensitive << ( ap_CS_fsm ); sensitive << ( ap_sig_bdd_79 ); sensitive << ( ap_reg_ppiten_pp0_it6 ); sensitive << ( ap_reg_ppiten_pp0_it7 ); sensitive << ( ap_reg_ppiten_pp1_it0 ); SC_METHOD(thread_int_buffer_ce1); sensitive << ( ap_CS_fsm ); sensitive << ( ap_reg_ppiten_pp1_it0 ); SC_METHOD(thread_int_buffer_d0); sensitive << ( ap_CS_fsm ); sensitive << ( ap_reg_ppiten_pp0_it7 ); sensitive << ( bus_addr_read_reg_363 ); SC_METHOD(thread_int_buffer_we0); sensitive << ( ap_CS_fsm ); sensitive << ( ap_sig_bdd_79 ); sensitive << ( ap_reg_ppiten_pp0_it6 ); sensitive << ( ap_reg_ppiten_pp0_it7 ); sensitive << ( ap_reg_ppstg_exitcond2_reg_350_pp0_it6 ); SC_METHOD(thread_isIter0_fu_251_p2); sensitive << ( ap_CS_fsm ); sensitive << ( ap_reg_ppiten_pp0_it0 ); sensitive << ( ap_sig_bdd_79 ); sensitive << ( ap_reg_ppiten_pp0_it6 ); sensitive << ( exitcond2_fu_239_p2 ); sensitive << ( indvar_phi_fu_192_p4 ); SC_METHOD(thread_p_shl_cast_fu_290_p1); sensitive << ( p_shl_fu_282_p3 ); SC_METHOD(thread_p_shl_fu_282_p3); sensitive << ( tmp_24_fu_278_p1 ); SC_METHOD(thread_tmp_1_fu_213_p2); sensitive << ( offset ); sensitive << ( address ); SC_METHOD(thread_tmp_24_fu_278_p1); sensitive << ( i_phi_fu_204_p4 ); SC_METHOD(thread_tmp_3_cast_fu_229_p1); sensitive << ( tmp_3_fu_219_p4 ); SC_METHOD(thread_tmp_3_fu_219_p4); sensitive << ( tmp_1_fu_213_p2 ); SC_METHOD(thread_tmp_5_fu_294_p2); sensitive << ( p_shl_cast_fu_290_p1 ); sensitive << ( i_cast1_fu_274_p1 ); SC_METHOD(thread_tmp_6_fu_324_p1); sensitive << ( i_reg_200 ); SC_METHOD(thread_tmp_8_1_fu_309_p2); sensitive << ( tmp_5_fu_294_p2 ); SC_METHOD(thread_tmp_8_2_fu_330_p2); sensitive << ( tmp_5_reg_377 ); SC_METHOD(thread_tmp_9_1_fu_319_p0); sensitive << ( ap_CS_fsm ); sensitive << ( ap_reg_ppiten_pp1_it0 ); sensitive << ( tmp_8_1_fu_309_p2 ); SC_METHOD(thread_tmp_9_1_fu_319_p1); sensitive << ( tmp_9_1_fu_319_p0 ); SC_METHOD(thread_tmp_9_2_fu_339_p0); sensitive << ( ap_CS_fsm ); sensitive << ( ap_reg_ppiten_pp1_it0 ); sensitive << ( tmp_8_2_fu_330_p2 ); SC_METHOD(thread_tmp_9_2_fu_339_p1); sensitive << ( tmp_9_2_fu_339_p0 ); SC_METHOD(thread_tmp_9_fu_304_p0); sensitive << ( ap_CS_fsm ); sensitive << ( ap_reg_ppiten_pp1_it0 ); sensitive << ( tmp_5_fu_294_p2 ); SC_METHOD(thread_tmp_9_fu_304_p1); sensitive << ( tmp_9_fu_304_p0 ); SC_METHOD(thread_tmp_s_fu_257_p1); sensitive << ( ap_reg_ppstg_indvar_reg_188_pp0_it6 ); SC_METHOD(thread_ap_NS_fsm); sensitive << ( ap_start ); sensitive << ( ap_CS_fsm ); sensitive << ( ap_reg_ppiten_pp0_it0 ); sensitive << ( ap_reg_ppiten_pp0_it1 ); sensitive << ( ap_sig_bdd_79 ); sensitive << ( ap_reg_ppiten_pp0_it6 ); sensitive << ( ap_reg_ppiten_pp0_it7 ); sensitive << ( exitcond2_fu_239_p2 ); sensitive << ( exitcond1_fu_262_p2 ); sensitive << ( ap_reg_ppiten_pp1_it0 ); ap_CS_fsm = "000"; ap_reg_ppiten_pp0_it0 = SC_LOGIC_0; ap_reg_ppiten_pp0_it1 = SC_LOGIC_0; ap_reg_ppiten_pp0_it2 = SC_LOGIC_0; ap_reg_ppiten_pp0_it3 = SC_LOGIC_0; ap_reg_ppiten_pp0_it4 = SC_LOGIC_0; ap_reg_ppiten_pp0_it5 = SC_LOGIC_0; ap_reg_ppiten_pp0_it6 = SC_LOGIC_0; ap_reg_ppiten_pp0_it7 = SC_LOGIC_0; ap_reg_ppiten_pp1_it0 = SC_LOGIC_0; ap_reg_ppiten_pp1_it1 = SC_LOGIC_0; static int apTFileNum = 0; stringstream apTFilenSS; apTFilenSS << "load_points_buffer_sc_trace_" << apTFileNum ++; string apTFn = apTFilenSS.str(); mVcdFile = sc_create_vcd_trace_file(apTFn.c_str()); mVcdFile->set_time_unit(1, SC_PS); if (1) { #ifdef __HLS_TRACE_LEVEL_PORT_HIER__ sc_trace(mVcdFile, ap_clk, "(port)ap_clk"); sc_trace(mVcdFile, ap_rst, "(port)ap_rst"); sc_trace(mVcdFile, ap_start, "(port)ap_start"); sc_trace(mVcdFile, ap_done, "(port)ap_done"); sc_trace(mVcdFile, ap_idle, "(port)ap_idle"); sc_trace(mVcdFile, ap_ready, "(port)ap_ready"); sc_trace(mVcdFile, offset, "(port)offset"); sc_trace(mVcdFile, address, "(port)address"); sc_trace(mVcdFile, bus_r_req_din, "(port)bus_r_req_din"); sc_trace(mVcdFile, bus_r_req_full_n, "(port)bus_r_req_full_n"); sc_trace(mVcdFile, bus_r_req_write, "(port)bus_r_req_write"); sc_trace(mVcdFile, bus_r_rsp_empty_n, "(port)bus_r_rsp_empty_n"); sc_trace(mVcdFile, bus_r_rsp_read, "(port)bus_r_rsp_read"); sc_trace(mVcdFile, bus_r_address, "(port)bus_r_address"); sc_trace(mVcdFile, bus_r_datain, "(port)bus_r_datain"); sc_trace(mVcdFile, bus_r_dataout, "(port)bus_r_dataout"); sc_trace(mVcdFile, bus_r_size, "(port)bus_r_size"); sc_trace(mVcdFile, buffer_0_value_address0, "(port)buffer_0_value_address0"); sc_trace(mVcdFile, buffer_0_value_ce0, "(port)buffer_0_value_ce0"); sc_trace(mVcdFile, buffer_0_value_we0, "(port)buffer_0_value_we0"); sc_trace(mVcdFile, buffer_0_value_d0, "(port)buffer_0_value_d0"); sc_trace(mVcdFile, buffer_1_value_address0, "(port)buffer_1_value_address0"); sc_trace(mVcdFile, buffer_1_value_ce0, "(port)buffer_1_value_ce0"); sc_trace(mVcdFile, buffer_1_value_we0, "(port)buffer_1_value_we0"); sc_trace(mVcdFile, buffer_1_value_d0, "(port)buffer_1_value_d0"); sc_trace(mVcdFile, buffer_2_value_address0, "(port)buffer_2_value_address0"); sc_trace(mVcdFile, buffer_2_value_ce0, "(port)buffer_2_value_ce0"); sc_trace(mVcdFile, buffer_2_value_we0, "(port)buffer_2_value_we0"); sc_trace(mVcdFile, buffer_2_value_d0, "(port)buffer_2_value_d0"); #endif #ifdef __HLS_TRACE_LEVEL_INT__ sc_trace(mVcdFile, ap_CS_fsm, "ap_CS_fsm"); sc_trace(mVcdFile, indvar_reg_188, "indvar_reg_188"); sc_trace(mVcdFile, ap_reg_ppstg_indvar_reg_188_pp0_it1, "ap_reg_ppstg_indvar_reg_188_pp0_it1"); sc_trace(mVcdFile, ap_reg_ppiten_pp0_it0, "ap_reg_ppiten_pp0_it0"); sc_trace(mVcdFile, ap_reg_ppiten_pp0_it1, "ap_reg_ppiten_pp0_it1"); sc_trace(mVcdFile, ap_reg_ppiten_pp0_it2, "ap_reg_ppiten_pp0_it2"); sc_trace(mVcdFile, ap_reg_ppiten_pp0_it3, "ap_reg_ppiten_pp0_it3"); sc_trace(mVcdFile, ap_reg_ppiten_pp0_it4, "ap_reg_ppiten_pp0_it4"); sc_trace(mVcdFile, ap_reg_ppiten_pp0_it5, "ap_reg_ppiten_pp0_it5"); sc_trace(mVcdFile, exitcond2_reg_350, "exitcond2_reg_350"); sc_trace(mVcdFile, ap_reg_ppstg_exitcond2_reg_350_pp0_it5, "ap_reg_ppstg_exitcond2_reg_350_pp0_it5"); sc_trace(mVcdFile, ap_sig_bdd_79, "ap_sig_bdd_79"); sc_trace(mVcdFile, ap_reg_ppiten_pp0_it6, "ap_reg_ppiten_pp0_it6"); sc_trace(mVcdFile, ap_reg_ppiten_pp0_it7, "ap_reg_ppiten_pp0_it7"); sc_trace(mVcdFile, ap_reg_ppstg_indvar_reg_188_pp0_it2, "ap_reg_ppstg_indvar_reg_188_pp0_it2"); sc_trace(mVcdFile, ap_reg_ppstg_indvar_reg_188_pp0_it3, "ap_reg_ppstg_indvar_reg_188_pp0_it3"); sc_trace(mVcdFile, ap_reg_ppstg_indvar_reg_188_pp0_it4, "ap_reg_ppstg_indvar_reg_188_pp0_it4"); sc_trace(mVcdFile, ap_reg_ppstg_indvar_reg_188_pp0_it5, "ap_reg_ppstg_indvar_reg_188_pp0_it5"); sc_trace(mVcdFile, ap_reg_ppstg_indvar_reg_188_pp0_it6, "ap_reg_ppstg_indvar_reg_188_pp0_it6"); sc_trace(mVcdFile, i_reg_200, "i_reg_200"); sc_trace(mVcdFile, bus_addr_reg_344, "bus_addr_reg_344"); sc_trace(mVcdFile, exitcond2_fu_239_p2, "exitcond2_fu_239_p2"); sc_trace(mVcdFile, ap_reg_ppstg_exitcond2_reg_350_pp0_it1, "ap_reg_ppstg_exitcond2_reg_350_pp0_it1"); sc_trace(mVcdFile, ap_reg_ppstg_exitcond2_reg_350_pp0_it2, "ap_reg_ppstg_exitcond2_reg_350_pp0_it2"); sc_trace(mVcdFile, ap_reg_ppstg_exitcond2_reg_350_pp0_it3, "ap_reg_ppstg_exitcond2_reg_350_pp0_it3"); sc_trace(mVcdFile, ap_reg_ppstg_exitcond2_reg_350_pp0_it4, "ap_reg_ppstg_exitcond2_reg_350_pp0_it4"); sc_trace(mVcdFile, ap_reg_ppstg_exitcond2_reg_350_pp0_it6, "ap_reg_ppstg_exitcond2_reg_350_pp0_it6"); sc_trace(mVcdFile, indvar_next_fu_245_p2, "indvar_next_fu_245_p2"); sc_trace(mVcdFile, indvar_next_reg_354, "indvar_next_reg_354"); sc_trace(mVcdFile, isIter0_fu_251_p2, "isIter0_fu_251_p2"); sc_trace(mVcdFile, isIter0_reg_359, "isIter0_reg_359"); sc_trace(mVcdFile, bus_addr_read_reg_363, "bus_addr_read_reg_363"); sc_trace(mVcdFile, exitcond1_fu_262_p2, "exitcond1_fu_262_p2"); sc_trace(mVcdFile, exitcond1_reg_368, "exitcond1_reg_368"); sc_trace(mVcdFile, ap_reg_ppiten_pp1_it0, "ap_reg_ppiten_pp1_it0"); sc_trace(mVcdFile, ap_reg_ppiten_pp1_it1, "ap_reg_ppiten_pp1_it1"); sc_trace(mVcdFile, i_1_fu_268_p2, "i_1_fu_268_p2"); sc_trace(mVcdFile, i_1_reg_372, "i_1_reg_372"); sc_trace(mVcdFile, tmp_5_fu_294_p2, "tmp_5_fu_294_p2"); sc_trace(mVcdFile, tmp_5_reg_377, "tmp_5_reg_377"); sc_trace(mVcdFile, tmp_6_fu_324_p1, "tmp_6_fu_324_p1"); sc_trace(mVcdFile, tmp_6_reg_392, "tmp_6_reg_392"); sc_trace(mVcdFile, int_buffer_address0, "int_buffer_address0"); sc_trace(mVcdFile, int_buffer_ce0, "int_buffer_ce0"); sc_trace(mVcdFile, int_buffer_we0, "int_buffer_we0"); sc_trace(mVcdFile, int_buffer_d0, "int_buffer_d0"); sc_trace(mVcdFile, int_buffer_q0, "int_buffer_q0"); sc_trace(mVcdFile, int_buffer_address1, "int_buffer_address1"); sc_trace(mVcdFile, int_buffer_ce1, "int_buffer_ce1"); sc_trace(mVcdFile, int_buffer_q1, "int_buffer_q1"); sc_trace(mVcdFile, indvar_phi_fu_192_p4, "indvar_phi_fu_192_p4"); sc_trace(mVcdFile, i_phi_fu_204_p4, "i_phi_fu_204_p4"); sc_trace(mVcdFile, tmp_s_fu_257_p1, "tmp_s_fu_257_p1"); sc_trace(mVcdFile, tmp_9_fu_304_p1, "tmp_9_fu_304_p1"); sc_trace(mVcdFile, tmp_9_1_fu_319_p1, "tmp_9_1_fu_319_p1"); sc_trace(mVcdFile, tmp_9_2_fu_339_p1, "tmp_9_2_fu_339_p1"); sc_trace(mVcdFile, tmp_3_cast_fu_229_p1, "tmp_3_cast_fu_229_p1"); sc_trace(mVcdFile, tmp_1_fu_213_p2, "tmp_1_fu_213_p2"); sc_trace(mVcdFile, tmp_3_fu_219_p4, "tmp_3_fu_219_p4"); sc_trace(mVcdFile, tmp_24_fu_278_p1, "tmp_24_fu_278_p1"); sc_trace(mVcdFile, p_shl_fu_282_p3, "p_shl_fu_282_p3"); sc_trace(mVcdFile, p_shl_cast_fu_290_p1, "p_shl_cast_fu_290_p1"); sc_trace(mVcdFile, i_cast1_fu_274_p1, "i_cast1_fu_274_p1"); sc_trace(mVcdFile, tmp_9_fu_304_p0, "tmp_9_fu_304_p0"); sc_trace(mVcdFile, tmp_8_1_fu_309_p2, "tmp_8_1_fu_309_p2"); sc_trace(mVcdFile, tmp_9_1_fu_319_p0, "tmp_9_1_fu_319_p0"); sc_trace(mVcdFile, tmp_8_2_fu_330_p2, "tmp_8_2_fu_330_p2"); sc_trace(mVcdFile, tmp_9_2_fu_339_p0, "tmp_9_2_fu_339_p0"); sc_trace(mVcdFile, ap_NS_fsm, "ap_NS_fsm"); #endif } } load_points_buffer::~load_points_buffer() { if (mVcdFile) sc_close_vcd_trace_file(mVcdFile); delete int_buffer_U; } void load_points_buffer::thread_ap_clk_no_reset_() { if ( ap_rst.read() == ap_const_logic_1) { ap_CS_fsm = ap_ST_st1_fsm_0; } else { ap_CS_fsm = ap_NS_fsm.read(); } if ( ap_rst.read() == ap_const_logic_1) { ap_reg_ppiten_pp0_it0 = ap_const_logic_0; } else { if ((esl_seteq<1,3,3>(ap_ST_pp0_stg0_fsm_1, ap_CS_fsm.read()) && !(ap_sig_bdd_79.read() && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it6.read())) && !esl_seteq<1,1,1>(ap_const_lv1_0, exitcond2_fu_239_p2.read()))) { ap_reg_ppiten_pp0_it0 = ap_const_logic_0; } else if ((esl_seteq<1,3,3>(ap_ST_st1_fsm_0, ap_CS_fsm.read()) && !esl_seteq<1,1,1>(ap_start.read(), ap_const_logic_0))) { ap_reg_ppiten_pp0_it0 = ap_const_logic_1; } } if ( ap_rst.read() == ap_const_logic_1) { ap_reg_ppiten_pp0_it1 = ap_const_logic_0; } else { if ((esl_seteq<1,3,3>(ap_ST_pp0_stg0_fsm_1, ap_CS_fsm.read()) && !(ap_sig_bdd_79.read() && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it6.read())) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond2_fu_239_p2.read()))) { ap_reg_ppiten_pp0_it1 = ap_const_logic_1; } else if (((esl_seteq<1,3,3>(ap_ST_st1_fsm_0, ap_CS_fsm.read()) && !esl_seteq<1,1,1>(ap_start.read(), ap_const_logic_0)) || (esl_seteq<1,3,3>(ap_ST_pp0_stg0_fsm_1, ap_CS_fsm.read()) && !(ap_sig_bdd_79.read() && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it6.read())) && !esl_seteq<1,1,1>(ap_const_lv1_0, exitcond2_fu_239_p2.read())))) { ap_reg_ppiten_pp0_it1 = ap_const_logic_0; } } if ( ap_rst.read() == ap_const_logic_1) { ap_reg_ppiten_pp0_it2 = ap_const_logic_0; } else { if ((esl_seteq<1,3,3>(ap_ST_pp0_stg0_fsm_1, ap_CS_fsm.read()) && !(ap_sig_bdd_79.read() && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it6.read())))) { ap_reg_ppiten_pp0_it2 = ap_reg_ppiten_pp0_it1.read(); } } if ( ap_rst.read() == ap_const_logic_1) { ap_reg_ppiten_pp0_it3 = ap_const_logic_0; } else { if ((esl_seteq<1,3,3>(ap_ST_pp0_stg0_fsm_1, ap_CS_fsm.read()) && !(ap_sig_bdd_79.read() && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it6.read())))) { ap_reg_ppiten_pp0_it3 = ap_reg_ppiten_pp0_it2.read(); } } if ( ap_rst.read() == ap_const_logic_1) { ap_reg_ppiten_pp0_it4 = ap_const_logic_0; } else { if ((esl_seteq<1,3,3>(ap_ST_pp0_stg0_fsm_1, ap_CS_fsm.read()) && !(ap_sig_bdd_79.read() && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it6.read())))) { ap_reg_ppiten_pp0_it4 = ap_reg_ppiten_pp0_it3.read(); } } if ( ap_rst.read() == ap_const_logic_1) { ap_reg_ppiten_pp0_it5 = ap_const_logic_0; } else { if ((esl_seteq<1,3,3>(ap_ST_pp0_stg0_fsm_1, ap_CS_fsm.read()) && !(ap_sig_bdd_79.read() && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it6.read())))) { ap_reg_ppiten_pp0_it5 = ap_reg_ppiten_pp0_it4.read(); } } if ( ap_rst.read() == ap_const_logic_1) { ap_reg_ppiten_pp0_it6 = ap_const_logic_0; } else { if ((esl_seteq<1,3,3>(ap_ST_pp0_stg0_fsm_1, ap_CS_fsm.read()) && !(ap_sig_bdd_79.read() && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it6.read())))) { ap_reg_ppiten_pp0_it6 = ap_reg_ppiten_pp0_it5.read(); } } if ( ap_rst.read() == ap_const_logic_1) { ap_reg_ppiten_pp0_it7 = ap_const_logic_0; } else { if ((esl_seteq<1,3,3>(ap_ST_pp0_stg0_fsm_1, ap_CS_fsm.read()) && !(ap_sig_bdd_79.read() && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it6.read())))) { ap_reg_ppiten_pp0_it7 = ap_reg_ppiten_pp0_it6.read(); } else if ((esl_seteq<1,3,3>(ap_ST_st1_fsm_0, ap_CS_fsm.read()) && !esl_seteq<1,1,1>(ap_start.read(), ap_const_logic_0))) { ap_reg_ppiten_pp0_it7 = ap_const_logic_0; } } if ( ap_rst.read() == ap_const_logic_1) { ap_reg_ppiten_pp1_it0 = ap_const_logic_0; } else { if ((esl_seteq<1,3,3>(ap_ST_pp1_stg0_fsm_2, ap_CS_fsm.read()) && !esl_seteq<1,1,1>(ap_const_lv1_0, exitcond1_fu_262_p2.read()))) { ap_reg_ppiten_pp1_it0 = ap_const_logic_0; } else if ((esl_seteq<1,3,3>(ap_ST_pp0_stg0_fsm_1, ap_CS_fsm.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it0.read()) && !(ap_sig_bdd_79.read() && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it6.read())) && !esl_seteq<1,1,1>(ap_const_lv1_0, exitcond2_fu_239_p2.read()))) { ap_reg_ppiten_pp1_it0 = ap_const_logic_1; } } if ( ap_rst.read() == ap_const_logic_1) { ap_reg_ppiten_pp1_it1 = ap_const_logic_0; } else { if ((esl_seteq<1,3,3>(ap_ST_pp1_stg1_fsm_3, ap_CS_fsm.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond1_reg_368.read()))) { ap_reg_ppiten_pp1_it1 = ap_const_logic_1; } else if (((esl_seteq<1,3,3>(ap_ST_pp0_stg0_fsm_1, ap_CS_fsm.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it0.read()) && !(ap_sig_bdd_79.read() && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it6.read())) && !esl_seteq<1,1,1>(ap_const_lv1_0, exitcond2_fu_239_p2.read())) || (esl_seteq<1,3,3>(ap_ST_pp1_stg1_fsm_3, ap_CS_fsm.read()) && !esl_seteq<1,1,1>(ap_const_lv1_0, exitcond1_reg_368.read())))) { ap_reg_ppiten_pp1_it1 = ap_const_logic_0; } } if ((esl_seteq<1,3,3>(ap_ST_pp0_stg0_fsm_1, ap_CS_fsm.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it0.read()) && !(ap_sig_bdd_79.read() && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it6.read())) && !esl_seteq<1,1,1>(ap_const_lv1_0, exitcond2_fu_239_p2.read()))) { i_reg_200 = ap_const_lv5_0; } else if ((esl_seteq<1,3,3>(ap_ST_pp1_stg0_fsm_2, ap_CS_fsm.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp1_it1.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond1_reg_368.read()))) { i_reg_200 = i_1_reg_372.read(); } if ((esl_seteq<1,3,3>(ap_ST_st1_fsm_0, ap_CS_fsm.read()) && !esl_seteq<1,1,1>(ap_start.read(), ap_const_logic_0))) { indvar_reg_188 = ap_const_lv6_0; } else if ((esl_seteq<1,3,3>(ap_ST_pp0_stg0_fsm_1, ap_CS_fsm.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it1.read()) && !(ap_sig_bdd_79.read() && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it6.read())) && esl_seteq<1,1,1>(exitcond2_reg_350.read(), ap_const_lv1_0))) { indvar_reg_188 = indvar_next_reg_354.read(); } if ((esl_seteq<1,3,3>(ap_ST_pp0_stg0_fsm_1, ap_CS_fsm.read()) && !(ap_sig_bdd_79.read() && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it6.read())))) { ap_reg_ppstg_exitcond2_reg_350_pp0_it1 = exitcond2_reg_350.read(); ap_reg_ppstg_exitcond2_reg_350_pp0_it2 = ap_reg_ppstg_exitcond2_reg_350_pp0_it1.read(); ap_reg_ppstg_exitcond2_reg_350_pp0_it3 = ap_reg_ppstg_exitcond2_reg_350_pp0_it2.read(); ap_reg_ppstg_exitcond2_reg_350_pp0_it4 = ap_reg_ppstg_exitcond2_reg_350_pp0_it3.read(); ap_reg_ppstg_exitcond2_reg_350_pp0_it5 = ap_reg_ppstg_exitcond2_reg_350_pp0_it4.read(); ap_reg_ppstg_exitcond2_reg_350_pp0_it6 = ap_reg_ppstg_exitcond2_reg_350_pp0_it5.read(); ap_reg_ppstg_indvar_reg_188_pp0_it1 = indvar_reg_188.read(); ap_reg_ppstg_indvar_reg_188_pp0_it2 = ap_reg_ppstg_indvar_reg_188_pp0_it1.read(); ap_reg_ppstg_indvar_reg_188_pp0_it3 = ap_reg_ppstg_indvar_reg_188_pp0_it2.read(); ap_reg_ppstg_indvar_reg_188_pp0_it4 = ap_reg_ppstg_indvar_reg_188_pp0_it3.read(); ap_reg_ppstg_indvar_reg_188_pp0_it5 = ap_reg_ppstg_indvar_reg_188_pp0_it4.read(); ap_reg_ppstg_indvar_reg_188_pp0_it6 = ap_reg_ppstg_indvar_reg_188_pp0_it5.read(); } if ((esl_seteq<1,3,3>(ap_ST_pp0_stg0_fsm_1, ap_CS_fsm.read()) && esl_seteq<1,1,1>(ap_reg_ppstg_exitcond2_reg_350_pp0_it5.read(), ap_const_lv1_0) && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it6.read()) && !(ap_sig_bdd_79.read() && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it6.read())))) { bus_addr_read_reg_363 = bus_r_datain.read(); } if ((esl_seteq<1,3,3>(ap_ST_st1_fsm_0, ap_CS_fsm.read()) && !esl_seteq<1,1,1>(ap_start.read(), ap_const_logic_0))) { bus_addr_reg_344 = (sc_lv<32>) (tmp_3_cast_fu_229_p1.read()); } if ((esl_seteq<1,3,3>(ap_ST_pp1_stg0_fsm_2, ap_CS_fsm.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp1_it0.read()))) { exitcond1_reg_368 = exitcond1_fu_262_p2.read(); i_1_reg_372 = i_1_fu_268_p2.read(); } if ((esl_seteq<1,3,3>(ap_ST_pp0_stg0_fsm_1, ap_CS_fsm.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it0.read()) && !(ap_sig_bdd_79.read() && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it6.read())))) { exitcond2_reg_350 = exitcond2_fu_239_p2.read(); indvar_next_reg_354 = indvar_next_fu_245_p2.read(); } if ((esl_seteq<1,3,3>(ap_ST_pp0_stg0_fsm_1, ap_CS_fsm.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it0.read()) && !(ap_sig_bdd_79.read() && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it6.read())) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond2_fu_239_p2.read()))) { isIter0_reg_359 = isIter0_fu_251_p2.read(); } if ((esl_seteq<1,3,3>(ap_ST_pp1_stg0_fsm_2, ap_CS_fsm.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp1_it0.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond1_fu_262_p2.read()))) { tmp_5_reg_377 = tmp_5_fu_294_p2.read(); } if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp1_it0.read()) && esl_seteq<1,3,3>(ap_ST_pp1_stg1_fsm_3, ap_CS_fsm.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond1_reg_368.read()))) { tmp_6_reg_392 = tmp_6_fu_324_p1.read(); } } void load_points_buffer::thread_ap_done() { if (((!esl_seteq<1,1,1>(ap_const_logic_1, ap_start.read()) && esl_seteq<1,3,3>(ap_ST_st1_fsm_0, ap_CS_fsm.read())) || esl_seteq<1,3,3>(ap_ST_st13_fsm_4, ap_CS_fsm.read()))) { ap_done = ap_const_logic_1; } else { ap_done = ap_const_logic_0; } } void load_points_buffer::thread_ap_idle() { if ((!esl_seteq<1,1,1>(ap_const_logic_1, ap_start.read()) && esl_seteq<1,3,3>(ap_ST_st1_fsm_0, ap_CS_fsm.read()))) { ap_idle = ap_const_logic_1; } else { ap_idle = ap_const_logic_0; } } void load_points_buffer::thread_ap_ready() { if (esl_seteq<1,3,3>(ap_ST_st13_fsm_4, ap_CS_fsm.read())) { ap_ready = ap_const_logic_1; } else { ap_ready = ap_const_logic_0; } } void load_points_buffer::thread_ap_sig_bdd_79() { ap_sig_bdd_79 = (esl_seteq<1,1,1>(bus_r_rsp_empty_n.read(), ap_const_logic_0) && esl_seteq<1,1,1>(ap_reg_ppstg_exitcond2_reg_350_pp0_it5.read(), ap_const_lv1_0)); } void load_points_buffer::thread_buffer_0_value_address0() { buffer_0_value_address0 = (sc_lv<4>) (tmp_6_fu_324_p1.read()); } void load_points_buffer::thread_buffer_0_value_ce0() { if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp1_it0.read()) && esl_seteq<1,3,3>(ap_ST_pp1_stg1_fsm_3, ap_CS_fsm.read()))) { buffer_0_value_ce0 = ap_const_logic_1; } else { buffer_0_value_ce0 = ap_const_logic_0; } } void load_points_buffer::thread_buffer_0_value_d0() { buffer_0_value_d0 = int_buffer_q0.read(); } void load_points_buffer::thread_buffer_0_value_we0() { if (((esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp1_it0.read()) && esl_seteq<1,3,3>(ap_ST_pp1_stg1_fsm_3, ap_CS_fsm.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond1_reg_368.read())))) { buffer_0_value_we0 = ap_const_logic_1; } else { buffer_0_value_we0 = ap_const_logic_0; } } void load_points_buffer::thread_buffer_1_value_address0() { buffer_1_value_address0 = (sc_lv<4>) (tmp_6_fu_324_p1.read()); } void load_points_buffer::thread_buffer_1_value_ce0() { if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp1_it0.read()) && esl_seteq<1,3,3>(ap_ST_pp1_stg1_fsm_3, ap_CS_fsm.read()))) { buffer_1_value_ce0 = ap_const_logic_1; } else { buffer_1_value_ce0 = ap_const_logic_0; } } void load_points_buffer::thread_buffer_1_value_d0() { buffer_1_value_d0 = int_buffer_q1.read(); } void load_points_buffer::thread_buffer_1_value_we0() { if (((esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp1_it0.read()) && esl_seteq<1,3,3>(ap_ST_pp1_stg1_fsm_3, ap_CS_fsm.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond1_reg_368.read())))) { buffer_1_value_we0 = ap_const_logic_1; } else { buffer_1_value_we0 = ap_const_logic_0; } } void load_points_buffer::thread_buffer_2_value_address0() { buffer_2_value_address0 = (sc_lv<4>) (tmp_6_reg_392.read()); } void load_points_buffer::thread_buffer_2_value_ce0() { if ((esl_seteq<1,3,3>(ap_ST_pp1_stg0_fsm_2, ap_CS_fsm.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp1_it1.read()))) { buffer_2_value_ce0 = ap_const_logic_1; } else { buffer_2_value_ce0 = ap_const_logic_0; } } void load_points_buffer::thread_buffer_2_value_d0() { buffer_2_value_d0 = int_buffer_q1.read(); } void load_points_buffer::thread_buffer_2_value_we0() { if (((esl_seteq<1,3,3>(ap_ST_pp1_stg0_fsm_2, ap_CS_fsm.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp1_it1.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond1_reg_368.read())))) { buffer_2_value_we0 = ap_const_logic_1; } else { buffer_2_value_we0 = ap_const_logic_0; } } void load_points_buffer::thread_bus_r_address() { bus_r_address = bus_addr_reg_344.read(); } void load_points_buffer::thread_bus_r_dataout() { bus_r_dataout = ap_const_lv32_0; } void load_points_buffer::thread_bus_r_req_din() { bus_r_req_din = ap_const_logic_0; } void load_points_buffer::thread_bus_r_req_write() { if ((esl_seteq<1,3,3>(ap_ST_pp0_stg0_fsm_1, ap_CS_fsm.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it1.read()) && !(ap_sig_bdd_79.read() && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it6.read())) && esl_seteq<1,1,1>(exitcond2_reg_350.read(), ap_const_lv1_0) && !esl_seteq<1,1,1>(ap_const_lv1_0, isIter0_reg_359.read()))) { bus_r_req_write = ap_const_logic_1; } else { bus_r_req_write = ap_const_logic_0; } } void load_points_buffer::thread_bus_r_rsp_read() { if ((esl_seteq<1,3,3>(ap_ST_pp0_stg0_fsm_1, ap_CS_fsm.read()) && esl_seteq<1,1,1>(ap_reg_ppstg_exitcond2_reg_350_pp0_it5.read(), ap_const_lv1_0) && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it6.read()) && !(ap_sig_bdd_79.read() && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it6.read())))) { bus_r_rsp_read = ap_const_logic_1; } else { bus_r_rsp_read = ap_const_logic_0; } } void load_points_buffer::thread_bus_r_size() { bus_r_size = ap_const_lv32_30; } void load_points_buffer::thread_exitcond1_fu_262_p2() { exitcond1_fu_262_p2 = (!i_phi_fu_204_p4.read().is_01() || !ap_const_lv5_10.is_01())? sc_lv<1>(): sc_lv<1>(i_phi_fu_204_p4.read() == ap_const_lv5_10); } void load_points_buffer::thread_exitcond2_fu_239_p2() { exitcond2_fu_239_p2 = (!indvar_phi_fu_192_p4.read().is_01() || !ap_const_lv6_30.is_01())? sc_lv<1>(): sc_lv<1>(indvar_phi_fu_192_p4.read() == ap_const_lv6_30); } void load_points_buffer::thread_i_1_fu_268_p2() { i_1_fu_268_p2 = (!i_phi_fu_204_p4.read().is_01() || !ap_const_lv5_1.is_01())? sc_lv<5>(): (sc_bigint<5>(i_phi_fu_204_p4.read()) + sc_biguint<5>(ap_const_lv5_1)); } void load_points_buffer::thread_i_cast1_fu_274_p1() { i_cast1_fu_274_p1 = esl_zext<7,5>(i_phi_fu_204_p4.read()); } void load_points_buffer::thread_i_phi_fu_204_p4() { if ((esl_seteq<1,3,3>(ap_ST_pp1_stg0_fsm_2, ap_CS_fsm.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp1_it1.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, exitcond1_reg_368.read()))) { i_phi_fu_204_p4 = i_1_reg_372.read(); } else { i_phi_fu_204_p4 = i_reg_200.read(); } } void load_points_buffer::thread_indvar_next_fu_245_p2() { indvar_next_fu_245_p2 = (!indvar_phi_fu_192_p4.read().is_01() || !ap_const_lv6_1.is_01())? sc_lv<6>(): (sc_bigint<6>(indvar_phi_fu_192_p4.read()) + sc_biguint<6>(ap_const_lv6_1)); } void load_points_buffer::thread_indvar_phi_fu_192_p4() { if ((esl_seteq<1,3,3>(ap_ST_pp0_stg0_fsm_1, ap_CS_fsm.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it1.read()) && esl_seteq<1,1,1>(exitcond2_reg_350.read(), ap_const_lv1_0))) { indvar_phi_fu_192_p4 = indvar_next_reg_354.read(); } else { indvar_phi_fu_192_p4 = indvar_reg_188.read(); } } void load_points_buffer::thread_int_buffer_address0() { if ((esl_seteq<1,3,3>(ap_ST_pp0_stg0_fsm_1, ap_CS_fsm.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it7.read()))) { int_buffer_address0 = (sc_lv<6>) (tmp_s_fu_257_p1.read()); } else if ((esl_seteq<1,3,3>(ap_ST_pp1_stg0_fsm_2, ap_CS_fsm.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp1_it0.read()))) { int_buffer_address0 = (sc_lv<6>) (tmp_9_fu_304_p1.read()); } else { int_buffer_address0 = "XXXXXX"; } } void load_points_buffer::thread_int_buffer_address1() { if (esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp1_it0.read())) { if (esl_seteq<1,3,3>(ap_ST_pp1_stg1_fsm_3, ap_CS_fsm.read())) { int_buffer_address1 = (sc_lv<6>) (tmp_9_2_fu_339_p1.read()); } else if (esl_seteq<1,3,3>(ap_ST_pp1_stg0_fsm_2, ap_CS_fsm.read())) { int_buffer_address1 = (sc_lv<6>) (tmp_9_1_fu_319_p1.read()); } else { int_buffer_address1 = "XXXXXX"; } } else { int_buffer_address1 = "XXXXXX"; } } void load_points_buffer::thread_int_buffer_ce0() { if (((esl_seteq<1,3,3>(ap_ST_pp1_stg0_fsm_2, ap_CS_fsm.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp1_it0.read())) || (esl_seteq<1,3,3>(ap_ST_pp0_stg0_fsm_1, ap_CS_fsm.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it7.read()) && !(ap_sig_bdd_79.read() && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it6.read()))))) { int_buffer_ce0 = ap_const_logic_1; } else { int_buffer_ce0 = ap_const_logic_0; } } void load_points_buffer::thread_int_buffer_ce1() { if (((esl_seteq<1,3,3>(ap_ST_pp1_stg0_fsm_2, ap_CS_fsm.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp1_it0.read())) || (esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp1_it0.read()) && esl_seteq<1,3,3>(ap_ST_pp1_stg1_fsm_3, ap_CS_fsm.read())))) { int_buffer_ce1 = ap_const_logic_1; } else { int_buffer_ce1 = ap_const_logic_0; } } void load_points_buffer::thread_int_buffer_d0() { int_buffer_d0 = bus_addr_read_reg_363.read(); } void load_points_buffer::thread_int_buffer_we0() { if (((esl_seteq<1,3,3>(ap_ST_pp0_stg0_fsm_1, ap_CS_fsm.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it7.read()) && !(ap_sig_bdd_79.read() && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it6.read())) && esl_seteq<1,1,1>(ap_const_lv1_0, ap_reg_ppstg_exitcond2_reg_350_pp0_it6.read())))) { int_buffer_we0 = ap_const_logic_1; } else { int_buffer_we0 = ap_const_logic_0; } } void load_points_buffer::thread_isIter0_fu_251_p2() { isIter0_fu_251_p2 = (!indvar_phi_fu_192_p4.read().is_01() || !ap_const_lv6_0.is_01())? sc_lv<1>(): sc_lv<1>(indvar_phi_fu_192_p4.read() == ap_const_lv6_0); } void load_points_buffer::thread_p_shl_cast_fu_290_p1() { p_shl_cast_fu_290_p1 = esl_zext<7,6>(p_shl_fu_282_p3.read()); } void load_points_buffer::thread_p_shl_fu_282_p3() { p_shl_fu_282_p3 = esl_concat<4,2>(tmp_24_fu_278_p1.read(), ap_const_lv2_0); } void load_points_buffer::thread_tmp_1_fu_213_p2() { tmp_1_fu_213_p2 = (!address.read().is_01() || !offset.read().is_01())? sc_lv<32>(): (sc_bigint<32>(address.read()) + sc_biguint<32>(offset.read())); } void load_points_buffer::thread_tmp_24_fu_278_p1() { tmp_24_fu_278_p1 = i_phi_fu_204_p4.read().range(4-1, 0); } void load_points_buffer::thread_tmp_3_cast_fu_229_p1() { tmp_3_cast_fu_229_p1 = esl_zext<64,30>(tmp_3_fu_219_p4.read()); } void load_points_buffer::thread_tmp_3_fu_219_p4() { tmp_3_fu_219_p4 = tmp_1_fu_213_p2.read().range(31, 2); } void load_points_buffer::thread_tmp_5_fu_294_p2() { tmp_5_fu_294_p2 = (!p_shl_cast_fu_290_p1.read().is_01() || !i_cast1_fu_274_p1.read().is_01())? sc_lv<7>(): (sc_bigint<7>(p_shl_cast_fu_290_p1.read()) - sc_biguint<7>(i_cast1_fu_274_p1.read())); } void load_points_buffer::thread_tmp_6_fu_324_p1() { tmp_6_fu_324_p1 = esl_zext<64,5>(i_reg_200.read()); } void load_points_buffer::thread_tmp_8_1_fu_309_p2() { tmp_8_1_fu_309_p2 = (!tmp_5_fu_294_p2.read().is_01() || !ap_const_lv7_1.is_01())? sc_lv<7>(): (sc_bigint<7>(tmp_5_fu_294_p2.read()) + sc_biguint<7>(ap_const_lv7_1)); } void load_points_buffer::thread_tmp_8_2_fu_330_p2() { tmp_8_2_fu_330_p2 = (!tmp_5_reg_377.read().is_01() || !ap_const_lv7_2.is_01())? sc_lv<7>(): (sc_bigint<7>(tmp_5_reg_377.read()) + sc_biguint<7>(ap_const_lv7_2)); } void load_points_buffer::thread_tmp_9_1_fu_319_p0() { tmp_9_1_fu_319_p0 = esl_sext<32,7>(tmp_8_1_fu_309_p2.read()); } void load_points_buffer::thread_tmp_9_1_fu_319_p1() { tmp_9_1_fu_319_p1 = esl_zext<64,32>(tmp_9_1_fu_319_p0.read()); } void load_points_buffer::thread_tmp_9_2_fu_339_p0() { tmp_9_2_fu_339_p0 = esl_sext<32,7>(tmp_8_2_fu_330_p2.read()); } void load_points_buffer::thread_tmp_9_2_fu_339_p1() { tmp_9_2_fu_339_p1 = esl_zext<64,32>(tmp_9_2_fu_339_p0.read()); } void load_points_buffer::thread_tmp_9_fu_304_p0() { tmp_9_fu_304_p0 = esl_sext<32,7>(tmp_5_fu_294_p2.read()); } void load_points_buffer::thread_tmp_9_fu_304_p1() { tmp_9_fu_304_p1 = esl_zext<64,32>(tmp_9_fu_304_p0.read()); } void load_points_buffer::thread_tmp_s_fu_257_p1() { tmp_s_fu_257_p1 = esl_zext<64,6>(ap_reg_ppstg_indvar_reg_188_pp0_it6.read()); } void load_points_buffer::thread_ap_NS_fsm() { switch (ap_CS_fsm.read().to_uint()) { case 0 : if (!esl_seteq<1,1,1>(ap_start.read(), ap_const_logic_0)) { ap_NS_fsm = ap_ST_pp0_stg0_fsm_1; } else { ap_NS_fsm = ap_ST_st1_fsm_0; } break; case 1 : if ((!(esl_seteq<1,3,3>(ap_ST_pp0_stg0_fsm_1, ap_CS_fsm.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it7.read()) && !(ap_sig_bdd_79.read() && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it6.read())) && !esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it6.read())) && !(esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it0.read()) && !(ap_sig_bdd_79.read() && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it6.read())) && !esl_seteq<1,1,1>(ap_const_lv1_0, exitcond2_fu_239_p2.read()) && !esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it1.read())))) { ap_NS_fsm = ap_ST_pp0_stg0_fsm_1; } else if (((esl_seteq<1,3,3>(ap_ST_pp0_stg0_fsm_1, ap_CS_fsm.read()) && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it7.read()) && !(ap_sig_bdd_79.read() && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it6.read())) && !esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it6.read())) || (esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it0.read()) && !(ap_sig_bdd_79.read() && esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it6.read())) && !esl_seteq<1,1,1>(ap_const_lv1_0, exitcond2_fu_239_p2.read()) && !esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp0_it1.read())))) { ap_NS_fsm = ap_ST_pp1_stg0_fsm_2; } else { ap_NS_fsm = ap_ST_pp0_stg0_fsm_1; } break; case 2 : if (!(esl_seteq<1,1,1>(ap_const_logic_1, ap_reg_ppiten_pp1_it0.read()) && !esl_seteq<1,1,1>(ap_const_lv1_0, exitcond1_fu_262_p2.read()))) { ap_NS_fsm = ap_ST_pp1_stg1_fsm_3; } else { ap_NS_fsm = ap_ST_st13_fsm_4; } break; case 3 : ap_NS_fsm = ap_ST_pp1_stg0_fsm_2; break; case 4 : ap_NS_fsm = ap_ST_st1_fsm_0; break; default : ap_NS_fsm = (sc_lv<3>) ("XXX"); break; } } }
#include <stdio.h> #include <stdlib.h> #include <sys/signal.h> #include "transx_def.hpp" #include "transx_manager.hpp" #include "transx_extern.hpp" #include <unistd.h> #include <iostream> #include <fstream> #include <pthread.h> #include <ctime> #include <sys/types.h> #include <sys/syscall.h> #define gettid() syscall(SYS_gettid) extern void *start_operation(long, long); //starts operation by doing conditional wait extern void *finish_operation(long); // finishes abn operation by removing conditional wait extern void *open_logfile_for_append(); //opens log file for writing extern void *do_commit_abort(long, char); //commit/abort based on char value (the code is same for us) extern transx_manager *t_manager; // Transaction manager object FILE *logfile; //declare globally to be used by all /* Transaction class constructor */ /* Initializes transaction id and status and thread id */ /* Input: Transaction id, status, thread id */ transx::transx(long tid, char Txstatus, char type, pthread_t thrid) { this->lockmode = (char) ' '; //default this->Txtype = type; //R = read only, W=Read/Write this->sgno = 1; this->tid = tid; this->obno = -1; //set it to a invalid value this->status = Txstatus; this->pid = thrid; this->head = NULL; this->nextr = NULL; this->semno = -1; //init to an invalid sem value } /* Method used to obtain reference to a transaction node */ /* Inputs the transaction id. Makes a linear scan over the */ /* linked list of transaction nodes and returns the reference */ /* of the required node if found. Otherwise returns NULL */ transx* get_tx(long tid1) { transx *txptr, *lastr1; if (t_manager->lastr != NULL) { // If the list is not empty lastr1 = t_manager->lastr; // Initialize lastr1 to first node's ptr for (txptr = lastr1; (txptr != NULL); txptr = txptr->nextr) if (txptr->tid == tid1) // if required id is found return txptr; return (NULL); // if not found in list return NULL } return (NULL); // if list is empty return NULL } // routine to start an operation by checking the previous operation of the same // tx has completed; otherwise, it will do a conditional wait until the // current thread signals a broadcast void *start_operation(long tid, long count) { cout << "thread: "<< gettid() << "calling start_operation " << tid<< " "<< count<< "\n"; pthread_mutex_lock(&t_manager->mutexpool[tid]); // Lock mutex[t] to make other // threads of same transaction to wait while (t_manager->condset[tid] != count) // wait if condset[t] is != count pthread_cond_wait(&t_manager->condpool[tid], &t_manager->mutexpool[tid]); } // Otherside of the start operation; // signals the conditional broadcast void *finish_operation(long tid) { cout << "thread: "<< gettid() << "calling finish_operation " << tid<< " "<<t_manager->condset[tid]<< "\n"; t_manager->condset[tid]--; // decr condset[tid] for allowing the next op pthread_cond_broadcast(&t_manager->condpool[tid]); // other waiting threads of same tx pthread_mutex_unlock(&t_manager->mutexpool[tid]); } /* Method that handles "BeginTx tid" in test file */ /* Inputs a pointer to transaction id, obj pair as a struct. Creates a new */ /* transaction node, initializes its data members and */ /* adds it to transaction list */ void *begintx(void *arg) { #ifdef TM_DEBUG cout << "thread: "<< gettid() << " entering begintx\n"; #endif struct t_info *td = (struct t_info*) arg; //YOUR CODE HERE start_operation(td->tid, td->count); fflush(stdout); // create a new transx object transx *newTr = new transx(td->tid, TR_ACTIVE, td->type, pthread_self()); transx_P(0); // add to the list if (t_manager->lastr == NULL) t_manager->lastr = newTr; else { newTr->nextr = t_manager->lastr; t_manager->lastr = newTr; } transx_V(0); finish_operation(td->tid); #ifdef TM_DEBUG cout << "thread: "<< gettid() << " leaving begintx\n"; #endif pthread_exit(NULL); } /* Method to handle Readtx action in test file */ /* Inputs a pointer to structure that contans */ /* tx id and object no to read. Reads the object */ /* if the object is not yet present in hash table */ /* or same tx holds a lock on it. Otherwise waits */ /* until the lock is released */ void *readtx(void *arg) { #ifdef TM_DEBUG cout << "thread: "<< gettid() << " entering readtx\n"; #endif //YOUR CODE HERE struct t_info *td = (struct t_info*) arg; start_operation (td->tid, td->count); transx_P(0); transx *curr_tx = get_tx(td->tid); cout << curr_tx; // if this transaction does not exist then return if (curr_tx == NULL) { cout << "thread: "<< gettid() << " Trying to read a nonexistent transaction: "<<td->tid<<"\n"; transx_V(0); finish_operation (td->tid); pthread_exit(NULL); return (0); } // if this transaction is aborted then return else perform read if (curr_tx->status != TR_ABORT) { curr_tx->set_lock(curr_tx->tid, 1, td->obno, td->count, 'S'); } else { //cout << "thread: "<< gettid() <<" abort the transaction marked abort\n"; //curr_tx->status = TR_ABORT; //do_commit_abort(curr_tx->tid, curr_tx->status); transx_V(0); } #ifdef TM_DEBUG cout << "thread: "<< gettid() <<" leaving readtx\n"; fflush(stdout); #endif finish_operation (td->tid); pthread_exit(NULL); } /*Similar with readtx but to handle Writetx action*/ void *writetx(void *arg) { #ifdef TM_DEBUG cout << "thread: "<< gettid() <<" entering writetx\n"; #endif //YOUR CODE HERE struct t_info *td = (struct t_info*) arg; start_operation (td->tid, td->count); transx_P(0); transx *curr_tx = get_tx(td->tid); // if this transaction does not exist then return if (curr_tx == NULL) { cout <<"thread: "<< gettid() <<" Trying to read a nonexistent transaction: "<<td->tid<<"\n"; transx_V(0); finish_operation (td->tid); pthread_exit(NULL); return (0); } // if this transaction is already aborted then return else perform write if (curr_tx->status != TR_ABORT) { curr_tx->set_lock(curr_tx->tid, 1, td->obno, td->count, 'X'); } else { //curr_tx->status = TR_ABORT; //do_commit_abort(curr_tx->tid, curr_tx->status); transx_V(0); } #ifdef TM_DEBUG cout << "thread: "<< gettid() <<" leaving writetx\n"; #endif finish_operation (td->tid); pthread_exit(NULL); } /*Handle of abort action*/ void *aborttx(void *arg) { //YOUR CODE HERE #ifdef TM_DEBUG cout << "thread: "<< gettid() <<" entering aborttx\n"; #endif struct t_info *td = (struct t_info*) arg; start_operation (td->tid, td->count); transx_P(0); // call abort transaction after setting locks. do_commit_abort(td->tid, TR_ABORT) ; transx_V(0); finish_operation (td->tid); pthread_exit(NULL); #ifdef TM_DEBUG cout << "thread: "<< gettid() <<" leaving aborttx\n"; #endif } /*Handle of commit action*/ void *committx(void *arg) { //YOUR CODE HERE #ifdef TM_DEBUG cout<<"thread: "<< gettid() <<" entering committx\n"; #endif struct t_info *td = (struct t_info*) arg; start_operation (td->tid, td->count); transx_P(0); transx *curr_tx = get_tx(td->tid); // if this transaction does not exist then return if (curr_tx == NULL) { cout <<"thread: "<< gettid() <<" ERROR: Trying to commit/abort a non existent transaction\n"; transx_V(0); finish_operation (td->tid); pthread_exit(NULL); return(0); } // if this transaction is already aborted then return /*if (curr_tx->status == TR_ABORT) { cout << "thread: "<< gettid() << "calling transx_V(0) from committx \n"; transx_V(0); finish_operation (td->tid); cout << "thread: "<< gettid() <<" leaving committx\n"; pthread_exit(NULL); return(0); }*/ if (curr_tx->status != TR_ABORT) { // if this transaction is not aborted then continue do_commit_abort(td->tid, TR_END) ; } transx_V(0); finish_operation (td->tid); #ifdef TM_DEBUG cout << "thread: "<< gettid() <<" leaving committx\n"; #endif pthread_exit(NULL); } /* this method sets lock on objno1 with lockmode1 for a tx in this*/ int transx::set_lock(long tid1, long sgno1, long obno1, int count, char lockmode1) { //if the thread has to wait, block the thread on a semaphore from the //sempool in the transaction manager. Set the appropriate parameters in the //transaction list if waiting. //if successful return(0); // If the owner is different, current txn may go to deadlock // so we will put the transaction in waiting mode and see if deadlock happens // If the requested object is no longer acquired by any other transaction, // we will lock the object for this transaction //YOUR CODE HERE #ifdef TM_DEBUG cout << "thread: "<< gettid() <<" entering TxWnsx::set_lock\n"; #endif int t_status; //open_logfile_for_append(); transx_hlink *amIowner = hash_t1->findt(this->tid, sgno1, obno1); // if this object is not occupied by current transaction else then // check who is the owner if (amIowner == NULL) { transx_hlink * whoIsOwner = hash_t1->find(sgno1, obno1); if (whoIsOwner == NULL) { hash_t1->add(this, sgno1, obno1, lockmode1); transx_V(0); perform_readWrite(tid1, obno1, lockmode1); } else { //if requested object is acquired by other transaction //then wait till the object becomes free //also check if we can enter deadlock while waiting #ifdef TM_DEBUG cout << "thread: "<< gettid() << " " << whoIsOwner->tid << " is owner of "<< obno1 <<"\n"; #endif transx_V(0); //Set the appropriate parameters in the transaction list if waiting wait_for *dd = new wait_for(); this->setTx_semno(whoIsOwner->tid, whoIsOwner->tid); this->status = TR_WAIT; this->lockmode = lockmode1; this->obno = obno1; // make this transaction wait so that we can check if we have a deadlock if (dd->deadlock() != 1) { #ifdef TM_DEBUG cout << "thread: "<< gettid() <<" owner tid: " << whoIsOwner->tid<<"\n"; #endif // if deadlock wont happen then we can continue transx_P(whoIsOwner->tid); if (this->status != TR_ABORT) this->status = TR_ACTIVE; transx_P(0); set_lock(this->tid, sgno1, obno1, count, lockmode1); } //since currently in this peroject perform_readwrite() is modifying the value of //object even for read operation ('S' lock mode) hence we did not distinguish this //function for 'S' and 'X' lock mode. //If, read was not modifying the objects value then set_lock would allow two 'S' transactions //together while blcoking the writes. //Still, we are implementing this effect here by not aborting if the transaction is demanding //a shared lock when we do wound wait( instead we ask it to wait). //We only abort when we are requesting 'X' lock. } } else { // if this object is occupied by current transaction then // we can continue performing read write #ifdef TM_DEBUG cout << "thread: "<< gettid() << " " << this->tid <<" is owner of "<< obno1 <<"\n"; #endif this->status = TR_ACTIVE; this->lockmode = lockmode1; transx_V(0); this->perform_readWrite(tid, obno1, lockmode1); } #ifdef TM_DEBUG cout<<"thread: "<< gettid() <<" leaving TxWnsx::set_lock\n"; #endif return (0); } // this part frees all locks owned by the transaction // Need to free the thread in the waiting queue // try to obtain the lock for the freed threads // if the process itself is blocked, clear the wait and semaphores int transx::free_locks() { //YOUR CODE HERE #ifdef TM_DEBUG cout<<"thread: "<< gettid() <<" entering transx::free_locks \n"; #endif //open_logfile_for_append(); transx_hlink *link = head; while (link != NULL) { hash_t1->remove(this, 1, (long)link->obno) ; link = link->nextp; } fprintf(logfile, "\n"); fflush(logfile); #ifdef TM_DEBUG cout<< "thread: "<< gettid() <<" leaving transx::free_locks\n"; #endif return(0); } // called from commit/abort with appropriate parameter to do the actual // operation. Make sure you give error messages if you are trying to // commit/abort a non-existant tx void *do_commit_abort(long t, char status) { //YOUR CODE HERE #ifdef TM_DEBUG cout<<"thread: "<< gettid() << " entering do_commit_abort\n"; #endif int waiting; transx *curr_tx = get_tx(t); open_logfile_for_append(); if (curr_tx == NULL) { return(0); } //set the status to commit or abort curr_tx->status = status; if (status == TR_END) { fprintf(logfile, "T%d\t \tCommitTx\t\t\t\t \t\t %c\n", curr_tx->tid, curr_tx->status); fflush(logfile); } else { fprintf(logfile, "T%d\t \tAbortTx\t\t\t\t \t\t %c\n", curr_tx->tid, curr_tx->status); fflush(logfile); } // check if there are transactions waiting for this semaphore // if yes then release the semaphore if(curr_tx->semno >= 0){ waiting = transx_wait(curr_tx->semno); if (waiting > 0) { for (int i = waiting; i > 0; i--) { transx_V(curr_tx->semno); } } } //free all the locks which are held by this transaction //before removing it from the transaction manager list curr_tx->free_locks(); curr_tx->remove_tx(); #ifdef TM_DEBUG cout<<"thread: "<< gettid() <<" leaving do_commit_abort\n"; #endif } int transx::remove_tx() { //remove the transaction from the TM transx *txptr, *lastr1; lastr1 = t_manager->lastr; for (txptr = t_manager->lastr; txptr != NULL; txptr = txptr->nextr) { // scan through list if (txptr->tid == this->tid) { // if req node is found lastr1->nextr = txptr->nextr; // update nextr value; done //delete this; return (0); } else lastr1 = txptr->nextr; // else update prev value } fprintf(logfile, "Trying to Remove a Tx:%d that does not exist\n", this->tid); fflush(logfile); printf("Trying to Remove a Tx:%d that does not exist\n", this->tid); fflush(stdout); return (-1); } // CURRENTLY Not USED // USED to COMMIT // remove the transaction and free all associate dobjects. For the time being // this can be used for commit of the transaction. int transx::end_tx() { transx *linktx, *prevp; linktx = prevp = t_manager->lastr; while (linktx) { if (linktx->tid == this->tid) break; prevp = linktx; linktx = linktx->nextr; } if (linktx == NULL) { printf("\ncannot remove a Tx node; error\n"); fflush(stdout); return (1); } if (linktx == t_manager->lastr) t_manager->lastr = linktx->nextr; else { prevp = t_manager->lastr; while (prevp->nextr != linktx) prevp = prevp->nextr; prevp->nextr = linktx->nextr; } } // check which other transaction has the lock on the same obno // returns the hash node transx_hlink * transx::others_lock(transx_hlink *hnodep, long sgno1, long obno1) { transx_hlink *ep; ep = hash_t1->find(sgno1, obno1); while (ep) // while ep is not null { if ((ep->obno == obno1)&&(ep->sgno == sgno1)&&(ep->tid != this->tid)) return (ep); // return the hashnode that holds the lock else ep = ep->next; } return (NULL); // Return null otherwise } // routine to print the tx list // TX_DEBUG should be defined in the Makefile to print void transx::print_tm() { transx *txptr; #ifdef TX_DEBUG printf("printing the tx list \n"); printf("Tid\tTxType\tThrid\t\tobjno\tlock\tstatus\tsemno\n"); fflush(stdout); #endif txptr = t_manager->lastr; while (txptr != NULL) { #ifdef TX_DEBUG printf("%d\t%c\t%d\t%d\t%c\t%c\t%d\n", txptr->tid, txptr->Txtype, txptr->pid, txptr->obno, txptr->lockmode, txptr->status, txptr->semno); fflush(stdout); #endif txptr = txptr->nextr; } fflush(stdout); } // routine to perform the acutual read/write operation // based on the lockmode void transx::perform_readWrite(long tid, long obno, char lockmode) { int j; double result = 0.0; cout <<"thread: "<< gettid() <<" In read write\n"; open_logfile_for_append(); int obValue = t_manager->objarray[obno]->value; if (this->status != TR_ABORT) { if (lockmode == 'X') // write op { t_manager->objarray[obno]->value = obValue + 1; // update value of obj fprintf(logfile, "T%d\t \tWriteTx\t\t%d:%d:%d\tWriteLock\tGranted\t\t %c\n", this->tid, obno, t_manager->objarray[obno]->value, t_manager->optime[tid], this->status); fflush(logfile); for (j = 0; j < t_manager->optime[tid]*20; j++) result = result + (double) random(); } else { //read op t_manager->objarray[obno]->value = obValue - 1; // update value of obj fprintf(logfile, "T%d\t \tReadTx\t\t%d:%d:%d\tReadLock\tGranted\t\t %c\n", this->tid, obno, t_manager->objarray[obno]->value, t_manager->optime[tid], this->status); fflush(logfile); for (j = 0; j < t_manager->optime[tid]*10; j++) result = result + (double) random(); } } cout <<"thread: "<< gettid() <<" exit read write\n"; } // routine that sets the semno in the Tx when another tx waits on it. // the same number is the same as the tx number on which a Tx is waiting int transx::setTx_semno(long tid, int semno) { transx *txptr; txptr = get_tx(tid); if (txptr == NULL) { printf("\n:::ERROR:Txid %d wants to wait on sem:%d of tid:%d which does not exist\n", this->tid, semno, tid); fflush(stdout); return (-1); } if (txptr->semno == -1) { txptr->semno = semno; return (0); } else if (txptr->semno != semno) { #ifdef TX_DEBUG printf(":::ERROR Trying to wait on sem:%d, but on Tx:%d\n", semno, txptr->tid); fflush(stdout); #endif exit(1); } return (0); } void *open_logfile_for_append() { if ((logfile = fopen(t_manager->logfile, "a")) == NULL) { printf("\nCannot open log file for append:%s\n", t_manager->logfile); fflush(stdout); exit(1); } }
#include "globals.h" namespace { ColorVectorMap InitColorMap() { ColorVectorMap map; map['F'] = std::tr1::shared_ptr<ColorVector>(new ColorVector(1.0f, 0.0f, 0.0f)); map['B'] = std::tr1::shared_ptr<ColorVector>(new ColorVector(0.0f, 1.0f, 0.0f)); map['U'] = std::tr1::shared_ptr<ColorVector>(new ColorVector(0.0f, 0.0f, 1.0f)); map['D'] = std::tr1::shared_ptr<ColorVector>(new ColorVector(1.0f, 1.0f, 0.0f)); map['L'] = std::tr1::shared_ptr<ColorVector>(new ColorVector(1.0f, 0.0f, 1.0f)); map['R'] = std::tr1::shared_ptr<ColorVector>(new ColorVector(0.0f, 1.0f, 1.0f)); return map; } } ColorVectorMap ColorMap = InitColorMap(); float CameraSpeed = 1.0f; float RotateSpeed = 1.0f;
#include <bits/stdc++.h> using namespace std; int main(){ int n; cin >> n; for (int x=1; x<=n; ++x){ for (int y=1; y<=n; ++y){ if (y<x){ cout << " "; } else { cout << "*"; } } cout << "\n"; } }
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<assert.h> #include<stdlib.h> #include"glut.h" #define GET_ARRAY_SIZE(a) (sizeof(a)/sizeof(a[0])) #define quadsR (.5f) #define height (14) #define width (78) int* map; int* readCsv(char* _fileName, const int _width, const int _height){ char buff[256]; int num; FILE *pFile = fopen( _fileName, "r" ); assert(pFile != NULL); int *_p = (int*)malloc(sizeof(int)*_width*_height); for (int i = 0; i < _width*_height; i++){ if (fscanf(pFile, "%d", &num) != NULL){ _p[i] = num; fscanf(pFile, "%1s", buff); } else{ printf("ファイルデータが正しくありません。\n"); getchar(); exit(0); } } return _p; } void display(){ glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective( 60, 1, 0.1, 100); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt( width / 2, 0, 70,//GLdouble eyex,eyey,eyez, width / 2, 0, 0,//GLdouble centerx,centery,centerz, 0, 1, 0);//GLdouble upx,upy, upz static unsigned char indices[] = { 0, 1, 2, 1, 3, 2 }; for (int i = 0; i < height; i++){ for (int n = 0; n < width; n++){ if (map[i*width+n]!=0){ float v[] = { -quadsR + n, quadsR - i, -quadsR + n, -quadsR - i, quadsR + n, quadsR - i, quadsR + n, -quadsR - i }; glEnableClientState(GL_VERTEX_ARRAY); // GLenum array glVertexPointer( 2, GL_FLOAT, 0, v);//GLint size, GLenum type, GLsizei stride, const GLvoid *pointer glDrawElements( GL_TRIANGLES, GET_ARRAY_SIZE(indices), GL_UNSIGNED_BYTE, indices); } } } glFlush(); } void timer(int value){ glutPostRedisplay();//再描画 glutTimerFunc( 1000 / 60, timer, 0); //unsigned int millis, void (GLUTCALLBACK *func)(int value), int value } void main(int argc,char*argv[]){ map = readCsv("map.csv", width, height); for (int i = 0; i < width * height; i++){ if ((i + 1) % width == 0){ printf("%d\n", map[i]); } else{ printf("%d", map[i]); } } glutInit(&argc, argv); glutCreateWindow(argv[0]); glutDisplayFunc(display);//void (GLUTCALLBACK *func)(void) glutTimerFunc( 0, timer, 0); //unsigned int millis, void (GLUTCALLBACK *func)(int value), int value glutMainLoop(); }
#define VC_EXTRALEAN #define _USE_MATH_DEFINES #include <windows.h> #include <commctrl.h> #include <scrnsave.h> #include <gdiplus.h> #include <time.h> #include <math.h> #include <string> #include "resource.h" #pragma comment(lib, "scrnsavw.lib") #pragma comment (lib, "comctl32.lib") using namespace Gdiplus; #pragma comment(lib, "gdiplus.lib") static HDC g_hDC = NULL; static HBITMAP g_hBmp = NULL; static HFONT g_hFontResource = NULL; static HFONT g_hLargeFont = NULL; static HFONT g_hSmallFont = NULL; static SIZE g_screenSize; static SIZE g_largeTextSize; static BOOL g_is24Hour; static BOOL g_AnimatedClockHands; static GdiplusStartupInput g_gdiplusStartupInput; static ULONG_PTR g_gdiplusToken; extern HINSTANCE hMainInstance; TCHAR szAppName[APPNAMEBUFFERLEN]; TCHAR szIniFile[MAXFILELEN]; const TCHAR szFormatOptionName[] = TEXT("Use24Hour"); const TCHAR szClockHandOptionName[] = TEXT("AnimatedClockHands"); #define DRAW_TIMER 0x1 void Init(HWND hWnd); void UpdateFrame(HWND hWnd); LRESULT WINAPI ScreenSaverProcW(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch(message) { case WM_CREATE: { Init(hWnd); break; } case WM_DESTROY: { KillTimer(hWnd, DRAW_TIMER); ReleaseDC(hWnd, g_hDC); DeleteObject(g_hDC); DeleteObject(g_hBmp); DeleteObject(g_hLargeFont); DeleteObject(g_hSmallFont); RemoveFontMemResourceEx(g_hFontResource); GdiplusShutdown(g_gdiplusToken); break; } case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hWnd, &ps); BitBlt(hdc, 0, 0, g_screenSize.cx, g_screenSize.cy, g_hDC, 0, 0, SRCCOPY); EndPaint(hWnd, &ps); return 0; break; } case WM_TIMER: { if (wParam == DRAW_TIMER) UpdateFrame(hWnd); break; } } return DefScreenSaverProc(hWnd, message, wParam, lParam); } void LoadConfiguration() { LoadString(hMainInstance, idsAppName, szAppName, APPNAMEBUFFERLEN); LoadString(hMainInstance, idsIniFile, szIniFile, MAXFILELEN); g_is24Hour = GetPrivateProfileInt(szAppName, szFormatOptionName, FALSE, szIniFile); g_AnimatedClockHands = GetPrivateProfileInt(szAppName, szClockHandOptionName, FALSE, szIniFile); } void Init(HWND hWnd) { LoadConfiguration(); GdiplusStartup(&g_gdiplusToken, &g_gdiplusStartupInput, NULL); RECT r; GetClientRect(hWnd, &r); g_screenSize.cy = r.bottom - r.top; g_screenSize.cx = r.right - r.left; HDC hDc = GetDC(hWnd); g_hBmp = CreateCompatibleBitmap(hDc, g_screenSize.cx, g_screenSize.cy); g_hDC = CreateCompatibleDC(hDc); ReleaseDC(hWnd, hDc); SelectObject(g_hDC, g_hBmp); SetTextColor(g_hDC, RGB(255, 255, 255)); SetBkColor(g_hDC, RGB(0, 0, 0)); { // Load Geo-sans Light font from application resources. HMODULE hResInstance = NULL; HRSRC hResource = FindResource(hResInstance, MAKEINTRESOURCE(IDR_FONT_GEOSANSLIGHT), TEXT("BINARY")); if (hResource) { HGLOBAL mem = LoadResource(hResInstance, hResource); if (mem) { void *data = LockResource(mem); size_t len = SizeofResource(hResInstance, hResource); DWORD nFonts; g_hFontResource = (HFONT)AddFontMemResourceEx(data, len, NULL, &nFonts); } DeleteObject(mem); } LOGFONT lf; memset(&lf, 0, sizeof(lf)); wcscpy_s(lf.lfFaceName, TEXT("GeosansLight")); lf.lfQuality = ANTIALIASED_QUALITY; lf.lfHeight = g_screenSize.cy / 5; g_hLargeFont = CreateFontIndirect(&lf); SelectObject(g_hDC, g_hLargeFont); const TCHAR szPlaceholder[] = TEXT("00:00:00"); GetTextExtentPoint32(g_hDC, szPlaceholder, sizeof(szPlaceholder) / sizeof(TCHAR) - 1, &g_largeTextSize); g_largeTextSize.cx = g_largeTextSize.cx + g_largeTextSize.cx / 25; lf.lfHeight = g_screenSize.cy / 28; g_hSmallFont = CreateFontIndirect(&lf); } SetTimer(hWnd, DRAW_TIMER, 1000, NULL); UpdateFrame(hWnd); } void UpdateFrame(HWND hWnd) { tm timeinfo; time_t rawtime; time(&rawtime); localtime_s(&timeinfo, &rawtime); REAL clock_diameter = g_screenSize.cy / 25.0f; REAL clock_left = g_screenSize.cx - g_largeTextSize.cx - g_largeTextSize.cx / 9.0f; { // Draw analog clock REAL clock_radius = clock_diameter / 2.0f; REAL clock_top = (g_screenSize.cy + g_largeTextSize.cy) / 2.0f - clock_diameter * 2.0f; REAL clock_centerX = clock_left + clock_radius; REAL clock_centerY = clock_top + clock_radius; REAL clock_handWidth = clock_radius / 4.0f; REAL clock_handGap = clock_handWidth * 1.75; REAL clock_minuteAngle = -M_PI_2; REAL clock_hourAngle = M_PI_4; if (g_AnimatedClockHands) { clock_minuteAngle = timeinfo.tm_min / 60.0f * M_PI * 2 - M_PI_2; clock_hourAngle = timeinfo.tm_hour / 12.0f * M_PI * 2 - M_PI_2 + clock_minuteAngle / 12; } Graphics graphics(g_hDC); graphics.SetSmoothingMode(SmoothingModeAntiAlias); graphics.Clear(Color(0, 0, 0)); Pen pen(Color(255, 255, 255), clock_handWidth + 1); graphics.DrawEllipse(&pen, clock_left, clock_top, clock_diameter, clock_diameter); pen.SetWidth(clock_handWidth - 0.5f); pen.SetStartCap(LineCapRound); graphics.DrawLine(&pen, clock_centerX, clock_centerY, clock_centerX + cos(clock_hourAngle) * (clock_radius - clock_handGap), clock_centerY + sin(clock_hourAngle) * (clock_radius - clock_handGap)); graphics.DrawLine(&pen, clock_centerX, clock_centerY, clock_centerX + cos(clock_minuteAngle) * (clock_radius - clock_handGap), clock_centerY + sin(clock_minuteAngle) * (clock_radius - clock_handGap)); } { // Draw time text const size_t nBufferSize = 16; TCHAR szBuffer[nBufferSize]; wcsftime(szBuffer, nBufferSize, g_is24Hour ? TEXT("%H:%M:%S") : TEXT("%I:%M:%S"), &timeinfo); std::wstring strval(szBuffer); SelectObject(g_hDC, g_hLargeFont); TextOut(g_hDC, g_screenSize.cx - g_largeTextSize.cx, (g_screenSize.cy - g_largeTextSize.cy) / 2, strval.c_str(), strval.size()); if (!g_is24Hour) { // Draw AM/PM wcsftime(szBuffer, nBufferSize, TEXT("%p"), &timeinfo); strval = szBuffer; SelectObject(g_hDC, g_hSmallFont); SIZE smallTextSize; GetTextExtentPoint32(g_hDC, strval.c_str(), strval.size(), &smallTextSize); TextOut(g_hDC, clock_left - (smallTextSize.cx - clock_diameter) / 2, (g_screenSize.cy - smallTextSize.cy) / 2, strval.c_str(), strval.size()); } } RECT r; GetClientRect(hWnd, &r); InvalidateRect(hWnd, &r, false); } BOOL WINAPI ScreenSaverConfigureDialog(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { switch(message) { case WM_INITDIALOG: { LoadConfiguration(); CheckDlgButton(hDlg, IDC_24HOUR_CHECK, g_is24Hour); CheckDlgButton(hDlg, IDC_ANIMATEHANDS_CHECK, g_AnimatedClockHands); return TRUE; } case WM_COMMAND: { switch(LOWORD(wParam)) { case ID_OK: { TCHAR szBuffer[8]; g_is24Hour = IsDlgButtonChecked(hDlg, IDC_24HOUR_CHECK); _itow_s(g_is24Hour, szBuffer, 10); WritePrivateProfileString(szAppName, szFormatOptionName, szBuffer, szIniFile); g_AnimatedClockHands = IsDlgButtonChecked(hDlg, IDC_ANIMATEHANDS_CHECK); _itow_s(g_AnimatedClockHands, szBuffer, 10); WritePrivateProfileString(szAppName, szClockHandOptionName, szBuffer, szIniFile); } case ID_CANCEL: { EndDialog(hDlg, LOWORD(wParam) == ID_OK); return TRUE; } } break; } case WM_NOTIFY: { LPNMHDR pnmh = (LPNMHDR)lParam; if (pnmh->idFrom == IDC_SYSLINK_WEBSITE) { if ((pnmh->code == NM_CLICK) || (pnmh->code == NM_RETURN)) { PNMLINK link = (PNMLINK)lParam; ShellExecute(NULL, TEXT("open"), link->item.szUrl, NULL, NULL, SW_SHOWNORMAL); } } break; } case WM_CLOSE: { EndDialog(hDlg, FALSE); return TRUE; } } return FALSE; } BOOL WINAPI RegisterDialogClasses(HANDLE /*hInst*/) { InitCommonControls(); return TRUE; }
#include <string> #include <vector> #include <iostream> using namespace std; string solution(string s) { string answer = ""; if (s.size()%2==0){ int tmp = s.size()/2 -1; cout<<s[tmp]<<s[tmp+1]<<endl; answer+=s[tmp]; answer+=s[tmp+1]; } else{ int tmp = s.size()/2; answer = s[tmp]; } return answer; } int main(){ cout<<solution("abcde")<<endl; cout<<solution("qwer")<<endl; }
#include "Commands.h" #include "iostream" #include "GlobalVariables.h" MvCommand::MvCommand(string args):BaseCommand(args){ } void MvCommand::execute(FileSystem & fs) { if (verbose == 2 || verbose == 3) cout << toString() + " " + getArgs() << endl; int whereSpace = getArgs().find_first_of(' '); string sourceDir = getArgs().substr(0, whereSpace); string destDir = getArgs().substr(whereSpace + 1); vector<string> *vSource = split(sourceDir); vector<string> *vDest = split(destDir); Directory *initDir = &fs.getWorkingDirectory(); bool success = fs.changeDirectoryFromAddress(*vSource, 1, sourceDir.at(0) == '/', false); if (!success) { cout << "The system cannot find the path specified" << endl; goto endFunc; } else { BaseFile *copy; Directory* dirToRemoveFrom; bool isFound = false; for (int i = 0; !isFound && (unsigned) i < fs.getWorkingDirectory().getChildren().size(); i++) { if (fs.getWorkingDirectory().getChildren().at(i)->getName() == vSource->at(vSource->size() - 1)) { isFound = true; copy = fs.getWorkingDirectory().getChildren().at(i); dirToRemoveFrom=&fs.getWorkingDirectory(); break; } } if (!isFound) { cout << "The system cannot find the path specified" << endl; goto endFunc; } fs.setWorkingDirectory(initDir); success = fs.changeDirectoryFromAddress(*vDest, 0, getArgs()[0] == '/', false); if (!success) { cout << "The system cannot find the path specified" << endl; goto endFunc; } else { if (fs.getWorkingDirectory().fileExists(copy->getName())) { cout << "File already exists" << endl; goto endFunc; } if (copy->getType() == "DIR") { Directory *copyDir = dynamic_cast<Directory *>(copy); fs.getWorkingDirectory().addFile(new Directory(*copyDir)); dirToRemoveFrom->removeFile(copy); copyDir = nullptr; } else { File *copyFile = dynamic_cast<File *>(copy); fs.getWorkingDirectory().addFile(new File(*copyFile)); dirToRemoveFrom->removeFile(copy); copyFile = nullptr; } } } endFunc: delete vSource; delete vDest; fs.setWorkingDirectory(initDir); return; } string MvCommand::toString(){ return "mv"; }
// Fill out your copyright notice in the Description page of Project Settings. #include "./HealthAndDamageComponent.h" #include "./DefenceBuffBaseComponent.h" #include "Net/UnrealNetwork.h" UHealthAndDamageComponent::UHealthAndDamageComponent(const class FObjectInitializer& PCIP) : Super(PCIP) { N_MaxHealth = 100; PrimaryComponentTick.bCanEverTick = false; } void UHealthAndDamageComponent::BeginPlay() { Super::BeginPlay(); if (GetOwner()->HasAuthority()) { N_CurrentHealth = N_MaxHealth; } } void UHealthAndDamageComponent::Server_TakeDamage_Implementation(const int DamageAmount) { int damageAmount = DamageAmount; TArray<UActorComponent*> actorComponents = GetOwner()->GetComponentsByClass(UDefenceBuffBaseComponent::StaticClass()); for (int i = 0; i < actorComponents.Num(); i++) { UDefenceBuffBaseComponent* damageDebuff = Cast<UDefenceBuffBaseComponent>(actorComponents[i]); damageAmount = damageDebuff->TakeDamage(DamageAmount); } const int lastHealth = N_CurrentHealth; N_CurrentHealth -= damageAmount; OnDamageTaken.Broadcast(damageAmount); if (lastHealth != N_CurrentHealth) { OnHealthChanged.Broadcast(N_CurrentHealth); } if (N_CurrentHealth <= 0) { OnUnitDied.Broadcast(GetOwner()); } } void UHealthAndDamageComponent::Server_AddHealth_Implementation(const int HealthAmount) { N_CurrentHealth += HealthAmount; if (N_CurrentHealth > N_MaxHealth) { N_CurrentHealth = N_MaxHealth; } OnHealthChanged.Broadcast(N_CurrentHealth); } void UHealthAndDamageComponent::Server_SetMaxHealth_Implementation(const int HealthAmount, const bool ResetCurrentHealth) { N_MaxHealth = HealthAmount; if (ResetCurrentHealth) { N_CurrentHealth = HealthAmount; } } void UHealthAndDamageComponent::Server_SetHealth_Implementation(const int HealthAmount) { N_CurrentHealth = HealthAmount; if (N_CurrentHealth > N_MaxHealth) { N_CurrentHealth = N_MaxHealth; } OnHealthChanged.Broadcast(N_CurrentHealth); } void UHealthAndDamageComponent::SetMaxHealth(const int HealthAmount, const bool ResetCurrentHealth) { Server_SetMaxHealth(HealthAmount, ResetCurrentHealth); } void UHealthAndDamageComponent::SetHealth(const int HealthAmount) { Server_SetHealth(HealthAmount); } void UHealthAndDamageComponent::AddHealth(const int HealthAmount) { Server_AddHealth(HealthAmount); } void UHealthAndDamageComponent::TakeDamage(const int DamageAmount) { Server_TakeDamage(DamageAmount); } void UHealthAndDamageComponent::OnDataFromNetwork() { OnDataFromServer.Broadcast(); } int UHealthAndDamageComponent::GetCurrentHealth() { return N_CurrentHealth; } void UHealthAndDamageComponent::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); DOREPLIFETIME(UHealthAndDamageComponent, N_MaxHealth); DOREPLIFETIME(UHealthAndDamageComponent, N_CurrentHealth); }
#include "graph.h" #include <fstream> #include <random> #include <chrono> #include <algorithm> void generate_data () { const std::vector<int> dist_sizes {1000, 10000, 100000}; const int upper_bound_diameter = 5000000; const int upper_bound_clustering = 500000; const int reps = 5; const int d = 5; const std::vector<std::string> header_diameter {"diameter.csv", "Nodes", "Diameter"}; const std::vector<std::string> header_clustering {"clustering.csv", "Nodes", "Clustering"}; generate_data_variable_size_data(header_diameter, upper_bound_diameter, reps, d, Algorithm::Diameter); generate_data_variable_size_data(header_clustering, upper_bound_clustering, reps, d, Algorithm::Clustering); // degree distribution for (int sz : dist_sizes) { std::cout << "Degree distribution, doing size: " << sz << std::endl; std::string filename = "deg_distri_" + std::to_string(sz) + ".csv"; create_empty_timings_file({filename, "Degree", "Nodes"}); Graph g = create_barabasi_albert_graph(sz, d); std::vector<std::pair<int, int>> mapping_sorted; std::map<int, int> mapping = get_degree_distribution(g); for (const auto& ele : mapping) { mapping_sorted.push_back(std::make_pair(ele.first, ele.second)); } std::sort(mapping_sorted.begin(), mapping_sorted.end(), [](const std::pair<int, int>& a, const std::pair<int, int>& b){ return a.first < b.first; }); for (const auto& ele : mapping_sorted) { add_timings_to_file({filename, std::to_string(ele.first), std::to_string(ele.second)}); } } } void generate_data_variable_size_data(const std::vector<std::string>& header, int upper_bound, int reps, int d, Algorithm algo) { create_empty_timings_file(header); // Display what we are diong, ie: diameter or clustering std::cout << header.back() << std::endl; for (int sz = 10; sz <= upper_bound; sz *= 2) { std::cout << "Executing size: " << sz << std::endl; double total = 0; for (int rep = 0; rep < reps; ++rep) { Graph g = create_barabasi_albert_graph(sz, d); switch (algo) { case Algorithm::Diameter: total += get_diameter(g); break; case Algorithm::Clustering: total += get_clustering_coefficient(g); break; } } add_timings_to_file({header.front(), std::to_string(sz), std::to_string(total/reps)}); } } void graph_to_file(Graph* g) { if (!g) { return; } const std::vector<std::string> node_file {"file_of_graph_node.csv", "Id", "Label"}; const std::vector<std::string> edge_file {"file_of_graph_edge.csv", "Source", "Target", "Type"}; create_empty_timings_file(node_file); create_empty_timings_file(edge_file); for (const auto& node_id : g->get_ids_nodes()) { for (const auto& node : g->get_neighbors(Node(node_id))) { add_timings_to_file({edge_file.front(), std::to_string(node_id), std::to_string(node.get_m_id()), "Undirected"}); } add_timings_to_file({node_file.front(), std::to_string(node_id), std::to_string(node_id)}); } } void create_empty_timings_file(std::vector<std::string> data) { std::ofstream f; f.open(data.front(), std::ios::trunc); for (unsigned int i = 1; i < data.size(); ++i) { f << data[i]; if (i < data.size() - 1) { f << ","; } } f << "\n"; f.close(); } void add_timings_to_file(std::vector<std::string> data) { std::ofstream f; f.open(data.front(), std::ios::app); for (unsigned int i = 1; i < data.size(); ++i) { f << data[i]; if (i < data.size() - 1) { f << ","; } } f << "\n"; f.close(); } int get_diameter(Graph graph) { unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); std::mt19937 rng = std::mt19937(seed); std::uniform_int_distribution<int> dist(0 + Graph::offset(), graph.get_num_nodes()); int Dmax = 0; Diameter_result ecce = graph.get_eccentricity(dist(rng)); while (ecce.result > Dmax) { Dmax = ecce.result; ecce = graph.get_eccentricity(ecce.to); } return Dmax; } float get_clustering_coefficient(Graph graph) { return static_cast<float>(3 * graph.get_triangles())/graph.total_two_edge_path(); } std::map<int, int> get_degree_distribution(Graph graph) { // vertex to degree mapping, we cant degree to vertex so just reverse std::map<int, int> pre_process = graph.vertex_to_degree_map(); std::map<int, int> post_process; for (std::map<int, int>::iterator itr = pre_process.begin(); itr != pre_process.end(); ++itr) { post_process[itr->second]++; } return post_process; } Graph make_graph(int num_nodes, std::vector<int> u, std::vector<int> v) { if (u.size() != v.size()) { return Graph(); } Graph g; for (int i = 0; i < num_nodes; ++i) { g.add_vertex(); } for (unsigned int i = 0; i < u.size(); ++i) { g.add_edge(u[i], v[i]); } return g; }
// C++ for the Windows Runtime vv1.0.170303.6 // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once #include "base.h" WINRT_WARNING_PUSH #include "internal/Windows.Foundation.3.h" #include "internal/Windows.Foundation.Collections.3.h" #include "internal/Windows.System.Diagnostics.3.h" #include "Windows.System.h" WINRT_EXPORT namespace winrt { namespace impl { template <typename D> struct produce<D, Windows::System::Diagnostics::IProcessCpuUsage> : produce_base<D, Windows::System::Diagnostics::IProcessCpuUsage> { HRESULT __stdcall abi_GetReport(impl::abi_arg_out<Windows::System::Diagnostics::IProcessCpuUsageReport> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().GetReport()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::System::Diagnostics::IProcessCpuUsageReport> : produce_base<D, Windows::System::Diagnostics::IProcessCpuUsageReport> { HRESULT __stdcall get_KernelTime(impl::abi_arg_out<Windows::Foundation::TimeSpan> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().KernelTime()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_UserTime(impl::abi_arg_out<Windows::Foundation::TimeSpan> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().UserTime()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::System::Diagnostics::IProcessDiagnosticInfo> : produce_base<D, Windows::System::Diagnostics::IProcessDiagnosticInfo> { HRESULT __stdcall get_ProcessId(uint32_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().ProcessId()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_ExecutableFileName(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().ExecutableFileName()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_Parent(impl::abi_arg_out<Windows::System::Diagnostics::IProcessDiagnosticInfo> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().Parent()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_ProcessStartTime(impl::abi_arg_out<Windows::Foundation::DateTime> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().ProcessStartTime()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_DiskUsage(impl::abi_arg_out<Windows::System::Diagnostics::IProcessDiskUsage> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().DiskUsage()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_MemoryUsage(impl::abi_arg_out<Windows::System::Diagnostics::IProcessMemoryUsage> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().MemoryUsage()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_CpuUsage(impl::abi_arg_out<Windows::System::Diagnostics::IProcessCpuUsage> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().CpuUsage()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::System::Diagnostics::IProcessDiagnosticInfoStatics> : produce_base<D, Windows::System::Diagnostics::IProcessDiagnosticInfoStatics> { HRESULT __stdcall abi_GetForProcesses(impl::abi_arg_out<Windows::Foundation::Collections::IVectorView<Windows::System::Diagnostics::ProcessDiagnosticInfo>> processes) noexcept override { try { typename D::abi_guard guard(this->shim()); *processes = detach_abi(this->shim().GetForProcesses()); return S_OK; } catch (...) { *processes = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_GetForCurrentProcess(impl::abi_arg_out<Windows::System::Diagnostics::IProcessDiagnosticInfo> processes) noexcept override { try { typename D::abi_guard guard(this->shim()); *processes = detach_abi(this->shim().GetForCurrentProcess()); return S_OK; } catch (...) { *processes = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::System::Diagnostics::IProcessDiskUsage> : produce_base<D, Windows::System::Diagnostics::IProcessDiskUsage> { HRESULT __stdcall abi_GetReport(impl::abi_arg_out<Windows::System::Diagnostics::IProcessDiskUsageReport> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().GetReport()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::System::Diagnostics::IProcessDiskUsageReport> : produce_base<D, Windows::System::Diagnostics::IProcessDiskUsageReport> { HRESULT __stdcall get_ReadOperationCount(int64_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().ReadOperationCount()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_WriteOperationCount(int64_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().WriteOperationCount()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_OtherOperationCount(int64_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().OtherOperationCount()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_BytesReadCount(int64_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().BytesReadCount()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_BytesWrittenCount(int64_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().BytesWrittenCount()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_OtherBytesCount(int64_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().OtherBytesCount()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::System::Diagnostics::IProcessMemoryUsage> : produce_base<D, Windows::System::Diagnostics::IProcessMemoryUsage> { HRESULT __stdcall abi_GetReport(impl::abi_arg_out<Windows::System::Diagnostics::IProcessMemoryUsageReport> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().GetReport()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::System::Diagnostics::IProcessMemoryUsageReport> : produce_base<D, Windows::System::Diagnostics::IProcessMemoryUsageReport> { HRESULT __stdcall get_NonPagedPoolSizeInBytes(uint64_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().NonPagedPoolSizeInBytes()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_PageFaultCount(uint32_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().PageFaultCount()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_PageFileSizeInBytes(uint64_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().PageFileSizeInBytes()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_PagedPoolSizeInBytes(uint64_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().PagedPoolSizeInBytes()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_PeakNonPagedPoolSizeInBytes(uint64_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().PeakNonPagedPoolSizeInBytes()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_PeakPageFileSizeInBytes(uint64_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().PeakPageFileSizeInBytes()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_PeakPagedPoolSizeInBytes(uint64_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().PeakPagedPoolSizeInBytes()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_PeakVirtualMemorySizeInBytes(uint64_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().PeakVirtualMemorySizeInBytes()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_PeakWorkingSetSizeInBytes(uint64_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().PeakWorkingSetSizeInBytes()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_PrivatePageCount(uint64_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().PrivatePageCount()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_VirtualMemorySizeInBytes(uint64_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().VirtualMemorySizeInBytes()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_WorkingSetSizeInBytes(uint64_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().WorkingSetSizeInBytes()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::System::Diagnostics::ISystemCpuUsage> : produce_base<D, Windows::System::Diagnostics::ISystemCpuUsage> { HRESULT __stdcall abi_GetReport(impl::abi_arg_out<Windows::System::Diagnostics::ISystemCpuUsageReport> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().GetReport()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::System::Diagnostics::ISystemCpuUsageReport> : produce_base<D, Windows::System::Diagnostics::ISystemCpuUsageReport> { HRESULT __stdcall get_KernelTime(impl::abi_arg_out<Windows::Foundation::TimeSpan> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().KernelTime()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_UserTime(impl::abi_arg_out<Windows::Foundation::TimeSpan> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().UserTime()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_IdleTime(impl::abi_arg_out<Windows::Foundation::TimeSpan> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().IdleTime()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::System::Diagnostics::ISystemDiagnosticInfo> : produce_base<D, Windows::System::Diagnostics::ISystemDiagnosticInfo> { HRESULT __stdcall get_MemoryUsage(impl::abi_arg_out<Windows::System::Diagnostics::ISystemMemoryUsage> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().MemoryUsage()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall get_CpuUsage(impl::abi_arg_out<Windows::System::Diagnostics::ISystemCpuUsage> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().CpuUsage()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::System::Diagnostics::ISystemDiagnosticInfoStatics> : produce_base<D, Windows::System::Diagnostics::ISystemDiagnosticInfoStatics> { HRESULT __stdcall abi_GetForCurrentSystem(impl::abi_arg_out<Windows::System::Diagnostics::ISystemDiagnosticInfo> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().GetForCurrentSystem()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::System::Diagnostics::ISystemMemoryUsage> : produce_base<D, Windows::System::Diagnostics::ISystemMemoryUsage> { HRESULT __stdcall abi_GetReport(impl::abi_arg_out<Windows::System::Diagnostics::ISystemMemoryUsageReport> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().GetReport()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::System::Diagnostics::ISystemMemoryUsageReport> : produce_base<D, Windows::System::Diagnostics::ISystemMemoryUsageReport> { HRESULT __stdcall get_TotalPhysicalSizeInBytes(uint64_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().TotalPhysicalSizeInBytes()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_AvailableSizeInBytes(uint64_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().AvailableSizeInBytes()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_CommittedSizeInBytes(uint64_t * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().CommittedSizeInBytes()); return S_OK; } catch (...) { return impl::to_hresult(); } } }; } namespace Windows::System::Diagnostics { template <typename D> uint32_t impl_IProcessDiagnosticInfo<D>::ProcessId() const { uint32_t value {}; check_hresult(WINRT_SHIM(IProcessDiagnosticInfo)->get_ProcessId(&value)); return value; } template <typename D> hstring impl_IProcessDiagnosticInfo<D>::ExecutableFileName() const { hstring value; check_hresult(WINRT_SHIM(IProcessDiagnosticInfo)->get_ExecutableFileName(put_abi(value))); return value; } template <typename D> Windows::System::Diagnostics::ProcessDiagnosticInfo impl_IProcessDiagnosticInfo<D>::Parent() const { Windows::System::Diagnostics::ProcessDiagnosticInfo value { nullptr }; check_hresult(WINRT_SHIM(IProcessDiagnosticInfo)->get_Parent(put_abi(value))); return value; } template <typename D> Windows::Foundation::DateTime impl_IProcessDiagnosticInfo<D>::ProcessStartTime() const { Windows::Foundation::DateTime value {}; check_hresult(WINRT_SHIM(IProcessDiagnosticInfo)->get_ProcessStartTime(put_abi(value))); return value; } template <typename D> Windows::System::Diagnostics::ProcessDiskUsage impl_IProcessDiagnosticInfo<D>::DiskUsage() const { Windows::System::Diagnostics::ProcessDiskUsage value { nullptr }; check_hresult(WINRT_SHIM(IProcessDiagnosticInfo)->get_DiskUsage(put_abi(value))); return value; } template <typename D> Windows::System::Diagnostics::ProcessMemoryUsage impl_IProcessDiagnosticInfo<D>::MemoryUsage() const { Windows::System::Diagnostics::ProcessMemoryUsage value { nullptr }; check_hresult(WINRT_SHIM(IProcessDiagnosticInfo)->get_MemoryUsage(put_abi(value))); return value; } template <typename D> Windows::System::Diagnostics::ProcessCpuUsage impl_IProcessDiagnosticInfo<D>::CpuUsage() const { Windows::System::Diagnostics::ProcessCpuUsage value { nullptr }; check_hresult(WINRT_SHIM(IProcessDiagnosticInfo)->get_CpuUsage(put_abi(value))); return value; } template <typename D> Windows::Foundation::Collections::IVectorView<Windows::System::Diagnostics::ProcessDiagnosticInfo> impl_IProcessDiagnosticInfoStatics<D>::GetForProcesses() const { Windows::Foundation::Collections::IVectorView<Windows::System::Diagnostics::ProcessDiagnosticInfo> processes; check_hresult(WINRT_SHIM(IProcessDiagnosticInfoStatics)->abi_GetForProcesses(put_abi(processes))); return processes; } template <typename D> Windows::System::Diagnostics::ProcessDiagnosticInfo impl_IProcessDiagnosticInfoStatics<D>::GetForCurrentProcess() const { Windows::System::Diagnostics::ProcessDiagnosticInfo processes { nullptr }; check_hresult(WINRT_SHIM(IProcessDiagnosticInfoStatics)->abi_GetForCurrentProcess(put_abi(processes))); return processes; } template <typename D> Windows::System::Diagnostics::ProcessMemoryUsageReport impl_IProcessMemoryUsage<D>::GetReport() const { Windows::System::Diagnostics::ProcessMemoryUsageReport value { nullptr }; check_hresult(WINRT_SHIM(IProcessMemoryUsage)->abi_GetReport(put_abi(value))); return value; } template <typename D> uint64_t impl_IProcessMemoryUsageReport<D>::NonPagedPoolSizeInBytes() const { uint64_t value {}; check_hresult(WINRT_SHIM(IProcessMemoryUsageReport)->get_NonPagedPoolSizeInBytes(&value)); return value; } template <typename D> uint32_t impl_IProcessMemoryUsageReport<D>::PageFaultCount() const { uint32_t value {}; check_hresult(WINRT_SHIM(IProcessMemoryUsageReport)->get_PageFaultCount(&value)); return value; } template <typename D> uint64_t impl_IProcessMemoryUsageReport<D>::PageFileSizeInBytes() const { uint64_t value {}; check_hresult(WINRT_SHIM(IProcessMemoryUsageReport)->get_PageFileSizeInBytes(&value)); return value; } template <typename D> uint64_t impl_IProcessMemoryUsageReport<D>::PagedPoolSizeInBytes() const { uint64_t value {}; check_hresult(WINRT_SHIM(IProcessMemoryUsageReport)->get_PagedPoolSizeInBytes(&value)); return value; } template <typename D> uint64_t impl_IProcessMemoryUsageReport<D>::PeakNonPagedPoolSizeInBytes() const { uint64_t value {}; check_hresult(WINRT_SHIM(IProcessMemoryUsageReport)->get_PeakNonPagedPoolSizeInBytes(&value)); return value; } template <typename D> uint64_t impl_IProcessMemoryUsageReport<D>::PeakPageFileSizeInBytes() const { uint64_t value {}; check_hresult(WINRT_SHIM(IProcessMemoryUsageReport)->get_PeakPageFileSizeInBytes(&value)); return value; } template <typename D> uint64_t impl_IProcessMemoryUsageReport<D>::PeakPagedPoolSizeInBytes() const { uint64_t value {}; check_hresult(WINRT_SHIM(IProcessMemoryUsageReport)->get_PeakPagedPoolSizeInBytes(&value)); return value; } template <typename D> uint64_t impl_IProcessMemoryUsageReport<D>::PeakVirtualMemorySizeInBytes() const { uint64_t value {}; check_hresult(WINRT_SHIM(IProcessMemoryUsageReport)->get_PeakVirtualMemorySizeInBytes(&value)); return value; } template <typename D> uint64_t impl_IProcessMemoryUsageReport<D>::PeakWorkingSetSizeInBytes() const { uint64_t value {}; check_hresult(WINRT_SHIM(IProcessMemoryUsageReport)->get_PeakWorkingSetSizeInBytes(&value)); return value; } template <typename D> uint64_t impl_IProcessMemoryUsageReport<D>::PrivatePageCount() const { uint64_t value {}; check_hresult(WINRT_SHIM(IProcessMemoryUsageReport)->get_PrivatePageCount(&value)); return value; } template <typename D> uint64_t impl_IProcessMemoryUsageReport<D>::VirtualMemorySizeInBytes() const { uint64_t value {}; check_hresult(WINRT_SHIM(IProcessMemoryUsageReport)->get_VirtualMemorySizeInBytes(&value)); return value; } template <typename D> uint64_t impl_IProcessMemoryUsageReport<D>::WorkingSetSizeInBytes() const { uint64_t value {}; check_hresult(WINRT_SHIM(IProcessMemoryUsageReport)->get_WorkingSetSizeInBytes(&value)); return value; } template <typename D> Windows::System::Diagnostics::ProcessDiskUsageReport impl_IProcessDiskUsage<D>::GetReport() const { Windows::System::Diagnostics::ProcessDiskUsageReport value { nullptr }; check_hresult(WINRT_SHIM(IProcessDiskUsage)->abi_GetReport(put_abi(value))); return value; } template <typename D> int64_t impl_IProcessDiskUsageReport<D>::ReadOperationCount() const { int64_t value {}; check_hresult(WINRT_SHIM(IProcessDiskUsageReport)->get_ReadOperationCount(&value)); return value; } template <typename D> int64_t impl_IProcessDiskUsageReport<D>::WriteOperationCount() const { int64_t value {}; check_hresult(WINRT_SHIM(IProcessDiskUsageReport)->get_WriteOperationCount(&value)); return value; } template <typename D> int64_t impl_IProcessDiskUsageReport<D>::OtherOperationCount() const { int64_t value {}; check_hresult(WINRT_SHIM(IProcessDiskUsageReport)->get_OtherOperationCount(&value)); return value; } template <typename D> int64_t impl_IProcessDiskUsageReport<D>::BytesReadCount() const { int64_t value {}; check_hresult(WINRT_SHIM(IProcessDiskUsageReport)->get_BytesReadCount(&value)); return value; } template <typename D> int64_t impl_IProcessDiskUsageReport<D>::BytesWrittenCount() const { int64_t value {}; check_hresult(WINRT_SHIM(IProcessDiskUsageReport)->get_BytesWrittenCount(&value)); return value; } template <typename D> int64_t impl_IProcessDiskUsageReport<D>::OtherBytesCount() const { int64_t value {}; check_hresult(WINRT_SHIM(IProcessDiskUsageReport)->get_OtherBytesCount(&value)); return value; } template <typename D> Windows::System::Diagnostics::ProcessCpuUsageReport impl_IProcessCpuUsage<D>::GetReport() const { Windows::System::Diagnostics::ProcessCpuUsageReport value { nullptr }; check_hresult(WINRT_SHIM(IProcessCpuUsage)->abi_GetReport(put_abi(value))); return value; } template <typename D> Windows::Foundation::TimeSpan impl_IProcessCpuUsageReport<D>::KernelTime() const { Windows::Foundation::TimeSpan value {}; check_hresult(WINRT_SHIM(IProcessCpuUsageReport)->get_KernelTime(put_abi(value))); return value; } template <typename D> Windows::Foundation::TimeSpan impl_IProcessCpuUsageReport<D>::UserTime() const { Windows::Foundation::TimeSpan value {}; check_hresult(WINRT_SHIM(IProcessCpuUsageReport)->get_UserTime(put_abi(value))); return value; } template <typename D> Windows::System::Diagnostics::SystemMemoryUsage impl_ISystemDiagnosticInfo<D>::MemoryUsage() const { Windows::System::Diagnostics::SystemMemoryUsage value { nullptr }; check_hresult(WINRT_SHIM(ISystemDiagnosticInfo)->get_MemoryUsage(put_abi(value))); return value; } template <typename D> Windows::System::Diagnostics::SystemCpuUsage impl_ISystemDiagnosticInfo<D>::CpuUsage() const { Windows::System::Diagnostics::SystemCpuUsage value { nullptr }; check_hresult(WINRT_SHIM(ISystemDiagnosticInfo)->get_CpuUsage(put_abi(value))); return value; } template <typename D> Windows::System::Diagnostics::SystemDiagnosticInfo impl_ISystemDiagnosticInfoStatics<D>::GetForCurrentSystem() const { Windows::System::Diagnostics::SystemDiagnosticInfo value { nullptr }; check_hresult(WINRT_SHIM(ISystemDiagnosticInfoStatics)->abi_GetForCurrentSystem(put_abi(value))); return value; } template <typename D> Windows::System::Diagnostics::SystemMemoryUsageReport impl_ISystemMemoryUsage<D>::GetReport() const { Windows::System::Diagnostics::SystemMemoryUsageReport value { nullptr }; check_hresult(WINRT_SHIM(ISystemMemoryUsage)->abi_GetReport(put_abi(value))); return value; } template <typename D> uint64_t impl_ISystemMemoryUsageReport<D>::TotalPhysicalSizeInBytes() const { uint64_t value {}; check_hresult(WINRT_SHIM(ISystemMemoryUsageReport)->get_TotalPhysicalSizeInBytes(&value)); return value; } template <typename D> uint64_t impl_ISystemMemoryUsageReport<D>::AvailableSizeInBytes() const { uint64_t value {}; check_hresult(WINRT_SHIM(ISystemMemoryUsageReport)->get_AvailableSizeInBytes(&value)); return value; } template <typename D> uint64_t impl_ISystemMemoryUsageReport<D>::CommittedSizeInBytes() const { uint64_t value {}; check_hresult(WINRT_SHIM(ISystemMemoryUsageReport)->get_CommittedSizeInBytes(&value)); return value; } template <typename D> Windows::System::Diagnostics::SystemCpuUsageReport impl_ISystemCpuUsage<D>::GetReport() const { Windows::System::Diagnostics::SystemCpuUsageReport value { nullptr }; check_hresult(WINRT_SHIM(ISystemCpuUsage)->abi_GetReport(put_abi(value))); return value; } template <typename D> Windows::Foundation::TimeSpan impl_ISystemCpuUsageReport<D>::KernelTime() const { Windows::Foundation::TimeSpan value {}; check_hresult(WINRT_SHIM(ISystemCpuUsageReport)->get_KernelTime(put_abi(value))); return value; } template <typename D> Windows::Foundation::TimeSpan impl_ISystemCpuUsageReport<D>::UserTime() const { Windows::Foundation::TimeSpan value {}; check_hresult(WINRT_SHIM(ISystemCpuUsageReport)->get_UserTime(put_abi(value))); return value; } template <typename D> Windows::Foundation::TimeSpan impl_ISystemCpuUsageReport<D>::IdleTime() const { Windows::Foundation::TimeSpan value {}; check_hresult(WINRT_SHIM(ISystemCpuUsageReport)->get_IdleTime(put_abi(value))); return value; } inline Windows::Foundation::Collections::IVectorView<Windows::System::Diagnostics::ProcessDiagnosticInfo> ProcessDiagnosticInfo::GetForProcesses() { return get_activation_factory<ProcessDiagnosticInfo, IProcessDiagnosticInfoStatics>().GetForProcesses(); } inline Windows::System::Diagnostics::ProcessDiagnosticInfo ProcessDiagnosticInfo::GetForCurrentProcess() { return get_activation_factory<ProcessDiagnosticInfo, IProcessDiagnosticInfoStatics>().GetForCurrentProcess(); } inline Windows::System::Diagnostics::SystemDiagnosticInfo SystemDiagnosticInfo::GetForCurrentSystem() { return get_activation_factory<SystemDiagnosticInfo, ISystemDiagnosticInfoStatics>().GetForCurrentSystem(); } } } template<> struct std::hash<winrt::Windows::System::Diagnostics::IProcessCpuUsage> { size_t operator()(const winrt::Windows::System::Diagnostics::IProcessCpuUsage & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::System::Diagnostics::IProcessCpuUsageReport> { size_t operator()(const winrt::Windows::System::Diagnostics::IProcessCpuUsageReport & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::System::Diagnostics::IProcessDiagnosticInfo> { size_t operator()(const winrt::Windows::System::Diagnostics::IProcessDiagnosticInfo & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::System::Diagnostics::IProcessDiagnosticInfoStatics> { size_t operator()(const winrt::Windows::System::Diagnostics::IProcessDiagnosticInfoStatics & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::System::Diagnostics::IProcessDiskUsage> { size_t operator()(const winrt::Windows::System::Diagnostics::IProcessDiskUsage & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::System::Diagnostics::IProcessDiskUsageReport> { size_t operator()(const winrt::Windows::System::Diagnostics::IProcessDiskUsageReport & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::System::Diagnostics::IProcessMemoryUsage> { size_t operator()(const winrt::Windows::System::Diagnostics::IProcessMemoryUsage & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::System::Diagnostics::IProcessMemoryUsageReport> { size_t operator()(const winrt::Windows::System::Diagnostics::IProcessMemoryUsageReport & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::System::Diagnostics::ISystemCpuUsage> { size_t operator()(const winrt::Windows::System::Diagnostics::ISystemCpuUsage & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::System::Diagnostics::ISystemCpuUsageReport> { size_t operator()(const winrt::Windows::System::Diagnostics::ISystemCpuUsageReport & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::System::Diagnostics::ISystemDiagnosticInfo> { size_t operator()(const winrt::Windows::System::Diagnostics::ISystemDiagnosticInfo & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::System::Diagnostics::ISystemDiagnosticInfoStatics> { size_t operator()(const winrt::Windows::System::Diagnostics::ISystemDiagnosticInfoStatics & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::System::Diagnostics::ISystemMemoryUsage> { size_t operator()(const winrt::Windows::System::Diagnostics::ISystemMemoryUsage & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::System::Diagnostics::ISystemMemoryUsageReport> { size_t operator()(const winrt::Windows::System::Diagnostics::ISystemMemoryUsageReport & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::System::Diagnostics::ProcessCpuUsage> { size_t operator()(const winrt::Windows::System::Diagnostics::ProcessCpuUsage & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::System::Diagnostics::ProcessCpuUsageReport> { size_t operator()(const winrt::Windows::System::Diagnostics::ProcessCpuUsageReport & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::System::Diagnostics::ProcessDiagnosticInfo> { size_t operator()(const winrt::Windows::System::Diagnostics::ProcessDiagnosticInfo & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::System::Diagnostics::ProcessDiskUsage> { size_t operator()(const winrt::Windows::System::Diagnostics::ProcessDiskUsage & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::System::Diagnostics::ProcessDiskUsageReport> { size_t operator()(const winrt::Windows::System::Diagnostics::ProcessDiskUsageReport & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::System::Diagnostics::ProcessMemoryUsage> { size_t operator()(const winrt::Windows::System::Diagnostics::ProcessMemoryUsage & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::System::Diagnostics::ProcessMemoryUsageReport> { size_t operator()(const winrt::Windows::System::Diagnostics::ProcessMemoryUsageReport & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::System::Diagnostics::SystemCpuUsage> { size_t operator()(const winrt::Windows::System::Diagnostics::SystemCpuUsage & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::System::Diagnostics::SystemCpuUsageReport> { size_t operator()(const winrt::Windows::System::Diagnostics::SystemCpuUsageReport & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::System::Diagnostics::SystemDiagnosticInfo> { size_t operator()(const winrt::Windows::System::Diagnostics::SystemDiagnosticInfo & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::System::Diagnostics::SystemMemoryUsage> { size_t operator()(const winrt::Windows::System::Diagnostics::SystemMemoryUsage & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::System::Diagnostics::SystemMemoryUsageReport> { size_t operator()(const winrt::Windows::System::Diagnostics::SystemMemoryUsageReport & value) const noexcept { return winrt::impl::hash_unknown(value); } }; WINRT_WARNING_POP
#include "Tree.h" MP::Tree::Tree(sf::Texture* texturePtr, sf::Vector2f coord, float treeScale) { aAnimation.loadObjectTextures( texturePtr, 2, 2, 64); setObjectCoord(coord); aAnimation.setOrigin(32, 55); aAnimation.setScale(treeScale, treeScale); _obj_animation_sleep_time = sf::milliseconds(RiD::ConfigurationLoader::getIntData("game settings", "blockLength")); } void MP::Tree::_tree_animation(sf::Clock& globalClock) { if (globalClock.getElapsedTime() > _ready_animation_time) { aAnimation.setNextSprite(0, 3); setLastActiveAnimation(globalClock); } } void MP::Tree::update(TaskManager& aMainTaskManager, sf::Clock& globalClock) { if(aMainTaskManager.getCurrentState()==TaskManager::stateType::stateGame) _tree_animation(globalClock); } void MP::Tree::render(TaskManager& aMainTaskManager, sf::RenderWindow& mainWindow) { if (aMainTaskManager.getCurrentState() == TaskManager::stateType::stateGame) mainWindow.draw(aAnimation.getObjectSprite()); }
#ifndef __ATOM__ #define __ATOM__ #include <string> #include <sstream> #include <vector> #include "element.h" #include "vec.h" class atom { public: // index of type to atom int type; // pointer to the element element *ele; // position vec pos; // force vec force; // define whether movable, 0, not movable; 1, movable but not removable; 2, all free int if_move; void line_from_in(std::string tmp, std::vector<element>& ele_list); void line_from_qe(std::stringstream& ss, std::vector<element>& ele_list); void print(); }; #endif
#pragma once #include "Cubemap.h" #include "client\Graphics\Shader.h" class Skybox { private: GLuint skyboxVAO; GLuint skyboxVBO; GLuint cubemap; Shader *shader; public: Skybox(); ~Skybox(); void setupVAO(string directory); void draw(); };
/*********************************************************************** created: 5/7/2004 author: Paul D Turner purpose: Interface to XML parser for GUILayout files *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2006 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 _CEGUIGUILayout_xmlHandler_h_ #define _CEGUIGUILayout_xmlHandler_h_ #include "CEGUI/WindowManager.h" #include "CEGUI/XMLHandler.h" // Start of CEGUI namespace section namespace CEGUI { /*! \brief Handler class used to parse the GUILayout XML files using SAX2 */ class GUILayout_xmlHandler : public XMLHandler { typedef WindowManager::PropertyCallback PropertyCallback; public: static const String NativeVersion; //!< The only version that we will allow to load /************************************************************************* Construction & Destruction *************************************************************************/ /*! \brief Constructor for GUILayout_xmlHandler objects */ GUILayout_xmlHandler(PropertyCallback* callback = nullptr, void* userdata = nullptr) : d_root(nullptr), d_propertyCallback(callback), d_userData(userdata) {} /*! \brief Destructor for GUILayout_xmlHandler objects */ virtual ~GUILayout_xmlHandler(void) {} const String& getSchemaName() const override; const String& getDefaultResourceGroup() const override; /************************************************************************* SAX2 Handler overrides *************************************************************************/ /*! \brief document processing (only care about elements, schema validates format) */ void elementStart(const String& element, const XMLAttributes& attributes) override; void elementEnd(const String& element) override; void text(const String& text) override; /************************************************************************* Functions used by our implementation *************************************************************************/ /*! \brief Destroy all windows created so far. */ void cleanupLoadedWindows(void); /*! \brief Return a pointer to the 'root' window created. */ Window* getLayoutRootWindow(void) const; static const String GUILayoutElement; //!< Tag name for GUILayout elements. static const String LayoutImportElement; //!< Tag name for LayoutImport elements. static const String EventElement; //!< Tag name for Event elements. static const String LayoutImportFilenameAttribute;//!< Attribute name that stores the file name of the layout to import. static const String LayoutImportResourceGroupAttribute; //!< Attribute name that stores the resource group identifier used when loading imported file. static const String EventNameAttribute; //!< Attribute name that stores the event name to be subscribed. static const String EventFunctionAttribute; //!< Attribute name that stores the name of the scripted function to be bound. static const String GUILayoutVersionAttribute; //!< Attribute name that stores the xml file version. private: /*! \brief Method that handles the opening GUILayout XML element. \note This method just checks the version attribute and there is no equivalent elementGUILayoutEnd method, because it would be just NOOP anyways */ void elementGUILayoutStart(const XMLAttributes& attributes); /*! \brief Method that handles the opening Window XML element. */ void elementWindowStart(const XMLAttributes& attributes); /*! \brief Method that handles the opening AutoWindow XML element. */ void elementAutoWindowStart(const XMLAttributes& attributes); /*! \brief Method that handles the UserString XML element. */ void elementUserStringStart(const XMLAttributes& attributes); /*! \brief Method that handles the Property XML element. */ void elementPropertyStart(const XMLAttributes& attributes); /*! \brief Method that handles the LayoutImport XML element. */ void elementLayoutImportStart(const XMLAttributes& attributes); /*! \brief Method that handles the Event XML element. */ void elementEventStart(const XMLAttributes& attributes); /*! \brief Method that handles the closing Window XML element. */ void elementWindowEnd(); /*! \brief Method that handles the closing AutoWindow XML element. */ void elementAutoWindowEnd(); /*! \brief Method that handles the closing of a UserString XML element. */ void elementUserStringEnd(); /*! \brief Method that handles the closing of a property XML element. */ void elementPropertyEnd(); void operator=(const GUILayout_xmlHandler&) {} /************************************************************************* Implementation Data *************************************************************************/ typedef std::pair<Window*, bool> WindowStackEntry; //!< Pair used as datatype for the window stack. second is false if the window is an autowindow. typedef std::vector<WindowStackEntry> WindowStack; Window* d_root; //!< Will point to first window created. WindowStack d_stack; //!< Stack used to keep track of what we're doing to which window. PropertyCallback* d_propertyCallback; //!< Callback for every property loaded void* d_userData; //!< User data for the property callback String d_stringItemName; //!< Use for long property or user string value String d_stringItemValue; //!< Use for long property or user string value }; } // End of CEGUI namespace section #endif // end of guard _CEGUIGUILayout_xmlHandler_h_
#include <iostream> #include "UDP_listener.hpp" int main (int args, char ** argv) { UDP_listener udpd(1234); udpd.run(); return 0; }
/* NO WARRANTY * * BECAUSE THE PROGRAM IS IN THE PUBLIC DOMAIN, THERE IS NO * WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE * LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE AUTHORS * AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT * WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO * THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD * THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL * NECESSARY SERVICING, REPAIR OR CORRECTION. * * IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN * WRITING WILL ANY AUTHOR, OR ANY OTHER PARTY WHO MAY MODIFY * AND/OR REDISTRIBUTE THE PROGRAM, BE LIABLE TO YOU FOR DAMAGES, * INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL * DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM * (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING * RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES * OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER * PROGRAMS), EVEN IF SUCH AUTHOR OR OTHER PARTY HAS BEEN ADVISED * OF THE POSSIBILITY OF SUCH DAMAGES. */ #include "stdafx.h" #include "Application\DigitalSimulatorApp.h" #include "MailLink.h" #include "imapi.h" #define TOOLTIP_ID 1 BEGIN_MESSAGE_MAP(CMailLink, CStatic) //{{AFX_MSG_MAP(CMailLink) ON_CONTROL_REFLECT(STN_CLICKED, OnClicked) ON_WM_CTLCOLOR_REFLECT() ON_WM_SETCURSOR() ON_WM_MOUSEMOVE() //}}AFX_MSG_MAP END_MESSAGE_MAP() //---------------------------------------------------------------------------- CMailLink::CMailLink(){ //---------------------------------------------------------------------------- PROC_TRACE; m_hLinkCursor = NULL; // No cursor as yet m_crLinkColour = RGB( 0, 0, 238); // Blue m_crVisitedColour = RGB( 85, 26, 139); // Purple m_crHoverColour = ::GetSysColor(COLOR_HIGHLIGHT); m_bOverControl = FALSE; // Cursor not yet over control m_bVisited = FALSE; // Hasn't been visited yet. m_bUnderline = TRUE; // Underline the link? m_bAdjustToFit = TRUE; // Resize the window to fit the text? m_receiver.Empty(); m_subject.Empty(); m_body.Empty(); } //---------------------------------------------------------------------------- CMailLink::~CMailLink(){ //---------------------------------------------------------------------------- PROC_TRACE; m_Font.DeleteObject(); if (m_hLinkCursor != NULL) { ::DestroyCursor(m_hLinkCursor); m_hLinkCursor = NULL; } } //---------------------------------------------------------------------------- BOOL CMailLink::PretranslateMessage(MSG* pMsg) { //---------------------------------------------------------------------------- PROC_TRACE; m_ToolTip.RelayEvent(pMsg); return CStatic::PreTranslateMessage(pMsg); } //---------------------------------------------------------------------------- void CMailLink::OnClicked(){ //---------------------------------------------------------------------------- PROC_TRACE; CIMapi mail; CString subject; if(m_subjectPrefix != "") subject= m_subjectPrefix + ": " + m_subject; else subject= m_subject; mail.Subject(subject); mail.To(m_receiver); if(!mail.Send()){ AfxMessageBox("Mail konnte nicht gesendet werden", MB_ICONEXCLAMATION | MB_OK); } SetVisited(); // Repaint to show visited colour } //---------------------------------------------------------------------------- HBRUSH CMailLink::CtlColor(CDC* pDC, UINT nCtlColor) { //---------------------------------------------------------------------------- PROC_TRACE; ASSERT(nCtlColor == CTLCOLOR_STATIC); if (m_bOverControl) pDC->SetTextColor(m_crHoverColour); else if (m_bVisited) pDC->SetTextColor(m_crVisitedColour); else pDC->SetTextColor(m_crLinkColour); // transparent text. pDC->SetBkMode(TRANSPARENT); return (HBRUSH)GetStockObject(NULL_BRUSH); } //---------------------------------------------------------------------------- void CMailLink::OnMouseMove(UINT nFlags, CPoint point) { //---------------------------------------------------------------------------- PROC_TRACE; CStatic::OnMouseMove(nFlags, point); if (m_bOverControl) // Cursor is currently over control { CRect rect; GetClientRect(rect); if (!rect.PtInRect(point)) { m_bOverControl = FALSE; ReleaseCapture(); RedrawWindow(); return; } } else // Cursor has just moved over control { m_bOverControl = TRUE; RedrawWindow(); SetCapture(); } } //---------------------------------------------------------------------------- BOOL CMailLink::OnSetCursor(CWnd* /*pWnd*/, UINT /*nHitTest*/, UINT /*message*/) { //---------------------------------------------------------------------------- PROC_TRACE; if (m_hLinkCursor) { ::SetCursor(m_hLinkCursor); return TRUE; } return FALSE; } //---------------------------------------------------------------------------- void CMailLink::PreSubclassWindow() { //---------------------------------------------------------------------------- PROC_TRACE; // We want to get mouse clicks via STN_CLICKED DWORD dwStyle = GetStyle(); ::SetWindowLong(GetSafeHwnd(), GWL_STYLE, dwStyle | SS_NOTIFY); // Set the subject as the window text if (m_subject.IsEmpty()) GetWindowText(m_subject); // Check that the window text isn't empty. If it is, set it as the URL. CString strWndText; GetWindowText(strWndText); if (strWndText.IsEmpty()) { ASSERT(!m_subject.IsEmpty()); // Window and URL both NULL. DUH! SetWindowText(m_subject); } // Create the font LOGFONT lf; GetFont()->GetLogFont(&lf); lf.lfUnderline = m_bUnderline; m_Font.CreateFontIndirect(&lf); SetFont(&m_Font); PositionWindow(); // Adjust size of window to fit URL if necessary SetDefaultCursor(); // Try and load up a "hand" cursor // Create the tooltip CRect rect; GetClientRect(rect); m_ToolTip.Create(this); m_ToolTip.AddTool(this, m_subject, rect, TOOLTIP_ID); CStatic::PreSubclassWindow(); } ///////////////////////////////////////////////////////////////////////////// // CMailLink operations //---------------------------------------------------------------------------- void CMailLink::SetReceiver(CString receiver){ //---------------------------------------------------------------------------- PROC_TRACE; m_receiver = receiver; PositionWindow(); } //---------------------------------------------------------------------------- void CMailLink::SetSubject(CString subject){ //---------------------------------------------------------------------------- PROC_TRACE; m_subject = subject; PositionWindow(); } //---------------------------------------------------------------------------- void CMailLink::SetSubjectPrefix(CString prefix){ //---------------------------------------------------------------------------- PROC_TRACE; m_subjectPrefix = prefix; } //---------------------------------------------------------------------------- void CMailLink::SetBody(CString body){ //---------------------------------------------------------------------------- PROC_TRACE; m_body = body; PositionWindow(); } //---------------------------------------------------------------------------- void CMailLink::SetColours(COLORREF crLinkColour, COLORREF crVisitedColour, COLORREF crHoverColour /* = -1 */) { //---------------------------------------------------------------------------- PROC_TRACE; m_crLinkColour = crLinkColour; m_crVisitedColour = crVisitedColour; if (crHoverColour == -1) m_crHoverColour = ::GetSysColor(COLOR_HIGHLIGHT); else m_crHoverColour = crHoverColour; if (::IsWindow(m_hWnd)) Invalidate(); } //---------------------------------------------------------------------------- COLORREF CMailLink::GetLinkColour() const{ //---------------------------------------------------------------------------- PROC_TRACE; return m_crLinkColour; } //---------------------------------------------------------------------------- COLORREF CMailLink::GetVisitedColour() const{ //---------------------------------------------------------------------------- PROC_TRACE; return m_crVisitedColour; } //---------------------------------------------------------------------------- COLORREF CMailLink::GetHoverColour() const{ //---------------------------------------------------------------------------- PROC_TRACE; return m_crHoverColour; } //---------------------------------------------------------------------------- void CMailLink::SetVisited(BOOL bVisited /* = TRUE */) { //---------------------------------------------------------------------------- PROC_TRACE; m_bVisited = bVisited; if (::IsWindow(GetSafeHwnd())) Invalidate(); } //---------------------------------------------------------------------------- BOOL CMailLink::GetVisited() const{ //---------------------------------------------------------------------------- PROC_TRACE; return m_bVisited; } //---------------------------------------------------------------------------- void CMailLink::SetLinkCursor(HCURSOR hCursor){ //---------------------------------------------------------------------------- PROC_TRACE; m_hLinkCursor = hCursor; if (m_hLinkCursor == NULL) SetDefaultCursor(); } //---------------------------------------------------------------------------- HCURSOR CMailLink::GetLinkCursor() const{ //---------------------------------------------------------------------------- PROC_TRACE; return m_hLinkCursor; } //---------------------------------------------------------------------------- void CMailLink::SetUnderline(BOOL bUnderline /* = TRUE */){ //---------------------------------------------------------------------------- PROC_TRACE; m_bUnderline = bUnderline; if (::IsWindow(GetSafeHwnd())) { LOGFONT lf; GetFont()->GetLogFont(&lf); lf.lfUnderline = m_bUnderline; m_Font.DeleteObject(); m_Font.CreateFontIndirect(&lf); SetFont(&m_Font); Invalidate(); } } //---------------------------------------------------------------------------- BOOL CMailLink::GetUnderline() const{ //---------------------------------------------------------------------------- PROC_TRACE; return m_bUnderline; } //---------------------------------------------------------------------------- void CMailLink::SetAutoSize(BOOL bAutoSize /* = TRUE */){ //---------------------------------------------------------------------------- PROC_TRACE; m_bAdjustToFit = bAutoSize; if (::IsWindow(GetSafeHwnd())) PositionWindow(); } //---------------------------------------------------------------------------- BOOL CMailLink::GetAutoSize() const{ //---------------------------------------------------------------------------- PROC_TRACE; return m_bAdjustToFit; } // Move and resize the window so that the window is the same size // as the hyperlink text. This stops the hyperlink cursor being active // when it is not directly over the text. If the text is left justified // then the window is merely shrunk, but if it is centred or right // justified then the window will have to be moved as well. // // Suggested by Pål K. Tønder //---------------------------------------------------------------------------- void CMailLink::PositionWindow(){ //---------------------------------------------------------------------------- PROC_TRACE; if (!::IsWindow(GetSafeHwnd()) || !m_bAdjustToFit) return; // Get the current window position CRect rect; GetWindowRect(rect); CWnd* pParent = GetParent(); if (pParent) pParent->ScreenToClient(rect); // Get the size of the window text CString strWndText; GetWindowText(strWndText); CDC* pDC = GetDC(); CFont* pOldFont = pDC->SelectObject(&m_Font); CSize Extent = pDC->GetTextExtent(strWndText); pDC->SelectObject(pOldFont); ReleaseDC(pDC); // Get the text justification via the window style DWORD dwStyle = GetStyle(); // Recalc the window size and position based on the text justification if (dwStyle & SS_CENTERIMAGE) rect.DeflateRect(0, (rect.Height() - Extent.cy)/2); else rect.bottom = rect.top + Extent.cy; if (dwStyle & SS_CENTER) rect.DeflateRect((rect.Width() - Extent.cx)/2, 0); else if (dwStyle & SS_RIGHT) rect.left = rect.right - Extent.cx; else // SS_LEFT = 0, so we can't test for it explicitly rect.right = rect.left + Extent.cx; // Move the window SetWindowPos(NULL, rect.left, rect.top, rect.Width(), rect.Height(), SWP_NOZORDER); } ///////////////////////////////////////////////////////////////////////////// // CMailLink implementation // The following appeared in Paul DiLascia's Jan 1998 MSJ articles. // It loads a "hand" cursor from the winhlp32.exe module //---------------------------------------------------------------------------- void CMailLink::SetDefaultCursor(){ //---------------------------------------------------------------------------- PROC_TRACE; if (m_hLinkCursor == NULL) // No cursor handle - load our own { // Get the windows directory CString strWndDir; GetWindowsDirectory(strWndDir.GetBuffer(MAX_PATH), MAX_PATH); strWndDir.ReleaseBuffer(); strWndDir += _T("\\winhlp32.exe"); // This retrieves cursor #106 from winhlp32.exe, which is a hand pointer HMODULE hModule = LoadLibrary(strWndDir); if (hModule) { HCURSOR hHandCursor = ::LoadCursor(hModule, MAKEINTRESOURCE(106)); if (hHandCursor) m_hLinkCursor = CopyCursor(hHandCursor); } FreeLibrary(hModule); } }
/* * SPDX-FileCopyrightText: 2020 Rolf Eike Beer <eike@sf-mail.de> * * SPDX-License-Identifier: GPL-3.0-or-later */ #include "RelationMemberModel.h" #include <osm.h> #include <osm_objects.h> #include <QDataStream> #include <QHash> #include <QMimeData> #include "osm2go_i18n.h" #include "osm2go_platform_qt.h" namespace { QHash<const char *, QString> roleCache; class memberQ { public: memberQ(const member_t &m); bool operator==(const member_t &other) const; bool operator==(const memberQ &other) const { return object == other.object && role == other.role; } inline bool operator!=(const member_t &other) const { return !operator==(other); } inline bool operator!=(const memberQ &other) const { return !operator==(other); } object_t object; QString role; }; memberQ::memberQ(const member_t &m) : object(m.object) { if (m.role != nullptr) { auto it = roleCache.find(m.role); if (it == roleCache.end()) it = roleCache.insert(m.role, QString::fromUtf8(m.role)); role = *it; } } bool memberQ::operator==(const member_t &other) const { if (object != other.object) return false; if (role.isEmpty()) return other.role == nullptr; const auto it = roleCache.find(other.role); if (it == roleCache.end()) return false; return *it == role; } const std::vector<member_t> emptyMembers; } // namespace class RelationMemberModel::RelationMemberModelPrivate { public: RelationMemberModelPrivate(relation_t *rel, osm_t::ref o); relation_t * const m_relation; const relation_t * const m_origRelation; osm_t::ref m_osm; std::vector<memberQ> m_members; ///< editable member list const std::vector<member_t> &m_origMembers; ///< upstream member list }; RelationMemberModel::RelationMemberModelPrivate::RelationMemberModelPrivate(relation_t *rel, osm_t::ref o) : m_relation(rel) , m_origRelation(o->originalObject(rel)) , m_osm(o) , m_origMembers(m_origRelation != nullptr ? m_origRelation->members : m_relation->isNew() ? emptyMembers : m_relation->members) { assert(roleCache.empty()); m_members.reserve(m_relation->members.size()); for (auto &&m : m_relation->members) m_members.push_back(m); } RelationMemberModel::RelationMemberModel(relation_t *rel, osm_t::ref o, QObject *parent) : QAbstractTableModel(parent) , d_ptr(new RelationMemberModelPrivate(rel, o)) { } RelationMemberModel::~RelationMemberModel() { roleCache.clear(); } int RelationMemberModel::rowCount(const QModelIndex &parent) const { const Q_D(RelationMemberModel); if (unlikely(parent.isValid())) return 0; return d->m_members.size(); } int RelationMemberModel::columnCount(const QModelIndex &parent) const { if (unlikely(parent.isValid())) return 0; return MEMBER_NUM_COLS; } QVariant RelationMemberModel::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation != Qt::Horizontal || role != Qt::DisplayRole) return QVariant(); switch (section) { case MEMBER_COL_TYPE: return trstring("Type"); case MEMBER_COL_ID: return trstring("Id"); case MEMBER_COL_NAME: return trstring("Name"); case MEMBER_COL_ROLE: return trstring("Role"); default: return QVariant(); } } QVariant RelationMemberModel::data(const QModelIndex &index, int role) const { const Q_D(RelationMemberModel); if (unlikely(!index.isValid())) return QVariant(); const auto &member = d->m_members.at(index.row()); switch (role) { case Qt::DisplayRole: case Qt::EditRole: switch (index.column()) { case MEMBER_COL_TYPE: return member.object.type_string(); case MEMBER_COL_ID: return static_cast<qint64>(member.object.get_id()); case MEMBER_COL_NAME: if (member.object.is_real()) return member.object.get_name(*d->m_osm); break; case MEMBER_COL_ROLE: return member.role; default: break; } break; case Qt::FontRole: if (static_cast<unsigned int>(index.row()) < d->m_origMembers.size()) { bool changed = false; const auto &oldMember = d->m_origMembers.at(index.row()); switch (index.column()) { case MEMBER_COL_TYPE: changed = (member.object.type != oldMember.object.type); break; case MEMBER_COL_ID: changed = (member.object.get_id() != oldMember.object.get_id()); break; case MEMBER_COL_ROLE: changed = (member.role != oldMember.role); break; default: break; } if (changed) return osm2go_platform::modelHightlightModified(); } break; case Qt::UserRole: switch (index.column()) { case MEMBER_COL_ID: return QVariant::fromValue(const_cast<void *>(static_cast<const void *>(&member.object))); case MEMBER_COL_ROLE: return QVariant::fromValue(static_cast<void *>(d->m_relation)); default: break; } break; default: break; } return QVariant(); } bool RelationMemberModel::setData(const QModelIndex &index, const QVariant &value, int role) { Q_D(RelationMemberModel); if (unlikely(!index.isValid())) return false; auto &member = d->m_members.at(index.row()); switch (role) { case Qt::EditRole: switch (index.column()) { case MEMBER_COL_ROLE: member.role = value.toString(); return true; default: break; } break; } return false; } Qt::ItemFlags RelationMemberModel::flags(const QModelIndex &index) const { const Q_D(RelationMemberModel); auto r = QAbstractTableModel::flags(index); if (unlikely(!index.isValid())) return r; const auto &member = d->m_members.at(index.row()); if (!member.object.is_real()) r &= ~Qt::ItemIsEnabled; r |= Qt::ItemNeverHasChildren; if (index.column() == MEMBER_COL_ROLE) r |= Qt::ItemIsEditable; return r; } bool RelationMemberModel::moveRows(const QModelIndex &sourceParent, int sourceRow, int count, const QModelIndex &destinationParent, int destinationChild) { Q_D(RelationMemberModel); assert(!sourceParent.isValid()); assert(!destinationParent.isValid()); assert_cmpnum(count, 1); // move onto itself assert_cmpnum_op(sourceRow, !=, destinationChild - 1); beginMoveRows(sourceParent, sourceRow, sourceRow, destinationParent, destinationChild); auto itOld = std::next(d->m_members.begin(), sourceRow); const auto member = *itOld; d->m_members.erase(itOld); auto itNew = std::next(d->m_members.begin(), destinationChild < sourceRow ? destinationChild : destinationChild - 1); d->m_members.insert(itNew, member); endMoveRows(); return true; } bool RelationMemberModel::commit() { Q_D(RelationMemberModel); const auto ritEnd = d->m_relation->members.end(); auto rit = d->m_relation->members.begin(); auto it = d->m_members.cbegin(); for (; rit != ritEnd; it++, rit++) if (*it != *rit) break; if (rit == ritEnd) return false; d->m_osm->mark_dirty(d->m_relation); for (; it != d->m_members.cend(); it++, rit++) { if (it->role.isEmpty()) { rit->object = it->object; rit->role = nullptr; continue; } // use the constructor as that will match the object in the valueCache // and add it there instead of copying a temporary *rit = member_t(it->object, it->role.toStdString().c_str()); } return true; }
#pragma once #include "EnemySpaceshipRange.h" #include <SFML/Graphics.hpp> constexpr float DeathballShape{ 5.0f }; struct AlienBullets { sf::CircleShape deathball; float CourseUp = 0; float CourseGoUp = 0; bool Active = 0; AlienBullets(); void setPos(float X, float Y); void Shoot(float deltatime); void draw(sf::RenderWindow& windows, AlienShipsRange*& RangeShips, int& RangeShipsQuant, AlienBullets*& bullets, int& bulletsquant, float deltatime); };
// @copyright 2017 - 2018 Shaun Ostoic // Distributed under the MIT License. // (See accompanying file LICENSE.md or copy at https://opensource.org/licenses/MIT) #pragma once #include <boost/winapi/basic_types.hpp> namespace boost::winapi { #if !defined (BOOST_USE_WINDOWS_H) constexpr boost::winapi::DWORD_ ANYSIZE_ARRAY_ = 1; typedef struct _LUID_ { boost::winapi::DWORD_ LowPart; boost::winapi::LONG_ HighPart; } LUID_, *PLUID_; typedef struct _LUID_AND_ATTRIBUTES_ { LUID_ Luid; boost::winapi::DWORD_ Attributes; } LUID_AND_ATTRIBUTES_, *PLUID_AND_ATTRIBUTES_; typedef LUID_AND_ATTRIBUTES_ LUID_AND_ATTRIBUTES_ARRAY_[ANYSIZE_ARRAY_]; typedef LUID_AND_ATTRIBUTES_ARRAY_ *PLUID_AND_ATTRIBUTES_ARRAY_; #else constexpr DWORD_ ANYSIZE_ARRAY_ = ANYSIZE_ARRAY; using _LUID_ = ::_LUID; using LUID_ = ::LUID; using PLUID_ = ::PLUID; using _LUID_AND_ATTRIBUTES_ = ::_LUID_AND_ATTRIBUTES; using LUID_AND_ATTRIBUTES_ = ::LUID_AND_ATTRIBUTES; using LUID_AND_ATTRIBUTES_ARRAY_ = ::LUID_AND_ATTRIBUTES_ARRAY; using PLUID_AND_ATTRIBUTES_ARRAY_ = ::PLUID_AND_ATTRIBUTES_ARRAY; using PRIVILEGE_SET_ = ::PRIVILEGE_SET; using PPRIVILEGE_SET_ = ::PPRIVILEGE_SET; #endif // !defined BOOST_USE_WINDOWS_H } // end namespace winapi
// // TicTacToe.cpp // // Created by Olivier Cuisenaire on 18.02.15. // Copyright (c) 2015 Olivier Cuisenaire. All rights reserved. // #include <cstdlib> #include <ctime> #include <iostream> #include <limits> using namespace std; // // Variables globales // // les joueurs sont +1 et -1. 0 pour les cases vides const int X = 1, O = -1, EMPTY = 0; // tableau de 3x3 cases. int board[3][3]; ///////////////////////////////////////////////// // // Fonctions // // calcule la ligne correspondant à un movement // de 1 à 9. int iFromN(int n) { return (n-1)/3; } // calcule la colonne correspondant à un movement // de 1 à 9. int jFromN(int n) { return (n-1)%3; } // efface le tableau void clearBoard() { for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) board[i][j] = EMPTY; } // applique un movement en mettant à // currentPlayer la case du tableau // correspondante. void applyMove(int n, int player) { int i = iFromN(n); int j = jFromN(n); board[i][j] = player; } void eraseMove(int n) { applyMove(n,EMPTY); } // verifie sur le joueur est gagnant. // player doit être +1 ou -1; bool isWinner(int player) { int win = 3*player; return ( (board[0][0] + board[0][1] + board[0][2] == win) // ligne 0 || (board[1][0] + board[1][1] + board[1][2] == win) // ligne 1 || (board[2][0] + board[2][1] + board[2][2] == win) // ligne 2 || (board[0][0] + board[1][0] + board[2][0] == win) // colonne 0 || (board[0][1] + board[1][1] + board[2][1] == win) // colonne 1 || (board[0][2] + board[1][2] + board[2][2] == win) // colonne 2 || (board[0][0] + board[1][1] + board[2][2] == win) // diagonale || (board[2][0] + board[1][1] + board[0][2] == win) ); // diagonale } // trouve le joueur gagnant. Renvoie EMPTY // si aucun joueur ne gagne à ce stade. int getWinner() { if (isWinner(X)) return X; else if (isWinner(O)) return O; else return EMPTY; } // indique si le tableau est plein // (les 9 cases sont non vides) bool isFull() { for (int i=0;i<3;++i) for (int j=0;j<3;++j) if (board[i][j] == EMPTY) return false; return true; } // verifie le validite d'un movement. // doit etre entre 1 et 9 (inclus) et // la case corrspondant doit etre vide. bool isValidMove(int n) { if(n<1 || n>9) return false; int i = iFromN(n); int j = jFromN(n); if(board[i][j] != EMPTY) return false; return true; } // affiche le tableau void printBoard() { cout << "\n+-+-+-+\n"; for (int i = 0; i < 3; i++) { cout << "|"; for (int j = 0; j < 3; j++) { switch (board[i][j]) { case X: cout << "X"; break; case O: cout << "O"; break; case EMPTY: cout << " "; break; } cout << "|" ; } cout << " "; for (int j = 0; j < 3; j++) cout << j+3*i+1 << " "; cout << "\n+-+-+-+\n"; } } // calcule le score estime par l'AI pour // un movement donne. // // Vous pouvez appeler les fonctions suivantes // // applyMove // eraseMove // isWinner // isFull // isValidMove // // et bien sur la fonction score elle-même cette // fonction étant normalement recursive. // double score(int n, int player) { // A MODIFIER double playerScore = rand(); return playerScore; } // choisit automatiquement le prochain mouvement // comme etant celui qui donne le meilleur score // appelle typiquement la fonction score ci-dessus. int ai(int player) { // A MODIFIER int bestMove = 1+rand()%9; while (! isValidMove(bestMove) ) { bestMove = 1+rand()%9; } return bestMove; } // choisit interactivement le prochain mouvement // en le demandant au joueur et en verifiant que // le choix est licite. // cette fonction est recursive si le choix est // illicite. int interactive(int player) { cout << endl << "Prochain mouvement du joueur " << ((player==X) ? "X" : "O" ) << ": " << flush; int n; cin >> n; cout << endl; if(!cin.good() || !isValidMove(n)) { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(),'\n'); cout << "Mouvement non valide. Essayez encore." << endl; return interactive(player); } else return n; } // choisit interactivement le nombre de joueurs humains // en le demandant au joueur et en verifiant que // le choix est licite. // cette fonction est recursive si le choix est // illicite. int askNumberOfPlayers() { cout << "Combien de joueurs humains? (0,1 ou 2) " << flush; int n; cin >> n; cout << endl; if(!cin.good() || (n < 0) || (n>2) ) { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(),'\n'); cout << "Nombre de joueur invalide. " << endl; return askNumberOfPlayers(); } else return n; } // programme principal. Demande le nombre de joueurs // humains, choisit aleatoirement qui commence en cas // de match humain/ordinateur. Puis boucle tant qu'il // n'y a pas de vainqueur et que le tableau n'est pas // plein. Affiche le resultat du match. int main() { // joueur courant. +1 ou -1; int currentPlayer; // indique si un joueur est humain ou ordinateur bool human[2]; srand ( (int) time(0) ); int np = askNumberOfPlayers(); switch(np) { case 0: human[0] = human[1] = false; break; case 1: human[0] = rand() % 2; // choix aleatoire du premier joueur human[1] = !human[0]; break; case 2: human[0] = human[1] = true; break; } clearBoard(); currentPlayer = X; while( getWinner() == EMPTY && !isFull() ) { printBoard(); int nextMove; if (human[(currentPlayer + 1) / 2]) nextMove = interactive(currentPlayer); else { nextMove = ai(currentPlayer); cout << endl << "AI joue " << nextMove << endl; } applyMove(nextMove,currentPlayer); currentPlayer = - currentPlayer; } printBoard(); int winner = getWinner(); if (winner != EMPTY) cout << " \n\n" << (winner == X ? 'X' : 'O') << " gagne! \n\n\n"; else cout << " \n\n Egalité! \n\n\n"; return EXIT_SUCCESS; }
#include<bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector<int> v(n),v1; set<int>s; for(int i=0;i<n;i++){ cin>>v[i]; s.insert(v[i]); } for(auto x:s) v1.push_back(x); for(auto x:s) { for(int i=0;i<v1.size();i++) { if(v1[i]!=x&&v1[i]%x==0) { s.erase(v1[i]); } } } cout<<s.size()<<endl; }
/* * File: main.h * Author: gmena * * Created on 23 de agosto de 2014, 02:21 PM */ #include "Service.h" #include "Processor.h" #include "Array.h" #include "PackGestor.h" #include "Console.h" #include "File.h" #include <unistd.h> #include <libini.h> #ifndef MAIN_H #define MAIN_H using namespace std; #endif /* MAIN_H */
 /// @file symbol_test.cc /// @brief Symbol のテストプログラム /// @author Yusuke Matsunaga (松永 裕介) /// /// Copyright (C) 2013 Yusuke Matsunaga /// All rights reserved. #include "led_nsdef.h" #include "Symbol.h" BEGIN_NAMESPACE_YM_LED class SymbolTestWidget : public QWidget { public: /// @brief コンストラクタ /// @param[in] parent 親のウィジェット SymbolTestWidget(QWidget* parent = NULL); protected: /// @brief 描画イベントのハンドラ void paintEvent(QPaintEvent* event); private: ////////////////////////////////////////////////////////////////////// // データメンバ ////////////////////////////////////////////////////////////////////// // 入力シンボル Symbol* mInputSymbol; // 出力シンボル Symbol* mOutputSymbol; // バッファシンボル Symbol* mBufSymbol; // NOT シンボル Symbol* mNotSymbol; // AND シンボル Symbol* mAndSymbol; // OR シンボル Symbol* mOrSymbol; // XOR シンボル Symbol* mXorSymbol; }; // @brief コンストラクタ // @param[in] parent 親のウィジェット SymbolTestWidget::SymbolTestWidget(QWidget* parent) : QWidget(parent) { mInputSymbol = new Symbol(kGtInput); mOutputSymbol = new Symbol(kGtOutput); mBufSymbol = new Symbol(kGtBuffer); mNotSymbol = new Symbol(kGtNot); mAndSymbol = new Symbol(kGtNand, 7); mOrSymbol = new Symbol(kGtNor, 23); mXorSymbol = new Symbol(kGtXnor, 28); } // @brief 描画イベントのハンドラ void SymbolTestWidget::paintEvent(QPaintEvent* event) { QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing, true); painter.setBrush(QBrush(Qt::green, Qt::SolidPattern)); painter.eraseRect(rect()); { QMatrix matrix; matrix.translate(20.0, 20.0); painter.setMatrix(matrix); mInputSymbol->draw_symbol(painter); } { QMatrix matrix; matrix.translate(200.0, 20.0); painter.setMatrix(matrix); mOutputSymbol->draw_symbol(painter); } { QMatrix matrix; matrix.translate(100.0, 20.0); painter.setMatrix(matrix); mBufSymbol->draw_symbol(painter); } { QMatrix matrix; matrix.translate(100.0, 70.0); painter.setMatrix(matrix); mNotSymbol->draw_symbol(painter); } { QMatrix matrix; matrix.translate(150.0, 100.0); painter.setMatrix(matrix); mAndSymbol->draw_symbol(painter); } { QMatrix matrix; matrix.translate(400.0, 100.0); painter.setMatrix(matrix); mOrSymbol->draw_symbol(painter); } { QMatrix matrix; matrix.translate(600.0, 200.0); painter.setMatrix(matrix); mXorSymbol->draw_symbol(painter); } } END_NAMESPACE_YM_LED int main(int argc, char** argv) { using nsYm::nsLed::SymbolTestWidget; QApplication app(argc, argv); QWidget* w = new SymbolTestWidget(); w->show(); return app.exec(); }
#ifndef ESA_EWDL_ETHERCAT_TXPDO_H #define ESA_EWDL_ETHERCAT_TXPDO_H namespace esa { namespace ewdl { namespace ethercat { namespace pdo { struct TxPDO1 { uint16 error_code; uint16 status_word; int8 mode_of_operation_display; int32 position_actual_value; int32 follow_error_actual_value; uint16 touch_probe_status; int32 touch_probe_pos1_pos_value; int32 touch_probe_pos1_neg_value; int32 touch_probe_pos2_pos_value; int32 touch_probe_pos2_neg_value; uint32 digital_inputs; void operator<<(uint8 *data_ptr) { error_code = 0x0000; status_word = 0x0000; mode_of_operation_display = 0x00; position_actual_value = 0x00000000; follow_error_actual_value = 0x00000000; touch_probe_status = 0x0000; touch_probe_pos1_pos_value = 0x00000000; touch_probe_pos1_neg_value = 0x00000000; touch_probe_pos2_pos_value = 0x00000000; touch_probe_pos2_neg_value = 0x00000000; digital_inputs = 0x00000000; error_code |= (0x00FF & *data_ptr++) << 0; error_code |= (0x00FF & *data_ptr++) << 8; status_word |= (0x00FF & *data_ptr++) << 0; status_word |= (0x00FF & *data_ptr++) << 8; mode_of_operation_display |= (0xFF & *data_ptr++) << 0; position_actual_value |= (0x000000FF & *data_ptr++) << 0; position_actual_value |= (0x000000FF & *data_ptr++) << 8; position_actual_value |= (0x000000FF & *data_ptr++) << 16; position_actual_value |= (0x000000FF & *data_ptr++) << 24; follow_error_actual_value |= (0x000000FF & *data_ptr++) << 0; follow_error_actual_value |= (0x000000FF & *data_ptr++) << 8; follow_error_actual_value |= (0x000000FF & *data_ptr++) << 16; follow_error_actual_value |= (0x000000FF & *data_ptr++) << 24; touch_probe_status |= (0x00FF & *data_ptr++) << 0; touch_probe_status |= (0x00FF & *data_ptr++) << 8; touch_probe_pos1_pos_value |= (0x000000FF & *data_ptr++) << 0; touch_probe_pos1_pos_value |= (0x000000FF & *data_ptr++) << 8; touch_probe_pos1_pos_value |= (0x000000FF & *data_ptr++) << 16; touch_probe_pos1_pos_value |= (0x000000FF & *data_ptr++) << 24; touch_probe_pos1_neg_value |= (0x000000FF & *data_ptr++) << 0; touch_probe_pos1_neg_value |= (0x000000FF & *data_ptr++) << 8; touch_probe_pos1_neg_value |= (0x000000FF & *data_ptr++) << 16; touch_probe_pos1_neg_value |= (0x000000FF & *data_ptr++) << 24; touch_probe_pos2_pos_value |= (0x000000FF & *data_ptr++) << 0; touch_probe_pos2_pos_value |= (0x000000FF & *data_ptr++) << 8; touch_probe_pos2_pos_value |= (0x000000FF & *data_ptr++) << 16; touch_probe_pos2_pos_value |= (0x000000FF & *data_ptr++) << 24; touch_probe_pos2_neg_value |= (0x000000FF & *data_ptr++) << 0; touch_probe_pos2_neg_value |= (0x000000FF & *data_ptr++) << 8; touch_probe_pos2_neg_value |= (0x000000FF & *data_ptr++) << 16; touch_probe_pos2_neg_value |= (0x000000FF & *data_ptr++) << 24; digital_inputs |= (0x000000FF & *data_ptr++) << 0; digital_inputs |= (0x000000FF & *data_ptr++) << 8; digital_inputs |= (0x000000FF & *data_ptr++) << 16; digital_inputs |= (0x000000FF & *data_ptr++) << 24; } // std::stream operator <<(std::stream &os, const T &obj) { // os << "RxPDO0:\n"); // printf("\tErrorCode: %x\n", rx_pdo.error_code); // printf("\tStatusWord: %d\n", rx_pdo.status_word); // printf("\tModes of Operation Display: %d\n", rx_pdo.modes_of_operation_display); // printf("\tPosition Actual Value: %d\n", rx_pdo.position_actual_value); // printf("\tFollow Error Actual Value: %d\n", rx_pdo.follow_error_actual_value); // printf("\tTouch Probe Status: %d\n", rx_pdo.touch_probe_status); // printf("\tTouch probe pos1 neg value: %d\n", rx_pdo.touch_probe_pos1_neg_value); // printf("\tTouch probe pos1 pos value: %d\n", rx_pdo.touch_probe_pos1_pos_value); // printf("\tTouch probe pos2 pos value: %d\n", rx_pdo.touch_probe_pos2_pos_value); // printf("\tTouch probe pos2 neg value: %d\n", rx_pdo.touch_probe_pos2_neg_value); // printf("\tDigital Inputs: %.32x\n", rx_pdo.digital_inputs); // } }; struct TxPDO2 { uint16 error_code; uint16 status_word; int8 mode_of_operation_display; int32 position_actual_value; int32 velocity_actual_value; int32 follow_error_actual_value; uint16 touch_probe_status; int32 touch_probe_pos1_pos_value; int32 touch_probe_pos1_neg_value; int32 touch_probe_pos2_pos_value; int32 touch_probe_pos2_neg_value; uint32 digital_inputs; void operator<<(uint8 *data_ptr) { error_code = 0x0000; status_word = 0x0000; mode_of_operation_display = 0x00; position_actual_value = 0x00000000; velocity_actual_value = 0x00000000; follow_error_actual_value = 0x00000000; touch_probe_status = 0x0000; touch_probe_pos1_pos_value = 0x00000000; touch_probe_pos1_neg_value = 0x00000000; touch_probe_pos2_pos_value = 0x00000000; touch_probe_pos2_neg_value = 0x00000000; digital_inputs = 0x00000000; error_code |= (0x00FF & *data_ptr++) << 0; error_code |= (0x00FF & *data_ptr++) << 8; status_word |= (0x00FF & *data_ptr++) << 0; status_word |= (0x00FF & *data_ptr++) << 8; mode_of_operation_display |= (0xFF & *data_ptr++) << 0; position_actual_value |= (0x000000FF & *data_ptr++) << 0; position_actual_value |= (0x000000FF & *data_ptr++) << 8; position_actual_value |= (0x000000FF & *data_ptr++) << 16; position_actual_value |= (0x000000FF & *data_ptr++) << 24; velocity_actual_value |= (0x000000FF & *data_ptr++) << 0; velocity_actual_value |= (0x000000FF & *data_ptr++) << 8; velocity_actual_value |= (0x000000FF & *data_ptr++) << 16; velocity_actual_value |= (0x000000FF & *data_ptr++) << 24; follow_error_actual_value |= (0x000000FF & *data_ptr++) << 0; follow_error_actual_value |= (0x000000FF & *data_ptr++) << 8; follow_error_actual_value |= (0x000000FF & *data_ptr++) << 16; follow_error_actual_value |= (0x000000FF & *data_ptr++) << 24; touch_probe_status |= (0x00FF & *data_ptr++) << 0; touch_probe_status |= (0x00FF & *data_ptr++) << 8; touch_probe_pos1_pos_value |= (0x000000FF & *data_ptr++) << 0; touch_probe_pos1_pos_value |= (0x000000FF & *data_ptr++) << 8; touch_probe_pos1_pos_value |= (0x000000FF & *data_ptr++) << 16; touch_probe_pos1_pos_value |= (0x000000FF & *data_ptr++) << 24; touch_probe_pos1_neg_value |= (0x000000FF & *data_ptr++) << 0; touch_probe_pos1_neg_value |= (0x000000FF & *data_ptr++) << 8; touch_probe_pos1_neg_value |= (0x000000FF & *data_ptr++) << 16; touch_probe_pos1_neg_value |= (0x000000FF & *data_ptr++) << 24; touch_probe_pos2_pos_value |= (0x000000FF & *data_ptr++) << 0; touch_probe_pos2_pos_value |= (0x000000FF & *data_ptr++) << 8; touch_probe_pos2_pos_value |= (0x000000FF & *data_ptr++) << 16; touch_probe_pos2_pos_value |= (0x000000FF & *data_ptr++) << 24; touch_probe_pos2_neg_value |= (0x000000FF & *data_ptr++) << 0; touch_probe_pos2_neg_value |= (0x000000FF & *data_ptr++) << 8; touch_probe_pos2_neg_value |= (0x000000FF & *data_ptr++) << 16; touch_probe_pos2_neg_value |= (0x000000FF & *data_ptr++) << 24; digital_inputs |= (0x000000FF & *data_ptr++) << 0; digital_inputs |= (0x000000FF & *data_ptr++) << 8; digital_inputs |= (0x000000FF & *data_ptr++) << 16; digital_inputs |= (0x000000FF & *data_ptr++) << 24; } // std::stream operator <<(std::stream &os, const T &obj) { // os << "RxPDO0:\n"); // printf("\tErrorCode: %x\n", rx_pdo.error_code); // printf("\tStatusWord: %d\n", rx_pdo.status_word); // printf("\tModes of Operation Display: %d\n", rx_pdo.modes_of_operation_display); // printf("\tPosition Actual Value: %d\n", rx_pdo.position_actual_value); // printf("\tFollow Error Actual Value: %d\n", rx_pdo.follow_error_actual_value); // printf("\tTouch Probe Status: %d\n", rx_pdo.touch_probe_status); // printf("\tTouch probe pos1 neg value: %d\n", rx_pdo.touch_probe_pos1_neg_value); // printf("\tTouch probe pos1 pos value: %d\n", rx_pdo.touch_probe_pos1_pos_value); // printf("\tTouch probe pos2 pos value: %d\n", rx_pdo.touch_probe_pos2_pos_value); // printf("\tTouch probe pos2 neg value: %d\n", rx_pdo.touch_probe_pos2_neg_value); // printf("\tDigital Inputs: %.32x\n", rx_pdo.digital_inputs); // } }; struct TxPDO3 { uint16 error_code; uint16 status_word; int8 mode_of_operation_display; int32 position_actual_value; int32 velocity_actual_value; int32 follow_error_actual_value; uint32 digital_inputs; void operator<<(uint8 *data_ptr) { error_code = 0x0000; status_word = 0x0000; mode_of_operation_display = 0x00; position_actual_value = 0x00000000; velocity_actual_value = 0x00000000; follow_error_actual_value = 0x00000000; digital_inputs = 0x00000000; error_code |= (0x00FF & *data_ptr++) << 0; error_code |= (0x00FF & *data_ptr++) << 8; status_word |= (0x00FF & *data_ptr++) << 0; status_word |= (0x00FF & *data_ptr++) << 8; mode_of_operation_display |= (0xFF & *data_ptr++) << 0; position_actual_value |= (0x000000FF & *data_ptr++) << 0; position_actual_value |= (0x000000FF & *data_ptr++) << 8; position_actual_value |= (0x000000FF & *data_ptr++) << 16; position_actual_value |= (0x000000FF & *data_ptr++) << 24; velocity_actual_value |= (0x000000FF & *data_ptr++) << 0; velocity_actual_value |= (0x000000FF & *data_ptr++) << 8; velocity_actual_value |= (0x000000FF & *data_ptr++) << 16; velocity_actual_value |= (0x000000FF & *data_ptr++) << 24; follow_error_actual_value |= (0x000000FF & *data_ptr++) << 0; follow_error_actual_value |= (0x000000FF & *data_ptr++) << 8; follow_error_actual_value |= (0x000000FF & *data_ptr++) << 16; follow_error_actual_value |= (0x000000FF & *data_ptr++) << 24; digital_inputs |= (0x000000FF & *data_ptr++) << 0; digital_inputs |= (0x000000FF & *data_ptr++) << 8; digital_inputs |= (0x000000FF & *data_ptr++) << 16; digital_inputs |= (0x000000FF & *data_ptr++) << 24; } // std::stream operator <<(std::stream &os, const T &obj) { // os << "RxPDO0:\n"); // printf("\tErrorCode: %x\n", rx_pdo.error_code); // printf("\tStatusWord: %d\n", rx_pdo.status_word); // printf("\tModes of Operation Display: %d\n", rx_pdo.modes_of_operation_display); // printf("\tPosition Actual Value: %d\n", rx_pdo.position_actual_value); // printf("\tFollow Error Actual Value: %d\n", rx_pdo.follow_error_actual_value); // printf("\tTouch Probe Status: %d\n", rx_pdo.touch_probe_status); // printf("\tTouch probe pos1 neg value: %d\n", rx_pdo.touch_probe_pos1_neg_value); // printf("\tTouch probe pos1 pos value: %d\n", rx_pdo.touch_probe_pos1_pos_value); // printf("\tTouch probe pos2 pos value: %d\n", rx_pdo.touch_probe_pos2_pos_value); // printf("\tTouch probe pos2 neg value: %d\n", rx_pdo.touch_probe_pos2_neg_value); // printf("\tDigital Inputs: %.32x\n", rx_pdo.digital_inputs); // } }; struct TxPDO4 { uint16 error_code; uint16 status_word; int8 mode_of_operation_display; int32 position_actual_value; int32 velocity_actual_value; int32 follow_error_actual_value; uint32 digital_inputs; void operator<<(uint8 *data_ptr) { error_code = 0x0000; status_word = 0x0000; mode_of_operation_display = 0x00; position_actual_value = 0x00000000; velocity_actual_value = 0x00000000; follow_error_actual_value = 0x00000000; digital_inputs = 0x00000000; error_code |= (0x00FF & *data_ptr++) << 0; error_code |= (0x00FF & *data_ptr++) << 8; status_word |= (0x00FF & *data_ptr++) << 0; status_word |= (0x00FF & *data_ptr++) << 8; mode_of_operation_display |= (0xFF & *data_ptr++) << 0; position_actual_value |= (0x000000FF & *data_ptr++) << 0; position_actual_value |= (0x000000FF & *data_ptr++) << 8; position_actual_value |= (0x000000FF & *data_ptr++) << 16; position_actual_value |= (0x000000FF & *data_ptr++) << 24; velocity_actual_value |= (0x000000FF & *data_ptr++) << 0; velocity_actual_value |= (0x000000FF & *data_ptr++) << 8; velocity_actual_value |= (0x000000FF & *data_ptr++) << 16; velocity_actual_value |= (0x000000FF & *data_ptr++) << 24; follow_error_actual_value |= (0x000000FF & *data_ptr++) << 0; follow_error_actual_value |= (0x000000FF & *data_ptr++) << 8; follow_error_actual_value |= (0x000000FF & *data_ptr++) << 16; follow_error_actual_value |= (0x000000FF & *data_ptr++) << 24; digital_inputs |= (0x000000FF & *data_ptr++) << 0; digital_inputs |= (0x000000FF & *data_ptr++) << 8; digital_inputs |= (0x000000FF & *data_ptr++) << 16; digital_inputs |= (0x000000FF & *data_ptr++) << 24; } // std::stream operator <<(std::stream &os, const T &obj) { // os << "RxPDO0:\n"); // printf("\tErrorCode: %x\n", rx_pdo.error_code); // printf("\tStatusWord: %d\n", rx_pdo.status_word); // printf("\tModes of Operation Display: %d\n", rx_pdo.modes_of_operation_display); // printf("\tPosition Actual Value: %d\n", rx_pdo.position_actual_value); // printf("\tFollow Error Actual Value: %d\n", rx_pdo.follow_error_actual_value); // printf("\tTouch Probe Status: %d\n", rx_pdo.touch_probe_status); // printf("\tTouch probe pos1 neg value: %d\n", rx_pdo.touch_probe_pos1_neg_value); // printf("\tTouch probe pos1 pos value: %d\n", rx_pdo.touch_probe_pos1_pos_value); // printf("\tTouch probe pos2 pos value: %d\n", rx_pdo.touch_probe_pos2_pos_value); // printf("\tTouch probe pos2 neg value: %d\n", rx_pdo.touch_probe_pos2_neg_value); // printf("\tDigital Inputs: %.32x\n", rx_pdo.digital_inputs); // } }; // union TxPDO // { // TxPDO0 _0; // TxPDO1 _1; // TxPDO2 _2; // TxPDO3 _3; // }; } } } } // namespace #endif
#include <stdint.h> #include <stdio.h> #include <chrono> #include <iostream> #include <random> #define TREE_DEPTH 16ull #define TREE_SIZE (-1 + (1ull << (TREE_DEPTH + 1ull))) #define boolean(arg) (!!(arg)) extern "C" { uint64_t retrieve_lvl_ht(uint64_t offset) { uint8_t lvl = 0; while( !boolean( (uint64_t)offset & ((4096ul << lvl) + 1) ) ) { ++lvl; } return TREE_DEPTH - lvl; } uint64_t retrieve_lvl(uint64_t offset) { uint64_t lvl = 0; uint64_t align = 4096ul; uint64_t b = offset % align; while(!(b)) { ++lvl; align <<= 1; b = offset % align; } return TREE_DEPTH - lvl; } } int main() { std::random_device rd; std::mt19937 mt(rd()); std::chrono::steady_clock::time_point begin, end; uint64_t bruh = 0; uint64_t avg0 = 0, avg1 = 0, avg2 = 0, avg3 = 0; uint64_t iterations = 10000000; uint64_t rand = 0; for(uint64_t i = 0; i < iterations; ++i) { rand = mt() & 0xfffffff; begin = std::chrono::steady_clock::now(); bruh = retrieve_lvl(0x1ffFF000ul + 4096ul * rand); end = std::chrono::steady_clock::now(); avg0 += std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count(); avg1 += std::chrono::duration_cast<std::chrono::nanoseconds> (end - begin).count(); } std::cout << "difference [v0norm]= " << avg0 / iterations << "[µs]" << std::endl; std::cout << "difference [v0norm]= " << avg1 / iterations << "[ns]" << std::endl; for(uint64_t i = 0; i < iterations; ++i) { rand = mt() & 0xfffffff; begin = std::chrono::steady_clock::now(); bruh = retrieve_lvl_ht(0x1ffFF000ul + 4096ul * rand); end = std::chrono::steady_clock::now(); avg2 += std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count(); avg3 += std::chrono::duration_cast<std::chrono::nanoseconds> (end - begin).count(); } std::cout << "difference [v1optm]= " << avg2 / iterations << "[µs]" << std::endl; std::cout << "difference [v1optm]= " << avg3 / iterations << "[ns]" << std::endl; /* * Tested with GCC 9.3 and 10.2. * With GCC 9.3: * -O1: * v0norm is faster (by about 150%->200%) * -O2: * v1optm is faster (by 1.5->4 times) * * With GCC 10.2: * -O1: * same performance (deviations of 1%->5%) * -O2: * v1optm is faster (by about 150%->400%) * * Bottom Line: * When debugging, use preferable to use the first version. * When running in release, preferable to use the second version. * Why did I test this: * this function is run in pfa_free() every de-allocation * if this is not fast, it'll slow down the general performance of the system. * I found out that modulus (%) operations are generally slow (because they use a div instruction). * for n = 2^m, in k % n, there is a faster way to perform a % using bit operations: m % n == m & (n - 1) * Tested this, and generally this optimization is helpful. */ }
#include <SD.h> #include <SPI.h> #include <Servo.h> #define s0 9 #define s1 8 #define s2 7 #define s3 6 #define out 5 #define servoYpin 3 #define servoXpin 4 #define CLK 13 #define MISO 12 #define MOSI 11 #define CS 10 #define NUMBER_OF_MEASUREMENTS 50 #define DEBUG 0 Servo servoX; Servo servoY; int _ready = 0; int z = 0; struct stats_t{ float tab[NUMBER_OF_MEASUREMENTS][4]; float sX[4] = {0,0,0,0}; //reads average float sigmum[4] = {0,0,0,0}; //sum (read - reads average)^2 float variance[4] = {0,0,0,0}; float sd[4] = {0,0,0,0}; //standard deviation }; struct rgb_t{ volatile float R; volatile float G; volatile float B; //float cct, cct2; //CCT CCT2 }; struct scaled_t{ float R_min_scaled; float G_min_scaled; float B_min_scaled; float L_min_scaled; float R_max_scaled; float G_max_scaled; float B_max_scaled; float L_max_scaled; float saturation_irradiance = 600000.0; //czestotliwosc pracy fotodiody krzemowej dla s0 = HIGH, s1 = HIGH }; struct reads_t{ struct stats_t stats; struct scaled_t min_max; struct rgb_t rgb; volatile float kolor[4]; volatile long duration; }; void color(struct reads_t*); void FREQ_to_RGB(struct reads_t*); void convert_RGB_to_0_to_100_scale(struct reads_t*); void RGB_to_HSL(struct reads_t*, float&, float&, float&); void collect(struct reads_t*); void statistical_processing(struct reads_t*); void average(struct reads_t*); void variance_deviation(struct reads_t*); bool cleaning_data(struct reads_t*); void scale(struct reads_t*, int*); int servo_start_position(); void servo_scale_black(); void scale_black(struct reads_t*); void choose_black(struct reads_t*); void servo_scale_white(); void choose_white(struct reads_t*); void sd_init(); void pattern_to_SD(); void setup(){ Serial.begin(9600); pinMode(s0, OUTPUT); pinMode(s1, OUTPUT); pinMode(s2, OUTPUT); pinMode(s3, OUTPUT); pinMode(out, INPUT); pinMode(CS, OUTPUT); digitalWrite(s0, HIGH); //czestotliwosc na wyjsciu: digitalWrite(s1, HIGH); //100% servoY.attach(servoYpin); servoX.attach(servoXpin); } void loop(){ struct reads_t whatreads; float Hue = 0, Saturation = 0; if(!_ready){ scale(&whatreads, &_ready); } if(_ready){ delay(800); servoY.detach(); servoX.detach(); delay(25); sd_init(); pattern_to_SD(); } while(1){ color(&whatreads); FREQ_to_RGB(&whatreads); // Serial.print("R = "); Serial.print(whatreads.rgb.R); // Serial.print("G = "); Serial.print(whatreads.rgb.G); // Serial.print("B = "); Serial.println(whatreads.rgb.B); // CIE_tristimulus(&whatreads); // nie wiem // Serial.print(whatreads.rgb.cct); // czy tego // Serial.println("K"); // potrzebuje float Luminance; //= map(whatreads.kolor[3], whatreads.min_max.L_min_scaled, whatreads.min_max.L_max_scaled, 0, 100); // Luminance = constrain(whatreads.kolor[3], 0, 100); convert_RGB_to_0_to_100_scale(&whatreads); RGB_to_HSL(&whatreads, Hue, Saturation, Luminance); Serial.print("Hue: "); Serial.println(Hue*360); Serial.print("Saturation: "); Serial.println(Saturation); Serial.print("Luminance: "); Serial.println(Luminance); } } /******************************************************************** * TCS 2300 * * |s2 s3 | Fotodioda| |s0 s1 | Czestotliwosc na wyjsciu| * * |--------+----------| |--------+-------------------------| * * |0 0 | Czerwony | |0 0 | wylaczenie zasilania | * * |0 1 | Niebieski| |0 1 | 2% | * * |1 0 | Czysta | |1 0 | 20% | * * |1 1 | Zielony | |1 1 | 100% | * ********************************************************************/ void color(struct reads_t *r){ digitalWrite(s2, LOW); //R digitalWrite(s3, LOW); r->kolor[0] = pulseIn(out, LOW); r->kolor[0] = r->min_max.saturation_irradiance / r->kolor[0]; digitalWrite(s2, HIGH); //G digitalWrite(s3, HIGH); r->kolor[1] = pulseIn(out, LOW); r->kolor[1] = r->min_max.saturation_irradiance / r->kolor[1]; digitalWrite(s2, LOW); //B digitalWrite(s3, HIGH); r->kolor[2] = pulseIn(out, LOW); r->kolor[2] = r->min_max.saturation_irradiance / r->kolor[2]; digitalWrite(s2, HIGH); //C digitalWrite(s3, LOW); r->kolor[3] = pulseIn(out, LOW); r->kolor[3] = r->min_max.saturation_irradiance / r->kolor[3]; delay(20); } void FREQ_to_RGB(struct reads_t *r){ r->rgb.R = (r->kolor[0] - r->min_max.R_min_scaled) * (255 - 0) / (r->min_max.R_max_scaled - r->min_max.R_min_scaled) + 0; //skalowanie do formatu RGB r->rgb.R = constrain(r->rgb.R, 0, 255); if(DEBUG==1){Serial.print("R = "); Serial.println(r->kolor[0]);} r->rgb.G = (r->kolor[1] - r->min_max.G_min_scaled) * (255 - 0) / (r->min_max.G_max_scaled - r->min_max.G_min_scaled) + 0; //skalowanie do formatu RGB r->rgb.G = constrain(r->rgb.G, 0, 255); if(DEBUG==1){Serial.print("G = "); Serial.println(r->kolor[1]);} r->rgb.B = (r->kolor[2] - r->min_max.B_min_scaled) * (255 - 0) / (r->min_max.B_max_scaled - r->min_max.B_min_scaled) + 0; //skalowanie do formatu RGB r->rgb.B = constrain(r->rgb.B, 0, 255); if(DEBUG==1){Serial.print("B = "); Serial.println(r->kolor[2]);} } void convert_RGB_to_0_to_100_scale(struct reads_t *r){ r->rgb.R = (((float) r->kolor[0]) / 65536) * 100; r->rgb.G = (((float) r->kolor[1]) / 65536) * 100; r->rgb.B = (((float) r->kolor[2])/ 65536) * 100; } //void CIE_tristimulus(struct reads_t *r){ // ///************************ CIE_tristimulus_XYZ ********************/ // const float X = (-0.14282 * r->rgb.R) + (1.54924 * r->rgb.G) + (-0.95641 * r->rgb.B); // const float Y = (-0.32466 * r->rgb.R) + (1.57837 * r->rgb.G) + (-0.73191 * r->rgb.B); // const float Z = (-0.68202 * r->rgb.R) + (0.77073 * r->rgb.G) + (0.56332 * r->rgb.B); ///*****************************************************************/ // ///********************** CHROMATICLY COORTINATES ******************/ // const float x = X / (X + Y + Z); // const float y = Y / (X + Y + Z); ///*****************************************************************/ // ///************************ McCamy's Formula ***********************/ // const float n = (x - 0.332) / (0.1858 - y); // r->rgb.cct = (449 * n * n * n) + (3525 * n * n) + (6823.3 * n) + 5520.33; //CCT [Kelvin] <- for 'absolute' black object ///*****************************************************************/ // // return; //} void RGB_to_HSL(struct reads_t *r, float& Hue, float& Saturation, float& Luminance){ float fmin, fmax; fmax = max(max(r->rgb.R, r->rgb.G), r->rgb.B); fmin = min(min(r->rgb.R, r->rgb.G), r->rgb.B); Luminance = fmax; //Luminance = map(Luminance, r->min_max.L_min_scaled, r->min_max.L_max_scaled, 0, 100); //Luminance = constrain(r->kolor[3], 0, 100); if (fmax > 0) Saturation = (fmax - fmin) / fmax; else Saturation = 0; if (Saturation == 0) Hue = 0; else{ if(fmax == r->rgb.R) Hue = (r->rgb.G - r->rgb.B) / (fmax - fmin); else if (fmax == r->rgb.G) Hue = 2 + (r->rgb.B - r->rgb.R) / (fmax - fmin); else Hue = 4 + (r->rgb.R - r->rgb.G) / (fmax - fmin); Hue = Hue / 6; if (Hue < 0) Hue += 1; } } void collect(struct reads_t *r){ for(int i = 0; i < NUMBER_OF_MEASUREMENTS; ++i){ color(r); for(int j = 0; j < 4; ++j){ if(i < NUMBER_OF_MEASUREMENTS){ r->stats.tab[i][j] = r->kolor[j]; } } } statistical_processing(r); } void statistical_processing(struct reads_t *r){ average(r); variance_deviation(r); if(cleaning_data(r)) average(r); } void average(struct reads_t *r){ for(int i = 0; i < 4; ++i){ for(int j = 0; j < NUMBER_OF_MEASUREMENTS; ++j){ if(r->stats.tab[j][i] != 0){ r->stats.sX[i] += r->stats.tab[j][i]; } } if(DEBUG==1){Serial.println();} r->stats.sX[i] /= NUMBER_OF_MEASUREMENTS; if(DEBUG==1){Serial.print("sX = "); Serial.println(r->stats.sX[i]);} } } void variance_deviation(struct reads_t *r){ for(int i = 0; i < 4; ++i){ for(int j = 0; j < NUMBER_OF_MEASUREMENTS; ++j){ if(r->stats.tab[j][i] != 0){ r->stats.variance[i] += ( (r->stats.tab[j][i] - r->stats.sX[i]) * (r->stats.tab[j][i] - r->stats.sX[i]) ) / NUMBER_OF_MEASUREMENTS; } } if(DEBUG==1){Serial.print("variance = "); Serial.println(r->stats.variance[i], 8);} r->stats.sd[i] = sqrt(r->stats.variance[i]); if(DEBUG==1){Serial.println(r->stats.sd[i], 8);} } for(int i = 0; i < 4; ++i){ r->stats.variance[i] = 0; } } bool cleaning_data(struct reads_t *r){ int flag = 0; for(int i = 0; i < 4; ++i){ for(int j = 0; j < NUMBER_OF_MEASUREMENTS; ++j){ if( r->stats.sX[i] - 2 * r->stats.sd[i] > r->stats.tab[j][i] || r->stats.sX[i] + 2 * r->stats.sd[i] < r->stats.tab[j][i] ){ if(DEBUG==1){Serial.println("clearing...");} r->stats.tab[j][i] = 0; flag = 1; } if(flag) return true; } } return false; } void scale(struct reads_t *r, int *_ready){ servo_scale_black(); scale_black(r); delay(3000); servo_scale_white(); scale_white(r); delay(3000); if(DEBUG==1){ Serial.print("R_min = "); Serial.print(r->min_max.R_min_scaled, 8); Serial.print(" "); Serial.print("R_max = "); Serial.println(r->min_max.R_max_scaled, 8); Serial.print("G_min = "); Serial.print(r->min_max.G_min_scaled, 8); Serial.print(" "); Serial.print("G_max = "); Serial.println(r->min_max.G_max_scaled, 8); Serial.print("B_min = "); Serial.print(r->min_max.B_min_scaled, 8); Serial.print(" "); Serial.print("B_max = "); Serial.println(r->min_max.B_max_scaled, 8); Serial.print("L_min = "); Serial.print(r->min_max.L_min_scaled, 8); Serial.print(" "); Serial.print("L_max = "); Serial.println(r->min_max.L_max_scaled, 8); } *_ready = servo_start_position(); } int servo_start_position(){ servoX.write(90); servoY.write(110); return 1; } void servo_scale_black(){ servoY.write(30); servoX.write(0); } void scale_black(struct reads_t *r){ collect(r); choose_black(r); } void choose_black(struct reads_t *r){ r->min_max.R_min_scaled = r->stats.sX[0]; r->min_max.G_min_scaled = r->stats.sX[1]; r->min_max.B_min_scaled = r->stats.sX[2]; r->min_max.L_min_scaled = r->stats.sX[3]; } void servo_scale_white(){ servoX.write(180); } void scale_white(struct reads_t *r){ collect(r); choose_white(r); } void choose_white(struct reads_t *r){ r->min_max.R_max_scaled = r->stats.sX[0]; r->min_max.G_max_scaled = r->stats.sX[1]; r->min_max.B_max_scaled = r->stats.sX[2]; r->min_max.L_max_scaled = r->stats.sX[3]; } void sd_init(){ if(!SD.begin(CS)){ Serial.println("Nie znaleziono karty SD"); return; } Serial.println("Znaleziono karte SD"); return; } void pattern_to_SD(){ File database; database = SD.open("database.txt", FILE_WRITE); if(database){ Serial.print("Gotowy do działania"); } else{ Serial.print("Nie znaleziono bazy danych wzorcow"); } database.close(); return; }
/*题目:给你一个大小为?m* n的方阵?mat,方阵由若干军人和平民组成,分别用 1 和 0 表示。请你返回方阵中战斗力最弱的k行的索引,按从最弱到最强排序。 如果第i行的军人数量少于第j行,或者两行军人数量相同但 i 小于 j,那么我 们认为第 i 行的战斗力比第j行弱。军人 总是 排在一行中的靠前位置,也就是 说 1 总是出现在 0 之前。*/ /*思路:本题采用 快速排序法,其中采用了一个特殊的技巧,就是将下标和下标对应的数值 进行合并,再之后快速排序时,可以让下标和数值同时影响结果,方法是将数值乘以数组长 度再加上下标值,这样的话,数值不同时按数值排序,数值相同时按照下标排序,最后结果 对数组长度取余就可以返回下标,如果需要返回数值可以直接除以数组长度*/ #include<stdio.h> #include<string.h> #include<stdlib.h> int cmp(const void*a,const void*b); int main() { int *returnSize,k,matColSize,matSize; int mat[5][5] = {{1,1,0,0,0},{1,1,1,1,0},{1,0,0,0,0},{1,1,0,0,0},{1,1,1,1,1}}; matSize = sizeof(mat)/sizeof(mat[0]); matColSize = sizeof(mat[0])/sizeof(mat[0][0]); printf("输入行数:"); scanf("%d",&k); int* res=(int*)calloc(k,sizeof(int)); int* num=(int*)calloc(matSize,sizeof(int)); memset(num,0,sizeof(int)*matSize); for(int i=0;i<matSize;i++){ for(int j=0;j<matColSize;j++){ if(mat[i][j]==1){ //数组数值乘以数值长度 num[i]+=matSize; }else{ break; } } //在数值中加上下标 num[i]+=i; } qsort(num,matSize,sizeof(int),cmp); for(int i=0;i<k;i++){ //返回时对数组长度取余返回下标 res[i]=num[i]%matSize; } for(int i=0;i<k;i++) printf("%d",res[i]); } int cmp(const void*a,const void*b){ return *(int*)a-*(int*)b; }
/* Snowman sample * by R. Teather * Edited by Noel Brett */ /* Borna Kalantar kalantb 001207031 Rebecca Tran tranr5 001425611 Neil Robichaud robichne 001425566 Sean McKay mckaysm 001423885 */ #ifdef __APPLE__ # include <OpenGL/gl.h> # include <OpenGL/glu.h> # include <GLUT/glut.h> #else # include <GL/gl.h> # include <GL/glu.h> # include <GL/freeglut.h> #endif #include <stdio.h> #include <stdlib.h> #include <ctime> #include <cmath> #include <string> #include "math3D.h" //#include "LevelLoader.h" #include <string> #include <sstream> using namespace std; //brass float m_amb1[] = {0.135, 0.2225, 0.1575, 1.0}; //setting the material for the ambient, diffuse and specular values float m_diff1[] = {0.54, 0.89, 0.63, 1.0}; float m_spec1[] = {0.316228, 0.316228, 0.316228, 1.0}; float shiny1 = 0.1; //obsidian // float m_amb1[] = {0.05375, 0.05, 0.06625, 1.0}; //setting the material for the ambient, diffuse and specular values // float m_diff1[] = {0.18275, 0.17, 0.22525, 1.0}; // float m_spec1[] = {0.332741, 0.328634, 0.346435, 1.0}; // float shiny1 = 0.3; float m_amb2[] = {0.0, 0.0, 0.0, 1.0}; //setting the material for the ambient, diffuse and specular values black plastic float m_diff2[] = {0.01, 0.01, 0.01, 1.0}; float m_spec2[] = {0.50, 0.50, 0.50, 1.0}; float shiny2 = 0.25; float m_amb3[] = {0.0, 0.0, 0.0, 1.0}; //setting the material for the ambient, diffuse and specular values white plastic float m_diff3[] = {0.55, 0.55, 0.55, 1.0}; float m_spec3[] = {0.70, 0.70, 0.70, 1.0}; float shiny3 = 0.25; float m_amb4[] = {0.25, 0.20725, 0.20725, 1.0}; //setting the material for the ambient, diffuse and specular values pearl for ball float m_diff4[] = {1.00, 0.829, 0.829, 1.0}; float m_spec4[] = {0.296648, 0.296648, 0.296648, 1.0}; float shiny4 = 0.088; float amb0[4] = {1,1,1,1}; float diff0[4] = {1,1,1,1}; float spec0[4] = {1,1,1,1}; float m_amb[] = {0.33, 0.22, 0.03, 1.0}; float m_diff[] = {0.78, 0.57, 0.11, 1.0}; float m_spec[] = {0.99, 0.91, 0.81, 1.0}; float shiny = 27.8; float yAngle = 0; float xAngle = 0; int intscorecounter = 0; string stringscorecounter = ""; const char* counterstring; float boxDepth = 5; bool selected = false; bool throwing = false; bool launched = false; int startingMousepos[2]; int finalMousepos[2]; float startTime; float endTime; float averageXVelocity; float averageZVelocity; float windspeed = 0; float position[] = {0,1,-4}; float startingPos[] = {0,1,-4}; float basketRadius = 1; float basketheight = 2; float basketPos[] = {0, basketheight, 4}; float velocity[] = {0,0,0}; float acceleration[] = {windspeed,-100,0}; float ballRotation[] = {0,0,0}; /*** EYE LOCATION ***/ float eye[] = {0,0,0}; float lookat[] = {0,0,0}; float light1_pos[]= {0,4,-4,1}; //last num one is pofloat light float light2_pos[]= {0,0,0,1}; //last num one is pofloat light float angle1 = 0.0f; /* display function - GLUT display callback function * clears the screen, sets the camera position, draws the ground plane and movable box */ int mapSize = 300; float heightMap[1000][1000]; int maxX = mapSize; int maxZ = mapSize; float eyex = 0; float eyey = 3; float eyez = -7; float lookatx = 0; float lookaty = 0; float lookatz = 0; bool spherical = false; float eyeradius = 10; float eyetheta = 4.71; float eyephi = 1.43; float lookatradius = 0; float lookattheta = 0; float lookatphi = 0; // x = eyeradius * sin(eyephi) * cos(eyetheta) // y = eyeradius * cos(eyephi) // z = eyeradius * sin(eyetheta) * sin(eyephi) bool textureToggle = false; GLubyte *img_data1; GLubyte *img_data2; GLubyte *img_data3; GLuint textures[3]; //array for storing the three different textures int width, height, ppmax; //width, height, max variables for the file of the texures GLUquadricObj *sphereOBJ = NULL; void drawBall(){ glPushMatrix(); //everytime the ball travels one circumference it will rotate one revolution glTranslatef(position[0],position[1],position[2]); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, m_amb4); //putting material onto the terrain glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, m_diff4); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, m_spec4); glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, shiny4); sphereOBJ = gluNewQuadric(); gluQuadricDrawStyle(sphereOBJ, GLU_FILL); gluQuadricTexture(sphereOBJ, GL_TRUE); gluQuadricNormals(sphereOBJ, GLU_SMOOTH); gluSphere(sphereOBJ, 1, 100, 100); glPopMatrix(); } GLubyte* LoadPPM(char* file, int* width, int* height, int* ppmax) { GLubyte* img; FILE *fd; int n, m; int k, nm; char c; int i; char b[100]; float s; int red, green, blue; //first open file and check if it's an ASCII PPM (indicated by P3 at the start) fd = fopen(file, "r"); fscanf(fd,"%[^\n] ",b); if(b[0]!='P'|| b[1] != '3') { printf("%s is not a PPM file!\n",file); exit(0); } printf("%s is a PPM file\n", file); fscanf(fd, "%c",&c); //next, skip past the comments - any line starting with # while(c == '#') { fscanf(fd, "%[^\n] ", b); printf("%s\n",b); fscanf(fd, "%c",&c); } ungetc(c,fd); // now get the dimensions and max colour value from the image fscanf(fd, "%d %d %d", &n, &m, &k); printf("%d rows %d columns max value= %d\n",n,m,k); // calculate number of pixels and allocate storage for this nm = n*m; img = (GLubyte*)malloc(3*sizeof(GLuint)*nm); s=255.0/k; // for every pixel, grab the read green and blue values, storing them in the image data array for(i=0;i<nm;i++) { fscanf(fd,"%d %d %d",&red, &green, &blue ); img[3*nm-3*i-3]=red*s; img[3*nm-3*i-2]=green*s; img[3*nm-3*i-1]=blue*s; } // finally, set the "return parameters" (width, height, max) and return the image array *width = n; *height = m; *ppmax = k; return img; } // textures function void initTexture(void) { img_data1 = LoadPPM("hay.ppm", &width, &height, &ppmax); //loading the texture by using the LoadPPM function, into img_data1 img_data2 = LoadPPM("tree.ppm", &width, &height, &ppmax); img_data3 = LoadPPM("crates.ppm", &width, &height, &ppmax); //enabling textures glEnable(GL_TEXTURE_2D); glGenTextures(3, textures); //using three textures glBindTexture(GL_TEXTURE_2D, textures[0]); //binding the first texture stored in the textures array glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, img_data1); //getting the necessary information of the texture glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); //setting parameters glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glBindTexture(GL_TEXTURE_2D, textures[1]); //binding the first texture stored in the textures array glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, img_data2); //getting the necessary information of the texture glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); //setting parameters glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glBindTexture(GL_TEXTURE_2D, textures[2]); //binding the first texture stored in the textures array glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, img_data3); //getting the necessary information of the texture glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); //setting parameters glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } void updateeyeposition(){ if (spherical){ eye[0] = eyeradius * sin(eyephi) * cos(eyetheta); eye[1] = eyeradius * cos(eyephi); eye[2] = eyeradius * sin(eyetheta) * sin(eyephi); } else{ eye[0] = eyex; eye[1] = eyey; eye[2] = eyez; } } void sphericaltocartesion(){ eyex = eyeradius * sin(eyephi) * cos(eyetheta); eyey = eyeradius * cos(eyephi); eyez = eyeradius * sin(eyetheta) * sin(eyephi); } void cartesiontospherical(){ eyeradius = sqrtf(eyex * eyex + eyey * eyey + eyez * eyez); eyephi = acos(eyey/eyeradius); eyetheta = atan(eyez/eyex); if(eyetheta > 0 ){ eyetheta += 3.14; } if(eyez > 0){ eyetheta += 3.14; } } // BORNA UPDATE TO HERE void textprinter(int x, int y, char* text) { glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0, 800, 0, 800, -1, 1); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glRasterPos2i(x,y); char* c; //character iterator (ptr) for(c = text; *c != '\0'; c++) //stop when we hit null character { glutStrokeCharacter(GLUT_STROKE_ROMAN, *c); //print one char } // glRasterPos2i(x,y); // // //character iterator (ptr) // for(c = text2; *c != '\0'; c++) //stop when we hit null character // { // // glutStrokeCharacter(GLUT_STROKE_ROMAN, *c); //print one char // } glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); } void changetostring(int integer){ stringstream streamint; streamint << integer; stringscorecounter = streamint.str(); counterstring = stringscorecounter.c_str();; } void drawFloor(){ glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, m_amb1); //putting material onto the terrain glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, m_diff1); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, m_spec1); glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, shiny1*128); //floor glPushMatrix(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glColor3f(1, 0, 0); glBegin(GL_QUADS); glNormal3f(0, 1, 0); glVertex3f(5, 0, 5); glVertex3f(5, 0, -5); glVertex3f(-5, 0, -5); glVertex3f(-5, 0, 5); glEnd(); glPopMatrix(); //ceiling glPushMatrix(); glTranslatef(0, 10, 0); glBegin(GL_QUADS); glNormal3f(0, -1, 0); glVertex3f(5, 0, 5); glVertex3f(5, 0, -5); glVertex3f(-5, 0, -5); glVertex3f(-5, 0, 5); glEnd(); glPopMatrix(); //right wall glPushMatrix(); glTranslatef(-5, 5, 0); glRotatef(90, 0, 0, 1); glBegin(GL_QUADS); glNormal3f(1, 0, 0); glVertex3f(5, 0, 5); glVertex3f(5, 0, -5); glVertex3f(-5, 0, -5); glVertex3f(-5, 0, 5); glEnd(); glPopMatrix(); //left wall glPushMatrix(); glTranslatef(5, 5, 0); glRotatef(90, 0, 0, 1); glBegin(GL_QUADS); glNormal3f(1, 0, 0); glVertex3f(5, 0, 5); glVertex3f(5, 0, -5); glVertex3f(-5, 0, -5); glVertex3f(-5, 0, 5); glEnd(); glPopMatrix(); //back wall glPushMatrix(); glTranslatef(0, 5, 5); glRotatef(90, 1, 0, 0); glBegin(GL_QUADS); glNormal3f(0, 0, -1); glVertex3f(5, 0, 5); glVertex3f(5, 0, -5); glVertex3f(-5, 0, -5); glVertex3f(-5, 0, 5); glEnd(); glPopMatrix(); } bool bounced = false; void resetBall() { windspeed = -50 + rand()%100; position[0] = startingPos[0]; position[1] = startingPos[1]; position[2] = startingPos[2]; velocity[0] = 0.0f; velocity[1] = 0.0f; velocity[2] = 0.0f; acceleration[0] = windspeed; acceleration[1] = -100.0f; acceleration[2] = 0.0f; launched = false; bounced = false; } int snowmanCounter = 0; bool movingRight = true; float pos[] = {0,1,0}; float rot[] = {0,0,0}; float headRot[] = {0,0,0}; void DrawSnowman(float* pos, float* rot){ glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, m_amb3); //putting material onto the terrain glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, m_diff3); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, m_spec3); glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, shiny3*128); glPushMatrix(); // printf("%i\n", counter); if(movingRight == true){ if(snowmanCounter > -50){ glTranslatef(0.1*snowmanCounter,0,0); snowmanCounter--; } else if (snowmanCounter == -50){ glTranslatef(0.1*snowmanCounter,0,0); snowmanCounter++; movingRight = false; } } if(movingRight == false){ if(snowmanCounter < 50){ glTranslatef(0.1*snowmanCounter,0,0); snowmanCounter++; } else if(snowmanCounter == 50){ glTranslatef(0.1*snowmanCounter,0,0); snowmanCounter--; movingRight = true; } } glPushMatrix(); glTranslatef(pos[0], pos[1], pos[2]); // glRotatef(rot[1], 0, 1, 0); glRotatef(180,0,1,0); //draw body glColor3f(1,1,1); glutSolidSphere(1, 16, 16); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, m_amb2); //putting material onto the terrain glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, m_diff2); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, m_spec2); glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, shiny2*128); //draw buttons glPushMatrix(); glTranslatef(0, 0.35, 0.9); glColor3f(0, 0, 0); glutSolidSphere(0.1, 10, 10); glPopMatrix(); glPushMatrix(); glTranslatef(0, 0.15, 0.95); glColor3f(0, 0, 0); glutSolidSphere(0.1, 10, 10); glPopMatrix(); glPushMatrix(); glTranslatef(0, -0.05, 0.95); glColor3f(0, 0, 0); glutSolidSphere(0.1, 10, 10); glPopMatrix(); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, m_amb3); //putting material onto the glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, m_diff3); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, m_spec3); glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, shiny3*128); glPushMatrix(); //translate relative to body, and draw head glTranslatef(0, 1.25, 0); glRotatef(headRot[1], 0, 1, 0); //turn the head relative to the body glColor3f(1,1,1); glutSolidSphere(0.5, 16, 16); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, m_amb2); //putting material onto the glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, m_diff2); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, m_spec2); glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, shiny2*128); //translate and draw right eye glPushMatrix(); glTranslatef(0.2, 0.15, 0.45); glColor3f(0,0,0); glutSolidSphere(0.1, 10, 10); glPopMatrix(); //translate and draw left eye glPushMatrix(); glTranslatef(-0.2, 0.15, 0.45); glColor3f(0,0,0); glutSolidSphere(0.1, 10, 10); glPopMatrix(); //translate and draw nose glPushMatrix(); glTranslatef(0, 0, 0.5); glColor3f(1,0.4,0); glutSolidSphere(0.1, 10, 10); glPopMatrix(); glPopMatrix();//body glPopMatrix();//snowman glPopMatrix(); } void drawBasket() { glColor3f(1,0,0); glPushMatrix(); glTranslatef(basketPos[0], basketPos[1], basketPos[2]); glPushMatrix(); glTranslatef(0, 0.8, 1); glScalef(2.5, 2.5, 0.1); glutSolidCube(1); glPopMatrix(); glRotatef(90, 1, 0, 0); glutSolidTorus(basketRadius / 5, basketRadius, 100, 100); glPopMatrix(); } bool pendingStop = false; float groundstartTime; float currentTime; void startTimer(){ groundstartTime=(GLfloat)glutGet(GLUT_ELAPSED_TIME); } float terminalWind = 50; void ballMotion(int value){ //printf("%f\n",position[1]); if(bounced){ if (pendingStop == false){ pendingStop = true; startTimer(); //starts a 3 second timer } else{ currentTime = (GLfloat)glutGet(GLUT_ELAPSED_TIME); // printf("%f\n", currentTime-groundstartTime); if ((currentTime - groundstartTime) > 5000){ printf("times up\n"); pendingStop = false; launched = false; resetBall(); } } } if (launched == true) { if(abs(velocity[0]) < terminalWind){ velocity[0] += windspeed/60; } velocity[0] += acceleration[0]/60; velocity[1] += acceleration[1]/60; velocity[2] += acceleration[2]/60; position[0] += velocity[0]/60; position[1] += velocity[1]/60; position[2] += velocity[2]/60; if (position[2] > 5 ){ velocity[2] = -1*(velocity[2] - 0.5*velocity[2]); position[2] = 5.0 + velocity[2]/60; printf("out of z pos wall"); } else if (position[2] < -5 ){ velocity[2] = -1*(velocity[2] - 0.5*velocity[2]); position[2] = -5.0 + velocity[2]/60; printf("out of z neg wall"); } if (position[0] < -5){ velocity[0] = -1*(velocity[0] - 0.5*velocity[0]); position[0] = -5.0 + velocity[0]/60; printf("out of x neg wall"); } else if (position[0] > 5){ velocity[0] = -1*(velocity[0] - 0.5*velocity[0]); position[0] = 5.0 + velocity[0]/60; printf("out of x pos wall"); } if (position[1] < 1){ intscorecounter = 0; velocity[1] = -1*(velocity[1] - 0.5*velocity[1]); //lose half magnitude and reverse direction position[1] = 1.0 + velocity[1]/60; bounced = true; } //Intersection with inside of basket (scoring) if ((position[0] > (basketPos[0] - basketRadius)) && (position[0] < (basketPos[0] + basketRadius))) { if ((position[2] > (basketPos[2] - basketRadius)) && (position[2] < (basketPos[2] + basketRadius))) { if (position[1] > basketPos[1] && position[1] < (basketPos[1] + 0.5f) && !bounced) { printf("scored\n"); resetBall(); intscorecounter++; } } } //Intersection with outside of basket (rim shot) if ((position[0] > (basketPos[0] - basketRadius)) && (position[0] < (basketPos[0] + basketRadius))) { if ((position[2] > (basketPos[2] - basketRadius)) && (position[2] < (basketPos[2] + basketRadius))) { if (position[1] < basketPos[1] && bounced) { velocity[0] = -1*(velocity[0] - 0.5*velocity[0]); //lose half magnitude and reverse direction position[0] = position[0] + velocity[0]/60; velocity[2] = -1*(velocity[2] - 0.5*velocity[2]); //lose half magnitude and reverse direction position[2] = position[2] + velocity[2]/60; } } } } glutTimerFunc(17,ballMotion,0); } float input1, input2, input3; int text = 2; void keyboard(unsigned char key, int x, int y) { /* key presses move the cube, if it isn't at the extents (hard-coded here) */ switch (key) { case 'q': case 27: exit (0); break; case 'W': case 'w': if (eyez < 0){ eyez +=0.1; } else{ eyez -=0.1; } break; case 'a': case 'A': if (eyez < 0){ eyex +=0.1; } else{ eyex -=0.1; } break; case 'S': case 's': if (eyez < 0){ eyez -=0.1; } else{ eyez +=0.1; } break; case 'D': case 'd': if (eyez < 0){ eyex -=0.1; } else{ eyex +=0.1; } break; case 'U': case 'u': eyey +=0.1; break; case 'I': case 'i': if (eyey > 0) { eyey -=0.1; } break; case 'z': eyeradius += 0.1; break; case 'Z': eyeradius -= 0.1; break; case 'x': eyetheta += 0.05; break; case 'X': eyetheta -= 0.05; break; case 'c': if(eyephi < 1.5){ eyephi += 0.05; } break; case 'C': if(eyephi > -1.5){ eyephi -= 0.05; } break; case 'm': case 'M': if (spherical){ sphericaltocartesion(); spherical = false; } else{ cartesiontospherical(); spherical = true; } break; break; case '1': if (textureToggle == true){ glEnable(GL_TEXTURE_2D); // glBindTexture(GL_TEXTURE_2D, textures[0]); textureToggle = false; } else { glDisable(GL_TEXTURE_2D); textureToggle = true; } break; case '2': text = 2; // glBindTexture(GL_TEXTURE_2D, textures[0]); break; case '3': text = 3; // glBindTexture(GL_TEXTURE_2D, textures[1]); break; case '4': text = 4; // glBindTexture(GL_TEXTURE_2D, textures[2]); break; case 'r': case 'R': resetBall(); break; } glutPostRedisplay(); } void special(int key, int x, int y) { switch(key) { case GLUT_KEY_UP: eye[1] += 1; lookat[1] += 1; break; case GLUT_KEY_DOWN: eye[1] -= 1; lookat[1] -= 1; break; case GLUT_KEY_LEFT: eye[0] -= 1; lookat[0] -= 1; break; case GLUT_KEY_RIGHT: eye[0] += 1; lookat[0] += 1; break; } glutPostRedisplay(); } void init(void){ resetBall(); glClearColor(0, 0, 0, 0); glColor3f(1,0,0); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); //glEnable(GL_LIGHT1); glLightfv(GL_LIGHT0, GL_AMBIENT, amb0); glLightfv(GL_LIGHT0, GL_DIFFUSE, diff0); glLightfv(GL_LIGHT0, GL_SPECULAR, spec0); glLightfv(GL_LIGHT1, GL_AMBIENT, amb0); glLightfv(GL_LIGHT1, GL_DIFFUSE, diff0); glLightfv(GL_LIGHT1, GL_SPECULAR, spec0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum(-10,10,-10,10,0,1000); gluPerspective(90, 1, 1, 1000); } void ballTexture(){ switch(text){ case 2: glBindTexture(GL_TEXTURE_2D, textures[0]); break; case 3: glBindTexture(GL_TEXTURE_2D, textures[1]); break; case 4: glBindTexture(GL_TEXTURE_2D, textures[2]); break; } } void display(void) { float origin[3] = {0,0,0}; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); updateeyeposition(); glLoadIdentity(); changetostring(intscorecounter); glDisable(GL_LIGHTING); glColor3f(1, 0, 0); textprinter(750,780, (char*)counterstring); glEnable(GL_LIGHTING); gluLookAt(eye[0],eye[1],eye[2], lookat[0],lookat[1],lookat[2], 0, 1, 0); glLightfv(GL_LIGHT0, GL_POSITION, light1_pos); glLightfv(GL_LIGHT1, GL_POSITION, light2_pos); drawFloor(); glDisable(GL_TEXTURE_2D); drawBasket(); DrawSnowman(pos, rot); if(textureToggle == true){ glEnable(GL_TEXTURE_2D); } ballTexture(); drawBall(); glutSwapBuffers(); glutPostRedisplay(); } bool calcIntersection(vec3D r0, vec3D rd) { //Max and min of bounding box for ball vec3D min, max; min.x = position[0] - 0.5f; min.y = position[1] - 0.5f; min.z = position[2] - 0.5f; max.x = min.x + 1.0f; max.y = min.y + 1.0f; max.z = min.z + 1.0f; //Calculate points on the front face of the ball point3D p0, p1, p2, p3; p0.x = min.x; p0.y = min.y; p0.z = max.z; p1.x = max.x; p1.y = min.y; p1.z = max.z; p2.x = max.x; p2.y = max.y; p2.z = max.z; p3.x = min.x; p3.y = max.y; p3.z = max.z; //Calculate the equation of the plane intersecting with the face float a, b, c, d; vec3D t1, t2, norm; t1 = t1.createVector(p1, p0); t2 = t2.createVector(p2, p0); norm = t1.crossProduct(t2); norm = norm.normalize(); d = -((norm.x * p0.x) + (norm.y * p0.y) + (norm.z * p0.z)); a = norm.x; b = norm.y; c = norm.z; //Test for intersection of the ray and the plane float t, dot0, dotD; vec3D is; dot0 = (a * r0.x) + (b * r0.y) + (c * r0.z); dotD = (a * rd.x) + (b * rd.y) + (c * r0.z); if (dot0 == 0) return false; t = -((dot0 + d) / dotD); is = r0 + rd.vectorMultiply(t); if ((is.x > p0.x) && (is.x < p1.x) && (is.y > p0.y) && (is.y < p2.y)) { return true; } else { return false; } } bool rayCast(float x, float y) { GLint viewport[4]; //declaring arrays and variables GLdouble modelview[16]; GLdouble projection[16]; float winX; float winY; GLdouble pos1X, pos1Y, pos1Z; GLdouble pos2X, pos2Y, pos2Z; GLdouble dirX, dirY, dirZ; vec3D r0, rd; glGetIntegerv(GL_VIEWPORT, viewport); glGetDoublev(GL_MODELVIEW_MATRIX, modelview); glGetDoublev(GL_PROJECTION_MATRIX, projection); //Flip the y coordinate to have the proper opengl screen coords winX = x; winY = (float)viewport[3] - y; //Unproject the coordinates from screen to world coordinates on the near clipping plane gluUnProject(winX, winY, 0.0, modelview, projection, viewport, &pos1X, &pos1Y, &pos1Z); //Unproject the coordinates from screen to world coordinates on the far clipping plane gluUnProject(winX, winY, 1.0, modelview, projection, viewport, &pos2X, &pos2Y, &pos2Z); //Calculate a normalized ray between the far and near clipping planes dirX = pos2X - pos1X; dirY = pos2Y - pos1Y; dirZ = pos2Z - pos1Z; r0.x = pos1X; r0.y = pos1Y; r0.z = pos1Z; rd.x = dirX; rd.y = dirY; rd.z = dirZ; rd = rd.normalize(); if (calcIntersection(r0, rd)) { return true; } else { return false; } } void mouse(int btn, int state, int x, int y){ if (btn == GLUT_LEFT_BUTTON && launched == false){ if (state == GLUT_DOWN){ startingMousepos[0] = x, startingMousepos[1] = y; //store the starting mouse position startTime=(GLfloat)glutGet(GLUT_ELAPSED_TIME); //store the time when the user first clicks down } else if(state == GLUT_UP){ finalMousepos[0] = x; finalMousepos[1] = y; endTime=(GLfloat)glutGet(GLUT_ELAPSED_TIME); //store the time when the user first clicks down float timeElapsed = endTime - startTime; float dy = -(finalMousepos[1] - startingMousepos[1]); float dx = -(finalMousepos[0] - startingMousepos[0]); averageXVelocity = dx/timeElapsed; averageZVelocity = dy/timeElapsed; velocity[0] += averageXVelocity*5; velocity[1] = 20; velocity[2] += averageZVelocity*5; printf("%f\n", windspeed); launched = true; bounced = false; } } } void callbackinit(){ glutTimerFunc(0, ballMotion, 0); } /* main function - program entry point */ int main(int argc, char** argv) { srand(time(NULL)); glutInit(&argc, argv); //starts up GLUT glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(800, 800); glutInitWindowPosition(100, 100); glutCreateWindow("BallToss"); //creates the window glutDisplayFunc(display); //registers "display" as the display callback function glutKeyboardFunc(keyboard); glutMouseFunc(mouse); glutSpecialFunc(special); glEnable(GL_DEPTH_TEST); //glFrontFace((GL_CCW)); //glCullFace(GL_BACK); //glEnable(GL_CULL_FACE); init(); initTexture(); callbackinit(); glutMainLoop(); //starts the event loop return(0); //return may not be necessary on all compilers }
#define BOOST_TEST_MAIN #include "task_13.h" #include <boost/test/unit_test.hpp> //testcase 1 BOOST_AUTO_TEST_CASE(test_1){ int m = 5; int n = 3; string actual = task::getMatrix(m, n); stringstream ss_test; ss_test << " 1 2 4 7 10" << endl << " 3 5 8 11 13" << endl << " 6 9 12 14 15" << endl; string expected = ss_test.str(); BOOST_REQUIRE_EQUAL(strcmp(expected.c_str(),actual.c_str()), 0); } //testcase 2 BOOST_AUTO_TEST_CASE(test_2){ int m = 5; int n = 3; string actual = task::getMatrix(m, n); stringstream ss_test; ss_test << " 1 2 4 7 10" << endl << " 3 5 8 11 13" << endl << " 6 9 12 14 15"; string expected = ss_test.str(); BOOST_CHECK(strcmp(expected.c_str(),actual.c_str()), 0); }
#ifndef ROSE_GENERIC_DATAFLOW_COMMON_H #define ROSE_GENERIC_DATAFLOW_COMMON_H #include <sage3.h> #include <list> using std::list; #include <map> using std::map; using std::pair; using std::make_pair; #include <set> using std::set; #include <vector> using std::vector; #include <string> using std::string; #include <iostream> using std::ostream; using std::ofstream; #include <sstream> using std::stringstream; using std::ostringstream; using std::endl; using std::cout; using std::cerr; #include "AnalysisDebuggingUtils.h" using namespace VirtualCFG; const int ZERO = 0; //const int SPECIAL = 1; const int INF = 10101010; const std::string ZEROStr = "0"; //const std::string SPECIALStr = "$"; inline bool XOR(bool x, bool y) { return x != y; } #define SgDefaultFile Sg_File_Info::generateDefaultFileInfoForTransformationNode() /* ############################# ######### T Y P E S ######### ############################# */ typedef long long quad; //typedef quad variable; typedef std::map<quad, quad> m_quad2quad; typedef std::map<quad, std::string> m_quad2str; typedef std::map<quad, m_quad2quad> m_quad2map; typedef std::pair<quad, quad> quadpair; typedef std::list<quad> quadlist; typedef std::map<quad, quadpair> m_quad2quadpair; typedef std::map<quad, bool> m_quad2bool; #endif
/******************************************************************************* * Cristian Alexandrescu * * 2163013577ba2bc237f22b3f4d006856 * * 11a4bb2c77aca6a9927b85f259d9af10db791ce5cf884bb31e7f7a889d4fb385 * * bc9a53289baf23d369484f5343ed5d6c * *******************************************************************************/ /* Problem 11991 - Easy Problem from Rujia Liu? */ #include <iostream> #include <unordered_map> #include <map> #include <vector> using namespace std; int main() { for (int nNoNumbers, nNoQueries; cin >> nNoNumbers >> nNoQueries;) { typedef unordered_map<unsigned int, vector<unsigned int>> STRUCT_TYPE; // typedef map<unsigned int, vector<unsigned int>> STRUCT_TYPE; STRUCT_TYPE oDict; for (int nLoop = 1; nLoop <= nNoNumbers; nLoop++) { unsigned int nNumber; cin >> nNumber; oDict[nNumber].push_back(nLoop); } while (nNoQueries--) { unsigned int nK, nV, nResponse = 0; cin >> nK >> nV; auto oIt = oDict.find(nV); if (oIt != oDict.end() && oIt->second.size() >= nK) nResponse = oIt->second[nK - 1]; cout << nResponse << endl; } } return 0; }
/***************************************************************************************************** * 剑指offer第64题 * 如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间 的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。我们使用 Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。 * * Input: 数据流 * Output: 数据流的中位数----注意奇偶性 * * Note: (时间复杂度O(nlogn),空间复杂度O(1),利用最大堆和最小堆实现) * 利用优先队列实现最大堆最小堆,如果不声明greater<int>,的话,默认为最大堆,即less<int>() 因为要求的是中位数,那么这两个堆,大顶堆用来存较小的数,从大到小排列;(注意一定要分奇偶数) 小顶堆存较大的数,从小到大的顺序排序*,显然中位数就是大顶堆的根节点与小顶堆的根节点和的平均数。 ⭐保证:小顶堆中的元素都大于等于大顶堆中的元素,所以每次塞值,并不是直接塞进去,而是从另一个堆中poll出一个最大(最小)的塞值 ⭐当数目为偶数的时候,将这个值插入大顶堆中,再将大顶堆中根节点(即最大值)插入到小顶堆中; ⭐当数目为奇数的时候,将这个值插入小顶堆中,再讲小顶堆中根节点(即最小值)插入到大顶堆中; ⭐取中位数的时候,如果当前个数为偶数,显然是取小顶堆和大顶堆根结点的平均值;如果当前个数为奇数,显然是取小顶堆的根节点 * author: lcxanhui@163.com * time: 2019.7.8 ******************************************************************************************************/ #include <iostream> #include <vector> #include <queue> using namespace std; class Solution { public: void Insert(int num) { if (max_heap.size() == 0) { max_heap.push(num); return; } //下面分三大种情况进行讨论,每种情况有特殊的小情况 if (max_heap.size() == min_heap.size()) { if (num < max_heap.top()) max_heap.push(num); else min_heap.push(num); } else if (max_heap.size() > min_heap.size()) //此种情况下下一个数据应该插入到小顶堆中 { //注意特殊情况,也就是插入小顶堆的数比大顶堆的堆顶的数还要小 if (num < max_heap.top()) { min_heap.push(max_heap.top()); max_heap.pop(); max_heap.push(num); } else min_heap.push(num); } else if (max_heap.size() < min_heap.size()) //此种情况下下一个数据应该插入到大顶堆中 { if (num > min_heap.top()) { max_heap.push(min_heap.top()); min_heap.pop(); min_heap.push(num); } else max_heap.push(num); } } double GetMedian() { if (max_heap.size() == min_heap.size()) return (max_heap.top() + min_heap.top()) / 2.0; else if (max_heap.size() > min_heap.size()) return max_heap.top(); else return min_heap.top(); } private: priority_queue<int, vector<int>, less<int>()> max_heap; //最大堆(大顶堆)--系统默认 priority_queue<int, vector<int>, greater<int>()> min_heap; //最小堆(小顶堆) }; int main(void) { Solution s; s.Insert(5); cout << s.GetMedian() << " "; s.Insert(2); cout << s.GetMedian() << " "; s.Insert(6); cout << s.GetMedian() << " "; s.Insert(4); cout << s.GetMedian() << " "; system("pause"); return 0; }