text
stringlengths
8
6.88M
//===-- mess/simple-cli-client.hh - SimpleCLIClient class -------*- C++ -*-===// // // ODB Library // Author: Steven Lariau // //===----------------------------------------------------------------------===// /// /// \file /// SimpleCLIClient class definition. Can be used on client or server side /// //===----------------------------------------------------------------------===// #pragma once #include "../server/fwd.hh" #include "fwd.hh" #include <string> #include <vector> namespace odb { /// This is a basic CLI to communicate with the Debugger /// Can be used either Server Side or client side /// It takes a string (line command), parse it, use DBClient API, and produce a /// new string with the results. /// /// Available commands: /// Each command is a space-separated list of arguments /// /// /// Print registers: /// preg <type> <reg>+ /// /// /// Update registers /// sreg <type> (<reg> <val>)+ /// /// Print registers infos /// pregi <reg>+ /// /// Read memory /// pmem <type> <val> (addr) <int> (nb items) /// /// Write memory /// smem <type> <val> (addr) <val>+ /// /// Print symbol informations /// psym <symbol> /// /// Print code at current position /// code <int=3> (nb-lines, before and after current position) /// /// Add breakpoint /// b <val> (address) /// /// Delete breakpoint /// delb <val> (address) /// /// Resume execution: /// c / continue (continue) /// s / step (step) /// n / next (step over) /// fin / finish (step out) /// /// Print current state informations (addr, stack) /// state /// /// Print call stack /// bt /// /// Print VM informations /// vm /// /// /// Usual arguments: /// <type>: u8, i8, u16, i16, u32, i32, u64, i64, f32, f64 /// <reg>: '%' (<reg-name> | <reg-id>) /// <val>: <int> | <float> | <symbol> /// (If symbol, val is symbol address) /// <symbol>: '@' (<symbol-name> | <symbol-id>) /// <int> : signed in base 2/8/10/16 /// prefix 0b, 0, and 0x to change bases /// class SimpleCLIClient { public: SimpleCLIClient(DBClient &env); SimpleCLIClient(const SimpleCLIClient &) = delete; std::string exec(const std::string &cmd); private: DBClient &_env; std::vector<std::string> _cmd; std::string _cmd_preg(); std::string _cmd_sreg(); std::string _cmd_pregi(); std::string _cmd_pmem(); std::string _cmd_smem(); std::string _cmd_psym(); std::string _cmd_code(); std::string _cmd_b(); std::string _cmd_delb(); std::string _cmd_continue(); std::string _cmd_step(); std::string _cmd_next(); std::string _cmd_finish(); std::string _cmd_state(); std::string _cmd_bt(); std::string _cmd_vm(); }; } // namespace odb
#include <Arduino.h> #include <EEPROM.h> #define EEPROM_SIZE 128 int eepromAddress[3] = {0, 32, 64}; String sentences[3] = {"State success", "SSID success", "PWD success"}; char readData[32], receivedData[32], ssid[32], pwd[32]; int dataIndex = 0; char *strings[128]; char *ptr = NULL; char test2[128]; bool test = true; char *First; char *Second; void readEEPROM(int address, char *data); void writeEEPROM(int address, char *data); void setup() { Serial.begin(9600); // Initialize EEPROM EEPROM.begin(EEPROM_SIZE); delay(100); readEEPROM(0, readData); Serial.print("Isi EEPROM 0: "); Serial.println(readData); readEEPROM(32, ssid); Serial.print("Isi EEPROM 32: "); Serial.println(ssid); readEEPROM(64, pwd); Serial.print("Isi EEPROM 64: "); Serial.println(pwd); } void changeChar(char nameValue); void loop() { if (Serial.available()) { receivedData[dataIndex] = Serial.read(); dataIndex++; if (receivedData[dataIndex - 1] == '\n') { byte indexstrok = 0; ptr = strtok(receivedData, ";"); while (ptr != NULL) { strings[indexstrok] = ptr; indexstrok++; ptr = strtok(NULL, ";"); } Serial.println("String: " + String(strings[0])); Serial.println("String: " + String(strings[1])); dataIndex = 0; writeEEPROM(32, strings[0]); writeEEPROM(64, strings[1]); test2[0] = '1'; writeEEPROM(0, test2); // dataIndex = 0; //writeEEPROM(0, ptr); //memset(receivedData, 0, EEPROM_SIZE); } } } void readEEPROM(int address, char *data) { for (int i = 0; i < 32; i++) { data[i] = EEPROM.read(address + i); } } void writeEEPROM(int address, char *data) { Serial.println("Start Writing to EEPROM"); for (int i = 0; i < 32; i++) { EEPROM.write(address + i, data[i]); } EEPROM.commit(); } void changeChar(char nameValue) { Serial.println("Entering Funcction"); int i = 0; char str[] = {nameValue}; char delim[] = ","; char *token = strtok(str, delim); while (i < 3) { token = strtok(NULL, delim); sentences[i] = token; i++; } for (int i = 0; i < 2; i++) { Serial.println(sentences[i]); } } /* #include <Arduino.h> #include <Wire.h> #include <SPI.h> #include <EEPROM.h> //light sensor #define bh1750Address 0x23 #define bh1750Len 2 //function Light Sensor void bh1750Req(int address); int bh1750Read(int address); // variable Light Sensors byte buff[2]; unsigned short lux = 0; //define Led and Button Pin #define LED1 2 #define LED2 4 #define LED3 16 #define LED4 17 #define button 15 int btnState; //btn volatile bool interruptState = false; int totalInterruptCounter = 0; hw_timer_s *timer = NULL; portMUX_TYPE timerMux = portMUX_INITIALIZER_UNLOCKED; // char *strings[128]; char *ptr = NULL; void IRAM_ATTR gpioISR() { //ledStatus = !ledStatus; //digitalWrite(BUILTIN_LED,ledStatus); } void autoBrightness(); //auto brightness function //EEPROM Configurations #define eepromSize 128 #define eepromState 0 #define eepromSSID 32 #define eepromPWD 64 char readState[32], receivedData[32], readSSID[32], receiveSSID[32], readPWD[32], receivePWD[32]; int dataIndex = 0; char readSerial[32]; int serialIndex = 0; // char *ssid; char *pwd; //* Function void readEEPROM(int address, char *data); void writeEEPROM(int address, char *data); void setup() { // put your setup code here, to run once: Wire.begin(); EEPROM.begin(eepromSize); delay(200); pinMode(LED1, OUTPUT); pinMode(LED2, OUTPUT); pinMode(LED3, OUTPUT); pinMode(LED4, OUTPUT); pinMode(button, INPUT_PULLUP); Serial.begin(9600); //* Read EEPROM State readEEPROM(eepromState, readState); Serial.println("LED State = " + String(readState)); //* Read EEPROM SSID readEEPROM(eepromSSID, readSSID); Serial.println("SSID = " + String(readSSID)); //*Read EEPROM PWD readEEPROM(eepromPWD, readPWD); Serial.println("PWD = " + String(readPWD)); } void loop() { //! Write EEPROM if (Serial.available()) { receiveSSID[dataIndex] = Serial.read(); dataIndex++; if (receiveSSID[dataIndex - 1] == '\n') { //Parsing Data byte indexstrok = 0; ptr = strtok(receivedData, ";"); while (ptr != NULL) { strings[indexstrok] = ptr; indexstrok++; ptr = strtok(NULL, ";"); } ssid = strings[0]; pwd = strings[1]; dataIndex = 0; writeEEPROM(eepromSSID,ssid); memset(ssid, 0, eepromSize); writeEEPROM(eepromSSID, receiveSSID); memset(receiveSSID, 0, eepromSize); } } //! AutoBRightness /* if (Serial.available()) { Serial.println("Masukkan SSID"); receiveSSID[dataIndex] = Serial.read(); dataIndex++; if (receiveSSID[dataIndex - 1] == '\n') { dataIndex = 0; writeEEPROM(eepromSSID, readSSID); memset(receiveSSID, 0, eepromSize); } */ /*else if (Serial.read() == '2') { receivePWD[dataIndex] = Serial.read(); dataIndex++; if (receivePWD[dataIndex - 1] == '\n') { dataIndex = 0; writeEEPROM(eepromPWD, readPWD); memset(receivePWD, 0, eepromSize); } } else if (Serial.read() == '3') { receiveState[dataIndex] = Serial.read(); dataIndex++; if (receiveState[dataIndex - 1] == '\n') { dataIndex = 0; writeEEPROM(eepromState, readState); memset(receiveState, 0, eepromSize); } } } } */ /* void bh1750Req(int address) { Wire.beginTransmission(address); Wire.write(0x10); Wire.endTransmission(); } int bh1750read(int address) { int i = 0; Wire.beginTransmission(address); Wire.requestFrom(address, 2); while (Wire.available()) { buff[i] = Wire.read(); i++; } Wire.endTransmission(); return i; } */ /*void autoBrightness() { if (btnState == !1) { memcpy(writepage, "ON", sizeof("ON")); spiChip.erasePageSector(0xFFFF); spiChip.pageWrite(writepage, 0XFFFF); Serial.println("Writing is Done"); if (bh1750read(bh1750address) == bh1750Len) { lux = (((unsigned short)buff[0] << 8) | (unsigned short)buff[1]) / 1.2; Serial.println("LUX : " + String(lux)); } if (lux >= 0 && lux <= 250) { digitalWrite(LED1, HIGH); digitalWrite(LED2, HIGH); digitalWrite(LED3, HIGH); digitalWrite(LED4, HIGH); } else if (lux >= 251 && lux <= 500) { digitalWrite(LED1, HIGH); digitalWrite(LED2, HIGH); digitalWrite(LED3, HIGH); digitalWrite(LED4, LOW); } else if (lux >= 501 && lux <= 750) { digitalWrite(LED1, HIGH); digitalWrite(LED2, HIGH); digitalWrite(LED3, LOW); digitalWrite(LED4, LOW); } else if (lux >= 751 && lux <= 1000) { digitalWrite(LED1, HIGH); digitalWrite(LED2, LOW); digitalWrite(LED3, LOW); digitalWrite(LED4, LOW); } else { digitalWrite(LED1, LOW); digitalWrite(LED2, LOW); digitalWrite(LED3, LOW); digitalWrite(LED4, LOW); } } else { memcpy(writepage, "OFF", sizeof("OFF")); spiChip.erasePageSector(0xFFFF); spiChip.pageWrite(writepage, 0XFFFF); Serial.println("Writing is Done"); digitalWrite(LED1, LOW); digitalWrite(LED2, LOW); digitalWrite(LED3, LOW); digitalWrite(LED4, LOW); } delay(2000); } */ /* //EEPROM Configurations void readEEPROM(int address, char *data) { for (int i = 0; i < eepromSize; i++) { data[i] = EEPROM.read(address + 1); } } void writeEEPROM(int address, char *data) { Serial.println("Start Writing to EEPROM"); for (int i = 0; i < eepromSize; i++) { EEPROM.write(address + i, data[i]); } EEPROM.commit(); } */
/** * Programming Assignment #4 : Six Degrees of Kevin Bacon * CSC300 - Data Structures - Fall 2015 * Professor: Dr. John Weiss * * Author: Lucas Carpenter * * Compile: g++ -O -o Bacon_Number -std=c++14 BaconGame.cpp Graph.cpp * * Usage: Bacon_Number <database_file> [alternate_start] **/ //preprocessors #include <ctime> #include <iostream> #include <fstream> #include "Graph.h" using namespace std; //function prototypes bool handleDatabase ( char* file, Graph g ); /** * main(int, char*), the starting point of the program, if the arguments * in are 2 or 3, the program will read the input file for <database_file> * and initialize the graph class, setting the 'center' to [alternate_start] * If an invalid number of arguments are input, it will print an error message * and a usage statement. **/ int main ( int argc, char* argv[] ) { if ( argc == 3 ) { // starts the game with an alternate 'center' Graph g ( argv[2] ); handleDatabase ( argv[1], g ); } else if ( argc == 2 ) { // starts the game with the default 'center' Graph g ( "Bacon, Kevin" ); handleDatabase ( argv[1], g ); } else { // usage statement cout << "Usage: Bacon_Number <database_file> [alternate_start]\n\n" << "database_file - contains records of the form: \n\t Movie Name/actor1/actor2/...\n" << "alternate_start - supply a different center of universe, default = \"Bacon, Kevin\"\n" << "\t quotes are required\n"; return 1; } return 0; } /** * handleDatabase(char*, Graph), takes an input file from char*, and * dissects the contents into movies and actors to be stored in Graph * Also handles outputting onto the screen using Graph's member functions * and handling the menu once the Graph has been built. **/ bool handleDatabase ( char* file, Graph g ) { ifstream in; in.open ( file, ios::in ); if ( !in ) { cout << "Unable to open file " << file << ". Exiting Program.\n"; return false; } string data = ""; int pos; // while the file has information to read, read it. auto c1 = clock(); while ( getline ( in, data ) ) { pos = data.find ( '/' ); // find the end of the movie title if ( !g.setMovie ( data.substr ( 0, pos ) ) ) return false;// set current movie data = data.substr ( pos + 1, data.length() ); // change data input to just have actors do { pos = data.find ( '/' ); if ( pos == -1 ) pos = data.length(); if ( !g.addActor ( data.substr ( 0, pos ) ) ) return false; if ( pos != data.length() ) data = data.substr ( pos + 1, data.length() ); else data = ""; } while ( data != "" ); } auto c2 = clock(); // prints movie hash table size and actors hash table size to the screen cout << "Reading movies: " << g.getMovieSize() << " and " << g.getActorSize() << " actors in database.\n"; cout << "Elapsed time: "; auto totaltime = c2 - c1; cout << ( totaltime / ( CLOCKS_PER_SEC ) ) << " sec\n"; g.printCentersMovies(); g.createMST(); g.printStats(); string prompt = ""; while ( true ) { cout << "Enter the name of an actor <Last, First> \"\" to exit: "; getline ( cin, prompt ); if ( prompt == "" ) exit ( 0 ); g.getPath ( prompt ); } return true; }
/* ======================================================================== DEVise Data Visualization Software (c) Copyright 1992-1996 By the DEVise Development Group Madison, Wisconsin All Rights Reserved. ======================================================================== Under no circumstances is this software to be copied, distributed, or altered in any way without prior permission from the DEVise Development Group. */ /* $Id: Exit.c,v 1.12 1996/12/20 16:49:27 wenger Exp $ $Log: Exit.c,v $ Revision 1.12 1996/12/20 16:49:27 wenger Conditionaled out RTree code for libcs and attrproj. Revision 1.11 1996/12/15 06:52:31 donjerko Added the initialization and shutdown for RTree code. Revision 1.10 1996/11/26 09:29:59 beyer The exit code now removes the temp directory for its process. This could be more portable -- right now it just calls 'rm -fr'. Revision 1.9 1996/09/04 21:24:48 wenger 'Size' in mapping now controls the size of Dali images; improved Dali interface (prevents Dali from getting 'bad window' errors, allows Devise to kill off the Dali server); added devise.dali script to automatically start Dali server along with Devise; fixed bug 037 (core dump if X is mapped to a constant); improved diagnostics for bad command-line arguments. Revision 1.8 1996/05/20 18:44:59 jussi Merged with ClientServer library code. Revision 1.7 1996/05/20 17:47:37 jussi Had to undo some previous changes. Revision 1.6 1996/05/09 18:12:11 kmurli No change to this makefile. Revision 1.5 1996/04/22 21:10:42 jussi Error message printed to console includes file name and line number. Revision 1.4 1996/04/16 19:45:35 jussi Added DoAbort() method and DOASSERT macro. Revision 1.3 1996/01/11 21:51:14 jussi Replaced libc.h with stdlib.h. Added copyright notice. Revision 1.2 1995/09/05 21:12:45 jussi Added/updated CVS header. */ #include <stdio.h> #include <stdlib.h> //#include <unistd.h> #include <string.h> #include <io.h> #include "Exit.h" #if !defined(LIBCS) && !defined(ATTRPROJ) #include "Init.h" #include "Control.h" //#include "DaliIfc.h" #endif //#if !defined(LIBCS) && !defined(ATTRPROJ) //#include "RTreeCommon.h" //#endif void Exit::DoExit(int code) { //#if !defined(LIBCS) && !defined(ATTRPROJ) // shutdown_system(VolumeName, RTreeFile, VolumeSize); //#endif //#if !defined(LIBCS) && !defined(ATTRPROJ) //if (Init::DoAbort()) { // fflush(stdout); // fflush(stderr); // abort(); //} //if (Init::DaliQuit()) { // (void) DaliIfc::Quit(Init::DaliServer()); //} //#endif // hack to get rid of temp directory - this could probably be written // a bit more portably, but oh well. char *tmpDir = getenv("DEVISE_TMP"); if (!tmpDir) tmpDir = "tmp"; pid_t pid = getpid(); char buf[512]; DOASSERT(strlen(tmpDir) + 25 <= 512, "String space too small"); sprintf(buf, "rm -fr %s/DEVise_%ld", tmpDir, (long)pid); system(buf); exit(code); } void Exit::DoAbort(char *reason, char *file, int line) { char fulltext[256]; sprintf(fulltext, "%s (%s:%d)", reason, file, line); fprintf(stderr, "An internal error has occurred. The reason is:\n"); fprintf(stderr, " %s\n", fulltext); //#if !defined(LIBCS) && !defined(ATTRPROJ) //ControlPanel::Instance()->DoAbort(fulltext); //if (Init::DaliQuit()) { // (void) DaliIfc::Quit(Init::DaliServer()); //} //#endif DoExit(2); }
#include <stdio.h> #include<stdlib.h> /*Programa que muestra la sumatoria de los numeros pares e impares del 1 al 100 Fecha:15 Febrero 2018 Elaborado por: Viviana Rojas Ruiz*/ int main() { int i; int *pn; int num=100; int sumaPares=0; int sumaImpar=0; pn=new int[num]; for(i=0;i<num;i++){ pn[i]=i; if(i%2==0){ sumaPares=sumaPares+i; }else if(i%2==1){ sumaImpar=sumaImpar+i; } } for(i=0;i<num;i++){ printf("%d ",*(pn+i)); } printf("\nSuma Pares==> %d",sumaPares); printf("\nSuma Impares==> %d",sumaImpar); delete[]pn; return 0; }
#ifndef NESTED_INTEGRATION_FUSION_ITERATE_HPP #define NESTED_INTEGRATION_FUSION_ITERATE_HPP #include <boost/fusion/iterator/equal_to.hpp> #include <boost/fusion/include/equal_to.hpp> #include <boost/fusion/iterator/key_of.hpp> #include <boost/fusion/include/key_of.hpp> #include <boost/fusion/support/is_sequence.hpp> #include <boost/fusion/include/is_sequence.hpp> #include "nested/integration/iterate.hpp" #include "nested/integration/state.hpp" namespace nested { namespace integrate { namespace iterate { namespace fusion { namespace detail { template<typename State, typename First, typename Last, typename F> inline void iterate(First const&, Last const&, F&, boost::mpl::true_) {} template<typename State, typename First, typename Last, typename F> inline void iterate(First const& first, Last const& last, F& f, boost::mpl::false_) { using namespace boost::fusion; typedef typename result_of::key_of<First>::type key_type; f.template operator()<typename integrate::state::next<State, key_type>::type>(*first); detail::iterate<State>(next(first), last, f, result_of::equal_to<typename result_of::next<First>::type, Last>()); } } // namespace detail template<typename State, typename T> struct iteration { typedef boost::fusion::traits::is_sequence<T> iterable; template<typename Functor> static void iterate(T& sequence, Functor& functor) { dispatch(sequence, functor, iterable()); } private: template<typename Functor> static void dispatch(T& sequence, Functor& functor, boost::mpl::true_) { using namespace boost::fusion; detail::iterate<State>(begin(sequence), end(sequence), functor, result_of::equal_to<typename result_of::begin<T>::type, typename result_of::end<T>::type>()); } template<typename Functor> static void dispatch(T& sequence, Functor& functor, boost::mpl::false_) { iterate::iterate<State>(sequence, functor); } }; // struct iteration } // namespace fusion } // namespace iterate } // namespace integrate } // namespace nested #endif // #ifndef NESTED_INTEGRATION_FUSION_ITERATE_HPP
#include "TextureManager.hpp" #include <QImageReader> #include "LevelManager.hpp" using namespace Maint; using namespace OMGTarga; using namespace std; TextureManager::TextureManager() : _levelManager(NULL) { } TextureManager::~TextureManager() { for(QHash<QString, QImage*>::iterator it = images.begin(); it != images.end(); ++it) { delete *it; } int targaCount = targaDataList.size(); for(int i = 0; i < targaCount; ++i) { delete [] targaDataList[i]; } } void TextureManager::SetLevelManager(LevelManager *levelManager) { _levelManager = levelManager; } QImage* TextureManager::GetTexture(const QString& path) { if(_levelManager == NULL) { return NULL; } QHash<QString, QImage*>::iterator it = images.find(path); if(it != images.end()) { return *it; } Targa targa; QString absolutePath = _levelManager->ConfigRelativeToAbsolutePath(path); if(!targa.LoadFromFile(absolutePath.toStdString())) { return NULL; } unsigned char* imageData = new unsigned char[targa.GetImageDataSize(ByteOrder::RGB, ScreenOrigin::TopLeft)]; targa.GetImageData(imageData, ByteOrder::RGB, ScreenOrigin::TopLeft); short int width = targa.GetWidth(); short int height = targa.GetHeight(); QImage* image = new QImage(imageData, width, height, QImage::Format_ARGB32); images.insert(path, image); targaDataList.push_back(imageData); TextureChanged(path); return image; }
#pragma once #include "Types.h" #include <SDL.h> class Inputs { private: SDL_Event event; public: bool keyPressed[(int)InputKey::COUNT]; bool keyDown[(int)InputKey::COUNT]; Vec2 mousePosition; Inputs(); void UpdateInputs(); void SetKey(InputKey key, bool value); void SetAllFalse(); bool* GetInputs(); Vec2 GetMousePosition(); bool GetKey(InputKey key); ~Inputs(); };
/* OVERVIEW: You are given 2 bank statements that are ordered by date. Write a function that returns dates common to both statements (ie both statements have transactions in these dates). E.g.: Input: A[3] = { { 10, "09-10-2003", "First" }, { 20, "19-10-2004", "Second" }, { 30, "03-03-2005", "Third" } }; B[3] = { { 10, "09-10-2003", "First" }, { 220, "18-01-2010", "Sixth" }, { 320, "27-08-2015", "Seventh" } }; Output: { { 10, "09-10-2003", "First" } } INPUTS: Two bank statements (array of transactions). OUTPUT: Transactions having same dates. ERROR CASES: Return NULL for invalid inputs. NOTES: */ #include <iostream> int Older1(char*, char*); int dateCheck1(int, int, int); int Valid1(char*, char*); struct transaction { int amount; char date[11]; char description[20]; }; struct transaction * sortedArraysCommonElements(struct transaction *A, int ALen, struct transaction *B, int BLen) { int n, i=0,equal,j=0,k=0; struct transaction *result; if (A == NULL || B == NULL || ALen <= 0 || BLen <= 0) return NULL; result = (struct transaction*)malloc((ALen + BLen)*sizeof(struct transaction)); //result = NULL; if (ALen <= BLen) n = ALen; else n = BLen; for (j = 0; j < n;) { if (Older1(A[j].date, B[k].date) == 1) j++; else if (Older1(A[j].date, B[k].date) == 2) k++; else{ result[i] = A[j]; i++; j++; k++; } } if (i == 0) return NULL; return result; } int Older1(char *dob1, char *dob2) { if ((dob1[2] != '-') || (dob2[2] != '-') || (dob1[5] != '-') || (dob2[5] != '-')) return -1; else{ return(Valid1(dob1, dob2)); } } int Valid1(char *d1, char *d2) { int i = 9, a1[3], a2[3], k = 0, t = 1, p = 0, c = 0; while (i >= 0) { if (d1[i] != '-') { if ((d1[i] >= 48 && d1[i] <= 57) && (d2[i] >= 48 && d2[i] <= 57)) { if (t == 1) { k = k + ((int)d1[i] - 48); p = p + ((int)d2[i] - 48); t++; } else if (t == 2) { k = k + 10 * ((int)d1[i] - 48); p = p + 10 * ((int)d2[i] - 48); t++; } else if (t == 3) { k = k + 100 * ((int)d1[i] - 48); p = p + 100 * ((int)d2[i] - 48); t++; } else{ k = k + 1000 * ((int)d1[i] - 48); p = p + 1000 * ((int)d2[i] - 48); t++; } } else return -1; } else{ a1[c] = k; a2[c] = p; c++; k = 0; p = 0; t = 1; } i--; } a1[c] = k; a2[c] = p; c = dateCheck1(a1[2], a1[1], a1[0]); if (c == 0) return -1; c = dateCheck1(a2[2], a2[1], a2[0]); if (c == 0) return -1; for (c = 0; c <3; c++) { if (a2[c] > a1[c]) return 1; if (a1[c] > a2[c]) return 2; } return 0; } int dateCheck1(int date, int month, int year) { if (date<1 || date>31 || month<1 || month>12 || year<0) return 0; else if (((month == 4) || (month == 6) || (month == 9) || (month == 11)) && (date <= 30)) { return 1; } else if ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && (date <= 31)) { return 1; } else if (month == 2) { if (year % 4 != 0 && date <= 28) return 1; else if (year % 4 == 0 && date <= 29) return 1; else return 0; } else return 0; }
#include "DisplayManager.h" #include "Loader.h" #include "Render.h" #include "RawModel.h" #include "StaticShader.h" #include "Camera.h" const char* VERTEX_SHADER_FILLPATH = "../../Shader/vertexShader.vs"; const char* FRAGMENT_SHADER_FILLPATH = "../../Shader/fragmentShader.fs"; const char* IMAGE1_FILLPATH = "../../Shader/container.jpg"; const char* IMAGE2_FILLPATH = "../../Shader/awesomeface.png"; Camera mCamera = glm::vec3(0.0f, 0.0f, 3.0f); int main() { DisplayManager mDisplayManager; mDisplayManager.CreateDisplay(); Loader mLoader; float position[] = { //// 第一个三角形 //0.5f, 0.5f, 0.0f, // 右上角 //0.5f, -0.5f, 0.0f, // 右下角 //-0.5f, 0.5f, 0.0f, // 左上角 //// 第二个三角形 //0.5f, -0.5f, 0.0f, // 右下角 //-0.5f, -0.5f, 0.0f, // 左下角 //-0.5f, 0.5f, 0.0f // 左上角 //// 正方形 // 0.5f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f, // 右上角 // 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f,// 右下角 // -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f,// 左下角 //-0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f // 左上角 // 位置 // 颜色 // 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, // 右下 //-0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, // 左下 // 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f // 顶部 // ---- 位置 ---- ---- 颜色 ---- - 纹理坐标 - // 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // 右上 // 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // 右下 //-0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // 左下 //-0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f // 左上 #pragma region CubePosition // ---- 位置 ---- ---- 颜色 ---- - 纹理坐标 - - 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, //左下 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, //右下 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, //右上 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, //左上 -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f #pragma endregion }; unsigned int indexData[]{// 注意索引从0开始! //0, 1, 3, // 第一个三角形 //1, 2, 3 // 第二个三角形 #pragma region CubeIndex 0, 1, 2, 0, 2, 4, 6, 7, 8, 6, 8, 10, 12, 13, 14, 12, 14, 16, 18, 19, 20, 18, 20, 22, 24, 25, 26, 24, 26, 28, 30, 31, 32, 30, 32, 34, #pragma endregion }; RawModel* mModel = mLoader.loadToVao(position, sizeof(position),indexData,sizeof(indexData)); Render mRender; StaticShader mShader; EMDisplayState mDisplayState; // timing float deltaTime = 0.0f; // time between current frame and last frame float lastFrame = 0.0f; while (!mDisplayManager.isRequestClose()) { // per-frame time logic // -------------------- float currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; mDisplayManager.processInput(mDisplayManager.mDisplay.mWindow, deltaTime); mRender.prepare(); mShader.Start(); mRender.onRender(mModel,&mShader); mShader.Stop(); mDisplayState = mDisplayManager.UpdateDisplay(); if (mDisplayState == EMDisplayState::State_Reload) { mShader.reloadShader(); } } mShader.CleanUp(); mLoader.cleanUp(); mDisplayManager.DestroyDisplay(); return 0; }
// // Created by OLD MAN on 2019/9/3. // #include <iostream> using namespace std; int main(){ int n,a=0,b=0,c=0; cin>>n; for(int i=0;i<n;i++){ int n1,n2,n3; cin>>n1>>n2>>n3; a+=n1; b+=n2; c+=n3; } cout<<a<<" "<<b<<" "<<c<<" "<<a+b+c; }
// IPNotFound.cpp : 实现文件 // #include "stdafx.h" #include "Talk2Me.h" #include "IPNotFound.h" #include "afxdialogex.h" // CIPNotFound 对话框 IMPLEMENT_DYNAMIC(CIPNotFound, CDialogEx) CIPNotFound::CIPNotFound(CWnd* pParent /*=NULL*/) : CDialogEx(CIPNotFound::IDD, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } CIPNotFound::~CIPNotFound() { } void CIPNotFound::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CIPNotFound, CDialogEx) // ON_STN_CLICKED(IDC_IPNOTFOUNDTIP_STATIC, &CIPNotFound::OnStnClickedIpnotfoundtipStatic) END_MESSAGE_MAP() BOOL CIPNotFound::OnInitDialog() { CDialogEx::OnInitDialog(); // 将“关于...”菜单项添加到系统菜单中。 // IDM_ABOUTBOX 必须在系统命令范围内。 ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动 // 执行此操作 SetIcon(m_hIcon, TRUE); // 设置大图标 SetIcon(m_hIcon, FALSE); // 设置小图标 // TODO: 在此添加额外的初始化代码 /*m_ipOfPartner = ntohl(inet_addr("0.0.0.1")); UpdateData(false);*/ return TRUE; // 除非将焦点设置到控件,否则返回 TRUE }
#ifndef FASTLEDSTRIP_H_ #define FASTLEDSTRIP_H_ #include <FastLED.h> /* La strip è composta da LED WS2812B che hanno 3 pin in entrata e 3 pin in uscita (power, ground e data) Ogni LED utilizzato utilizza circa 3 BYTES di RAM, quindi la striscia usa circa 3 x 150 = 450 BYTES di RAM Ogni metro si striscia utilizza circa 2 Ah alla massima lumosità quindi l'intera striscia consuma 2 x 2,5 = 5 Ah In totale Arduino UNO ha 2048 BYTES di RAM mentre Arduino MEGA 2560 ha 8192 BYTES */ /* Vari metodi di impostare il colore Blu Turchese RAL 5018 1) objLEDStrip[0].red = 5; objLEDStrip[0].green = 139; objLEDStrip[0].blue = 140; o objLEDStrip[0].r = 5; objLEDStrip[0].g = 139; objLEDStrip[0].b = 140; o objLEDStrip[0][0] = 5; objLEDStrip[0][1] = 139; objLEDStrip[0][2] = 140; 2) objLEDStrip[0] = #058b8c; 3) objLEDStrip[0].setRGB( 5, 139, 140 ); o objLEDStrip[0].CRGB( 5, 139, 140 ); o objLEDStrip[0] = CRGB::Turchese */ // PIN a cui è collegato il pin dati della strip #define LED_PIN 6 // Tipo di LED utilizzato sulla strip (WS2812B) #define LED_TYPE WS2812 // Numero totale di LED sulla strip #define NUM_LEDS 150 // Larghezza del cursore in LED - deve essere un numero dispari >= 3 #define CURSOR_LEDS 13 // #define COLOR_ORDER GRB // Luminosità iniziale dei LED (da 0 a 255) #define BRIGHTNESS 255 // Tempo di aggiornamento dello stato dei LED ogni secondo #define UPDATES_PER_SECOND 100 // Velocità di accensione o spegnimento del successivo LED #define WAIT_TO_NEXT 20 // Stato del LED a spento #define OFF false // Stato del LED a accesso #define ON true // Set the amount to fade I usually do 5, 10, 15, 20, 25 etc even up to 255 #define FADE_RATE 25 extern CRGB objDefaultColor; // La dichiarazione delle funzioni non è necessaria nel file .ino /* * Funzione che imposta i parametri di inizializzazione dell strip */ void LEDStripSetup( void ); // La dichiarazione delle funzioni non è necessaria nel file .ino /* * Funzione che imposta la strip tutta accesa (150 LED) alla massima luminosità * con tutti i LED di colore Turchese. * Il parametro booleano indica se accendere o spegnere la strip. * L'animazione di accensione avviene dal centro verso l'esterno. * L'animazione di spegnimento avviene dall'esterno verso il centro. */ void StripFullLenghtMode( bool bState, CRGB objColor = objDefaultColor, int nBrightness = BRIGHTNESS, int nSpeed = 0 ); /* * Funzione che imposta la strip tutta spenda (150 LED) ad eccezzione di 3 LED in corrispondenza * della coordinata X della punta della fresa che saranno accesi alla massima luminosità di colore * Turchese. I 5 LED a destra e sinistra di questi 3 LED dimuniranno progressivamente la loro * luminosità del colore Turchese fino allo spegnimento al 6° LED a destra e a sinistra. * L'animazione di accensione avviene dal centro verso l'esterno. * L'animazione di spegnimento avviene dall'esterno verso il centro. */ void StripFollowMode( bool bState, int nBitXPosition ); void CylonBounce( int red, int green, int blue, int EyeSize, int SpeedDelay, int ReturnDelay ); #endif
// Created on: 2009-04-06 // Created by: Sergey ZARITCHNY // Copyright (c) 2009-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _TDataXtd_Constraint_HeaderFile #define _TDataXtd_Constraint_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <TDataXtd_ConstraintEnum.hxx> #include <TDF_Attribute.hxx> #include <Standard_Integer.hxx> #include <TDF_LabelList.hxx> #include <Standard_OStream.hxx> class TDataStd_Real; class Standard_GUID; class TDF_Label; class TNaming_NamedShape; class TDF_RelocationTable; class TDF_DataSet; class TDataXtd_Constraint; DEFINE_STANDARD_HANDLE(TDataXtd_Constraint, TDF_Attribute) //! The groundwork to define constraint attributes. //! The constraint attribute contains the following sorts of data: //! - Type whether the constraint attribute is a //! geometric constraint or a dimension //! - Value the real number value of a numeric //! constraint such as an angle or a radius //! - Geometries to identify the geometries //! underlying the topological attributes which //! define the constraint (up to 4) //! - Plane for 2D constraints. class TDataXtd_Constraint : public TDF_Attribute { public: //! Returns the GUID for constraints. Standard_EXPORT static const Standard_GUID& GetID(); //! Finds or creates the 2D constraint attribute //! defined by the planar topological attribute plane //! and the label label. //! Constraint methods //! ================== Standard_EXPORT static Handle(TDataXtd_Constraint) Set (const TDF_Label& label); Standard_EXPORT TDataXtd_Constraint(); //! Finds or creates the constraint attribute defined //! by the topological attribute G1 and the constraint type type. Standard_EXPORT void Set (const TDataXtd_ConstraintEnum type, const Handle(TNaming_NamedShape)& G1); //! Finds or creates the constraint attribute defined //! by the topological attributes G1 and G2, and by //! the constraint type type. Standard_EXPORT void Set (const TDataXtd_ConstraintEnum type, const Handle(TNaming_NamedShape)& G1, const Handle(TNaming_NamedShape)& G2); //! Finds or creates the constraint attribute defined //! by the topological attributes G1, G2 and G3, and //! by the constraint type type. Standard_EXPORT void Set (const TDataXtd_ConstraintEnum type, const Handle(TNaming_NamedShape)& G1, const Handle(TNaming_NamedShape)& G2, const Handle(TNaming_NamedShape)& G3); //! Finds or creates the constraint attribute defined //! by the topological attributes G1, G2, G3 and G4, //! and by the constraint type type. //! methods to read constraint fields //! ================================= Standard_EXPORT void Set (const TDataXtd_ConstraintEnum type, const Handle(TNaming_NamedShape)& G1, const Handle(TNaming_NamedShape)& G2, const Handle(TNaming_NamedShape)& G3, const Handle(TNaming_NamedShape)& G4); //! Returns true if this constraint attribute is valid. //! By default, true is returned. //! When the value of a dimension is changed or //! when a geometry is moved, false is returned //! until the solver sets it back to true. Standard_EXPORT Standard_Boolean Verified() const; //! Returns the type of constraint. //! This will be an element of the //! TDataXtd_ConstraintEnum enumeration. Standard_EXPORT TDataXtd_ConstraintEnum GetType() const; //! Returns true if this constraint attribute is //! two-dimensional. Standard_EXPORT Standard_Boolean IsPlanar() const; //! Returns the topological attribute of the plane //! used for planar - i.e., 2D - constraints. //! This plane is attached to another label. //! If the constraint is not planar, in other words, 3D, //! this function will return a null handle. Standard_EXPORT const Handle(TNaming_NamedShape)& GetPlane() const; //! Returns true if this constraint attribute is a //! dimension, and therefore has a value. Standard_EXPORT Standard_Boolean IsDimension() const; //! Returns the value of a dimension. //! This value is a reference to a TDataStd_Real attribute. //! If the attribute is not a dimension, this value will //! be 0. Use IsDimension to test this condition. Standard_EXPORT const Handle(TDataStd_Real)& GetValue() const; //! Returns the number of geometry attributes in this constraint attribute. //! This number will be between 1 and 4. Standard_EXPORT Standard_Integer NbGeometries() const; //! Returns the integer index Index used to access //! the array of the constraint or stored geometries of a dimension //! Index has a value between 1 and 4. //! methods to write constraint fields (use builder) //! ================================== Standard_EXPORT Handle(TNaming_NamedShape) GetGeometry (const Standard_Integer Index) const; //! Removes the geometries involved in the //! constraint or dimension from the array of //! topological attributes where they are stored. Standard_EXPORT void ClearGeometries(); //! Finds or creates the type of constraint CTR. Standard_EXPORT void SetType (const TDataXtd_ConstraintEnum CTR); //! Finds or creates the plane of the 2D constraint //! attribute, defined by the planar topological attribute plane. Standard_EXPORT void SetPlane (const Handle(TNaming_NamedShape)& plane); //! Finds or creates the real number value V of the dimension constraint attribute. Standard_EXPORT void SetValue (const Handle(TDataStd_Real)& V); //! Finds or creates the underlying geometry of the //! constraint defined by the topological attribute G //! and the integer index Index. Standard_EXPORT void SetGeometry (const Standard_Integer Index, const Handle(TNaming_NamedShape)& G); //! Returns true if this constraint attribute defined by status is valid. //! By default, true is returned. //! When the value of a dimension is changed or //! when a geometry is moved, false is returned until //! the solver sets it back to true. //! If status is false, Verified is set to false. Standard_EXPORT void Verified (const Standard_Boolean status); Standard_EXPORT void Inverted (const Standard_Boolean status); Standard_EXPORT Standard_Boolean Inverted() const; Standard_EXPORT void Reversed (const Standard_Boolean status); Standard_EXPORT Standard_Boolean Reversed() const; //! collects constraints on Childs for label <aLabel> Standard_EXPORT static void CollectChildConstraints (const TDF_Label& aLabel, TDF_LabelList& TheList); Standard_EXPORT const Standard_GUID& ID() const Standard_OVERRIDE; Standard_EXPORT void Restore (const Handle(TDF_Attribute)& With) Standard_OVERRIDE; Standard_EXPORT Handle(TDF_Attribute) NewEmpty() const Standard_OVERRIDE; Standard_EXPORT void Paste (const Handle(TDF_Attribute)& Into, const Handle(TDF_RelocationTable)& RT) const Standard_OVERRIDE; Standard_EXPORT virtual Standard_OStream& Dump (Standard_OStream& anOS) const Standard_OVERRIDE; Standard_EXPORT virtual void References (const Handle(TDF_DataSet)& DS) const Standard_OVERRIDE; DEFINE_STANDARD_RTTIEXT(TDataXtd_Constraint,TDF_Attribute) protected: private: TDataXtd_ConstraintEnum myType; Handle(TDataStd_Real) myValue; Handle(TDF_Attribute) myGeometries[4]; Handle(TNaming_NamedShape) myPlane; Standard_Boolean myIsReversed; Standard_Boolean myIsInverted; Standard_Boolean myIsVerified; }; #endif // _TDataXtd_Constraint_HeaderFile
//知识点: 双指针(尺取法) ,枚举. /* By:Luckyblock 题目要求: 给定一数列, 从其中选择 两组数 要求 每组中 各数相差<=K, 求 可以选择的数的 最多的数量 分析题意: - 首先对数列进行排序, 则选择的对象 则变成了 数的范围区间 以便于之后的处理 - 先只考虑 选出一个数组的情况: 可以发现, 若固定了区间的左端点, 并向右寻找最优的右端点 当 左端点右移时, 右端点也只单调右移 所以可以使用双指针(尺取法), 先令左端点 = 1, 并向右寻找 第一个满足条件的右端点 之后 左端点右移, 右端点 继续右移, 直到满足条件 在模拟的 过程中取最小的区间大小 按照 上述过程进行模拟, 由于 左右端点 都只单调右移, 则 总复杂度为O(n) - 再考虑选择 两个区间 可以枚举分界线, 把整个 序列分为两份, 并在两侧 分别选出 合法的最长的区间长度 为满足上述要求, 可以取前缀最大值 则 在枚举分界线后, 可以O(1)查询两侧的 最值 */ #include<cstdio> #include<algorithm> #include<ctype.h> #define int long long #define max(a,b) (a>b?a:b) const int MARX = 5e4+10; //============================================================= int n,k,ans,a[MARX]; int pre[MARX],aft[MARX]; //============================================================= inline int read() { int s=1, w=0; char ch=getchar(); for(; !isdigit(ch);ch=getchar()) if(ch=='-') s =-1; for(; isdigit(ch);ch=getchar()) w = w*10+ch-'0'; return s*w; } //============================================================= signed main() { n = read(), k = read(); for(int i=1; i<=n; i++) a[i] = read(); std::sort(a+1,a+n+1);//排序 int l = 1,r = 1; pre[1] = 1; for(r=2; r<=n; r++)//预处理 1~i的最长区间长度 { for(; a[r] - a[l] > k && l>0;) l++;//更新左端点 pre[r] = max(pre[r-1], r-l+1);//取前缀最大值 } l = n,r = n; aft[n] = 1; for(l=n-1; l>=1; l--)//预处理 i~n的最长区间长度 { for(; a[r] - a[l] > k && r<=n;) r--;//更新右端点 aft[l] = max(aft[l+1], r-l+1);//取后缀最大值 } for(int i = 2; i < n; i ++)//枚举分界线, 取最大值作为答案 ans = max(ans,pre[i]+aft[i+1]); printf("%lld",ans); }
#ifndef __REPORTEDITORVIEW_H #define __REPORTEDITORVIEW_H //----------------------------------------------------------------------------- #include "IReportEditorView.h" #include "IReportEditorView.h" #include "IViewWindow.h" namespace wh{ //----------------------------------------------------------------------------- class ReportEditorView : public IReportEditorView { wxDialog* mFrame; wxTextCtrl* mTitleText; wxTextCtrl* mNoteText; wxTextCtrl* mScriptText; wxStdDialogButtonSizer* mBtnSizer; wxButton* mBtnSizerOK; wxButton* mBtnSizerCancel; void OnCancel(wxCommandEvent& evt); void OnOk(wxCommandEvent& evt); wxString mId; public: ReportEditorView(std::shared_ptr<IViewWindow> wnd); virtual void SetReportItem(const rec::ReportItem&) override; virtual void Show()override; virtual void Close()override; }; //----------------------------------------------------------------------------- }//namespace wh{ #endif // __****_H
// This file was generated based on '/Users/r0xstation/Library/Application Support/Fusetools/Packages/Uno.Permissions/1.3.2/Permissions.uno'. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.Object.h> namespace g{namespace Uno{namespace Permissions{struct PlatformPermission;}}} namespace g{ namespace Uno{ namespace Permissions{ // public struct PlatformPermission :9 // { uStructType* PlatformPermission_typeof(); struct PlatformPermission { uStrong<uString*> Name; }; // } }}} // ::g::Uno::Permissions
//********************************************************************************* // Universidad de Costa Rica // Estructuras de Computadores Digitales II // Tarea 2: Paralelizacion de Clustering Data Mining // I Ciclo 2017 // // Secuential.cpp // // Prof: Francisco Rivera // Authors: Pablo Avila B30724 // Guido Armas B30647 // // Data obtained from: http://vpl.astro.washington.edu/spectra/stellar/proxcen.htm //********************************************************************************* #include "Functions.h" #include <string> #include <ctime> using namespace std; int main(int argc, char* argv[]){ clock_t start; double duration; start = clock(); Functions Func; int oxygen =0; int hydrogenAlpha =0; int sodium =0; int iron =0; int hydrogenbeta =0; int calcium =0; int unknown =0; string fileData = "dataProximaCentauri.csv"; int sizeFile = Func.getFileLines(fileData); // Matriz que contiene la longitud de onda e irrandianza de una medicion // en cada fila, con un numero "sizeFile" de filas. float** spectrumPCentauri; spectrumPCentauri = Func.getFileData(fileData, sizeFile); //getElement implementation string* PCentauriElements; PCentauriElements = new string [sizeFile]; for (int i = 0; i < sizeFile; i++){ if ((spectrumPCentauri[i][0] < Oxygen_WL + Oxygen_TL) && (spectrumPCentauri[i][0] > Oxygen_WL - Oxygen_TL)){ PCentauriElements[i] = "Oxygen"; oxygen +=1; } else if ((spectrumPCentauri[i][0] < Hydro_a_WL + Hydro_a_TL) && (spectrumPCentauri[i][0] > Hydro_a_WL - Hydro_a_TL)){ PCentauriElements[i] = "Hydrogen alpha"; hydrogenAlpha +=1; } else if ((spectrumPCentauri[i][0] < Sodium_WL + Sodium_TL) && (spectrumPCentauri[i][0] > Sodium_WL - Sodium_TL)){ PCentauriElements[i] = "Neutral sodium"; sodium +=1; } else if ((spectrumPCentauri[i][0] < Iron_WL + Iron_TL) && (spectrumPCentauri[i][0] > Iron_WL - Iron_TL)){ PCentauriElements[i] = "Neutral iron"; iron +=1; } else if ((spectrumPCentauri[i][0] < Hydro_b_WL + Hydro_b_TL) && (spectrumPCentauri[i][0] > Hydro_b_WL - Hydro_b_TL)){ PCentauriElements[i] = "Hydrogen beta"; hydrogenbeta +=1; } else if ((spectrumPCentauri[i][0] < Calcium_WL + Calcium_TL) && (spectrumPCentauri[i][0] > Calcium_WL - Calcium_TL)){ PCentauriElements[i] = "Ionized calcium"; calcium +=1; } else{ PCentauriElements[i] = "Unknown element"; //Elemento desconocido o WL no calza dentro de uno de los elementos conocidos unknown +=1; } } //PCentauriElements = Func.getElement(spectrumPCentauri, sizeFile); // for(int i=0; i<sizeFile; i++){ // // WL [nm], Flux [W/m2/nm] // cout << "\nWave Length [nm]: " << spectrumPCentauri[i][0] << " Irradiance [W/m2/nm]: " << spectrumPCentauri[i][1] <<endl; // cout << "Element: "; // for (int j = 0; j < 15; j++){ // cout << PCentauriElements[i][j]; // } // cout<<endl; // } cout <<endl<< "-----Serial Algorithm STATS-----" <<endl<<endl; cout <<" Oxygen: "<< oxygen << endl; cout <<" Hydrogen Alpha: "<< hydrogenAlpha << endl; cout <<" Neutral Sodium: "<< sodium << endl; cout <<" Neutral Iron: "<< iron << endl; cout <<" Hydrogen Beta: "<< hydrogenbeta << endl; cout <<" Ionized Calcium: "<< calcium << endl; cout <<" Unknown Element: "<< unknown << endl; duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC; cout<<endl<<" Serial Time: "<< duration <<" [s]" <<endl<<endl; return 0; }
/* * economy.hpp * * Created on: May 28, 2015 * Author: arun */ #ifndef ECONOMY_HPP_ #define ECONOMY_HPP_ #include "BaseHeader.h" #include "households.h" #include <string> #include <fstream> #include <sstream> #include <random> using namespace std; class Economy{ public: Economy(int numHouseholds, int seed); ~Economy(); void initialize(const EquilFns &pol, const StochProc& proc, const State& p_currentState); void simulateOnePeriod(int newPhiState, double r); void testOnePeriod(int newPhiState, double r, double randNum) const; double getAverage(unsigned int state); double getAverageTest(unsigned int state) const; double getAverageAssets(); void printEconomy(std::string fileName); protected: Household **myHHs; private: int phiState; const unsigned int econSize; uniform_real_distribution<double> distr; mt19937 gener; }; #endif /* ECONOMY_HPP_ */
class Actuator { private: int Pin; public: void Init(int pin) { Pin = pin; // use LED for testing pinMode(Pin, OUTPUT); } void Open() { // use LED for testing digitalWrite(Pin, HIGH); delay(1000); } void Close() { // use LED for testing digitalWrite(Pin, LOW); delay(1000); } };
/* * LoadBalancer.cc * * Created on: Nov 17, 2017 * Author: cis505 */ #include "../common/json.hpp" #include "../FE_server/feconfig.h" #include "../FE_server/feserver.h" #include "../FE_server/httpservice.h" using json = nlohmann::json; //============================ // system funcs //============================ static void http_sig_handler(int signum){ switch(signum){ case SIGINT: if(threads.size() == 0){ break; } for(pthread_t i : threads){ pthread_kill(i, SIGALRM); } break; case SIGALRM: break; default: break; } } //================== //For Sig handling //================== static void setmask(){ int err; sigset_t mask; sigaddset(&mask, SIGINT); if((err = pthread_sigmask(SIG_SETMASK, &mask, NULL)) != 0){ fprintf(stderr,"sigblock error"); exit(1); } } vector<string> stringSplit(const string &input, const char &delimiter) { stringstream stringStream(input); string token; vector<string> tokens; while(getline(stringStream, token, delimiter)) { tokens.push_back(token); } return tokens; } vector<ServerStatusDTO> parseConfigFile(const string &configFileName) { std::ifstream configFile(configFileName); std::string line; if (!configFile.is_open()) { cerr << "Could not open config file '" << configFileName << "'" << endl; exit(1); } vector<ServerStatusDTO> servers; while(getline(configFile, line)) { vector<string> tokens = stringSplit(line, ','); if (tokens.size() == 4) { int groupId = stoi(tokens[0]); string address = tokens[1]; int port = stoi(tokens[2]); string heartbeatAddress = tokens[3]; ServerStatusDTO server; server.set_groupid(groupId); server.set_ipaddress(address); server.set_port(port); server.set_heartbeataddress(heartbeatAddress); server.set_status(ServerStatus::UNKNOWN); servers.push_back(server); } else { cerr << "Invalid config file" << endl; exit(1); } } return servers; } json serverStatusDtoToJson(const ServerStatusDTO &serverStatus) { string status = "RUNNING"; if (serverStatus.status() == ServerStatus::RECOVERING) { status = "RECOVERING"; } else if (serverStatus.status() == ServerStatus::UNKNOWN) { status = "UNKNOWN"; } json jsonObj; jsonObj["address"] = serverStatus.ipaddress() + ":" + to_string(serverStatus.port()); jsonObj["status"] = status; jsonObj["heartbeatAddress"] = serverStatus.heartbeataddress(); return jsonObj; } string serverStatusVectorToJson(const vector<ServerStatusDTO> &serverStatuses) { vector<json> jsonVector; for (const ServerStatusDTO &server : serverStatuses) { jsonVector.push_back(serverStatusDtoToJson(server)); } json jsonObj = json(jsonVector); return jsonObj.dump(); } void writeServerStatusToFile(const vector<ServerStatusDTO> &serverStatuses, string fileName) { ofstream file("./views/" + fileName); if (file.is_open()) { file << serverStatusVectorToJson(serverStatuses); } else { cerr << "Could not write server status file " << fileName << endl; } file.close(); } void heartbeatThreadFn(AdminConsoleData* adminConsoleData) { setmask(); cerr << "Starting heartbeat thread" << endl; // Stop when the run flag is set to false while (adminConsoleData->run) { for (int i = 0; i < adminConsoleData->feServers.size(); i++) { ServerStatusDTO* server = &(adminConsoleData->feServers[i]); cerr << "Checking heartbeat of FE server" << server->ipaddress() << ":" << server->port() << endl; // TODO: Update to not create a new client each time. I was having trouble storing multiple clients in a vector and accessing them here HeartbeatServiceClient heartbeatClient(grpc::CreateChannel(server->heartbeataddress(), grpc::InsecureChannelCredentials())); ServerStatusDTO newStatus = heartbeatClient.heartbeat(server->ipaddress(), server->port()); string statusStr; if (newStatus.status() == ServerStatus::RUNNING) { statusStr = "RUNNING"; } else { statusStr = "UNKNOWN"; } cerr << "Heartbeat response of FE server " << server->ipaddress() << ":" << server->port() << ":" << statusStr << endl; lock_guard<mutex> lock(adminConsoleData->mtx); server->set_status(newStatus.status()); } for (int i = 0; i < adminConsoleData->beServers.size(); i++) { ServerStatusDTO* server = &(adminConsoleData->beServers[i]); cerr << "Checking heartbeat of BE server " << server->ipaddress() << ":" << server->port() << endl; // TODO: Update to not create a new client each time. I was having trouble storing multiple clients in a vector and accessing them here HeartbeatServiceClient heartbeatClient(grpc::CreateChannel(server->heartbeataddress(), grpc::InsecureChannelCredentials())); ServerStatusDTO newStatus = heartbeatClient.heartbeat(server->ipaddress(), server->port()); string statusStr; if (newStatus.status() == ServerStatus::RUNNING) { statusStr = "RUNNING"; } else { statusStr = "UNKNOWN"; } cerr << "Heartbeat response of BE server " << server->ipaddress() << ":" << server->port() << ":" << statusStr << endl; lock_guard<mutex> lock(adminConsoleData->mtx); server->set_status(newStatus.status()); } writeServerStatusToFile(adminConsoleData->feServers, "feServerData"); writeServerStatusToFile(adminConsoleData->beServers, "beServerData"); this_thread::sleep_for(chrono::seconds(10)); } } int main(int argc, char *argv[]){ int c = 0; int pflag = 0, aflag = 0, vflag = 0; char * pvalue = NULL; int server_port = 7000; // default port = 7000 string masterAddr = "localhost:50080"; //parse input flag using getopt() while((c = getopt(argc, argv, "p:m:av"))!= -1){ switch(c){ case 'p': pvalue = optarg; pflag = 1; break; case 'a': aflag = 1; break; case 'v': vflag = 1; break; case 'm': masterAddr = optarg; break; case '?': if(optopt == 'p'){ fprintf(stderr, "Option -%c requires an argument.\n", optopt); }else { fprintf(stderr, "Unknown option '-%c.\n",optopt); } exit(1); default: abort(); } } if(aflag == 1){ fprintf(stderr, "YudingAi, yudingai\n"); exit(1); } if(vflag == 1){ db = true; } //cerr << "from main db value is "<<db << endl; if(pflag == 1){ server_port = stoi(pvalue); } string feConfigFile; string beConfigFile; if (argc - optind < 2) { fprintf(stderr, "Usage: [-v] [-p <port>] <feServerConfigFile> <beServerConfigFile>\n"); exit(1); } else { feConfigFile = std::string(argv[optind]); beConfigFile = std::string(argv[optind + 1]); } srand(time(NULL)); FEServer Fs(local_host, server_port); struct sigaction sa; sa.sa_handler = http_sig_handler; sa.sa_flags = 0; sigemptyset(&sa.sa_mask); if(sigaction(SIGINT, &sa, NULL) == -1){ perror("SIGACTION"); } if(sigaction(SIGALRM, &sa, NULL) == -1){ perror("SIGACTION"); } // TODO: This should be changed to the big table master server address eventually grpc::ChannelArguments channelArgs; channelArgs.SetMaxReceiveMessageSize(-1); AdminConsoleRepositoryClient adminClient(grpc::CreateCustomChannel("localhost:50051", grpc::InsecureChannelCredentials(), channelArgs)); MasterServiceClient masterServer(grpc::CreateChannel(masterAddr, grpc::InsecureChannelCredentials())); AdminConsoleData data; data.feServers = parseConfigFile(feConfigFile); data.beServers = parseConfigFile(beConfigFile); data.adminConsoleRepository = &adminClient; data.masterServer = &masterServer; // Set up a thread to periodically send a heartbeat message to each FE & BE server thread heartbeatThread(heartbeatThreadFn, &data); // default port and host: localhost:7000 Fs.runAdminConsole(data); // Let the heartbeat thread know to stop data.run = false; heartbeatThread.join(); return 0; }
/* ID: stevenh6 TASK: gift1 LANG: C++ */ #include <iostream> #include <fstream> #include <string> #include <map> using namespace std; map<string, int> p; ifstream fin ("gift1.in"); ofstream fout ("gift1.out"); void addb(int indiv, int count) { for (int i = 0; i < count; i++) { string per; getline(fin, per); p[per] += indiv; } } int main() { int np; string ln; getline(fin, ln); np = stoi(ln); string people[np]; for (int i = 0; i < np; i++) { string per; getline(fin, per); people[i] = per; p[per] = 0; } for (int j = 0; j < np; j++) { string per; getline(fin, per); string data; getline(fin, data); int tot = 0; int denom = 0; string::size_type pos = data.find(' '); if (data.npos != pos) { denom = stoi(data.substr(pos + 1)); tot = stoi(data.substr(0, pos)); } p[per] -= tot; cout << per + " " + to_string(tot) + " " + to_string(denom) << endl; if (denom != 0) { p[per] += tot % denom; addb(tot/denom, denom); } } for (int k = 0; k < np; k++) { string out = people[k] + " " + to_string(p[people[k]]); fout << out << endl; } return 0; }
#include "stdafx.h" #include "FileOpe.h" #include <io.h> using namespace std; FileOpe::FileOpe() { init(); } FileOpe::FileOpe(const char* name) { init(); //openFlag = Open(name); fileName = name; /*if (!isExist()) { fileName.assign(""); }*/ } FileOpe::FileOpe(const FileOpe& tt) { init(); fileName = tt.getPath() + tt.getName(); } FileOpe& FileOpe::operator=(const FileOpe& tt) { init(); fileName = tt.getPath() + tt.getName(); return *this; } bool FileOpe::operator<(const FileOpe& a) { return this->getName() < a.getName(); } FileOpe::~FileOpe() { Close(); init(); } void FileOpe::init() { openFlag = false; fileName.clear(); fio.clear(); fileName = ""; } bool FileOpe::Open() { //fileName = name; if (!isExist()) { return false; } if (openFlag) { return openFlag; } fio.open(fileName); openFlag = !fio.fail(); return openFlag; } bool FileOpe::Close() { if (!fio.is_open()) { return true; } fio.close(); //init(); openFlag = fio.is_open(); return !openFlag; } bool FileOpe::Rename(const char* newName) { if (getName() == newName)// != 0) { return false; } if (!openFlag) openFlag = Open(); string path = getPath() + newName; ofstream newFile(path); /*string temp; while (getline(fio, temp)) { newFile << temp << endl; }*/ newFile << fio.rdbuf(); newFile.close(); Delete(); fileName = path; Close(); return true; } bool FileOpe::Delete() { if (isOpen())Close(); if (!isExist())return false; if (remove(fileName.c_str()))return false; else return true; } bool FileOpe::MoveTo(const char* newPath, bool isDelete) { bool res = true; if (!openFlag) { openFlag = Open(); } string str = newPath; str += '\\' + getName(); ofstream newFile(str); if (newFile.fail()) return false; /*string temp; while (getline(fio,temp)) { newFile << temp << endl; }*/ newFile << fio.rdbuf(); newFile.close(); if (isDelete) res = Delete(); init(); fileName = str; Close(); return res; } bool FileOpe::CopyFrom(const char* sourceFile) { ifstream inFile(sourceFile); if (inFile.fail())return false; if (fileName.empty())return false; Close(); if(openFlag = Open())fio << inFile.rdbuf(); else return false; /*string temp; while (getline(inFile, temp)) { fio << temp << endl; }*/ inFile.close(); return true; } bool FileOpe::isOpen() { if (fileName.empty() || !fio.is_open()) { return false; } return fio.is_open(); } bool FileOpe::isExist() { if (_access(fileName.c_str(), 0) == -1) return false; else return true; } string FileOpe::getName()const { int a = fileName.find_last_of('\\'); if (a == -1) return string(); basic_string <char> res = fileName.substr(a+1); return res; } string FileOpe::getPath()const { int a = fileName.find_last_of('\\'); if (a == -1) return string(); basic_string <char> res = fileName.substr(0, a+1); return res; } string FileOpe::getExtension()const { int a = fileName.find_last_of('.'); if (a == -1) return string(); basic_string <char> res = fileName.substr(a+1); return res; }
// Generated by gencpp from file seagull_autopilot_msgs/AutopilotStatus.msg // DO NOT EDIT! #ifndef SEAGULL_AUTOPILOT_MSGS_MESSAGE_AUTOPILOTSTATUS_H #define SEAGULL_AUTOPILOT_MSGS_MESSAGE_AUTOPILOTSTATUS_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> #include <seagull_commons_msgs/SeagullHeader.h> namespace seagull_autopilot_msgs { template <class ContainerAllocator> struct AutopilotStatus_ { typedef AutopilotStatus_<ContainerAllocator> Type; AutopilotStatus_() : header() , orbitRadius(0) , trackerStatus(0) , timeToWp(0) , wpFrom(0) , wpTo(0) , airBoundaryViolated(false) , autopilotEngineKill(false) , commsTimeout(false) , fligthTimerElapsed(false) , fligthTermination(false) , gpsTimeout(false) , orbiting(false) , loopControl1(0) , loopControl2(0) , loopControl3(0) , loopControl4(0) , loopControl5(0) , loopControl6(0) , loopControl7(0) , loopControl8(0) , loopControlCount(0) , userAction0(false) , userAction1(false) , userAction2(false) , userAction3(false) , userAction4(false) , userAction5(false) , userAction6(false) , userAction7(false) , elapsedTime(0) { } AutopilotStatus_(const ContainerAllocator& _alloc) : header(_alloc) , orbitRadius(0) , trackerStatus(0) , timeToWp(0) , wpFrom(0) , wpTo(0) , airBoundaryViolated(false) , autopilotEngineKill(false) , commsTimeout(false) , fligthTimerElapsed(false) , fligthTermination(false) , gpsTimeout(false) , orbiting(false) , loopControl1(0) , loopControl2(0) , loopControl3(0) , loopControl4(0) , loopControl5(0) , loopControl6(0) , loopControl7(0) , loopControl8(0) , loopControlCount(0) , userAction0(false) , userAction1(false) , userAction2(false) , userAction3(false) , userAction4(false) , userAction5(false) , userAction6(false) , userAction7(false) , elapsedTime(0) { } typedef ::seagull_commons_msgs::SeagullHeader_<ContainerAllocator> _header_type; _header_type header; typedef uint8_t _orbitRadius_type; _orbitRadius_type orbitRadius; typedef uint8_t _trackerStatus_type; _trackerStatus_type trackerStatus; typedef uint16_t _timeToWp_type; _timeToWp_type timeToWp; typedef uint8_t _wpFrom_type; _wpFrom_type wpFrom; typedef uint8_t _wpTo_type; _wpTo_type wpTo; typedef uint8_t _airBoundaryViolated_type; _airBoundaryViolated_type airBoundaryViolated; typedef uint8_t _autopilotEngineKill_type; _autopilotEngineKill_type autopilotEngineKill; typedef uint8_t _commsTimeout_type; _commsTimeout_type commsTimeout; typedef uint8_t _fligthTimerElapsed_type; _fligthTimerElapsed_type fligthTimerElapsed; typedef uint8_t _fligthTermination_type; _fligthTermination_type fligthTermination; typedef uint8_t _gpsTimeout_type; _gpsTimeout_type gpsTimeout; typedef uint8_t _orbiting_type; _orbiting_type orbiting; typedef uint8_t _loopControl1_type; _loopControl1_type loopControl1; typedef uint8_t _loopControl2_type; _loopControl2_type loopControl2; typedef uint8_t _loopControl3_type; _loopControl3_type loopControl3; typedef uint8_t _loopControl4_type; _loopControl4_type loopControl4; typedef uint8_t _loopControl5_type; _loopControl5_type loopControl5; typedef uint8_t _loopControl6_type; _loopControl6_type loopControl6; typedef uint8_t _loopControl7_type; _loopControl7_type loopControl7; typedef uint8_t _loopControl8_type; _loopControl8_type loopControl8; typedef uint8_t _loopControlCount_type; _loopControlCount_type loopControlCount; typedef uint8_t _userAction0_type; _userAction0_type userAction0; typedef uint8_t _userAction1_type; _userAction1_type userAction1; typedef uint8_t _userAction2_type; _userAction2_type userAction2; typedef uint8_t _userAction3_type; _userAction3_type userAction3; typedef uint8_t _userAction4_type; _userAction4_type userAction4; typedef uint8_t _userAction5_type; _userAction5_type userAction5; typedef uint8_t _userAction6_type; _userAction6_type userAction6; typedef uint8_t _userAction7_type; _userAction7_type userAction7; typedef uint16_t _elapsedTime_type; _elapsedTime_type elapsedTime; enum { STATUS_OFF = 0u }; enum { STATUS_ON = 1u }; enum { STATUS_AUTO = 2u }; typedef boost::shared_ptr< ::seagull_autopilot_msgs::AutopilotStatus_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::seagull_autopilot_msgs::AutopilotStatus_<ContainerAllocator> const> ConstPtr; }; // struct AutopilotStatus_ typedef ::seagull_autopilot_msgs::AutopilotStatus_<std::allocator<void> > AutopilotStatus; typedef boost::shared_ptr< ::seagull_autopilot_msgs::AutopilotStatus > AutopilotStatusPtr; typedef boost::shared_ptr< ::seagull_autopilot_msgs::AutopilotStatus const> AutopilotStatusConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::seagull_autopilot_msgs::AutopilotStatus_<ContainerAllocator> & v) { ros::message_operations::Printer< ::seagull_autopilot_msgs::AutopilotStatus_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace seagull_autopilot_msgs namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False} // {'seagull_autopilot_msgs': ['/home/ciafa/sharpeye15/sharpeye15_ws/src/seagull_autopilot_msgs/msg'], 'seagull_commons_msgs': ['/home/ciafa/sharpeye15/sharpeye15_ws/src/seagull_commons_msgs/msg'], 'std_msgs': ['/opt/ros/indigo/share/std_msgs/cmake/../msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::seagull_autopilot_msgs::AutopilotStatus_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::seagull_autopilot_msgs::AutopilotStatus_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::seagull_autopilot_msgs::AutopilotStatus_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::seagull_autopilot_msgs::AutopilotStatus_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::seagull_autopilot_msgs::AutopilotStatus_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::seagull_autopilot_msgs::AutopilotStatus_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::seagull_autopilot_msgs::AutopilotStatus_<ContainerAllocator> > { static const char* value() { return "ba6bd3a788b80b299ef58cd33c2e580f"; } static const char* value(const ::seagull_autopilot_msgs::AutopilotStatus_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0xba6bd3a788b80b29ULL; static const uint64_t static_value2 = 0x9ef58cd33c2e580fULL; }; template<class ContainerAllocator> struct DataType< ::seagull_autopilot_msgs::AutopilotStatus_<ContainerAllocator> > { static const char* value() { return "seagull_autopilot_msgs/AutopilotStatus"; } static const char* value(const ::seagull_autopilot_msgs::AutopilotStatus_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::seagull_autopilot_msgs::AutopilotStatus_<ContainerAllocator> > { static const char* value() { return "seagull_commons_msgs/SeagullHeader header\n\ uint8 orbitRadius\n\ uint8 trackerStatus\n\ uint16 timeToWp\n\ uint8 wpFrom\n\ uint8 wpTo\n\ bool airBoundaryViolated\n\ bool autopilotEngineKill\n\ bool commsTimeout\n\ bool fligthTimerElapsed\n\ bool fligthTermination\n\ bool gpsTimeout\n\ bool orbiting\n\ uint8 loopControl1\n\ uint8 loopControl2\n\ uint8 loopControl3\n\ uint8 loopControl4\n\ uint8 loopControl5\n\ uint8 loopControl6\n\ uint8 loopControl7\n\ uint8 loopControl8\n\ uint8 loopControlCount\n\ uint8 STATUS_OFF=0\n\ uint8 STATUS_ON=1\n\ uint8 STATUS_AUTO=2\n\ bool userAction0\n\ bool userAction1\n\ bool userAction2\n\ bool userAction3\n\ bool userAction4\n\ bool userAction5\n\ bool userAction6\n\ bool userAction7\n\ uint16 elapsedTime\n\ \n\ ================================================================================\n\ MSG: seagull_commons_msgs/SeagullHeader\n\ Header header\n\ uint16 vehicleId\n\ ================================================================================\n\ MSG: std_msgs/Header\n\ # Standard metadata for higher-level stamped data types.\n\ # This is generally used to communicate timestamped data \n\ # in a particular coordinate frame.\n\ # \n\ # sequence ID: consecutively increasing ID \n\ uint32 seq\n\ #Two-integer timestamp that is expressed as:\n\ # * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')\n\ # * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')\n\ # time-handling sugar is provided by the client library\n\ time stamp\n\ #Frame this data is associated with\n\ # 0: no frame\n\ # 1: global frame\n\ string frame_id\n\ "; } static const char* value(const ::seagull_autopilot_msgs::AutopilotStatus_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::seagull_autopilot_msgs::AutopilotStatus_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.header); stream.next(m.orbitRadius); stream.next(m.trackerStatus); stream.next(m.timeToWp); stream.next(m.wpFrom); stream.next(m.wpTo); stream.next(m.airBoundaryViolated); stream.next(m.autopilotEngineKill); stream.next(m.commsTimeout); stream.next(m.fligthTimerElapsed); stream.next(m.fligthTermination); stream.next(m.gpsTimeout); stream.next(m.orbiting); stream.next(m.loopControl1); stream.next(m.loopControl2); stream.next(m.loopControl3); stream.next(m.loopControl4); stream.next(m.loopControl5); stream.next(m.loopControl6); stream.next(m.loopControl7); stream.next(m.loopControl8); stream.next(m.loopControlCount); stream.next(m.userAction0); stream.next(m.userAction1); stream.next(m.userAction2); stream.next(m.userAction3); stream.next(m.userAction4); stream.next(m.userAction5); stream.next(m.userAction6); stream.next(m.userAction7); stream.next(m.elapsedTime); } ROS_DECLARE_ALLINONE_SERIALIZER; }; // struct AutopilotStatus_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::seagull_autopilot_msgs::AutopilotStatus_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::seagull_autopilot_msgs::AutopilotStatus_<ContainerAllocator>& v) { s << indent << "header: "; s << std::endl; Printer< ::seagull_commons_msgs::SeagullHeader_<ContainerAllocator> >::stream(s, indent + " ", v.header); s << indent << "orbitRadius: "; Printer<uint8_t>::stream(s, indent + " ", v.orbitRadius); s << indent << "trackerStatus: "; Printer<uint8_t>::stream(s, indent + " ", v.trackerStatus); s << indent << "timeToWp: "; Printer<uint16_t>::stream(s, indent + " ", v.timeToWp); s << indent << "wpFrom: "; Printer<uint8_t>::stream(s, indent + " ", v.wpFrom); s << indent << "wpTo: "; Printer<uint8_t>::stream(s, indent + " ", v.wpTo); s << indent << "airBoundaryViolated: "; Printer<uint8_t>::stream(s, indent + " ", v.airBoundaryViolated); s << indent << "autopilotEngineKill: "; Printer<uint8_t>::stream(s, indent + " ", v.autopilotEngineKill); s << indent << "commsTimeout: "; Printer<uint8_t>::stream(s, indent + " ", v.commsTimeout); s << indent << "fligthTimerElapsed: "; Printer<uint8_t>::stream(s, indent + " ", v.fligthTimerElapsed); s << indent << "fligthTermination: "; Printer<uint8_t>::stream(s, indent + " ", v.fligthTermination); s << indent << "gpsTimeout: "; Printer<uint8_t>::stream(s, indent + " ", v.gpsTimeout); s << indent << "orbiting: "; Printer<uint8_t>::stream(s, indent + " ", v.orbiting); s << indent << "loopControl1: "; Printer<uint8_t>::stream(s, indent + " ", v.loopControl1); s << indent << "loopControl2: "; Printer<uint8_t>::stream(s, indent + " ", v.loopControl2); s << indent << "loopControl3: "; Printer<uint8_t>::stream(s, indent + " ", v.loopControl3); s << indent << "loopControl4: "; Printer<uint8_t>::stream(s, indent + " ", v.loopControl4); s << indent << "loopControl5: "; Printer<uint8_t>::stream(s, indent + " ", v.loopControl5); s << indent << "loopControl6: "; Printer<uint8_t>::stream(s, indent + " ", v.loopControl6); s << indent << "loopControl7: "; Printer<uint8_t>::stream(s, indent + " ", v.loopControl7); s << indent << "loopControl8: "; Printer<uint8_t>::stream(s, indent + " ", v.loopControl8); s << indent << "loopControlCount: "; Printer<uint8_t>::stream(s, indent + " ", v.loopControlCount); s << indent << "userAction0: "; Printer<uint8_t>::stream(s, indent + " ", v.userAction0); s << indent << "userAction1: "; Printer<uint8_t>::stream(s, indent + " ", v.userAction1); s << indent << "userAction2: "; Printer<uint8_t>::stream(s, indent + " ", v.userAction2); s << indent << "userAction3: "; Printer<uint8_t>::stream(s, indent + " ", v.userAction3); s << indent << "userAction4: "; Printer<uint8_t>::stream(s, indent + " ", v.userAction4); s << indent << "userAction5: "; Printer<uint8_t>::stream(s, indent + " ", v.userAction5); s << indent << "userAction6: "; Printer<uint8_t>::stream(s, indent + " ", v.userAction6); s << indent << "userAction7: "; Printer<uint8_t>::stream(s, indent + " ", v.userAction7); s << indent << "elapsedTime: "; Printer<uint16_t>::stream(s, indent + " ", v.elapsedTime); } }; } // namespace message_operations } // namespace ros #endif // SEAGULL_AUTOPILOT_MSGS_MESSAGE_AUTOPILOTSTATUS_H
#include "StatusEdge.h" typedef StatusBase<NfaStatusNumber, EdgeMatchContent> NfaStatusBase; typedef NfaStatusBase::EdgeBase NfaEdgeBase; typedef Status<NfaStatusBase, NfaEdgeBase> NfaStatus; typedef NfaStatus::Edge NfaEdge; template<> Link<NfaStatusBase*> NfaStatusBase::AllStatus{}; template<> Link<NfaEdgeBase*> NfaEdgeBase::AllEdge{}; typedef StatusBase<DfaStatusNumber, EdgeMatchContent> DfaStatusBase; typedef DfaStatusBase::EdgeBase DfaEdgeBase; typedef Status<DfaStatusBase, DfaEdgeBase> DfaStatus; typedef DfaStatus::Edge DfaEdge; template<> Link<DfaStatusBase*> DfaStatusBase::AllStatus{}; template<> Link<DfaEdgeBase*> DfaEdgeBase::AllEdge{}; //class EdgeMatchContent---------------------------- EdgeMatchContent::EdgeMatchContent() { } void EdgeMatchContent::Add(const int MatchContent) { Data.Add(MatchContent); } void EdgeMatchContent::Add(Set<int> &MatchContent) { Data.Add(MatchContent); } //class NfaStatusNumber------------------------------ int NfaStatusNumber::StaticStatusNumber=0; NfaStatusNumber::NfaStatusNumber() { StatusNumber=++StaticStatusNumber; } //class DfaStatusNumber------------------------------ int DfaStatusNumber::StaticStatusNumber=0; DfaStatusNumber::DfaStatusNumber() { Number=++StaticStatusNumber; } void DfaStatusNumber::Add(const int Temp_StatusNumber) { StatusNumber.Add(Temp_StatusNumber); }
// // Created by fab on 27/02/2020. // #ifndef DUMBERENGINE_UTILITIES_HPP #define DUMBERENGINE_UTILITIES_HPP #include <cstdlib> #ifndef NAN #define NAN(x) (x!=x) #endif #ifndef max #define max(a,b) (((a) > (b)) ? (a) : (b)) #endif #ifndef min #define min(a,b) (((a) < (b)) ? (a) : (b)) #endif #ifndef sign #define sign(a) (((a) >= (0)) ? (1) : (-1)) #endif #define BUFFER_OFFSET(i) (reinterpret_cast<void*>(i)) inline double randf() { double rnd = rand(); rnd /= RAND_MAX; return rnd; } template<class T> inline T round(T val) { T rest; modf(val,&rest); if (rest > 0.5) return ceil(val); return floor(val); } #endif //DUMBERENGINE_UTILITIES_HPP
#ifndef FORGETPASS_H #define FORGETPASS_H #include <QWidget> #include <QCloseEvent> #include "connection.h" namespace Ui { class forgetpass; } class forgetpass : public QWidget { Q_OBJECT public: explicit forgetpass(QWidget *parent = 0); ~forgetpass(); void closeEvent(QCloseEvent * event); private slots: void on_showpass_pressed(); void on_showpass_released(); void on_showconfpass_pressed(); void on_showconfpass_released(); void on_showmasterkey_pressed(); void on_showmasterkey_released(); void on_reset_clicked(); void on_confirmpassword_textChanged(const QString &arg1); void on_userid_returnPressed(); void on_password_returnPressed(); void on_confirmpassword_returnPressed(); void on_masterkey_returnPressed(); private: Ui::forgetpass *ui; }; #endif // FORGETPASS_H
//////////////////////////////////////////////////////////////////////////////// // //(C) Andy Thomason 2012-2014 // // Modular Framework for OpenGLES2 rendering on multiple platforms. // // fluid example based on Joss Stam paper. // #include <valarray> #include <memory> namespace octet { /// Scene containing a box with octet. class example_fluids : public app { // scene for drawing box ref<visual_scene> app_scene; class mesh_fluid : public mesh { struct my_vertex { vec3p pos; vec3p color; }; dynarray<my_vertex> vertices; std::vector<float> prev_density; std::vector<float> prev_vx; std::vector<float> prev_vy; std::vector<float> density; std::vector<float> vx; std::vector<float> vy; ivec3 dim; public: mesh_fluid(aabb_in bb, ivec3_in dim) : mesh(), dim(dim) { mesh::set_aabb(bb); density.resize((dim.x()+1)*(dim.y()+1)); vx.resize((dim.x()+1)*(dim.y()+1)); vy.resize((dim.x()+1)*(dim.y()+1)); prev_density.resize((dim.x()+1)*(dim.y()+1)); prev_vx.resize((dim.x()+1)*(dim.y()+1)); prev_vy.resize((dim.x()+1)*(dim.y()+1)); //density[50 +(dim.x()+1) * 50] = 1; //prev_vx[50 +(dim.x()+1) * 50] = 1; dynarray<uint32_t> indices; int stride = dim.x() + 1; for (int i = 0; i < dim.x(); ++i) { for (int j = 0; j < dim.y(); ++j) { indices.push_back((i+1) +(j+0)*stride); indices.push_back((i+0) +(j+1)*stride); indices.push_back((i+1) +(j+1)*stride); indices.push_back((i+1) +(j+0)*stride); indices.push_back((i+0) +(j+0)*stride); indices.push_back((i+0) +(j+1)*stride); } } set_indices(indices); clear_attributes(); add_attribute(attribute_pos, 3, GL_FLOAT, 0); add_attribute(attribute_color, 3, GL_FLOAT, 12); } /// clamp edges to same (or negative) value of inner pixels /// to act as a barrier void set_boundary( int N, int b, float * x ) { auto IX = [=](int i, int j) { return i +(N+2)*j; }; for ( int i=1 ; i<=N ; i++ ) { x[IX(0 ,i)] = b==1 ? -x[IX(1,i)] : x[IX(1,i)]; x[IX(N+1,i)] = b==1 ? -x[IX(N,i)] : x[IX(N,i)]; x[IX(i,0 )] = b==2 ? -x[IX(i,1)] : x[IX(i,1)]; x[IX(i,N+1)] = b==2 ? -x[IX(i,N)] : x[IX(i,N)]; } x[IX(0 ,0 )] = 0.5f*(x[IX(1,0 )]+x[IX(0 ,1)]); x[IX(0 ,N+1)] = 0.5f*(x[IX(1,N+1)]+x[IX(0 ,N)]); x[IX(N+1,0 )] = 0.5f*(x[IX(N,0 )]+x[IX(N+1,1)]); x[IX(N+1,N+1)] = 0.5f*(x[IX(N,N+1)]+x[IX(N+1,N)]); } /// solve diffusion equations (propagation into adjacent cells) /// by repeated aplication of a weighted average. /// Use a fixed number of iterations. /// at the end x should not change (you should test this yourself) void gauss_siedel( int N, int b, float * x, float * x0, float a, float c ) { auto IX = [=](int i, int j) { return i +(N+2)*j; }; for ( int k=0 ; k<20 ; k++ ) { for ( int i=1 ; i<=N ; i++ ) { for ( int j=1 ; j<=N ; j++ ) { x[IX(i,j)] = (x0[IX(i,j)] + a*(x[IX(i-1,j)]+x[IX(i+1,j)]+x[IX(i,j-1)]+x[IX(i,j+1)]))/c; } } set_boundary( N, b, x ); } } /// calculate diffision by approximating with a weighted average void diffusion( int N, int b, float * x, float * x0, float diff, float dt ) { float a = dt * diff * (N * N); gauss_siedel( N, b, x, x0, a, 1+4*a ); } /// carry a quantity (velocity or density) from one cell to another. void advection_step( int N, int b, float * d, float * d0, float * u, float * v, float dt ) { auto IX = [=](int i, int j) { return i +(N+2)*j; }; float dt0 = dt*N; for ( int i=1 ; i<=N ; i++ ) { for ( int j=1 ; j<=N ; j++ ) { // (x, y) is the address to copy from float x = i-dt0*u[IX(i,j)], y = j-dt0*v[IX(i,j)]; // clamp x and y if (x<0.5f) x=0.5f; else if (x>N+0.5f) x=N+0.5f; if (y<0.5f) y=0.5f; else if (y>N+0.5f) y=N+0.5f; // s1 and s0 are lerp coordinates [0,1) within the source cell int i0=(int)x, i1=i0+1; int j0=(int)y, j1=j0+1; float s1 = x - i0, s0 = 1 - s1; float t1 = y - j0, t0 = 1 - t1; // sample the source d[IX(i,j)] = s0*(t0*d0[IX(i0,j0)]+t1*d0[IX(i0,j1)]) + s1*(t0*d0[IX(i1,j0)]+t1*d0[IX(i1,j1)]) ; } } // copy values out to the boundary. set_boundary( N, b, d ); } // stablisation step. adjust the velocity to prevent increase in energy // in the system. void project( int N, float * u, float * v, float * p, float * div ) { auto IX = [=](int i, int j) { return i +(N+2)*j; }; // calculate divergence into div // set initial value of p for ( int i=1 ; i<=N ; i++ ) { for ( int j=1 ; j<=N ; j++ ) { div[IX(i,j)] = -0.5f*(u[IX(i+1,j)]-u[IX(i-1,j)]+v[IX(i,j+1)]-v[IX(i,j-1)])/N; p[IX(i,j)] = 0; } } // copy pixels to boundary set_boundary( N, 0, div ); set_boundary( N, 0, p ); // p += div[x+/-1, y+/-1] * 4; gauss_siedel( N, 0, p, div, 1, 4 ); // calculate velocity from pressure-like "p" for ( int i=1 ; i<=N ; i++ ) { for ( int j=1 ; j<=N ; j++ ) { // u from left and right u[IX(i,j)] -= 0.5f*N*(p[IX(i+1,j)]-p[IX(i-1,j)]); // v from up and down. v[IX(i,j)] -= 0.5f*N*(p[IX(i,j+1)]-p[IX(i,j-1)]); } } // copy velocity to boundary set_boundary( N, 1, u ); set_boundary( N, 2, v ); } /// Given a velocity field, carry a value around the simulation /// and diffuse the value. void density_step( int N, float * x, float * x0, float * u, float * v, float diff, float dt ) { // apply diffusion to density. If there is no velocity, the value will still spread. std::swap( x0, x ); diffusion( N, 0, x, x0, diff, dt ); // use the velocity field to carry density around. std::swap( x0, x ); advection_step( N, 0, x, x0, u, v, dt ); } /// Compute the new velocity field. void velocity_step( int N, float * u, float * v, float * u0, float * v0, float visc, float dt ) { // diffuse into neighouring cells std::swap( u0, u ); diffusion( N, 1, u, u0, visc, dt ); std::swap( v0, v ); diffusion( N, 2, v, v0, visc, dt ); // stabilise the system using poisson project( N, u, v, u0, v0 ); std::swap( u0, u ); std::swap( v0, v ); // use advection to move the velocity itself advection_step( N, 1, u, u0, u0, v0, dt ); advection_step( N, 2, v, v0, u0, v0, dt ); // stabilise the system using poisson project( N, u, v, u0, v0 ); } void update(int frame_number) { float dt = 1.0f / 30; int N = dim.x()-1; assert(density.size() == (N+2)*(N+2)); float *u = vx.data(), *v = vy.data(), *u_prev = prev_vx.data(), *v_prev = prev_vy.data(); float *dens = density.data(), *dens_prev = prev_density.data(); float visc = 0.0f; float diff = 0.0f; //printf("dtot=%f\n", std::accumulate(density.cbegin(), density.cend(), 0.0f)); // fill the input values std::fill(prev_vx.begin(), prev_vx.end(), 0.0f); std::fill(prev_vy.begin(), prev_vy.end(), 0.0f); std::fill(prev_density.begin(), prev_density.end(), 0.0f); // you could use a UI to do this. float c = math::cos(frame_number*0.01f); float s = math::sin(frame_number*0.01f); density[50 +(dim.x()+1) * 50] += 100 * dt; u[50 +(dim.x()+1) * 50] += c * (100 * dt); v[50 +(dim.x()+1) * 50] += s * (100 * dt); // step the simulation. //get_from_UI( dens_prev, u_prev, v_prev ); long long t0 = __rdtsc(); velocity_step( N, u, v, u_prev, v_prev, visc, dt ); density_step( N, dens, dens_prev, u, v, diff, dt ); long long t1 = __rdtsc(); printf("%lld clocks\n", t1-t0); //printf("dtot=%f\n", std::accumulate(density.cbegin(), density.cend(), 0.0f)); aabb bb = mesh::get_aabb(); float sx = bb.get_half_extent().x()*(2.0f/dim.x()); float sy = bb.get_half_extent().y()*(2.0f/dim.y()); float cx = bb.get_center().x() - bb.get_half_extent().x(); float cy = bb.get_center().y() - bb.get_half_extent().y(); vertices.resize((dim.x()+1)*(dim.y()+1)); int stride =(dim.x()+1); size_t d = 0; for (int i = 0; i <= dim.x(); ++i) { for (int j = 0; j <= dim.y(); ++j) { my_vertex v; v.pos = vec3p(i * sx + cx, j * sy + cy, 0); v.color = vec3p(std::max(0.0f, std::min(density[i+j*stride], 1.0f) ), 0, 0); vertices[d++] = v; } } mesh::set_vertices<my_vertex>(vertices); } }; ref<mesh_fluid> the_mesh; public: /// this is called when we construct the class before everything is initialised. example_fluids(int argc, char **argv) : app(argc, argv) { } /// this is called once OpenGL is initialized void app_init() { app_scene = new visual_scene(); app_scene->create_default_camera_and_lights(); material *red = new material(vec4(1, 0, 0, 1), new param_shader("shaders/simple_color.vs", "shaders/simple_color.fs")); the_mesh = new mesh_fluid(aabb(vec3(0), vec3(10)), ivec3(100, 100, 0)); scene_node *node = new scene_node(); app_scene->add_child(node); app_scene->add_mesh_instance(new mesh_instance(node, the_mesh, red)); } /// this is called to draw the world void draw_world(int x, int y, int w, int h) { int vx = 0, vy = 0; get_viewport_size(vx, vy); app_scene->begin_render(vx, vy, vec4(0, 0, 0, 1)); the_mesh->update(get_frame_number()); // update matrices. assume 30 fps. app_scene->update(1.0f/30); // draw the scene app_scene->render((float)vx / vy); } }; }
#include "StdAfx.h" namespace UiLib { CControlUI::CControlUI() : m_pManager(NULL), m_pParent(NULL), m_bUpdateNeeded(true), m_bMenuUsed(false), m_bVisible(true), m_bInternVisible(true), m_bFocused(false), m_bEnabled(true), m_bRandom(false), m_bGetRegion(false), m_bMouseEnabled(true), m_bKeyboardEnabled(true), m_bFloat(false), m_bSetPos(false), m_chShortcut('\0'), m_pTag(NULL), m_dwBackColor(0), m_dwBackColor2(0), m_dwBackColor3(0), m_dwDisabledBkColor(0xFFF0F0F0), m_dwBorderColor(0), m_dwFocusBorderColor(0), m_dwHoverBorderColor(0), m_bColorHSL(false), m_bHover(false), m_nBorderSize(0), m_nHoverBorderSize(0), m_nFocusBorderSize(0) { m_tCurEffects.m_bEnableEffect = false; m_tCurEffects.m_iZoom = -1; m_tCurEffects.m_dFillingBK = 0xffffffff; m_tCurEffects.m_iOffectX = 0; m_tCurEffects.m_iOffectY = 0; m_tCurEffects.m_iAlpha = -255; m_tCurEffects.m_fRotation = 0.0; m_tCurEffects.m_iNeedTimer = 350; memcpy(&m_tMouseInEffects,&m_tCurEffects,sizeof(TEffectAge)); memcpy(&m_tMouseOutEffects,&m_tCurEffects,sizeof(TEffectAge)); memcpy(&m_tMouseClickEffects,&m_tCurEffects,sizeof(TEffectAge)); m_cXY.cx = m_cXY.cy = 0; m_cxyFixed.cx = m_cxyFixed.cy = 0; m_cxyMin.cx = m_cxyMin.cy = 0; m_cxyMax.cx = m_cxyMax.cy = 9999; m_cxyBorderRound.cx = m_cxyBorderRound.cy = 0; ::ZeroMemory(&m_rcPadding, sizeof(m_rcPadding)); ::ZeroMemory(&m_rcItem, sizeof(RECT)); ::ZeroMemory(&m_rcPaint, sizeof(RECT)); ::ZeroMemory(&m_tRelativePos, sizeof(TRelativePosUI)); m_hRgn = CreateRectRgn(0,0,0,0); //定义新的空的HRGN.不能初始化为NULL #ifdef DEVELOP m_dwBorderColor = 0xffff0000; m_nBorderSize = 1; #endif // _DEBUG } CControlUI::~CControlUI() { ::DeleteObject(m_hRgn); if( OnDestroy ) OnDestroy(this); if( m_pManager != NULL ) m_pManager->ReapObjects(this); } CDuiString CControlUI::GetName() const { return m_sName; } void CControlUI::SetName(LPCTSTR pstrName) { m_sName = pstrName; } LPVOID CControlUI::GetInterface(LPCTSTR pstrName) { if( _tcscmp(pstrName, _T("Control")) == 0 ) return this; return NULL; } LPCTSTR CControlUI::GetClass() const { return _T("ControlUI"); } UINT CControlUI::GetControlFlags() const { return 0; } bool CControlUI::Activate() { if( !IsVisible() ) return false; if( !IsEnabled() ) return false; return true; } CPaintManagerUI* CControlUI::GetManager() const { return m_pManager; } void CControlUI::SetManager(CPaintManagerUI* pManager, CControlUI* pParent, bool bInit) { m_pManager = pManager; m_pParent = pParent; if( bInit && m_pParent ) Init(); } CControlUI * CControlUI::GetParentByName(CDuiString pstrName) { if( pstrName == m_pParent->GetName()) return m_pParent; else return m_pParent->GetParentByName(pstrName); } CControlUI* CControlUI::GetParent() const { return m_pParent; } bool CControlUI::IsParent(CControlUI* v_pParent) const { if (v_pParent) { CControlUI* pParent = GetParent(); while (pParent) { if (pParent == v_pParent) { return true; } pParent = pParent->GetParent(); } } return false; } CDuiString CControlUI::GetText() const { return m_sText; } void CControlUI::SetText(LPCTSTR pstrText) { if( m_sText == pstrText ) return; if(m_pManager&&m_pManager->IsUseMutiLanguage()) { m_sText = m_pManager->GetStringFromID(pstrText); if(m_sText.IsEmpty()) m_sText = pstrText; } else m_sText = pstrText; Invalidate(); } DWORD CControlUI::GetBkColor() const { return m_dwBackColor; } void CControlUI::SetBkColor(DWORD dwBackColor) { if( m_dwBackColor == dwBackColor ) return; m_dwBackColor = dwBackColor; Invalidate(); } DWORD CControlUI::GetBkColor2() const { return m_dwBackColor2; } void CControlUI::SetBkColor2(DWORD dwBackColor) { if( m_dwBackColor2 == dwBackColor ) return; m_dwBackColor2 = dwBackColor; Invalidate(); } DWORD CControlUI::GetBkColor3() const { return m_dwBackColor3; } void CControlUI::SetDisabledBkColor( DWORD dwDisabledBkColor ) { m_dwDisabledBkColor = dwDisabledBkColor; Invalidate(); } DWORD CControlUI::GetDisibledBkColor() const { return m_dwDisabledBkColor; } void CControlUI::SetBkColor3(DWORD dwBackColor) { if( m_dwBackColor3 == dwBackColor ) return; m_dwBackColor3 = dwBackColor; Invalidate(); } LPCTSTR CControlUI::GetBkImage() { return m_sBkImage; } LPCTSTR CControlUI::GetDisableBkImage() { return m_sDisableBkImage; } void CControlUI::SetDisableBkImage(LPCTSTR pStrImage) { if( m_sDisableBkImage == pStrImage ) return; m_sDisableBkImage = pStrImage; Invalidate(); } void CControlUI::SetBkImage(LPCTSTR pStrImage) { if( m_sBkImage == pStrImage ) return; m_sBkImage = pStrImage; m_bGetRegion = true; Invalidate(); } DWORD CControlUI::GetBorderColor() const { return m_dwBorderColor; } void CControlUI::SetBorderColor(DWORD dwBorderColor) { if( m_dwBorderColor == dwBorderColor ) return; m_dwBorderColor = dwBorderColor; Invalidate(); } DWORD CControlUI::GetFocusBorderColor() const { return m_dwFocusBorderColor; } void CControlUI::SetFocusBorderColor(DWORD dwBorderColor,int nSize) { if( m_dwFocusBorderColor == dwBorderColor ) return; if(nSize != -1) m_nFocusBorderSize = nSize; else m_nFocusBorderSize = m_nBorderSize; m_dwFocusBorderColor = dwBorderColor; Invalidate(); } void CControlUI::SetHoverBorderColor(DWORD dwBorderColor,int nSize) { if( m_dwHoverBorderColor == dwBorderColor ) return; if(nSize != -1) m_nHoverBorderSize = nSize; else m_nFocusBorderSize = m_nBorderSize; m_dwHoverBorderColor = dwBorderColor; Invalidate(); } bool CControlUI::IsColorHSL() const { return m_bColorHSL; } void CControlUI::SetColorHSL(bool bColorHSL) { if( m_bColorHSL == bColorHSL ) return; m_bColorHSL = bColorHSL; Invalidate(); } int CControlUI::GetBorderSize() const { return m_nBorderSize; } void CControlUI::SetBorderSize(int nSize) { if( m_nBorderSize == nSize ) return; m_nBorderSize = nSize; Invalidate(); } SIZE CControlUI::GetBorderRound() const { return m_cxyBorderRound; } void CControlUI::SetBorderRound(SIZE cxyRound) { m_cxyBorderRound = cxyRound; Invalidate(); } bool CControlUI::DrawImage(HDC hDC, LPCTSTR pStrImage, LPCTSTR pStrModify, bool bNeedAlpha, BYTE bNewFade) { return CRenderEngine::DrawImageString(hDC, m_pManager, m_rcItem, m_rcPaint, pStrImage, pStrModify, bNeedAlpha, bNewFade); } void CControlUI::GetRegion(HDC hDC, LPCTSTR pStrImage, COLORREF dwColorKey) { m_bGetRegion = false; HDC memDC; memDC = ::CreateCompatibleDC(hDC); const TImageInfo* data = NULL; data = m_pManager->GetImageEx((LPCTSTR)pStrImage, NULL); if( !data ) return; HBITMAP pOldMemBmp=NULL; //将位图选入临时DC pOldMemBmp = (HBITMAP)SelectObject(memDC,data->hBitmap); BITMAP bit; ::GetObject(data->hBitmap, sizeof(BITMAP), &bit);//取得位图参数,这里要用到位图的长和宽 int y = 0; int iX = 0; HRGN rgnTemp; //保存临时region for(y=0;y<=bit.bmHeight ;y++) { iX = 0; do { //跳过透明色找到下一个非透明色的点. COLORREF res1 = RGB(255,255,255); COLORREF RES = ::GetPixel(memDC,iX,y); while (iX <= bit.bmWidth && ::GetPixel(memDC,iX,y) == dwColorKey) iX++; //记住这个起始点 int iLeftX = iX; //寻找下个透明色的点 while (iX <= bit.bmWidth && ::GetPixel(memDC,iX,y) != dwColorKey) ++iX; //创建一个包含起点与重点间高为1像素的临时“region” rgnTemp = ::CreateRectRgn(iLeftX, y, iX, y+1); //合并到主"region". ::CombineRgn(m_hRgn,m_hRgn,rgnTemp, RGN_OR); //删除临时"region",否则下次创建时和出错 ::DeleteObject(rgnTemp); } while(iX < bit.bmWidth ); iX = 0; } if(pOldMemBmp) ::SelectObject(memDC,pOldMemBmp); } const RECT& CControlUI::GetPos() const { return m_rcItem; } void CControlUI::SetPos(RECT rc) { if( rc.right < rc.left ) rc.right = rc.left; if( rc.bottom < rc.top ) rc.bottom = rc.top; //设定刷新区域为控件原来大小; CDuiRect invalidateRc = m_rcItem; //若原来未设置大小,可能是隐藏,则直接使用控件最新的位置作为刷新区域; if( ::IsRectEmpty(&invalidateRc) ) invalidateRc = rc; //将新的区域设定为控件大小; m_rcItem = rc; if( m_pManager == NULL ) return; if( !m_bSetPos ) { m_bSetPos = true; //相应控件的OnSize消息; if( OnSize ) OnSize(this); m_bSetPos = false; } //若是悬浮控件; if( m_bFloat ) { //获取父控件位置修改预设值; CControlUI* pParent = GetParent(); if( pParent != NULL ) { RECT rcParentPos = pParent->GetPos(); //在父控件上的左上点坐标; if( m_cXY.cx >= 0 ) m_cXY.cx = m_rcItem.left - rcParentPos.left; else m_cXY.cx = m_rcItem.right - rcParentPos.right; if( m_cXY.cy >= 0 ) m_cXY.cy = m_rcItem.top - rcParentPos.top; else m_cXY.cy = m_rcItem.bottom - rcParentPos.bottom; //宽度; m_cxyFixed.cx = m_rcItem.right - m_rcItem.left; //高度; m_cxyFixed.cy = m_rcItem.bottom - m_rcItem.top; } } m_bUpdateNeeded = false; //若原来控件所在区域与传入RC不同则取并集; invalidateRc.Join(m_rcItem); CControlUI* pParent = this; RECT rcTemp; RECT rcParent; //循环遍历父控件; while( pParent = pParent->GetParent() ) { rcTemp = invalidateRc; //获取父控件的位置; rcParent = pParent->GetPos(); //将父控件的位置与子控件的位置取交集,防止渲染区域超出; if( !::IntersectRect(&invalidateRc, &rcTemp, &rcParent) ) { return; } } //刷新子控件在父控件中的位置; m_pManager->Invalidate(invalidateRc); } int CControlUI::GetWidth() const { return m_rcItem.right - m_rcItem.left; } int CControlUI::GetHeight() const { return m_rcItem.bottom - m_rcItem.top; } int CControlUI::GetX() const { return m_rcItem.left; } int CControlUI::GetY() const { return m_rcItem.top; } RECT CControlUI::GetPadding() const { return m_rcPadding; } void CControlUI::SetPadding(RECT rcPadding) { m_rcPadding = rcPadding; NeedParentUpdate(); } SIZE CControlUI::GetFixedXY() const { return m_cXY; } void CControlUI::SetFixedXY(SIZE szXY) { m_cXY.cx = szXY.cx; m_cXY.cy = szXY.cy; if( !m_bFloat ) NeedParentUpdate(); else NeedUpdate(); } int CControlUI::GetFixedWidth() const { return m_cxyFixed.cx; } void CControlUI::SetFixedWidth(int cx) { if( cx < 0 ) return; m_cxyFixed.cx = cx; if( !m_bFloat ) NeedParentUpdate(); else NeedUpdate(); } int CControlUI::GetFixedHeight() const { return m_cxyFixed.cy; } void CControlUI::SetFixedHeight(int cy) { if( cy < 0 ) return; m_cxyFixed.cy = cy; if( !m_bFloat ) NeedParentUpdate(); else NeedUpdate(); } int CControlUI::GetMinWidth() const { return m_cxyMin.cx; } void CControlUI::SetMinWidth(int cx) { if( m_cxyMin.cx == cx ) return; if( cx < 0 ) return; m_cxyMin.cx = cx; if( !m_bFloat ) NeedParentUpdate(); else NeedUpdate(); } int CControlUI::GetMaxWidth() const { return m_cxyMax.cx; } void CControlUI::SetMaxWidth(int cx) { if( m_cxyMax.cx == cx ) return; if( cx < 0 ) return; m_cxyMax.cx = cx; if( !m_bFloat ) NeedParentUpdate(); else NeedUpdate(); } int CControlUI::GetMinHeight() const { return m_cxyMin.cy; } void CControlUI::SetMinHeight(int cy) { if( m_cxyMin.cy == cy ) return; if( cy < 0 ) return; m_cxyMin.cy = cy; if( !m_bFloat ) NeedParentUpdate(); else NeedUpdate(); } int CControlUI::GetMaxHeight() const { return m_cxyMax.cy; } void CControlUI::SetMaxHeight(int cy) { if( m_cxyMax.cy == cy ) return; if( cy < 0 ) return; m_cxyMax.cy = cy; if( !m_bFloat ) NeedParentUpdate(); else NeedUpdate(); } void CControlUI::SetRelativePos(SIZE szMove,SIZE szZoom) { m_tRelativePos.bRelative = TRUE; m_tRelativePos.nMoveXPercent = szMove.cx; m_tRelativePos.nMoveYPercent = szMove.cy; m_tRelativePos.nZoomXPercent = szZoom.cx; m_tRelativePos.nZoomYPercent = szZoom.cy; } void CControlUI::SetRelativeParentSize(SIZE sz) { m_tRelativePos.szParent = sz; } TRelativePosUI CControlUI::GetRelativePos() const { return m_tRelativePos; } bool CControlUI::IsRelativePos() const { return m_tRelativePos.bRelative; } CDuiString CControlUI::GetToolTip() const { return m_sToolTip; } void CControlUI::SetToolTip(LPCTSTR pstrText) { m_sToolTip = pstrText; } TCHAR CControlUI::GetShortcut() const { return m_chShortcut; } void CControlUI::SetShortcut(TCHAR ch) { m_chShortcut = ch; } bool CControlUI::IsContextMenuUsed() const { return m_bMenuUsed; } void CControlUI::SetContextMenuUsed(bool bMenuUsed) { m_bMenuUsed = bMenuUsed; } const CDuiString& CControlUI::GetUserData() { return m_sUserData; } void CControlUI::SetUserData(LPCTSTR pstrText) { m_sUserData = pstrText; } UINT_PTR CControlUI::GetTag() const { return m_pTag; } void CControlUI::SetTag(UINT_PTR pTag) { m_pTag = pTag; } bool CControlUI::IsVisible() const { return m_bVisible && m_bInternVisible; } void CControlUI::SetVisible(bool bVisible) { if( m_bVisible == bVisible ) return; bool v = IsVisible(); m_bVisible = bVisible; if( m_bFocused ) m_bFocused = false; if (!bVisible && m_pManager && m_pManager->GetFocus() == this) { m_pManager->SetFocus(NULL) ; } if( IsVisible() != v ) { NeedParentUpdate(); } } void CControlUI::SetInternVisible(bool bVisible) { m_bInternVisible = bVisible; if (!bVisible && m_pManager && m_pManager->GetFocus() == this) { m_pManager->SetFocus(NULL) ; } } bool CControlUI::IsEnabled() const { return m_bEnabled; } bool CControlUI::IsRandom() const { return m_bRandom; } void CControlUI::SetEnabled(bool bEnabled) { if( m_bEnabled == bEnabled ) return; m_bEnabled = bEnabled; Invalidate(); } void CControlUI::SetRandom(bool bRandom) { if( m_bRandom == bRandom ) return; m_bRandom = bRandom; Invalidate(); } bool CControlUI::IsMouseEnabled() const { return m_bMouseEnabled; } void CControlUI::SetMouseEnabled(bool bEnabled) { m_bMouseEnabled = bEnabled; } bool CControlUI::IsKeyboardEnabled() const { return m_bKeyboardEnabled ; } void CControlUI::SetKeyboardEnabled(bool bEnabled) { m_bKeyboardEnabled = bEnabled ; } bool CControlUI::IsFocused() const { return m_bFocused; } bool CControlUI::IsHovered() const { return m_bHover; } void CControlUI::SetFocus() { if( m_pManager != NULL ) m_pManager->SetFocus(this); } bool CControlUI::IsFloat() const { return m_bFloat; } void CControlUI::SetFloat(bool bFloat) { if( m_bFloat == bFloat ) return; m_bFloat = bFloat; NeedParentUpdate(); } //************************************ // Method: GetStyleName // FullName: CControlUI::GetStyleName // Access: virtual public // Returns: const CDuiString& // Qualifier: // Node: //************************************ const CDuiString& CControlUI::GetStyleName() { try { return m_sStyleName; } catch(...) { throw "CControlUI::GetStyleName"; } } //************************************ // Method: SetStyleName // FullName: CControlUI::SetStyleName // Access: virtual public // Returns: void // Qualifier: // Parameter: LPCTSTR pStrStyleName // Node: //************************************ void CControlUI::SetStyleName( LPCTSTR pStrStyleName,CPaintManagerUI* pm /*= NULL*/ ) { if(!pStrStyleName || _tclen(pStrStyleName) <= 0 || !GetManager() && !pm) return; CStdStringPtrMap* pStyleMap = NULL; if(pm) pStyleMap = pm->GetControlStyles(pStrStyleName); else pStyleMap = GetManager()->GetControlStyles(pStrStyleName); if(!pStyleMap) return; for(int nIndex = 0;nIndex < pStyleMap->GetSize();nIndex++) { CDuiString nKey = pStyleMap->GetAt(nIndex); CDuiString* nVal = static_cast<CDuiString*>(pStyleMap->Find(nKey)); SetAttribute(nKey.GetData(),nVal->GetData()); } m_sStyleName = pStrStyleName; Invalidate(); } CControlUI* CControlUI::FindControl(FINDCONTROLPROC Proc, LPVOID pData, UINT uFlags) { if( (uFlags & UIFIND_VISIBLE) != 0 && !IsVisible() ) return NULL; if( (uFlags & UIFIND_ENABLED) != 0 && !IsEnabled() ) return NULL; //判断是否启用不规则区,而非矩形 if( (uFlags & UIFIND_HITTEST) != 0) { if (!m_bMouseEnabled) return NULL; if (!IsRandom()) { if(!::PtInRect(&m_rcItem, * static_cast<LPPOINT>(pData))) return NULL; } else { if(!::PtInRegion(m_hRgn,static_cast<LPPOINT>(pData)->x,static_cast<LPPOINT>(pData)->y)) return NULL; } } return Proc(this, pData); } void CControlUI::Invalidate() { if( !IsVisible() ) return; RECT invalidateRc = m_rcItem; CControlUI* pParent = this; RECT rcTemp; RECT rcParent; while( pParent = pParent->GetParent() ) { rcTemp = invalidateRc; rcParent = pParent->GetPos(); if( !::IntersectRect(&invalidateRc, &rcTemp, &rcParent) ) { return; } } if( m_pManager != NULL ) m_pManager->Invalidate(invalidateRc); } bool CControlUI::IsUpdateNeeded() const { return m_bUpdateNeeded; } void CControlUI::NeedUpdate() { if( !IsVisible() ) return; m_bUpdateNeeded = true; Invalidate(); if( m_pManager != NULL ) m_pManager->NeedUpdate(); } void CControlUI::NeedParentUpdate() { if( GetParent() ) { GetParent()->NeedUpdate(); GetParent()->Invalidate(); } else { NeedUpdate(); } if( m_pManager != NULL ) m_pManager->NeedUpdate(); } DWORD CControlUI::GetAdjustColor(DWORD dwColor) { if( !m_bColorHSL ) return dwColor; short H, S, L; CPaintManagerUI::GetHSL(&H, &S, &L); return CRenderEngine::AdjustColor(dwColor, H, S, L); } void CControlUI::Init() { DoInit(); if( OnInit ) OnInit(this); } void CControlUI::DoInit() { } void CControlUI::Event(TEventUI& event) { if( OnEvent(&event) ) DoEvent(event); } void CControlUI::DoEvent(TEventUI& event) { if( event.Type == UIEVENT_SETCURSOR ) { ::SetCursor(::LoadCursor(NULL, MAKEINTRESOURCE(IDC_ARROW))); return; } if( event.Type == UIEVENT_SETFOCUS ) { m_bFocused = true; Invalidate(); return; } if( event.Type == UIEVENT_KILLFOCUS ) { m_bFocused = false; Invalidate(); return; } if( event.Type == UIEVENT_MOUSEENTER ) { if(PtInRect(&m_rcItem,event.ptMouse)&&!m_bHover) m_bHover = true; } if( event.Type == UIEVENT_MOUSELEAVE ) { if(!PtInRect(&m_rcItem,event.ptMouse)&&m_bHover) m_bHover = false; } if( event.Type == UIEVENT_TIMER ) { m_pManager->SendNotify(this, _T("timer"), event.wParam, event.lParam); return; } if( event.Type == UIEVENT_CONTEXTMENU ) { if( IsContextMenuUsed() ) { m_pManager->SendNotify(this, _T("menu"), event.wParam, event.lParam); return; } } if(event.Type == UIEVENT_RELOADSTYLE) { if(!m_sStyleName.IsEmpty()) SetStyleName(m_sStyleName.GetData()); } if( m_pParent != NULL ) m_pParent->DoEvent(event); } void CControlUI::SetAttribute(LPCTSTR pstrName, LPCTSTR pstrValue) { if( _tcscmp(pstrName, _T("pos")) == 0 ) { RECT rcPos = { 0 }; LPTSTR pstr = NULL; rcPos.left = _tcstol(pstrValue, &pstr, 10); ASSERT(pstr); rcPos.top = _tcstol(pstr + 1, &pstr, 10); ASSERT(pstr); rcPos.right = _tcstol(pstr + 1, &pstr, 10); ASSERT(pstr); rcPos.bottom = _tcstol(pstr + 1, &pstr, 10); ASSERT(pstr); SIZE szXY = {rcPos.left >= 0 ? rcPos.left : rcPos.right, rcPos.top >= 0 ? rcPos.top : rcPos.bottom}; SetFixedXY(szXY); SetFixedWidth(rcPos.right - rcPos.left); SetFixedHeight(rcPos.bottom - rcPos.top); } else if( _tcscmp(pstrName, _T("relativepos")) == 0 ) { SIZE szMove,szZoom; LPTSTR pstr = NULL; szMove.cx = _tcstol(pstrValue, &pstr, 10); ASSERT(pstr); szMove.cy = _tcstol(pstr + 1, &pstr, 10); ASSERT(pstr); szZoom.cx = _tcstol(pstr + 1, &pstr, 10); ASSERT(pstr); szZoom.cy = _tcstol(pstr + 1, &pstr, 10); ASSERT(pstr); SetRelativePos(szMove,szZoom); } else if( _tcscmp(pstrName, _T("padding")) == 0 ) { RECT rcPadding = { 0 }; LPTSTR pstr = NULL; rcPadding.left = _tcstol(pstrValue, &pstr, 10); ASSERT(pstr); rcPadding.top = _tcstol(pstr + 1, &pstr, 10); ASSERT(pstr); rcPadding.right = _tcstol(pstr + 1, &pstr, 10); ASSERT(pstr); rcPadding.bottom = _tcstol(pstr + 1, &pstr, 10); ASSERT(pstr); SetPadding(rcPadding); } else if( _tcscmp(pstrName, _T("bkcolor")) == 0 || _tcscmp(pstrName, _T("bkcolor1")) == 0 ) { while( *pstrValue > _T('\0') && *pstrValue <= _T(' ') ) pstrValue = ::CharNext(pstrValue); if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue); LPTSTR pstr = NULL; DWORD clrColor = _tcstoul(pstrValue, &pstr, 16); SetBkColor(clrColor); } else if( _tcscmp(pstrName, _T("bkcolor2")) == 0 ) { while( *pstrValue > _T('\0') && *pstrValue <= _T(' ') ) pstrValue = ::CharNext(pstrValue); if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue); LPTSTR pstr = NULL; DWORD clrColor = _tcstoul(pstrValue, &pstr, 16); SetBkColor2(clrColor); } else if( _tcscmp(pstrName, _T("bkcolor3")) == 0 ) { while( *pstrValue > _T('\0') && *pstrValue <= _T(' ') ) pstrValue = ::CharNext(pstrValue); if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue); LPTSTR pstr = NULL; DWORD clrColor = _tcstoul(pstrValue, &pstr, 16); SetBkColor3(clrColor); } else if( _tcscmp(pstrName, _T("disabledbkcolor")) == 0 ) { if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue); LPTSTR pstr = NULL; DWORD clrColor = _tcstoul(pstrValue, &pstr, 16); SetDisabledBkColor(clrColor); } else if( _tcscmp(pstrName, _T("bordercolor")) == 0 ) { if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue); LPTSTR pstr = NULL; DWORD clrColor = _tcstoul(pstrValue, &pstr, 16); SetBorderColor(clrColor); } else if( _tcscmp(pstrName, _T("focusbordercolor")) == 0 ) { if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue); LPTSTR pstr = NULL; DWORD clrColor = _tcstoul(pstrValue, &pstr, 16); SetFocusBorderColor(clrColor); } else if( _tcscmp(pstrName, _T("hoverbordercolor")) == 0 ) {//添加hoverbordercolor属性 if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue); LPTSTR pstr = NULL; DWORD clrColor = _tcstoul(pstrValue, &pstr, 16); SetHoverBorderColor(clrColor, 1); } else if( _tcscmp(pstrName, _T("colorhsl")) == 0 ) SetColorHSL(_tcscmp(pstrValue, _T("true")) == 0); else if( _tcscmp(pstrName, _T("bordersize")) == 0 ) SetBorderSize(_ttoi(pstrValue)); else if( _tcscmp(pstrName, _T("borderround")) == 0 ) { SIZE cxyRound = { 0 }; LPTSTR pstr = NULL; cxyRound.cx = _tcstol(pstrValue, &pstr, 10); ASSERT(pstr); cxyRound.cy = _tcstol(pstr + 1, &pstr, 10); ASSERT(pstr); SetBorderRound(cxyRound); } else if( _tcscmp(pstrName, _T("bkimage")) == 0 ) SetBkImage(pstrValue); else if(_tcscmp(pstrName, _T("diablebkimage")) == 0 ) SetDisableBkImage(pstrValue); else if( _tcscmp(pstrName, _T("width")) == 0 ) SetFixedWidth(_ttoi(pstrValue)); else if( _tcscmp(pstrName, _T("height")) == 0 ) SetFixedHeight(_ttoi(pstrValue)); else if( _tcscmp(pstrName, _T("minwidth")) == 0 ) SetMinWidth(_ttoi(pstrValue)); else if( _tcscmp(pstrName, _T("minheight")) == 0 ) SetMinHeight(_ttoi(pstrValue)); else if( _tcscmp(pstrName, _T("maxwidth")) == 0 ) SetMaxWidth(_ttoi(pstrValue)); else if( _tcscmp(pstrName, _T("maxheight")) == 0 ) SetMaxHeight(_ttoi(pstrValue)); else if( _tcscmp(pstrName, _T("name")) == 0 ) SetName(pstrValue); else if( _tcscmp(pstrName, _T("text")) == 0 ) SetText(pstrValue); else if( _tcscmp(pstrName, _T("tooltip")) == 0 ) SetToolTip(pstrValue); else if( _tcscmp(pstrName, _T("userdata")) == 0 ) SetUserData(pstrValue); else if( _tcscmp(pstrName, _T("enabled")) == 0 ) SetEnabled(_tcscmp(pstrValue, _T("true")) == 0); else if( _tcscmp(pstrName, _T("mouse")) == 0 ) SetMouseEnabled(_tcscmp(pstrValue, _T("true")) == 0); else if( _tcscmp(pstrName, _T("keyboard")) == 0 ) SetKeyboardEnabled(_tcscmp(pstrValue, _T("true")) == 0); else if( _tcscmp(pstrName, _T("visible")) == 0 ) SetVisible(_tcscmp(pstrValue, _T("true")) == 0); else if( _tcscmp(pstrName, _T("random")) == 0 ) SetRandom(_tcscmp(pstrValue, _T("true")) == 0); else if( _tcscmp(pstrName, _T("float")) == 0 ) SetFloat(_tcscmp(pstrValue, _T("true")) == 0); else if( _tcscmp(pstrName, _T("shortcut")) == 0 ) SetShortcut(pstrValue[0]); else if( _tcscmp(pstrName, _T("menu")) == 0 ) SetContextMenuUsed(_tcscmp(pstrValue, _T("true")) == 0); else if( _tcscmp(pstrName, _T("animeffects")) == 0 ) SetAnimEffects(_tcscmp(pstrValue, _T("true")) == 0); else if( _tcscmp(pstrName, _T("adveffects")) == 0 ) SetEffectsStyle(pstrValue,&m_tCurEffects); else if( _tcscmp(pstrName, _T("easyeffects")) == 0 ) AnyEasyEffectsPorfiles(pstrValue,&m_tCurEffects); else if( _tcscmp(pstrName, _T("mouseineffects")) == 0 ) SetEffectsStyle(pstrValue,&m_tMouseInEffects); else if( _tcscmp(pstrName, _T("mouseouteffects")) == 0 ) SetEffectsStyle(pstrValue,&m_tMouseOutEffects); else if( _tcscmp(pstrName, _T("mouseclickeffects")) == 0 ) SetEffectsStyle(pstrValue,&m_tMouseClickEffects); else if( _tcscmp(pstrName, _T("effectstyle")) == 0 ) SetEffectsStyle(pstrValue,&m_tCurEffects); else if( _tcscmp(pstrName, _T("mouseinstyle")) == 0 ) SetEffectsStyle(pstrValue,&m_tMouseInEffects); else if( _tcscmp(pstrName, _T("mouseoutstyle")) == 0 ) SetEffectsStyle(pstrValue,&m_tMouseOutEffects); else if( _tcscmp(pstrName, _T("mouseclickstyle")) == 0 ) SetEffectsStyle(pstrValue,&m_tMouseClickEffects); } CControlUI* CControlUI::ApplyAttributeList(LPCTSTR pstrList) { CDuiString sItem; CDuiString sValue; while( *pstrList != _T('\0') ) { sItem.Empty(); sValue.Empty(); while( *pstrList != _T('\0') && *pstrList != _T('=') ) { LPTSTR pstrTemp = ::CharNext(pstrList); while( pstrList < pstrTemp) { sItem += *pstrList++; } } ASSERT( *pstrList == _T('=') ); if( *pstrList++ != _T('=') ) return this; ASSERT( *pstrList == _T('\"') ); if( *pstrList++ != _T('\"') ) return this; while( *pstrList != _T('\0') && *pstrList != _T('\"') ) { LPTSTR pstrTemp = ::CharNext(pstrList); while( pstrList < pstrTemp) { sValue += *pstrList++; } } ASSERT( *pstrList == _T('\"') ); if( *pstrList++ != _T('\"') ) return this; SetAttribute(sItem, sValue); if( *pstrList++ != _T(' ') ) return this; } return this; } SIZE CControlUI::EstimateSize(SIZE szAvailable) { return m_cxyFixed; } void CControlUI::DoPaint(HDC hDC, const RECT& rcPaint) { if( !::IntersectRect(&m_rcPaint, &rcPaint, &m_rcItem) ) return; // 绘制循序:背景颜色->背景图->状态图->文本->边框 if( m_cxyBorderRound.cx > 0 || m_cxyBorderRound.cy > 0 ) { CRenderClip roundClip; CRenderClip::GenerateRoundClip(hDC, m_rcPaint, m_rcItem, m_cxyBorderRound.cx, m_cxyBorderRound.cy, roundClip); PaintBkColor(hDC); PaintBkImage(hDC); PaintStatusImage(hDC); PaintText(hDC); PaintBorder(hDC); } else { PaintBkColor(hDC); PaintBkImage(hDC); PaintStatusImage(hDC); PaintText(hDC); PaintBorder(hDC); } } void CControlUI::PaintBkColor(HDC hDC) { if( m_dwBackColor != 0 ) { if( m_dwBackColor2 != 0 ) { if( m_dwBackColor3 != 0 ) { RECT rc = m_rcItem; rc.bottom = (rc.bottom + rc.top) / 2; CRenderEngine::DrawGradient(hDC, rc, GetAdjustColor(m_dwBackColor), GetAdjustColor(m_dwBackColor2), true, 8); rc.top = rc.bottom; rc.bottom = m_rcItem.bottom; CRenderEngine::DrawGradient(hDC, rc, GetAdjustColor(m_dwBackColor2), GetAdjustColor(m_dwBackColor3), true, 8); } else CRenderEngine::DrawGradient(hDC, m_rcItem, GetAdjustColor(m_dwBackColor), GetAdjustColor(m_dwBackColor2), true, 16); } else if( m_dwBackColor >= 0xFF000000 ) CRenderEngine::DrawColor(hDC, m_rcPaint, GetAdjustColor(m_dwBackColor)); else CRenderEngine::DrawColor(hDC, m_rcItem, GetAdjustColor(m_dwBackColor)); } } void CControlUI::PaintBkImage(HDC hDC) { if( m_sBkImage.IsEmpty() ) return; if (m_bGetRegion) { GetRegion(hDC,m_sBkImage,RGB(0,0,0)); } if(IsEnabled()) { if( !DrawImage(hDC, (LPCTSTR)m_sBkImage) ) m_sBkImage.Empty(); } else { if( !DrawImage(hDC, (LPCTSTR)m_sDisableBkImage) ) m_sDisableBkImage.Empty(); } } void CControlUI::PaintStatusImage(HDC hDC) { return; } void CControlUI::PaintText(HDC hDC) { return; } void CControlUI::PaintBorder(HDC hDC) { if( m_cxyBorderRound.cx > 0 || m_cxyBorderRound.cy > 0 )//画圆角边框 { if (IsFocused() && m_dwFocusBorderColor != 0 && m_nFocusBorderSize > 0) CRenderEngine::DrawRoundRect(hDC, m_rcItem, m_nFocusBorderSize, m_cxyBorderRound.cx, m_cxyBorderRound.cy, GetAdjustColor(m_dwFocusBorderColor)); else if(IsHovered() && m_dwHoverBorderColor !=0 && m_nHoverBorderSize >0) CRenderEngine::DrawRoundRect(hDC, m_rcItem, m_nHoverBorderSize, m_cxyBorderRound.cx, m_cxyBorderRound.cy, GetAdjustColor(m_dwHoverBorderColor)); else if(m_nBorderSize >0) CRenderEngine::DrawRoundRect(hDC, m_rcItem, m_nBorderSize, m_cxyBorderRound.cx, m_cxyBorderRound.cy, GetAdjustColor(m_dwBorderColor)); } else { if (IsFocused() && m_dwFocusBorderColor != 0 && m_nFocusBorderSize >0) CRenderEngine::DrawRect(hDC, m_rcItem, m_nFocusBorderSize, GetAdjustColor(m_dwFocusBorderColor)); else if(IsHovered() && m_dwHoverBorderColor !=0 && m_nHoverBorderSize > 0) CRenderEngine::DrawRect(hDC, m_rcItem, m_nHoverBorderSize, GetAdjustColor(m_dwHoverBorderColor)); else if(m_nBorderSize > 0) CRenderEngine::DrawRect(hDC, m_rcItem, m_nBorderSize, GetAdjustColor(m_dwBorderColor)); } } void CControlUI::DoPostPaint(HDC hDC, const RECT& rcPaint) { return; } //************************************ // Method: GetEffectStyle // FullName: CControlUI::GetEffectStyle // Access: virtual public // Returns: UiLib::CDuiString // Qualifier: const // Note: //************************************ CDuiString CControlUI::GetEffectStyle() const { try { return m_strEffectStyle; } catch (...) { throw "CControlUI::GetEffectStyle"; } } //************************************ // Method: SetAnimEffects // FullName: CControlUI::SetAnimEffects // Access: virtual public // Returns: void // Qualifier: // Parameter: bool bEnableEffect // Note: //************************************ void CControlUI::SetAnimEffects( bool bEnableEffect ) { try { m_bEnabledEffect = bEnableEffect; } catch (...) { throw "CControlUI::SetAnimEffects"; } } //************************************ // Method: GetAnimEffects // FullName: CControlUI::GetAnimEffects // Access: virtual public // Returns: bool // Qualifier: const // Note: //************************************ bool CControlUI::GetAnimEffects() const { try { return m_bEnabledEffect; } catch (...) { throw "CControlUI::GetAnimEffects"; } } //************************************ // Method: SetEffectsZoom // FullName: CControlUI::SetEffectsZoom // Access: virtual public // Returns: void // Qualifier: // Parameter: int iZoom // Note: //************************************ void CControlUI::SetEffectsZoom( int iZoom ) { try { m_tCurEffects.m_iZoom = iZoom; } catch (...) { throw "CControlUI::SetEffectsZoom"; } } //************************************ // Method: GetEffectsZoom // FullName: CControlUI::GetEffectsZoom // Access: virtual public // Returns: int // Qualifier: const // Note: //************************************ int CControlUI::GetEffectsZoom() const { try { return m_tCurEffects.m_iZoom; } catch (...) { throw "CControlUI::GetEffectsZoom"; } } //************************************ // Method: SetEffectsFillingBK // FullName: CControlUI::SetEffectsFillingBK // Access: virtual public // Returns: void // Qualifier: // Parameter: DWORD dFillingBK // Note: //************************************ void CControlUI::SetEffectsFillingBK( DWORD dFillingBK ) { try { m_tCurEffects.m_dFillingBK = dFillingBK; } catch (...) { throw "CControlUI::SetEffectsFillingBK"; } } //************************************ // Method: GetEffectsFillingBK // FullName: CControlUI::GetEffectsFillingBK // Access: virtual public // Returns: DWORD // Qualifier: const // Note: //************************************ DWORD CControlUI::GetEffectsFillingBK() const { try { return m_tCurEffects.m_dFillingBK; } catch (...) { throw "CControlUI::GetEffectsFillingBK"; } } //************************************ // Method: SetEffectsOffectX // FullName: CControlUI::SetEffectsOffectX // Access: virtual public // Returns: void // Qualifier: // Parameter: int iOffectX // Note: //************************************ void CControlUI::SetEffectsOffectX( int iOffectX ) { try { m_tCurEffects.m_iOffectX = iOffectX; } catch (...) { throw "CControlUI::SetEffectsOffectX"; } } //************************************ // Method: GetEffectsOffectX // FullName: CControlUI::GetEffectsOffectX // Access: virtual public // Returns: int // Qualifier: const // Note: //************************************ int CControlUI::GetEffectsOffectX() const { try { return m_tCurEffects.m_iOffectX; } catch (...) { throw "CControlUI::GetEffectsOffectX"; } } //************************************ // Method: SetEffectsOffectY // FullName: CControlUI::SetEffectsOffectY // Access: virtual public // Returns: void // Qualifier: // Parameter: int iOffectY // Note: //************************************ void CControlUI::SetEffectsOffectY( int iOffectY ) { try { m_tCurEffects.m_iOffectY = iOffectY; } catch (...) { throw "CControlUI::SetEffectsOffectY"; } } //************************************ // Method: GetEffectsOffectY // FullName: CControlUI::GetEffectsOffectY // Access: virtual public // Returns: int // Qualifier: const // Note: //************************************ int CControlUI::GetEffectsOffectY() const { try { return m_tCurEffects.m_iOffectY; } catch (...) { throw "CControlUI::GetEffectsOffectY"; } } //************************************ // Method: SetEffectsAlpha // FullName: CControlUI::SetEffectsAlpha // Access: virtual public // Returns: void // Qualifier: // Parameter: int iAlpha // Note: //************************************ void CControlUI::SetEffectsAlpha( int iAlpha ) { try { m_tCurEffects.m_iAlpha = iAlpha; } catch (...) { throw "CControlUI::SetEffectsAlpha"; } } //************************************ // Method: GetEffectsAlpha // FullName: CControlUI::GetEffectsAlpha // Access: virtual public // Returns: int // Qualifier: const // Note: //************************************ int CControlUI::GetEffectsAlpha() const { try { return m_tCurEffects.m_iAlpha; } catch (...) { throw "CControlUI::GetEffectsAlpha"; } } //************************************ // Method: SetEffectsRotation // FullName: CControlUI::SetEffectsRotation // Access: virtual public // Returns: void // Qualifier: // Parameter: float fRotation // Note: //************************************ void CControlUI::SetEffectsRotation( float fRotation ) { try { m_tCurEffects.m_fRotation = fRotation; } catch (...) { throw "CControlUI::SetEffectsRotation"; } } //************************************ // Method: GetEffectRotation // FullName: CControlUI::GetEffectsRotation // Access: virtual public // Returns: float // Qualifier: // Note: //************************************ float CControlUI::GetEffectsRotation() { try { return m_tCurEffects.m_fRotation; } catch (...) { throw "CControlUI::GetEffectsRotation"; } } //************************************ // Method: SetEffectsNeedTimer // FullName: CControlUI::SetEffectsNeedTimer // Access: virtual public // Returns: void // Qualifier: // Parameter: int iNeedTimer // Note: //************************************ void CControlUI::SetEffectsNeedTimer( int iNeedTimer ) { try { m_tCurEffects.m_iNeedTimer = iNeedTimer; } catch (...) { throw "CControlUI::SetEffectsNeedTimer"; } } //************************************ // Method: GetEffectsNeedTimer // FullName: CControlUI::GetEffectsNeedTimer // Access: virtual public // Returns: int // Qualifier: // Note: //************************************ int CControlUI::GetEffectsNeedTimer() { try { return m_tCurEffects.m_iNeedTimer; } catch (...) { throw "CControlUI::GetEffectsNeedTimer"; } } //************************************ // Method: GetCurEffects // FullName: CControlUI::GetCurEffects // Access: virtual public // Returns: TEffectAge* // Qualifier: // Note: //************************************ TEffectAge* CControlUI::GetCurEffects() { try { return &m_tCurEffects; } catch (...) { throw "CControlUI::GetCurEffects"; } } //************************************ // Method: GetMouseInEffect // FullName: CControlUI::GetMouseInEffect // Access: virtual public // Returns: TEffectAge* // Qualifier: // Note: //************************************ TEffectAge* CControlUI::GetMouseInEffect() { try { return &m_tMouseInEffects; } catch (...) { throw "CControlUI::GetMouseInEffect"; } } //************************************ // Method: GetMouseOutEffect // FullName: CControlUI::GetMouseOutEffect // Access: virtual public // Returns: TEffectAge* // Qualifier: // Note: //************************************ TEffectAge* CControlUI::GetMouseOutEffect() { try { return &m_tMouseOutEffects; } catch (...) { throw "CControlUI::GetMouseOutEffect"; } } //************************************ // Method: GetClickInEffect // FullName: CControlUI::GetClickInEffect // Access: virtual public // Returns: TEffectAge* // Qualifier: // Note: //************************************ TEffectAge* CControlUI::GetClickInEffect() { try { return &m_tMouseClickEffects; } catch (...) { throw "CControlUI::GetClickInEffect"; } } //************************************ // Method: SetEffectsStyle // FullName: CControlUI::SetEffectsStyle // Access: virtual public // Returns: void // Qualifier: // Parameter: LPCTSTR pstrEffectStyle // Parameter: TEffectAge * pTEffectAge // Note: //************************************ void CControlUI::SetEffectsStyle( LPCTSTR pstrEffectStyle,TEffectAge* pTEffectAge /*= NULL*/ ) { try { m_strEffectStyle = GetManager()->GetEffectsStyle(pstrEffectStyle); if(m_strEffectStyle.IsEmpty() && pstrEffectStyle) { AnyEffectsAdvProfiles(pstrEffectStyle,pTEffectAge); AnyEasyEffectsPorfiles(pstrEffectStyle,pTEffectAge); } else if(!m_strEffectStyle.IsEmpty()) { AnyEffectsAdvProfiles(m_strEffectStyle,pTEffectAge); AnyEasyEffectsPorfiles(m_strEffectStyle,pTEffectAge); } } catch (...) { throw "CControlUI::SetEffectsStyle"; } } //************************************ // Method: AnyEffectsAdvProfiles // FullName: UiLib::CControlUI::AnyEffectsAdvProfiles // Access: public // Returns: void // Qualifier: // Parameter: LPCTSTR pstrEffects // Parameter: TEffectAge * pTEffectAge //************************************ void CControlUI::AnyEffectsAdvProfiles( LPCTSTR pstrEffects,TEffectAge* pTEffectAge /*= NULL*/ ) { try { CDuiString sItem; CDuiString sValue; LPTSTR pstr = NULL; TEffectAge* pcTEffectAge = pTEffectAge?pTEffectAge:&m_tCurEffects; while( *pstrEffects != _T('\0') ) { sItem.Empty(); sValue.Empty(); while( *pstrEffects > _T('\0') && *pstrEffects <= _T(' ') ) pstrEffects = ::CharNext(pstrEffects); while( *pstrEffects != _T('\0') && *pstrEffects != _T('=') && *pstrEffects > _T(' ') ) { LPTSTR pstrTemp = ::CharNext(pstrEffects); while( pstrEffects < pstrTemp) { sItem += *pstrEffects++; } } while( *pstrEffects > _T('\0') && *pstrEffects <= _T(' ') ) pstrEffects = ::CharNext(pstrEffects); if( *pstrEffects++ != _T('=') ) break; while( *pstrEffects > _T('\0') && *pstrEffects <= _T(' ') ) pstrEffects = ::CharNext(pstrEffects); if( *pstrEffects++ != _T('\'') ) break; while( *pstrEffects != _T('\0') && *pstrEffects != _T('\'') ) { LPTSTR pstrTemp = ::CharNext(pstrEffects); while( pstrEffects < pstrTemp) { sValue += *pstrEffects++; } } if( *pstrEffects++ != _T('\'') ) break; if( !sValue.IsEmpty() ) { if( sItem == _T("zoom") ) pcTEffectAge->m_iZoom = (_ttoi(sValue.GetData())); else if( sItem == _T("fillingbk") ){ if(sValue == _T("none")) sValue == _T("#ffffffff"); if( *sValue.GetData() == _T('#')) sValue = ::CharNext(sValue.GetData()); pcTEffectAge->m_dFillingBK = (_tcstoul(sValue.GetData(),&pstr,16)); ASSERT(pstr); } else if( sItem == _T("offsetx") ) pcTEffectAge->m_iOffectX = (_ttoi(sValue.GetData())); else if( sItem == _T("offsety") ) pcTEffectAge->m_iOffectY = (_ttoi(sValue.GetData())); else if( sItem == _T("alpha") ) pcTEffectAge->m_iAlpha = (_ttoi(sValue.GetData())); else if( sItem == _T("rotation") ) pcTEffectAge->m_fRotation = (float)(_tstof(sValue.GetData())); else if( sItem == _T("needtimer") ) pcTEffectAge->m_iNeedTimer = (_ttoi(sValue.GetData())); } if( *pstrEffects++ != _T(' ') ) break; } pcTEffectAge->m_bEnableEffect = true; } catch (...) { throw "CControlUI::AnyEffectsAdvProfiles"; } } //************************************ // Method: AnyEasyEffectsPorfiles // FullName: UiLib::CControlUI::AnyEasyEffectsPorfiles // Access: public // Returns: void // Qualifier: // Parameter: LPCTSTR pstrEffects // Parameter: TEffectAge * pTEffectAge //************************************ void CControlUI::AnyEasyEffectsPorfiles( LPCTSTR pstrEffects,TEffectAge* pTEffectAge /*= NULL*/ ) { try { CDuiString sItem; CDuiString sValue; CDuiString sAnim; LPTSTR pstr = NULL; TEffectAge* pcTEffectAge = pTEffectAge?pTEffectAge:&m_tCurEffects; while( *pstrEffects != _T('\0') ) { sItem.Empty(); sValue.Empty(); while( *pstrEffects > _T('\0') && *pstrEffects <= _T(' ') ) pstrEffects = ::CharNext(pstrEffects); while( *pstrEffects != _T('\0') && *pstrEffects != _T('=') && *pstrEffects > _T(' ') ) { LPTSTR pstrTemp = ::CharNext(pstrEffects); while( pstrEffects < pstrTemp) { sItem += *pstrEffects++; } } while( *pstrEffects > _T('\0') && *pstrEffects <= _T(' ') ) pstrEffects = ::CharNext(pstrEffects); if( *pstrEffects++ != _T('=') ) break; while( *pstrEffects > _T('\0') && *pstrEffects <= _T(' ') ) pstrEffects = ::CharNext(pstrEffects); if( *pstrEffects++ != _T('\'') ) break; while( *pstrEffects != _T('\0') && *pstrEffects != _T('\'') ) { LPTSTR pstrTemp = ::CharNext(pstrEffects); while( pstrEffects < pstrTemp) { sValue += *pstrEffects++; } } if( *pstrEffects++ != _T('\'') ) break; if( !sValue.IsEmpty() ) { if( sItem == _T("anim") ){ sAnim = sValue; if(sValue == _T("zoom+")){ if(pcTEffectAge->m_iZoom > 0) pcTEffectAge->m_iZoom = (pcTEffectAge->m_iZoom - pcTEffectAge->m_iZoom*2); if(pcTEffectAge->m_iZoom == 0) pcTEffectAge->m_iZoom = -1; pcTEffectAge->m_iAlpha = -255; pcTEffectAge->m_fRotation = 0.0; } else if(sValue == _T("zoom-")){ if(pcTEffectAge->m_iZoom < 0) pcTEffectAge->m_iZoom = (pcTEffectAge->m_iZoom - pcTEffectAge->m_iZoom*2); if(pcTEffectAge->m_iZoom == 0) pcTEffectAge->m_iZoom = 1; pcTEffectAge->m_iAlpha = 255; pcTEffectAge->m_fRotation = 0.0; } else if(sValue == _T("left2right")){ if(pcTEffectAge->m_iOffectX > 0) pcTEffectAge->m_iOffectX = (pcTEffectAge->m_iOffectX - pcTEffectAge->m_iOffectX*2); pcTEffectAge->m_iAlpha = 255; pcTEffectAge->m_iZoom = 0; pcTEffectAge->m_iOffectY = 0; pcTEffectAge->m_fRotation = 0.0; } else if(sValue == _T("right2left")){ if(pcTEffectAge->m_iOffectX < 0) pcTEffectAge->m_iOffectX = (pcTEffectAge->m_iOffectX - pcTEffectAge->m_iOffectX*2); pcTEffectAge->m_iAlpha = 255; pcTEffectAge->m_iZoom = 0; pcTEffectAge->m_iOffectY = 0; pcTEffectAge->m_fRotation = 0.0; } else if(sValue == _T("top2bottom")){ if(pcTEffectAge->m_iOffectY > 0) pcTEffectAge->m_iOffectY = (pcTEffectAge->m_iOffectY - pcTEffectAge->m_iOffectY*2); pcTEffectAge->m_iAlpha = 255; pcTEffectAge->m_iZoom = 0; pcTEffectAge->m_iOffectX = 0; pcTEffectAge->m_fRotation = 0.0; } else if(sValue == _T("bottom2top")){ if(pcTEffectAge->m_iOffectY < 0) pcTEffectAge->m_iOffectY = (pcTEffectAge->m_iOffectY - pcTEffectAge->m_iOffectY*2); pcTEffectAge->m_iAlpha = 255; pcTEffectAge->m_iZoom = 0; pcTEffectAge->m_iOffectX = 0; pcTEffectAge->m_fRotation = 0.0; } } else if( sItem == _T("offset") ){ if(sAnim == _T("zoom+") || sAnim == _T("zoom-")){ pcTEffectAge->m_iOffectX = 0; pcTEffectAge->m_iOffectY = 0; } else if(sAnim == _T("left2right") || sAnim == _T("right2left")){ pcTEffectAge->m_iOffectX = _ttoi(sValue.GetData()); pcTEffectAge->m_iOffectY = 0; if(sAnim == _T("left2right")) if(pcTEffectAge->m_iOffectX > 0) pcTEffectAge->m_iOffectX = (pcTEffectAge->m_iOffectX - pcTEffectAge->m_iOffectX*2); else if(sAnim == _T("right2left")) if(pcTEffectAge->m_iOffectX < 0) pcTEffectAge->m_iOffectX = (pcTEffectAge->m_iOffectX - pcTEffectAge->m_iOffectX*2); } else if(sAnim == _T("top2bottom") || sAnim == _T("bottom2top")){ pcTEffectAge->m_iOffectX = 0; pcTEffectAge->m_iOffectY = _ttoi(sValue.GetData()); if(sAnim == _T("top2bottom")) if(pcTEffectAge->m_iOffectY > 0) pcTEffectAge->m_iOffectY = (pcTEffectAge->m_iOffectY - pcTEffectAge->m_iOffectY*2); if(sAnim == _T("bottom2top")) if(pcTEffectAge->m_iOffectY < 0) pcTEffectAge->m_iOffectY = (pcTEffectAge->m_iOffectY - pcTEffectAge->m_iOffectY*2); } } else if( sItem == _T("needtimer") ) pcTEffectAge->m_iNeedTimer = (_ttoi(sValue.GetData())); else if( sItem == _T("fillingbk") ){ if(sValue == _T("none")) sValue == _T("#ffffffff"); if( *sValue.GetData() == _T('#')) sValue = ::CharNext(sValue.GetData()); pcTEffectAge->m_dFillingBK = _tcstoul(sValue.GetData(),&pstr,16); ASSERT(pstr); } } if( *pstrEffects++ != _T(' ') ) break; } pcTEffectAge->m_bEnableEffect = true; } catch (...) { throw "CControlUI::AnyEasyEffectsPorfiles"; } } //************************************ // Method: TriggerEffects // FullName: CControlUI::TriggerEffects // Access: virtual public // Returns: void // Qualifier: // Parameter: TEffectAge * pTEffectAge // Note: //************************************ void CControlUI::TriggerEffects( TEffectAge* pTEffectAge /*= NULL*/ ) { try { try { TEffectAge* pcTEffect = pTEffectAge?pTEffectAge:&m_tCurEffects; // if(GetManager() && m_bEnabledEffect && pcTEffect->m_bEnableEffect) // GetManager()->AddAnimationJob(CDxAnimationUI(UIANIMTYPE_FLAT,0,pcTEffect->m_iNeedTimer,pcTEffect->m_dFillingBK,pcTEffect->m_dFillingBK,GetPos(),pcTEffect->m_iOffectX,pcTEffect->m_iOffectY,pcTEffect->m_iZoom,pcTEffect->m_iAlpha,(float)pcTEffect->m_fRotation)); } catch (...) { throw "CControlUI::TriggerEffects"; } } catch (...) { throw "CControlUI::TriggerEffects"; } } } // namespace UiLib
#define BOOST_TEST_MODULE uri test #include <boost/test/unit_test.hpp> #include <stdio.h> #include "uri.hh" using namespace ten; /* TODO: test uris from: * http://code.google.com/p/google-url/source/browse/trunk/src/gurl_unittest.cc */ BOOST_AUTO_TEST_CASE(uri_constructor) { uri u; BOOST_CHECK(u.scheme.empty()); BOOST_CHECK(u.userinfo.empty()); BOOST_CHECK(u.host.empty()); BOOST_CHECK(u.path.empty()); BOOST_CHECK(u.query.empty()); BOOST_CHECK(u.fragment.empty()); BOOST_CHECK_EQUAL(0, u.port); } BOOST_AUTO_TEST_CASE(uri_parse_long) { static const char uri1[] = "http://www.google.com/images?hl=en&client=firefox-a&hs=tldrls=org.mozilla:en-US:official&q=philippine+hijacked+bus+picturesum=1&ie=UTF-8&source=univ&ei=SC-_TLbjE5H2tgO70PHODA&sa=X&oi=image_result_group&ct=titleresnum=1&ved=0CCIQsAQwAAbiw=1239bih=622"; uri u(uri1); } BOOST_AUTO_TEST_CASE(uri_parse_brackets) { static const char uri1[] = "http://ad.doubleclick.net/adi/N5371.Google/B4882217.2;sz=160x600;pc=[TPAS_ID];click=http://googleads.g.doubleclick.net/aclk?sa=l&ai=Bepsf-z83TfuWJIKUjQS46ejyAeqc0t8B2uvnkxeiro6LRdC9wQEQARgBIPjy_wE4AFC0-b7IAmDJ9viGyKOgGaABnoHS5QOyAQ53d3cub3NuZXdzLmNvbboBCjE2MHg2MDBfYXPIAQnaAS9odHRwOi8vd3d3Lm9zbmV3cy5jb20vdXNlci9qYWNrZWVibGV1L2NvbW1lbnRzL7gCGMgCosXLE6gDAegDrwLoA5EG6APgBfUDAgAARPUDIAAAAA&num=1&sig=AGiWqty7uE4ibhWIPcOiZlX0__AQkpGEWA&client=ca-pub-6467510223857492&adurl=;ord=410711259?"; uri u(uri1); } BOOST_AUTO_TEST_CASE(uri_parse_pipe) { static const char uri1[] = "http://ads.pointroll.com/PortalServe/?pid=1048344U85520100615200820&flash=10time=3|18:36|-8redir=$CTURL$r=0.8149350655730814"; uri u(uri1); } BOOST_AUTO_TEST_CASE(uri_parse_unicode_escape) { static const char uri1[] = "http://b.scorecardresearch.com/b?C1=8&C2=6035047&C3=463.9924&C4=ad21868c&C5=173229&C6=16jfaue1ukmeoq&C7=http%3A//remotecontrol.mtv.com/2011/01/20/sammi-sweetheart-giancoloa-terrell-owens-hair/&C8=Hot%20Shots%3A%20Sammi%20%u2018Sweetheart%u2019%20Lets%20Terrell%20Owens%20Play%20With%20Her%20Hair%20%BB%20MTV%20Remote%20Control%20Blog&C9=&C10=1680x1050rn=58013009"; uri u(uri1); } BOOST_AUTO_TEST_CASE(uri_parse_double_percent) { static const char uri1[] = "http://bh.contextweb.com/bh/getuid?url=http://image2.pubmatic.com/AdServer/Pug?vcode=bz0yJnR5cGU9MSZqcz0xJmNvZGU9ODI1JnRsPTQzMjAw&piggybackCookie=%%CWGUID%%,User_tokens:%%USER_TOKENS%%"; uri u(uri1); } BOOST_AUTO_TEST_CASE(uri_parse_percent_amp) { static const char uri1[] = "http://b.scorecardresearch.com/foo=1&cr=2%&c9=thing"; uri u(uri1); } BOOST_AUTO_TEST_CASE(uri_parse_badencode) { static const char uri1[] = "http://b.scorecardresearch.com/b?c1=2&c2=6035223rn=1404429288&c7=http%3A%2F%2Fdetnews.com%2Farticle%2F20110121%2FMETRO01%2F101210376%2FDetroit-women-get-no-help-in-arrest-of-alleged-car-thief&c8=Detroit%20women%20get%20no%20help%20in%20arrest%20of%20alleged%2&cv=2.2&cs=js"; uri u(uri1); } BOOST_AUTO_TEST_CASE(uri_russian_decode) { static const char uri1[] = "http://example.com:3010/path/search.proto?q=%D0%BF%D1%83%D1%82%D0%B8%D0%BD"; uri u(uri1); u.normalize(); // NOTE: the string below should appear as russian BOOST_CHECK_EQUAL(uri::decode(u.query), "?q=путин"); } BOOST_AUTO_TEST_CASE(uri_parse_query) { static const char uri1[] = "http://example.com:3010/path/search.proto?q=%D0%BF%D1%83%D1%82%D0%B8%D0%BD"; uri u(uri1); u.normalize(); uri::query_params params = u.parse_query(); // NOTE: the string below should appear as russian BOOST_CHECK_EQUAL(params.size(), 1); BOOST_CHECK_EQUAL(uri::find_param(params, "q")->second, "путин"); } BOOST_AUTO_TEST_CASE(uri_parse_dups) { static const char uri1[] = "http://example.com:3030/path/search.proto?&&q=obama&q=obama"; uri u(uri1); } BOOST_AUTO_TEST_CASE(carrot_in_uri) { // this used to throw a parser error because of ^ in the query string static const char path[] = "/path/search.proto?&&__geo=213&nocache=da&q=%D0%A0%D0%BE%D1%81%D1%81%D0%B8%D1%8F+^+stuff"; uri tmp; tmp.host = "localhost"; tmp.scheme = "http"; tmp.path = path; uri u(tmp.compose()); } BOOST_AUTO_TEST_CASE(uri_transform) { /* examples from http://tools.ietf.org/html/rfc3986#section-5.4.1 */ static const char base_uri[] = "http://a/b/c/d;p?q"; uri b; uri t; uri r; BOOST_CHECK(b.parse(base_uri, strlen(base_uri))); r.path = "g"; t.transform(b, r); BOOST_CHECK_EQUAL("http://a/b/c/g", t.compose()); r.clear(); t.clear(); r.path = "./g"; t.transform(b, r); BOOST_CHECK_EQUAL("http://a/b/c/g", t.compose()); r.clear(); t.clear(); r.path = "g/"; t.transform(b, r); BOOST_CHECK_EQUAL("http://a/b/c/g/", t.compose()); r.clear(); t.clear(); r.path = "/g"; t.transform(b, r); BOOST_CHECK_EQUAL("http://a/g", t.compose()); r.clear(); t.clear(); r.host = "g"; t.transform(b, r); BOOST_CHECK_EQUAL("http://g/", t.compose()); r.clear(); t.clear(); r.query = "?y"; t.transform(b, r); BOOST_CHECK_EQUAL("http://a/b/c/d;p?y", t.compose()); r.clear(); t.clear(); r.path = "g"; r.query = "?y"; t.transform(b, r); BOOST_CHECK_EQUAL("http://a/b/c/g?y", t.compose()); r.clear(); t.clear(); r.fragment = "#s"; t.transform(b, r); BOOST_CHECK_EQUAL("http://a/b/c/d;p?q#s", t.compose()); r.clear(); t.clear(); r.path = "g"; r.fragment = "#s"; t.transform(b, r); BOOST_CHECK_EQUAL("http://a/b/c/g#s", t.compose()); r.clear(); t.clear(); r.path = "g"; r.query = "?y"; r.fragment = "#s"; t.transform(b, r); BOOST_CHECK_EQUAL("http://a/b/c/g?y#s", t.compose()); r.clear(); t.clear(); r.path = ";x"; t.transform(b, r); BOOST_CHECK_EQUAL("http://a/b/c/;x", t.compose()); r.clear(); t.clear(); r.path = "g;x"; t.transform(b, r); BOOST_CHECK_EQUAL("http://a/b/c/g;x", t.compose()); r.clear(); t.clear(); r.path = "g;x"; r.query = "?y"; r.fragment = "#s"; t.transform(b, r); BOOST_CHECK_EQUAL("http://a/b/c/g;x?y#s", t.compose()); r.clear(); t.clear(); r.path = ""; t.transform(b, r); BOOST_CHECK_EQUAL("http://a/b/c/d;p?q", t.compose()); r.clear(); t.clear(); r.path = "."; t.transform(b, r); BOOST_CHECK_EQUAL("http://a/b/c/", t.compose()); r.clear(); t.clear(); r.path = "./"; t.transform(b, r); BOOST_CHECK_EQUAL("http://a/b/c/", t.compose()); r.clear(); t.clear(); r.path = ".."; t.transform(b, r); BOOST_CHECK_EQUAL("http://a/b/", t.compose()); r.clear(); t.clear(); r.path = "../g"; t.transform(b, r); BOOST_CHECK_EQUAL("http://a/b/g", t.compose()); r.clear(); t.clear(); r.path = "../.."; t.transform(b, r); BOOST_CHECK_EQUAL("http://a/", t.compose()); r.clear(); t.clear(); r.path = "../../"; t.transform(b, r); BOOST_CHECK_EQUAL("http://a/", t.compose()); r.clear(); t.clear(); r.path = "../../g"; t.transform(b, r); BOOST_CHECK_EQUAL("http://a/g", t.compose()); r.clear(); t.clear(); /* abnormal examples */ r.path = "../../../g"; t.transform(b, r); BOOST_CHECK_EQUAL("http://a/g", t.compose()); r.clear(); t.clear(); r.path = "../../../../g"; t.transform(b, r); BOOST_CHECK_EQUAL("http://a/g", t.compose()); r.clear(); t.clear(); r.path = "/./g"; t.transform(b, r); BOOST_CHECK_EQUAL("http://a/g", t.compose()); r.clear(); t.clear(); r.path = "/../g"; t.transform(b, r); BOOST_CHECK_EQUAL("http://a/g", t.compose()); r.clear(); t.clear(); r.path = "g."; t.transform(b, r); BOOST_CHECK_EQUAL("http://a/b/c/g.", t.compose()); r.clear(); t.clear(); r.path = ".g"; t.transform(b, r); BOOST_CHECK_EQUAL("http://a/b/c/.g", t.compose()); r.clear(); t.clear(); r.path = "g.."; t.transform(b, r); BOOST_CHECK_EQUAL("http://a/b/c/g..", t.compose()); r.clear(); t.clear(); r.path = "..g"; t.transform(b, r); BOOST_CHECK_EQUAL("http://a/b/c/..g", t.compose()); r.clear(); t.clear(); /* nonsensical */ r.path = "./../g"; t.transform(b, r); BOOST_CHECK_EQUAL("http://a/b/g", t.compose()); r.clear(); t.clear(); r.path = "./g/."; t.transform(b, r); BOOST_CHECK_EQUAL("http://a/b/c/g/", t.compose()); r.clear(); t.clear(); r.path = "g/./h"; t.transform(b, r); BOOST_CHECK_EQUAL("http://a/b/c/g/h", t.compose()); r.clear(); t.clear(); r.path = "g/../h"; t.transform(b, r); BOOST_CHECK_EQUAL("http://a/b/c/h", t.compose()); r.clear(); t.clear(); r.path = "g;x=1/./y"; t.transform(b, r); BOOST_CHECK_EQUAL("http://a/b/c/g;x=1/y", t.compose()); r.clear(); t.clear(); r.path = "g;x=1/../y"; t.transform(b, r); BOOST_CHECK_EQUAL("http://a/b/c/y", t.compose()); r.clear(); t.clear(); } BOOST_AUTO_TEST_CASE(uri_compose) { static const char uri1[] = "eXAMPLE://ExAmPlE.CoM/foo/../boo/%25hi%0b/.t%65st/./this?query=string#frag"; uri u(uri1); BOOST_CHECK_EQUAL(uri1, u.compose()); u.normalize(); BOOST_CHECK_EQUAL("example://example.com/boo/%25hi%0B/.test/this?query=string#frag", u.compose()); } BOOST_AUTO_TEST_CASE(uri_normalize_host) { static const char uri1[] = "eXAMPLE://ExAmPlE.CoM/"; uri u(uri1); u.normalize(); BOOST_CHECK_EQUAL("example.com", u.host); } BOOST_AUTO_TEST_CASE(uri_normalize_one_slash) { static const char uri1[] = "eXAMPLE://a"; static const char uri2[] = "eXAMPLE://a/"; uri u(uri1); u.normalize(); BOOST_CHECK_EQUAL("/", u.path); u.clear(); BOOST_CHECK(u.parse(uri2, strlen(uri2))); u.normalize(); BOOST_CHECK_EQUAL("/", u.path); } BOOST_AUTO_TEST_CASE(uri_normalize_all_slashes) { static const char uri1[] = "eXAMPLE://a//////"; uri u(uri1); u.normalize(); BOOST_CHECK_EQUAL("/", u.path); } BOOST_AUTO_TEST_CASE(uri_normalize) { static const char uri1[] = "eXAMPLE://a/./b/../b/%63/%7bfoo%7d"; uri u(uri1); u.normalize(); BOOST_CHECK_EQUAL("/b/c/%7Bfoo%7D", u.path); u.clear(); const char uri2[] = "http://host/../"; BOOST_CHECK(u.parse(uri2, strlen(uri2))); u.normalize(); BOOST_CHECK_EQUAL("/", u.path); BOOST_CHECK_EQUAL("host", u.host); u.clear(); static const char uri3[] = "http://host/./"; BOOST_CHECK(u.parse(uri3, strlen(uri3))); u.normalize(); BOOST_CHECK_EQUAL("/", u.path); BOOST_CHECK_EQUAL("host", u.host); } BOOST_AUTO_TEST_CASE(uri_parse_parts) { const char uri1[] = "http://example.com/path/to/something?query=string#frag"; uri u; BOOST_CHECK(u.parse(uri1, strlen(uri1))); BOOST_CHECK_EQUAL("http", u.scheme); BOOST_CHECK_EQUAL("example.com", u.host); BOOST_CHECK_EQUAL("/path/to/something", u.path); BOOST_CHECK_EQUAL("?query=string", u.query); BOOST_CHECK_EQUAL("#frag", u.fragment); const char uri2[] = "http://jason:password@example.com:5555/path/to/"; BOOST_CHECK(u.parse(uri2, strlen(uri2))); BOOST_CHECK_EQUAL("http", u.scheme); BOOST_CHECK_EQUAL("jason:password", u.userinfo); BOOST_CHECK_EQUAL("example.com", u.host); BOOST_CHECK_EQUAL("/path/to/", u.path); BOOST_CHECK_EQUAL(5555, u.port); const char uri3[] = "http://baduri;f[303fds"; const char *error_at = NULL; BOOST_CHECK(!u.parse(uri3, strlen(uri3), &error_at)); BOOST_CHECK(error_at != NULL); BOOST_CHECK_EQUAL("[303fds", error_at); const char uri4[] = "https://example.com:23999"; BOOST_CHECK(u.parse(uri4, strlen(uri4))); BOOST_CHECK_EQUAL("https", u.scheme); BOOST_CHECK_EQUAL("example.com", u.host); BOOST_CHECK_EQUAL(23999, u.port); BOOST_CHECK(u.path.empty()); BOOST_CHECK(u.query.empty()); BOOST_CHECK(u.fragment.empty()); const char uri5[] = "svn+ssh://jason:password@example.com:22/thing/and/stuff"; BOOST_CHECK(u.parse(uri5, strlen(uri5))); BOOST_CHECK_EQUAL("svn+ssh", u.scheme); BOOST_CHECK_EQUAL("jason:password", u.userinfo); BOOST_CHECK_EQUAL("example.com", u.host); BOOST_CHECK_EQUAL(22, u.port); BOOST_CHECK_EQUAL("/thing/and/stuff", u.path); BOOST_CHECK(u.query.empty()); BOOST_CHECK(u.fragment.empty()); }
#pragma once #include "GameNode.h" #include <vector> using namespace std; #define SPEED 3 #define GRAVITY 0.25f #define JUMP -12 enum STATUS { STATUS_WALK, STATUS_IDLE = 4, STATUS_JUMPUP, STATUS_JUMPDOWN }; struct tagMonsterInfo { float x, y; float speed; int monsterNumber; }; class MainGame19 : public GameNode { private: Image * bg; Image * arthur; Image * monster[3]; vector<tagMonsterInfo> monsterInfo; STATUS status; float moveFrame; float vy; // armor 0 unArmor 3 int vector; int loopX; int oldScore; int score; char str[128]; RECT box; RECT temp; bool isDebug; bool isNextLevel; bool isOver; bool isStart; DWORD prevTime; DWORD curTime; public: MainGame19(); ~MainGame19(); HRESULT Init() override; void Release() override; void Update() override; void Render(HDC hdc) override; void Jump(); void AddMonster(int number); };
/*-------------------------------------------------------------------------------------- dmd_latin_chars Demo and example Latin-1 encoding project for the Freetronics DMD, a 512 LED matrix display panel arranged in a 32 x 16 layout. See http://www.freetronics.com/dmd for resources and a getting started guide. This example code is in the public domain. It demonstrates using the ISO-8859-1 (Latin-1) extended character set. Thanks to Xavier Seignard for contributing Latin-1 support. ******************************* HOW TO ENTER Latin-1 CHARACTERS ******************************* Unfortunately entering Latin-1 characters like à or è is not as simple as just typing them. Arduino Sketches are saved in Unicode UTF-8 format, but the DMD library does not understand Unicode (it's too complex.) To enter the characters as Latin-1, look at the codepage layout here and look for the hexadecimal digit that corresponds to the character you want. https://en.wikipedia.org/wiki/ISO/IEC_8859-1#Codepage_layout For example, á (lowercase a, rising diacritical mark) has hex value 00E0 in Latin-1. To translate this into a constant string, replace the leading 00 with \x - so the string could be "The Portugese for rapid is r\xE0pido". To be safe, the string may also need to be separated in its own quote marks - ie "The Portugese for rapid is r""\xE0""pido" When you compile the sketch, the compiler will join all these strings up into one long string - however without the quotes around the \x it may try to include additional characters as part of the hexadecimal sequence. /*-------------------------------------------------------------------------------------- Includes --------------------------------------------------------------------------------------*/ #include <SPI.h> //SPI.h must be included as DMD is written by SPI (the IDE complains otherwise) #include <DMD.h> // #include <TimerOne.h> // #include "SystemFont5x7.h" #include "Arial_Black_16_ISO_8859_1.h" //Fire up the DMD library as dmd #define DISPLAYS_ACROSS 1 #define DISPLAYS_DOWN 1 DMD dmd(DISPLAYS_ACROSS, DISPLAYS_DOWN); /*-------------------------------------------------------------------------------------- Interrupt handler for Timer1 (TimerOne) driven DMD refresh scanning, this gets called at the period set in Timer1.initialize(); --------------------------------------------------------------------------------------*/ void ScanDMD() { dmd.scanDisplayBySPI(); } /*-------------------------------------------------------------------------------------- setup Called by the Arduino architecture before the main loop begins --------------------------------------------------------------------------------------*/ void setup(void) { //initialize TimerOne's interrupt/CPU usage used to scan and refresh the display Timer1.initialize( 3000 ); //period in microseconds to call ScanDMD. Anything longer than 5000 (5ms) and you can see flicker. Timer1.attachInterrupt( ScanDMD ); //attach the Timer1 interrupt to ScanDMD which goes to dmd.scanDisplayBySPI() //clear/init the DMD pixels held in RAM dmd.clearScreen( true ); //true is normal (all pixels off), false is negative (all pixels on) Serial.begin(115200); } /*-------------------------------------------------------------------------------------- loop Arduino architecture main loop --------------------------------------------------------------------------------------*/ void loop(void) { dmd.clearScreen( true ); dmd.selectFont(Arial_Black_16_ISO_8859_1); // Français, Österreich, Magyarország const char *MSG = "Fran""\xe7""ais, ""\xd6""sterreich, Magyarorsz""\xe1""g"; dmd.drawMarquee(MSG,strlen(MSG),(32*DISPLAYS_ACROSS)-1,0); long start=millis(); long timer=start; while(1){ if ((timer+30) < millis()) { dmd.stepMarquee(-1,0); timer=millis(); } } }
#include "behaviorwindow.h" #include "ui_behaviorwindow.h" #include "mainwindow.h" #include <ledlabel.h> #include "Dependencies/LightParameter.h" #include "Dependencies/NeoPixelCodeConverter.h" #include <QtAlgorithms> #include <QColorDialog> #include <vector> std::vector<LightParameter> *vectorOfStructs; NeoPixelCodeConverter convertColor; MainWindow *parentForBWin; BehaviorWindow::BehaviorWindow(std::vector<LightParameter> *vecOfStruct, QVector<LEDLabel*> orderedLEDs, QWidget *parent): QDialog(parent), ui(new Ui::BehaviorWindow) { ui->setupUi(this); parentForBWin = ((MainWindow*)(this->parentWidget())); bWindowID = -1; vectorOfStructs = vecOfStruct; this->setWindowTitle(QString("Group #%1").arg(vectorOfStructs->size())); this->listLEDs = orderedLEDs; QString list = "IDs: #"; QString sep = ", #"; for (int p = 0; p < listLEDs.size(); p++) { int id = listLEDs.at(p)->getID(); vectOfIDs.push_back(id); } qSort(vectOfIDs.begin(), vectOfIDs.begin()+(vectOfIDs.size())); for (int i = 0; i < vectOfIDs.size(); i++) { if(vectOfIDs.at(i) >= 0) list = QString(list + QString::number(vectOfIDs.at(i)) + sep); else list = QString(list + QString("NA") + sep); } list.chop(3); ui->listSelected->setText(list); SetUpUi(); } void BehaviorWindow::SetUpUi() { setColor(1, Qt::white); setColor(2, Qt::white); ui->color2Test->hide(); // ui->color1Button->setChecked(true); ui->color2Button->hide(); //enum ActivePattern { NO_PAT, RAINBOW_CYCLE, THEATER_CHASE, COLOR_WIPE, //SCANNER, FADE, BLINK, ON_AND_OFF, PULSATING, //LOADING, STEP}; ui->patternMenuBox->addItem("NONE"); ui->patternMenuBox->addItem("RAINBOW_CYCLE"); ui->patternMenuBox->addItem("THEATER_CHASE"); ui->patternMenuBox->addItem("COLOR_WIPE"); ui->patternMenuBox->addItem("SCANNER"); ui->patternMenuBox->addItem("FADE"); ui->patternMenuBox->addItem("BLINK"); ui->patternMenuBox->addItem("ON_AND_OFF"); ui->patternMenuBox->addItem("PULSATING"); ui->patternMenuBox->addItem("LOADING"); ui->patternMenuBox->addItem("STEP"); ui->directionMenuBox->addItem("FORWARD"); ui->directionMenuBox->addItem("REVERSE"); // Set Pattern defaults // selectedParameters = LightParameter(NONE, FORWARD, ); EnableInput(true, ui->startTimeInput); EnableInput(true, ui->cyclesInput); EnableInput(true, ui->intervalInput); EnableInput(true, ui->cyclesInput); EnableInput(false, ui->onTimeInput); EnableInput(false, ui->offTimeInput); ui->startTimeInput->setValidator(new QIntValidator(0, 10000000, this)); ui->cyclesInput->setValidator(new QIntValidator(0, 10000000, this)); ui->intervalInput->setValidator(new QIntValidator(0, 10000000, this)); ui->onTimeInput->setValidator(new QIntValidator(0, 10000000, this)); ui->offTimeInput->setValidator(new QIntValidator(0, 10000000, this)); } BehaviorWindow::~BehaviorWindow() { qDebug() << "Destroying BWindow"; delete ui; for (int i = 0; i < listLEDs.size(); i++) { listLEDs.at(i)->setLEDColor(QColor(255, 255, 255), listLEDs.at(i)->getID()); } listLEDs.clear(); vectOfIDs.clear(); qDebug() << "listLEDs= " << listLEDs; qDebug() << "vectOfIDs= " << vectOfIDs; } void BehaviorWindow::setColor(int whichLED, QColor desiredColor) { if (whichLED == 1) { ui->color1Test->setLEDColor(desiredColor, 1); color1 = desiredColor; } if (whichLED == 2) { ui->color2Test->setLEDColor(desiredColor, 2); color2 = desiredColor; } // ui->showRGB->setText(QString("RGB = (%1, %2, %3)").arg(desiredColor.red()) //.arg(desiredColor.green()) //.arg(desiredColor.blue())); } void BehaviorWindow::on_setButton_clicked() { if (UpdateVect()) //returns true and updates vector if valid pattern { for (int i = 0; i < listLEDs.size(); i++) { listLEDs.at(i)->setLEDColor(color1, listLEDs.at(i)->getID()); } parentForBWin->clearSelectedLEDs(); parentForBWin->updateDisplay(); close(); } } void BehaviorWindow::on_cancelButton_clicked() { //return the color chosen by user close(); //ui->color2Button->show(); } bool BehaviorWindow::UpdateVect() { qDebug() << "WindowId = " << bWindowID; int arrayIDs[listLEDs.size()]; int arrayLength = listLEDs.size(); for (int i = 0; i < arrayLength; i++) { arrayIDs[i] = vectOfIDs.at(i); qDebug() << QString("group at %1: ").arg(i) << arrayIDs[i]; } qDebug() << "grouplength: " << arrayLength; int currentPatInt = ui->patternMenuBox->currentIndex(); ActivePattern pat = (ActivePattern)(currentPatInt); qDebug() << "Pattern: " << pat; Direction dir = (Direction)(ui->directionMenuBox->currentIndex()); qDebug() << "Direction: " << dir; unsigned long startTime = (ui->startTimeInput->text()).toLong(); qDebug() << "Start Time: " << startTime; unsigned long interval = (ui->intervalInput->text()).toLong(); qDebug() << "Interval: " << interval; unsigned long cyc; if (!(ui->cyclesInput->isReadOnly())) { cyc = (ui->cyclesInput->text()).toLong(); } else cyc = 0; qDebug() << "Cycles: " << cyc; uint32_t c1; uint32_t c2; if (ui->color1Test->isVisible()) c1 = convertColor.Color(color1.red(),color1.green(), color1.blue(),0); else c1 = 0; if (ui->color2Test->isVisible()) c2 = convertColor.Color(color2.red(),color2.green(),color2.blue(),0); else c2 = 0; qDebug() << "Color1: " << c1; qDebug() << "Color2: " << c2; unsigned long onTime; unsigned long offTime; if (ui->onTimeInput->isReadOnly()) { onTime = 0; } else{ onTime = (ui->onTimeInput->text()).toLong(); qDebug() << "Ontime: " << onTime; } if (ui->offTimeInput->isReadOnly()) { offTime = 0; } else{ offTime = (ui->offTimeInput->text()).toLong(); qDebug() << "Offtime: " << offTime; } int index = 0; int brightness = 255; qDebug() << "index: " << index; qDebug() << "brightness: " << brightness; if(!PatternAllowed(bWindowID, LightParameter(pat , dir, startTime, cyc, index, onTime, offTime, brightness, c1, c2, interval, arrayIDs, arrayLength))) { return false; } if (bWindowID == -1){ qDebug() << "About to Push Back vectorOfStructs"; vectorOfStructs->push_back(LightParameter(pat , dir, startTime, cyc, index, onTime, offTime, brightness, c1, c2, interval, arrayIDs, arrayLength)); // parentForBWin-> qDebug() << "Finished Pushing Back vectorOfStructs"; qDebug() << "about to parentForBWin->pushVecOfBWindows"; parentForBWin->pushVecOfBWindows(this); qDebug() << "finished parentForBWin->pushVecOfBWindows"; bWindowID = vectorOfStructs->size()-1; qDebug() << " finished bWindowID = vectorOfStructs->size()-1;"; } else if (bWindowID >= 0){ vectorOfStructs->at(bWindowID).pattern = pat; vectorOfStructs->at(bWindowID).direction = dir; vectorOfStructs->at(bWindowID).startTime = startTime; vectorOfStructs->at(bWindowID).cycles = cyc; vectorOfStructs->at(bWindowID).index = index; vectorOfStructs->at(bWindowID).onTime = onTime; vectorOfStructs->at(bWindowID).offTime = offTime; vectorOfStructs->at(bWindowID).brightness = brightness; vectorOfStructs->at(bWindowID).Color1 = c1; vectorOfStructs->at(bWindowID).Color2 = c2; vectorOfStructs->at(bWindowID).interval = interval; //vectorOfStructs->at(bWindowID).group = arrayIDs; //ectorOfStructs->at(bWindowID).grouplength = arrayLength; } return true; } void BehaviorWindow::on_patternMenuBox_activated(int index) { // 0: NONE, 1: RAINBOW_CYCLE,2: THEATER_CHASE,3: COLOR_WIPE,4: SCANNER, // 5: FADE,6: BLINK,7: ON_AND_OFF,8: PULSATING,9: LOADING,10: STEP if (index == 1) { ui->color2Button->hide(); ui->color2Test->hide(); ui->color1Button->hide(); color1 = QColor(255,220,220); ui->color1Test->hide(); EnableInput(false, ui->onTimeInput); EnableInput(false, ui->offTimeInput); EnableInput(true, ui->cyclesInput); // EnableSliders(false); } else if (index == 2 || index == 5) { ui->color2Button->show(); ui->color2Test->show(); ui->color1Button->show(); ui->color1Test->show(); EnableInput(false, ui->onTimeInput); EnableInput(false, ui->offTimeInput); EnableInput(true, ui->cyclesInput); } else if (index == 3) { ui->color2Button->hide(); ui->color2Test->hide(); ui->color1Button->show(); ui->color1Test->show(); EnableInput(false, ui->onTimeInput); EnableInput(false, ui->offTimeInput); EnableInput(false, ui->cyclesInput); } else if (index == 7) { ui->color2Button->hide(); ui->color2Test->hide(); ui->color1Button->show(); ui->color1Test->show(); EnableInput(true, ui->onTimeInput); EnableInput(true, ui->offTimeInput); EnableInput(true, ui->cyclesInput); } else { ui->color2Button->hide(); ui->color2Test->hide(); ui->color1Button->show(); ui->color1Test->show(); EnableInput(false, ui->onTimeInput); EnableInput(false, ui->offTimeInput); EnableInput(true, ui->cyclesInput); } } void BehaviorWindow::EnableInput(bool enabled, QLineEdit *thisone) { if (enabled) { thisone->setReadOnly(false); thisone->setText("0"); } else { thisone->setText("Disabled"); thisone->setReadOnly(true); } } void BehaviorWindow::on_color1Button_clicked() { QColorDialog dialog; QColor currentColor = ui->color1Test->getLEDColor(); //return the color chosen by user QColor chosenColor = dialog.getColor(currentColor, this, "Choose Color!!"); setColor(1, chosenColor); } void BehaviorWindow::on_color2Button_clicked() { QColorDialog dialog; QColor currentColor = ui->color2Test->getLEDColor(); //return the color chosen by user QColor chosenColor = dialog.getColor(currentColor, this, "Choose Color!!"); setColor(2, chosenColor); } void BehaviorWindow::on_calcStopTimeLabel_clicked() { ActivePattern pat = ActivePattern(ui->patternMenuBox->currentIndex()); unsigned long start = ui->startTimeInput->text().toLong(); unsigned long cycle = ui->cyclesInput->text().toLong(); unsigned long interval = ui->intervalInput->text().toLong(); unsigned long on = ui->onTimeInput->text().toLong(); unsigned long off = ui->offTimeInput->text().toLong(); int length = listLEDs.size(); uint32_t c1 = convertColor.Color(color1.red(),color1.green(), color1.blue(),0); double stop = (parentForBWin->getStopTime(pat, start, cycle, interval, on, off, length, c1))/1000.0; ui->stopTimeLabel->setText(QString("Stop Time = %1 Seconds").arg(stop)); } //Checks for Overlap errors bool BehaviorWindow::PatternAllowed(int currentID, LightParameter strucToAdd) { //First assume that the pattern is allowed bool patternAllowed = true; for (int patToTest = 0; patToTest < vectorOfStructs->size(); patToTest++) { //dont check for overlap if it is window being edited if (patToTest == currentID) break; bool oneLEDInCommon = false; for (int i = 0; i < strucToAdd.grouplength; i++) { for (int p = 0; p < vectorOfStructs->at(patToTest).grouplength; p++) { if(strucToAdd.group[i] == vectorOfStructs->at(patToTest).group[p]) { oneLEDInCommon = true; break; } } if (oneLEDInCommon) break; } if(oneLEDInCommon) { //at least one LED in Common, now check overlapping ranges of time if((strucToAdd.startTime <= parentForBWin->getStopTime(vectorOfStructs->at(patToTest))) && (vectorOfStructs->at(patToTest).startTime <= parentForBWin->getStopTime(strucToAdd))) { patternAllowed = false; QMessageBox::warning(this, "Warning", "LEDs in common with an existing group, and there is a time overlap. Group not allowed!!"); break; } } } return patternAllowed; }
#include <iostream> #include <cstdlib> #include <time.h> #include "DIET_client.h" const char *configuration_file = "/root/dietg/cfgs/client.cfg"; const float MIN_DURATION = 20.0; const float MAX_DURATION = 60.0; const float MIN_NUMPROCESSES = 1; const float MAX_NUMPROCESSES = 4; const double SIZE_MATRIX = 1e10; //at least 09 int main(int argc, char **argv) { srandom(time(NULL)); //double duration = random() * ((MAX_DURATION - MIN_DURATION) / RAND_MAX) + MIN_DURATION; double size_matrix = SIZE_MATRIX; double size_hostname; char * hostname[64]; int num_processes = int(random() * ((MAX_NUMPROCESSES - MIN_NUMPROCESSES) / RAND_MAX) + MIN_NUMPROCESSES); double *result = NULL; diet_profile_t *profile; time_t start,stop; double elapsed_secs_time; /* Matrix multiplication */ time(&start); diet_initialize(configuration_file, argc, argv); profile=diet_profile_alloc("matmut",0,0,1); diet_scalar_set(diet_parameter(profile, 0), &size_matrix, DIET_VOLATILE, DIET_DOUBLE); diet_string_set(diet_parameter(profile, 1), NULL, DIET_VOLATILE); if (!diet_call(profile)) { std::cout << "diet call success" << std::endl; diet_string_get(diet_parameter(profile,1), &hostname, NULL); time(&stop); elapsed_secs_time = difftime(stop,start); std::cout << *hostname << " : Time for client (regular) = " << elapsed_secs_time << std::endl; } else { std::cout << "diet call error" << std::endl; } diet_profile_free(profile); diet_finalize(); }
#include <cstdlib> #include <ctime> #include <algorithm> #include <list> #include <iterator> #include <iostream> #include "Population.h" using namespace std; namespace HWA2{ Population::Population(int popSizeIn){ std::srand(std::time(0)); popSize = popSizeIn; pop = new std::vector<Gene>; readDataset(); std::cout << "dataset read" << std::endl; generatePopulation(); std::cout << "population created" << std::endl; } void Population::readDataset(){ dataset = new std::vector<std::vector<int> >; int ds[31][13] = { {0, 0, 0 ,0 ,1, 0, 0, 1, 1, 0, 0, 0, 1}, //1864 {1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1}, //1868 {1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1}, //1872 {1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1}, //1880 {0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1}, //1888 {0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1}, //1900 {1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1}, //1904 {1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1}, //1908 {0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1}, //1916 {0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1}, //1924 {1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1}, //1928 {0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1}, //1936 {1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1}, //1940 {1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1}, //1944 {1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1}, //1948 {0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1}, //1956 {0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1}, //1964 {0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1}, //1972 {1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0}, //1860 {1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0}, //1876 {1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0}, //1884 {0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0}, //1892 {0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0}, //1896 {1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0}, //1912 {1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0}, //1920 {1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0}, //1932 {1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0}, //1952 {1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0}, //1960 {1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0}, //1968 {1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0}, //1976 {0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0}}; //1980 for (int i = 0; i < 31; i++){ std::vector<int> temp; for (int j = 0; j < 13; j++){ temp.push_back(ds[i][j]); } dataset->push_back(temp); } } void Population::generatePopulation(){ for (int i = 0; i < popSize; i++){ std::vector<int> gene; for (std::size_t j = 0; j < dataset->operator[](0).size()-1; j++){ gene.push_back(std::rand()%2); } pop->insert(pop->end(), Gene(gene)); } _bestGene = &pop->operator[](0); } //------------------------------------------------------------------------------------------------------------------------ double Population::calculateFitness(){ double totalFitness = 0; for (std::size_t i = 0; i < pop->size(); i++){ // for each gene in the population Gene& temp = pop->operator[](i); double fitness = differentialScore(temp)*(1-((double)temp.cardinality()/temp.size()))*correctness(temp); temp.fitness(fitness); if (temp.fitness() > _bestGene->fitness()){ _bestGene = &temp; } totalFitness += fitness; } return totalFitness/pop->size(); } void Population::reproduce(int noOfCrosspoints, int mutationMethod){ std::vector<Gene> pool; for (std::size_t i = 0; i < pop->size(); i++){ // for each gene in the population //cout << pop->at(i).fitness() << endl; for (int j = 0; j < pop->operator[](i).fitness()*100; j++){ // pool.push_back(pop->operator[](i)); } } // cout << pool.size() << endl; std::vector<Gene> newPop; for (std::size_t i = 0; i < pop->size(); i++){ Gene parent1 = pool.operator[](std::rand()%pool.size()); Gene parent2 = pool.operator[](std::rand()%pool.size()); std::vector<int> child = nPointCrossover(parent1, parent2, noOfCrosspoints); mutate(child, mutationMethod); newPop.push_back(Gene(child)); } // cout << "crossovers complete" << endl; //history->push_back(pop); *pop = newPop; } void Population::mutate(std::vector<int>& child, int mutationMethod){ if(std::rand()%10 == 1){ int index = std::rand()%sizeof(child); child[index] = (child[index]+1)%2; } } //------------------------------------------------------------------------------------------------------------------------ double Population::differentialScore(const Gene& gene) const{ // cout << "differentialScore entered" << endl; std::vector<std::vector<int> >* sets = new std::vector<std::vector<int> >; // cout << "cardinality: " << gene.cardinality() << ":" << gene.activeIndexs().size()<< endl; // cout << "dataset size: " << dataset->size() << endl; for (size_t i = 0; i < dataset->size(); i++){ // loop through the dataset // GETTING STUCK HERE ON SECOND ROUND // cout << "dataset position: "; // cout << i << endl; std::vector<int> seti(gene.activeIndexs().size()); // new temp vector to hold this set for (int k = 0; k < gene.activeIndexs().size(); k++){ // decode the active set // cout << gene.activeIndexs()[k] << " "; seti[k] = dataset->operator[](i)[gene.activeIndexs()[k]]; } if (std::find(sets->begin(), sets->end(), seti) == sets->end()){ // if the set is new // cout << "\na " << sets->size() << endl; sets->push_back(seti); // add it to the list of sets // cout << "b " << sets->size() << endl; } // cout << "i " << i << endl; } // cout << "leaving differentialScore" << endl; return (double)sets->size()/gene.size(); } double Population::correctness(const Gene& gene) const{ // cout << "correctness entered" << endl; std::list<std::vector<int> >* sets = new std::list<std::vector<int> >; std::list<std::vector<int> >* classSets = new std::list<std::vector<int> >; for (std::size_t j = 0; j < dataset->size(); j++){ // loop through the dataset std::vector<int> seti(gene.cardinality()+1); // new temp vector to hold this set for (int k = 0; k < gene.cardinality(); k++){ // decode the active set seti[k] = dataset->operator[](j)[gene.activeIndexs()[k]]; } seti[gene.cardinality()] = 2; if (std::find(sets->begin(), sets->end(), seti) == sets->end()){ // if the set is new sets->push_front(seti); // add it to the list of sets } seti[gene.cardinality()] = dataset->operator[](j)[gene.size()]; if (std::find(classSets->begin(), classSets->end(), seti) == classSets->end()){ // if the set is new classSets->push_front(seti); // addbestGene it to the list of sets } } // cout << sets->size() << ":" << classSets->size() << ":" << gene.cardinality() << endl; if (sets->size() == classSets->size()) return 1; return 0.5; } //------------------------------------------------------------------------------------------------------------------------ std::vector<int> Population::nPointCrossover(const Gene& parent1, const Gene& parent2, int noOfCrosspoints){ std::vector<int> childGene; std::vector<int> crossPoints; const Gene* activeParent = &parent1; for (std::size_t i = 0; crossPoints.size() < noOfCrosspoints; i++){ // creating the crossover points int crosspoint = std::rand()%parent1.size(); if (std::find(crossPoints.begin(), crossPoints.end(), crosspoint) == crossPoints.end()){ crossPoints.push_back(crosspoint); // cout << crosspoint << endl; } } // cout << "crossover points found" << endl; for (std::size_t i = 0; i < parent1.size(); i++){ childGene.push_back(activeParent->gene()[i]); if (std::find(crossPoints.begin(), crossPoints.end(), i) != crossPoints.end()){ if (activeParent == &parent1){ activeParent = &parent2; } else{ activeParent = &parent1; } } } // cout << "crossover complete" << endl; return childGene; } Gene Population::bestGene() const{ return *_bestGene; } }
#pragma once #include <fstream> #include <tuple> #include <memory> #include <yaml-cpp/yaml.h> #include "Types/Configurable.hpp" class YAMLStream { public: enum Type{ in, out }; YAMLStream(); YAMLStream(std::string_view filepath, Type flag); void open(std::string_view filePath, Type flag); void close(); bool isOpen(); YAMLStream& operator<<(const std::pair<std::string, std::unique_ptr<Configurable>>& node); YAML::Node operator[](std::string_view name); private: bool m_IsOpen; YAML::Node m_Node; std::unique_ptr<YAML::Emitter> m_Emitter; std::ofstream m_OutFile; };
#include "util/Vec3f.h" class Entity { private: Vec3f _pos; int list; Vec3f target; bool targetReached; public: Entity(); Entity(Vec3f pos); void tick(); void draw(); void setTarget(Vec3f t); bool reachedTarget(); };
// { Driver Code Starts #include <bits/stdc++.h> using namespace std; char getMaxOccuringChar(char *); int main() { char str[] = "ashsssuu"; char a=getMaxOccuringChar(str); cout << a << endl; } // } Driver Code Ends char getMaxOccuringChar(char *str) { int count[256]; memset(count, 0, sizeof(count)); while (*str != '\0') { count[*str]++; str++; } for (int i = 0; i < 256; i++) if (count[i] > 0) cout << count[i]<<" "<<i<<endl; int maxInd = 0; int freq = 0; int i; for (i = 0; i < 256; i++) { if (count[i] > freq) { freq = count[i]; maxInd = i; } } cout<<"maxInd: "<<maxInd<<endl; char a= maxInd; return a; }
#include <iostream> #include <iomanip> #include <string> #include <vector> #include <math.h> using namespace std; int task4() { float meters; cout << "Enter meters: \n"; cin >> meters; float kilometers = meters / 1000; cout << "Kilometers: " << setprecision(5) << kilometers << '\n'; return 0; }
#include<vector> #include<iostream> #include<algorithm> #include<deque> using namespace std; bool compare(vector<int>& a,vector<int>& b) { return a[0]+a[1]<b[0]+b[1]; } class Solution { public: vector<vector<int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) { //基本思想:大顶堆,问题转化为215数组中的前K个最小元素,时间复杂度O(m*n*logk) //构造大顶堆,将前K个最小元素保存至大顶堆中,只要有比堆顶元素小的就入堆 vector<vector<int>> res; k=nums1.size()*nums2.size()<k?nums1.size()*nums2.size():k; vector<vector<int>> max_heap; for(int i=0;i<nums1.size();i++) { for(int j=0;j<nums2.size();j++) { if(max_heap.size()<k||max_heap[0][0]+max_heap[0][1]>nums1[i]+nums2[j]) { max_heap.push_back({nums1[i],nums2[j]}); push_heap(max_heap.begin(), max_heap.end(),compare); } if(max_heap.size()>k) { pop_heap(max_heap.begin(), max_heap.end(),compare); max_heap.pop_back(); } } } while(!max_heap.empty()) { pop_heap(max_heap.begin(), max_heap.end(),compare); res.push_back(max_heap.back()); max_heap.pop_back(); } reverse(res.begin(),res.end()); return res; } }; class Solution { public: struct Node{ int i,j; int u,v; Node(){} Node(int i,int j,int u,int v):i(i),j(j),u(u),v(v){} bool operator>(const Node& a)const {return this->u+this->v>a.u+a.v;} }; vector<vector<int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) { vector<vector<int>> res; if(nums1.size()==0||nums2.size()==0) return res; k=nums1.size()*nums2.size()<k?nums1.size()*nums2.size():k; Node tmp; priority_queue<Node,vector<Node>,greater<Node>> min_heap; for(int i=0;i<nums1.size();i++) min_heap.push(Node(i,0,nums1[i],nums2[0])); while(k--) { tmp=min_heap.top(); min_heap.pop(); res.push_back(vector<int>{tmp.u,tmp.v}); if(tmp.j+1!=nums2.size()) { tmp.j++; tmp.v=nums2[tmp.j]; min_heap.push(tmp); } } return res; } }; class Solution1 { public: vector<vector<int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) { //基本思想:小顶堆,问题转化为23合并K个有序数组,时间复杂度O(k*logn) //构造小顶堆,将前K个最小元素保存至小顶堆中,pair<int,int>中first是nums1中的元素,second是nums2中的下标 //把每个数组的第一个元素加入小顶堆,弹出小顶堆的堆顶元素 //弹出的元素来自哪个数组,就把那个数组的下一个元素加入小顶堆 //直到所有数组都没有下一个元素,我们只需要弹出K次,即可获取前K小的元素 vector<vector<int>> res; if(nums1.size()==0||nums2.size()==0) return res; k=nums1.size()*nums2.size()<k?nums1.size()*nums2.size():k; vector<pair<int,int>> min_heap; for(int i=0;i<nums1.size();i++) { min_heap.push_back(pair<int,int>{nums1[i],0}); push_heap(min_heap.begin(), min_heap.end(),[nums2](pair<int,int>& a,pair<int,int>& b){return a.first+nums2[a.second]>b.first+nums2[b.second];}); } while(k--) { res.push_back(vector<int>{min_heap[0].first,nums2[min_heap[0].second]}); min_heap[0].second++; pair<int,int> temp=min_heap[0]; pop_heap(min_heap.begin(), min_heap.end(),[nums2](pair<int,int>& a,pair<int,int>& b){return a.first+nums2[a.second]>b.first+nums2[b.second];}); min_heap.pop_back(); if(temp.second!=nums2.size()) { min_heap.push_back(temp); push_heap(min_heap.begin(), min_heap.end(),[nums2](pair<int,int>& a,pair<int,int>& b){return a.first+nums2[a.second]>b.first+nums2[b.second];}); } } return res; } }; int main() { Solution1 solute; vector<int> nums1{1,7,8}; vector<int> nums2{2,4,6}; int k=4; vector<vector<int>> res=solute.kSmallestPairs(nums1,nums2,k); for_each(res.begin(),res.end(),[](vector<int> v){cout<<v[0]<<" "<<v[1]<<endl;}); return 0; }
#include<iostream> using namespace std; int sum(int k) {int t=0; while (k) {t=t+k%10; k/=10; } return (t > 9)?sum(t):t; } int main() {int n,k,now; while (1) {cin >> n; if (!n) break; now = k = sum(n); for (int i = 1;i < n; i++) now = sum(now*k); cout << now << endl; } return 0; }
#ifndef _RABBITS_HPP_ #define _RABBITS_HPP_ class Rabbits { public: Rabbits( ); Rabbits( bool mature, bool sex, int monthsPassed = 0 ); ~Rabbits( ); bool get_mature( ) const; void set_mature( bool mature ); bool get_sex( ) const; void set_sex( bool sex ); int get_monthsPassed( ) const; void set_monthsPassed( int monthsPassed ); unsigned long reproduce( Rabbits* partner ); protected: private: bool _mature; // sexual maturity bool _sex; // true == female int _monthsPassed; // Number of months since last reproduction unsigned long int _adn; }; #endif // _RABBITS_HPP_
// // Created by manout on 17-3-20. // #include "common_use.h" #include "BiNode.h" /* * Given preorder and inorder traversal of a tree, construct the binary tree * 从先序遍历序列和中序遍历序列中还原二叉树的结构 * 分析: * 利用二叉树的递归性质和中序先序的关系还原二叉树 */ BiNode* build_tree(const vector<int>& pre_order,const vector<int>& in_order) { return build(begin(pre_order), end(pre_order), begin(in_order), end(in_order)); } template <typename It> BiNode* build(It pre_first, It pre_last, It in_first, It in_last) { if(pre_first == pre_last or in_first == in_last) { return nullptr; } BiNode* root = new BiNode(pre_first -> val); auto rootpos = find(in_first, in_last, *pre_first); auto left_size = distance(in_first, rootpos); root->left = build(next(pre_first), next(pre_first, left_size + 1), in_first, rootpos); root->right = build(next(pre_first, left_size + 1), pre_last, next(rootpos), in_last); return root; }
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- // // Copyright (C) 1995-2007 Opera Software AS. All rights reserved. // // This file is part of the Opera web browser. It may not be distributed // under any circumstances. // // Arjan van Leeuwen (arjanl) #ifndef MBOXSTORE_H #define MBOXSTORE_H #include "adjunct/m2/src/include/defs.h" class StoreMessage; class OpFile; /** @brief Abstract class for 'raw' mail storage * @author Arjan van Leeuwen * * The store is able to handle different formats for 'raw' mail storage. * Every raw mail storage format should be implemented by inheriting from this class. * If you create your own mail storage class, remember to make an entry for it in * AccountTypes::MboxType. */ class MboxStore { public: enum StoreFeatures { UPDATE_FULL_MESSAGES = 1 << 0 ///< it's possible to update one existing message in this store using UpdateMessage() }; virtual ~MboxStore() {} /** Initializes this message store. No other functions are called before this is called. * @param store_path explisitly defines the mail root directory, if empty default to MAIL_ROOT_DIR */ virtual OP_STATUS Init(const OpStringC& store_path) = 0; /** Gets type of store * @return Type of store */ virtual AccountTypes::MboxType GetType() = 0; /** Gets features supported by this store * @return Bitwise OR of StoreFeatures values */ virtual int GetFeatures() = 0; /** Add a new message to the store * @param message Message to add * @param mbx_data Should be set to new mbx_data if save was successful * @return OpStatus::OK if save was successful, error codes otherwise */ virtual OP_STATUS AddMessage(StoreMessage& message, INT64& mbx_data) = 0; /** Fully update an existing message in the store (overwrites existing message) * @param message Message to update * @param mbx_data Existing mbx_data from the store if there was any, 0 otherwise. Might be changed by this function to have new mbx_data. * @return OpStatus::OK if save was successful, OpStatus::ERR_NOT_SUPPORTED if not supported for this store, error codes otherwise */ virtual OP_STATUS UpdateMessage(StoreMessage& message, INT64& mbx_data) { return OpStatus::ERR_NOT_SUPPORTED; } /** Update the status of an existing message in the store * @param message Message to update * @param mbx_data Existing mbx_data from the store if there was any, 0 otherwise. Might be changed by this function to have new mbx_data. * @return OpStatus::OK if save was successful, error codes otherwise */ virtual OP_STATUS UpdateMessageStatus(StoreMessage& message, INT64& mbx_data) = 0; /** Get a message from the store * @param mbx_data mbx_data that was saved with the message * @param message Where to place the message if found, prefilled with ID, account ID and sent date * @param override Whether to override data already found in message with data from raw file * @return OpStatus::OK if message was found and retrieved, OpStatus::ERR_FILE_NOT_FOUND if not found, error codes otherwise */ virtual OP_STATUS GetMessage(INT64 mbx_data, StoreMessage& message, BOOL override = FALSE) = 0; /** Get a draft from the store, only implemented by MboxPerMail * @param message Where to place the message if found * @param id Message id to retrieve * @return OpStatus::OK if message was found and retrieved, OpStatus::ERR_FILE_NOT_FOUND if not found, error codes otherwise */ virtual OP_STATUS GetDraftMessage(StoreMessage& message, message_gid_t id) { return OpStatus::ERR; } /** Whether a message is cached in this store * @param id Message to check for * @return Whether the message is cached, or TRUE if the store doesn't have a cache */ virtual BOOL IsCached(message_gid_t id) = 0; /** Remove a message from the store * @param mbx_data mbx_data that was saved with the message * @param id Message to remove * @param account_id Account of this message * @param sent_date Time when message was sent * @param draft Whether this was a draft * @return OpStatus::OK if delete was successful or if message didn't exist, error codes otherwise */ virtual OP_STATUS RemoveMessage(INT64 mbx_data, message_gid_t id, UINT16 account_id, time_t sent_date, BOOL draft = FALSE) = 0; /** Commit pending data to the store (if necessary) */ virtual OP_STATUS CommitData() = 0; /** Reads an mbox-format message starting at the current position of the file * @param message Where to save message * @param file Where to read message from * @param override Whether to override data already found in message with data from raw file * @param import ignore message id and account id */ static OP_STATUS ReadMboxMessage(StoreMessage& message, OpFile& file, BOOL override, BOOL import = FALSE); protected: /** Writes out a message to a specified file, not including mbox-format 'From ' line * @param message Message to write out * @param file Where to write */ static OP_STATUS WriteRawMessage(StoreMessage& message, OpFile& file); /** Reads a message starting at the current position of the file, not including mbox-format 'From ' line * @param message Where to save message * @param file Where to read message from * @param override Whether to override data already found in message with data from raw file * @param import ignore mesasge id and account id */ static OP_STATUS ReadRawMessage(StoreMessage& message, OpFile& file, BOOL override, BOOL import = FALSE); /** Writes out an mbox-format message to a specified file * @param message Message to write out * @param file Where to write */ static OP_STATUS WriteMboxMessage(StoreMessage& message, OpFile& file); /** Reads a 'From ' line from an mbox-format file, gets time received * @param file Where to read line from */ static OP_STATUS ReadFromLine(OpFile& file); /** Creates a 'From ' line for an mbox-format file * @param message Message for which to create line * @param file Output */ static OP_STATUS WriteFromLine(StoreMessage& message, OpFile& file); /** Reads an 'X-Opera-Status: ' header from a file (Opera-specific header) * @param message Where to save data found in status line (if overwrite) * @param has_internet_location Whether the message as an internet location header * @param mbox_raw_len Length of message in bytes (after Opera-specific headers) * @param file Where to read line from * @param overwrite_ids Whether to overwrite the message id, parent id and account id found in the status line * @param overwrite_flags Whether to overwrite the flags found in the status line (useful when importing) */ static OP_STATUS ReadStatusLine(StoreMessage& message, BOOL& has_internet_location, UINT32& mbox_raw_len, OpFile& file, BOOL overwrite_ids = FALSE, BOOL ovewrite_flags = FALSE); /** Creates an 'X-Opera-Status: ' header line (Opera-specific header) * @param message Message for which to create header * @param recv_time Time when message was received * @param file Output */ static OP_STATUS WriteStatusLine(StoreMessage& message, OpFile& file); /** Reads an 'X-Opera-Location: ' header from a file (Opera-specific header) * @param internet_location Found location * @param file Where to read line from */ static OP_STATUS ReadInternetLocation(OpString8& internet_location, OpFile& file); /** Writes an 'X-Opera-Location: ' header to a file (Opera-specific header) * @param internet_location Location to save * @param file Output */ static OP_STATUS WriteInternetLocation(const OpStringC8& internet_location, OpFile& file); }; #endif // MBOXSTORE_H
int sz[MAX]; bool erased[MAX]; vi grafo[MAX]; void dfs(int u, int p=-1){ sz[u] = 1; for(int v: grafo[u]) if(v!=p and !erased[v]){ dfs(v, u); sz[u] += sz[v]; } } int centroid(int u, int p=-1, int size=-1){ if(size==-1) size = sz[u]; for(int v: grafo[u]) if(v!=p and !erased[v] and sz[v]>size/2) return centroid(v, u, size); return u; } pii centroids(int u=1){ // idx 1 dfs(u); int c1=centroid(u), c2=c1; for(int v: grafo[c1]) if(2*sz[v]==sz[u]) c2=v; return {c1, c2}; }
//Andrea Peņa Calvin #include "jugador.h" tTecla leerTecla() { tTecla sol = TERROR; int dir; std::cin.sync(); dir = _getch(); // dir: tipo int if (dir == 13) sol = TSALIR; else if (dir == 32) sol = TLASER; else if (dir == 0xe0) { dir = _getch(); switch (dir) { case 72: sol = TAVANZA; break; case 75: sol = TIZQUIERDA; break; case 77: sol = TDERECHA; break; default: sol = TERROR; } } return sol; } void mostrarJuego(const tJuego & mijuego) { //tablero mostrarTablero(mijuego.tablero); std::cout << '\n'; //jugadores for (int i = 0; i < mijuego.numjugadores; i++) { colorFondo(PALETA[i + 5]); if (mijuego.turno == i) std::cout << "> "; std::cout << i + 1 << " " << mijuego.arrayjug[i].nombre << ":"; colorFondo(0); std::cout << " " << mijuego.arrayjug[i].manojug[0]; colorFondo(PALETA[9]); std::cout << "^"; colorFondo(0); std::cout << " " << mijuego.arrayjug[i].manojug[1]; colorFondo(PALETA[9]); std::cout << "<"; colorFondo(0); std::cout << " " << mijuego.arrayjug[i].manojug[2]; colorFondo(PALETA[9]); std::cout << ">"; colorFondo(0); std::cout << " " << mijuego.arrayjug[i].manojug[3]; colorFondo(PALETA[9]); std::cout << "-" << '\n'; colorFondo(0); } } bool realizarMovimiento(tTablero & tablero, tCoordenada & coor, const tArrayCartas & vCartas, const int & tamano) { bool encontrarjoya = false; tDir direccion = tablero[coor.x][coor.y].tort.dir; for (int k = 0; k < tamano && !encontrarjoya; k++) { if (*(vCartas[k]) == AVANZAR) { if (movPosible(tablero, coor, direccion)) { if (tablero[coor.x + incF[direccion]][coor.y + incC[direccion]].estado == JOYA) encontrarjoya = true; avanzar(tablero, direccion, coor); } } else if (*(vCartas[k]) == GIRODERECHA) { ++direccion; } else if (*(vCartas[k]) == GIROIZQUIERDA) { --direccion; } else if (*(vCartas[k]) == LASER) { laser(tablero, coor, direccion); } } tablero[coor.x][coor.y].tort.dir = direccion; return encontrarjoya; } bool ejecutarturnos(tJuego & mijuego) { bool ok = false;//verdadero si encuentra la joya char op; std::cout << "Elija una opcion: robar (R) o crear una secuencia (E)." << '\n'; std::cin >> op; while (op != 'R' && op != 'E') { std::cout << "Opcion no valida, introduzca una correcta: " << '\n'; std::cin >> op; } if (op == 'R') { bool a; tCarta carta; a = cogerCarta(mijuego.arrayjug[mijuego.turno].mazojug, carta); if (a) { ++mijuego.arrayjug[mijuego.turno].manojug[carta]; } } else if (op == 'E') { std::cout << "Introduce la secuencia: "; tArrayCartas vectorcartas, cartasadevolver; for (int i = 0; i < NUMEROCARTAS; i++) { vectorcartas[i] = new tCarta; cartasadevolver[i] = new tCarta; } tTecla key = leerTecla(); int x = 0; while (key != TSALIR) { if (key != TERROR) { if (mijuego.arrayjug[mijuego.turno].manojug[key] > 0) { *(vectorcartas[x])=tCarta(key); *(cartasadevolver[x]) = tCarta(key); x++; mijuego.arrayjug[mijuego.turno].manojug[key]--; if (key == TAVANZA)std::cout << "A "; else if (key == TLASER)std::cout << "LA "; else if (key == TIZQUIERDA)std::cout << "GI "; else if (key == TDERECHA)std::cout << "GD "; } else std::cout << "No tienes esa carta, introduce otra: "; } else std::cout << "Introduzca una tecla valida: "; key = leerTecla(); } std::cout << '\n'; ok = realizarMovimiento(mijuego.tablero, mijuego.arrayjug[mijuego.turno].coorjug, vectorcartas, x); devolverCarta(mijuego.arrayjug[mijuego.turno].mazojug, cartasadevolver, x); for (int j = 0; j < NUMEROCARTAS; ++j) { delete vectorcartas[j]; delete cartasadevolver[j]; } } return ok; } void mazosmanos(tJuego & mijuego) {//crea el mazo y la mano de cada jugador tCarta carta; bool a; for (int i = 0; i < mijuego.numjugadores; i++) { crearMazoAleatorio(mijuego.arrayjug[i].mazojug); //mazo mijuego.arrayjug[i].manojug.resize(NUM_DIRECCIONES, 0); //mano=03 cartas de la parte superior for (int k = 0; k < NUM_DIRECCIONES-1; k++) { a = cogerCarta(mijuego.arrayjug[i].mazojug, carta); if (a) ++mijuego.arrayjug[i].manojug[carta]; } } }
#ifndef cryptobox_core_HSM_hpp #define cryptobox_core_HSM_hpp #include <string> #include <optional> #include "cryptobox/core/Common.hpp" namespace cryptobox { class HSM { public: // status for the verification of the signature enum Status { Accepted, Rejected }; HSM(std::string const&); ~HSM(); // create a new entry std::optional<HandleT> Create(); // sign std::optional<Buffer> Sign(HandleT, Buffer const&); // verify std::optional<std::pair<Status, Buffer>> Verify(HandleT, Buffer const&); private: HandleEntryMap entries_; std::string storagePath_; }; } #endif // cryptobox_core_HSM_hpp
/************************************************************************/ /* tools */ /************************************************************************/ #ifndef __UTIL_H__ #define __UTIL_H__ #include <opencv2/opencv.hpp> #include <string> #include <iostream> #include <fstream> #include <string> #include <vector> #include <algorithm> #include <assert.h> #include <iomanip> #include <iosfwd> #include <memory> #include <utility> #include <deque> #include <chrono> #include <future> #include <glog/logging.h> #include "Stopwatch.hpp" #include "CBase64Coder.h" #ifndef WIN32 #include "pthread.h" #include <unistd.h> #include <sys/stat.h> #endif #ifdef WIN32 #include "stdio.h" #include "conio.h" #include <direct.h> #include <io.h> #endif // WIN32 /* #ifndef max #define max(a,b) (((a) > (b)) ? (a) : (b)) #endif #ifndef min #define min(a,b) (((a) < (b)) ? (a) : (b)) #endif */ namespace ice { ////////////////////////////////////////////////////////////////////////// //global var ////////////////////////////////////////////////////////////////////////// extern int g_store_id; extern int g_camera_id; extern float g_detect_thresh;//[0, 1] extern int g_upload_interval;//[-1, >0] extern bool g_use_ksj;//[true, false] extern bool g_show_video;//[true, false] extern cv::Size g_detect_win; extern int g_margin; /************************************************************************/ /* filepath : read file names from videoList : save file name list */ /************************************************************************/ int getFileList(std::string filepath, std::vector<std::string> &videoList); /************************************************************************/ /* return codes */ /************************************************************************/ enum RETCODES { RETCODES_SUCCESS = 0, RETCODES_NULLPTR, RETCODES_INIT_ERROR, }; int parseCfg(const char* cfg); void split(std::string& str, std::vector<std::string>& stringArr, char c); std::string getSystemTime(); double distanceOfIOU(cv::Rect & r1, cv::Rect & r2); int L1distanceOfCentroid(cv::Rect & r1, cv::Rect & r2); int distanceOfCentroid(cv::Rect& r1, cv::Rect& r2); int distanceOfCentroid(cv::Rect& r1, cv::Point& pos); int distanceOfCentroid(cv::Point& pos1, cv::Point& pos2); cv::Rect scaleRect(cv::Rect& r, float factor); //cv::Rect subRect(cv::Rect& r, cv::Mat& frame); std::vector<cv::Rect> subRect(cv::Rect& r, cv::Mat& frame); cv::Rect clothRect(cv::Rect& r, cv::Mat& frame); bool matchRoi(cv::Mat& roi1,cv::Mat& roi2, int thresh); double calcRoiDist(cv::Mat& roi1, cv::Mat& roi2); int getNewestERP(std::vector<std::string>& newErpVec); double calcTraitsDist(std::vector<cv::Point> points_1, std::vector<cv::Point> points_2); // Serialize a cv::Mat to a stringstream std::stringstream serialize(cv::Mat input); // Deserialize a Mat from a stringstream cv::Mat deserialize(std::stringstream& input); void saveImageByIndex(cv::Mat& roi, size_t index, std::string& info); } /************************************************************************/ /* macro used in this global scope */ /************************************************************************/ //match distance #define DIST_HUMAN 70 ////////////////////////////////////////////////////////////////////////// #define INTERVAL 1 #endif // __UTIL_H__
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #include "core/pch.h" #include "modules/doc/imageprogresshandler.h" #include "modules/hardcore/mem/mem_man.h" #include "modules/img/decoderfactorygif.h" #include "modules/img/img_module.h" #include "modules/url/url_enum.h" #ifdef EMBEDDED_ICC_SUPPORT #include "modules/img/imagecolormanager.h" #endif // EMBEDDED_ICC_SUPPORT #ifdef _JPG_SUPPORT_ #include "modules/img/decoderfactoryjpg.h" #endif // _JPG_SUPPORT_ #ifdef _PNG_SUPPORT_ #include "modules/img/decoderfactorypng.h" #endif // _PNG_SUPPORT_ #ifdef ICO_SUPPORT #include "modules/img/decoderfactoryico.h" #endif // _ICO_SUPPORT_ #ifdef _XBM_SUPPORT_ #include "modules/img/decoderfactoryxbm.h" #endif // _XBM_SUPPORT_ #ifdef _BMP_SUPPORT_ #include "modules/img/decoderfactorybmp.h" #endif // _BMP_SUPPORT_ #ifdef WBMP_SUPPORT #include "modules/img/decoderfactorywbmp.h" #endif // WBMP_SUPPORT #ifdef WEBP_SUPPORT #include "modules/img/decoderfactorywebp.h" #endif // WEBP_SUPPORT static void ImgModuleAddImageFactoryL(ImageDecoderFactory* factory, INT32 type, BOOL check_header) { OP_STATUS ret_val = imgManager->AddImageDecoderFactory(factory, type, check_header); if (OpStatus::IsError(ret_val)) { OP_DELETE(factory); LEAVE(ret_val); } } void ImgModule::InitL(const OperaInitInfo& info) { ImageProgressHandler* progressHandler = ImageProgressHandler::Create(); if (progressHandler == NULL) { LEAVE(OpStatus::ERR_NO_MEMORY); } imgManager = ImageManager::Create(progressHandler); if (imgManager == NULL) { OP_DELETE(progressHandler); LEAVE(OpStatus::ERR_NO_MEMORY); } #ifdef EMBEDDED_ICC_SUPPORT g_color_manager = ImageColorManager::Create(); if (g_color_manager == NULL) { LEAVE(OpStatus::ERR_NO_MEMORY); } #endif // EMBEDDED_ICC_SUPPORT ImageDecoderFactory* gif_factory = OP_NEW_L(DecoderFactoryGif, ()); ImgModuleAddImageFactoryL(gif_factory, URL_GIF_CONTENT, TRUE); #if defined(_JPG_SUPPORT_) ImageDecoderFactory* jpg_factory = OP_NEW_L(DecoderFactoryJpg, ()); ImgModuleAddImageFactoryL(jpg_factory, URL_JPG_CONTENT, TRUE); #endif // _JPG_SUPPORT_ #if defined(_PNG_SUPPORT_) ImageDecoderFactory* png_factory = OP_NEW_L(DecoderFactoryPng, ()); ImgModuleAddImageFactoryL(png_factory, URL_PNG_CONTENT, TRUE); #endif // _PNG_SUPPORT_ #if defined(ICO_SUPPORT) ImageDecoderFactory* ico_factory = OP_NEW_L(DecoderFactoryIco, ()); ImgModuleAddImageFactoryL(ico_factory, URL_ICO_CONTENT, TRUE); #endif // ICO_SUPPORT #if defined(_XBM_SUPPORT_) ImageDecoderFactory* xbm_factory = OP_NEW_L(DecoderFactoryXbm, ()); ImgModuleAddImageFactoryL(xbm_factory, URL_XBM_CONTENT, TRUE); #endif // _XBM_SUPPORT_ #if defined(_BMP_SUPPORT_) ImageDecoderFactory* bmp_factory = OP_NEW_L(DecoderFactoryBmp, ()); ImgModuleAddImageFactoryL(bmp_factory, URL_BMP_CONTENT, TRUE); #endif // _BMP_SUPPORT_ #if defined(WBMP_SUPPORT) ImageDecoderFactory* wbmp_factory = OP_NEW_L(DecoderFactoryWbmp, ()); ImgModuleAddImageFactoryL(wbmp_factory, URL_WBMP_CONTENT, TRUE); #endif // WBMP_SUPPORT #ifdef WEBP_SUPPORT ImageDecoderFactory* webp_factory = OP_NEW_L(DecoderFactoryWebP, ()); ImgModuleAddImageFactoryL(webp_factory, URL_WEBP_CONTENT, TRUE); #endif // WEBP_SUPPORT #ifdef ASYNC_IMAGE_DECODERS # ifdef ASYNC_IMAGE_DECODERS_EMULATION AsyncImageDecoderFactory* async_factory = OP_NEW_L(AsyncEmulationDecoderFactory, ()); # else AsyncImageDecoderFactory* async_factory = NULL; LEAVE_IF_ERROR(AsyncImageDecoderFactory::Create(&async_factory)); # endif // ASYNC_IMAGE_DECODERS_EMULATION imgManager->SetAsyncImageDecoderFactory(async_factory); #endif // ASYNC_IMAGE_DECODERS if (g_memory_manager != NULL) { imgManager->SetCacheSize(g_memory_manager->GetMaxImgMemory(), IMAGE_CACHE_POLICY_SOFT); // FIXME:IMG-KILSMO } } void ImgModule::Destroy() { OP_DELETE(imgManager); imgManager = NULL; #ifdef EMBEDDED_ICC_SUPPORT OP_DELETE(g_color_manager); g_color_manager = NULL; #endif // EMBEDDED_ICC_SUPPORT }
/** *AUTHOR:Harsh Agrawal* *Birla Institute of Technology,Mesra* **/ #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; const int N=2e5+1; #define for0(i,e) for(ll i=0;i<e;i++) #define forx(i,x,e) for(ll i=x;i<e;i++) #define ln "\n" #define in(a) cin>>a #define out(a) cout>>a; #define pb push_back #define vll vector<ll> #define vvll vector<vll> #define vi vector<int> #define vvi vector<vi> #define qll queue<ll> #define fastIO ios_base::sync_with_stdio(0);\ cin.tie(NULL);\ cout.tie(NULL) ll n,k,ans=0; vll arr; void bsearch(ll low , ll high, ll x){ while(low<=high){ ll mid = (low + high)/2; if(arr[mid] == x){ ans++; return; } else if(arr[mid] < x){ low = mid + 1; } else{ high = mid - 1; } } return; } void solve(){ cin>>n>>k; arr.resize(n); for0(i,n) cin>>arr[i]; sort(arr.begin(),arr.end()); for0(i,n){ bsearch(0,n-1,arr[i]+k); //bsearch(0,n-1,arr[i]-k); } cout<<ans<<endl; } int main(){ ll t=1;//cin>>t; while(t--){ solve(); } }
// Created on: 2016-04-07 // Copyright (c) 2016 OPEN CASCADE SAS // Created by: Oleg AGASHIN // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _IMeshTools_Parameters_HeaderFile #define _IMeshTools_Parameters_HeaderFile #include <IMeshTools_MeshAlgoType.hxx> #include <Precision.hxx> //! Structure storing meshing parameters struct IMeshTools_Parameters { //! Default constructor IMeshTools_Parameters () : MeshAlgo (IMeshTools_MeshAlgoType_DEFAULT), Angle(0.5), Deflection(0.001), AngleInterior(-1.0), DeflectionInterior(-1.0), MinSize (-1.0), InParallel (Standard_False), Relative (Standard_False), InternalVerticesMode (Standard_True), ControlSurfaceDeflection (Standard_True), EnableControlSurfaceDeflectionAllSurfaces(Standard_False), CleanModel (Standard_True), AdjustMinSize (Standard_False), ForceFaceDeflection (Standard_False), AllowQualityDecrease (Standard_False) { } //! Returns factor used to compute default value of MinSize //! (minimum mesh edge length) from deflection static Standard_Real RelMinSize() { return 0.1; } //! 2D Delaunay triangulation algorithm factory to use IMeshTools_MeshAlgoType MeshAlgo; //! Angular deflection used to tessellate the boundary edges Standard_Real Angle; //!Linear deflection used to tessellate the boundary edges Standard_Real Deflection; //! Angular deflection used to tessellate the face interior Standard_Real AngleInterior; //! Linear deflection used to tessellate the face interior Standard_Real DeflectionInterior; //! Minimum size parameter limiting size of triangle's edges to prevent //! sinking into amplification in case of distorted curves and surfaces. Standard_Real MinSize; //! Switches on/off multi-thread computation Standard_Boolean InParallel; //! Switches on/off relative computation of edge tolerance<br> //! If true, deflection used for the polygonalisation of each edge will be //! <defle> * Size of Edge. The deflection used for the faces will be the //! maximum deflection of their edges. Standard_Boolean Relative; //! Mode to take or not to take internal face vertices into account //! in triangulation process Standard_Boolean InternalVerticesMode; //! Parameter to check the deviation of triangulation and interior of //! the face Standard_Boolean ControlSurfaceDeflection; // Enables/disables check triggered by ControlSurfaceDeflection flag // for all types of surfaces including analytical. Standard_Boolean EnableControlSurfaceDeflectionAllSurfaces; //! Cleans temporary data model when algorithm is finished. Standard_Boolean CleanModel; //! Enables/disables local adjustment of min size depending on edge size. //! Disabled by default. Standard_Boolean AdjustMinSize; //! Enables/disables usage of shape tolerances for computing face deflection. //! Disabled by default. Standard_Boolean ForceFaceDeflection; //! Allows/forbids the decrease of the quality of the generated mesh //! over the existing one. Standard_Boolean AllowQualityDecrease; }; #endif
#include <stdio.h> int i; void g(); void f() { int i; i = 3; { int i; i = 2; g(); } g(); } void g() { i = i + 1; printf("g: %d\n", i); } int main() { i = 5; g(); f(); return 0; }
#pragma once #include <SFML/Graphics.hpp> namespace CAE { namespace WindowHelper { //sf::Vector2f get } }
#include "CCheckMnick.h" #include "json/json.h" #include "Logger.h" #include "threadres.h" #include "Helper.h" int CCheckMnick::do_request(const Json::Value& root, char *client_ip, HttpResult& out) { out["result"] = 1; std::string username = root["param"]["mnick"].asString(); if (!isNickNameInRule(username)) { out["result"] = 0; } // else // { //ToLower(username); //username = Helper::filterInput(username); //Loader_Tcp::callServer2CheckName()->checkUserName(username);//调C++词库看用户名是否合法 // } //out = write.write(ret); return status_ok; }
#include <algorithm> #include <chrono> #include <future> #include <iostream> #include <map> #include <numeric> #include <string> #include <thread> #include <tuple> #include <type_traits> #include <utility> #include <vector> #include <cmath> #include <cstddef> #include <cstdint> #include <cstring> #include "algorithms.hpp" #include "compile_time.hpp" #include "storages.hpp" #include "tests.hpp" #include "utils.hpp" #include "validator.hpp" /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Some helper to get the name of the compiler. #if defined(__GNUG__) && !defined(__clang__) #define COMPILER_GCC #elif defined(__clang__) #define COMPILER_CLANG #endif namespace detail { [[maybe_unused]] static inline auto getCompilerName() { #if defined(COMPILER_GCC) return "gcc"; #elif defined(COMPILER_CLANG) return "clang"; #else return "unknown"; #endif } } // namespace detail /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // A generic sieve benchmark runner that takes a sieve type and config, and runs it, potentially in parallel. template<typename Sieve, std::size_t SieveSize, typename Time> struct Runner { inline auto operator()(const Time& runTime, const std::size_t numThreads = 1) { const auto runThread = [&] { auto error = false; auto passes = std::size_t{0}; const auto start = std::chrono::high_resolution_clock::now(); auto end = start; while(true) { Sieve sieve(SieveSize); sieve.runSieve(); ++passes; if(end = std::chrono::high_resolution_clock::now(); end - start >= runTime) { if(!validate(SieveSize, sieve.countPrimes())) { std::cout << "Error: Results not valid!" << std::endl; error = true; } break; } } return std::tuple{error, passes, start, end, Sieve{}.getConfig()}; }; auto runs = std::vector<std::future<std::invoke_result_t<decltype(runThread)>>>{}; while(runs.size() < numThreads) { runs.push_back(std::async(std::launch::async, runThread)); } // Collect the result(s) of the benchmark, this is done through std::async to be compatible with the TestRunner, // but isn't done in parallel, contrary to the TestRunner which runs all tests in parallel. auto res = std::async([&] { auto totalPasses = std::size_t{0}; auto earliestStart = std::chrono::high_resolution_clock::now(); auto latestEnd = earliestStart; const auto [config, error] = [&] { auto error = false; for(auto i = std::size_t{0}; i < runs.size(); ++i) { const auto [runError, passes, start, end, cfg] = runs[i].get(); error |= runError; totalPasses += passes; earliestStart = std::min(earliestStart, start); latestEnd = std::max(latestEnd, end); if(i + 1 >= runs.size()) { return std::pair{cfg, error}; } } return std::pair{Config{}, true}; }(); const auto duration = latestEnd - earliestStart; const auto durationS = std::chrono::duration_cast<std::chrono::microseconds>(duration).count() / 1'000'000.0; const auto name = config.name + "-" + detail::getCompilerName(); std::cout << name << ";" << totalPasses << ";" << durationS << ";" << numThreads << ";algorithm=" << config.algorithm << ",faithful=" << (config.faithful ? "yes" : "no") << ",bits=" << config.bits << std::endl; return !error; }); res.wait(); return res; } }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Convenience function that starts a runner, potentially in parallel. template<typename RunnerT, typename Time> static inline auto parallelRunner(const Time& runTime, const bool parallelize = true) { auto runnerResults = std::vector<std::invoke_result_t<RunnerT, Time, std::size_t>>{}; if(parallelize) { runnerResults.push_back(RunnerT{}(runTime, std::thread::hardware_concurrency())); } runnerResults.push_back(RunnerT{}(runTime, 1)); return runnerResults; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Helper to append to a container using move semantics. static inline void moveAppend(auto& dst, auto&& src) { dst.insert(dst.end(), std::make_move_iterator(src.begin()), std::make_move_iterator(src.end())); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Function to create and run all possible combinations of optimizations in order to find a set of optimal // combinations any given system/hardware. template<std::size_t SieveSize, template<typename, auto, typename> typename RunnerT, typename Time> static inline auto runAll(const Time& runTime, const bool parallelize = true) { // The possible optimizations. constexpr auto wheels = std::tuple{1, 6}; constexpr auto strides = std::tuple{DynStride::NONE, DynStride::OUTER, DynStride::BOTH}; constexpr auto sizes = std::tuple{true, false}; constexpr auto inverts = std::tuple{true, false}; using types_t = std::tuple<bool, std::uint8_t, std::uint16_t, std::uint32_t, std::uint64_t>; auto runnerResults = std::vector<std::future<bool>>{}; // Nested compile time loop to create the cartesian product of the optimizations above. utils::for_constexpr( [&](const auto wheelIdx) { constexpr auto wheelSize = std::get<wheelIdx.value>(wheels); utils::for_constexpr( [&](const auto strideIdx) { constexpr auto stride = std::get<strideIdx.value>(strides); utils::for_constexpr( [&](const auto sizeIdx) { constexpr auto size = std::get<sizeIdx.value>(sizes); utils::for_constexpr( [&](const auto invertIdx) { constexpr auto inverted = std::get<invertIdx.value>(inverts); utils::for_constexpr( [&](const auto typeIdx) { if constexpr(!(size && wheelSize == 0)) { using type_t = std::tuple_element_t<typeIdx.value, types_t>; using vector_sieve_t = GenericSieve<VectorStorage<type_t, inverted>, wheelSize, stride, size>; using array_sieve_t = GenericSieve<ArrayStorage<type_t, inverted>, wheelSize, stride, size>; using bit_sieve_t = GenericSieve<BitStorage<type_t, inverted>, wheelSize, stride, size>; using masked_bit_sieve_t = GenericSieve<MaskedBitStorage<type_t, inverted>, wheelSize, stride, size>; using strided_bit_sieve_t = GenericSieve<StridedBitStorage<type_t, inverted>, wheelSize, stride, size>; moveAppend(runnerResults, parallelRunner<RunnerT<vector_sieve_t, SieveSize, Time>>(runTime, parallelize)); moveAppend(runnerResults, parallelRunner<RunnerT<array_sieve_t, SieveSize, Time>>(runTime, parallelize)); // The bit-based sieves cannot use bool, because C++ only allows true/false for bools. if constexpr(!std::is_same_v<type_t, bool>) { moveAppend(runnerResults, parallelRunner<RunnerT<bit_sieve_t, SieveSize, Time>>(runTime, parallelize)); moveAppend(runnerResults, parallelRunner<RunnerT<masked_bit_sieve_t, SieveSize, Time>>(runTime, parallelize)); moveAppend(runnerResults, parallelRunner<RunnerT<strided_bit_sieve_t, SieveSize, Time>>(runTime, parallelize)); } } }, std::make_index_sequence<std::tuple_size_v<types_t>>{}); }, std::make_index_sequence<std::tuple_size_v<decltype(inverts)>>{}); }, std::make_index_sequence<std::tuple_size_v<decltype(sizes)>>{}); }, std::make_index_sequence<std::tuple_size_v<decltype(strides)>>{}); }, std::make_index_sequence<std::tuple_size_v<decltype(wheels)>>{}); return runnerResults; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Runs tests for every sieve from sieve size 0 up to SIEVE_SIZE. [[maybe_unused]] static inline auto runTests(const auto& runTime) { using run_time_t = std::remove_cvref_t<decltype(runTime)>; constexpr auto SIEVE_SIZE = 50'000; // The tests are run in parallel, but not using the parallelism of runAll/parallelRunner as this would run duplicates // of the same sieve. Rather the TestRunner internally spawns a thread for every sieve. auto res = runAll<SIEVE_SIZE, TestRunner>(runTime, false); moveAppend(res, parallelRunner<TestRunner<PreGenerated<SIEVE_SIZE>, SIEVE_SIZE, run_time_t>>(runTime, false)); return res; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Runs the pre-generated benchmark. template<std::size_t SieveSize> [[maybe_unused]] static inline auto runPregen(const auto& runTime) { using run_time_t = std::remove_cvref_t<decltype(runTime)>; return parallelRunner<Runner<PreGenerated<SieveSize>, SieveSize, run_time_t>>(runTime); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Runs the base algorithm benchmarks that were determined to be optimal for Intel/AMD. template<std::size_t SieveSize> [[maybe_unused]] static inline auto runBase(const auto& runTime) { using run_time_t = std::remove_cvref_t<decltype(runTime)>; auto res = std::vector<std::future<bool>>{}; // clang-format off using base_runners_t = std::tuple< GenericSieve<StridedBitStorage<std::uint8_t, true>, 1, DynStride::NONE, true>, GenericSieve<VectorStorage<std::uint8_t, false>, 1, DynStride::BOTH, true>, GenericSieve<ArrayStorage<bool, true>, 1, DynStride::NONE, true> >; // clang-format on utils::for_constexpr( [&](const auto idx) { using runner_t = std::tuple_element_t<idx.value, base_runners_t>; moveAppend(res, parallelRunner<Runner<runner_t, SieveSize, run_time_t>>(runTime)); }, std::make_index_sequence<std::tuple_size_v<base_runners_t>>{}); return res; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Runs the wheel algorithm benchmarks that were determined to be optimal for Intel/AMD. template<std::size_t SieveSize> [[maybe_unused]] static inline auto runWheel(const auto& runTime) { using run_time_t = std::remove_cvref_t<decltype(runTime)>; auto res = std::vector<std::future<bool>>{}; // clang-format off using wheel_runners_t = std::tuple< GenericSieve<BitStorage<std::uint32_t, true>, 6, DynStride::OUTER, true>, GenericSieve<VectorStorage<std::uint8_t, true>, 6, DynStride::OUTER, true>, GenericSieve<MaskedBitStorage<std::uint32_t, false>, 6, DynStride::OUTER, true> >; // clang-format on utils::for_constexpr( [&](const auto idx) { using runner_t = std::tuple_element_t<idx.value, wheel_runners_t>; moveAppend(res, parallelRunner<Runner<runner_t, SieveSize, run_time_t>>(runTime)); }, std::make_index_sequence<std::tuple_size_v<wheel_runners_t>>{}); return res; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Runs the benchmark suite, testing all combinations for optimizations. template<std::size_t SieveSize> [[maybe_unused]] static inline auto runSuite(const auto& runTime) { return runAll<SieveSize, Runner>(runTime); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Launch the benchmark selected by the given pre-processor define. int main() { constexpr auto RUN_TIME = std::chrono::seconds(5); #ifdef RUN_TESTS auto res = runTests(RUN_TIME); #else constexpr auto SIEVE_SIZE = 1'000'000; #ifdef RUN_PREGEN auto res = runPregen<SIEVE_SIZE>(RUN_TIME); #elif RUN_SUITE auto res = runSuite<SIEVE_SIZE>(RUN_TIME); #elif RUN_BASE auto res = runBase<SIEVE_SIZE>(RUN_TIME); #elif RUN_WHEEL auto res = runWheel<SIEVE_SIZE>(RUN_TIME); #endif #endif // Only if no errors occurred does the exit code represent success. return std::all_of(res.begin(), res.end(), [](auto& run) { return run.get(); }) ? EXIT_SUCCESS : EXIT_FAILURE; }
#include <iostream> using namespace std; class PlatypusDuckAndBeaver { public: int minimumAnimals(int webbedFeet, int duckBills, int beaverTails) { int maxWebbedFeet = duckBills*2 + beaverTails*4; int platypusCnt = (maxWebbedFeet - webbedFeet)/2; return (duckBills+beaverTails)-platypusCnt; } };
#pragma once namespace jsvector { typedef JSBool(* jsVectorOp)(JSContext* cx, JSObject* obj, D3DXVECTOR3& vec, void* user); struct jsVectorOps { jsVectorOp get; jsVectorOp set; }; JSObject* NewVector(JSContext* cx, JSObject* parent, const D3DXVECTOR3& vec); JSObject* NewWrappedVector(JSContext* cx, JSObject* parent, D3DXVECTOR3* vec, bool readonly = false, jsVectorOps* ops = NULL, void* user = NULL); JSBool SetVector(JSContext* cx, JSObject* obj, const D3DXVECTOR3& vec); JSBool GetVector(JSContext* cx, JSObject* obj, D3DXVECTOR3& vec); JSBool ParseVector(JSContext* cx, D3DXVECTOR3& vec, uintN argc, jsval* argv); }
#include <vector> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <list> #include <algorithm> #include <sstream> #include <set> #include <cmath> #include <map> #include <stack> #include <queue> #include <cstdio> #include <cstdlib> #include <cstring> #include <numeric> #include <bitset> #include <deque> const long long LINF = (1e15); const int INF = (1<<27); #define EPS 1e-6 const int MOD = 1000000007; using namespace std; class TrafficCongestion { public: int theMinCars(int treeHeight) { long long f[1000005]; memset(f, 0, sizeof(f)); f[0] = f[1] = 1; f[2] = 3; for (int i=3; i<=treeHeight; ++i) { f[i] = (f[i-1] + 2*f[i-2])%MOD; } return (int)f[treeHeight]; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arg0 = 1; int Arg1 = 1; verify_case(0, Arg1, theMinCars(Arg0)); } void test_case_1() { int Arg0 = 2; int Arg1 = 3; verify_case(1, Arg1, theMinCars(Arg0)); } void test_case_2() { int Arg0 = 3; int Arg1 = 5; verify_case(2, Arg1, theMinCars(Arg0)); } void test_case_3() { int Arg0 = 585858; int Arg1 = 548973404; verify_case(3, Arg1, theMinCars(Arg0)); } // END CUT HERE }; // BEGIN CUT HERE int main() { TrafficCongestion ___test; ___test.run_test(-1); } // END CUT HERE
#include<iostream> #include<vector> // for 2D vector using namespace std; int main() { // Initializing 2D vector "vect" with // // values vector< vector<int> > vect{{1, 2, 3,5}, {4, 5, 6,8}, {7, 8, 9,2}}; //size of 2d vect cout<<"no. of rows : "<<vect.size(); cout<<endl; cout<<"no.of columns: "<<vect[0].size(); // Displaying the 2D vector for (int i=0; i<vect.size(); i++) { for (int j=0; j<vect[i].size() ;j++) cout << vect[i][j] << " "; cout << endl; } return 0; }
/* * Class storing data for screen location relative to level */ #include <cassert> #include "playingscreen.h" void PlayingScreen::unitTest() { PlayingScreen* scr = new PlayingScreen(0, 0, 100, 100, 200, 100); assert(scr->getX() == 0); assert(scr->getY() == 0); assert(scr->getCenterX(10) == 45); assert(scr->getCenterY(40) == 30); scr->setLocation(10, 20); assert(scr->getX() == 10); assert(scr->getY() == 20); scr->setScreenSize(50, 50); assert(scr->getCenterX(40) == 5); delete scr; } int PlayingScreen::getCenterX(int objWidth) { return (int) (0.5 * (width - objWidth)); } int PlayingScreen::getCenterY(int objHeight) { return (int) (0.5 * (height - objHeight)); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2009 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #include "core/pch.h" #ifdef DAPI_VCARD_SUPPORT #include "modules/device_api/OpVCardEntry.h" #include "modules/pi/device_api/OpAddressBook.h" #include "modules/device_api/src/VCardGlobals.h" static OpString* MakeOpString(const uni_char* val) { OpString* retval = OP_NEW(OpString, ()); RETURN_VALUE_IF_NULL(retval, NULL); OP_STATUS status = retval->Set(val); if (OpStatus::IsError(status)) { OP_DELETE(retval); return NULL; } return retval; } /*static*/ BOOL OpVCardEntry::FindFieldWithMeaning(OpAddressBook::OpAddressBookFieldInfo::Meaning meaning, const OpAddressBook::OpAddressBookFieldInfo* infos, UINT32 infos_count, UINT32& index) { for (index = 0; index < infos_count; ++index) { if (infos[index].meaning == meaning) return TRUE; } return FALSE; } OP_STATUS OpVCardEntry::ImportFromOpAddressBookItem(OpAddressBookItem* address_book_item) { const OpAddressBook::OpAddressBookFieldInfo* infos; UINT32 count; address_book_item->GetAddressBook()->GetFieldInfos(&infos, &count); OpString current_val; UINT32 index = 0; // formatted name is made by concatenating title and full name // if there is no full name than we try to make it using first/second/last name // TODO - in some locales family name comes first etc. - make it work too OpString formatted_name; OpString value_buffer; BOOL has_full_name = FALSE; if (FindFieldWithMeaning(OpAddressBook::OpAddressBookFieldInfo::MEANING_TITLE, infos, count, index)) { UINT32 val_count; address_book_item->GetValueCount(index, &val_count); for (UINT32 i = 0; i < val_count; ++i) { RETURN_IF_ERROR(address_book_item->GetValue(index, i, &value_buffer)); if (value_buffer.CStr()) { RETURN_IF_ERROR(formatted_name.AppendFormat(UNI_L("%s "), value_buffer.CStr())); RETURN_IF_ERROR(AddHonorificPrefix(value_buffer.CStr())); } } } if (FindFieldWithMeaning(OpAddressBook::OpAddressBookFieldInfo::MEANING_FULL_NAME, infos, count, index)) { has_full_name = TRUE; RETURN_IF_ERROR(address_book_item->GetValue(index, 0, &value_buffer)); if (value_buffer.CStr()) RETURN_IF_ERROR(formatted_name.AppendFormat(UNI_L("%s "), value_buffer.CStr())); } if (FindFieldWithMeaning(OpAddressBook::OpAddressBookFieldInfo::MEANING_FIRST_NAME, infos, count, index)) { UINT32 val_count; address_book_item->GetValueCount(index, &val_count); if (val_count > 0) { RETURN_IF_ERROR(address_book_item->GetValue(index, 0, &value_buffer)); if (value_buffer.CStr()) { RETURN_IF_ERROR(AddGivenName(value_buffer.CStr())); if (!has_full_name) RETURN_IF_ERROR(formatted_name.AppendFormat(UNI_L("%s "), value_buffer.CStr())); } } for (UINT32 i = 1; i < val_count; ++i) { RETURN_IF_ERROR(address_book_item->GetValue(index, i, &value_buffer)); if (value_buffer.CStr()) { RETURN_IF_ERROR(AddAdditionalName(value_buffer.CStr())); if (!has_full_name) RETURN_IF_ERROR(formatted_name.AppendFormat(UNI_L("%s "), value_buffer.CStr())); } } } if (FindFieldWithMeaning(OpAddressBook::OpAddressBookFieldInfo::MEANING_MIDDLE_NAME, infos, count, index)) { UINT32 val_count; address_book_item->GetValueCount(index, &val_count); for (UINT32 i = 0; i < val_count; ++i) { RETURN_IF_ERROR(address_book_item->GetValue(index, i, &value_buffer)); if (value_buffer.CStr()) { RETURN_IF_ERROR(AddAdditionalName(value_buffer.CStr())); if (!has_full_name) RETURN_IF_ERROR(formatted_name.AppendFormat(UNI_L("%s "), value_buffer.CStr())); } } } if (FindFieldWithMeaning(OpAddressBook::OpAddressBookFieldInfo::MEANING_LAST_NAME, infos, count, index)) { UINT32 val_count; address_book_item->GetValueCount(index, &val_count); for (UINT32 i = 0; i < val_count; ++i) { RETURN_IF_ERROR(address_book_item->GetValue(index, i, &value_buffer)); if (value_buffer.CStr()) { RETURN_IF_ERROR(AddFamilyName(value_buffer.CStr())); if (!has_full_name) RETURN_IF_ERROR(formatted_name.AppendFormat(UNI_L("%s "), value_buffer.CStr())); } } } if (!formatted_name.IsEmpty()) { formatted_name.Strip(); RETURN_IF_ERROR(SetFormattedName(formatted_name.CStr())); } if (FindFieldWithMeaning(OpAddressBook::OpAddressBookFieldInfo::MEANING_EMAIL, infos, count, index)) { UINT32 val_count; address_book_item->GetValueCount(index, &val_count); for (UINT32 i = 0; i < val_count; ++i) { RETURN_IF_ERROR(address_book_item->GetValue(index, i, &value_buffer)); if (value_buffer.CStr()) RETURN_IF_ERROR(AddEMail(OpVCardEntry::EMAIL_DEFAULT, value_buffer.CStr())); } } if (FindFieldWithMeaning(OpAddressBook::OpAddressBookFieldInfo::MEANING_PRIVATE_LANDLINE_PHONE, infos, count, index)) { UINT32 val_count; address_book_item->GetValueCount(index, &val_count); for (UINT32 i = 0; i < val_count; ++i) { RETURN_IF_ERROR(address_book_item->GetValue(index, i, &value_buffer)); if (value_buffer.CStr()) RETURN_IF_ERROR(AddTelephoneNumber(OpVCardEntry::TELEPHONE_VOICE|OpVCardEntry::TELEPHONE_HOME, value_buffer.CStr())); } } if (FindFieldWithMeaning(OpAddressBook::OpAddressBookFieldInfo::MEANING_WORK_LANDLINE_PHONE, infos, count, index)) { UINT32 val_count; address_book_item->GetValueCount(index, &val_count); for (UINT32 i = 0; i < val_count; ++i) { RETURN_IF_ERROR(address_book_item->GetValue(index, i, &value_buffer)); if (value_buffer.CStr()) RETURN_IF_ERROR(AddTelephoneNumber(OpVCardEntry::TELEPHONE_VOICE|OpVCardEntry::TELEPHONE_WORK, value_buffer.CStr())); } } if (FindFieldWithMeaning(OpAddressBook::OpAddressBookFieldInfo::MEANING_LANDLINE_PHONE, infos, count, index)) { UINT32 val_count; address_book_item->GetValueCount(index, &val_count); for (UINT32 i = 0; i < val_count; ++i) { RETURN_IF_ERROR(address_book_item->GetValue(index, i, &value_buffer)); if (value_buffer.CStr()) RETURN_IF_ERROR(AddTelephoneNumber(OpVCardEntry::TELEPHONE_VOICE, value_buffer.CStr())); } } if (FindFieldWithMeaning(OpAddressBook::OpAddressBookFieldInfo::MEANING_PRIVATE_MOBILE_PHONE, infos, count, index)) { UINT32 val_count; address_book_item->GetValueCount(index, &val_count); for (UINT32 i = 0; i < val_count; ++i) { RETURN_IF_ERROR(address_book_item->GetValue(index, i, &value_buffer)); if (value_buffer.CStr()) RETURN_IF_ERROR(AddTelephoneNumber(OpVCardEntry::TELEPHONE_VOICE|OpVCardEntry::TELEPHONE_CELL, value_buffer.CStr())); } } if (FindFieldWithMeaning(OpAddressBook::OpAddressBookFieldInfo::MEANING_WORK_MOBILE_PHONE, infos, count, index)) { UINT32 val_count; address_book_item->GetValueCount(index, &val_count); for (UINT32 i = 0; i < val_count; ++i) { RETURN_IF_ERROR(address_book_item->GetValue(index, i, &value_buffer)); if (value_buffer.CStr()) RETURN_IF_ERROR(AddTelephoneNumber(OpVCardEntry::TELEPHONE_VOICE|OpVCardEntry::TELEPHONE_CELL|OpVCardEntry::TELEPHONE_WORK, value_buffer.CStr())); } } if (FindFieldWithMeaning(OpAddressBook::OpAddressBookFieldInfo::MEANING_MOBILE_PHONE, infos, count, index)) { UINT32 val_count; address_book_item->GetValueCount(index, &val_count); for (UINT32 i = 0; i < val_count; ++i) { RETURN_IF_ERROR(address_book_item->GetValue(index, i, &value_buffer)); if (value_buffer.CStr()) RETURN_IF_ERROR(AddTelephoneNumber(OpVCardEntry::TELEPHONE_VOICE|OpVCardEntry::TELEPHONE_CELL, value_buffer.CStr())); } } if (FindFieldWithMeaning(OpAddressBook::OpAddressBookFieldInfo::MEANING_WORK_PHONE, infos, count, index)) { UINT32 val_count; address_book_item->GetValueCount(index, &val_count); for (UINT32 i = 0; i < val_count; ++i) { RETURN_IF_ERROR(address_book_item->GetValue(index, i, &value_buffer)); if (value_buffer.CStr()) RETURN_IF_ERROR(AddTelephoneNumber(OpVCardEntry::TELEPHONE_VOICE|OpVCardEntry::TELEPHONE_WORK, value_buffer.CStr())); } } if (FindFieldWithMeaning(OpAddressBook::OpAddressBookFieldInfo::MEANING_PRIVATE_PHONE, infos, count, index)) { UINT32 val_count; address_book_item->GetValueCount(index, &val_count); for (UINT32 i = 0; i < val_count; ++i) { RETURN_IF_ERROR(address_book_item->GetValue(index, i, &value_buffer)); if (value_buffer.CStr()) RETURN_IF_ERROR(AddTelephoneNumber(OpVCardEntry::TELEPHONE_VOICE, value_buffer.CStr())); } } if (FindFieldWithMeaning(OpAddressBook::OpAddressBookFieldInfo::MEANING_PRIVATE_FAX, infos, count, index)) { UINT32 val_count; address_book_item->GetValueCount(index, &val_count); for (UINT32 i = 0; i < val_count; ++i) { RETURN_IF_ERROR(address_book_item->GetValue(index, i, &value_buffer)); if (value_buffer.CStr()) RETURN_IF_ERROR(AddTelephoneNumber(OpVCardEntry::TELEPHONE_FAX|OpVCardEntry::TELEPHONE_HOME, value_buffer.CStr())); } } if (FindFieldWithMeaning(OpAddressBook::OpAddressBookFieldInfo::MEANING_WORK_FAX, infos, count, index)) { UINT32 val_count; address_book_item->GetValueCount(index, &val_count); for (UINT32 i = 0; i < val_count; ++i) { RETURN_IF_ERROR(address_book_item->GetValue(index, i, &value_buffer)); if (value_buffer.CStr()) RETURN_IF_ERROR(AddTelephoneNumber(OpVCardEntry::TELEPHONE_FAX|OpVCardEntry::TELEPHONE_WORK, value_buffer.CStr())); } } if (FindFieldWithMeaning(OpAddressBook::OpAddressBookFieldInfo::MEANING_FAX, infos, count, index)) { UINT32 val_count; address_book_item->GetValueCount(index, &val_count); for (UINT32 i = 0; i < val_count; ++i) { RETURN_IF_ERROR(address_book_item->GetValue(index, i, &value_buffer)); if (value_buffer.CStr()) RETURN_IF_ERROR(AddTelephoneNumber(OpVCardEntry::TELEPHONE_FAX, value_buffer.CStr())); } } if (FindFieldWithMeaning(OpAddressBook::OpAddressBookFieldInfo::MEANING_COMPANY, infos, count, index)) { UINT32 val_count; address_book_item->GetValueCount(index, &val_count); for (UINT32 i = 0; i < val_count; ++i) { RETURN_IF_ERROR(address_book_item->GetValue(index, i, &value_buffer)); const uni_char* organization_chain[1] = {value_buffer.CStr()}; if (value_buffer.CStr()) RETURN_IF_ERROR(SetOrganizationalChain(organization_chain, ARRAY_SIZE(organization_chain))); } } if (FindFieldWithMeaning(OpAddressBook::OpAddressBookFieldInfo::MEANING_FULL_ADDRESS, infos, count, index)) { UINT32 val_count; address_book_item->GetValueCount(index, &val_count); OpString label_buffer; for (UINT32 i = 0; i < val_count; ++i) { UINT32 val_count; address_book_item->GetValueCount(index, &val_count); for (UINT32 i = 0; i < val_count; ++i) { RETURN_IF_ERROR(address_book_item->GetValue(index, i, &value_buffer)); if (value_buffer.CStr()) { label_buffer.Empty(); RETURN_IF_ERROR(label_buffer.AppendFormat(UNI_L("%s\n%s"),formatted_name.CStr(), value_buffer.CStr())); RETURN_IF_ERROR(AddPostalLabelAddress(OpVCardEntry::ADDRESS_DEFAULT, label_buffer.CStr())); } } } } UINT32 country_index = 0, state_index = 0, city_index = 0, street_index = 0, number_index = 0, postal_code_index = 0; BOOL has_country = FindFieldWithMeaning(OpAddressBook::OpAddressBookFieldInfo::MEANING_ADDRESS_COUNTRY, infos, count, country_index); BOOL has_state = FindFieldWithMeaning(OpAddressBook::OpAddressBookFieldInfo::MEANING_ADDRESS_STATE, infos, count, state_index); BOOL has_city = FindFieldWithMeaning(OpAddressBook::OpAddressBookFieldInfo::MEANING_ADDRESS_CITY, infos, count, city_index); BOOL has_street = FindFieldWithMeaning(OpAddressBook::OpAddressBookFieldInfo::MEANING_ADDRESS_STREET, infos, count, street_index); BOOL has_number = FindFieldWithMeaning(OpAddressBook::OpAddressBookFieldInfo::MEANING_ADDRESS_NUMBER, infos, count, number_index); BOOL has_postal_code = FindFieldWithMeaning(OpAddressBook::OpAddressBookFieldInfo::MEANING_ADDRESS_POSTAL_CODE, infos, count, postal_code_index); UINT32 max_count = 0, tmp_count = 0; address_book_item->GetValueCount(country_index, &max_count); address_book_item->GetValueCount(state_index, &tmp_count); max_count = max_count > tmp_count ? max_count : tmp_count; address_book_item->GetValueCount(city_index, &tmp_count); max_count = max_count > tmp_count ? max_count : tmp_count; address_book_item->GetValueCount(street_index, &tmp_count); max_count = max_count > tmp_count ? max_count : tmp_count; address_book_item->GetValueCount(number_index, &tmp_count); max_count = max_count > tmp_count ? max_count : tmp_count; address_book_item->GetValueCount(postal_code_index, &tmp_count); max_count = max_count > tmp_count ? max_count : tmp_count; OpString country_buffer, state_buffer, city_buffer, street_buffer, number_buffer, postal_code_buffer; OpString street_address; for (UINT32 i = 0; i < max_count; ++i) { if (has_country) RETURN_IF_ERROR(address_book_item->GetValue(country_index, i, &country_buffer)); if (has_state) RETURN_IF_ERROR(address_book_item->GetValue(state_index, i, &state_buffer)); if (has_city) RETURN_IF_ERROR(address_book_item->GetValue(city_index, i, &city_buffer)); if (has_street) RETURN_IF_ERROR(address_book_item->GetValue(street_index, i, &street_buffer)); if (has_number) RETURN_IF_ERROR(address_book_item->GetValue(number_index, i, &number_buffer)); if (has_postal_code) RETURN_IF_ERROR(address_book_item->GetValue(postal_code_index, i, &postal_code_buffer)); if (country_buffer.CStr() || state_buffer.CStr() || city_buffer.CStr() || street_buffer.CStr() || number_buffer.CStr() || postal_code_buffer.CStr()) // at least one must be non-NULL { street_address.Empty(); RETURN_IF_ERROR(street_address.AppendFormat(UNI_L("%s %s"), street_buffer.CStr(), number_buffer.CStr())); RETURN_IF_ERROR(AddStructuredAddress(OpVCardEntry::ADDRESS_DEFAULT ,NULL, NULL, street_address.CStr(), city_buffer.CStr() , state_buffer.CStr(), postal_code_buffer.CStr(), country_buffer.CStr())); } } return OpStatus::OK; } OP_STATUS OpVCardEntry::ApplyTypeFlags(OpDirectoryEntryContentLine* value, int flags, const uni_char* const* flags_texts, int last_flag) { // delete all type flags while (value->GetParams()->Delete(UNI_L("TYPE"), 0) == OpStatus::OK) { } for (int mask = 1, i = 0; mask <= last_flag; mask <<= 1, ++i) { if (flags & mask) { OpString* type_string = MakeOpString(flags_texts[i]); RETURN_OOM_IF_NULL(type_string); RETURN_IF_ERROR(value->GetParams()->Add(UNI_L("TYPE"), type_string)); } } return OpStatus::OK; } // see RFC2426 (vCard) - FN OP_STATUS OpVCardEntry::SetFormattedName(const uni_char* fn) { OpDirectoryEntryContentLine* value; RETURN_OOM_IF_NULL(value = FindOrConstructNamedContentLine(UNI_L("FN"))); OpDirectoryEntryContentLine::ValueStruct* value_struct = OpDirectoryEntryContentLine::NewStringValue(fn); RETURN_OOM_IF_NULL(value_struct); RETURN_IF_ERROR(value->SetValue(0, 0, value_struct)); return OpStatus::OK; } // see RFC2426 (vCard) - N - 1st field OP_STATUS OpVCardEntry::AddFamilyName(const uni_char* family_name) { OpDirectoryEntryContentLine* value; RETURN_OOM_IF_NULL(value = FindOrConstructNamedContentLine(UNI_L("N"), 5)); OpDirectoryEntryContentLine::ValueStruct* value_struct = OpDirectoryEntryContentLine::NewStringValue(family_name); RETURN_OOM_IF_NULL(value_struct); RETURN_IF_ERROR(value->AddValue(0, value_struct)); return OpStatus::OK; } // see RFC2426 (vCard) - N - 2nd field OP_STATUS OpVCardEntry::AddGivenName(const uni_char* given_name) { OpDirectoryEntryContentLine* value; RETURN_OOM_IF_NULL(value = FindOrConstructNamedContentLine(UNI_L("N"), 5)); OpDirectoryEntryContentLine::ValueStruct* value_struct = OpDirectoryEntryContentLine::NewStringValue(given_name); RETURN_OOM_IF_NULL(value_struct); RETURN_IF_ERROR(value->AddValue(1, value_struct)); return OpStatus::OK; } // see RFC2426 (vCard) - N - 3rd field OP_STATUS OpVCardEntry::AddAdditionalName(const uni_char* additional_name) { OpDirectoryEntryContentLine* value; RETURN_OOM_IF_NULL(value = FindOrConstructNamedContentLine(UNI_L("N"), 5)); OpDirectoryEntryContentLine::ValueStruct* value_struct = OpDirectoryEntryContentLine::NewStringValue(additional_name); RETURN_OOM_IF_NULL(value_struct); RETURN_IF_ERROR(value->AddValue(2, value_struct)); return OpStatus::OK; } // see RFC2426 (vCard) - N - 4th field OP_STATUS OpVCardEntry::AddHonorificPrefix(const uni_char* honorific_prefix) { OpDirectoryEntryContentLine* value; RETURN_OOM_IF_NULL(value = FindOrConstructNamedContentLine(UNI_L("N"), 5)); OpDirectoryEntryContentLine::ValueStruct* value_struct = OpDirectoryEntryContentLine::NewStringValue(honorific_prefix); RETURN_OOM_IF_NULL(value_struct); RETURN_IF_ERROR(value->AddValue(3, value_struct)); return OpStatus::OK; } // see RFC2426 (vCard) - N - 5th field OP_STATUS OpVCardEntry::AddHonorificSuffix(const uni_char* honorific_suffix) { OpDirectoryEntryContentLine* value; RETURN_OOM_IF_NULL(value = FindOrConstructNamedContentLine(UNI_L("N"), 5)); OpDirectoryEntryContentLine::ValueStruct* value_struct = OpDirectoryEntryContentLine::NewStringValue(honorific_suffix); RETURN_OOM_IF_NULL(value_struct); RETURN_IF_ERROR(value->AddValue(4, value_struct)); return OpStatus::OK; } // see RFC2426 (vCard) - NICKNAME OP_STATUS OpVCardEntry::AddNickname(const uni_char* nickname) { OpDirectoryEntryContentLine* value; RETURN_OOM_IF_NULL(value = FindOrConstructNamedContentLine(UNI_L("NICKNAME"))); OpDirectoryEntryContentLine::ValueStruct* value_struct = OpDirectoryEntryContentLine::NewStringValue(nickname); RETURN_OOM_IF_NULL(value_struct); RETURN_IF_ERROR(value->AddValue(0, value_struct)); return OpStatus::OK; } // see RFC2426 (vCard) - BDAY OP_STATUS OpVCardEntry::SetBirthday(int year, int month, int day, double time_of_day = 0.0, double time_offset = 0.0) { return OpStatus::ERR_NOT_SUPPORTED; } // see RFC2426 (vCard) - ADR OP_STATUS OpVCardEntry::AddStructuredAddress(int type_flags , const uni_char* post_office_box , const uni_char* extended_address , const uni_char* street_address , const uni_char* locality , const uni_char* region , const uni_char* postal_code , const uni_char* country_name) { OpDirectoryEntryContentLine* value; RETURN_OOM_IF_NULL(value = ConstructNewNamedContentLine(UNI_L("ADR"), 7)); OpDirectoryEntryContentLine::ValueStruct* value_struct = OpDirectoryEntryContentLine::NewStringValue(post_office_box); RETURN_OOM_IF_NULL(value_struct); RETURN_IF_ERROR(value->SetValue(0, 0, value_struct)); value_struct = OpDirectoryEntryContentLine::NewStringValue(extended_address); RETURN_OOM_IF_NULL(value_struct); RETURN_IF_ERROR(value->SetValue(1, 0, value_struct)); value_struct = OpDirectoryEntryContentLine::NewStringValue(street_address); RETURN_OOM_IF_NULL(value_struct); RETURN_IF_ERROR(value->SetValue(2, 0, value_struct)); value_struct = OpDirectoryEntryContentLine::NewStringValue(locality); RETURN_OOM_IF_NULL(value_struct); RETURN_IF_ERROR(value->SetValue(3, 0, value_struct)); value_struct = OpDirectoryEntryContentLine::NewStringValue(region); RETURN_OOM_IF_NULL(value_struct); RETURN_IF_ERROR(value->SetValue(4, 0, value_struct)); value_struct = OpDirectoryEntryContentLine::NewStringValue(postal_code); RETURN_OOM_IF_NULL(value_struct); RETURN_IF_ERROR(value->SetValue(5, 0, value_struct)); value_struct = OpDirectoryEntryContentLine::NewStringValue(country_name); RETURN_OOM_IF_NULL(value_struct); RETURN_IF_ERROR(value->SetValue(6, 0, value_struct)); return ApplyAddressTypeFlags(value, type_flags); } OP_STATUS OpVCardEntry::ApplyAddressTypeFlags(OpDirectoryEntryContentLine* value, int flags) { OP_ASSERT(1 << (ARRAY_SIZE(g_device_api.GetVCardGlobals()->address_type_names)-1) == ADDRESS_LAST); return ApplyTypeFlags(value, flags, g_device_api.GetVCardGlobals()->address_type_names, ADDRESS_LAST); } // see RFC2426 (vCard) - LABEL OP_STATUS OpVCardEntry::AddPostalLabelAddress(int type_flags , const uni_char* address) { OpDirectoryEntryContentLine* value; RETURN_OOM_IF_NULL(value = ConstructNewNamedContentLine(UNI_L("LABEL"))); OpDirectoryEntryContentLine::ValueStruct* value_struct = OpDirectoryEntryContentLine::NewStringValue(address); RETURN_OOM_IF_NULL(value_struct); RETURN_IF_ERROR(value->SetValue(0, 0, value_struct)); return ApplyAddressTypeFlags(value, type_flags); } // see RFC2426 (vCard) - TEL OP_STATUS OpVCardEntry::AddTelephoneNumber(int type_flags , const uni_char* number) { //TODO validate telephone OpDirectoryEntryContentLine* value; RETURN_OOM_IF_NULL(value = ConstructNewNamedContentLine(UNI_L("TEL"))); OpDirectoryEntryContentLine::ValueStruct* value_struct = OpDirectoryEntryContentLine::NewStringValue(number); RETURN_OOM_IF_NULL(value_struct); RETURN_IF_ERROR(value->SetValue(0, 0, value_struct)); return ApplyTelephoneTypeFlags(value, type_flags); } OP_STATUS OpVCardEntry::ApplyTelephoneTypeFlags(OpDirectoryEntryContentLine* value, int flags) { OP_ASSERT(1 << (ARRAY_SIZE(g_device_api.GetVCardGlobals()->phone_type_names)-1) == TELEPHONE_LAST); return ApplyTypeFlags(value, flags, g_device_api.GetVCardGlobals()->phone_type_names, TELEPHONE_LAST); } OP_STATUS OpVCardEntry::ApplyEmailTypeFlags(OpDirectoryEntryContentLine* value, int flags) { OP_ASSERT(1 << (ARRAY_SIZE(g_device_api.GetVCardGlobals()->email_type_names)-1) == EMAIL_LAST); return ApplyTypeFlags(value, flags, g_device_api.GetVCardGlobals()->email_type_names, EMAIL_LAST); } // see RFC2426 (vCard) - EMAIL OP_STATUS OpVCardEntry::AddEMail(int type_flags , const uni_char* email) { OpDirectoryEntryContentLine* value; RETURN_OOM_IF_NULL(value = ConstructNewNamedContentLine(UNI_L("EMAIL"))); OpDirectoryEntryContentLine::ValueStruct* value_struct = OpDirectoryEntryContentLine::NewStringValue(email); RETURN_OOM_IF_NULL(value_struct); RETURN_IF_ERROR(value->SetValue(0, 0, value_struct)); return ApplyEmailTypeFlags(value, type_flags); } // see RFC2426 (vCard) - MAILER OP_STATUS OpVCardEntry::SetMailer(const uni_char* mailer) { OpDirectoryEntryContentLine* value; RETURN_OOM_IF_NULL(value = FindOrConstructNamedContentLine(UNI_L("MAILER"))); OpDirectoryEntryContentLine::ValueStruct* value_struct = OpDirectoryEntryContentLine::NewStringValue(mailer); RETURN_OOM_IF_NULL(value_struct); RETURN_IF_ERROR(value->SetValue(0, 0, value_struct)); return OpStatus::OK; } // see RFC2426 (vCard) - TZ OP_STATUS OpVCardEntry::SetTimezone(double timezone_offset) { OpDirectoryEntryContentLine* value; RETURN_OOM_IF_NULL(value = FindOrConstructNamedContentLine(UNI_L("TZ"))); OpDirectoryEntryContentLine::ValueStruct* value_struct = OpDirectoryEntryContentLine::NewFloatValue(timezone_offset); RETURN_OOM_IF_NULL(value_struct); RETURN_IF_ERROR(value->SetValue(0, 0, value_struct)); return OpStatus::OK; } // see RFC2426 (vCard) - GEO OP_STATUS OpVCardEntry::SetLocation(double latitude, double longitude) { OpDirectoryEntryContentLine* value; RETURN_OOM_IF_NULL(value = FindOrConstructNamedContentLine(UNI_L("GEO"))); OpDirectoryEntryContentLine::ValueStruct* value_struct = OpDirectoryEntryContentLine::NewFloatValue(latitude); RETURN_OOM_IF_NULL(value_struct); RETURN_IF_ERROR(value->SetValue(0, 0, value_struct)); value_struct = OpDirectoryEntryContentLine::NewFloatValue(longitude); RETURN_OOM_IF_NULL(value_struct); RETURN_IF_ERROR(value->SetValue(1, 0, value_struct)); return OpStatus::OK; } // see RFC2426 (vCard) - TITLE OP_STATUS OpVCardEntry::SetOrganizationTitle(const uni_char* title) { OpDirectoryEntryContentLine* value; RETURN_OOM_IF_NULL(value = FindOrConstructNamedContentLine(UNI_L("TITLE"))); OpDirectoryEntryContentLine::ValueStruct* value_struct = OpDirectoryEntryContentLine::NewStringValue(title); RETURN_OOM_IF_NULL(value_struct); RETURN_IF_ERROR(value->SetValue(0, 0, value_struct)); return OpStatus::OK; } // see RFC2426 (vCard) - ROLE OP_STATUS OpVCardEntry::SetOrganizationRole(const uni_char* role) { OpDirectoryEntryContentLine* value; RETURN_OOM_IF_NULL(value = FindOrConstructNamedContentLine(UNI_L("ROLE"))); OpDirectoryEntryContentLine::ValueStruct* value_struct = OpDirectoryEntryContentLine::NewStringValue(role); RETURN_OOM_IF_NULL(value_struct); RETURN_IF_ERROR(value->SetValue(0, 0, value_struct)); return OpStatus::OK; } // see RFC2426 (vCard) - AGENT OP_STATUS OpVCardEntry::AddAgentURI(const uni_char* uri){ return OpStatus::ERR_NOT_SUPPORTED; } OP_STATUS OpVCardEntry::AddAgentVCard(const OpVCardEntry* v_card){ return OpStatus::ERR_NOT_SUPPORTED; } OP_STATUS OpVCardEntry::AddAgentText(const uni_char* agent_text){ return OpStatus::ERR_NOT_SUPPORTED; } // see RFC2426 (vCard) - ORG OP_STATUS OpVCardEntry::SetOrganizationalChain(const uni_char** organizational_chain, UINT32 chain_length) { OpDirectoryEntryContentLine* value; RETURN_OOM_IF_NULL(value = FindOrConstructNamedContentLine(UNI_L("ORG"))); for (UINT32 i = 0; i < chain_length; ++i) { OpDirectoryEntryContentLine::ValueStruct* value_struct = OpDirectoryEntryContentLine::NewStringValue(organizational_chain[i]); RETURN_OOM_IF_NULL(value_struct); RETURN_IF_ERROR(value->SetValue(i, 0, value_struct)); } return OpStatus::OK; } // see RFC2426 (vCard) - CATEGORIES OP_STATUS OpVCardEntry::AddCategory(const uni_char* category){ return OpStatus::ERR_NOT_SUPPORTED; } // see RFC2426 (vCard) - NOTE OP_STATUS OpVCardEntry::AddNote(const uni_char* note){ return OpStatus::ERR_NOT_SUPPORTED; } // see RFC2426 (vCard) - SORT-STRING OP_STATUS OpVCardEntry::AddSortString(const uni_char* sort_string){ return OpStatus::ERR_NOT_SUPPORTED; } // see RFC2426 (vCard) - URL OP_STATUS OpVCardEntry::AddURL(const uni_char* url){ return OpStatus::ERR_NOT_SUPPORTED; } // see RFC2426 (vCard) - PHOTO OP_STATUS OpVCardEntry::AddPhoto(const uni_char* uri){ return OpStatus::ERR_NOT_SUPPORTED; } OP_STATUS OpVCardEntry::AddPhoto(OpFileDescriptor* opened_input_file, const uni_char* type){ return OpStatus::ERR_NOT_SUPPORTED; } // see RFC2426 (vCard) - LOGO OP_STATUS OpVCardEntry::AddLogo(const uni_char* uri){ return OpStatus::ERR_NOT_SUPPORTED; } OP_STATUS OpVCardEntry::AddLogo(OpFileDescriptor* opened_input_file, const uni_char* type){ return OpStatus::ERR_NOT_SUPPORTED; } // see RFC2426 (vCard) - SOUND OP_STATUS OpVCardEntry::AddSound(const uni_char* uri){ return OpStatus::ERR_NOT_SUPPORTED; } OP_STATUS OpVCardEntry::AddSound(OpFileDescriptor* opened_input_file, const uni_char* type){ return OpStatus::ERR_NOT_SUPPORTED; } OP_STATUS OpVCardEntry::Print(OpFileDescriptor* opened_file) { OP_ASSERT(opened_file); const char* preamble = "BEGIN:VCARD\r\nPROFILE:VCARD\r\nVERSION:3.0\r\n"; RETURN_IF_ERROR(opened_file->Write(preamble, op_strlen(preamble))); RETURN_IF_ERROR(OpDirectoryEntry::Print(opened_file)); const char* ending = "END:VCARD\r\n"; return opened_file->Write(ending, op_strlen(ending)); } #endif // DAPI_VCARD_SUPPORT
/* * StorageRepositoryImpl.h * * Created on: Nov 11, 2017 * Author: cis505 */ #ifndef BE_SERVER_STORAGEREPOSITORYIMPL_H_ #define BE_SERVER_STORAGEREPOSITORYIMPL_H_ #include <iostream> #include <memory> #include <queue> #include <string> #include <unordered_map> #include <vector> #include <set> #include "BigTable.h" #include "../common/StorageRepository.grpc.pb.h" #include <grpc++/grpc++.h> #include <grpc++/server_context.h> using grpc::ServerContext; using grpc::Status; using grpc::ServerWriter; using storagerepository::StorageRepository; using storagerepository::FileDTO; using storagerepository::GetFileRequest; using storagerepository::AddFileResponse; using storagerepository::RenameFileRequest; using storagerepository::RenameFileResponse; using storagerepository::MoveFileRequest; using storagerepository::MoveFileResponse; struct filemeta{ int type; // 1 for file, 2 for folder int size; string name; string path; string fuid; string time; }; class StorageRepositoryImpl final : public StorageRepository::Service { public: explicit StorageRepositoryImpl(BigTable* bigTablePtr) { this->bigTablePtr = bigTablePtr; } static vector<filemeta> parseFileList(string user, string folder, vector<string>& unmatched, BigTable* bigTablePtr); static vector<filemeta> deleteFolderHelper(string user, string folder, vector<string>& unmatched, BigTable* bigTablePtr); /* Given username and file identifier(fuid), download one FileDTO */ Status GetFile(ServerContext* context, const GetFileRequest* request, FileDTO* response) override; /* Given username and folder identifier(folder name), download a list of FileDTO */ Status GetFilesByFolder(ServerContext* context, const GetFileRequest* request, ServerWriter<FileDTO>* writer) override; /* Given folder name, return the list of file names under that folder */ Status GetFileList(ServerContext* context, const GetFileRequest* request, ServerWriter<FileDTO>* writer) override; /* Upload file to key-value storage */ Status AddFile(ServerContext* context, const FileDTO* request, AddFileResponse* response) override; /* Delete file from key-value storage */ Status DeleteFile(ServerContext* context, const GetFileRequest* request, AddFileResponse* response) override; /* Add a new folder in filelist */ Status AddFolder(ServerContext* context, const FileDTO* request, AddFileResponse* response) override; /* Delete all files and subfolders in the given folder from key-value storage */ Status DeleteFolder(ServerContext* context, const GetFileRequest* request, AddFileResponse* response) override; /* Rename the file by updating the filelist in key-value storage */ Status RenameFile(ServerContext* context, const RenameFileRequest* request, RenameFileResponse* response) override; /* Move the file to another folder, update the filelist in key-value storage */ Status MoveFile(ServerContext* context, const MoveFileRequest* request, MoveFileResponse* response) override; /* Rename the folder by updating the filelist in key-value storage */ Status RenameFolder(ServerContext* context, const RenameFileRequest* request, RenameFileResponse* response) override; private: BigTable* bigTablePtr; }; struct flistline{ string name; string fuid; }; struct chunkmeta{ int sequence; // sequence num of chunk file, start from 1 string fuid; // uid of the chunk file, used to retrieve chunk file data }; struct compChunk { bool operator()(const chunkmeta& a, const chunkmeta& b) const { return a.sequence < b.sequence; } }; #endif /* BE_SERVER_STORAGEREPOSITORYIMPL_H_ */
// Created on: 1993-03-10 // Created by: JCV // Copyright (c) 1993-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Geom_Parabola_HeaderFile #define _Geom_Parabola_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <Geom_Conic.hxx> #include <Standard_Integer.hxx> class gp_Parab; class gp_Ax2; class gp_Ax1; class gp_Pnt; class gp_Vec; class gp_Trsf; class Geom_Geometry; class Geom_Parabola; DEFINE_STANDARD_HANDLE(Geom_Parabola, Geom_Conic) //! Describes a parabola in 3D space. //! A parabola is defined by its focal length (i.e. the //! distance between its focus and its apex) and is //! positioned in space with a coordinate system //! (gp_Ax2 object) where: //! - the origin is the apex of the parabola, //! - the "X Axis" defines the axis of symmetry; the //! parabola is on the positive side of this axis, //! - the origin, "X Direction" and "Y Direction" define the //! plane of the parabola. //! This coordinate system is the local coordinate //! system of the parabola. //! The "main Direction" of this coordinate system is a //! vector normal to the plane of the parabola. The axis, //! of which the origin and unit vector are respectively the //! origin and "main Direction" of the local coordinate //! system, is termed the "Axis" or "main Axis" of the parabola. //! The "main Direction" of the local coordinate system //! gives an explicit orientation to the parabola, //! determining the direction in which the parameter //! increases along the parabola. //! The Geom_Parabola parabola is parameterized as follows: //! P(U) = O + U*U/(4.*F)*XDir + U*YDir //! where: //! - P is the point of parameter U, //! - O, XDir and YDir are respectively the origin, "X //! Direction" and "Y Direction" of its local coordinate system, //! - F is the focal length of the parabola. //! The parameter of the parabola is therefore its Y //! coordinate in the local coordinate system, with the "X //! Axis" of the local coordinate system defining the origin //! of the parameter. //! The parameter range is ] -infinite, +infinite [. class Geom_Parabola : public Geom_Conic { public: //! Creates a parabola from a non transient one. Standard_EXPORT Geom_Parabola(const gp_Parab& Prb); //! Creates a parabola with its local coordinate system "A2" //! and it's focal length "Focal". //! The XDirection of A2 defines the axis of symmetry of the //! parabola. The YDirection of A2 is parallel to the directrix //! of the parabola. The Location point of A2 is the vertex of //! the parabola //! Raised if Focal < 0.0 Standard_EXPORT Geom_Parabola(const gp_Ax2& A2, const Standard_Real Focal); //! D is the directrix of the parabola and F the focus point. //! The symmetry axis (XAxis) of the parabola is normal to the //! directrix and pass through the focus point F, but its //! location point is the vertex of the parabola. //! The YAxis of the parabola is parallel to D and its location //! point is the vertex of the parabola. The normal to the plane //! of the parabola is the cross product between the XAxis and the //! YAxis. Standard_EXPORT Geom_Parabola(const gp_Ax1& D, const gp_Pnt& F); //! Assigns the value Focal to the focal distance of this parabola. //! Exceptions Standard_ConstructionError if Focal is negative. Standard_EXPORT void SetFocal (const Standard_Real Focal); //! Converts the gp_Parab parabola Prb into this parabola. Standard_EXPORT void SetParab (const gp_Parab& Prb); //! Returns the non transient parabola from gp with the same //! geometric properties as <me>. Standard_EXPORT gp_Parab Parab() const; //! Computes the parameter on the reversed parabola, //! for the point of parameter U on this parabola. //! For a parabola, the returned value is: -U. Standard_EXPORT Standard_Real ReversedParameter (const Standard_Real U) const Standard_OVERRIDE; //! Returns the value of the first or last parameter of this //! parabola. This is, respectively: //! - Standard_Real::RealFirst(), or //! - Standard_Real::RealLast(). Standard_EXPORT Standard_Real FirstParameter() const Standard_OVERRIDE; //! Returns the value of the first or last parameter of this //! parabola. This is, respectively: //! - Standard_Real::RealFirst(), or //! - Standard_Real::RealLast(). Standard_EXPORT Standard_Real LastParameter() const Standard_OVERRIDE; //! Returns False Standard_EXPORT Standard_Boolean IsClosed() const Standard_OVERRIDE; //! Returns False Standard_EXPORT Standard_Boolean IsPeriodic() const Standard_OVERRIDE; //! Computes the directrix of this parabola. //! This is a line normal to the axis of symmetry, in the //! plane of this parabola, located on the negative side //! of its axis of symmetry, at a distance from the apex //! equal to the focal length. //! The directrix is returned as an axis (gp_Ax1 object), //! where the origin is located on the "X Axis" of this parabola. Standard_EXPORT gp_Ax1 Directrix() const; //! Returns 1. (which is the eccentricity of any parabola). Standard_EXPORT Standard_Real Eccentricity() const Standard_OVERRIDE; //! Computes the focus of this parabola. The focus is on the //! positive side of the "X Axis" of the local coordinate //! system of the parabola. Standard_EXPORT gp_Pnt Focus() const; //! Computes the focal distance of this parabola //! The focal distance is the distance between the apex //! and the focus of the parabola. Standard_EXPORT Standard_Real Focal() const; //! Computes the parameter of this parabola which is the //! distance between its focus and its directrix. This //! distance is twice the focal length. //! If P is the parameter of the parabola, the equation of //! the parabola in its local coordinate system is: Y**2 = 2.*P*X. Standard_EXPORT Standard_Real Parameter() const; //! Returns in P the point of parameter U. //! If U = 0 the returned point is the origin of the XAxis and //! the YAxis of the parabola and it is the vertex of the parabola. //! P = S + F * (U * U * XDir + * U * YDir) //! where S is the vertex of the parabola, XDir the XDirection and //! YDir the YDirection of the parabola's local coordinate system. Standard_EXPORT void D0 (const Standard_Real U, gp_Pnt& P) const Standard_OVERRIDE; //! Returns the point P of parameter U and the first derivative V1. Standard_EXPORT void D1 (const Standard_Real U, gp_Pnt& P, gp_Vec& V1) const Standard_OVERRIDE; //! Returns the point P of parameter U, the first and second //! derivatives V1 and V2. Standard_EXPORT void D2 (const Standard_Real U, gp_Pnt& P, gp_Vec& V1, gp_Vec& V2) const Standard_OVERRIDE; //! Returns the point P of parameter U, the first second and third //! derivatives V1 V2 and V3. Standard_EXPORT void D3 (const Standard_Real U, gp_Pnt& P, gp_Vec& V1, gp_Vec& V2, gp_Vec& V3) const Standard_OVERRIDE; //! For the point of parameter U of this parabola, //! computes the vector corresponding to the Nth derivative. //! Exceptions Standard_RangeError if N is less than 1. Standard_EXPORT gp_Vec DN (const Standard_Real U, const Standard_Integer N) const Standard_OVERRIDE; //! Applies the transformation T to this parabola. Standard_EXPORT void Transform (const gp_Trsf& T) Standard_OVERRIDE; //! Returns the parameter on the transformed curve for //! the transform of the point of parameter U on <me>. //! //! me->Transformed(T)->Value(me->TransformedParameter(U,T)) //! //! is the same point as //! //! me->Value(U).Transformed(T) //! //! This methods returns <U> * T.ScaleFactor() Standard_EXPORT Standard_Real TransformedParameter (const Standard_Real U, const gp_Trsf& T) const Standard_OVERRIDE; //! Returns a coefficient to compute the parameter on //! the transformed curve for the transform of the //! point on <me>. //! //! Transformed(T)->Value(U * ParametricTransformation(T)) //! //! is the same point as //! //! Value(U).Transformed(T) //! //! This methods returns T.ScaleFactor() Standard_EXPORT Standard_Real ParametricTransformation (const gp_Trsf& T) const Standard_OVERRIDE; //! Creates a new object which is a copy of this parabola. Standard_EXPORT Handle(Geom_Geometry) Copy() const Standard_OVERRIDE; //! Dumps the content of me into the stream Standard_EXPORT virtual void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const Standard_OVERRIDE; DEFINE_STANDARD_RTTIEXT(Geom_Parabola,Geom_Conic) protected: private: Standard_Real focalLength; }; #endif // _Geom_Parabola_HeaderFile
/* -*- Mode: c++; indent-tabs-mode: nil; c-file-style: "gnu" -*- * * Copyright (C) 1995-2002 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #ifndef XSLT_FOREACH_H #define XSLT_FOREACH_H #ifdef XSLT_SUPPORT #include "modules/xslt/src/xslt_templatecontent.h" #include "modules/xslt/src/xslt_simple.h" #include "modules/xslt/src/xslt_program.h" class XSLT_Sort; class XSLT_ForEach : public XSLT_TemplateContent { protected: XSLT_String select; XSLT_Sort *sort; XSLT_Program program; BOOL compiled; public: XSLT_ForEach (); ~XSLT_ForEach (); XSLT_Sort *AddSort (XSLT_StylesheetParserImpl *parser, XSLT_Sort *sort); virtual void CompileL (XSLT_Compiler *compiler); virtual XSLT_Element *StartElementL (XSLT_StylesheetParserImpl *parser, XSLT_ElementType type, const XMLCompleteNameN &completename, BOOL &ignore_element); virtual void AddAttributeL (XSLT_StylesheetParserImpl *parser, XSLT_AttributeType type, const XMLCompleteNameN &name, const uni_char *value, unsigned value_length); }; #endif // XSLT_SUPPORT #endif // XSLT_FOREACH_H
////////////////////////////////////////////////////////////////////// ///Copyright (C) 2011-2012 Benjamin Quach // //This file is part of the "Lost Horizons" video game demo // //"Lost Horizons" is free software: you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation, either version 3 of the License, or //(at your option) any later version. // //This program is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. // //You should have received a copy of the GNU General Public License //along with this program. If not, see <http://www.gnu.org/licenses/>. // /////////////////////////////////////////////////////////////////////// //Dock Menu //Opens when player is docked at a station #ifndef _DOCKMENU_H_ #define _DOCKMENU_H_ #include "irrlicht.h" #include "player.h" #include "keylistener.h" #include "ship.h" using namespace irr; using namespace gui; using namespace video; using namespace core; class CDockMenu { public: CDockMenu(irr::IrrlichtDevice *graphics, KeyListener *receiver); ~CDockMenu(); void setupTabs(); void setVisible(bool isvisible); void menuLoop(Player *CPlayer,CShip* docked_station); void runMarket(Player *CPlayer,CShip* docked_station); void runRepair(Player *CPlayer); void drop(); void setMenuOpen(bool open) { menu_open=open; } private: bool menu_open; irr::IrrlichtDevice *graphics; KeyListener *receiver; core::dimension2d<s32> t; core::rect<s32> window_size; gui::IGUIElement *control; gui::IGUITabControl *tab_control; gui::IGUITab *market; struct marketTabStruct { gui::IGUIListBox *buying; gui::IGUIStaticText *buy_cost; gui::IGUIStaticText *buy_description; gui::IGUIListBox *selling; gui::IGUIStaticText *sell_cost; gui::IGUIButton *buy_button; bool buy_pressed; gui::IGUIButton *sell_button; bool sell_pressed; gui::IGUIStaticText *player_money; }; marketTabStruct marketTab; std::vector<item*> temp_pri; std::vector<item*> temp_sec; gui::IGUITab *repair; struct repairTabStruct { gui::IGUIButton *repair_hull; gui::IGUIStaticText *repair_hull_price; gui::IGUIButton *repair_armor; gui::IGUIStaticText *repair_armor_price; gui::IGUIComboBox *weapon_primary; gui::IGUIStaticText *primary; gui::IGUIStaticText *primary_description; gui::IGUIComboBox *weapon_secondary; gui::IGUIStaticText *secondary; gui::IGUIStaticText *secondary_description; gui::IGUIComboBox *weapon_light; gui::IGUIStaticText *light; gui::IGUIStaticText *light_description; }; repairTabStruct repairTab; gui::IGUITab *tavern; gui::IGUITab *headquarter; }; #endif
// Copyright (c) 2007-2021 Hartmut Kaiser // Copyright (c) 2013 Agustin Berge // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) /// \file wait_any.hpp #pragma once #if defined(DOXYGEN) namespace pika { /// The function \a wait_any is a non-deterministic choice operator. It /// OR-composes all future objects given and returns after one future of /// that list finishes execution. /// /// \param first [in] The iterator pointing to the first element of a /// sequence of \a future or \a shared_future objects for /// which \a wait_any should wait. /// \param last [in] The iterator pointing to the last element of a /// sequence of \a future or \a shared_future objects for /// which \a wait_any should wait. /// /// \note The function \a wait_any returns after at least one future has /// become ready. All input futures are still valid after \a wait_any /// returns. /// /// \note The function wait_any will rethrow any exceptions /// captured by the futures while becoming ready. If this /// behavior is undesirable, use \a wait_any_nothrow /// instead. /// template <typename InputIter> void wait_any(InputIter first, InputIter last); /// The function \a wait_any is a non-deterministic choice operator. It /// OR-composes all future objects given and returns after one future of /// that list finishes execution. /// /// \param futures [in] A vector holding an arbitrary amount of \a future or /// \a shared_future objects for which \a wait_any should /// wait. /// /// \note The function \a wait_any returns after at least one future has /// become ready. All input futures are still valid after \a wait_any /// returns. /// /// \note The function wait_any will rethrow any exceptions /// captured by the futures while becoming ready. If this /// behavior is undesirable, use \a wait_any_nothrow /// instead. /// template <typename R> void wait_any(std::vector<future<R>>& futures); /// The function \a wait_any is a non-deterministic choice operator. It /// OR-composes all future objects given and returns after one future of /// that list finishes execution. /// /// \param futures [in] Amn array holding an arbitrary amount of \a future or /// \a shared_future objects for which \a wait_any should /// wait. /// /// \note The function \a wait_any returns after at least one future has /// become ready. All input futures are still valid after \a wait_any /// returns. /// /// \note The function wait_any will rethrow any exceptions /// captured by the futures while becoming ready. If this /// behavior is undesirable, use \a wait_any_nothrow /// instead. /// template <typename R, std::size_t N> void wait_any(std::array<future<R>, N>& futures); /// The function \a wait_any is a non-deterministic choice operator. It /// OR-composes all future objects given and returns after one future of /// that list finishes execution. /// /// \param futures [in] An arbitrary number of \a future or \a shared_future /// objects, possibly holding different types for which /// \a wait_any should wait. /// /// \note The function \a wait_any returns after at least one future has /// become ready. All input futures are still valid after \a wait_any /// returns. /// /// \note The function wait_any will rethrow any exceptions /// captured by the futures while becoming ready. If this /// behavior is undesirable, use \a wait_any_nothrow /// instead. /// template <typename... T> void wait_any(T&&... futures); /// The function \a wait_any_n is a non-deterministic choice operator. It /// OR-composes all future objects given and returns after one future of /// that list finishes execution. /// /// \param first [in] The iterator pointing to the first element of a /// sequence of \a future or \a shared_future objects for /// which \a wait_any_n should wait. /// \param count [in] The number of elements in the sequence starting at /// \a first. /// /// \note The function \a wait_any_n returns after at least one future has /// become ready. All input futures are still valid after \a wait_any_n /// returns. /// /// \note The function wait_any_n will rethrow any exceptions /// captured by the futures while becoming ready. If this /// behavior is undesirable, use \a wait_any_n_nothrow /// instead. /// template <typename InputIter> void wait_any_n(InputIter first, std::size_t count); } // namespace pika #else // DOXYGEN # include <pika/config.hpp> # include <pika/async_combinators/wait_some.hpp> # include <pika/futures/future.hpp> # include <pika/iterator_support/traits/is_iterator.hpp> # include <pika/preprocessor/strip_parens.hpp> # include <array> # include <cstddef> # include <tuple> # include <utility> # include <vector> /////////////////////////////////////////////////////////////////////////////// namespace pika { /////////////////////////////////////////////////////////////////////////// template <typename Future> void wait_any_nothrow(std::vector<Future> const& futures) { pika::wait_some_nothrow(1, futures); } template <typename Future> void wait_any(std::vector<Future> const& futures) { pika::wait_some(1, futures); } template <typename Future> void wait_any_nothrow(std::vector<Future>& lazy_values) { pika::wait_any_nothrow(const_cast<std::vector<Future> const&>(lazy_values)); } template <typename Future> void wait_any(std::vector<Future>& lazy_values) { pika::wait_any(const_cast<std::vector<Future> const&>(lazy_values)); } template <typename Future> void wait_any_nothrow(std::vector<Future>&& lazy_values) { pika::wait_any_nothrow(const_cast<std::vector<Future> const&>(lazy_values)); } template <typename Future> void wait_any(std::vector<Future>&& lazy_values) { pika::wait_any(const_cast<std::vector<Future> const&>(lazy_values)); } /////////////////////////////////////////////////////////////////////////// template <typename Future, std::size_t N> void wait_any_nothrow(std::array<Future, N> const& futures) { pika::wait_some_nothrow(1, futures); } template <typename Future, std::size_t N> void wait_any(std::array<Future, N> const& futures) { pika::wait_some(1, futures); } template <typename Future, std::size_t N> void wait_any_nothrow(std::array<Future, N>& lazy_values) { pika::wait_any_nothrow(const_cast<std::array<Future, N> const&>(lazy_values)); } template <typename Future, std::size_t N> void wait_any(std::array<Future, N>& lazy_values) { pika::wait_any(const_cast<std::array<Future, N> const&>(lazy_values)); } template <typename Future, std::size_t N> void wait_any_nothrow(std::array<Future, N>&& lazy_values) { pika::wait_any_nothrow(const_cast<std::array<Future, N> const&>(lazy_values)); } template <typename Future, std::size_t N> void wait_any(std::array<Future, N>&& lazy_values) { pika::wait_any(const_cast<std::array<Future, N> const&>(lazy_values)); } /////////////////////////////////////////////////////////////////////////// template <typename Iterator, typename Enable = std::enable_if_t<pika::traits::is_iterator_v<Iterator>>> void wait_any_nothrow(Iterator begin, Iterator end) { pika::wait_some_nothrow(1, begin, end); } template <typename Iterator, typename Enable = std::enable_if_t<pika::traits::is_iterator_v<Iterator>>> void wait_any(Iterator begin, Iterator end) { pika::wait_some(1, begin, end); } inline void wait_any_nothrow() { pika::wait_some_nothrow(1); } inline void wait_any() { pika::wait_some(1); } /////////////////////////////////////////////////////////////////////////// template <typename Iterator, typename Enable = std::enable_if_t<pika::traits::is_iterator_v<Iterator>>> void wait_any_n_nothrow(Iterator begin, std::size_t count) { pika::wait_some_n_nothrow(1, begin, count); } template <typename Iterator, typename Enable = std::enable_if_t<pika::traits::is_iterator_v<Iterator>>> void wait_any_n(Iterator begin, std::size_t count) { pika::wait_some_n(1, begin, count); } /////////////////////////////////////////////////////////////////////////// template <typename... Ts> void wait_any_nothrow(Ts&&... ts) { pika::wait_some_nothrow(1, PIKA_FORWARD(Ts, ts)...); } template <typename... Ts> void wait_any(Ts&&... ts) { pika::wait_some(1, PIKA_FORWARD(Ts, ts)...); } } // namespace pika #endif // DOXYGEN
#include <ros/ros.h> #include <tf/tf.h> #include <moveit/move_group_interface/move_group.h> #include <geometry_msgs/PoseStamped.h> #include <moveit_msgs/AttachedCollisionObject.h> #include <moveit_msgs/CollisionObject.h> #include <moveit_msgs/Grasp.h> #include <moveit_msgs/DisplayTrajectory.h> #include <visualization_msgs/Marker.h> #include <visualization_msgs/MarkerArray.h> #include <moveit/move_group_interface/move_group.h> #include <moveit/planning_scene_interface/planning_scene_interface.h> #include <moveit_msgs/DisplayRobotState.h> #include <moveit_msgs/DisplayTrajectory.h> #include <shape_tools/solid_primitive_dims.h> int main(int argc, char** argv) { ros::init(argc,argv,"katana_test"); ros::NodeHandle nh; moveit::planning_interface::PlanningSceneInterface planning_scene_interface; ros::Publisher display_publisher = nh.advertise<moveit_msgs::DisplayTrajectory>("/move_group/display_planned_path", 1, true); moveit_msgs::DisplayTrajectory display_trajectory; ros::AsyncSpinner spinner(1); spinner.start(); geometry_msgs::PoseStamped p1; p1.header.stamp = ros::Time::now(); p1.header.frame_id = "base_link"; p1.pose.orientation.w = 1.0; p1.pose.position.x = 0.5; p1.pose.position.y = 0.0; p1.pose.position.z = 0.8; geometry_msgs::PoseStamped p2; p2.header.stamp = ros::Time::now(); p2.header.frame_id = "base_link"; p2.pose.orientation.w = 1.0; p2.pose.position.x = 0.45; p2.pose.position.y = 0.2; p2.pose.position.z = 0.6; moveit::planning_interface::MoveGroup katana("manipulator"); katana.setNamedTarget("home"); katana.move(); geometry_msgs::Point p; p.x = 0.4; p.y = 0.25; p.z = 0.85; /* katana.setPositionTarget(p.x,p.y,p.z,"katana_gripper_tool_frame"); std::vector<double> currJoints = katana.getCurrentJointValues(); std::vector<std::string> jointNames = katana.getActiveJoints(); for(int i = 0; i < currJoints.size(); i++) { katana.setJointValueTarget(jointNames[i],currJoints[i]); } katana.setJointValueTarget("katana_motor5_wrist_roll_joint",1.57); katana.move(); currJoints = katana.getCurrentJointValues(); jointNames = katana.getActiveJoints(); for(int i = 0; i < currJoints.size(); i++) { katana.setJointValueTarget(jointNames[i],currJoints[i]); } katana.setJointValueTarget("katana_motor5_wrist_roll_joint",1.57); katana.setJointValueTarget("katana_motor1_pan_joint",1.57); katana.move(); ros::Duration(2.0).sleep(); katana.setJointValueTarget("katana_motor1_pan_joint",1.57); katana.move(); ros::Duration(2.0).sleep(); katana.setJointValueTarget("katana_motor1_pan_joint",-1.57); katana.move(); ros::Duration(2.0).sleep(); katana.setPositionTarget(p.x,p.y,p.z,"katana_gripper_tool_frame"); katana.move(); ros::Duration(2.0).sleep(); katana.setPlanningTime(45.0); tf::Quaternion q; geometry_msgs::Quaternion q2; geometry_msgs::Pose pose; q = tf::createQuaternionFromRPY(0.0,0.0,0.0); tf::quaternionTFToMsg(q,q2); pose.position = p; pose.orientation = q2; std::cout << "test"; katana.setPoseTarget(pose,"katana_gripper_tool_frame"); //katana.move(); std::vector<double> rpy = katana.getCurrentRPY(); for(int i = 0; i < rpy.size(); i++) { ROS_INFO("%f",rpy[i]); } katana.setPositionTarget(p.x,p.y,p.z,"katana_gripper_tool_frame"); katana.move(); rpy = katana.getCurrentRPY(); for(int i = 0; i < rpy.size(); i++) { ROS_INFO("%f",rpy[i]); } */ katana.allowReplanning(true); katana.setPositionTarget(0.3,0.4,0.9,katana.getEndEffectorLink()); katana.move(); std::vector<geometry_msgs::Pose> waypoints; geometry_msgs::Pose pose = katana.getCurrentPose(katana.getEndEffectorLink()).pose; pose.position.x += 0.05; pose.position.y += 0.1; waypoints.push_back(pose); pose.position.x -= 0.1; pose.position.y -= 0.2; waypoints.push_back(pose); moveit_msgs::RobotTrajectory trajectory; double frac = katana.computeCartesianPath(waypoints, 0.01, 0.0 ,trajectory); ros::spin(); }
// resolution de la cam : 128 x 96 pixels // angles de detection theoriques: 33 horizontal, 23 vertical // couleurs fils : rouge = +5V, noir = GROUND, vert = SCL, jaune = SDA // champ de vision horizontal 37.5° // champ de vision vertical 29° #include <Wire.h> int IRsensorAddress = 0xB0; //int IRsensorAddress = 0x58; int slaveAddress; int i; unsigned long time; double a, b, c, delta, result1, result2; int Ix[4]; int Iy[4]; double x1, x2, x3, x4, x5, x6, x7, y1, y2, y3, y4, y5, y6, y7; int angles[4][2]; double u, v; void Write_2bytes(byte d1, byte d2) //1er octet = adresse, 2eme octet = valeur { Wire.beginTransmission(slaveAddress); Wire.write(d1); delay(100); Wire.write(d2); Wire.endTransmission(); } void reading(int slaveAddress, int *Ix, int *Iy) //IR sensor read { byte data_buf[12]; int i; int s; Wire.beginTransmission(slaveAddress); Wire.write(0x37); //we select the adress where we want to begin to read the data Wire.endTransmission(); Wire.requestFrom(slaveAddress, 12); //requesting 12 bytes from the camera (MSB comes first) i = 0; while (Wire.available() && i < 12) { data_buf[i] = Wire.read(); i++; } Ix[0] = data_buf[0]; Iy[0] = data_buf[1]; s = data_buf[2]; Ix[0] += (s & 0x30) << 4; Iy[0] += (s & 0xC0) << 2; Ix[1] = data_buf[3]; Iy[1] = data_buf[4]; s = data_buf[5]; Ix[1] += (s & 0x30) << 4; Iy[1] += (s & 0xC0) << 2; Ix[2] = data_buf[6]; Iy[2] = data_buf[7]; s = data_buf[8]; Ix[2] += (s & 0x30) << 4; Iy[2] += (s & 0xC0) << 2; Ix[3] = data_buf[9]; Iy[3] = data_buf[10]; s = data_buf[11]; Ix[3] += (s & 0x30) << 4; Iy[3] += (s & 0xC0) << 2; delay(10); } void setup() { slaveAddress = IRsensorAddress >> 1; // This results in 0x21 as the address to pass to TWI Serial.begin(9600); Wire.begin(); // IR sensor initialize Write_2bytes(0x30, 0x01); delay(100); //control byte, allows modification of settings Write_2bytes(0x06, 0x90); delay(100); //sensitivity block 1, max blob size E [0x62-0xC8] Write_2bytes(0x08, 0x41); delay(100); //sensitivity block 1, sensor gain, smaller values = higher gain Write_2bytes(0x1A, 0x40); delay(100); //sensitivity block 2, sensor gain limit, must be less than gain for camera to function Write_2bytes(0x1B, 0x03); delay(100); //sensitivity block 2, min blob size, Wii uses values from 3 to 5 Write_2bytes(0x33, 0x03); delay(100); //mode number (1=basic, 3=extended, 5=full) Write_2bytes(0x30, 0x08); delay(100); //control byte, reenable operation delay(100); // Calibration : //face camera : 0 = haut droite, 1 = haut gauche, 2 = bas gauche, 3 = bas droite i = 0; Serial.print("Angle "); Serial.println(i); while (true) { reading(slaveAddress, Ix, Iy); if (Ix[0] != 1023) { Ix[0] = 1023 - Ix[0]; angles[i][0] = Ix[0]; angles[i][1] = Iy[0]; Serial.print("Ok : ("); Serial.print(angles[i][0]); Serial.print(","); Serial.print(angles[i][1]); Serial.println(")"); Serial.println(); i += 1; if (i == 4) { break; } delay(2000); Serial.print("Angle "); Serial.println(i); } } x1 = angles[0][0]; x2 = angles[1][0]; x3 = angles[2][0]; x4 = angles[3][0]; y1 = angles[0][1]; y2 = angles[1][1]; y3 = angles[2][1]; y4 = angles[3][1]; Serial.println("Calibration finie"); } void loop() { reading(slaveAddress, Ix, Iy); i = 0; Ix[i] = 1023 - Ix[i]; if (Ix[i] != 0) { x5 = Ix[i]; y5 = Iy[i]; a = x1 * (y3 - y4) - x2 * (y3 - y4) - (x3 - x4) * (y1 - y2); b = -x1 * (y3 - 2 * y4 + y5) - x2 * (y4 - y5) + x3 * (y1 - y5) + x4 * (-2 * y1 + y2 + y5) + x5 * (y1 - y2 + y3 - y4); c = -x1 * (y4 - y5) + x4 * (y1 - y5) - x5 * (y1 - y4); delta = pow(b, 2) - 4 * a * c; if (delta == 0) { result1 = result2 = (-b) / (2 * a); } else if (delta > 0) { delta = sqrt(delta); result1 = (-b + delta) / (2 * a); result2 = (-b - delta) / (2 * a); } else { } u = abs(result2); x6 = x4 + u * (x3 - x4); y6 = y4 + u * (y3 - y4); x7 = x1 + u * (x2 - x1); y7 = y1 + u * (y2 - y1); if (abs(x7 - x6) > abs(y7 - y6)) { v = abs(x5 - x7) / abs(x6 - x7); } else { v = abs(y5 - y7) / abs(y6 - y7); } Serial.print( u ); Serial.print(","); Serial.print( v ); Serial.println(","); } else { u = -1; v = -1; } //delay(10); }
/* -*-C++-*- */ /* * Copyright 2016 EU Project ASAP 619706. * * 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. */ #ifndef INCLUDED_ASAP_DENSE_VECTOR_H #define INCLUDED_ASAP_DENSE_VECTOR_H #include <iostream> #include <memory> #include <type_traits> #include <limits> #include <cilk/cilk.h> #include <cilk/reducer.h> #include "asap/traits.h" #include "asap/vector_ops.h" #include "asap/memory.h" namespace asap { /** @brief A dense vector * * @tparam IndexTy The type used to index the vector, typically an integer type * @tparam ValueTy The type of the elements stored in the vector * @tparam IsVectorized Whether to use vector (SIMD) operations * @tparam MemoryMgmt Whether vectors own the associated heap memory * @tparam Allocator The memory allocator used by this class */ template<typename IndexTy, typename ValueTy, bool IsVectorized, typename MemoryMgmt = mm_ownership_policy, typename Allocator = std::allocator<ValueTy>> class dense_vector { public: /** Whether to use vector (SIMD) operations */ static const bool is_vectorized = IsVectorized; /** The type used to index the vector, typically an integer type */ typedef IndexTy index_type; /** The type of the elements stored in the vector */ typedef ValueTy value_type; /** Whether vectors own the associated heap memory */ typedef MemoryMgmt memory_mgmt_type; /** The memory allocator used by this class */ typedef Allocator allocator_type; /** The class holding the vector operations for this class */ typedef dense_vector_operations<index_type, value_type, is_vectorized> vector_ops; /** A tag class describing the characteristics of this class */ struct _asap_tag : tag_dense, tag_vector { }; /** A dummy method definition to implement type inspection */ void asap_decl(void); private: /** Pointer to a dense array of values */ value_type *m_value; /** The length of the vector */ index_type m_length; private: /** The default constructor is disabled. * @details Length cannot be changed for a vector */ dense_vector() = delete; // : m_value(nullptr), m_length(0) { } public: /** Constructor for an empty vector with specified length. * * @details * Disallow this constructor in case vector does not do its own * memory management. * * @tparam MMT Whether the vector owns the heap memory * @param length_ The length of the vector */ template<typename MMT = memory_mgmt_type, typename = typename std::enable_if< std::is_same<MMT, memory_mgmt_type>::value && MMT::has_ownership>::type> dense_vector(index_type length_) : m_length(length_) { if( memory_mgmt_type::allocate ) m_value = allocator_type().allocate( m_length ); else m_value = nullptr; } /** Assignment constructor * * @param value_ An array of values * @param length_ The length of the vector */ dense_vector(value_type *value_, index_type length_) : m_length(length_) { if( memory_mgmt_type::assign ) { m_value = allocator_type().allocate( m_length ); vector_ops::copy( value_, length_, m_value ); } else m_value = value_; } /** Move constructor * * @param pt The dense vector to move */ dense_vector(dense_vector &&pt) : m_length( pt.m_length ) { if( memory_mgmt_type::assign_rvalue ) { m_value = allocator_type().allocate( m_length ); vector_ops::copy( pt.m_value, pt.m_length, m_value ); } else { m_value = pt.m_value; pt.m_value = nullptr; // necessary? } } /** Copy constructor * * @param pt The dense vector to copy */ dense_vector(const dense_vector &pt) : m_length( pt.m_length ) { if( memory_mgmt_type::assign ) { m_value = allocator_type().allocate( m_length ); vector_ops::copy( pt.m_value, pt.m_length, m_value ); } else m_value = pt.m_value; } /** Destructor */ ~dense_vector() { if( m_value && memory_mgmt_type::deallocate ) allocator_type().deallocate( m_value, m_length ); } /** Copy-assignment operator */ dense_vector & operator = ( const dense_vector & dv ) { // Cleanup if( m_value && memory_mgmt_type::deallocate ) allocator_type().deallocate( m_value, m_length ); // New value m_length = dv.m_length; if( memory_mgmt_type::assign ) { m_value = allocator_type().allocate( m_length ); vector_ops::copy( dv.m_value, dv.m_length, m_value ); } else m_value = dv.m_value; return *this; } /** Move-assignment operator */ dense_vector & operator = ( dense_vector && dv ) { if( m_value && memory_mgmt_type::deallocate ) allocator_type().deallocate( m_value, m_length ); m_value = std::move(dv.m_value); dv.m_value = 0; m_length = std::move(dv.m_length); dv.m_length = 0; return *this; } /** Return the length of the vector */ index_type length() const { return m_length; } /** Return the dense array of values */ const value_type * get_value() const { return m_value; } /** Return a reference to specific element */ value_type & operator[]( index_type idx ) { return m_value[idx]; // unchecked } /** Return a specific element * @details Assuming trivial types, copy is better than by reference */ value_type operator[]( index_type idx ) const { return m_value[idx]; // unchecked } /** Apply a functor to every element of the vector * @param fn Functor to apply. Takes two arguments: the index and the value */ template<typename Fn> void map( Fn & fn ) { for( index_type i=0; i < m_length; ++i ) fn( i, m_value[i] ); } /** Normalize, i.e., scale by length of vector */ void normalize(value_type n) { vector_ops::scale( m_value, m_length, value_type(1)/n ); } /** Scale by the specific value */ void scale(value_type alpha) { vector_ops::scale( m_value, m_length, alpha ); } /** Set all elements to zero */ void clear() { vector_ops::set( m_value, m_length, value_type(0) ); clear_attributes(); } /** Clear the attributes of the vector (generic function) */ void clear_attributes() { } /** Return the square of Euclidean distance to another dense vector * with elements of the same type */ template<typename OtherVectorTy> typename std::enable_if<is_dense_vector<OtherVectorTy>::value, value_type>::type sq_dist(OtherVectorTy const& p) const { return vector_ops::square_euclidean_distance( m_value, m_length, p.get_value() ); } /** Return the square of Euclidean distance of the vector to itself */ value_type sq_norm() const { return vector_ops::square_norm( m_value, m_length ); } /** Element-wise vector addition with vector of same type * Used in reduction of centre computations */ template<typename OtherVectorTy> const typename std::enable_if<is_dense_vector<OtherVectorTy>::value, dense_vector>::type & operator += ( const OtherVectorTy & pt ) { vector_ops::add( m_value, m_length, pt.get_value() ); return *this; } /** Element-wise vector addition with sparse vector of same-type elements */ template<typename OtherVectorTy> const typename std::enable_if<is_sparse_vector<OtherVectorTy>::value, dense_vector>::type & operator += ( const OtherVectorTy & pt ) { for(int j = 0; j < pt.nonzeros(); j++) { value_type v; index_type c; pt.get( j, v, c ); m_value[c] += v; } return *this; } /** Copy vector attributes, if any */ template<typename OtherVectorTy> typename std::enable_if<is_dense_vector<OtherVectorTy>::value>::type copy_attributes( const OtherVectorTy & pt ) { } }; /** @brief A set of dense vectors. * * @detail * A dense vector set with memory allocation optimized such that memory * is allocated only once for all vectors. This requires the use of * dense vectors without ownership of the vector data. * * @tparam VectorTy The type of dense vectors stored */ template<typename VectorTy> class dense_vector_set { public: typedef typename VectorTy::index_type index_type; typedef typename VectorTy::value_type value_type; typedef typename VectorTy::memory_mgmt_type memory_mgmt_type; typedef typename VectorTy::allocator_type allocator_type; typedef VectorTy vector_type; typedef const vector_type * const_iterator; typedef vector_type * iterator; protected: vector_type *m_vectors; value_type *m_alloc; size_t m_number; size_t m_length; public: // Constructor intended only for use by reducers dense_vector_set() : m_vectors(nullptr), m_alloc(nullptr), m_number(0), m_length(0) { static_assert( is_dense_vector<VectorTy>::value, "vector_type must be dense" ); static_assert( !memory_mgmt_type::has_ownership, "vector_type must not have data ownership" ); } // Proper constructor dense_vector_set(size_t number, size_t length) : m_number(number), m_length( length ) { size_t aligned_length = length; // TODO: round up to SIMD vector length // and guarantee alignment m_alloc = allocator_type().allocate( m_number*aligned_length ); typename allocator_type::template rebind<vector_type>:: other dv_alloc; m_vectors = dv_alloc.allocate( m_number ); value_type *p = m_alloc; for( size_t i=0; i < m_number; ++i ) { dv_alloc.construct( &m_vectors[i], p, length ); p += aligned_length; } } dense_vector_set(const dense_vector_set & dvs) : dense_vector_set(dvs.m_number, dvs.m_vectors ? dvs.m_vectors[0].length() : 0) { std::cerr << "DVS copy construct\n"; assert( m_length == dvs.m_length ); for( size_t i=0; i < m_number; ++i ) m_vectors[i].copy_attributes( dvs.m_vectors[i] ); size_t aligned_length = m_length; // TODO std::copy( &dvs.m_alloc[0], &dvs.m_alloc[m_number*aligned_length], &m_alloc[0] ); } dense_vector_set(dense_vector_set && dvs) : m_vectors(dvs.m_vectors), m_alloc(dvs.m_alloc), m_number(dvs.m_number), m_length(dvs.m_length) { std::cerr << "DVS move construct\n"; dvs.m_vectors = 0; dvs.m_alloc = 0; dvs.m_number = 0; dvs.m_length = 0; } ~dense_vector_set() { typename allocator_type::template rebind<vector_type>:: other dv_alloc; for( size_t i=0; i < m_number; ++i ) dv_alloc.destroy( &m_vectors[i] ); dv_alloc.deallocate( m_vectors, m_number ); size_t aligned_length = m_length; // TODO allocator_type().deallocate( m_alloc, m_number*aligned_length ); } bool check_init( size_t number, size_t length ) { if( m_vectors == nullptr ) { new (this) dense_vector_set( number, length ); // initialize return true; } else return false; } void swap( dense_vector_set & dvs ) { std::swap( m_vectors, dvs.m_vectors ); std::swap( m_alloc, dvs.m_alloc ); std::swap( m_number, dvs.m_number ); std::swap( m_length, dvs.m_length ); } size_t number() const { return m_number; } size_t size() const { return m_number; } size_t length() const { return m_length; } void trim_number( size_t n ) { if( n < m_number ) m_number = n; } void fill( value_type val ) { size_t aligned_length = m_length; // TODO std::fill( &m_alloc[0], &m_alloc[m_number*aligned_length], val ); } void clear() { size_t aligned_length = m_length; // TODO // TODO: vectorize std::fill( &m_alloc[0], &m_alloc[m_number*aligned_length], value_type(0) ); for( size_t i=0; i < m_number; ++i ) m_vectors[i].clear_attributes(); } const vector_type & operator[] ( size_t idx ) const { return m_vectors[idx]; } vector_type & operator[] ( size_t idx ) { return m_vectors[idx]; } iterator begin() { return &m_vectors[0]; } iterator end() { return &m_vectors[m_number]; } const_iterator cbegin() const { return &m_vectors[0]; } const_iterator cend() const { return &m_vectors[m_number]; } dense_vector_set & operator += ( const dense_vector_set & dvs ) { assert( m_number == dvs.m_number ); assert( m_length == dvs.m_length ); for( size_t i=0; i < m_number; ++i ) m_vectors[i] += dvs.m_vectors[i]; return *this; } }; template<typename VectorTy> typename std::enable_if<asap::is_dense_vector<VectorTy>::value, std::ostream &>::type & operator << ( std::ostream & os, const VectorTy & dv ) { os << '{'; for( int i=0, e=dv.length(); i != e; ++i ) { os << dv[i]; if( i+1 < e ) os << ", "; } os << '}'; return os; } template<typename VectorTy> typename std::enable_if<asap::is_sparse_vector<VectorTy>::value, std::ostream &>::type operator << ( std::ostream & os, const VectorTy & sv ) { os << '{'; for( int i=0, e=sv.nonzeros(); i != e; ++i ) { typename VectorTy::value_type v; typename VectorTy::index_type c; sv.get( i, v, c ); os << c << " " << v; if( i+1 < e ) os << ", "; } os << '}'; return os; } } #endif // INCLUDED_ASAP_DENSE_VECTOR_H
/* XMRig * Copyright 2010 Jeff Garzik <jgarzik@pobox.com> * Copyright 2012-2014 pooler <pooler@litecoinpool.org> * Copyright 2014 Lucas Jones <https://github.com/lucasjones> * Copyright 2014-2016 Wolf9466 <https://github.com/OhGodAPet> * Copyright 2016 Jay D Dee <jayddee246@gmail.com> * Copyright 2017-2018 XMR-Stak <https://github.com/fireice-uk>, <https://github.com/psychocrypt> * Copyright 2018-2021 SChernykh <https://github.com/SChernykh> * Copyright 2016-2021 XMRig <https://github.com/xmrig>, <support@xmrig.com> * * 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 * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef XMRIG_POOLS_H #define XMRIG_POOLS_H #include <vector> #include "base/net/stratum/Pool.h" namespace xmrig { class IJsonReader; class IStrategy; class IStrategyListener; class Pools { public: static const char *kDonateLevel; static const char *kDonateOverProxy; static const char *kPools; static const char *kRetries; static const char *kRetryPause; enum ProxyDonate { PROXY_DONATE_NONE, PROXY_DONATE_AUTO, PROXY_DONATE_ALWAYS }; Pools(); # ifdef XMRIG_FEATURE_BENCHMARK inline bool isBenchmark() const { return !!m_benchmark; } # else inline constexpr bool isBenchmark() const { return false; } # endif inline const std::vector<Pool> &data() const { return m_data; } inline int retries() const { return m_retries; } inline int retryPause() const { return m_retryPause; } inline ProxyDonate proxyDonate() const { return m_proxyDonate; } inline bool operator!=(const Pools &other) const { return !isEqual(other); } inline bool operator==(const Pools &other) const { return isEqual(other); } bool isEqual(const Pools &other) const; int donateLevel() const; IStrategy *createStrategy(IStrategyListener *listener) const; rapidjson::Value toJSON(rapidjson::Document &doc) const; size_t active() const; uint32_t benchSize() const; void load(const IJsonReader &reader); void print() const; void toJSON(rapidjson::Value &out, rapidjson::Document &doc) const; private: void setDonateLevel(int level); void setProxyDonate(int value); void setRetries(int retries); void setRetryPause(int retryPause); int m_donateLevel; int m_retries = 5; int m_retryPause = 5; ProxyDonate m_proxyDonate = PROXY_DONATE_AUTO; std::vector<Pool> m_data; # ifdef XMRIG_FEATURE_BENCHMARK std::shared_ptr<BenchConfig> m_benchmark; # endif }; } /* namespace xmrig */ #endif /* XMRIG_POOLS_H */
#ifndef CONTAINER_H #define CONTAINER_H #include "object.h" class Container:protected Object { public: friend std::ostream& operator<<(std::ostream& out, const Container& plant); //Перегрузка оператора вывода friend std::istream& operator>>(std::istream& in, const Container& plant); //Перегрузка оператора ввода Container();//Конструктор бы сделать int getid(); bool getmaterial(bool a); int getcoordx(); int getcoordy(); void setid(int id); void setx(int x); void sety(int y); void setmat_metal(bool a); void setmat_organic(bool a); void setmat_glass(bool a); void setmat_plastic(bool a); void setmat_paper(bool a); }; #endif // CONTAINER_H
// Q 19 #include"stdio.h" #include"conio.h" void main(void) { int a,b,c,d,e,f,g; clrscr(); printf("Step 1 -> "); for(a=1; a<=10; a++) { b=a*a; printf("%d ",b); } printf("\n\nStep 2 -> "); for(c=1; c<=10; c++) { d=c*c; printf("%d+",d); } printf("\n\nAverage = Sum of No's / Total Numbers"); for(e=1; e<=10; e+=2) f+=e; g=f/10; printf("\n\nAv = %d / 10 = %d",f,g); getch(); }
#include<fstream> #include<string.h> #include<ctype.h> #include<iostream> #include<algorithm> #include<map> #include<unordered_map> #include<array> #include<deque> #include<unordered_set> using namespace std; int n, i, min1, n1, n2; char c1, c2; vector <int> vec; vector <int> ::iterator it; int main() { cin >> n; cin >> c1; // Read the first character. for (i = 2; i <= n; i++) { cin >> c2; if (c1 == 'R'&&c2 == 'L') vec.push_back(i); // We keep in the vec all the positions where we have one R next to an L. c1 = c2; } cin >> n1; // Read the first number. if (vec.size() != 0) { it = vec.begin(); min1 = 1 << 30; // In min1 we will store the minimum distance between a pair of particles RL. for (i = 2; i <= n; i++) { cin >> n2; if (*it == i) // If our current element is in the vector, that means the two numbers belong to one RL pair that we need to check for minimum. { if (min1 > (n2 - n1) / 2) // We need to divide by 2 because both particles will be moving towards each-other with the same speed so they will meet halfway everytime. min1 = (n2 - n1) / 2; if (it != vec.end() - 1) // If we still have pairs of RL in the vector, we increase the iterator. it++; } n1 = n2; } cout << min1; } else cout << -1; // If the vector is empty, that means that there are no RL pairs which means no 2 particles will ever collide, therefore printing -1. return 0; }
/* Crayfish - A collection of tools for TUFLOW and other hydraulic modelling packages Copyright (C) 2016 Lutra Consulting info at lutraconsulting dot co dot uk Lutra Consulting 23 Chestnut Close Burgess Hill West Sussex RH15 8HN 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. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef CRAYFISH_H #define CRAYFISH_H #include <QString> #include "crayfish_mesh.h" //class Mesh; class DataSet; struct LoadStatus { LoadStatus() { clear(); } void clear() { mLastError = Err_None; mLastWarning = Warn_None; } enum Error { Err_None, Err_NotEnoughMemory, Err_FileNotFound, Err_UnknownFormat, Err_IncompatibleMesh, Err_InvalidData, Err_MissingDriver }; enum Warning { Warn_None, Warn_UnsupportedElement, Warn_InvalidElements, Warn_ElementWithInvalidNode, Warn_ElementNotUnique, Warn_NodeNotUnique }; Error mLastError; Warning mLastWarning; }; class Crayfish { public: //Crayfish(); static Mesh* loadMesh(const QString& meshFile, LoadStatus* status = 0); static Mesh::DataSets loadDataSet(const QString& fileName, const Mesh* mesh, LoadStatus* status = 0); static bool exportRawDataToTIF(const Output* output, double mupp, const QString& outFilename, const QString& projWkt); protected: static Mesh* loadSWW(const QString& fileName, LoadStatus* status = 0); static Mesh* loadGRIB(const QString& fileName, LoadStatus* status = 0); static Mesh* loadMesh2DM(const QString& fileName, LoadStatus* status = 0); static Mesh* loadHec2D(const QString& fileName, LoadStatus* status = 0); static Mesh* loadNetCDF(const QString& fileName, LoadStatus* status = 0); static Mesh* loadSerafin(const QString& fileName, LoadStatus* status = 0); static Mesh::DataSets loadBinaryDataSet(const QString& datFileName, const Mesh* mesh, LoadStatus* status = 0); static Mesh::DataSets loadAsciiDataSet(const QString& fileName, const Mesh* mesh, LoadStatus* status = 0); static Mesh::DataSets loadXmdfDataSet(const QString& datFileName, const Mesh* mesh, LoadStatus* status = 0); }; #endif // CRAYFISH_H
#ifndef __SORTS_CPP #define __SORTS_CPP #include "sorts.h" //===================================================================================== vector<long> InsertionSort(vector<long> nums) { int size = nums.size(); long numbers[size]; for (int i = 0; i < size; i++) { numbers[i] = nums[i]; } for (int i = 0; i < size; i++) { int j = i; while (j > 0 && numbers[j-1] > numbers[j]) { long temp = numbers[j-1]; numbers[j-1] = numbers[j]; numbers[j] = temp; j--; } } vector<long> result; for (int i = 0; i < size; i++) { result.push_back(numbers[i]); } return result; } //===================================================================================== vector<long> MergeSort(vector<long> nums) { List<long> numbers; int len = nums.size(); for (int i = 0; i < len; i++) { numbers.insertAtTail(nums[i]); } List<long> sorted_list = mergeSort(numbers); vector<long> result; ListItem<long> *ptr = sorted_list.getHead(); while (ptr != NULL) { result.push_back(ptr->value); ptr = ptr->next; } return result; } /* Merge Sort Helper Functions */ //===================================================================================== List<long> mergeSort(List<long> sort_list) { if (sort_list.length() == 0 || sort_list.length() == 1) { return sort_list; } else { ListItem<long> *left, *right; // Split List // ListItem<long> *ptr = sort_list.getHead(); left = ptr; for (int i = 0; i < (sort_list.length() / 2) -1 ; i++) { ptr = ptr->next; } right = ptr->next; ptr->next = NULL; // ......... // List<long> left_list, right_list; left_list.head = left; right_list.head = right; return merger(mergeSort(left_list), mergeSort(right_list)); } } List<long> merger(List<long> left, List<long> right) { List<long> temp; ListItem<long> *ptr1 = left.getHead(); while (ptr1 != NULL) { temp.insertSorted(ptr1->value); ptr1 = ptr1->next; } ptr1 = right.getHead(); while (ptr1 != NULL) { temp.insertSorted(ptr1->value); ptr1 = ptr1->next; } return temp; } //===================================================================================== vector<long> QuickSortArray(vector<long> nums) { int size = nums.size(); long numbers[size]; for (int i = 0; i < size; i++) { numbers[i] = nums[i]; } long *sorted_numbers = quickSortArray(numbers, size); vector<long> result; for (int i = 0; i < size; i++) { result.push_back(sorted_numbers[i]); } return result; } // ====================================================================================// long *quickSortArray(long *numbers, int size) { if (size <= 1) { return numbers; } else { long pivot = numbers[size/2-1]; int g_size = 0, l_size = 0, e_size = 0; for (int i = 0; i < size; i++) { if (numbers[i] < pivot) { l_size++; } else if (numbers[i] > pivot) { g_size++; } else { e_size++; } } long greaterThan[g_size], lowerThan[l_size], equal[e_size]; for (int i = 0, l_index = 0, g_index = 0, e_index = 0; i < size; i++) { if (numbers[i] < pivot) { lowerThan[l_index] = numbers[i]; l_index++; } else if (numbers[i] > pivot) { greaterThan[g_index] = numbers[i]; g_index++; } else { equal[e_index] = numbers[i]; e_index++; } } long *v_left = quickSortArray(lowerThan, l_size); long *v_right = quickSortArray(greaterThan, g_size); long array_left[l_size]; long array_right[g_size]; for (int i = 0 ; i < l_size; i++) { array_left[i] = v_left[i]; } for (int i = 0 ; i < g_size; i++) { array_right[i] = v_right[i]; } long *result = new long[size]; int index = 0; for (int i = 0; i < l_size; i++, index++) { result[index] = array_left[i]; } for (int i = 0; i < e_size; i++, index++) { result[index] = equal[i]; } for (int i = 0; i < g_size; i++, index++) { result[index] = array_right[i]; } return result; } } //=====================================================================================// vector<long> QuickSortList(vector<long> nums) { List<long> numbers; int len = nums.size(); for (int i = 0; i < len; i++) { numbers.insertAtTail(nums[i]); } List<long> sorted_list = quickSortList(numbers); vector<long> result; ListItem<long> *ptr = sorted_list.getHead(); while (ptr != NULL) { result.push_back(ptr->value); ptr = ptr->next; } return result; } List<long> quickSortList(List<long> numbers) { if (numbers.length() <= 1) { return numbers; } else { long pivot_index = numbers.length() / 2 -1; ListItem<long> *pivot = numbers.getHead(); for (int i = 0; i < pivot_index; i++) { pivot = pivot->next; } List<long> greaterThan, lowerThan, equal; ListItem<long> *ptr = numbers.getHead(); while (ptr != NULL) { if (ptr->value < pivot->value) { lowerThan.insertAtTail(ptr->value); } else if (ptr->value > pivot->value) { greaterThan.insertAtTail(ptr->value); } else { equal.insertAtTail(ptr->value); } ptr = ptr->next; } List<long> list_left = quickSortList(lowerThan); List<long> list_right = quickSortList(greaterThan); List<long> result; ListItem<long> *list_ptr; list_ptr = list_left.getHead(); while (list_ptr != NULL) { result.insertAtTail(list_ptr->value); list_ptr = list_ptr->next; } list_ptr = equal.getHead(); while (list_ptr != NULL) { result.insertAtTail(list_ptr->value); list_ptr = list_ptr->next; } list_ptr = list_right.getHead(); while (list_ptr != NULL) { result.insertAtTail(list_ptr->value); list_ptr = list_ptr->next; } return result; } } //===================================================================================== vector<long> HeapSort(vector<long> nums) { int array_size = nums.size(); long *numbers = new long[array_size]; for (int i = 0; i < array_size; i++) { numbers[i] = nums[i]; buildHeapify(numbers, i); } long *sorted_numbers = new long[array_size]; for (int i = 0; i < nums.size(); i++) { sorted_numbers[i] = numbers[0]; numbers[0] = numbers[array_size - 1]; array_size--; heapify(numbers, array_size, 0); } vector<long> result; for (int i = 0; i < nums.size(); i++) { result.push_back(sorted_numbers[i]); } return result; } /*Heap Sort Helper Functions*/ //===================================================================================== void heapify(long *numbers, int array_size, int index) { if (index >= array_size - 1) { return; } else { int right = 2*index + 2; int left = 2*index + 1; if (right <= array_size - 1 && numbers[right] < numbers[index]) { long temp = numbers[right]; numbers[right] = numbers[index]; numbers[index] = temp; heapify(numbers, array_size, right); } if (left <= array_size - 1 && numbers[left] < numbers[index]) { long temp = numbers[left]; numbers[left] = numbers[index]; numbers[index] = temp; heapify(numbers, array_size, left); } } } void buildHeapify(long *numbers, int index) { if (index == 0) { return; } else { int parent_index = (index - 1) / 2; if (numbers[parent_index] > numbers[index]) { long temp = numbers[parent_index]; numbers[parent_index] = numbers[index]; numbers[index] = temp; buildHeapify(numbers, parent_index); } } } //===================================================================================== vector<long> BucketSort(vector<long> nums, int max) { int size = nums.size(); List<long> *hashTable = new List<long>[max]; long maxVal = nums[0]; for (int i = 1; i < size; i++) { if (nums[i] > maxVal) { maxVal = nums[i]; } } for (int i = 0; i < max; i++) { hashTable[i].head = NULL; } for (int i = 0; i < size; i++) { int index = (nums[i] * max) / (maxVal + 1); hashTable[index].insertSorted(nums[i]); } vector<long> result; for (int i = 0; i < max; i++) { ListItem<long> *ptr = hashTable[i].getHead(); while (ptr != NULL) { result.push_back(ptr->value); ptr = ptr->next; } } return result; } #endif
// Given a number, remove consecutive repeated digits from it using stack #include<bits/stdc++.h> using namespace std; string func(string s) { int i=0; stack<char>a; while(i < s.length()) { if(a.empty() || s[i] != a.top()) { a.push(s[i]); i++; } else { a.pop(); i++; } } if(!a.empty()) { string s1; while(!a.empty()) { s1 = a.top() + s1; a.pop(); } return s1; } else return "Empty string"; } int main() { string s; cout<<"Enter a number "; cin>>s; cout<<"\nNumber without consecutive repeat is "<<func(s); return 0; }
/************************************************************************************** * File Name : CoolDown.cpp * Project Name : Keyboard Warriors * Primary Author : Wonju Cho * Secondary Author : * Copyright Information : * "All content 2019 DigiPen (USA) Corporation, all rights reserved." **************************************************************************************/ #include "CoolDown.hpp" #include "PATH.hpp" void CoolDown::Initialize(const Camera& camera_, const CameraView& view_) { animationShader.LoadShaderFrom(PATH::animation_vert, PATH::animation_frag); const Mesh mesh = MESH::create_rectangle({ 0.0f }, { 1.0f }); knightCoolMesh = mesh; archerCoolMesh = mesh; magicianCoolMesh = mesh; const mat3<float> worldToNDC = view_.GetCameraToNDCTransform() * camera_.WorldToCamera(); //knightAnimation.Initialize({2, 1, 1.0f}, animationShader); //knightCoolMaterial.CreateAnimation(animationShader, PATH::twocountdown, knightAnimation, worldToNDC * knightCoolTransform.GetModelToWorld()); knightCoolMaterial.shader = animationShader; archerCoolMaterial.shader = animationShader; magicianCoolMaterial.shader = animationShader; knightCoolMaterial.vertices.InitializeWithMeshAndLayout(knightCoolMesh, texturelayout); archerCoolMaterial.vertices.InitializeWithMeshAndLayout(archerCoolMesh, texturelayout); magicianCoolMaterial.vertices.InitializeWithMeshAndLayout(magicianCoolMesh, texturelayout); knightCoolMaterial.texture.LoadTextureFrom(PATH::twocountdown); archerCoolMaterial.texture.LoadTextureFrom(PATH::threecountdown); magicianCoolMaterial.texture.LoadTextureFrom(PATH::fourcountdown); knightCoolTransform.SetTranslation(coolKnightPosition); knightCoolTransform.SetScale(size); magicianCoolTransform.SetTranslation(coolMagicianPosition); magicianCoolTransform.SetScale(size); archerCoolTransform.SetTranslation(coolArcherPosition); archerCoolTransform.SetScale(size); knightAnimation.Initialize({ 2, 1, 1.0f }, animationShader); archerAnimation.Initialize({ 3, 1, 1.0f }, animationShader); magicianAnimation.Initialize({ 4, 1, 1.0f }, animationShader); knightCoolMaterial.ndc = worldToNDC * knightCoolTransform.GetModelToWorld(); archerCoolMaterial.ndc = worldToNDC * archerCoolTransform.GetModelToWorld(); magicianCoolMaterial.ndc = worldToNDC * magicianCoolTransform.GetModelToWorld(); } void CoolDown::CoolDownUpdate(float dt) { if (isKnightCoolDown) { knightAnimation.Animate(dt); Draw::draw(knightCoolMaterial); knightCoolDown -= dt; if (knightCoolDown <= 0.0f) { knightCoolDown = knightCoolTime; isKnightCoolDown = false; } } if (isArcherCoolDown) { archerAnimation.Animate(dt); Draw::draw(archerCoolMaterial); archerCoolDown -= dt; if (archerCoolDown <= 0.0f) { archerCoolDown = archerCoolTime; isArcherCoolDown = false; } } if (isMagicianCoolDown) { magicianAnimation.Animate(dt); Draw::draw(magicianCoolMaterial); magicianCoolDown -= dt; if (magicianCoolDown <= 0.0f) { magicianCoolDown = magicianCoolTime; isMagicianCoolDown = false; } } } bool CoolDown::GetKnightCoolDown() { return isKnightCoolDown; } bool CoolDown::GetArcherCoolDown() { return isArcherCoolDown; } bool CoolDown::GetMagicianCoolDown() { return isMagicianCoolDown; } void CoolDown::SetKnightCoolDown() { isKnightCoolDown = true; } void CoolDown::SetArcherCoolDown() { isArcherCoolDown = true; } void CoolDown::SetMagicianCoolDown() { isMagicianCoolDown = true; }
/** * Copyright (c) 2020, Timothy Stack * * 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 Timothy Stack 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 REGENTS 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 REGENTS 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 lnav_string_attr_type_hh #define lnav_string_attr_type_hh #include <string> #include <utility> #include <stdint.h> #include "base/intern_string.hh" #include "mapbox/variant.hpp" class logfile; struct bookmark_metadata; /** Roles that can be mapped to curses attributes using attrs_for_role() */ enum class role_t : int32_t { VCR_NONE = -1, VCR_TEXT, /*< Raw text. */ VCR_IDENTIFIER, VCR_SEARCH, /*< A search hit. */ VCR_OK, VCR_INFO, VCR_ERROR, /*< An error message. */ VCR_WARNING, /*< A warning message. */ VCR_ALT_ROW, /*< Highlight for alternating rows in a list */ VCR_HIDDEN, VCR_CURSOR_LINE, VCR_DISABLED_CURSOR_LINE, VCR_ADJUSTED_TIME, VCR_SKEWED_TIME, VCR_OFFSET_TIME, VCR_INVALID_MSG, VCR_STATUS, /*< Normal status line text. */ VCR_WARN_STATUS, VCR_ALERT_STATUS, /*< Alert status line text. */ VCR_ACTIVE_STATUS, /*< */ VCR_ACTIVE_STATUS2, /*< */ VCR_STATUS_TITLE, VCR_STATUS_SUBTITLE, VCR_STATUS_INFO, VCR_STATUS_STITCH_TITLE_TO_SUB, VCR_STATUS_STITCH_SUB_TO_TITLE, VCR_STATUS_STITCH_SUB_TO_NORMAL, VCR_STATUS_STITCH_NORMAL_TO_SUB, VCR_STATUS_STITCH_TITLE_TO_NORMAL, VCR_STATUS_STITCH_NORMAL_TO_TITLE, VCR_STATUS_TITLE_HOTKEY, VCR_STATUS_DISABLED_TITLE, VCR_STATUS_HOTKEY, VCR_INACTIVE_STATUS, VCR_INACTIVE_ALERT_STATUS, VCR_SCROLLBAR, VCR_SCROLLBAR_ERROR, VCR_SCROLLBAR_WARNING, VCR_FOCUSED, VCR_DISABLED_FOCUSED, VCR_POPUP, VCR_COLOR_HINT, VCR_QUOTED_CODE, VCR_CODE_BORDER, VCR_KEYWORD, VCR_STRING, VCR_COMMENT, VCR_DOC_DIRECTIVE, VCR_VARIABLE, VCR_SYMBOL, VCR_NUMBER, VCR_RE_SPECIAL, VCR_RE_REPEAT, VCR_FILE, VCR_DIFF_DELETE, /*< Deleted line in a diff. */ VCR_DIFF_ADD, /*< Added line in a diff. */ VCR_DIFF_SECTION, /*< Section marker in a diff. */ VCR_LOW_THRESHOLD, VCR_MED_THRESHOLD, VCR_HIGH_THRESHOLD, VCR_H1, VCR_H2, VCR_H3, VCR_H4, VCR_H5, VCR_H6, VCR_HR, VCR_HYPERLINK, VCR_LIST_GLYPH, VCR_BREADCRUMB, VCR_TABLE_BORDER, VCR_TABLE_HEADER, VCR_QUOTE_BORDER, VCR_QUOTED_TEXT, VCR_FOOTNOTE_BORDER, VCR_FOOTNOTE_TEXT, VCR_SNIPPET_BORDER, VCR_INDENT_GUIDE, VCR_INLINE_CODE, VCR_FUNCTION, VCR_TYPE, VCR_SEP_REF_ACC, VCR__MAX }; struct text_attrs { bool empty() const { return this->ta_attrs == 0 && !this->ta_fg_color && !this->ta_bg_color; } text_attrs operator|(const text_attrs& other) const { return text_attrs{ this->ta_attrs | other.ta_attrs, this->ta_fg_color ? this->ta_fg_color : other.ta_fg_color, this->ta_bg_color ? this->ta_bg_color : other.ta_bg_color, }; } bool operator==(const text_attrs& other) const { return this->ta_attrs == other.ta_attrs && this->ta_fg_color == other.ta_fg_color && this->ta_bg_color == other.ta_bg_color; } int32_t ta_attrs{0}; nonstd::optional<short> ta_fg_color; nonstd::optional<short> ta_bg_color; }; struct block_elem_t { wchar_t value; role_t role; }; using string_attr_value = mapbox::util::variant<int64_t, role_t, text_attrs, const intern_string_t, std::string, std::shared_ptr<logfile>, bookmark_metadata*, timespec, string_fragment, block_elem_t>; class string_attr_type_base { public: explicit string_attr_type_base(const char* name) noexcept : sat_name(name) { } const char* const sat_name; }; using string_attr_pair = std::pair<const string_attr_type_base*, string_attr_value>; template<typename T> class string_attr_type : public string_attr_type_base { public: using value_type = T; explicit string_attr_type(const char* name) noexcept : string_attr_type_base(name) { } template<typename U = T> std::enable_if_t<!std::is_void<U>::value, string_attr_pair> value( const U& val) const { return std::make_pair(this, val); } template<typename U = T> std::enable_if_t<std::is_void<U>::value, string_attr_pair> value() const { return std::make_pair(this, string_attr_value{}); } }; extern string_attr_type<void> SA_ORIGINAL_LINE; extern string_attr_type<void> SA_BODY; extern string_attr_type<void> SA_HIDDEN; extern string_attr_type<const intern_string_t> SA_FORMAT; extern string_attr_type<void> SA_REMOVED; extern string_attr_type<void> SA_PREFORMATTED; extern string_attr_type<std::string> SA_INVALID; extern string_attr_type<std::string> SA_ERROR; extern string_attr_type<int64_t> SA_LEVEL; extern string_attr_type<string_fragment> SA_ORIGIN; extern string_attr_type<int64_t> SA_ORIGIN_OFFSET; extern string_attr_type<role_t> VC_ROLE; extern string_attr_type<role_t> VC_ROLE_FG; extern string_attr_type<text_attrs> VC_STYLE; extern string_attr_type<int64_t> VC_GRAPHIC; extern string_attr_type<block_elem_t> VC_BLOCK_ELEM; extern string_attr_type<int64_t> VC_FOREGROUND; extern string_attr_type<int64_t> VC_BACKGROUND; extern string_attr_type<std::string> VC_HYPERLINK; namespace lnav { namespace string { namespace attrs { template<typename S> inline std::pair<S, string_attr_pair> preformatted(S str) { return std::make_pair(std::move(str), SA_PREFORMATTED.template value()); } template<typename S> inline std::pair<S, string_attr_pair> href(S str, std::string href) { return std::make_pair(std::move(str), VC_HYPERLINK.template value(std::move(href))); } } // namespace attrs } // namespace string namespace roles { template<typename S> inline std::pair<S, string_attr_pair> error(S str) { return std::make_pair(std::move(str), VC_ROLE.template value(role_t::VCR_ERROR)); } template<typename S> inline std::pair<S, string_attr_pair> warning(S str) { return std::make_pair(std::move(str), VC_ROLE.template value(role_t::VCR_WARNING)); } template<typename S> inline std::pair<S, string_attr_pair> status(S str) { return std::make_pair(std::move(str), VC_ROLE.template value(role_t::VCR_STATUS)); } template<typename S> inline std::pair<S, string_attr_pair> inactive_status(S str) { return std::make_pair(std::move(str), VC_ROLE.template value(role_t::VCR_INACTIVE_STATUS)); } template<typename S> inline std::pair<S, string_attr_pair> status_title(S str) { return std::make_pair(std::move(str), VC_ROLE.template value(role_t::VCR_STATUS_TITLE)); } template<typename S> inline std::pair<S, string_attr_pair> ok(S str) { return std::make_pair(std::move(str), VC_ROLE.template value(role_t::VCR_OK)); } template<typename S> inline std::pair<S, string_attr_pair> file(S str) { return std::make_pair(std::move(str), VC_ROLE.template value(role_t::VCR_FILE)); } template<typename S> inline std::pair<S, string_attr_pair> symbol(S str) { return std::make_pair(std::move(str), VC_ROLE.template value(role_t::VCR_SYMBOL)); } template<typename S> inline std::pair<S, string_attr_pair> keyword(S str) { return std::make_pair(std::move(str), VC_ROLE.template value(role_t::VCR_KEYWORD)); } template<typename S> inline std::pair<S, string_attr_pair> variable(S str) { return std::make_pair(std::move(str), VC_ROLE.template value(role_t::VCR_VARIABLE)); } template<typename S> inline std::pair<S, string_attr_pair> number(S str) { return std::make_pair(std::move(str), VC_ROLE.template value(role_t::VCR_NUMBER)); } template<typename S> inline std::pair<S, string_attr_pair> comment(S str) { return std::make_pair(std::move(str), VC_ROLE.template value(role_t::VCR_COMMENT)); } template<typename S> inline std::pair<S, string_attr_pair> identifier(S str) { return std::make_pair(std::move(str), VC_ROLE.template value(role_t::VCR_IDENTIFIER)); } template<typename S> inline std::pair<S, string_attr_pair> string(S str) { return std::make_pair(std::move(str), VC_ROLE.template value(role_t::VCR_STRING)); } template<typename S> inline std::pair<S, string_attr_pair> hr(S str) { return std::make_pair(std::move(str), VC_ROLE.template value(role_t::VCR_HR)); } template<typename S> inline std::pair<S, string_attr_pair> hyperlink(S str) { return std::make_pair(std::move(str), VC_ROLE.template value(role_t::VCR_HYPERLINK)); } template<typename S> inline std::pair<S, string_attr_pair> list_glyph(S str) { return std::make_pair(std::move(str), VC_ROLE.template value(role_t::VCR_LIST_GLYPH)); } template<typename S> inline std::pair<S, string_attr_pair> breadcrumb(S str) { return std::make_pair(std::move(str), VC_ROLE.template value(role_t::VCR_BREADCRUMB)); } template<typename S> inline std::pair<S, string_attr_pair> quoted_code(S str) { return std::make_pair(std::move(str), VC_ROLE.template value(role_t::VCR_QUOTED_CODE)); } template<typename S> inline std::pair<S, string_attr_pair> code_border(S str) { return std::make_pair(std::move(str), VC_ROLE.template value(role_t::VCR_CODE_BORDER)); } template<typename S> inline std::pair<S, string_attr_pair> snippet_border(S str) { return std::make_pair(std::move(str), VC_ROLE.template value(role_t::VCR_SNIPPET_BORDER)); } template<typename S> inline std::pair<S, string_attr_pair> table_border(S str) { return std::make_pair(std::move(str), VC_ROLE.template value(role_t::VCR_TABLE_BORDER)); } template<typename S> inline std::pair<S, string_attr_pair> table_header(S str) { return std::make_pair(std::move(str), VC_ROLE.template value(role_t::VCR_TABLE_HEADER)); } template<typename S> inline std::pair<S, string_attr_pair> quote_border(S str) { return std::make_pair(std::move(str), VC_ROLE.template value(role_t::VCR_QUOTE_BORDER)); } template<typename S> inline std::pair<S, string_attr_pair> quoted_text(S str) { return std::make_pair(std::move(str), VC_ROLE.template value(role_t::VCR_QUOTED_TEXT)); } template<typename S> inline std::pair<S, string_attr_pair> footnote_border(S str) { return std::make_pair(std::move(str), VC_ROLE.template value(role_t::VCR_FOOTNOTE_BORDER)); } template<typename S> inline std::pair<S, string_attr_pair> footnote_text(S str) { return std::make_pair(std::move(str), VC_ROLE.template value(role_t::VCR_FOOTNOTE_TEXT)); } template<typename S> inline std::pair<S, string_attr_pair> h1(S str) { return std::make_pair(std::move(str), VC_ROLE.template value(role_t::VCR_H1)); } template<typename S> inline std::pair<S, string_attr_pair> h2(S str) { return std::make_pair(std::move(str), VC_ROLE.template value(role_t::VCR_H2)); } template<typename S> inline std::pair<S, string_attr_pair> h3(S str) { return std::make_pair(std::move(str), VC_ROLE.template value(role_t::VCR_H3)); } template<typename S> inline std::pair<S, string_attr_pair> h4(S str) { return std::make_pair(std::move(str), VC_ROLE.template value(role_t::VCR_H4)); } template<typename S> inline std::pair<S, string_attr_pair> h5(S str) { return std::make_pair(std::move(str), VC_ROLE.template value(role_t::VCR_H5)); } template<typename S> inline std::pair<S, string_attr_pair> h6(S str) { return std::make_pair(std::move(str), VC_ROLE.template value(role_t::VCR_H6)); } namespace literals { inline std::pair<std::string, string_attr_pair> operator"" _ok(const char* str, std::size_t len) { return std::make_pair(std::string(str, len), VC_ROLE.template value(role_t::VCR_OK)); } inline std::pair<std::string, string_attr_pair> operator"" _error( const char* str, std::size_t len) { return std::make_pair(std::string(str, len), VC_ROLE.template value(role_t::VCR_ERROR)); } inline std::pair<std::string, string_attr_pair> operator"" _warning( const char* str, std::size_t len) { return std::make_pair(std::string(str, len), VC_ROLE.template value(role_t::VCR_WARNING)); } inline std::pair<std::string, string_attr_pair> operator"" _info( const char* str, std::size_t len) { return std::make_pair(std::string(str, len), VC_ROLE.template value(role_t::VCR_INFO)); } inline std::pair<std::string, string_attr_pair> operator"" _symbol( const char* str, std::size_t len) { return std::make_pair(std::string(str, len), VC_ROLE.template value(role_t::VCR_SYMBOL)); } inline std::pair<std::string, string_attr_pair> operator"" _keyword( const char* str, std::size_t len) { return std::make_pair(std::string(str, len), VC_ROLE.template value(role_t::VCR_KEYWORD)); } inline std::pair<std::string, string_attr_pair> operator"" _variable( const char* str, std::size_t len) { return std::make_pair(std::string(str, len), VC_ROLE.template value(role_t::VCR_VARIABLE)); } inline std::pair<std::string, string_attr_pair> operator"" _comment( const char* str, std::size_t len) { return std::make_pair(std::string(str, len), VC_ROLE.template value(role_t::VCR_COMMENT)); } inline std::pair<std::string, string_attr_pair> operator"" _hotkey( const char* str, std::size_t len) { return std::make_pair(std::string(str, len), VC_ROLE.template value(role_t::VCR_STATUS_HOTKEY)); } inline std::pair<std::string, string_attr_pair> operator"" _h1(const char* str, std::size_t len) { return std::make_pair(std::string(str, len), VC_ROLE.template value(role_t::VCR_H1)); } inline std::pair<std::string, string_attr_pair> operator"" _h2(const char* str, std::size_t len) { return std::make_pair(std::string(str, len), VC_ROLE.template value(role_t::VCR_H2)); } inline std::pair<std::string, string_attr_pair> operator"" _h3(const char* str, std::size_t len) { return std::make_pair(std::string(str, len), VC_ROLE.template value(role_t::VCR_H3)); } inline std::pair<std::string, string_attr_pair> operator"" _h4(const char* str, std::size_t len) { return std::make_pair(std::string(str, len), VC_ROLE.template value(role_t::VCR_H4)); } inline std::pair<std::string, string_attr_pair> operator"" _h5(const char* str, std::size_t len) { return std::make_pair(std::string(str, len), VC_ROLE.template value(role_t::VCR_H5)); } inline std::pair<std::string, string_attr_pair> operator"" _hr(const char* str, std::size_t len) { return std::make_pair(std::string(str, len), VC_ROLE.template value(role_t::VCR_HR)); } inline std::pair<std::string, string_attr_pair> operator"" _hyperlink( const char* str, std::size_t len) { return std::make_pair(std::string(str, len), VC_ROLE.template value(role_t::VCR_HYPERLINK)); } inline std::pair<std::string, string_attr_pair> operator"" _list_glyph( const char* str, std::size_t len) { return std::make_pair(std::string(str, len), VC_ROLE.template value(role_t::VCR_LIST_GLYPH)); } inline std::pair<std::string, string_attr_pair> operator"" _breadcrumb( const char* str, std::size_t len) { return std::make_pair(std::string(str, len), VC_ROLE.template value(role_t::VCR_BREADCRUMB)); } inline std::pair<std::string, string_attr_pair> operator"" _quoted_code( const char* str, std::size_t len) { return std::make_pair(std::string(str, len), VC_ROLE.template value(role_t::VCR_QUOTED_CODE)); } inline std::pair<std::string, string_attr_pair> operator"" _code_border( const char* str, std::size_t len) { return std::make_pair(std::string(str, len), VC_ROLE.template value(role_t::VCR_CODE_BORDER)); } inline std::pair<std::string, string_attr_pair> operator"" _table_border( const char* str, std::size_t len) { return std::make_pair(std::string(str, len), VC_ROLE.template value(role_t::VCR_TABLE_BORDER)); } inline std::pair<std::string, string_attr_pair> operator"" _quote_border( const char* str, std::size_t len) { return std::make_pair(std::string(str, len), VC_ROLE.template value(role_t::VCR_QUOTE_BORDER)); } inline std::pair<std::string, string_attr_pair> operator"" _quoted_text( const char* str, std::size_t len) { return std::make_pair(std::string(str, len), VC_ROLE.template value(role_t::VCR_QUOTED_TEXT)); } inline std::pair<std::string, string_attr_pair> operator"" _footnote_border( const char* str, std::size_t len) { return std::make_pair(std::string(str, len), VC_ROLE.template value(role_t::VCR_FOOTNOTE_BORDER)); } inline std::pair<std::string, string_attr_pair> operator"" _footnote_text( const char* str, std::size_t len) { return std::make_pair(std::string(str, len), VC_ROLE.template value(role_t::VCR_FOOTNOTE_BORDER)); } inline std::pair<std::string, string_attr_pair> operator"" _snippet_border( const char* str, std::size_t len) { return std::make_pair(std::string(str, len), VC_ROLE.template value(role_t::VCR_SNIPPET_BORDER)); } inline std::pair<std::string, string_attr_pair> operator"" _link( const char* str, std::size_t len) { return std::make_pair(std::string(str, len), VC_HYPERLINK.template value(std::string(str, len))); } } // namespace literals } // namespace roles } // namespace lnav #endif
/** * \file expatpp.hpp contains the expatpp libraries interface header * * See LICENSE for copyright information. */ #ifndef expatpp_hpp #define expatpp_hpp #include "xmlparser.hpp" #endif // #ifndef expatpp_hpp
// dog.c // AUTHOR: Julia Sales // ID: jesales // DESCRIPTION: A simple program that replicates // the cat function on termninal. // Resources used were piazza posts and man pages. #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <err.h> #include <string.h> int main (int argc, char *argv[]) { int i, j, in, file_in, file; const int buf_size = 32768; char dash[] = "-"; char stdin_buf[1]; // This takes in stdin // from command line // If "dog" is just enterned into the command line // SOURCE: read how to use read and write on manpages if (argc == 1) { in = read (STDIN_FILENO, stdin_buf, sizeof(stdin_buf)); while (in > 0) { write (STDOUT_FILENO, stdin_buf, sizeof(stdin_buf)); in = read (STDIN_FILENO, stdin_buf, sizeof(stdin_buf)); } } // If more than one command is entered into command // line. can either be "-" or file name(s). else { for(i = 1; i < argc; i++) { // error if no file is found // If a dash is entered if (*argv[i] == *dash) { // This takes in stdin from command line in = read (STDIN_FILENO, stdin_buf, sizeof(stdin_buf)); while (in > 0) { write (1, stdin_buf, sizeof(stdin_buf)); in = read (STDIN_FILENO, stdin_buf, sizeof(stdin_buf)); } } // If a file name(s) are entered else { if(argc > 1) { // opens first file // print errors if no file name is found file = open (argv[i], O_RDONLY); // SOURCE: Referenced from student on piazza const int buf_size = 32768; char file_buf[buf_size]; // print error is file is not found if ( file == -1 ){ warn ("%s", argv[i]); exit (1); } else { file_in = read (file, file_buf, buf_size); // print error if file cannot be read if (file_in == -1){ warn ("%s", argv[i]); exit (1); } //while (file_in >= buf_size) { //file_in = read (file, file_in, buf_size); //write (1, file_in, buf_size); //} //file_buf[]; //end = read(file, file_buf, buf_size + file_in); //printf ("%d\n", end); //if () // write the contents of a file else { while (file_in >= buf_size) { write (1, file_buf, file_in); file_in = read (file, file_buf, file_in); } write (1, file_buf, file_in); } } } } } close(in); close (file_in); close (file); } }
// Created on: 1996-11-25 // Created by: Philippe MANGIN // Copyright (c) 1996-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _BRepBlend_AppSurface_HeaderFile #define _BRepBlend_AppSurface_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <Approx_SweepApproximation.hxx> #include <AppBlend_Approx.hxx> #include <GeomAbs_Shape.hxx> #include <Standard_Integer.hxx> #include <TColgp_Array2OfPnt.hxx> #include <TColStd_Array2OfReal.hxx> #include <TColStd_Array1OfReal.hxx> #include <TColStd_Array1OfInteger.hxx> #include <TColgp_Array1OfPnt2d.hxx> #include <Standard_OStream.hxx> class Approx_SweepFunction; //! Used to Approximate the blending surfaces. class BRepBlend_AppSurface : public AppBlend_Approx { public: DEFINE_STANDARD_ALLOC //! Approximation of the new Surface (and //! eventually the 2d Curves on the support //! surfaces). //! Normally the 2d curve are //! approximated with an tolerance given by the //! resolution on support surfaces, but if this //! tolerance is too large Tol2d is used. Standard_EXPORT BRepBlend_AppSurface(const Handle(Approx_SweepFunction)& Funct, const Standard_Real First, const Standard_Real Last, const Standard_Real Tol3d, const Standard_Real Tol2d, const Standard_Real TolAngular, const GeomAbs_Shape Continuity = GeomAbs_C0, const Standard_Integer Degmax = 11, const Standard_Integer Segmax = 50); Standard_Boolean IsDone() const; Standard_EXPORT void SurfShape (Standard_Integer& UDegree, Standard_Integer& VDegree, Standard_Integer& NbUPoles, Standard_Integer& NbVPoles, Standard_Integer& NbUKnots, Standard_Integer& NbVKnots) const; Standard_EXPORT void Surface (TColgp_Array2OfPnt& TPoles, TColStd_Array2OfReal& TWeights, TColStd_Array1OfReal& TUKnots, TColStd_Array1OfReal& TVKnots, TColStd_Array1OfInteger& TUMults, TColStd_Array1OfInteger& TVMults) const; Standard_Integer UDegree() const; Standard_Integer VDegree() const; const TColgp_Array2OfPnt& SurfPoles() const; const TColStd_Array2OfReal& SurfWeights() const; const TColStd_Array1OfReal& SurfUKnots() const; const TColStd_Array1OfReal& SurfVKnots() const; const TColStd_Array1OfInteger& SurfUMults() const; const TColStd_Array1OfInteger& SurfVMults() const; //! returns the maximum error in the surface approximation. Standard_EXPORT Standard_Real MaxErrorOnSurf() const; Standard_Integer NbCurves2d() const; Standard_EXPORT void Curves2dShape (Standard_Integer& Degree, Standard_Integer& NbPoles, Standard_Integer& NbKnots) const; Standard_EXPORT void Curve2d (const Standard_Integer Index, TColgp_Array1OfPnt2d& TPoles, TColStd_Array1OfReal& TKnots, TColStd_Array1OfInteger& TMults) const; Standard_Integer Curves2dDegree() const; const TColgp_Array1OfPnt2d& Curve2dPoles (const Standard_Integer Index) const; const TColStd_Array1OfReal& Curves2dKnots() const; const TColStd_Array1OfInteger& Curves2dMults() const; Standard_EXPORT void TolReached (Standard_Real& Tol3d, Standard_Real& Tol2d) const; //! returns the maximum error in the <Index> 2d curve approximation. Standard_EXPORT Standard_Real Max2dError (const Standard_Integer Index) const; Standard_EXPORT Standard_Real TolCurveOnSurf (const Standard_Integer Index) const; //! display information on approximation. Standard_EXPORT void Dump (Standard_OStream& o) const; protected: private: Approx_SweepApproximation approx; }; #include <BRepBlend_AppSurface.lxx> #endif // _BRepBlend_AppSurface_HeaderFile
#include "MyChiSquared.h" MyChiSquared::MyChiSquared( mat xin, mat yin, mat ein ) : xMatrix(xin), yMeasured(yin) { mat buffMatrix(ein.n_rows,ein.n_rows); for (int i = 0; i < ein.n_rows; ++i) for (int j = 0; j < ein.n_rows; ++i) buffMatrix(i,j) = 0; for (int i = 0; i < ein.n_rows ; ++i){ buffMatrix(i,i) = ein(i,0) * ein(i,0); } inverseErrorMatrix = buffMatrix.i(); } void MyChiSquared::setParameters( mat params ) { function.setParameters(params); } double MyChiSquared::evaluate() { mat yTheoretical = function.evaluate(xMatrix); mat D = yTheoretical - yMeasured; mat ChiSq = D.t()*inverseErrorMatrix*D; return ChiSq(0,0); }
/* * ==================================================================== * Python_appui.h * * Copyright (c) 2005 Nokia Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== */ #ifndef __PYTHON_APPUI_H #define __PYTHON_APPUI_H #include <coecntrl.h> #include <eiklbo.h> #include <aknenv.h> #include <aknappui.h> #include <aknapp.h> #include "CSPyInterpreter.h" #include <Python.rsg> #include "sdkversion.h" class CAmarettoAppUi; class CAmarettoCallback : public CBase { public: CAmarettoCallback(CAmarettoAppUi* aAppUi):iAppUi(aAppUi) {;} virtual ~CAmarettoCallback() {;} void Call(void* aArg=NULL); protected: CAmarettoAppUi* iAppUi; private: virtual TInt CallImpl(void* aArg)=0; }; struct SAmarettoEventInfo { enum TEventType {EKey}; TEventType iType; /* TCoeEvent iControlEvent; */ TKeyEvent iKeyEvent; /* TEventCode iEventType; */ }; #define KMaxPythonMenuExtensions 30 #define EPythonMenuExtensionBase 0x6008 class CAmarettoAppUi : public CAknAppUi { public: CAmarettoAppUi(TInt aExtensionMenuId):iExtensionMenuId(aExtensionMenuId), aSubPane(NULL) {;} void ConstructL(); ~CAmarettoAppUi(); IMPORT_C void RunScriptL(const TDesC& aFileName, const TDesC* aArg=NULL); TBool ProcessCommandParametersL(TApaCommand, TFileName&, const TDesC8&); friend TInt AsyncRunCallbackL(TAny*); void ReturnFromInterpreter(TInt aError); TInt EnableTabs(const CDesCArray* aTabTexts, CAmarettoCallback* aFunc); void SetActiveTab(TInt aIndex); TInt SetHostedControl(CCoeControl* aControl, CAmarettoCallback* aFunc=NULL); void RefreshHostedControl(); void SetExitFlag() {iInterpreterExitPending = ETrue;} void SetMenuDynInitFunc(CAmarettoCallback* aFunc) {iMenuDynInitFunc = aFunc;} void SetMenuCommandFunc(CAmarettoCallback* aFunc) {iMenuCommandFunc = aFunc;} void SetExitFunc(CAmarettoCallback* aFunc) {iExitFunc = aFunc;} void SetFocusFunc(CAmarettoCallback* aFunc) {iFocusFunc = aFunc;} struct TAmarettoMenuDynInitParams { TInt iMenuId; CEikMenuPane *iMenuPane; }; TInt subMenuIndex[KMaxPythonMenuExtensions]; void CleanSubMenuArray(); CCoeControl* iContainer; CEikMenuPane* aSubPane; private: void HandleCommandL(TInt aCommand); void HandleForegroundEventL(TBool aForeground); void DynInitMenuPaneL(TInt aMenuId, CEikMenuPane* aMenuPane); void DoRunScriptL(); void DoExit(); CSPyInterpreter* iInterpreter; CAmarettoCallback* iMenuDynInitFunc; CAmarettoCallback* iMenuCommandFunc; CAmarettoCallback* iExitFunc; CAmarettoCallback* iFocusFunc; TBool iInterpreterExitPending; TInt iExtensionMenuId; CAsyncCallBack* iAsyncCallback; TBuf<KMaxFileName> iScriptName; TBuf8<KMaxFileName> iEmbFileName; }; IMPORT_C CEikAppUi* CreateAmarettoAppUi(TInt); #endif /* __PYTHON_APPUI_H */
#include "EventHandler.h" #include <SFML/Window/Event.hpp> #include <SFML/Graphics/RenderWindow.hpp> #include "Log.h" #include "MouseEventHandler.h" #include "GamePadEventHandler.h" #include "KeyboardEventHandler.h" namespace Platy { namespace Game { sf::Event EventHandler::myEvent; void EventHandler::HandleEvent(sf::RenderWindow& aWindow) { while (aWindow.pollEvent(myEvent)) { switch (myEvent.type) { case sf::Event::Closed: Log::Dispose(); aWindow.close(); break; case sf::Event::GainedFocus: break; case sf::Event::LostFocus: break; case sf::Event::KeyPressed: case sf::Event::KeyReleased: KeyboardEventHandler::HandleEvent(myEvent); break; case sf::Event::MouseButtonPressed: case sf::Event::MouseButtonReleased: case sf::Event::MouseEntered: case sf::Event::MouseLeft: case sf::Event::MouseMoved: case sf::Event::MouseWheelMoved: case sf::Event::MouseWheelScrolled: MouseEventHandler::HandleEvent(myEvent, aWindow); break; case sf::Event::JoystickButtonPressed: case sf::Event::JoystickButtonReleased: case sf::Event::JoystickMoved: case sf::Event::JoystickConnected: case sf::Event::JoystickDisconnected: GamePadEventHandler::HandleEvent(myEvent); break; case sf::Event::TextEntered: case sf::Event::Resized: case sf::Event::TouchBegan: case sf::Event::TouchMoved: case sf::Event::TouchEnded: case sf::Event::SensorChanged: case sf::Event::Count: break; } } } } }
int find(int x) { for(int i=1;i<=mn;i++) if(!used[i]&&map[x][i]) { used[i]=true; if(match[i]==-1||find(match[i])) { match[i]=x; return true; } } return false; } int Hungry() { int sum=0; for(int i=1;i<=cn;i++) { memset(used,false,sizeof(used)); if(find(i))sum++; } return sum; }
/** ****************************************************************************** * Copyright (c) 2019 - ~, SCUT-RobotLab Development Team * @file SourceManage.cpp * @author 苏锴南 15013073869 * @brief 底盘电源管理 * @date 2019-11-12 * @version 2.0 * @par Change Log: * <table> * <tr><th>Date <th>Version <th>Author <th>Description * <tr><td>2019-11-8 <td> 1.0 <td>苏锴南 <td> * </table> * ============================================================================== ##### How to use this driver ##### ============================================================================== @note -# SourceManage_Init -# Update(ADC采集数组) 如果采集顺序变化 要更改.h里面相应的数组位置宏定义 -# Set_ChargePower(设定充电功率) -# Cap_Manage BAT_Boost_Manage ESC_Boost_Manage example: void SourceManage_Task(void const * argument) { TickType_t xLastWakeTime; const TickType_t xFrequency = 2; xLastWakeTime = xTaskGetTickCount(); static uint32_t ADCReadBuff[8]; HAL_ADC_Start_DMA(&hadc1, (uint32_t *)ADCReadBuff, 7); HAL_DAC_Start(&hdac, DAC_CHANNEL_1); ChassisSource.SourceManage_Init(); for(;;) { vTaskDelayUntil(&xLastWakeTime,xFrequency); 更新数据 SourceManage.Update(ADCReadBuff); SourceManage.Set_ChargePower(PowerCtrl.Get_ChargePower()); 电容 升压板控制 SourceManage.Manage(); } } @warning ****************************************************************************** * @attention * * if you had modified this file, please make sure your code does not have many * bugs, update the version Number, write dowm your name and the date, the most * important is make sure the users will have clear and definite understanding * through your new brief. * * <h2><center>&copy; Copyright (c) 2019 - ~, SCUT-RobotLab Development Team. * All rights reserved.</center></h2> ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "SourceManage.h" #include "string.h" /** * @brief 更新电压电流等参数 * @note * @param ADC采集数组 顺序表在.h文件中 * @retval None * @author 苏锴南 */ void SourceManage_ClassDef::Update(uint32_t *_ADCReadBuff) { ADC_To_Real(_ADCReadBuff); Calc_Power(); capObj.Voltage = voltage.vol_Cap; capObj.chargePower_Now = power.pow_Charge; } /** * @brief 把ADC值转换成电压电流真实值 * @note * @param ADC采集数组 * @retval None * @author 苏锴南 */ void SourceManage_ClassDef::ADC_To_Real(uint32_t *_ADCReadBuff) { /* 计算电压真值 */ voltage.vol_In = Convert_To_RealVol(_ADCReadBuff[VOL_IN]); voltage.vol_Cap = Convert_To_RealVol(_ADCReadBuff[VOL_CAP]); voltage.vol_Out = Convert_To_RealVol(_ADCReadBuff[VOL_OUT]); /* 计算电流真值 */ current.cur_In = Convert_To_RealCur_IN(_ADCReadBuff[CUR_IN]); current.cur_Out = Convert_To_RealCur_Out(_ADCReadBuff[CUR_OUT]);//大量程 if(current.cur_Out < 0) {current.cur_Out = 0;} } /** * @brief 计算电池输入功率、输出功率、电容功率 * @note * @param None * @retval None * @author 苏锴南 */ void SourceManage_ClassDef::Calc_Power(void) { power.pow_In = Calc_RealPower(voltage.vol_In, current.cur_In); power.pow_motor = Calc_RealPower(voltage.vol_Out, current.cur_Out); power.pow_Charge = power.pow_In - power.pow_motor; if(power.pow_Charge < 0) {power.pow_Charge = 0;} } uint8_t switchNumber[6]={0,G1_SWITCH_PIN,G2_SWITCH_PIN,G3_SWITCH_PIN,G4_SWITCH_PIN,G5_SWITCH_PIN}; /** * @brief 控制开关的通断 * @param _switchNumber [选择的开关数:1-5]; switchStatus[开关状态:SWITCH_ON 打开开关 SWITCH_OFF 断开开关] * @return none * @author Joanna */ /** * @brief 控制开关的通断 * @note * @param _switchNumber [选择的开关数:1-5]; switchStatus[开关状态:SWITCH_ON 打开开关 SWITCH_OFF 断开开关] * @retval None * @author Joanna */ void SourceManage_ClassDef::switchCtrl(uint8_t _switchNumber,GPIO_PinState switchStatus) { HAL_GPIO_WritePin(G_SWITCH_PORT,switchNumber[_switchNumber], switchStatus); } void SourceManage_ClassDef::StopCharge() { HAL_GPIO_WritePin(CHARGE_CTRL_GPIO_Port,CHARGE_CTRL_Pin,GPIO_PIN_RESET); } void SourceManage_ClassDef::StartCharge() { HAL_GPIO_WritePin(CHARGE_CTRL_GPIO_Port,CHARGE_CTRL_Pin,GPIO_PIN_SET); } /** * @brief 由电池供电转到电容供电 * @note * @param None * @retval None * @author 苏锴南 */ void SourceManage_ClassDef::BATToCAP() { switchCtrl(1,SWITCH_OFF); HAL_Delay(1); switchCtrl(4,SWITCH_ON); HAL_Delay(1); switchCtrl(2,SWITCH_OFF); HAL_Delay(1); switchCtrl(3,SWITCH_ON); HAL_Delay(1); switchCtrl(5,SWITCH_ON); } /** * @brief 由电容供电转到电源供电 * @note * @param None * @retval None * @author 苏锴南 */ void SourceManage_ClassDef::CAPToBAT() { switchCtrl(3,SWITCH_OFF); HAL_Delay(1); switchCtrl(2,SWITCH_ON); HAL_Delay(1); switchCtrl(4,SWITCH_OFF); HAL_Delay(1); switchCtrl(1,SWITCH_ON); HAL_Delay(1); switchCtrl(5,SWITCH_OFF); } /** * @brief 24V输出全部关闭 * @note * @param None * @retval None * @author 苏锴南 */ void SourceManage_ClassDef::ALLCLOSE() { switchCtrl(3,SWITCH_OFF); switchCtrl(2,SWITCH_OFF); switchCtrl(4,SWITCH_OFF); switchCtrl(1,SWITCH_OFF); switchCtrl(5,SWITCH_OFF); } /** * @brief 三区间检测 * @note 1.带一定的min max滞后 2.cnt不能超过255 3.min = max时,只会返回LOW和HIGH * @param None * @retval None * @author 苏锴南 */ void SourceManage_ClassDef::Block_Check(float min,float max,float real, statusCheck_t* p_statusCheck, int32_t cnt) { if(real < min) { p_statusCheck->statusCnt++; if(p_statusCheck->statusCnt >= cnt) { p_statusCheck->statusCnt = 0; p_statusCheck->statusFlag = Block_LOW; } } else if(real >= max) { p_statusCheck->statusCnt++; if(p_statusCheck->statusCnt >= cnt) { p_statusCheck->statusCnt = 0; p_statusCheck->statusFlag = Block_HIGH; } } else { p_statusCheck->statusCnt = 0; p_statusCheck->statusFlag = Block_MID; } } /** * @brief 电容管理 * @note 电容启动管理 电容状态检测 计算并设定电容充电电流 * @param None * @retval None * @author 苏锴南 */ void SourceManage_ClassDef::Cap_Manage(void) { Check_CapStatus(); Set_ChargeCurrent(); } /** * @brief 检查电容状态 包括充电状态和放电状态 * @note * @param None * @retval None * @author 苏锴南 */ void SourceManage_ClassDef::Check_CapStatus(void) { /* 电容电量检测 */ Block_Check(CAPVOL_LOW, CAPVOL_HIGH, capObj.Voltage, &capObj.volStatusCheck, 50); if(capObj.volStatusCheck.statusFlag == Block_LOW) { capObj.volStatus = LOW; /* 电容电压过低 */ } else if(capObj.volStatusCheck.statusFlag == Block_HIGH) { capObj.volStatus = FULL; /* 电容充满 */ } else { capObj.volStatus = MID2; } /* 电容充电检测 */ Block_Check(voltage.vol_In-BOOSTCHARGE_dV, voltage.vol_In-BOOSTCHARGE_dV, capObj.Voltage, &capObj.chargeStatusCheck, 50); if(capObj.chargeStatusCheck.statusFlag == Block_LOW) { capObj.chargeStatus = LOW; } else { capObj.chargeStatus = MID2; /* 需要开启升压充电 */ } } /** * @brief 设定电容充电功率 * @note * @param None * @retval None * @author 苏锴南 */ void SourceManage_ClassDef::Set_ChargePower(float inputPower) { capObj.chargePower_Set = inputPower; } /** * @brief 设定电容充电电流 * @note * @param None * @retval None * @author 苏锴南 */ void SourceManage_ClassDef::Set_ChargeCurrent(void) { float output = 0; float chargeCurrent = capObj.chargePower_Set/capObj.Voltage; /* 判断电容是否充满 */ if(capObj.volStatus == FULL) { chargeCurrent = 0; } else { /* 判断是否需要小电流充电 */ if(capObj.Voltage >= LOWCURRENT_VOL) if(chargeCurrent >= LOWCURRENT) chargeCurrent = LOWCURRENT; if(chargeCurrent >= 10.0f) chargeCurrent = 10.0f; } output = (uint32_t)(chargeCurrent / 5 / (3.3f/4096.0f)); capObj.charge_DAC_Value = output; } /** * @brief 电池升压板管理 * @note * @param None * @retval None * @author 苏锴南 */ void SourceManage_ClassDef::BAT_Boost_Manage() { if(capObj.chargeStatus == MID2)/* 需要开启升压充电 */ BAT_BOOST = OPEN; else BAT_BOOST = CLOSE; // uint8_t msg_send[8] = {0}; // msg_send[0] = 0x55; // if(BAT_BOOST == OPEN)//开启电池升压板 // msg_send[1] = 0x33; // else // msg_send[1] = 0x44; // BAT_Boost_Board_Msg.ID = 0x200; // memcpy(BAT_Boost_Board_Msg.msg_send, msg_send, 8);/* 不能是200 等待改升压板程序 */ } /** * @brief 电调升压板管理 * @note * @param None * @retval None * @author 苏锴南 */ void SourceManage_ClassDef::ESC_Boost_Manage() { uint8_t msg_send[8] = {0}; ESC_BOOST=OPEN; msg_send[0]=4;//24V升压输出 ESC_Boost_Board_Msg.ID = 0x303; memcpy(ESC_Boost_Board_Msg.msg_send, msg_send, 8); } /** * @brief 电源管理初始化 * @note * @param None * @retval None * @author 苏锴南 */ void SourceManage_ClassDef::SourceManage_Init() { /* 采样板缓启动 */ ALLCLOSE(); HAL_Delay(300); StartCharge(); HAL_Delay(300); Set_ChargePower(0); ESC_BOOST=CLOSE; BAT_BOOST=CLOSE; } /** * @brief 电容启动管理 * @note 初始化时只有当电容大于15V时才打开电容输出 * @param None * @retval None * @author 苏锴南 */ void SourceManage_ClassDef::Cap_Boot_Manage(void) { static uint8_t bootFlag = 0; /* 等待充完电再开CAP供电 */ if(bootFlag == 0) { if(capObj.Voltage>=15) { BATToCAP(); bootFlag=1; } else ALLCLOSE(); } } void SourceManage_ClassDef::Set_Mode(DischargeMode _mode) { Mode = _mode; } void SourceManage_ClassDef::Manage(void) { /* 电容 升压板控制 */ if(Mode == CAP) Cap_Boot_Manage(); /* 只有启动完成电容才会输出 */ else CAPToBAT(); Cap_Manage(); BAT_Boost_Manage(); ESC_Boost_Manage(); }
#include<iostream> #include<vector> #include<algorithm> #include<set> #include<map> using namespace std; int pick=45; int guess(int num) { if(pick<num) return -1; else if(pick>num) return 1; else return 0; } class Solution { public: int guessNumber(int n) { //基本思想:二分查找折半查找,求mid时不能用mid=(high+low)/2会超过2^31-1 int mid,low=1,high=n; while(true) { mid=(high-low)/2+low; if(guess(mid)==-1) high=mid-1; else if(guess(mid)==1) low=mid+1; else break; } return mid; } }; int main() { Solution solute; int n=78; cout<<solute.guessNumber(n)<<endl; return 0; }
#include <iostream> #include <algorithm> #include <cstdio> #include <cstdlib> #include <ctime> #include <memory.h> #include <cmath> #include <string> #include <cstring> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> #include <sstream> #include <complex> #include <cassert> typedef long double LD; typedef long long LL; typedef unsigned long long ULL; typedef unsigned int uint; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; LL gcd(LL x, LL y) { LL z; while (y) { z = x % y; x = y; y = z; } return x; } LL f[18][111111]; int lg2[111111]; inline LL get(int l, int r) { int t = lg2[r - l + 1]; return gcd(f[t][l], f[t][r - (1 << t) + 1]); } inline void maximize(LL& x, LL y) { if (y > x) x = y; } int main() { // freopen(".in", "r", stdin); // freopen(".out", "w", stdout); for (int i = 2; i <= 111111; ++i) lg2[i] = lg2[i >> 1] + 1; int T; scanf("%d", &T); while (T--) { int n; scanf("%d", &n); for (int i = 0; i < n; ++i) scanf("%lld", &f[0][i]); for (int j = 1; (1 << j) <= n; ++j) { for (int i = 0; i + (1 << j) <= n; ++i) { f[j][i] = gcd(f[j - 1][i], f[j - 1][i + (1 << (j - 1))]); } } LL ans = 0; for (int l = 0; l < n; ++l) { int r = l; while (r < n) { // cerr << l << " " << r << " -> "; LL g = get(l, r); int left = r; int right = n - 1; while (left < right) { int c = (right + left + 1) / 2; if (get(l, c) == g) left = c; else right = c - 1; } maximize(ans, get(l, left) * (left - l + 1)); // cerr << l << " " << left << endl; r = l + 2 * (left - l + 1) - 1; } } printf("%lld\n", ans); } return 0; }
#include <iostream> #include <stdlib.h> using namespace std; int main(){ #ifdef WIN32 cout << "launching RINS -> 640x640" << endl; system(".\\Release\\RINS.exe"); #endif }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2011 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #include "core/pch.h" #include "OpSearchEdit.h" #include "modules/doc/doc.h" #include "modules/dochand/win.h" #include "modules/dochand/winman.h" #include "modules/prefs/prefsmanager/collections/pc_doc.h" #include "modules/pi/OpDragManager.h" #include "modules/inputmanager/inputmanager.h" #include "modules/skin/OpSkinManager.h" #include "modules/dragdrop/dragdrop_manager.h" #include "adjunct/desktop_util/search/search_net.h" #include "adjunct/desktop_util/search/searchenginemanager.h" #include "adjunct/desktop_util/actions/action_utils.h" #include "adjunct/quick/managers/FavIconManager.h" #include "adjunct/quick_toolkit/widgets/OpToolbar.h" #include "adjunct/quick/windows/BrowserDesktopWindow.h" #include "adjunct/quick/Application.h" #ifdef ENABLE_USAGE_REPORT #include "adjunct/quick/usagereport/UsageReport.h" #endif DEFINE_CONSTRUCT(OpSearchEdit); /*********************************************************************************** ** ** OpSearchEdit ** ** @param search_type - this really is index in searchengines model ** (and should not be used in this way) ** Default value is 0 ** ** However in some cases it is a search type, ** then it's -type, so to find the correct search, ** take abs(type) and find the index of the search ** with the given type ** ***********************************************************************************/ // Yes, sorry about that param name, but honestly, that's what it is OpSearchEdit::OpSearchEdit(INT32 index_or_negated_search_type) : m_search_in_page(FALSE) , m_search_in_speeddial(FALSE) , m_status(SEARCH_STATUS_NORMAL) { Initialize(index_or_negated_search_type); } OpSearchEdit::OpSearchEdit(const OpString& guid) : m_search_in_page(FALSE) , m_search_in_speeddial(FALSE) , m_status(SEARCH_STATUS_NORMAL) { SearchTemplate* search = g_searchEngineManager->GetByUniqueGUID(guid); Initialize((search ? g_searchEngineManager->GetSearchIndex(search) : 0)); } void OpSearchEdit::Initialize(INT32 index_or_negated_search_type) { GetBorderSkin()->SetImage("Edit Search Skin", "Edit Skin"); SetSpyInputContext(this, FALSE); SetUpdateNeededWhen(UPDATE_NEEDED_WHEN_VISIBLE); SetListener(this); g_favicon_manager->AddListener(this); UpdateSearch(index_or_negated_search_type); OpInputAction* action = OP_NEW(OpInputAction, (OpInputAction::ACTION_SEARCH)); if (!action) { init_status = OpStatus::ERR_NO_MEMORY; return; } action->SetActionData(index_or_negated_search_type); SetAction(action); } /***********************************************************************************/ void OpSearchEdit::SetSearchStatus(SEARCH_STATUS status) { m_status = status; InvalidateAll(); } void OpSearchEdit::OnPaint(OpWidgetPainter* widget_painter, const OpRect &paint_rect) { if (m_status == SEARCH_STATUS_NOMATCH) g_skin_manager->DrawElement(vis_dev, "Edit Search No Match Skin", GetBounds()); OpEdit::OnPaint(widget_painter, paint_rect); } /*********************************************************************************** ** ** OnDeleted ** ***********************************************************************************/ void OpSearchEdit::OnDeleted() { SetSpyInputContext(NULL, FALSE); if (g_favicon_manager ) { g_favicon_manager->RemoveListener(this); } OpEdit::OnDeleted(); } /*********************************************************************************** ** ** ** ***********************************************************************************/ void OpSearchEdit::OnChange(OpWidget *widget, BOOL changed_by_mouse) { if (m_search_in_page) { Search(0); } } /*********************************************************************************** ** ** UpdateSearch ** ***********************************************************************************/ void OpSearchEdit::UpdateSearch(INT32 index_or_negated_search_type) { m_index_or_negated_search_type = index_or_negated_search_type; m_index_in_search_model = TranslateType(m_index_or_negated_search_type); SearchTemplate* search = g_searchEngineManager->GetSearchEngine(m_index_in_search_model); // This is actually the search type INT32 type = search ? search->GetSearchType() : -1; m_search_in_page = (type == SEARCH_TYPE_INPAGE); autocomp.SetType(type == SEARCH_TYPE_GOOGLE ? AUTOCOMPLETION_GOOGLE : AUTOCOMPLETION_OFF); SetOnChangeOnEnter(!m_search_in_page); // Set the action that should be performed when enter is pressed currently // the index_or_type is used in the action to identify the search OpInputAction* action = OP_NEW(OpInputAction, (m_search_in_page ? OpInputAction::ACTION_FIND_NEXT : OpInputAction::ACTION_SEARCH)); if (!action) return; action->SetActionData(m_search_in_page ? TRUE : index_or_negated_search_type); SetAction(action); // Update ghost string OpString buf; g_searchEngineManager->MakeSearchWithString(m_index_in_search_model, buf); SetGhostText(buf.HasContent() ? buf.CStr() : UNI_L("")); GetForegroundSkin()->SetImage("Search Web"); UpdateSearchIcon(); } /*********************************************************************************** ** ** SetForceSearchInpage - force inline search, typically used for the search bar ** ***********************************************************************************/ void OpSearchEdit::SetForceSearchInpage(BOOL force_search_in_page) { m_search_in_page = force_search_in_page; SetOnChangeOnEnter(!m_search_in_page); // Set the action that should be performed when enter is pressed currently // the index_or_type is used in the action to identify the search OpInputAction* action = OP_NEW(OpInputAction, (m_search_in_page ? OpInputAction::ACTION_FIND_NEXT : OpInputAction::ACTION_SEARCH)); if (!action) return; action->SetActionData(m_search_in_page ? TRUE : m_index_or_negated_search_type); SetAction(action); // workaround for missing inline search in configured searches if(m_search_in_page && m_index_in_search_model == 0) { // Update ghost string OpString buf; TRAPD(err, buf.ReserveL(64)); g_languageManager->GetString(Str::S_FIND_IN_PAGE, buf); RemoveChars(buf, UNI_L("&")); SetGhostText(buf.CStr()); } UpdateSearchIcon(); } /*********************************************************************************** ** ** TranslateType ** ** @param INT32 index_or_negated_search_type ** ***********************************************************************************/ INT32 OpSearchEdit::TranslateType(INT32 index_or_negated_search_type) { if (index_or_negated_search_type >= 0) { // It's actually an index already :) return index_or_negated_search_type; } // When search_type is negative is is the only time it is really a search // so make it posivitve then search for the search with that type and // return its index INT32 search_type = abs(index_or_negated_search_type); return g_searchEngineManager->SearchTypeToIndex((SearchType)search_type); } /*********************************************************************************** ** ** UpdateSearchIcon ** ***********************************************************************************/ void OpSearchEdit::UpdateSearchIcon() { if (m_search_in_page) { GetForegroundSkin()->SetImage("Search Web"); } else { SearchTemplate* search = g_searchEngineManager->GetSearchEngine(m_index_in_search_model); if (search) { Image img = search->GetIcon(); if (!img.IsEmpty()) GetForegroundSkin()->SetBitmapImage(img, FALSE); else GetForegroundSkin()->SetImage(search->GetSkinIcon()); } } } /*********************************************************************************** ** ** OnFavIconAdded ** ***********************************************************************************/ void OpSearchEdit::OnFavIconAdded(const uni_char* document_url, const uni_char* image_path) { UpdateSearchIcon(); } /*********************************************************************************** ** ** OnFavIconsRemoved ** ***********************************************************************************/ void OpSearchEdit::OnFavIconsRemoved() { UpdateSearchIcon(); } /*********************************************************************************** ** ** Search ** ***********************************************************************************/ void OpSearchEdit::Search(OpInputAction* action) { OpString keyword; GetText(keyword); if (m_search_in_page) { g_input_manager->InvokeAction(OpInputAction::ACTION_FIND_INLINE, 0, keyword.CStr()); } else if (action) { SearchEngineManager::SearchSetting settings; g_application->AdjustForAction(settings, action, 0); if (m_search_in_speeddial) { BrowserDesktopWindow* bw = g_application->GetActiveBrowserDesktopWindow(); if (bw) settings.m_target_window = bw->GetActiveDocumentDesktopWindow(); } else { settings.m_target_window = GetTargetDocumentDesktopWindow(); } settings.m_keyword.Set(keyword); int id = g_searchEngineManager->SearchIndexToID(m_index_in_search_model); settings.m_search_template = g_searchEngineManager->SearchFromID(id); settings.m_search_issuer = m_search_in_speeddial ? SearchEngineManager::SEARCH_REQ_ISSUER_SPEEDDIAL : SearchEngineManager::SEARCH_REQ_ISSUER_OTHERS; if (settings.m_keyword.HasContent() && settings.m_search_template) { g_searchEngineManager->DoSearch(settings); #ifdef ENABLE_USAGE_REPORT if(GetParent() && GetParent()->GetType() == WIDGET_TYPE_SPEEDDIAL_SEARCH) { if(g_usage_report_manager && g_usage_report_manager->GetSearchReport()) { g_usage_report_manager->GetSearchReport()->AddSearch(SearchReport::SearchSpeedDial, settings.m_search_template->GetUniqueGUID()); } } #endif } } } /*********************************************************************************** ** ** OnInputAction ** ***********************************************************************************/ BOOL OpSearchEdit::OnInputAction(OpInputAction* action) { switch (action->GetAction()) { // Just so that we can Escape into the document case OpInputAction::ACTION_STOP: { if (action->IsKeyboardInvoked() && GetTargetDocumentDesktopWindow() && !GetTargetDocumentDesktopWindow()->GetWindowCommander()->IsLoading() && IsFocused()) { g_input_manager->InvokeAction(OpInputAction::ACTION_FOCUS_PAGE); return TRUE; } break; } case OpInputAction::ACTION_SEARCH: { UpdateSearch(action->GetActionData()); Search(action); return TRUE; } } return OpEdit::OnInputAction(action); } /*********************************************************************************** ** ** OnDragStart ** ** Note: the ID set on the drag object is the index_or_negated_search_type ** ***********************************************************************************/ void OpSearchEdit::OnDragStart(OpWidget* widget,INT32 pos, INT32 x, INT32 y) { if (!g_application->IsDragCustomizingAllowed()) return; DesktopDragObject* drag_object = GetDragObject(OpTypedObject::DRAG_TYPE_SEARCH_EDIT, x, y); if (drag_object) { drag_object->SetID(m_index_or_negated_search_type); drag_object->SetObject(this); g_drag_manager->StartDrag(drag_object, NULL, FALSE); } } /*********************************************************************************** ** ** OnContextMenu ** ***********************************************************************************/ /*virtual*/ BOOL OpSearchEdit::OnContextMenu(OpWidget* widget, INT32 child_index, const OpPoint &menu_point, const OpRect *avoid_rect, BOOL keyboard_invoked) { BOOL handled = static_cast<OpWidgetListener*>(GetParent())->OnContextMenu(this, child_index, menu_point, avoid_rect, keyboard_invoked); if (!handled) { HandleWidgetContextMenu(widget, menu_point); } return handled; } /*********************************************************************************** ** ** OnSettingsChanged ** ***********************************************************************************/ void OpSearchEdit::OnSettingsChanged(DesktopSettings* settings) { OpEdit::OnSettingsChanged(settings); if (settings->IsChanged(SETTINGS_SEARCH) && m_search_in_speeddial) { SearchTemplate* search = g_searchEngineManager->GetDefaultSpeedDialSearch(); // We currently (unfortunately) need to send the index to UpdateSearch, so get it UpdateSearch(g_searchEngineManager->GetSearchIndex(search)); } }
/* kamalsam */ #include<iostream> using namespace std; int main() { long long int n; int r=0; cin>>n; while(n>1&&r==0) { if(n%2==0) n/=2; else r=1; } if(r==1) cout<<"NIE"<<endl; else cout<<"TAK"<<endl; return 0; }
#include "cameraNavigator.h" #include "events/event.hpp" #include <imgui.h> namespace gui = ImGui; namespace lab { } #if 0 void camera_navigator(lab::FontManager& fontManager, const unsigned int frameRate) { SetFont small(fontManager.mono_small_font); ImVec2 pos = gui::GetCursorScreenPos(); gui::SetNextWindowPos(pos); gui::SetNextWindowCollapsed(true, ImGuiSetCond_FirstUseEver); if (gui::Begin("Statistics", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize)) { gui::Text("FPS : %u", frameRate); gui::Separator(); gui::Text("MSPF : %.3f ms ", 1000.0f / float(frameRate)); gui::Separator(); auto stats = gfx::getStats(); gui::Text("Wait Render : %fms", stats->waitToRender); gui::Text("Wait Submit : %fms", stats->waitToSubmit); gui::Text("Draw calls: %u", stats->numDraw); gui::Text("Compute calls: %u", stats->numCompute); if (gui::Checkbox("More Stats", &ui_more_stats)) { /* if (more_stats) gfx::setDebug(BGFX_DEBUG_STATS); else gfx::setDebug(BGFX_DEBUG_NONE); */ } } gui::End(); } #endif
// Author: WangZhan -> wangzhan.1985@gmail.com #pragma once #include "MessageLoop.h" #include "WaitableEvent.h" class MessageLoopThread { public: struct Options { Options() : messageLoopType(MessageLoop::Type_default), iStackSize(0) {} Options(MessageLoop::Type type, size_t iSize) : messageLoopType(type), iStackSize(iSize) {} MessageLoop::Type messageLoopType; size_t iStackSize; }; explicit MessageLoopThread(const tstring &csThreadName); virtual ~MessageLoopThread(); bool Start(); bool StartWithOptions(const Options &options); void Stop(); MessageLoop* GetMessageLoop() const { return m_pMessageLoop; } HANDLE GetThreadHandle() const { return m_hThreadHandle; } DWORD GetThreadID() const { return m_dwThreadID; } tstring GetThreadName() const { return m_csThreadName; } protected: virtual void Initialize() {} virtual void ThreadMain(); virtual void CleanUp() {} static DWORD WINAPI ThreadProc(void *pParam); private: struct StartupData { explicit StartupData(const Options &op) : option(op), event(true, false) {} Options option; WaitableEvent event; }; StartupData *m_pStartupData; bool m_bStarted; bool m_bStopping; tstring m_csThreadName; HANDLE m_hThreadHandle; DWORD m_dwThreadID; MessageLoop *m_pMessageLoop; };
// Copyright (c) 2020 The Orbit Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ScopeTimer.h" #include "Threading.h" #include "absl/strings/str_format.h" thread_local size_t CurrentDepth = 0; thread_local size_t CurrentDepthLocal = 0; void Timer::Start() { m_TID = GetCurrentThreadId(); m_Depth = CurrentDepth++; m_Start = MonotonicTimestampNs(); } void Timer::Stop() { m_End = MonotonicTimestampNs(); --CurrentDepth; } ScopeTimer::ScopeTimer(const char*) { m_Timer.Start(); } ScopeTimer::~ScopeTimer() { m_Timer.Stop(); } LocalScopeTimer::LocalScopeTimer() : millis_(nullptr) { ++CurrentDepthLocal; } LocalScopeTimer::LocalScopeTimer(double* millis) : millis_(millis) { ++CurrentDepthLocal; timer_.Start(); } LocalScopeTimer::LocalScopeTimer(const std::string& message) : millis_(nullptr), message_(message) { std::string tabs; for (size_t i = 0; i < CurrentDepthLocal; ++i) { tabs += " "; } LOG("%sStarting %s...", tabs.c_str(), message_.c_str()); ++CurrentDepthLocal; timer_.Start(); } LocalScopeTimer::~LocalScopeTimer() { timer_.Stop(); --CurrentDepthLocal; if (millis_ != nullptr) { *millis_ = timer_.ElapsedMillis(); } if (!message_.empty()) { std::string tabs; for (size_t i = 0; i < CurrentDepthLocal; ++i) { tabs += " "; } LOG("%s%s took %f ms.", tabs.c_str(), message_.c_str(), timer_.ElapsedMillis()); } }
#ifndef __BOX2D_GAME_SCENE_H__ #define __BOX2D_GAME_SCENE_H__ #include "GameScene.h" #include "Box2D/Box2D.h" #include "cocos2d.h" // Game scene with box2d physics class Box2DGameScene : public GameScene, public b2ContactListener { public: static cocos2d::Scene* createScene(); virtual bool init() override; // static create() CREATE_FUNC(Box2DGameScene); // Clean memory upon destruction ~Box2DGameScene(); private: // Clean memory before leaving virtual void beforeLeavingScene() override; // Go to game over screen virtual void continueToGameOver(float dT) override; // Physics class b2World* sceneWorld_ = nullptr; class b2Body* edgeBody_ = nullptr; // Called from physics when contact starts void BeginContact(b2Contact* contact) override; // Update physics here virtual void updatePhysics(float dT); // Create spaceship virtual Spaceship* createSpaceship() override; // Create new pillar virtual Pillar* createNewPillar() override; }; #endif // __BOX2D_GAME_SCENE_H__
// Copyright (c) 2019 The NavCoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "navcoinlistwidget.h" NavCoinListWidget::NavCoinListWidget(QWidget *parent, QString title, ValidatorFunc validator) : QWidget(parent), listWidget(new QListWidget), addInput(new QLineEdit), removeBtn( new QPushButton), warningLbl(new QLabel), validatorFunc(validator) { QVBoxLayout* layout = new QVBoxLayout(); QHBoxLayout* addLayout = new QHBoxLayout(); QFrame* add = new QFrame(); add->setLayout(addLayout); QPushButton* addBtn = new QPushButton(tr("Add")); removeBtn = new QPushButton(tr("Remove")); removeBtn->setVisible(false); addLayout->addWidget(addInput); addLayout->addWidget(addBtn); addLayout->addWidget(removeBtn); this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); this->setLayout(layout); QLabel* titleLbl = new QLabel(title); warningLbl->setObjectName("warning"); warningLbl->setVisible(false); layout->addWidget(titleLbl); layout->addWidget(listWidget); layout->addWidget(add); layout->addWidget(warningLbl); connect(addBtn, SIGNAL(clicked()), this, SLOT(onInsert())); connect(removeBtn, SIGNAL(clicked()), this, SLOT(onRemove())); connect(listWidget, SIGNAL(currentItemChanged(QListWidgetItem *, QListWidgetItem *)), this, SLOT(onSelect(QListWidgetItem *))); listWidget->setSortingEnabled(true); } void NavCoinListWidget::onRemove() { listWidget->takeItem(listWidget->row(listWidget->currentItem())); } void NavCoinListWidget::onSelect(QListWidgetItem* item) { removeBtn->setVisible(item != nullptr); } void NavCoinListWidget::onInsert() { QString itemText = addInput->text(); for(int row = 0; row < listWidget->count(); row++) { QListWidgetItem *item = listWidget->item(row); if (item->text() == itemText) { warningLbl->setText(tr("Duplicated entry")); warningLbl->setVisible(true); return; } } if (!(validatorFunc)(itemText)) { warningLbl->setText(tr("Entry not valid")); warningLbl->setVisible(true); return; } warningLbl->setVisible(false); addInput->setText(""); QListWidgetItem *newItem = new QListWidgetItem; newItem->setText(itemText); int row = listWidget->row(listWidget->currentItem()); listWidget->insertItem(row, newItem); } QStringList NavCoinListWidget::getEntries() { QStringList ret; for(int row = 0; row < listWidget->count(); row++) { QListWidgetItem *item = listWidget->item(row); ret << item->text(); } return ret; }
#include "ProductB2.h" #include<iostream> ProductB2::ProductB2() {}; ProductB2::~ProductB2() {}; void ProductB2::Use(){ std::cout << "use productB2" << std::endl; }
#ifndef BS_FUZZY_INTEGRAL_HPP #define BS_FUZZY_INTEGRAL_HPP #include <bs/defs.hpp> #include <opencv2/imgproc.hpp> using namespace cv; namespace { inline void sort3 (double* f, int* i) { static const int arr [][3] = { { 2, 1, 0 }, { 1, 2, 0 }, { 0, 0, 0 }, { 1, 0, 2 }, { 2, 0, 1 }, { 0, 0, 0 }, { 0, 2, 1 }, { 0, 1, 2 } }; const auto& a = f [0]; const auto& b = f [1]; const auto& c = f [2]; unsigned mask = (a >= b ? 4 : 0) | (a >= c ? 2 : 0) | (b >= c ? 1 : 0); const auto& p = arr [mask]; i [0] = p [0]; i [1] = p [1]; i [2] = p [2]; } inline double h_texture (double lhs, double rhs, double off = 1./255) { return (lhs + off) < rhs ? lhs / rhs : lhs > (rhs + off) ? rhs / lhs : 1; } inline Vec3f h_texture (const Vec3f& lhs, const Vec3f& rhs, double off = 1./255) { Vec3f result; #define T(a, b, c) c = h_texture (a, b, off) T (lhs [0], rhs [0], result [0]); T (lhs [1], rhs [1], result [1]); T (lhs [2], rhs [2], result [2]); #undef T return result; } inline Mat similarity1 (const Mat& fg, const Mat& bg) { Mat d = Mat (fg.size (), CV_32F, Scalar (0)); #pragma omp parallel for for (size_t i = 0; i < fg.total (); ++i) { d.at< float > (i) = h_texture (fg.at< float > (i), bg.at< float > (i)); } return d; } inline Mat similarity3 (const Mat& fg, const Mat& bg) { Mat d = Mat (fg.size (), CV_32FC3, Scalar (0)); for (size_t i = 0; i < fg.total (); ++i) { d.at< Vec3f > (i) = h_texture (fg.at< Vec3f > (i), bg.at< Vec3f > (i)); } return d; } inline Mat choquet_integral (const Mat& H, const Mat& I, const vector< double >& g) { Mat S (H.size (), CV_32F); #pragma omp parallel for for (size_t i = 0; i < H.total (); ++i) { const auto h = H.at< float > (i); const auto d = I.at< Vec3f > (i); S.at< float > (i) = h * g [0] + d [0] * g [1] + d [1] * g [2]; } return S; } inline Mat sugeno_integral (const Mat& H, const Mat& I, const vector< double >& g) { double h_x [3], s [3]; Mat S (H.size (), CV_32F); #pragma omp parallel for for (size_t i = 0; i < H.total (); ++i) { const auto h = H.at< float > (i); const auto d = I.at< Vec3f > (i); // // Certainly, the feature sets is X = {x_1, x_2, x_3 }. One element is // x_1 = {texture} and the others are x_2 = { I_1 } and x_3 = { I_2 } // [...] Let h_i : X → [0,1] be a fuzzy function. Fuzzy function // h_1 = h(x_1) = h_{texture} is the evaluation of texture feature. // Fuzzy function h_2 = h(x_2) = h_{ΔI_1} is the evaluation of color // feature I_1. Fuzzy function h_3 = h(x_3) = h_{ΔI_2} is the // evaluation of color feature I_2. // h_x [0] = h; h_x [1] = d [0]; h_x [2] = d [1]; int index [3] = { 0, 1, 2 }; // // The calculation of the fuzzy integral is as follows: suppose // h(x_1) ≥ h(x_2) ≥ h(x_3), if not, X is rearranged so that // this relation holds [...] // sort3 (h_x, index); // // [...] A fuzzy integral, S, with respect to a fuzzy measure g // over X can be computed by S = max_{i=1}^n[min(h(x_i), g(X_i))]: // s [0] = (min) (h_x [index [0]], 1.); s [1] = (min) (h_x [index [1]], g [index [1]] + g [index [2]]); s [2] = (min) (h_x [index [2]], g [index [2]]); S.at< float > (i) = max_element (s, s + 3)[0]; } return S; } inline Mat update_background (const Mat& F, const Mat& B, const Mat& S, float alpha) { Mat result (F.size (), CV_32FC3, Scalar (0)); double min_, max_; std::tie (min_, max_) = bs::minmax (S); #pragma omp parallel for for (size_t i = 0; i < F.total (); ++i) { auto& dst = result.at< Vec3f > (i); const auto& f = F.at< Vec3f > (i); const auto& b = B.at< Vec3f > (i); const auto& s = S.at< float > (i); const auto beta = 1. - max_ * (s - min_) / (max_ - min_); dst [0] = beta * b [0] + (1 - beta) * (alpha * f [0] + (1 - alpha) * b [0]); dst [1] = beta * b [1] + (1 - beta) * (alpha * f [1] + (1 - alpha) * b [1]); dst [2] = beta * b [2] + (1 - beta) * (alpha * f [2] + (1 - alpha) * b [2]); } return result; } } #endif // BS_FUZZY_INTEGRAL_HPP
#include "BallLocalizer.h" #include "Config.h" #include "Util.h" #include <vector> #include <algorithm> BallLocalizer::BallLocalizer() { } BallLocalizer::~BallLocalizer() { } void BallLocalizer::update(Math::Position robotPosition, const BallList& visibleBalls, const Math::Polygon& cameraFOV, double dt) { Ball* closestBall; std::vector<int> handledBalls; float globalAngle; for (unsigned int i = 0; i < visibleBalls.size(); i++) { globalAngle = Math::floatModulus(robotPosition.orientation + visibleBalls[i]->angle, Math::TWO_PI); visibleBalls[i]->x = robotPosition.x + Math::cos(globalAngle) * visibleBalls[i]->distance; visibleBalls[i]->y = robotPosition.y + Math::sin(globalAngle) * visibleBalls[i]->distance; closestBall = getBallAround(visibleBalls[i]->x, visibleBalls[i]->y); if (closestBall != NULL) { closestBall->updateVisible(visibleBalls[i]->x, visibleBalls[i]->y, visibleBalls[i]->distance, visibleBalls[i]->angle, dt); handledBalls.push_back(closestBall->id); } else { Ball* newBall = new Ball(visibleBalls[i]->x, visibleBalls[i]->y, visibleBalls[i]->distance, visibleBalls[i]->angle, dt); balls.push_back(newBall); handledBalls.push_back(newBall->id); } } for (unsigned int i = 0; i < balls.size(); i++) { if (std::find(handledBalls.begin(), handledBalls.end(), balls[i]->id) != handledBalls.end()) { continue; } balls[i]->updateInvisible(dt); } purge(visibleBalls, cameraFOV); } Ball* BallLocalizer::getBallAround(float x, float y) { float distance; float minDistance = -1; Ball* ball; Ball* closestBall = NULL; for (unsigned int i = 0; i < balls.size(); i++) { ball = balls[i]; distance = Math::distanceBetween(ball->x, ball->y, x, y); if ( distance <= Config::maxBallIdentityDistance && ( minDistance == -1 || distance < minDistance ) ) { minDistance = distance; closestBall = ball; } } return closestBall; } void BallLocalizer::purge(const BallList& visibleBalls, const Math::Polygon& cameraFOV) { BallList remainingBalls; Ball* ball; for (unsigned int i = 0; i < balls.size(); i++) { ball = balls[i]; if (!ball->shouldBeRemoved()) { remainingBalls.push_back(ball); if (!isValid(ball, visibleBalls, cameraFOV)) { ball->markForRemoval(Config::ballRemoveTime); } } else { delete ball; ball = NULL; } } balls = remainingBalls; } bool BallLocalizer::isValid(Ball* ball, const BallList& visibleBalls, const Math::Polygon& cameraFOV) { double currentTime = Util::millitime(); if (currentTime - ball->updatedTime > Config::ballPurgeLifetime) { return false; } Math::Vector velocity(ball->velocityX, ball->velocityY); if (velocity.getLength() > Config::ballMaxVelocity) { return false; } // @TODO Remove if in either goal or out of bounds.. if (cameraFOV.containsPoint(ball->x, ball->y)) { bool ballNear = false; float distance; for (unsigned int i = 0; i < visibleBalls.size(); i++) { distance = Math::distanceBetween(ball->x, ball->y, visibleBalls[i]->x, visibleBalls[i]->y); if (distance <= Config::ballFovCloseEnough) { ballNear = true; break; } } if (!ballNear) { return false; } } return true; }
#ifndef FIELD_H #define FIELD_H #include <cmath> #include <cstdlib> #include <iostream> #include <string> #include <list> #include <vector> const int N = 9; // size of the field const int K = std::ceil(N/2.0); struct pos { int a, b; }; extern pos not_a_position; struct move { pos a, b, c; int dir; move(){ a = not_a_position; b = not_a_position; c = not_a_position; } }; enum stone { EMPTY = 0, BLACK = 1, WHITE = 2 }; class field { stone stones[N+2][N+2]; public: field() { for(int i = 0; i < N+2; ++i) { for(int j = 0; j < N+2; ++j) stones[i][j] = EMPTY; } } stone get_stone(int a, int b) { if((a < 0) || (a >= N+2) || (b < 0) || (b >= N+2)) return EMPTY; return stones[a][b]; } stone get_stone(pos p) { return get_stone(p.a, p.b); } void set_stone(int a, int b, stone s) { stones[a][b] = s; } bool is_pos_inside(int a, int b) { return (a > 0) && (b > 0) && (a < 10) && (b < 10) && (std::abs((long)(a-b)) < 5); } }; field copy_field(field f); // a field with normal start conditions (valid only for N=9) field start_field(); field coordinate_field(); void print_field(field f); extern const pos unitvec[6]; void print_position(pos p); field test_field(); void do_move(field& f, move m); std::string number_to_string(int num); void possible_moves(field& f, stone player, std::list<move>* list); void vector_possible_moves(field& f, stone player, std::vector<move>* vec); bool is_valid_pos(pos p); double UH1_field(field& f, int player); // ---------- Direction ----------------- bool is_equal(pos a, pos b); pos add_pos(pos a, pos b); pos sub_pos(pos a, pos b); pos inv_dir(pos a); bool move_valid(pos a, pos dir,field &f); bool move_valid(pos a,pos b, pos dir,field &f); bool move_valid(pos a,pos b, pos c, pos dir,field &f); bool move_valid(move Move,field &f); bool is_over_bord(move Move); // ---------- Misc ----------------------- void print_move(move Move); int string_to_number(std::string str); pos read_position(); move read_move(); void print_position(pos p); int count_stones(int color,field &f); stone check_victory(field &f); #endif