text
stringlengths
8
6.88M
#include "HttpRequest.h" #include "HttpServer.h" #include "HttpStringParser.h" /* * 字符串分割函数 */ static std::vector<std::string> split(std::string str, std::string pattern) { std::string::size_type pos; std::vector<std::string> result; str += pattern;//扩展字符串以方便操作 int size = str.size(); for (int i = 0; i < size; i++) { pos = str.find(pattern, i); if (pos < size) { result.emplace_back(str.substr(i, pos - i)); i = pos + pattern.size() - 1; } } return result; } /* * 获取当前程序运行路径 */ static std::string GetProgramDir() { char exeFullPath[MAX_PATH]; // Full path std::string strPath = ""; GetModuleFileNameA(NULL, exeFullPath, MAX_PATH); strPath = (std::string)exeFullPath; // Get full path of the file int pos = strPath.find_last_of('\\', strPath.length()); return strPath.substr(0, pos); // Return the directory without the file name } /* * 得到一行数据,只要发现c为\n,就认为是一行结束,如果读到\r,再用MSG_PEEK的方式读入一个字符,如果是\n,从socket用读出 * 如果是下个字符则不处理,将c置为\n,结束。如果读到的数据为0中断,或者小于0,也视为结束,c置为\n */ int HttpRequest::getLine(int sock, char * buf, int size) { int i = 0; char c = '\0'; int n; while ((i < size - 1) && (c != '\n')) { n = recv(sock, &c, 1, 0); /* DEBUG printf("%02X\n", c); */ if (n > 0) { if (c == '\r') { //偷窥一个字节,如果是\n就读走 n = recv(sock, &c, 1, MSG_PEEK); /* DEBUG printf("%02X\n", c); */ if ((n > 0) && (c == '\n')) recv(sock, &c, 1, 0); else //不是\n(读到下一行的字符)或者没读到,置c为\n 跳出循环,完成一行读取 c = '\n'; } buf[i] = c; i++; } else c = '\n'; } buf[i] = '\0'; return(i); } /* * 获得请求内容, 内部做分行处理 */ std::vector<std::string> HttpRequest::getRequestContent() { //定义长度变量 int send_len = 0; int recv_len = 0; int len = 0; //定义发送缓冲区和接受缓冲区 char send_buf[100]; char recv_buf[100]; while (1) { recv_len = recv(this->clientSocketID, recv_buf, 100, 0); if (recv_len < 0) { std::cout << "接受失败!" << std::endl; break; } else { std::cout << "客户端信息:" << recv_buf << std::endl; } std::cout << "请输入回复信息:"; //std::cin >> send_buf; //send_len = send(s_accept, send_buf, 100, 0); if (send_len < 0) { std::cout << "发送失败!" << std::endl; break; } } /* char buf[20480]; int rcd; std::string longContent; while (true) { memset(buf, 0, 0); rcd = recv(this->clientSocketID, buf, 20480, 0); if (rcd == 0) break; if (rcd == SOCKET_ERROR) { rcd = WSAGetLastError(); if (rcd == WSAETIMEDOUT) break; this->pmLog->print(this->LOGFILENAME, "FATAL ERROR 接收时出现错误!\nRecv error!\nError code:" + std::to_string(WSAGetLastError())); break; } longContent += std::string(buf); } std::vector<std::string> res = split(longContent, "\r\n");*/ /* int numchars = this->getLine(this->clientSocketID, buf, sizeof(buf));; if (numchars == 0) return res; else { res.emplace_back(std::string(buf)); while (true) { numchars = this->getLine(this->clientSocketID, buf, sizeof(buf)); if (!((numchars > 0) && strcmp("\n", buf))) break; else { res.emplace_back(std::string(buf)); } } }*/ std::vector<std::string> res = {}; return res; } /* * 通用请求 * s: 备选字符串, 对于非200响应是默认发送消息, 对于200响应是文件路径 * , isRenderFile: 是否用文件内容, (enum)en请求类型 */ void HttpRequest::CommonResponse(std::string s, bool isRenderFile, enum HTTPCODE hc) { switch (hc) { case HttpRequest::HTTP200: { send(this->clientSocketID, this->HTTP_CODE200.c_str(), (int)this->HTTP_CODE200.size(), 0); break; } case HttpRequest::HTTP404: { send(this->clientSocketID, this->HTTP_CODE404.c_str(), (int)this->HTTP_CODE404.size(), 0); break; } case HttpRequest::HTTP400: { send(this->clientSocketID, this->HTTP_CODE400.c_str(), (int)this->HTTP_CODE400.size(), 0); break; } case HttpRequest::HTTP500: { send(this->clientSocketID, this->HTTP_CODE500.c_str(), (int)this->HTTP_CODE500.size(), 0); break; } case HttpRequest::HTTP501: { send(this->clientSocketID, this->HTTP_CODE501.c_str(), (int)this->HTTP_CODE501.size(), 0); break; } default: break; } send(this->clientSocketID, this->HTTP_SERVER.c_str(), (int)this->HTTP_SERVER.size(), 0); send(this->clientSocketID, this->HTTP_CHARSET.c_str(), (int)this->HTTP_CHARSET.size(), 0); send(this->clientSocketID, this->HTTP_EMPTR_LINE.c_str(), (int)this->HTTP_EMPTR_LINE.size(), 0); if (isRenderFile) { switch (hc) { case HttpRequest::HTTP200: { if (!this->SendFileContent(s.c_str())) { if (!this->SendFileContent(FILE_NOTFOUND.c_str())) send(this->clientSocketID, "url file not found", (int)s.size(), 0); } break; } case HttpRequest::HTTP404: { if (!this->SendFileContent(FILE_NOTFOUND.c_str())) send(this->clientSocketID, s.c_str(), (int)s.size(), 0); break; } case HttpRequest::HTTP400: { if (!this->SendFileContent(FILE_BAD_REQUEST.c_str())) send(this->clientSocketID, s.c_str(), (int)s.size(), 0); break; } case HttpRequest::HTTP500: { if (!this->SendFileContent(FILE_INTERNAL_SERVER_ERROR.c_str())) send(this->clientSocketID, s.c_str(), (int)s.size(), 0); break; } case HttpRequest::HTTP501: { if (!this->SendFileContent(FILE_METHOD_NOT_IMPLEMENTED.c_str())) send(this->clientSocketID, s.c_str(), (int)s.size(), 0); break; } default: break; } } else send(this->clientSocketID, s.c_str(), (int)s.size(), 0); } /* * 发送文件内容 * 返回true说明文件存在发送成功, false说明文件不存在, 需要调用者自行处理content内容 * 注意: 此处用到工作目录, filename 按照如下格式html/404.html * 因此: 用filesystem库格式化这个目录, 再用C api进行文件读写 */ bool HttpRequest::SendFileContent(const char * filename) { std::filesystem::path filePath = std::filesystem::absolute(filename); std::string windowsTypePath = filePath.string(); FILE *resource = NULL; errno_t err; err = fopen_s(&resource, windowsTypePath.c_str(), "r"); if (err != 0) return false; else { char buf[1024]; fgets(buf, sizeof(buf), resource); //循环读 while (!feof(resource)) { send(this->clientSocketID, buf, strlen(buf), 0); fgets(buf, sizeof(buf), resource); } if (strlen(buf) != 0) send(this->clientSocketID, buf, strlen(buf), 0); fclose(resource); return true; } } /* * HttpRequest类初始化, 初始化客户端SocketID * 初始化项目目录 */ HttpRequest::HttpRequest(unsigned int c) :clientSocketID(c) { pmLog = Mlog::Instance(); } /* * 接受请求总接口 */ void HttpRequest::acceptRequestInterface() { /* //定义长度变量 int send_len = 0; int recv_len = 0; int len = 0; //定义发送缓冲区和接受缓冲区 char send_buf[100]; char recv_buf[100]; while (1) { recv_len = recv(this->clientSocketID, recv_buf, 100, 0); if (recv_len < 0) { std::cout << "接受失败!" << std::endl; break; } else { std::cout << "客户端信息:" << recv_buf << std::endl; } std::cout << "请输入回复信息:"; std::cin >> send_buf; send_len = send(this->clientSocketID, send_buf, 100, 0); if (send_len < 0) { std::cout << "发送失败!" << std::endl; break; } }*/ //获取请求数据 pmLog->print(this->LOGFILENAME, " "); pmLog->print(this->LOGFILENAME, "================================="); pmLog->print(this->LOGFILENAME, "begin accept_request"); std::vector<std::string> requestContent = this->getRequestContent(); //打印request所有信息 for (auto& rC : requestContent) this->pmLog->print(this->LOGFILENAME, rC); if (requestContent.empty()) this->pmLog->print(this->LOGFILENAME, "Confusing HTTP data: empty"); else if (PRINT_ALL_RAW_DATA_DEBUG) this->NotFound("NOT FOUNDDDDD", true); else { httpMethodStr hms = parserFirstLine(requestContent[0]); //解析第一行字符串 if (hms.httpMethod == HTTPMETHOD::HTTPMETHOD_OTHER) { this->MethodNotImplemented("NOT IMPLEMENTED!!", true); } else if (hms.httpMethod == HTTPMETHOD::HTTPMETHOD_GET_PARAERROR) { this->BadRequest("BAD REQUEST!!", true); } else if (hms.httpMethod == HTTPMETHOD::HTTPMETHOD_GET_COMMON || hms.httpMethod == HTTPMETHOD::HTTPMETHOD_POST) //查找文件 { //this->NotFound("NOT FOUNDDDDD", true); //如果hms.dir为空, 则使用DEFAULT_FILE //否则如果hms.dir[0] == '/'则去除头部(实际上一定是'/')再用hms.dir //否则直接用hms.dir if (hms.dir.empty()) this->NormalRequest(DEFAULT_FILE, true); else if (hms.dir[0] == '/') { hms.dir.erase(hms.dir.begin()); this->NormalRequest(hms.dir, true); } else this->NormalRequest(hms.dir, true); //执行cgi文件 //execute_cgi(client, path, method, query_string); } } this->pmLog->print(this->LOGFILENAME, "end accept_request"); } void HttpRequest::closeRequestInterface() { this->pmLog->destroy(); } HttpRequest::~HttpRequest() { } /* * 子线程函数 */ void acceptRequestThread(unsigned int client) { HttpRequest h(client); h.acceptRequestInterface(); h.closeRequestInterface(); }
/* value_test.cpp -*- C++ -*- Rémi Attab (remi.attab@gmail.com), 26 Mar 2014 FreeBSD-style copyright and disclaimer apply Tests for the Value function. */ #define BOOST_TEST_MAIN #define BOOST_TEST_DYN_LINK #include "tests.h" #include "reflect.h" #include "test_types.h" #include <boost/test/unit_test.hpp> using namespace reflect; /******************************************************************************/ /* VOID */ /******************************************************************************/ BOOST_AUTO_TEST_CASE(void_) { Value val; BOOST_CHECK(val.isVoid()); BOOST_CHECK_EQUAL(Value().type(), val.type()); } /******************************************************************************/ /* CONSTRUCT */ /******************************************************************************/ // Make sure that Value compiles regardless of whether the copy/move // constructors are there or not. We should instead break at runtime IF they are // used. BOOST_AUTO_TEST_CASE(construct) { BOOST_TEST_CHECKPOINT("construct-int"); Value(0); BOOST_TEST_CHECKPOINT("construct-ncp"); test::NotCopiable ncp; Value(std::move(ncp)); BOOST_TEST_CHECKPOINT("construct-nmv"); test::NotMovable nmv; Value(std::move(nmv)); BOOST_TEST_CHECKPOINT("construct-ncs"); std::unique_ptr<test::NotConstructible> ncs(test::NotConstructible::make()); CHECK_ERROR(Value(std::move(*ncs))); BOOST_TEST_CHECKPOINT("construct-done"); } /******************************************************************************/ /* DESTRUCT */ /******************************************************************************/ struct Destruct { ~Destruct() { count++; } static void reset() { count = 0; } static size_t count; }; size_t Destruct::count = 0; reflectType(Destruct) { reflectPlumbing(); } BOOST_AUTO_TEST_CASE(destruct) { auto check = [] (std::string name, size_t count) { std::cerr << name << ": " << Destruct::count << std::endl; BOOST_CHECK_EQUAL(Destruct::count, count); Destruct::reset(); }; Destruct d; Destruct::reset(); { Value obj{d}; (void) obj; } check("lref", 0); { Value obj(std::move(d)); (void) obj; } check("rref", 1); { Value obj(std::move(d)); Value valueCopy(obj); (void) valueCopy; } check("value-copy", 1); // The reflected copy constructor is a lambda that returns a rvalue which is // moved into the Value object but also destroyed. hence the 3 instead of // the expected two. { Value obj(std::move(d)); Value objCopy = obj.copy(); (void) objCopy; } check("obj-copy", 2 + 1); { Value obj(std::move(d)); Value valueMove = std::move(obj); (void) valueMove; } check("value-move", 1); // Calling move creates lots of temporaries that are moved around quite a // bit. I hand checked these to make sure that there's only call to the // destructor that originates from a shared_ptr as we expect. { Value obj(std::move(d)); Value objMove = obj.move(); (void) objMove; } check("obj-move", 3 + 1); } /******************************************************************************/ /* LVALUE */ /******************************************************************************/ BOOST_AUTO_TEST_CASE(lValue) { unsigned u = 10; Value lValue(u); BOOST_CHECK(!lValue.isConst()); BOOST_CHECK_EQUAL(lValue.refType(), RefType::LValue); BOOST_CHECK_EQUAL(lValue.get<unsigned>(), u); } /******************************************************************************/ /* CONST LVALUE */ /******************************************************************************/ BOOST_AUTO_TEST_CASE(constLValue) { const unsigned u = 10; Value lValue(u); BOOST_CHECK(lValue.isConst()); BOOST_CHECK_EQUAL(lValue.refType(), RefType::LValue); BOOST_CHECK_EQUAL(lValue.get<unsigned>(), u); } /******************************************************************************/ /* RVALUE */ /******************************************************************************/ BOOST_AUTO_TEST_CASE(rValue) { unsigned u = 10; Value rValue(std::move(u)); u = 20; // Just to make sure we don't have a ref to u. BOOST_CHECK(!rValue.isConst()); BOOST_CHECK_EQUAL(rValue.refType(), RefType::LValue); BOOST_CHECK_EQUAL(rValue.get<unsigned>(), 10u); } /******************************************************************************/ /* CONST RVALUE */ /******************************************************************************/ BOOST_AUTO_TEST_CASE(constRValue) { const unsigned i = 0; Value rValue(std::move(i)); BOOST_CHECK(!rValue.isConst()); BOOST_CHECK_EQUAL(rValue.refType(), RefType::LValue); } /******************************************************************************/ /* PARENT-CHILD */ /******************************************************************************/ BOOST_AUTO_TEST_CASE(parent) { test::Parent p(10, 20); Value value(p); BOOST_CHECK_EQUAL(&value.get<test::Interface>(), &p); BOOST_CHECK_EQUAL(&value.get<test::Parent>(), &p); CHECK_ERROR(value.get<test::Child>()); } BOOST_AUTO_TEST_CASE(child) { test::Child c(10, 20); Value value(c); BOOST_CHECK_EQUAL(&value.get<test::Interface>(), &c); BOOST_CHECK_EQUAL(&value.get<test::Parent>(), &c); BOOST_CHECK_EQUAL(&value.get<test::Child>(), &c); } /******************************************************************************/ /* CONVERTIBLE */ /******************************************************************************/ BOOST_AUTO_TEST_CASE(convertible) { test::Object o(10); test::Convertible c(o); Value value(c); BOOST_CHECK_EQUAL(&value.get<test::Convertible>(), &c); CHECK_ERROR(value.get<test::Parent>()); } /******************************************************************************/ /* COMPILATION */ /******************************************************************************/ BOOST_AUTO_TEST_CASE(copyMove) { test::Object obj(10); Value vObj(obj); { Value copy = vObj.copy(); BOOST_CHECK_EQUAL(copy.field<int>("value"), 10); BOOST_CHECK_EQUAL(vObj.field<int>("value"), 10); BOOST_CHECK_EQUAL(obj.value, 10); } { Value moved = vObj.move(); BOOST_CHECK_EQUAL(moved.field<int>("value"), 10); BOOST_CHECK(vObj.isVoid()); BOOST_CHECK_EQUAL(obj.value, 0); } }
/* =============================================================================== Name : main.c Author : $(author) Version : Copyright : $(copyright) Description : main definition =============================================================================== */ #if defined (__USE_LPCOPEN) #if defined(NO_BOARD_LIB) #include "chip.h" #else #include "board.h" #endif #endif #include "DigitalIOPin.h" #include <cr_section_macros.h> #include <mutex> #include "syslog.h" #include <semphr.h> #include <queue.h> #include "ITM_write.h" #include <time.h> // TODO: insert other include files here // TODO: insert other definitions and declarations here #include "FreeRTOS.h" #include "task.h" #include <stdlib.h> #include "event_groups.h" EventGroupHandle_t eventSW; static void prvSetupHardware(void) { SystemCoreClockUpdate(); Board_Init(); /* Initial LED0 state is off */ Board_LED_Set(0, false); } Syslog logger = Syslog(); static void vTask1(void *pvParameters) { DigitalIoPin button1 (17, 0, true, true, false); bool release = true; while(1) { if(button1.read()) { if(release) { xEventGroupSetBits(eventSW, (1<<0)); release = false; } }else{release = true;} } } static void vTask2(void *pvParameters) { EventBits_t eBit; EventBits_t waitBit = (1<<0); char debug[30]; while (1) { eBit = xEventGroupWaitBits(eventSW, waitBit, pdTRUE, pdTRUE, portMAX_DELAY); int start_ticks = xTaskGetTickCount(); int interval = rand()% 1000 + 1000; vTaskDelay(interval); if((eBit & waitBit) != 0) { int elapsed = xTaskGetTickCount() - start_ticks; sprintf(debug,"Task 2 wait %d ms.\r\n", elapsed); logger.write(debug); } vTaskDelay(5); } } //Debug print task static void vTask3(void *pvParameters) { EventBits_t eBit; EventBits_t waitBit = (1<<0); char debug[30]; while (1) { eBit = xEventGroupWaitBits(eventSW, waitBit, pdTRUE, pdTRUE, portMAX_DELAY); int start_ticks = xTaskGetTickCount(); int interval = rand()% 1000 + 1000; vTaskDelay(interval); if((eBit & waitBit) != 0) { int elapsed = xTaskGetTickCount() - start_ticks; sprintf(debug,"Task 3 wait %d ms.\r\n", elapsed); logger.write(debug); } vTaskDelay(5); } } static void vTask4(void *pvParameters) { EventBits_t eBit; EventBits_t waitBit = (1<<0); char debug[30]; while (1) { eBit = xEventGroupWaitBits(eventSW, waitBit, pdTRUE, pdTRUE, portMAX_DELAY); int start_ticks = xTaskGetTickCount(); int interval = rand()% 1000 + 1000; vTaskDelay(interval); if((eBit & waitBit) != 0) { int elapsed = xTaskGetTickCount() - start_ticks; sprintf(debug,"Task 4 wait %d ms.\r\n", elapsed); logger.write(debug); } vTaskDelay(5); } } extern "C" { void vConfigureTimerForRunTimeStats( void ) { Chip_SCT_Init(LPC_SCTSMALL1); LPC_SCTSMALL1->CONFIG = SCT_CONFIG_32BIT_COUNTER; LPC_SCTSMALL1->CTRL_U = SCT_CTRL_PRE_L(255) | SCT_CTRL_CLRCTR_L; // set prescaler to 256 (255 + 1), and start timer } } int main(void) { prvSetupHardware(); ITM_init(); eventSW = xEventGroupCreate(); srand(time(NULL)); xTaskCreate(vTask1, "vTask1", configMINIMAL_STACK_SIZE *2 , NULL, (tskIDLE_PRIORITY + 1UL), (TaskHandle_t *) NULL); xTaskCreate(vTask2, "vTask2", configMINIMAL_STACK_SIZE *3 , NULL, (tskIDLE_PRIORITY + 1UL), (TaskHandle_t *) NULL); xTaskCreate(vTask3, "vTask3", configMINIMAL_STACK_SIZE *3 , NULL, (tskIDLE_PRIORITY + 1UL), (TaskHandle_t *) NULL); xTaskCreate(vTask4, "vTask4", configMINIMAL_STACK_SIZE *3 , NULL, (tskIDLE_PRIORITY + 1UL), (TaskHandle_t *) NULL); vTaskStartScheduler(); return 1; }
#ifndef ADMINISTRADOR_H #define ADMINISTRADOR_H #include <QMainWindow> #include <QMap> #include <QString> #include <QMessageBox> #include "resultados.h" #include "principal.h" using namespace std; namespace Ui { class Administrador; } class Administrador : public QMainWindow { Q_OBJECT public: explicit Administrador(QWidget *parent = nullptr); ~Administrador(); private slots: void on_cmdAcceder_clicked(); void on_cmdCancelar_clicked(); private: Ui::Administrador *ui; QMap<QString, int> map; }; #endif // ADMINISTRADOR_H
/* // Created by: Jacob Cassady // Date Created: 9/3/2016 // Last Updated: 9/9/2016 */ /* Problem statement: Design a class template, OrderedCollection, that stores a collection of Comparables (in an array), along with the current size of the collection. Provide public functions isEmpty, makeEmpty, insert, remove, findMin, and findMax. findMin and findMax return references to the smallest and largest, respectively, Comparable in the collection. explain what can be done if these operations are performed on an empty collection. */ #include <iostream> #include <string> using namespace std; template<typename Comparable> class OrderedCollection{ public: /***************CONSTRUCTORS***************/ OrderedCollection(void) { collectionSize = 0; collection[1000] = 0; } OrderedCollection(unsigned size, Comparable intialValue){ collectionSize = size; collection[1000] = 0; for(unsigned collection_i=0; collection_i<collectionSize; collection_i++){ collection[collection_i] = intialValue; } } /***************END CONSTRUCTORS***************/ /***************ACCESSOR METHODS***************/ bool isEmpty(void) const{ if(collectionSize == 0){ return 0; } else { return 1; } } Comparable findMin(void) const{ Comparable min; min = 0; if(collectionSize == 0){ cout << "This collection is empty. Unable to return min Comparable." << endl; } else { min = collection[0]; for(unsigned collection_i = 0; collection_i < collectionSize; collection_i++){ if(collection[collection_i] < min){ min = collection[collection_i]; } } } return min; } Comparable findMax(void) const{ Comparable max; max = 0; if(collectionSize == 0){ cout << "This collection is empty. Unable to return max Comparable." << endl; } else { max = collection[0]; for(unsigned collection_i = 0; collection_i<collectionSize; collection_i++){ if(collection[collection_i] > max){ max = collection[collection_i]; } } } return max; } void displayContents(void) const { if(collectionSize == 0) { cout << "This collection is empty. There are no contents to display" << endl; } else { for(unsigned collection_i=0; collection_i<collectionSize; collection_i++){ cout << collection[collection_i] << endl; } } } /***************END ACCESSOR METHODS***************/ /***************MUTATOR METHODS***************/ void makeEmpty(void){ if (collectionSize == 0){ cout << "This collection is already empty" << endl; } else { for(unsigned collection_i = 0; collection_i < collectionSize; collection_i++){ collection[collection_i] = 0; } collectionSize = 0; } } void insert(Comparable newComparable){ collectionSize++; collection[(collectionSize-1)] = newComparable; } void remove(Comparable oldComparable){ bool found; unsigned tempCount=0; Comparable tempArray[1000]; found = false; for(unsigned collection_i=0; collection_i<collectionSize; collection_i++){ if(collection[collection_i] == oldComparable){ found = true; for(unsigned i=0; i<collectionSize; i++){ if(i != collection_i){ tempArray[tempCount] = collection[i]; tempCount++; } } break; } if(found){ break; } } if(found){ cout << "We were able to find and delete the first instance of " << oldComparable << "." << endl; for(unsigned collection_i=0; collection_i<collectionSize; collection_i++){ collection[collection_i] = tempArray[collection_i]; } collectionSize--; } else { cout << "Comparable not found within collection." << endl; } } /***************END MUTATOR METHODS***************/ private: Comparable collection[1000]; unsigned collectionSize; }; int main() { OrderedCollection<int> templateCollection; templateCollection.insert(5); templateCollection.insert(500); templateCollection.insert(5000); templateCollection.displayContents(); cout << templateCollection.findMin() << endl; cout << templateCollection.findMax() << endl; templateCollection.remove(500); templateCollection.displayContents(); templateCollection.makeEmpty(); cout << templateCollection.findMin() << endl; return 0; }
#include<cstdio> #include<sstream> #include<cstdlib> #include <iomanip> #include<cctype> #include<cmath> #include<algorithm> #include<set> #include<queue> #include<stack> #include<list> #include<iostream> #include<fstream> #include<numeric> #include<string> #include <unordered_map> #include<vector> #include<cstring> #include<map> #include<iterator> using namespace std; int ara[1000002]; bool ok[1000002]; int bsearch(int x,int y) { int low=0,high=y-1; while(low<=high) { int mid=(low+high)>>1; if(ara[mid]==x)return mid; if(ara[mid]<x)low=mid+1; else high=mid-1; } return -1; } int main() { int m,n; while(true) { int x,i=0,j,cnt=0; memset(ok,false,sizeof(ok)); scanf("%d %d",&m,&n); if(m==0 && n==0)break; if(m==0 || n==0) { for(int i=0;i<m;i++)scanf("%d",&x); for(int i=0;i<n;i++)scanf("%d",&x); printf("0\n"); } else{ for(i=0;i<m;i++){ scanf("%d",&x); ara[i]=x; } sort(ara,ara+i); for( j=0;j<n;j++){ scanf("%d",&x); int ck=bsearch(x,i); if(ck!=-1 && ok[ck]==false){cnt++;ok[ck]=true;} //if(ck)cnt++; } printf("%d\n",cnt); } } return 0; }
#include <SPI.h> #include <LedCubeStills.h> #include <LedCubeSequences.h> int clockPin = 13; int dataPin = 11; int latchEnablePin = 8; int outputEnablePin = 10; byte leds[8][8]; // [z],[y],1<<x int activeLayerIndex = 0; void setup() { Serial.begin(9600); // Timer 2 Initialization for 125uS interrupt. cli(); // Disable global interrupts TCCR2B = 0; TCCR2A = 0; TCNT2= 0; // Set counter to 0; OCR2A = 250; // Output Compare Register set to 250 TCCR2B |= 1 << CS21; // Set prescaler for 2MHz (16MHz/8). Error in documentation: not CA21. TCCR2A |= 1 << WGM21; // CTC Mode TIMSK2 |= 1 << OCIE1A; // Compare match A interrupt mask sei(); // Global interrupt enable (SREG[7] = 1) // Timer 2 Initialization End // SPI Initialization SPI.beginTransaction(SPISettings(14000000, MSBFIRST, SPI_MODE0)); // We never call endTransaction SPI.begin(); // SPI Initialization end // Cube Initialization pinMode(latchEnablePin, OUTPUT); pinMode(outputEnablePin, OUTPUT); digitalWrite(outputEnablePin, LOW); digitalWrite(latchEnablePin, LOW); LedCubeStills::clearAll(leds); // Cube Initialization End } void loop() { LedCubeStills::flood(leds); } ISR(TIMER2_COMPA_vect) { digitalWrite(latchEnablePin, LOW); SPI.transfer(leds[activeLayerIndex][7]); SPI.transfer(leds[activeLayerIndex][6]); SPI.transfer(leds[activeLayerIndex][5]); SPI.transfer(leds[activeLayerIndex][4]); SPI.transfer(leds[activeLayerIndex][3]); SPI.transfer(leds[activeLayerIndex][2]); SPI.transfer(leds[activeLayerIndex][1]); SPI.transfer(leds[activeLayerIndex][0]); SPI.transfer(~((byte)1<<activeLayerIndex)); activeLayerIndex = (activeLayerIndex+1)%8; digitalWrite(latchEnablePin, HIGH); }
// Decimal to hexadecimal #include <iostream> using namespace std; //convert decimal to hexadecimal void convert(int num) { char arr[100]; int i = 0; while (num != 0) { int temp = 0; temp = num % 16; if (temp < 10) { arr[i] = temp + 48; i++; } else { arr[i] = temp + 55; i++; } num = num / 16; } for (int j = i - 1; j >= 0; j--) cout << arr[j]; } int main() { int num = 6789; cout << num << " converted to hexadeciaml: "; convert(num); return 0; }
// // Observable.hpp // Assignment3 // // Created by mushfiqur anik on 2019-11-17. // Copyright © 2019 mushfiqur anik. All rights reserved. // #pragma once #include <list> using namespace std; class Observer; class Observable { public: virtual ~Observable() {}; virtual void Attach(Observer *) = 0; virtual void Detach(Observer *) = 0; virtual void Notify() = 0; virtual void Notify(int playerID, string phase, string action) = 0; // This is for the PhaseObserver View protected: Observable() {}; private: list<Observer*> _observers; };
class Solution { public: string shortestPalindrome(string s) { int n = s.size(); vector<int> fail(n, -1); for (int i = 1; i < n; ++i) { int j = fail[i - 1]; while (j != -1 && s[j + 1] != s[i]) { j = fail[j]; } if (s[j + 1] == s[i]) { fail[i] = j + 1; } } int best = -1; for (int i = n - 1; i >= 0; --i) { while (best != -1 && s[best + 1] != s[i]) { best = fail[best]; } if (s[best + 1] == s[i]) { ++best; } } string add = (best == n - 1 ? "" : s.substr(best + 1, n)); reverse(add.begin(), add.end()); return add + s; } };
#ifndef DLLMYSQL_H #define DLLMYSQL_H #include "QSqlTableModel" #include <QObject> #include "dllmysql_global.h" class DLLMYSQLSHARED_EXPORT DLLMySQL: public QObject { Q_OBJECT public: DLLMySQL(); int DLLMYSQLSHARED_EXPORT validateCard(QString cardId); int DLLMYSQLSHARED_EXPORT validatePINCode(QString , int); bool DLLMYSQLSHARED_EXPORT mysqlconnection(); QString DLLMYSQLSHARED_EXPORT findName(int); double DLLMYSQLSHARED_EXPORT raiseMoney(int, int); double DLLMYSQLSHARED_EXPORT showBalance(int); QSqlTableModel *showTransactions(int, int); int DLLMYSQLSHARED_EXPORT invoiceCount(int); int DLLMYSQLSHARED_EXPORT getInvoiceId(int); void DLLMYSQLSHARED_EXPORT getInvoiceDetails(int); bool DLLMYSQLSHARED_EXPORT payInvoice(int,int,double); void DLLMYSQLSHARED_EXPORT getDonateInfo(int); bool DLLMYSQLSHARED_EXPORT payDonation(int,int,int); //mita, milta,paljonko signals: void DLLMYSQLSHARED_EXPORT sendTili(QString); void DLLMYSQLSHARED_EXPORT sendSaaja(QString); void DLLMYSQLSHARED_EXPORT sendViite(QString); void DLLMYSQLSHARED_EXPORT lahetaSumma(double); }; #endif // DLLMYSQL_H
/* * Copyright 2016-2017 Flatiron Institute, Simons Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "icomponent.h" #include "objectregistry.h" IComponent::IComponent(QObject* parent) : QObject(parent) { } void IComponent::extensionsReady() {} QStringList IComponent::dependencies() const { return QStringList(); } void IComponent::addObject(QObject* o) { ObjectRegistry::addObject(o); } void IComponent::addAutoReleasedObject(QObject* o) { ObjectRegistry::addAutoReleasedObject(o); } void IComponent::removeObject(QObject* o) { ObjectRegistry::removeObject(o); }
// Node for a binary tree // Created by A. Student // Modified by: Tuan Truong // This hash table is using linked list as a collision resolution method #ifndef _HASH_TABLE_H #define _HASH_TABLE_H #include<string> #include<iostream> #include<iomanip> #include<cmath> #include"SList.hpp" using namespace std; template<class ItemType> class HashTable { private: SList<ItemType>* data; // an array of Linked List int size; // the hash table size int count; // number of items in the hash table int dankHash(string key) const; // good hash int oofHash(string key) const; // bad hash public: // the main functions HashTable(int number) { allocateMemory(number); count = 0; } ~HashTable() { delete[] data; } void allocateMemory(int number); bool insert(ItemType item); bool search(const ItemType target, ItemType &returnItem, int compare(ItemType left, ItemType right)); bool remove(const ItemType target, ItemType &returnItem, int compare(ItemType left, ItemType right)); void printHashTable(void print(ItemType)); void printHashSeq(void print(ItemType)); // getters int getSize() const { return size; } int getCount() const { return count; } double getLoadFactor() const; int getCollisions() const; bool isEmpty() const { return count == 0; } }; // check if the number is prime bool IsPrime(int number) { for (int i = 2; i < number / 2; i++) { if (number % i == 0) { return false; } } return true; } // allcate the memory for the hash table template<class ItemType> void HashTable<ItemType>::allocateMemory(int number) { int size = number * 2 + 1; //size = number * 2 + 1; while (!IsPrime(size)) { size++; } data = new SList<ItemType>[size]; count = 0; this->size = size; } // the good hashing function template<class ItemType> int HashTable<ItemType>::dankHash(string key) const { int index = 0; for (int i = 0; i < key.length(); i++) { index += key[i] * key[i] * key[i]; } return index % size; } // the bad hashing function template<class ItemType> int HashTable<ItemType>::oofHash(string key) const { int index = 0; for (int i = 0; i < key.length(); i++) { index += key[i]; } return index % size; } // insert the item into the hash table template<class ItemType> bool HashTable<ItemType>::insert(ItemType item) { //if (isFull()) //return false; int index = dankHash(item->getModelNo()); // the good hasing function data[index].insertNode(item); count++; return true; } // search for an item from the hash table template<class ItemType> bool HashTable<ItemType>::search(const ItemType target, ItemType& returnItem, int compare(ItemType left, ItemType right)) { bool found = false; int index = dankHash(target->getModelNo());// good hashing function if (data[index].searchList(target, returnItem, compare)) { found = true; } return found; } // remove an item from the hash table template<class ItemType> bool HashTable<ItemType>::remove(const ItemType target, ItemType &returnItem, int compare(ItemType left, ItemType right)) { bool removed = false; int index = dankHash(target->getModelNo()); // good hashing function if (data[index].deleteNode(target, compare)) { removed = true; } count--; return removed; } // get the load factor of the hash table template<class ItemType> double HashTable<ItemType>::getLoadFactor() const { double loaded = 0; for (int i = 0; i < size; i++) { if (!data[i].isEmpty()) loaded++; } return loaded / size; } // this function prints the hash table vertially and linked list collisions horizontally template<class ItemType> void HashTable<ItemType>::printHashTable(void print(ItemType)) { for (int i = 0; i < size; i++) { cout << "|" << setw(2) << i << "| : "; data[i].traverseForward(print); } } // this function prints the unsorted data based on hash sequence template<class ItemType> void HashTable<ItemType>::printHashSeq(void print(ItemType)) { for (int i = 0; i < size; i++) { data[i].traverseHash(print); } } template<class ItemType> int HashTable<ItemType>::getCollisions() const { int noCol = 0; for (int i = 0; i < size; i++) { if (!data[i].isEmpty()) { noCol += data[i].getCount() - 1; } } return noCol; } #endif
/* MIT License Copyright (c) 2019 Vladislav Gusak Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Functions.hpp" #include <cmath> using namespace TSP; Matrix Common::createMatrix(const std::vector<Point>& points) { Matrix result(points.size()); for (size_t i = 0; i < points.size(); ++i) { result[i] = Row(points.size()); for (size_t j = 0; j < points.size(); ++j) { result[i][j] = distance(points[i], points[j]); } } return result; } double Common::distance(const Point& lhs, const Point& rhs) { return sqrt(pow(lhs.x - rhs.x , 2) + pow(lhs.y - rhs.y, 2)); }
#include "util.h" #include"Poco.h" void D_ADMINSETTING::Jsonize(JsonIO & json) { json ("ID",data.ID ) ("ROOTPATH",data.ROOTPATH) ("STATICPATH",data.STATICPATH) ("IMAGEPATH",data.IMAGEPATH) ("BACKUPPATH",data.BACKUPPATH) ("SERVERPORT",data.SERVERPORT) ("HOSTNAME",data.HOSTNAME) ; } D_ADMINSETTING D_ADMINSETTING::Create(Http& http){ S_ADMINSETTING pObj; // params container try{ // pObj.ID =atoi((String)http["ID"]); pObj.ROOTPATH=((String)http["ROOTPATH"]); pObj.STATICPATH=((String)http["STATICPATH"]); pObj.IMAGEPATH=((String)http["IMAGEPATH"]); pObj.BACKUPPATH=((String)http["BACKUPPATH"]); pObj.SERVERPORT=((String)http["SERVERPORT"]); pObj.HOSTNAME=((String)http["HOSTNAME"]); } catch(...) { Cout() << "Error D_ADMINSETTING::Create"; } return Create(pObj); } D_ADMINSETTING D_ADMINSETTING::Create(S_ADMINSETTING& pObj){ D_ADMINSETTING tObj = GetById(pObj.ID); if(tObj.data.ID < 0) { SQL * Insert( ADMINSETTING ) //(ID,pObj.ID) (ROOTPATH,pObj.ROOTPATH) (STATICPATH,pObj.STATICPATH) (IMAGEPATH,pObj.IMAGEPATH) (BACKUPPATH,pObj.BACKUPPATH) (SERVERPORT,pObj.SERVERPORT) (HOSTNAME,pObj.HOSTNAME) ; //---------------------------------------- Cout()<<"\nCreated ADMINSETTING:"<<tObj<<"\n"; } else { Cout()<<"\nUser Setting existed:"<<tObj.data.HOSTNAME<<"\n"; } return tObj; } /* update user information based on ID ex: http://127.0.0.1:8001/tis/api/user/update?ID=3&EMAIL=user23@simaget.com&PASSWORD=12345&FULLNAME=user2%20simaget&PHONE=987654321&DATEOFBIRTH=2000/03/01 */ D_ADMINSETTING D_ADMINSETTING::Edit(Http& http){ S_ADMINSETTING pObj; // params container try{ pObj.ID =atoi((String)http["ID"]); pObj.ROOTPATH=((String)http["ROOTPATH"]); pObj.STATICPATH=((String)http["STATICPATH"]); pObj.IMAGEPATH=((String)http["IMAGEPATH"]); pObj.BACKUPPATH=((String)http["BACKUPPATH"]); pObj.SERVERPORT=((String)http["SERVERPORT"]); pObj.HOSTNAME=((String)http["HOSTNAME"]); } catch(...) { Cout() << "Error D_ADMINSETTING::Update"; } return Edit(pObj); } D_ADMINSETTING D_ADMINSETTING::Edit(S_ADMINSETTING& pObj){ // check any same email registered D_ADMINSETTING tObj = GetById(pObj.ID); if(tObj.data.ID > 0) { SQL * Update( ADMINSETTING ) (ROOTPATH,pObj.ROOTPATH) (STATICPATH,pObj.STATICPATH) (IMAGEPATH,pObj.IMAGEPATH) (BACKUPPATH,pObj.BACKUPPATH) (SERVERPORT,pObj.SERVERPORT) (HOSTNAME,pObj.HOSTNAME) .Where( ID == pObj.ID); //---------------------------------------- tObj = GetById(pObj.ID); Cout()<<"\nUpdated Admin Setting:"<<tObj<<"\n"; } else { Cout()<<"\nAdmin Setting did not exist:"<<tObj.data.ID<<"\n"; tObj = Create(pObj); } return tObj; } void D_ADMINSETTING::Delete(Http& http){ // do not delete setting? } /* */ Vector<D_ADMINSETTING> D_ADMINSETTING::Retrieve(Http& http){ S_ADMINSETTING pObj; // params container PAGINATION pager(http); // extract pager try{ pObj.ID =atoi((String)http["ID"]); pObj.ROOTPATH=((String)http["ROOTPATH"]); pObj.STATICPATH=((String)http["STATICPATH"]); pObj.IMAGEPATH=((String)http["IMAGEPATH"]); pObj.BACKUPPATH=((String)http["BACKUPPATH"]); pObj.SERVERPORT=((String)http["SERVERPORT"]); pObj.HOSTNAME=((String)http["HOSTNAME"]); } catch(...) { Cout() << "Error get params"; } int row =0; //------------------------ SqlBool where; if(pObj.ID>0) where = ID == pObj.ID; if(pObj.ROOTPATH.IsEmpty()==false) where = where && ROOTPATH == pObj.ROOTPATH; if(pObj.STATICPATH.IsEmpty()==false) where = where && STATICPATH == pObj.STATICPATH; if(pObj.IMAGEPATH.IsEmpty()==false) where = where && IMAGEPATH == pObj.IMAGEPATH; if(pObj.BACKUPPATH.IsEmpty()==false) where = where && BACKUPPATH == pObj.BACKUPPATH; if(pObj.SERVERPORT.IsEmpty()==false) where = where && SERVERPORT == pObj.SERVERPORT; if(pObj.HOSTNAME.IsEmpty()==false) where = where && HOSTNAME == pObj.HOSTNAME; //------------------------ Cout()<<"\n"<<pObj<<"\n"; SQL * Select ( SqlAll() ).From ( ADMINSETTING ).Where(where).OrderBy ( ID ).Limit(pager.OFFSET, pager.SIZE); Vector<D_ADMINSETTING> vector; S_ADMINSETTING x; while ( SQL.Fetch ( x ) ){ vector.Add ( D_ADMINSETTING(x) ); row++; if(row >= pager.SIZE) break; } //-------------------------------------------------------- return vector; } String D_ADMINSETTING::RetrieveAsJson(Http& http){ return StoreAsJson(Retrieve(http),true); } /* Get Admin Setting by ID */ D_ADMINSETTING D_ADMINSETTING::GetById(int id){ D_ADMINSETTING rs; S_ADMINSETTING x; try{ SqlBool where; where = ID == id;// condition SQL * Select ( SqlAll() ).From ( ADMINSETTING ).Where(where).Limit(1);; while ( SQL.Fetch ( x ) ){ rs = D_ADMINSETTING(x); break; } } catch(...){ Cout() << "Error D_ADMINSETTING::Get(String id)"; } return rs; }
#pragma once #include "Headers.h" #include <vector> template <class Name, class Weight> class Graph { public: template <class Name> class Vertex { private: Name name; public: Vertex(Name name) { this->name = name; } Name getName() { return this->name; } }; template <class Name, class Weight> class Edge { private: Weight weight; Vertex<Name>* from; Vertex<Name>* to; public: Edge(Name first, Name second, Weight weight) { this->weight = weight; this->from = new Vertex<Name>(first); this->to = new Vertex<Name>(second); } Weight getWeight() { return this->weight; } pair<Vertex<Name>*, Vertex<Name>*> getVertex() { return make_pair(from, to); } }; public: Graph() { this->edgeList = new ListSequence<Edge<Name, Weight>*>(); this->vertexList = new ListSequence<Vertex<Name>*>(); } void addVertex(Name name) { bool containVertex = false; Vertex<Name>* toAdd = new Vertex<Name>(name); for (int i = 0; i < this->getVertexCount(); i++) { if (this->vertexList->Get(i)->getName() == name) { containVertex = true; break; } } if (!containVertex) { vertexList->Prepend(toAdd); } else { cout << "\n\tThis Vertex is already in Graph!"; } } void addEdge(Name first, Name second, Weight weight) { if (this->containsEdge(first, second) == -1) { Edge<Name, Weight>* edgeToAdd = new Edge<Name, Weight>(first, second, weight); this->edgeList->Prepend(edgeToAdd); int whichToAdd = 0; Vertex<Name>* firstToAdd = new Vertex<Name>(first); Vertex<Name>* secondToAdd = new Vertex<Name>(second); if (containsVertex(first) == -1) { vertexList->Prepend(firstToAdd); } if (containsVertex(second) == -1) { vertexList->Prepend(secondToAdd); } } else { cout << "\n\tThis Edge is already in Graph!"; } } int containsVertex(Name name) { for (int i = 0; i < this->getVertexCount(); ++i) { if (this->vertexList->Get(i)->getName() == name) { return i; } } return -1; } int containsEdge(Name first, Name second) { for (int i = 0; i < this->getEdgeCount(); ++i) { if (this->edgeList->Get(i)->getVertex().first->getName() == first && this->edgeList->Get(i)->getVertex().second->getName() == second) { return i; } } return -1; } void removeEdge(Name first, Name second) { if (containsEdge(first, second) != -1) { this->edgeList->RemoveAt(containsEdge(first, second)); } else { cout << "\n\tThere are no such Edge in Graph!\n"; } } // temp. unavailable void removeVertex(Name name) { if (containsVertex(name) != -1) { for (int i = 0; i < this->getEdgeCount(); ++i) { if (this->edgeList->Get(i)->getVertex().first->getName() == name) { removeEdge(this->edgeList->Get(i)->getVertex().first->getName(), this->edgeList->Get(i)->getVertex().second->getName()); i--; } if (this->edgeList->Get(i)->getVertex().second->getName() == name) { removeEdge(this->edgeList->Get(i)->getVertex().second->getName(), this->edgeList->Get(i)->getVertex().first->getName()); i--; } } this->vertexList->RemoveAt(this->containsVertex(name)); } else { cout << "\n\tThere are no such Vertex in Graph!\n"; } } void returnEdgeList() { for (int i = 0; i < getEdgeCount(); i++) { cout << "\t" << i + 1 << ". (" << this->edgeList->Get(i)->getVertex().first->getName() << " -> " << this->edgeList->Get(i)->getVertex().second->getName() << "): weight - " << this->edgeList->Get(i)->getWeight() << endl; } } void returnVertexList() { for (int i = 0; i < getVertexCount(); i++) { cout << "\t" << i + 1 << ". " << vertexList->Get(i)->getName() << endl; } } // Adjacency Matrix vector<vector<Weight>> getAdjMatrix() { vector<vector<Weight> > matrix(this->getVertexCount(), std::vector<Weight>(this->getVertexCount(), 0)); for (int i = 0; i < this->getVertexCount(); ++i) { for (int j = 0; j < this->getVertexCount(); ++j) { matrix[i][j] = 9999; } } for (int i = 0; i < this->getEdgeCount(); ++i) { int frst = 0; int scnd = 0; for (int j = 0; j < this->getVertexCount(); ++j) { if (this->edgeList->Get(i)->getVertex().first->getName() == vertexList->Get(j)->getName()) { frst = j; } if (this->edgeList->Get(i)->getVertex().second->getName() == vertexList->Get(j)->getName()) { scnd = j; } } if (matrix[frst][scnd] > this->edgeList->Get(i)->getWeight()) { matrix[frst][scnd] = this->edgeList->Get(i)->getWeight(); } } for (int i = 0; i < this->getVertexCount(); ++i) { matrix[i][i] = 0; } return matrix; } // Dijkstra void dijkstra(char StartVertex, char EndVertex) { int startnode; int endnode; for (int i = 0; i < this->getVertexCount(); i++) { if (this->vertexList->Get(i)->getName() == StartVertex) { startnode = i; } if (this->vertexList->Get(i)->getName() == EndVertex) { endnode = i; } } vector<vector<Weight>> G = this->getAdjMatrix(); vector<vector<Weight> > cost(this->getVertexCount(), std::vector<Weight>(this->getVertexCount(), 0)); vector<Weight> distance(this->getVertexCount()), pred(this->getVertexCount()); vector<Weight> visited(this->getVertexCount()); int count, mindistance, nextnode, i, j; for (i = 0; i < this->getVertexCount(); i++) for (j = 0; j < this->getVertexCount(); j++) if (G[i][j] == 0 || G[i][j] == INF) cost[i][j] = INF; else cost[i][j] = G[i][j]; for (i = 0; i < this->getVertexCount(); i++) { distance[i] = cost[startnode][i]; pred[i] = startnode; visited[i] = 0; } distance[startnode] = 0; visited[startnode] = 1; count = 1; while (count < this->getVertexCount() - 1) { mindistance = INF; for (i = 0; i < this->getVertexCount(); i++) if (distance[i] < mindistance && !visited[i]) { mindistance = distance[i]; nextnode = i; } visited[nextnode] = 1; for (i = 0; i < this->getVertexCount(); i++) if (!visited[i]) if (mindistance + cost[nextnode][i] < distance[i]) { distance[i] = mindistance + cost[nextnode][i]; pred[i] = nextnode; } count++; } int start = endnode; vector<pair<int, int>> path; for (i = 0; i < this->getVertexCount(); i++) if (i != startnode && i == endnode) { string graphAPI_V; if (distance[i] != INF) { cout << "\n\tDistance to Vertex '" << this->vertexList->Get(i)->getName() << "' = " << distance[i]; cout << "\n\tPath: \t'" << this->vertexList->Get(i)->getName(); j = i; do { graphAPI_V += this->vertexList->Get(j)->getName(); graphAPI_V += "[color=\"olivedrab1\",style=filled,fillcolor=\"olivedrab1\"] "; path.push_back(make_pair(j, pred[j])); j = pred[j]; cout << "' <- '" << this->vertexList->Get(j)->getName(); } while (j != startnode); cout << "'" << endl; graphAPI_V += this->vertexList->Get(j)->getName(); graphAPI_V += "[color=\"olivedrab1\",style=filled,fillcolor=\"olivedrab1\"] "; } else { cout << "\n\tYou can't get to Vertex '" << this->vertexList->Get(endnode)->getName() << "' from Vertex '" << this->vertexList->Get(startnode)->getName() << "'\n"; } string graphAPI, graphAPI_edge; j = i; if (this->getEdgeCount() > 0) { graphAPI = "https://chart.apis.google.com/chart?cht=gv&chl=digraph{bgcolor=\"skyblue\";"; for (int i = 0; i < this->getVertexCount(); i++) { graphAPI += this->vertexList->Get(i)->getName(); graphAPI += "[color=\"white\",style=filled,fillcolor=\"white\"] "; } graphAPI += graphAPI_V; string label = "[label=\""; int firstV, secondV; for (int k = 0; k < this->getEdgeCount(); k++) { graphAPI += this->edgeList->Get(k)->getVertex().first->getName(); graphAPI += "->"; graphAPI += this->edgeList->Get(k)->getVertex().second->getName(); graphAPI += label; graphAPI += to_string(this->edgeList->Get(k)->getWeight()); graphAPI += "\","; graphAPI_edge = "color=\"white\"] "; for (int f = 0; f < this->getVertexCount(); f++) { if (this->edgeList->Get(k)->getVertex().first->getName() == this->vertexList->Get(f)->getName()) { secondV = f; } if (this->edgeList->Get(k)->getVertex().second->getName() == this->vertexList->Get(f)->getName()) { firstV = f; } } for (int f = 0; f < path.size(); f++) { if (firstV == path[f].first && secondV == path[f].second) { graphAPI_edge = "color=\"olivedrab1\"] "; } } graphAPI += graphAPI_edge; } graphAPI += "}"; } else { graphAPI = "https://chart.apis.google.com/chart?cht=gv&chl=graph{bgcolor=\"skyblue\";"; graphAPI += graphAPI_V; for (int k = 0; k < this->getVertexCount(); k++) { graphAPI += this->vertexList->Get(k)->getName(); graphAPI += "[color=\"white\",style=filled,fillcolor=\"white\"] "; } graphAPI += "}"; } cout << "\n========================================================================================================================"; cout << "\n\tGraph Visualisation (shortest path): \n\n\n" << graphAPI << "\n\n\n\t(!JUST COPY AND PASTE AS URL!) \n"; cout << "========================================================================================================================"; } } void getSmallestPaths() { vector<vector<string>> mtrx(this->getVertexCount(), std::vector<string>(this->getVertexCount(), "")); for (int m = 0; m < this->getVertexCount(); m++) { int startnode = m; vector<vector<Weight>> G = this->getAdjMatrix(); vector<vector<Weight>> cost(this->getVertexCount(), std::vector<Weight>(this->getVertexCount(), 0)); vector<Weight> distance(this->getVertexCount()), pred(this->getVertexCount()); vector<Weight> visited(this->getVertexCount()); int count, mindistance, i, j; int nextnode = startnode; for (i = 0; i < this->getVertexCount(); i++) for (j = 0; j < this->getVertexCount(); j++) if (G[i][j] == 0 || G[i][j] == INF) cost[i][j] = INF; else cost[i][j] = G[i][j]; for (i = 0; i < this->getVertexCount(); i++) { distance[i] = cost[startnode][i]; pred[i] = startnode; visited[i] = 0; } distance[startnode] = 0; visited[startnode] = 1; count = 1; while (count < this->getVertexCount() - 1) { mindistance = INF; for (i = 0; i < this->getVertexCount(); i++) if (distance[i] < mindistance && !visited[i]) { mindistance = distance[i]; nextnode = i; } visited[nextnode] = 1; for (i = 0; i < this->getVertexCount(); i++) if (!visited[i]) if (mindistance + cost[nextnode][i] < distance[i]) { distance[i] = mindistance + cost[nextnode][i]; pred[i] = nextnode; } count++; } string out = ""; for (i = 0; i < this->getVertexCount(); i++) { out = ""; if (i != startnode) { if (distance[i] != INF) { out += this->vertexList->Get(i)->getName(); j = i; do { j = pred[j]; out += " <- "; out += this->vertexList->Get(j)->getName(); } while (j != startnode); } else { out += "No path"; } } else { out += "<----->"; } mtrx[startnode][i] = out; } } // OUTPUT cout << "\n\tMATRIX OF PATHS\n\n"; cout << " "; for (int i = 0; i < this->getVertexCount(); i++) { cout.width(18); cout << this->vertexList->Get(i)->getName(); } cout << endl << "\t"; for (int i = 0; i < this->getVertexCount(); i++) { cout.width(18); cout << "==================="; } cout << endl; for (int i = 0; i < this->getVertexCount(); i++) { cout << "\t" << this->vertexList->Get(i)->getName() << "|"; for (int j = 0; j < this->getVertexCount(); j++) { cout.width(18); cout << mtrx[i][j]; } cout << endl; } } void getGraphAPI() { string graphAPI, graphAPI_edge; ListSequence<Graph<char, int>::Edge<char, int>*>* G = this->edgeList; if (G->GetSize() > 0) { ListSequence<Graph<char, int>::Vertex<char>*>* E = this->vertexList; graphAPI = "https://chart.apis.google.com/chart?cht=gv&chl=digraph{bgcolor=\"skyblue\";"; for (int i = 0; i < this->getVertexCount(); i++) { graphAPI += E->Get(i)->getName(); graphAPI += "[color=\"white\",style=filled,fillcolor=\"white\"] "; } string label = "[color=\"white\",label=\""; for (int i = 0; i < this->getEdgeCount(); i++) { graphAPI += G->Get(i)->getVertex().first->getName(); graphAPI += "->"; graphAPI += G->Get(i)->getVertex().second->getName(); graphAPI += label; graphAPI += to_string(G->Get(i)->getWeight()); graphAPI += "\"] "; } graphAPI += "}"; } else { ListSequence<Graph<char, int>::Vertex<char>*>* E = this->getVetex(); graphAPI = "https://chart.apis.google.com/chart?cht=gv&chl=graph{bgcolor=\"skyblue\";"; for (int i = 0; i < this->getVertexCount(); i++) { graphAPI += E->Get(i)->getName(); graphAPI += "[color=\"white\",style=filled,fillcolor=\"white\"] "; } graphAPI += "}"; } cout << "\n========================================================================================================================"; cout << "\n\n\tGraph Visualisation: \n\n\n" << graphAPI << "\n\n\n\t(!JUST COPY AND PASTE AS URL!) \n"; cout << "========================================================================================================================"; } ListSequence<Edge<Name, Weight>*>* getEdges() { return this->edgeList; } ListSequence<Vertex<Name>*>* getVetex() { return this->vertexList; } int getEdgeCount() { return this->edgeList->GetSize(); } int getVertexCount() { return this->vertexList->GetSize(); } private: const int INF = 9999; ListSequence<Vertex<Name>*>* vertexList; ListSequence<Edge<Name, Weight>*>* edgeList; };
#include <opencv2/opencv.hpp> #include "Contour.hpp" #include "ContourDetector.hpp" #include "HSVImage.hpp" ContourDetector::Params::Params() { filter_by_hue = false; min_hue = 0; max_hue = 255; filter_by_saturation = false; min_saturation = 0; max_saturation = 255; filter_by_value = false; min_value = 0; max_value = 255; filter_by_area = false; min_area = 0; max_area = 1e6; filter_with_canny = true; min_canny = 0; max_canny = 50; filter_with_blur = true; } ContourDetector::ContourDetector(const ContourDetector:: Params & parameters):params(parameters) { } std::vector < Contour > ContourDetector::detect(cv::Mat image) { HSVImage hsv_image = HSVImage(image); cv::Mat hue_thresholded_lower; cv::Mat hue_thresholded_upper; cv::Mat hue_thresholded; cv::Mat saturation_thresholded_lower; cv::Mat saturation_thresholded_upper; cv::Mat saturation_thresholded; cv::Mat value_thresholded_lower; cv::Mat value_thresholded_upper; cv::Mat value_thresholded; cv::Mat threshold_out; cv::Mat blur_out; cv::Mat canny_out; cv::Mat processed_img; cv::threshold(hsv_image.hue, hue_thresholded_lower, params.min_hue, 255, CV_THRESH_BINARY); cv::threshold(hsv_image.hue, hue_thresholded_upper, params.max_hue, 255, CV_THRESH_BINARY_INV); hue_thresholded = hue_thresholded_lower & hue_thresholded_upper; cv::threshold(hsv_image.saturation, saturation_thresholded_lower, params.min_saturation, 255, CV_THRESH_BINARY); cv::threshold(hsv_image.saturation, saturation_thresholded_upper, params.max_saturation, 255, CV_THRESH_BINARY_INV); saturation_thresholded = saturation_thresholded_lower & saturation_thresholded_upper; cv::threshold(hsv_image.value, value_thresholded_lower, params.min_value, 255, CV_THRESH_BINARY); cv::threshold(hsv_image.value, value_thresholded_upper, params.max_value, 255, CV_THRESH_BINARY_INV); value_thresholded = value_thresholded_lower & value_thresholded_upper; threshold_out = hue_thresholded.clone(); if (params.filter_by_saturation) threshold_out = threshold_out & saturation_thresholded; if (params.filter_by_value) threshold_out = threshold_out & value_thresholded; if (params.filter_with_blur) { cv::Mat blur_tmp; cv::pyrDown(threshold_out, blur_tmp, cv::Size(threshold_out.cols / 2, threshold_out.rows / 2)); cv::pyrUp(blur_tmp, blur_out, threshold_out.size()); } else blur_out = threshold_out.clone(); if (params.filter_with_canny) { cv::Canny(blur_out, canny_out, params.min_canny, params.max_canny, 5); cv::dilate(canny_out, canny_out, cv::Mat(), cv::Point(-1, -1)); } else canny_out = blur_out.clone(); std::vector < std::vector < cv::Point > >all_contours_raw; cv::findContours(canny_out, all_contours_raw, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE); std::vector < Contour > all_contours; for (uint i = 0; i < all_contours_raw.size(); i++) all_contours.push_back(Contour(all_contours_raw.at(i))); std::vector < Contour > area_filtered_contours; if (params.filter_by_area) { for (uint i = 0; i < all_contours.size(); i++) { if (all_contours.at(i).get_area() > params.min_area && area_filtered_contours.at(i).get_area() < params.max_area) area_filtered_contours.push_back(all_contours. at(i)); } } else area_filtered_contours = all_contours; return area_filtered_contours; }
#include <QString> #include <iostream> namespace { class Main { public: Main() { } ~Main() { } private: }; } int main() { auto msg = QString("Hello, world"); std::cout << msg.toStdString() << std::endl; return 0; }
/* * Particle.h * * Created on: Jun 7, 2015 * Author: colman */ #include "robot.h" #include "Globals.h" #include "pngUtil.h" #ifndef PARTICLE_H_ #define PARTICLE_H_ class Particle { private: double _x; double _y; double _yaw; double _belief; public: Particle(double x, double y, double yaw, double belief); double getX(); double getY(); double getYaw(); double getBelief(); virtual ~Particle(); double UpdateParticle(double dx, double dy, double dyaw, LaserProxy* lp, pngUtil* map); Particle* CreateNewParticle(); double probByMov(double dx, double dy, double dyaw); double probByScan(LaserProxy* lp, pngUtil* map); }; #endif /* PARTICLE_H_ */
#include<bits/stdc++.h> using namespace std; void reverseArray(char arr[], int start, int end){ while(start < end){ swap(arr[start], arr[end]); start++; end--; } } void printArray(char arr[], int size){ for(int i=0; i<size; i++){ cout<<arr[i]<<" "; } cout<<endl; } bool isAlphabet(char x){ return ( (x >='A' && x <='Z') || (x >='a' && x <='z') ); } int main(){ char a[] = "Ab,c,de!$"; int size = sizeof(a)/sizeof(a[0]); char temp[size]; int j = 0; for(int i=0; i< size; i++){ if(isAlphabet(a[i])){ temp[j++] = a[i]; } } temp[j] = '\0'; int size_temp = j; //cout<<temp<<endl; printArray(a,size); reverseArray(temp,0,size_temp-1); //cout<<temp<<endl; j=0; for(int i=0; i<size; i++){ if(isAlphabet(a[i])){ a[i]=temp[j]; j++; } } printArray(a,size); return 0; }
#ifndef NAVMESH_H #define NAVMESH_H #include "dllmacro.h" #include "shapes.h" #include "mapobject.h" #include "pathfinder.h" #include "agentbuilder.h" namespace POICS{ enum class CornerSmoothing {NONE, PORTAL, POLYOFFSET}; /* Hertel-Mehlhorn convex polygon partition based navigation mesh */ class POICS_API HMNavMesh { private: std::vector<Polygon> corridors; PathFinder& pathfinder; bool trianglenavmesh, makelane; CornerSmoothing smoothing; public: HMNavMesh(PathFinder& _pathfinder, bool _triangle, bool _makelane, CornerSmoothing _smoothing) : pathfinder(_pathfinder), trianglenavmesh(_triangle), makelane(_makelane), smoothing(_smoothing){ pathfinder.setCorridors(corridors); } ~HMNavMesh(){} void build(MapArea& maparea); std::vector<Polygon>& getCorridors(){ return corridors;} void getPath(const Point& start, int startCorridor, const Point& end, int endCorridor, double agentWidth, std::vector<Point>& result_path) const; double getDistance(const Point& start, int startCorridor, const Point& end, int endCorridor, double agentWidth) const; int findCorridor(const Point& p); void calculateDensity(AgentList& agents, double radius); }; } #endif
/**************************************************************************** ** ** Copyright (C) 2009 Du Hui. ** ****************************************************************************/ #ifndef COMPORTDLG_H #define COMPORTDLG_H #include <QtGui/QDialog> class QSerialComm; namespace Ui { class comPortDlg; } class comPortDlg : public QDialog { Q_OBJECT public: comPortDlg(QWidget *parent = 0); ~comPortDlg(); void accept(); void reject(); QString selectedCommPorts() { return m_selectedCommPorts; } protected: void changeEvent(QEvent *e); private: int listAvailableComms(); QSerialComm * m_Comm; QString m_selectedCommPorts; Ui::comPortDlg *m_ui; }; #endif // COMPORTDLG_H
#include <typeinfo> #include <iostream> using namespace std; template <typename Type> class Node { public: Type data; Node<Type> *next = NULL; }; template <typename Type> class LinkedList { public: // Constructor LinkedList(); // Destructor ~LinkedList(); // Get the value located at index Type Get(const int index); // Add val at head void AddAtHead(const Type& val); // Add val at index void AddAtIndex(const int index, const Type& val); // Delete an element located at index void DeleteAtIndex(const int index); // Delete val in linked list void DeleteValue(const Type& val); // Move the first element of val to head void MoveToHead(const Type& val); // Rotate the linked list right by steps times void Rotate(const int steps); // Reduce value that repeats multiple times void Reduce(); // reverse at every k number of nodes at a time void K_Reverse(const int k); // rearrage nodes to zig-zag manner void ZigZagRearrange(); // Return the number of elements in the linked list int Size(); // Delete all elements from the linked list void CleanUp(); // Print the list void Print(); private: Node<Type> *head; }; /* * Implementation */ template <typename Type> LinkedList<Type>::LinkedList() : head(NULL) {} template <typename Type> LinkedList<Type>::~LinkedList() { CleanUp(); } template <typename Type> Type LinkedList<Type>::Get(const int index) { Node<Type> *GetNode = head; if(index < 0 || index > Size()-1) return -1; else { for(int a = 0; a < index; a++) GetNode = GetNode->next; } return GetNode->data; } template <typename Type> void LinkedList<Type>::AddAtHead(const Type& val) { Node<Type> *AddNode = new Node<Type>; if(head == NULL) { AddNode->data = val; head = AddNode; AddNode->next = NULL; } else { AddNode->data = val; AddNode->next = head; head = AddNode; } } template <typename Type> void LinkedList<Type>::AddAtIndex(const int index, const Type& val) { Node<Type> *Letsgo = head; Node<Type> *InsertNode = new Node<Type>; int sizes = Size(); if(index < 0 || index > sizes) return; else if(index == 0) AddAtHead(val); else if(index == sizes) { for(int a = 0; a < sizes - 1; a++) Letsgo = Letsgo->next; InsertNode->data = val; Letsgo->next = InsertNode; InsertNode->next = NULL; } else { for(int a = 0; a < index - 1; a++) Letsgo = Letsgo->next; InsertNode->data = val; InsertNode->next = Letsgo->next; Letsgo->next = InsertNode; } } template <typename Type> void LinkedList<Type>::DeleteAtIndex(const int index) { Node<Type> *DeleteNode = head; int sizes = Size(); if(index < 0 || index > sizes-1) return; else if(index == 0) { head = DeleteNode->next; } else if(index == sizes-1) { for(int a = 0; a < sizes-2; a++) DeleteNode = DeleteNode->next; DeleteNode->next = NULL; } else { for(int a = 0; a < index-1; a++) DeleteNode = DeleteNode->next; DeleteNode->next = DeleteNode->next->next; } } template <typename Type> void LinkedList<Type>::DeleteValue(const Type& val) { Node<Type> *DelNode; int Dval = 0; for(DelNode = head; DelNode != NULL; DelNode = DelNode->next) { if(DelNode->data == val) { DeleteAtIndex(Dval); break; } Dval++; } } template <typename Type> void LinkedList<Type>::MoveToHead(const Type& val) { Node<Type> *MoveNode; int Mval = 0; for(MoveNode = head; MoveNode != NULL; MoveNode = MoveNode->next) { if(MoveNode->data == val) { DeleteAtIndex(Mval); AddAtHead(val); break; } Mval++; } } template <typename Type> void LinkedList<Type>::Rotate(const int steps) { Node<Type> *RotNode = head; int sizes = Size(); int headval; if(steps < 0) return; for(int a = 0; a < steps; a++) { headval = Get(sizes-1); DeleteAtIndex(sizes-1); AddAtHead(headval); } } template <typename Type> void LinkedList<Type>::Reduce() { Node<Type> *ReNode1 = head; Node<Type> *ReNode2; int sizes = Size(); int check; for(int a = 0; a < sizes; a++) { check = 0; ReNode2 = head; for(int b = 0; b < a; b++) { if(ReNode2->data == ReNode1->data) { ReNode1 = ReNode1->next; check = 1; sizes = sizes-1; DeleteAtIndex(a); a--; break; } ReNode2 = ReNode2->next; } if(check != 1) ReNode1 = ReNode1->next; } } template <typename Type> void LinkedList<Type>::K_Reverse(const int k) { Node<Type> *point = head; Node<Type> *Rev; Node<Type> *temp; int sizes = Size(); for(int a = 0; a < sizes/k; a++) { Rev = point; for(int b = 0; b < k; b++) Rev = Rev->next; if(a == sizes/k - 1) { for(int c = 0; c < k; c++) { temp = Rev; Rev = point; point = point->next; Rev->next = temp; } if(a == 0) head = Rev; } else { for(int d = 0; d < k; d++) { temp = Rev; Rev = point; point = point->next; if(d == 0) { for(int e = 0; e < k-1; e++) temp = temp->next; Rev->next = temp; } else Rev->next = temp; } if(a == 0) head = Rev; } } } template <typename Type> void LinkedList<Type>::ZigZagRearrange() { int sizes = Size(); for(int a = 0; a < (sizes/2)-1; a++) { int k = Get(sizes/2 + a); DeleteAtIndex(sizes/2 + a); AddAtIndex(2*a+1, k); } } template <typename Type> int LinkedList<Type>::Size() { Node<Type> *counter; int count = 0; for(counter = head; counter != NULL; counter = counter->next) count++; return count; } template <typename Type> void LinkedList<Type>::CleanUp() { int sizes = Size(); for(int a = 0; a < sizes; a++) DeleteAtIndex(0); } template <typename Type> void LinkedList<Type>::Print() { Node<Type> *printer = head; int sizes = Size(); cout << "("; for(int a = 0; a < sizes; a++) { cout << printer->data; if(a != sizes-1) cout << ","; printer = printer->next; } cout << ")" << endl; } int main() { LinkedList<int> LL; for(int i = 0; i < 10; i++) LL.AddAtHead(i); LL.Print(); // (9,8,7,6,5,4,3,2,1,0) cout << LL.Get(2) << endl; //7 LL.AddAtIndex(1,8); LL.Print(); // (9,8,8,7,6,5,4,3,2,1,0) LL.DeleteAtIndex(3); LL.Print(); // (9,8,8,6,5,4,3,2,1,0) LL.DeleteValue(9); LL.Print(); // (8,8,6,5,4,3,2,1,0) LL.MoveToHead(2); LL.Print(); // (2,8,8,6,5,4,3,1,0) LL.Rotate(2); LL.Print(); // (1,0,2,8,8,6,5,4,3) LL.AddAtHead(4); LL.Print(); // (4,1,0,2,8,8,6,5,4,3) LL.Reduce(); LL.Print(); // (4,1,0,2,8,6,5,3) LL.AddAtIndex(7,10); LL.Print(); // (4,1,0,2,8,6,5,10,3) LL.ZigZagRearrange(); LL.Print(); // (4,8,1,6,0,5,2,10,3) cout << LL.Size() << endl; // 9 LL.K_Reverse(3); LL.Print(); // (1,8,4,5,0,6,3,10,2) cout << LL.Size() << endl; // 9 LL.CleanUp(); cout << LL.Size() << endl; // 0 }
#ifndef QPROMODIALOG_H #define QPROMODIALOG_H #include <QWidget> #include <QLabel> #include <QLineEdit> #include <QVBoxLayout> #include <QPushButton> class QPromoDialog : public QWidget { Q_OBJECT private: std::string cf; QLineEdit* insert_cf; public: explicit QPromoDialog(QWidget *parent = nullptr); signals: void emitPromo(const std::string&); public slots: void slotPromo(); }; #endif // QPROMODIALOG_H
//========================================================================== // WATCHINSPECTOR.CC - part of // // OMNeT++/OMNEST // Discrete System Simulation in C++ // // Implementation of // inspectors // //========================================================================== /*--------------------------------------------------------------* Copyright (C) 1992-2008 Andras Varga Copyright (C) 2006-2008 OpenSim Ltd. This file is distributed WITHOUT ANY WARRANTY. See the file `license' for details on this and other legal matters. *--------------------------------------------------------------*/ #include <string.h> #include <math.h> #include "tkenv.h" #include "tklib.h" #include "inspectorfactory.h" #include "watchinspector.h" #include "cwatch.h" #include "cstlwatch.h" NAMESPACE_BEGIN void _dummy_for_watchinspector() {} class WatchInspectorFactory : public InspectorFactory { public: WatchInspectorFactory(const char *name) : InspectorFactory(name) {} bool supportsObject(cObject *obj) { // Return true if it's a watch for a simple type (int, double, string etc). // For structures, we prefer the normal GenericObjectInspector. // Currently we're prepared for cStdVectorWatcherBase. return dynamic_cast<cWatchBase *>(obj) && !dynamic_cast<cStdVectorWatcherBase *>(obj); } int getInspectorType() {return INSP_OBJECT;} double getQualityAsDefault(cObject *object) {return 2.0;} Inspector *createInspector() {return new WatchInspector(this);} }; Register_InspectorFactory(WatchInspectorFactory); WatchInspector::WatchInspector(InspectorFactory *f) : Inspector(f) { } void WatchInspector::createWindow(const char *window, const char *geometry) { Inspector::createWindow(window, geometry); CHK(Tcl_VarEval(interp, "createWatchInspector ", windowName, " ", TclQuotedString(geometry).get(), NULL )); } void WatchInspector::useWindow(const char *window) { Inspector::useWindow(window); } void WatchInspector::refresh() { Inspector::refresh(); cWatchBase *watch = static_cast<cWatchBase *>(object); setLabel(".main.name.l", watch ? (std::string(watch->getClassName())+" "+watch->getName()).c_str() : "n/a"); setEntry(".main.name.e", watch ? watch->info().c_str() : "n/a"); } void WatchInspector::commit() { cWatchBase *watch = static_cast<cWatchBase *>(object); const char *s = getEntry(".main.name.e"); if (watch->supportsAssignment()) watch->assign(s); else CHK(Tcl_VarEval(interp,"messagebox {Warning} {This inspector doesn't support changing the value.} warning ok", NULL)); Inspector::commit(); // must be there after all changes } NAMESPACE_END
#ifndef BONEINFO_H #define BONEINFO_H #include "Bone.h" #include <map> namespace kyrbos { class ENGINE_API BoneInfo { public: // Tiene que ser todo publico, ya que es solo una estructura con data! Bone* m_pkBone; D3DXMATRIX offSetMatrix; std::vector<unsigned int> m_mVIndex; std::vector<float> m_mVWeights; BoneInfo(); void SetOffSetMatrix(float a1, float a2, float a3, float a4, float b1, float b2, float b3, float b4, float c1, float c2, float c3, float c4, float d1, float d2, float d3, float d4); void AddVertexWeight(unsigned int index, float weight); void SetBone(Bone* pkBone); }; } #endif
/* main.cpp Author: Izaak Coleman */ #include <iostream> #include <iomanip> #include <vector> #include <string> #include "boost/program_options.hpp" #include <sys/stat.h> // benchmarking #include <sys/resource.h> #include <chrono> #include "SNVIdentifier.h" #include "GenomeMapper.h" #include "gsa.h" using namespace std; // Return values static const int ERROR_IN_COMMAND_LINE = 1; static const int SUCCESS = 0; static const int ERROR_UNHANDLED_EXCEPTION = 2; static const int CALIB = 4; static const int BASE33_CONVERSION = 33; static const int PHRED_LBOUND = 0; static const int PHRED_UBOUND = 42; // Default option values static const int PRI_MSS = 2; static const int AUX_MSS = 4; static const int MAX_SNPS = 5; static const int ECONT = 0; static const int MIN_PHRED_QUAL = 35; static const int MIN_MAPQ = 0; static const double ALLELE_FREQ_OF_ERR = 0.1; static const string OUTPUT_PATH = "./"; static const string CHR = ""; static const string EMFIL = "on"; int main(int argc, char** argv) { try { namespace po = boost::program_options; po::options_description desc("Options"); desc.add_options() ("help", "Print options description.") ("primary_mss", po::value<int>()->default_value(PRI_MSS), "Minimum suffix size of sections extracted from the primary " "suffix array. Integer ranged [1, maxint].\n") ("emfilter", po::value<string>()->default_value(EMFIL), "Apply emfilter to input tumour data (on|off).\n") ("auxiliary_mss", po::value<int>()->default_value(AUX_MSS), "Minimum suffix size of sections extracted from the auxiliary suffix array. " "Integer ranged [1, maxint].\n") ("min_phred,h", po::value<int>()->default_value(MIN_PHRED_QUAL), "Minimum phred score of a base contributing to a phred-filtered " "consensus sequence Base-33 phred score. Integer ranged [0,42]\n") ("max_allele_freq_of_error,f", po::value<double>()->default_value(ALLELE_FREQ_OF_ERR), "Used in masking filter's indicator function. All candidate variants with an allele frequency equal to or below " "this value will be considered sequencing errors and discarded. " "Real number ranged [0,1]\n") ("max_SNPs,l", po::value<int>()->default_value(MAX_SNPS), "Max number of SNPs in consensus sequence allowed before multi-locus " "filter will be triggered, resulting in the consensus pair being " "discarded. Integer [0, maxint]. \n") ("min_mapq,q", po::value<int>()->default_value(MIN_MAPQ), "Aligned control consensus sequences with a Bowtie2 given MAPQ score " "below this value will be discarded. Integer ranged [0,42] \n.") ("expected_contamination,e", po::value<double>()->default_value(ECONT), "Proportion of sequencing reads within the tumour dataset expected to derive from healthy tissue. " "Real number ranged [0,1].\n") ("chromosome,c", po::value<string>()->default_value(CHR), "For targeted sequencing data analysis. If specified, GeDi will filter " "out all SNV calls that do not reside within the specified chromosome. " "Note that the passed argument should exactly match the fasta header of " "the desired chromosome within the reference genome used for alignment. " "If not specified, GeDi will report all SNVs called regardless of the " "chromosome they reside in. (string). \n") ("expected_coverage,v", po::value<int>()->required(), "Expected coverage of input dataset. Integer range [0,maxint]. Required.\n") ("n_threads,t", po::value<int>()->required(), "Number of threads GeDi will execute with during parallel sections. Integer. Required ranged [1,maxint].\n") ("input_files,i", po::value<string>()->required(), "Path and file name of the users .file_list. Required.\n") ("bt2-idx,x", po::value<string>()->required(), "Basename of Bowtie2 reference genome index. Specified value " "should be identical to Bowtie2's -x option if running Bowtie2 " "from GeDi. Required.\n") ("output_basename,o", po::value<string>()->required(), "Basename for SNV_results, fastq.gz, sam files output by GeDi. Required.\n"); po::variables_map vm; try { po::store(po::parse_command_line(argc, argv, desc),vm); if (vm.count("help")) { cout.precision(1); std::cout << "***********************************************************************" << std::endl << "* Generalized Suffix Array based Direct Comparison (GeDi) SNV caller. *" << std::endl << "***********************************************************************" << std::endl << std::endl << std::endl; std::cout << "usage: [optional parameters] -v coverage -t n_threads -i fastq_list -x bowtie_index -o output_file_basename" << std::endl << std::endl << "Default values passed to parameters are in parentheses." << std::endl; std::cout << desc << std::endl; return SUCCESS; } // Throw if required options are missing. po::notify(vm); // Check supplied options are valid. if (vm["min_phred"].as<int>() < PHRED_LBOUND || vm["min_phred"].as<int>() > PHRED_UBOUND) { std::cerr << "ERROR: " << "--min_phred must take integer value in range [0-42]." << std::endl << std::endl << "Read --help for required and default parameters." << std::endl << "Program terminating." << std::endl; return ERROR_IN_COMMAND_LINE; } if (vm["emfilter"].as<string>() != "on" && vm["emfilter"].as<string>() != "off") { std::cerr << "ERROR: " << "--emfilter must take value 'on' or 'off'" << std::endl << std::endl << "Read --help for required and default parameters." << std::endl << "Program terminating." << std::endl; return ERROR_IN_COMMAND_LINE; } if (vm["primary_mss"].as<int>() < 1) { std::cerr << "ERROR: " << "--primary_mss must be at least 1." << std::endl << std::endl << "Read --help for required and default parameters." << std::endl << "Program terminating." << std::endl; return ERROR_IN_COMMAND_LINE; } if (vm["auxiliary_mss"].as<int>() < 1) { std::cerr << "ERROR: " << "--auxiliary_mss must be at least 1." << std::endl << std::endl << "Read --help for required and default parameters." << std::endl << "Program terminating." << std::endl; return ERROR_IN_COMMAND_LINE; } if (vm["max_allele_freq_of_error"].as<double>() < 0 || vm["max_allele_freq_of_error"].as<double>() > 1) { std::cerr << "ERROR: " << "--max_allele_freq_of_error must a real number in range [0-1]." << std::endl << std::endl << "Read --help for required and default parameters." << std::endl << "Program terminating." << std::endl; return ERROR_IN_COMMAND_LINE; } if (vm["expected_contamination"].as<double>() < 0 || vm["expected_contamination"].as<double>() > 1) { std::cerr << "ERROR: " << "--expected_contamination must a real number in range [0-1]." << std::endl << std::endl << "Read --help for required and default parameters." << std::endl << "Program terminating." << std::endl; return ERROR_IN_COMMAND_LINE; } if (vm["expected_coverage"].as<int>() < 0) { std::cerr << "ERROR: " << "--expected_coverage must be at least 0." << std::endl << std::endl << "Read --help for required and default parameters." << std::endl << "Program terminating." << std::endl; return ERROR_IN_COMMAND_LINE; } if (vm["n_threads"].as<int>() < 1) { std::cerr << "ERROR: " << "--n_threads must be at least 1." << std::endl << std::endl << "Read --help for required and default parameters." << std::endl << "Program terminating." << std::endl; return ERROR_IN_COMMAND_LINE; } if (vm["max_SNPs"].as<int>() < 0) { std::cerr << "ERROR: " << "--max_SNPs must be at least 0." << std::endl << std::endl << "Read --help for required and default parameters." << std::endl << "Program terminating." << std::endl; return ERROR_IN_COMMAND_LINE; } if (vm["min_mapq"].as<int>() < PHRED_LBOUND || vm["min_mapq"].as<int>() > PHRED_UBOUND) { std::cerr << "ERROR: " << "--min_mapq must be an integer value in range [0-42]." << std::endl << std::endl << "Read --help for required and default parameters." << std::endl << "Program terminating." << std::endl; return ERROR_IN_COMMAND_LINE; } struct stat info_p, info_i; string output_dir = get_dir_from_filename(vm["output_basename"].as<string>()); if (stat(output_dir.c_str(), &info_p) != 0) { std::cerr << "ERROR: " << "Cannot access " << output_dir << std::endl << "Please check path is correct." << std::endl << "Program terminating." << std::endl; return ERROR_IN_COMMAND_LINE; } else if (!(info_p.st_mode & S_IFDIR)) { std::cerr << "ERROR: " << vm["output_dir"].as<string>() << " cannot be found. Please check directory exists." << std::endl << "before running GeDi." << std::endl << "Program terminating." << std::endl; return ERROR_IN_COMMAND_LINE; } if (stat(vm["input_files"].as<string>().c_str(), &info_i) != 0) { std::cerr << "ERROR: " << "Cannot access " << vm["input_files"].as<string>() << std::endl << "Please check filename is correct." << std::endl << "Program terminating." << std::endl; return ERROR_IN_COMMAND_LINE; } else if (!(info_p.st_mode & S_IFDIR)) { std::cerr << "ERROR: " << vm["input_files"].as<string>() << " cannot be found. Please check filename is correct." << std::endl << "Program terminating." << std::endl; return ERROR_IN_COMMAND_LINE; } } catch(po::error& e) { std::cerr << "ERROR: " << e.what() << std::endl << std::endl; std::cerr << "Read --help for required and default parameters." << std::endl << "Program terminating." << std::endl; return ERROR_IN_COMMAND_LINE; } // Run GeDi struct rusage gedi_rss; getrusage(RUSAGE_SELF, &gedi_rss); auto gedi_runtime_start = std::chrono::steady_clock::now(); cout << "Running GeDi with " << vm["n_threads"].as<int>() << " threads." << endl; GSA gsa(vm["input_files"].as<string>(), vm["n_threads"].as<int>(), vm["bt2-idx"].as<string>(), vm["emfilter"].as<string>()); SNVIdentifier snvId(gsa, vm["output_basename"].as<string>(), vm["min_phred"].as<int>()+BASE33_CONVERSION, vm["primary_mss"].as<int>(), vm["auxiliary_mss"].as<int>(), vm["expected_coverage"].as<int>()*CALIB, vm["n_threads"].as<int>(), vm["max_SNPs"].as<int>(), vm["expected_contamination"].as<double>(), vm["max_allele_freq_of_error"].as<double>()); GenomeMapper mapper(snvId, vm["output_basename"].as<string>(), vm["chromosome"].as<string>(), vm["bt2-idx"].as<string>(), vm["min_mapq"].as<int>()); auto gedi_runtime_end = std::chrono::steady_clock::now(); double gedi_runtime = std::chrono::duration_cast<std::chrono::milliseconds>(gedi_runtime_end - gedi_runtime_start).count(); gedi_runtime = gedi_runtime / 60000; // minutes getrusage(RUSAGE_SELF, &gedi_rss); cout << std::fixed; cout << std::setprecision(2); cout << endl << endl; cout << "GeDi terminated successfully." << endl << "Runtime (mins): " << gedi_runtime << endl << "Memory usage (bytes) : " << gedi_rss.ru_maxrss << endl; return SUCCESS; } catch(std::exception& e) { std::cerr << "Unhandled exception reached main: " << e.what() << ", application will now exit" << std::endl; return ERROR_UNHANDLED_EXCEPTION; } return SUCCESS; }
//************************************************************************** //** //** See jlquake.txt for copyright info. //** //** This program is free software; you can redistribute it and/or //** modify it under the terms of the GNU General Public License //** as published by the Free Software Foundation; either version 3 //** of the License, or (at your option) any later version. //** //** This program is distributed in the hope that it will be useful, //** but WITHOUT ANY WARRANTY; without even the implied warranty of //** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //** included (gnu.txt) GNU General Public License for more details. //** //************************************************************************** #include "local.h" #include "../../client_main.h" #define MAX_PROJECTILES_Q1 32 struct q1projectile_t { int modelindex; vec3_t origin; vec3_t angles; }; static q1projectile_t clq1_projectiles[ MAX_PROJECTILES_Q1 ]; static int clq1_num_projectiles; int clq1_spikeindex; void CLQ1_ClearProjectiles() { clq1_num_projectiles = 0; } // Nails are passed as efficient temporary entities void CLQW_ParseNails( QMsg& message ) { int c = message.ReadByte(); for ( int i = 0; i < c; i++ ) { byte bits[ 6 ]; for ( int j = 0; j < 6; j++ ) { bits[ j ] = message.ReadByte(); } if ( clq1_num_projectiles == MAX_PROJECTILES_Q1 ) { continue; } q1projectile_t* pr = &clq1_projectiles[ clq1_num_projectiles ]; clq1_num_projectiles++; pr->modelindex = clq1_spikeindex; pr->origin[ 0 ] = ( ( bits[ 0 ] + ( ( bits[ 1 ] & 15 ) << 8 ) ) << 1 ) - 4096; pr->origin[ 1 ] = ( ( ( bits[ 1 ] >> 4 ) + ( bits[ 2 ] << 4 ) ) << 1 ) - 4096; pr->origin[ 2 ] = ( ( bits[ 3 ] + ( ( bits[ 4 ] & 15 ) << 8 ) ) << 1 ) - 4096; pr->angles[ 0 ] = 360 * ( bits[ 4 ] >> 4 ) / 16; pr->angles[ 1 ] = 360 * bits[ 5 ] / 256; } } void CLQ1_LinkProjectiles() { q1projectile_t* pr = clq1_projectiles; for ( int i = 0; i < clq1_num_projectiles; i++, pr++ ) { // grab an entity to fill in if ( pr->modelindex < 1 ) { continue; } refEntity_t ent; Com_Memset( &ent, 0, sizeof ( ent ) ); ent.reType = RT_MODEL; ent.hModel = cl.model_draw[ pr->modelindex ]; VectorCopy( pr->origin, ent.origin ); CLQ1_SetRefEntAxis( &ent, pr->angles ); R_AddRefEntityToScene( &ent ); } }
#ifdef CQUEUE_H_ #define CQUEUE_H_ #include <iostream> using namespace std; class CQueue { private: }; #endif
#pragma once #include <limits> #include <dtl/dtl.hpp> //===----------------------------------------------------------------------===// // Third party dependency: 'libdivide' by ridiculous_fish // Usable under the terms in either zlib or Boost license. // See 'thirdparty/libdivide/LICENSE.txt' for details. //===----------------------------------------------------------------------===// // Note: libdivide is used to find magic numbers #include "thirdparty/libdivide/libdivide.h" namespace dtl { static constexpr uint32_t max_divisor_u32 = std::numeric_limits<uint32_t>::max() - 2; struct fast_divisor_u32_t { uint32_t magic; uint32_t shift_amount; uint32_t divisor; }; /// Finds a magic number (which is not a power of two) to divide by n. /// Thereby, only magic number are considered that do not require an 'addition' step. (cheap) static fast_divisor_u32_t next_cheap_magic(uint32_t n) { n = std::max(n, 2u); const uint32_t d_max = max_divisor_u32; assert(n <= d_max); // TODO remove redundancy enum { LIBDIVIDE_32_SHIFT_MASK = 0x1F, LIBDIVIDE_64_SHIFT_MASK = 0x3F, LIBDIVIDE_ADD_MARKER = 0x40, LIBDIVIDE_U32_SHIFT_PATH = 0x80, LIBDIVIDE_U64_SHIFT_PATH = 0x80, LIBDIVIDE_S32_SHIFT_PATH = 0x20, LIBDIVIDE_NEGATIVE_DIVISOR = 0x80 }; for (uint32_t d = n; d <= d_max; d++) { auto div = libdivide::libdivide_u32_gen(d); auto add_indicator = ((div.more & LIBDIVIDE_ADD_MARKER) != 0); if (add_indicator) { continue; } if (div.more & LIBDIVIDE_U32_SHIFT_PATH) { continue; } // only "algo 1" assert(d >= n); return {div.magic, (div.more & static_cast<uint32_t>(LIBDIVIDE_32_SHIFT_MASK)), d}; } throw "Failed to find a cheap magic number."; } //===----------------------------------------------------------------------===// // The actual implementation(s) for division. //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // Scalar //===----------------------------------------------------------------------===// __forceinline__ __host__ __device__ static uint32_t mulhi_u32(const uint32_t a, const uint32_t b) { const uint64_t prod = static_cast<uint64_t>(a) * static_cast<uint64_t>(b); return static_cast<uint32_t>(prod >> 32); } // works only for "cheap" magic numbers __forceinline__ __host__ __device__ static uint32_t fast_div_u32(const uint32_t dividend, const uint32_t magic, const uint32_t shift_amount) { const uint32_t quotient = mulhi_u32(dividend, magic); return quotient >> shift_amount; } __forceinline__ __host__ __device__ static uint32_t fast_div_u32(const uint32_t dividend, const fast_divisor_u32_t& divisor) { return fast_div_u32(dividend, divisor.magic, divisor.shift_amount); } __forceinline__ __host__ __device__ static uint32_t fast_mod_u32(const uint32_t dividend, const fast_divisor_u32_t& divisor) { return dividend - fast_div_u32(dividend, divisor.magic, divisor.shift_amount) * divisor.divisor; } //===----------------------------------------------------------------------===// // AVX-512 //===----------------------------------------------------------------------===// #if defined(__AVX512F__) __forceinline__ static __m512i mulhi_u32(const __m512i a, const uint32_t b) { const __m512i b_v = _mm512_set1_epi32(b); // shift 32-bit input to 64-bit lanes const __m512i a_odd_u64 = _mm512_srli_epi64(a, 32); const __m512i a_even_u64 = a; // multiply const __m512i p_odd_u64 = _mm512_mul_epu32(a_odd_u64, b_v); const __m512i p_even_u64 =_mm512_mul_epu32(a_even_u64, b_v); // merge the higher 32-bits of products back into a single ZMM register const __m512i p_even_hi_u64 = _mm512_srli_epi64(p_even_u64, 32); return _mm512_mask_mov_epi32(p_odd_u64, __mmask16(0b0101010101010101), p_even_hi_u64); } __forceinline__ static __m512i mulhi_u32(const __m512i a, const __m512i b) { // shift 32-bit input to 64-bit lanes const __m512i a_odd_u64 = _mm512_srli_epi64(a, 32); const __m512i a_even_u64 = a; const __m512i b_odd_u64 = _mm512_srli_epi64(b, 32); const __m512i b_even_u64 = b; // multiply const __m512i p_odd_u64 = _mm512_mul_epu32(a_odd_u64, b_odd_u64); const __m512i p_even_u64 =_mm512_mul_epu32(a_even_u64, b_even_u64); // merge the higher 32-bits of products back into a single ZMM register const __m512i p_even_hi_u64 = _mm512_srli_epi64(p_even_u64, 32); return _mm512_mask_mov_epi32(p_odd_u64, __mmask16(0b0101010101010101), p_even_hi_u64); } // works only for "cheap" magic numbers __forceinline__ static __m512i fast_div_u32(const __m512i dividend, const uint32_t magic, const uint32_t shift_amount) { const __m512i quotient = mulhi_u32(dividend, magic); return _mm512_srlv_epi32(quotient, _mm512_set1_epi32(shift_amount)); } __forceinline__ static __m512i fast_div_u32(const __m512i dividend, const __m512i magic, const __m512i shift_amount) { const __m512i quotient = mulhi_u32(dividend, magic); return _mm512_srlv_epi32(quotient, shift_amount); } __forceinline__ static __m512i fast_div_u32(const __m512i dividend, const fast_divisor_u32_t& divisor) { return fast_div_u32(dividend, divisor.magic, divisor.shift_amount); } __forceinline__ static __m512i fast_mod_u32(const __m512i dividend, const fast_divisor_u32_t& divisor) { const __m512i floor_div = fast_div_u32(dividend, divisor.magic, divisor.shift_amount); const __m512i t = _mm512_mullo_epi32(floor_div, _mm512_set1_epi32(divisor.divisor)); return dividend - t ; } #endif // defined(__AVX512F__) //===----------------------------------------------------------------------===// // AVX2 //===----------------------------------------------------------------------===// #if defined(__AVX2__) __forceinline__ static __m256i mulhi_u32(const __m256i a, const uint32_t b) { const __m256i b_v = _mm256_set1_epi32(b); // shift 32-bit input to 64-bit lanes const __m256i a_odd_u64 = _mm256_srli_epi64(a, 32); const __m256i a_even_u64 = a; // multiply const __m256i p_odd_u64 = _mm256_mul_epu32(a_odd_u64, b_v); const __m256i p_even_u64 =_mm256_mul_epu32(a_even_u64, b_v); // merge the higher 32-bits of products back into a single ZMM register const __m256i p_even_hi_u64 = _mm256_srli_epi64(p_even_u64, 32); return _mm256_blend_epi32(p_odd_u64, p_even_hi_u64, 0b01010101); } __forceinline__ static __m256i mulhi_u32(const __m256i a, const __m256i b) { // shift 32-bit input to 64-bit lanes const __m256i a_odd_u64 = _mm256_srli_epi64(a, 32); const __m256i a_even_u64 = a; const __m256i b_odd_u64 = _mm256_srli_epi64(b, 32); const __m256i b_even_u64 = b; // multiply const __m256i p_odd_u64 = _mm256_mul_epu32(a_odd_u64, b_odd_u64); const __m256i p_even_u64 =_mm256_mul_epu32(a_even_u64, b_even_u64); // merge the higher 32-bits of products back into a single YMM register const __m256i p_even_hi_u64 = _mm256_srli_epi64(p_even_u64, 32); return _mm256_blend_epi32(p_odd_u64, p_even_hi_u64, 0b01010101); } // works only for "cheap" magic numbers __forceinline__ static __m256i fast_div_u32(const __m256i dividend, const uint32_t magic, const uint32_t shift_amount) { const __m256i quotient = mulhi_u32(dividend, magic); return _mm256_srli_epi32(quotient, shift_amount); } __forceinline__ static __m256i fast_div_u32(const __m256i dividend, const __m256i magic, const __m256i shift_amount) { const __m256i quotient = mulhi_u32(dividend, magic); return _mm256_srlv_epi32(quotient, shift_amount); } __forceinline__ static __m256i fast_div_u32(const __m256i dividend, const fast_divisor_u32_t& divisor) { return fast_div_u32(dividend, divisor.magic, divisor.shift_amount); } __forceinline__ static __m256i fast_mod_u32(const __m256i dividend, const fast_divisor_u32_t& divisor) { const __m256i floor_div = fast_div_u32(dividend, divisor.magic, divisor.shift_amount); const __m256i t = _mm256_mullo_epi32(floor_div, _mm256_set1_epi32(divisor.divisor)); return dividend - t; } #endif // defined(__AVX2__) } // namespace dtl
#include <stdlib.h> // standard C library #include <mpi.h> // MPI library #include <time.h> // Time library // KOMPILACJA // mpicxx -o runfile fiverr_mpi.cpp // po użyciu powyższej komendy utworzony zostanie plik runfile, który możemy uruchomić za pomocą: // mpiexec -N 4 runfile // gdzie -N odpowiada za liczbę użytych procesorów (w powyższym przypadku są to 4 procesory), oczywiście liczba ta nie może // przewyższać możliwości komputera. // KOD // Tutaj umieszczona jest funkcja, w tym przypadku jest to Ax^2+Bx+C, ale może to być również inna funkcja double f1(double x, double a, double b, double c) { return (a*x*x + b*x + c); } // Główny kod programu int main(int argc, char *argv[]){ // Deklarujemy utworzenie MPI MPI_Init(&argc, &argv); // inicjujemy zmienne dla każdego procesu int a,b,c; // A, B i C z zadania int lim_a,lim_b; // a i b z zadania long long int n; // n z zadania (liczba operacji) double h; // h - wykorzystana przy obliczaniu całki double result; // wynik obliczeń clock_t start, end; // zmienne pomocnicze do obliczania czasu pracy programu int world_rank; int world_size; // przypisz liczbę używanych procesorów do world_size MPI_Comm_size(MPI_COMM_WORLD, &world_size); // przypisz numer procesora do world_rank MPI_Comm_rank(MPI_COMM_WORLD, &world_rank); // poniższy kod wykona tylko proces z numerem 0 (węzeł 0) wpisujemy tam dane wejściowe if(world_rank == 0){ printf("Korzystasz z %d procesorów\n", world_size); printf("Wpisz A\n"); scanf("%d",&a); printf("Wpisz B\n"); scanf("%d",&b); printf("Wpisz C\n"); scanf("%d",&c); printf("Wpisz granicę całkowania a\n"); scanf("%d",&lim_a); printf("Wpisz granicę całkowania b\n"); scanf("%d",&lim_b); printf("Wpisz n - liczbę podziałów\n"); scanf("%lld",&n); h = (lim_b-lim_a)/double(n); // obliczamy h - identyczne dla każdego procesu } // rozsyłamy dane wpisane w procesorze 0 do innych procesów MPI_Bcast(&a, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast(&b, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast(&c, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast(&lim_a, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast(&lim_b, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast(&n, 1, MPI_LONG_LONG_INT, 0, MPI_COMM_WORLD); MPI_Bcast(&h, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD); // koniec rozsyłania // dane są rozesłane, rozpoczynamy odliczanie czasu pracy start = clock(); // deklarujemy zmienne różne dla każdego procesu (każdy procesor będzie obliczać tylko część całki) int local_n = n/world_size; // liczba operacji na jeden procesor double local_a = lim_a + world_rank * local_n * h; // początek przedziału obliczeń dla jednego procesora double local_b = local_a + local_n * h; // koniec przedziału obliczeń dla jednego procesora // lokalna zmienna pomocnicza double x = local_a; // lokalny wynik double integral = (f1(local_a, a, b, c)+f1(local_b, a, b, c))/2.0; // funkcja obliczająca całkę oznaczoną for(int i = 1; i <= local_n-1; i++) { x += h; // obliczamy nowe x, a nastepnie integral += f1(x, a, b, c); // wykorzystujemy je do pozyskania kolejnej części całki, a, b i c są tutaj stałe zmienia się jedynie x } integral = integral*h; //printf("%f\n", integral); // wyniki poszczególnych obliczeń procesów MPI_Reduce(&integral, &result, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); // odsyłamy obliczone całki lokalne do procesu o numerze 0 i sumujemy je do zmiennej result end = clock(); // skończyliśmy obliczanie, więc zatrzymujemy zegar // Wyświetlamy wyniki korzystając z procesu o numerze 0 if(world_rank == 0){ double cpu_time_used; // zmienna pomocnicza cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC; // tutaj obliczamy liczbę sekund potrzebną na realizację programu. printf("Zadanie obliczono w %f sekund.\n", cpu_time_used); // wyświetlanie czasu realizacji zadania printf("Calka: %f\n", result); // wyświetlanie wyniku. } MPI_Finalize(); // KONIEC OBLICZEŃ return 0; } // KOD
#include <Siv3D.hpp> int whiteCount = 0; int blueCount = 0; int count = 1; int othelloStone[8][8]; double FILED[8][8]; int white = 1; int blue = 2; Array<Rect> cell; Array<Circle> stone; Array<Rect> WALL; void Wall() { for (int i = 0; i < 8; i++) for (int j = 0; j < 8; j++) { WALL << Rect(220, 100 + 50 * i, 50 + 50 * j, 50).drawFrame(1, 0); } } void initialize() { for(int i = 0; i < 8; i++) { for(int j = 0; j < 8; j++) { othelloStone[i][j] = 0; cell << Rect(223 + 50 * j, 103 + 50 * i, 45, 45); stone << Circle(245 + 50 * j, 125 + 50 * i, 15); } } othelloStone[3][3] = white; othelloStone[3][4] = blue; othelloStone[4][3] = blue; othelloStone[4][4] = white; } void reverseWhite(int x, int y) { // このnは青 for(int n = 1; n <= 6; n++) { // n + 1が挟む先の白 bool flag = othelloStone[x + n + 1][y] == white; for(int i = 1; i <= n; i++) { // ここは(color[][]&& == blue color[][] == blueの部分) flag &= othelloStone[x + i][y] == blue; } // trueの場合 if(flag) { for(int i = 1; i <= n; i++) { //ここは前やったcolor[i + n][i + j] = white の部分 othelloStone[x + i][y] = white; } } } for(int n = 1; n <= 6; n++) { bool flag = othelloStone[x - n - 1][y] == white; for(int i = 1; i <= n; i++) { flag &= othelloStone[x - i][y] == blue; } if(flag) { for(int i = 1; i <= n; i++) { othelloStone[x - i][y] = white; } } } for(int n = 1; n <= 6; n++) { bool flag = othelloStone[x][y + n + 1] == white; for(int i = 1; i <= n; i++) { flag &= othelloStone[x][y + i] == blue; } if(flag) { for(int i = 1; i <= n; i++) { othelloStone[x][y + i] = white; } } } for(int n = 1; n <= 6; n++) { bool flag = othelloStone[x][y - n - 1] == white; for(int i = 1; i <= n; i++) { flag &= othelloStone[x][y - i] == blue; } if(flag) { for(int i = 0; i <= n; i++) { othelloStone[x][y - i] = white; } } } for(int n = 0; n <= 6; n++) { bool flag = othelloStone[x + n + 1][y + 1] == white; for(int i = 1; i <= n; i++) { flag &= othelloStone[x][y + i] == blue; } if(flag) { for(int i = 1; i <= n; i++) { othelloStone[x + i][y + i] = white; } } } for(int n = 1; n < 6; n++) { bool flag = othelloStone[x - n - 1][y - n - 1] == white; for(int i = 1; i <= n; i++) { flag &= othelloStone[x - i][y - i] == blue; } if(flag) { for(int i = 1; i <= n; i++) { othelloStone[x - i][y - i] = white; } } } //下に石があった場合の右ななめ for(int n = 1; n < 6; n++) { bool flag = othelloStone[x + n + 1][y + n + 1] == white; for(int i = 1; i <= n; i++) { flag &= othelloStone[x + i][y + i] == blue; } if(flag) { for(int i = 1; i <= n; i++) { othelloStone[x + i][y + i] = white; } } } // 左斜めの処理 for(int n = 1; n <= 6; n++) { bool flag = othelloStone[x + n + 1][y - n - 1] == white; for(int i = 1; i <= n; i++) { flag &= othelloStone[x + i][y - i] == blue; } if(flag) { for(int i = 1; i <= n; i++) { othelloStone[x + i][y - i] = white; } } } for(int n = 1; n <= 6; n++) { bool flag = othelloStone[x - n - 1][y + n + 1] == white; for(int i = 1; i <= n; i++) { flag &= othelloStone[x - i][y + i] == blue; } if(flag) { for(int i = 1; i <= n; i++) { othelloStone[x - i][y + i] = white; } } } } void reverseBlue(int x, int y) { for(int n = 1; n <= 6; n++) { bool flag = othelloStone[x + n + 1][y] == blue; for(int i = 1; i <= n; i++) { flag &= othelloStone[x + i][y] == white; } if(flag) { for(int i = 1; i <= n; i++) { othelloStone[x + i][y] = blue; } } } for(int n = 1; n <= 6; n++) { bool flag = othelloStone[x - n - 1][y] == blue; for(int i = 1; i <= n; i++) { flag &= othelloStone[x - i][y] == white; } if(flag) { for(int i = 1; i <= n; i++) { othelloStone[x - i][y] = blue; } } } for(int n = 1; n <= 6; n++) { bool flag = othelloStone[x][y + n + 1] == blue; for(int i = 1; i <= n; i++) { flag &= othelloStone[x][y + i] == white; } if(flag) { for(int i = 1; i <= n; i++) { othelloStone[x][y + i] = blue; } } } for(int n = 1; n <= 6; n++) { bool flag = othelloStone[x][y - n - 1] == blue; for(int i = 1; i <= n; i++) { flag &= othelloStone[x][y - i] == white; } if(flag) { for(int i = 0; i <= n; i++) { othelloStone[x][y - i] = blue; } } } for(int n = 0; n <= 6; n++) { bool flag = othelloStone[x + n + 1][y + 1] == blue; for(int i = 1; i <= n; i++) { flag &= othelloStone[x][y + i] == white; } if(flag) { for(int i = 1; i <= n; i++) { othelloStone[x + i][y + i] = blue; } } } for(int n = 1; n < 6; n++) { bool flag = othelloStone[x - n - 1][y - n - 1] == blue; for(int i = 1; i <= n; i++) { flag &= othelloStone[x - i][y - i] == white; } if(flag) { for(int i = 1; i <= n; i++) { othelloStone[x - i][y - i] = blue; } } } for(int n = 1; n < 6; n++) { bool flag = othelloStone[x + n + 1][y + n + 1] == blue; for(int i = 1; i <= n; i++) { flag &= othelloStone[x + i][y + i] == white; } if(flag) { for(int i = 1; i <= n; i++) { othelloStone[x + i][y + i] = blue; } } } for(int n = 1; n <= 6; n++) { bool flag = othelloStone[x + n + 1][y - n - 1] == blue; for(int i = 1; i <= n; i++) { flag &= othelloStone[x + i][y - i] == white; } if(flag) { for(int i = 1; i <= n; i++) { othelloStone[x + i][y - i] = blue; } } } for(int n = 1; n <= 6; n++) { bool flag = othelloStone[x - n - 1][y + n + 1] == blue; for(int i = 1; i <= n; i++) { flag &= othelloStone[x - i][y + i] == white; } if(flag) { for(int i = 1; i <= n; i++) { othelloStone[x - i][y + i] = blue; } } } } void Main() { initialize(); while(System::Update()) { // カウントして、割ったあまりが1なら白と、2なら青と (coutn % 2 == // 0なら白と)(count %2 == 1なら青とひ表示o Wall(); for (int x = 0; x < 8; x++) for (int y = 0; y < 8; y++) { if (cell[x + y * 8].leftClicked()) { // 重ねておけないように if (othelloStone[x][y] == white && othelloStone[x][y] == white ) break; if (othelloStone[x][y] == blue && othelloStone[x][y] == blue ) break; // ターン変更 count++; // もしカウントが割り切れるなら白を描画、割り切れないならブルーを描画 if (count % 2 == 0) { othelloStone[x][y] = white; reverseWhite(x, y); } else { othelloStone[x][y] = blue; reverseBlue(x, y); } } if (othelloStone[x][y] == white) stone[x + y * 8].draw(); if (othelloStone[x][y] == blue) stone[x + y * 8].draw(Palette::Skyblue); } } }
#include "pch.h" #include "SymbolSet.h" #include <algorithm> SymbolSet::SymbolSet(){ } SymbolSet::~SymbolSet() { } int SymbolSet::in_Tab(string name) { transform(name.begin(), name.end(), name.begin(), ::towlower); if (Tab.getinfo(name)) { ifo = Tab.ret_info(); return 1; } return 0; } int SymbolSet::in_ATab(string name) { transform(name.begin(), name.end(), name.begin(), ::towlower); if (ATab.getinfo(name)) { ifo = ATab.ret_info(); return 1; } return 0; } int SymbolSet::in_FTab(string name) { transform(name.begin(), name.end(), name.begin(), ::towlower); for (auto i = FTab.begin(); i != FTab.end(); ++i) { if (i->ReName() == name) { reFTab = *i; return 1; } } return 0; } void SymbolSet::PrintSymbolSet() { cout << endl; cout << "this is SymbolSet const" << endl; Tab.PrintTable(); cout << "this is SymbolSet Array" << endl; ATab.PrintTable(); cout << "this is SymbolSet Function" << endl; for (auto i = FTab.begin(); i != FTab.end(); i++) { i->PrintTable(); } } /////////////////////////Table///////////////////////// Table::Table() { tablesize = 0; adr = 0; } int Table::insert_map(string name, info inf) { transform(name.begin(), name.end(), name.begin(), ::towlower); for (auto it = m.begin(); it != m.end(); ++it) { if (it->first == name) { return 0; } } inf.adr = this->adr; // cout << "##########################" << adr << endl; m.insert({ name, inf }); adr += inf.size; tablesize += inf.size; return 1; } int Table::getinfo(string name) { transform(name.begin(), name.end(), name.begin(), ::towlower); for (auto it = m.begin(); it != m.end(); ++it) { if (it->first == name) { ifo = it->second; return 1; } } return 0; } void Table::PrintTable() { for (auto i = m.begin(); i != m.end(); i++) { if (i->second.typ == info::chars) { cout << "char "<< i->first + ":" << i->second.ch << ",size is " << i->second.size << ", adr is: " << i->second.adr << "; "; } else cout << "int " << i->first + ":" + to_string(i->second.value) << ",size is " << i->second.size << ", adr is: " << i->second.adr << "; "; } cout << endl; } void Table::setreg(string name, string reg) { if (getinfo(name)) { m[name].reg = reg; } } string Table::reReg(string name) { if (getinfo(name)) { return m[name].reg; } return "NOREG_ERROR"; } ////////////////////////Fuction Table/////////////////////////// FTable::FTable(string name, funcType ftyp) { transform(name.begin(), name.end(), name.begin(), ::towlower); this->name = name; this->functy = ftyp; } int FTable::insert_para(string name, info inf) { transform(name.begin(), name.end(), name.begin(), ::towlower); return para.insert_map(name, inf); } int FTable::insert_arr(string name, info inf) { transform(name.begin(), name.end(), name.begin(), ::towlower); return arr.insert_map(name, inf); } int FTable::insert_ft(string name, info inf) { transform(name.begin(), name.end(), name.begin(), ::towlower); return ft.insert_map(name, inf); } int FTable::in_para(string name) { transform(name.begin(), name.end(), name.begin(), ::towlower); if (para.getinfo(name)) { ifo = para.ret_info(); return 1; } return 0; } int FTable::in_arr(string name) { transform(name.begin(), name.end(), name.begin(), ::towlower); if (arr.getinfo(name)) { ifo = arr.ret_info(); return 1; } return 0; } int FTable::in_ft(string name) { transform(name.begin(), name.end(), name.begin(), ::towlower); if (ft.getinfo(name)) { ifo = ft.ret_info(); return 1; } return 0; } void FTable::PrintTable() { cout << "Function name is : " + this->name; cout << ", Fucntion Type is : " << this->functy << endl; cout << "Function para is :"; para.PrintTable(); cout << "Function arr is :"; arr.PrintTable(); cout << "Function ft is : "; ft.PrintTable(); cout << endl; }
#include <iostream> #include <math.h> using namespace std; /* ---------------------------------- */ // QUASI-NEWTON METHOD /* TODO: * translate terms to English * format and style code * add explanations, code too verbose */ /* ---------------------------------- */ double f1_paraboloid(double x, double y) { return x*x + y*y - x*y - x - y; } double f1_paraboloid_Dx(double x, double y) { return 2*x - y - 1; } double f1_paraboloid_Dy(double x, double y) { return -x + 2*y - 1; } void matr_vec(double A[2][2], double x[2], double r[2]) { r[0] = A[0][0] * x[0] + A[0][1] * x[1]; r[1] = A[1][0] * x[0] + A[1][1] * x[1]; } double vect_transXvect(double vec1[2], double vec2[2]) { double out = 0; for (int i = 0; i < 2; i++) { out = out + vec1[i] * vec2[i]; } return out; } void vec_matr(double punct[2], double A[2][2], double sol[2]) { sol[0] = punct[0] * A[0][0] + punct[1] * A[1][0]; sol[1] = punct[0] * A[0][1] + punct[1] * A[1][1]; } double norma(double vect[2]) { double suma = 0; for (int i = 0; i < 2; i++) { suma = suma + vect[i] * vect[i]; } return sqrt(suma); } void scale_add(double coef, double veca[2], double vecb[2], double out[2]) { for (int i = 0; i < 2; i++) { out[i] = veca[i] + coef * vecb[i]; } } double vec_mat_vec(double vec1[2], double matr[2][2], double vec2[2]) { double sol[2]; double out; vec_matr(vec1, matr, sol); out = vect_transXvect(sol, vec2); return out; } void adunare_vectori(int n, double punct[2], double pas[2], double next[2]) { for (int i = 0; i < n; i++) { next[i] = punct[i] + pas[i]; } } void a_scale(int n, double coef, double in[2], double out[2]) { int i; for (i = 0; i < n; i++) out[i] = coef * in[i]; } void adunare_vectori(int n, double punct[2],double pas[2],double next[2]) { int i=0; for(i=0;i<n;i++){ next[i]=punct[i]+pas[i]; } } void adunare_matrici(double coef,double matr1[2][2],double matr2[2][2],double matr_out[2][2]) { for(int i=0;i<2;i++) for(int j=0;j<2;j++) matr_out[i][j]=matr1[i][j]+coef*matr2[i][j]; } void inmultire_matrici(double matr1[2][2],double matr2[2][2],double matr_out[2][2]) { for(int i=0;i<2;i++) for(int j=0;j<2;j++) matr_out[i][j]=matr1[i][0]*matr2[0][j]+matr1[i][1]*matr2[1][j]; } void scalarXmatrice(double scalar,double matr_in[2][2],double matr_out[2][2]) { int i=0; int j=0; for( i=0;i<2;i++) for( j=0;j<2;j++) matr_out[i][j]=scalar*matr_in[i][j]; } double gold_search(double f(double,double), double dir[], double x[], double tol) { double xnew[2]; double gr=(1+sqrt(5))/2; double step[2]; double alphar = 1/gr; a_scale(2, alphar, dir, step); adunare_vectori(2,x,step,xnew); double fr = f(xnew[0],xnew[1]); double alphal = 1/(gr*gr); a_scale(2, alphal, dir, step); adunare_vectori(2,x,step,xnew); double fl = f(xnew[0],xnew[1]); double ngrad = norma(dir); double dist = (alphar-alphal); while(ngrad*dist>tol) { dist = (alphar-alphal)/gr; if(fr > fl) { alphar = alphal; fr = fl; alphal -= dist; a_scale(2, alphal, dir, step); adunare_vectori(2,x,step,xnew); fl = f(xnew[0],xnew[1]); } else { alphal = alphar; fl = fr; alphar += dist; a_scale(2, alphar, dir,step); adunare_vectori(2,x,step,xnew); fr = f(xnew[0],xnew[1]); } } return (alphal+alphar)/2; } void gradient(double f(double,double),double punct[2],double grad[2],double tol) { double h; double eps=sqrt(tol); double f0; double f1; double x[2]; a_scale(2,1,punct,x); f0=f(x[0],x[1]); for(int i=0;i<2;i++) { h=fabs(x[i])*sqrt(eps)+0.00000000001; x[i]+=h; f1=f(x[0],x[1]); x[i]-=h; grad[i]=(f1-f0)/h; } } void vectXvect_trans(double vec1[2],double vec2[2],double matr[2][2]) { for(int i=0;i<2;i++) for(int j=0;j<2;j++) matr[i][j]=vec1[i]*vec2[j]; } void Quasi_Newton( double f(double,double), double punctcurent[2], double tol, double n) { fprintf("%f,%f\n",punctcurent[0],punctcurent[1]); double gradpred[2]; double gradcurent[2]; double B[2][2]={1,0,0,1}; double B1[2][2]; double B2[2][2]; double k; double aflat=false; double s[2]; double alfa; double q[2]; double p[2]; double punctpred[2]; gradient(f,punctcurent,gradpred,tol); a_scale(2,1,punctcurent,punctpred); while((aflat==false)&&(n>0)) { matr_vec(B,gradpred,s); s[0]=(-1)*s[0]; s[1]=(-1)*s[1]; alfa=gold_search(f,s,punctpred,tol); scale_add(alfa,punctpred,s,punctcurent); fprintf("%f,%f\n",punctcurent[0],punctcurent[1]); gradient(f,punctcurent,gradcurent,tol); scale_add(-1,gradcurent,gradpred,q); scale_add(-1,punctcurent,punctpred,p); k=vect_transXvect(p,q); vectXvect_trans(p,p,B1); scalarXmatrice(1/k,B1,B1); adunare_matrici(1,B,B1,B); k=vec_mat_vec(q,B,q); double r[2]; matr_vec(B,q,r); vectXvect_trans(r,q,B2); inmultire_matrici(B2,B,B2); scalarXmatrice(1/k,B2,B2); adunare_matrici(-1,B,B2,B); if(norma(gradcurent)<tol) { aflat=true; } else { a_scale(2,1,gradcurent,gradpred); a_scale(2,1,punctcurent,punctpred); } n--; } } int main() { int n = 2; double tol = 1e-3; double x_start[2] = {9, 7}; Quasi_Newton( f1_paraboloid, x_start, tol, n ); return 0; }
#include <iostream> #include <fstream> #include <string> #include "Text.h" namespace w3 { Text::Text() { } Text::Text(char* filename) { std::fstream in(filename, std::ios::in); if (in.is_open()) { std::string line; while (getline(in, line)) LineCount++; std::cout << "'" << filename << "' contains " << LineCount << " lines.\n"; LineTable = new std::string[LineCount]; in.clear(); //clear eof(end of file) error state in.seekp(0); //go back to the start of file for (size_t i = 0; i < LineCount; i++) { getline(in, LineTable[i]); if (auto cr = LineTable[i].find('/r')) if (cr != std::string::npos) LineTable[i].erase(cr, 1); } //for (size_t i = 0; i < LineCount; i++) // cout << i+1 << ": '" << LineTable[i] << "'\n"; } else { std::cerr << "Cannot open file'" << filename << "'\n"; exit(1); } } Text::~Text() { delete[] LineTable; } size_t Text::size() { return LineCount; } Text& Text::operator=(const Text& rhs) { if (this != &rhs) { delete[] LineTable; LineCount = rhs.LineCount; LineTable = new std::string[LineCount]; for (size_t i = 0; i < LineCount; i++) LineTable[i] = rhs.LineTable[i]; } return *this; } Text&& Text::operator=(Text&& rhs) { //Text&& operator = (Text&& rhs) if (this != &rhs) { delete[] LineTable; LineCount = rhs.LineCount; LineTable = rhs.LineTable; rhs.LineCount = 0; rhs.LineTable = nullptr; } //return *this; return std::move(*this); } Text::Text(const Text& rhs) { LineCount = rhs.LineCount; LineTable = new std::string[LineCount]; for (size_t i = 0; i < LineCount; i++) LineTable[i] = rhs.LineTable[i]; } Text::Text(Text&& rhs) { LineCount = rhs.LineCount; LineTable = rhs.LineTable; rhs.LineCount = 0; rhs.LineTable = nullptr; } };
#ifndef GAMEMANAGER_H #define GAMEMANAGER_H #include <iostream> #include <SDL.h> #include <fstream> #include <vector> #include "GameWindow.h" #include "Sprite.h" #include "PlayerCharacter.h" #include "Environment.h" #include "Button.h" #include "MainMenu.h" class GameManager { public: GameManager(int passed_ScreenWidth, int passed_ScreenHeight); ~GameManager(void); void GameLoop(void); float CameraX; float CameraY; bool check_collision(SDL_Rect a, SDL_Rect b); void Collision(); void UpdateGameInput(); int UpdateEditModeInputs(); bool ButtonControls(Button* button, bool has_animation = true); void ButtonControls(); void UpdateLevels(); private: string levelname; vector<string> existinglevels; int ScreenWidth; int ScreenHeight; unsigned int timecheck; bool quit; bool pressed; bool started; bool gamecreated; bool loading; bool paused; bool levelload; Environment* Level; GameWindow* gamewindow; PlayerCharacter* playercharacter; MainMenu* mainmenu; fstream gamefile; Sprite* loadscreen; int type; Mix_Music* bgm; Sprite* cursor; }; #endif // GAMEMANAGER_H
/* Copyright (c) 2005-2023, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef ABSTRACTACINARUNITFACTORY_HPP_ #define ABSTRACTACINARUNITFACTORY_HPP_ #include "AbstractAcinarUnit.hpp" #include "AbstractTetrahedralMesh.hpp" /** * A factory to ease creating acinar unit objects for use in a ventilation simulation. * * The user should implement their own concrete class, in particular implementing * CreateAcinarUnitForNode(Node*), which should return the acinar unit corresponding to a * given node. FinaliseAcinarUnitCreation() can be used to (eg) add global compliance (such * as chest wall) to the models */ class AbstractAcinarUnitFactory { private: /** The mesh is automatically set in VentilationProblem * This member variable should be accessed through GetMesh(), which will check if it has been set before * and throw an exception otherwise.*/ AbstractTetrahedralMesh<1,3>* mpMesh; public: /** * @return a newly acinar unit object for the given node. * * @param pNode Pointer to node object. */ virtual AbstractAcinarUnit* CreateAcinarUnitForNode(Node<3>* pNode) = 0; /** * May be overridden by subclasses to perform any necessary work after all acinar * have been created. * * @param pAcinarUnitsDistributed Pointer to a vector of acinar unit pointers. * @param lo Lowest index owned by this process. * @param hi Highest index owned by this process. */ // virtual void FinaliseAcinarUnitCreation(std::vector< AbstractAcinarUnit* >* pAcinarUnitsDistributed, // unsigned lo, unsigned hi); /** * @return The number of acini */ virtual unsigned GetNumberOfAcini(); /** * As this method is pure virtual, it must be overridden in subclasses. * * @param time The current time in seconds * @param pNode Pointer to node object. * @return The pleural pressure at the given node at the given time */ virtual double GetPleuralPressureForNode(double time, Node<3>* pNode)=0; /** * Default constructor. */ AbstractAcinarUnitFactory(); /** * Destructor */ virtual ~AbstractAcinarUnitFactory(); /** * @param pMesh the mesh for which to create acinar units. */ virtual void SetMesh(AbstractTetrahedralMesh<1,3>* pMesh); /** * @return the mesh used to create the acinar. */ AbstractTetrahedralMesh<1,3>* GetMesh(); }; #endif /*ABSTRACTACINARUNITFACTORY_HPP_*/
/************************************************************* * > File Name : c1071_1.cpp * > Author : Tony * > Created Time : 2019/10/04 12:05:00 * > Algorithm : SegmentTree **************************************************************/ #include <bits/stdc++.h> using namespace std; inline int read() { int x = 0; int f = 1; char ch = getchar(); while (!isdigit(ch)) {if (ch == '-') f = -1; ch = getchar();} while (isdigit(ch)) {x = x * 10 + ch - 48; ch = getchar();} return x * f; } const int maxn = 200010; const int inf = 0x7fffffff; int n, m, a[maxn]; struct Node { int laz; int sum, maxx, minn; #define sum(p) tree[p].sum #define laz(p) tree[p].laz #define maxx(p) tree[p].maxx #define minn(p) tree[p].minn }tree[maxn << 2]; void pushup(int p) { sum(p) = sum(p<<1) + sum(p<<1|1); maxx(p) = max(maxx(p<<1), maxx(p<<1|1)); minn(p) = min(minn(p<<1), minn(p<<1|1)); } void build(int p, int l, int r) { if (l == r) { sum(p) = maxx(p) = minn(p) = a[l]; return; } int mid = (l + r) >> 1; build(p<<1, l, mid); build(p<<1|1, mid + 1, r); pushup(p); } void pushdown(int p) { if (laz(p)) { sum(p<<1) = -sum(p<<1); sum(p<<1|1) = -sum(p<<1|1); int tmp = maxx(p<<1); maxx(p<<1) = -minn(p<<1); minn(p<<1) = -tmp; tmp = maxx(p<<1|1); maxx(p<<1|1) = -minn(p<<1|1); minn(p<<1|1) = -tmp; laz(p<<1) ^= 1; laz(p<<1|1) ^= 1; laz(p) = 0; } } void updPoint(int p, int L, int R, int id, int v) { if (L == R && L == id) { laz(p) = 0; sum(p) = maxx(p) = minn(p) = v; return; } pushdown(p); int mid = (L + R) >> 1; if (id <= mid) updPoint(p<<1, L, mid, id, v); if (id > mid) updPoint(p<<1|1, mid + 1, R, id, v); pushup(p); } void updAdd(int p, int L, int R, int id, int v) { if (L == R && L == id) { laz(p) = 0; sum(p) += v; maxx(p) += v; minn(p) += v; return; } pushdown(p); int mid = (L + R) >> 1; if (id <= mid) updAdd(p<<1, L, mid, id, v); if (id > mid) updAdd(p<<1|1, mid + 1, R, id, v); pushup(p); } void updRange(int p, int L, int R, int l, int r) { if (l <= L && R <= r) { sum(p) = -sum(p); int tmp = maxx(p); maxx(p) = -minn(p); minn(p) = -tmp; laz(p) ^= 1; return; } pushdown(p); int mid = (L + R) >> 1; if (l <= mid) updRange(p<<1, L, mid, l, r); if (r > mid) updRange(p<<1|1, mid + 1, R, l, r); pushup(p); } int queryMax(int p, int L, int R, int l, int r) { if (l <= L && R <= r) { return maxx(p); } pushdown(p); int mid = (L + R) >> 1; int ans = -inf; if (l <= mid) ans = max(ans, queryMax(p<<1, L, mid, l, r)); if (r > mid) ans = max(ans, queryMax(p<<1|1, mid + 1, R, l, r)); return ans; } int queryMin(int p, int L, int R, int l, int r) { if (l <= L && R <= r) { return minn(p); } pushdown(p); int mid = (L + R) >> 1; int ans = inf; if (l <= mid) ans = min(ans, queryMin(p<<1, L, mid, l, r)); if (r > mid) ans = min(ans, queryMin(p<<1|1, mid + 1, R, l, r)); return ans; } int querySum(int p, int L, int R, int l, int r) { if (l <= L && R <= r) { return sum(p); } pushdown(p); int mid = (L + R) >> 1; int ans = 0; if (l <= mid) ans += querySum(p<<1, L, mid, l, r); if (r > mid) ans += querySum(p<<1|1, mid + 1, R, l, r); return ans; } int lastans = 0; int main() { n = read(); m = read(); for (int i = 1; i <= n; ++i) { a[i] = read(); } build(1, 1, n); while (m--) { lastans = abs(lastans); int opt = read(), x = read(), y = read(); int l = ((x ^ lastans) % n) + 1; int r = ((y ^ lastans) % n) + 1; if (l > r) swap(l, r); switch(opt) { case 1: updPoint(1, 1, n, ((x ^ lastans) % n) + 1, y); break; case 2: updAdd(1, 1, n, ((x ^ lastans) % n) + 1, y); break; case 3: updRange(1, 1, n, l, r); break; case 4: printf("%d\n", lastans = queryMax(1, 1, n, l, r)); break; case 5: printf("%d\n", lastans = queryMin(1, 1, n, l, r)); break; case 6: printf("%d\n", lastans = querySum(1, 1, n, l, r)); break; } } return 0; }
#include <iostream> //For files #include <fstream> #include <cctype> //For character handling #include <string> #include <chrono> #include <vector> #include <algorithm> #include <iomanip> class User { public: User();//Constructor User(char, char, char, int); //Constructor ~User(); //Deconstructor void checkIfUserExists(int, std::string); void updateUser(int, std::string); bool deleteUser(int, std::string); void login(); private: struct UserInfo{ private: public: UserInfo(); UserInfo(std::string userNamex, std::string countryx, std::string genderx, unsigned int agex); std::string userName; std::string country; std::string gender; int age; }; };
//Student Name: Bair Suimaliev //Student email: bsuimaliev@myseneca.ca //Student ID: 159350198 //Date: 09.27.2021 //I have done all the coding by myselfand only copied the code //that my professor provided to complete my workshopsand assignments. #pragma once #ifndef _SDDS_STRINGSET_H_ #define _SDDS_STRINGSET_H_ #include <iostream> #include <iomanip> #include <ctime> #include <chrono> #include <string> #include <fstream> using namespace std; namespace sdds { class StringSet { string* strings{ nullptr }; size_t stringsCount = 0; public: //Constructor StringSet(); //Destructor ~StringSet(); //Constructor with one argument StringSet(const char* f); //Copy Constructor StringSet(const StringSet& obj); //Move Constructor StringSet(StringSet&& obj)noexcept; //Copy Assignment StringSet& operator=(const StringSet& obj); //Move Assignment StringSet& operator=(StringSet&& obj) noexcept; //Function for returning number of strings in the current object size_t size(); //Index Subscript Operator string operator[](size_t index) const; }; } #endif // !_SDDS_STRINGSET_H_
#ifndef REGISTER_H #define REGISTER_H #include "../visitors/codevisitor.h" #include <string> using namespace std; /** * A register is an abstraction used by three address code to represent * identifiers. */ class Register { public: Register(bool global): isGlobal_(global) { } virtual ~Register() { } /** * Returns the name of the identifier represented by this register */ virtual string* name() const = 0; /** * Accept a CodeVisitor for double dispatch */ virtual void accept(CodeVisitor* v) = 0; /** * Is this register containing a temporary variable or not? */ virtual bool isTemporary() const { return false; } /** * Is this register containing a constant or not? */ virtual bool isConstant() const { return false; } bool operator<(Register& other) { return ((*name()) < (*other.name())); } bool operator==(Register& other) { return ((*name()) == (*other.name())); } /** * @return whether this register is global or not */ bool isGlobal() const { return isGlobal_; } private: bool isGlobal_; /**< is this register global or not? */ }; #endif
#include <cstdio> // Min => Max // DATA: indexd | A[i] | unindexed void direct_insert_sort(int arr[], int n) { int i, j, tmp; // tmp as temporary data for(i = 1; i < n; i++) { if(arr[i-1] > arr[i]) { tmp = arr[i]; for(j = i-1; arr[j] > tmp; j--) // move forward to reseve i's postion arr[j+1] = arr[j]; arr[j+1] = tmp; // ATTENTION: Check the location } } } int main() { int arr[] = {73, 68, 80, 85, 73, 74, 33, 49, 74, 90, 23, 22, 1, 0, 57, 11, 27, 35, 60, 45}; int len = sizeof(arr) / sizeof(arr[0]); direct_insert_sort(arr, len); for(int i = 0; i < len; i++) { printf("%d ", arr[i]); } return 0; }
#include "RenderingSystem.h" RenderingSystem::RenderingSystem() { height=screenHeight; width=screenWidth; glClearColor(0.0f,0.0f,0.4f,0.0f); glViewport(0.0f, 0.0f, width, height); glEnable(GL_DEPTH_TEST); } RenderingSystem::~RenderingSystem() { } void RenderingSystem::set2D() { glMatrixMode(GL_PROJECTION); gluOrtho2D(0,width,0,height); glMatrixMode(GL_MODELVIEW); } void RenderingSystem::setTransformationMatrices(Scene* scene) { glm::mat4 projection = glm::perspective(scene->SceneCamera->Zoom, (float)screenWidth/(float)screenHeight, 0.1f, 100.0f); glm::mat4 view = scene->SceneCamera->GetViewMatrix(); glUniformMatrix4fv(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "projection"), 1, GL_FALSE, glm::value_ptr(projection)); glUniformMatrix4fv(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "view"), 1, GL_FALSE, glm::value_ptr(view)); } void RenderingSystem::DrawBackground(Scene* scene,int factor) { //Space2D glm::mat4 model0; model0=glm::scale(model0,glm::vec3(0.2f,0.155f,0.1f)); model0=glm::rotate(model0, PI/2.f,glm::vec3(1.0f,0.0f,0.0f)); //Remember that angle better to be in RADIANS !! model0 = glm::translate(model0, glm::vec3(0.0f, 0.0f, -factor*45.7f)); // Remember that axes are also rotated !! glUniformMatrix4fv(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "model"), 1, GL_FALSE, glm::value_ptr(model0)); scene->Background->Draw(*scene->SceneResources->lightingShader); } static int repeat=5; void RenderingSystem::DrawModels(Scene* scene) { scene->SceneResources->lightingShader->Use(); this->setTransformationMatrices(scene); //Continuously draw background for (int i = 0; i < repeat; i++) { this->DrawBackground(scene,i); } repeat++; //Render Player glUniformMatrix4fv(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "model"), 1, GL_FALSE, glm::value_ptr(scene->player->getModel()->getModelTransformations())); scene->player->getModel()->Draw(*scene->SceneResources->lightingShader); //Render Enemies for(int i=0;i<scene->getEnemiesNo();i++) { glUniformMatrix4fv(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "model"), 1, GL_FALSE, glm::value_ptr(scene->Enemies[i]->getModel()->getModelTransformations())); scene->Enemies[i]->getModel()->Draw(*scene->SceneResources->lightingShader); } } void RenderingSystem::Render(Scene* scene) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); DrawModels(scene); ComputeLight(scene); glfwSwapBuffers(); } void RenderingSystem::ComputeLight(Scene* scene) { scene->SceneResources->lightingShader->Use(); float Xs[4]={0.7f,2.3f,-4.0f,0.0f}; float Ys[4]={0.2f,-3.3f,2.0f,0.0f}; float Zs[4]={2.0f,-4.0f,-12.0f,-3.0f}; glm::vec3 pointLightPositions[] = { glm::vec3( Xs[0], Ys[0], Zs[0]), glm::vec3( Xs[1], Ys[1], Zs[1]), glm::vec3( Xs[2], Ys[2], Zs[2]), glm::vec3( Xs[3], Ys[3], Zs[3]) }; glUniform1i(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "material.diffuse"), 0); glUniform1i(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "material.specular"), 1); glUniform1f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "material.shininess"), 32.0f); GLint viewPosLoc = glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "viewPos"); glUniform3f(viewPosLoc, scene->getSceneCamera()->Position.x, scene->getSceneCamera()->Position.y, scene->getSceneCamera()->Position.z); // Directional light glUniform3f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "dirLight.direction"), -0.2f, -1.0f, -0.3f); glUniform3f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "dirLight.ambient"), 0.05f, 0.05f, 0.05f); glUniform3f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "dirLight.diffuse"), 0.4f, 0.4f, 0.4f); glUniform3f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "dirLight.specular"), 0.5f, 0.5f, 0.5f); // Point light 1 glUniform3f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "pointLights[0].position"), pointLightPositions[0].x, pointLightPositions[0].y, pointLightPositions[0].z); glUniform3f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "pointLights[0].ambient"), 0.05f, 0.05f, 0.05f); glUniform3f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "pointLights[0].diffuse"), 0.8f, 0.8f, 0.8f); glUniform3f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "pointLights[0].specular"), 1.0f, 1.0f, 1.0f); glUniform1f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "pointLights[0].constant"), 1.0f); glUniform1f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "pointLights[0].linear"), 0.09); glUniform1f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "pointLights[0].quadratic"), 0.032); // Point light 2 glUniform3f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "pointLights[1].position"), pointLightPositions[1].x, pointLightPositions[1].y, pointLightPositions[1].z); glUniform3f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "pointLights[1].ambient"), 0.05f, 0.05f, 0.05f); glUniform3f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "pointLights[1].diffuse"), 0.8f, 0.8f, 0.8f); glUniform3f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "pointLights[1].specular"), 1.0f, 1.0f, 1.0f); glUniform1f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "pointLights[1].constant"), 1.0f); glUniform1f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "pointLights[1].linear"), 0.09); glUniform1f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "pointLights[1].quadratic"), 0.032); // Point light 3 glUniform3f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "pointLights[2].position"), pointLightPositions[2].x, pointLightPositions[2].y, pointLightPositions[2].z); glUniform3f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "pointLights[2].ambient"), 0.05f, 0.05f, 0.05f); glUniform3f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "pointLights[2].diffuse"), 0.8f, 0.8f, 0.8f); glUniform3f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "pointLights[2].specular"), 1.0f, 1.0f, 1.0f); glUniform1f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "pointLights[2].constant"), 1.0f); glUniform1f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "pointLights[2].linear"), 0.09); glUniform1f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "pointLights[2].quadratic"), 0.032); // Point light 4 glUniform3f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "pointLights[3].position"), pointLightPositions[3].x, pointLightPositions[3].y, pointLightPositions[3].z); glUniform3f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "pointLights[3].ambient"), 0.05f, 0.05f, 0.05f); glUniform3f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "pointLights[3].diffuse"), 0.8f, 0.8f, 0.8f); glUniform3f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "pointLights[3].specular"), 1.0f, 1.0f, 1.0f); glUniform1f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "pointLights[3].constant"), 1.0f); glUniform1f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "pointLights[3].linear"), 0.09); glUniform1f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "pointLights[3].quadratic"), 0.032); // SpotLight glUniform3f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "spotLight.position"), scene->getSceneCamera()->Position.x, scene->getSceneCamera()->Position.y, scene->getSceneCamera()->Position.z); glUniform3f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "spotLight.direction"), scene->getSceneCamera()->Front.x, scene->getSceneCamera()->Front.y, scene->getSceneCamera()->Front.z); glUniform3f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "spotLight.ambient"), 0.0f, 0.0f, 0.0f); glUniform3f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "spotLight.diffuse"), 1.0f, 1.0f, 1.0f); glUniform3f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "spotLight.specular"), 1.0f, 1.0f, 1.0f); glUniform1f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "spotLight.constant"), 1.0f); glUniform1f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "spotLight.linear"), 0.09); glUniform1f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "spotLight.quadratic"), 0.032); glUniform1f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "spotLight.cutOff"), glm::cos(glm::radians(12.5f))); glUniform1f(glGetUniformLocation(scene->SceneResources->lightingShader->getProgram(), "spotLight.outerCutOff"), glm::cos(glm::radians(15.0f))); }
#include "Collision.h" Collision::Collision(sf::Vector2f bird_size, float world_bottom) { this->bird_size = bird_size; this->world_bottom = world_bottom; world_top = 0.0f; } Collision::~Collision() { } bool Collision::isCollision(sf::Vector2f bird_position, int amount_of_columns, std::vector<sf::RectangleShape> columns) { float world_borderline = 10.0f; bool isCollisionWithColumn = false; for (auto& c : columns) { auto c_xPos = c.getPosition().x; auto c_yPos = c.getPosition().y; auto c_xSize = c.getSize().x; auto c_ySize = c.getSize().y; if ((bird_position.y + bird_size.y >= c_yPos && bird_position.y <= c_yPos + c_ySize) && (bird_position.x + bird_size.x >= c_xPos && bird_position.x <= c_xPos + c_xSize)) { isCollisionWithColumn = true; break; } } return (isCollisionWithColumn || (amount_of_columns > 0 && (bird_position.y <= world_top + world_borderline || bird_position.y >= world_bottom - world_borderline))) ? true : false; }
#include "RegisterWidget.h" #include <QPalette> #include <QFont> #include <QDebug> #include <QPushButton> #include <QEventLoop> #include "../CommonFiles/Constants.h" #include "MessageBoxWidget.h" #include <QMessageBox> #include <QKeyEvent> #include <QCryptographicHash> RegisterWidget::RegisterWidget(int width, int height, QWidget *parent) : QWidget(parent) { this->resize(width, height); this->setFocus(); QImage glassImage("images/MessageBoxWidget/testglass.png"); m_glass = new QLabel(this); m_glass->setPixmap(QPixmap::fromImage(glassImage.scaled(width, height, Qt::KeepAspectRatio))); QImage background("images/AuthWidget/sign_up/background.png"); m_background = new QLabel(m_glass); const int backgroundWidth = width * 0.85; const int backgroundHeight = height * 0.85; m_background->setPixmap(QPixmap::fromImage(background.scaled(backgroundWidth, backgroundHeight, Qt::KeepAspectRatio))); m_background->resize(backgroundWidth, backgroundHeight); m_background->move(width * 0.6 , height * 0.1); QImage welcomeLbl("images/AuthWidget/sign_up/sign_up_label.png"); const int welcomeLblX = 115 * width / 1920; const int welcomeLblY = 188 * height / 1080; const QSize welcomeLblSize = welcomeLbl.size() / 2 * width / 1920; m_welcomeLbl = new QLabel(m_background); m_welcomeLbl->setPixmap(QPixmap::fromImage(welcomeLbl.scaled(welcomeLblSize, Qt::KeepAspectRatio))); m_welcomeLbl->move(welcomeLblX, welcomeLblY); QImage usernameLbl("images/AuthWidget/username.png"); const int usernameLblX = welcomeLblX; const int usernameLblY = welcomeLblY + welcomeLblSize.height() + height * 0.01 + height * 0.06; const QSize usernameLblSize = usernameLbl.size() / 2 * width / 1920; m_usernameLbl = new QLabel(m_background); m_usernameLbl->setPixmap(QPixmap::fromImage(usernameLbl.scaled(usernameLblSize, Qt::KeepAspectRatio))); m_usernameLbl->move (usernameLblX, usernameLblY); QImage usernameField("images/AuthWidget/lineEdit.png"); const int usernameFieldX = usernameLblX; const int usernameFieldY = usernameLblY + usernameLblSize.height() + height * 0.01; const QSize usernameFieldSize = usernameField.size() / 2 * width / 1920; m_usernameField = new QLabel(m_background); m_usernameField->setPixmap(QPixmap::fromImage(usernameField.scaled(usernameFieldSize, Qt::KeepAspectRatio))); m_usernameField->move(usernameFieldX, usernameFieldY); QImage passwordLabel("images/AuthWidget/password.png"); const int passwordLblX = usernameLblX; const int passwordLblY = usernameFieldY + usernameFieldSize.height() + height * 0.01; const QSize passwordLblSize = passwordLabel.size() / 2 * width / 1920; m_passwordLbl = new QLabel(m_background); m_passwordLbl->setPixmap(QPixmap::fromImage(passwordLabel.scaled(passwordLblSize, Qt::KeepAspectRatio))); m_passwordLbl->move(passwordLblX, passwordLblY); QImage passwordField("images/AuthWidget/lineEdit.png"); const int passwordFieldX = usernameLblX; const int passwordFieldY = passwordLblY + passwordLblSize.height() + height * 0.01; const QSize passwordFieldSize = passwordField.size() / 2 * width / 1920; m_passwordField = new QLabel(m_background); m_passwordField->setPixmap(QPixmap::fromImage(usernameField.scaled(passwordFieldSize, Qt::KeepAspectRatio))); m_passwordField->move(passwordFieldX, passwordFieldY); QImage confirmPasswordLbl("images/AuthWidget/sign_up/confirm_password.png"); const int confirmPasswordLblX = passwordFieldX; const int confirmPasswordLblY = passwordFieldY + passwordFieldSize.height() + height * 0.01; const QSize confirmPasswordLblSize = confirmPasswordLbl.size() / 2 * width / 1920; m_confirmPasswordLbl = new QLabel(m_background); m_confirmPasswordLbl->setPixmap(QPixmap::fromImage(confirmPasswordLbl.scaled(confirmPasswordLblSize, Qt::KeepAspectRatio))); m_confirmPasswordLbl->move(confirmPasswordLblX, confirmPasswordLblY); QImage confirmPasswordField("images/AuthWidget/lineEdit.png"); const int confirmPasswordFieldX = confirmPasswordLblX; const int confirmPasswordFieldY = confirmPasswordLblY + confirmPasswordLblSize.height() + height * 0.01; const QSize confirmPasswordFieldSize = confirmPasswordField.size() / 2 * width / 1920; m_confirmPasswordField = new QLabel(m_background); m_confirmPasswordField->setPixmap(QPixmap::fromImage(confirmPasswordField.scaled(confirmPasswordFieldSize, Qt::KeepAspectRatio))); m_confirmPasswordField->move(confirmPasswordFieldX, confirmPasswordFieldY); QPalette palette; palette.setColor(QPalette::Text, QColor(153, 70, 170)); QFont font("Times New Roman", 23 * width / 1920); m_usernameEdit = new QLineEdit(m_background); m_usernameEdit->setStyleSheet("QLineEdit {background-color: rgba(0, 0, 0, 0);}"); m_usernameEdit->setFont(font); m_usernameEdit->setPalette(palette); m_usernameEdit->setFixedSize(usernameFieldSize); m_usernameEdit->setMaxLength(16); m_usernameEdit->move(usernameFieldX+ 6 * width / 1980, usernameFieldY); m_usernameEdit->setFrame(false); m_usernameEdit->setFocus(); connect(m_usernameEdit, SIGNAL(returnPressed()), this, SLOT(enteredLogin())); m_passwordEdit = new QLineEdit(m_background); m_passwordEdit->setStyleSheet("QLineEdit {background-color: rgba(0, 0, 0, 0);}"); m_passwordEdit->setFont(font); m_passwordEdit->setPalette(palette); m_passwordEdit->setFixedSize(passwordFieldSize); m_passwordEdit->setMaxLength(16); m_passwordEdit->move(passwordFieldX+ 6 * width / 1980, passwordFieldY); m_passwordEdit->setFrame(false); m_passwordEdit->setEchoMode(QLineEdit::Password); connect(m_passwordEdit, SIGNAL(returnPressed()), this, SLOT(enteredPassword())); m_confirmPasswordEdit = new QLineEdit(m_background); m_confirmPasswordEdit->setStyleSheet("QLineEdit {background-color: rgba(0, 0, 0, 0);}"); m_confirmPasswordEdit->setFont(font); m_confirmPasswordEdit->setPalette(palette); m_confirmPasswordEdit->setFixedSize(confirmPasswordFieldSize); m_confirmPasswordEdit->setMaxLength(16); m_confirmPasswordEdit->move(confirmPasswordFieldX+ 6 * width / 1980, confirmPasswordFieldY); m_confirmPasswordEdit->setFrame(false); m_confirmPasswordEdit->setEchoMode(QLineEdit::Password); connect(m_confirmPasswordEdit, SIGNAL(returnPressed()), this, SLOT(confirmedPassword())); QImage signUp("images/AuthWidget/sign_up/sign_up_1.png"); QImage signUpClicked("images/AuthWidget/sign_up/sign_up_2.png"); const double buttonAspectRatio = (double) signUp.size().width() / signUp.size().height(); const int buttonHeight = height * 0.08; const int buttonWidth = buttonHeight * buttonAspectRatio; const int signUpX = confirmPasswordFieldX ; const int signUpY = confirmPasswordFieldY + buttonHeight; m_signUp = new ButtonLabel(buttonWidth, buttonHeight, signUp, signUpClicked, m_background); m_signUp->move(signUpX, signUpY); connect(m_signUp, SIGNAL(clicked()), this, SLOT(signUpClicked())); QImage cancel("images/AuthWidget/sign_up/cancel1.png"); QImage cancelClicked("images/AuthWidget/sign_up/cancel2.png"); m_cancel = new ButtonLabel(buttonWidth, buttonHeight, cancel, cancelClicked, m_background); m_cancel->move(signUpX + buttonWidth * 1.1, signUpY); connect(m_cancel, SIGNAL(clicked()), this, SLOT(cancledClicked())); } RegisterWidget::~RegisterWidget() { } int RegisterWidget::exec() { QEventLoop l; this->show(); connect(this, SIGNAL(stopExecEvent() ), &l, SLOT(quit()) ); l.exec(); this->close(); return 0; } QString RegisterWidget::getLogin() const { return m_savedLogin; } QString RegisterWidget::getPassword() const { return m_savedPassword; } void RegisterWidget::keyPressEvent(QKeyEvent *event) { QWidget::keyPressEvent(event); switch (event->key()) { // Esc case 16777216: m_cancel->clickButton(); } } void RegisterWidget::enteredLogin() { m_passwordEdit->setFocus(); } void RegisterWidget::enteredPassword() { m_confirmPasswordEdit->setFocus(); } void RegisterWidget::confirmedPassword() { m_signUp->clickButton(); } void RegisterWidget::signUpClicked() { QString login = m_usernameEdit->text(); QString password = m_passwordEdit->text(); QString confirmedPassword = m_confirmPasswordEdit->text(); if (login.length() > LOGIN_MAX || login.length() < LOGIN_MIN) { QString err ("Error! Login must consists of " + QString::number(LOGIN_MIN) + "-" + QString::number(LOGIN_MAX) + " characters in length"); MessageBoxWidget widg(this->width(), this->height(), err, this); widg.exec(); m_usernameEdit->clear(); m_passwordEdit->clear(); m_confirmPasswordEdit->clear(); m_usernameEdit->setFocus(); return; } if (password.length() > PASSWORD_MAX || password.length() < PASSWORD_MIN) { QString err("Error! Password must consists of " + QString::number(PASSWORD_MIN) + "-" + QString::number(PASSWORD_MAX) + " characters in length"); MessageBoxWidget widg(this->width(), this->height(), err, this); widg.exec(); m_passwordEdit->clear(); m_confirmPasswordEdit->clear(); m_passwordEdit->setFocus(); return; } if (password != confirmedPassword) { QString err ("Error! Passwords do not match."); MessageBoxWidget widg(this->width(), this->height(), err, this); widg.exec(); m_confirmPasswordEdit->clear(); m_confirmPasswordEdit->setFocus(); return; } m_savedLogin = login; QCryptographicHash md5(QCryptographicHash::Md5); md5.addData(m_passwordEdit->text().toStdString().c_str()); m_savedPassword = md5.result().toHex().constData(); emit trySignUp(m_savedLogin, m_savedPassword); } void RegisterWidget::cancledClicked() { emit stopExecEvent(); } void RegisterWidget::userRegistred() { MessageBoxWidget widg(this->width(), this->height(), "Signed up!", this); widg.exec(); emit stopExecEvent(); } void RegisterWidget::openErrorWidget(const QString &err) { MessageBoxWidget widg(this->width(), this->height(), err, this); widg.exec(); m_usernameEdit->clear(); m_passwordEdit->clear(); m_confirmPasswordEdit->clear(); m_usernameEdit->setFocus(); }
//Seth Stoltenow Delivery 2 CSCI 465 UND Fall 2018. Completed in Linux Mint on GCC 5.4.0 //ID: 1119117 //Email: seth.stoltenow@und.edu //To compile entire program: g++ lexer-SethStoltenow.cpp parser-SethStoltenow.cpp -o pascal -std=c++11 //To run: ./pascal input3.pas //Or: g++ -c lexer-SethStoltenow.cpp parser-SethStoltenow.cpp -std=c++11 //Then: g++ lexer-SethStoltenow.o parser-SethStoltenow.o -o pascal #include <iostream> #include <stdlib.h> #include <stack> #include <string> #include <map> using namespace std; extern map<string, string> symbolTable; extern string gstring; extern int gslength; extern int lineNumber; class symTabEntry { public: string type; //datatype string value; //spelling of the variable string scope; //name of function where it exists int offset; //starting value of array int size; //number of elements in an array int offsetFP; //offset from the frame pointer, for functions symTabEntry(string inType, string inValue, string inScope, int inOffset, int inSize, int inOffsetFP) { type = inType; value = inValue; scope = inScope; offset = inOffset; size = inSize; offsetFP = inOffsetFP; } symTabEntry() { type = ""; value = ""; scope = ""; offset = 0; size = 0; offsetFP = 0; } }; class token { public: string type; string value; token(string inType, string inVal) { type = inType; value = inVal; } }; class parser { public: //int isID(); int init(); void initRules(); int parse(token inTok); string getRule(token tok, string inState); //stack<string> ruleStack; }; class getSymbolNew { public: token * getSym(ifstream& file); }; class lexer { public: getSymbolNew get; token nextTok(); int initLex(string fileName); lexer() { } };
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct bst_node_t{ unsigned key,left_fruit; struct bst_node_t *left, *right, *parent; }BSTNode; typedef struct bst_metadata_t{ unsigned _size_node; BSTNode *_head; }BSTree; /* save node count */ /* List fungsi DONE Insert DONE Remove DONE Find DONE Init DONE Create Node (Init buat Node lol) DONE Find Deepest Delete certain Node Traversal: PreOrder PostOrder Inorder the idea is to */ /* As for now, depth isn't used*/ void bst_init(BSTree *tree) { tree->_size_node = 0; tree->_head = NULL; } BSTNode* bstNode_init(int value) { BSTNode *newNode = (BSTNode*)malloc(sizeof(BSTNode)); newNode->key = value; newNode->left_fruit = 0; newNode->left = NULL; newNode->right = NULL; newNode->parent = NULL; return newNode; } void __bst_ParentNodeAdd(BSTNode *now) { if(now->parent && now==now->parent->left) { //printf("\nadding %u left_fruit to %u.\n",now->parent->key,now->parent->left_fruit+1); now->parent->left_fruit++; __bst_ParentNodeAdd(now->parent); } } BSTNode* __bst_findNode(BSTNode *node,unsigned value, unsigned *tracker) { //printf("[tracker IS %u!!!]\n",*tracker); if(node) { if(node->left && value > node->key) { //*tracker+=1; return __bst_findNode(node->left,value,tracker); } //printf("[%d]->",node->key); else if(node->right && value < node->key) { *tracker+=node->left_fruit+1; return __bst_findNode(node->right,value,tracker); } else if(node->key == value) { *tracker+=node->left_fruit+1; //printf("[tracker IS %u!!!]\n",*tracker); return node; } } return NULL; } BSTNode* __bst_findParent(BSTNode *node,unsigned value) { if(node) { if(node->left && value > node->key) { node=node->left; return __bst_findParent(node,value);\ }else if(node->right && value < node->key) { node=node->right; return __bst_findParent(node,value); } } return node; } BSTNode* __bst_findDeepestNode(BSTNode *node) { if(node) { if(node->left) { node=node->left; return __bst_findDeepestNode(node); }else if(node->right) { node=node->right; return __bst_findDeepestNode(node); } } return node; } bool bst_insert(BSTree *tree, unsigned value) { BSTNode *newNode=bstNode_init(value); if(newNode) { if(tree->_head) { BSTNode *parent=__bst_findParent(tree->_head,value); newNode->parent=parent; if(parent && value > parent->key) { parent->left=newNode; } else if(parent && value < parent->key) { parent->right=newNode; } __bst_ParentNodeAdd(newNode); tree->_size_node++; return true; }else { tree->_head=newNode; tree->_size_node++; return true; } } return false; } bool bst_remove(BSTree *tree) { BSTNode *delThis=__bst_findDeepestNode(tree->_head),*temp; if(delThis) { temp=delThis->parent; if(temp->left == delThis) //SHITSHITSBHIT WILL IT BE NULL OR NOT??? temp->left=NULL; else temp->right=NULL; free(delThis); tree->_size_node--; return true; } return false; } void bst_print_inorder(BSTNode *now) { //printf("[IN]"); if(now) { if(now->parent) printf("%u->",now->parent->key); else printf("head->"); printf("[%u,<%u]\n",now->key,now->left_fruit); bst_print_inorder(now->left); bst_print_inorder(now->right); } } int main() { BSTree myTree; BSTNode *found = NULL; bst_init(&myTree); unsigned t,value,track; short int query; scanf("%u",&t); while(t--) { scanf("%hd %u",&query, &value); printf("%hd %u\n",query, value); if(query == 1) { bst_insert(&myTree,value); }else { track=0; found=__bst_findNode(myTree._head,value,&track); if(found) printf("%u\n",track); else printf("Data tidak ada\n"); } bst_print_inorder(myTree._head); } return 0; }
// github.com/andy489 // https://www.hackerrank.com/contests/practice-8-sda/challenges/maze-9 #include <iostream> #include <vector> #include <queue> using namespace std; vector<int> xd{1, 0, -1, 0}, yd{0, -1, 0, 1}; #define DIRECTIONS 4 struct Cell { char ch; int x, y, level; bool visited; Cell(char ch = 'a', int x = -1, int y = -1, int level = -1, bool visited = 0) : ch(ch), x(x), y(y), level(level), visited(visited) {} }; bool isValid(vector<vector<Cell>> &maze, int x, int y, int n, int m) { return x >= 0 && y >= 0 && x < n && y < m && maze[x][y].ch != '#'; } void bfs(Cell *s, vector<vector<Cell>> &maze, int n, int m) { queue<Cell *> Q; s->visited = true; s->level = 0; Q.push(s); while (!Q.empty()) { Cell *curr = Q.front(); Q.pop(); for (int i = 0; i < DIRECTIONS; ++i) { int newX = curr->x + xd[i]; int newY = curr->y + yd[i]; if (isValid(maze, newX, newY, n, m) && !maze[newX][newY].visited) { maze[newX][newY].visited = true; maze[newX][newY].level = curr->level + 1; Q.push(&maze[newX][newY]); } if (isValid(maze, newX, newY, n, m)) { bool flag = false; while (isValid(maze, newX + xd[i], newY + yd[i], n, m)) { flag = true; newX += xd[i]; newY += yd[i]; } if (flag && !maze[newX][newY].visited) { maze[newX][newY].visited = true; maze[newX][newY].level = curr->level + 1; Q.push(&maze[newX][newY]); } } } } } int main() { int n, m, i, j; char ch; Cell *start(nullptr), *fin(nullptr); cin >> n >> m; vector<vector<Cell>> maze; maze.assign(n, vector<Cell>(m)); for (i = 0; i < n; ++i) { for (j = 0; j < m; ++j) { cin >> ch; maze[i][j] = {ch, i, j}; if (ch == 'S') start = &maze[i][j]; if (ch == 'F') fin = &maze[i][j]; } } bfs(start, maze, n, m); return cout << fin->level, 0; }
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> using namespace std; struct data{ long long pos; long long val; }a[100010]; long long sum[100010]; long long sum2[100010]; long long n,m; bool cmp(data a,data b){ return a.pos<b.pos; } int main(){ int i,j,k; cin>>m>>n; for(i=1;i<=n;i++) cin>>a[i].pos>>a[i].val; sort(a+1,a+1+n,cmp); long long ans=-1; for(i=1;i<=n;i++){ sum[i]=sum[i-1]+(long long)a[i].pos*a[i].val; sum2[i]=sum2[i-1]+a[i].val; } for(i=1;i<=n;i++){ long long tmp=sum2[i-1]*a[i].pos-sum[i-1]; tmp+=sum[n]-sum[i]-(sum2[n]-sum2[i])*a[i].pos; if(ans==-1||ans>tmp) ans=tmp; } cout<<ans<<endl; return 0; }
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ // 只有根节点才能包含左右子树,否则得到的答案是最大二叉树和 class Solution { public: int maxPathSum(TreeNode* root) { int ret = INT_MIN; dfs(root, ret); return ret; } int dfs(TreeNode* root, int& ret) { if (root == NULL) return 0; int leftSum = dfs(root->left, ret); int l = leftSum > 0 ? leftSum : 0; int rightSum = dfs(root->right, ret); int r = rightSum > 0 ? rightSum : 0; ret = max(ret, root->val + l + r); // 注意这里求的是包含根节点的情况,而通过上面的赋值,我已经把只有根节点&包含左子树&包含右子树的情况都考虑进去 return max(root->val + l, root->val + r); // 这个返回设计很巧妙,返回的是只包含左子树/只包含右子树的值,可以用于上层计算 } };
#include <iostream> #include <vector> using namespace std; class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { map<int, int> hash; for (int i = 0; i < nums.size(); ++i) { if (hash.end() == hash.find(target - nums[i])) { hash[nums[i]] = i; } else { return {hash[target-nums[i]], i}; } } } }; int main() { return 0; }
/*********************************************************************** created: Fri Mar 02 2012 author: Paul D Turner <paul@cegui.org.uk> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2012 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. ***************************************************************************/ #include "CEGUI/falagard/EventAction.h" #include "CEGUI/falagard/XMLEnumHelper.h" #include "CEGUI/falagard/XMLHandler.h" #include "CEGUI/XMLSerializer.h" #include "CEGUI/Window.h" #include "CEGUI/Logger.h" #include "CEGUI/SharedStringStream.h" namespace CEGUI { //----------------------------------------------------------------------------// // Functor used to subscribe to events - this is where the magic happens! struct EventActionFunctor { EventActionFunctor(Window& window, ChildEventAction action) : window(window), action(action) {} bool operator()(const EventArgs& /*args*/) const { switch (action) { case ChildEventAction::Redraw: window.invalidate(false); return true; case ChildEventAction::Layout: window.performChildLayout(false, false); return true; default: throw InvalidRequestException("invalid action."); } } Window& window; ChildEventAction action; }; //----------------------------------------------------------------------------// EventAction::EventAction(const String& event_name, ChildEventAction action) : d_eventName(event_name), d_action(action) { } //----------------------------------------------------------------------------// EventAction::~EventAction() { } //----------------------------------------------------------------------------// void EventAction::setEventName(const String& event_name) { d_eventName = event_name; } //----------------------------------------------------------------------------// const String& EventAction::getEventName() const { return d_eventName; } //----------------------------------------------------------------------------// void EventAction::setAction(ChildEventAction action) { d_action = action; } //----------------------------------------------------------------------------// ChildEventAction EventAction::getAction() const { return d_action; } //----------------------------------------------------------------------------// void EventAction::initialiseWidget(Window& widget) const { Window* parent = widget.getParent(); if (!parent) throw InvalidRequestException( "EvenAction can only be initialised on child widgets."); d_connections.insert( std::make_pair(makeConnectionKeyName(widget), widget.subscribeEvent(d_eventName, EventActionFunctor(*parent, d_action)))); } //----------------------------------------------------------------------------// void EventAction::cleanupWidget(Window& widget) const { const String keyname(makeConnectionKeyName(widget)); ConnectionMap::iterator i = d_connections.find(keyname); if (i != d_connections.end()) d_connections.erase(i); else Logger::getSingleton().logEvent("EventAction::cleanupWidget: " "An event connection with key '" + keyname + "' was not " "found. This may be harmless, but most likely could point " "to a double-deletion or some other serious issue.", LoggingLevel::Error); } //----------------------------------------------------------------------------// void EventAction::writeXMLToStream(XMLSerializer& xml_stream) const { xml_stream.openTag(Falagard_xmlHandler::EventActionElement) .attribute(Falagard_xmlHandler::EventAttribute, d_eventName) .attribute(Falagard_xmlHandler::ActionAttribute, FalagardXMLHelper<ChildEventAction>::toString(d_action)) .closeTag(); } //----------------------------------------------------------------------------// String EventAction::makeConnectionKeyName(const Window& /*widget*/) const { String addressStr = SharedStringstream::GetPointerAddressAsString(this); return addressStr + d_eventName + FalagardXMLHelper<ChildEventAction>::toString(d_action); } //----------------------------------------------------------------------------// }
/* * Game.c pp * * Created on: 22 Oct 2016 * Author: andrew */ #include "Game.h" #include "mainWindow.h" #include <iostream> #include <string> #ifndef NDEBUG #define DeBug(msg) std::cout << msg << std::endl #else #define DeBug(msg) #endif Game::Game() { bHasStopped = false; bShallStop = false; iPossibleResults =0; vPlaySeq={18,21,20,19,17,15,16,13,11,14,12,10,8,9,7,6,5,2,1,4,3}; } Game::~Game() { } void Game::play_game(mainWindow* caller) { try { DeBug("Game::play_game - Start"); if (!bShallStop) { DeBug("Game::play_game - running"); std::vector<GameBoard> vGameInPlay; { std::lock_guard<std::mutex> lock(m_Mutex); vGameBoard.empty(); //clear old results iPossibleResults = vGameInPlay.size(); } for(auto seq : vPlaySeq) { DeBug("Game::play_game - Square " <<seq ); vGameInPlay = game_turn(seq, vGameInPlay); int iSize = vGameInPlay.size(); DeBug("Game::play_game - vGameInPlay.size() "<<iSize); { std::lock_guard<std::mutex> lock(m_Mutex); iPossibleResults = iSize; //check for hand brake if (bShallStop) { DeBug("Game::play_game - Hand Brake STOP"); break; ///exit for loop } } caller->notify(); } { std::lock_guard<std::mutex> lock(m_Mutex); vGameBoard = vGameInPlay; iPossibleResults = vGameInPlay.size(); } } DeBug("Game::play_game - stopping"); { std::lock_guard<std::mutex> lock(m_Mutex); bShallStop = false; bHasStopped = true; } caller->notify(); DeBug("Game::play_game - End"); } catch(const std::exception& e) { DeBug("Game::play_game - ERROR " << e.what()); } } void Game::stop_game() { DeBug("Game::stop_game - Start"); std::lock_guard<std::mutex> lock(m_Mutex); bShallStop = true; } bool Game::has_stopped() const { DeBug("Game::has_stopped - Start"); std::lock_guard<std::mutex> lock(m_Mutex); return bHasStopped; } unsigned int Game::get_result_num() { DeBug("Game::get_result_num"); std::lock_guard<std::mutex> lock(m_Mutex); int iSize = vGameBoard.size(); DeBug("get_result_num - size " <<iSize); return iSize; } GameBoard Game::get_result(unsigned int iNum) { try { DeBug("Game::get_result - START " << iNum); GameBoard oResult; std::lock_guard<std::mutex> lock(m_Mutex); if (iNum<=vGameBoard.size()) oResult = vGameBoard[iNum]; DeBug("Game::get_result - END"); return oResult; } catch(const std::exception& e) { DeBug("Game::get_result - ERROR " << e.what()); GameBoard oResult; return oResult; //return empty vector } } unsigned int Game::get_possible_results_num() { std::lock_guard<std::mutex> lock(m_Mutex); DeBug("get_possible_results_num" << iPossibleResults); return iPossibleResults; } std::vector<GameBoard> Game::game_turn(int iSquare, std::vector<GameBoard> vBoard) { try { DeBug("Game::game_turn - Start iSquare " << iSquare); std::vector<GameBoard> vReturn; //check if new game if(vBoard.size()==0) { DeBug("Game::game_turn - New game "); GameBoard newGame; vReturn = newGame.game_move(iSquare); } else { for( auto i : vBoard ) { DeBug("Game::game_turn -Next Square "); std::vector<GameBoard> vTemp; vTemp = i.game_move(iSquare); vReturn.insert(vReturn.end(), vTemp.begin(), vTemp.end()); } } DeBug("Game::game_turn - End"); return vReturn; } catch(const std::exception& e) { DeBug("Game::game_turn - ERROR " << e.what()); std::vector<GameBoard> vReturn; return vReturn; //return empty vector } }
/** * Date: 2019-11-09 22:18:16 * LastEditors: Aliver * LastEditTime: 2019-11-09 22:53:37 */ #ifndef _TEST6_H #define _TEST6_H #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> using namespace std; const char *filename = "./tmp.txt"; inline void exitWithError(const char *pro) { perror(pro); exit(EXIT_FAILURE); } inline void setNonBlock(const int fd) { if (fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK) == -1) exitWithError("fcntl"); } inline int readLock(int fd, bool wait = false) { struct flock lock; lock.l_type = F_RDLCK; lock.l_start = 0; lock.l_len = 0; lock.l_whence = SEEK_SET; int cmd = wait ? F_SETLKW : F_SETLK; if (fcntl(fd, cmd, &lock) == -1) exitWithError("fcntl"); return 0; } inline int writeLock(int fd, bool wait = false) { struct flock lock; lock.l_type = F_WRLCK; lock.l_start = 0; lock.l_len = 0; lock.l_whence = SEEK_SET; int cmd = wait ? F_SETLKW : F_SETLK; if (fcntl(fd, cmd, &lock) == -1) exitWithError("fcntl"); return 0; } inline int unLock(int fd) { struct flock lock; lock.l_type = F_UNLCK; lock.l_start = 0; lock.l_len = 0; lock.l_whence = SEEK_SET; if (fcntl(fd, F_SETLK, &lock) == -1) exitWithError("fcntl"); return 0; } #endif
#include <bits/stdc++.h> using namespace std; int main() { long int dp[15]; dp[0] = 1; for(int i=1; i<15; i++) dp[i] = 5*dp[i-1]; int t; cin>>t; while(t--) { int n, ans = 0; cin>>n; for(int i=1; i<14; i++) ans += (int)(n/dp[i]); cout<<ans<<endl; } }
/* We have two sorted array. Without using additional memory we need to merge these two arrays such that the initial numbers are in the 1st array and the remaining numbers are in the second array. Put the small sized array as arr1; complexity=n*n+n*m; ( n<m ) */ #include<iostream> using namespace std; void merge(int arr1[],int n1,int arr2[],int n2) { int p1=0; while(p1<n1) { while(arr1[p1]<arr2[0]) p1++; int t=arr1[p1]; arr1[p1]=arr2[0]; p1++; int m=1; cout<<"t: "<<t<<" arr2[0]: "<<arr2[0]<<endl; while(arr2[m]<t&&m<n2) { arr2[m-1]=arr2[m]; m++; } arr2[m-1]=t; //cout<<"p1: "<<p1<<" m: "<<m<<endl; } } int main() { int arr1[]={2,3,5,6}; int arr2[]={1,4}; int n1=sizeof(arr1)/sizeof(int); int n2=sizeof(arr2)/sizeof(int); merge(arr1,n1,arr2,n2); for(int i=0;i<n1;i++) cout<<arr1[i]<<" "; for(int i=0;i<n2;i++) cout<<arr2[i]<<" "; system("pause"); return 0; }
#include "BigIntegerAlgorithms.hh" #include <iostream> #include <fstream> #include <stdlib.h> #include <vector> #include <string> using namespace std; void nextPermut(int* permut, bool* used, int m, int n, int pos, BigInteger& k, BigInteger& counter) { for (int i = 0; i < n; ++i) { if (counter >= k) return; if (!used[i]) { used[i] = true; permut[pos] = i + 1; if (pos < m - 1) nextPermut(permut, used, m, n, pos + 1, k, counter); else ++counter; used[i] = false; } } } static string get_day(int N, BigInteger k, int m) { bool* used = new bool[N]{}; int* permut = new int[m]; BigInteger counter = 0; nextPermut(permut, used, m, N, 0, k, counter); string result; for (int i = 0; i < m - 1; ++i) result += to_string(permut[i]) + " "; result += to_string(permut[m - 1]); delete[] used; delete[] permut; return result; } int main(int argc, const char* argv[]) { int M, N, K; fstream fin; fstream fout; fin.open("input.txt", ios::in); fout.open("output.txt", ios::out); if (fin.is_open()) { string str; getline(fin, str); N = atoi(str.c_str()); getline(fin, str); //K = atoi(str.c_str()); BigInteger K = stringToBigInteger(str); getline(fin, str); M = atoi(str.c_str()); fout << get_day(N, K, M) << endl; fout.close(); fin.close(); } return 0; }
#pragma once #include <list> #include <string> #include <vector> #include <map> #include <iostream> #include "SDL\include\SDL.h" #include "Globals.h" using namespace std; class Application; struct PhysBody3D; class JSON_File; class Module { private: bool enabled; const char * name; public: Module(bool start_enabled = true) {} virtual ~Module() {} virtual bool Init(JSON_File* conf) { return true; } virtual bool Init() { return true; } virtual bool Start() { return true; } virtual update_status PreUpdate (float dt) { return UPDATE_CONTINUE; } virtual update_status Update (float dt) { return UPDATE_CONTINUE; } virtual update_status PostUpdate (float dt) { return update_status::UPDATE_CONTINUE; } virtual bool CleanUp() { return true; } virtual void OnCollision(PhysBody3D* body1, PhysBody3D* body2) {} void SetName(const char* name) { this->name = name; } const char * GetName() { return name; }; virtual void ImGuiDraw() {} virtual void Load(JSON_File* config) {} virtual void Save(JSON_File* c) {} };
// // bfb_algorithm.hpp // BFBDetectGraph // // Created by Tidesun on 25/3/2019. // Copyright © 2019 Oliver. All rights reserved. // #ifndef bfb_algorithm_hpp #define bfb_algorithm_hpp #include <iostream> #include <vector> #include <unordered_map> #include <array> #include "Graph.hpp" using namespace std; class BFBAlgorithm { protected: vector<Segment> allSegments; vector<Vertex> resultPath; double resultCost; int observedLen; char baseDir; char extendingDir; double haploidDepth; double costThreshold; unordered_map<int,pair<Segment*,Segment*>> vertexOrderMap; unordered_map<int,unordered_map<int,array<array<Edge*,2>,2>>> adjacentMatrix; public: BFBAlgorithm(Graph* g, double _costThreshold,char _baseDir,char _extendingDir); ~BFBAlgorithm(); vector<Vertex> createBase(double &cost); void generateAdjacentMatrix(Segment sourceSegment, Segment targetSegment); Edge* getConnectedEdge(Vertex lastVertex,Vertex candidate,double &tempCost); void printResult(); virtual void traverseUtil() = 0; }; #endif /* bfb_algorithm_hpp */
#include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <unordered_map> #include <utility> #include "hw2_types.h" #include "hw2_file_ops.h" #include "hw2_math_ops.h" std::vector<Camera> cameras; std::vector<Model> models; std::vector<Color> colors; std::vector<Translation> translations; std::vector<Rotation> rotations; std::vector<Scaling> scalings; std::vector<tinymath::vec3> vertices; std::vector<std::unordered_map<int, tinymath::vec3>> nvertices; Color backgroundColor; // backface culling setting, default disabled int backfaceCullingSetting = 0; Color **image; /* Initializes image with background color */ void initializeImage(Camera cam) { int i, j; for (i = 0; i < cam.sizeX; i++) for (j = 0; j < cam.sizeY; j++) { image[i][j].r = backgroundColor.r; image[i][j].g = backgroundColor.g; image[i][j].b = backgroundColor.b; } } tinymath::vec3 calculateNormal( const tinymath::vec3 & vertexA, const tinymath::vec3 & vertexB, const tinymath::vec3 & vertexC ) { tinymath::vec3 normal; tinymath::vec3 edgeBC = vertexC - vertexB; tinymath::vec3 edgeBA = vertexA - vertexB; normal = tinymath::normalize(tinymath::cross(edgeBC, edgeBA)); return normal; } void modellingTransform() { std::cout << "Started Modelling Transform" << std::endl; for (const auto & model: models) { std::unordered_map<int, tinymath::vec3> map; for (const auto & vertexId: model.usedVertices) { map.insert(std::make_pair(vertexId, vertices[vertexId-1])); for (int i= 0; i < model.numberOfTransformations; i++) { char tType = model.transformationTypes[i]; int tId = model.transformationIDs[i]; if (tType == 't') { Translation t = translations[tId-1]; tinymath::translate(map[vertexId],t); } else if (tType == 's') { Scaling s = scalings[tId-1]; tinymath::scale(map[vertexId],s); } else { //model.type == 'r' Rotation r = rotations[tId-1]; tinymath::rotate(map[vertexId],r); } } } nvertices.push_back(map); } } std::vector<std::unordered_map<int, tinymath::vec3>> cameraTransform(const Camera & cam) { std::cout << "Started Camera Transform" << std::endl; tinymath::vec3 u = cam.u; tinymath::vec3 v = cam.v; tinymath::vec3 w = cam.w; tinymath::vec3 pos = cam.pos; std::vector<std::unordered_map<int, tinymath::vec3>> newPositions; for (const auto & model: models) { std::unordered_map<int, tinymath::vec3> map; for (const auto & vertexId: model.usedVertices) { tinymath::vec3 vertex = nvertices[model.modelId-1][vertexId]; tinymath::vec3 vec = vertex; vec.x = dot(vertex,u) - dot(pos,u); vec.y = dot(vertex,v) - dot(pos,v); vec.z = dot(vertex,w) - dot(pos,w); map.insert(std::make_pair(vertexId,vec)); } newPositions.push_back(map); } return newPositions; } std::vector<std::unordered_map<int, tinymath::vec3>> perspectiveTransform(const Camera & cam, std::vector<std::unordered_map<int, tinymath::vec3>> & relPositions) { std::cout << "Started Perspective Transform" << std::endl; double n = cam.n, f = cam.f, l = cam.l, r = cam.r, b = cam.b, t = cam.t; for (auto & map: relPositions) { for (auto & pair: map) { tinymath::vec3 vertex = pair.second; double x = vertex.x, y = vertex.y, z = vertex.z; vertex.x = -(2*n*x + (r+l)*z) / ((r-l)*z); vertex.y = -(2*n*y + (t+b)*z) / ((t-b)*z); vertex.z = (f+n)/(f-n) + (2*f*n)/(z*(f-n)); pair.second = vertex; } } return relPositions; } void rasterizeLine(int x0, int y0, int x1, int y1, Color c0, Color c1) { bool l = false; if (abs(y1-y0) > abs(x1-x0)) { l = true; } if ((l == false && x1 < x0) || (l == true && y1 < y0)) { std::swap(x0,x1); std::swap(y0,y1); c0.swap(c1); } int inc = 1; if ((l == false && y1 < y0) || (l == true && x1 < x0)){ inc = -1; } Color c = c0; if (l == true) { Color dc = (c1 - c0)/(y1 - y0); int x = x0; int d = inc*0.5*(y0 - y1) + (x1 - x0); for (int y = y0; y <= y1; y++) { image[x][y] = c.round(); if (d*inc > 0) { x += inc; d += inc*(y0 - y1) + (x1 - x0); } else d+= (x1-x0); c = c+dc; } return; } int y = y0; int d = (y0 - y1) + inc*0.5*(x1 - x0); Color dc = (c1 - c0)/(x1 - x0); for (int x = x0; x <= x1; x++) { image[x][y] = c.round(); if (d*inc < 0) { y += inc; d += (y0 - y1) + inc*(x1 - x0); } else d+= (y0-y1); c = c+dc; } } void viewportTransform(const Camera & cam, std::vector<std::unordered_map<int, tinymath::vec3>> & newPositions ) { //map to 2d std::cout << "Started Viewing Transform" << std::endl; int nx = cam.sizeX; int ny = cam.sizeY; for (const auto & model: models) { for (const auto & triangle: model.triangles) { tinymath::vec3 v0 = newPositions[model.modelId-1][triangle.vertexIds[0]]; tinymath::vec3 v1 = newPositions[model.modelId-1][triangle.vertexIds[1]]; tinymath::vec3 v2 = newPositions[model.modelId-1][triangle.vertexIds[2]]; tinymath::vec3 normal = calculateNormal(v0,v1,v2); double dot = tinymath::dot(calculateNormal(v0,v1,v2),v0); if (backfaceCullingSetting == 1 && dot < 0) { continue; } int xmin = nx, xmax = -1, ymin = ny, ymax = -1; std::vector<tinymath::vec3> points; for (auto vertexId : triangle.vertexIds) { tinymath::vec3 vertex = newPositions[model.modelId-1][vertexId]; int pixelx = (vertex.x*nx + (nx-1) + 1)/2; int pixely = (vertex.y*ny + (ny-1) + 1)/2; vertex.x = pixelx; vertex.y = pixely; image[pixelx][pixely] = colors[vertex.colorId-1]; points.push_back(vertex); if (model.type == 1){ xmin = std::min(xmin,pixelx); xmax = std::max(xmax,pixelx); ymin = std::min(ymin,pixely); ymax = std::max(ymax,pixely); } } int x0 = points[0].x; int y0 = points[0].y; Color c0 = colors[points[0].colorId-1]; int x1 = points[1].x; int y1 = points[1].y; Color c1 = colors[points[1].colorId-1]; int x2 = points[2].x; int y2 = points[2].y; Color c2 = colors[points[2].colorId-1]; line line01(x0,y0,x1,y1); double f01 = line01(x2,y2); line line12(x1,y1,x2,y2); double f12 = line12(x0,y0); line line20(x2,y2,x0,y0); double f20 = line20(x1,y1); if (model.type == 0) { //wireframe rasterizeLine(x0,y0,x1,y1,c0,c1); rasterizeLine(x1,y1,x2,y2,c1,c2); rasterizeLine(x2,y2,x0,y0,c2,c0); } else { //solid for (int x = xmin; x <= xmax; x++){ for (int y = ymin; y <= ymax; y++){ double alpha = line12(x,y)/f12; double beta = line20(x,y)/f20; double gamma = line01(x,y)/f01; if (alpha >= 0 && beta >= 0 && gamma >= 0){ Color c; c = c0*alpha + c1*beta + c2*gamma; image[x][y] = c; } } } } } } } void forwardRenderingPipeline(const Camera & cam) { std::vector<std::unordered_map<int, tinymath::vec3>> relPos = cameraTransform(cam); perspectiveTransform(cam, relPos); viewportTransform(cam, relPos); } int main(int argc, char **argv) { if (argc < 2) { std::cout << "Usage: ./rasterizer <scene file> <camera file>" << std::endl; return 1; } readSceneFile(argv[1]); readCameraFile(argv[2]); modellingTransform(); image = 0; for (auto & cam: cameras) { int nx = cam.sizeX; int ny = cam.sizeY; if (image) { for (int j = 0; j < nx; j++) { delete[] image[j]; } delete[] image; } image = new Color*[nx]; if (image == NULL) { std::cout << "ERROR: Cannot allocate memory for image" << std::endl; exit(1); } for (int j = 0; j < nx; j ++) { image[j] = new Color[ny]; if (image[j] == NULL) { std::cout << "ERROR: Cannot allocate memory for image" << std::endl; exit(1); } } initializeImage(cam); //OUR MAIN FUNCTION forwardRenderingPipeline(cam); writeImageToPPMFile(cam); convertPPMToPNG(cam.outputFileName, 1); } return 0; }
/*************************************************************************** Copyright (c) 2020 Philip Fortier 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. ***************************************************************************/ // SCICompilerView.cpp : implementation of the CScriptView class // #include "stdafx.h" #include "ScriptDocument.h" #include "ScriptView.h" #include "resource.h" #include "Vocab000.h" #include "VocabAutoCompleteDialog.h" #include "AppState.h" #include "ScriptFrame.h" #include "ClassBrowser.h" #include "ScriptOM.h" #include "CrystalScriptStream.h" #include "GotoDialog.h" #include "CompiledScript.h" #include "Vocab99x.h" #include "SCO.h" #include "scii.h" #include "SyntaxParser.h" #include "CodeToolTips.h" #include "CodeAutoComplete.h" #include "InsertObject.h" #include "ClassBrowser.h" #include "CObjectWrap.h" #include "ResourceEntity.h" #include "Task.h" #include "SyntaxContext.h" #include "ParserCommon.h" #include "ParserActions.h" #include "ClipboardUtil.h" #include "FakeEgo.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // Time for tooltip to appear #define TOOLTIPTIMER_ID 1 #define TOOLTIPTIMER_INITIAL 500 // Time for tooltip to expire #define TOOLTIPEXPIRE_ID 2 #define TOOLTIPEXPIRE_TIMEOUT 8000 using namespace sci; using namespace std; #define UWM_AUTOCOMPLETEREADY (WM_APP + 0) #define UWM_HOVERTIPREADY (WM_APP + 1) void DoToolTipParse(ScriptId scriptId, CCrystalScriptStream &stream, CScriptStreamLimiter &limiter, ToolTipResult &result) { class CToolTipSyntaxParserCallback : public ISyntaxParserCallback { public: CToolTipSyntaxParserCallback(SyntaxContext &context, ToolTipResult &result) : _context(context), _result(result) {} bool Done() { _result = GetToolTipResult<SyntaxContext>(&_context); return false; } private: SyntaxContext &_context; ToolTipResult &_result; }; Script script(scriptId); SyntaxContext context(stream.begin(), script, PreProcessorDefinesFromSCIVersion(appState->GetVersion()), false, false); CToolTipSyntaxParserCallback callback(context, result); limiter.SetCallback(&callback); SyntaxParser_Parse(script, stream, PreProcessorDefinesFromSCIVersion(appState->GetVersion()), nullptr, false, &context); } // CScriptView IMPLEMENT_DYNCREATE(CScriptView, CCrystalEditView) BEGIN_MESSAGE_MAP(CScriptView, CCrystalEditView) ON_WM_CONTEXTMENU() ON_WM_ACTIVATE() ON_WM_KILLFOCUS() ON_WM_SETFOCUS() ON_WM_CHAR() ON_WM_LBUTTONDOWN() ON_WM_RBUTTONDOWN() ON_WM_MOUSEMOVE() ON_WM_TIMER() ON_WM_DESTROY() ON_COMMAND(ID_INSERTOBJECT, OnInsertObject) ON_COMMAND(ID_INSERTOBJECTAT, OnInsertObjectAt) ON_COMMAND(ID_SCRIPT_PASTECOORD, OnPasteCoord) ON_COMMAND(ID_SCRIPT_PASTE_X, OnPasteXY) ON_COMMAND(ID_SCRIPT_PASTE_APPROACHX, OnPasteApproachXY) ON_COMMAND_RANGE(ID_INSERTMETHODAT1, ID_INSERTMETHODAT18, OnInsertMethodAtRange) ON_COMMAND_RANGE(ID_INSERTOBJECTAT1, ID_INSERTOBJECTAT18, OnInsertObjectAtRange) ON_COMMAND(ID_ADDAS_NOUN, OnAddAsNoun) ON_COMMAND(ID_ADDAS_IMPERATIVEVERB, OnAddAsImperativeVerb) ON_COMMAND(ID_ADDAS_SYNONYMOF, OnAddAsSynonymOf) ON_COMMAND(ID_ADDAS_PREPOSITION, OnAddAsPreposition) ON_COMMAND(ID_ADDAS_QUALIFYINGADJECTIVE, OnAddAsQualifyingAdjective) ON_COMMAND(ID_ADDAS_RELATIVEPRONOUN, OnAddAsRelativePronoun) ON_COMMAND(ID_ADDAS_INDICATIVEVERB, OnAddAsIndicativeVerb) ON_COMMAND(ID_ADDAS_ADVERB, OnAddAsAdverb) ON_COMMAND(ID_ADDAS_ARTICLE, OnAddAsArticle) ON_COMMAND(ID_GOTOSCRIPT, OnGotoScriptHeader) ON_COMMAND(ID_MAIN_RELOADSYNTAXCOLORS, OnReloadSyntaxColors) ON_COMMAND(ID_EDIT_GOTO, OnGoto) ON_COMMAND(ID_SCRIPT_GOTODEFINITION, OnGotoDefinition) ON_COMMAND(ID_SCRIPT_OPENVIEW, OnOpenView) ON_COMMAND(ID_INTELLISENSE, OnIntellisense) ON_UPDATE_COMMAND_UI(ID_ADDAS_NOUN, OnUpdateAddAs) ON_UPDATE_COMMAND_UI(ID_ADDAS_IMPERATIVEVERB, OnUpdateAddAs) ON_UPDATE_COMMAND_UI(ID_ADDAS_SYNONYMOF, OnUpdateAddAs) ON_UPDATE_COMMAND_UI(ID_ADDAS_PREPOSITION, OnUpdateAddAs) ON_UPDATE_COMMAND_UI(ID_ADDAS_QUALIFYINGADJECTIVE, OnUpdateAddAs) ON_UPDATE_COMMAND_UI(ID_ADDAS_RELATIVEPRONOUN, OnUpdateAddAs) ON_UPDATE_COMMAND_UI(ID_ADDAS_INDICATIVEVERB, OnUpdateAddAs) ON_UPDATE_COMMAND_UI(ID_ADDAS_ADVERB, OnUpdateAddAs) ON_UPDATE_COMMAND_UI(ID_ADDAS_ARTICLE, OnUpdateAddAs) ON_UPDATE_COMMAND_UI(ID_GOTOSCRIPT, OnUpdateGotoScriptHeader) ON_UPDATE_COMMAND_UI(ID_SCRIPT_OPENVIEW, OnUpdateOpenView) ON_UPDATE_COMMAND_UI(ID_SCRIPT_GOTODEFINITION, OnUpdateGotoDefinition) // ON_COMMAND(ID_VISUALSCRIPT, OnVisualScript) ON_MESSAGE(UWM_AUTOCOMPLETEREADY, OnAutoCompleteReady) ON_MESSAGE(UWM_HOVERTIPREADY, OnHoverTipReady) ON_COMMAND(ID_MAIN_TOGGLEBLOCKCOMMENT, OnToggleComment) ON_UPDATE_COMMAND_UI(ID_MAIN_TOGGLEBLOCKCOMMENT, OnUpdateIsSCI) //ON_UPDATE_COMMAND_UI(ID_VISUALSCRIPT, OnUpdateAlwaysOn) END_MESSAGE_MAP() // CScriptView construction/destruction CScriptView::CScriptView() : _classBrowser(appState->GetClassBrowser()) { _fInOnChar = FALSE; _pwndToolTip = nullptr; _ptLastMM = CPoint(0, 0); _ptToolTipWord = CPoint(0, 0); _pAutoComp = nullptr; _pACThread = nullptr; _hoverTipScheduler = nullptr; _pMethodTip = nullptr; _lastHoverTipParse = -1; SetViewTabs(appState->_fShowTabs); } void CScriptView::UpdateCaret() { __super::UpdateCaret(); if (!_fInOnChar) { // If the caret moved while we weren't in OnChar, then close the autocomplete window if // the cursor pos changed. if (_ptAC != GetCursorPos()) { _ptAC = GetCursorPos(); if (_pAutoComp) { _pAutoComp->Hide(); } //_pParseContext->ResetState(); } } // Inform that the curpos pos changed. GetDocument()->UpdateAllViewsAndNonViews(this, 0, &WrapHint(ScriptChangeHint::Pos)); } void CScriptView::ScrollPosChanged() { // Hide any tooltip if (_pMethodTip) { _pMethodTip->Hide(); } if (_pwndToolTip) { _pwndToolTip->Hide(); } } void CScriptView::UpdateView(CCrystalTextView *pSource, CUpdateContext *pContext, DWORD dwFlags, int nLineIndex /*= -1*/) { if (_pACThread) { // This detects the case when text is inserted prior to the last autocompleted point, // thus invalidating our current autocomplete position and requiring us to reparse from the beginning. CPoint pt = _pACThread->GetCompletedPosition(); CPoint ptRecalced(pt); if (pContext) { pContext->RecalcPoint(ptRecalced); } if (!pContext || (ptRecalced != pt)) { _pACThread->ResetPosition(); } } // If the document was modified, we should ignore any hover tip task result: _lastHoverTipParse = -1; __super::UpdateView(pSource, pContext, dwFlags, nLineIndex); } BOOL CScriptView::PreTranslateMessage(MSG *pMsg) { if (pMsg->message >= WM_KEYFIRST && pMsg->message <= WM_KEYLAST) { if (_pAutoComp && _pAutoComp->IsWindowVisible()) { if (pMsg->message != WM_CHAR) // These VK codes don't make sense to check during WM_CHAR { if ((pMsg->wParam == VK_DOWN) || (pMsg->wParam == VK_UP) || (pMsg->wParam == VK_NEXT) || (pMsg->wParam == VK_PRIOR)) { // Send it to the listbox. _pAutoComp->SendMessage(pMsg->message, pMsg->wParam, pMsg->lParam); return TRUE; } else if (pMsg->wParam == VK_RETURN) { if (OnACDoubleClick()) { return TRUE; } // But if nothing is selected, do default handling. } else if (pMsg->wParam == VK_ESCAPE) { // Just close it. _pAutoComp->Hide(); return TRUE; } } } if (_pMethodTip && _pMethodTip->IsWindowVisible()) { if (pMsg->message != WM_CHAR) // These VK codes don't make sense to check during WM_CHAR { if (pMsg->wParam == VK_ESCAPE) { _pMethodTip->Hide(); } } } if (_pwndToolTip && _pwndToolTip->IsWindowVisible()) { // If we get a char, or something else (e.g. keydown) that is one of these 4 vkeys, // then hide the tooltip. if ((pMsg->message == WM_CHAR) || ((pMsg->wParam == VK_DOWN) || (pMsg->wParam == VK_UP) || (pMsg->wParam == VK_NEXT) || (pMsg->wParam == VK_PRIOR))) { _pwndToolTip->Hide(); } } } return __super::PreTranslateMessage(pMsg); } BOOL CScriptView::PreCreateWindow(CREATESTRUCT& cs) { // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs return __super::PreCreateWindow(cs); } void CScriptView::SyntaxHighlightScriptElements(const sci::Script &script) { bool needRepaint = false; if (_classesSyntaxHighlight.empty()) { // First time needRepaint = true; } _classesSyntaxHighlight.clear(); _procsSyntaxHighlight.clear(); _instancesSyntaxHighlight.clear(); // Collect procedures and instance names from the script for (auto &theClass : script.GetClasses()) { if (theClass->IsInstance()) { _instancesSyntaxHighlight.insert(theClass->GetName()); } else { _classesSyntaxHighlight.insert(theClass->GetName()); } } for (auto &theProc : script.GetProcedures()) { _procsSyntaxHighlight.insert(theProc->GetName()); } // And add in those from the class browser. _classBrowser.GetSyntaxHighlightClasses(_classesSyntaxHighlight); _classBrowser.GetSyntaxHighlightProcOrKernels(_procsSyntaxHighlight); if (needRepaint) { Invalidate(); } } // CScriptView drawing CCrystalTextBuffer *CScriptView::LocateTextBuffer() { // Here, we want to connect to a particular buffer in the document CScriptDocument *pDoc = GetDocument(); if (pDoc) { return pDoc->GetTextBuffer(); } else { return nullptr; } } // SCI keywords bool _IsKeyword(const std::string &word, std::vector<std::string> &sortedVector, LPTSTR *rg_OrigList, size_t size) { if (sortedVector.empty()) { // First time caller... sortedVector.insert(sortedVector.begin(), rg_OrigList, &rg_OrigList[size]); sort(sortedVector.begin(), sortedVector.end()); } return binary_search(sortedVector.begin(), sortedVector.end(), word); } std::vector<std::string> emptyList; std::vector<std::string> topLevelKeywordsSCI = { // Keep this alphabetically sorted. _T("class"), _T("define"), _T("enum"), _T("extern"), _T("include"), _T("instance"), _T("local"), _T("procedure"), _T("public"), _T("script#"), _T("string"), _T("synonyms"), _T("text#"), _T("use"), }; std::vector<std::string> topLevelKeywordsStudio = { // Keep this alphabetically sorted. _T("class"), _T("define"), _T("exports"), _T("include"), _T("instance"), _T("local"), _T("procedure"), _T("public"), _T("script"), _T("string"), _T("synonyms"), _T("use"), _T("version"), }; bool IsTopLevelKeyword(LangSyntax lang, const std::string &word) { auto &list = GetTopLevelKeywords(lang); return binary_search(list.begin(), list.end(), word); } const std::vector<std::string> &GetTopLevelKeywords(LangSyntax lang) { switch (lang) { case LangSyntaxSCI: return topLevelKeywordsSCI; case LangSyntaxStudio: return topLevelKeywordsStudio; } return emptyList; } std::vector<std::string> codeLevelKeywordsSCI = { // Sorted #ifdef ENABLE_EXISTS _T("&exists"), #endif #ifdef ENABLE_GETPOLY _T("&getpoly"), #endif _T("&rest"), _T("&sizeof"), // _T("&tmp"), // This is special _T("and"), _T("argc"), _T("asm"), _T("break"), _T("breakif"), _T("cond"), _T("contif"), _T("continue"), _T("else"), _T("enum"), _T("false"), _T("for"), #ifdef ENABLE_FOREACH _T("foreach"), #endif _T("if"), _T("mod"), _T("not"), _T("null") _T("of"), _T("or"), _T("repeat"), _T("return"), _T("scriptNumber"), _T("self"), _T("super"), _T("switch"), _T("switchto"), _T("true"), _T("while"), }; std::vector<std::string> codeLevelKeywordsStudio = { // Sorted _T("and"), _T("asm"), _T("break"), _T("case"), _T("default"), _T("do"), _T("else"), _T("for"), _T("if"), _T("neg"), _T("not"), _T("of"), _T("or"), _T("rest"), _T("return"), _T("scriptNumber"), _T("self"), _T("send"), _T("super"), _T("switch"), _T("var"), _T("while"), _T("paramTotal") }; bool IsCodeLevelKeyword(LangSyntax lang, const std::string &word) { auto &list = GetCodeLevelKeywords(lang); return binary_search(list.begin(), list.end(), word); } // Keep in alphabetical order std::vector<std::string> valueKeywordsSCI = { "argc", "false", "null", "objectFunctionArea", "objectInfo", "objectLocal", "objectName", "objectSize", "objectSpecies", "objectSuperclass", "objectTotalProperties", "objectType", "scriptNumber", "self", "true", }; // Keep in alphabetical order std::vector<std::string> valueKeywordsStudio = { "paramTotal", "scriptNumber", "self", }; bool IsValueKeyword(LangSyntax lang, const std::string &word) { auto &list = GetValueKeywords(lang); return binary_search(list.begin(), list.end(), word); } std::vector<std::string> classLevelKeywordsStudio = { "method", "properties" }; #ifdef ENABLE_VERBS std::vector<std::string> classLevelKeywordsSCI = { "method", "properties", "procedure", "verbs" }; #else std::vector<std::string> classLevelKeywordsSCI = { "method", "properties", "procedure" }; #endif bool IsClassLevelKeyword(LangSyntax lang, const std::string &word) { auto &list = GetClassLevelKeywords(lang); return binary_search(list.begin(), list.end(), word); } // Sorted: std::vector<std::string> unimplementedKeywordsSCI = { "class#", "classdef", "extern", "file#", "global", "methods", "selectors", "super#", }; bool IsUnimplementedKeyword(LangSyntax lang, const std::string &word) { if (lang == LangSyntaxSCI) { return binary_search(unimplementedKeywordsSCI.begin(), unimplementedKeywordsSCI.end(), word); } return false; } bool IsSCIKeyword(LangSyntax lang, const std::string &word) { return (IsValueKeyword(lang, word) || IsCodeLevelKeyword(lang, word) || IsTopLevelKeyword(lang, word) || IsClassLevelKeyword(lang, word) || IsUnimplementedKeyword(lang, word) || ((lang == LangSyntaxSCI) && (word == "&tmp"))); } const std::vector<std::string> &GetValueKeywords(LangSyntax lang) { switch (lang) { case LangSyntaxSCI: return valueKeywordsSCI; case LangSyntaxStudio: return valueKeywordsStudio; } return emptyList; } const std::vector<std::string> &GetCodeLevelKeywords(LangSyntax lang) { switch (lang) { case LangSyntaxSCI: return codeLevelKeywordsSCI; case LangSyntaxStudio: return codeLevelKeywordsStudio; } return emptyList; } const std::vector<std::string> &GetClassLevelKeywords(LangSyntax lang) { switch (lang) { case LangSyntaxSCI: return classLevelKeywordsSCI; case LangSyntaxStudio: return classLevelKeywordsStudio; } return emptyList; } static BOOL IsSCISelectorLiteral(LPCTSTR pszChars, int nLength) { BOOL bRet = FALSE; if (pszChars[0] == '#') { bRet = TRUE; for (int i = 1; i < nLength; i++) { if (!isalnum(pszChars[i])) { bRet = FALSE; break; } } } return bRet; } static BOOL IsSCIKeyword(LangSyntax lang, LPCTSTR pszChars, int nLength) { return IsSCIKeyword(lang, std::string(pszChars, nLength)); } BOOL IsStudioNumber(LPCTSTR pszChars, int nLength) { // Hex if (nLength > 1 && pszChars[0] == '$') { for (int I = 1; I < nLength; I++) { if (isdigit(pszChars[I]) || (pszChars[I] >= 'A' && pszChars[I] <= 'F') || (pszChars[I] >= 'a' && pszChars[I] <= 'f')) continue; return FALSE; } return TRUE; } if (!isdigit(pszChars[0]) && ((nLength <= 1) || (pszChars[0] != '-') || !isdigit(pszChars[1]))) return FALSE; for (int I = 1; I < nLength; I++) { if (! isdigit(pszChars[I]) && pszChars[I] != '+' && pszChars[I] != '-' && pszChars[I] != '.' && pszChars[I] != 'e' && pszChars[I] != 'E') return FALSE; } return TRUE; } BOOL IsSCISelectorCall(LPCTSTR pszChars, int nLength) { char ch = pszChars[nLength - 1]; return ch == ':' || ch == '?'; } BOOL IsSCINumber(LPCTSTR pszChars, int nLength) { if (nLength > 1) { // Binary if (pszChars[0] == '%') { for (int i = 1; i < nLength; i++) { if ((pszChars[i] == '1') || (pszChars[i] == '0')) continue; return FALSE; } return TRUE; } // Character literal else if (pszChars[0] == '`') { int lengthRequired = 2; if ((pszChars[1] == '^') || (pszChars[1] == '@') || (pszChars[1] == '#')) { lengthRequired++; } return (lengthRequired == nLength); } } return IsStudioNumber(pszChars, nLength); } BOOL IsStringCharEscaped(LPCTSTR pszChars, int indexOfChar) { BOOL isEscaped{ FALSE }; if (indexOfChar != 0) { for (int i{ indexOfChar - 1 }; i >= 0; i--) { if (pszChars[i] == '\\') { isEscaped = !isEscaped; } else { break; } } } return isEscaped; } #define DEFINE_BLOCK(pos, colorindex) \ ASSERT((pos) >= 0 && (pos) <= nLength);\ if (pBuf != nullptr)\ {\ if (nActualItems == 0 || pBuf[nActualItems - 1].m_nCharPos <= (pos)){\ pBuf[nActualItems].m_nCharPos = (pos);\ pBuf[nActualItems].m_nColorIndex = (colorindex);\ nActualItems ++;}\ } #define COOKIE_COMMENT 0x0001 #define COOKIE_SELECTOR 0x0002 #define COOKIE_EXT_COMMENT 0x0004 #define COOKIE_STRING 0x0008 #define COOKIE_CHAR 0x0010 #define COOKIE_INTERNALSTRING 0x0020 // Various states we can be in: // % bin digit enum class HighlightState { None, Number, Hex, BinaryLiteral, CharLiteral, SelectorLiteral, RegularToken, RegularTokenOrNumber, SelectorCall, }; void CScriptView::_ParseLineSCIHelper(TEXTBLOCK *pBuf, int &nActualItems, PCSTR pszChars, int nIdentBegin, int I, int nLength) { if (IsSCISelectorCall(pszChars + nIdentBegin, I - nIdentBegin)) { DEFINE_BLOCK(nIdentBegin, COLORINDEX_SELECTORCALL); } else if (IsSCIKeyword(LangSyntaxSCI, pszChars + nIdentBegin, I - nIdentBegin)) { DEFINE_BLOCK(nIdentBegin, COLORINDEX_KEYWORD); } // REVIEW: We'll need more things, for back-quote else if (IsSCINumber(pszChars + nIdentBegin, I - nIdentBegin)) { DEFINE_BLOCK(nIdentBegin, COLORINDEX_NUMBER); } else if (IsSCISelectorLiteral(pszChars + nIdentBegin, I - nIdentBegin)) { DEFINE_BLOCK(nIdentBegin, COLORINDEX_SELECTORLITERAL); } else { // We get this from our combobox script tasks. A bit of a hack, but it's an // easy way to get proc/class names. std::string text(pszChars + nIdentBegin, pszChars + I); if (_procsSyntaxHighlight.find(text) != _procsSyntaxHighlight.end()) { DEFINE_BLOCK(nIdentBegin, COLORINDEX_PROCEDURE); } else if (_classesSyntaxHighlight.find(text) != _classesSyntaxHighlight.end()) { DEFINE_BLOCK(nIdentBegin, COLORINDEX_CLASS); } else if (_instancesSyntaxHighlight.find(text) != _instancesSyntaxHighlight.end()) { DEFINE_BLOCK(nIdentBegin, COLORINDEX_INSTANCE); } } } DWORD CScriptView::_ParseLineSCI(DWORD dwCookie, int nLineIndex, TEXTBLOCK *pBuf, int &nActualItems) { HighlightState state = HighlightState::None; int nLength = GetLineLength(nLineIndex); LPCTSTR pszChars = GetLineChars(nLineIndex); BOOL bFirstChar = TRUE; BOOL bRedefineBlock = TRUE; BOOL bDecIndex = FALSE; int nIdentBegin = -1; int I = 0; for (;; I++) { if (bRedefineBlock) { int nPos = I; if (bDecIndex) nPos--; if (dwCookie & (COOKIE_COMMENT | COOKIE_EXT_COMMENT)) { DEFINE_BLOCK(nPos, COLORINDEX_COMMENT); } else if (dwCookie & (COOKIE_STRING)) { DEFINE_BLOCK(nPos, COLORINDEX_STRING); } else if (dwCookie & (COOKIE_CHAR)) { DEFINE_BLOCK(nPos, COLORINDEX_SAID); } else if (dwCookie & COOKIE_SELECTOR) { DEFINE_BLOCK(nPos, COLORINDEX_SELECTORLITERAL); } else if (dwCookie & COOKIE_INTERNALSTRING) { DEFINE_BLOCK(nPos, COLORINDEX_INTERNALSTRING); } else { DEFINE_BLOCK(nPos, COLORINDEX_NORMALTEXT); } bRedefineBlock = FALSE; bDecIndex = FALSE; } if (I == nLength) break; // Turning off things... if (dwCookie & COOKIE_COMMENT) { DEFINE_BLOCK(I, COLORINDEX_COMMENT); dwCookie |= COOKIE_COMMENT; break; } // String constant "...." if (dwCookie & COOKIE_STRING) { if (pszChars[I] == '"' && !IsStringCharEscaped(pszChars, I)) { dwCookie &= ~COOKIE_STRING; bRedefineBlock = TRUE; } continue; } // Internal string {....} if (dwCookie & COOKIE_INTERNALSTRING) { if (pszChars[I] == '}' && !IsStringCharEscaped(pszChars, I)) { dwCookie &= ~COOKIE_INTERNALSTRING; bRedefineBlock = TRUE; } continue; } // Said spec '..' if (dwCookie & COOKIE_CHAR) { if (pszChars[I] == '\'' && !IsStringCharEscaped(pszChars, I)) { dwCookie &= ~COOKIE_CHAR; bRedefineBlock = TRUE; } continue; } /////////////////////// // Starting things // REVIEW: This should only be true if it's not in a string if (pszChars[I] == ';') { DEFINE_BLOCK(I, COLORINDEX_COMMENT); dwCookie |= COOKIE_COMMENT; break; } // Normal text if (pszChars[I] == '"') { DEFINE_BLOCK(I, COLORINDEX_STRING); dwCookie |= COOKIE_STRING; continue; } if (pszChars[I] == '{') { DEFINE_BLOCK(I, COLORINDEX_INTERNALSTRING); dwCookie |= COOKIE_INTERNALSTRING; continue; } if (pszChars[I] == '\'') { DEFINE_BLOCK(I, COLORINDEX_SAID); dwCookie |= COOKIE_CHAR; continue; } if (bFirstChar) { if (!isspace(pszChars[I])) bFirstChar = FALSE; } if (pBuf == nullptr) continue; // We don't need to extract keywords, // for faster parsing skip the rest of loop bool sumup = false; char ch = pszChars[I]; switch (state) { case HighlightState::None: if (isalpha(ch) || ch == '_' || ch == '&') // & to support &rest and &temp { state = HighlightState::RegularToken; } else if (ch == '-') // - to support -info-, or it could be a number { state = HighlightState::RegularTokenOrNumber; } else if (isdigit(ch)) { state = HighlightState::Number; } else if (ch == '$') { state = HighlightState::Hex; } else if (ch == '#') { state = HighlightState::SelectorLiteral; } else if (ch == '%') { state = HighlightState::BinaryLiteral; } else if (ch == '`') { state = HighlightState::CharLiteral; } if (state != HighlightState::None) { // Beginning a token if (nIdentBegin == -1) nIdentBegin = I; } break; case HighlightState::RegularTokenOrNumber: if (isdigit(ch)) { state = HighlightState::Number; // Now we know... } else if (isalpha(ch)) { state = HighlightState::RegularToken; // Now we know... } else { sumup = true; } break; case HighlightState::RegularToken: if (isalnum(ch) || ch == '_' || ch == '-' || ch == '#') // # for "script#" { // good, keep going } else if (ch == '?' || ch == ':') { state = HighlightState::SelectorCall; } else { sumup = true; } break; case HighlightState::SelectorCall: sumup = true; // We're done break; case HighlightState::CharLiteral: sumup = (!isalnum(ch) && ch != '^' || ch != '@'); case HighlightState::BinaryLiteral: sumup = (ch != '0' && ch != '1'); break; case HighlightState::Hex: sumup = !isxdigit(ch); break; case HighlightState::Number: sumup = !isdigit(ch); break; case HighlightState::SelectorLiteral: sumup = !isalnum(ch) && ch != '_' && ch != '-'; break; } if (sumup) { if (nIdentBegin >= 0) { _ParseLineSCIHelper(pBuf, nActualItems, pszChars, nIdentBegin, I, nLength); bRedefineBlock = TRUE; bDecIndex = TRUE; nIdentBegin = -1; } state = HighlightState::None; } } if (nIdentBegin >= 0) { _ParseLineSCIHelper(pBuf, nActualItems, pszChars, nIdentBegin, I, nLength); } dwCookie &= ~COOKIE_COMMENT; return dwCookie; } DWORD CScriptView::ParseLine(DWORD dwCookie, int nLineIndex, TEXTBLOCK *pBuf, int &nActualItems) { LangSyntax lang = GetDocument()->GetScriptId().Language(); switch (lang) { case LangSyntaxSCI: return _ParseLineSCI(dwCookie, nLineIndex, pBuf, nActualItems); case LangSyntaxStudio: return _ParseLineStudio(dwCookie, nLineIndex, pBuf, nActualItems); } return 0; } // // SCI syntax highlighting // DWORD CScriptView::_ParseLineStudio(DWORD dwCookie, int nLineIndex, TEXTBLOCK *pBuf, int &nActualItems) { int nLength = GetLineLength(nLineIndex); if (nLength <= 0) return dwCookie & COOKIE_EXT_COMMENT; LPCTSTR pszChars = GetLineChars(nLineIndex); BOOL bFirstChar = (dwCookie & ~COOKIE_EXT_COMMENT) == 0; BOOL bRedefineBlock = TRUE; BOOL bDecIndex = FALSE; int nIdentBegin = -1; int I = 0; for (; ; I++) { if (bRedefineBlock) { int nPos = I; if (bDecIndex) nPos--; if (dwCookie & (COOKIE_COMMENT | COOKIE_EXT_COMMENT)) { DEFINE_BLOCK(nPos, COLORINDEX_COMMENT); } else if (dwCookie & (COOKIE_STRING)) { DEFINE_BLOCK(nPos, COLORINDEX_STRING); } else if (dwCookie & (COOKIE_CHAR)) { DEFINE_BLOCK(nPos, COLORINDEX_SAID); } else if (dwCookie & COOKIE_SELECTOR) { DEFINE_BLOCK(nPos, COLORINDEX_SELECTORLITERAL); } else if (dwCookie & COOKIE_INTERNALSTRING) { DEFINE_BLOCK(nPos, COLORINDEX_INTERNALSTRING); } else { DEFINE_BLOCK(nPos, COLORINDEX_NORMALTEXT); } bRedefineBlock = FALSE; bDecIndex = FALSE; } if (I == nLength) break; if (dwCookie & COOKIE_COMMENT) { DEFINE_BLOCK(I, COLORINDEX_COMMENT); dwCookie |= COOKIE_COMMENT; break; } // String constant "...." if (dwCookie & COOKIE_STRING) { if (pszChars[I] == '"' && (I == 0 || pszChars[I - 1] != '\\')) { dwCookie &= ~COOKIE_STRING; bRedefineBlock = TRUE; } continue; } // Internal string {....} if (appState->_fAllowBraceSyntax) { if (dwCookie & COOKIE_INTERNALSTRING) { if (pszChars[I] == '}' && (I == 0 || pszChars[I - 1] != '\\')) { dwCookie &= ~COOKIE_INTERNALSTRING; bRedefineBlock = TRUE; } continue; } } // Said spec '..' if (dwCookie & COOKIE_CHAR) { if (pszChars[I] == '\'' && (I == 0 || pszChars[I - 1] != '\\')) { dwCookie &= ~COOKIE_CHAR; bRedefineBlock = TRUE; } continue; } // Extended comment /*....*/ if (dwCookie & COOKIE_EXT_COMMENT) { if (I > 0 && pszChars[I] == '/' && pszChars[I - 1] == '*') { dwCookie &= ~COOKIE_EXT_COMMENT; bRedefineBlock = TRUE; } continue; } if (I > 0 && pszChars[I] == '/' && pszChars[I - 1] == '/') { DEFINE_BLOCK(I - 1, COLORINDEX_COMMENT); dwCookie |= COOKIE_COMMENT; break; } // Normal text if (pszChars[I] == '"') { DEFINE_BLOCK(I, COLORINDEX_STRING); dwCookie |= COOKIE_STRING; continue; } if (appState->_fAllowBraceSyntax && pszChars[I] == '{') { DEFINE_BLOCK(I, COLORINDEX_INTERNALSTRING); dwCookie |= COOKIE_INTERNALSTRING; continue; } if (pszChars[I] == '\'') { DEFINE_BLOCK(I, COLORINDEX_SAID); dwCookie |= COOKIE_CHAR; continue; } if (I > 0 && pszChars[I] == '*' && pszChars[I - 1] == '/') { DEFINE_BLOCK(I - 1, COLORINDEX_COMMENT); dwCookie |= COOKIE_EXT_COMMENT; continue; } if (bFirstChar) { if (! isspace(pszChars[I])) bFirstChar = FALSE; } if (pBuf == nullptr) continue; // We don't need to extract keywords, // for faster parsing skip the rest of loop if (isalnum(pszChars[I]) || pszChars[I] == '_' || pszChars[I] == '$' || pszChars[I] == '#') { if (nIdentBegin == -1) nIdentBegin = I; } else { if (nIdentBegin >= 0) { if (IsSCIKeyword(LangSyntaxStudio, pszChars + nIdentBegin, I - nIdentBegin)) { DEFINE_BLOCK(nIdentBegin, COLORINDEX_KEYWORD); } else if (IsStudioNumber(pszChars + nIdentBegin, I - nIdentBegin)) { DEFINE_BLOCK(nIdentBegin, COLORINDEX_NUMBER); } else if (IsSCISelectorLiteral(pszChars + nIdentBegin, I - nIdentBegin)) { DEFINE_BLOCK(nIdentBegin, COLORINDEX_SELECTORLITERAL); } bRedefineBlock = TRUE; bDecIndex = TRUE; nIdentBegin = -1; } } } if (nIdentBegin >= 0) { if (IsSCIKeyword(LangSyntaxStudio, pszChars + nIdentBegin, I - nIdentBegin)) { DEFINE_BLOCK(nIdentBegin, COLORINDEX_KEYWORD); } else if (IsStudioNumber(pszChars + nIdentBegin, I - nIdentBegin)) { DEFINE_BLOCK(nIdentBegin, COLORINDEX_NUMBER); } } if (pszChars[nLength - 1] != '\\') dwCookie &= COOKIE_EXT_COMMENT; return dwCookie; } void CScriptView::OnCompile() { CScriptDocument *pDocument = GetDocument(); if (pDocument) { //pDocument->CompileScript(); } } BOOL _GetMenuItem(PCTSTR pszText, CMenu *pMenu, UINT *pnID) { BOOL fRet = FALSE; UINT nCount = pMenu->GetMenuItemCount(); for (UINT i = 0; i < nCount; i++) { TCHAR szBuffer[MAX_PATH] = { 0 }; MENUITEMINFO mii = { 0 }; mii.cbSize = sizeof(mii); mii.fMask = MIIM_STRING; mii.cch = ARRAYSIZE(szBuffer); mii.dwTypeData = szBuffer; if (pMenu->GetMenuItemInfo(i, &mii, TRUE)) { if (0 == lstrcmpi(pszText, mii.dwTypeData)) { fRet = TRUE; *pnID = i; break; } } } return fRet; } BOOL _GetAddAsMenuItem(CMenu *pMenu, UINT *pnID) { return _GetMenuItem(TEXT("Add as"), pMenu, pnID); } BOOL _GetGoToDefnMenuItem(CMenu *pMenu, UINT *pnID) { return _GetMenuItem(TEXT("Go to definition"), pMenu, pnID); } BOOL _GetInsertObjectMenuItem(CMenu *pMenu, UINT *pnID) { return _GetMenuItem(TEXT("Insert object"), pMenu, pnID); } BOOL _GetInsertMethodMenuItem(CMenu *pMenu, UINT *pnID) { return _GetMenuItem(TEXT("Insert method"), pMenu, pnID); } void CScriptView::OnContextMenu(CWnd *pWnd, CPoint point) { CPoint ptClient = point; ScreenToClient(&ptClient); CPoint ptText = ptClient; AdjustTextPoint(ptText); BOOL fPossiblyOnWord = _ClientToTextNoMargin(ptText, ptText); // Reset these strings. _contextMenuText = TEXT(""); _gotoScriptText = TEXT(""); _gotoDefinitionText = TEXT(""); _helpUrl = TEXT(""); _gotoView = 0xffff; _vocabWordInfo = 0xffffffff; CMenu contextMenu; contextMenu.LoadMenu(IDR_MENUSCRIPT); CMenu* pTracker; pTracker = contextMenu.GetSubMenu(0); if (pTracker) { if (fPossiblyOnWord) { BOOL fIsHeaderLabel = GetHeaderFile(ptText, _gotoScriptText); if (!fIsHeaderLabel) { UINT nItem; if (_GetAddAsMenuItem(pTracker, &nItem)) { MENUITEMINFO mii = { 0 }; mii.cbSize = sizeof(mii); // Get the text around the place where the user clicked CPoint ptRight = WordToRight(ptText); CPoint ptLeft = WordToLeft(ptText); TCHAR szBuffer[MAX_PATH]; bool fDisableMenuOption = true; if (appState->GetVersion().HasSaidVocab && (ptRight != ptLeft)) { // This is a potential vocab string. GetText(ptLeft, ptRight, _contextMenuText); if (IsValidVocabString(_contextMenuText, FALSE)) { StringCchPrintf(szBuffer, ARRAYSIZE(szBuffer), TEXT("Add \"%s\" as"), (PCTSTR)_contextMenuText); mii.fMask = MIIM_STRING; mii.dwTypeData = szBuffer; fDisableMenuOption = false; } } if (fDisableMenuOption) { _contextMenuText = TEXT(""); // Disable the item. mii.fMask = MIIM_STATE; mii.fState = MFS_DISABLED; } pTracker->SetMenuItemInfo(nItem, &mii, TRUE); } } } uint16_t possibleResourceNumber = 0xffff; if (fPossiblyOnWord) { // Do a parse to see if we have something interesting to show for the "goto" entry. CPoint ptRight = WordToRight(ptText); CScriptStreamLimiter limiter(LocateTextBuffer(), ptRight, 0); CCrystalScriptStream stream(&limiter); ToolTipResult result; DoToolTipParse(GetDocument()->GetScriptId(), stream, limiter, result); if (!result.empty()) { _gotoDefinitionText = result.strBaseText.c_str(); _gotoScript = result.scriptId; _gotoLineNumber = result.iLineNumber; _helpUrl = result.helpURL.c_str(); _vocabWordInfo = result.vocabWordInfo; if (result.possibleResourceNumber == 0xffff) { possibleResourceNumber = result.possibleResourceNumber; } } if (possibleResourceNumber == 0xffff) { // The parser won't set this for raw integers (too much work to get it to work), so we'll // just try a conversion right here. CPoint ptRight = WordToRight(ptText); CPoint ptLeft = WordToLeft(ptText); CString strMaybeNumber; GetText(ptLeft, ptRight, strMaybeNumber); std::string maybeNumber = strMaybeNumber; // A little hokey, but this lets us re-use the parser code to get an integer. struct DummyContext { void ReportError(PCSTR psz, PCSTR &) {} void SetInteger(int value, bool neg, bool hex, PCSTR &) { this->value = value; } int value; }; DummyContext dummyContext; const char *pszTemp = maybeNumber.c_str(); if (IntegerExpandedPWorker(&dummyContext, pszTemp)) { possibleResourceNumber = dummyContext.value; } } if ((int)possibleResourceNumber < appState->GetVersion().GetMaximumResourceNumber()) { if (appState->GetResourceMap().DoesResourceExist(ResourceType::View, (int)possibleResourceNumber)) { _gotoView = possibleResourceNumber; } } } // Add objects? UINT insertObjectIndex; if (_GetInsertObjectMenuItem(pTracker, &insertObjectIndex)) { CMenu *subMenu = pTracker->GetSubMenu(insertObjectIndex); if (subMenu) { _availableObjects = make_unique<AvailableObjects>(GetDocument()->GetScriptId().Language()); for (size_t i = 0; i < _availableObjects->GetObjects().size(); i++) { int iIndex = 0; MENUITEMINFO mii = { 0 }; mii.cbSize = sizeof(mii); mii.fMask = MIIM_ID | MIIM_STRING; mii.wID = ID_INSERTOBJECTAT1 + i; std::string foo = _availableObjects->GetObjects()[i]->GetSuperClass(); mii.dwTypeData = const_cast<LPSTR>(foo.c_str()); subMenu->InsertMenuItem(ID_INSERTOBJECTAT1 + i, &mii, FALSE); } } } // Add methods? UINT insertMethodIndex; if (_GetInsertMethodMenuItem(pTracker, &insertMethodIndex)) { CMenu *subMenu = pTracker->GetSubMenu(insertMethodIndex); if (subMenu) { subMenu->RemoveMenu(0, MF_BYPOSITION); _availableMethods = make_unique<AvailableMethods>(GetDocument()->GetScriptId().Language()); for (size_t i = 0; i < _availableMethods->GetMethods().size(); i++) { int iIndex = 0; MENUITEMINFO mii = { 0 }; mii.cbSize = sizeof(mii); mii.fMask = MIIM_ID | MIIM_STRING; mii.wID = ID_INSERTMETHODAT1 + i; std::string foo = _availableMethods->GetMethods()[i]->GetName(); mii.dwTypeData = const_cast<LPSTR>(foo.c_str()); subMenu->InsertMenuItem(ID_INSERTMETHODAT1 + i, &mii, FALSE); } } } pTracker->TrackPopupMenu(TPM_LEFTALIGN | TPM_LEFTBUTTON | TPM_RIGHTBUTTON, point.x , point.y , AfxGetMainWnd()); } //has always to be called (function of base class) __super::OnContextMenu(pWnd, point); } void CScriptView::OnActivate(UINT nState, CWnd *pWndOther, BOOL bMinimized) { // REVIEW: This is never called. __super::OnActivate(nState, pWndOther, bMinimized); } void CScriptView::OnKillFocus(CWnd *pNewWnd) { if (_pAutoComp && _pMethodTip) { if (_pAutoComp->IsWindowVisible() || _pMethodTip->IsWindowVisible()) { if (pNewWnd->GetSafeHwnd() != _pAutoComp->GetSafeHwnd()) { // We're being de-focused, to a window other than the intellisense listbox. // So hide it. _pAutoComp->Hide(); _pMethodTip->Hide(); } } } if (_pwndToolTip) { _pwndToolTip->Hide(); } __super::OnKillFocus(pNewWnd); } void CScriptView::OnSetFocus(CWnd *pNewWnd) { appState->GiveMeAutoComplete(this); if (_pACThread) { _pACThread->InitializeForScript(LocateTextBuffer(), GetDocument()->GetScriptId().Language()); } if (_pAutoComp && _pAutoComp->IsWindowVisible()) { // We're being focused, to a window other than the intellisense listbox. // So hide it. _pAutoComp->Hide(); _pMethodTip->Hide(); } __super::OnSetFocus(pNewWnd); } void CScriptView::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags) { _fInOnChar = TRUE; __super::OnChar(nChar, nRepCnt, nFlags); _fInOnChar = FALSE; _ptAC = GetCursorPos(); if (nChar > 31) { OnIntellisense(); } } void CScriptView::OnLButtonDown(UINT nFlags, CPoint point) { if (_pMethodTip) { _pMethodTip->Hide(); } KillTimer(TOOLTIPTIMER_ID); if (_pwndToolTip) { _pwndToolTip->Hide(); } __super::OnLButtonDown(nFlags, point); } void CScriptView::OnRButtonDown(UINT nFlags, CPoint point) { if (_pMethodTip) { _pMethodTip->Hide(); } KillTimer(TOOLTIPTIMER_ID); if (_pwndToolTip) { _pwndToolTip->Hide(); } __super::OnRButtonDown(nFlags, point); } void CScriptView::OnMouseMove(UINT nFlags, CPoint point) { if (_pwndToolTip) { CPoint ptWordRight, ptDummy; BOOL fInEditableArea = _ScreenToWordRight(point, ptDummy, ptWordRight); if (!fInEditableArea || (_ptToolTipWord != ptWordRight)) { _pwndToolTip->Hide(); SetTimer(TOOLTIPTIMER_ID, TOOLTIPTIMER_INITIAL, nullptr); } } _ptLastMM = point; __super::OnMouseMove(nFlags, point); } void CScriptView::OnTimer(UINT nIDEvent) { switch (nIDEvent) { case TOOLTIPTIMER_ID: { KillTimer(TOOLTIPTIMER_ID); // Is mouse still over the window? Do we still have focus? CPoint pt; if (::GetCursorPos(&pt)) { ScreenToClient(&pt); CRect rc; GetClientRect(&rc); if (rc.PtInRect(pt)) { // Still in the window, good. if (pt == _ptLastMM) { // At the same spot. Try to bring up a tooltip. _BringUpToolTip(pt); } } } } break; case TOOLTIPEXPIRE_ID: { KillTimer(TOOLTIPEXPIRE_ID); _pwndToolTip->Hide(); } break; } __super::OnTimer(nIDEvent); } void CScriptView::_OnAddAs(WordClass dwClass) { ResourceEntity *pResource = appState->GetResourceMap().GetVocabResourceToEdit(); if (pResource) { Vocab000 *pVocab000 = pResource->TryGetComponent<Vocab000>(); if (pVocab000) { VocabChangeHint hint = pVocab000->AddNewWord(_contextMenuText, dwClass, TRUE); if (hint != VocabChangeHint::None) { appState->GetResourceMap().AppendResource(*pResource); } } } } void CScriptView::_OnInsertObject(bool currentPosition) { CScriptDocument *pDoc = GetDocument(); if (pDoc) { CInsertObject dialog(pDoc->GetScriptId().Language()); if (IDOK == dialog.DoModal()) { CString strBuffer = dialog.GetBuffer(); if (!currentPosition) { MoveToEnd(); } PasteTextAtCursorAndHightlightWord(strBuffer, c_szUnnamedObject); } } } void CScriptView::OnDestroy() { if (_hoverTipScheduler) { _hoverTipScheduler->DeactivateHWND(this->GetSafeHwnd()); } __super::OnDestroy(); } void CScriptView::OnInsertObject() { _OnInsertObject(false); } void CScriptView::OnInsertObjectAt() { _OnInsertObject(true); } void CScriptView::OnPasteCoord() { std::string text; ProcessClipboardDataIfAvailable(appState->ViewAttributesClipboardFormat, AfxGetMainWnd(), [&text](sci::istream &data) { size_t count; data >> count; assert(count >= 1); for (size_t i = 0; i < count; i++) { FakeEgo fakeEgo; data >> fakeEgo; text += fmt::format(" {0} {1}", fakeEgo.Location.x, fakeEgo.Location.y); } } ); if (!text.empty()) { PasteTextAtCursor(text.c_str()); } } void CScriptView::_OnPasteXYHelper(const std::string &formatString) { std::string text; ProcessClipboardDataIfAvailable(appState->ViewAttributesClipboardFormat, AfxGetMainWnd(), [&text, &formatString](sci::istream &data) { size_t count; data >> count; assert(count >= 1); FakeEgo fakeEgo; data >> fakeEgo; text += fmt::format(formatString, fakeEgo.Location.x, fakeEgo.Location.y); } ); if (!text.empty()) { PasteTextAtCursor(text.c_str()); } } void CScriptView::OnPasteXY() { _OnPasteXYHelper("\r\n\t\tx {0}\r\n\t\ty {1}"); } void CScriptView::OnPasteApproachXY() { _OnPasteXYHelper("\r\n\t\tapproachX {0}\r\n\t\tapproachY {1}"); } void CScriptView::OnInsertMethodAtRange(UINT nID) { int index = nID - ID_INSERTMETHODAT1; if (_availableMethods) { CString strBuffer; const MethodDefinition *methodDef = _availableMethods->GetMethods()[index]; _availableMethods->PrepareBuffer(methodDef, strBuffer); PasteTextAtCursor(strBuffer); _availableMethods.reset(nullptr); } } void CScriptView::OnInsertObjectAtRange(UINT nID) { int index = nID - ID_INSERTOBJECTAT1; if (_availableObjects) { CString strBuffer; ClassDefinition *classDef = _availableObjects->GetObjects()[index]; classDef->SetName(c_szUnnamedObject); _availableObjects->PrepareBuffer(classDef, strBuffer); PasteTextAtCursorAndHightlightWord(strBuffer, c_szUnnamedObject); _availableObjects.reset(nullptr); } } void CScriptView::OnAddAsNoun() { _OnAddAs(WordClass::Noun); } void CScriptView::OnAddAsImperativeVerb() { _OnAddAs(WordClass::ImperativeVerb); } void CScriptView::OnAddAsPreposition() { _OnAddAs(WordClass::Proposition); } void CScriptView::OnAddAsQualifyingAdjective() { _OnAddAs(WordClass::QualifyingAdjective); } void CScriptView::OnAddAsRelativePronoun() { _OnAddAs(WordClass::RelativePronoun); } void CScriptView::OnAddAsIndicativeVerb() { _OnAddAs(WordClass::IndicativeVerb); } void CScriptView::OnAddAsAdverb() { _OnAddAs(WordClass::Adverb); } void CScriptView::OnAddAsArticle() { _OnAddAs(WordClass::Article); } void CScriptView::OnAddAsSynonymOf() { ASSERT(!_contextMenuText.IsEmpty()); CVocabAutoCompleteDialog dialog; dialog.SetWord(_contextMenuText); if (IDOK == dialog.DoModal()) { CString strWord = dialog.GetWord(); CString strSynonym = dialog.GetSynonym(); ResourceEntity *resource = appState->GetResourceMap().GetVocabResourceToEdit(); if (resource) { Vocab000 *pVocab000 = resource->TryGetComponent<Vocab000>(); if (pVocab000) { VocabChangeHint hint = pVocab000->AddSynonym(strWord, strSynonym); if (hint != VocabChangeHint::None) { appState->GetResourceMap().AppendResource(*resource); } } } } } void CScriptView::OnUpdateIsSCI(CCmdUI *pCmdUI) { pCmdUI->Enable(GetDocument() && (GetDocument()->GetScriptId().Language() == LangSyntaxSCI)); } void CScriptView::OnUpdateAddAs(CCmdUI *pCmdUI) { pCmdUI->Enable(!_contextMenuText.IsEmpty()); } void CScriptView::OnReloadSyntaxColors() { LoadSyntaxHighlightingColors(); Invalidate(); } void CScriptView::OnGotoScriptHeader() { ASSERT(!_gotoScriptText.IsEmpty()); // Search in various folders for the script. appState->OpenScriptHeader((PCSTR)_gotoScriptText); } void CScriptView::OnOpenView() { appState->OpenMostRecentResource(ResourceType::View, _gotoView); } void CScriptView::OnGotoDefinition() { CScriptDocument *pDoc = GetDocument(); if (pDoc) { if (!_helpUrl.IsEmpty()) { // Navigate to that help page. ShellExecute(NULL, "open", _helpUrl, "", "", SW_SHOWNORMAL); } else if (_vocabWordInfo != 0xffffffff) { // Open the vocab to the word requested appState->OpenMostRecentResourceAt(ResourceType::Vocab, appState->GetVersion().MainVocabResource, _vocabWordInfo); } else { // Ensure the script is open (might not be if we did a "compile all") // +1 because line# in crystal-edit-speak starts at 1 appState->OpenScriptAtLine(_gotoScript.GetFullPath(), _gotoLineNumber + 1); } } } void CScriptView::OnInitialUpdate() { __super::OnInitialUpdate(); if (_pACThread) { _pACThread->InitializeForScript(LocateTextBuffer(), GetDocument()->GetScriptId().Language()); } } // // Given a screen coordinate, finds the corresponding point in text coordinates // that would be used for parsing a tooltip. Also returns the point under ptClient. // BOOL CScriptView::_ScreenToWordRight(CPoint ptClient, CPoint &ptUnder, CPoint &ptWordRight) { AdjustTextPoint(ptClient); BOOL fRet = _ClientToTextNoMargin(ptClient, ptUnder); if (fRet) { // Move to the end of the word to the right. ptWordRight = WordToRight(ptUnder); } return fRet; } void CScriptView::_TriggerHoverTipParse(CPoint pt) { if (appState->AreHoverTipsEnabled() && _hoverTipScheduler) { _lastHoverTipParse = _hoverTipScheduler->SubmitTask( this->GetSafeHwnd(), UWM_HOVERTIPREADY, make_unique<HoverTipPayload>(GetDocument()->GetScriptId(), LocateTextBuffer(), pt), [](ITaskStatus &status, HoverTipPayload &payload) { std::unique_ptr<HoverTipResponse> response = std::make_unique<HoverTipResponse>(); response->Location = payload.Location; DoToolTipParse(payload.ScriptId, payload.Stream, payload.Limiter, response->Result); return response; } ); } else { _lastHoverTipParse = -1; } } void CScriptView::_BringUpToolTip(CPoint ptClient) { // Kill any expire id. We don't want an old one coming along and expiring a new tooltip KillTimer(TOOLTIPEXPIRE_ID); if (_pwndToolTip) { CPoint ptUnder, ptToolTipWord; BOOL fInEditableArea = _ScreenToWordRight(ptClient, ptUnder, ptToolTipWord); // If ptUnder == ptToolTipWord, then there's no word under the mouse. if (fInEditableArea && (ptToolTipWord != ptUnder)) { _ptToolTipWord = ptToolTipWord; _TriggerHoverTipParse(_ptToolTipWord); } } } #define SMUDGE_FACTOR 10 // So we can hit test characters at the end of the line. BOOL CScriptView::_ClientToTextNoMargin(CPoint ptClient, CPoint &ptText) { BOOL fRet = FALSE; // We want to fail this operation if the client point is off the end of the line. ptText = ClientToText(ptClient); int nChars = GetLineLength(ptText.y); CPoint ptTest(nChars, ptText.y); CPoint ptClientTest = TextToClient(ptTest); ptClientTest.x += SMUDGE_FACTOR; return (ptClient.x <= ptClientTest.x); } void CScriptView::OnIntellisense() { //assert(_hEventACDone); //assert(_hEventDoAC); if (!appState->IsCodeCompletionEnabled()) { // Nothing to see here... return; } // Set our current position CPoint pt = GetCursorPos(); // And do the autocomplete if (appState->IsCodeCompletionEnabled()) { _pACThread->StartAutoComplete(pt, this->GetSafeHwnd(), UWM_AUTOCOMPLETEREADY, GetDocument()->GetScriptId().GetResourceNumber()); } // Wake up the autocomplete parsecontext, after telling it where we are. //CPoint pt = GetCursorPos(); //_pParseContext->SetCurrentPos(_pStream, _pLimiter, FALSE, LINECHAR2POS(pt.y, pt.x)); //_pParseContext->SetOptions(PARSECONTEXTOPTION_FORAUTOCOMPLETE); // SetEvent(_hEventDoAC); // Wait until it's done. //if (WAIT_OBJECT_0 == WaitForSingleObject(_hEventACDone, INFINITE)) { // We have a result. // ResetEvent(_hEventACDone); // Reset for next time. //AutoCompleteResult &result = _pParseContext->GetResult(); /* if (appState->IsParamInfoEnabled()) { if (result.HasMethodTip()) { // Make it visible. CPoint ptClient = TextToClient(GetCursorPos()); ClientToScreen(&ptClient); ptClient.y -= GetLineHeight() + 2; _pMethodTip->Show(ptClient, result.strMethod, result.strParams, result.cParamNumber); } else { // Hide it. _pMethodTip->Hide(); } }*/ } } BOOL CScriptView::OnACDoubleClick() { BOOL fSomethingWasSelected = FALSE; // In either case, hide the listbox _pAutoComp->Hide(); if (_pAutoComp->GetCurSel() != LB_ERR) { CString strChoice; if (_pAutoComp->GetSelectedText(strChoice)) { fSomethingWasSelected = TRUE; // Put this text in the document. // Delete what the user typed in first, if anything CPoint ptAutoStart = _autoCompleteWordStartPosition; if (ptAutoStart.x >= 0) { if (ptAutoStart != GetCursorPos()) { SetSelection(ptAutoStart, GetCursorPos()); // Then stick the chosen text in. ReplaceSelection(strChoice); } else { // If nothing typed, then jsut insert it. PasteTextAtCursor(strChoice); } // It will be highlighted... so unhighlight it. SetSelection(GetCursorPos(), GetCursorPos()); _pAutoComp->RememberChoice(strChoice); } // else oh well } } return fSomethingWasSelected; } void CScriptView::OnToggleComment() { if (GetDocument() && GetDocument()->GetScriptId().Language() == LangSyntaxSCI) { // This is for SCI Script only. There are no multiline comments, so this helps with that. // Get the current block of code. See if the lines predominatly have comments or not. // Then toggle that. CPoint ptStart, ptEnd; GetSelection(ptStart, ptEnd); // Possibly start at the *next* line so used doesn't have to be exact when selecting text. if ((ptStart.y < ptEnd.y) && (ptStart.x > 0)) { ptStart.y++; ptStart.x = 0; } int isComment = 0; for (int line = ptStart.y; line <= ptEnd.y; line++) { PCSTR pszChars = GetLineChars(line); isComment += (pszChars && pszChars[0] == ';') ? 1 : -1; } if (isComment >= 0) { // Uncomment RemoveFromLines(ptStart.y, ptEnd.y, ';'); } else { // Comment PrependToLines(ptStart.y, ptEnd.y, ";;;"); } } } #if 0 void CScriptView::OnVisualScript() { SCIClassBrowser &browser = appState->GetClassBrowser(); ClassBrowserLock lock(browser); lock.Lock(); std::string fullPath = GetDocument()->GetScriptId().GetFullPath(); const sci::Script *pScript = browser.GetLKGScript(fullPath); CVisualScriptDialog dialog(const_cast<sci::Script *>(pScript), &browser); dialog.DoModal(); } #endif void CScriptView::OnUpdateGotoScriptHeader(CCmdUI *pCmdUI) { if (_gotoScriptText.IsEmpty()) { pCmdUI->Enable(FALSE); } else { pCmdUI->Enable(TRUE); TCHAR szBuffer[MAX_PATH]; StringCchPrintf(szBuffer, ARRAYSIZE(szBuffer), TEXT("Open %s"), (PCTSTR)_gotoScriptText); pCmdUI->SetText(szBuffer); } } void CScriptView::OnUpdateOpenView(CCmdUI *pCmdUI) { if (_gotoView == 0xffff) { pCmdUI->Enable(FALSE); } else { pCmdUI->Enable(TRUE); pCmdUI->SetText(fmt::format("Open view {0}", _gotoView).c_str()); } } void CScriptView::OnUpdateGotoDefinition(CCmdUI *pCmdUI) { if (_gotoDefinitionText.IsEmpty()) { pCmdUI->Enable(FALSE); } else { pCmdUI->Enable(TRUE); TCHAR szBuffer[MAX_PATH]; StringCchPrintf(szBuffer, ARRAYSIZE(szBuffer), TEXT("Go to definition: %s"), (PCTSTR)_gotoDefinitionText); pCmdUI->SetText(szBuffer); } } void CScriptView::HighlightLine(CPoint pt) { int cChars = GetLineLength(pt.y); CPoint ptStart(0, pt.y); CPoint ptEnd(cChars, pt.y); SetSelection(ptStart, ptEnd); SetAnchor(ptStart); } // // Returns the brace balance of a line. If positive, then // there are more ( than ) // int CScriptView::GetParenBalance(int nLineIndex) { assert(nLineIndex >= 0); LPCTSTR pszChars = GetLineChars(nLineIndex); int nLength = GetLineLength(nLineIndex); int nPos = 0; int nBraceCount = 0; BOOL fDontCountQuote = FALSE; int nDontCountCurly = 0; while (nPos < nLength) { switch (pszChars[nPos]) { // Attempt to not count ( ) that are in { } or " // Not quite exact, but good enough. case '{': nDontCountCurly++; break; case '}': nDontCountCurly--; break; case '"': // Not quite exact, but should be good enough. break; } if ((nDontCountCurly == 0) && !fDontCountQuote) { switch (pszChars[nPos]) { case '(': nBraceCount++; break; case ')': if (nBraceCount > 0) { nBraceCount--; } break; } } nPos++; } return nBraceCount; } bool _IsFileChar(char ch) { return isalnum(ch) || ch == '.' || ch == '_'; } // // Puts the name of the header file under the cursor in strHeader. // Returns true if it's a header file. // BOOL CScriptView::GetHeaderFile(CPoint pt, CString &strHeader) { ASSERT_VALIDTEXTPOS(pt); BOOL fRet = FALSE; int nLength = GetLineLength(pt.y); LPCTSTR pszChars = GetLineChars(pt.y); int iEnd = pt.x; if ((iEnd >= 0) && (iEnd < nLength)) { // Forward while ((iEnd < nLength) && _IsFileChar(pszChars[iEnd])) { iEnd++; } int iStart = pt.x; // Backward while ((iStart >= 0) && _IsFileChar(pszChars[iStart])) { iStart--; } iStart++; if (iEnd > iStart) { std::string potentialHeaderName(&pszChars[iStart], iEnd - iStart); if (IsCodeFile(potentialHeaderName)) { // We have a header file. TCHAR szBuf[MAX_PATH]; StringCchCopyN(szBuf, ARRAYSIZE(szBuf), &pszChars[iStart], iEnd - iStart); strHeader = szBuf; fRet = TRUE; } } } return fRet; } void CScriptView::GetSelectedText(CString &text) { CPoint ptStart, ptEnd; GetSelection(ptStart, ptEnd); if (ptStart != ptEnd) { GetText(ptStart, ptEnd, text); } } void CScriptView::OnGoto() { CGotoDialog dialog; if (IDOK == dialog.DoModal()) { int nLine = dialog.GetLineNumber(); nLine = min(GetLineCount(), nLine); nLine--; // 0-based, but dialog is 1 based. nLine = max(0, nLine); int nChar = min(GetLineLength(nLine), GetCursorPos().x); SetCursorPos(CPoint(nChar, nLine)); EnsureVisible(CPoint(nChar, nLine)); } } LRESULT CScriptView::OnHoverTipReady(WPARAM wParam, LPARAM lParam) { if (_hoverTipScheduler) { std::unique_ptr<HoverTipResponse> response = _hoverTipScheduler->RetrieveResponse(_lastHoverTipParse); if (response) { CPoint ptClient = response->Location; if (response && !response->Result.empty()) { // Place the tooltip below the line and a little to the left. CPoint ptTip = ptClient; ptTip.x = max(0, ptTip.x - response->Result.OriginalText.size()); ptTip = TextToClient(ptTip); ptTip.y += GetLineHeight(); CRect rcScript; GetWindowRect(&rcScript); _pwndToolTip->Show(CPoint(rcScript.left + ptTip.x, rcScript.top + ptTip.y), response->Result.strTip); SetTimer(TOOLTIPEXPIRE_ID, TOOLTIPEXPIRE_TIMEOUT, nullptr); } } } return 0; } LRESULT CScriptView::OnAutoCompleteReady(WPARAM wParam, LPARAM lParam) { std::unique_ptr<AutoCompleteResult> result = _pACThread->GetResult(wParam); if (result) { _autoCompleteWordStartPosition = result->OriginalLimit; auto &choices = result->choices; if (choices.size() == 0) { // No results if (_pAutoComp->IsWindowVisible()) { _pAutoComp->Hide(); } } else { if (result->fResultsChanged) { _pAutoComp->UpdateChoices(choices); } // Make it visible (or update size of already visible) CPoint ptClient = TextToClient(GetCursorPos()); ClientToScreen(&ptClient); ptClient.x -= 10; // Just offset a little ptClient.y += GetLineHeight() + 2; // Move it below the lien. _pAutoComp->Show(ptClient); } } return 0; } // CScriptView diagnostics #ifdef _DEBUG void CScriptView::AssertValid() const { CCrystalEditView::AssertValid(); } void CScriptView::Dump(CDumpContext& dc) const { CCrystalEditView::Dump(dc); } CScriptDocument* CScriptView::GetDocument() const // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CScriptDocument))); return static_cast<CScriptDocument*>(m_pDocument); } #endif //_DEBUG // CScriptView message handlers
// C++ for the Windows Runtime vv1.0.170303.6 // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once #include "../base.h" #include "Windows.Foundation.Collections.0.h" #include "Windows.Foundation.1.h" WINRT_EXPORT namespace winrt { namespace ABI::Windows::Foundation::Collections { struct __declspec(uuid("8a43ed9f-f4e6-4421-acf9-1dab2986820c")) __declspec(novtable) IPropertySet : Windows::Foundation::IInspectable { }; } namespace ABI { template <> struct traits<Windows::Foundation::Collections::PropertySet> { using default_interface = Windows::Foundation::Collections::IPropertySet; }; template <> struct traits<Windows::Foundation::Collections::StringMap> { using default_interface = Windows::Foundation::Collections::IMap<hstring, hstring>; }; template <> struct traits<Windows::Foundation::Collections::ValueSet> { using default_interface = Windows::Foundation::Collections::IPropertySet; }; } namespace Windows::Foundation::Collections { template <typename D> struct WINRT_EBO impl_IPropertySet { }; } namespace impl { template <> struct traits<Windows::Foundation::Collections::IPropertySet> { using abi = ABI::Windows::Foundation::Collections::IPropertySet; template <typename D> using consume = Windows::Foundation::Collections::impl_IPropertySet<D>; }; template <> struct traits<Windows::Foundation::Collections::PropertySet> { using abi = ABI::Windows::Foundation::Collections::PropertySet; static constexpr const wchar_t * name() noexcept { return L"Windows.Foundation.Collections.PropertySet"; } }; template <> struct traits<Windows::Foundation::Collections::StringMap> { using abi = ABI::Windows::Foundation::Collections::StringMap; static constexpr const wchar_t * name() noexcept { return L"Windows.Foundation.Collections.StringMap"; } }; template <> struct traits<Windows::Foundation::Collections::ValueSet> { using abi = ABI::Windows::Foundation::Collections::ValueSet; static constexpr const wchar_t * name() noexcept { return L"Windows.Foundation.Collections.ValueSet"; } }; } }
// -*- C++ -*- // // Copyright (C) 1998, 1999, 2000, 2002 Los Alamos National Laboratory, // Copyright (C) 1998, 1999, 2000, 2002 CodeSourcery, LLC // // This file is part of FreePOOMA. // // FreePOOMA is free software; you can redistribute it and/or modify it // under the terms of the Expat license. // // 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 Expat // license for more details. // // You should have received a copy of the Expat license along with // FreePOOMA; see the file LICENSE. // //----------------------------------------------------------------------------- // Class: // DataBrowser // Global Function Templates: // dbprint //----------------------------------------------------------------------------- #ifndef POOMA_DATABROWSER_DATABROWSER_H #define POOMA_DATABROWSER_DATABROWSER_H ////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- // Overview: // // Classes: // // DataBrowser : ??? // // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // // Global Function Templates: // // dbprint() : ??? //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Typedefs: //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Includes: //----------------------------------------------------------------------------- #include "Array/PrintArray.h" #include "DataBrowser/RangeMaker.h" //----------------------------------------------------------------------------- // Forward Declarations: //----------------------------------------------------------------------------- class Inform; // ---------------------------------------------------------------------------- // Prototypes from DataBrowser.cmpl.cpp, needed for linking. // Global PrintArray, for storing persistent formatting parameter set: extern PrintArray dataBrowserPrintArray; // Global functions for setting formatting parameters, stored in // dataBrowserPrintArray: int dbDomainWidth(); void dbSetDomainWidth(int val); int dbDataWidth(); void dbSetDataWidth(int val); int dbDataPrecision(); void dbSetDataPrecision(int val); int dbCarReturn(); void dbSetCarReturn(int val); bool dbScientific(); void dbSetScientific(bool val); int dbSpacing(); void dbSetSpacing(int val); // Global Inform*, for storing address of desired output Inform object: extern Inform *dataBrowserInform; // Global functions for setting dataBrowserInform: void dbSetInform(Inform &inform); void dbSwapInform(); // ---------------------------------------------------------------------------- //----------------------------------------------------------------------------- // // Full Description: // // Classes: // // DataBrowser: // // DataBrowser is a functor class .... // // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // // Global Function Templates: // // dbprint() : .... //----------------------------------------------------------------------------- // General template: no implementation template<class DataBrowserTag> class DataBrowser { public: DataBrowser() { CTAssert(0); } }; // For now, only support IJK-indexable array ASCII output to an Inform stream. // In principle, DataBrowserTag classes could describe other browser types such // as TK windows with spreadsheet-like or pixmap representations. Whether to // use DataBrowser for that or use something else like DataConnect is not yet // resolved. // Tag Class to use for DataBrowserTag representing Array-type ASCII text // output: template<int Dim> class ArrayPrintDataBrowser; // Partial specializations of DataBrowser<ArrayPrintDataBrowser<Dim> > for // specific values of Dim. These are useable for printing values from various // POOMA container types: Arrays, DynamicArrays, and Fields centered on // logically-rectilinear meshes using DiscreteGeometry. template<int Dim> class DataBrowser<ArrayPrintDataBrowser<Dim> > { public: //--------------------------------------------------------------------------- // Exported typedefs and constants // none? // -------------------------------------------------------------------------- // Constructors. // Default ctor. Sets up typical Inform and PrintArray objects. DataBrowser() : inform_m(dataBrowserInform), pa_m() { } // Construct with a container: template<class Container> DataBrowser(const Container &c) : totalDomain_m(c.totalDomain()), view_m(c.totalDomain()), inform_m(dataBrowserInform), pa_m() { } // Construct with a container and another domain to store as a view: template<class Container, class DomainType> DataBrowser(const Container &c, const DomainType &domain) : totalDomain_m(c.totalDomain()), view_m(domain), inform_m(dataBrowserInform), pa_m() { } // -------------------------------------------------------------------------- // Destructor. ~DataBrowser() { }; // -------------------------------------------------------------------------- // Methods. // Print the whole container: template<class Container> void print(const Container &c) { pa_m.print(*inform_m, c); } // Print a view of the whole container: template<class Container, class DomainType> void print(const Container &c, const DomainType &d) { pa_m.print(*inform_m, c, d); } // Set all the formatting parameters from the example PrintArray's values: void setFormatParameters(PrintArray &pa) { pa_m.setFormatParameters(pa); } // Reset the Inform pointer: void setInform(Inform &inform) { inform_m = &inform; } protected: private: // POOMA PrintArray object used for the actual output: PrintArray pa_m; // (Current working) total domain: Range<Dim> totalDomain_m; // (Current working) view domain: Range<Dim> view_m; // POOMA Inform object for output: Inform *inform_m; }; // ---------------------------------------------------------------------------- // // Global Function Templates: // // ---------------------------------------------------------------------------- // Print all elements in the container: template<class Container> void dbprint(const Container &c) { DataBrowser<ArrayPrintDataBrowser<Container::dimensions> > db(c, c.totalDomain()); db.setFormatParameters(dataBrowserPrintArray); db.print(c); } // Print a specified view of elements in the container: template<class Container, class DomainType> void dbprint(const Container &c, const DomainType &domain) { DataBrowser<ArrayPrintDataBrowser<Container::dimensions> > db(c, domain); db.setFormatParameters(dataBrowserPrintArray); db.print(c, domain); } // Print a specified Range<Dim> view of elements in the container, specified // using a list of integers. This requires the RangeMaker monkey business. To // support dimensionalitys 1-7, with sensible numbers of integer arguments for // each, prototypes for 1-21 integer arguments are needed, excluding the // numbers {11,13,16,17,19,20}. template<class Container> void dbprint(const Container &c, const int &i0) { Range<Container::dimensions> domain = RangeMaker<Container::dimensions, 1>()(i0); dbprint(c, domain); } template<class Container> void dbprint(const Container &c, const int &i0, const int &i1) { Range<Container::dimensions> domain = RangeMaker<Container::dimensions, 2>()(i0, i1); dbprint(c, domain); } template<class Container> void dbprint(const Container &c, const int &i0, const int &i1, const int &i2) { Range<Container::dimensions> domain = RangeMaker<Container::dimensions, 3>()(i0, i1, i2); dbprint(c, domain); } template<class Container> void dbprint(const Container &c, const int &i0, const int &i1, const int &i2, const int &i3) { Range<Container::dimensions> domain = RangeMaker<Container::dimensions, 4>()(i0, i1, i2, i3); dbprint(c, domain); } template<class Container> void dbprint(const Container &c, const int &i0, const int &i1, const int &i2, const int &i3, const int &i4) { Range<Container::dimensions> domain = RangeMaker<Container::dimensions, 5>()(i0, i1, i2, i3, i4); dbprint(c, domain); } template<class Container> void dbprint(const Container &c, const int &i0, const int &i1, const int &i2, const int &i3, const int &i4, const int &i5) { Range<Container::dimensions> domain = RangeMaker<Container::dimensions, 6>()(i0, i1, i2, i3, i4, i5); dbprint(c, domain); } template<class Container> void dbprint(const Container &c, const int &i0, const int &i1, const int &i2, const int &i3, const int &i4, const int &i5, const int &i6) { Range<Container::dimensions> domain = RangeMaker<Container::dimensions, 7>()(i0, i1, i2, i3, i4, i5, i6); dbprint(c, domain); } template<class Container> void dbprint(const Container &c, const int &i0, const int &i1, const int &i2, const int &i3, const int &i4, const int &i5, const int &i6, const int &i7) { Range<Container::dimensions> domain = RangeMaker<Container::dimensions, 8>()(i0, i1, i2, i3, i4, i5, i6, i7); dbprint(c, domain); } template<class Container> void dbprint(const Container &c, const int &i0, const int &i1, const int &i2, const int &i3, const int &i4, const int &i5, const int &i6, const int &i7, const int &i8) { Range<Container::dimensions> domain = RangeMaker<Container::dimensions, 9>()(i0, i1, i2, i3, i4, i5, i6, i7, i8); dbprint(c, domain); } template<class Container> void dbprint(const Container &c, const int &i0, const int &i1, const int &i2, const int &i3, const int &i4, const int &i5, const int &i6, const int &i7, const int &i8, const int &i9) { Range<Container::dimensions> domain = RangeMaker<Container::dimensions,10>()(i0, i1, i2, i3, i4, i5, i6, i7, i8, i9); dbprint(c, domain); } template<class Container> void dbprint(const Container &c, const int &i0, const int &i1, const int &i2, const int &i3, const int &i4, const int &i5, const int &i6, const int &i7, const int &i8, const int &i9, const int &i10, const int &i11) { Range<Container::dimensions> domain = RangeMaker<Container::dimensions,12>()(i0, i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11); dbprint(c, domain); } template<class Container> void dbprint(const Container &c, const int &i0, const int &i1, const int &i2, const int &i3, const int &i4, const int &i5, const int &i6, const int &i7, const int &i8, const int &i9, const int &i10, const int &i11, const int &i12, const int &i13) { Range<Container::dimensions> domain = RangeMaker<Container::dimensions,14>()(i0, i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11, i12, i13); dbprint(c, domain); } template<class Container> void dbprint(const Container &c, const int &i0, const int &i1, const int &i2, const int &i3, const int &i4, const int &i5, const int &i6, const int &i7, const int &i8, const int &i9, const int &i10, const int &i11, const int &i12, const int &i13, const int &i14) { Range<Container::dimensions> domain = RangeMaker<Container::dimensions,15>()(i0, i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11, i12, i13, i14); dbprint(c, domain); } template<class Container> void dbprint(const Container &c, const int &i0, const int &i1, const int &i2, const int &i3, const int &i4, const int &i5, const int &i6, const int &i7, const int &i8, const int &i9, const int &i10, const int &i11, const int &i12, const int &i13, const int &i14, const int &i15) { Range<Container::dimensions> domain = RangeMaker<Container::dimensions,16>()(i0, i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11, i12, i13, i14, i15); dbprint(c, domain); } template<class Container> void dbprint(const Container &c, const int &i0, const int &i1, const int &i2, const int &i3, const int &i4, const int &i5, const int &i6, const int &i7, const int &i8, const int &i9, const int &i10, const int &i11, const int &i12, const int &i13, const int &i14, const int &i15, const int &i16, const int &i17) { Range<Container::dimensions> domain = RangeMaker<Container::dimensions,18>()(i0, i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11, i12, i13, i14, i15, i16, i17); dbprint(c, domain); } template<class Container> void dbprint(const Container &c, const int &i0, const int &i1, const int &i2, const int &i3, const int &i4, const int &i5, const int &i6, const int &i7, const int &i8, const int &i9, const int &i10, const int &i11, const int &i12, const int &i13, const int &i14, const int &i15, const int &i16, const int &i17, const int &i18, const int &i19) { Range<Container::dimensions> domain = RangeMaker<Container::dimensions,20>()(i0, i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11, i12, i13, i14, i15, i16, i17, i18, i19); dbprint(c, domain); } template<class Container> void dbprint(const Container &c, const int &i0, const int &i1, const int &i2, const int &i3, const int &i4, const int &i5, const int &i6, const int &i7, const int &i8, const int &i9, const int &i10, const int &i11, const int &i12, const int &i13, const int &i14, const int &i15, const int &i16, const int &i17, const int &i18, const int &i19, const int &i20) { Range<Container::dimensions> domain = RangeMaker<Container::dimensions,21>()(i0, i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11, i12, i13, i14, i15, i16, i17, i18, i19, i20); dbprint(c, domain); } #endif // POOMA_DATABROWSER_DATABROWSER_H // ACL:rcsinfo // ---------------------------------------------------------------------- // $RCSfile: DataBrowser.h,v $ $Author: richard $ // $Revision: 1.6 $ $Date: 2004/11/01 18:16:27 $ // ---------------------------------------------------------------------- // ACL:rcsinfo
#pragma once #include <map> #include <string> using std::map; using std::string; class Asset { public: /*Abstract function, don't call */ virtual bool load( string file ) = 0; /*Abstract function, don't call */ virtual void unload() = 0; }; class Assets { public: /*Load an asset from a file. Returns a pointer to the asset if successful or nullptr if not.*/ template<typename T> T* load( string file ) { T* result = nullptr; map<string,Asset*>::const_iterator it = mAssets.find( file ); if( it != mAssets.end() ) result = (T*)it->second; else { result = new T(); if( !result->load( file ) ) { delete result; result = nullptr; } } return result; } /*Unloads all assets and deletes them.*/ void unload(); Assets& operator=( const Assets& ref ); Assets( const Assets& ref ); Assets(); ~Assets(); private: map<string,Asset*> mAssets; };
#ifndef EXPENSES_H #define EXPENSES_H #include <QWidget> #include <QtSql> #include<QCompleter> #include<QMenuBar> #include<QMenu> #include<QDate> #include<QSqlQuery> #include<QMessageBox> #include<QByteArray> #include<QtNetwork/QNetworkInterface> #include<QBuffer> #include<QFile> #include<QIODevice> #include<QPixmap> #include<QComboBox> #include<QFontComboBox> #include<QTableWidgetItem> #include<QTimer> #include<qtrpt.h> #include<qshortcut.h> namespace Ui { class expenses; } class expenses : public QWidget { Q_OBJECT private slots: void ClearAll(); void set_edit(); void set_unedit(); void save(); void save_print(); void update_time(); void on_tableWidget_cellChanged(int row, int column); void on_save_clicked(); void on_pushButton_4_clicked(); void on_pushButton_5_clicked(); void on_saved_clicked(); void on_delete_rec_clicked(); void on_rec_no_textChanged(const QString &arg1); void on_next_rec_clicked(); void on_back_rec_clicked(); public: explicit expenses(QWidget *parent = nullptr); ~expenses(); private: Ui::expenses *ui; int cur_row; bool saved; QSqlDatabase db; QSqlDatabase db2; QSqlQueryModel *model; QSqlQueryModel *model1; QSqlQueryModel *model2; QSqlQueryModel *model3; QSqlQueryModel *model4; QSqlQueryModel *model5; }; #endif // EXPENSES_H
/** * author : Wang Shaotong * email : wangshaotongsydemon@gmail.com * date : 2020-04-27 * * id : hdu 2111 * name : Saving HDU * url : http://acm.hdu.edu.cn/showproblem.php?pid=2111 * level : 1 * tag : 贪心 */ #include <iostream> #include <algorithm> using namespace std; const int MAXN = 120; class Obj { public: int p, m; }; bool cmp(Obj o1, Obj o2) { return o1.p > o2.p; } int main() { int v, n; while (cin >> v >> n && v != 0) { Obj obj[MAXN]; for (int i = 0; i < n; i++) { cin >> obj[i].p >> obj[i].m; } sort(obj, obj + n, cmp); int ans = 0; for (int i = 0; i < n; i++) { if (v >= obj[i].m) { v -= obj[i].m; ans += obj[i].p * obj[i].m; } else { ans += obj[i].p * v; break; } } cout << ans << endl; } return 0; }
/*============================================================================== Copyright (c) Laboratory for Percutaneous Surgery (PerkLab) Queen's University, Kingston, ON, Canada. All Rights Reserved. See COPYRIGHT.txt or http://www.slicer.org/copyright/copyright.txt for details. 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. This file was originally developed by Kyle Sunderland, PerkLab, Queen's University and was supported through CANARIE's Research Software Program, and Cancer Care Ontario. ==============================================================================*/ #ifndef __vtkMRMLPlusServerLauncherNode_h #define __vtkMRMLPlusServerLauncherNode_h // MRML includes #include <vtkMRMLNode.h> // PlusRemote includes #include "vtkSlicerPlusRemoteModuleMRMLExport.h" // VTK includes #include <vtkCommand.h> class vtkMRMLIGTLConnectorNode; class vtkMRMLPlusServerNode; class vtkMRMLScene; class vtkMRMLTextNode; /// \ingroup IGT /// \brief Parameter set node for the plus remote launcher widget /// class VTK_SLICER_PLUSREMOTE_MODULE_MRML_EXPORT vtkMRMLPlusServerLauncherNode : public vtkMRMLNode { public: static vtkMRMLPlusServerLauncherNode* New(); vtkTypeMacro(vtkMRMLPlusServerLauncherNode, vtkMRMLNode); void PrintSelf(ostream& os, vtkIndent indent) override; // Standard MRML node methods virtual vtkMRMLNode* CreateNodeInstance() override; virtual void ReadXMLAttributes(const char** atts) override; virtual void WriteXML(ostream& of, int indent) override; virtual void Copy(vtkMRMLNode* node) override; virtual const char* GetNodeTagName() override { return "PlusServerLauncher"; } protected: vtkMRMLPlusServerLauncherNode(); virtual ~vtkMRMLPlusServerLauncherNode(); vtkMRMLPlusServerLauncherNode(const vtkMRMLPlusServerLauncherNode&); void operator=(const vtkMRMLPlusServerLauncherNode&); public: static const std::string CONNECTOR_REFERENCE_ROLE; static const std::string PLUS_SERVER_REFERENCE_ROLE; enum { LOG_ERROR = 1, LOG_WARNING = 2, LOG_INFO = 3, LOG_DEBUG = 4, LOG_TRACE = 5, }; enum { ServerAddedEvent = vtkCommand::UserEvent + 701, ServerRemovedEvent, }; /// Get the hostname used to connect to PlusServerLauncher vtkGetMacro(Hostname, std::string); /// Set the hostname used to connect to PlusServerLauncher vtkSetMacro(Hostname, std::string); /// Get the port used to connect to PlusServerLauncher vtkGetMacro(Port, int); /// Set the port used to connect to PlusServerLauncher vtkSetMacro(Port, int); /// Get the log level of the PlusServerLauncher vtkGetMacro(LogLevel, int); /// Set the log level of the PlusServerLauncher vtkSetMacro(LogLevel, int); // Create a server node using the configFileNode and set the desired state to ON vtkMRMLPlusServerNode* StartServer(vtkMRMLTextNode* configFileNode, int logLevel = LOG_INFO); /// Get the connector node for the PlusServerLauncher vtkMRMLIGTLConnectorNode* GetConnectorNode(); /// Set and observe the connector node for the PlusServerLauncher void SetAndObserveConnectorNode(vtkMRMLIGTLConnectorNode* node); /// Add and observe a server node. This will also set the launcher node of the server node. void AddAndObserveServerNode(vtkMRMLPlusServerNode* serverNode); /// Remove the server reference and observers. THis will also remove the launcher from the server node. void RemoveServerNode(vtkMRMLPlusServerNode* serverNode); /// Returns a list of all server node references for this launcher node std::vector<vtkMRMLPlusServerNode*> GetServerNodes(); private: std::string Hostname; int Port; int LogLevel; }; #endif // __vtkMRMLPlusServerLauncherNode_h
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QFile> #include <QTextStream> #include "basic_types.h" #include "messages.h" #include "sdfiles.h" #include <QDebug> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_clicked() { QFile file("C:\\Users\\wurenji.ZKXS\\Desktop\\HYL.txt"); //QFile file("G:\\SIASUN.txt"); QByteArray b; QList<QByteArray> arrayList; if(!file.open(QIODevice::ReadOnly)) { qDebug()<<"can't open"; return; } else { // 用"\r\n"即0d0a分行,每一行存储一个数据结构,见sdfiles.h b = file.readAll(); QByteArray turn("\r\n",2); int len = turn.length(); int start = 0; int end = b.indexOf(turn,start); while(end != -1) { arrayList<<b.mid(start,(end-start)); start = end + len; end = b.indexOf(turn,start); } //qDebug()<<arrayList.count(); } for(int i = 0;i<arrayList.size();i++) { //读取每一行的数据 const char* logData = arrayList.at(i).data(); //第一个字节为message_id qDebug()<<QString::number(*logData); // 2为gpsRaw_t if(*logData == 2) { logData ++; gpsRaw_t* gps = (gpsRaw_t*)logData; qDebug()<<gps->alt<<gps->sat; } //1为marg_t (imu) else if(*logData == 1) { logData ++; marg_t* imu = (marg_t*)logData; qDebug()<<imu->acc.x<<imu->acc.y<<imu->acc.z; } } }
#include <math.h> #include <conio.h> #include <stdio.h> #include <locale.h> #include <stdlib.h> #include <string.h> void calcula (int *x, int *y, int *z) { *z = *x + *y; printf ("Primeiro número: %d\nSegundo número: %d\nSoma: %d", *x, *y, *z); } int main (void) { setlocale (LC_ALL, "Portuguese"); int Num1 = 5, Num2 = 7, Soma = 0; calcula (&Num1, &Num2, &Soma); getch(); return 0; }
/*************************************************************************** Copyright (c) 2020 Philip Fortier 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 "stdafx.h" #include "ClassBrowser.h" #include "ScriptOMAll.h" #include "CrystalScriptStream.h" #include "SyntaxParser.h" #include "SyntaxContext.h" #include "CodeAutoComplete.h" #include "AppState.h" #include "format.h" using namespace sci; using namespace std; bool SyntaxParser_ParseAC(sci::Script &script, CCrystalScriptStream::const_iterator &streamIt, std::unordered_set<std::string> preProcessorDefines, SyntaxContext *pContext); AutoCompleteChoice::AutoCompleteChoice() { _iIcon = AutoCompleteIconIndex::Unknown; } AutoCompleteChoice::AutoCompleteChoice(const std::string &text, AutoCompleteIconIndex iIcon) { _strLower = text; std::transform(_strLower.begin(), _strLower.end(), _strLower.begin(), ::tolower); _strText = text; _iIcon = iIcon; } AutoCompleteChoice::AutoCompleteChoice(const std::string &text, const std::string &lower, AutoCompleteIconIndex iIcon) { _strText = text; _strLower = lower, _iIcon = iIcon; } const std::string &AutoCompleteChoice::GetText() const { return _strText; } const std::string &AutoCompleteChoice::GetLower() const { return _strLower; } AutoCompleteIconIndex AutoCompleteChoice::GetIcon() const { return _iIcon; } bool operator<(const AutoCompleteChoice &one, const AutoCompleteChoice &two) { return one.GetLower() < two.GetLower(); } template<typename _TCollection, typename _TNameFunc> void MergeResults(std::vector<AutoCompleteChoice> &existingResults, const std::string &prefixLower, AutoCompleteIconIndex icon, _TCollection &items, _TNameFunc nameFunc) { std::vector<AutoCompleteChoice> newResults; for (auto &item : items) { std::string name = nameFunc(item); std::string lower = name; std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); if (0 == lower.compare(0, prefixLower.size(), prefixLower)) { newResults.emplace_back(name, lower, icon); } } if (!newResults.empty()) { std::sort(newResults.begin(), newResults.end()); std::vector<AutoCompleteChoice> tempResults; tempResults.reserve(newResults.size() + existingResults.size()); std::merge(existingResults.begin(), existingResults.end(), newResults.begin(), newResults.end(), back_inserter(tempResults)); std::swap(tempResults, existingResults); } } void MergeResults(std::vector<AutoCompleteChoice> &existingResults, const std::string &prefix, AutoCompleteIconIndex icon, const std::vector<std::string> &items) { return MergeResults(existingResults, prefix, icon, items, [](const std::string text) { return text; }); } std::unique_ptr<AutoCompleteResult> GetAutoCompleteResult(const std::string &prefixIn, uint16_t scriptNumber, SyntaxContext &context, std::unordered_set<std::string> &parsedCustomHeaders) { // Use the scriptNumber provided instead of that in the SyntaxContext's script, because we may not have reached the scriptNumber declaration in the script yet. std::string prefix = prefixIn; std::transform(prefix.begin(), prefix.end(), prefix.begin(), ::tolower); std::unique_ptr<AutoCompleteResult> result = std::make_unique<AutoCompleteResult>(); if (!prefix.empty()) { auto acContexts = context.GetParseAutoCompleteContext(); //OutputDebugString(fmt::format("ParseContext: {}\n", (int)acContext).c_str()); AutoCompleteSourceType sourceTypes = AutoCompleteSourceType::None; for (auto acContext : acContexts) { switch (acContext) { case ParseAutoCompleteContext::Selector: sourceTypes |= AutoCompleteSourceType::Selector; break; case ParseAutoCompleteContext::ClassSelector: sourceTypes |= AutoCompleteSourceType::ClassSelector; break; case ParseAutoCompleteContext::TopLevelKeyword: sourceTypes |= AutoCompleteSourceType::TopLevelKeyword; break; case ParseAutoCompleteContext::PureValue: sourceTypes |= AutoCompleteSourceType::ClassName | AutoCompleteSourceType::Variable | AutoCompleteSourceType::Define | AutoCompleteSourceType::ClassSelector | AutoCompleteSourceType::Instance; break; case ParseAutoCompleteContext::StartStatementExtras: // Also keywords, but we add those later. sourceTypes |= AutoCompleteSourceType::Kernel | AutoCompleteSourceType::Procedure; break; case ParseAutoCompleteContext::StudioValue: sourceTypes |= AutoCompleteSourceType::ClassName | AutoCompleteSourceType::Variable | AutoCompleteSourceType::Define | AutoCompleteSourceType::Kernel | AutoCompleteSourceType::Procedure | AutoCompleteSourceType::ClassSelector | AutoCompleteSourceType::Instance; break; case ParseAutoCompleteContext::LValue: sourceTypes |= AutoCompleteSourceType::Variable | AutoCompleteSourceType::ClassSelector; break; case ParseAutoCompleteContext::DefineValue: sourceTypes |= AutoCompleteSourceType::Define; break; case ParseAutoCompleteContext::SuperClass: sourceTypes |= AutoCompleteSourceType::ClassName; break; case ParseAutoCompleteContext::ScriptName: sourceTypes |= AutoCompleteSourceType::ScriptName; break; default: // Other things handled below break; } } // Get things from the big global list SCIClassBrowser &browser = appState->GetClassBrowser(); if (sourceTypes != AutoCompleteSourceType::None) { browser.GetAutoCompleteChoices(prefix, sourceTypes, result->choices); } // Now get things from the local script // First, ensure any headers that we've encountered are parsed for (const string &include : context.Script().GetIncludes()) { if (parsedCustomHeaders.find(include) == parsedCustomHeaders.end()) { // Tell the class browser to pull this in. This could take some time, but the class browser // isn't locked during most of this time. browser.TriggerCustomIncludeCompile(include); parsedCustomHeaders.insert(include); } } // Grab variables and defines from included headers if (IsFlagSet(sourceTypes, AutoCompleteSourceType::Variable | AutoCompleteSourceType::Define)) { // Let's through sizeof in here too... MergeResults(result->choices, prefix, AutoCompleteIconIndex::Keyword, { "&sizeof" }); ClassBrowserLock browserLock(browser); browserLock.Lock(); for (const std::string &headerName : parsedCustomHeaders) { sci::Script *headerScript = browser.GetCustomHeader(headerName); if (headerScript) { if (IsFlagSet(sourceTypes, AutoCompleteSourceType::Variable)) { MergeResults(result->choices, prefix, AutoCompleteIconIndex::Variable, headerScript->GetScriptVariables(), [](const std::unique_ptr<VariableDecl> &theVar) { return theVar->GetName(); } ); } if (IsFlagSet(sourceTypes, AutoCompleteSourceType::Define)) { MergeResults(result->choices, prefix, AutoCompleteIconIndex::Define, headerScript->GetDefines(), [](const std::unique_ptr<Define> &theDefine) { return theDefine->GetName(); } ); } } } } if (IsFlagSet(sourceTypes, AutoCompleteSourceType::Procedure)) { // non-public procedures in this script (public ones are already included in the global list) ClassBrowserLock browserLock(browser); browserLock.Lock(); const Script *thisScript = browser.GetLKGScript(scriptNumber); if (thisScript) { std::vector<std::string> procNames; for (auto &theProc : thisScript->GetProcedures()) { if (!theProc->IsPublic()) { procNames.push_back(theProc->GetName()); } } MergeResults(result->choices, prefix, AutoCompleteIconIndex::Procedure, procNames); } } if (IsFlagSet(sourceTypes, AutoCompleteSourceType::Instance)) { // Instances in this script ClassBrowserLock browserLock(browser); browserLock.Lock(); const Script *thisScript = browser.GetLKGScript(scriptNumber); if (thisScript) { std::vector<std::string> instanceNames; for (auto &theClass : thisScript->GetClasses()) { if (theClass->IsInstance()) { instanceNames.push_back(theClass->GetName()); } } MergeResults(result->choices, prefix, AutoCompleteIconIndex::Class, instanceNames); } } if (IsFlagSet(sourceTypes, AutoCompleteSourceType::Variable)) { ClassBrowserLock browserLock(browser); browserLock.Lock(); const Script *thisScript = browser.GetLKGScript(scriptNumber); if (thisScript) { // Script variables MergeResults(result->choices, prefix, AutoCompleteIconIndex::Variable, thisScript->GetScriptVariables(), [](const std::unique_ptr<VariableDecl> &theVar) { return theVar->GetName(); } ); // Script strings MergeResults(result->choices, prefix, AutoCompleteIconIndex::Variable, thisScript->GetScriptStringsDeclarations(), [](const std::unique_ptr<VariableDecl> &theVar) { return theVar->GetName(); } ); if (context.FunctionPtr) { MergeResults(result->choices, prefix, AutoCompleteIconIndex::Variable, context.FunctionPtr->GetVariables(), [](const std::unique_ptr<VariableDecl> &theVar) { return theVar->GetName(); }); if (!context.FunctionPtr->GetSignatures().empty()) { MergeResults(result->choices, prefix, AutoCompleteIconIndex::Variable, context.FunctionPtr->GetSignatures()[0]->GetParams(), [](const std::unique_ptr<FunctionParameter> &theVar) { return theVar->GetName(); }); } } } } // Property selectors for the *current* class if (IsFlagSet(sourceTypes, AutoCompleteSourceType::ClassSelector) && context.ClassPtr) { ClassBrowserLock browserLock(browser); browserLock.Lock(); std::string species = context.ClassPtr->IsInstance() ? context.ClassPtr->GetSuperClass() : context.ClassPtr->GetName(); auto properties = browser.CreatePropertyArray(species); MergeResults(result->choices, prefix, AutoCompleteIconIndex::Variable, *properties, [](const ClassProperty *classProp) { return classProp->GetName(); } ); } if (IsFlagSet(sourceTypes, AutoCompleteSourceType::Define)) { // Local script defines ClassBrowserLock browserLock(browser); browserLock.Lock(); const Script *thisScript = browser.GetLKGScript(scriptNumber); if (thisScript) { MergeResults(result->choices, prefix, AutoCompleteIconIndex::Define, thisScript->GetDefines(), [](const std::unique_ptr<Define> &theDefine) { return theDefine->GetName(); } ); } } if (containsV(acContexts, ParseAutoCompleteContext::Export)) { ClassBrowserLock browserLock(browser); browserLock.Lock(); const Script *thisScript = browser.GetLKGScript(scriptNumber); if (thisScript) { MergeResults(result->choices, prefix, AutoCompleteIconIndex::Procedure, thisScript->GetProcedures(), [](const std::unique_ptr<ProcedureDefinition> &proc) { return proc->GetName(); } ); MergeResults(result->choices, prefix, AutoCompleteIconIndex::Procedure, thisScript->GetClasses(), [](const std::unique_ptr<ClassDefinition> &proc) { return proc->IsInstance() ? proc->GetName() : ""; // Classes can't be exports. } ); } } // Some weird special cases. if (containsV(acContexts, ParseAutoCompleteContext::Temp)) { MergeResults(result->choices, prefix, AutoCompleteIconIndex::Keyword, { "&tmp" } ); } if (containsV(acContexts, ParseAutoCompleteContext::Rest)) { MergeResults(result->choices, prefix, AutoCompleteIconIndex::Keyword, { "&rest" }); } if (containsV(acContexts, ParseAutoCompleteContext::Else)) { MergeResults(result->choices, prefix, AutoCompleteIconIndex::Keyword, { "else" }); } if (containsV(acContexts, ParseAutoCompleteContext::DefineValue)) { MergeResults(result->choices, prefix, AutoCompleteIconIndex::Keyword, { "scriptNumber" }); } LangSyntax lang = context.Script().Language(); if (containsV(acContexts, ParseAutoCompleteContext::TopLevelKeyword)) { MergeResults(result->choices, prefix, AutoCompleteIconIndex::Keyword, GetTopLevelKeywords(lang)); } if (containsV(acContexts, ParseAutoCompleteContext::ClassLevelKeyword)) { MergeResults(result->choices, prefix, AutoCompleteIconIndex::Keyword, GetClassLevelKeywords(lang)); } if (containsV(acContexts, ParseAutoCompleteContext::StudioValue)) { MergeResults(result->choices, prefix, AutoCompleteIconIndex::Keyword, GetCodeLevelKeywords(lang)); } if (containsV(acContexts, ParseAutoCompleteContext::StartStatementExtras)) { MergeResults(result->choices, prefix, AutoCompleteIconIndex::Keyword, GetCodeLevelKeywords(lang)); } if (containsV(acContexts, ParseAutoCompleteContext::PureValue)) { MergeResults(result->choices, prefix, AutoCompleteIconIndex::Keyword, GetValueKeywords(lang)); } // Possible de-dupe // vec.erase(unique(vec.begin(), vec.end()), vec.end()); result->fResultsChanged = true; // TODO } return result; } AutoCompleteThread2::AutoCompleteThread2() : _nextId(0), _instruction(AutoCompleteInstruction::None), _bgStatus(AutoCompleteStatus::Pending), _lang(LangSyntaxUnknown), _bufferUI(nullptr) { _thread = std::thread(s_ThreadWorker, this); } AutoCompleteThread2::~AutoCompleteThread2() { { std::lock_guard<std::mutex> lock(_mutex); _instruction = AutoCompleteInstruction::Abort; } _condition.notify_one(); _thread.join(); } void AutoCompleteThread2::InitializeForScript(CCrystalTextBuffer *buffer, LangSyntax lang) { _bufferUI = buffer; _lang = lang; // TODO: Cancel any parsing? Or I guess it really doesn't matter. Except that if a script is closed, we want to know, so we don't send message to non-existent hwnd. } #define EXTRA_AC_CHARS 100 void AutoCompleteThread2::StartAutoComplete(CPoint pt, HWND hwnd, UINT message, uint16_t scriptNumber) { // Take note if the background thread is potentially ready to continue parsing from where it left off. bool bgIsWaiting; { std::lock_guard<std::mutex> lock(_mutex); bgIsWaiting = (_bgStatus == AutoCompleteStatus::WaitingForMore) || (_bgStatus == AutoCompleteStatus::Parsing); } if (bgIsWaiting && (_lastHWND == hwnd) && (pt.y == _lastPoint.y) && (pt.x > _lastPoint.x)) { // Continue an existing parse. CString strText; _bufferUI->GetText(_lastPoint.y, _lastPoint.x, pt.y, pt.x, strText); { std::lock_guard<std::mutex> lock(_mutex); _additionalCharacters += (PCSTR)strText; //OutputDebugString(fmt::format("UI: Continue parse with {0}\n", (PCSTR)strText).c_str()); _instruction = AutoCompleteInstruction::Continue; } _condition.notify_one(); } else { // Now start a fresh parse // Make a copy of the text buffer std::unique_ptr<CScriptStreamLimiter> limiter = std::make_unique<CScriptStreamLimiter>(_bufferUI, pt, EXTRA_AC_CHARS); //limiter->Limit(LineCol(pt.y, pt.x)); std::unique_ptr<CCrystalScriptStream> stream = std::make_unique<CCrystalScriptStream>(limiter.get()); //OutputDebugString(fmt::format("UI: Start new parse at {0},{1}\n", pt.x, pt.y).c_str()); // Give the work to the background thread { std::lock_guard<std::mutex> lock(_mutex); _additionalCharacters.clear(); _limiterPending = move(limiter); _streamPending = move(stream); _scriptNumberPending = scriptNumber; _id.hwnd = hwnd; _id.id = _nextId; _id.message = message; _instruction = AutoCompleteInstruction::Restart; } _condition.notify_one(); } _nextId++; _lastHWND = hwnd; _lastPoint = pt; } void AutoCompleteThread2::ResetPosition() { _lastHWND = nullptr; _lastPoint = CPoint(); { std::lock_guard<std::mutex> lock(_mutex); _limiterPending.reset(nullptr); _streamPending.reset(nullptr); _id.hwnd = nullptr; _id.id = -1; _additionalCharacters = ""; _instruction = AutoCompleteInstruction::Restart; } _condition.notify_one(); } CPoint AutoCompleteThread2::GetCompletedPosition() { return _lastPoint; } std::unique_ptr<AutoCompleteResult> AutoCompleteThread2::GetResult(int id) { std::unique_ptr<AutoCompleteResult> result; { std::lock_guard<std::mutex> lock(_mutexResult); if (_resultId == id) { result = move(_result); } } return result; } UINT AutoCompleteThread2::s_ThreadWorker(void *pParam) { (reinterpret_cast<AutoCompleteThread2*>(pParam))->_DoWork(); return 0; } void AutoCompleteThread2::_SetResult(std::unique_ptr<AutoCompleteResult> result, AutoCompleteThread2::AutoCompleteId id) { { std::lock_guard<std::mutex> lock(_mutexResult); _resultId = id.id; _result = move(result); } SendMessage(id.hwnd, id.message, id.id, 0); } void AutoCompleteThread2::_DoWork() { while (_instruction != AutoCompleteInstruction::Abort) { std::unique_lock<std::mutex> lock(_mutex); if (_instruction == AutoCompleteInstruction::Abort) { // Important to ask this in the lock. break; } _condition.wait(lock, [&]() { return this->_instruction != AutoCompleteInstruction::None; }); while (_instruction == AutoCompleteInstruction::Restart) { _instruction = AutoCompleteInstruction::None; std::unique_ptr<CScriptStreamLimiter> limiter = move(_limiterPending); std::unique_ptr<CCrystalScriptStream> stream = move(_streamPending); _bgStatus = AutoCompleteStatus::Parsing; if (!this->_additionalCharacters.empty()) { // It's possible the UI thread saw we were parsing, and so it // just placed some additional characters in the buffer. But we then // failed to parse, so we're restarting. There's no way that we'll // succeed parsing though, so let's jus fail limiter = nullptr; stream = nullptr; _bgStatus = AutoCompleteStatus::Pending; } uint16_t scriptNumber = _scriptNumberPending; AutoCompleteId id = _id; // Unlock before we do expensive stuff lock.unlock(); if (limiter) { assert(id.hwnd); class AutoCompleteParseCallback : public ISyntaxParserCallback { public: AutoCompleteParseCallback(uint16_t scriptNumber, SyntaxContext &context, AutoCompleteThread2 &ac, CScriptStreamLimiter &limiter, AutoCompleteId id) : _context(context), _id(id), _ac(ac), _limiter(limiter), _scriptNumber(scriptNumber) {} bool Done() { std::string word = _limiter.GetLastWord(); // Figure out the result std::unique_ptr<AutoCompleteResult> result = GetAutoCompleteResult(word, _scriptNumber, _context, _parsedCustomHeaders); result->OriginalLimit = _limiter.GetLimit(); result->OriginalLimit.x -= word.length(); result->OriginalLimit.x = max(result->OriginalLimit.x, 0); _ac._SetResult(move(result), _id); std::unique_lock<std::mutex> lock(_ac._mutex); _ac._bgStatus = AutoCompleteStatus::WaitingForMore; _ac._condition.wait(lock, [&]() { return this->_ac._instruction != AutoCompleteInstruction::None; }); // There is a small race condition between here.... bool continueParsing = (_ac._instruction == AutoCompleteInstruction::Continue); // We need to set this to none now that we've received the orders, assuming this wasn't an abort if (_ac._instruction != AutoCompleteInstruction::Abort) { _ac._instruction = AutoCompleteInstruction::None; } std::string additionalCharacters; if (continueParsing) { _ac._bgStatus = AutoCompleteStatus::Parsing; additionalCharacters = _ac._additionalCharacters; _ac._additionalCharacters = ""; _limiter.Extend(additionalCharacters); //OutputDebugString(fmt::format("BG: Continuing parse with {0}\n", additionalCharacters).c_str()); } else { _ac._bgStatus = AutoCompleteStatus::Pending; //OutputDebugString(fmt::format("BG: Bailing out from parse\n").c_str()); } return continueParsing; // false -> bail } private: uint16_t _scriptNumber; SyntaxContext &_context; AutoCompleteId _id; AutoCompleteThread2 &_ac; CScriptStreamLimiter &_limiter; std::unordered_set<std::string> _parsedCustomHeaders; }; ScriptId scriptId; scriptId.SetLanguage(_lang); sci::Script script(scriptId); // Needed to get the language right. CCrystalScriptStream::const_iterator it(limiter.get()); SyntaxContext context(it, script, PreProcessorDefinesFromSCIVersion(appState->GetVersion()), false, false); #ifdef PARSE_DEBUG context.ParseDebug = true; #endif AutoCompleteParseCallback callback(scriptNumber, context, *this, *limiter, id); limiter->SetCallback(&callback); bool result = SyntaxParser_ParseAC(script, it, PreProcessorDefinesFromSCIVersion(appState->GetVersion()), &context); } else { break; // Go back to waiting } lock.lock(); _bgStatus = AutoCompleteStatus::Pending; } } }
//************************************************************************** //** //** See jlquake.txt for copyright info. //** //** This program is free software; you can redistribute it and/or //** modify it under the terms of the GNU General Public License //** as published by the Free Software Foundation; either version 3 //** of the License, or (at your option) any later version. //** //** This program is distributed in the hope that it will be useful, //** but WITHOUT ANY WARRANTY; without even the implied warranty of //** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //** included (gnu.txt) GNU General Public License for more details. //** //************************************************************************** #ifndef __idCommon__ #define __idCommon__ #include "qcommon.h" #include <setjmp.h> class idCommon : public Interface { public: // Prints message to the console, which may cause a screen update. virtual void Printf( const char* format, ... ) id_attribute( ( format( printf, 2, 3 ) ) ) = 0; // Prints message that only shows up if the "developer" cvar is set, virtual void DPrintf( const char* format, ... ) id_attribute( ( format( printf, 2, 3 ) ) ) = 0; // Issues a C++ throw. Normal errors just abort to the game loop, // which is appropriate for media or dynamic logic errors. virtual void Error( const char* format, ... ) id_attribute( ( format( printf, 2, 3 ) ) ) = 0; // Fatal errors quit all the way to a system dialog box, which is appropriate for // static internal errors or cases where the system may be corrupted. virtual void FatalError( const char* format, ... ) id_attribute( ( format( printf, 2, 3 ) ) ) = 0; virtual void EndGame( const char* format, ... ) id_attribute( ( format( printf, 2, 3 ) ) ) = 0; virtual void ServerDisconnected( const char* format, ... ) id_attribute( ( format( printf, 2, 3 ) ) ) = 0; virtual void Disconnect( const char* format, ... ) id_attribute( ( format( printf, 2, 3 ) ) ) = 0; }; extern idCommon* common; extern char com_errorMessage[ MAXPRINTMSG ]; extern jmp_buf abortframe; #endif
// Time complexity: O(log(n)) #include <iostream> using namespace std; int main() { int n = 0; cin >> n; int a = 0, i = n; while (i >= 1) { a = a + 1; i /= 2; } return 0; }
#include "board.h" #include "boardchesspiece.h" #include <iostream> using namespace std; board::board() { // set W values for (int h = 0; h <= 1; h++) { for (int w = 0; w <= 7; w++) { cboard[w][h].x = 'W'; } } // set B values for (int h = 6; h <= 7; h++) { for (int w = 0; w <= 7; w++) { cboard[w][h].x = 'B'; } } //set individual values; //rook cboard[0][0].y = 'R'; cboard[7][0].y = 'R'; cboard[0][7].y = 'R'; cboard[7][7].y = 'R'; //knight cboard[1][0].y = 'N'; cboard[6][0].y = 'N'; cboard[1][7].y = 'N'; cboard[6][7].y = 'N'; //bishop cboard[2][0].y = 'B'; cboard[5][0].y = 'B'; cboard[2][7].y = 'B'; cboard[5][7].y = 'B'; //queen cboard[3][0].y = 'Q'; cboard[3][7].y = 'Q'; //king cboard[4][0].y = 'K'; cboard[4][7].y = 'K'; //pawns for (int w = 0; w <= 7; w++) { cboard[w][1].y = 'P'; } for (int w = 0; w <= 7; w++) { cboard[w][6].y = 'P'; } } board::~board() { } void board::printboard() { for (int h = 0; h <= 7; h++) { cout << "-------------------------" << endl << "|"; for (int w = 0; w <= 7; w++) { cout << cboard[w][h].x; cout << cboard[w][h].y << "|"; } cout << " " << h+1 << endl; } cout << "-------------------------" << endl << " 1 2 3 4 5 6 7 8 " << endl; } void board::movepiece(int ox, int oy, int nx, int ny) { //assign new square cboard[nx][ny].x = cboard[ox][oy].x; cboard[nx][ny].y = cboard[ox][oy].y; //set original square to clear cboard[ox][oy].x = ' '; cboard[ox][oy].y = ' '; } bool board::moveislegal(int ox, int oy, int nx, int ny, int player) { if (cboard[ox][oy].x == ' ') { cout << "There's nothing there, silly goose." << endl; return false; } else if (cboard[ox][oy].x == 'W' && player == 2) { cout << "Thats not yours!!!" << endl; return false; } else if (cboard[ox][oy].x == 'B' && player == 1) { cout << "Thats not yours!!!" << endl; return false; } else if (ox - nx == 0 && oy - ny == 0) { cout << "You have to move." << endl; return false; } else if (cboard[ox][oy].x == cboard[nx][ny].x) { cout << "No friendly fire." << endl; return false; } else if (cboard[nx][ny].y == 'K') { cout << "The king cannot fall!" << endl; return false; } //rook rules else if (cboard[ox][oy].y == 'R') { if (ox - nx == 0 || oy - ny == 0) { if (notobstructed(ox, oy, nx, ny)) return true; else { cout << "This piece is obstructed and connot move to selected square" << endl; return false; } } else { cout << "This piece cannot move to that square." << endl; return false; } } //pawn rules else if (cboard[ox][oy].y == 'P') { if (cboard[ox][oy].x == 'W') { if (ny - oy == 1 && ox - nx == 0) { if (notobstructed(ox, oy, nx, ny)) return true; else { cout << "This piece is obstructed and connot move to selected square" << endl; return false; } } else if (ny - oy == 1 && abs(ox - nx) == 1) { if (cboard[nx][ny].x == 'B') { return true; } else return false; } } if (cboard[ox][oy].x == 'B') { if (oy - ny == 1 && ox - nx == 0) { if (notobstructed(ox, oy, nx, ny)) return true; else { cout << "This piece is obstructed and connot move to selected square" << endl; return false; } } else if (oy - ny == 1 && abs(ox - nx) == 1) { if (cboard[nx][ny].x == 'W') { return true; } else return false; } else return false; } else { cout << "This piece cannot move to that square." << endl; return false; } } // knight rules else if (cboard[ox][oy].y == 'N') { if (abs(ox - nx) == 1 && abs(oy - ny) == 2) return true; else if (abs(ox - nx) == 2 && abs(oy - ny) == 1) return true; else return false; } //bishop rules else if (cboard[ox][oy].y == 'B') { if (abs(ox - nx) == abs(oy - ny)) { if (notobstructed(ox, oy, nx, ny)) return true; else { cout << "This piece is obstructed and connot move to selected square" << endl; return false; } } else { cout << "This piece cannot move to that square." << endl; return false; } } //king rules if (cboard[ox][oy].y == 'K') { if (abs(ox - nx) <= 1 && abs(oy - ny) <= 1) { return true; } else return false; } //queen rules if (cboard[ox][oy].y == 'Q') { if (ox - nx == 0 || oy - ny == 0) { cboard[ox][oy].y = 'R'; if (notobstructed(ox, oy, nx, ny)) { cboard[ox][oy].y = 'Q'; return true; } else { cout << "This piece is obstructed and connot move to selected square" << endl; cboard[ox][oy].y = 'Q'; return false; } } else if (abs(ox - nx) == abs(oy - ny)) { cboard[ox][oy].y = 'B'; if (notobstructed(ox, oy, nx, ny)){ cboard[ox][oy].y = 'Q'; return true; } else { cout << "This piece is obstructed and connot move to selected square" << endl; cboard[ox][oy].y = 'Q'; return false; } } else { cout << "This piece cannot move to that square." << endl; return false; } } //all checks complete. else return true; } bool board::notobstructed(int ox, int oy, int nx, int ny) { //rook rules if (cboard[ox][oy].y == 'R') { //cout << cboard[ox][oy].y; if (ox - nx == 0) { if (oy < ny) { for (int h = oy+1; h < ny; h++) { if (cboard[ox][h].y != ' ') return false; } return true; } else { for (int h = oy-1; h > ny; h--) { if (cboard[ox][h].y != ' ') return false; } return true; } } else if (oy - ny == 0) { if (ox < nx) { for (int w = ox+1; w < nx; w++) { if (cboard[w][oy].y != ' ') return false; } return true; } else { for (int w = ox-1; w > nx; w--) { if (cboard[w][oy].y != ' ') return false; } return true; } } } //pawn rules if (cboard[ox][oy].y == 'P') { if (cboard[nx][ny].y == ' ') return true; else return false; } //bishop rules if (cboard[ox][oy].y == 'B') { //cout << cboard[ox][oy].y; if (nx - ox > 0 && ny - oy > 0) { for (int h = 1; h < ny - oy; h++) { if (cboard[ox + h][oy + h].y != ' ') return false; } } else if (nx - ox > 0 && ny - oy < 0) { for (int h = 1; h < nx - ox; h++) { if (cboard[ox + h][oy - h].y != ' ') return false; } } else if (nx - ox < 0 && ny - oy > 0) { for (int h = 1; h < ny - oy; h++) { if (cboard[ox - h][oy + h].y != ' ') return false; } } else if (nx - ox < 0 && ny - oy < 0) { for (int h = 1; h < abs(ny - oy); h++) { if (cboard[ox - h][oy - h].y != ' ') return false; } } else return true; } //all checks complete. else { //cout << cboard[ox][oy].y; return true; } }; char board::kingnottaken(int nx, int ny) { if (cboard[nx][ny].y == 'K') return 'n'; else return 'y'; }
/*************************************************************************** # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of NVIDIA CORPORATION 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 "AS IS" AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY # OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **************************************************************************/ #include "stdafx.h" #include "ImageIO.h" #include "DirectXTex.h" #include <filesystem> namespace Falcor { namespace { /** Wrapper around DirectXTex image containers because there are separate API calls for each type. */ struct ApiImage { /** If true, Image is holding the data. Otherwise data is in ScratchImage. */ bool isSingleImage() const { return image.pixels != nullptr; } /** Get the DXGI Format of the image. */ DXGI_FORMAT getFormat() const { return isSingleImage() ? image.format : scratchImage.GetMetadata().format; } // Single Raw Bitmap DirectX::Image image = {}; // One or more images with metadata and managed memory. DirectX::ScratchImage scratchImage; }; struct ImportData { // The full path of the file that was found in data directories std::string fullpath; // Commonly used values converted or casted for cleaner access ResourceFormat format; uint32_t width; uint32_t height; uint32_t depth; uint32_t arraySize; uint32_t mipLevels; // Original API data ApiImage image; }; ImportData loadDDS(const std::string& filename, bool loadAsSrgb) { assert(hasSuffix(filename, ".dds", false)); ImportData data; if (findFileInDataDirectories(filename, data.fullpath) == false) { throw std::exception(("Can't find file: " + filename).c_str()); } DirectX::DDS_FLAGS flags = DirectX::DDS_FLAGS_NONE; if (FAILED(DirectX::LoadFromDDSFile(string_2_wstring(data.fullpath).c_str(), flags, nullptr, data.image.scratchImage))) { throw std::exception(("Failed to load file: " + filename).c_str()); } const auto& meta = data.image.scratchImage.GetMetadata(); ResourceFormat format = getResourceFormat(meta.format); data.format = loadAsSrgb ? linearToSrgbFormat(format) : format; data.width = (uint32_t)meta.width; data.height = (uint32_t)meta.height; data.depth = (uint32_t)meta.depth; data.arraySize = (uint32_t)meta.arraySize; data.mipLevels = (uint32_t)meta.mipLevels; return data; } void validateSavePath(const std::string& filename) { if (std::filesystem::path(filename).is_absolute() == false) { throw std::exception((filename + " is not an absolute path.").c_str()); } if (getExtensionFromFile(filename) != "dds") { throw std::exception((filename + " does not end in dds").c_str()); } } DXGI_FORMAT asCompressedFormat(DXGI_FORMAT format, ImageIO::CompressionMode mode) { // 7 block compression formats, and 3 variants for each. // Most of them are UNORM, SRGB, and TYPELESS, but BC4 and BC5 are different static const DXGI_FORMAT kCompressedFormats[7][3] = { // Unorm sRGB Typeless {DXGI_FORMAT_BC1_UNORM, DXGI_FORMAT_BC1_UNORM_SRGB, DXGI_FORMAT_BC1_TYPELESS}, {DXGI_FORMAT_BC2_UNORM, DXGI_FORMAT_BC2_UNORM_SRGB, DXGI_FORMAT_BC2_TYPELESS}, {DXGI_FORMAT_BC3_UNORM, DXGI_FORMAT_BC3_UNORM_SRGB, DXGI_FORMAT_BC3_TYPELESS}, // Unsigned Signed Typeless {DXGI_FORMAT_BC4_UNORM, DXGI_FORMAT_BC4_SNORM, DXGI_FORMAT_BC4_TYPELESS}, {DXGI_FORMAT_BC5_UNORM, DXGI_FORMAT_BC5_SNORM, DXGI_FORMAT_BC5_TYPELESS}, {DXGI_FORMAT_BC6H_UF16, DXGI_FORMAT_BC6H_SF16, DXGI_FORMAT_BC6H_TYPELESS}, // Unorm sRGB Typeless {DXGI_FORMAT_BC7_UNORM, DXGI_FORMAT_BC7_UNORM_SRGB, DXGI_FORMAT_BC7_TYPELESS} }; bool isSRGB = DirectX::IsSRGB(format); // Applicable for 8-bit per channel RGB color modes bool isTypeless = DirectX::IsTypeless(format); switch (mode) { case ImageIO::CompressionMode::BC1: case ImageIO::CompressionMode::BC2: case ImageIO::CompressionMode::BC3: case ImageIO::CompressionMode::BC7: return kCompressedFormats[uint32_t(mode)][isSRGB ? 1 : (isTypeless ? 2 : 0)]; case ImageIO::CompressionMode::BC4: case ImageIO::CompressionMode::BC5: // Always Unorm for single/two-channel (BC4 grayscale, or BC5 normals) return kCompressedFormats[uint32_t(mode)][(isTypeless ? 2 : 0)]; case ImageIO::CompressionMode::BC6: // Always use Snorm for float formats // TODO: Check if format is signed return kCompressedFormats[uint32_t(mode)][isTypeless ? 2 : 1]; default: return format; } } void compress(ApiImage& image, ImageIO::CompressionMode mode) { if (isCompressedFormat(getResourceFormat(image.getFormat()))) { throw std::exception("Image is already compressed."); } const DirectX::TEX_COMPRESS_FLAGS flags = mode == ImageIO::CompressionMode::BC7 ? DirectX::TEX_COMPRESS_BC7_QUICK : DirectX::TEX_COMPRESS_DEFAULT; HRESULT result = S_OK; if (image.isSingleImage()) { result = DirectX::Compress(image.image, asCompressedFormat(image.getFormat(), mode), flags, DirectX::TEX_THRESHOLD_DEFAULT, image.scratchImage); // Clear bitmap since compression outputted to the scratchImage image.image = {}; } else { // Compression will output "in place" back to ApiImage, so move the input out here DirectX::ScratchImage inputImage(std::move(image.scratchImage)); const auto& meta = inputImage.GetMetadata(); result = DirectX::Compress(inputImage.GetImages(), inputImage.GetImageCount(), meta, asCompressedFormat(meta.format, mode), flags, DirectX::TEX_THRESHOLD_DEFAULT, image.scratchImage); } if (FAILED(result)) { throw std::exception("Failed to compress."); } } /** Saves image data to a DDS file. Optionally compresses image. */ void exportDDS(const std::string& filename, ApiImage& image, ImageIO::CompressionMode mode) { validateSavePath(filename); // Compress try { if (mode != ImageIO::CompressionMode::None) { compress(image, mode); } } catch (const std::exception& e) { // Forward exception along with filename for context throw std::exception((filename + ": " + e.what()).c_str()); } // Save const DirectX::DDS_FLAGS saveFlags = DirectX::DDS_FLAGS_NONE; HRESULT result = S_OK; if (image.isSingleImage()) { result = DirectX::SaveToDDSFile(image.image, saveFlags, string_2_wstring(filename).c_str()); } else { const auto& scratchImage = image.scratchImage; result = DirectX::SaveToDDSFile(scratchImage.GetImages(), scratchImage.GetImageCount(), scratchImage.GetMetadata(), saveFlags, string_2_wstring(filename).c_str()); } if (FAILED(result)) { throw std::exception(("Failed to export " + filename).c_str()); } } } Bitmap::UniqueConstPtr ImageIO::loadBitmapFromDDS(const std::string& filename) { ImportData data = loadDDS(filename, false); const auto& scratchImage = data.image.scratchImage; const auto& meta = scratchImage.GetMetadata(); if (meta.IsCubemap() || meta.IsVolumemap()) { throw std::exception(("Cannot load " + filename + " as a Bitmap. Invalid resource dimension.").c_str()); } // Create from first image auto pImage = scratchImage.GetImage(0, 0, 0); return Bitmap::create((uint32_t)data.width, (uint32_t)data.height, data.format, pImage->pixels); } Texture::SharedPtr ImageIO::loadTextureFromDDS(const std::string& filename, bool loadAsSrgb) { ImportData data = loadDDS(filename, loadAsSrgb); const auto& scratchImage = data.image.scratchImage; const auto& meta = scratchImage.GetMetadata(); Texture::SharedPtr pTex; switch (meta.dimension) { case DirectX::TEX_DIMENSION_TEXTURE1D: pTex = Texture::create1D(data.width, data.format, data.arraySize, data.mipLevels, scratchImage.GetPixels()); break; case DirectX::TEX_DIMENSION_TEXTURE2D: if (meta.IsCubemap()) { pTex = Texture::createCube(data.width, data.height, data.format, data.arraySize / 6, data.mipLevels, scratchImage.GetPixels()); } else { pTex = Texture::create2D(data.width, data.height, data.format, data.arraySize, data.mipLevels, scratchImage.GetPixels()); } break; case DirectX::TEX_DIMENSION_TEXTURE3D: pTex = Texture::create3D(data.width, data.height, data.depth, data.format, data.mipLevels, scratchImage.GetPixels()); break; } if (pTex != nullptr) { pTex->setSourceFilename(data.fullpath); } return pTex; } void ImageIO::saveToDDS(const std::string& filename, const Bitmap& bitmap, CompressionMode mode) { ApiImage image; image.image.width = bitmap.getWidth(); image.image.height = bitmap.getHeight(); image.image.format = getDxgiFormat(bitmap.getFormat()); image.image.rowPitch = bitmap.getRowPitch(); image.image.slicePitch = bitmap.getSize(); image.image.pixels = bitmap.getData(); exportDDS(filename, image, mode); } void ImageIO::saveToDDS(CopyContext* pContext, const std::string& filename, const Texture::SharedPtr& pTexture, CompressionMode mode) { DirectX::TexMetadata meta = {}; meta.width = pTexture->getWidth(); meta.height = pTexture->getHeight(); meta.depth = pTexture->getDepth(); meta.arraySize = pTexture->getArraySize(); meta.mipLevels = pTexture->getMipCount(); meta.format = getDxgiFormat(pTexture->getFormat()); switch (pTexture->getType()) { case Resource::Type::Texture1D: meta.dimension = DirectX::TEX_DIMENSION_TEXTURE1D; break; case Resource::Type::TextureCube: meta.miscFlags |= DirectX::TEX_MISC_TEXTURECUBE; // No break, cubes are also Texture2Ds case Resource::Type::Texture2D: meta.dimension = DirectX::TEX_DIMENSION_TEXTURE2D; break; case Resource::Type::Texture3D: meta.dimension = DirectX::TEX_DIMENSION_TEXTURE3D; throw std::exception("saveToDDS: Saving 3D textures currently not supported."); default: throw std::exception("saveToDDS: Invalid resource dimension."); } ApiImage image; auto& scratchImage = image.scratchImage; HRESULT result = scratchImage.Initialize(meta); assert(SUCCEEDED(result)); for (uint32_t i = 0; i < pTexture->getArraySize(); i++) { for (uint32_t m = 0; m < pTexture->getMipCount(); m++) { uint32_t subresource = pTexture->getSubresourceIndex(i, m); const DirectX::Image* pImage = scratchImage.GetImage(m, i, 0); std::vector<uint8_t> subresourceData = pContext->readTextureSubresource(pTexture.get(), subresource); assert(subresourceData.size() == pImage->slicePitch); std::memcpy(pImage->pixels, subresourceData.data(), subresourceData.size()); } } exportDDS(filename, image, mode); } }
#include <stdio.h> #include <omp.h> #include <stdlib.h> #include <ctime> int main() { srand(time(NULL)); int m=500,n=500,p=500; int b=100; int A[m][n]; int B[n][p]; for (int i=0;i<m;i+=1) for (int j=0;j<n;j+=1) { A[i][j]=rand()%b; } for (int i=0;i<n;i+=1) for (int j=0;j<p;j+=1) { B[i][j]=rand()%b; } int C[m][p]; int Cone[m][p]; for (int i=0;i<m;i+=1) for (int j=0;j<p;j+=1) C[i][j]=0; clock_t start=clock(); for (int i=0;i<m;i+=1) for (int j=0;j<p;j+=1) for (int k=0;k<n;k+=1) C[i][j]+=A[i][k]*B[k][j]; clock_t end=clock(); double time=(double)(end-start)/CLOCKS_PER_SEC; printf("Standart %f \n", time); for (int i=0;i<m;i+=1) for (int j=0;j<p;j+=1) Cone[i][j]=0; double wstart=omp_get_wtime(); #pragma omp parallel for for (int i=0;i<m;i+=1) for (int j=0;j<p;j+=1) for (int k=0;k<n;k+=1) Cone[i][j]+=A[i][k]*B[k][j]; double wend=omp_get_wtime(); printf("ijk %f \n",wend-wstart); for (int i=0;i<m;i+=1) for (int j=0;j<p;j+=1) Cone[i][j]=0; wstart=omp_get_wtime(); #pragma omp parallel for for (int i=0;i<m;i+=1) for (int k=0;k<n;k+=1) for (int j=0;j<p;j+=1) Cone[i][j]+=A[i][k]*B[k][j]; wend=omp_get_wtime(); printf("ikj %f \n",wend-wstart); for (int i=0;i<m;i+=1) for (int j=0;j<p;j+=1) Cone[i][j]=0; wstart=omp_get_wtime(); #pragma omp parallel for for (int j=0;j<p;j+=1) for (int i=0;i<m;i+=1) for (int k=0;k<n;k+=1) Cone[i][j]+=A[i][k]*B[k][j]; wend=omp_get_wtime(); printf("jik %f \n",wend-wstart); for (int i=0;i<m;i+=1) for (int j=0;j<p;j+=1) Cone[i][j]=0; wstart=omp_get_wtime(); #pragma omp parallel for for (int j=0;j<p;j+=1) for (int k=0;k<n;k+=1) for (int i=0;i<m;i+=1) Cone[i][j]+=A[i][k]*B[k][j]; wend=omp_get_wtime(); printf("jki %f \n",wend-wstart); for (int i=0;i<m;i+=1) for (int j=0;j<p;j+=1) Cone[i][j]=0; wstart=omp_get_wtime(); #pragma omp parallel for for (int k=0;k<n;k+=1) for (int j=0;j<p;j+=1) for (int i=0;i<m;i+=1) Cone[i][j]+=A[i][k]*B[k][j]; wend=omp_get_wtime(); printf("kji %f \n",wend-wstart); for (int i=0;i<m;i+=1) for (int j=0;j<p;j+=1) Cone[i][j]=0; wstart=omp_get_wtime(); #pragma omp parallel for for (int k=0;k<n;k+=1) for (int i=0;i<m;i+=1) for (int j=0;j<p;j+=1) Cone[i][j]+=A[i][k]*B[k][j]; wend=omp_get_wtime(); printf("kij %f \n",wend-wstart); 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. */ #include <cstdlib> #include <cassert> #include <iostream> #include <algorithm> #include "Warnings.hpp" #include "Exception.hpp" #include "LogFile.hpp" #include "FileFinder.hpp" #include "PosixPathFixer.hpp" #include "GetCurrentWorkingDirectory.hpp" Warnings* Warnings::mpInstance = nullptr; Warnings::Warnings() { } void Warnings::NoisyDestroy(void) { PrintWarnings(); QuietDestroy(); } void Warnings::QuietDestroy(void) { if (mpInstance) { delete mpInstance; mpInstance = nullptr; } } void Warnings::PrintWarnings(void) { if (mpInstance) { for (WarningsContainerType::iterator it = mpInstance->mWarningMessages.begin(); it != mpInstance->mWarningMessages.end(); ++it) { /* * Look at my warnings please. * First in pair is the context. * Second in pair is that actual warning. */ std::cout << it->first << it->second << std::endl; } } } Warnings* Warnings::Instance() { if (mpInstance == nullptr) { mpInstance = new Warnings(); std::atexit(NoisyDestroy); } return mpInstance; } void Warnings::AddWarning(const std::string& rMessage, const std::string& rFilename, unsigned lineNumber, bool onlyOnce) { std::string posix_filename(ChastePosixPathFixer::ToPosix(fs::path(rFilename))); std::stringstream line_number_stream; line_number_stream << lineNumber; std::string context("Chaste warning: in file " + posix_filename + " at line " + line_number_stream.str() + ": "); std::pair<std::string, std::string> item(context, rMessage); if (onlyOnce) { WarningsContainerType::iterator it = find(mWarningMessages.begin(), mWarningMessages.end(), item); if (it != mWarningMessages.end()) { return; } } mWarningMessages.push_back(item); LOG(1, context + rMessage); } unsigned Warnings::GetNumWarnings() { return mWarningMessages.size(); } std::string Warnings::GetNextWarningMessage() { if (mWarningMessages.empty()) { EXCEPTION("There are no warnings"); } std::string message = mWarningMessages.front().second; // Second in pair is the actual warning mWarningMessages.pop_front(); return message; }
#include <stdio.h> #include <string.h> int n,m; int can_eat[50][50]; char name[50][11]; int g_select; int min(int a,int b) { if(a<b) return a; else return b; } int find(char *input) { for(int i=0;i<n;i++) if(strcmp(input,name[i]) == 0) return i; return -1; } int func(int pos,int select, int *check) { if(pos == n) { g_select = min(g_select,select); return select; } if(select > g_select) return g_select; int ret = 50; for(int i=0;i<m;i++) if(check[i] == 1) if(can_eat[i][pos] == 1) return func(pos+1,select,check); for(int i=0;i<m;i++) { if(check[i] == 0) { if(can_eat[i][pos] == 1) { check[i] = 1; ret = min(ret,func(pos+1,select+1,check)); check[i] = 0; } } } return ret; } int main() { int c; int check[50]; scanf("%d", &c); while(c--) { g_select = 50; scanf("%d %d",&n,&m); for(int i=0;i<n;i++) scanf("%s",name[i]); char temp[11]; int temp_2; for(int i=0;i<m;i++) { scanf("%d",&temp_2); for(int j=0;j<n;j++) can_eat[i][j] = 0; for(int j=0;j<temp_2;j++) { scanf("%s",temp); can_eat[i][find(temp)] = 1; } } for(int i=0;i<m;i++) check[i] = 0; printf("%d\n",func(0,0,check)); } }
#ifndef _HS_SFM_BUNDLE_ADJUSTMENT_BA_NAIVE_AUGMENTOR_HPP_ #define _HS_SFM_BUNDLE_ADJUSTMENT_BA_NAIVE_AUGMENTOR_HPP_ #include "hs_sfm/bundle_adjustment/ba_naive_augmented_normal_matrix.hpp" #include "hs_sfm/bundle_adjustment/ba_naive_vector_function.hpp" namespace hs { namespace sfm { namespace ba { template <typename _Scalar> class BANaiveAugmentor { public: typedef _Scalar Scalar; typedef int Err; typedef BANaiveVectorFunction<Scalar> VectorFunction; typedef typename VectorFunction::Index Index; typedef BANaiveAugmentedNormalMatrix<Scalar, Index, VectorFunction::params_per_camera_, VectorFunction::params_per_point_> AugmentedNormalMatrix; typedef typename AugmentedNormalMatrix::NormalMatrix NormalMatrix; AugmentedNormalMatrix operator()(const NormalMatrix& normal_matrix, Scalar mu) const { return AugmentedNormalMatrix(normal_matrix, mu); } }; } } } #endif
#ifndef DBOPERATOR_H #define DBOPERATOR_H #include <iostream> #include <QtSql> #include <QtDebug> using namespace std; class DbOperator { public: DbOperator(); void addDatabase(); void checkDB(); QSqlDatabase mydb; void open(); void close(); bool isOpen(); }; #endif // DBOPERATOR_H
#ifndef GENERADOR_ESTRUCTURA_NIVELES_H #define GENERADOR_ESTRUCTURA_NIVELES_H #include "proto_sala.h" #include "../definiciones/definiciones.h" #include <vector> #include <stdexcept> namespace App_Generador { class Generador_estructura_niveles { ////////////// //Definiciones public: private: struct SalaNoExisteException:public std::logic_error { public: int x, y; SalaNoExisteException(int px, int py, const std::string& m) :logic_error(m), x(px), y(py) {} }; struct SalaExisteException:public std::logic_error { public: int x, y; SalaExisteException(int px, int py, const std::string& m) :logic_error(m), x(px), y(py) {} }; ////////////// //Propiedades private: std::vector<Proto_sala> salas; ////////////// //Métodos privados private: /** * @param int px * @param int py * @return Proto_sala& * @throw SalaNoExisteException */ Proto_sala& obtener_sala_pos(int px, int py); /** * @param int px * @param int py * @return bool */ bool es_pos_libre(int px, int py); /** * @param int px * @param int px * @return direcciones * Devuelve las direcciones en las que hay huecos libres para la sala. */ App_Definiciones::direcciones obtener_libres_adyacentes_para_posicion(int px, int py) { return base_obtener_adyacentes_para_posicion(px, py, true); } /** * @param int px * @param int px * @return App_Definiciones::direcciones * Devuelve las direcciones en las que hay huecos ocupados para las coordenadas. */ App_Definiciones::direcciones obtener_ocupadas_adyacentes_para_posicion(int px, int py) { return base_obtener_adyacentes_para_posicion(px, py, false); } /** * Base para las dos anteriores... */ App_Definiciones::direcciones base_obtener_adyacentes_para_posicion(int px, int py, bool libre); /** * @param int x : posición x * @param int y : posición y * @param App_Definiciones::direcciones salidas * @param bool principal * @param Proto_sala::tipos tipo * @throw SalaExisteException */ void construir_sala(int x, int y, App_Definiciones::direcciones salidas, bool principal, Proto_sala::tipos tipo); /** * @param App_Definiciones::direcciones * @return App_Definiciones::direcciones. */ App_Definiciones::direcciones obtener_salida_aleatoria(App_Definiciones::direcciones salidas); /** * @return std::vector<coordenadas_t_dim> * Obtiene un vector con todas las posibles posiciones en las que * se podría añadir una sala. */ std::vector<App_Definiciones::tipos::coordenadas_t_dim> obtener_potenciales_conectadas(); /** * @param coordenadas_t_dim coordenadas * @param App_Definiciones::direcciones s * @return coordenadas_t_dim * Devuelve el par de de coordenadas que estarían en la dirección * especificada a partir de las coordenadas especificadas. */ App_Definiciones::tipos::coordenadas_t_dim coordenadas_desde_posicion_y_direccion(App_Definiciones::tipos::coordenadas_t_dim coords, App_Definiciones::direcciones s); /** * @param coordenadas_t_dim& sala_a * @param coordenadas_t_dim& sala_b * Si las salas son adyacentes actualiza su valor de salidas para * que estén conectadas. */ void conectar_proto_salas(App_Definiciones::tipos::coordenadas_t_dim& sala_a, App_Definiciones::tipos::coordenadas_t_dim& sala_b); void conectar_proto_salas(Proto_sala& sala_a, Proto_sala& sala_b); ////////////// //Interface pública public: Generador_estructura_niveles() {} /** * @param unsigned int c * @throw SalaExisteException cuando hay un fallo en la generación. * @throw SelectorAleatorioException cuando hay un fallo en la generación. * @throw std::logic_error, para cualquiera de las de arriba. * * Inicia la generación del camino principal compuesto de tantas salas * como especifique el parámetro. */ void generar_camino_principal(unsigned int c); /** * @param unsigned int c * Inicia la generación de tantas salas secundarias como se indique. */ void generar_salas_secundarias(unsigned int c); /** * Hace que la sala en la esquina superior izquierda sean las coordenadas * 0,0 y ajusta el resto. */ void normalizar(); const std::vector<Proto_sala>& acc_proto_salas() const {return salas;} }; } #endif
#ifndef __LINBOX_matrix_SlicedPolynomialMatrix_SlicedPolynomialVector_H #define __LINBOX_matrix_SlicedPolynomialMatrix_SlicedPolynomialVector_H #include <vector> #include <iostream> #include <fstream> #include <stdlib.h> #include <stdint.h> #include "linbox/vector/blas-vector.h" #include <givaro/modular.h> #include <givaro/givpoly1dense.h> #include <givaro/givpoly1denseops.inl> namespace LinBox { template <class _Field, class _VectorElement = double> class SlicedPolynomialVector /*Requirement: variable class _Field must be a representation of a field of order p^e *and have functions that return p (characteristic()) and e (exponent()). *For example, Givaro::GfqDom. */ /*Description: this class implements representation of a vector over GF *as a vector of length n of vectors over F (BlasVectors), *which corresponds to representation of this vector as a polynomial of degree n-1 with vector-coefficients. */ { public: typedef _Field Field; typedef typename Field::Element Element; typedef std::vector<MatrixElement> Rep; typedef _VectorElement VectorElement; typedef typename Givaro::Modular<VectorElement> IntField; typedef typename SlicedPolynomialVector<Field, VectorElement> Self_t; typedef typename Givaro::Poly1Dom<IntField, Dense>::Rep polynomial; private: _Field *GF; IntField F; private: size_t e; // GF.cardinality == p^e std::vector<BlasVector<IntField>> V; typedef typename Field::Residu_t GFqDompolynomial; public: polynomial irreducible() { polynomial res; size_t p = GF->characteristic(); GFqDompolynomial z = GF->irreducible(); for (size_t i = 0; i <= e; i++) { res.push_back(z % p); z = z / p; } return res; } //////////////// //Constructors// //////////////// public: /*! Allocates a vector of new zero vectors of size 0. */ SlicedPolynomialVector (const _Field &BF); /*Allocates a vector of new vectors of size m. */ SlicedPolynomialVector (const _Field &BF, const size_t &m); /////////////// // Destructor// /////////////// public: ~SlicedPolynomialVector(){} //////////////////////// //dimensions of vector// //////////////////////// public: /*Get length of V. * @returns length of V */ size_t length() const; /*Get the number of rows in a vector. * @returns Number of rows in a vector */ size_t rowdim() const; ///////////////// //return fields// ///////////////// public: const _Field& fieldGF() const; const IntField& fieldF() const; ///////////////////////// //functions for entries// ///////////////////////// public: /* Set the entry of the m-th vector-coefficient at the (k) position to a_mk. * @param m vector-coefficient number, 0...length() - 1 * @param k Row number 0...rowdim () - 1 * @param a_mk Element to set */ void setEntry (size_t m, size_t k, const _MatrixElement &a_mk); private: /* Get a writeable reference to the m-th vector-coefficient at the (k) position. * @param m vector-coefficient number, 0...length() - 1 * @param k Row number 0...rowdim () - 1 * @returns Reference to vector entry */ _MatrixElement &refEntry (size_t m, size_t k); public: /* Get a read-only reference to the m-th vector-coefficient at the (k) position. * @param m vector-coefficient number, 0...length() - 1 * @param k Row number 0...rowdim () - 1 * @returns Const reference to vector entry */ _MatrixElement &getEntry (size_t m, size_t k); ///////////////////////////////////// //functions for matrix-coefficients// ///////////////////////////////////// public: /* Set the m-th vector-coefficient to V_m. * @param m vector-coefficient number, 0...length() - 1 * @param V_m matrix to set */ void setVectorCoefficient (size_t m, const BlasVector<IntField> &V_m) ; private: /* Get a writeable reference to the m-th matrix-coefficient. * @param m matrix-coefficient number, 0...length() - 1 * @returns Reference to matrix-coefficent */ BlasVector<IntField> &refVectorCoefficient (size_t m) ; public: /** Get a read-only reference to the m-th matrix-coefficient * @param m matrix-coefficient number, 0...length() - 1 * @returns Const reference to matrix-coefficent */ const BlasVector<IntField> &getVectorCoefficient (size_t m) const ; ///////// //swaps// ///////// public: /* Swap i1-th and i2-th rows of matrices. * This is done inplace. */ void swapRows(size_t k1, size_t k2); ////////////////// //input / output// ////////////////// public: std::istream &read (std::istream &file); std::ostream &write (std::ostream &os) { int K = this->length(); int I = this->rowdim(); for (int k = 0; k < K; k++) { for (int i = 0; i < I; i++) { os << this->getEntry(k, i, j) << " "; } os << std::endl; } return os; } }; } #include "SlicedPolynomialVector.inl" #endif
class Solution { public: int removeDuplicates(vector<int>& nums) { // 数组操作,思路偏脑筋急转弯 int i = 0; for (int num : nums) { // 遍历数组中的元素 if (i < 2 || nums[i - 2] < num) nums[i++] = num; // 因为至多两个元素连续,并且根据题目要求元素大小递增 // 新的nums是在原有的nums下更新的,这个新的nums不会把原来nums全部元素都更新,它会更新前面一部分的内容 // 更新的范围就是0到i,最后return i就好。如果是返回更新之后的nums,那么在原有nums的基础上截取前i个的部分即可 } return i; } }; // reference https://leetcode-cn.com/u/yinyinnie/ // 本题是“原地改动”数组的模范题目,还有其他的“原地”修改的题目和本题思路相似,都是直接在原数组上进行更新,但前面更新之后的内容 // 不会影响到后面正在进行的操作。需要掌握这种思想
#ifndef FASTCG_COLORS_H #define FASTCG_COLORS_H #include <glm/glm.hpp> namespace FastCG { class Colors { public: static const glm::vec4 NONE; static const glm::vec4 WHITE; static const glm::vec4 SILVER; static const glm::vec4 GRAY; static const glm::vec4 BLACK; static const glm::vec4 RED; static const glm::vec4 MAROON; static const glm::vec4 YELLOW; static const glm::vec4 OLIVE; static const glm::vec4 LIME; static const glm::vec4 GREEN; static const glm::vec4 AQUA; static const glm::vec4 TEAL; static const glm::vec4 BLUE; static const glm::vec4 NAVY; static const glm::vec4 FUCHSIA; static const glm::vec4 PURPLE; static const size_t NUMBER_OF_COMMON_LIGHT_COLORS; static const glm::vec4 COMMON_LIGHT_COLORS[]; private: Colors() = delete; ~Colors() = delete; }; } #endif
#pragma once #include <vector> #include "typedValue.h" PP_API void InitOptPattern(); void Optimize(CodeThread *ioThread);
// // Created by Alex Shaver on 8/30/17. // #ifndef FACTORYEXAMPLE_ANCHOR_H #define FACTORYEXAMPLE_ANCHOR_H #include "Alpha.h" class Anchor : public Alpha{ public: void print() override; }; #endif //FACTORYEXAMPLE_ANCHOR_H
// // Copyright (c) 2003--2009 // Toon Knapen, Karl Meerbergen, Kresimir Fresl, // Thomas Klimpel and Rutger ter Borg // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // THIS FILE IS AUTOMATICALLY GENERATED // PLEASE DO NOT EDIT! // #ifndef BOOST_NUMERIC_BINDINGS_LAPACK_COMPUTATIONAL_POEQU_HPP #define BOOST_NUMERIC_BINDINGS_LAPACK_COMPUTATIONAL_POEQU_HPP #include <boost/assert.hpp> #include <boost/mpl/bool.hpp> #include <boost/numeric/bindings/lapack/detail/lapack.h> #include <boost/numeric/bindings/traits/is_complex.hpp> #include <boost/numeric/bindings/traits/is_real.hpp> #include <boost/numeric/bindings/traits/traits.hpp> #include <boost/numeric/bindings/traits/type_traits.hpp> #include <boost/static_assert.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/utility/enable_if.hpp> namespace boost { namespace numeric { namespace bindings { namespace lapack { //$DESCRIPTION // overloaded functions to call lapack namespace detail { inline void poequ( integer_t const n, float* a, integer_t const lda, float* s, float& scond, float& amax, integer_t& info ) { LAPACK_SPOEQU( &n, a, &lda, s, &scond, &amax, &info ); } inline void poequ( integer_t const n, double* a, integer_t const lda, double* s, double& scond, double& amax, integer_t& info ) { LAPACK_DPOEQU( &n, a, &lda, s, &scond, &amax, &info ); } inline void poequ( integer_t const n, traits::complex_f* a, integer_t const lda, float* s, float& scond, float& amax, integer_t& info ) { LAPACK_CPOEQU( &n, traits::complex_ptr(a), &lda, s, &scond, &amax, &info ); } inline void poequ( integer_t const n, traits::complex_d* a, integer_t const lda, double* s, double& scond, double& amax, integer_t& info ) { LAPACK_ZPOEQU( &n, traits::complex_ptr(a), &lda, s, &scond, &amax, &info ); } } // value-type based template template< typename ValueType, typename Enable = void > struct poequ_impl{}; // real specialization template< typename ValueType > struct poequ_impl< ValueType, typename boost::enable_if< traits::is_real<ValueType> >::type > { typedef ValueType value_type; typedef typename traits::type_traits<ValueType>::real_type real_type; // templated specialization template< typename MatrixA, typename VectorS > static void invoke( MatrixA& a, VectorS& s, real_type& scond, real_type& amax, integer_t& info ) { BOOST_STATIC_ASSERT( (boost::is_same< typename traits::matrix_traits< MatrixA >::value_type, typename traits::vector_traits< VectorS >::value_type >::value) ); BOOST_ASSERT( traits::matrix_num_columns(a) >= 0 ); BOOST_ASSERT( traits::leading_dimension(a) >= std::max(1, traits::matrix_num_columns(a)) ); detail::poequ( traits::matrix_num_columns(a), traits::matrix_storage(a), traits::leading_dimension(a), traits::vector_storage(s), scond, amax, info ); } }; // complex specialization template< typename ValueType > struct poequ_impl< ValueType, typename boost::enable_if< traits::is_complex<ValueType> >::type > { typedef ValueType value_type; typedef typename traits::type_traits<ValueType>::real_type real_type; // templated specialization template< typename MatrixA, typename VectorS > static void invoke( MatrixA& a, VectorS& s, real_type& scond, real_type& amax, integer_t& info ) { BOOST_ASSERT( traits::matrix_num_columns(a) >= 0 ); BOOST_ASSERT( traits::leading_dimension(a) >= std::max(1, traits::matrix_num_columns(a)) ); detail::poequ( traits::matrix_num_columns(a), traits::matrix_storage(a), traits::leading_dimension(a), traits::vector_storage(s), scond, amax, info ); } }; // template function to call poequ template< typename MatrixA, typename VectorS > inline integer_t poequ( MatrixA& a, VectorS& s, typename traits::type_traits< typename traits::matrix_traits< MatrixA >::value_type >::real_type& scond, typename traits::type_traits< typename traits::matrix_traits< MatrixA >::value_type >::real_type& amax ) { typedef typename traits::matrix_traits< MatrixA >::value_type value_type; integer_t info(0); poequ_impl< value_type >::invoke( a, s, scond, amax, info ); return info; } }}}} // namespace boost::numeric::bindings::lapack #endif
/*************************************************************************** Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved. 2010-2020 DADI ORISTAR TECHNOLOGY DEVELOPMENT(BEIJING)CO.,LTD FileName: RTPSession.cpp Description: Provides a class to manipulate transmission of the media data, also receive and respond to client's feedback. Comment: copy from Darwin Streaming Server 5.5.5 Author: taoyunxing@dadimedia.com Version: v1.0.0.1 CreateDate: 2010-08-16 LastUpdate: 2010-08-16 ****************************************************************************/ #include "RTPSession.h" #include "RTSPProtocol.h" #include "QTSServerInterface.h" #include "QTSS.h" #include "OS.h" #include "OSMemory.h" #include <errno.h> #define RTPSESSION_DEBUGGING 1 RTPSession::RTPSession() : RTPSessionInterface(), /* invocation related interface */ fModule(NULL),/* 默认Module指针为空 */ fHasAnRTPStream(false),/* 默认没有RTP Stream,设置在RTPSession::AddStream() */ fCurrentModuleIndex(0), fCurrentState(kStart),/* rtp session current state */ fClosingReason(qtssCliSesCloseClientTeardown),/* 默认是Client自己关闭的,设置另见RTPSession::Run() */ fCurrentModule(0), fModuleDoingAsyncStuff(false), fLastBandwidthTrackerStatsUpdate(0) { #if DEBUG fActivateCalled = false; #endif this->SetTaskName("RTPSession"); /* inherited from Task::SetTaskName() */ /* set QTSS module state vars,进一步设置另见RTPSession::Run() */ fModuleState.curModule = NULL; fModuleState.curTask = this; fModuleState.curRole = 0; } RTPSession::~RTPSession() { // Delete all the streams RTPStream** theStream = NULL; UInt32 theLen = 0; /* 假如预设值能打印RUDP信息 */ if (QTSServerInterface::GetServer()->GetPrefs()->GetReliableUDPPrintfsEnabled()) { SInt32 theNumLatePacketsDropped = 0;/* 丢弃延迟包个数 */ SInt32 theNumResends = 0; /* 重传包个数 */ /* 遍历该RTPSession的每个RTPStream,计算丢弃的过时包总数和重传包总数 */ for (int x = 0; this->GetValuePtr(qtssCliSesStreamObjects, x, (void**)&theStream, &theLen) == QTSS_NoErr; x++) { Assert(theStream != NULL); Assert(theLen == sizeof(RTPStream*)); if (*theStream != NULL) { /* 计算丢弃的过时包总数 */ theNumLatePacketsDropped += (*theStream)->GetStalePacketsDropped(); /* 得到重传包总数 */ theNumResends += (*theStream)->GetResender()->GetNumResends(); } } /* 得到客户端请求播放文件的Full URL */ char* theURL = NULL; (void)this->GetValueAsString(qtssCliSesFullURL, 0, &theURL); Assert(theURL != NULL); /* 获得RTPBandwidthTracker类 */ RTPBandwidthTracker* tracker = this->GetBandwidthTracker(); qtss_printf("Client complete. URL: %s.\n",theURL); qtss_printf("Max congestion window: %ld. Min congestion window: %ld. Avg congestion window: %ld\n", tracker->GetMaxCongestionWindowSize(), tracker->GetMinCongestionWindowSize(), tracker->GetAvgCongestionWindowSize()); qtss_printf("Max RTT: %ld. Min RTT: %ld. Avg RTT: %ld\n", tracker->GetMaxRTO(), tracker->GetMinRTO(), tracker->GetAvgRTO()); qtss_printf("Num resends: %ld. Num skipped frames: %ld. Num late packets dropped: %ld\n", theNumResends, this->GetFramesSkipped(), theNumLatePacketsDropped); delete [] theURL; } /* 遍历该RTPSession的每个RTPStream,逐一删除它们 */ for (int x = 0; this->GetValuePtr(qtssCliSesStreamObjects, x, (void**)&theStream, &theLen) == QTSS_NoErr; x++) { Assert(theStream != NULL); Assert(theLen == sizeof(RTPStream*)); if (*theStream != NULL) delete *theStream; } /* 获取服务器接口类,逐一将该RTPSession从qtssSvrClientSessions属性中删去 */ QTSServerInterface* theServer = QTSServerInterface::GetServer(); { OSMutexLocker theLocker(theServer->GetMutex()); RTPSession** theSession = NULL; // Remove this session from the qtssSvrClientSessions attribute UInt32 y = 0; for ( ; y < theServer->GetNumRTPSessions(); y++) { QTSS_Error theErr = theServer->GetValuePtr(qtssSvrClientSessions, y, (void**)&theSession, &theLen, true); Assert(theErr == QTSS_NoErr); if (*theSession == this) { theErr = theServer->RemoveValue(qtssSvrClientSessions, y, QTSSDictionary::kDontObeyReadOnly); break; } } Assert(y < theServer->GetNumRTPSessions()); theServer->AlterCurrentRTPSessionCount(-1); if (!fIsFirstPlay) // The session was started playing (the counter ignores additional pause-play changes while session is active) theServer->AlterRTPPlayingSessions(-1); } //we better not be in the RTPSessionMap anymore! #if DEBUG Assert(!fRTPMapElem.IsInTable()); StrPtrLen theRTSPSessionID(fRTSPSessionIDBuf,sizeof(fRTSPSessionIDBuf)); /* 从RTPSession Map中删去它们 */ OSRef* theRef = QTSServerInterface::GetServer()->GetRTPSessionMap()->Resolve(&theRTSPSessionID); Assert(theRef == NULL); #endif } /* 用当前RTSPSession构造一个OSRef实例, 在RTPSession Map(Hash表)中注册并加入该引用OSRef元(其key值唯一), 同时更新qtssSvrClientSessions的属性,及QTSServerInterface中的总RTPSession数 */ QTSS_Error RTPSession::Activate(const StrPtrLen& inSessionID) { //Set the session ID for this session /* 用入参配置fRTSPSessionIDBuf的值(是C-String) */ Assert(inSessionID.Len <= QTSS_MAX_SESSION_ID_LENGTH); ::memcpy(fRTSPSessionIDBuf, inSessionID.Ptr, inSessionID.Len); fRTSPSessionIDBuf[inSessionID.Len] = '\0'; /* 用C-String的fRTSPSessionIDBuf设置qtssCliSesRTSPSessionID的属性值 */ this->SetVal(qtssCliSesRTSPSessionID, &fRTSPSessionIDBuf[0], inSessionID.Len); /* 用qtssCliSesRTSPSessionID的属性值来得到一个RTPSession Map的引用OSRef元 */ fRTPMapElem.Set(*this->GetValue(qtssCliSesRTSPSessionID), this); /* 获取服务器接口 */ QTSServerInterface* theServer = QTSServerInterface::GetServer(); //Activate puts the session into the RTPSession Map /* 在RTPSession Map(Hash表)中注册并加入一个引用OSRef,若字符串标识唯一,就能成功返回OS_NoErr;若有一个相同key值的元素,就返回错误EPERM */ QTSS_Error err = theServer->GetRTPSessionMap()->Register(&fRTPMapElem); //若有同名键值,立即返回 if (err == EPERM) return err; /* 确保key值唯一 */ Assert(err == QTSS_NoErr); // // Adding this session into the qtssSvrClientSessions attr and incrementing the number of sessions must be atomic /* 锁定服务器对象 */ OSMutexLocker locker(theServer->GetMutex()); // // Put this session into the qtssSvrClientSessions attribute of the server #if DEBUG Assert(theServer->GetNumValues(qtssSvrClientSessions) == theServer->GetNumRTPSessions());//确保属性qtssSvrClientSessions中的RTPSession个数和服务器中实际的个数相同 #endif /* 设置qtssSvrClientSessions的第GetNumRTPSessions()个RTPSession的属性 */ RTPSession* theSession = this; err = theServer->SetValue(qtssSvrClientSessions, theServer->GetNumRTPSessions(), &theSession, sizeof(theSession), QTSSDictionary::kDontObeyReadOnly); Assert(err == QTSS_NoErr); #if DEBUG fActivateCalled = true; #endif /* 及时更新QTSServerInterface中的总RTPSession数 */ QTSServerInterface::GetServer()->IncrementTotalRTPSessions(); return QTSS_NoErr; } /* 针对TCP Intervead mode,遍历RTPSession中的每个RTPStream,找到入参指定的RTPStream(其RTP/RTCP channel号就是指定channel号)并返回 */ RTPStream* RTPSession::FindRTPStreamForChannelNum(UInt8 inChannelNum) { RTPStream** theStream = NULL; UInt32 theLen = 0; for (int x = 0; this->GetValuePtr(qtssCliSesStreamObjects, x, (void**)&theStream, &theLen) == QTSS_NoErr; x++) { Assert(theStream != NULL); Assert(theLen == sizeof(RTPStream*)); if (*theStream != NULL) if (((*theStream)->GetRTPChannelNum() == inChannelNum) || ((*theStream)->GetRTCPChannelNum() == inChannelNum)) return *theStream; } return NULL; // Couldn't find a matching stream } /* used in QTSSCallbacks::QTSS_AddRTPStream() */ /* 循环产生一个能唯一标识该RTPSession的RTPStream数组中新的RTPStream的随机数(作为SSRC),搭建一个新的RTPStream,放入RTPStream的数组 */ QTSS_Error RTPSession::AddStream(RTSPRequestInterface* request, RTPStream** outStream, QTSS_AddStreamFlags inFlags) { Assert(outStream != NULL); // Create a new SSRC for this stream. This should just be a random number unique // to all the streams in the session /* 循环产生一个能唯一标识该RTPSession的RTPStream数组中新的RTPStream的随机数,作为SSRC(它和该数组中现存的每个RTPStream的SSRC都不同) */ UInt32 theSSRC = 0; while (theSSRC == 0) { /* 产生随机数,它在该RTPSession的RTPStream数组中唯一标识一个RTPSream */ theSSRC = (SInt32)::rand(); RTPStream** theStream = NULL; UInt32 theLen = 0; /* 遍历RTPSession中的每个RTPStream,若它的SSRC恰和theSSRC相同,就将theSSRC置0,使得该循环继续 */ for (int x = 0; this->GetValuePtr(qtssCliSesStreamObjects, x, (void**)&theStream, &theLen) == QTSS_NoErr; x++) { Assert(theStream != NULL); Assert(theLen == sizeof(RTPStream*)); if (*theStream != NULL) if ((*theStream)->GetSSRC() == theSSRC) theSSRC = 0; } } /***************** 新建一个RTPStream对象,它有唯一标识它的SSRC(随机数) *************/ *outStream = NEW RTPStream(theSSRC, this); /***************** 新建一个RTPStream对象 *************/ /* 以指定加入方式搭建该RTSP Request的RTPStream */ QTSS_Error theErr = (*outStream)->Setup(request, inFlags); /* 假如搭建不成功,就删去新建RTPStream对象 */ if (theErr != QTSS_NoErr) // If we couldn't setup the stream, make sure not to leak memory! delete *outStream; /* 假如搭建成功,将其放入RTPStream Array中,注意下面qtssCliSesStreamObjects是个多值索引的属性 */ else { // If the stream init succeeded, then put it into the array of setup streams theErr = this->SetValue(qtssCliSesStreamObjects, this->GetNumValues(qtssCliSesStreamObjects), outStream, sizeof(RTPStream*), QTSSDictionary::kDontObeyReadOnly); Assert(theErr == QTSS_NoErr); fHasAnRTPStream = true;/* 现在有一个RTPStream */ } return theErr; } /* used in RTPSession::Play() */ /* 遍历RTPSession中的每个RTPStream,用入参指定的LateTolerance值设置LateTolerance,并设置胖化瘦化参数 */ void RTPSession::SetStreamThinningParams(Float32 inLateTolerance) { // Set the thinning params in all the RTPStreams of the RTPSession // Go through all the streams, setting their thinning params RTPStream** theStream = NULL; UInt32 theLen = 0; for (int x = 0; this->GetValuePtr(qtssCliSesStreamObjects, x, (void**)&theStream, &theLen) == QTSS_NoErr; x++) { Assert(theStream != NULL); Assert(theLen == sizeof(RTPStream*)); if (*theStream != NULL) { (*theStream)->SetLateTolerance(inLateTolerance); (*theStream)->SetThinningParams(); } } } /* 设置好各种参数后发信号开始触发RTPSession和发送SR包.播放影片,下面是设置步骤:(1)记录并设置相应的播放时间;(2)设置播放状态,播放标志,更新播放的RTPSession总数; (3)根据电影的平均比特率设置Client Windows size,重置过缓冲窗;(4)遍历RTPSession中的每个RTPStream,设置打薄参数,重置打薄延迟参数,清除上个Play中重传类的RTP包;(5)假如获得的movie 平均比特率>0,就灵活调整TCP RTSP Socket缓存大小以适应movie比特率,且介于预设的最大值和最小值之间;(6)发信号启动该RTP Session任务; */ QTSS_Error RTPSession::Play(RTSPRequestInterface* request, QTSS_PlayFlags inFlags) { //first setup the play associated session interface variables Assert(request != NULL); /* 假如没有Module数组,立即返回 */ if (fModule == NULL) return QTSS_RequestFailed;//Can't play if there are no associated streams //what time is this play being issued(触发) at? 记录Play触发的时刻 fLastBitRateUpdateTime = fNextSendPacketsTime = fPlayTime = OS::Milliseconds(); /* 假如是第一次播放,同步当前播放时间 */ if (fIsFirstPlay) fFirstPlayTime = fPlayTime; /* 获取当前播放时间戳和RTSP Request Header Range中的fStartTime的差值 */ fAdjustedPlayTime = fPlayTime - ((SInt64)(request->GetStartTime() * 1000)); //for RTCP SRs(RTCP发送方报告), we also need to store the play time in NTP fNTPPlayTime = OS::TimeMilli_To_1900Fixed64Secs(fPlayTime); //we are definitely playing now, so schedule(调度) the object! fState = qtssPlayingState; fIsFirstPlay = false;/* 现在不是第一次播放 */ fPlayFlags = inFlags;/* 是生成SR包还是AppendServerInfo进SR包 */ /* track how many sessions are playing,see QTSServerInterface.h,使fNumRTPPlayingSessions加1 */ QTSServerInterface::GetServer()-> AlterRTPPlayingSessions(1); /* set Client window size according to bitrate,,参见RTPBandwidthTracker::SetWindowSize() */ //根据电影的平均比特率设置Client Windows size UInt32 theWindowSize; /* 获取电影的平均比特率 */ UInt32 bitRate = this->GetMovieAvgBitrate(); /* 假如电影的平均比特率为0或超过1Mbps,就设置Windowsize 为64Kbytes */ if ((bitRate == 0) || (bitRate > QTSServerInterface::GetServer()->GetPrefs()->GetWindowSizeMaxThreshold() * 1024)) theWindowSize = 1024 * QTSServerInterface::GetServer()->GetPrefs()->GetLargeWindowSizeInK(); /* 假如电影的平均比特率超过200kbps,就设置Windowsize 为48Kbytes */ else if (bitRate > QTSServerInterface::GetServer()->GetPrefs()->GetWindowSizeThreshold() * 1024) theWindowSize = 1024 * QTSServerInterface::GetServer()->GetPrefs()->GetMediumWindowSizeInK(); /* 否则,,就设置Windowsize 为24Kbytes */ else theWindowSize = 1024 * QTSServerInterface::GetServer()->GetPrefs()->GetSmallWindowSizeInK(); qtss_printf("bitrate = %d, window size = %d\n", bitRate, theWindowSize); /* 设置Client窗口大小,参见RTPBandwidthTracker::SetWindowSize() */ this->GetBandwidthTracker()->SetWindowSize(theWindowSize); /* 重置过缓冲窗 */ this->GetOverbufferWindow()->ResetOverBufferWindow(); // Go through all the streams, setting their thinning params RTPStream** theStream = NULL; UInt32 theLen = 0; /* 遍历RTPSession中的每个RTPStream,设置打薄参数,重置打薄延迟参数,清除上个Play中重传类的RTP包 */ for (int x = 0; this->GetValuePtr(qtssCliSesStreamObjects, x, (void**)&theStream, &theLen) == QTSS_NoErr; x++) { Assert(theStream != NULL); Assert(theLen == sizeof(RTPStream*)); if (*theStream != NULL) { /* 设置打薄参数 */ (*theStream)->SetThinningParams(); (*theStream)->ResetThinningDelayParams(); // If we are using reliable UDP, then make sure to clear all the packets from the previous play spurt out of the resender (*theStream)->GetResender()->ClearOutstandingPackets(); } } qtss_printf("movie bitrate = %d, window size = %d\n", this->GetMovieAvgBitrate(), theWindowSize); Assert(this->GetBandwidthTracker()->BytesInList() == 0); // Set the size of the RTSPSession's send buffer to an appropriate max size // based on the bitrate of the movie. This has 2 benefits: // 1) Each socket normally defaults to 32 K. A smaller buffer prevents the // system from getting buffer starved if lots of clients get flow-controlled // // 2) We may need to scale up buffer sizes for high-bandwidth movies in order // to maximize thruput, and we may need to scale down buffer sizes for low-bandwidth // movies to prevent us from buffering lots of data that the client can't use // // If we don't know any better, assume maximum buffer size. /* 获取服务器预设值来得到最大TCP缓冲区大小 */ QTSServerPrefs* thePrefs = QTSServerInterface::GetServer()->GetPrefs(); UInt32 theBufferSize = thePrefs->GetMaxTCPBufferSizeInBytes(); #if RTPSESSION_DEBUGGING qtss_printf("RTPSession GetMovieAvgBitrate %li\n",(SInt32)this->GetMovieAvgBitrate() ); #endif /* 假如获得的movie平均比特率>0,就灵活调整TCP Socket缓存大小以适应movie比特率,且介于预设的最大值和最小值之间 */ if (this->GetMovieAvgBitrate() > 0) { // We have a bit rate... use it. /* 由电影比特率和预设的缓存秒数(0.5s),得到实际的缓存大小(字节) */ Float32 realBufferSize = (Float32)this->GetMovieAvgBitrate() * thePrefs->GetTCPSecondsToBuffer(); theBufferSize = (UInt32)realBufferSize; theBufferSize >>= 3; // Divide by 8 to convert from bits to bytes // Round down to the next lowest power of 2. /* 四舍五入到最接近的小于它的2的幂,该函数定义见下面 */ /* 将入参变为2的幂的特殊算法:先将入参表示为十六进制,从第29bit位开始从高到底开始走,若遇到值为1的bit位,就返回该bit位值为1,其它31个bit位值全为0的数;若一直没有1,返回0 */ theBufferSize = this->PowerOf2Floor(theBufferSize); //下面对缓存大小进行保护,使真实值务必介于预设的最大值和最小值之间 // This is how much data we should buffer based on the scaling factor... if it is lower than the min, raise to min if (theBufferSize < thePrefs->GetMinTCPBufferSizeInBytes()) theBufferSize = thePrefs->GetMinTCPBufferSizeInBytes(); // Same deal for max buffer size if (theBufferSize > thePrefs->GetMaxTCPBufferSizeInBytes()) theBufferSize = thePrefs->GetMaxTCPBufferSizeInBytes(); } /* 设置上面的接收缓存大小为TCP RTSP Socket的缓存大小 */ Assert(fRTSPSession != NULL); // can this ever happen? if (fRTSPSession != NULL) fRTSPSession->GetSocket()->SetSocketBufSize(theBufferSize);/* set RTSP buffer size by above value */ #if RTPSESSION_DEBUGGING qtss_printf("RTPSession %ld: In Play, about to call Signal\n",(SInt32)this); #endif /* after set some parama, a rtp session task is about to start */ //发信号启动该RTP Session任务 this->Signal(Task::kStartEvent); return QTSS_NoErr; } /* used in RTPSession::Play() */ /* 将入参变为2的幂的特殊算法:先将入参表示为十六进制,从第29bit位开始从高到底开始走,若遇到值为1的bit位,就返回该bit位值为1,其它31个bit位值全为0的数;若一直没有1,返回0 */ UInt32 RTPSession::PowerOf2Floor(UInt32 inNumToFloor) { UInt32 retVal = 0x10000000; while (retVal > 0) { /* 十六位数与如何计算? */ if (retVal & inNumToFloor) /* 输入数最高位域(4bit-wide)的第四个bit的值必须是1,就把该bit以后的28位都变为0 */ return retVal; else retVal >>= 1;/* 否则retVal减半 */ } return retVal; } /* 减少该RTSP会话的持有对象计数,设置RTPSession状态为暂停,置空fRTSPSession,再发信号删去该RTPSession */ void RTPSession::Teardown() { // To proffer a quick death of the RTSP session, let's disassociate // ourselves with it right now. // Note that this function relies on the session mutex being grabbed, because // this fRTSPSession pointer could otherwise be being used simultaneously by // an RTP stream. if (fRTSPSession != NULL) fRTSPSession->DecrementObjectHolderCount();/* 减少该RTSP会话的持有对象计数 */ fRTSPSession = NULL; fState = qtssPausedState; /* 发信号删去该RTPSession */ this->Signal(Task::kKillEvent); } /* 遍历RTPSession中的每个RTPStream,若类型为qtssPlayRespWriteTrackInfo,为每个RTPStream附加RTP时间戳和序列号信息,向Client的RTSPResponseStream中放入标准响应内容如下: RTSP/1.0 200 OK\r\n Server: DSS/5.5.3.7 (Build/489.8; Platform/Linux; Release/Darwin; )\r\n Cseq: 11\r\n Session: 7736802604597532330\r\n Range: npt=0.00000-70.00000\r\n RTP-Info: url=rtsp://172.16.34.22/sample_300kbit.mp4/trackID=3;seq=15724;rtptime=503370233,url=rtsp://172.16.34.22/sample_300kbit.mp4/trackID=4;seq=5452;rtptime=1925920323\r\n \r\n */ void RTPSession::SendPlayResponse(RTSPRequestInterface* request, UInt32 inFlags) { QTSS_RTSPHeader theHeader = qtssRTPInfoHeader; RTPStream** theStream = NULL; UInt32 theLen = 0; /* 获得该RTPSession所具有的RTPStream的个数 */ UInt32 valueCount = this->GetNumValues(qtssCliSesStreamObjects); /* 是最后一个RTPStream吗? */ Bool16 lastValue = false; /* 遍历RTPSession中的每个RTPStream,为每个RTPStream附加RTP时间戳和序列号信息 */ for (UInt32 x = 0; x < valueCount; x++) { /* 获取指定索引值的RTPStream */ this->GetValuePtr(qtssCliSesStreamObjects, x, (void**)&theStream, &theLen); Assert(theStream != NULL); Assert(theLen == sizeof(RTPStream*)); if (*theStream != NULL) { /* 对最后一个RTPStream,设置lastValue为true,这样会额外附加"\r\n" */ if (x == (valueCount -1)) lastValue = true; /* 在QTSS_SendStandardRTSPResponse中,若类型为qtssPlayRespWriteTrackInfo,附加RTP时间戳和序列号信息 */ (*theStream)->AppendRTPInfo(theHeader, request, inFlags,lastValue); theHeader = qtssSameAsLastHeader;//这样会附加","而非"RTPInfo" } } /* 向Client的RTSPResponseStream中放入上述指定好的响应内容 */ request->SendHeader(); } /* 针对Client发送的DESCRIBE,向RTSPResponseStream中附加如下内容: Last-Modified: Wed, 25 Nov 2009 06:44:41 GMT\r\n Cache-Control: must-revalidate\r\n Content-length: 1209\r\n Date: Fri, 02 Jul 2010 05:03:08 GMT\r\n Expires: Fri, 02 Jul 2010 05:03:08 GMT\r\n Content-Type: application/sdp\r\n x-Accept-Retransmit: our-retransmit\r\n x-Accept-Dynamic-Rate: 1\r\n Content-Base: rtsp://172.16.34.22/sample_300kbit.mp4/\r\n 这样,向Client回送如下内容: RTSP/1.0 200 OK\r\n Server: DSS/5.5.3.7 (Build/489.8; Platform/Linux; Release/Darwin; )\r\n Cseq: 8\r\n Last-Modified: Wed, 25 Nov 2009 06:44:41 GMT\r\n Cache-Control: must-revalidate\r\n Content-length: 1209\r\n Date: Fri, 02 Jul 2010 05:03:08 GMT\r\n Expires: Fri, 02 Jul 2010 05:03:08 GMT\r\n Content-Type: application/sdp\r\n x-Accept-Retransmit: our-retransmit\r\n x-Accept-Dynamic-Rate: 1\r\n Content-Base: rtsp://172.16.34.22/sample_300kbit.mp4/\r\n \r\n */ void RTPSession::SendDescribeResponse(RTSPRequestInterface* inRequest) { /* 假如当前RTSP Request的状态是"304 Not Modified",仅需向Client的RTSPResponseStream中放入标准响应内容,返回 */ if (inRequest->GetStatus() == qtssRedirectNotModified) { (void)inRequest->SendHeader(); return; } // write date and expires /* 向Client的Describe的RTSPResponseStream中放入如下内容: Date: Fri, 02 Jul 2010 05:22:36 GMT\r\n Expires: Fri, 02 Jul 2010 05:22:36 GMT\r\n */ inRequest->AppendDateAndExpires(); //write content type header //附加如下一行:Content-Type: application/sdp\r\n static StrPtrLen sContentType("application/sdp"); inRequest->AppendHeader(qtssContentTypeHeader, &sContentType); // write x-Accept-Retransmit header //附加如下一行:x-Accept-Retransmit: our-retransmit\r\n static StrPtrLen sRetransmitProtocolName("our-retransmit"); inRequest->AppendHeader(qtssXAcceptRetransmitHeader, &sRetransmitProtocolName); // write x-Accept-Dynamic-Rate header //附加如下一行:x-Accept-Dynamic-Rate: 1\r\n static StrPtrLen dynamicRateEnabledStr("1"); inRequest->AppendHeader(qtssXAcceptDynamicRateHeader, &dynamicRateEnabledStr); //write content base header //附加如下一行:Content-Base: rtsp://172.16.34.22/sample_h264_1mbit.mp4/\r\n inRequest->AppendContentBaseHeader(inRequest->GetValue(qtssRTSPReqAbsoluteURL)); //I believe the only error that can happen is if the client has disconnected. //if that's the case, just ignore it, hopefully the calling module will detect //this and return control back to the server ASAP /* 向Client的RTSPResponseStream中放入标准响应内容 */ (void)inRequest->SendHeader(); } /* 仅需向Client的RTSPResponseStream中放入标准响应内容: RTSP/1.0 200 OK\r\n Server: DSS/5.5.3.7 (Build/489.8; Platform/Linux; Release/Darwin; )\r\n Cseq: 8\r\n \r\n */ void RTPSession::SendAnnounceResponse(RTSPRequestInterface* inRequest) { // // Currently, no need to do anything special for an announce response (void)inRequest->SendHeader(); } /* 正常状态下Run()函数的返回值有两种:如果返回值为正数,代表下一次发送数据包的时间,规定时间到来的时候, TaskThread线程会自动调用Run函数;如果返回值等于0,在下次任何事件发生时,Run函数就会被调用,这种情况 往往发生在所有数据都已经发送完成或者该RTPSession对象将要被杀死的时候。而如果返回值为负数,则TaskThread 线程会delete RTPSession对象 */ SInt64 RTPSession::Run() { #if DEBUG Assert(fActivateCalled); #endif /* first acquire event flags and which event should be send to task(role) */ EventFlags events = this->GetEvents(); QTSS_RoleParams theParams; /* 注意QTSS_RoleParams是联合体,每次只取一个.这里ClientSession就是指RTPSession */ theParams.clientSessionClosingParams.inClientSession = this; //every single role being invoked now has this as the first parameter #if RTPSESSION_DEBUGGING qtss_printf("RTPSession %ld: In Run. Events %ld\n",(SInt32)this, (SInt32)events); #endif // Some callbacks look for this struct in the thread object,设置当前线程的私有数据 OSThreadDataSetter theSetter(&fModuleState, NULL); /****************** CASE: Return -1 ************************************************************************/ //if we have been instructed to go away(走开), then let's delete ourselves if ((events & Task::kKillEvent) || (events & Task::kTimeoutEvent) || (fModuleDoingAsyncStuff)) { /* 假如Module是同步(sync)模式,从RTP Session map中注销本RTPSession的表元,若失败,就发信号去Kill该RTPSession; 若成功,遍历RTPSession中的每个RTPStream,逐一发送BYE包 */ if (!fModuleDoingAsyncStuff) { if (events & Task::kTimeoutEvent) fClosingReason = qtssCliSesCloseTimeout;//关闭RTPSession是因为超时 //deletion is a bit complicated. For one thing, it must happen from within //the Run function to ensure that we aren't getting events when we are deleting //ourselves. We also need to make sure that we aren't getting RTSP requests //(or, more accurately, that the stream object isn't being used by any other //threads). We do this by first removing the session from the session map. #if RTPSESSION_DEBUGGING qtss_printf("RTPSession %ld: about to be killed. Eventmask = %ld\n",(SInt32)this, (SInt32)events); #endif // We cannot block(阻塞) waiting to UnRegister(注销), because we have to // give the RTSPSessionTask a chance to release the RTPSession. /* 获取服务器全局的 RTP Session map,并尝试从中注销本RTPSession的表元,若不成功就发信号去Kill该RTPSession */ OSRefTable* sessionTable = QTSServerInterface::GetServer()->GetRTPSessionMap(); Assert(sessionTable != NULL); if (!sessionTable->TryUnRegister(&fRTPMapElem)) { //Send an event to this task. this->Signal(Task::kKillEvent);// So that we get back to this place in the code return kCantGetMutexIdleTime; /* 10 */ } // The ClientSessionClosing role is allowed to do async stuff fModuleState.curTask = this; /* 若从RTP Session map中成功注销了本RTPSession的表元,则Module可作异步,要从代码中返回(参见RTSPSession::Run()),以等待下次继续接受数据 */ fModuleDoingAsyncStuff = true; // So that we know to jump back to the right place in the code fCurrentModule = 0; // Set the reason parameter in object QTSS_ClientSessionClosing_Params theParams.clientSessionClosingParams.inReason = fClosingReason; // If RTCP packets are being generated internally for this stream, Send a BYE now. RTPStream** theStream = NULL; UInt32 theLen = 0; /* 遍历RTPSession中的每个RTPStream,逐一发送BYE包 */ if (this->GetPlayFlags() & qtssPlayFlagsSendRTCP) { SInt64 byePacketTime = OS::Milliseconds(); for (int x = 0; this->GetValuePtr(qtssCliSesStreamObjects, x, (void**)&theStream, &theLen) == QTSS_NoErr; x++) if (theStream && *theStream != NULL) (*theStream)->SendRTCPSR(byePacketTime, true);//true means send BYE } } //at this point, we know no one is using this session, so invoke the //session cleanup role. We don't need to grab the session mutex before //invoking modules here, because the session is unregistered(注销) and //therefore there's no way another thread could get involved anyway //假如Module是异步模式,现在确信没有Module调用该RTPSession,就调用注册Session cleanup role的Module去关闭它,无须使用互斥锁 UInt32 numModules = QTSServerInterface::GetNumModulesInRole(QTSSModule::kClientSessionClosingRole); { for (; fCurrentModule < numModules; fCurrentModule++) { fModuleState.eventRequested = false; fModuleState.idleTime = 0; QTSSModule* theModule = QTSServerInterface::GetModule(QTSSModule::kClientSessionClosingRole, fCurrentModule); /* 调用模块的Client Session Closing角色,使得模块可以在客户会话关闭时进行必要的处理 */ (void)theModule->CallDispatch(QTSS_ClientSessionClosing_Role, &theParams); // If this module has requested an event, return and wait for the event to transpire(显现,发生) if (fModuleState.eventRequested) return fModuleState.idleTime; // If the module has requested idle time... } } return -1;//doing this will cause the destructor to get called. } /****************** CASE: Return 0 ************************************************************************/ //if the RTP stream is currently paused, just return without doing anything.We'll get woken up again when a play is issued if ((fState == qtssPausedState) || (fModule == NULL)) return 0; /****************** CASE: Return any positive value ************************************************************************/ //Make sure to grab the session mutex here, to protect the module against RTSP requests coming in while it's sending packets { /* 锁定该RTPSession并设置QTSS_SendPackets_Params准备send packets */ OSMutexLocker locker(&fSessionMutex); //just make sure we haven't been scheduled before our scheduled play //time. If so, reschedule ourselves for the proper time. (if client //sends a play while we are already playing, this may occur) /* obtain the current time to send RTP packets */ //设定数据包发送时间,防止被提前发送,刷新QTSS_RTPSendPackets_Params中的当前时间戳 theParams.rtpSendPacketsParams.inCurrentTime = OS::Milliseconds(); /* fNextSendPacketsTime see RTPSessionInterface.h,表示send Packets的绝对时间戳 */ //未到发送时间时处理重传和设置等待发包的时间 if (fNextSendPacketsTime > theParams.rtpSendPacketsParams.inCurrentTime) { /* 重传RTPStream的二维数组 */ RTPStream** retransStream = NULL; UInt32 retransStreamLen = 0; // Send retransmits if we need to /* 先查找该RTPSession的重传流类,为该RTPSession的每个RTPStream设置重传 */ for (int streamIter = 0; this->GetValuePtr(qtssCliSesStreamObjects, streamIter, (void**)&retransStream, &retransStreamLen) == QTSS_NoErr; streamIter++) if (retransStream && *retransStream) (*retransStream)->SendRetransmits(); //计算还需多长时间才可运行。 /*outNextPacketTime是间隔时间,以毫秒为单位。在这个角色返回之前,模块需要设定一个合适 的outNextPacketTime值,这个值是当前时刻inCurrentTime和服务器再次为当前会话调用QTSS_RTPSendPackets_Role 角色的时刻fNextSendPacketsTime之间的时间间隔。*/ /* 为重传包设置重传的时间间隔,隔这么多时间后就发送该重传包 */ theParams.rtpSendPacketsParams.outNextPacketTime = fNextSendPacketsTime - theParams.rtpSendPacketsParams.inCurrentTime; } else /* retransmit scheduled data normally */ { /* 下一个送包时间已过? 马上开始发包了 */ #if RTPSESSION_DEBUGGING qtss_printf("RTPSession %ld: about to call SendPackets\n",(SInt32)this); #endif /* fLastBandwidthTrackerStatsUpdate see RTPSession.h,是否我们忘记更新状态了? */ /* 假如更新间隔超过1000毫秒,立即获取最新的BandWidth */ if ((theParams.rtpSendPacketsParams.inCurrentTime - fLastBandwidthTrackerStatsUpdate) > 1000) /* GetBandwidthTracker() see RTPSessionInterface.h, UpdateStats() see RTPBandwidthTracker.h */ this->GetBandwidthTracker()->UpdateStats(); //下次运行时间的缺省值为0,不管怎样,马上将该包发送出去 /* 将送包时间间隔设置为0,准备发包 */ theParams.rtpSendPacketsParams.outNextPacketTime = 0; // Async event registration is definitely allowed from this role. /* 不用接受可以发包的通知了 */ fModuleState.eventRequested = false; /* make assure that there is a QTSSModule, here we use QTSSFileModule */ /* 因为我们马上要调用这个模块发包 */ /* 试问:它是如何获知QTSSModule是哪个模块的?它的调用在RTSPSession::Run()中的kPreprocessingRequest 和kProcessingRequest等;设置用SetPacketSendingModule(),得到用GetPacketSendingModule() */ Assert(fModule != NULL); /* 调用QTSSFileModuleDispatch(), refer to QTSSFileModule.cpp */ /* QTSS_RTPSendPackets_Role角色的责任是向客户端发送媒体数据,并告诉服务器什么时候模块(只能是QTSSFileModule)的QTSS_RTPSendPackets_Role角色应该再次被调用。*/ (void)fModule->CallDispatch(QTSS_RTPSendPackets_Role, &theParams); #if RTPSESSION_DEBUGGING qtss_printf("RTPSession %ld: back from sendPackets, nextPacketTime = %"_64BITARG_"d\n",(SInt32)this, theParams.rtpSendPacketsParams.outNextPacketTime); #endif //make sure not to get deleted accidently! /* 送完这个包后再设置下次送包的正确的时间间隔 */ /* make sure that the returned value is nonnegative, otherwise will be deleted by TaskTheread */ if (theParams.rtpSendPacketsParams.outNextPacketTime < 0) theParams.rtpSendPacketsParams.outNextPacketTime = 0; /* fNextSendPacketsTime see RTPSessionInterface.h */ /* QTSS_RTPSendPackets_Params中重要的时间关系 */ /* 紧接着设置下次送包的绝对时间戳 吗 */ fNextSendPacketsTime = theParams.rtpSendPacketsParams.inCurrentTime + theParams.rtpSendPacketsParams.outNextPacketTime; } } // Make sure the duration between calls to Run() isn't greater than the max retransmit delay interval.发送间隔(50毫秒)<=重传间隔(仅针对RUDP,默认500毫秒) /* obtain the preferred max retransmit delay time in Msec, see QTSServerInterface.h */ UInt32 theRetransDelayInMsec = QTSServerInterface::GetServer()->GetPrefs()->GetMaxRetransmitDelayInMsec(); /* obtain the preferred duration between two calls to Run() in Msec, see QTSServerInterface.h */ UInt32 theSendInterval = QTSServerInterface::GetServer()->GetPrefs()->GetSendIntervalInMsec(); // We want to avoid waking up to do retransmits, and then going back to sleep for like, 1 msec. So, // only adjust the time to wake up if the next packet time is greater than the max retransmit delay + // the standard interval between wakeups. /* adjust the time to wake up */ /* in general,theRetransDelayInMsec is bigger than theSendInterval 必要时缩短下一个包到来的时间间隔 */ if (theParams.rtpSendPacketsParams.outNextPacketTime > (theRetransDelayInMsec + theSendInterval)) theParams.rtpSendPacketsParams.outNextPacketTime = theRetransDelayInMsec; Assert(theParams.rtpSendPacketsParams.outNextPacketTime >= 0);//we'd better not get deleted accidently! /* return the next desired runtime */ return theParams.rtpSendPacketsParams.outNextPacketTime; }
#ifndef CELLO_COMPONENT_FACTORY_H #define CELLO_COMPONENT_FACTORY_H #include <functional> #include <map> #include <string> #include <stdexcept> #include <core/SimulationTypes.h> #include <util/Util.h> using std::function; using std::map; using std::runtime_error; using std::string; namespace cello { class Atlas; class Component; typedef function<Component*()> ComponentCreator; class ComponentFactory : NonCopyable { public: static ComponentFactory* getInstance(); virtual ~ComponentFactory(); bool registerComponent(ComponentType componentType, string name, ComponentCreator creator); ComponentType getComponentType(string componentTypeStr); string getComponentTypeName(ComponentType componentType); Component* createComponent(ComponentType componentType); protected: ComponentFactory(); private: map<string, ComponentType> _componentTypeNameMap; map<ComponentType, string> _componentTypeMap; map<ComponentType, ComponentCreator> _componentCreatorMap; }; } #endif
#include <iostream> #include <vector> #include <Eigen/Dense> #include <ros/ros.h> #include <ros_node/kalman.h> #include <opencv/cv.h> #include <opencv/highgui.h> using namespace std; //using namespace cv; const int winWidth = 800; const int winHeight = 600; cv::Point mousePosition = cv::Point(winWidth>>1, winHeight>>1); //mouse call back void mouseEvent(int event, int x, int y, int flags, void *param) { if(event==CV_EVENT_MOUSEMOVE) { mousePosition=cv::Point(x,y); } } int main(int argc, char* argv[]) { ros::init(argc, argv, "ros_node_node"); const int stateNum=4; const int measureNum=2; // double dt = 1.0/30; // Time step Eigen::MatrixXd A(stateNum, stateNum); // System dynamics matrix Eigen::MatrixXd C(measureNum, stateNum); // Output matrix Eigen::MatrixXd Q(stateNum, stateNum); // Process noise covariance Eigen::MatrixXd R(measureNum, measureNum); // Measurement noise covariance Eigen::MatrixXd P(stateNum, stateNum); // Estimate error covariance // Discrete LTI projectile motion, measuring position only A << 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1; C << 1, 0, 0, 0, 0, 1, 0, 0; // Reasonable covariance matrices Q << 0.05, 0, 0.05, 0, 0, 0.05, 0, 0.05, 0.05, 0, 0.05, 0, 0, 0.05, 0, 0.05; // Q << 0.0000000005, 0, 0.0000000005, 0, 0, 0.0000000005, 0, 0.0000000005, 0.0000000005, 0, 0.0000000005, 0, 0, 0.0000000005, 0, 0.0000000005; R << 0.1, 0, 0, 0.1; // R << 1000000, 0, 0, 1000000; P << 0.1, 0, 0, 0, 0, 0.1, 0, 0, 0, 0, 0.1, 0, 0, 0, 0, 0.1; std::cout << "A: \n" << A << std::endl; std::cout << "C: \n" << C << std::endl; std::cout << "Q: \n" << Q << std::endl; std::cout << "R: \n" << R << std::endl; std::cout << "P: \n" << P << std::endl; // Construct the filter kalmanfilter kf(0, A, C, Q, R, P); // Best guess of initial states Eigen::VectorXd x0(stateNum); x0 << 0, 0, 0, 0; kf.init(0,x0); cout << "x0: \n" << x0 << endl; Eigen::VectorXd y(measureNum); cv::Mat showImg(winWidth, winHeight,CV_8UC3); for(;;) { cv::setMouseCallback("Kalman", mouseEvent); showImg.setTo(0); y << (double)mousePosition.x, (double)mousePosition.y; kf.update(y); Eigen::VectorXd x_hat = kf.state(); cv::Point predictPt = cv::Point(x_hat[0], x_hat[1]); // circle(showImg, statePt, 5, CV_RGB(255,0,0),1);//former point circle(showImg, predictPt, 5, CV_RGB(0,255,0),1);//predict point circle(showImg, mousePosition, 5, CV_RGB(0,0,255),1);//ture point cv::putText(showImg, "Red: Former Point", cvPoint(10,30), cv::FONT_HERSHEY_SIMPLEX, 1 ,cv::Scalar :: all(255)); cv::putText(showImg, "Green: Predict Point", cvPoint(10,60), cv::FONT_HERSHEY_SIMPLEX, 1 ,cv::Scalar :: all(255)); cv::putText(showImg, "Blue: Ture Point", cvPoint(10,90), cv::FONT_HERSHEY_SIMPLEX, 1 ,cv::Scalar :: all(255)); cv::imshow( "Kalman", showImg ); int key = cv::waitKey(3); if (key == 27) { break; } } ros::spin(); return 0; }
#pragma once #include <string> #include <memory> #include "Logger.hpp" #include "LogSpace.hpp" #include "UserInactivityDetector.hpp" enum class AnswerType { disaccepted, accepted }; class ChatRequest { public: std::string answerForChatRequest(const std::string& senderUsername, const std::string& decision) const; std::string sendChatRequest(const std::string& receiverUsername) const; ChatRequest(); ~ChatRequest(); ChatRequest(ChatRequest &&) = delete; ChatRequest operator=(ChatRequest &&) = delete; ChatRequest(const ChatRequest &) = delete; ChatRequest operator=(const ChatRequest &) = delete; private: bool changeUserStatus(const std::string& username, const std::string& newStatus) const; std::unique_ptr<std::string> getChatFolderName(const std::string& folderName) const; std::unique_ptr<std::string> getUserStatus(const std::string& username) const; bool isUserActive(const std::string& username) const; bool approveChatInvitation() const; std::string sendAnswer(const std::string& senderUsername, AnswerType type) const; void showInvitation(const std::string& senderUsername) const; bool waitForAnswer(const std::string& username) const; Logger _log {LogSpace::ChatStarter}; };
#include "pwmwebserver.h" #include "JsonArrayStream.h" #include "gpiopwm.h" PwmWebServer::PwmWebServer(PwmInterface &pwm) : pwm(pwm), testEndpoint("/test"), endpointChannelCount("/ajax/pwm/channelCount"), endpointTest("/ajax/test"), endpointSetBool("/ajax/setBool"), endpointSetInt("/ajax/setInt"), endpointSetString("/ajax/setString") { endpointChannelCount.setCallback([&pwm]() { return pwm.getChannelCount(); }); endpointTest.setCallback([this]() { return this->get_a_vector(); }); endpointSetBool.setCallback( [](bool value) { debugf("got %s", value ? "true" : "false"); }); endpointSetInt.setCallback([](int value) { debugf("got %d", value); }); endpointSetString.setCallback( [](const String &value) { debugf("got %s", value.c_str()); }); } void PwmWebServer::onAjaxAsArray(HttpRequest &request, HttpResponse &response) { if (request.method == HTTP_GET) { auto *jsonArrayStream = new JsonArrayStream(); auto &array = jsonArrayStream->getRoot(); for (size_t i = 0; i < pwm.getChannelCount(); ++i) array.add(pwm.getDuty(i)); response.sendDataStream(jsonArrayStream, ContentType::toString(MIME_JSON)); } else if (request.method == HTTP_POST) { StaticJsonBuffer<4096> jsonBuffer; auto &root = jsonBuffer.parseArray(request.getBody()); for (size_t i = 0; i < root.size(); ++i) { pwm.setDuty(i, static_cast<uint32>(root[i])); } response.sendString(""); response.code = 200; } } std::array<int, 3> PwmWebServer::get_a_vector() { std::array<int, 3> ret; ret[0] = 1; ret[1] = 2; ret[2] = 3; for (auto &i : ret) { debugf("get_a_vector %d", i); } return ret; } void PwmWebServer::init() { server.listen(80); server.paths.set("/ajax/pwm/asArray", HttpPathDelegate(&PwmWebServer::onAjaxAsArray, this)); server.paths.set(endpointChannelCount.getEndpoint(), endpointChannelCount); server.paths.set(testEndpoint.getEndpoint(), testEndpoint); server.paths.set(endpointTest.getEndpoint(), endpointTest); server.paths.set(endpointSetBool.getEndpoint(), endpointSetBool); server.paths.set(endpointSetInt.getEndpoint(), endpointSetInt); server.paths.set(endpointSetString.getEndpoint(), endpointSetString); server.setBodyParser(ContentType::toString(MIME_JSON), bodyToStringParser); // server.setDefaultHandler(onFile); }
/*! *@FileName: KaiXinApp_StatusFaceList.h *@Author: GoZone *@Date: *@Log: Author Date Description * *@section Copyright * =======================================================================<br> * Copyright ? 2010-2012 GOZONE <br> * All Rights Reserved.<br> * The file is generated by Kaixin_Component Wizard for Tranzda Mobile Platform <br> * =======================================================================<br> */ #ifndef __KAIXINAPI_STATUSFACELIST_H__ #define __KAIXINAPI_STATUSFACELIST_H__ #include "KaiXinAPI.h" typedef struct { int sface; char slogo[256]; int ntype; }StatusFaceList_faces; typedef struct { int ret; int uid; int n; int nSize_faces; //Save the array size by code_gen tools. StatusFaceList_faces* faces; }tResponseStatusFaceList; extern void* KaiXinAPI_StatusFaceList_JsonParse(char *text); class TStatusFaceListForm : public TWindow { public: TStatusFaceListForm(TApplication* pApp); virtual ~TStatusFaceListForm(void); virtual Boolean EventHandler(TApplication * appP, EventType * eventP); private: Boolean _OnWinInitEvent(TApplication * pApp, EventType * pEvent); Boolean _OnWinClose(TApplication * pApp, EventType * pEvent); Boolean _OnCtrlSelectEvent(TApplication * pApp, EventType * pEvent); }; #endif
#include "Shader.h" #include <cstdio> #include <cstdlib> #include <iostream> #include <fstream> #include <sstream> GLuint Shader::currentlyBoundShaderID = 0x0; Shader::Shader() { init = false; } Shader::Shader(const char *vert, const char *frag, bool isFile) { setup(vert, frag, isFile); init = true; } Shader::~Shader() { glDeleteProgram(pid); } void Shader::bind() { if (currentlyBoundShaderID != pid) { currentlyBoundShaderID = pid; glUseProgram(pid); } } void Shader::unbind() { if (currentlyBoundShaderID != (0x0)) { currentlyBoundShaderID = (0x0); glUseProgram(0); } } GLuint &Shader::getPid(){ return currentlyBoundShaderID; } bool Shader::isInitilized(){ return init; } void Shader::printLog(const char* tag) { char glslLog[1024]; GLsizei glslLogSize; //Extract the error log for this shader's pid glGetProgramInfoLog(pid, 1024, &glslLogSize, glslLog); //If the log isn't empty, print the contents if (glslLogSize > 0) std::cerr << tag << "(" << pid << ") - Shader error log:" << std::endl << glslLog << std::endl; else std::cerr << tag << "(" << pid << ") - Shaders compiled successfully!" << std::endl; } void Shader::setup(const GLchar *vs, const GLchar *fs, bool isFile) { std::string vertexCode; std::string fragmentCode; if (isFile){ // 1. Retrieve the vertex/fragment source code from filePath std::ifstream vShaderFile; std::ifstream fShaderFile; // ensures ifstream objects can throw exceptions: vShaderFile.exceptions(std::ifstream::badbit); fShaderFile.exceptions(std::ifstream::badbit); try { // Open files vShaderFile.open(vs); fShaderFile.open(fs); std::stringstream vShaderStream, fShaderStream; // Read file's buffer contents into streams vShaderStream << vShaderFile.rdbuf(); fShaderStream << fShaderFile.rdbuf(); // close file handlers vShaderFile.close(); fShaderFile.close(); // Convert stream into string vertexCode = vShaderStream.str(); fragmentCode = fShaderStream.str(); } catch (std::ifstream::failure e){ std::cout << "ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ" << std::endl; } } else{ vertexCode = vs; fragmentCode = fs; } const GLchar* vShaderCode = vertexCode.c_str(); const GLchar * fShaderCode = fragmentCode.c_str(); // 2. Compile shaders GLuint vertex, fragment; GLint success; GLchar infoLog[512]; // Vertex Shader vertex = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex, 1, &vShaderCode, NULL); glCompileShader(vertex); // Print compile errors if any glGetShaderiv(vertex, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(vertex, 512, NULL, infoLog); std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl; } // Fragment Shader fragment = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment, 1, &fShaderCode, NULL); glCompileShader(fragment); // Print compile errors if any glGetShaderiv(fragment, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(fragment, 512, NULL, infoLog); std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl; } // Shader Program this->pid = glCreateProgram(); glAttachShader(this->pid, vertex); glAttachShader(this->pid, fragment); glLinkProgram(this->pid); // Print linking errors if any glGetProgramiv(this->pid, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(this->pid, 512, NULL, infoLog); std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl; } // Delete the shaders as they're linked into our program now and no longer necessery glDeleteShader(vertex); glDeleteShader(fragment); //Unbind to not mix up shaders //unbind(); }
/** * [Question] * - Insertion Sort のアルゴリズムを実装するにはどうすればよいですか? * * [Solution] * - 前から順に走査 * - 自分より前で昇順になるように適切な位置に挿入 * * [計算量] * - O(N^2) * */ #include <iostream> #include <vector> void straight_insertion_sort(std::vector<int> &v) { // 配列が空 or 長さ1ならソートの必要がない if (v.size() == 0 | v.size() == 1) return; // 配列長が2以上のときはソートを実施 for (int i = 1; i < v.size(); i++) { // 自分より前で適切な位置に挿入する // j が挿入位置になる for (int j = i; j > 0; j--) { // 自分より大きければ後ろにずらす if (v[j-1] > v[j]) std::swap(v[j-1], v[j]); else break; } } } int main() { /* INPUT */ std::vector<int> v = {30, 88, 17, 1, 20, 25, 30, 88, 100, 17, 2, 1}; /* SOLVE */ straight_insertion_sort(v); for (int i = 0; i < v.size(); i++) std::cout << v[i] << " "; std::cout << std::endl; return 0; }
#include "utils.h" #include "..\Constants.h" namespace input { bool convertMouse2Grid(int* gridX, int* gridY) { ds::vec2 mousePos = ds::getMousePosition(); float fy = (mousePos.y - static_cast<float>(STARTY - HALF_CELL_SIZE)) / static_cast<float>(CELL_SIZE); float fx = (mousePos.x - static_cast<float>(STARTX - HALF_CELL_SIZE)) / static_cast<float>(CELL_SIZE); if (fx >= 0.0f && fy >= 0.0f) { int mx = static_cast<int>(fx); int my = static_cast<int>(fy); if (mx < MAX_X && my < MAX_Y) { *gridX = mx; *gridY = my; return true; } } return false; } }
/* * 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 <flux/Stack> #include <flux/rounding> #include <flux/str> namespace flux { String fnum(float64_t x, int precision, int base, int screen) { Ref< Stack<int> > digits = Stack<int>::create(screen < 128 ? 128 : 2 * screen /*save bet*/); uint64_t xi = union_cast<uint64_t>(x); uint64_t f = (xi << 12) >> 12; // fraction int e = int((xi << 1) >> 53); // exponent int s = int(xi >> 63); // sign String text; int i = 0; if ((e == 0x7FF) && (f != 0)) // NaN { return "nan"; } else if ((e == 0x7FF) && (f == 0)) // infinite { return s ? "-inf" : "inf"; } else if ((e == 0) && (f == 0)) // zero { return "0"; } else // if (((0 < e) && (e < 0x7FF)) || ((e == 0) && (f != 0))) // normalized or denormalized number { bool normalized = (0 < e) && (e < 0x7FF); int eb = e - 1023 + int(!normalized); // exponent with bias applied int eba = int(roundToZero(log(pow(float64_t(2.), eb)) / log(float64_t(base)))); // exponent in user defined base float64_t cba = pow(float64_t(2.),float64_t(eb)) / pow(float64_t(base),float64_t(eba)); // correction factor of user defined base uint64_t m = (uint64_t(normalized) << 52) | f; // mantissa const uint64_t q = uint64_t((uint64_t(1) << 52) / cba); // quotient // workaround to prevent leading zeros if (m < q) { m *= base; --eba; } digits->clear(); int ni = 1; // number of digits of integral part if ((-screen <= eba) && (eba <= screen)) { if (eba > 0) { ni += eba; eba = 0; } else { while (eba < 0) { digits->push(0); ++eba; } } } while (digits->count() < precision) { int d = int(m / q); digits->push(d); m -= d * q; m *= base; } int ns = 0; // number of significiant digits { for (int i = 0; i < digits->count(); ++i) if (digits->bottom(i) != 0) ns = i + 1; } int wi = ni + s; int wf = (ns > ni) ? ns - ni : 0; int ne = 0; // number of exponent digits { for (int h = eba; h != 0; h /= base) ++ne; } text = String(wi + int(wf != 0) + wf + int(ne != 0) * (1 + int(eba < 0) + ne), ' '); if (s == 1) text->at(i++) = '-'; const char *fig = "0123456789abcdef"; int k = 0; // digit index for (int l = 0; l < ni; ++l) text->at(i++) = fig[digits->bottom(k++)]; if (wf != 0) { text->at(i++) = '.'; for (int l = 0; l < wf; ++l) { if (digits->count() <= k) text->at(i++) = '0'; else text->at(i++) = fig[digits->bottom(k++)]; } } if (ne != 0) { text->at(i++) = 'e'; if (eba < 0) { text->at(i++) = '-'; eba = -eba; } for (int l = ne-1, h = eba; l >= 0; --l, h /= base) text->at(i+l) = fig[h % base]; i += ne; } } return text; } String fixed(float64_t x, int nf) { double ip; double fp = modf(x, &ip); String sip = inum(int64_t(ip)); if (nf <= 0) return sip; String s = String(sip->count() + 1 + nf, '.'); *s = *sip; if (fp < 0) fp = -fp; for (int i = 0; i < nf; ++i) fp *= 10; fp = round(fp); *(s->select(sip->count() + 1, s->count())) = *right(inum(uint64_t(fp)), nf, '0'); return s; } String dec(const Variant &x, int n) { return (type(x) == Variant::FloatType) ? dec(float(x), n > 0 ? n : 7) : dec(int(x), n); } String str(void *x) { if (sizeof(void *) == sizeof(uint64_t)) return dec(union_cast<uint64_t>(x)); return dec(union_cast<uint32_t>(x)); } String left(const String &s, int w, char blank) { if (s->count() > w) return s; else return s + String(w - s->count(), blank); } String right(const String &s, int w, char blank) { if (s->count() > w) return s; else return String(w - s->count(), blank) + s; } } // namespace flux
#include <bits/stdc++.h> #define ll long long std::map<ll , ll> f ; int T ; ll n , k ; ll solve(ll x) { if (x <= k) return 1 ; if (f.count(x)) return f[x] ; ll res = 1 + solve(x >> 1) + solve(x - (x >> 1)) ; return (f[x] = res) ; } int main() { scanf("%d" , &T) ; for (; T-- ;) { scanf("%lld %lld" , &n , &k) ; f.clear() ; f[1] = 1 ; printf("%lld\n" , solve(n)) ; } return 0 ; }
void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); pinMode(2, OUTPUT); digitalWrite(A2, LOW); } // the loop routine runs over and over again forever: void loop() { //determines the levels of dryness unsigned char green=25; unsigned char yellow=50; unsigned char red=60; //Turns off all lights at the start of the loop to ensure only 1 light can be on at a time digitalWrite(4, LOW); digitalWrite(3, LOW); digitalWrite(2, LOW); // read the input on analog pin 0 and devides it by 10 so it can be saved in a char and outputs are more stable: unsigned char sensorValue = analogRead(A0)/10; // print out the value you read, together with the values for dryness levels //code is printed in this order so the colors match in the plotter Serial.print(sensorValue); Serial.print(","); Serial.print(red); Serial.print(","); Serial.print(green); Serial.print(","); Serial.println(yellow); //determines what happens if the sensor value reaches certain levels of dryness if(sensorValue>red){ Serial.println("Ground is too dry"); digitalWrite(4, HIGH); delay(500); digitalWrite(4, LOW); delay(500); }else { //no standard "else if" to make sure there will always be a delay of 1 second if(sensorValue>yellow){ Serial.println("the plants will need water soon"); digitalWrite(3, HIGH); }else if(sensorValue<green){ Serial.println("the plants are properly watered"); digitalWrite(2, HIGH); } else { Serial.println("no action required"); } delay(1000); } }
#include<bits/stdc++.h> using namespace std; int main(){ string s,s1; cin>>s>>s1; reverse(s.begin(),s.end()); if(s==s1) cout<<"YES"; else cout<<"NO"; return 0; }
#include <iostream> #include <time.h> #include <cstdlib> #include <vector> #include <limits.h> #include <utility> #include <chrono> #include <math.h> using namespace std; const int BOARD_SIDE = 10000; const int SAMPLE_SIZE = 25 * log2(BOARD_SIDE); const int CAP_ZEROS = 2 * log2(BOARD_SIDE); typedef vector<vector<int>> vvi; typedef pair<int, int> pii; const int MOVES_FOR_RESTART = 350; class Game { public: void generateInitialBoard() { initSizes(); chrono::steady_clock::time_point begin = chrono::steady_clock::now(); for (int i = 0; i < BOARD_SIDE; i++) { vector<int> candidates; vector<int> conflitsCurrentRow(BOARD_SIDE); int minConflicts = INT_MAX; vector<int> samples; samples.resize(SAMPLE_SIZE); vector<int> zeros; for (int j = 0; j < SAMPLE_SIZE; j++) { int sampleIdx = rand() % BOARD_SIDE; samples[j] = sampleIdx; int conflicts = getConflictsAtPosition(i, samples[j]); if (conflicts == -3) { // because of the way getConflictsAtPosition is implemented zeros.push_back(samples[j]); if (zeros.size() >= CAP_ZEROS) { break; } } if (conflicts < minConflicts) { minConflicts = conflicts; } } if (zeros.size() < CAP_ZEROS) { for (int j = 0; j < samples.size(); j++) { int conflicts = getConflictsAtPosition(i, samples[j]); if (conflicts == minConflicts) { candidates.push_back(samples[j]); } } } int pos = (zeros.size() < CAP_ZEROS) ? candidates[rand() % candidates.size()] : zeros[rand() % zeros.size()]; queens[i] = pos; updateConflicts(i, pos, 1); } chrono::steady_clock::time_point end = chrono::steady_clock::now(); cout << "Initialization took: " << chrono::duration_cast<chrono::milliseconds>(end - begin).count() << "[ms]" << endl; } int getTotalConflicts() { return getConflictFromDirecton(conflictsMainDiag) + getConflictFromDirecton(conflictsSecDiag) + getConflictFromDirecton(conflictsColumns); } void makeMove() { int maxConflicts = 0; vector<int> candidates; for (int i = 0; i < queens.size(); i++) { int currentConflicts = getConflictsAtPosition(i, queens[i]); if (currentConflicts > maxConflicts) { maxConflicts = currentConflicts; } } for (int i = 0; i < queens.size(); i++) { int currentConflicts = getConflictsAtPosition(i, queens[i]); if (currentConflicts == maxConflicts) { candidates.push_back(i); } } int worstQueenIdx = candidates[rand() % candidates.size()]; int minConflicts = INT_MAX; vector<int> moveCandidates; for (int i = 0; i < BOARD_SIDE; i++) { int currentConflicts = getConflictsAtPosition(worstQueenIdx, i); if (currentConflicts < minConflicts) { minConflicts = currentConflicts; } } for (int i = 0; i < BOARD_SIDE; i++) { int currentConflicts = getConflictsAtPosition(worstQueenIdx, i); if (currentConflicts == minConflicts) { moveCandidates.push_back(i); } } int movePos = moveCandidates[rand() % moveCandidates.size()]; updateConflicts(worstQueenIdx, queens[worstQueenIdx], -1); updateConflicts(worstQueenIdx, movePos, 1); queens[worstQueenIdx] = movePos; } void solveRandomRestart() { int moves = 0; int restarts = 0; while (getTotalConflicts() > 0) { if (moves > MOVES_FOR_RESTART) { generateInitialBoard(); restarts++; moves = 0; continue; } makeMove(); moves++; } cout << "moves: " << moves << endl; cout << "restarts: " << restarts << endl; if (BOARD_SIDE <= 15) { printBoard(); } } private: vector<int> queens; vector<int> conflictsMainDiag; vector<int> conflictsSecDiag; vector<int> conflictsColumns; int getMainDiag(int x, int y) { return (BOARD_SIDE - 1 - x + y); } int getSecDiag(int x, int y) { return x + y; } int getConflictsAtPosition(int x, int y) { return conflictsColumns[y] + conflictsMainDiag[getMainDiag(x, y)] + conflictsSecDiag[getSecDiag(x, y)] - 3; } void initSizes() { queens.assign(BOARD_SIDE, 0); conflictsColumns.assign(BOARD_SIDE, 0); conflictsMainDiag.assign(2 * BOARD_SIDE - 1, 0); conflictsSecDiag.assign(2 * BOARD_SIDE - 1, 0); } int getConflictFromDirecton(vector<int>& v) { int sum = 0; for (int conf : v) { if (conf > 1) { sum += (conf - 1); } } return sum; } void updateConflicts(int x, int y, int factor) { conflictsColumns[y] += factor; conflictsMainDiag[getMainDiag(x, y)] += factor; conflictsSecDiag[getSecDiag(x, y)] += factor; } void printBoard(){ for(int i = 0; i < BOARD_SIDE; i++){ for(int j = 0; j < BOARD_SIDE; j++){ if(j == queens[i]){ cout << "X "; } else { cout << "- "; } } cout << endl; } } }; int main() { srand(time(nullptr)); ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); chrono::steady_clock::time_point begin = chrono::steady_clock::now(); Game game; game.generateInitialBoard(); game.solveRandomRestart(); chrono::steady_clock::time_point end = chrono::steady_clock::now(); cout << "Time difference = " << chrono::duration_cast<chrono::milliseconds>(end - begin).count() << "[ms]" << endl; }